From bcf6d46fb7fe427ca1a733a9b6f367c903dc04ee Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 01:00:35 -0600 Subject: [PATCH] build: single-file bundles build/Rosetta.luau + build/rosetta.lua (tools/bundle.py), terse README with generated format / codec tables - tools/bundle.py: every module a function in __FILES with a cached __include; requires become __include calls, so only the API and its load-time requires run on require. Rosetta._internal(path) includes any module by its src path. --!native modules get @native on each function (NATIVE re-checked on the bundle); linemaps map bundle lines back to sources (--where). LuaJIT bundle inlines the compat prelude. - tools/build.py: the multi-file trees move to build/_modules (gitignored); each target also writes its bundle. - tools/test.sh: api + docs/example tests also run against both bundles; fails when build/ is stale. - default.project.json mounts build/Rosetta.luau; examples/love loads build/rosetta.lua. - README: one line, install, quick start, doc links, generated format table and codec list (tools/gen_registry.py), licence TODO. DOCS lint checks the generated sections and the links. --- .gitignore | 8 +- README.md | 367 +- build/Rosetta.luau | 198571 ++++++++++++++++++++++++++++ build/Rosetta.luau.linemap.json | 539 + build/rosetta.lua | 199233 +++++++++++++++++++++++++++++ build/rosetta.lua.linemap.json | 539 + compat/luajit.lua | 3 +- default.project.json | 2 +- docs/guide/README.md | 31 +- examples/love/main.lua | 6 +- tools/bench.sh | 4 +- tools/build.py | 33 +- tools/bundle.py | 336 + tools/gen_registry.py | 69 +- tools/lint_rules.py | 37 +- tools/test.sh | 43 +- 16 files changed, 399611 insertions(+), 210 deletions(-) create mode 100644 build/Rosetta.luau create mode 100644 build/Rosetta.luau.linemap.json create mode 100644 build/rosetta.lua create mode 100644 build/rosetta.lua.linemap.json create mode 100644 tools/bundle.py diff --git a/.gitignore b/.gitignore index bf2550b..f7b15d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,9 @@ -# build outputs (tools/build.py) and generated test fixtures (tools/fixtures.py) -/build/ +# build outputs (tools/build.py): the single-file bundles and their linemaps are committed, the rest is internal +/build/* +!/build/Rosetta.luau +!/build/rosetta.lua +!/build/*.linemap.json +# generated test fixtures (tools/fixtures.py) /tests/gen/ # Rojo /*.rbxm diff --git a/README.md b/README.md index 24a8524..7af4b19 100644 --- a/README.md +++ b/README.md @@ -1,162 +1,249 @@ # rosetta -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/Rosetta/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming -`Decoder`, every model format loads as a `Scene`. - -174 formats: images (25), audio (21), video (11), 3D models (32), CAD (1), fonts (11), archives (31), data (11), -vector graphics and tile maps (2), layered images (3), subtitles (3), music (20) and playlists (3). 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. `tools/lint.sh` checks these counts against the registry. - -```luau -local F = require(Rosetta) -- LuaJIT: require("rosetta"); luau CLI: require("@rosetta") -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 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). +Read, write and convert file formats in pure Luau, on Roblox, LuaJIT / LÖVE and the Luau CLI. ## Install -**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Rosetta` (requires turned into instance -paths); `default.project.json` mounts it, so `rojo build -o Rosetta.rbxm` (or `rojo serve`) gives a `Rosetta` -ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Rosetta)`. There is no file system: -pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage, `F.host.toEditableMesh(prim, page)` an -EditableMesh (a merged triangle primitive split by `F.host.meshPages`). +- **Roblox:** put [`build/Rosetta.luau`](build/Rosetta.luau) in a ModuleScript (e.g. ReplicatedStorage.Rosetta), + or mount it with Rojo (`"Rosetta": { "$path": "rosetta/build/Rosetta.luau" }`; this repo's `default.project.json` + does). Then `local F = require(ReplicatedStorage.Rosetta)`. +- **LÖVE / LuaJIT:** copy [`build/rosetta.lua`](build/rosetta.lua). `local F = require("rosetta")` with its folder on + `package.path`, or `local F = dofile("rosetta.lua")`. +- **Luau CLI:** alias the sources in `.luaurc` (`"rosetta": "rosetta/src/Rosetta"`), then + `local F = require("@rosetta")`. -**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/rosetta/` (Lua 5.1 + LuaJIT FFI; the Luau -standard library pieces come from `rosetta/_compat.lua`). Copy the `rosetta` folder into the game (or put -`build/luajit/?.lua;build/luajit/?/init.lua` on `package.path`) and `local F = require("rosetta")`. 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 `@rosetta` runs `src/` directly (no file system). +Internal modules are reachable as `F._internal("codecs/video/Mpeg1")` (bundles) or `require("@rosetta/codecs/video/Mpeg1")` +(CLI). ## Quick start ```luau --- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR, EXR, DDS, KTX, PCX, ... -> Image -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, WavPack, APE, TTA, Musepack, AC-3, --- QOA, ADPCM (ADX, VAG, BRSTM, ...) -> 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, Ogg Theora, FLV, FLI, Smacker, Y4M (+ animated images) --- -> VideoDecoder -local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts) - --- models: glTF / GLB (+ Draco), OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX, 3DS, MS3D, LWO, .x, IQM, B3D, --- PMX / PMD, VRML, X3D, LDraw, MD2 / MD3 / MDL / MD5, BSP, SMD, Roblox (rbxm / rbxmx / .mesh), --- Minecraft (.schem, .mca), Qubicle -> Scene -local scene = F.model.load(glbBytes) -local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space - --- CAD, fonts, archives, data, vector, tile maps, layered, subtitles, music, playlists -local font = F.font.load(ttfBytes) -- TTF / OTF, WOFF / WOFF2, BMFont, bitmap fonts: outlines, kerning -local zip = F.archive.load(zipBytes) -- zip, tar, 7z, gzip, cab, iso, ...; saves zip / tar / gzip -local t = F.data.load('{"a": [1, 2]}', { format = "json" }) -- JSON, XML, YAML, TOML, CSV, INI, plist, CBOR, NBT, ... -local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64) -- SVG; Tiled maps load as a TileMap -local flat = F.ops.layers.flatten(F.layered.load(psdBytes)) -- PSD, Aseprite, OpenRaster -local subs = F.subtitle.load(srtText) -- SRT, WebVTT, ASS / SSA -local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / AHX / MIDI, ...: rendered to audio -local step = F.cad.load(stepText) -- STEP entity graph (B-rep through a plug-in) -local list = F.playlist.load(m3uText) -- M3U / M3U8, PLS, XSPF +local img, err = F.load(pngBytes) -- buffer | string | path; errors are values, nothing throws +if not img then error(tostring(err)) end +local small = F.ops.image.resize(img, 64, 64, "lanczos") +local webp = F.save(small, nil, { format = "webp" }) -- a buffer +local png = F.convert(jpegBytes, "png") -- load + save +local dec = F.audio.open(flacBytes) -- streaming: dec:read(n) -> interleaved f32 buffer, frames +local scene = F.model.load(glbBytes) -- every model format loads as a Scene +local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame +print(F.detect(webp), #F.formats()) -- "webp", the format list ``` -## The API in short +## Docs -`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.music` (also `F.music.new` / `addPattern` / `setCell` / ...), `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). +- Guide: [overview, install, inputs, errors, options](docs/guide/README.md), [images](docs/guide/image.md), + [audio](docs/guide/audio.md), [music](docs/guide/music.md), [video](docs/guide/video.md), + [3D scenes](docs/guide/scene.md), [Roblox files](docs/guide/roblox.md), [CAD](docs/guide/cad.md), + [fonts](docs/guide/font.md), [archives](docs/guide/archive.md), [data](docs/guide/data.md), + [Minecraft and voxels](docs/guide/voxel.md), [vector](docs/guide/vector.md), [layered images](docs/guide/layered.md), + [tile maps](docs/guide/tilemap.md), [subtitles](docs/guide/subtitles.md), [playlists](docs/guide/playlist.md), + [recipes](docs/guide/recipes.md) +- [docs/API.md](docs/API.md): the API reference +- [docs/STYLE.md](docs/STYLE.md): code layout, rules and tooling (`bash tools/test.sh` runs everything) -## Host notes +## Formats -| Host | Files | Bridges | -|---|---|---| -| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)`, `meshPages` / `toEditableMesh(prim, page)` | -| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` | -| LuaJIT | `io.open` | | -| luau CLI | none | | + +174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +adds each format's capabilities. -- **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.ROSETTA_NO_JIT_TUNE = true` before requiring the library to leave the - JIT settings alone. +| Category | Format | Extensions | Read | Write | +|---|---|---|---|---| +| Images | ani | .ani | yes | yes | +| Images | blp | .blp | yes | yes | +| Images | bmp | .bmp .dib | yes | yes | +| Images | dds | .dds | yes | yes | +| Images | exr | .exr | yes | yes | +| Images | gif | .gif | yes | yes | +| Images | hdr | .hdr .pic .rgbe | yes | yes | +| Images | icns | .icns | yes | yes | +| Images | ico | .ico .cur | yes | yes | +| Images | ilbm | .iff .ilbm .lbm .pbm | yes | yes | +| Images | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | +| Images | ktx | .ktx2 .ktx | yes | yes | +| Images | pcx | .pcx .pcc .dcx | yes | yes | +| Images | png | .png .apng | yes | yes | +| Images | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | +| Images | qoi | .qoi | yes | yes | +| Images | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | +| Images | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | +| Images | tga | .tga .icb .vda .vst .tpic | yes | yes | +| Images | tiff | .tif .tiff | yes | yes | +| Images | tim | .tim | yes | yes | +| Images | vtf | .vtf | yes | - | +| Images | webp | .webp | yes | yes | +| Images | xbm | .xbm .bm | yes | yes | +| Images | xpm | .xpm .pm | yes | yes | +| Audio | aac | .aac .adts | yes | - | +| Audio | ac3 | .ac3 .a52 | yes | - | +| Audio | adpcm | .adpcm .ima | yes | yes | +| Audio | adx | .adx | yes | yes | +| Audio | aiff | .aiff .aif .aifc .afc | yes | yes | +| Audio | ape | .ape | yes | - | +| Audio | au | .au .snd | yes | yes | +| Audio | brstm | .brstm .bcstm .bfstm | yes | - | +| Audio | caf | .caf .caff | yes | yes | +| Audio | flac | .flac .oga | yes | yes | +| Audio | m4a | .m4a .m4b .m4r | yes | yes | +| Audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | +| Audio | mpc | .mpc .mp+ .mpp | yes | - | +| Audio | opus | .opus | yes | yes | +| Audio | qoa | .qoa | yes | yes | +| Audio | tta | .tta | yes | - | +| Audio | vag | .vag | yes | yes | +| Audio | voc | .voc | yes | yes | +| Audio | vorbis | .ogg .oga | yes | yes | +| Audio | wav | .wav .wave .rf64 .bw64 | yes | yes | +| Audio | wavpack | .wv | yes | - | +| Video | avi | .avi | yes | yes | +| Video | fli | .fli .flc .flx | yes | - | +| Video | flv | .flv | yes | yes | +| Video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | +| Video | mkv | .mkv .webm .mka .mk3d | yes | yes | +| Video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | +| Video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | +| Video | mpegts | .ts .m2ts .mts .tsv | yes | - | +| Video | ogv | .ogv .ogg | yes | yes | +| Video | smk | .smk | yes | - | +| Video | y4m | .y4m | yes | yes | +| 3D models | 3ds | .3ds | yes | yes | +| 3D models | 3mf | .3mf | yes | yes | +| 3D models | b3d | .b3d | yes | - | +| 3D models | bsp | .bsp | yes | - | +| 3D models | dae | .dae .zae | yes | yes | +| 3D models | fbx | .fbx | yes | yes | +| 3D models | gltf | .gltf .glb | yes | yes | +| 3D models | iqm | .iqm | yes | yes | +| 3D models | ldraw | .ldr .mpd .dat | yes | - | +| 3D models | lwo | .lwo .lxo | yes | - | +| 3D models | mca | .mca .mcr | yes | - | +| 3D models | md2 | .md2 | yes | - | +| 3D models | md3 | .md3 | yes | - | +| 3D models | md5 | .md5mesh .md5anim | yes | - | +| 3D models | mdl | .mdl | yes | - | +| 3D models | ms3d | .ms3d | yes | yes | +| 3D models | obj | .obj | yes | yes | +| 3D models | off | .off | yes | yes | +| 3D models | ply | .ply | yes | yes | +| 3D models | pmx | .pmx .pmd | yes | - | +| 3D models | qb | .qb | yes | yes | +| 3D models | rbxm | .rbxm .rbxl | yes | yes | +| 3D models | rbxmx | .rbxmx .rbxlx | yes | yes | +| 3D models | robloxmesh | .mesh | yes | yes | +| 3D models | schematic | .schem .schematic .litematic | yes | yes | +| 3D models | smd | .smd | yes | yes | +| 3D models | stl | .stl | yes | yes | +| 3D models | usda | .usda .usd .usdz | yes | yes | +| 3D models | vox | .vox | yes | yes | +| 3D models | vrml | .wrl .wrz .vrml | yes | yes | +| 3D models | x | .x | yes | - | +| 3D models | x3d | .x3d .x3dv .x3dz .x3dvz .x3db | yes | yes | +| CAD | step | .step .stp .p21 | yes | yes | +| Fonts | bdf | .bdf | yes | yes | +| Fonts | bmfont | .fnt | yes | yes | +| Fonts | eot | .eot | yes | yes | +| Fonts | fon | .fon .fnt | yes | - | +| Fonts | hershey | .jhf | yes | - | +| Fonts | pcf | .pcf | yes | - | +| Fonts | psf | .psf .psfu | yes | yes | +| Fonts | ttf | .ttf .otf .ttc .otc | yes | - | +| Fonts | type1 | .pfb .pfa .t1 | yes | - | +| Fonts | woff | .woff | yes | - | +| Fonts | woff2 | .woff2 | yes | - | +| Archives | 7z | .7z | yes | - | +| Archives | adf | .adf | yes | - | +| Archives | applesingle | .as .applesingle .appledouble | yes | yes | +| Archives | ar | .a .ar .deb .lib | yes | yes | +| Archives | arj | .arj | yes | - | +| Archives | binhex | .hqx .hcx | yes | yes | +| Archives | br | .br | yes | - | +| Archives | bz2 | .bz2 .tbz2 .tbz | yes | - | +| Archives | cab | .cab | yes | yes | +| Archives | cpio | .cpio | yes | yes | +| Archives | d64 | .d64 .d71 .d81 | yes | yes | +| Archives | fat | .img .ima .vfd .flp .fat | yes | yes | +| Archives | grp | .grp | yes | yes | +| Archives | gzip | .gz .tgz .gzip | yes | yes | +| Archives | iso | .iso | yes | - | +| Archives | lha | .lzh .lha .lzs | yes | yes | +| Archives | lz4 | .lz4 .tlz4 | yes | yes | +| Archives | macbinary | .bin .macbin | yes | yes | +| Archives | mpq | .mpq .w3x .w3m .sc2map .sc2data .s2ma .scm .scx | yes | - | +| Archives | pak | .pak .sin | yes | yes | +| Archives | rpm | .rpm | yes | - | +| Archives | tar | .tar | yes | yes | +| Archives | uu | .uu .uue .xxe .b64 | yes | yes | +| Archives | vpk | .vpk | yes | yes | +| Archives | wad | .wad | yes | yes | +| Archives | xz | .xz .txz .lzma | yes | - | +| Archives | yenc | .yenc .ync | yes | yes | +| Archives | z | .z .taz .tz | yes | yes | +| Archives | zip | .zip .wsz | yes | yes | +| Archives | zoo | .zoo | yes | - | +| Archives | zst | .zst .tzst | yes | - | +| Data | cbor | .cbor | yes | yes | +| Data | csv | .csv .tsv | yes | yes | +| Data | ini | .ini .cfg .conf .inf .desktop | yes | yes | +| Data | json | .json .jsonl .ndjson .geojson | yes | yes | +| Data | msgpack | .msgpack .mpk | yes | yes | +| Data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | +| Data | plist | .plist | yes | yes | +| Data | snbt | .snbt | yes | yes | +| Data | toml | .toml | yes | yes | +| Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | +| Data | yaml | .yaml .yml | yes | yes | +| Vector graphics and tile maps | svg | .svg | yes | yes | +| Vector graphics and tile maps | tiled | .tmx .tmj .tsx .tsj | yes | yes | +| Layered images | aseprite | .aseprite .ase | yes | yes | +| Layered images | ora | .ora | yes | yes | +| Layered images | psd | .psd .psb | yes | yes | +| Subtitles | ass | .ass .ssa | yes | yes | +| Subtitles | srt | .srt | yes | yes | +| Subtitles | vtt | .vtt .webvtt | yes | yes | +| Music | 669 | .669 | yes | - | +| Music | ahx | .ahx .thx | yes | - | +| Music | far | .far | yes | - | +| Music | hmp | .hmp .hmi | yes | - | +| Music | hvl | .hvl | yes | - | +| Music | it | .it | yes | - | +| Music | med | .med .mmd0 .mmd1 .mmd2 .mmd3 .omed | yes | - | +| Music | midi | .mid .midi .smf .kar .rmi | yes | yes | +| Music | mod | .mod .m15 .stk .nst | yes | yes | +| Music | mtm | .mtm | yes | - | +| Music | mus | .mus | yes | - | +| Music | okt | .okt .okta | yes | - | +| Music | ptm | .ptm | yes | - | +| Music | s3m | .s3m | yes | - | +| Music | sf2 | .sf2 | yes | - | +| Music | stm | .stm | yes | - | +| Music | ult | .ult | yes | - | +| Music | umx | .umx | yes | - | +| Music | xm | .xm | yes | yes | +| Music | xmi | .xmi .xmidi | yes | - | +| Playlists | m3u | .m3u .m3u8 | yes | yes | +| Playlists | pls | .pls | yes | yes | +| Playlists | xspf | .xspf | yes | yes | + -## Layout +## Codecs and containers -``` -src/Rosetta/ - init.luau Registry.luau (generated) api: F.* - ops/ editing on the standard types (ImageOps, MeshOps, LayerOps, AudioOps, ...) - // formats: only what is specific to the format (parsing, mapping, writing) - containers/ Archive AudioWrap Avi Chunks Cpio Demux Ebml Fat Iso9660 IsoBmff MacFile - MpegEs MpegPs MpegTs Ogg Riff Tar Zip - codecs/compress/ Brotli Bzip2 Deflate Explode Lz4 Lzh Lzma Lzw Lzx PackBits Quantum - UnixCompress Xxh32 Zstd - codecs/entropy/ Huffman RangeCoder - codecs/image/ Bcn Blend Dct Etc Half Jpeg Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv - codecs/audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa (MP1-3) - Musepack Opus Pcm Qoa Resample SoundFont Stream Tracker Tta Vorbis - VorbisComment WavPack - codecs/video/ Dsp H263 H264 Legacy (FLI, Cinepak, MSV1, QT RLE, SMC, Smacker) Mpeg1 Mpeg2 - Theora Video (the codec registry) - codecs/text/ Json Nbt Text Url Xml - codecs/font/ Bitmap Cff GlyphNames TrueType - codecs/model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml - host/ runtime adapters (only the api uses them) - Types.luau the standard types + constructors - core/ Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input Md5 Sniff -compat/luajit.lua tools/ tests/ (T.luau, /.luau, codecs/, containers/, gen/) docs/ licenses/ -examples/love/ -``` + +Shared by the formats, not loadable on their own (`src/Rosetta/codecs//`, `src/Rosetta/containers/`; +[docs/FORMATS.md](docs/FORMATS.md) describes each). The bundles reach them as `F._internal("codecs/video/Mpeg1")`. -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, types, headers, requires, native-throw, layers, deps, contract, DUP, docs -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/Rosetta/Registry.luau + docs/FORMATS.md from the format folders -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#`); the fixture generators run ffmpeg, ImageMagick, libwebp, flac, -lame, opus-tools, vorbis-tools, assimp, fontTools and others through nix. - -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). - -## Performance - -`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). +| Domain | Modules | +|---|---| +| audio | Aac, Ac3, Adpcm, Alac, Ape, ApeTag, Flac, Hively, Mdct, MidiRender, Mpa, Musepack, Opus, Pcm, Qoa, Resample, SoundFont, Stream, Tracker, Tta, Vorbis, VorbisComment, WavPack | +| compress | Brotli, Bzip2, Deflate, Explode, Lz4, Lzh, Lzma, Lzw, Lzx, PackBits, Quantum, UnixCompress, Xxh32, Zstd | +| entropy | Huffman, RangeCoder | +| font | Bitmap, Cff, GlyphNames, TrueType | +| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | +| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | +| text | Json, Nbt, Text, Url, Xml | +| video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | +| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | + ## Licence -See [licenses/NOTICE.md](licenses/NOTICE.md). +TODO: no licence chosen yet. Third-party notices: [licenses/NOTICE.md](licenses/NOTICE.md). diff --git a/build/Rosetta.luau b/build/Rosetta.luau new file mode 100644 index 0000000..05dab0e --- /dev/null +++ b/build/Rosetta.luau @@ -0,0 +1,198571 @@ +--!optimize 2 +--!nocheck +-- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- require(this) -> the API (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. +-- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where). +local __FILES = {} +local __LOADED = {} +local function __include(path) + local r = __LOADED[path] + if r == nil then + local f = __FILES[path] + if f == nil then + error("rosetta: no module '" .. tostring(path) .. "'", 2) + end + __LOADED[path] = false -- while it runs (a cycle, or a module that threw) + r = f() + if r == nil then + r = true + end + __LOADED[path] = r + elseif r == false then + error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) + end + return r +end +__FILES[""] = function() + +-- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). +-- Every format of a category maps onto one standard type (src/Rosetta/Types.luau): a PNG and a WebP both load as an +-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension. +-- +-- local F = require(Rosetta) -- Roblox: the ModuleScript; LuaJIT: require("rosetta"); luau: "@rosetta" +-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err +-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...) +-- local dec = F.audio.open(src) -- streaming decoders (audio / video) +-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format +-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files +-- local s = F.saveString(img, { format = "png" }) +-- local buf = F.convert(src, "png", opts?) -- load + save +-- F.formats() -- the capability list (also docs/FORMATS.md) +-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector +-- +-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Registry = __include("Registry") +local Video = __include("codecs/video/Video") +local AudioWrap = __include("containers/AudioWrap") +local Rbx = __include("codecs/model/Rbx") +local ImageOps = __include("ops/ImageOps") +local host = __include("host") + +local F = {} + +F.version = "0.1.0" +F.Err = Err +F.Types = Types +F.Bytes = Bytes +F.Rbx = Rbx -- the Roblox instance tree helpers (codecs/model/Rbx: tree, instance, add, set, get, find, descendants) +F.null = Types.null +F.host = host +F.plugins = {} :: { [string]: any } -- injected optional dependencies (plugins.brep for cad/step) + +-- value.kind -> category +local KIND_CATEGORY: { [string]: string } = { + image = "image", + audio = "audio", + video = "video", + scene = "model", + rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx) + cad = "cad", + font = "font", + archive = "archive", + vector = "vector", + tilemap = "vector", + layered = "layered", + subtitles = "subtitle", + music = "music", + midi = "music", + playlist = "playlist", +} + +-- ------------------------------------------------------------------------------------------------ registry access +local loaded: { [string]: any } = {} + +local function module(entry: Registry.Entry): (any, Err.Err?) + local m = loaded[entry.path] + if m then + return m + end + local ok, res = pcall(entry.load) + if not ok then + return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res)) + end + loaded[entry.path] = res + return res +end + +local function inCategory(entry: Registry.Entry, category: string?): boolean + return category == nil or entry.category == category +end + +-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches +local function find(key: string, category: string?): Registry.Entry? + local k = string.lower(key) + for _, e in Registry do + if e.name == k and inCategory(e, category) then + return e + end + end + for _, e in Registry do + if inCategory(e, category) and table.find(e.extensions, k) then + return e + end + end + return nil +end + +-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension +local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?) + if format then + local e = find(format, category) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. (if category then " in " .. category else "")) + end + return e, nil + end + local ext = Input.extension(name) + local best: Registry.Entry? = nil + local bestScore = 0 + for _, e in Registry do + if inCategory(e, category) and (e.caps.decode or e.caps.open) then + local m = module(e) + if m and m.sniff then + local ok, score = pcall(m.sniff, Bytes.reader(buf)) + if ok and type(score) == "number" and score > 0 then + if ext and table.find(e.extensions, ext) then + score += 0.01 -- ties go to the extension + end + if score > bestScore then + best, bestScore = e, score + end + end + end + end + end + if best then + return best, nil + end + if ext then + local e = find(ext, category) + if e then + return e, nil + end + end + return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. (if name then " (" .. name .. ")" else "") .. (if category then " for " .. category else "")) +end + +-- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that +-- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered = +-- true: open the format, which renders it, instead of decoding it) +local function detectFor(buf: buffer, name: string?, o: { [string]: any }): (Registry.Entry?, Err.Err?, boolean) + local entry, err = detect(buf, name, o.category, o.format) + if not entry and o.category == "audio" then + local e = detect(buf, name, "music", o.format) + if e and e.caps.render then + return e, nil, true + end + end + return entry, err, false +end + +local function tag(value: any, formatName: string) + if type(value) == "table" then + local meta = value.meta + if type(meta) == "table" then + if meta.source == nil then + meta.source = { format = formatName } + elseif type(meta.source) == "table" and meta.source.format == nil then + meta.source.format = formatName + end + end + end +end + +-- full decode through a streaming decoder (audio formats with open but no decode) +local function drain(dec: any): any + local channels = dec.channels + local parts, total = {}, 0 + while true do + local out, n = dec:read(65536) + if not out or n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + local a = Types.Audio.new(dec.sampleRate, channels, total) + local o = 0 + for _, p in parts do + buffer.copy(a.samples, o, p) + o += buffer.len(p) + end + a.tags = dec.tags or {} + return a +end + +-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs) +local function siblings(path: string): (uri: string) -> buffer? + local dir = string.match(path, "^(.*[/\\])") or "" + return function(uri: string): buffer? + if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then + return nil + end + local u = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + for part in string.gmatch(u, "[^/\\]+") do + if part == ".." then + return nil + end + end + local b = host.readFile(dir .. u) + return b + end +end + +-- ------------------------------------------------------------------------------------------------ API +type Options = { [string]: any } -- format (name or extension), category, path, data, name, + format options + +local load: (src: any, opts: Options?) -> (any, Err.Err?) + +-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer +-- | string, else the files next to the descriptor on hosts with a file system +local function pageLoader(value: any, name: string?, o: Options) + if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then + return + end + local user: any = o.loadPage + if value.pages or (value.meta.pageLoader and type(user) ~= "function") then + return + end + local dir = if name then string.match(name, "^(.*[/\\])") or "" else nil + if type(user) ~= "function" and not (dir and host.hasFiles) then + return + end + value.meta.pageLoader = function(file: string, page: number): (any, Err.Err?) + local src: any + if type(user) == "function" then + src = (user :: any)(file, page) + else + src = (dir :: string) .. file + end + if type(src) == "table" then + return src -- already an Image + end + if src == nil then + return nil, Err.new(Err.IO, "no data for page " .. file) + end + return load(src, { category = "image", name = file, path = type(user) ~= "function" }) + end +end + +-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a +-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer +-- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's +-- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the +-- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font. +local function unwrap(value: any, formatName: string, o: Options): any + if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then + return value + end + if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then + return value + end + local payload = value.meta.payload + if not value.meta.stream and type(payload) ~= "string" then + return value + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then + return value + end + local entryName = if type(payload) == "string" then payload else list[1].name + local rok, inner = pcall(value.read, value, entryName) + if not rok or type(inner) ~= "buffer" then + return value + end + local category = "archive" + local e = detect(inner, nil, "archive", nil) + local innerExt = Input.extension(entryName) or "" + if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then + -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font + e = detect(inner, entryName, "font", nil) + category = "font" + end + if not e then + return value + end + local io = table.clone(o) + io.category = category + io.name = entryName + io._depth = (o._depth or 0) + 1 + local v = load(inner, io) + if type(v) ~= "table" or type(v.meta) ~= "table" then + return value + end + if type(payload) == "string" then + v.meta.container = formatName + v.meta.outer = value + else + v.meta.compression = formatName + end + return v +end + +-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format, +-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> +-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for +-- the embedded parts) when called directly. +-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. +-- +-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded +-- as music (sniffed, or as the given format). +-- +-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets +-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / +-- FLAC / AC-3 as they are), opened through F.open with that format. +local function openAudio(demuxer: any, track: any): (any, Err.Err?) + local buf, fmt, err = AudioWrap.wrap(demuxer, track) + if not buf then + return nil, err + end + local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) + -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is + -- already the decoder's own (its first packet returns nothing) + -- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does) + if dec and fmt ~= "opus" and fmt ~= "vorbis" then + local skip = if type(track.codecDelay) == "number" and track.codecDelay > 0 then math.floor(track.codecDelay * dec.sampleRate + 0.5) else 0 + local length = if type(track.playDuration) == "number" and track.playDuration > 0 then math.floor(track.playDuration * dec.sampleRate + 0.5) else nil + if skip > 0 or length then + dec = AudioWrap.trim(dec, skip, length) + end + end + return dec, oerr +end + +local function withHooks(o: Options): Options + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then + return o + end + local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end + if c.openAudio == nil then + c.openAudio = openAudio + end + if c.decodeImage == nil then + c.decodeImage = function(b: buffer): (any, Err.Err?) + return F.load(b, { category = "image" }) + end + end + if c.encodeImage == nil then + c.encodeImage = function(img: any, format: string): (any, Err.Err?) + return F.save(img, nil, { format = format, category = "image" }) + end + end + if c.decodeModule == nil then + -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format + c.decodeModule = function(b: buffer, format: string?): (any, Err.Err?) + return F.load(b, { category = "music", format = format }) + end + end + return c +end + +-- load(src, opts?) -> value | nil, Err +function F.load(src: any, opts: Options?): (any, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + if name and o.name == nil then + o = table.clone(o) + o.name = name -- formats may use the file name (single-stream archives name their entry after it) + end + local entry, derr, rendered = detectFor(buf, name, o) + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then + -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder + o = table.clone(o) + o.resolve = siblings(name) + end + local value, err + if m.decode and not rendered then + local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) + end + value, err = v, e + elseif m.open then + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec then + value = if type(dec) == "table" and dec.kind == "video" then dec else drain(dec) + end + err = e + else + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name) + end + if value == nil then + return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) + end + tag(value, entry.name) + pageLoader(value, name, o) + return unwrap(value, entry.name, o) +end +load = F.load + +-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err +function F.open(src: any, opts: Options?): (any, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, derr = detectFor(buf, name, o) + if not entry and o.category == "video" and o.format == nil then + entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos + end + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if not m.open and entry.category == "image" and o.category == "video" then + local io = table.clone(o) + io.category = "image" + io.format = entry.name + local img, lerr = F.load(buf, io) + if not img then + return nil, lerr + end + return F.video.fromImage(img, o) + end + if not m.open then + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) + end + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec == nil then + return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name) + end + return dec +end + +local encodeTextures: (scene: any) -> Err.Err? + +-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil, +-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are +-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap +-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is. +local function videoToImage(v: any, o: Options): (any, Err.Err?) + if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then + return nil, Err.new(Err.ARG, "save: not a VideoDecoder") + end + local cap = o.maxFrames or 300 + local want = o.frames + local fps = o.fps + if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then + return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000") + end + local limit = math.floor(if want then math.min(want, cap) else cap) + local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1) + limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h)))) + local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1 + local images: { any }, delays: { number } = {}, {} + local t0: number? = nil + local taken = 0 -- output slots used (fps mode) + while #images < limit do + local ok, f, ferr = pcall(v.nextFrame, v) + if not ok then + return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f)) + end + if f == nil then + if ferr then + return nil, ferr + end + break + end + local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur + local delay = dur + if fps then + local start: number = t0 or f.pts + t0 = start + local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken + delay = slots / fps + taken += math.max(0, slots) + end + if delay > 0 then + local rok, img = pcall(v.toRGBA, v, f) + if not rok or type(img) ~= "table" then + return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8") + end + table.insert(images, img) + table.insert(delays, delay) + end + end + if #images == 0 then + return nil, Err.new(Err.ARG, "save: the video has no frames") + end + local img, ierr = ImageOps.fromFrames(images, delays) + if not img then + return nil, ierr + end + img.loops = if type(v.loops) == "number" then v.loops else 0 + img.meta.source = { format = v.format } + return img, nil +end + +-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method +-- for other engines) or a Midi (music/midi render) | +-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... +local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } +local function renderMusic(value: any, o: Options): (any, Err.Err?) + local ok, dec, err + if value.kind == "midi" then + local m, merr = F.format("midi") + if not m then + return nil, merr + end + ok, dec, err = pcall(m.render, value, o) + elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then + -- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an + -- empty Decoder carrying .err) + ok, dec = pcall(value.render, value, o) + if ok and type(dec) == "table" and dec.err then + return nil, dec.err + end + else + local Tracker: any = __include("codecs/audio/Tracker") + ok, dec, err = pcall(Tracker.render, value, o) + end + if not ok then + return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec)) + end + if dec == nil then + return nil, err or Err.new(Err.ARG, "render failed") + end + return dec, nil +end + +-- the writable format for a value: opts.format, the destination's extension, or the source format +local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entry?, any, Err.Err?, string?) + local category = o.category + if category == nil and type(value) == "table" and type(value.kind) == "string" then + category = KIND_CATEGORY[value.kind] + end + local key = o.format or Input.extension(dest) + if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then + key = value.meta.source.format + end + if key == nil then + return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") + end + local entry = find(key, category) + if not entry and category == "image" and type(value) == "table" and value.kind == "image" then + entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") + end + if not entry and category == "video" and type(value) == "table" and value.kind == "video" then + entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif") + end + if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav") + end + if not entry then + return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. (if category then " for " .. category else "")) + end + local m, merr = module(entry) + if not m then + return nil, nil, merr + end + if not m.encode then + local alt = nil + for _, e in Registry do + if e.category == entry.category and e.caps.encode then + alt = e.name + break + end + end + return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. (if alt then "; try " .. alt else "")), entry.name) + end + return entry, m, nil, key +end + +-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images) +function encodeTextures(scene: any): Err.Err? + if type(scene.textures) ~= "table" then + return nil + end + for _, tex in scene.textures do + if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then + local png, err = F.save(tex.image, nil, { format = "png" }) + if not png then + return err + end + tex.data, tex.mime = png, "image/png" + end + end + return nil +end + +-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files +-- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the +-- caller's opts.files); with a dest they are written next to it. +function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?, { [string]: any }?) + local o: Options = opts or {} + local entry, m, err, key = encoderFor(value, dest, o) + if not entry then + return nil, err + end + -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file) + -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin) + o = table.clone(o) + o.format = o.format or key + if dest then + o.name = o.name or string.match(dest, "([^/\\]+)$") + if o.files == nil then + o.files = {} + end + elseif o.files == nil and entry.caps.extraFiles then + o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages + end + if entry.category == "video" and type(value) == "table" and value.kind == "image" then + local v, verr = F.video.fromImage(value) + if not v then + return nil, verr + end + value = v + end + if entry.category == "image" and type(value) == "table" and value.kind == "video" then + local img, ierr = videoToImage(value, o) + if not img then + return nil, ierr + end + value = img + end + if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts + if not dec then + return nil, rerr + end + value = dec + end + if type(value) == "table" and value.kind == "scene" then + local terr = encodeTextures(value) + if terr then + return nil, terr + end + end + local ok, buf, e = pcall(m.encode, value, withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) + end + if buf == nil then + return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name) + end + if dest then + local wok, werr = host.writeFile(dest, buf) + if not wok then + return nil, werr + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) then + local dir = string.match(dest, "^(.*[/\\])") or "" + for fname, data in o.files do + local fok, ferr = host.writeFile(dir .. fname, if type(data) == "string" then buffer.fromstring(data) else data) + if not fok then + return nil, ferr + end + end + end + return true + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then + return buf, nil, o.files + end + return buf +end + +-- saveString(value, opts?) -> string | nil, Err +function F.saveString(value: any, opts: Options?): (string?, Err.Err?) + local buf, err = F.save(value, nil, opts) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. +function F.convert(src: any, format: string, opts: Options?): (any, Err.Err?, { [string]: any }?) + local o: Options = opts or {} + local value, err = F.load(src, o) + if value == nil then + return nil, err + end + local so = table.clone(o) + so.format = format + so.category = nil + return F.save(value, o.out, so) +end + +-- detect(src, opts?) -> format name | nil, Err +function F.detect(src: any, opts: Options?): (string?, Err.Err?) + local o: Options = opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, err = detect(buf, name, o.category, o.format) + if not entry then + return nil, err + end + -- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm) + local m = module(entry) + if m and type(m.variant) == "function" then + local ok, v = pcall(m.variant, Bytes.reader(buf)) + if ok and type(v) == "string" then + return v, nil + end + end + return entry.name, nil +end + +type FormatInfo = { name: string, category: string, extensions: { string }, mime: { string }, caps: { [string]: any } } + +-- formats(category?) -> { FormatInfo } (no format module is loaded) +function F.formats(category: string?): { FormatInfo } + local out = {} + for _, e in Registry do + if inCategory(e, category) then + table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps }) + end + end + return out +end + +-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info) +function F.format(name: string): (any, Err.Err?) + local e = find(name) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name) + end + return module(e) +end + +-- ------------------------------------------------------------------------------------------------ category facades +-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category +local function with(opts: Options?, category: string): Options + local o: Options = if opts then table.clone(opts) else {} + o.category = category + return o +end +for category in Types.CATEGORIES do + local cat: string = category + F[cat] = { + load = function(src: any, opts: Options?): (any, Err.Err?) + return F.load(src, with(opts, cat)) + end, + open = function(src: any, opts: Options?): (any, Err.Err?) + return F.open(src, with(opts, cat)) + end, + save = function(value: any, dest: string?, opts: Options?): (any, Err.Err?) + return F.save(value, dest, with(opts, cat)) + end, + formats = function(): { FormatInfo } + return F.formats(cat) + end, + } +end +F.data.null = Types.null + +-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; +-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel +-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. +for _, fn in { "toBodies", "fromBodies", "tessellate" } do + local name: string = fn + F.cad[name] = function(value: any, opts: Options?): (any, any) + local o: Options = if opts then table.clone(opts) else {} + if o.plugins == nil then + o.plugins = F.plugins + end + local m, err = F.format("step") + if not m then + return nil, err + end + local ok, a, b = pcall(m[name], value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") + end + if a == nil and type(b) == "table" and b.code then + return nil, Err.wrap(b, "step") + end + return a, b + end +end +-- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker +-- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module +for _, fn in { "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" } do + local name: string = fn + F.music[name] = function(...: any): (any, Err.Err?) + return (F.ops.music :: any)[name](...) + end +end +-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited +-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). +F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) + if type(img) ~= "table" or img.kind ~= "image" then + return nil, Err.new(Err.ARG, "fromImage: expected an Image") + end + local frames, delays = { img }, { 0.1 } + if type(img.frames) == "table" and #img.frames > 0 then + local list, cerr = ImageOps.coalesce(img) + if not list then + return nil, cerr + end + frames = list + delays = {} + for i, f in img.frames do + delays[i] = if type(f.delay) == "number" and f.delay > 0 then f.delay else 0.1 + end + elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then + local c, cerr = ImageOps.convert(img, "rgba8") + if not c then + return nil, cerr + end + frames = { c } + end + local src = type(img.meta) == "table" and img.meta.source + return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) +end +-- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence: +-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1) +F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) + return Video.fromFrames(images, delays, opts) +end +-- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) +F.video.codecs = Video + +-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or +-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images +-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose +-- image format is missing or broken keep image = nil and report an Err. +F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: Err.Err }) + local errs: { [number]: Err.Err } = {} + if type(scene) ~= "table" or type(scene.textures) ~= "table" then + return scene, errs + end + local resolve: ((any) -> any)? = opts and opts.resolve + for i, tex in scene.textures do + if type(tex) == "table" and tex.image == nil then + local data = tex.data + if data == nil and tex.uri and resolve then + data = resolve(tex.uri) + end + if data ~= nil then + local img, err = F.load(data, { category = "image", name = tex.uri, data = true }) + if img then + tex.image = img + elseif err then + errs[i] = err + end + end + end + end + return scene, errs +end + +-- ------------------------------------------------------------------------------------------------ ops +-- F.ops: editing on the standard types, loaded on first use. +-- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... +-- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... +-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves +-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, +-- concat, fade, peak, rms +-- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music) +-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector +local OPS: { [string]: () -> any } = { + image = function() + return ImageOps + end, + mesh = function() + return __include("ops/MeshOps") + end, + layers = function() + return __include("ops/LayerOps") + end, + audio = function() + return __include("ops/AudioOps") + end, + music = function() + return __include("ops/MusicOps") + end, + vector = function() + return { + rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?) + local svg, err = F.format("svg") + if not svg then + return nil, err + end + local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg") + end + if img == nil and rerr then + return nil, Err.wrap(rerr, "svg") + end + return img, rerr + end, + } + end, +} +F.ops = setmetatable({}, { + __index = function(t: any, k: string): any + local make = OPS[k] + if not make then + return nil + end + local m = make() + rawset(t, k, m) + return m + end, +}) :: any + +return F +end +__FILES["Registry"] = function() + +-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit. +-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format +-- module on first use (a static require, as Roblox needs). Order: category, then name. +type Entry = { + name: string, + category: string, + path: string, + extensions: { string }, + mime: { string }, + deps: { string }, + caps: { [string]: any }, + load: () -> any, +} + +local list: { Entry } = { + { + name = "ani", + category = "image", + path = "image/ani", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, + load = function() + return __include("image/ani") + end, + }, + { + name = "blp", + category = "image", + path = "image/blp", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, + load = function() + return __include("image/blp") + end, + }, + { + name = "bmp", + category = "image", + path = "image/bmp", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 __include("image/bmp") + end, + }, + { + name = "dds", + category = "image", + path = "image/dds", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, + load = function() + return __include("image/dds") + end, + }, + { + name = "exr", + category = "image", + path = "image/exr", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, + load = function() + return __include("image/exr") + end, + }, + { + name = "gif", + category = "image", + path = "image/gif", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 __include("image/gif") + end, + }, + { + name = "hdr", + category = "image", + path = "image/hdr", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, + load = function() + return __include("image/hdr") + end, + }, + { + name = "icns", + category = "image", + path = "image/icns", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, + load = function() + return __include("image/icns") + end, + }, + { + name = "ico", + category = "image", + path = "image/ico", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 __include("image/ico") + end, + }, + { + name = "ilbm", + category = "image", + path = "image/ilbm", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, + load = function() + return __include("image/ilbm") + end, + }, + { + name = "jpeg", + category = "image", + path = "image/jpeg", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 __include("image/jpeg") + end, + }, + { + name = "ktx", + category = "image", + path = "image/ktx", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, + load = function() + return __include("image/ktx") + end, + }, + { + name = "pcx", + category = "image", + path = "image/pcx", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, + load = function() + return __include("image/pcx") + end, + }, + { + name = "png", + category = "image", + path = "image/png", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 __include("image/png") + end, + }, + { + name = "pnm", + category = "image", + path = "image/pnm", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, + load = function() + return __include("image/pnm") + end, + }, + { + name = "qoi", + category = "image", + path = "image/qoi", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, + load = function() + return __include("image/qoi") + end, + }, + { + name = "sgi", + category = "image", + path = "image/sgi", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, + load = function() + return __include("image/sgi") + end, + }, + { + name = "sunras", + category = "image", + path = "image/sunras", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, + load = function() + return __include("image/sunras") + end, + }, + { + name = "tga", + category = "image", + path = "image/tga", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, + load = function() + return __include("image/tga") + end, + }, + { + name = "tiff", + category = "image", + path = "image/tiff", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 __include("image/tiff") + end, + }, + { + name = "tim", + category = "image", + path = "image/tim", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, + load = function() + return __include("image/tim") + end, + }, + { + name = "vtf", + category = "image", + path = "image/vtf", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, + load = function() + return __include("image/vtf") + end, + }, + { + name = "webp", + category = "image", + path = "image/webp", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 __include("image/webp") + end, + }, + { + name = "xbm", + category = "image", + path = "image/xbm", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, + load = function() + return __include("image/xbm") + end, + }, + { + name = "xpm", + category = "image", + path = "image/xpm", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, + load = function() + return __include("image/xpm") + end, + }, + { + name = "aac", + category = "audio", + path = "audio/aac", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-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 __include("audio/aac") + end, + }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return __include("audio/ac3") + end, + }, + { + name = "adpcm", + category = "audio", + path = "audio/adpcm", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, + load = function() + return __include("audio/adpcm") + end, + }, + { + name = "adx", + category = "audio", + path = "audio/adx", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, + load = function() + return __include("audio/adx") + end, + }, + { + name = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return __include("audio/aiff") + end, + }, + { + name = "ape", + category = "audio", + path = "audio/ape", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, + load = function() + return __include("audio/ape") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 __include("audio/au") + end, + }, + { + name = "brstm", + category = "audio", + path = "audio/brstm", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, + load = function() + return __include("audio/brstm") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 __include("audio/caf") + end, + }, + { + name = "flac", + category = "audio", + path = "audio/flac", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 __include("audio/flac") + end, + }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 __include("audio/m4a") + end, + }, + { + name = "mp3", + category = "audio", + path = "audio/mp3", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 __include("audio/mp3") + end, + }, + { + name = "mpc", + category = "audio", + path = "audio/mpc", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, + load = function() + return __include("audio/mpc") + end, + }, + { + name = "opus", + category = "audio", + path = "audio/opus", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 __include("audio/opus") + end, + }, + { + name = "qoa", + category = "audio", + path = "audio/qoa", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, + load = function() + return __include("audio/qoa") + end, + }, + { + name = "tta", + category = "audio", + path = "audio/tta", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, + load = function() + return __include("audio/tta") + end, + }, + { + name = "vag", + category = "audio", + path = "audio/vag", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, + load = function() + return __include("audio/vag") + end, + }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return __include("audio/voc") + end, + }, + { + name = "vorbis", + category = "audio", + path = "audio/vorbis", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + 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 __include("audio/vorbis") + end, + }, + { + name = "wav", + category = "audio", + path = "audio/wav", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, + load = function() + return __include("audio/wav") + end, + }, + { + name = "wavpack", + category = "audio", + path = "audio/wavpack", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, + load = function() + return __include("audio/wavpack") + end, + }, + { + name = "avi", + category = "video", + path = "video/avi", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, + load = function() + return __include("video/avi") + end, + }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return __include("video/fli") + end, + }, + { + name = "flv", + category = "video", + path = "video/flv", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, + load = function() + return __include("video/flv") + end, + }, + { + name = "h264", + category = "video", + path = "video/h264", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 __include("video/h264") + end, + }, + { + name = "mkv", + category = "video", + 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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, + load = function() + return __include("video/mkv") + end, + }, + { + name = "mp4", + category = "video", + 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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, + load = function() + return __include("video/mp4") + end, + }, + { + name = "mpegps", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, + load = function() + return __include("video/mpegps") + end, + }, + { + name = "mpegts", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, + load = function() + return __include("video/mpegts") + end, + }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return __include("video/ogv") + end, + }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return __include("video/smk") + end, + }, + { + name = "y4m", + category = "video", + path = "video/y4m", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 __include("video/y4m") + end, + }, + { + name = "3ds", + category = "model", + path = "model/3ds", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, + load = function() + return __include("model/3ds") + end, + }, + { + name = "3mf", + category = "model", + path = "model/3mf", + extensions = { "3mf" }, + mime = { "model/3mf" }, + 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 __include("model/3mf") + end, + }, + { + name = "b3d", + category = "model", + path = "model/b3d", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, + load = function() + return __include("model/b3d") + end, + }, + { + name = "bsp", + category = "model", + path = "model/bsp", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + load = function() + return __include("model/bsp") + end, + }, + { + name = "dae", + category = "model", + path = "model/dae", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 __include("model/dae") + end, + }, + { + name = "fbx", + category = "model", + path = "model/fbx", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 __include("model/fbx") + end, + }, + { + name = "gltf", + category = "model", + path = "model/gltf", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, + load = function() + return __include("model/gltf") + end, + }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return __include("model/iqm") + end, + }, + { + name = "ldraw", + category = "model", + path = "model/ldraw", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, + load = function() + return __include("model/ldraw") + end, + }, + { + name = "lwo", + category = "model", + path = "model/lwo", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, + load = function() + return __include("model/lwo") + end, + }, + { + name = "mca", + category = "model", + path = "model/mca", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, + load = function() + return __include("model/mca") + end, + }, + { + name = "md2", + category = "model", + path = "model/md2", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, + load = function() + return __include("model/md2") + end, + }, + { + name = "md3", + category = "model", + path = "model/md3", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, + load = function() + return __include("model/md3") + end, + }, + { + name = "md5", + category = "model", + path = "model/md5", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, + load = function() + return __include("model/md5") + end, + }, + { + name = "mdl", + category = "model", + path = "model/mdl", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, + load = function() + return __include("model/mdl") + end, + }, + { + name = "ms3d", + category = "model", + path = "model/ms3d", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, + load = function() + return __include("model/ms3d") + end, + }, + { + name = "obj", + category = "model", + path = "model/obj", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/obj") + end, + }, + { + name = "off", + category = "model", + path = "model/off", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + 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 __include("model/off") + end, + }, + { + name = "ply", + category = "model", + path = "model/ply", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + 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 __include("model/ply") + end, + }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return __include("model/pmx") + end, + }, + { + name = "qb", + category = "model", + path = "model/qb", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, + load = function() + return __include("model/qb") + end, + }, + { + name = "rbxm", + category = "model", + path = "model/rbxm", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, + load = function() + return __include("model/rbxm") + end, + }, + { + name = "rbxmx", + category = "model", + path = "model/rbxmx", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, + load = function() + return __include("model/rbxmx") + end, + }, + { + name = "robloxmesh", + category = "model", + path = "model/robloxmesh", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, + load = function() + return __include("model/robloxmesh") + end, + }, + { + name = "schematic", + category = "model", + path = "model/schematic", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, + load = function() + return __include("model/schematic") + end, + }, + { + name = "smd", + category = "model", + path = "model/smd", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, + load = function() + return __include("model/smd") + end, + }, + { + name = "stl", + category = "model", + path = "model/stl", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + 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 __include("model/stl") + end, + }, + { + name = "usda", + category = "model", + path = "model/usda", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 __include("model/usda") + end, + }, + { + name = "vox", + category = "model", + path = "model/vox", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, + load = function() + return __include("model/vox") + end, + }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return __include("model/vrml") + end, + }, + { + name = "x", + category = "model", + path = "model/x", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/x") + end, + }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return __include("model/x3d") + end, + }, + { + name = "step", + category = "cad", + path = "cad/step", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, + load = function() + return __include("cad/step") + end, + }, + { + name = "bdf", + category = "font", + path = "font/bdf", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, + load = function() + return __include("font/bdf") + end, + }, + { + name = "bmfont", + category = "font", + path = "font/bmfont", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, + load = function() + return __include("font/bmfont") + end, + }, + { + name = "eot", + category = "font", + path = "font/eot", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, + load = function() + return __include("font/eot") + end, + }, + { + name = "fon", + category = "font", + path = "font/fon", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, + load = function() + return __include("font/fon") + end, + }, + { + name = "hershey", + category = "font", + path = "font/hershey", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, + load = function() + return __include("font/hershey") + end, + }, + { + name = "pcf", + category = "font", + path = "font/pcf", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, + load = function() + return __include("font/pcf") + end, + }, + { + name = "psf", + category = "font", + path = "font/psf", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, + load = function() + return __include("font/psf") + end, + }, + { + name = "ttf", + category = "font", + path = "font/ttf", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, + load = function() + return __include("font/ttf") + end, + }, + { + name = "type1", + category = "font", + path = "font/type1", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, + load = function() + return __include("font/type1") + end, + }, + { + name = "woff", + category = "font", + path = "font/woff", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, + load = function() + return __include("font/woff") + end, + }, + { + name = "woff2", + category = "font", + path = "font/woff2", + extensions = { "woff2" }, + mime = { "font/woff2" }, + 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 __include("font/woff2") + end, + }, + { + name = "7z", + category = "archive", + path = "archive/7z", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + 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 __include("archive/7z") + end, + }, + { + name = "adf", + category = "archive", + path = "archive/adf", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, + load = function() + return __include("archive/adf") + end, + }, + { + name = "applesingle", + category = "archive", + path = "archive/applesingle", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, + load = function() + return __include("archive/applesingle") + end, + }, + { + name = "ar", + category = "archive", + path = "archive/ar", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, + load = function() + return __include("archive/ar") + end, + }, + { + name = "arj", + category = "archive", + path = "archive/arj", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, + load = function() + return __include("archive/arj") + end, + }, + { + name = "binhex", + category = "archive", + path = "archive/binhex", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, + load = function() + return __include("archive/binhex") + end, + }, + { + name = "br", + category = "archive", + path = "archive/br", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/br") + end, + }, + { + name = "bz2", + category = "archive", + path = "archive/bz2", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/bz2") + end, + }, + { + name = "cab", + category = "archive", + path = "archive/cab", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, + load = function() + return __include("archive/cab") + end, + }, + { + name = "cpio", + category = "archive", + path = "archive/cpio", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, + load = function() + return __include("archive/cpio") + end, + }, + { + name = "d64", + category = "archive", + path = "archive/d64", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, + load = function() + return __include("archive/d64") + end, + }, + { + name = "fat", + category = "archive", + path = "archive/fat", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, + load = function() + return __include("archive/fat") + end, + }, + { + name = "grp", + category = "archive", + path = "archive/grp", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, + load = function() + return __include("archive/grp") + end, + }, + { + name = "gzip", + category = "archive", + path = "archive/gzip", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, + load = function() + return __include("archive/gzip") + end, + }, + { + name = "iso", + category = "archive", + path = "archive/iso", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, + load = function() + return __include("archive/iso") + end, + }, + { + name = "lha", + category = "archive", + path = "archive/lha", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, + load = function() + return __include("archive/lha") + end, + }, + { + name = "lz4", + category = "archive", + path = "archive/lz4", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, + load = function() + return __include("archive/lz4") + end, + }, + { + name = "macbinary", + category = "archive", + path = "archive/macbinary", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, + load = function() + return __include("archive/macbinary") + end, + }, + { + name = "mpq", + category = "archive", + path = "archive/mpq", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, + load = function() + return __include("archive/mpq") + end, + }, + { + name = "pak", + category = "archive", + path = "archive/pak", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, + load = function() + return __include("archive/pak") + end, + }, + { + name = "rpm", + category = "archive", + path = "archive/rpm", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, + load = function() + return __include("archive/rpm") + end, + }, + { + name = "tar", + category = "archive", + path = "archive/tar", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, + load = function() + return __include("archive/tar") + end, + }, + { + name = "uu", + category = "archive", + path = "archive/uu", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, + load = function() + return __include("archive/uu") + end, + }, + { + name = "vpk", + category = "archive", + path = "archive/vpk", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, + load = function() + return __include("archive/vpk") + end, + }, + { + name = "wad", + category = "archive", + path = "archive/wad", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, + load = function() + return __include("archive/wad") + end, + }, + { + name = "xz", + category = "archive", + path = "archive/xz", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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 __include("archive/xz") + end, + }, + { + name = "yenc", + category = "archive", + path = "archive/yenc", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, + load = function() + return __include("archive/yenc") + end, + }, + { + name = "z", + category = "archive", + path = "archive/z", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, + load = function() + return __include("archive/z") + end, + }, + { + name = "zip", + category = "archive", + path = "archive/zip", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, + load = function() + return __include("archive/zip") + end, + }, + { + name = "zoo", + category = "archive", + path = "archive/zoo", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, + load = function() + return __include("archive/zoo") + end, + }, + { + name = "zst", + category = "archive", + path = "archive/zst", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/zst") + end, + }, + { + name = "cbor", + category = "data", + path = "data/cbor", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, + load = function() + return __include("data/cbor") + end, + }, + { + name = "csv", + category = "data", + path = "data/csv", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, + load = function() + return __include("data/csv") + end, + }, + { + name = "ini", + category = "data", + path = "data/ini", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return __include("data/ini") + end, + }, + { + name = "json", + category = "data", + path = "data/json", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, + load = function() + return __include("data/json") + end, + }, + { + name = "msgpack", + category = "data", + path = "data/msgpack", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, + load = function() + return __include("data/msgpack") + end, + }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return __include("data/nbt") + end, + }, + { + name = "plist", + category = "data", + path = "data/plist", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + 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 __include("data/plist") + end, + }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return __include("data/snbt") + end, + }, + { + name = "toml", + category = "data", + path = "data/toml", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, + load = function() + return __include("data/toml") + end, + }, + { + name = "xml", + category = "data", + path = "data/xml", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, + load = function() + return __include("data/xml") + end, + }, + { + name = "yaml", + category = "data", + path = "data/yaml", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + 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 __include("data/yaml") + end, + }, + { + name = "svg", + category = "vector", + path = "vector/svg", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 __include("vector/svg") + end, + }, + { + name = "tiled", + category = "vector", + 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/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, + caps = { decode = true, encode = true, tilesets = true, infinite = true }, + load = function() + return __include("vector/tiled") + end, + }, + { + name = "aseprite", + category = "layered", + path = "layered/aseprite", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + 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 __include("layered/aseprite") + end, + }, + { + name = "ora", + category = "layered", + path = "layered/ora", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, + load = function() + return __include("layered/ora") + end, + }, + { + name = "psd", + category = "layered", + path = "layered/psd", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 __include("layered/psd") + end, + }, + { + name = "ass", + category = "subtitle", + path = "subtitle/ass", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/ass") + end, + }, + { + name = "srt", + category = "subtitle", + path = "subtitle/srt", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, + load = function() + return __include("subtitle/srt") + end, + }, + { + name = "vtt", + category = "subtitle", + path = "subtitle/vtt", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/vtt") + end, + }, + { + name = "669", + category = "music", + path = "music/669", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, + load = function() + return __include("music/669") + end, + }, + { + name = "ahx", + category = "music", + path = "music/ahx", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, + load = function() + return __include("music/ahx") + end, + }, + { + name = "far", + category = "music", + path = "music/far", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, + load = function() + return __include("music/far") + end, + }, + { + name = "hmp", + category = "music", + path = "music/hmp", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, + load = function() + return __include("music/hmp") + end, + }, + { + name = "hvl", + category = "music", + path = "music/hvl", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, + load = function() + return __include("music/hvl") + end, + }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return __include("music/it") + end, + }, + { + name = "med", + category = "music", + path = "music/med", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/med") + end, + }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return __include("music/midi") + end, + }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mod") + end, + }, + { + name = "mtm", + category = "music", + path = "music/mtm", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mtm") + end, + }, + { + name = "mus", + category = "music", + path = "music/mus", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, + load = function() + return __include("music/mus") + end, + }, + { + name = "okt", + category = "music", + path = "music/okt", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, + load = function() + return __include("music/okt") + end, + }, + { + name = "ptm", + category = "music", + path = "music/ptm", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ptm") + end, + }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/s3m") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return __include("music/sf2") + end, + }, + { + name = "stm", + category = "music", + path = "music/stm", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, + load = function() + return __include("music/stm") + end, + }, + { + name = "ult", + category = "music", + path = "music/ult", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ult") + end, + }, + { + name = "umx", + category = "music", + path = "music/umx", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, + load = function() + return __include("music/umx") + end, + }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/xm") + end, + }, + { + name = "xmi", + category = "music", + path = "music/xmi", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, + load = function() + return __include("music/xmi") + end, + }, + { + name = "m3u", + category = "playlist", + 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/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, + load = function() + return __include("playlist/m3u") + end, + }, + { + name = "pls", + category = "playlist", + path = "playlist/pls", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/pls") + end, + }, + { + name = "xspf", + category = "playlist", + path = "playlist/xspf", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/xspf") + end, + }, +} + +return list +end +__FILES["Types"] = function() + +-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors. +-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a +-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name. +-- +-- local T = require("@rosetta/Types") +-- local img = T.Image.new(64, 32) -- rgba8, zero-filled +-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32 +-- +-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels. +local Err = __include("core/Err") + +local Types = {} + +type Err = Err.Err + +-- ------------------------------------------------------------------------------------------------ Image +-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the +-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each). +type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p" +local BPP: { [string]: number } = { + rgba8 = 4, + rgba16 = 8, + rgbaf32 = 16, + rgb8 = 3, + gray8 = 1, + gray16 = 2, + graya8 = 2, + alpha8 = 1, +} +Types.BPP = table.freeze(BPP) :: { [string]: number } + +type ImageMeta = { + colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ... + gamma: number?, + icc: buffer?, -- the raw ICC profile + exif: buffer?, -- the raw EXIF block (TIFF header onwards) + dpi: { x: number, y: number }?, + palette: { { number } }?, -- { r, g, b, a } 0..255 per entry, for palette sources + text: { [string]: string }?, -- tEXt / comments + source: { format: string, bitDepth: number?, colorType: string?, [string]: any }?, + [string]: any, +} + +-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y +type Frame = { + image: Image, + delay: number, -- seconds + x: number, + y: number, + dispose: "none" | "background" | "previous", + blend: "source" | "over", +} + +type Image = { + kind: "image", + width: number, + height: number, + format: PixelFormat, + pixels: buffer, + frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame) + 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, +} + +local Image = {} +-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8) +function Image.new(width: number, height: number, format: PixelFormat?): Image + local f: PixelFormat = format or "rgba8" + local size + if f == "yuv420p" then + local cw, ch = (width + 1) // 2, (height + 1) // 2 + size = width * height + 2 * cw * ch + else + size = width * height * (BPP[f] or 4) + end + return { + kind = "image", + width = width, + height = height, + format = f, + pixels = buffer.create(size), + frames = nil, + loops = 0, + meta = {}, + } +end +-- bpp(format) -> bytes per pixel (nil for planar formats) +function Image.bpp(format: string): number? + return BPP[format] +end +Types.Image = Image + +-- ------------------------------------------------------------------------------------------------ Audio +type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ... + +-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share) +type Decoder = { + sampleRate: number, + channels: number, + frames: number, -- total sample frames (estimate for VBR streams without an index), 0 = unknown + duration: number, -- seconds + bitrate: number, -- bits per second (average) + tags: Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end); out (if given) is reused when big enough + read: (self: any, n: number, out: buffer?) -> (buffer, number), + seek: (self: any, seconds: number) -> (), + position: (self: any) -> number, -- seconds +} + +-- a fully decoded sound (F.load / F.audio.load) +type Audio = { + kind: "audio", + sampleRate: number, + channels: number, + frames: number, + samples: buffer, -- interleaved f32, frames * channels * 4 bytes + tags: Tags, + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +local Audio = {} +function Audio.new(sampleRate: number, channels: number, frames: number): Audio + return { + kind = "audio", + sampleRate = sampleRate, + channels = channels, + frames = frames, + samples = buffer.create(frames * channels * 4), + tags = {}, + meta = {}, + } +end +Types.Audio = Audio + +-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI) +type Module = { + kind: "music", + title: string, + format: string, -- "mod", "s3m", "xm", "it" (codecs/audio/Tracker); "ahx", "hvl" (codecs/audio/Hively, own render) + channels: number, + patterns: { any }, + order: { number }, + instruments: { any }, + samples: { any }, + render: (self: any, opts: any?) -> Decoder, -- every music file is also audio + meta: { [string]: any }, +} + +type MidiEvent = { tick: number, type: string, channel: number?, data: { number }?, meta: any? } +type Midi = { + kind: "midi", + format: number, -- SMF 0 / 1 / 2 + division: number, -- ticks per quarter note (or SMPTE, negative) + tracks: { { events: { MidiEvent }, name: string? } }, + meta: { [string]: any }, + render: ((self: any, opts: any?) -> Decoder)?, -- set by music/midi decode: the SoundFont synth as an audio Decoder +} +local Midi = {} +function Midi.new(division: number?): Midi + return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } +end +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/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 +-- / duration and every `duration` / `seek` argument are seconds. +type Track = { + id: number, -- the container's track number (Matroska TrackNumber, AVI stream index + 1, TS PID, ...) + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- our codec id: "vp8", "mjpeg", "mpeg1", "h264", "rawvideo"; "pcm_s16le", "mp3", "opus", "vorbis", ... + codecTag: string?, -- the container's own id ("V_VP8", "MJPG", stream_type "0x01", "avc1", ...) + timescale: number, -- ticks per second for pts / dts / duration + duration: number?, -- seconds + default: boolean?, + language: string?, + name: string?, + -- video + width: number?, + height: number?, + frameRate: number?, -- frames per second (nominal; 0 / nil when unknown) + pixelFormat: string?, -- raw video: "yuv420p", "rgb24", "bgr24", ... + -- audio + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + codecDelay: number?, -- seconds of decoder output to drop at the start (encoder priming: Matroska CodecDelay, the + -- first edit's media time of an MP4 audio track) + playDuration: number?, -- seconds to play after the codec delay (an MP4 edit list's length: the end padding cut) + config: buffer?, -- codec configuration (CodecPrivate, avcC, OpusHead, Vorbis headers, AVI strf extra, ...) + [string]: any, +} +type Packet = { + track: number, -- Track.id + pts: number, -- presentation time, ticks + dts: number?, -- decode time, ticks (nil = pts) + duration: number?, -- ticks + keyframe: boolean, + data: buffer, -- the packet's bytes (its own buffer) +} +type Demuxer = { + kind: "demuxer", + format: string, -- the container format name + tracks: { Track }, + duration: number, -- seconds (0 = unknown) + startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it) + meta: { [string]: any }, -- title, tags, ... + -- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position + packets: (self: any, track: number?) -> () -> Packet?, + -- read(trackId?) -> the next Packet (one track, or any) | nil at the end + read: (self: any, track: number?) -> Packet?, + -- seek(seconds): every track to its last keyframe at or before the time + seek: (self: any, seconds: number) -> (), + track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind +} +type VideoFrame = { + image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed) + pts: number, -- seconds from the start of the stream (the demuxer's startTime) + duration: number, -- seconds + keyframe: boolean?, + index: number, -- 1-based, in output order +} +type VideoDecoder = { + kind: "video", + format: string, -- the container format name ("mkv", "avi", "gif", ...) + codec: string, -- the video codec id ("vp8", "mjpeg", "frames" for animated images) + width: number, + height: number, + frameRate: number, -- frames per second (nominal) + frames: number, -- frame count when known (0 = unknown) + duration: number, -- seconds + track: Track?, -- the video track decoded + nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end + toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8) + seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it) + reset: (self: any) -> (), -- back to the start + audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError) + audioError: Err?, + demuxer: Demuxer?, -- nil for frames-backed videos (animated images) + meta: { [string]: any }, +} +-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out +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 + flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive() + reset: (self: any) -> (), -- after a seek: drop references / held pictures +} + +-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) +-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no +-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255, +-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the +-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load. +-- +-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference +-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the +-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture +-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write +-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil, +-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you. +-- +-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look +-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it +-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the +-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`. +type Accessor = { + data: buffer, -- tightly packed, little endian + type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16", + components: number, -- 1 (SCALAR) .. 4 (VEC4), 4 (MAT2), 9 (MAT3), 16 (MAT4) + count: number, + matrix: boolean?, -- components 4 / 9 / 16 are MAT2 / MAT3 / MAT4 (glTF), not VEC4 + name: string?, +} +type Primitive = { + attributes: { [string]: Accessor }, -- POSITION, NORMAL, TANGENT, TEXCOORD_n, COLOR_n, JOINTS_n, WEIGHTS_n; custom + -- attributes start with "_" (glTF convention: PLY extra vertex properties, ...) + indices: Accessor?, + -- "polygons": faces (u32, one size per face) splits indices into n-gons (OBJ / PLY / OFF with triangulate = false; + -- MeshOps.triangulate turns them into triangles) + mode: "triangles" | "lines" | "points" | "triangle_strip" | "triangle_fan" | "line_strip" | "line_loop" | "polygons", + faces: Accessor?, + material: number?, -- index into scene.materials (1-based) + targets: { { [string]: Accessor } }?, -- morph targets (POSITION / NORMAL / TANGENT deltas) + extras: { [string]: any }?, +} +type Mesh = { name: string?, primitives: { Primitive }, weights: { number }?, extras: { [string]: any }? } +type Sampler = { + wrapS: ("repeat" | "clamp" | "mirror")?, -- default "repeat" + wrapT: ("repeat" | "clamp" | "mirror")?, + filter: ("linear" | "nearest")?, -- magnification + minFilter: string?, -- "nearest" | "linear" | "nearest_mipmap_nearest" | ... (glTF names, lower case) +} +type Texture = { + name: string?, + image: Image?, -- decoded (F.model.loadTextures or the caller), never by a model format + data: buffer?, -- the encoded image bytes (embedded / GLB / data: URI / resolved external file) + mime: string?, -- "image/png", "image/jpeg", "image/webp", "image/ktx2", ... + uri: string?, -- the external file name (relative to the model) when the data was not available or not embedded + sampler: Sampler?, + extras: { [string]: any }?, +} +type TextureRef = { + texture: number, -- index into scene.textures (1-based) + texCoord: number?, -- TEXCOORD_n set (default 0) + scale: number?, -- normalTexture scale + strength: number?, -- occlusionTexture strength + -- KHR_texture_transform (texCoord overrides the ref's texCoord) + transform: { offset: { number }?, scale: { number }?, rotation: number?, texCoord: number? }?, +} +type Material = { + name: string?, + baseColor: { number }, -- r, g, b, a linear 0..1 + baseColorTexture: TextureRef?, + metallic: number, + roughness: number, + metallicRoughnessTexture: TextureRef?, + normalTexture: TextureRef?, + occlusionTexture: TextureRef?, + emissive: { number }, + emissiveTexture: TextureRef?, + alphaMode: "opaque" | "mask" | "blend", + alphaCutoff: number, + doubleSided: boolean, + -- glTF material extensions by name (KHR_materials_emissive_strength = { emissiveStrength = 5 }, KHR_materials_unlit + -- = {}, ...), their fields as in glTF except textureInfo objects, which are TextureRefs + extensions: { [string]: any }?, + extras: { [string]: any }?, -- classic Phong (OBJ / FBX): ambient, diffuse, specular, shininess, ... +} +type Node = { + name: string?, + children: { number }, -- node indices (1-based) + mesh: number?, + camera: number?, + light: number?, + skin: number?, + voxels: number?, -- index into scene.voxels (MagicaVoxel shapes; MeshOps.meshVoxels gives them meshes) + translation: { number }?, -- TRS, or matrix (column-major 4x4), not both + rotation: { number }?, -- quaternion x, y, z, w + scale: { number }?, + matrix: { number }?, + weights: { number }?, -- morph target weights + extras: { [string]: any }?, +} +type Camera = { name: string?, type: "perspective" | "orthographic", yfov: number?, aspect: number?, xmag: number?, ymag: number?, znear: number, zfar: number? } +type Light = { name: string?, type: "directional" | "point" | "spot", color: { number }, intensity: number, range: number?, innerCone: number?, outerCone: number? } +type Skin = { name: string?, joints: { number }, inverseBindMatrices: Accessor?, skeleton: number? } +type Channel = { node: number, path: "translation" | "rotation" | "scale" | "weights", input: Accessor, output: Accessor, interpolation: "LINEAR" | "STEP" | "CUBICSPLINE" } +type Animation = { name: string?, channels: { Channel } } + +-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index +type VoxelMaterial = { type: string, [string]: any } -- "diffuse" | "metal" | "glass" | "emit" | "blend" | "media" | ..., MATL properties (numbers when numeric) +type Voxels = { + kind: "voxels", + name: string?, + size: { number }, -- x, y, z cells + data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) + palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) + materials: { [number]: VoxelMaterial }?, -- by palette index + -- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its + -- colour view (block colours from a default table) + blocks: VoxelBlocks?, + -- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian, + -- a = 0 empty), data / palette being an indexed view of it + colors: buffer?, +} +type VoxelBlocks = { + palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0 + data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette + blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid) + entities: { any }?, -- entity records (NBT compounds) +} +local Voxels = {} +-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) +function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels + local pal = palette + if not pal then + local p = table.create(255) + for i = 1, 255 do + p[i] = { i, i, i, 255 } + end + pal = p + end + return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil } +end +-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check +function Voxels.get(v: Voxels, x: number, y: number, z: number): number + return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) +end +function Voxels.set(v: Voxels, x: number, y: number, z: number, index: number) + buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) +end +Types.Voxels = Voxels + +type Scene = { + kind: "scene", + nodes: { Node }, + roots: { number }, -- top-level node indices + meshes: { Mesh }, + materials: { Material }, + textures: { Texture }, + cameras: { Camera }, + lights: { Light }, + skins: { Skin }, + animations: { Animation }, + voxels: { Voxels }?, -- voxel grids (VOX), referenced by node.voxels + meta: { up: "y" | "z"?, unit: number?, source: { format: string, [string]: any }?, [string]: any }, +} + +local Scene = {} +function Scene.new(): Scene + return { + kind = "scene", + nodes = {}, + roots = {}, + meshes = {}, + materials = {}, + textures = {}, + cameras = {}, + lights = {}, + skins = {}, + animations = {}, + voxels = nil, + meta = {}, + } +end +-- the byte size of one component of an accessor type +local COMPONENT_SIZE: { [string]: number } = { + f32 = 4, + f64 = 8, + u8 = 1, + u16 = 2, + u32 = 4, + i8 = 1, + i16 = 2, + i32 = 4, + unorm8 = 1, + unorm16 = 2, + snorm8 = 1, + snorm16 = 2, +} +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)) + return { data = d, type = type, components = components, count = count } +end +function Scene.material(name: string?): Material + return { + name = name, + baseColor = { 1, 1, 1, 1 }, + metallic = 1, + roughness = 1, + emissive = { 0, 0, 0 }, + alphaMode = "opaque", + alphaCutoff = 0.5, + doubleSided = false, + } +end +-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF) +function Scene.fromPrimitive(prim: Primitive, name: string?): Scene + local s = Scene.new() + s.meshes[1] = { name = name, primitives = { prim } } + s.nodes[1] = { name = name, children = {}, mesh = 1 } + s.roots[1] = 1 + return s +end +Types.Scene = Scene + +-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted +-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type. +function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)? + local d, n, t = acc.data, acc.components, acc.type + local size = COMPONENT_SIZE[t] + if not size or type(d) ~= "buffer" then + return nil + end + local stride = n * size + local rb = buffer + if t == "f32" then + local f = rb.readf32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "f64" then + local f = rb.readf64 + return function(i: number, c: number): number + return f(d, i * stride + c * 8) + end + elseif t == "u8" or t == "unorm8" then + local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c) * k + end + elseif t == "u16" or t == "unorm16" then + local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) * k + end + elseif t == "u32" then + local f = rb.readu32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + elseif t == "i8" then + local f = rb.readi8 + return function(i: number, c: number): number + return f(d, i * stride + c) + end + elseif t == "snorm8" then + local f = rb.readi8 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c) / 127, -1) + end + elseif t == "i16" then + local f = rb.readi16 + return function(i: number, c: number): number + return f(d, i * stride + c * 2) + end + elseif t == "snorm16" then + local f = rb.readi16 + return function(i: number, c: number): number + return math.max(f(d, i * stride + c * 2) / 32767, -1) + end + elseif t == "i32" then + local f = rb.readi32 + return function(i: number, c: number): number + return f(d, i * stride + c * 4) + end + end + return nil +end + +-- the identity and products of column-major 4x4 matrices (flat arrays of 16) +local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) +Scene.IDENTITY = IDENTITY +function Scene.mul(a: { number }, b: { number }): { number } + local m = table.create(16, 0) + for col = 0, 3 do + for row = 0, 3 do + local s = 0 + for k = 0, 3 do + s += a[k * 4 + row + 1] * b[col * 4 + k + 1] + end + m[col * 4 + row + 1] = s + end + end + return m +end +-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S) +function Scene.nodeMatrix(node: Node): { number } + if node.matrix and #node.matrix == 16 then + return node.matrix + end + local t, r, sc = node.translation, node.rotation, node.scale + if not t and not r and not sc then + return IDENTITY + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + end + local x, y, z, w = 0, 0, 0, 1 + if r then + x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1 + end + local sx, sy, sz = 1, 1, 1 + if sc then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + end + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0, + (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0, + (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0, + tx, ty, tz, 1, + } +end +type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number } +-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots +-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent. +function Scene.flatten(scene: Scene): { Placed } + local out: { Placed } = {} + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + local seen: { [number]: boolean } = {} + local function visit(i: number, parent: { number }) + local node = nodes[i] + if not node or seen[i] then + return + end + seen[i] = true + local m = Scene.nodeMatrix(node) + local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m) + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + for _, p in mesh.primitives do + table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number }) + end + end + for _, c in node.children or {} do + visit(c, world) + end + end + for _, r in roots do + visit(r, IDENTITY) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ Cad +-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Rosetta.plugins.brep) +-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; +-- section = the DATA section index when a file has more than one (edition 3) +type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? } +type Cad = { + kind: "cad", + schema: string, -- "AP203", "AP214", "AP242", ... + header: { [string]: any }, + entities: { [number]: StepEntity }, + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ Font +type Font = { + kind: "font", + info: { family: string?, style: string?, fullName: string?, [string]: any }, + unitsPerEm: number, + ascent: number, + descent: number, + lineGap: number, + glyphIndex: (self: any, codepoint: number) -> number, -- 0 = .notdef + advance: (self: any, glyph: number) -> number, -- font units + kern: (self: any, a: number, b: number) -> number, + outline: (self: any, glyph: number) -> { { op: string, [number]: number } }?, -- moveTo / lineTo / quadTo / cubicTo + rasterize: (self: any, glyph: number, px: number) -> Image?, -- alpha8 + pages: { Image }?, -- bitmap fonts (BMFont) + bitmap: BitmapStrike?, -- bitmap fonts with per-glyph bitmaps (BDF, PCF, PSF, FON): codecs/font/Bitmap + meta: { [string]: any }, +} +-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline +type BitmapGlyph = { + codepoint: number?, -- Unicode (nil for unencoded glyphs) + name: string?, -- glyph name (BDF STARTCHAR, PCF glyph names, PostScript names) + width: number, -- bitmap width / height in pixels + height: number, + left: number, -- x of the bitmap's left column relative to the pen + top: number, -- y of the bitmap's top row above the baseline (BDF: BBXoff + BBh) + advance: number, -- pen advance in pixels + pixels: buffer, -- u8 per pixel (width * height, rows top down): 0 = off, 255 = on (grey fonts use 1..254) +} +type BitmapStrike = { + size: number, -- pixel size (em height in pixels) + ascent: number, -- pixels above the baseline + descent: number, -- pixels below the baseline (positive) + glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph) + default: number?, -- glyph index (0-based) used for unmapped code points + map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph) +} + +-- ------------------------------------------------------------------------------------------------ Archive +type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean } +type Archive = { + kind: "archive", + format: string, + list: (self: any) -> { ArchiveEntry }, + read: (self: any, name: string) -> (buffer?, Err?), + add: (self: any, name: string, data: buffer | string, opts: any?) -> (), + write: (self: any, opts: any?) -> (buffer?, Err?), + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ Data +-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a +-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers. +local nullMeta = { __tostring = function() + return "null" +end } +Types.null = table.freeze(setmetatable({}, nullMeta)) + +-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry +-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked +-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted). +-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" }) +-- Types.set(o, "c", 3) -- assigns and appends "c" to the order +-- for _, k in Types.keys(o) do ... end +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: { [any]: any } = t or {} + if getmetatable(o) == nil then + setmetatable(o, OBJECT) + end + objectMeta[o] = keys or {} + return o +end +-- isObject(v) -> true for tables made by Types.object +function Types.isObject(v: any): boolean + return type(v) == "table" and objectMeta[v] ~= nil +end +-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns) +function Types.set(o: { [any]: any }, k: any, v: any) + local order = objectMeta[o] + if order and o[k] == nil and v ~= nil then + table.insert(order, k) + 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 + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + 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 } + local order = objectMeta[t] + local out, seen = {}, {} + if order then + for _, k in order do + if t[k] ~= nil and not seen[k] then + seen[k] = true + table.insert(out, k) + end + end + end + local rest = {} + for k in next, t do + if not seen[k] then + table.insert(rest, k) + end + end + if #rest > 0 then + table.sort(rest, keyLess) + table.move(rest, 1, #rest, #out + 1, out) + end + return out +end + +-- Dates and times (TOML datetimes, plist , CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the +-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes +-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...). +type Date = { + kind: "datetime" | "datetime-local" | "date-local" | "time-local", + year: number?, + month: number?, + day: number?, + hour: number?, + minute: number?, + second: number?, + nanosecond: number?, -- 0 .. 999999999 + offset: number?, -- minutes east of UTC +} +local DateMeta = {} +local function p2(n: number): string + return string.format("%02d", n) +end +local function fmtDate(d: any): string + 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 = s .. "T" + end + s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) + local ns = d.nanosecond or 0 + if ns > 0 then + local f = string.format("%09d", ns) + s ..= "." .. (string.gsub(f, "0+$", "")) + end + if d.offset then + if d.offset == 0 then + s ..= "Z" + else + local o = math.abs(d.offset) + s ..= (if d.offset < 0 then "-" else "+") .. p2(o // 60) .. ":" .. p2(o % 60) + end + end + end + return s +end +DateMeta.__tostring = fmtDate +DateMeta.__eq = function(a: any, b: any): boolean + return fmtDate(a) == fmtDate(b) and a.kind == b.kind +end +local DateLib = {} +-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm) +local function daysFromCivil(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = (m + 9) % 12 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end +local function civilFromDays(z: number): (number, number, number) + z += 719468 + local era = (if z >= 0 then z else z - 146096) // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + 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) +DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01 +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 + local d: any = {} + for k, v in f do + d[k] = v + end + if d.kind == nil then + d.kind = if d.year and d.hour then (if d.offset then "datetime" else "datetime-local") + elseif d.year then "date-local" + else "time-local" + end + return setmetatable(d, DateMeta) :: any +end +-- is(v) -> true for Dates +function DateLib.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == DateMeta +end +-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...) +function DateLib.valid(d: Date): boolean + if d.year then + local y, m, dd = d.year, d.month or 0, d.day or 0 + if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then + return false + end + if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then + return false + end + end + if d.hour then + if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then + return false + end + end + if d.offset and math.abs(d.offset) >= 24 * 60 then + return false + end + return true +end +-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27", +-- "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: 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 :: string + if rest == "" then + return if DateLib.valid(d) then DateLib.new(d) else nil + end + local sep = string.sub(rest, 1, 1) + if sep ~= "T" and sep ~= "t" and sep ~= " " then + return nil + end + rest = string.sub(rest, 2) + end + local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$") + if not h then + return nil + end + d.hour, d.minute = tonumber(h), tonumber(mi) + rest = r2 :: string + local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") + if not sec then + return nil + end + d.second = tonumber(sec) + rest = r3 :: string + local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") + if frac then + d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) + rest = r4 :: string + else + d.nanosecond = 0 + end + if rest ~= "" then + if not d.year then + return nil + end + if rest == "Z" or rest == "z" then + d.offset = 0 + else + local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$") + if not sign then + return nil + end + local oh_n, om_n = tonumber(oh) :: number, tonumber(om) :: number + if oh_n > 23 or om_n > 59 then + return nil + end + d.offset = (oh_n * 60 + om_n) * (if sign == "-" then -1 else 1) + end + end + return if DateLib.valid(d) then DateLib.new(d) else nil +end +-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC) +function DateLib.toUnix(d: Date): number + local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0 + local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60 + return s + (d.nanosecond or 0) / 1e9 +end +-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC) +function DateLib.fromUnix(t: number, offset: number?): Date + local off = offset or 0 + local whole = math.floor(t) + local ns = math.floor((t - whole) * 1e9 + 0.5) + if ns >= 1e9 then + whole += 1 + ns -= 1e9 + end + local lt = whole + off * 60 + local days = lt // 86400 + local secs = lt - days * 86400 + local y, m, dd = civilFromDays(days) + return DateLib.new({ + kind = "datetime", + year = y, + month = m, + day = dd, + hour = secs // 3600, + minute = (secs // 60) % 60, + second = secs % 60, + nanosecond = ns, + offset = off, + }) +end +Types.Date = table.freeze(DateLib) + +-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with +-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings. +type XmlNode = { + name: string, + attrs: { [string]: string }, + children: { XmlNode | string }, + parent: XmlNode?, + text: string?, -- "#comment" / "#cdata" / "#pi" (the data after the target) / "#doctype" content + target: string?, -- "#pi": the target + ns: string?, -- the namespace URI (opts.namespaces) + [string]: any, +} + +-- ------------------------------------------------------------------------------------------------ Vector +type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any } +type VectorPath = { + d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands + fill: Paint?, + fillRule: "nonzero" | "evenodd", + stroke: Paint?, + strokeWidth: number, + transform: { number }?, -- a, b, c, d, e, f + opacity: number, + group: number?, -- index into meta.groups (svg 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?, +} +type Vector = { + kind: "vector", + width: number, + height: number, + viewBox: { number }, -- x, y, w, h + paths: { VectorPath }, + meta: { [string]: any }, +} +local Vector = {} +function Vector.new(width: number, height: number): Vector + return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } +end +Types.Vector = Vector + +-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite) +-- 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`). +type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? } +type Layer = { name: string, image: Image, x: number, y: number, opacity: number, blend: string, visible: boolean, children: { Layer }?, clip: boolean?, mask: LayerMask? } +type Layered = { + kind: "layered", + width: number, + height: number, + layers: { Layer }, -- bottom to top (a tree: groups have children); animations: frame 1's layers + frames: { { layers: { Layer }, delay: number } }?, -- animations (Aseprite): every frame's layers, delay in seconds + meta: { [string]: any }, +} +local Layered = {} +function Layered.new(width: number, height: number): Layered + return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } +end +-- layer(name, image, x?, y?) -> a visible normal layer at full opacity +function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer + return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } +end +-- group(name, children) -> a pass-through group layer +function Layered.group(name: string, children: { Layer }): Layer + return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children } +end +Types.Layered = Layered + +-- ------------------------------------------------------------------------------------------------ TileMap (Tiled) +-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept). +-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller +-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite +-- maps, objects' shapes, per-tile data, ...: see vector/tiled). +type Tileset = { name: string, firstGid: number, tileWidth: number, tileHeight: number, columns: number, count: number, image: Image?, source: string?, [string]: any } +type TileLayer = { name: string, type: "tiles" | "objects" | "image" | "group", width: number?, height: number?, data: { number }?, objects: { any }?, visible: boolean, opacity: number, properties: { [string]: any }, [string]: any } +type TileMap = { + kind: "tilemap", + width: number, + height: number, + tileWidth: number, + tileHeight: number, + orientation: string, + tilesets: { Tileset }, + layers: { TileLayer }, + properties: { [string]: any }, + meta: { [string]: any }, + [string]: any, +} +local TileMap = {} +function TileMap.new(width: number, height: number, tileWidth: number, tileHeight: number): TileMap + return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } +end +Types.TileMap = TileMap + +-- ------------------------------------------------------------------------------------------------ Subtitles +type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds +type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } } +local Subtitles = {} +function Subtitles.new(): Subtitles + return { kind = "subtitles", cues = {}, styles = {}, meta = {} } +end +Types.Subtitles = Subtitles + +-- ------------------------------------------------------------------------------------------------ Playlist +-- the playlist-luau shape +type PlaylistEntry = { + url: string, + title: string?, + duration: number?, + playable: boolean, + reason: string?, + bandwidth: number?, + codecs: string?, + attributes: { [string]: string }?, + byteRange: { length: number, offset: number? }?, +} +type Playlist = { + kind: "playlist", + format: string, -- "m3u", "pls", "hls", "xspf" + entries: { PlaylistEntry }, + warnings: { string }, + title: string?, + hls: { [string]: any }?, + meta: { [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ the format contract +-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) +type Caps = { decode: boolean, encode: boolean, [string]: any } +type Format = { + name: string, + category: string, + extensions: { string }, + mime: { string }, + deps: { string }, + sniff: (r: any) -> number, -- confidence 0..1 from the first bytes (a core/Bytes Reader); must not consume / throw + decode: ((r: any, opts: any?) -> (any, Err?))?, + encode: ((value: any, opts: any?) -> (buffer?, Err?))?, + open: ((r: any, opts: any?) -> (any, Err?))?, -- streaming categories (audio / video) + caps: Caps, +} + +-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to +Types.CATEGORIES = table.freeze({ + image = "image", + audio = "audio", + video = "video", + model = "scene", + cad = "cad", + font = "font", + archive = "archive", + data = "data", + vector = "vector", + layered = "layered", + subtitle = "subtitles", + music = "music", + playlist = "playlist", +} :: { [string]: string }) + +return Types +end +__FILES["archive/7z"] = function() + +-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose +-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) +-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / +-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, +-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, +-- Windows / Unix attributes, folder and file CRC-32s (verified on read). +-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other +-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") +local Header = __include("archive/7z/Header") + +-- ------------------------------------------------------------------------------------------------ contract +local SevenZip = { + name = "7z", + category = "archive", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + 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 }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30) + checkCrc: boolean?, -- verify CRC-32s on read (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "7z\188\175\39\28" + +-- method id -> xz filter id (BCJ / delta) +local FILTERS: { [string]: number } = { + ["\3\3\1\3"] = 0x04, -- x86 + ["\3\3\2\5"] = 0x05, -- PowerPC + ["\3\3\5\1"] = 0x07, -- ARM + ["\3\3\7\1"] = 0x08, -- ARM-Thumb + ["\3\3\8\5"] = 0x09, -- SPARC + ["\10"] = 0x0A, -- ARM64 + ["\3"] = 0x03, -- delta +} +local NAMES: { [string]: string } = { + ["\0"] = "copy", + ["\3\1\1"] = "lzma", + ["\33"] = "lzma2", + ["\4\1\8"] = "deflate", + ["\4\1\9"] = "deflate64", + ["\4\2\2"] = "bzip2", + ["\3\4\1"] = "ppmd", + ["\3\3\1\27"] = "bcj2", + ["\6\241\7\1"] = "aes", + ["\4\247\17\1"] = "zstd", + ["\4\247\17\2"] = "brotli", + ["\3\3\1\3"] = "bcj", + ["\3\3\2\5"] = "ppc", + ["\3\3\5\1"] = "arm", + ["\3\3\7\1"] = "armt", + ["\3\3\8\5"] = "sparc", + ["\10"] = "arm64", + ["\3"] = "delta", +} + +local function methodName(id: string): string + local n = NAMES[id] + if n then + return n + end + local hex = {} + for i = 1, #id do + table.insert(hex, string.format("%02x", string.byte(id, i))) + end + return "method " .. table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function SevenZip.sniff(r: Bytes.Reader): number + return if r:peek(6) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream +type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number } + +local function packStart(ctx: Ctx, s: Header.Streams, index: number): number + local p = ctx.base + 32 + s.packPos + for i = 1, index do + p += s.packSizes[i] + end + return p +end + +local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) + -- coder -> first in / out stream index + local inBase, outBase = {}, {} + local ni, no = 0, 0 + for i, c in f.coders do + inBase[i], outBase[i] = ni, no + ni += c.numIn + no += c.numOut + end + local depth = 0 + local function out(outIdx: number): (buffer?, Err.Err?) + depth += 1 + if depth > 32 then + return nil, Err.new(Err.CORRUPT, "coder graph too deep") + end + local ci + for i, c in f.coders do + if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then + ci = i + end + end + if not ci then + return nil, Err.new(Err.CORRUPT, "bad bind pair") + end + local c = f.coders[ci] + if c.numIn ~= 1 or c.numOut ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") + end + local size = f.unpackSizes[outIdx + 1] or 0 + if size > ctx.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) + end + -- the coder's input: another coder's output, or a packed stream + local inIdx = inBase[ci] + local src: buffer, so: number, sl: number + local bound = nil + for _, bp in f.bindPairs do + if bp.inIndex == inIdx then + bound = bp.outIndex + end + end + if bound then + local b, e = out(bound) + if not b then + return nil, e + end + src = b + so = 0 + sl = buffer.len(b) + else + local k = table.find(f.packed, inIdx) + if not k then + return nil, Err.new(Err.CORRUPT, "unbound coder input") + end + local pi = f.firstPack + k - 1 + if pi >= #s.packSizes then + return nil, Err.new(Err.CORRUPT, "missing pack stream") + end + so = packStart(ctx, s, pi) + sl = s.packSizes[pi + 1] + if so + sl > ctx.limit or so < ctx.base then + return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) + end + src = ctx.buf + end + local id = c.id + 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, nil + elseif id == "\3\1\1" then + if buffer.len(c.props) < 5 then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties") + end + local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) + return b, if b then nil else e + elseif id == "\33" then + local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) + return b, if b then nil else e + elseif id == "\4\1\8" then + local b, e = Deflate.inflate(src, so, sl, size) + return b, if b then nil else e + elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames) + local b, e + if id == "\4\2\2" then + b, e = Bzip2.decompress(src, so, sl, opts) + else + b, e = Zstd.decompress(src, so, sl, opts) + end + if not b then + return nil, e + end + if buffer.len(b) ~= size then + return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") + end + return b, nil + elseif FILTERS[id] then + if sl ~= size then + return nil, Err.new(Err.CORRUPT, "filter size mismatch") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) + if not ok then + return nil, e + end + return b, nil + end + return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") + end + local main = Header.mainOut(f) + if not main then + return nil, Err.new(Err.CORRUPT, "folder without a main output") + end + return out(main) +end + +local function folderMethod(f: Header.Folder): string + local names = {} + for _, c in f.coders do + table.insert(names, methodName(c.id)) + end + return table.concat(names, "+") +end + +function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + 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 + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) + end + if buffer.readstring(b, base, 6) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) + end + if buffer.readu8(b, base + 6) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) + end + if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then + return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) + end + local hr = Bytes.reader(b, base + 12, 20) + local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() + local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes } + local a = Archive.new("7z") + if nextSize == 0 then + return a, nil -- an empty archive + end + local ho = base + 32 + nextOff + if nextOff < 0 or ho + nextSize > limit then + return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) + end + if Crc32.raw(b, ho, nextSize) ~= nextCrc then + return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) + end + local hbuf, hoff, hlen = b, ho, nextSize + local parsed + for _ = 1, 4 do + local p, perr = Header.parse(hbuf, hoff, hlen) + if not p then + return nil, perr + end + if not p.encoded then + parsed = p + break + end + -- an encoded header: decode folder 1 of its streams, then parse again + local es = p.encoded + local f = es.folders[1] + if not f then + return nil, Err.new(Err.CORRUPT, "encoded header without a folder") + end + local hb, herr = decodeFolder(ctx, es, f) + if not hb then + return nil, herr + end + 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 = hb + hoff = 0 + hlen = buffer.len(hb) + end + if not parsed then + return nil, Err.new(Err.CORRUPT, "nested encoded headers") + end + 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: { number }, subOffset: { number } = {}, {} + do + local si = 1 + for fi, f in s.folders do + if f.numSub > 1 then + a.meta.solid = true + end + local off = 0 + for _ = 1, f.numSub do + subFolder[si], subOffset[si] = fi, off + off += s.subSizes[si] or 0 + si += 1 + end + if off > Header.unpackSize(f) then + return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") + end + end + end + local function folderData(fi: number): (buffer?, Err.Err?) + local c = cache[fi] + if c then + return c, nil + end + local f = s.folders[fi] + local d, e = decodeFolder(ctx, s, f) + if not d then + return nil, e + end + if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") + end + cache[fi] = d + return d, nil + end + local si = 0 + for _, file in parsed.files do + if file.anti then + continue + end + local attr = file.attributes + local isDir = file.emptyStream and not file.emptyFile + if attr and bit32.band(attr, 0x10) ~= 0 then + isDir = true + end + local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil + local e: Archive.Entry = { + name = file.name, + size = 0, + dir = isDir, + mtime = file.mtime, + attributes = attr, + mode = mode, + } + if not file.emptyStream then + si += 1 + local idx = si + local fi = subFolder[idx] + if not fi then + return nil, Err.new(Err.CORRUPT, "more files than streams") + end + local size = s.subSizes[idx] + e.size = size + e.method = folderMethod(s.folders[fi]) + if s.folders[fi].numSub == 1 then + local pk = 0 + for k = 1, #s.folders[fi].packed do + pk += s.packSizes[s.folders[fi].firstPack + k] or 0 + end + e.compressedSize = pk + end + e.crc = s.subCrcs[idx] + e.load = function(): (buffer?, Err.Err?) + local d, derr = folderData(fi) + if not d then + return nil, derr + end + local off = subOffset[idx] + if off + size > buffer.len(d) then + return nil, Err.new(Err.CORRUPT, "substream past its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, d, off, size) + local want = s.subCrcs[idx] + 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, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +return SevenZip +end +__FILES["archive/7z/Header"] = function() + +-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): +-- 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 = __include("codecs/text/Text") +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Header = {} + +type Coder = { id: string, numIn: number, numOut: number, props: buffer } +type Folder = { + coders: { Coder }, + bindPairs: { { inIndex: number, outIndex: number } }, + packed: { number }, -- in-stream index of each packed stream + unpackSizes: { number }, -- per out stream + crc: number?, + firstPack: number, -- index of the folder's first pack stream (0-based) + numSub: number, -- substreams (files) in the folder +} +type Streams = { + packPos: number, + packSizes: { number }, + folders: { Folder }, + subSizes: { number }, -- every substream, folder by folder + subCrcs: { [number]: number }, -- 1-based substream index -> CRC +} +type File = { + name: string, + emptyStream: boolean, + emptyFile: boolean, + anti: boolean, + mtime: number?, + attributes: number?, +} +type Parsed = { streams: Streams?, files: { File }, encoded: Streams? } + +local K = { + End = 0x00, + Header = 0x01, + ArchiveProperties = 0x02, + AdditionalStreamsInfo = 0x03, + MainStreamsInfo = 0x04, + FilesInfo = 0x05, + PackInfo = 0x06, + UnPackInfo = 0x07, + SubStreamsInfo = 0x08, + Size = 0x09, + CRC = 0x0A, + Folder = 0x0B, + CodersUnPackSize = 0x0C, + NumUnPackStream = 0x0D, + EmptyStream = 0x0E, + EmptyFile = 0x0F, + Anti = 0x10, + Name = 0x11, + MTime = 0x14, + WinAttributes = 0x15, + EncodedHeader = 0x17, + Dummy = 0x19, +} +Header.K = K + +local Fail = {} + +local function bad(r: Bytes.Reader, msg: string, code: string?): never + error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) +end + +local function check(r: Bytes.Reader) + if r.err then + error(setmetatable({ err = r.err }, Fail), 0) + end +end + +local function byte(r: Bytes.Reader): number + local v = r:u8() + check(r) + return v +end + +-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes +local function number(r: Bytes.Reader): number + local first = byte(r) + local mask = 0x80 + local value = 0 + for i = 0, 7 do + if bit32.band(first, mask) == 0 then + local high = bit32.band(first, mask - 1) + return value + high * 2 ^ (8 * i) + end + value += byte(r) * 2 ^ (8 * i) + mask = bit32.rshift(mask, 1) + end + return value +end + +-- a count bounded by the bytes left (every counted item takes at least `min` bytes) +local function count(r: Bytes.Reader, min: number?): number + local n = number(r) + if n * (min or 1) > r:remaining() + 1 then + bad(r, "count " .. n .. " is larger than the header") + end + return n +end + +local function bits(r: Bytes.Reader, n: number): { boolean } + local out = table.create(n, false) + local cur, mask = 0, 0 + for i = 1, n do + if mask == 0 then + cur = byte(r) + mask = 0x80 + end + out[i] = bit32.band(cur, mask) ~= 0 + mask = bit32.rshift(mask, 1) + end + return out +end + +-- bits preceded by an "all defined" byte +local function defined(r: Bytes.Reader, n: number): { boolean } + if byte(r) ~= 0 then + return table.create(n, true) + end + return bits(r, n) +end + +local function digests(r: Bytes.Reader, n: number): { [number]: number } + local def = defined(r, n) + local out = {} + for i = 1, n do + if def[i] then + out[i] = r:u32le() + end + end + check(r) + return out +end + +local function packInfo(r: Bytes.Reader, s: Streams) + s.packPos = number(r) + local n = count(r) + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.Size then + for i = 1, n do + s.packSizes[i] = number(r) + end + elseif t == K.CRC then + digests(r, n) + else + bad(r, "unexpected property " .. t .. " in pack info") + end + end + if #s.packSizes ~= n then + bad(r, "missing pack sizes") + end +end + +local function folder(r: Bytes.Reader): Folder + local ncoders = count(r) + if ncoders == 0 or ncoders > 64 then + bad(r, "bad coder count " .. ncoders) + end + local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } + local totalIn, totalOut = 0, 0 + for _ = 1, ncoders do + local flags = byte(r) + if bit32.band(flags, 0x80) ~= 0 then + bad(r, "alternative coder methods", Err.UNSUPPORTED) + end + local idSize = bit32.band(flags, 0x0F) + local id = r:string(idSize) + check(r) + local nin, nout = 1, 1 + if bit32.band(flags, 0x10) ~= 0 then + nin = number(r) + nout = number(r) + if nin > 64 or nout > 64 then + bad(r, "bad coder stream count") + end + end + local props = buffer.create(0) + if bit32.band(flags, 0x20) ~= 0 then + local n = count(r) + props = r:bytes(n) + check(r) + end + table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) + totalIn += nin + totalOut += nout + end + if totalOut == 0 then + bad(r, "a folder without output") + end + for _ = 1, totalOut - 1 do + local i, o = number(r), number(r) + table.insert(f.bindPairs, { inIndex = i, outIndex = o }) + end + local npacked = totalIn - (totalOut - 1) + if npacked < 1 then + bad(r, "bad bind pairs") + end + if npacked == 1 then + for i = 0, totalIn - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.inIndex == i then + bound = true + end + end + if not bound then + table.insert(f.packed, i) + break + end + end + if #f.packed ~= 1 then + bad(r, "no packed stream") + end + else + for _ = 1, npacked do + table.insert(f.packed, number(r)) + end + end + return f +end + +-- the folder's main out stream: the one no bind pair consumes +function Header.mainOut(f: Folder): number? + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for o = 0, total - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.outIndex == o then + bound = true + end + end + if not bound then + return o + end + end + return nil +end + +function Header.unpackSize(f: Folder): number + local m = Header.mainOut(f) + return if m then f.unpackSizes[m + 1] or 0 else 0 +end + +local function unpackInfo(r: Bytes.Reader, s: Streams) + if byte(r) ~= K.Folder then + bad(r, "expected the folder list") + end + local n = count(r) + if byte(r) ~= 0 then + bad(r, "external folders", Err.UNSUPPORTED) + end + for i = 1, n do + s.folders[i] = folder(r) + end + if byte(r) ~= K.CodersUnPackSize then + bad(r, "expected the coder unpack sizes") + end + for _, f in s.folders do + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for k = 1, total do + f.unpackSizes[k] = number(r) + end + end + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.CRC then + local d = digests(r, n) + for i = 1, n do + s.folders[i].crc = d[i] + end + else + bad(r, "unexpected property " .. t .. " in unpack info") + end + end +end + +local function subStreamsInfo(r: Bytes.Reader, s: Streams) + local t = byte(r) + if t == K.NumUnPackStream then + for _, f in s.folders do + f.numSub = count(r, 0) + end + t = byte(r) + end + local sizes = s.subSizes + if t == K.Size then + for _, f in s.folders do + if f.numSub > 0 then + local sum = 0 + for _ = 1, f.numSub - 1 do + local v = number(r) + sum += v + table.insert(sizes, v) + end + local total = Header.unpackSize(f) + if sum > total then + bad(r, "substream sizes exceed the folder") + end + table.insert(sizes, total - sum) + end + end + t = byte(r) + else + for _, f in s.folders do + if f.numSub > 1 then + bad(r, "missing substream sizes") + elseif f.numSub == 1 then + table.insert(sizes, Header.unpackSize(f)) + end + end + end + -- CRCs for the streams whose folder CRC does not already cover them + local unknown = 0 + for _, f in s.folders do + if not (f.numSub == 1 and f.crc) then + unknown += f.numSub + end + end + while t ~= K.End do + if t == K.CRC then + local d = digests(r, unknown) + local k, si = 1, 1 + for _, f in s.folders do + if f.numSub == 1 and f.crc then + s.subCrcs[si] = f.crc + si += 1 + else + for _ = 1, f.numSub do + s.subCrcs[si] = d[k] + k += 1 + si += 1 + end + end + end + else + bad(r, "unexpected property " .. t .. " in substreams info") + end + t = byte(r) + end +end + +local function streamsInfo(r: Bytes.Reader): Streams + local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local sawSub = false + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.PackInfo then + packInfo(r, s) + elseif t == K.UnPackInfo then + unpackInfo(r, s) + elseif t == K.SubStreamsInfo then + subStreamsInfo(r, s) + sawSub = true + else + bad(r, "unexpected property " .. t .. " in streams info") + end + end + if not sawSub then + for i, f in s.folders do + f.numSub = 1 + table.insert(s.subSizes, Header.unpackSize(f)) + if f.crc then + s.subCrcs[i] = f.crc + end + end + end + local p = 0 + for _, f in s.folders do + f.firstPack = p + p += #f.packed + end + if p > #s.packSizes then + bad(r, "folders use more pack streams than exist") + end + return s +end + +local function utf16(b: buffer, o: number, n: number): string + return Text.utf16(b, o, n, false) +end + +local function filesInfo(r: Bytes.Reader): { File } + local n = count(r, 0) + if n > 1000000 then + bad(r, "too many files", Err.LIMIT) + end + local files: { File } = table.create(n) :: { File } + for i = 1, n do + files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } + end + local empties: { number } = {} + while true do + local t = byte(r) + if t == K.End then + break + end + local size = number(r) + if size > r:remaining() then + bad(r, "file property past the header") + end + local pr = r:slice(size) + check(r) + if t == K.EmptyStream then + local v = bits(pr, n) + empties = {} + for i = 1, n do + files[i].emptyStream = v[i] + if v[i] then + table.insert(empties, i) + end + end + elseif t == K.EmptyFile or t == K.Anti then + local v = bits(pr, #empties) + for k, i in empties do + if t == K.EmptyFile then + files[i].emptyFile = v[k] + else + files[i].anti = v[k] + end + end + elseif t == K.Name then + if byte(pr) ~= 0 then + bad(pr, "external names", Err.UNSUPPORTED) + end + local b = pr.buf + local p = pr.pos + for i = 1, n do + local q = p + while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do + q += 2 + end + if q + 1 >= pr.limit then + bad(pr, "unterminated name") + end + files[i].name = utf16(b, p, q - p) + p = q + 2 + end + elseif t == K.MTime or t == K.WinAttributes then + local def = defined(pr, n) + if byte(pr) ~= 0 then + bad(pr, "external file properties", Err.UNSUPPORTED) + end + for i = 1, n do + if def[i] then + if t == K.MTime then + local ft = pr:u64le() + files[i].mtime = math.floor(ft / 1e7 - 11644473600) + else + files[i].attributes = pr:u32le() + end + end + end + check(pr) + end + -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped + end + return files +end + +local function header(r: Bytes.Reader): Parsed + local p: Parsed = { streams = nil, files = {}, encoded = nil } + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.ArchiveProperties then + while true do + local pt = byte(r) + if pt == 0 then + break + end + r:skip(number(r)) + check(r) + end + elseif t == K.AdditionalStreamsInfo then + streamsInfo(r) + elseif t == K.MainStreamsInfo then + p.streams = streamsInfo(r) + elseif t == K.FilesInfo then + p.files = filesInfo(r) + else + bad(r, "unexpected property " .. t .. " in the header") + end + end + return p +end + +-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to +-- decode and parse again. +function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) + local r = Bytes.reader(b, o, n) + local ok, res = pcall(function(): Parsed + local t = byte(r) + if t == K.Header then + return header(r) + elseif t == K.EncodedHeader then + return { streams = nil, files = {}, encoded = streamsInfo(r) } + end + return bad(r, "bad header type " .. t) + end) + if ok then + return res, nil + end + if type(res) == "table" and getmetatable(res :: any) == Fail then + return nil, (res :: any).err + end + error(res, 0) +end + +return Header +end +__FILES["archive/adf"] = function() + +-- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an +-- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international, +-- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through +-- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the +-- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked +-- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...), +-- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are +-- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description +-- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk +-- images (use the partition contents), dircache blocks (not needed to read). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Adf = { + name = "adf", + category = "archive", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 65536 + +-- ------------------------------------------------------------------------------------------------ constants +local BS = 512 +local HT = 72 -- hash table slots in a 512-byte block +local T_HEADER, T_DATA, T_LIST = 2, 8, 16 +local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4 +local EPOCH = 252460800 -- 1978-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function Adf.sniff(r: Bytes.Reader): number + local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return 0 + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then + return 0 + end + return if n == 901120 or n == 1802240 then 0.95 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function latin1(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +type Disk = { b: buffer, base: number, blocks: number } + +local function u32(d: Disk, blk: number, off: number): number + local o = d.base + blk * BS + off + return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3) +end + +local function i32(d: Disk, blk: number, off: number): number + local v = u32(d, blk, off) + return if v >= 0x80000000 then v - 0x100000000 else v +end + +local function bstr(d: Disk, blk: number, off: number, max: number): string + local o = d.base + blk * BS + off + local n = math.min(buffer.readu8(d.b, o), max) + return latin1(buffer.readstring(d.b, o + 1, n)) +end + +local function checksumOk(d: Disk, blk: number): boolean + local sum = 0 + for i = 0, BS - 4, 4 do + sum = (sum + u32(d, blk, i)) % 0x100000000 + end + return sum == 0 +end + +local function date(d: Disk, blk: number, off: number): number + return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH +end + +-- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables) +local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?) + local out = {} + local blk = hdr + local seen: { [number]: boolean } = {} + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or seen[blk] then + return nil, "bad extension block " .. blk + end + seen[blk] = true + if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then + return nil, "bad extension block " .. blk + end + local n = u32(d, blk, 8) + if n > HT then + return nil, "bad block count in " .. blk + end + for k = 0, n - 1 do + local db = u32(d, blk, 24 + (HT - 1 - k) * 4) + if db < 2 or db >= d.blocks then + return nil, "bad data block " .. db + end + table.insert(out, db) + if #out > maxBlocks then + return nil, "more data blocks than the disk has" + end + end + blk = u32(d, blk, BS - 8) + end + return out, nil +end + +local function readFile(d: Disk, hdr: number, ofs: boolean): (buffer?, string?) + local size = u32(d, hdr, BS - 188) + if size > d.blocks * BS then + return nil, "file larger than the disk" + end + local list, err = dataBlocks(d, hdr, d.blocks) + if not list then + return nil, err + end + local out = buffer.create(size) + local o = 0 + for _, db in list do + if o >= size then + break + end + if ofs then + if u32(d, db, 0) ~= T_DATA then + return nil, "data block " .. db .. " is not an OFS data block" + end + local n = math.min(u32(d, db, 12), 488, size - o) + buffer.copy(out, o, d.b, d.base + db * BS + 24, n) + o += n + else + local n = math.min(BS, size - o) + buffer.copy(out, o, d.b, d.base + db * BS, n) + o += n + end + end + if o < size then + return nil, "file data ends early" + end + return out, nil +end + +function Adf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks") + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" then + return nil, Err.new(Err.CORRUPT, "no DOS boot block") + end + local flags = string.byte(h, 4) + if flags > 5 then + return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems") + end + local d: Disk = { b = r.buf, base = r.base, blocks = n // BS } + local ofs = bit32.band(flags, 1) == 0 + local root = (d.blocks - 1 + 2) // 2 + if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then + return nil, Err.new(Err.CORRUPT, "no root block at " .. root) + end + if not checksumOk(d, root) then + return nil, Err.new(Err.CHECKSUM, "root block checksum") + end + local a = Archive.new("adf") + a.meta.volume = bstr(d, root, BS - 80, 30) + a.meta.fs = if ofs then "ofs" else "ffs" + a.meta.intl = flags >= 2 + a.meta.dircache = flags >= 4 + a.meta.dosType = flags + a.meta.modified = date(d, root, BS - 92) + a.meta.created = date(d, root, BS - 28) + a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks } + local maxEntries = o.maxEntries or 65536 + local count = 0 + local pathOf: { [number]: string } = {} + local links: { { entry: any, target: number } } = {} + local visited: { [number]: boolean } = { [root] = true } + + local function walk(dir: number, prefix: string): (boolean, Err.Err?) + for slot = 0, HT - 1 do + local blk = u32(d, dir, 24 + slot * 4) + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or visited[blk] then + return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk) + end + visited[blk] = true + count += 1 + if count > maxEntries then + return false, Err.new(Err.LIMIT, "more than maxEntries entries") + end + if u32(d, blk, 0) ~= T_HEADER then + return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block") + end + if not checksumOk(d, blk) then + return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum") + end + local name = prefix .. bstr(d, blk, BS - 80, 30) + local st = i32(d, blk, BS - 4) + local e: any = { + name = name, + size = 0, + dir = false, + mtime = date(d, blk, BS - 92), + protect = u32(d, blk, BS - 192), + comment = bstr(d, blk, BS - 184, 79), + method = "store", + } + if e.comment == "" then + e.comment = nil + end + if st == ST_USERDIR then + e.name = name .. "/" + e.dir = true + pathOf[blk] = e.name + Archive.put(a, e) + local ok, err = walk(blk, e.name) + if not ok then + return false, err + end + elseif st == ST_FILE then + e.size = u32(d, blk, BS - 188) + pathOf[blk] = name + local hb = blk + e.load = function(): (buffer?, Err.Err?) + local data, err = readFile(d, hb, ofs) + if not data then + return nil, Err.new(Err.CORRUPT, tostring(err)) + end + return data, nil + end + Archive.put(a, e) + elseif st == ST_SOFTLINK then + local lo = d.base + blk * BS + 24 + local s = buffer.readstring(d.b, lo, BS - 24 - 200) + e.link = latin1(string.match(s, "^[^%z]*") or "") + e.type = "symlink" + Archive.put(a, e) + elseif st == ST_LINKFILE or st == ST_LINKDIR then + e.type = "hardlink" + e.dir = st == ST_LINKDIR + if e.dir then + e.name = name .. "/" + end + Archive.put(a, e) + table.insert(links, { entry = e, target = u32(d, blk, BS - 44) }) + end + blk = u32(d, blk, BS - 16) + end + end + return true, nil + end + local ok, err = walk(root, "") + if not ok then + return nil, err + end + -- hard links: the linked path, and a file link reads its target's data + for _, l in links do + local target = pathOf[l.target] + l.entry.hardlink = target + if target and not l.entry.dir then + local te = a._byName[target] + if te then + l.entry.size = te.size + l.entry.load = te.load + end + end + end + return a, nil +end + +return Adf +end +__FILES["archive/applesingle"] = function() + +-- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740): +-- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2: +-- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags). +-- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the +-- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name +-- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds +-- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with +-- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS / +-- MS-DOS / AFP info entries (kept in meta.entries as id + length). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local AppleSingle = { + name = "applesingle", + category = "archive", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, +} + +type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it) +type EncodeOptions = { + double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false) + name: string?, -- the name of a buffer / string value (default "data") +} + +-- ------------------------------------------------------------------------------------------------ constants +local SINGLE, DOUBLE = 0x00051600, 0x00051607 +local Y2K = 946684800 -- 2000-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function AppleSingle.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 then + return 0 + end + local magic = string.sub(h, 1, 4) + local ver = string.sub(h, 5, 8) + if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return AppleSingle.encode(a, o) +end + +local function i32(v: number): number + return if v >= 0x80000000 then v - 0x100000000 else v +end + +function AppleSingle.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local magic, ver = r:u32be(), r:u32be() + r:skip(16) + local count = r:u16be() + if r.err then + return nil, r.err + end + if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then + return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble") + end + local size = r:size() + local info: MacFile.Info = { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 } + local others = {} + local total = 0 + for _ = 1, count do + local id, off, len = r:u32be(), r:u32be(), r:u32be() + if r.err then + return nil, r.err + end + if off + len > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end") + end + total += len + if total > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "entries larger than maxBytes") + end + local e = r:sub(off, len) + if id == 1 then + info.data = e:bytes(len) + elseif id == 2 then + info.rsrc = e:bytes(len) + elseif id == 3 then + info.name = MacFile.name(e:string(len)) + elseif id == 4 then + info.comment = MacFile.name(e:string(len)) + elseif id == 8 and len >= 8 then + local c, m = e:u32be(), e:u32be() + info.created = if c == 0x80000000 then nil else i32(c) + Y2K + info.modified = if m == 0x80000000 then nil else i32(m) + Y2K + elseif id == 7 and len >= 12 and ver == 0x10000 then + local c, m = e:u32be(), e:u32be() + info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m) + elseif id == 9 and len >= 10 then + info.type, info.creator = e:string(4), e:string(4) + info.flags = e:u16be() + else + table.insert(others, { id = id, length = len }) + end + end + if info.name == "" then + local n = if type(o.name) == "string" then string.match(o.name, "([^/\\]+)$") else nil + info.name = if n then (string.match(n, "^%._(.+)$") or n) else "data" + end + local a = Archive.new("applesingle", encoder) + MacFile.put(a, info, magic == DOUBLE) + a.meta.double = magic == DOUBLE + a.meta.entries = others + a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0 + a.meta.source = { format = "applesingle", variant = if magic == DOUBLE then "appledouble" else "applesingle", version = ver // 0x10000 } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function AppleSingle.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + local function date(t: number?): number + if type(t) ~= "number" then + return 0x80000000 + end + return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000 + end + local dates = Bytes.writer(16) + dates:u32be(date(f.created or f.modified)) + dates:u32be(date(f.modified)) + dates:u32be(0x80000000) + dates:u32be(0x80000000) + local finder = Bytes.writer(32) + finder:string(f.type) + finder:string(f.creator) + finder:u16be(f.flags) + finder:string(string.rep("\0", 22)) + local entries: { { any } } = { { 3, buffer.fromstring(name) } } + if f.comment then + table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) }) + end + table.insert(entries, { 8, dates:finish() }) + table.insert(entries, { 9, finder:finish() }) + if not o.double then + table.insert(entries, { 1, f.data }) + end + if buffer.len(f.rsrc) > 0 or o.double then + table.insert(entries, { 2, f.rsrc }) + end + local w = Bytes.writer() + w:u32be(if o.double then DOUBLE else SINGLE) + w:u32be(0x20000) + w:string(string.rep("\0", 16)) + w:u16be(#entries) + local off = 26 + 12 * #entries + for _, e in entries do + w:u32be(e[1]) + w:u32be(off) + w:u32be(buffer.len(e[2])) + off += buffer.len(e[2]) + end + for _, e in entries do + w:bytes(e[2]) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork +function AppleSingle.new(): any + local a = Archive.new("applesingle", encoder) + a.meta.source = { format = "applesingle" } + return a +end + +return AppleSingle +end +__FILES["archive/ar"] = function() + +-- archive/ar: Unix ar archives ("!\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/" +-- and "/SYM64/" symbol tables) and BSD (inline "#1/" names, the "__.SYMDEF" symbol table), read into the standard +-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not +-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their +-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and +-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed +-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and +-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!"), writing symbol tables (a re-written +-- library needs ranlib), writing .deb control data (any entries write as a plain ar). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Ar = { + name = "ar", + category = "archive", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, +} + +type DecodeOptions = { + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26) +} +type EncodeOptions = { + variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "!\n" +local HEADER = 60 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ar.sniff(r: Bytes.Reader): number + if r:peek(8) == MAGIC then + return if r:peek(13, 68) == "debian-binary" then 1 else 0.9 + end + return if r:peek(8) == "!\n" then 0.5 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function decimal(s: string): number? + local d = string.match(s, "^%s*(%d+)%s*$") + return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil) +end + +-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names +local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } } + local out = {} + local w = if wide then 8 else 4 + if n < w then + return out + end + local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o)) + if count * w + w > n then + return out + end + local s = o + w + count * w + local e = o + n + for i = 0, count - 1 do + local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4))) + local q = s + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off }) + s = q + 1 + if s > e then + break + end + end + return out +end + +-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings +local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } } + local out = {} + if n < 8 then + return out + end + local rb = buffer.readu32(b, o) + if rb % 8 ~= 0 or rb + 8 > n then + return out + end + local strs = o + 8 + rb + local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs) + for i = 0, rb // 8 - 1 do + local sx = buffer.readu32(b, o + 4 + i * 8) + if sx < strn then + local q = strs + sx + while q < strs + strn and buffer.readu8(b, q) ~= 0 do + q += 1 + end + table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) }) + end + end + return out +end + +-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab) +local function controlFields(s: string): { [string]: string } + local out: { [string]: string } = {} + local last: string? = nil + for line in string.gmatch(s, "([^\n]*)\n?") do + local c = string.sub(line, 1, 1) + if (c == " " or c == "\t") and last then + out[last] ..= "\n" .. string.sub(line, 2) + else + local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$") + if k then + out[k], last = v :: string, k + end + end + end + return out +end + +-- control.tar[.ext] -> the control file's fields, or nil +local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }? + local ext = string.match(name, "^control%.tar%.?(%w*)$") + local raw: buffer? + local opts: any = { maxBytes = maxBytes } + if ext == "" then + raw = buffer.create(n) + buffer.copy(raw :: buffer, 0, b, o, n) + elseif ext == "gz" then + raw = Deflate.gunzip(b, o, n) + elseif ext == "xz" then + raw = Lzma.xz(b, o, n, opts) + elseif ext == "lzma" then + raw = Lzma.alone(b, o, n, opts) + elseif ext == "zst" then + raw = Zstd.decompress(b, o, n, opts) + elseif ext == "bz2" then + raw = Bzip2.decompress(b, o, n, opts) + end + if not raw then + return nil + end + local list = Tar.read(raw) + for _, e in list or {} do + if (e.name == "./control" or e.name == "control") and e.type == "0" then + return controlFields(buffer.readstring(raw, e.offset, e.size)) + end + end + return nil +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Ar.encode(archive, opts) +end + +function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxEntries = o.maxEntries or 1e6 + local b, base, e = r.buf, r.base, r.limit + if r:peek(8) == "!\n" then + return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base) + end + if r:peek(8) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local a = Archive.new("ar", encode) + local variant = "gnu" + local longNames: string? = nil + local symbols: { { name: string, offset: number } }? = nil + local offsets: { [number]: string } = {} -- header offset (from the start) -> member name + local count = 0 + local p = base + 8 + while p < e do + local c = buffer.readu8(b, p) + if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then + break -- trailing padding (bsdtar fills its last 10240-byte block with zeros) + end + if p + HEADER > e then + return nil, Err.new(Err.TRUNCATED, "member header past the end", p) + end + if buffer.readstring(b, p + 58, 2) ~= "`\n" then + return nil, Err.new(Err.CORRUPT, "bad member header", p + 58) + end + local rawName = buffer.readstring(b, p, 16) + local mtime = decimal(buffer.readstring(b, p + 16, 12)) + local uid = decimal(buffer.readstring(b, p + 28, 6)) + local gid = decimal(buffer.readstring(b, p + 34, 6)) + local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$") + local size = decimal(buffer.readstring(b, p + 48, 10)) + if not (mtime and uid and gid and modeS and size) then + return nil, Err.new(Err.CORRUPT, "bad member header field", p) + end + local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number + local data = p + HEADER + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "member data past the end", data) + end + local nextP = data + size + size % 2 + local name = string.gsub(rawName, " +$", "") + local dataSize = size + if string.sub(name, 1, 3) == "#1/" then + local n = tonumber(string.sub(name, 4)) + if not n or n > size then + return nil, Err.new(Err.CORRUPT, "bad BSD name length", p) + end + name = buffer.readstring(b, data, n) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + data += n + dataSize -= n + variant = "bsd" + elseif name == "//" then + longNames = buffer.readstring(b, data, size) + p = nextP + continue + elseif name == "/" or name == "/SYM64/" then + symbols = sysvSymbols(b, data, size, name == "/SYM64/") + p = nextP + continue + elseif string.match(name, "^/%d+$") then + local off = tonumber(string.sub(name, 2)) :: number + if not longNames or off >= #longNames then + return nil, Err.new(Err.CORRUPT, "long name outside the name table", p) + end + local s = string.match(longNames, "^([^\n]*)", off + 1) :: string + name = string.gsub(s, "/$", "") + elseif string.sub(name, -1) == "/" then + name = string.sub(name, 1, -2) + end + if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then + symbols = bsdSymbols(b, data, dataSize) + variant = "bsd" + p = nextP + continue + end + if name == "" then + return nil, Err.new(Err.CORRUPT, "empty member name", p) + end + offsets[p - base] = name + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + Archive.put(a, { + name = name, + size = dataSize, + dir = false, + mtime = mtime, + uid = uid, + gid = gid, + mode = bit32.band(mode, 0xFFF), + armode = modeS, + method = "store", + load = if dataSize > 0 then lazy(b, data, dataSize) else nil, + }) + p = nextP + end + if symbols then + local out = {} + for _, s in symbols do + table.insert(out, { name = s.name, member = offsets[s.offset] }) + end + a.meta.symbols = out + end + a.meta.source = { format = "ar", variant = variant } + -- Debian packages + local list = a._entries + if list[1] and list[1].name == "debian-binary" then + a.meta.source.variant = "deb" + local v = a:read("debian-binary") + a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil + for _, ent in list do + if string.match(ent.name, "^data%.tar") then + a.meta.payload = ent.name + elseif string.match(ent.name, "^control%.tar") then + local cb = a:read(ent.name) + if cb then + a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26) + end + end + end + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function pad(s: string, n: number): string + return s .. string.rep(" ", n - #s) +end + +local function header(name: string, e: any, size: number): string? + local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0) + local uid = if type(e.uid) == "number" then e.uid else 0 + local gid = if type(e.gid) == "number" then e.gid else 0 + local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode + else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4) + local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) } + local w = { 12, 6, 6, 8, 10 } + for i, s in f do + if #s > w[i] or string.find(s, "[^%d]") then + return nil + end + end + return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n" +end + +function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local o: EncodeOptions = opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu") + if variant ~= "gnu" and variant ~= "bsd" then + return nil, Err.new(Err.ARG, "variant must be gnu or bsd") + end + local files = {} + for _, it in items do + local e: any = it.entry + if not e.dir and (e.type == nil or e.type == "0") then + local data, err = it.read() + if not data then + return nil, err + end + table.insert(files, { e = e, data = data }) + end + end + local w = Bytes.writer(1024) + w:string(MAGIC) + -- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table + local table_: { string } = {} + local nameOf: { string } = {} + local tsize = 0 + for i, f in files do + local name: string = f.e.name + if string.find(name, "\n") or name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar") + end + if variant == "gnu" then + if #name > 15 or string.find(name, "[/ ]") then + nameOf[i] = "/" .. tsize + table.insert(table_, name .. "/\n") + tsize += #name + 2 + else + nameOf[i] = name .. "/" + end + end + end + if #table_ > 0 then + local t = table.concat(table_) + if #t % 2 == 1 then + t ..= "\n" + end + w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t) + end + for i, f in files do + local name: string = f.e.name + local size = buffer.len(f.data) + local prefix = "" + local field = nameOf[i] + if variant == "bsd" then + if #name > 16 or string.find(name, " ") then + field = "#1/" .. #name + prefix = name + else + field = name + end + end + local h = header(field, f.e, size + #prefix) + if not h then + return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header") + end + w:string(h) + w:string(prefix) + w:bytes(f.data) + if (size + #prefix) % 2 == 1 then + w:string("\n") + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" }) +function Ar.new(): any + local a = Archive.new("ar", encode) + a.meta.source = { format = "ar", variant = "gnu" } + return a +end + +return Ar +end +__FILES["archive/arj"] = function() + +-- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS, +-- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style +-- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type +-- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM). +-- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files, +-- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those +-- entries / calls). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Arj = { + name = "arj", + category = "archive", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxEntries: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Arj.sniff(r: Bytes.Reader): number + local h = r:peek(4) + if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + return if size > 0 and size <= 2600 then 0.9 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { fields: Bytes.Reader, name: string, comment: string, size: number, at: number, next: number } + +-- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker +local function block(r: Bytes.Reader, p: number): (Header?, string?) + local h = r:sub(p, 4) + local id1, id2, size = h:u8(), h:u8(), h:u16le() + if h.err then + return nil, "truncated header" + end + if id1 ~= 0x60 or id2 ~= 0xEA then + return nil, "bad header id" + end + if size == 0 then + return nil, nil + end + if size > 2600 then + return nil, "header too large" + end + if p + 4 + size + 4 > r:size() then + return nil, "truncated header" + end + local crc = r:sub(p + 4 + size, 4):u32le() + if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then + return nil, "checksum: header CRC-32 mismatch" + end + local f = r:sub(p + 4, size) + local first = f:u8() + if first < 30 or first > size then + return nil, "bad first header size" + end + f:seek(first) + local name = f:cstring() + local comment = f:cstring() + -- extended headers + local q = p + 4 + size + 4 + local guard = 0 + while true do + local e = r:sub(q, 2) + local n = e:u16le() + if e.err then + return nil, "truncated extended header" + end + q += 2 + if n == 0 then + break + end + q += n + 4 + guard += 1 + if guard > 256 or q > r:size() then + return nil, "truncated extended header" + end + end + f:seek(0) + return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil +end + +function Arj.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local main, err = block(r, 0) + if not main then + return nil, Err.from(err or "no main header", r.base) + end + local a = Archive.new("arj") + local mf = main.fields + mf:skip(1) + local version, minVersion, host = mf:u8(), mf:u8(), mf:u8() + local flags = mf:u8() + mf:skip(3) + local created = mf:u32le() + a.meta.archive = main.name + a.meta.comment = if main.comment ~= "" then main.comment else nil + a.meta.os = OS[host] + a.meta.created = Archive.fromDos(created) + a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags } + local p = main.next + local count = 0 + while true do + local h, herr = block(r, p) + if herr then + return nil, Err.from(herr, r.base + p) + end + if not h then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local f = h.fields + f:skip(1) + f:skip(2) + local hostOs = f:u8() + local fl = f:u8() + local method = f:u8() + local ftype = f:u8() + f:skip(1) + local stamp = f:u32le() + local packed, size, crc = f:u32le(), f:u32le(), f:u32le() + f:skip(2) + local mode = f:u16le() + local dataAt = h.next + if dataAt + packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt) + end + local name = string.gsub(h.name, "\\", "/") + local isDir = ftype == 3 + if isDir and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local e: any = { + name = name, + size = if isDir then 0 else size, + compressedSize = packed, + method = if method == 0 then "store" else "arj" .. method, + mtime = Archive.fromDos(stamp), + dir = isDir, + mode = mode, + os = OS[hostOs], + comment = if h.comment ~= "" then h.comment else nil, + fileType = ftype, + } + if ftype ~= 4 then -- 4: a volume label, not a file + if not isDir and size > 0 then + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local buf, at = r.buf, r.base + dataAt + e.load = function(): (buffer?, Err.Err?) + if bit32.band(fl, 0x01) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries") + end + if bit32.band(fl, 0x0C) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes") + end + local out: buffer?, derr: string? + if method == 0 then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out :: buffer, 0, buf, at, size) + elseif method >= 1 and method <= 3 then + out, derr = Lzh.decode(buf, at, packed, size, "lh6") + elseif method == 4 then + out, derr = Lzh.decode(buf, at, packed, size, "arj4") + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc32.of(out) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + end + p = dataAt + packed + end + return a, nil +end + +return Arj +end +__FILES["archive/binhex"] = function() + +-- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name, +-- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified: +-- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a +-- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file +-- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter +-- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with +-- archive/macbinary), several files in one .hqx (only the first is read). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local Binhex = { + name = "binhex", + category = "archive", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, +} + +type DecodeOptions = { maxBytes: number? } -- default 2^30 +type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") + +-- ------------------------------------------------------------------------------------------------ constants +local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" +local VALUE: { [number]: number } = {} +for i = 1, 64 do + VALUE[string.byte(ALPHABET, i)] = i - 1 +end +local BANNER = "(This file must be converted with BinHex" + +-- ------------------------------------------------------------------------------------------------ sniff +function Binhex.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + local at = string.find(head, BANNER, 1, true) + if not at then + return 0 + end + return if at == 1 then 1 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input) +local function unhex(text: string, maxBytes: number): (buffer?, string?) + local banner = string.find(text, BANNER, 1, true) + if not banner then + return nil, "no BinHex banner" + end + local start = string.find(text, ":", banner, true) + if not start then + return nil, "truncated: no data start" + end + local raw = Bytes.writer(#text) + local acc, nbits = 0, 0 + local closed = false + for i = start + 1, #text do + local c = string.byte(text, i) + if c == 58 then -- ":" + closed = true + break + end + local v = VALUE[c] + if v then + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v) + nbits += 6 + if nbits >= 8 then + nbits -= 8 + raw:u8(bit32.band(bit32.rshift(acc, nbits), 255)) + end + elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then + return nil, string.format("bad character 0x%02x", c) + end + end + if not closed then + return nil, "truncated: no closing colon" + end + local src = raw:finish() + -- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90 + local out = Bytes.writer(buffer.len(src) * 2) + local n = buffer.len(src) + local prev = 0 + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + if c == 0x90 and i + 1 < n then + local count = buffer.readu8(src, i + 1) + i += 2 + if count == 0 then + out:u8(0x90) + prev = 0x90 + else + if out:tell() + count > maxBytes then + return nil, "limit: data larger than maxBytes" + end + for _ = 2, count do + out:u8(prev) + end + end + else + out:u8(c) + prev = c + i += 1 + end + end + return out:finish(), nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Binhex.encode(a, o) +end + +function Binhex.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes) + if not b then + return nil, Err.from(err) + end + local h = Bytes.reader(b) + local nameLen = h:u8() + local name = h:string(nameLen) + h:skip(1) -- version + local ftype, creator = h:string(4), h:string(4) + local flags = h:u16be() + local dlen, rlen = h:u32be(), h:u32be() + local hcrc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + if dlen + rlen > maxBytes then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + local forks = {} + for k, len in { dlen, rlen } do + local at = h:tell() + local fork = h:bytes(len) + local crc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, at, len) ~= crc then + return nil, Err.new(Err.CHECKSUM, (if k == 1 then "data" else "resource") .. " fork CRC mismatch") + end + forks[k] = fork + end + local a = Archive.new("binhex", encoder) + MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "binhex" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local w = Bytes.writer() + w:u8(#name) + w:string(name) + w:u8(0) + w:string(f.type) + w:string(f.creator) + w:u16be(f.flags) + w:u32be(buffer.len(f.data)) + w:u32be(buffer.len(f.rsrc)) + local hdr = w:finish() + local body = Bytes.writer() + for _, part in { hdr, f.data, f.rsrc } do + body:bytes(part) + body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) + end + local src = body:finish() + -- RLE90 + local rle = Bytes.writer(buffer.len(src) + 16) + local n = buffer.len(src) + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + local run = 1 + while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do + run += 1 + end + if c == 0x90 then + rle:u8(0x90) + rle:u8(0) + run = 1 + else + rle:u8(c) + if run >= 3 then + rle:u8(0x90) + rle:u8(run) + else + run = 1 + end + end + i += run + end + local bytes = rle:finish() + -- 6-bit characters, 64 to a line (the first line includes the colon) + local chars = { ":" } + local col = 1 + local acc, nbits = 0, 0 + local function put(v: number) + table.insert(chars, string.sub(ALPHABET, v + 1, v + 1)) + col += 1 + if col == 64 then + table.insert(chars, "\n") + col = 0 + end + end + for k = 0, buffer.len(bytes) - 1 do + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k)) + nbits += 8 + while nbits >= 6 do + nbits -= 6 + put(bit32.band(bit32.rshift(acc, nbits), 63)) + end + end + if nbits > 0 then + put(bit32.band(bit32.lshift(acc, 6 - nbits), 63)) + end + table.insert(chars, ":\n") + return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork +function Binhex.new(): any + local a = Archive.new("binhex", encoder) + a.meta.source = { format = "binhex" } + return a +end + +return Binhex +end +__FILES["archive/br"] = function() + +-- 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/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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Br = { + name = "br", + category = "archive", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + name: string?, -- the file name (the api passes it): the entry is named after it + maxBytes: number?, -- refuse output larger than this (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff +local SNIFF_PREFIX = 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Br.sniff(r: Bytes.Reader): number + local n = r:remaining() + if n == 0 then + return 0 + end + if n <= SNIFF_WHOLE then + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 }) + if out and consumed == r.limit then + return if buffer.len(out) > 0 then 0.3 else 0.05 + end + return 0 + end + local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 }) + if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then + return 0.05 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local n = r:remaining() + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes }) + if not out then + local e: Err.Err = consumed + e.message = string.gsub(e.message, "^brotli: ", "") + return nil, e + end + local a = Archive.new("br") + a.meta.stream = true + a.meta.compressedSize = consumed - r.pos + Archive.put(a, { + name = Archive.streamName(opts, Br.extensions), + size = buffer.len(out), + compressedSize = consumed - r.pos, + method = "brotli", + dir = false, + data = out, + }) + return a, nil +end + +return Br +end +__FILES["archive/bz2"] = function() + +-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated +-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), +-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported: +-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Bzip2 = __include("codecs/compress/Bzip2") + +-- ------------------------------------------------------------------------------------------------ contract +local Bz2 = { + name = "bz2", + category = "archive", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger output (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bz2.sniff(r: Bytes.Reader): number + local h = r:peek(10) + if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then + return 0 + end + local lv = string.byte(h, 4) + if lv < 0x31 or lv > 0x39 then + return 0 + end + local magic = string.sub(h, 5, 10) + if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) + if not out then + return nil, consumed + end + local a = Archive.new("bz2") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(opts, Bz2.extensions), + size = buffer.len(out), + compressedSize = consumed - r.base, + method = "bzip2", + dir = false, + data = out, + }) + return a, nil +end + +return Bz2 +end +__FILES["archive/cab"] = function() + +-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and +-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose +-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum +-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local +-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) +-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same +-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the +-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a +-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), +-- signed / self-extracting stubs before the header. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzx = __include("codecs/compress/Lzx") +local Quantum = __include("codecs/compress/Quantum") +local Archive = __include("containers/Archive") +local Sum = __include("archive/cab/Sum") + +-- ------------------------------------------------------------------------------------------------ contract +local Cab = { + name = "cab", + category = "archive", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30) + maxEntries: number?, -- default 65535 + verify: boolean?, -- check the data block checksums (default true) +} +type EncodeOptions = { + compression: ("mszip" | "none")?, -- default "mszip" + level: number?, -- deflate level 0..9 (default 6) + setId: number?, -- the cabinet set id (default 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 +local ATTR_UTF8 = 0x80 +local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } +local BLOCK = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function Cab.sniff(r: Bytes.Reader): number + if r:peek(8) == "MSCF\0\0\0\0" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Folder = { + dataAt: number, -- offset of the first CFDATA (relative to the reader) + blocks: number, + type: number, -- typeCompress + index: number, +} +type Block = { at: number, len: number, size: number } + +-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next +-- cabinet (a block with cbUncomp 0) +local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) + local list: { Block } = {} + local p = f.dataAt + local total = 0 + for i = 1, f.blocks do + local h = r:sub(p, 8) + local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() + if h.err then + return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) + end + local at = p + 8 + dataReserve + if at + cbData > r:size() then + return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) + end + if cbUncomp == 0 then + return list, total, true + end + if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then + return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) + end + total += cbUncomp + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") + end + table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) + p = at + cbData + end + return list, total, false +end + +-- the decompressed data of a folder's blocks +local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) + local method = bit32.band(typ, 15) + local out = buffer.create(total) + if method == 0 then + local o = 0 + for _, b in list do + if b.len ~= b.size then + return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) + end + buffer.copy(out, o, buf, b.at, b.len) + o += b.len + end + return out, nil + elseif method == 1 then + local spans: { { offset: number, length: number, size: number } } = {} + for _, b in list do + table.insert(spans, { offset = b.at, length = b.len, size = b.size }) + end + return Deflate.mszip(buf, spans) + elseif method == 3 then + local bits = bit32.band(bit32.rshift(typ, 8), 31) + local n = 0 + for _, b in list do + n += b.len + end + local src = buffer.create(n) + local o = 0 + for _, b in list do + buffer.copy(src, o, buf, b.at, b.len) + o += b.len + end + local res, err = Lzx.decode(src, 0, n, total, bits) + if not res then + return nil, Err.from(err) + end + return res, nil + elseif method == 2 then + local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31)) + if not res then + return nil, Err.from(err) + end + return res, nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Cab.encode(archive, opts) +end + +function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65535 + local verify = o.verify ~= false + if not r:match("MSCF") then + return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) + end + r:skip(4) + local cbCabinet = r:u32le() + r:skip(4) + local coffFiles = r:u32le() + r:skip(4) + local minor, major = r:u8(), r:u8() + local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() + local setId, iCabinet = r:u16le(), r:u16le() + local headerReserve, folderReserve, dataReserve = 0, 0, 0 + if bit32.band(flags, FLAG_RESERVE) ~= 0 then + headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() + end + local a = Archive.new("cab", encode) + local meta: any = a.meta + if headerReserve > 0 then + meta.reserve = r:bytes(headerReserve) + end + if bit32.band(flags, FLAG_PREV) ~= 0 then + meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) + end + if bit32.band(flags, FLAG_NEXT) ~= 0 then + meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) + end + if r.err then + return nil, r.err + end + if major ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) + end + meta.setId, meta.cabinet = setId, iCabinet + meta.source = { + format = "cab", + version = major .. "." .. minor, + size = cbCabinet, + flags = flags, + reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, + } + -- folders + local folders: { Folder } = {} + local methods = {} + for i = 1, cFolders do + local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() + r:skip(folderReserve) + if r.err then + return nil, r.err + end + folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } + local m = METHOD[bit32.band(typ, 15)] + methods[i] = { + method = m or ("type " .. bit32.band(typ, 15)), + window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil, + level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil, + blocks = nblocks, + } + end + meta.folders = methods + if cFiles == 0 or cFolders == 0 then + return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders") + end + if cFiles > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries files") + end + -- the folder cache: the last decompressed folder + local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false + local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) + if cachedIndex == f.index then + return cachedData, nil, cachedRuns + end + local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) + if not list then + return nil, total, false + end + local data, err = inflateFolder(r.buf, list, total, f.type) + if not data then + return nil, err, false + end + cachedIndex, cachedData, cachedRuns = f.index, data, runs == true + return data, nil, runs + end + -- files + local fr = r:sub(coffFiles) + for _ = 1, cFiles do + local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() + local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() + local raw = fr:cstring(65536) + if fr.err then + return nil, fr.err + end + local name = string.gsub(raw, "\\", "/") + local spanned: string? = nil + local folder: Folder? + if iFolder == 0xFFFD or iFolder == 0xFFFF then + spanned = "a file continued from the previous cabinet" + folder = folders[1] + elseif iFolder == 0xFFFE then + spanned = "a file continued in the next cabinet" + folder = folders[#folders] + else + folder = folders[iFolder + 1] + if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then + spanned = "a folder continued from the previous cabinet" + end + end + if not folder then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) + end + local fo = folder :: Folder + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local e: any = { + name = name, + size = size, + method = METHOD[bit32.band(fo.type, 15)] or "unknown", + mtime = Archive.fromDos(date * 65536 + time), + dir = false, + attributes = bit32.band(attribs, 0xFF7F), + utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, + folder = fo.index, + offset = offset, + readonly = bit32.band(attribs, 0x01) ~= 0, + executable = bit32.band(attribs, 0x40) ~= 0, + } + if spanned then + e.spanned = true + end + if size > 0 or spanned then + e.load = function(): (buffer?, Err.Err?) + if spanned then + return nil, Err.new(Err.UNSUPPORTED, spanned :: string) + end + local data, err, runs = folderData(fo) + if not data then + return nil, err + end + if offset + size > buffer.len(data) then + if runs then + return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") + end + return nil, Err.new(Err.CORRUPT, "file past the end of its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, data, offset, size) + return out, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) +function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local compression = o.compression or "mszip" + if compression ~= "mszip" and compression ~= "none" then + return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") + end + local level = o.level or 6 + 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") + end + local files, ferr = Archive.files(archive) + if not files then + return nil, ferr + end + if #files == 0 then + return nil, Err.new(Err.ARG, "a cabinet needs at least one file") + end + if #files > 65535 then + return nil, Err.new(Err.ARG, "more than 65535 files") + end + local total = 0 + for _, f in files do + total += buffer.len(f.data) + end + if total > 0x7FFF8000 then + return nil, Err.new(Err.ARG, "more than 2 GB of data") + end + -- the folder data, in 32 KB blocks + local folder = buffer.create(total) + local p = 0 + for _, f in files do + buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) + p += buffer.len(f.data) + end + local data = Bytes.writer(total // 2 + 64) + local nblocks = 0 + local s = 0 + while s < total do + local n = math.min(BLOCK, total - s) + local chunk = buffer.create(n) + buffer.copy(chunk, 0, folder, s, n) + local payload: buffer + if compression == "mszip" then + local z, zerr = Deflate.compress(chunk, { level = level }) + if not z then + return nil, zerr + end + payload = buffer.create(buffer.len(z) + 2) + buffer.writeu16(payload, 0, 0x4B43) + buffer.copy(payload, 2, z, 0, buffer.len(z)) + else + payload = chunk + end + local len = buffer.len(payload) + data:u32le(Sum.block(payload, 0, len, n)) + data:u16le(len) + data:u16le(n) + data:bytes(payload) + nblocks += 1 + s += n + end + local blob = data:finish() + -- names and the file table + local table_ = Bytes.writer(64 + #files * 32) + local offset = 0 + for _, f in files do + local e: any = f.entry + local name = string.gsub(f.name, "/", "\\") + local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20 + if string.find(name, "[\128-\255]") then + attribs = bit32.bor(attribs, ATTR_UTF8) + end + local stamp = Archive.toDos(e.mtime) + table_:u32le(buffer.len(f.data)) + table_:u32le(offset) + table_:u16le(0) + table_:u16le(stamp // 65536) + table_:u16le(stamp % 65536) + table_:u16le(attribs) + table_:cstring(name) + offset += buffer.len(f.data) + end + local fileTable = table_:finish() + local nfolders = 1 + local coffFiles = 36 + 8 * nfolders + local dataAt = coffFiles + buffer.len(fileTable) + local size = dataAt + buffer.len(blob) + local w = Bytes.writer(size) + w:string("MSCF") + w:u32le(0) + w:u32le(size) + w:u32le(0) + w:u32le(coffFiles) + w:u32le(0) + w:u8(3) + w:u8(1) + w:u16le(nfolders) + w:u16le(#files) + w:u16le(0) + w:u16le(o.setId or 0) + w:u16le(0) + w:u32le(dataAt) + w:u16le(nblocks) + w:u16le(if compression == "mszip" then 1 else 0) + w:bytes(fileTable) + w:bytes(blob) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) +function Cab.new(): any + local a = Archive.new("cab", encode) + a.meta.source = { format = "cab" } + return a +end + +return Cab +end +__FILES["archive/cab/Sum"] = @native function() + + + +-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 +-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format +-- description ([MS-CAB] 2.4, CFDATA.csum). + +local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len +local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift + +local Sum = {} + +-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) +@native function Sum.of(buf: buffer, off: number, len: number, seed: number): number + if off < 0 or len <= 0 or off + len > blen(buf) then + return seed + end + local s = seed + local p = off + local stop = off + len - len % 4 + while p < stop do + s = bxor(s, readu32(buf, p)) + p += 4 + end + local rem = len % 4 + local tail = 0 + if rem == 3 then + tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) + elseif rem == 2 then + tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) + elseif rem == 1 then + tail = readu8(buf, p) + end + return bxor(s, tail) +end + +-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) +@native function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number + return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) +end + +return Sum +end +__FILES["archive/cpio"] = function() + +-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the +-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc +-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters), +-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor, +-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1") +-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local CpioFormat = { + name = "cpio", + category = "archive", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, +} + +type DecodeOptions = { + maxEntries: number?, -- default 1e6 + verify: boolean?, -- crc archives: check the data sums (default true) +} +type EncodeOptions = { + variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc" + format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default + block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function CpioFormat.sniff(r: Bytes.Reader): number + local m = r:peek(6) + if m == "070701" or m == "070702" or m == "070707" then + return 1 + end + local b2 = r:peek(2) + if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return CpioFormat.encode(archive, opts) +end + +function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("cpio", encode) + for _, e in list do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = if data then e.size else 0, + dir = e.dir, + mtime = e.mtime, + mode = bit32.band(e.mode, 0xFFF), + uid = e.uid, + gid = e.gid, + type = e.type, + link = e.link, + hardlink = e.hardlink, + nlink = e.nlink, + ino = e.ino, + devmajor = e.devmajor, + devminor = e.devminor, + rdevmajor = e.rdevmajor, + rdevminor = e.rdevminor, + method = "store", + load = if data then lazy(r.buf, e.offset, e.size) else nil, + }) + end + a.meta.source = { format = "cpio", variant = info.format } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(v: any): number? + return if type(v) == "number" then v else nil +end + +function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local index: { [string]: number } = {} + for i, it in items do + index[it.entry.name] = index[it.entry.name] or i + end + -- tar hard links ("1"): the same inode as their target, which counts the links + local links: { [number]: number } = {} + local target: { [number]: number } = {} + for i, it in items do + local e: any = it.entry + if e.type == "1" and type(e.link) == "string" and index[e.link] then + local t = index[e.link] + target[i] = t + links[t] = (links[t] or 1) + 1 + end + end + local list: { Cpio.WriteEntry } = {} + for i, it in items do + local e: any = it.entry + local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0" + local src = target[i] + local ino, nlink = num(e.ino), num(e.nlink) + if src then + typ, ino, nlink = "0", src, links[src] + elseif links[i] then + ino, nlink = i, links[i] + end + local data: buffer? = nil + if typ == "0" then + local b, err = (items[src or i] :: any).read() + if not b then + return nil, err + end + data = b + end + local mode = num(e.mode) + table.insert(list, { + name = e.name, + data = data, + type = typ, + link = if type(e.link) == "string" and typ == "2" then e.link else nil, + mode = if mode then bit32.band(mode, 0xFFF) else nil, + uid = num(e.uid), + gid = num(e.gid), + nlink = nlink, + mtime = num(e.mtime), + ino = ino, + devmajor = num(e.devmajor), + devminor = num(e.devminor), + rdevmajor = num(e.rdevmajor), + rdevminor = num(e.rdevminor), + }) + end + -- opts.format may also be the api's format name ("cpio"): the variant default then + local o: any = opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc" + local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own) + return Cpio.write(list, { format = variant, block = o.block }) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write() +function CpioFormat.new(): any + local a = Archive.new("cpio", encode) + a.meta.source = { format = "cpio" } + return a +end + +return CpioFormat +end +__FILES["archive/d64"] = function() + +-- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info +-- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and +-- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are +-- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are +-- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII +-- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the +-- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any +-- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS +-- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers' +-- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local D64 = { + name = "d64", + category = "archive", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 4096 +type EncodeOptions = { + variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64" + disk: string?, -- disk name (default "rosetta" / the name read) + id: string?, -- two-character disk id (default "fl") +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" } +local TYPE_CODE: { [string]: number } = { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 } + +type Geometry = { kind: string, tracks: number, offsets: { number }, spt: { number }, dirTrack: number, total: number } + +local function geometry(kind: string, tracks: number): Geometry + local offsets, spt = {}, {} + local o = 0 + for t = 1, tracks do + local n + if kind == "d81" then + n = 40 + else + local s = if kind == "d71" and t > 35 then t - 35 else t + n = if s <= 17 then 21 elseif s <= 24 then 19 elseif s <= 30 then 18 else 17 + end + offsets[t], spt[t] = o, n + o += n * 256 + end + return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = if kind == "d81" then 40 else 18, total = o } +end + +-- image sizes -> geometry (sizes with the error-info block appended too) +local function detect(len: number): Geometry? + for _, g in { { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } } :: { { any } } do + local geo = geometry(g[1] :: string, g[2] :: number) + local sectors = geo.total // 256 + if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then + return geo + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function D64.sniff(r: Bytes.Reader): number + local geo = detect(r:size()) + if not geo then + return 0 + end + -- the BAM / header sector: dir track link and DOS version byte + local h = r:sub(geo.offsets[geo.dirTrack], 256) + local t, s, v = h:u8(), h:u8(), h:u8() + if geo.kind == "d81" then + return if t == 40 and s == 3 and v == 0x44 then 0.9 else 0.3 + end + return if t == 18 and s == 1 and (v == 0x41 or v == 0) then 0.9 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function petscii(raw: string): string + local out = table.create(#raw) + for i = 1, #raw do + local c = string.byte(raw, i) + if c >= 0x41 and c <= 0x5A then + out[i] = string.char(c + 32) + elseif c >= 0xC1 and c <= 0xDA then + out[i] = string.char(c - 0x80) + elseif c >= 0x61 and c <= 0x7A then + out[i] = string.char(c - 32) + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + out[i] = string.char(c) + else + out[i] = utf8.char(0xE000 + c) + end + end + return table.concat(out) +end + +local function toPetscii(name: string): string + local out = {} + if not utf8.len(name) then + return string.sub(name, 1, 16) + end + for _, c in utf8.codes(name) do + local b + if c >= 0x61 and c <= 0x7A then + b = c - 32 + elseif c >= 0x41 and c <= 0x5A then + b = c + 0x80 + elseif c >= 0xE000 and c <= 0xE0FF then + b = c - 0xE000 + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + b = c + else + b = 0x3F + end + table.insert(out, string.char(b)) + end + return string.sub(table.concat(out), 1, 16) +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return D64.encode(a, o) +end + +-- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops +local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?) + local w = Bytes.writer() + local seen: { [number]: boolean } = {} + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] then + return nil, string.format("chain leaves the disk at %d/%d", t, s) + end + local key = t * 256 + s + if seen[key] then + return nil, string.format("chain loops at %d/%d", t, s) + end + seen[key] = true + local o = base + geo.offsets[t] + s * 256 + local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if nt == 0 then + local last = math.max(ns, 1) + if last >= 2 then + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1))) + end + else + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254))) + end + t, s = nt, ns + end + return w:finish(), nil +end + +function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local geo = detect(r:size()) + if not geo then + return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)") + end + local b, base = r.buf, r.base + local hdr = base + geo.offsets[geo.dirTrack] + local nameAt, idAt = if geo.kind == "d81" then 0x04 else 0x90, if geo.kind == "d81" then 0x16 else 0xA2 + local diskRaw = buffer.readstring(b, hdr + nameAt, 16) + local a = Archive.new("d64", encoder) + a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", ""))) + a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2)) + a.meta.variant = geo.kind + a.meta.tracks = geo.tracks + a.meta.errorInfo = r:size() ~= geo.total + a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } + -- the directory chain + local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) + local seen: { [number]: boolean } = {} + local count = 0 + local maxEntries = o.maxEntries or 4096 + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then + return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s)) + end + seen[t * 256 + s] = true + local so = base + geo.offsets[t] + s * 256 + for k = 0, 7 do + local e = so + k * 32 + local ft = buffer.readu8(b, e + 2) + local kind = bit32.band(ft, 15) + if ft ~= 0 and kind ~= 0 then + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries") + end + local raw = buffer.readstring(b, e + 5, 16) + local name = petscii((string.gsub(raw, "\160+$", ""))) + local base_name, n = name, 2 + while a._byName[name] do + name = base_name .. ";" .. n + n += 1 + end + local ty = TYPES[kind] or "?" + local entry: any = { + name = name, + rawName = raw, + type = ty, + closed = bit32.band(ft, 0x80) ~= 0, + locked = bit32.band(ft, 0x40) ~= 0, + blocks = buffer.readu16(b, e + 30), + dir = false, + method = "store", + } + if ty == "cbm" or ty == "dir" then + entry.size = 0 + else + local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4)) + if not data then + return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err)) + end + entry.size = buffer.len(data) + entry.data = data + if ty == "rel" then + entry.recordLength = buffer.readu8(b, e + 23) + end + end + Archive.put(a, entry) + end + end + t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- BAM layout per variant: where each track's free count + bitmap lives +local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number) + -- returns (offset of the free count, offset of the bitmap, bitmap bytes) + local dir = geo.offsets[geo.dirTrack] + if geo.kind == "d81" then + local side = if t <= 40 then 1 else 2 + local tt = if t <= 40 then t else t - 40 + local o = dir + side * 256 + 0x10 + (tt - 1) * 6 + return o, o + 1, 5 + end + if t <= 35 then + local o = dir + 4 + (t - 1) * 4 + return o, o + 1, 3 + end + -- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0 + return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3 +end + +local function setFree(geo: Geometry, img: buffer, t: number, s: number, free: boolean) + local co, bo = bamEntry(geo, img, t) + local byte = bo + bit32.rshift(s, 3) + local mask = bit32.lshift(1, bit32.band(s, 7)) + local cur = buffer.readu8(img, byte) + local isFree = bit32.band(cur, mask) ~= 0 + if free and not isFree then + buffer.writeu8(img, byte, bit32.bor(cur, mask)) + buffer.writeu8(img, co, buffer.readu8(img, co) + 1) + elseif not free and isFree then + buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask))) + buffer.writeu8(img, co, buffer.readu8(img, co) - 1) + end +end + +function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local variant = o.variant or (if type(value) == "table" and type(value.meta) == "table" and value.meta.variant then value.meta.variant else "d64") + if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then + return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81") + end + local files, err = Archive.files(value, "data") + if not files then + return nil, err + end + local geo = geometry(variant, if variant == "d64" then 35 elseif variant == "d71" then 70 else 80) + local img = buffer.create(geo.total) + local dirT = geo.dirTrack + local dir = geo.offsets[dirT] + local diskName = toPetscii(o.disk or (if type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" then value.meta.disk else "rosetta")) + local id = toPetscii(o.id or "fl") + local function pad16(s: string): string + return s .. string.rep("\160", 16 - #s) + end + -- header / BAM + local firstDir + if variant == "d81" then + buffer.writestring(img, dir, "\40\3\68\0") + buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160") + for side = 1, 2 do + local bo = dir + side * 256 + buffer.writestring(img, bo, if side == 1 then "\40\2\68\187" else "\0\255\68\187") + buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0") + end + firstDir = 3 + else + buffer.writestring(img, dir, "\18\1\65" .. (if variant == "d71" then "\128" else "\0")) + buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160") + firstDir = 1 + end + for t = 1, geo.tracks do + for s = 0, geo.spt[t] - 1 do + setFree(geo, img, t, s, true) + end + end + -- system sectors: the header / BAM sectors and the first directory sector + local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true } + if variant == "d81" then + used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true + elseif variant == "d71" then + for s = 0, geo.spt[53] - 1 do + used[53 * 256 + s] = true + end + end + for k in used do + setFree(geo, img, k // 256, k % 256, false) + end + local maxDirSectors = geo.spt[dirT] - firstDir + if #files > maxDirSectors * 8 then + return nil, Err.new(Err.LIMIT, "too many files for one directory track") + end + -- allocation: tracks nearest the directory track first, interleave 10 + local order = {} + for d = 1, geo.tracks do + for _, t in { dirT - d, dirT + d } do + if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then + table.insert(order, t) + end + end + end + local ti, lastS = 1, -10 + local function alloc(): (number?, number?) + while ti <= #order do + local t = order[ti] + local n = geo.spt[t] + for k = 0, n - 1 do + local s = (lastS + 10 + k) % n + if not used[t * 256 + s] then + used[t * 256 + s] = true + setFree(geo, img, t, s, false) + lastS = s + return t, s + end + end + ti += 1 + lastS = -10 + end + return nil, nil + end + local dirSector, slot = firstDir, 0 + local dirSectors = { firstDir } + for _, f in files do + local data = f.data + local n = buffer.len(data) + local blocks = math.max(1, math.ceil(n / 254)) + local first_t, first_s = 0, 0 + local prev = -1 + for k = 0, blocks - 1 do + local t, s = alloc() + if not t or not s then + return nil, Err.new(Err.LIMIT, "disk full") + end + local so = geo.offsets[t] + s * 256 + if prev < 0 then + first_t, first_s = t, s + else + buffer.writeu8(img, prev, t) + buffer.writeu8(img, prev + 1, s) + end + local len = math.min(254, n - k * 254) + if len > 0 then + buffer.copy(img, so + 2, data, k * 254, len) + end + buffer.writeu8(img, so + 1, if k == blocks - 1 then len + 1 else 0) + prev = so + end + if slot == 8 then + -- next directory sector on the directory track (interleave 3) + local nextS = nil + for k = 0, geo.spt[dirT] - 1 do + local s = (dirSector + 3 + k) % geo.spt[dirT] + if not used[dirT * 256 + s] then + nextS = s + break + end + end + if not nextS then + return nil, Err.new(Err.LIMIT, "directory full") + end + used[dirT * 256 + nextS] = true + setFree(geo, img, dirT, nextS, false) + buffer.writeu8(img, dir + dirSector * 256, dirT) + buffer.writeu8(img, dir + dirSector * 256 + 1, nextS) + dirSector, slot = nextS, 0 + table.insert(dirSectors, nextS) + end + local e = dir + dirSector * 256 + slot * 32 + local ty: number = if type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] then TYPE_CODE[f.entry.type] :: number else 2 + buffer.writeu8(img, e + 2, 0x80 + ty) + buffer.writeu8(img, e + 3, first_t) + buffer.writeu8(img, e + 4, first_s) + local raw = if type(f.entry.rawName) == "string" and #f.entry.rawName == 16 then (string.gsub(f.entry.rawName, "\160+$", "")) else toPetscii(f.name) + buffer.writestring(img, e + 5, pad16(raw)) + buffer.writeu16(img, e + 30, blocks) + slot += 1 + end + buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF) + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" }) +function D64.new(variant: string?): any + local a = Archive.new("d64", encoder) + a.meta.variant = variant or "d64" + a.meta.source = { format = "d64" } + return a +end + +return D64 +end +__FILES["archive/fat"] = function() + +-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the +-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 +-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the +-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy +-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a +-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Fat = __include("containers/Fat") + +-- ------------------------------------------------------------------------------------------------ contract +local FatFormat = { + name = "fat", + category = "archive", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, +} + +type DecodeOptions = { + partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself) + maxEntries: number?, -- default 65536 +} +type EncodeOptions = { + size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) + label: string?, -- volume label +} + +-- ------------------------------------------------------------------------------------------------ sniff +function FatFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + if not v then + return 0 + end + return if v.partition then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return FatFormat.encode(a, o) +end + +function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition }) + if not v then + return nil, Err.from(err) + end + local list, lerr = Fat.list(v, o.maxEntries) + if not list then + return nil, Err.from(lerr) + end + local a = Archive.new("fat", encoder) + for _, e in list do + local entry = e + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + attr = e.attr, + shortName = e.shortName, + method = "store", + load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?) + local b, rerr = Fat.read(v :: Fat.Volume, entry) + if not b then + return nil, Err.from(rerr) + end + return b, nil + end, + }) + end + a.meta.fat = v.bits + a.meta.label = v.label + a.meta.oem = v.oem + a.meta.partition = v.partition + a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local files: { Fat.WriteFile } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime }) + end + local img, err = Fat.write(files, { size = o.size, label = o.label }) + if not img then + return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err)) + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) +function FatFormat.new(): any + local a = Archive.new("fat", encoder) + a.meta.source = { format = "fat" } + return a +end + +return FatFormat +end +__FILES["archive/grp"] = function() + +-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, +-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive +-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they +-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. +-- Not supported: the "GRP 2" / RFF / SSI variants. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Grp = { + name = "grp", + category = "archive", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false) + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "KenSilverman" + +-- ------------------------------------------------------------------------------------------------ sniff +function Grp.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Grp.encode(archive, opts) +end + +function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + if not r:match(MAGIC) then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local count = r:u32le() + if r.err then + return nil, r.err + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + if count * 16 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 12) + end + local a = Archive.new("grp", encode) + local at = 16 + count * 16 + local size = r.limit - r.base + for i = 0, count - 1 do + local name = r:fixed(12) + local n = r:u32le() + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + at += n + end + if r.err then + return nil, r.err + end + a.meta.source = { format = "grp", entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = it.entry.name + if opts and opts.upper then + name = string.upper(name) + end + if #name > 12 then + return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(MAGIC) + w:u32le(#files) + for _, f in files do + w:string(f.name) + w:fill(0, 12 - #f.name) + w:u32le(buffer.len(f.data)) + end + for _, f in files do + w:bytes(f.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty GRP Archive: a:add(name, data); a:write() +function Grp.new(): any + local a = Archive.new("grp", encode) + a.meta.source = { format = "grp" } + return a +end + +return Grp +end +__FILES["archive/gzip"] = function() + +-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the +-- 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/compress/Deflate. Not supported: FHCRC verification. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Gzip = { + name = "gzip", + category = "archive", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, +} + +type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME +type EncodeOptions = { + level: number?, -- 0..9, default 6 + name: string?, -- FNAME (default: the entry's name; none for a buffer) + mtime: number?, -- MTIME (default: the entry's mtime, else 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Gzip.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\31\139\8" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) +local function header(b: buffer, o: number, e: number): { [string]: any } + local h: { [string]: any } = {} + if o + 10 > e then + return h + end + local flg = buffer.readu8(b, o + 3) + h.mtime = buffer.readu32(b, o + 4) + h.os = buffer.readu8(b, o + 9) + local q = o + 10 + 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" } } :: { { any } } do + if bit32.band(flg, f[1]) ~= 0 then + local s = q + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + if q < e then + h[f[2]] = buffer.readstring(b, s, q - s) + end + q += 1 + end + end + return h +end + +function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) + if not out then + return nil, err + end + local h = header(r.buf, r.base, r.limit) + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip", os = h.os } + a.meta.comment = h.comment + local name = h.name + if not name or name == "" or string.find(name, "[/\\]") then + name = Archive.streamName(opts, Gzip.extensions) + end + Archive.put(a, { + name = name, + size = buffer.len(out), + compressedSize = r.limit - r.base, + method = "deflate", + mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil, + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + 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") + end + local data: buffer + local name: string? = o.name + local mtime: number = o.mtime or 0 + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + else + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local files: typeof(items) = {} + for _, it in items do + if not it.entry.dir then + table.insert(files, it) + end + end + if #files == 1 and #items == 1 then + local b, err = files[1].read() + if not b then + return nil, err + end + data = b + name = name or files[1].entry.name + mtime = o.mtime or files[1].entry.mtime or 0 + else + -- several entries: a tar inside + local list = {} + for _, it in items do + local e: any = it.entry + local b = nil + if not e.dir then + local rb, err = it.read() + if not rb then + return nil, err + end + b = rb + end + table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode }) + end + local t, terr = Tar.write(list) + if not t then + return nil, terr + end + data = t + end + end + if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then + mtime = 0 + end + local raw, cerr = Deflate.compress(data, { level = level }) + if not raw then + return nil, cerr + end + local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0)) + w:string("\31\139\8") + w:u8(if name then 8 else 0) + w:u32le(math.floor(mtime)) + w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0) + w:u8(255) + if name then + local z = string.find(name, "\0", 1, true) + w:cstring(if z then string.sub(name, 1, z - 1) else name) + end + w:bytes(raw) + w:u32le(Crc32.raw(data, 0, buffer.len(data))) + w:u32le(buffer.len(data) % 4294967296) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) +function Gzip.new(data: (buffer | string)?, name: string?): any + local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?) + return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip" } + if data then + a:add(name or "data", data) + end + return a +end + +return Gzip +end +__FILES["archive/iso"] = function() + +-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660: +-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories; +-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files. +-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts +-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El +-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one. +-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored +-- bytes), multi-session images (the first session). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Iso9660 = __include("containers/Iso9660") + +-- ------------------------------------------------------------------------------------------------ contract +local Iso = { + name = "iso", + category = "archive", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, +} + +type DecodeOptions = { + prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain) + maxEntries: number?, -- default 1e6 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Iso.sniff(r: Bytes.Reader): number + return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("iso") + local b, limit = r.buf, r.limit + for _, e in list do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + type = e.type, + mode = e.mode, + uid = e.uid, + gid = e.gid, + nlink = e.nlink, + link = e.link, + rdev = e.rdev, + hidden = e.hidden, + method = if e.zisofs then "zisofs" else "store", + load = if data + then function(): (buffer?, Err.Err?) + return Iso9660.extract(b, e, limit) + end + else nil, + }) + end + a.meta.boot = info.boot + info.boot = nil + a.meta.iso = info + a.meta.source = { format = "iso", tree = info.tree } + return a, nil +end + +return Iso +end +__FILES["archive/lha"] = function() + +-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their +-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS +-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, +-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. +-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower +-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header +-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu +-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), +-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or +-- at the first header found in the first 64 KB). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lha = { + name = "lha", + category = "archive", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxEntries: number?, -- default 65536 +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS: { [string]: boolean } = { + ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true, + ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true, + ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true, +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isHeader(s: string): boolean + if #s < 22 then + return false + end + local m = string.sub(s, 3, 7) + local level = string.byte(s, 21) + return METHODS[m] == true and level <= 3 +end + +function Lha.sniff(r: Bytes.Reader): number + if isHeader(r:peek(22)) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) +local function path(s: string): string + s = string.gsub(s, "[\\\255]", "/") + local parts = {} + for part in string.gmatch(s, "[^/]+") do + if part ~= "." and part ~= ".." then + table.insert(parts, part) + end + end + return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "") +end + +type Header = { + method: string, + packed: number, + size: number, + mtime: number?, + level: number, + name: string, + dir: string?, + crc: number?, + mode: number?, + uid: number?, + gid: number?, + uname: string?, + gname: string?, + attr: number?, + comment: string?, + os: string?, + dataAt: number, +} + +-- the extended headers from offset p (size field width w), until a zero size; returns the end offset +local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) + local size = first + local guard = 0 + while size ~= 0 do + guard += 1 + if guard > 4096 or size < w + 1 or p + size > limit then + return nil, "bad extended header" + end + local e = r:sub(p, size) + local kind = e:u8() + local body = size - 1 - w + if kind == 0x01 then + h.name = e:string(body) + elseif kind == 0x02 then + h.dir = e:string(body) + elseif kind == 0x3F or kind == 0x71 then + h.comment = e:string(body) + elseif kind == 0x40 and body >= 2 then + h.attr = e:u16le() + elseif kind == 0x50 and body >= 2 then + h.mode = e:u16le() + elseif kind == 0x51 and body >= 4 then + h.gid, h.uid = e:u16le(), e:u16le() + elseif kind == 0x52 then + h.gname = e:string(body) + elseif kind == 0x53 then + h.uname = e:string(body) + elseif kind == 0x54 and body >= 4 then + h.mtime = e:u32le() + elseif kind == 0x42 and body >= 16 then + h.packed, h.size = e:u64le(), e:u64le() + end + e:seek(size - w) + local nextSize = if w == 2 then e:u16le() else e:u32le() + if e.err then + return nil, "truncated extended header" + end + p += size + size = nextSize + end + return p, nil +end + +local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386", + [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", + [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } + +-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker +local function header(r: Bytes.Reader, p: number): (Header?, string?) + local limit = r:size() + if p >= limit or r:sub(p, 1):u8() == 0 then + return nil, nil + end + if p + 22 > limit then + return nil, "truncated header" + end + local s = r:sub(p, 26) + local b0 = s:u8() + s:u8() + local method = s:string(5) + local packed, size, stamp = s:u32le(), s:u32le(), s:u32le() + s:u8() + local level = s:u8() + if not METHODS[method] then + return nil, "bad method " .. method + end + local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 } + if level == 0 or level == 1 then + local hsize = b0 + 2 + if p + hsize > limit or hsize < 24 then + return nil, "truncated header" + end + local hr = r:sub(p + 21, hsize - 21) + local nlen = hr:u8() + h.name = hr:string(nlen) + h.crc = hr:u16le() + h.mtime = Archive.fromDos(stamp) + if level == 0 then + -- an optional Unix extension: 'U', mtime, mode, uid, gid + if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then + h.os = if hr:u8() == 0x55 then "unix" else "os68k" + h.mtime = hr:u32le() + h.mode = hr:u16le() + h.uid, h.gid = hr:u16le(), hr:u16le() + end + h.dataAt = p + hsize + else + h.os = OS[hr:u8()] + local first = r:sub(p + hsize - 2, 2):u16le() + local e, err = extended(r, p + hsize, 2, first, h, limit) + if not e then + return nil, err + end + h.packed = packed - (e - (p + hsize)) + h.dataAt = e + end + if hr.err then + return nil, "truncated header" + end + elseif level == 2 then + local total = r:sub(p, 2):u16le() + local hr = r:sub(p + 21, 5) + h.crc = hr:u16le() + local osByte = hr:u8() + h.os = OS[osByte] + if osByte == 0x4B then + total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates) + end + local first = hr:u16le() + h.mtime = stamp + local e, err = extended(r, p + 26, 2, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 26 or h.dataAt > limit then + return nil, "bad level 2 header size" + end + elseif level == 3 then + local hr = r:sub(p + 21, 11) + h.crc = hr:u16le() + h.os = OS[hr:u8()] + local total = hr:u32le() + local first = hr:u32le() + h.mtime = stamp + local e, err = extended(r, p + 32, 4, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 32 or h.dataAt > limit then + return nil, "bad level 3 header size" + end + else + return nil, "unsupported: header level " .. level + end + return h, nil +end + +local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" } + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Lha.encode(a, o) +end + +function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local p = 0 + -- a self-extracting stub: find the first header + if not isHeader(r:peek(22)) then + local head = r:peek(65536) + local at = nil + for k = 1, #head - 22 do + if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then + at = k - 1 + break + end + end + if not at then + return nil, Err.new(Err.CORRUPT, "no LHA header") + end + p = at + end + local a = Archive.new("lha", encoder) + local count = 0 + local levels = {} + while true do + local h, err = header(r, p) + if err then + return nil, Err.from(err, r.base + p) + end + if not h then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + levels[h.level] = true + if h.packed < 0 or h.dataAt + h.packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt) + end + -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do + local os = h.os + if os == nil or os == "msdos" or os == "atari" or os == "os2" then + if not string.find(h.name .. (h.dir or ""), "%l") then + h.name = string.lower(h.name) + h.dir = if h.dir then string.lower(h.dir) else nil + end + end + -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers) + local name = path(h.name) + if h.dir and h.dir ~= "" then + local d = path(h.dir) + if string.sub(d, -1) ~= "/" then + d ..= "/" + end + name = d .. name + end + local link: string? = nil + local bar = string.find(name, "|", 1, true) + if bar then + name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1) + end + local isDir = h.method == "lhd" + if isDir and link == nil and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local e: any = { + name = name, + size = if isDir or link then 0 else h.size, + compressedSize = h.packed, + method = h.method, + mtime = h.mtime, + dir = isDir and link == nil, + mode = h.mode, + uid = h.uid, + gid = h.gid, + uname = h.uname, + gname = h.gname, + attr = h.attr, + comment = h.comment, + os = h.os, + level = h.level, + crc = h.crc, + } + if link then + e.link = link + e.type = "symlink" + elseif not isDir and h.size > 0 then + if h.size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc + local buf, base = r.buf, r.base + e.load = function(): (buffer?, Err.Err?) + local out: buffer?, derr: string? + if method == "lh0" or method == "lz4" then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out :: buffer, 0, buf, base + at, size) + elseif LZH_METHOD[method] then + out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method]) + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if crc and Crc16.arc(out, 0, size) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + p = h.dataAt + h.packed + end + a.meta.source = { format = "lha", levels = levels } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out = Bytes.writer() + for _, it in items do + local e: any = it.entry + local data = buffer.create(0) + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local full = string.gsub(e.name, "/+$", "") + local dirPart, base = string.match(full, "^(.*/)([^/]*)$") + if not dirPart then + dirPart, base = "", full + end + if e.dir then + dirPart, base = full .. "/", "" + end + local h = Bytes.writer() + h:u16le(0) -- total size, patched + h:string(if e.dir then "-lhd-" else "-lh0-") + h:u32le(buffer.len(data)) + h:u32le(buffer.len(data)) + h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0) + h:u8(0x20) + h:u8(2) + h:u16le(Crc16.arc(data, 0, buffer.len(data))) + h:u8(0x55) -- 'U'nix + -- extended headers: [type][body][size of the next one]; the first size ends the base header + local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } } + if dirPart ~= "" then + table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) }) + end + if type(e.mode) == "number" then + local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000) + table.insert(exts, { 0x50, string.char(m % 256, m // 256) }) + end + h:u16le(#exts[1][2] + 3) + for i, x in exts do + h:u8(x[1]) + h:string(x[2]) + h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0) + end + local hb = h:finish() + local total = buffer.len(hb) + if total > 65535 then + return nil, Err.new(Err.ARG, "header too long for " .. e.name) + end + buffer.writeu16(hb, 0, total) + -- the header CRC covers the whole header with its own field zero + local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27 + buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total)) + out:bytes(hb) + out:bytes(data) + end + out:u8(0) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) +function Lha.new(): any + local a = Archive.new("lha", encoder) + a.meta.source = { format = "lha" } + return a +end + +return Lha +end +__FILES["archive/lz4"] = function() + +-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the +-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api +-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy +-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed +-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified +-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks +-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; +-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: +-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lz4 = __include("codecs/compress/Lz4") +local Xxh32 = __include("codecs/compress/Xxh32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lz4Format = { + name = "lz4", + category = "archive", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked) + name: string?, -- the file name (the api passes it): names the entry +} +type EncodeOptions = { + blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) + blockChecksum: boolean?, -- default false + contentChecksum: boolean?, -- default true + contentSize: boolean?, -- store the content size (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = 0x184D2204 +local LEGACY = 0x184C2102 +local LEGACY_BLOCK = 8 * 1048576 +local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lz4Format.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\4\34\77\24" then + return 1 + elseif m == "\2\33\76\24" then + return 0.9 + elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then + -- a skippable frame (zstd shares the magic): an LZ4 frame after it + local h = r:peek(4, 4) + if #h == 4 then + local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216 + if r:peek(4, 8 + n) == "\4\34\77\24" then + return 1 + end + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function skippable(m: number): boolean + return m >= 0x184D2A50 and m <= 0x184D2A5F +end + +type Out = { buf: buffer, n: number, max: number } + +-- room for k more bytes in the output (doubling, up to max) | false +local function room(out: Out, k: number): boolean + local need = out.n + k + if need > out.max then + return false + end + if need > buffer.len(out.buf) then + local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max)) + buffer.copy(nb, 0, out.buf, 0, out.n) + out.buf = nb + end + return true +end + +-- one LZ4 frame at p -> the input offset after it | nil, Err +local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) + if p + 7 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) + end + local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5) + if bit32.rshift(flg, 6) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4) + end + if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then + return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4) + end + local independent = bit32.band(flg, 0x20) ~= 0 + local blockSum = bit32.band(flg, 0x10) ~= 0 + local hasSize = bit32.band(flg, 0x08) ~= 0 + local contentSum = bit32.band(flg, 0x04) ~= 0 + local hasDict = bit32.band(flg, 0x01) ~= 0 + local bmax = SIZES[bit32.rshift(bd, 4)] + if not bmax then + return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5) + end + local q = p + 6 + local size: number? = nil + if hasSize then + if q + 8 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296 + q += 8 + end + if hasDict then + return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q) + end + if q + 1 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255) + if hc ~= buffer.readu8(b, q) then + return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q) + end + q += 1 + if size and out.n + size > out.max then + return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p) + end + local start = out.n + while true do + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "block header past the end", q) + end + local bs = buffer.readu32(b, q) + q += 4 + if bs == 0 then + break + end + local raw = bit32.band(bs, 0x80000000) ~= 0 + local n = bit32.band(bs, 0x7FFFFFFF) + if n > bmax then + return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4) + end + if q + n + (if blockSum then 4 else 0) > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then + return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n) + end + if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + if raw then + buffer.copy(out.buf, out.n, b, q, n) + out.n += n + else + local lim = math.min(out.n + bmax, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start) + if not dEnd then + if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + return nil, Err.from(msg, q) + end + out.n = dEnd + end + q += n + (if blockSum then 4 else 0) + end + if contentSum then + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q) + end + if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q) + end + q += 4 + end + if size and out.n - start ~= size then + return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6) + end + return q, nil +end + +-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows +local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?) + local q = p + 4 + while q + 4 <= e do + local n = buffer.readu32(b, q) + if n == MAGIC or n == LEGACY or skippable(n) then + break + end + q += 4 + if q + n > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim) + if not dEnd then + return nil, Err.from(msg, q) + end + out.n = dEnd + q += n + end + return q, nil +end + +-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err +function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + local verify = not (opts and opts.verify == false) + local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes } + local p, e = o, o + n + local frames = 0 + while p + 4 <= e do + local m = buffer.readu32(b, p) + local q, err + if m == MAGIC then + q, err = frame(b, p, e, out, verify) + frames += 1 + elseif m == LEGACY then + q, err = legacy(b, p, e, out) + frames += 1 + elseif skippable(m) then + if p + 8 > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + q = p + 8 + buffer.readu32(b, p + 4) + if q > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + elseif frames > 0 then + break -- trailing data after the frames (as lz4 -d, which warns) + else + return nil, Err.new(Err.CORRUPT, "bad magic", p) + end + if not q then + return nil, err + end + p = q :: number + end + if frames == 0 then + return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o) + end + local res = buffer.create(out.n) + buffer.copy(res, 0, out.buf, 0, out.n) + return res, nil +end + +local function encode(value: any, opts: any?): (buffer?, Err.Err?) + return Lz4Format.encode(value, opts) +end + +function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, err = Lz4Format.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("lz4", encode) + a.meta.stream = true + a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" } + local name = Archive.streamName(o, { "lz4" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and string.lower(ext) == "tlz4" then + name = stem .. ".tar" + end + Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- compress(data, opts?) -> one LZ4 frame | nil, Err +function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) + if not b then + return nil, aerr + end + local op: EncodeOptions = opts or {} + local bsize = op.blockSize or 4194304 + local bd = nil + for k, v in SIZES do + if v == bsize then + bd = k + end + end + if not bd then + return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304") + end + local blockSum = op.blockChecksum == true + local contentSum = op.contentChecksum ~= false + local withSize = op.contentSize == true + local w = Bytes.writer(n + n // 200 + 64) + w:u32le(MAGIC) + local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0) + w:u8(flg) + w:u8(bd * 16) + if withSize then + w:u32le(n % 4294967296) + w:u32le(n // 4294967296) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255) + w:u8(hc) + local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1)))) + local p = o + while p < o + n do + local k = math.min(bsize, o + n - p) + local c = Lz4.encodeInto(b, p, k, scratch, 0) + local at = w.pos + if c < k then + w:u32le(c) + local q = w:reserve(c) + buffer.copy(w.buf, q, scratch, 0, c) + w.pos = q + c + else + w:u32le(k + 0x80000000) + local q = w:reserve(k) + buffer.copy(w.buf, q, b, p, k) + w.pos = q + k + end + if blockSum then + local len = w.pos - at - 4 + w:u32le(Xxh32.hash(w.buf, at + 4, len)) + end + p += k + end + w:u32le(0) + if contentSum then + w:u32le(Xxh32.hash(b, o, n)) + end + return w:finish(), nil +end + +-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame +function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return Lz4Format.compress(data, opts) +end + +return Lz4Format +end +__FILES["archive/macbinary"] = function() + +-- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags, +-- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III +-- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its +-- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry +-- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / +-- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the +-- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local MacBinary = { + name = "macbinary", + category = "archive", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, +} + +type DecodeOptions = { maxBytes: number? } -- default 2^30 +type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data") + +-- ------------------------------------------------------------------------------------------------ sniff +-- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o +local function version(b: buffer, o: number, len: number): string? + if len < 128 then + return nil + end + local u8 = function(i: number): number + return buffer.readu8(b, o + i) + end + if u8(0) ~= 0 or u8(74) ~= 0 then + return nil + end + local nameLen = u8(1) + if nameLen < 1 or nameLen > 63 then + return nil + end + local function be32(i: number): number + return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3) + end + local dlen, rlen = be32(83), be32(87) + if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then + return nil + end + local crc = u8(124) * 256 + u8(125) + if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then + return if buffer.readstring(b, o + 102, 4) == "mBIN" then "III" else "II" + end + if buffer.readstring(b, o + 102, 4) == "mBIN" then + return nil -- III with a bad CRC + end + -- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file + if u8(82) ~= 0 then + return nil + end + for i = 99, 125 do + if u8(i) ~= 0 then + return nil + end + end + local need = 128 + math.ceil(dlen / 128) * 128 + rlen + return if need <= len + 127 then "I" else nil +end + +function MacBinary.sniff(r: Bytes.Reader): number + local n = math.min(r:remaining(), 128) + if n < 128 then + return 0 + end + local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + return if v == "III" then 0.95 elseif v == "II" then 0.8 elseif v == "I" then 0.3 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return MacBinary.encode(a, o) +end + +local function pad(n: number): number + return math.ceil(n / 128) * 128 +end + +function MacBinary.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local v = version(r.buf, r.base, len) + if not v then + if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + return nil, Err.new(if len < 128 then Err.TRUNCATED else Err.CORRUPT, "not a MacBinary header") + end + local h = r:sub(0, 128) + h:seek(1) + local name = h:string(h:u8()) + h:seek(65) + local ftype, creator = h:string(4), h:string(4) + local flagsHi = h:u8() + h:seek(83) + local dlen, rlen = h:u32be(), h:u32be() + local created, modified = h:u32be(), h:u32be() + local commentLen = h:u16be() + local flagsLo = h:u8() + h:seek(120) + local secondary = h:u16be() + if v == "I" then + commentLen, flagsLo, secondary = 0, 0, 0 + end + if dlen + rlen > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + r:seek(128 + pad(secondary)) + local data = r:bytes(dlen) + r:seek(128 + pad(secondary) + pad(dlen)) + local rsrc = r:bytes(rlen) + local comment: string? = nil + if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then + comment = MacFile.name(r:string(math.min(commentLen, r:remaining()))) + end + if r.err then + return nil, r.err + end + local a = Archive.new("macbinary", encoder) + MacFile.put(a, { + name = MacFile.name(name), + data = data, + rsrc = rsrc, + type = ftype, + creator = creator, + flags = flagsHi * 256 + flagsLo, + created = MacFile.fromMac(created), + modified = MacFile.fromMac(modified), + comment = comment, + }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "macbinary", version = v } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function MacBinary.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc) + local comment = if f.comment then MacFile.roman(f.comment) else "" + local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment) + buffer.writeu8(out, 1, #name) + buffer.writestring(out, 2, name) + buffer.writestring(out, 65, f.type) + buffer.writestring(out, 69, f.creator) + buffer.writeu8(out, 73, bit32.rshift(f.flags, 8)) + local function be32(at: number, v: number) + buffer.writeu32(out, at, bit32.byteswap(v)) + end + be32(83, dlen) + be32(87, rlen) + be32(91, MacFile.toMac(f.created or f.modified)) + be32(95, MacFile.toMac(f.modified)) + buffer.writeu8(out, 99, bit32.rshift(#comment, 8)) + buffer.writeu8(out, 100, bit32.band(#comment, 255)) + buffer.writeu8(out, 101, bit32.band(f.flags, 255)) + buffer.writestring(out, 102, "mBIN") + buffer.writeu8(out, 122, 130) + buffer.writeu8(out, 123, 129) + local crc = Crc16.ccitt(out, 0, 124) + buffer.writeu8(out, 124, bit32.rshift(crc, 8)) + buffer.writeu8(out, 125, bit32.band(crc, 255)) + buffer.copy(out, 128, f.data) + buffer.copy(out, 128 + pad(dlen), f.rsrc) + buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork +function MacBinary.new(): any + local a = Archive.new("macbinary", encoder) + a.meta.source = { format = "macbinary" } + return a +end + +return MacBinary +end +__FILES["archive/mpq"] = function() + +-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the +-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset +-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block +-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block +-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded +-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 +-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks +-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive +-- Format", and StormLib's documentation); no code taken. +-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET +-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, +-- writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Lzma = __include("codecs/compress/Lzma") +local Explode = __include("codecs/compress/Explode") +local Crypt = __include("archive/mpq/Crypt") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpq = { + name = "mpq", + category = "archive", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)") + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- the largest file read (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 +local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 +local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) +local TWO32 = 4294967296 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpq.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "MPQ\x1A" or m == "MPQ\x1B" then + return 1 + end + -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB + for at = 512, math.min(65536, r:remaining() - 32), 512 do + if r:peek(4, at) == "MPQ\x1A" then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros +local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?) + local out = buffer.create(want) + local p, stop, o = at + 4, at + n, 0 + while p < stop and o < want do + local c = buffer.readu8(b, p) + p += 1 + if c >= 0x80 then + local k = c - 0x7F + if p + k > stop then + return nil, "sparse run past the end" + end + k = math.min(k, want - o) + buffer.copy(out, o, b, p, k) + p += k + o += k + else + o = math.min(want, o + c + 3) + end + end + return out, nil +end + +-- one compressed sector (mask byte first) -> want bytes +local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) + if n < 1 then + return nil, Err.new(Err.CORRUPT, "empty compressed sector") + end + local mask = buffer.readu8(b, at) + local cur: buffer, cat: number, cn: number = b, at + 1, n - 1 + if mask == 0x12 then + if cn < 14 or buffer.readu8(b, cat) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") + end + local props = buffer.readstring(b, cat + 1, 5) + local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) + if not out then + return nil, e + end + return out, nil + end + if band(mask, 0xC1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) + end + if band(mask, 0x10) ~= 0 then + local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x08) ~= 0 then + local out, e = Explode.decompress(cur, cat, cn, want) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x02) ~= 0 then + local out, e = Deflate.zlib(cur, cat, cn) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x20) ~= 0 then + local out, msg = unsparse(cur, cat, cn, want) + if not out then + return nil, Err.from(msg) + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x3A) ~= mask then + return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) + end + if cn ~= want then + return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) + end + if cur == b then + local len = cn :: number + local copy = buffer.create(len) + buffer.copy(copy, 0, b, cat, len) + return copy, nil + end + return cur, nil +end + +type Block = { offset: number, csize: number, size: number, flags: number } + +-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) +local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) + local flags = blk.flags + if band(flags, FLAG_PATCH) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "patch files") + end + if blk.size > maxBytes then + return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") + end + if at + blk.csize > limit then + return nil, Err.new(Err.TRUNCATED, "file data past the end") + end + local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 + local key = 0 + if encrypted then + if not name then + return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") + end + key = Crypt.hash(Crypt.baseName(name), 3) + if band(flags, FLAG_FIX_KEY) ~= 0 then + key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) + end + end + local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 + local imploded = band(flags, FLAG_IMPLODE) ~= 0 + local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?) + local raw = buffer.create(sn) + buffer.copy(raw, 0, src, sat, sn) + if encrypted then + Crypt.decrypt(raw, 0, sn, k) + end + if compressed and sn < want then + if imploded then + return Explode.decompress(raw, 0, sn, want) + end + return decompress(raw, 0, sn, want) + end + if sn ~= want then + if sn > want then + local cut = buffer.create(want) + buffer.copy(cut, 0, raw, 0, want) + return cut, nil + end + return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) + end + return raw, nil + end + if band(flags, FLAG_SINGLE) ~= 0 then + local out, e = sector(b, at, blk.csize, blk.size, key) + if out and buffer.len(out) ~= blk.size then + return nil, Err.new(Err.CORRUPT, "file size mismatch") + end + return out, e + end + local out = buffer.create(blk.size) + local nsec = (blk.size + sectorSize - 1) // sectorSize + if not compressed then + -- stored in sectors (each decrypted with key + its index) + for i = 0, nsec - 1 do + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + i * sectorSize, want, want, key + i) + if not s then + return nil, e + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil + end + local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0) + if entries * 4 > blk.csize then + return nil, Err.new(Err.CORRUPT, "sector table larger than the file") + end + local tbl = buffer.create(entries * 4) + buffer.copy(tbl, 0, b, at, entries * 4) + if encrypted then + Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) + end + for i = 0, nsec - 1 do + local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) + if s1 < s0 or s1 > blk.csize then + return nil, Err.new(Err.CORRUPT, "bad sector offset table") + end + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + s0, s1 - s0, want, key + i) + if not s then + return nil, e + end + if buffer.len(s) ~= want then + return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil +end + +local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) + return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") +end + +-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil +local function findHeader(r: Bytes.Reader): number? + local size = r.limit - r.base + local p = 0 + while p + 32 <= size do + local m = buffer.readstring(r.buf, r.base + p, 4) + if m == "MPQ\x1A" then + return p + elseif m == "MPQ\x1B" and p + 12 <= size then + local at = p + buffer.readu32(r.buf, r.base + p + 8) + if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then + return at + end + end + p += 512 + end + return nil +end + +function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local found = findHeader(r) + if not found then + return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0) + end + local h: number = found + local hr = r:sub(h) + hr:skip(4) + local headerSize, archiveSize = hr:u32le(), hr:u32le() + local version, shift = hr:u16le(), hr:u16le() + local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() + local hiBlockPos, hashHi, blockHi = 0, 0, 0 + if version >= 1 and headerSize >= 44 then + hiBlockPos = hr:u64le() + hashHi, blockHi = hr:u16le(), hr:u16le() + end + if hr.err then + return nil, hr.err + end + if shift > 20 then + return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) + end + local sectorSize = 512 * 2 ^ shift + if hashCount == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") + end + local maxEntries: number = opts and opts.maxEntries or 1e6 + if hashCount > maxEntries * 4 or blockCount > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local size = r.limit - r.base + local hashAt = h + hashPos + hashHi * TWO32 + local blockAt = h + blockPos + blockHi * TWO32 + if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then + return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) + end + local hashes = buffer.create(hashCount * 16) + buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) + Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) + local blocksBuf = buffer.create(blockCount * 16) + buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) + Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) + local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1 + if hiAt >= 0 and hiAt + blockCount * 2 > size then + hiAt = -1 + end + local blocks: { Block } = {} + for i = 0, blockCount - 1 do + local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0 + blocks[i + 1] = { + offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, + csize = buffer.readu32(blocksBuf, i * 16 + 4), + size = buffer.readu32(blocksBuf, i * 16 + 8), + flags = buffer.readu32(blocksBuf, i * 16 + 12), + } + end + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local mask = hashCount - 1 + local pow2 = band(hashCount, mask) == 0 + -- lookup(name) -> block index (1-based) | nil + local function lookup(name: string): number? + local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) + local start = if pow2 then band(h0, mask) else h0 % hashCount + for k = 0, hashCount - 1 do + local o = ((start + k) % hashCount) * 16 + local bi = buffer.readu32(hashes, o + 12) + if bi == 0xFFFFFFFF then + return nil + end + if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then + return bi + 1 + end + end + return nil + end + local function usable(bi: number): boolean + local f = blocks[bi].flags + return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 + end + local function blockData(bi: number, name: string?): (buffer?, Err.Err?) + local blk = blocks[bi] + return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) + end + -- names: (listfile) and opts.names + local names: { string } = {} + for _, internal in { "(attributes)", "(signature)", "(user data)" } do + table.insert(names, internal) + end + local lf = lookup("(listfile)") + if lf and usable(lf) then + table.insert(names, "(listfile)") + local data = blockData(lf, "(listfile)") + if data then + for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do + local nm = string.match(line, "^%s*(.-)%s*$") + if nm and nm ~= "" then + table.insert(names, nm) + end + end + end + end + if opts and type(opts.names) == "table" then + for _, nm in opts.names do + if type(nm) == "string" then + table.insert(names, nm) + end + end + end + local a = Archive.new("mpq", encode) + local named: { [number]: string } = {} + local function add(bi: number, name: string?) + local blk = blocks[bi] + local entryName = name or string.format("File%08d.xxx", bi - 1) + Archive.put(a, { + name = entryName, + size = blk.size, + compressedSize = blk.csize, + dir = false, + method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store", + encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, + flags = blk.flags, + block = bi - 1, + load = function(): (buffer?, Err.Err?) + return blockData(bi, name) + end, + }) + end + for _, nm in names do + local bi = lookup(nm) + if bi and usable(bi) and not named[bi] then + named[bi] = nm + add(bi, nm) + end + end + for bi = 1, blockCount do + if not named[bi] and usable(bi) and blocks[bi].size > 0 then + add(bi, nil) + end + end + a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) +Mpq.hash = Crypt.hash + +return Mpq +end +__FILES["archive/mpq/Crypt"] = @native function() + + +-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file +-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois +-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every +-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot + +local Crypt = {} + +local TWO32 = 4294967296 +local TABLE = buffer.create(0x500 * 4) +do + local seed = 0x00100001 + for i1 = 0, 255 do + local i2 = i1 + for _ = 0, 4 do + seed = (seed * 125 + 3) % 0x2AAAAB + local t1 = band(seed, 0xFFFF) * 65536 + seed = (seed * 125 + 3) % 0x2AAAAB + local t2 = band(seed, 0xFFFF) + writeu32(TABLE, i2 * 4, t1 + t2) + i2 += 0x100 + end + end +end + +-- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +@native function Crypt.hash(name: string, kind: number): number + local s1, s2 = 0x7FED7FED, 0xEEEEEEEE + local base = kind * 0x100 + for i = 1, #name do + local c = string.byte(name, i) + if c >= 97 and c <= 122 then + c -= 32 + elseif c == 47 then + c = 92 + end + s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) + s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 + end + return s1 +end + +-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +@native function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) + local s2 = 0xEEEEEEEE + local k = key % TWO32 + for i = 0, n // 4 - 1 do + local o = at + i * 4 + s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 + local ch = bxor(readu32(buf, o), (k + s2) % TWO32) + k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) + s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 + writeu32(buf, o, ch) + end +end + +-- base name of an archived path (the file key uses it) +@native function Crypt.baseName(name: string): string + return string.match(name, "([^\\/]*)$") or name +end + +return Crypt +end +__FILES["archive/pak"] = function() + +-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the +-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored +-- bytes) and written from any Archive value. Written from the format description in the Quake source release +-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. +-- Not supported: Daikatana's compressed PAK entries. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Pak = { + name = "pak", + category = "archive", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake" + +-- ------------------------------------------------------------------------------------------------ constants +local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Pak.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Pak.encode(archive, opts) +end + +function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local magic = r:string(4) + local dirOfs, dirLen = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil + if not variant then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local nameLen = VARIANTS[variant].nameLen + local entrySize = nameLen + 8 + local size = r.limit - r.base + if dirOfs + dirLen > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) + end + if dirLen % entrySize ~= 0 then + return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) + end + local count = dirLen // entrySize + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + local a = Archive.new("pak", encode) + local d = r:sub(dirOfs, dirLen) + for i = 0, count - 1 do + local name = d:fixed(nameLen) + local at, n = d:u32le(), d:u32le() + if d.err then + return nil, d.err + end + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + end + a.meta.source = { format = "pak", variant = variant, entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake" + local v = VARIANTS[variant] + if not v then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = string.gsub(it.entry.name, "\\", "/") + if #name >= v.nameLen then + return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(v.magic) + w:u32le(0) + w:u32le(0) + local offsets: { number } = {} + for i, f in files do + offsets[i] = w:tell() + w:bytes(f.data) + end + local dirOfs = w:tell() + for i, f in files do + w:string(f.name) + w:fill(0, v.nameLen - #f.name) + w:u32le(offsets[i]) + w:u32le(buffer.len(f.data)) + end + w:setU32le(4, dirOfs) + w:setU32le(8, w:tell() - dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() +function Pak.new(variant: ("quake" | "sin")?): any + local a = Archive.new("pak", encode) + a.meta.source = { format = "pak", variant = variant or "quake" } + return a +end + +return Pak +end +__FILES["archive/rpm"] = function() + +-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature +-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in +-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with +-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload +-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed +-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not +-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package +-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio" +-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local Rpm = { + name = "rpm", + category = "archive", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- the largest decompressed payload (default 2^30) + maxEntries: number?, -- default 1e6 +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEAD_MAGIC = "\237\171\238\219" +local HEADER_MAGIC = "\142\173\232\1" +local RPMFILE_GHOST = 64 + +-- the tags meta.rpm names +local NAMES: { [number]: string } = { + [1000] = "name", + [1001] = "version", + [1002] = "release", + [1003] = "epoch", + [1004] = "summary", + [1005] = "description", + [1006] = "buildtime", + [1007] = "buildhost", + [1009] = "size", + [1010] = "distribution", + [1011] = "vendor", + [1014] = "license", + [1015] = "packager", + [1016] = "group", + [1020] = "url", + [1021] = "os", + [1022] = "arch", + [1044] = "sourcerpm", + [1047] = "provides", + [1049] = "requires", + [1124] = "payloadFormat", + [1125] = "payloadCompressor", + [1126] = "payloadFlags", + [5009] = "longsize", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Rpm.sniff(r: Bytes.Reader): number + return if r:peek(4) == LEAD_MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a header structure at p -> { [tag] = value }, end offset | nil, Err +local function header(b: buffer, p: number, e: number): (any, any) + if p + 16 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local n = bit32.byteswap(buffer.readu32(b, p + 8)) + local hsize = bit32.byteswap(buffer.readu32(b, p + 12)) + local index = p + 16 + local store = index + n * 16 + if n > 0x10000 or hsize > 0x10000000 then + return nil, Err.new(Err.LIMIT, "header too large", p) + end + if store + hsize > e then + return nil, Err.new(Err.TRUNCATED, "header data past the end", p) + end + local tags: { [number]: any } = {} + local se = store + hsize + for i = 0, n - 1 do + local q = index + i * 16 + local tag = bit32.byteswap(buffer.readu32(b, q)) + local typ = bit32.byteswap(buffer.readu32(b, q + 4)) + local off = bit32.byteswap(buffer.readu32(b, q + 8)) + local count = bit32.byteswap(buffer.readu32(b, q + 12)) + local d = store + off + if off > hsize then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0 + if width > 0 then + if d + count * width > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local v = table.create(count) + for k = 0, count - 1 do + local x = d + k * width + v[k + 1] = if width == 1 then buffer.readu8(b, x) + elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1)) + elseif width == 4 then bit32.byteswap(buffer.readu32(b, x)) + else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4)) + end + tags[tag] = v + elseif typ == 7 then + if d + count > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + tags[tag] = buffer.readstring(b, d, count) + elseif typ == 6 or typ == 8 or typ == 9 then + local v = {} + local s = d + local want = if typ == 6 then 1 else count + if want > hsize then + return nil, Err.new(Err.CORRUPT, "bad string count", q) + end + for _ = 1, want do + local z = s + while z < se and buffer.readu8(b, z) ~= 0 do + z += 1 + end + if z >= se then + return nil, Err.new(Err.CORRUPT, "unterminated string", s) + end + table.insert(v, buffer.readstring(b, s, z - s)) + s = z + 1 + end + tags[tag] = if typ == 6 then v[1] else v + end + end + return tags, se +end + +-- the file list of the header: { name, size, mode, mtime, link, user, group, flags } +local function files(tags: { [number]: any }): { any } + local names: { string } = {} + local bn, dn, di = tags[1117], tags[1118], tags[1116] + if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then + for i, base in bn do + local d = dn[(di[i] or 0) + 1] + names[i] = (if type(d) == "string" then d else "") .. base + end + elseif type(tags[1027]) == "table" then + names = tags[1027] + end + local sizes = tags[5008] or tags[1028] or {} + local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {} + local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {} + local out = {} + for i, n in names do + table.insert(out, { + name = n, + size = sizes[i] or 0, + mode = modes[i] or 0, + mtime = mtimes[i] or 0, + link = if links[i] and links[i] ~= "" then links[i] else nil, + user = users[i], + group = groups[i], + flags = flags[i] or 0, + }) + end + return out +end + +local function strip(name: string): string + return (string.gsub(name, "^%.?/+", "")) +end + +-- the payload: decompressed, then its cpio entries by stripped name +local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?) + local n = e - p + local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 } + local raw: buffer?, err: any + local m = if n >= 6 then buffer.readstring(b, p, 6) else "" + if string.sub(m, 1, 2) == "\31\139" then + raw, err = Deflate.gunzip(b, p, n) + elseif m == "\253" .. "7zXZ\0" then + raw, err = Lzma.xz(b, p, n, opts) + elseif string.sub(m, 1, 3) == "BZh" then + raw, err = Bzip2.decompress(b, p, n, opts) + elseif string.sub(m, 1, 4) == "\40\181\47\253" then + raw, err = Zstd.decompress(b, p, n, opts) + elseif compressor == "lzma" then + raw, err = Lzma.alone(b, p, n, opts) + elseif string.sub(m, 1, 5) == "07070" then + raw = buffer.create(n) + buffer.copy(raw :: buffer, 0, b, p, n) + else + return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p) + end + if not raw then + return nil, err + end + if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then + return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)") + end + local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries }) + if not list then + return nil, cerr + end + local by = {} + for _, ent in list do + by[strip(ent.name)] = ent + end + return { buf = raw, by = by }, nil +end + +function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, e = r.buf, r.base, r.limit + if e - base < 96 then + return nil, Err.new(Err.TRUNCATED, "lead past the end", base) + end + if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad lead magic", base) + end + local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5) + local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7)) + local leadName = buffer.readstring(b, base + 10, 66) + leadName = string.match(leadName, "^[^%z]*") :: string + if major < 3 then + return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4) + end + local sig, sigEnd = header(b, base + 96, e) + if not sig then + return nil, sigEnd + end + local hp = base + (sigEnd - base + 7) // 8 * 8 + local tags, hEnd = header(b, hp, e) + if not tags then + return nil, hEnd + end + local a = Archive.new("rpm") + local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } } + for tag, key in NAMES do + local v = tags[tag] + if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value + v = v[1] + end + info[key] = v + end + a.meta.rpm = info + a.meta.source = { format = "rpm", compressor = info.payloadCompressor } + if info.payloadFormat and info.payloadFormat ~= "cpio" then + return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd) + end + local cache: any = nil + local cacheErr: Err.Err? = nil + local function entry(name: string): (any, Err.Err?) + if not cache and not cacheErr then + cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o) + end + if not cache then + return nil, cacheErr + end + local ent = cache.by[name] + if not ent then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload") + end + return ent, nil + end + local list = files(tags) + if #list > (o.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many files") + end + for _, f in list do + if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then + continue + end + local name = strip(f.name) + local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0" + local data = typ == "0" and f.size > 0 + Archive.put(a, { + name = name, + size = if data then f.size else 0, + dir = typ == "5", + mtime = f.mtime, + mode = bit32.band(f.mode, 0xFFF), + type = typ, + link = if typ == "2" then f.link else nil, + uname = f.user, + gname = f.group, + method = if info.payloadCompressor then info.payloadCompressor else "store", + load = if data + then function(): (buffer?, Err.Err?) + local ent, err = entry(name) + if not ent then + return nil, err + end + local out = buffer.create(ent.size) + buffer.copy(out, 0, cache.buf, ent.offset, ent.size) + return out, nil + end + else nil, + }) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err +function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) + local a, err = Rpm.decode(r, opts) + if not a then + return nil, err + end + local p = r.base + 96 + local _, sigEnd = header(r.buf, p, r.limit) + local hp = r.base + (sigEnd - r.base + 7) // 8 * 8 + local _, hEnd = header(r.buf, hp, r.limit) + local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {}) + if not pl then + return nil, perr + end + return pl.buf, nil +end + +return Rpm +end +__FILES["archive/tar"] = function() + +-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value +-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + +-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which +-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). +-- Not supported: sparse files, multi-volume archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local TarFormat = { + name = "tar", + category = "archive", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, +} + +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed + +-- ------------------------------------------------------------------------------------------------ sniff +function TarFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + if not Tar.valid(r.buf, r.pos) then + return 0 + end + return if r:peek(5, 257) == "ustar" then 0.95 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return TarFormat.encode(archive, opts) +end + +function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, err + end + local a = Archive.new("tar", encode) + for _, e in list do + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + mode = e.mode, + uid = e.uid, + gid = e.gid, + uname = e.uname, + gname = e.gname, + type = e.type, + link = e.link, + method = "store", + load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size), + }) + end + a.meta.source = { format = "tar" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local list: { Tar.WriteEntry } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and e.type ~= "1" and e.type ~= "2" then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(list, { + name = e.name, + data = data, + dir = e.dir, + type = if type(e.type) == "string" and #e.type == 1 then e.type else nil, + link = if type(e.link) == "string" then e.link else nil, + mode = if type(e.mode) == "number" then e.mode else nil, + uid = if type(e.uid) == "number" then e.uid else nil, + gid = if type(e.gid) == "number" then e.gid else nil, + uname = if type(e.uname) == "string" then e.uname else nil, + gname = if type(e.gname) == "string" then e.gname else nil, + mtime = if type(e.mtime) == "number" then e.mtime else nil, + }) + end + return Tar.write(list, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() +function TarFormat.new(): any + local a = Archive.new("tar", encode) + a.meta.source = { format = "tar" } + return a +end + +return TarFormat +end +__FILES["archive/uu"] = function() + +-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin " block of a +-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode); +-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each +-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and +-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils +-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings +-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Uu = { + name = "uu", + category = "archive", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, +} + +type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +type EncodeOptions = { + variant: ("uu" | "xx" | "base64")?, -- default "uu" + mode: number?, -- file mode when the entry has none (default 0o644) + name: string?, -- the name of a buffer / string value (default "data") +} + +-- ------------------------------------------------------------------------------------------------ constants +local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +local XX_VALUE: { [number]: number } = {} +for i = 1, 64 do + XX_VALUE[string.byte(XX, i)] = i - 1 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Uu.sniff(r: Bytes.Reader): number + local head = r:peek(4096) + if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then + return 0.9 + end + if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the value of character c in a variant, or nil +local function value(c: number, xx: boolean): number? + if xx then + return XX_VALUE[c] + end + if c >= 32 and c <= 96 then + return bit32.band(c - 32, 63) + end + return nil +end + +-- does a data line fit the variant: every character valid and the length matching the count character +local function fits(line: string, xx: boolean): boolean + local n = value(string.byte(line, 1) or 0, xx) + if not n then + return false + end + local need = math.ceil(n / 3) * 4 + if #line - 1 < need or #line - 1 > need + 2 then + return false + end + for i = 2, need + 1 do + if not value(string.byte(line, i), xx) then + return false + end + end + return true +end + +-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line) +local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?) + local total = 0 + for _, l in lines do + total += value(string.byte(l, 1) or 0, xx) or 0 + end + if total > maxBytes then + return nil, "limit: data larger than maxBytes" + end + local out = buffer.create(total) + local o = 0 + for li, l in lines do + local n = value(string.byte(l, 1) or 0, xx) or 0 + local p = 2 + local left = n + while left > 0 do + local a = value(string.byte(l, p) or 0, xx) + local b = value(string.byte(l, p + 1) or 0, xx) + local c = value(string.byte(l, p + 2) or 0, xx) or 0 + local d = value(string.byte(l, p + 3) or 0, xx) or 0 + if not a or not b then + return nil, "bad character in line " .. li + end + local v = a * 262144 + b * 4096 + c * 64 + d + for k = 2, 0, -1 do + if left > 0 then + buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255)) + o += 1 + left -= 1 + end + end + p += 4 + end + end + return out, nil +end + +type Block = { name: string, mode: number, variant: string, data: buffer } + +local function parse(text: string, maxBytes: number): ({ Block }?, string?) + local lines = string.split(text, "\n") + local blocks: { Block } = {} + local i = 1 + while i <= #lines do + local line = string.gsub(lines[i], "\r$", "") + local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$") + if not b64 then + mode, name = string.match(line, "^begin ([0-7]+) (.+)$") + end + if mode and name then + local body: { string } = {} + local closed = false + i += 1 + while i <= #lines do + local l = string.gsub(lines[i], "\r$", "") + if (b64 and l == "====") or (not b64 and l == "end") then + closed = true + break + end + table.insert(body, l) + i += 1 + end + if not closed then + return nil, "truncated: block " .. name .. " has no end line" + end + local data, variant + if b64 then + local d, err = Base64.decode(table.concat(body)) + if not d then + return nil, "block " .. name .. ": " .. tostring(err) + end + data, variant = d, "base64" + else + -- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines + local data_lines: { string } = {} + for _, l in body do + if l ~= "" then + table.insert(data_lines, l) + end + end + local uuOk, xxOk = true, true + for _, l in data_lines do + uuOk = uuOk and fits(l, false) + xxOk = xxOk and fits(l, true) + end + local xx = xxOk and not uuOk + if not uuOk and not xxOk then + return nil, "block " .. name .. ": lines are neither uuencode nor xxencode" + end + local d, err = decodeLines(data_lines, xx, maxBytes) + if not d then + return nil, err + end + data, variant = d, if xx then "xx" else "uu" + end + table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data }) + end + i += 1 + end + if #blocks == 0 then + return nil, "no begin line" + end + return blocks, nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Uu.encode(a, o) +end + +function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30) + if not blocks then + return nil, Err.from(err) + end + local a = Archive.new("uu", encoder) + for _, b in blocks do + Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data }) + end + a.meta.stream = #a:list() == 1 + a.meta.source = { format = "uu", variant = blocks[1].variant } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function encodeLines(data: buffer, xx: boolean, out: { string }) + local n = buffer.len(data) + local function ch(v: number): string + if xx then + return string.sub(XX, v + 1, v + 1) + end + return if v == 0 then "`" else string.char(v + 32) + end + local p = 0 + while p < n do + local len = math.min(45, n - p) + local parts = { ch(len) } + for q = p, p + len - 1, 3 do + local b0 = buffer.readu8(data, q) + local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0 + local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0 + local v = b0 * 65536 + b1 * 256 + b2 + table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63))) + end + table.insert(out, table.concat(parts)) + p += len + end + table.insert(out, ch(0)) +end + +function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local variant = o.variant or "uu" + if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then + return nil, Err.new(Err.ARG, "variant must be uu, xx or base64") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local out: { string } = {} + for _, f in files do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4) + local m = string.format("%o", bit32.band(mode, 0xFFF)) + if variant == "base64" then + table.insert(out, "begin-base64 " .. m .. " " .. f.name) + local s = Base64.encode(f.data) + for p = 1, #s, 60 do + table.insert(out, string.sub(s, p, p + 59)) + end + table.insert(out, "====") + else + table.insert(out, "begin " .. m .. " " .. f.name) + encodeLines(f.data, variant == "xx", out) + table.insert(out, "end") + end + end + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant }) +function Uu.new(): any + local a = Archive.new("uu", encoder) + a.meta.source = { format = "uu" } + return a +end + +return Uu +end +__FILES["archive/vpk"] = function() + +-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the +-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes +-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the +-- numbered part files "_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes +-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's +-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), +-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the +-- Valve Developer Community VPK file format page; no code taken. +-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Crc32 = __include("core/Crc32") +local Md5 = __include("core/Md5") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Vpk = { + name = "vpk", + category = "archive", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + verify: boolean?, -- check each entry's CRC-32 on read (default true) + resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...) + files: { [string]: buffer | string }?, + name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names + maxEntries: number?, -- default 1e6 +} +type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = 0x55AA1234 +local EMBEDDED = 0x7FFF + +-- ------------------------------------------------------------------------------------------------ sniff +function Vpk.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then + return 0 + end + local v = r:peekU8(4) + return if v == 1 or v == 2 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Vpk.encode(archive, opts) +end + +-- the part file `index` as a buffer (cached per archive) +local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) + local cache: { [number]: buffer } = {} + local prefix = "pak01" + if opts and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") or opts.name + prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base + end + return function(index: number): (buffer?, Err.Err?) + local hit = cache[index] + if hit then + return hit, nil + end + local name = string.format("%s_%03d.vpk", prefix, index) + local b = Input.sibling(opts, name) + if not b then + return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") + end + cache[index] = b + return b, nil + end +end + +local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local src: buffer, at: number + if e.archiveIndex == EMBEDDED then + src, at = r.buf, r.base + dataBase + e.archiveOffset + if dataBase + e.archiveOffset + e.length > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") + end + else + local b, err = part(e.archiveIndex) + if not b then + return nil, err + end + src, at = b, e.archiveOffset + if at + e.length > buffer.len(b) then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) + end + end + local out = buffer.create(e.preloadLength + e.length) + buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) + buffer.copy(out, e.preloadLength, src, at, e.length) + if verify and Crc32.of(out) ~= e.crc32 then + return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") + end + return out, nil + end +end + +function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if sig ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", 0) + end + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) + end + local v2: any = nil + if version == 2 then + v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } + if r.err then + return nil, r.err + end + end + local headerLen = r:tell() - r.base + if headerLen + treeSize > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) + end + local t = r:sub(headerLen, treeSize) + local a = Archive.new("vpk", encode) + local part = partLoader(opts) + local verify = not (opts and opts.verify == false) + local maxEntries = opts and opts.maxEntries or 1e6 + local count = 0 + local parts: { [number]: boolean } = {} + local dataBase = headerLen + treeSize + while true do + local ext = t:cstring() + if t.err then + return nil, t.err + end + if ext == "" then + break + end + while true do + local path = t:cstring() + if t.err then + return nil, t.err + end + if path == "" then + break + end + while true do + local name = t:cstring() + if t.err then + return nil, t.err + end + if name == "" then + break + end + local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } + local term = t:u16le() + e.preloadAt = t.pos + t:skip(e.preloadLength) + if t.err then + return nil, t.err + end + if term ~= 0xFFFF then + return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext) + e.name = full + if e.archiveIndex ~= EMBEDDED then + parts[e.archiveIndex] = true + end + Archive.put(a, { + name = full, + size = e.preloadLength + e.length, + dir = false, + method = "store", + crc32 = e.crc32, + archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex, + preload = e.preloadLength, + load = loader(r, e, dataBase, part, verify), + }) + end + end + end + local partList: { number } = {} + for k in parts do + table.insert(partList, k) + end + table.sort(partList) + a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } + if v2 then + local md5At = dataBase + v2.fileDataSize + if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then + local m = r:sub(md5At + v2.archiveMd5Size, 48) + v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) + end + a.meta.source.v2 = v2 + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + -- group by extension, then path, keeping first-seen order + local exts: { string } = {} + local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {} + for _, it in items do + if not it.entry.dir then + local full = string.gsub(it.entry.name, "\\", "/") + local dir, file = string.match(full, "^(.*)/([^/]*)$") + if not dir then + dir, file = " ", full + end + local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$") + if not stem or stem == "" then + stem, ext = file, " " + end + if stem == "" or dir == "" or string.find(full, "\0", 1, true) then + return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) + end + local g = byExt[ext :: string] + if not g then + g = { paths = {}, byPath = {} } + byExt[ext :: string] = g + table.insert(exts, ext :: string) + end + local l = g.byPath[dir :: string] + if not l then + l = {} + g.byPath[dir :: string] = l + table.insert(g.paths, dir :: string) + end + table.insert(l, { name = stem :: string, data = it.data }) + end + end + local tree = Bytes.writer() + local data = Bytes.writer() + for _, ext in exts do + tree:cstring(ext) + local g = byExt[ext] + for _, path in g.paths do + tree:cstring(path) + for _, f in g.byPath[path] do + tree:cstring(f.name) + tree:u32le(Crc32.of(f.data)) + tree:u16le(0) + tree:u16le(EMBEDDED) + tree:u32le(data:tell()) + tree:u32le(buffer.len(f.data)) + tree:u16le(0xFFFF) + data:bytes(f.data) + end + tree:u8(0) + end + tree:u8(0) + end + tree:u8(0) + local tb, db = tree:finish(), data:finish() + local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) + w:u32le(SIGNATURE) + w:u32le(version) + w:u32le(buffer.len(tb)) + if version == 2 then + w:u32le(buffer.len(db)) + w:u32le(0) + w:u32le(48) + w:u32le(0) + end + w:bytes(tb) + w:bytes(db) + if version == 2 then + local treeMd5 = Md5.new() + treeMd5:update(tb) + local tmd = treeMd5:digest() + local chunkMd5 = Md5.new():digest() + local file = Md5.new() + local sofar = w:finish() + file:update(sofar) + file:update(buffer.fromstring(tmd .. chunkMd5)) + local out = Bytes.writer(buffer.len(sofar) + 48) + out:bytes(sofar) + out:string(tmd) + out:string(chunkMd5) + out:string(file:digest()) + return out:finish(), nil + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() +function Vpk.new(version: number?): any + local a = Archive.new("vpk", encode) + a.meta.source = { format = "vpk", version = version or 2 } + return a +end + +return Vpk +end +__FILES["archive/wad"] = function() + +-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the +-- standard Archive and written from any Archive value, plus the lumps as game data: +-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map +-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer +-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image +-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) +-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) +-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) +-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene +-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) +-- Entry names: the lump names, except lumps of a map, named "/" ("MAP01/THINGS"), and later lumps +-- repeating an earlier name, named "~" (n = 2, 3, ...), so every entry is unique; writing strips both again +-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom +-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. +-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, +-- big-endian (Jaguar) WADs, compressed Jaguar lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Archive = __include("containers/Archive") +local Pixels = __include("codecs/image/Pixels") +local Picture = __include("archive/wad/Picture") +local Map = __include("archive/wad/Map") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad = { + name = "wad", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD" +type Lump = { + name: string, -- the lump name as stored (upper case) + entry: string, -- the Archive entry name + index: number, -- 1-based position in the directory + offset: number, + size: number, + namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers) + map: string?, -- the map this lump belongs to + marker: boolean?, -- a zero-size marker (F_START, MAP01, ...) +} +type MapOptions = { + textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true) + palette: number?, -- PLAYPAL palette index (default 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAP_LUMPS: { [string]: boolean } = { + THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true, + SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true, + MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true, +} +-- namespace markers: first letter(s) before _START / _END +local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches", + P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps", + TX = "textures", HI = "hires", A = "acs", V = "voices" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + if m ~= "IWAD" and m ~= "PWAD" then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Wad.encode(archive, opts) +end + +local function nameAt(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local kind = r:string(4) + local count, dirOfs = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local size = r.limit - r.base + if count < 0 or dirOfs < 0 then + return nil, Err.new(Err.CORRUPT, "negative directory field", 4) + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many lumps: " .. count) + end + if dirOfs + count * 16 > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 8) + end + local a = Archive.new("wad", encode) + local lumps: { Lump } = {} + local seen: { [string]: number } = {} + local b = r.buf + local ns: string? = nil + local map: string? = nil + local udmf = false + for i = 0, count - 1 do + local o = r.base + dirOfs + i * 16 + local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4) + local name = nameAt(b, o + 8) + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16) + end + -- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map + local nextName = if i + 1 < count then nameAt(b, o + 24) else "" + local inMap: string? = nil + if map then + if udmf then + inMap = map + if name == "ENDMAP" then + map = nil + end + elseif MAP_LUMPS[name] then + inMap = map + else + map = nil + end + end + local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP") + if isMapMarker then + map, udmf = name, nextName == "TEXTMAP" + end + -- namespaces + local marker: boolean = false + local pre = string.match(name, "^(%w+)_START$") + local post = string.match(name, "^(%w+)_END$") + if pre and NAMESPACES[pre] then + ns = NAMESPACES[pre] + marker = true + elseif post and NAMESPACES[post] then + ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil + marker = true + end + local entry = if inMap then inMap .. "/" .. name else name + local k = seen[entry] + if k then + k += 1 + seen[entry] = k + entry = entry .. "~" .. k + else + seen[entry] = 1 + end + local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil } + table.insert(lumps, lump) + Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) }) + end + a.meta.source = { format = "wad", type = kind, lumps = count } + a.meta.wad = { lumps = lumps, buf = b, base = r.base } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD" + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") + end + local list: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name + base = string.upper((string.gsub(base, "~%d+$", ""))) + if #base > 8 or #base == 0 then + return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name) + end + table.insert(list, { name = base, data = it.data }) + end + end + local w = Bytes.writer() + w:string(kind) + w:u32le(#list) + w:u32le(0) + local offs: { number } = {} + for i, l in list do + offs[i] = w:tell() + w:bytes(l.data) + end + local dirOfs = w:tell() + for i, l in list do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:string(l.name) + w:fill(0, 8 - #l.name) + end + w:setU32le(8, dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a: any): any + return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil +end + +-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +local function find(w: any, name: string, ns: string?): Lump? + local up = string.upper(name) + local best: Lump? = nil + for _, l in w.lumps do + if l.name == up and not l.map then + if ns == nil or l.namespace == ns then + best = l + elseif not best then + best = l + end + end + end + if best and ns and best.namespace ~= ns then + for _, l in w.lumps do + if l.name == up and l.namespace == ns then + best = l + end + end + end + return best +end + +-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() +function Wad.new(kind: ("IWAD" | "PWAD")?): any + local a = Archive.new("wad", encode) + a.meta.source = { format = "wad", type = kind or "PWAD" } + return a +end + +-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) +function Wad.lumps(a: any): { Lump }? + local w = info(a) + return w and w.lumps +end + +-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err +function Wad.palette(a: any, index: number?): (buffer?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local l = find(w, "PLAYPAL") + local i = index or 0 + if not l or l.size < (i + 1) * 768 then + return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i) + end + return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil +end + +-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) +-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. +function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local kind = opts and opts.kind + local l = find(w, name, if kind == "flat" then "flats" else nil) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local pal, perr = Wad.palette(a, opts and opts.palette) + if not pal then + return nil, perr + end + local at = w.base + l.offset + local pw, ph, left, top = Picture.header(w.buf, at, l.size) + local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw)) + if asFlat then + local fw, fh = Picture.flatSize(l.size) + if not fw then + return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat") + end + local img = Types.Image.new(fw, fh) + Picture.flat(w.buf, at, fw, fh, pal, img.pixels) + img.meta.source = { format = "wad", kind = "flat", lump = l.name } + return img, nil + end + if not pw then + return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture") + end + local img = Types.Image.new(pw, ph) + local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph) + if not ok then + return nil, Err.from(msg, l.offset) + end + img.meta.offset = { left, top } + img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top } + return img, nil +end + +-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } +local function textureDefs(w: any): { [string]: any } + if w.textures then + return w.textures + end + local defs: { [string]: any } = {} + w.textures = defs + local pn = find(w, "PNAMES") + local names: { string } = {} + if pn and pn.size >= 4 then + local at = w.base + pn.offset + local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8) + for i = 0, n - 1 do + names[i + 1] = nameAt(w.buf, at + 4 + i * 8) + end + end + for _, tl in { "TEXTURE1", "TEXTURE2" } do + local l = find(w, tl) + if l and l.size >= 4 then + local r = Bytes.reader(w.buf, w.base + l.offset, l.size) + local n = r:i32le() + if n > 0 and n * 4 <= l.size - 4 then + for i = 0, n - 1 do + r:seek(4 + i * 4) + local o = r:i32le() + if o > 0 and o + 22 <= l.size then + r:seek(o) + local tname = string.upper(r:fixed(8)) + r:skip(4) + local tw, th = r:i16le(), r:i16le() + r:skip(4) + local pc = r:i16le() + local patches = {} + for _ = 1, math.max(0, pc) do + local px, py, pi = r:i16le(), r:i16le(), r:i16le() + r:skip(4) + if names[pi + 1] then + table.insert(patches, { x = px, y = py, patch = names[pi + 1] }) + end + end + if not r.err and tw > 0 and th > 0 and defs[tname] == nil then + defs[tname] = { width = tw, height = th, patches = patches } + end + r.err = nil + end + end + end + end + end + return defs +end + +-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) +function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local def = textureDefs(w)[string.upper(name)] + if not def then + return nil, Err.new(Err.ARG, "no texture named " .. tostring(name)) + end + if def.width * def.height > 4096 * 4096 then + return nil, Err.new(Err.LIMIT, "texture too big") + end + local img = Types.Image.new(def.width, def.height) + for _, p in def.patches do + local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" }) + if pimg then + Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y) + end + end + img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches } + return img, nil +end + +-- maps(a) -> { map names } in file order +function Wad.maps(a: any): { string } + local w = info(a) + local out: { string } = {} + if w then + local seen: { [string]: boolean } = {} + for _, l in w.lumps do + if l.map and not seen[l.map] then + seen[l.map] = true + table.insert(out, l.map) + end + end + end + return out +end + +-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) +function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local up = string.upper(name) + local lumps: { [string]: Map.Lump } = {} + for _, l in w.lumps do + if l.map == up and lumps[l.name] == nil then + lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size } + end + end + if not next(lumps) then + return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) + end + if lumps.TEXTMAP then + return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps") + end + local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil) + if not m then + return nil, Err.from(msg) + end + return m, nil +end + +-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and +-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes +-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData +function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?) + local m, err = Wad.mapData(a, name) + if not m then + return nil, err + end + local w = info(a) + local defs = textureDefs(w) + local images = not (opts and opts.textures == false) + local cache: { [string]: any } = {} + local pal = opts and opts.palette + local function image(kind: string, tname: string): Types.Image? + local key = kind .. ":" .. tname + local c = cache[key] + if c == nil then + local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal }) + c = img or false + cache[key] = c + end + return if c then c else nil + end + local tex: Map.Textures = { + size = function(kind: string, tname: string): (number?, number?) + if kind == "texture" then + local d = defs[tname] + if d then + return d.width, d.height + end + return nil, nil + end + local l = find(w, tname, "flats") + if l then + local fw, fh = Picture.flatSize(l.size) + return fw, fh + end + return nil, nil + end, + image = if images then image else nil, + } + local scene = Map.scene(m, tex, string.upper(name)) + scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 } + return scene, nil +end + +return Wad +end +__FILES["archive/wad/Map"] = function() + +-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, +-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a +-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with +-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the +-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one +-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z +-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not +-- supported. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") + +local Map = {} + +local Scene = Types.Scene +local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Lump = { buf: buffer, at: number, size: number } +type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? } +type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? } +type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number } +type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number } +type MapData = { + format: "doom" | "hexen", + things: { Thing }, + linedefs: { Linedef }, + sidedefs: { Sidedef }, + vertices: { number }, -- x1, y1, x2, y2, ... + sectors: { Sector }, +} +-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows +type Textures = { + size: (kind: string, name: string) -> (number?, number?), + image: ((kind: string, name: string) -> Types.Image?)?, +} + +-- ------------------------------------------------------------------------------------------------ parse +local function name8(b: buffer, at: number): string + local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper(if z then string.sub(s, 1, z - 1) else s) +end + +local function side(v: number): number? + return if v == 0xFFFF then nil else v + 1 +end + +-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) +function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?) + for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do + if not lumps[k] then + return nil, "map has no " .. k + end + end + local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } + local v = lumps.VERTEXES + for i = 0, v.size // 4 - 1 do + table.insert(m.vertices, readi16(v.buf, v.at + i * 4)) + table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2)) + end + local s = lumps.SECTORS + for i = 0, s.size // 26 - 1 do + local o = s.at + i * 26 + table.insert(m.sectors, { + floor = readi16(s.buf, o), + ceiling = readi16(s.buf, o + 2), + floorFlat = name8(s.buf, o + 4), + ceilingFlat = name8(s.buf, o + 12), + light = readi16(s.buf, o + 20), + special = readu16(s.buf, o + 22), + tag = readu16(s.buf, o + 24), + }) + end + local sd = lumps.SIDEDEFS + for i = 0, sd.size // 30 - 1 do + local o = sd.at + i * 30 + table.insert(m.sidedefs, { + xoff = readi16(sd.buf, o), + yoff = readi16(sd.buf, o + 2), + upper = name8(sd.buf, o + 4), + lower = name8(sd.buf, o + 12), + middle = name8(sd.buf, o + 20), + sector = readu16(sd.buf, o + 28) + 1, + }) + end + local l = lumps.LINEDEFS + local ls = if hexen then 16 else 14 + for i = 0, l.size // ls - 1 do + local o = l.at + i * ls + local b = l.buf + if hexen then + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu8(b, o + 6), + args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) }, + front = side(readu16(b, o + 12)), + back = side(readu16(b, o + 14)), + }) + else + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu16(b, o + 6), + tag = readu16(b, o + 8), + front = side(readu16(b, o + 10)), + back = side(readu16(b, o + 12)), + }) + end + end + local t = lumps.THINGS + if t then + local ts = if hexen then 20 else 10 + for i = 0, t.size // ts - 1 do + local o = t.at + i * ts + local b = t.buf + if hexen then + table.insert(m.things, { + tid = readi16(b, o), + x = readi16(b, o + 2), + y = readi16(b, o + 4), + z = readi16(b, o + 6), + angle = readi16(b, o + 8), + type = readu16(b, o + 10), + flags = readu16(b, o + 12), + special = readu8(b, o + 14), + args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) }, + }) + else + table.insert(m.things, { + x = readi16(b, o), + y = readi16(b, o + 2), + angle = readi16(b, o + 4), + type = readu16(b, o + 6), + flags = readu16(b, o + 8), + }) + end + end + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ sector outlines +-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; +-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; +-- chains that do not close are dropped +local function loops(m: MapData): { [number]: { { number } } } + local edges: { [number]: { { number } } } = {} + local nv = #m.vertices // 2 + local function add(sec: number, a: number, b: number) + local e = edges[sec] or {} + edges[sec] = e + table.insert(e, { a, b }) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local fs = ld.front and m.sidedefs[ld.front] + local bs = ld.back and m.sidedefs[ld.back] + local f = fs and fs.sector + local b = bs and bs.sector + if f ~= b then + if f and m.sectors[f] then + add(f, ld.v1, ld.v2) + end + if b and m.sectors[b] then + add(b, ld.v2, ld.v1) + end + end + end + end + local V = m.vertices + local out: { [number]: { { number } } } = {} + for sec, list in edges do + local from: { [number]: { number } } = {} + for i, e in list do + local l = from[e[1]] or {} + from[e[1]] = l + table.insert(l, i) + end + local used: { [number]: boolean } = {} + local res: { { number } } = {} + for start = 1, #list do + if not used[start] then + used[start] = true + local loop = { list[start][1] } + local cur = start + local closed = false + for _ = 1, #list do + local e = list[cur] + local at = e[2] + if at == loop[1] then + closed = true + break + end + table.insert(loop, at) + local cands = from[at] + local best, bestT = nil :: number?, math.huge + if cands then + local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2] + for _, c in cands do + if not used[c] then + local n2 = list[c][2] + local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2] + local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy) + if t < bestT then + best, bestT = c, t + end + end + end + end + if not best then + break + end + used[best] = true + cur = best + end + if closed and #loop >= 3 then + table.insert(res, loop) + end + end + end + out[sec] = res + end + return out +end + +local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean + local c = false + local n = #loop + local j = n + for i = 1, n do + local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2] + local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2] + if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then + c = not c + end + j = i + end + return c +end + +-- ------------------------------------------------------------------------------------------------ scene +type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } } + +local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 + +-- scene(m, tex, name) -> Scene +function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene + local batches: { [string]: Batch } = {} + local order: { string } = {} + local function batch(kind: string, tname: string): Batch + local key = kind .. ":" .. tname + local b = batches[key] + if not b then + b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} } + batches[key] = b + table.insert(order, key) + end + return b + end + local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number) + local p, n, t = b.pos, b.nrm, b.uv + p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z + n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz + t[#t + 1], t[#t + 2] = u, v + end + local V = m.vertices + local nv = #V // 2 + -- floors and ceilings + local secLoops = loops(m) + for sec, ls in secLoops do + local s = m.sectors[sec] + local flat: { { number } } = {} + for li, loop in ls do + local f: { number } = {} + for _, vi in loop do + table.insert(f, V[vi * 2 - 1]) + table.insert(f, V[vi * 2]) + end + flat[li] = f + end + local tris = Polygon.triangulate(flat) + for pass = 1, 2 do + local tname = if pass == 1 then s.floorFlat else s.ceilingFlat + local fw, fh = tex.size("flat", tname) + local w, h = fw or 64, fh or 64 + local z = if pass == 1 then s.floor else s.ceiling + local b = batch("flat", tname) + local nz = if pass == 1 then 1 else -1 + for k = 1, #tris, 6 do + for c = 0, 2 do + local cc = if pass == 1 then c else 2 - c + local loop = ls[tris[k + cc * 2]] + local vi = loop[tris[k + cc * 2 + 1]] + local x, y = V[vi * 2 - 1], V[vi * 2] + vert(b, x, y, z, 0, 0, nz, x / w, -y / h) + end + end + end + end + -- walls + local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number) + if tname == "-" or tname == "" or zt <= zb then + return + end + local tw, th = tex.size("texture", tname) + local w, h = tw or 64, th or 128 + local b = batch("texture", tname) + local dx, dy = x2 - x1, y2 - y1 + local l = math.sqrt(dx * dx + dy * dy) + local nx, ny = dy / l, -dx / l + local u0, u1 = xoff / w, (xoff + len) / w + local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zb, nx, ny, 0, u1, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zt, nx, ny, 0, u0, vt) + end + for _, ld in m.linedefs do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2] + local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2) + for sideN = 1, 2 do + local sdi = if sideN == 1 then ld.front else ld.back + local odi = if sideN == 1 then ld.back else ld.front + local sd = sdi and m.sidedefs[sdi] + local me = sd and m.sectors[sd.sector] + if sd and me then + local x1, y1, x2, y2 = ax, ay, bx, by + if sideN == 2 then + x1, y1, x2, y2 = bx, by, ax, ay + end + local od = odi and m.sidedefs[odi] + local other = od and m.sectors[od.sector] + if not other then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling + quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff) + else + if other.floor > me.floor then + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor + quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff) + end + local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY" + if other.ceiling < me.ceiling and not sky then + local th = select(2, tex.size("texture", sd.upper)) or 128 + local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th + quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff) + end + if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling) + local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi + quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff) + end + end + end + end + end + end + -- the scene + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = name, primitives = {} } + local texIndex: { [string]: number } = {} + for _, key in order do + local b = batches[key] + local n = #b.pos // 3 + if n > 0 then + local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + for i = 1, n * 3 do + writef32(pb, (i - 1) * 4, b.pos[i]) + writef32(nb, (i - 1) * 4, b.nrm[i]) + end + for i = 1, n * 2 do + writef32(ub, (i - 1) * 4, b.uv[i]) + end + for i = 0, n - 1 do + writeu32(ib, i * 4, i) + end + local ti = texIndex[key] + if not ti then + table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } }) + ti = #scene.textures + texIndex[key] = ti + end + local mat = Scene.material(b.name) + mat.metallic = 0 + mat.baseColorTexture = { texture = ti } + mat.extras = { wad = { kind = b.kind } } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, n), + NORMAL = Scene.accessor(nb, "f32", 3, n), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n), + }, + indices = Scene.accessor(ib, "u32", 1, n), + mode = "triangles" :: any, + material = #scene.materials, + extras = { wad = { kind = b.kind, texture = b.name } }, + }) + end + end + table.insert(scene.meshes, mesh) + scene.nodes[1] = { name = name, children = {}, mesh = 1 } + scene.roots[1] = 1 + -- things, on the floor of the sector under them + for i, th in m.things do + local z = th.z or 0 + for sec, ls in secLoops do + local inside = false + for _, loop in ls do + if insideLoop(V, loop, th.x, th.y) then + inside = not inside + end + end + if inside then + z += m.sectors[sec].floor + break + end + end + local a = math.rad(th.angle) / 2 + table.insert(scene.nodes, { + name = "thing " .. i, + children = {}, + translation = { th.x, th.y, z }, + rotation = { 0, 0, math.sin(a), math.cos(a) }, + extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } }, + }) + table.insert(scene.nodes[1].children, #scene.nodes) + end + return scene +end + +return Map +end +__FILES["archive/wad/Picture"] = @native function() + + +-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column +-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of +-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) +-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). +-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's +-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 + +local Picture = {} + +-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) +@native function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number) + if n < 8 then + return nil, 0, 0, 0 + end + local w, h = readu16(b, at), readu16(b, at + 2) + if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then + return nil, 0, 0, 0 + end + for x = 0, w - 1 do + local o = readu32(b, at + 8 + x * 4) + if o < 8 + w * 4 or o >= n then + return nil, 0, 0, 0 + end + end + return w, h, readi16(b, at + 4), readi16(b, at + 6) +end + +-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) +@native function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?) + local stop = at + n + for x = 0, w - 1 do + local p = at + readu32(b, at + 8 + x * 4) + local top = -1 + while true do + if p >= stop then + return false, "column " .. x .. " runs past the end" + end + local delta = readu8(b, p) + if delta == 255 then + break + end + if p + 3 > stop then + return false, "post header past the end" + end + local len = readu8(b, p + 1) + top = if delta <= top then top + delta else delta + if p + 4 + len > stop then + return false, "post past the end" + end + local src = p + 3 + for k = 0, len - 1 do + local y = top + k + if y < h then + writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4)) + end + end + p += 4 + len + end + end + return true, nil +end + +-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) +@native function Picture.flatSize(n: number): (number?, number) + if n == 4096 then + return 64, 64 + elseif n == 4160 then + return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding + elseif n == 8192 then + return 64, 128 + elseif n == 12800 then + return 64, 200 -- Heretic / Hexen scrolling flats + end + local s = math.floor(math.sqrt(n) + 0.5) + if s * s == n and s > 0 then + return s, s + end + if n > 0 and n % 64 == 0 then + return 64, n // 64 + end + return nil, 0 +end + +-- flat(b, at, w, h, pal, out): raw indexes, row by row +@native function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer) + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) + end +end + +-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), +-- clipped (composite wall textures from patches) +@native function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number) + local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 + for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do + local so, d = y * sw, (y + oy) * dw + ox + for x = x0, x1 do + local v = readu32(src, (so + x) * 4) + if v ~= 0 then + writeu32(dst, (d + x) * 4, v) + end + end + end +end + +return Picture +end +__FILES["archive/xz"] = function() + +-- 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/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: +-- the api unwraps an inner archive (a .tar.xz loads as the tar). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Xz = { + name = "xz", + category = "archive", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} + +-- ------------------------------------------------------------------------------------------------ constants +local XZ_MAGIC = "\253" .. "7zXZ\0" + +-- ------------------------------------------------------------------------------------------------ sniff +-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1), +-- a size of -1 or under 2^40, and a 0 range coder byte +local function aloneScore(r: Bytes.Reader): number + local h = r:peek(14) + if #h < 14 then + return 0 + end + local d = string.byte(h, 1) + if d >= 225 or string.byte(h, 14) ~= 0 then + return 0 + end + local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216 + local okDict = false + for n = 12, 31 do + if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then + okDict = true + break + end + end + if not okDict then + return 0 + end + local s = string.sub(h, 6, 13) + if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then + return 0 + end + return if d == 0x5D then 0.4 else 0.2 +end + +function Xz.sniff(r: Bytes.Reader): number + if r:peek(6) == XZ_MAGIC then + return 1 + end + return aloneScore(r) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, res + local method + if r:peek(6) == XZ_MAGIC then + out, res = Lzma.xz(r.buf, r.base, n, o) + method = "lzma2" + else + out, res = Lzma.alone(r.buf, r.base, n, o) + method = "lzma" + end + if not out then + return nil, res + end + local a = Archive.new("xz") + a.meta.stream = true + a.meta.container = if method == "lzma" then "lzma" else "xz" + Archive.put(a, { + name = Archive.streamName(o, Xz.extensions), + size = buffer.len(out), + compressedSize = n, + method = method, + dir = false, + data = out, + }) + return a, nil +end + +return Xz +end +__FILES["archive/yenc"] = function() + +-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive: +-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart +-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified +-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a +-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one +-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space +-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Yenc = { + name = "yenc", + category = "archive", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, +} + +type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30 +type EncodeOptions = { + line: number?, -- characters per line (default 128) + name: string?, -- the name of a buffer / string value (default "data") +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Yenc.sniff(r: Bytes.Reader): number + local head = r:peek(4096) + if string.match(head, "^=ybegin ") then + return 0.95 + end + return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- key=value fields of a keyword line; name= runs to the end of the line +local function fields(line: string): { [string]: string } + local f: { [string]: string } = {} + local s, name = string.match(line, "^(.-)name=(.*)$") + if s then + f.name = string.gsub(name :: string, "%s+$", "") + line = s + end + for k, v in string.gmatch(line, "(%w+)=(%S+)") do + f[k] = v + end + return f +end + +-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out) +local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number + local lim = buffer.len(out) + local esc = false + for p = i, j - 1 do + local c = buffer.readu8(src, p) + if c == 13 or c == 10 then + continue + end + if c == 61 and not esc then + esc = true + continue + end + if esc then + c -= 64 + esc = false + end + if o < lim then + buffer.writeu8(out, o, (c - 42) % 256) + end + o += 1 + end + return o +end + +-- count the decoded bytes of the data lines [i, j) +local function countData(src: buffer, i: number, j: number): number + local n, esc = 0, false + for p = i, j - 1 do + local c = buffer.readu8(src, p) + if c ~= 13 and c ~= 10 then + if c == 61 and not esc then + esc = true + else + esc = false + n += 1 + end + end + end + return n +end + +type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? } +type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? } + +local function hex(s: string?): number? + return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil +end + +local function parse(b: buffer, base: number, limit: number): ({ File }?, string?) + local files: { File } = {} + local byName: { [string]: File } = {} + local p = base + local cur: File? = nil + local part: Part? = nil + while p < limit do + local nl = p + while nl < limit and buffer.readu8(b, nl) ~= 10 do + nl += 1 + end + local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y" + if isKey then + local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "") + local kw = string.match(line, "^=y(%a+)") + local f = fields(line) + if kw == "begin" then + local name = f.name + local size = tonumber(f.size or "") + if not name or name == "" or not size or size < 0 then + return nil, "=ybegin without name or size" + end + local file: File? = byName[name] + if not file then + local nf: File = { name = name :: string, size = size, parts = {}, total = tonumber(f.total or "") } + byName[name] = nf + table.insert(files, nf) + file = nf + end + cur = file + part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") } + elseif kw == "part" and part then + local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "") + if not first or not last or first < 1 or last < first - 1 then + return nil, "bad =ypart range" + end + part.first, part.last = first - 1, last + part.from, part.to = nl + 1, nl + 1 + elseif kw == "end" and part and cur then + part.pcrc = hex(f.pcrc32) + if f.crc32 then + cur.crc = hex(f.crc32) + end + local size = tonumber(f.size or "") + if size and size ~= part.last - part.first then + return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")" + end + table.insert(cur.parts, part) + part = nil + end + elseif part then + part.to = nl + 1 + end + p = nl + 1 + end + if part then + return nil, "truncated: no =yend" + end + if #files == 0 then + return nil, "no =ybegin line" + end + return files, nil +end + +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return Yenc.encode(a, o) +end + +function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b = r.buf + local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b))) + if not files then + return nil, Err.from(perr) + end + local a = Archive.new("yenc", encoder) + local incomplete = {} + for _, f in files do + if f.size > maxBytes then + return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes") + end + local out = buffer.create(f.size) + local covered = 0 + for _, pt in f.parts do + local n = countData(b, pt.from, pt.to) + if n ~= pt.last - pt.first or pt.last > f.size then + return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first)) + end + local tmp = buffer.create(n) + decodeData(b, pt.from, pt.to, tmp, 0) + if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch") + end + buffer.copy(out, pt.first, tmp, 0, n) + covered += n + end + local whole = covered == f.size + if whole and f.crc and Crc32.of(out) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch") + end + if not whole then + table.insert(incomplete, f.name) + end + Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole }) + end + a.meta.stream = #files == 1 + a.meta.incomplete = if #incomplete > 0 then incomplete else nil + a.meta.source = { format = "yenc" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local lineLen = o.line or 128 + if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then + return nil, Err.new(Err.ARG, "line must be 2..997") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local w = Bytes.writer() + for _, f in files do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local data = f.data + local n = buffer.len(data) + w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name)) + local col = 0 + for i = 0, n - 1 do + local c = (buffer.readu8(data, i) + 42) % 256 + local critical = c == 0 or c == 10 or c == 13 or c == 61 + if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then + critical = true + elseif not critical and c == 46 and col == 0 then + critical = true + end + if critical then + w:u8(61) + w:u8((c + 64) % 256) + col += 2 + else + w:u8(c) + col += 1 + end + if col >= lineLen and i < n - 1 then + w:string("\r\n") + col = 0 + end + end + if n > 0 then + w:string("\r\n") + end + w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data))) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line }) +function Yenc.new(): any + local a = Archive.new("yenc", encoder) + a.meta.source = { format = "yenc" } + return a +end + +return Yenc +end +__FILES["archive/z"] = function() + +-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one +-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a +-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed, +-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is +-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local UnixCompress = __include("codecs/compress/UnixCompress") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Z = { + name = "z", + category = "archive", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} +type EncodeOptions = { + maxBits: number?, -- 9..16 (compress -b), default 16 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Z.sniff(r: Bytes.Reader): number + if r:peek(2) ~= "\31\157" then + return 0 + end + local f = r:peekU8(2) + return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the entry name: the file name without .Z; .taz / .tz name a tar +local function entryName(opts: DecodeOptions): string + local name = Archive.streamName(opts, { "z" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then + return stem .. ".tar" + end + return name +end + +local function encode(value: any, opts: any?): (buffer?, Err.Err?) + return Z.encode(value, opts) +end + +function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, err = UnixCompress.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 } + Archive.put(a, { + name = entryName(o), + size = buffer.len(out), + compressedSize = n, + method = "lzw", + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits }) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(data?, name?) -> a .Z Archive holding one entry +function Z.new(data: (buffer | string)?, name: string?): any + local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z" } + if data then + a:add(name or "data", data) + end + return a +end + +return Z +end +__FILES["archive/zip"] = function() + +-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. +-- 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/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. +-- +-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) +-- for _, e in a:list() do print(e.name, e.size, e.method) end +-- local data = a:read("dir/file.txt") +-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } +-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) +-- local b = Zip.create() -- an empty archive + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Container = __include("containers/Zip") + +-- ------------------------------------------------------------------------------------------------ contract +local Zip = { + name = "zip", + category = "archive", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + verify: boolean?, -- check every entry's CRC-32 on read (default true) +} +type AddOptions = Container.AddOptions +type WriteOptions = Container.FinishOptions + +-- ------------------------------------------------------------------------------------------------ constants +local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } + +local Archive = {} +Archive.__index = Archive + +local function new(zip: any, verify: boolean): any + local a = setmetatable({ + kind = "archive", + format = "zip", + meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil }, + _zip = zip, + _verify = verify, + _order = {} :: { string }, + _items = {} :: { [string]: any }, + }, Archive) + if zip then + for _, e in zip:list() do + if a._items[e.name] == nil then + table.insert(a._order, e.name) + end + a._items[e.name] = { raw = e } + end + end + return a +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Zip.sniff(r: Bytes.Reader): number + local s = r:peek(4) + -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff + if s == "PK\3\4" or s == "PK\5\6" then + return 0.6 + end + if string.sub(s, 1, 2) == "MZ" then + return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Archive | nil, Err +function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local zip, err = Container.open(r) + if not zip then + return nil, err + end + return new(zip, not (opts and opts.verify == false)), nil +end + +-- create() -> an empty Archive +function Zip.create(): Types.Archive + return new(nil, true) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written +-- here), or a plain table { [name] = buffer | string }. +function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") + end + if getmetatable(value) == Archive then + return value:write(opts) + end + local a = new(nil, true) + if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then + for _, e in value:list() do + if e.dir then + a:add(e.name, nil, { mtime = e.mtime }) + else + local data, err = value:read(e.name) + if not data then + return nil, err + end + a:add(e.name, data, { mtime = e.mtime }) + end + end + else + local names = {} + for k, v in value do + if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then + return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") + end + table.insert(names, k) + end + table.sort(names) + for _, k in names do + a:add(k, value[k]) + end + end + return a:write(opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the Archive methods (Types.Archive) + +-- list() -> { ArchiveEntry } in archive order (+ crc32, comment) +function Archive.list(self: any): { Types.ArchiveEntry } + local out = {} + for _, name in self._order do + local it = self._items[name] + if it.raw then + local e = it.raw + table.insert(out, { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = METHODS[e.method] or ("method " .. e.method), + mtime = e.mtime, + dir = e.isDir, + crc32 = e.crc32, + comment = e.comment, + }) + else + table.insert(out, { + name = name, + size = buffer.len(it.data), + compressedSize = nil, + method = it.opts.method or "deflate", + mtime = it.opts.mtime, + dir = string.sub(name, -1) == "/", + }) + end + end + return out +end + +-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup +function Archive.read(self: any, name: string): (buffer?, Err.Err?) + if type(name) ~= "string" then + return nil, Err.new(Err.ARG, "read: name must be a string") + end + local it = self._items[name] + if it and not it.raw then + local copy = buffer.create(buffer.len(it.data)) + buffer.copy(copy, 0, it.data) + return copy, nil + end + if it then + return self._zip:read(it.raw, self._verify) + end + if self._zip then + local e = self._zip:find(name) + if e and self._items[e.name] and self._items[e.name].raw == e then + return self._zip:read(e, self._verify) + end + end + return nil, Err.new(Err.ARG, "no entry " .. name) +end + +-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") +function Archive.add(self: any, name: string, data: any, opts: AddOptions?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + if self._items[name] == nil then + table.insert(self._order, name) + end + self._items[name] = { data = b, opts = opts or {} } +end + +-- remove(name) -> true when there was such an entry +function Archive.remove(self: any, name: string): boolean + if self._items[name] == nil then + return false + end + self._items[name] = nil + local i = table.find(self._order, name) + if i then + table.remove(self._order, i) + end + return true +end + +-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are +function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?) + local w = Container.writer() + for _, name in self._order do + local it = self._items[name] + local ok, err + if it.raw then + ok, err = w:addRaw(it.raw, self._zip) + else + ok, err = w:add(name, it.data, it.opts) + end + if not ok then + return nil, err + end + end + local o: WriteOptions = opts or {} + if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then + o = table.clone(o) + o.comment = self.meta.comment + end + return w:finish(o) +end + +Zip.Container = Container + +return Zip +end +__FILES["archive/zoo"] = function() + +-- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of +-- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers), +-- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit +-- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read +-- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not +-- supported: writing, file generations beyond keeping the newest (older versions of a name get ";"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzw = __include("codecs/compress/Lzw") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zoo = { + name = "zoo", + category = "archive", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse an entry larger than this (default 2^30) + maxEntries: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local TAG = 0xFDC4A7DC + +-- ------------------------------------------------------------------------------------------------ sniff +function Zoo.sniff(r: Bytes.Reader): number + local h = r:peek(24) + if #h < 24 then + return 0 + end + local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216 + if tag ~= TAG then + return 0 + end + return if string.sub(h, 1, 4) == "ZOO " then 1 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zoo.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local h = r:sub(0, 34) + local text = h:string(20) + local tag, start = h:u32le(), h:u32le() + h:skip(4) + local major, minor = h:u8(), h:u8() + if h.err then + return nil, h.err + end + if tag ~= TAG then + return nil, Err.new(Err.CORRUPT, "no zoo tag") + end + local a = Archive.new("zoo") + a.meta.text = string.match(text, "^[^%z\26]*") + a.meta.source = { format = "zoo", version = major .. "." .. minor } + local p = start + local count = 0 + local seen: { [number]: boolean } = {} + local size = r:size() + while true do + if seen[p] or p < 34 or p + 51 > size then + return nil, Err.new(if p + 51 > size then Err.TRUNCATED else Err.CORRUPT, "bad directory entry offset " .. p) + end + seen[p] = true + local e = r:sub(p, size - p) + local etag = e:u32le() + local etype, method = e:u8(), e:u8() + local nextP, dataAt = e:u32le(), e:u32le() + local date, time = e:u16le(), e:u16le() + local crc = e:u16le() + local orig, packed = e:u32le(), e:u32le() + e:skip(2) + local deleted = e:u8() + e:skip(1) + local commentAt, commentLen = e:u32le(), e:u16le() + local fname = e:fixed(13) + if e.err then + return nil, e.err + end + if etag ~= TAG then + return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p) + end + if nextP == 0 then + break + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local name, dir = fname, "" + local entry: any = {} + if etype == 2 then + local varLen = e:u16le() + e:skip(3) -- tz, dir_crc + if varLen > 0 then + local v = e:slice(varLen) + local nlen, dlen = v:u8(), v:u8() + local lname = v:string(nlen) + dir = v:string(dlen) + if nlen > 0 then + name = string.match(lname, "^[^%z]*") or lname + end + if v:remaining() >= 2 then + entry.system = v:u16le() + end + if v:remaining() >= 3 then + local f0, f1, f2 = v:u8(), v:u8(), v:u8() + local attr = f0 + f1 * 256 + f2 * 65536 + if bit32.band(attr, 0x400000) ~= 0 then + entry.mode = bit32.band(attr, 0xFFFF) + end + end + if v:remaining() >= 4 then + local vflag, ver = v:u16le(), v:u16le() + if bit32.band(vflag, 0x40) ~= 0 then + entry.version = ver + end + end + end + if e.err then + return nil, e.err + end + end + dir = string.match(dir, "^[^%z]*") or dir + dir = string.gsub(dir, "\\", "/") + local full = if dir ~= "" then (string.gsub(dir, "/+$", "")) .. "/" .. name else name + full = string.gsub(full, "^/+", "") + if deleted == 0 then + local key = full + if a._byName[key] then + key = full .. ";" .. tostring(entry.version or count) + end + entry.name = key + entry.size = orig + entry.compressedSize = packed + entry.method = if method == 0 then "store" elseif method == 1 then "lzw" elseif method == 2 then "lzh" else "method" .. method + entry.mtime = Archive.fromDos(date * 65536 + time) + entry.dir = false + if commentLen > 0 and commentAt + commentLen <= size then + entry.comment = r:sub(commentAt, commentLen):string(commentLen) + end + if dataAt + packed > size then + return nil, Err.new(Err.TRUNCATED, full .. ": data past the end") + end + if orig > maxBytes then + return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes") + end + if orig > 0 then + local buf, at = r.buf, r.base + dataAt + entry.load = function(): (buffer?, Err.Err?) + local out: buffer?, derr: string? + if method == 0 then + if packed < orig then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(orig) + buffer.copy(out :: buffer, 0, buf, at, orig) + elseif method == 1 then + local ob = buffer.create(orig) + local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo") + if n ~= orig then + return nil, Err.from(lerr or "corrupt: LZW data ends early") + end + out = ob + elseif method == 2 then + out, derr = Lzh.decode(buf, at, packed, orig, "lh5") + else + return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc16.arc(out, 0, orig) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, entry) + end + p = nextP + end + return a, nil +end + +return Zoo +end +__FILES["archive/zst"] = function() + +-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zst = { + name = "zst", + category = "archive", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse a decompressed size over this (default 2^30) + verify: boolean?, -- check the content checksum (default true) + name: string?, -- the file name, for the entry name (the api passes it) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Zst.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == Zstd.MAGIC then + return 1 + end + -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame + if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) + if not out then + return nil, err + end + local a = Archive.new("zst") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(o, Zst.extensions), + size = buffer.len(out), + compressedSize = len, + method = "zstd", + dir = false, + data = out, + }) + return a, nil +end + +return Zst +end +__FILES["audio/aac"] = function() + +-- 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/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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") + +-- ------------------------------------------------------------------------------------------------ contract +local AacFormat = { + name = "aac", + category = "audio", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 + +-- the size of an ID3v2 tag at p (0 if none) +local function id3Size(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local s = 0 + for i = 6, 9 do + s = s * 128 + bit32.band(readu8(b, p + i), 127) + end + local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 + return 10 + s + footer +end + +-- a few ID3v2.3 / 2.4 text frames -> tags +local ID3_TAGS: { [string]: string } = { + TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", + COMM = "comment", TCOM = "composer", TPE2 = "albumartist", +} +local function id3Tags(b: buffer, p: number, size: number): Types.Tags + local tags: Types.Tags = {} + local ver = readu8(b, p + 3) + if ver < 3 then + return tags + end + local q, stop = p + 10, p + size + while q + 10 <= stop do + local id = buffer.readstring(b, q, 4) + if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then + break + end + local n = 0 + for i = 4, 7 do + n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) + end + if n < 1 or q + 10 + n > stop then + break + end + local key = ID3_TAGS[id] + local enc = readu8(b, q + 10) + if key and (enc == 0 or enc == 3) then + local s = buffer.readstring(b, q + 11, n - 1) + if id == "COMM" and #s > 3 then + s = string.sub(s, 4) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, z + 1) + end + end + s = (string.gsub(s, "%z+$", "")) + tags[key] = s + end + q += 10 + n + end + return tags +end + +-- ------------------------------------------------------------------------------------------------ sniff +function AacFormat.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3Size(b, p, limit) + local h = Aac.adts(b, p, limit) + if not h then + return 0 + end + -- a second header right after the first makes it certain + local h2 = Aac.adts(b, p + h.frameSize, limit) + if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then + return 0.9 + end + return if p + h.frameSize >= limit then 0.7 else 0.4 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the frame index: offsets of every ADTS frame (resyncing over garbage) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + id3Size(b, r.base, limit) + local offs, sizes = {}, {} + local first: Aac.Adts? = nil + while p + 7 <= limit do + local h = Aac.adts(b, p, limit) + if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then + h = nil -- a false sync inside the data + end + if not h then + p += 1 + continue + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + if not first then + first = h + end + if h.blocks ~= 1 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) + end + table.insert(offs, p + h.headerSize) + table.insert(sizes, h.frameSize - h.headerSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first then + return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) + end + local h = first :: Aac.Adts + if h.objectType ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") + end + if h.channelConfig == 0 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") + end + local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number + local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) + if not dec then + return nil, derr + end + local d = dec :: Aac.Decoder + local sr = d.sampleRate + local nframes = #offs + local total = nframes * 1024 + local bytes = 0 + for _, s in sizes do + bytes += s + end + 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 out: any = { + sampleRate = sr, + channels = channels, + frames = total, + duration = total / sr, + bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, + tags = tags, + codec = "aac", + } + -- 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?) + local dec, err = AacFormat.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) +end + +return AacFormat +end +__FILES["audio/ac3"] = function() + +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through +-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) +-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block +-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and +-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). +-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Ac3 = __include("codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- refuse streams with more syncframes (default 2^22) + drc: number?, -- dynamic range control scale: 0 = off (default), 1 = full + crc: boolean?, -- check every syncframe's CRC (default true; a bad frame ends the stream with Err.CHECKSUM) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) +function Ac3Format.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return if p + h.frameSize >= limit then 0.6 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Ac3.Header?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first: Ac3.Header? = nil + while p + 8 <= limit do + local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil -- a false sync word + end + end + if not h then + p += 1 + continue + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function Ac3Format.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first :: Ac3.Header + local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i: number): number + return (i - 1) * 1536 + end, + decode = function(i: number): (number?, Err.Err?) + local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function(): { number } + return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format +end +__FILES["audio/adpcm"] = function() + +-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in +-- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by +-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such +-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs +-- here are the layouts those containers use: +-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first +-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order +-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) +-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) +-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime +-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) +-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients +-- live in a header: see audio/brstm and audio/adx). +-- +-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) +-- local raw = Adpcm.encode(a, { codec = "ima" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Raw = { + name = "adpcm", + category = "audio", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Codec = "ima" | "ima_wav" | "ms" | "ima_qt" | "psx" +type Options = { + codec: Codec?, -- default "ima" + sampleRate: number?, -- default 22050 (decode) + channels: number?, -- default 1 (decode) + blockAlign: number?, -- ima_wav / ms: bytes per block (default 1024 when decoding; 256 * channels when encoding) + lowFirst: boolean?, -- ima: the low nibble first + interleave: number?, -- psx: bytes per channel before the next channel (default 16) + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Raw.sniff(_r: Bytes.Reader): number + return 0 -- no header: found by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Raw.decode(r: Bytes.Reader, opts: Options?): (Types.Audio?, Err.Err?) + local dec, err = Raw.open(r, opts) + if not dec then + return nil, err + end + local limit = opts and opts.maxFrames or 2 ^ 28 + if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames)) + end + return Pcm.drain(dec, { format = "adpcm", codec = (dec :: any).codec }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Raw.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o: Options = opts or {} + local codec = o.codec or "ima" + if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then + return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms") + end + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local ch, n, x = a.channels, a.frames, a.samples + if codec == "ima" then + local out = buffer.create((n * ch + 1) // 2) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst) + end + return out, nil + end + local ba = o.blockAlign or 256 * ch + local spb = Decoder.blockFrames(codec, ba, ch) + if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then + return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba)) + end + if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then + return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels") + end + local blocks = (n + spb - 1) // spb + local out = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + local f0 = b * spb + if codec == "ms" then + Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba) + else + Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Raw.open(r: Bytes.Reader, opts: Options?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local o: Options = opts or {} + local codec = o.codec or "ima" + local rate, ch = o.sampleRate or 22050, o.channels or 1 + if not CODECS[codec] then + return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec)) + end + if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + local size = r.limit - r.base + local dec: any = { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 } + local d, err + if codec == "ima" then + d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst }) + elseif codec == "psx" then + local il = o.interleave or 16 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = if ch == 1 then 16 else il }) + else + local ba = o.blockAlign or 1024 + if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then + return nil, Err.new(Err.ARG, "bad blockAlign") + end + d, err = Decoder.blocks(dec, { kind = codec :: any, buf = r.buf, offset = r.base, size = size, blockAlign = ba }) + end + if not d then + return nil, err + end + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + return d, nil +end + +return Raw +end +__FILES["audio/adx"] = function() + +-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in +-- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), +-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder +-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), +-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, +-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and +-- exponential (4) encoding types, AHX. +-- +-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) +-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Adx = { + name = "adx", + category = "audio", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Loop = { start: number, stop: number } +type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +type EncodeOptions = { + loop: Loop?, -- loop points in frames (stop exclusive); default: the source's meta.source.loop / loop, else none + cutoff: number?, -- the predictor's high-pass cutoff in Hz (default 500, as CRI's encoders) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FRAME = 18 + +-- ------------------------------------------------------------------------------------------------ sniff +function Adx.sniff(r: Bytes.Reader): number + if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then + return 0 + end + local off = r:peekU8(2) * 256 + r:peekU8(3) + return if r:peek(6, off - 2) == "(c)CRI" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Adx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Adx.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Adx.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local loop = o.loop + if loop == nil then + local v = value :: any + local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop + loop = if type(m) == "table" then m else (if type(v.loop) == "table" then v.loop else nil) + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + local cutoff = o.cutoff or 500 + if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then + return nil, Err.new(Err.ARG, "bad cutoff") + end + cutoff = math.floor(cutoff) + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local hist = if ch > 1 then 4 * ch else 8 + local start = 0x18 + hist + (if loop then 0x18 else 0) + 6 + start = (start + 3) // 4 * 4 + local nframes = (n + 31) // 32 + local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) + w:u16be(0x8000) + w:u16be(start - 4) + w:u8(3) + w:u8(FRAME) + w:u8(4) + w:u8(ch) + w:u32be(rate) + w:u32be(n) + w:u16be(cutoff) + w:u16be(0x0400) + w:u32be(0) + w:fill(0, hist) + if loop then + local bytesAt = function(f: number): number + return start + (f // 32) * FRAME * ch + end + w:u16be(0) + w:u16be(1) + w:u32be(1) + w:u32be(loop.start) + w:u32be(bytesAt(loop.start)) + w:u32be(loop.stop) + w:u32be(bytesAt(loop.stop + 31)) + end + w:fill(0, start - 6 - w.pos) + w:string("(c)CRI") + local at = w:reserve(nframes * FRAME * ch) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) + end + w.pos = at + nframes * FRAME * ch + -- the end marker: scale 0x8001, then the padding size + w:u16be(0x8001) + w:u16be(FRAME - 4) + w:fill(0, FRAME - 4) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Adx.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if Adx.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an ADX file") + end + local h = r:sub(0) + local copyright = (h:seek(2) and h:u16be()) or 0 + local start = copyright + 4 + local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() + local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() + if h.err then + return nil, h.err + end + if version == 0x0408 or version == 0x0409 then + return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") + end + if enc ~= 3 then + return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. (if enc == 0x10 or enc == 0x11 then " (AHX)" else "")) + end + if fsize ~= FRAME or bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) + end + if ch < 1 or ch > 8 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) + end + local size = r.limit - r.base - start + if size < 0 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + -- loop points and the initial history (vgmstream's reading of the extra header fields) + local hist: { number }? = nil + local loopsAt: number? = nil + if version == 0x0300 then + if start - 6 >= 0x14 + 0x18 then + loopsAt = 0x14 + end + elseif version == 0x0400 then + local hsize = if ch > 1 then 4 * ch else 8 + hist = {} + for c = 0, ch - 1 do + local hh = r:sub(0x18 + c * 4, 4) + local h1, h2 = hh:i16be(), hh:i16be() + hist[c * 2 + 1], hist[c * 2 + 2] = if hh.err then 0 else h1, if hh.err then 0 else h2 + end + local ainf = 0 + local ai = r:sub(0x18 + hsize + 4, 8) + if ai:string(4) == "AINF" then + ainf = ai:u32be() + end + if start - ainf - 6 >= 0x18 + hsize + 0x18 then + loopsAt = 0x18 + hsize + end + end + local loopTable: { start: number, stop: number }? = nil + if loopsAt then + local l = r:sub(loopsAt + 4, 0x14) + local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() + if not l.err and flag ~= 0 and le > ls then + loopTable = { start = ls, stop = le } + end + end + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local dec: any = { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } + local d, err = Decoder.interleaved(dec, { + kind = "adx", + buf = r.buf, + offset = r.base + start, + size = size, + interleave = FRAME, + frames = frames, + c1 = c1, + c2 = c2, + v3 = version == 0x0300, + hist = hist, + }) + if not d then + return nil, err + end + d.bitrate = rate * FRAME * ch * 8 // 32 + return d, nil +end + +return Adx +end +__FILES["audio/aiff"] = function() + +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw +-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated +-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; +-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, +-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" + littleEndian: boolean?, -- 16-bit samples as AIFF-C "sowt" (default false: big endian; readers such as ffmpeg only + -- take 16-bit sowt, so other formats return Err.ARG) + aifc: boolean?, -- always write AIFF-C (default: only when the sample format needs it) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b: buffer, o: number): number + local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return if se >= 0x8000 then -v else v +end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w: Bytes.Writer, x: number) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e += 1 + end + while x < 2 ^ e do + e -= 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +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", nil + elseif bits <= 16 then + return "s16be", nil + elseif bits <= 24 then + return "s24be", nil + elseif bits <= 32 then + return "s32be", nil + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8", nil + elseif bits <= 16 then + return "s16le", nil + elseif bits <= 24 then + return "s24le", nil + elseif bits <= 32 then + return "s32le", nil + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8", nil + elseif comp == "in24" then + return "s24be", nil + elseif comp == "in32" then + return "s32be", nil + elseif comp == "42ni" then + return "s32le", nil + elseif comp == "fl32" or comp == "FL32" then + return "f32be", nil + elseif comp == "fl64" or comp == "FL64" then + return "f64be", nil + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw", nil + elseif comp == "alaw" or comp == "ALAW" then + return "alaw", nil + elseif comp == "ima4" then + return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return if form == "AIFF" or form == "AIFC" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + channels: number, + frames: number, + sampleRate: number, + bits: number, + format: string, + compression: string, + aifc: boolean, + dataOffset: number, -- absolute in r.buf + dataSize: number, -- bytes of sample data present + truncated: boolean, + tags: Types.Tags, +} + +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info: Info? = nil + local comm = false + local ssnd: number? = nil + local ssndLen = 0 + local tags: Types.Tags = {} + -- (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) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = if aifc then buffer.readstring(b, d + 18, 4) else "NONE" + if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(if comp == "NONE" or comp == "twos" or comp == "sowt" then Err.CORRUPT else Err.UNSUPPORTED, why :: string, d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + dataSize = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = if tags[key] then tags[key] .. "\n" .. s else s + end + if len > formEnd - d then + break + end + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info :: Info + if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local present + if fi.format == "ima4" then + fi.frames *= 64 -- COMM counts packets + present = if ssnd then ssndLen // (34 * fi.channels) * 64 else 0 + else + present = if ssnd then ssndLen // (fi.channels * Pcm.Convert.SIZE[fi.format]) else 0 + end + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + fi.dataSize = ssndLen + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(if aifc then "AIFC" else "AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in TEXT_ORDER do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen += plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr + if info.format == "ima4" then + local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } + dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) + if dec then + (dec :: any).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) + end + else + dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + end + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff +end +__FILES["audio/ape"] = function() + +-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), +-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end +-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). +-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 +-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. +-- +-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 +-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them +-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local ApeCodec = __include("codecs/audio/Ape") + +-- ------------------------------------------------------------------------------------------------ contract +local Ape = { + name = "ape", + category = "audio", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ape.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "MAC " or head == "MACF" then -- MACF: float samples + return 1 + end + if string.sub(head, 1, 3) == "ID3" then + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + local id = r:peek(4, 10 + sz + (if footer then 10 else 0)) + return if id == "MAC " or id == "MACF" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Ape.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Ape.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Ape.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = ApeCodec.info(buf, base, stop) + if not info then + return nil, err + end + if info.channels * info.blocksPerFrame > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") + end + local codec, cerr = ApeCodec.decoder(info) + if not codec then + return nil, cerr + end + local frames = info.totalBlocks + local bpf = info.blocksPerFrame + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + level = LEVELS[info.level] or tostring(info.level), + version = info.version, + md5 = info.md5, + source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, + } + local count = info.totalFrames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * bpf + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bitsPerSample - 1), + ints = not info.float, + }) +end + +return Ape +end +__FILES["audio/au"] = function() + +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 }, +} + +type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +type EncodeOptions = { + sampleFormat: ("s8" | "s16" | "s24" | "s32" | "f32" | "f64" | "ulaw" | "alaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS: { [number]: string } = { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b: buffer, o: number): number + return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r: Bytes.Reader): number + return if r:peek(4) == ".snd" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = if type(src.tags.comment) == "string" then src.tags.comment else "" + local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags: Types.Tags = {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = size // frameBytes + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec :: any + d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au +end +__FILES["audio/brstm"] = function() + +-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and +-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP +-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 +-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } +-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions +-- (the whole stream plays), the track table (channels are not grouped). +-- +-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Brstm = { + name = "brstm", + category = "audio", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Brstm.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then + return 0 + end + local bom = r:peek(2, 4) + return if bom == "\254\255" or bom == "\255\254" then 1 else 0 +end + +-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect +function Brstm.variant(r: Bytes.Reader): string? + local m = r:peek(4) + return if m == "RSTM" then "brstm" elseif m == "CSTM" then "bcstm" elseif m == "FSTM" then "bfstm" else nil +end + +-- ------------------------------------------------------------------------------------------------ decode +function Brstm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Brstm.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file +-- start); a read out of range records the error in .err and returns 0 +local function view(r: Bytes.Reader, be: boolean) + local v = { err = nil :: string? } + local size = r.limit - r.base + local function at(o: number, n: number): Bytes.Reader? + if o < 0 or o + n > size then + v.err = "an offset points past the end" + return nil + end + return r:sub(o, n) + end + function v.u8(o: number): number + local s = at(o, 1) + return if s then s:u8() else 0 + end + function v.u16(o: number): number + local s = at(o, 2) + return if s then (if be then s:u16be() else s:u16le()) else 0 + end + function v.i16(o: number): number + local s = at(o, 2) + return if s then (if be then s:i16be() else s:i16le()) else 0 + end + function v.u32(o: number): number + local s = at(o, 4) + return if s then (if be then s:u32be() else s:u32le()) else 0 + end + function v.i32(o: number): number + local s = at(o, 4) + return if s then (if be then s:i32be() else s:i32le()) else 0 + end + return v +end + +type Layout = { + codec: number, + loop: boolean, + ch: number, + rate: number, + loopStart: number, + frames: number, + blockSize: number, + lastPadded: number, + data: number, -- the first block (absolute in the file) + adp: { number }, -- each channel's DSP info offset (coefficients, then gain, ps, yn1, yn2) + hist: number?, -- the per-block history table: (yn1, yn2) per channel per block + histEntries: number, +} + +local function parseRstm(v: any): (Layout?, string?) + if v.u16(0x06) ~= 0x0100 then + return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) + end + local head = v.u32(0x10) + local adpc = v.u32(0x18) + if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian + return nil, "no HEAD chunk" + end + local base = head + 8 + local info = base + v.u32(base + 4) + local chans = base + v.u32(base + 20) + local ch = v.u8(info + 2) + local L: Layout = { + codec = v.u8(info), + loop = v.u8(info + 1) ~= 0, + ch = ch, + rate = v.u16(info + 4), + loopStart = v.u32(info + 8), + frames = v.u32(info + 12), + data = v.u32(info + 16), + blockSize = v.u32(info + 24), + lastPadded = v.u32(info + 40), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = base + v.u32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = base + v.u32(ci + 4) + end + if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" + L.hist = adpc + 8 + L.histEntries = (v.u32(adpc + 4) - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +local function parseFstm(v: any): (Layout?, string?) + local info: number, seek: number, data: number = 0, 0, 0 + local seekSize: number = 0 + for i = 0, math.min(v.u16(0x10), 16) - 1 do + local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) + if id == 0x4000 then + info = off + elseif id == 0x4001 then + seek = off + seekSize = v.u32(0x14 + i * 12 + 8) :: number + elseif id == 0x4002 then + data = off + end + end + if info == 0 or data == 0 then + return nil, "no INFO or DATA block" + end + local stream = info + 8 + v.i32(info + 0x0C) + local chans = info + 8 + v.i32(info + 0x1C) + local ch = v.u8(stream + 2) + local dataRef = stream + 0x30 + local L: Layout = { + codec = v.u8(stream), + loop = v.u8(stream + 1) ~= 0, + ch = ch, + rate = v.u32(stream + 4), + loopStart = v.u32(stream + 8), + frames = v.u32(stream + 12), + blockSize = v.u32(stream + 20), + lastPadded = v.u32(stream + 36), + data = if v.u16(dataRef) == 0x1F00 then data + 8 + v.i32(dataRef + 4) else data + 0x20, + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = chans + v.i32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = ci + v.i32(ci + 4) + end + if seek > 0 and seekSize > 8 then + L.hist = seek + 8 + L.histEntries = (seekSize - 8) // math.max(1, 4 * ch) + end + return L, nil +end + +function Brstm.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if r.limit - r.base < 0x40 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + if Brstm.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") + end + local magic = r:peek(4) + local be = r:peek(2, 4) == "\254\255" + local v = view(r, be) + local parsed: Layout?, msg: string? + if magic == "RSTM" then + if not be then + return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") + end + parsed, msg = parseRstm(v) + else + parsed, msg = parseFstm(v) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + elseif not parsed then + return nil, Err.from(msg) + end + local L = parsed :: Layout + local codec = CODECS[L.codec] + if not codec then + return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) + elseif codec == "ima" then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") + end + local ch = L.ch + if ch < 1 or L.rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") + end + local size = r.limit - r.base - L.data + if L.data < 0 or size < 0 then + return nil, Err.new(Err.TRUNCATED, "the data starts past the end") + end + local kind = if codec == "dsp" then "dsp" elseif codec == "pcm8" then "s8" elseif be then "s16be" else "s16le" + local coefs: buffer? = nil + local hist: { number }? = nil + if codec == "dsp" then + coefs = buffer.create(64 * ch) + hist = {} + for c = 0, ch - 1 do + local adp = L.adp[c + 1] + for k = 0, 15 do + buffer.writei32(coefs :: buffer, c * 64 + k * 4, v.i16(adp + k * 2)) + end + hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + end + end + local histAt, entries = L.hist, L.histEntries + local loop = if L.loop and L.loopStart < L.frames then { start = L.loopStart, stop = L.frames } else nil + local dec: any = { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } + local block = L.blockSize + if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then + return nil, Err.new(Err.CORRUPT, "bad block size " .. block) + end + local d, err = Decoder.interleaved(dec, { + kind = kind :: any, + buf = r.buf, + offset = r.base + L.data, + size = size, + interleave = block, + lastInterleave = if L.lastPadded > 0 and L.lastPadded <= block then L.lastPadded else block, + frames = L.frames, + coefs = coefs, + hist = hist, + restore = if codec == "dsp" and histAt + then function(row: number, st: buffer): boolean + if row >= entries then + return false + end + for c = 0, ch - 1 do + local p = (histAt :: number) + (row * ch + c) * 4 + buffer.writei32(st, c * 8, v.i16(p)) + buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) + end + return v.err == nil + end + else nil, + }) + if d then + d.bitrate = if d.duration > 0 then math.floor(size * 8 / d.duration) else 0 + end + return d, err +end + +return Brstm +end +__FILES["audio/caf"] = function() + +-- 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/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. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: +-- other compressed formats (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPackets: number?, -- packet table limit (default 2^24) +} +type EncodeOptions = { + codec: ("pcm" | "alac")?, -- default "alac" + bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 + tags: Types.Tags?, -- default: the audio's tags +} + +-- ------------------------------------------------------------------------------------------------ constants +local INFO_TAGS: { [string]: string } = { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO: { [string]: string } = {} +for k, v in INFO_TAGS do + TAG_INFO[v] = k +end + +-- mu-law / A-law -> linear 16-bit +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 + local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } +type Parsed = { + desc: Desc, + dataStart: number, -- absolute offset of the audio data + dataEnd: number, + cookie: buffer?, + packets: { number }?, -- sizes (pakt) + packetFrames: { number }?, + priming: number, + remainder: number, + validFrames: number?, + tags: Types.Tags, +} + +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo +local function esdsConfig(b: buffer): buffer? + local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len(): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n + end + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r: Bytes.Reader): number + local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +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 + local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + -- 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 = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket + if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v + end + end + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end + +-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err +type Source = { + channels: number, + rate: number, + packetCount: number, + packetFrames: (number) -> number, + decode: (number) -> (number?, Err.Err?), + pcm: { number }, + reset: () -> (), + codec: string, + bits: number?, +} + +local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) + local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = if fmt == "lpcm" then d.bits else 8 + local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (bits // 8) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = bits // 8 + if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = (p.dataEnd - p.dataStart) // bpf + local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src: Source = { + channels = ch, + rate = d.rate, + packetCount = (total + per - 1) // per, + packetFrames = function(i: number): number + return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = if fmt == "lpcm" then "pcm" else fmt, + bits = bits, + decode = function(i: number): (number?, Err.Err?) + local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() + else + v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() + end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) + v *= scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v *= scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v *= scale + end + pcm[k] = v + k += 1 + q += bps + end + end + return n, nil + end, + } + return src, nil + end + -- packetised codecs + local sizes = p.packets + if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none + if d.bytesPerPacket > 0 then + local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket + sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#(sizes :: { number }), 0) + local o = p.dataStart + for i, s in sizes :: { number } do + offsets[i] = o + o += s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil :: any + sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) + break + end + end + local count = #(sizes :: { number }) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i: number): number + return if pf then pf[i] else fpp + end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i: number): (number?, Err.Err?) + local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = if cookie then esdsConfig(cookie :: buffer) else nil + if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc :: buffer) + if not dec then + return nil, err + end + local ad = dec :: Aac.Decoder + return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i: number): (number?, Err.Err?) + return ad:decode(b, offsets[i], (sizes :: { number })[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local pp = p :: Parsed + if pp.desc.format == "ima4" then + -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets + local ch = pp.desc.channels + local packets = (pp.dataEnd - pp.dataStart) // (34 * ch) + local frames = packets * 64 + if pp.validFrames and pp.validFrames >= 0 then + frames = math.min(frames, pp.validFrames) + end + local dec: any = { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } + local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) + if d then + d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) + end + return d, derr + end + local s, serr = source(r, pp) + if not s then + return nil, serr + end + local src = s :: Source + local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total += src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + } + 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?) + local dec, err = Caf.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w: Bytes.Writer, typ: string, size: number) + w:string(typ) + w:i64be(size) +end + +-- encode(audio | decoder, opts?) -> buffer | nil, Err +function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + 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 + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + -- the source frames + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf: buffer? = nil + local function nextBlock(n: number): (buffer?, number, number) + if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done += k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done += got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes: { number } = {} + local enc: Alac.Encoder? = nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer + w:u32be(ch * depth // 8) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in tags do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in keys do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in sizes do + -- BER variable-length integer + local bytes = { s % 128 } + local v = s // 128 + while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v //= 128 + end + for _, x in bytes do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf +end +__FILES["audio/flac"] = function() + +-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, +-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. +-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals +-- 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 (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 +-- local i32, n = dec:readInt(4096) -- bit-exact integer samples +-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Stream = __include("audio/flac/Stream") +local Encode = __include("codecs/audio/Flac/Encode") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Flac = { + name = "flac", + category = "audio", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Decoder = Stream.Decoder +type OpenOptions = { + crc16: boolean?, -- check every frame's CRC-16 (default true; a bad frame is skipped by resyncing) + maxFrames: number?, -- decode(): refuse streams longer than this many sample frames (default 2^28) +} +type EncodeOptions = { + level: number?, -- 0..8 like libFLAC's -0 .. -8 (default 5) + bits: number?, -- bits per sample 4..24 (default: the source's meta.source.bitDepth / bitsPerSample if 4..24, else 16) + blockSize: number?, -- 16..65535 (default: the level's, 1152 or 4096) + seekInterval: number?, -- seconds between SEEKTABLE points when the length is known (default 10; 0 = none) + padding: number?, -- bytes of PADDING after the metadata (default 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Flac.sniff(r: Bytes.Reader): number + local head = r:peek(4) + if head == "fLaC" then + return 1 + end + if head == "OggS" then + -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) + local nseg = r:peekU8(26) + if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then + return 1 + end + return 0 + end + if string.sub(head, 1, 3) == "ID3" then + -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return if r:peek(4, 10 + sz + (if footer then 10 else 0)) == "fLaC" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Flac.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + 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 +-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err +function Flac.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value :: any + local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = if type(sb) == "number" and sb >= 4 and sb <= 24 then sb else 16 + end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src :: any, { + level = level, + bits = bits :: number, + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "rosetta", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Flac.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) + if not dec then + return nil, Err.new(code or Err.CORRUPT, tostring(msg)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Flac.Stream = Stream +Flac.Ogg = Ogg + +return Flac +end +__FILES["audio/flac/Meta"] = @native function() + + + +-- 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 = __include("codecs/audio/VorbisComment") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Meta = {} + +@native local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end +@native local function be24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end +@native local function be32(b: buffer, p: number): number + return be16(b, p) * 65536 + be16(b, p + 2) +end + +type StreamInfo = { + minBlockSize: number, + maxBlockSize: number, + minFrameSize: number, -- 0 = unknown + maxFrameSize: number, + sampleRate: number, + channels: number, + bitsPerSample: number, + totalSamples: number, -- 0 = unknown + md5: string, -- 32 hex digits (all zero = not set) +} + +type SeekPoint = { sample: number, offset: number, samples: number } + +type Picture = { + type: number, + mime: string, + description: string, + width: number, + height: number, + depth: number, + colors: number, + offset: number, -- the image bytes are buf[offset .. offset + size - 1] + size: number, +} + +type Info = { + streamInfo: StreamInfo, + seekTable: { SeekPoint }, + vendor: string, + tags: { [string]: string }, -- upper-case keys; repeated keys are joined with "; " + comments: { { key: string, value: string } }, -- every comment in order + pictures: { Picture }, + firstFrame: number, -- byte offset just after the last metadata block +} + +@native local function streamInfo(b: buffer, p: number): StreamInfo + local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) + local hex = table.create(16) + for i = 0, 15 do + hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) + end + return { + minBlockSize = be16(b, p), + maxBlockSize = be16(b, p + 2), + minFrameSize = be24(b, p + 4), + maxFrameSize = be24(b, p + 7), + sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), + channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, + bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, + totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), + md5 = table.concat(hex), + } +end + +@native local function vorbisComment(b: buffer, p: number, e: number, info: Info): boolean + if p + 4 > e then + return false + end + local vl = readu32(b, p) + p += 4 + if p + vl > e then + return false + end + info.vendor = buffer.readstring(b, p, vl) + p += vl + if p + 4 > e then + return false + end + local n = readu32(b, p) + p += 4 + for _ = 1, n do + if p + 4 > e then + return false + end + local l = readu32(b, p) + p += 4 + if p + l > e then + return false + end + local s = buffer.readstring(b, p, l) + p += l + local eq = string.find(s, "=", 1, true) + if eq then + 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 + end + return true +end + +@native local function picture(b: buffer, p: number, e: number): Picture? + if p + 8 > e then + return nil + end + local typ = be32(b, p) + local ml = be32(b, p + 4) + p += 8 + if p + ml + 4 > e then + return nil + end + local mime = buffer.readstring(b, p, ml) + p += ml + local dl = be32(b, p) + p += 4 + if p + dl + 20 > e then + return nil + end + local desc = buffer.readstring(b, p, dl) + p += dl + local pic = { + type = typ, + mime = mime, + description = desc, + width = be32(b, p), + height = be32(b, p + 4), + depth = be32(b, p + 8), + colors = be32(b, p + 12), + offset = p + 20, + size = be32(b, p + 16), + } + if pic.offset + pic.size > e then + return nil + end + return pic +end + +-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) +@native function Meta.parse(b: buffer, pos: number, len: number): (Info?, string?) + if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then + return nil, "Flac: no fLaC marker" + end + local info: Info = { + streamInfo = nil :: any, + seekTable = {}, + vendor = "", + tags = {}, + comments = {}, + pictures = {}, + firstFrame = 0, + } + local p = pos + 4 + while true do + if p + 4 > len then + return nil, "Flac: truncated metadata" + end + local h = readu8(b, p) + local last = h >= 128 + local typ = bit32.band(h, 127) + local size = be24(b, p + 1) + p += 4 + local e = p + size + if e > len then + return nil, "Flac: truncated metadata block" + end + if typ == 0 then + if size < 34 then + return nil, "Flac: bad STREAMINFO" + end + info.streamInfo = streamInfo(b, p) + elseif typ == 3 then + for q = p, e - 18, 18 do + local hi = be32(b, q) + if hi ~= 0xFFFFFFFF then -- placeholder points are all ones + table.insert(info.seekTable, { + sample = hi * 4294967296 + be32(b, q + 4), + offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), + samples = be16(b, q + 16), + }) + end + end + elseif typ == 4 then + vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + elseif typ == 6 then + local pic = picture(b, p, e) + if pic then + table.insert(info.pictures, pic) + end + elseif typ == 127 then + return nil, "Flac: invalid metadata block type" + end + p = e + if last then + break + end + end + if not info.streamInfo then + return nil, "Flac: no STREAMINFO" + end + local si = info.streamInfo + if si.sampleRate == 0 then + return nil, "Flac: bad STREAMINFO values" + end + info.firstFrame = p + return info, nil +end + +return Meta +end +__FILES["audio/flac/Stream"] = @native function() + + + +-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through +-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, +-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed +-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an +-- injected module). Nothing throws: open returns nil, message, code. +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Frame = __include("codecs/audio/Flac/Frame") +local Meta = __include("audio/flac/Meta") + +local Stream = {} + +local writef32, writei32 = buffer.writef32, buffer.writei32 +type Header = any -- Frame.Header +local PAD = Frame.PAD + +type Decoder = { + sampleRate: number, + channels: number, + bitsPerSample: number, + frames: number, -- total sample frames (per channel); 0 if unknown and not found + duration: number, -- seconds + bitrate: number, -- average bits per second of the audio data + tags: { [string]: string }, + comments: { { key: string, value: string } }, + vendor: string, + md5: string, + seekTable: { any }, + pictures: { any }, + container: string, -- "flac" | "ogg" + read: (Decoder, number, buffer?) -> (buffer, number), + readInt: (Decoder, number, buffer?) -> (buffer, number), + seek: (Decoder, number) -> boolean, + seekSample: (Decoder, number) -> boolean, + position: (Decoder) -> (number, number), +} + +local Dec = {} +Dec.__index = Dec + +-- the sample number of a frame +@native local function sampleOf(self: any, h: Header): number + return if h.variable then h.number else h.number * self._nominal +end + +-- a header that also matches the stream (guards the sync search against false syncs) +@native local function plausible(self: any, h: Header): boolean + if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then + return false + end + if self.frames > 0 and sampleOf(self, h) >= self.frames then + return false + end + return true +end + +@native local function findFrame(self: any, pos: number, limit: number): Header? + local b, len, si = self._b, self._len, self._si + while true do + local h = Frame.find(b, pos, limit, len, si) + if not h then + return nil + end + if plausible(self, h) then + return h + end + pos = h.offset + 1 + end +end + +@native local function ensure(self: any, n: number) + if n > self._cap then + for c = 1, self.channels do + self._chans[c] = table.create(n, 0) + end + self._cap = n + end +end + +-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. +@native local function decodeAt(self: any, pos: number): boolean + local b, len = self._b, self._len + while true do + local h = Frame.header(b, pos, len, self._si) + if not h or not plausible(self, h) then + h = findFrame(self, pos, len) + if not h then + self._pos = len + return false + end + end + ensure(self, h.blockSize) + local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) + if nextPos then + local s = sampleOf(self, h) + local n = h.blockSize + if self.frames > 0 and s + n > self.frames then + n = math.max(0, self.frames - s) + end + self._pos = nextPos + self._fs = s + self._fn = n + self._cur = 0 + return true + end + pos = h.offset + 1 + end +end + +@native local function pull(self: any, maxFrames: number, asInt: boolean, dst: buffer?): (buffer, number) + local ch = self.channels + local want = math.floor(tonumber(maxFrames) or 0) + if not (want >= 0) then + want = 0 -- negative or NaN + end + want = math.min(want, 2 ^ 26 // ch) -- keeps the output buffer under 256 MB + local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 + local out = if reuse then dst :: buffer else buffer.create(want * ch * 4) + local got = 0 + local scale = 1 / 2 ^ (self.bitsPerSample - 1) + local stride = ch * 4 + while got < want do + if self._cur >= self._fn then + if self._pos >= self._len or not decodeAt(self, self._pos) then + self._fs += self._cur + self._cur, self._fn = 0, 0 + break + end + end + local take = math.min(want - got, self._fn - self._cur) + local from = self._cur + 1 + local to = self._cur + take + for c = 1, ch do + local s = self._chans[c] + local o = (got * ch + c - 1) * 4 + if asInt then + for i = from, to do + writei32(out, o, s[i]) + o += stride + end + else + for i = from, to do + writef32(out, o, s[i] * scale) + o += stride + end + end + end + self._cur += take + got += take + end + if got < want and not reuse then + local short = buffer.create(got * ch * 4) + buffer.copy(short, 0, out, 0, got * ch * 4) + out = short + end + return out, got +end + +-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is +-- reused when big enough. +@native function Dec.read(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, false, out) +end + +-- The same as interleaved i32 integer samples (bit-exact, right-aligned) +@native function Dec.readInt(self: any, maxFrames: number, out: buffer?): (buffer, number) + return pull(self, maxFrames, true, out) +end + +-- seconds, sample frame of the next frame read() returns +@native function Dec.position(self: any): (number, number) + local s = self._fs + self._cur + return s / self.sampleRate, s +end + +-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets +-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. +@native function Dec.seekSample(self: any, t: number): boolean + t = math.floor(tonumber(t) or 0) + if not (t >= 0) then + t = 0 -- negative or NaN + end + if self.frames > 0 and t >= self.frames then + self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 + return true + end + if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then + self._cur = t - self._fs + return true + end + local first, len = self._first, self._len + local lo, hi = first, len + for _, sp in self.seekTable do + local o = first + sp.offset + if o < len then + if sp.sample <= t then + lo = math.max(lo, o) + else + hi = math.min(hi, o) + break + end + end + end + local window = math.max(16384, 2 * self._si.maxFrameSize) + while hi - lo > window do + local mid = (lo + hi) // 2 + local h = findFrame(self, mid, hi) + if h and sampleOf(self, h) <= t then + lo = h.offset + else + hi = mid + end + end + local pos = lo + while true do + local h = findFrame(self, pos, len) + if not h then + self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 + return false + end + local s = sampleOf(self, h) + if s + h.blockSize > t then + if decodeAt(self, h.offset) then + if self._fs <= t and t < self._fs + self._fn then + self._cur = t - self._fs + return true + elseif self._fs > t then + return false -- a hole in the stream: we are at the next frame + end + pos = self._pos + else + return false + end + else + pos = h.offset + h.size + end + end +end + +@native function Dec.seek(self: any, seconds: number): boolean + return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) +end + +-- Find the total length from the last frame (when STREAMINFO does not give it) +@native local function scanLength(self: any): number + local len = self._len + local step = math.max(65536, 2 * self._si.maxFrameSize) + local from = len + while from > self._first do + local start = math.max(self._first, from - step) + local best: Header? = nil + local pos = start + while true do + local h = findFrame(self, pos, from) + if not h then + break + end + best = h + pos = h.offset + 1 + end + if best then + local s = sampleOf(self, best) + -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here + return s + best.blockSize + end + from = start + end + return 0 +end + +@native local function skipId3(b: buffer, base: number, len: number): number + local p = 0 + while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do + local sz = 0 + for i = 6, 9 do + sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) + end + local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 + p += 10 + sz + (if footer then 10 else 0) + end + return p +end + +-- opts.crc16 = false skips the per-frame CRC-16 check +@native function Stream.open(buf: buffer, base: number, srcLen: number, opts: { crc16: boolean? }?): (Decoder?, string?, string?) + local b, len, container + if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then + local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) + if not demux then + return nil, (err :: any).message, "CORRUPT" + end + local serial = demux:find("flac") + if not serial then + return nil, "no FLAC stream in the Ogg file", "CORRUPT" + end + -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) + local packets, total = {}, 0 + for p in demux:packets(serial) do + local off, size = p.offset, p.size + if #packets == 0 then + if size < 13 then + return nil, "bad Ogg FLAC header", "CORRUPT" + end + off += 9 + size -= 9 + end + table.insert(packets, { p.data, off, size }) + total += size + end + b = buffer.create(total + PAD) + local o = 0 + for _, p in packets do + buffer.copy(b, o, p[1], p[2], p[3]) + o += p[3] + end + len = total + container = "ogg" + else + local start = skipId3(buf, base, srcLen) + if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then + return nil, "not a FLAC file", "CORRUPT" + end + len = srcLen - start + b = buffer.create(len + PAD) + buffer.copy(b, 0, buf, base + start, len) + container = "flac" + end + local info, err = Meta.parse(b, 0, len) + if not info then + return nil, err, "CORRUPT" + end + local si = info.streamInfo + local self = setmetatable({ + sampleRate = si.sampleRate, + channels = si.channels, + bitsPerSample = si.bitsPerSample, + frames = si.totalSamples, + duration = 0, + bitrate = 0, + tags = info.tags, + comments = info.comments, + vendor = info.vendor, + md5 = si.md5, + seekTable = info.seekTable, + pictures = info.pictures, + container = container, + _b = b, + _len = len, + _si = si, + _first = info.firstFrame, + _pos = info.firstFrame, + _chans = {}, + _cap = 0, + _cf = table.create(32, 0), + _crc = not (opts and opts.crc16 == false), + _fs = 0, + _fn = 0, + _cur = 0, + _nominal = math.max(si.maxBlockSize, 1), + }, Dec) + ensure(self, math.max(si.maxBlockSize, 16)) + local h = findFrame(self, info.firstFrame, len) + if h then + if not h.variable then + self._nominal = h.blockSize + end + end + if self.frames == 0 then + self.frames = scanLength(self) + end + self.duration = self.frames / self.sampleRate + if self.duration > 0 then + self.bitrate = (len - info.firstFrame) * 8 / self.duration + end + return self :: any, nil +end + +Stream.Dec = Dec + +return Stream +end +__FILES["audio/m4a"] = function() + +-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading +-- 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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local IsoBmff = __include("containers/IsoBmff") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + track: number?, -- the track id to play (default: the first AAC / ALAC track) + gapless: boolean?, -- apply the edit list (default true) + maxSamples: number?, -- sample table limit (default 2^25) +} +type EncodeOptions = { + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- samples per packet, default 4096 + tags: Types.Tags?, -- default: the audio's tags + pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats +type PacketDecoder = { + channels: number, + sampleRate: number, + frameSize: number, + pcm: { number }, + decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), + reset: () -> (), +} + +local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) + if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd: PacketDecoder = { + channels = cfg.channels, + sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config :: buffer) + if not dec then + return nil, err + end + local d = dec :: Aac.Decoder + local pd: PacketDecoder = { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +-- open(r, opts?) -> Types.Decoder | nil, Err +function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track: IsoBmff.Track? = nil + local other: IsoBmff.Track? = nil + for _, t in movie.tracks do + if t.kind == "audio" then + if o.track and t.id ~= o.track then + continue + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end + end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track :: IsoBmff.Track + local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd :: PacketDecoder + local channels, sr = p.channels, p.sampleRate + -- media ticks -> sample frames + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 + local total = 0 + for i = 1, t.sampleCount do + total += t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + end + local tags, pictures = IsoBmff.tags(r, movie) + -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex) + local smpb = tags.itunsmpb + if gapless and not t.edits and smpb then + local f: { number } = {} + for w in string.gmatch(smpb, "%x+") do + 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] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + local dec: any = { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + } + 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) + -- 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) +function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = M4a.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + 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, 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: 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 + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc :: Alac.Encoder + local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets: { buffer } = {} + local durations: { number } = {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + -- frames from an Audio buffer or a streaming Decoder + local src: buffer, srcFrames = nil :: any, 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk: buffer? = nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done += n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = if sr < 65536 then sr else 0 + local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = if timescale > 0 then timescale else 48000, + samples = packets, + durations = if timescale > 0 then durations else (function() + local d = {} + for i, v in durations do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)(), + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a +end +__FILES["audio/mp3"] = function() + +-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf +-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 +-- 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, 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; 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()) +-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Header = __include("codecs/audio/Mpa/Header") +local Index = __include("audio/mp3/Index") +local Tags = __include("audio/mp3/Tags") +local Stream = __include("audio/mp3/Stream") +local Encode3 = __include("codecs/audio/Mpa/Encode3") +local Encode2 = __include("codecs/audio/Mpa/Encode2") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp3 = { + name = "mp3", + category = "audio", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 +type OpenOptions = { + maxFrames: number?, -- refuse streams longer than this many sample frames per channel (default 2^31) +} +type Decoder = Stream.Decoder +type EncodeOptions = { + layer: number?, -- 3 (MP3, default) or 2 (MP2) + bitrate: number?, -- bits per second, constant: one of the layer's rates (default 128000 for layer III, 192000 for + -- layer II; MPEG-2 / 2.5 rates: 64000 / 96000); values below 1000 are kbit/s (128 = 128000, the old unit) + 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 +local MAX_FRAMES = 2 ^ 31 + +-- ------------------------------------------------------------------------------------------------ sniff +-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on +function Mp3.sniff(r: Bytes.Reader): number + local b, p, lim = r.buf, r.pos, r.limit + local id3 = false + for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other) + local n = if p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" then Tags.id3v2Size(b, p, lim) else 0 + if n <= 0 then + break + end + id3 = true + p += n + end + if p + 4 > lim or not Header.valid(b, p) then + return if id3 then 0.5 else 0 + end + local fb = Header.frameBytes(b, p, 0) + if fb > 0 then + fb += Header.padding(b, p) + if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then + return 0.9 + end + if p + fb == lim then + return 0.6 + end + end + return if id3 then 0.7 else 0.25 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts) -> Types.Audio (the whole stream, through open) +function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mp3.open(r, opts) + if not dec then + return nil, err + end + 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 + return a, derr +end + +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumartist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write +local function id3Tag(tags: { [string]: any }): buffer? + local w = Bytes.writer(256) + local seen: { [string]: boolean } = {} + local function syncsafe(v: number) + w:u8((v // 2097152) % 128) + w:u8((v // 16384) % 128) + w:u8((v // 128) % 128) + w:u8(v % 128) + end + for _, f in ID3_FRAMES do + local v = tags[f[1]] + if type(v) == "string" and #v > 0 and not seen[f[2]] then + seen[f[2]] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((n // 2097152) % 128) + out:u8((n // 16384) % 128) + out:u8((n // 128) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err +function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = if layer == 3 then Encode3 else Encode2 + -- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else + -- the highest); other input rates go through codecs/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 + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + end + -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s + local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96)) + if type(bitrate) == "number" and bitrate >= 1000 then + bitrate /= 1000 + end + if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring(if type(o.bitrate) == "number" and o.bitrate < 1000 then o.bitrate * 1000 else o.bitrate), layer, rate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = if o.id3 == false then nil else id3Tag(src.tags) + local out, msg = Enc.encode(src :: any, { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- 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 + if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then + out[k] = v + end + end + return out +end + +-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err +function Mp3.open(r: Bytes.Reader, opts: OpenOptions?): (Decoder?, Err.Err?) + local b = r.buf + if r.base ~= 0 or r.limit ~= buffer.len(b) then + b = buffer.create(r.limit - r.base) -- the core indexes from offset 0 + buffer.copy(b, 0, r.buf, r.base, r.limit - r.base) + end + local okTags, tags, start, stop = pcall(Tags.parse, b) + if not okTags then + tags, start, stop = { raw = {} }, 0, buffer.len(b) + end + local idx = Index.build(b, start, stop) + if not idx then + return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found") + end + local dec = Stream.new(b, idx, stringTags(tags), { + raw = tags.raw, + id3v2 = tags.id3v2, + id3v1 = tags.id3v1 == true, + ape = tags.ape == true, + }) + if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then + return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) + +return Mp3 +end +__FILES["audio/mp3/Index"] = @native function() + + + +-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame +-- (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 = __include("codecs/audio/Mpa/Header") +local Core = __include("codecs/audio/Mpa/Core") + +local band, rshift = bit32.band, bit32.rshift +local ru8 = buffer.readu8 +local min, max = math.min, math.max + +local compare, frameBytes, padding, findFrame = + Header.compare, Header.frameBytes, Header.padding, Header.findFrame + +local Index = {} + +Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here) +Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode + +type Index = { + n: number, -- frames + off: buffer, -- u32 byte offset per frame + size: buffer, -- u16 byte size per frame (header and padding included) + flags: buffer, -- u8 FLAG_* + out: buffer, -- u32 first output sample (before the encoder delay is cut) per frame + main: buffer, -- u16 layer III main data bytes per frame (0 for layers I / II) + outTotal: number, -- samples (per channel) of a continuous decode, delay not cut + bytes: number, -- audio bytes in indexed frames + -- format of the first frame + sampleRate: number, + channels: number, -- the most channels of any frame + layer: number, + version: number, -- 1, 2 or 2.5 + spf: number, -- samples per frame + -- Xing / Info / LAME + vbrTag: number, -- mp3dec_check_vbrtag result of the first frame (0 = none) + tagFrames: number, + delay: number, + padding: number, + skipped: number, -- frames with another sample rate or layer, left out +} + +@native local function grow(b: buffer, n: number): buffer + local nb = buffer.create(n) + buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) + return nb +end + +@native function Index.build(b: buffer, start: number, stop: number): Index? + local cap = 1024 + local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) + local n = 0 + local pos = start + local prev = -1 -- offset of the last decoded header (dec->header), -1 = none + local ffb = 0 -- free format bytes + local reserv = 0 + local outTotal = 0 + local bytes = 0 + local first = true + local skipped = 0 + local outCh = 0 -- the most channels of a frame that gives output + local hz, nch, layer, spf, version = 0, 0, 0, 0, 0 + local vbr, tagFrames, delay, pad = 0, 0, 0, 0 + + while true do + local remaining = stop - pos + if remaining <= 0 then + break + end + local fs = 0 + local reset = false + if remaining > 4 and prev >= 0 and compare(b, prev, pos) then + fs = frameBytes(b, pos, ffb) + padding(b, pos) + if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then + fs = 0 + end + end + if fs == 0 then + reset = true + reserv = 0 + local i + i, fs, ffb = findFrame(b, pos, remaining, 0) + if fs == 0 or i + fs > remaining then + break + end + pos += i + end + if fs < 4 or fs > Core.MAX_FRAME then + -- cannot happen with a well-formed header, but never index an impossible frame + prev = -1 + pos += max(fs, 1) + continue + end + local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3) + local fLayer = 4 - band(rshift(h1, 1), 3) + local fHz = Header.sampleRate(h1, h2) + local fCh = if band(h3, 0xC0) == 0xC0 then 1 else 2 + + if first then + first = false + 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) + if ret ~= 0 then + vbr, tagFrames, delay, pad = ret, frames, d, p + if ret < 0 then + delay, pad = 0, 0 + end + -- the tag frame is not audio; the next frame is found again from scratch + prev = -1 + pos += fs + continue + end + end + elseif fHz ~= hz or fLayer ~= layer then + skipped += 1 + prev = pos + pos += fs + continue + end + + local output = true + local mainBytes = 0 + local nextPrev = pos + if fLayer == 3 then + local mdb, p23, mb = Core.probeL3(b, pos, fs) + if mdb < 0 then + output = false + nextPrev = -1 -- mp3dec_init: the next frame re-syncs + else + mainBytes = mb + local have = min(reserv, mdb) + output = reserv >= mdb + local remains = have + mb - (if output then (p23 + 7) // 8 else 0) + reserv = max(0, min(remains, 511)) + end + else + output = Core.probeL12(b, pos, fs) + if not output then + nextPrev = -1 + end + end + + if output and fCh > outCh then + outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated + 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) :: buffer + end + buffer.writeu32(OFF, n * 4, pos) + buffer.writeu16(SIZE, n * 2, fs) + buffer.writeu8(FLAGS, n, (if reset then Index.FLAG_RESET else 0) + (if output then Index.FLAG_OUTPUT else 0)) + buffer.writeu32(OUT, n * 4, outTotal) + buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) + n += 1 + bytes += fs + if output then + outTotal += spf + end + prev = nextPrev + pos += fs + end + + if first then + return nil + end + return { + n = n, + off = OFF, + size = SIZE, + flags = FLAGS, + out = OUT, + main = MAIN, + outTotal = outTotal, + bytes = bytes, + sampleRate = hz, + channels = if outCh > 0 then outCh else nch, + layer = layer, + version = version, + spf = spf, + vbrTag = vbr, + tagFrames = tagFrames, + delay = delay, + padding = pad, + skipped = skipped, + } +end + +return Index +end +__FILES["audio/mp3/Stream"] = function() + + +-- 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 = __include("codecs/audio/Mpa/Core") +local Index = __include("audio/mp3/Index") + +local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT +local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32 +local band = bit32.band +local min, max, floor = math.min, math.max, math.floor + +local Stream = {} + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: { [string]: string }, + id3: any, + layer: number, + version: number, + vbr: boolean, + delay: number, + padding: number, + mpegFrames: number, + _buf: buffer, + _idx: any, + _st: any, + _pcm: buffer, + _cur: number, + _pcmPos: number, + _pcmEnd: number, + _minAbs: number, + _endAbs: number, + _pos: number, + }, + Decoder +)) + +-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) +function Stream.new(b: buffer, idx: any, tags: { [string]: string }, id3: any): Decoder + local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels + -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count + local delay = 0 + local total = idx.outTotal + if idx.vbrTag > 0 then + delay = idx.delay + local detected = spf * idx.tagFrames + if detected >= delay then + detected -= delay + end + if idx.padding > 0 and detected >= idx.padding then + detected -= idx.padding + end + total = max(0, total - delay) + total = min(total, detected) + end + delay = min(delay, idx.outTotal) + local self = setmetatable({ + sampleRate = hz, + channels = nch, + frames = total, + duration = total / hz, + bitrate = if idx.n > 0 then floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) else 0, -- bit/s + tags = tags, + id3 = id3, + layer = idx.layer, + version = idx.version, + vbr = idx.vbrTag ~= 0, + delay = delay, + padding = if idx.vbrTag > 0 then max(0, idx.padding) else 0, + mpegFrames = idx.n, + _buf = b, + _idx = idx, + _st = Core.newState(), + _pcm = buffer.create(1152 * 2 * 4), + _cur = 0, + _pcmPos = 0, + _pcmEnd = 0, + _minAbs = delay, + _endAbs = delay + total, + _pos = 0, + }, Decoder) + return self +end + + +-- decodes frames until one has samples inside [minAbs, endAbs); false at the end +local function fill(self: Decoder): boolean + local idx = self._idx + local n = idx.n + local spf = idx.spf + local st = self._st + while self._cur < n do + local f = self._cur + self._cur = f + 1 + local flags = ru8(idx.flags, f) + if band(flags, FLAG_RESET) ~= 0 then + Core.reset(st) + end + local a = ru32(idx.out, f * 4) + if a >= self._endAbs then + self._cur = n + return false + end + local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm) + if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then + if Core.lastChannels < self.channels then + Core.upmix(self._pcm, got) + end + local lo = max(a, self._minAbs) + local hi = min(a + spf, self._endAbs) + if hi > lo then + self._pcmPos = lo - a + self._pcmEnd = hi - a + return true + end + end + end + return false +end + +-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. +-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a +-- smaller out is ignored. +function Decoder.read(self: Decoder, maxFrames: number?, out: buffer?): (buffer, number) + local ch = self.channels + local want = tonumber(maxFrames) or 4096 + if want ~= want then + want = 0 + end + want = floor(max(0, min(want, self.frames - self._pos))) + if out and buffer.len(out) < want * ch * 4 then + out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + end + local dst = out or buffer.create(want * ch * 4) + local got = 0 + local pcm = self._pcm + while got < want do + if self._pcmPos >= self._pcmEnd then + if not fill(self) then + break + end + end + local k = min(want - got, self._pcmEnd - self._pcmPos) + buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4) + got += k + self._pcmPos += k + end + self._pos += got + if not out and got < want then + local r = buffer.create(got * ch * 4) + buffer.copy(r, 0, dst, 0, got * ch * 4) + dst = r + end + return dst, got +end + +-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier +-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. +function Decoder.seek(self: Decoder, seconds: number) + local hz = self.sampleRate + local target = floor((tonumber(seconds) or 0) * hz + 0.5) + target = max(0, min(target, self.frames)) + self:seekFrame(target) +end + +-- Seeks to a sample frame (0 .. frames). +function Decoder.seekFrame(self: Decoder, target: number) + target = tonumber(target) or 0 + if target ~= target then + target = 0 + end + target = max(0, min(floor(target), self.frames)) + local idx = self._idx + local abs = self.delay + target + self._pos = target + self._minAbs = abs + self._pcmPos, self._pcmEnd = 0, 0 + Core.reset(self._st) + local n = idx.n + if abs >= self._endAbs or n == 0 then + self._cur = n + return + end + -- last frame starting at or before abs + local lo, hi = 0, n - 1 + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ru32(idx.out, mid * 4) <= abs then + lo = mid + else + hi = mid - 1 + end + end + local j = lo + -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data + -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets + local need = if idx.layer == 3 then 511 else 0 + local s, back, acc = j, 0, 0 + while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do + if back >= 2 and acc >= need then + break + end + s -= 1 + back += 1 + if back >= 2 then + acc += ru16(idx.main, s * 2) + end + end + self._cur = s +end + +-- Current position: (seconds, sample frame) +function Decoder.position(self: Decoder): (number, number) + return self._pos / self.sampleRate, self._pos +end + +-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) +function Decoder.readAll(self: Decoder): (buffer, number) + return self:read(max(0, self.frames - self._pos)) +end + +Stream.Decoder = Decoder + +return Stream +end +__FILES["audio/mp3/Tags"] = function() + + +-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / +-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way +-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift +local ru8 = buffer.readu8 + +local Tags = {} + +-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions) +local GENRES = { + [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", + "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", + "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", + "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", + "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", + "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", + "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", + "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", + "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", + "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", + "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", + "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", + "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", + "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", + "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", + "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", + "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop", +} +Tags.GENRES = GENRES + +-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents) +local FIELDS = { + TIT2 = "title", TT2 = "title", + TPE1 = "artist", TP1 = "artist", + TALB = "album", TAL = "album", + TPE2 = "albumartist", TP2 = "albumartist", + TYER = "date", TYE = "date", TDRC = "date", + TRCK = "track", TRK = "track", + TPOS = "disc", TPA = "disc", + TCON = "genre", TCO = "genre", + TCOM = "composer", TCM = "composer", + COMM = "comment", COM = "comment", +} + +local function utf8char(cp: number): string + if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + cp = 0xFFFD + end + return utf8.char(cp) +end + +-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8) +local function decodeText(b: buffer, i: number, j: number, enc: number): string + local out = {} + if enc == 1 or enc == 2 then + local le = false + if enc == 1 and j - i >= 2 then + local b0, b1 = ru8(b, i), ru8(b, i + 1) + if b0 == 0xFF and b1 == 0xFE then + le = true + i += 2 + elseif b0 == 0xFE and b1 == 0xFF then + i += 2 + else + le = true -- no BOM: assume little-endian (what most taggers write) + end + end + local pending = 0 + while i + 1 < j do + local u = if le then bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) else bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + pending = u + else + if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then + u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00) + end + pending = 0 + table.insert(out, if u == 0 then "\0" else utf8char(u)) + end + end + elseif enc == 3 then + local s = buffer.readstring(b, i, j - i) + if utf8.len(s) then + return s + end + enc = 0 -- invalid UTF-8: fall back to latin-1 + end + if enc == 0 then + for k = i, j - 1 do + local c = ru8(b, k) + table.insert(out, if c < 0x80 then string.char(c) else utf8char(c)) + end + end + return table.concat(out) +end + +-- trim trailing NULs / spaces, join multi-value NUL separators with " / " +local function clean(s: string): string + s = string.gsub(s, "[%z%s]+$", "") + s = string.gsub(s, "%z+", " / ") + return s +end + +-- "(17)", "(17)Rock", "17" -> "Rock" +local function genreName(s: string): string + local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$")) + if n and GENRES[n] then + return GENRES[n] + end + local rest = string.match(s, "^%(%d+%)(.+)$") + return rest or s +end + +local function syncsafe(b: buffer, o: number): number + return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F)) +end + +local function be32(b: buffer, o: number): number + return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3)) +end + +-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer +local function deunsync(b: buffer, i: number, j: number): buffer + local out = buffer.create(math.max(0, j - i)) + local n = 0 + local k = i + while k < j do + local c = ru8(b, k) + buffer.writeu8(out, n, c) + n += 1 + k += if c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 then 2 else 1 + end + local r = buffer.create(n) + buffer.copy(r, 0, out, 0, n) + return r +end + +-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0 +function Tags.id3v2Size(b: buffer, o: number, len: number): number + if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then + return 0 + end + if band(ru8(b, o + 5), 15) ~= 0 then + return 0 + end + for k = 6, 9 do + if band(ru8(b, o + k), 0x80) ~= 0 then + return 0 + end + end + local size = syncsafe(b, o + 6) + 10 + if band(ru8(b, o + 5), 16) ~= 0 then + size += 10 + end + return size +end + +local function setField(tags: any, id: string, text: string) + tags.raw[id] = text + local f = FIELDS[id] + if f and tags[f] == nil and text ~= "" then + tags[f] = if f == "genre" then genreName(text) else text + end +end + +-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags +local function parseV2(b: buffer, o: number, size: number, tags: any) + local ver = ru8(b, o + 3) + local flags = ru8(b, o + 5) + if ver < 2 or ver > 4 then + return + end + tags.id3v2 = "2." .. ver + local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b)) + local body = b + local p, e = o + 10, bodyEnd + if band(flags, 0x80) ~= 0 and ver < 4 then + body = deunsync(b, p, e) + 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) + p += if ver == 3 then be32(body, p) + 4 else syncsafe(body, p) + end + local hdr = if ver == 2 then 6 else 10 + while p + hdr <= e do + local c0 = ru8(body, p) + if c0 == 0 then + break -- padding + end + local id, fsize, fflags + if ver == 2 then + id = buffer.readstring(body, p, 3) + fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5)) + fflags = 0 + else + id = buffer.readstring(body, p, 4) + fsize = if ver == 4 then syncsafe(body, p + 4) else be32(body, p + 4) + fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9)) + end + if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then + break + end + local fs, fe = p + hdr, p + hdr + fsize + local fb = body + local skip = false + if ver == 3 then + skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted + elseif ver == 4 then + skip = band(fflags, 0x000C) ~= 0 + if not skip and band(fflags, 0x0001) ~= 0 then + fs += 4 -- data length indicator + end + if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then + fb = deunsync(body, fs, fe) + fs = 0 + fe = buffer.len(fb) + end + end + if not skip and fs < fe then + local first = string.sub(id, 1, 1) + local enc = ru8(fb, fs) + if first == "T" and id ~= "TXXX" and id ~= "TXX" then + setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc))) + elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then + -- encoding, language[3], short description (NUL-terminated in the encoding), text + local q = fs + 4 + local wide = enc == 1 or enc == 2 + while q < fe do + if wide then + if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then + q += 2 + break + end + q += 2 + else + if ru8(fb, q) == 0 then + q += 1 + break + end + q += 1 + end + end + if q <= fe then + setField(tags, id, clean(decodeText(fb, q, fe, enc))) + end + end + end + p += hdr + fsize + end +end + +local function v1String(b: buffer, o: number, n: number): string + return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) +end + +-- Parses tags and returns (tags, audio start, audio end) for the buffer b. +-- 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) + local tags: any = { raw = {} } + local start, stop = 0, len + local v2 = Tags.id3v2Size(b, 0, len) + if v2 > 0 then + pcall(parseV2, b, 0, v2, tags) + start = math.min(v2, len) + end + -- mp3dec_skip_id3v1 on what follows the ID3v2 tag + local size = stop - start + if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then + local o = start + size - 128 + tags.id3v1 = true + local v1: { [string]: any } = { + title = v1String(b, o + 3, 30), + artist = v1String(b, o + 33, 30), + album = v1String(b, o + 63, 30), + 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) + v1.track = tostring(ru8(b, o + 126)) + else + v1.comment = v1String(b, o + 97, 30) + end + local g = ru8(b, o + 127) + if GENRES[g] then + v1.genre = GENRES[g] + end + for k, v in v1 do + if tags[k] == nil and v ~= "" then + tags[k] = v + end + end + size -= 128 + if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then + size -= 227 + end + end + if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then + size -= 32 + local t = start + size + 12 + local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24)) + if size >= tagSize then + size -= tagSize + end + tags.ape = true + end + stop = start + size + return tags, start, stop +end + +return Tags +end +__FILES["audio/mpc"] = function() + +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec +-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / +-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking +-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags +-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: +-- writing, SV4 - SV6 (UNSUPPORTED), chapters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local Musepack = __include("codecs/audio/Musepack") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpc = { + name = "mpc", + category = "audio", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- Err.LIMIT past this many output sample frames (default 2^31) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the size of an ID3v2 tag at p (0 if none) +local function id3v2(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local n = 10 + for i = 6, 9 do + n += bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) + end + return n + (if bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 then 10 else 0) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpc.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3v2(b, p, limit) + local v = Musepack.magic(b, p, limit) + if v == 8 then + return 1 + end + return if v == 7 then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mpc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o: DecodeOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + local start = base + id3v2(b, base, limit) + local tags, info = ApeTag.find(b, start, limit) + local stop = if info and info.start > start then info.start else limit + local s, err = Musepack.open(b, start, stop) + if not s then + return nil, err + end + if s.frames > (o.maxFrames or 2 ^ 31) then + return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") + end + local duration = s.frames / s.sampleRate + local dec = { + sampleRate = s.sampleRate, + channels = s.channels, + frames = s.frames, + duration = duration, + bitrate = if duration > 0 then math.floor(s.bytes * 8 / duration + 0.5) else 0, + tags = tags or {}, + codec = "musepack", + version = s.version, + profile = s.profile, + gain = s.gain, + } + return Stream.packets(dec, s :: any) +end + +function Mpc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Mpc.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) +end + +return Mpc +end +__FILES["audio/opus"] = function() + +-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a +-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK +-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). +-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, +-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms +-- pre-roll), damaged files (concealment). Output is always 48 kHz f32. +-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant +-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. +-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics +-- 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 +-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets +-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Decoder = __include("codecs/audio/Opus/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Pcm = __include("codecs/audio/Pcm") +local RangeDecoder = __include("codecs/entropy/RangeCoder/Decoder") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") +local Encode = __include("audio/opus/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Opus = { + name = "opus", + category = "audio", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 +type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true; false decodes damaged files) + stereo: boolean?, -- downmix more than 2 channels to stereo (default false; dec.channels is then 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local SAMPLE_RATE = 48000 + +-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile +local DOWNMIX = { + [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, + [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, + [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, + [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, + [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, + [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, +} +local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 +local MAX_PACKET = 5760 -- 120 ms + +type Head = { + version: number, + channels: number, + preSkip: number, + inputSampleRate: number, + outputGain: number, -- Q7.8 dB + mappingFamily: number, + streams: number, + coupled: number, + mapping: { number }, +} + +-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. +local function parseHead(b: buffer, off: number, size: number): (Head?, string?) + if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then + return nil, "not an OpusHead packet" + end + local version = buffer.readu8(b, off + 8) + if bit32.rshift(version, 4) ~= 0 then + return nil, "unsupported OpusHead version " .. version + end + local channels = buffer.readu8(b, off + 9) + if channels < 1 then + return nil, "OpusHead: zero channels" + end + local head: Head = { + version = version, + channels = channels, + preSkip = buffer.readu16(b, off + 10), + inputSampleRate = buffer.readu32(b, off + 12), + outputGain = buffer.readi16(b, off + 16), + mappingFamily = buffer.readu8(b, off + 18), + streams = 1, + coupled = channels - 1, + mapping = {}, + } + if head.mappingFamily == 0 then + if channels > 2 then + return nil, "OpusHead: mapping family 0 with more than 2 channels" + end + head.mapping = if channels == 2 then { 0, 1 } else { 0 } + else + if head.mappingFamily == 3 then + return nil, "unsupported channel mapping family 3 (projection)" + end + if size < 21 + channels then + return nil, "OpusHead: truncated channel mapping table" + end + head.streams = buffer.readu8(b, off + 19) + head.coupled = buffer.readu8(b, off + 20) + if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then + return nil, "OpusHead: bad stream counts" + end + for c = 0, channels - 1 do + local m = buffer.readu8(b, off + 21 + c) + if m ~= 255 and m >= head.streams + head.coupled then + return nil, "OpusHead: bad channel mapping" + end + head.mapping[c + 1] = m + end + end + return head, nil +end + +-- 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 "", {}, {} + end + local p = off + 8 + local e = off + size + local vlen = buffer.readu32(b, p) + p += 4 + if p + vlen > e then + return "", {}, {} + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 <= e then + 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) + p += 4 + if p + l > e then + break + end + table.insert(list, buffer.readstring(b, p, l)) + p += l + end + end + local tags, raw = VorbisComment.tags(list) + return vendor, tags, raw +end + +Opus.Decoder = Decoder +Opus.Packet = Packet +Opus.RangeDecoder = RangeDecoder +Opus.Celt = Celt +Opus.Silk = Silk +Opus.parseHead = parseHead +Opus.parseTags = parseTags +Opus.SAMPLE_RATE = SAMPLE_RATE + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when the file starts with an Ogg page whose first packet is an OpusHead +function Opus.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local nseg = r:peekU8(26) + if nseg < 1 then + return 0 + end + return if r:peek(8, 27 + nseg) == "OpusHead" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) +function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Opus.open(r, opts) + if not dec then + return nil, err + end + 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 +-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) +function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) + return Encode.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- Decodes the next packet into the pending buffer. Returns false at the end of the stream. +local function decodeNext(self: any): boolean + local p = self.demux:nextPacket(self.serial) + if p == nil then + return false + end + local n + if p.size > 0 then + n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) + else + n = -1 + end + if n < 0 then + -- corrupt or empty packet: conceal for its nominal duration + local dur = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else -1 + if dur <= 0 then + dur = self.lastDuration + end + n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) + if n < 0 then + n = dur + for i = 1, n * self.channels do + self.pend[i] = 0 + end + end + end + self.lastDuration = n + self.pendStart = self.decoded + self.pendLen = n + self.pendPos = 0 + self.decoded += n + return true +end + +-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if +-- given and big enough) is filled instead of a new buffer. +function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, number) + local ch = self.channels + local mf = if type(maxFrames) == "number" and maxFrames == maxFrames then maxFrames else 0 + local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) + local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 + local out = if reuse then into :: buffer else buffer.create(want * ch * 4) + local got = 0 + local gain = self.gain + while got < want do + if self.pendPos >= self.pendLen then + if not decodeNext(self) then + break + end + end + -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) + local s = self.pendStart + self.pendPos + if s < self.next then + self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) + continue + end + local n = math.min(self.pendLen - self.pendPos, want - got) + if self.downmix then + 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 + self.next += n + end + if got < want then + if not reuse then + local trimmed = buffer.create(got * ch * 4) + buffer.copy(trimmed, 0, out, 0, got * ch * 4) + out = trimmed + end + self.endSample = self.next -- the stream ended early (truncated file) + end + return out, got +end + +-- current playback position in seconds +function Stream.position(self: any): number + return (self.next - self.preSkip) / SAMPLE_RATE +end + +-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll +function Stream.seek(self: any, seconds: number) + local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0 + local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) + p = math.min(p, self.frames) + local target = p + self.preSkip -- decoded-sample index of the wanted sample + Decoder.resetMultistream(self.ms) + self.pendLen, self.pendPos = 0, 0 + local g = target - PREROLL + self.startGranule + local start = -1 + if g > self.startGranule then + start = self.demux:seekGranule(self.serial, g) or -1 + end + if start < 0 then + self.demux:rewind(self.serial) + self.demux:nextPacket(self.serial) -- OpusHead + self.demux:nextPacket(self.serial) -- OpusTags + self.decoded = 0 + else + self.decoded = start - self.startGranule + end + self.pendStart = self.decoded + self.next = target +end + +-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) +function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("opus") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") + end + local hp = demux:nextPacket(serial) + if hp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusHead") + end + local head, herr = parseHead(hp.data, hp.offset, hp.size) + if not head then + return nil, Err.new(if string.find(herr or "", "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, herr or "bad OpusHead") + end + local tp = demux:nextPacket(serial) + if tp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusTags") + end + 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 + while true do + local p = demux:nextPacket(serial) + if p == nil then + break + end + local d = if p.size > 0 then Packet.samples(p.data, p.offset, p.size) else 0 + sum += math.max(d, 0) + if p.granule ~= -1 then + startGranule = math.max(0, p.granule - sum) + break + end + end + demux:rewind(serial) + demux:nextPacket(serial) + demux:nextPacket(serial) + local info = demux:stream(serial) + local last = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else startGranule + local frames = math.max(0, last - startGranule - head.preSkip) + local downmix = nil + if opts and opts.stereo and head.channels > 2 then + downmix = DOWNMIX[head.channels] + if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally + downmix = table.create(head.channels * 2, 1 / head.channels) + end + end + local self = setmetatable({ + demux = demux, + serial = serial, + 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, + downmix = downmix, + frames = frames, + duration = frames / SAMPLE_RATE, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) else 0, + preSkip = head.preSkip, + startGranule = startGranule, + gain = 10 ^ (head.outputGain / (20 * 256)), + ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), + pend = table.create(MAX_PACKET * head.channels, 0), + pendStart = 0, + pendLen = 0, + pendPos = 0, + decoded = 0, -- decoded-sample index of the next packet's first sample + next = head.preSkip, -- decoded-sample index of the next sample read() returns + endSample = head.preSkip + frames, + lastDuration = 960, + }, Stream) + return self, nil +end + + +return Opus +end +__FILES["audio/opus/Encode"] = function() + +-- 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 (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in +-- rosetta. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") +local VorbisComment = __include("codecs/audio/VorbisComment") +local CeltEncoder = __include("codecs/audio/Opus/CeltEncoder") + +local Encode = {} + +type Options = { + bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant); values below 1000 + -- are kbit/s (96 = 96000), as for every encoder's bitrate option + tags: { [string]: string }?, -- default: the audio's tags + vendor: string?, -- OpusTags vendor (default "rosetta") + serial: number?, -- Ogg stream serial (default 0x4f707573) +} + +local floor = math.floor + +-- encode(audio | decoder, opts) -> buffer | nil, Err +function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?) + local o: Options = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + 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 = src.sampleRate + if rate < 1000 or rate > 768000 then + return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) + end + local bitrate = o.bitrate or 64000 * ch + if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then + bitrate *= 1000 -- kbit/s + end + if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then + return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") + end + -- the whole input at 48 kHz (codecs/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 + src = rs + end + 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 + local packets = (n48 + preSkip + FRAME - 1) // FRAME + -- zero padding to whole frames + for i = n48 * ch + 1, packets * FRAME * ch do + pcm[i] = 0 + end + local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) + local st = CeltEncoder.new(ch) + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(o.serial or 0x4f707573) + -- OpusHead + local head = Bytes.writer(19) + head:string("OpusHead") + head:u8(1) + head:u8(ch) + head:u16le(preSkip) + head:u32le(floor(rate)) + head:u16le(0) + head:u8(0) + s:packet(head:finish(), 0, { flush = true }) + -- OpusTags + local tags = o.tags or src.tags or {} + local tw = Bytes.writer(256) + tw:string("OpusTags") + local vendor = o.vendor or "rosetta" + tw:u32le(#vendor) + tw:string(vendor) + local fields = VorbisComment.fields(tags) + tw:u32le(#fields) + for _, field in fields do + tw:u32le(#field) + tw:string(field) + end + s:packet(tw:finish(), 0, { flush = true }) + -- audio + local toc = 31 * 8 + (if ch == 2 then 4 else 0) + for p = 0, packets - 1 do + local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) + local pkt = buffer.create(bytes + 1) + buffer.writeu8(pkt, 0, toc) + buffer.copy(pkt, 1, frame, 0, bytes) + local last = p == packets - 1 + local granule = if last then preSkip + n48 else (p + 1) * FRAME + s:packet(pkt, granule, { eos = last }) + end + return mux:finish(), nil +end + +return Encode +end +__FILES["audio/qoa"] = function() + +-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in +-- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order +-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its +-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): +-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel +-- count or rate change mid-stream (Err.UNSUPPORTED). +-- +-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder +-- local file = Qoa.encode(audio) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Codec = __include("codecs/audio/Qoa") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoa = { + name = "qoa", + category = "audio", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this many sample frames (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoa.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoaf" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoa.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Qoa.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoa.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then + return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") + end + local FL = Codec.FRAME_LEN + local w = Bytes.writer(8 + (if src.frames > 0 then Codec.frameSize(ch, (src.frames + 19) // 20) + 24 * ch * (src.frames // FL + 1) else 65536)) + w:string("qoaf") + w:u32be(0) + local lms = Codec.newLms(ch) + local fb = buffer.create(FL * ch * 4) + local tmp: buffer? = nil + local total = 0 + while true do + -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them + local have = 0 + while have < FL do + local b, n = src:read(FL - have, tmp) + if n <= 0 then + break + end + tmp = b + buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) + have += n + end + if have == 0 then + break + end + local at = w:reserve(Codec.frameSize(ch, (have + 19) // 20)) + w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) + total += have + if have < FL then + break + end + end + if src.err then + return nil, src.err + end + if total == 0 then + return nil, Err.new(Err.ARG, "QOA needs at least one sample") + end + if total >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "too many samples for QOA") + end + local out = w:finish() + buffer.writeu32(out, 4, bit32.byteswap(total)) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Qoa.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + if h:string(4) ~= "qoaf" then + return nil, Err.new(Err.CORRUPT, "not a QOA file") + end + local declared = h:u32be() + if h.err then + return nil, h.err + end + local buf = r.buf + -- the frame index: offsets, first frames + local offs, starts = {}, {} + local p, total = r.base + 8, 0 + local ch, rate = 0, 0 + while p < r.limit do + local info, msg = Codec.frameInfo(buf, p, r.limit - p) + if not info then + if #offs == 0 then + return nil, Err.from(msg, p - r.base) + end + break -- a cut or damaged tail: keep the whole frames + end + if #offs == 0 then + ch, rate = info.channels, info.rate + elseif info.channels ~= ch or info.rate ~= rate then + return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) + end + table.insert(offs, p) + table.insert(starts, total) + total += info.samples + p += info.size + if declared > 0 and total >= declared then + break + end + end + if #offs == 0 then + return nil, Err.new(Err.TRUNCATED, "no frames") + end + local frames = if declared > 0 then math.min(declared, total) else total + local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), + tags = {}, + streaming = declared == 0, + } + local limit = r.limit + return Stream.packets(dec, { + count = #offs, + start = function(i: number): number + return if i > #offs then total else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) + if not n then + return nil, Err.from(msg, offs[i] - r.base) + end + return n, nil + end, + pcm = function(): buffer + return pcm + end, + reset = function() end, + stop = frames, + }) +end + +return Qoa +end +__FILES["audio/tta"] = function() + +-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the +-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). +-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. +-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. +-- +-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt +-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local TtaCodec = __include("codecs/audio/Tta") + +-- ------------------------------------------------------------------------------------------------ contract +local Tta = { + name = "tta", + category = "audio", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- the size of an ID3v2 tag at the reader's start (0 when none) +local function id3Size(r: Bytes.Reader): number + if r:peek(3) ~= "ID3" then + return 0 + end + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return 10 + sz + (if footer then 10 else 0) +end + +function Tta.sniff(r: Bytes.Reader): number + return if r:peek(4, id3Size(r)) == "TTA1" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Tta.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Tta.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Tta.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local at = base + id3Size(r) + local tags, tagInfo = ApeTag.find(buf, at, limit) + local stop = if tagInfo then tagInfo.start else limit + local info, err = TtaCodec.info(buf, at, stop) + if not info then + return nil, err + end + if info.channels * info.frameLength > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") + end + local codec = TtaCodec.decoder(info, stop) + local frames = info.samples + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = false, + source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, + } + local fl, count = info.frameLength, info.frames + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then frames else (i - 1) * fl + end, + decode = function(i: number): (number?, Err.Err?) + return codec:frame(buf, i) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = 1 / 2 ^ (info.bitsPerSample - 1), + ints = true, + }) +end + +return Tta +end +__FILES["audio/vag"] = function() + +-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same +-- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow +-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono +-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / +-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. +-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame +-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game +-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). +-- +-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) +-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Vag = { + name = "vag", + category = "audio", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Loop = { start: number, stop: number } +type DecodeOptions = { + maxFrames: number?, -- decode(): Err.LIMIT past this (default 2^28) +} +type EncodeOptions = { + loop: Loop?, -- loop points in frames of the input (stop exclusive), rounded out to 28-sample frames; default: the + -- source's meta.source.loop, else none + name: string?, -- the 16-byte name field (default: tags.title) + interleave: number?, -- stereo: bytes per channel block (default 2048, a multiple of 16) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEVAG = { [0x00020001] = true, [0x00030000] = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Vag.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "VAGp" or m == "VAGi" or m == "KVAG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vag.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vag.open(r) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vag.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 2 then + return nil, Err.new(Err.ARG, "VAG holds mono or stereo") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local il = o.interleave or 2048 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + local loop = o.loop + local v = value :: any + if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then + loop = v.meta.source.loop + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + local nf = (n + 27) // 28 -- data frames (after the blank one) + local ls, le = -1, -1 + if loop then + if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + ls, le = loop.start // 28, (loop.stop + 27) // 28 - 1 + if le <= ls then + return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") + end + end + local chBytes = (nf + 1) * 16 + local stride = if ch == 1 then chBytes else (chBytes + il - 1) // il * il + local start = if ch == 1 then 0x30 else 0x800 + local out = buffer.create(start + stride * ch) + local title = o.name or (a.tags and a.tags.title) or "" + buffer.writestring(out, 0, if ch == 1 then "VAGp" else "VAGi") + buffer.writeu32(out, 4, bit32.byteswap(0x20)) + if ch == 2 then + buffer.writeu32(out, 8, il) + end + buffer.writeu32(out, 0x0C, bit32.byteswap(if ch == 1 then chBytes else stride)) + buffer.writeu32(out, 0x10, bit32.byteswap(rate)) + buffer.writestring(out, 0x20, string.sub(title, 1, 16)) + local st = buffer.create(8 * ch) + local plane = buffer.create(chBytes) + for c = 0, ch - 1 do + buffer.fill(plane, 0, 0) + Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) + for k = 0, nf - 1 do + local flag = if k == ls then 6 elseif k == le then 3 elseif k > ls and k < le then 2 else 0 + if not loop and k == nf - 1 then + flag = 1 + end + buffer.writeu8(plane, 16 + k * 16 + 1, flag) + end + if ch == 1 then + buffer.copy(out, start, plane, 0, chBytes) + else + for b = 0, stride // il - 1 do + local take = math.clamp(chBytes - b * il, 0, il) + if take > 0 then + buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) + end + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end +-- flag 3), or nil +local function findLoop(buf: buffer, p: number, frames: number, il: number, ch: number): Loop? + local ls, le = -1, -1 + for k = 0, frames - 1 do + local off = p + (k * 16) // il * il * ch + (k * 16) % il + local flag = bit32.band(buffer.readu8(buf, off + 1), 15) + if flag == 6 and ls < 0 then + ls = k * 28 + elseif flag == 3 and le < 0 then + le = k * 28 + 28 + if ls >= 0 then + break + end + end + end + return if ls >= 0 and le > ls then { start = ls, stop = le } else nil +end + +function Vag.open(r: Bytes.Reader, _opts: any?): (Types.Decoder?, Err.Err?) + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + local magic = h:string(4) + local total = r.limit - r.base + if magic == "KVAG" then + local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() + if h.err then + return nil, h.err + end + if rate < 1 or stereo > 1 then + return nil, Err.new(Err.CORRUPT, "bad KVAG header") + end + local dec: any = { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } + local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) + if d then + d.bitrate = rate * 4 * (stereo + 1) + end + return d, err + end + if magic ~= "VAGp" and magic ~= "VAGi" then + return nil, Err.new(Err.CORRUPT, "not a VAG file") + end + local version, il = h:u32be(), h:u32le() + local chSize, rate = h:u32be(), h:u32be() + local name = r:sub(0x20, 16):cstring(16) + if h.err then + return nil, h.err + end + if HEVAG[version] then + return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local ch, start = 1, 0x30 + if magic == "VAGi" then + ch, start = 2, 0x800 + if il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) + end + else + il = 16 + end + if total < start then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + local size = math.min(chSize * ch, total - start) + local p = r.base + start + local frames = math.min(chSize // 16, (size // (il * ch)) * (il // 16) + math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) // 16) + local loop = if magic == "VAGp" then findLoop(r.buf, p, frames, il, ch) else nil -- vgmstream: VAGi never loops + local tags = {} + if name ~= "" then + tags.title = name + end + local dec: any = { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } + local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) + if d then + d.bitrate = rate * 16 * 8 * ch // 28 + end + return d, err +end + +return Vag +end +__FILES["audio/voc"] = function() + +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +type DecodeOptions = { + maxFrames: number?, -- refuse more sample frames (default 2^28) +} +type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "alaw" | "ulaw")?, -- default "s16" +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Creative Voice File\26" +local T9_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS: { [number]: string } = { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b: buffer, o: number): number + return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r: Bytes.Reader): number + return if r:peek(20) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Segment = { at: number, frames: number, fmt: string? } -- fmt nil: silence + +function Voc.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt: string? = nil + local codec = -1 + local segments: { Segment } = {} + local total = 0 + local truncated = false + local tags: Types.Tags = {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at: number, bytes: number, fmt: string?, ch: number, sr: number): Err.Err? + if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = if fmt then bytes // (ch * Pcm.Convert.SIZE[fmt]) else bytes + if frames > 0 then + total += frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err: Err.Err? = nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, 1000000 // (256 - div) + if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, if channels > 0 then channels else 1, if rate > 0 then rate else 1000000 // (256 - div)) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = if tags.comment then tags.comment .. "\n" .. s else s + elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = 256000000 // (extChannels * (65536 - tc)) + elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new(if truncated then Err.TRUNCATED else Err.CORRUPT, "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in segments do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt :: string, n, a.samples, o) + end -- silence: the buffer is already zero + o += n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", version // 256, version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = if lastFmt == "s16le" then 16 else 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2]] + local frameBytes = size * src.channels + local framesPerBlock = MAX_BLOCK // frameBytes + local blockAt, blockFrames = -1, 0 + local tmp: buffer? = nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames += take + i += take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (len // 256) % 256) + w:setU8(blockAt + 3, len // 65536) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = Pcm.audioDecoder(a) :: any + dec.source = a.meta.source + return dec, nil +end + +return Voc +end +__FILES["audio/vorbis"] = function() + +-- 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/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, +-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Packet = __include("codecs/audio/Vorbis/Packet") +local Encode = __include("audio/vorbis/Encode") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "vorbis", + category = "audio", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + 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 }, +} + +type OpenOptions = { + verify: boolean?, -- check the Ogg page CRCs (default true) +} +type EncodeOptions = { + quality: number?, -- -1 .. 10 (default 3): the floor sits 2 * quality - 1 dB under the band energies (8 dB + -- less at the top of the spectrum), which sets the residue's quantization step + serial: number?, -- the Ogg stream serial number (default 0x464C5541) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- 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 + 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, 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, 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, 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, nil, Err.new(code, serr or "bad setup header") + end + local tags, raw = VorbisComment.tags(comments or {}) + return id, setup, vendor, tags, raw, nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r: Bytes.Reader): number + if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return if buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err +function Vorbis.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o: EncodeOptions = opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src :: any, { quality = q, vendor = "rosetta Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) +local function push(self: any, arrays: { { number } }, g0: number, count: number, hi: number) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self: any, count: number): { { number } } + local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +-- decode packets until something is queued; false at the end of the stream +local function decodeMore(self: any): boolean + local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = if p.eos and p.granule >= 0 then p.granule else math.huge + if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in self.pend do + push(self, c[1], g, c[2], endG) + g += c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos += count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self: any, n: number, out: buffer?): (buffer, number) + local ch = self.channels + n = math.max(0, math.floor(n)) + local b = if out and buffer.len(out) >= n * ch * 4 then out else buffer.create(n * ch * 4) + local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + 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[order[c]] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o += ch * 4 + end + end + got += take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4] += take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self: any): number + return (self.next - self.startG) / self.sampleRate +end + +-- back to the first audio packet +local function restart(self: any) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self: any, seconds: number) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount += count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in self.pend do + push(self, c[1], g0, c[2], math.huge) + g0 += c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + local demux, derr = Ogg.open(r, if opts and opts.verify == false then { verify = false } else nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum += prev // 4 + bs // 4 + end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = if info and info.lastGranule and info.lastGranule >= 0 then info.lastGranule else -1 + local startG = math.max(base, 0) + local frames = if lastG >= 0 then math.max(0, lastG - startG) else 0 + local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor(demux.size * 8 / (frames / rate)) else id.bitrateNominal, + 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, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three +-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. +-- local pd = Vorbis.packetDecoder(h1, h2, h3) +-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] +-- pd:reset() -- after a seek +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)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + 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 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self: any) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis +end +__FILES["audio/vorbis/Encode"] = @native function() + + + +-- 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/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 = __include("codecs/audio/Mdct") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Ogg = __include("containers/Ogg") +local Tables = __include("codecs/audio/Vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 + +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +@native local function newW(size: number): W + return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +@native local function put(w: W, v: number, n: number) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +@native local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +@native local function putString(w: W, s: string) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +@native local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + lengths: { number }, + codes: { number }, -- bit-reversed codewords (ready for the LSB-first writer) + lookup: number, -- 0 or 1 + minimum: number, + delta: number, + values: number, -- lookup1 values per dimension +} + +-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) +@native local function huffmanLengths(w: { number }): { number } + local n = #w + local total = 0 + for i = 1, n do + total += w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, @native function(a: number, b: number): boolean + if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 -- leaves, ascending + local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local nextId = n + @native local function pop(): number + local a = if h1 <= n then q1[h1] else nil + local b = if h2 <= t2 then q2[h2] else nil + if a and (not b or weight[a] <= weight[b]) then + h1 += 1 + return a + end + h2 += 1 + return b :: number + end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId += 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 += 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d += 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +@native local function assign(lens: { number }): { number } + local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in lens do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +@native local function makeBook(dims: number, entries: number, weight: (number) -> number, lookup: number, minimum: number, delta: number, values: number): Book + local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) +@native local function vqBook(dims: number, h: number, scale: number, s: number, zeroBoost: number): Book + local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, @native function(e: number): number + local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = x // values + wt *= exp(-abs(v) / s) * (if v == 0 then zeroBoost else 1) + end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, @native function(e: number): number + return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, @native function(e: number): number + return CLASS_W[e % NCLASS + 1] * CLASS_W[e // NCLASS + 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +@native local function float32Pack(x: number): number + local sign = if x < 0 then 2147483648 else 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m /= 2 + e += 1 + end + return sign + e * 2097152 + floor(m) +end + +@native local function writeBook(w: W, b: Book) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +@native local function putEntry(w: W, b: Book, e: number) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS: { number } = { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x += 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + -- bisection order over the sorted list + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh += 1 + if r[1] <= r[2] then + local m = (r[1] + r[2]) // 2 + table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = (NPOSTS - 2) // 4 -- 7 partitions of one class with 4 dimensions +local SORTED: { number } = table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, @native function(a: number, b: number): boolean + return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +@native local function yOf(db: number): number + local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = (abs(dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +@native local function renderFloor(Y: { number }, used: { boolean }, F: { number }) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do + local j = SORTED[q] + if not used[j] then + continue + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + F[x + 1] = Tables[y % 256 + 1] + x += 1 + end + end + lx, ly = hx, hy + end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +@native local function floorVal(Y: { number }, j: number): number + local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + local cands = { if d > 0 then 2 * d else -2 * d - 1, d + lowroom, -d + highroom - 1 } + for _, v in cands do + if v > 0 and v < RANGE then + local got + if v >= room then + got = if highroom > lowroom then v - lowroom + pred else pred - v + highroom - 1 + elseif v % 2 == 1 then + got = pred - (v + 1) // 2 + else + got = pred + v // 2 + end + if got == t then + return v + end + end + end + return 0 -- unreachable for t in range; fall back to the prediction +end + +-- ------------------------------------------------------------------------------------------------ headers +@native local function identHeader(ch: number, rate: number, nominal: number): buffer + local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +@native local function commentHeader(vendor: string, tags: { [string]: string }): buffer + local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, vendor) + local fields = VorbisComment.fields(tags) + put(w, #fields, 32) + for _, s in fields do + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +@native local function setupHeader(ch: number): buffer + local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in BOOKS do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits += POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, bits // 8, 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end + +-- ------------------------------------------------------------------------------------------------ encoder +type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + quality: number, -- -1 .. 10 + vendor: string, + serial: number, +} + +-- the residue of one partition: vectors of each pass for class c +@native local function writePartition(w: W, v: { number }, o: number, psize: number, c: number, pass: number) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, (book.values - 1) // 2 + local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(x // scale, -h, h) + end + v[o + i + k + 1] = x - q * scale + e += (q + h) * m + m *= values + end + putEntry(w, book, e) + i += dims + end +end + +@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + 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: { { 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: { { 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) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = N2 * ch // psize + local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + -- shift in the next 1024 input samples (zeros past the end) + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got += take + pendN -= take + pendOff += take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total += got + if srcDone and lastWanted < 0 then + lastWanted = (total + N2 - 1) // N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) + end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) + -- MDCT per channel + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy += xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = table.find(SORTED, j) :: number + local lo = if idx > 1 then (POSTS[SORTED[idx - 1]] + x) // 2 else 0 + local hi = if idx < NPOSTS then (POSTS[SORTED[idx + 1]] + x) // 2 else N2 - 1 + if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s += xc[i] * xc[i] + end + s /= (hi - lo + 1) + if s > e then + e = s + end + end + local db = if e > 0 then 10 * math.log10(e) - snrDb + 8 * x / N2 else -200 + Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j]], used[HIGH[j]] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = if a > 0 then a - b else b - a + else + m = b + an = if b > 0 then a - b else b - a + end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c += 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = if k == 0 then 0 else math.min(k * N2, if lastWanted >= 0 then total else math.huge) + stream:packet(pk, granule, if last then { eos = true } else nil) + if last then + break + end + k += 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +-- the codebooks (tests check the Huffman lengths are a valid prefix code) +Encode.BOOKS = BOOKS + +return Encode +end +__FILES["audio/wav"] = function() + + +-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no +-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. +-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE +-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF +-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). +-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when +-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, +-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. +-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. +-- +-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames +-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio +-- local file = Wav.encode(audio, { sampleFormat = "s24" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Riff = __include("containers/Riff") +local Codecs = __include("audio/wav/Codecs") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Wav = { + name = "wav", + category = "audio", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Tags = { [string]: string } +type OpenOptions = { + maxBytes: number?, -- unused (the file is already in memory); kept for symmetry +} +type EncodeOptions = { + sampleFormat: ("u8" | "s16" | "s24" | "s32" | "f32")?, -- default "s16" + rf64: (boolean | "auto")?, -- default "auto": RF64 only when the file passes 4 GiB + extensible: boolean?, -- force (true) or forbid (false) WAVE_FORMAT_EXTENSIBLE; default as ffmpeg + channelMask: number?, -- the EXTENSIBLE speaker mask (default: ffmpeg's default layout for the channel count) + tags: Tags?, -- default: the Audio's tags (title, artist, album, comment, date, genre, track, ...) + rf64Threshold: number?, -- testing: the RIFF size past which "auto" switches to RF64 (default 0xFFFFFFFF) +} + +-- ------------------------------------------------------------------------------------------------ constants +Wav.FORMAT_PCM = 1 +Wav.FORMAT_MS_ADPCM = 2 +Wav.FORMAT_FLOAT = 3 +Wav.FORMAT_ALAW = 6 +Wav.FORMAT_MULAW = 7 +Wav.FORMAT_IMA_ADPCM = 0x11 +Wav.FORMAT_EXTENSIBLE = 0xFFFE + +local FORMAT_NAMES = { + [1] = "pcm", + [2] = "ms_adpcm", + [3] = "float", + [6] = "alaw", + [7] = "mulaw", + [0x11] = "ima_adpcm", +} + +-- LIST/INFO ids -> tag names +local INFO_TAGS = { + INAM = "title", + IART = "artist", + IPRD = "album", + ICMT = "comment", + ICRD = "date", + IGNR = "genre", + ITRK = "track", + IPRT = "track", + ISFT = "encoder", + ICOP = "copyright", + IENG = "engineer", + ISBJ = "subject", + IKEY = "keywords", +} + +-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear) +local ALAW, MULAW = buffer.create(1024), buffer.create(1024) +do + for i = 0, 255 do + local a = bit32.bxor(i, 0x55) + local t = bit32.band(a, 15) + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg > 0 then + t = bit32.lshift(t * 2 + 1 + 32, seg + 2) + else + t = bit32.lshift(t * 2 + 1, 3) + end + if bit32.band(a, 0x80) == 0 then + t = -t + end + buffer.writef32(ALAW, i * 4, t / 32768) + local u = bit32.band(bit32.bnot(i), 255) + local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4)) + local v = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 + buffer.writef32(MULAW, i * 4, v / 32768) + end +end + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + sampleRate: number, + channels: number, + frames: number, + duration: number, + bitrate: number, + tags: Tags, + format: string, + formatTag: number, + bitsPerSample: number, + blockAlign: number, + container: string, + dataOffset: number, + dataSize: number, + truncated: boolean, + channelMask: number?, + validBits: number?, + _buf: buffer, + _pos: number, + _be: boolean, + _bytes: number, + _kind: string, + _spb: number, + _cache: buffer?, + _cacheBlock: number, + _cacheFrames: number, + _coefs: buffer?, + _ncoef: number, + _state: buffer?, + _tmp: buffer, + }, + Decoder +)) + +local function trimTag(s: string): string + -- strip trailing NULs / spaces + local e = #s + while e > 0 do + local c = string.byte(s, e) + if c ~= 0 and c ~= 32 then + break + end + e -= 1 + end + local z = string.find(s, "\0", 1, true) + if z and z <= e then + e = z - 1 + end + return string.sub(s, 1, e) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Wav.sniff(r: Bytes.Reader): number + return if Riff.sniff(r) == "WAVE" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file +function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = Wav.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec, { + format = "wav", + codec = dec.format, + bitDepth = dec.bitsPerSample, + container = dec.container, + channelMask = dec.channelMask, + truncated = dec.truncated, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 } +-- ffmpeg's default speaker masks per channel count (av_channel_layout_default) +local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F } +local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag +-- tags -> LIST/INFO ids (the first id per name) +local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } +local BLOCK = 65536 -- frames per data piece when streaming a Decoder + +-- the body of the encoder: { buffer } pieces of the file | nil, Err +local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean): (any, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") + end + local o: EncodeOptions = opts or {} + local kind = o.sampleFormat or "s16" + local bytes: number? = SAMPLE_BYTES[kind] + if not bytes then + return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32") + end + local rate: number, ch: number = value.sampleRate, value.channels + if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad sample rate") + end + if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad channel count") + end + local isAudio = type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)") + end + local frameBytes = bytes * ch + local pieces: { buffer } = {} + local frames: number = 0 + if isAudio then + frames = (value.frames :: number?) or (buffer.len(value.samples) // (ch * 4)) + if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels") + end + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + -- pieces of at most 256 MiB + local per = math.max(1, 0x10000000 // frameBytes) + local f0 = 0 + while f0 < frames do + local n = math.min(per, frames - f0) + local b = buffer.create(n * frameBytes) + Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind) + table.insert(pieces, b) + f0 += n + end + else + local tmp = buffer.create(BLOCK * ch * 4) + while true do + local ok, out, n = pcall(value.read, value, BLOCK, tmp) + if not ok then + return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out)) + end + if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then + break + end + n = math.min(n, buffer.len(out) // (ch * 4)) + local b = buffer.create(n * frameBytes) + Codecs.quantize(out, 0, b, 0, n * ch, kind) + table.insert(pieces, b) + frames += n + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + end + end + local dataSize = frames * frameBytes + local bits = bytes * 8 + local float = kind == "f32" + local tag = if float then 3 else 1 + local extensible = ch > 2 or rate > 48000 or (not float and bits > 16) + if o.extensible ~= nil then + extensible = o.extensible + end + local w = Riff.writer("WAVE", { rf64 = if o.rf64 ~= nil then o.rf64 else "auto", sampleCount = frames, rf64Threshold = o.rf64Threshold }) + local fmt = Bytes.writer(40) + fmt:u16le(if extensible then 0xFFFE else tag) + fmt:u16le(ch) + fmt:u32le(rate) + fmt:u32le(rate * frameBytes) + fmt:u16le(frameBytes) + fmt:u16le(bits) + if extensible then + fmt:u16le(22) + fmt:u16le(bits) + fmt:u32le(o.channelMask or MASKS[ch] or 0) + fmt:u16le(tag) + fmt:string(GUID_TAIL) + elseif float then + fmt:u16le(0) -- cbSize + end + w:chunk("fmt ", fmt:finish()) + if float then + local fact = Bytes.writer(4) + fact:u32le(if w.rf64 == true or frames > 0xFFFFFFFF then 0xFFFFFFFF else frames) -- RF64: in ds64 (as ffmpeg) + w:chunk("fact", fact:finish()) + end + local tags = o.tags or value.tags + if type(tags) == "table" then + local items = {} + local keys = {} + for k in tags do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + local v = tags[k] + -- 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 + end + if #items > 0 then + w:list("INFO", items) + end + end + w:chunk("data", pieces) + local _ = dataSize + return w:finish({ parts = asParts }) +end + +-- encode(audio or decoder, opts?) -> buffer | nil, Err +function Wav.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + return encodeParts(value, opts, false) +end + +-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other +-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB +function Wav.encodeParts(value: any, opts: EncodeOptions?): ({ buffer }?, Err.Err?) + return encodeParts(value, opts, true) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range +function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?) + if type(r) == "buffer" or type(r) == "string" then + r = Bytes.reader(if type(r) == "string" then buffer.fromstring(r) else r :: any) + end + local f, ferr = Riff.read(r, { openEnded = { data = true } }) + if not f then + return nil, ferr + end + if f.form ~= "WAVE" then + return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8) + end + local buf = f.buf + local magic = f.container + local be = f.bigEndian + + local fmt: any = nil + local tags: Tags = {} + local dataOff, dataSize = -1, 0 + local truncated = false + local ds64Frames: number? = if f.ds64 and f.ds64.sampleCount > 0 then f.ds64.sampleCount else nil + local factFrames: number? = nil + local function u16(o: number): number + return Riff.u16(f, o) + end + local function u32(o: number): number + return Riff.u32(f, o) + end + local function i16(o: number): number + local v = u16(o) + return if v >= 32768 then v - 65536 else v + end + for _, c in f.chunks do + local id, size, body, avail = c.id, c.size, c.offset, c.avail + if id == "fmt " and avail >= 14 then + fmt = { + tag = u16(body), + channels = u16(body + 2), + rate = u32(body + 4), + byteRate = u32(body + 8), + blockAlign = u16(body + 12), + bits = if avail >= 16 then u16(body + 14) else 8, + body = body, + avail = avail, + } + elseif id == "fact" and avail >= 4 then + factFrames = u32(body) + elseif id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, sc in Riff.list(f, c) do + local name = INFO_TAGS[sc.id] + if sc.avail > 0 then + local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) + if v ~= "" then + tags[name or string.lower(sc.id)] = v + end + end + end + elseif id == "data" and dataOff < 0 then + dataOff = body + dataSize = avail + truncated = c.truncated + end + local _ = size + end + + if not fmt then + return nil, Err.new(Err.CORRUPT, "no fmt chunk") + end + if dataOff < 0 then + return nil, Err.new(Err.CORRUPT, "no data chunk") + end + local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits + local channelMask: number? = nil + local validBits: number? = nil + if tag == 0xFFFE then + if fmt.avail < 40 then + return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension") + end + local valid = u16(fmt.body + 18) + channelMask = u32(fmt.body + 20) + tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag + -- valid bits < container bits: the samples are left-justified, so decoding the container is right + validBits = valid + end + if ch < 1 or ch > 255 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate > 4000000 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local name: string? = FORMAT_NAMES[tag] + if not name then + return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) + end + + local dec = setmetatable({}, Decoder) :: any + dec.sampleRate = rate + dec.channels = ch + dec.tags = tags + dec.format = name + dec.formatTag = tag + dec.bitsPerSample = bits + dec.container = magic + dec.dataOffset = dataOff + dec.dataSize = dataSize + dec.channelMask = channelMask + dec._buf = buf + dec._pos = 0 + dec._be = be + dec._tmp = buffer.create(8) + dec._cacheBlock = -1 + dec._cacheFrames = 0 + dec._ncoef = 0 + + local blockAlign: number = fmt.blockAlign + local frames: number + if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then + local bytes + if name == "alaw" or name == "mulaw" then + bytes = 1 + elseif name == "float" then + if bits ~= 32 and bits ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits) + end + bytes = bits // 8 + else + if bits < 1 or bits > 32 then + return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits) + end + -- container: from blockAlign when it is consistent, else from the bit depth + bytes = (bits + 7) // 8 + if blockAlign >= ch and blockAlign % ch == 0 and blockAlign // ch >= bytes and blockAlign // ch <= 4 then + bytes = blockAlign // ch + end + end + blockAlign = bytes * ch + dec._bytes = bytes + dec._kind = name + frames = dataSize // blockAlign + dec._spb = 1 + elseif name == "ima_adpcm" or name == "ms_adpcm" then + if blockAlign < 1 then + return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0") + end + local spb = if fmt.avail >= 20 then u16(fmt.body + 18) else 0 + if name == "ima_adpcm" then + if bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits) + end + if blockAlign < 4 * ch then + return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small") + end + local computed = (blockAlign - 4 * ch) * 2 // ch + 1 + if spb < 1 or spb > computed then + spb = computed + end + else + if blockAlign < 7 * ch then + return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small") + end + local computed = (blockAlign - 7 * ch) * 2 // ch + 2 + if spb < 2 or spb > computed then + spb = computed + end + -- coefficients from the fmt extension, else the 7 standard pairs + local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local ncoef = 7 + if fmt.avail >= 22 then + local k = u16(fmt.body + 20) + if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then + ncoef = k + c1, c2 = {}, {} + for i = 1, k do + c1[i] = i16(fmt.body + 22 + (i - 1) * 4) + c2[i] = i16(fmt.body + 24 + (i - 1) * 4) + end + end + end + local coefs = buffer.create(ncoef * 8) + for i = 1, ncoef do + buffer.writei32(coefs, (i - 1) * 8, c1[i]) + buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i]) + end + dec._coefs = coefs + dec._ncoef = ncoef + dec._state = buffer.create(20 * ch) + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + dec._kind = name + dec._spb = spb + dec._cache = buffer.create(spb * ch * 4) + local full = dataSize // blockAlign + frames = full * spb + local rest = dataSize - full * blockAlign + if rest > 0 then + -- a partial last block: the frames it holds whole + if name == "ima_adpcm" then + if rest >= 4 * ch then + frames += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + elseif rest >= 7 * ch then + frames += math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) + end + end + -- fact: the true length (the last block is padded) + if factFrames and factFrames > 0 and factFrames < frames then + frames = factFrames + end + else + return nil, Err.new(Err.UNSUPPORTED, "format " .. name) + end + if ds64Frames and ds64Frames > 0 and ds64Frames < frames then + frames = ds64Frames + end + dec.blockAlign = blockAlign + dec.frames = frames + dec.duration = frames / rate + dec.truncated = truncated + dec.validBits = validBits + dec.bitrate = if fmt.byteRate > 0 then fmt.byteRate * 8 else math.floor(rate * blockAlign * 8 / dec._spb) + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples +-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). +function Decoder.read(self: Decoder, maxFrames: number, out: buffer?): (buffer, number) + local ch = self.channels + local req = math.floor(tonumber(maxFrames) or 0) + if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT) + req = 0 + end + local want = math.max(0, math.min(req, self.frames - self._pos)) + local dst: buffer = if out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 + then out + else buffer.create(want * ch * 4) + if want == 0 then + return dst, 0 + end + local kind = self._kind + if self._spb == 1 then + local off = self.dataOffset + self._pos * self.blockAlign + local count = want * ch + if kind == "pcm" then + Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be) + elseif kind == "float" then + Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp) + elseif kind == "alaw" then + Codecs.law(self._buf, off, dst, 0, count, ALAW) + else + Codecs.law(self._buf, off, dst, 0, count, MULAW) + end + self._pos += want + return dst, want + end + -- block formats: decode a block into the cache, copy out of it + local spb, ba = self._spb, self.blockAlign + local cache = self._cache :: buffer + local done = 0 + while done < want do + local block = self._pos // spb + if block ~= self._cacheBlock then + local off = self.dataOffset + block * ba + local avail = math.min(ba, self.dataOffset + self.dataSize - off) + local got + if kind == "ima_adpcm" then + got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0) + else + got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs :: buffer, self._ncoef, + self._state :: buffer) + end + self._cacheBlock = block + self._cacheFrames = got + end + local inBlock = self._pos - block * spb + local k = math.min(want - done, self._cacheFrames - inBlock) + if k <= 0 then + break + end + Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch) + done += k + self._pos += k + end + return dst, done +end + +-- Moves to a time in seconds (clamped to the stream). +function Decoder.seek(self: Decoder, seconds: number) + local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Moves to a frame index (clamped). +function Decoder.seekFrame(self: Decoder, frame: number) + local f = math.floor(tonumber(frame) or 0) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Current position in seconds. +function Decoder.position(self: Decoder): number + return self._pos / self.sampleRate +end + +-- Current position in frames. +function Decoder.tell(self: Decoder): number + return self._pos +end + +return Wav +end +__FILES["audio/wav/Codecs"] = @native function() + + + +-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The +-- ADPCM block decoders moved to codecs/audio/Adpcm. +-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) +-- only calls them with ranges it has checked against the source length and the output size. +local readu8, readi8, readu16, readi16, readu32, readi32 = + buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap +local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32 + +local Codecs = {} + +-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, +-- from src[off] to dst (f32) starting at sample index d. +@native function Codecs.int(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean) + local o = d * 4 + if bytes == 1 then + for i = 0, count - 1 do + writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128) + end + elseif bytes == 2 then + if be then + for i = 0, count - 1 do + local s = off + i * 2 + local v = readi8(src, s) * 256 + readu8(src, s + 1) + writef32(dst, o + i * 4, v / 32768) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768) + end + end + elseif bytes == 3 then + if be then + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2) + writef32(dst, o + i * 4, v / 8388608) + end + else + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s + 2) * 65536 + readu16(src, s) + writef32(dst, o + i * 4, v / 8388608) + end + end + else + if be then + for i = 0, count - 1 do + local v = byteswap(readu32(src, off + i * 4)) + if v >= 0x80000000 then + v -= 0x100000000 + end + writef32(dst, o + i * 4, v / 2147483648) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648) + end + end + end +end + +-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. +@native function Codecs.float(src: buffer, off: number, dst: buffer, d: number, count: number, bytes: number, be: boolean, + tmp: buffer) + local o = d * 4 + if bytes == 4 then + if be then + for i = 0, count - 1 do + writeu32(tmp, 0, byteswap(readu32(src, off + i * 4))) + writef32(dst, o + i * 4, readf32(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(src, off + i * 4)) + end + end + else + if be then + for i = 0, count - 1 do + local s = off + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, s + 4))) + writeu32(tmp, 4, byteswap(readu32(src, s))) + writef32(dst, o + i * 4, readf64(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf64(src, off + i * 8)) + end + end + end +end + +-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table +@native function Codecs.law(src: buffer, off: number, dst: buffer, d: number, count: number, tbl: buffer) + local o = d * 4 + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) + end +end + +-- copy frames from a block cache into the output: count f32 values +@native function Codecs.copy(src: buffer, sOff: number, dst: buffer, dOff: number, count: number) + buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) +end + +-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), +-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. +@native function Codecs.quantize(src: buffer, s: number, dst: buffer, off: number, count: number, kind: string) + local so = s * 4 + if kind == "f32" then + buffer.copy(dst, off, src, so, count * 4) + elseif kind == "s16" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + writei16(dst, off + i * 2, v) + end + elseif kind == "s24" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5) + if v > 8388607 then + v = 8388607 + elseif v < -8388608 then + v = -8388608 + elseif v ~= v then + v = 0 + end + if v < 0 then + v += 16777216 + end + local o = off + i * 3 + writeu16(dst, o, v % 65536) + writeu8(dst, o + 2, v // 65536) + end + elseif kind == "s32" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5) + if v > 2147483647 then + v = 2147483647 + elseif v < -2147483648 then + v = -2147483648 + elseif v ~= v then + v = 0 + end + writei32(dst, off + i * 4, v) + end + else -- u8 + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5) + if v > 127 then + v = 127 + elseif v < -128 then + v = -128 + elseif v ~= v then + v = 0 + end + writeu8(dst, off + i, v + 128) + end + end +end + +return Codecs +end +__FILES["audio/wavpack"] = function() + +-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction +-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 +-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the +-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("c") +-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking +-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file +-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. +-- +-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... +-- local f32, n = dec:read(4096) +-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them +-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local WavPackCodec = __include("codecs/audio/WavPack") + +-- ------------------------------------------------------------------------------------------------ contract +local WavPack = { + name = "wavpack", + category = "audio", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + correction: (buffer | string)?, -- the .wvc file of a hybrid file (default: opts.resolve(name .. "c") when given) + resolve: ((uri: string) -> buffer?)?, -- sibling files (the api passes it for paths) + name: string?, -- the file name (the api passes it) + maxFrames: number?, -- decode(): refuse longer streams (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function WavPack.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "wvpk" then + return 0 + end + local v = r:peekU8(9) + return if v == 4 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function WavPack.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err?) + local dec, err = WavPack.open(r, opts) + if not dec then + return nil, err + end + local d = dec :: any + local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +type Index = { offsets: { { number } }, starts: { number }, samples: { number }, total: number, first: number, md5: string? } + +-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence +local function index(buf: buffer, base: number, limit: number): (Index?, string?) + local at = base + local idx: Index = { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } + local cur: { number }? = nil + local initial = -1 + local resyncs = 0 + while at + 32 <= limit do + local h = WavPackCodec.header(buf, at, limit) + if not h then + -- garbage (or a tag) between blocks: search the next header + if resyncs > 64 then + break + end + local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) + local k = string.find(s, "wvpk", 1, true) + if not k then + break + end + at = at + k + resyncs += 1 + continue + end + if initial < 0 then + initial = h.index + idx.total = h.total + end + if h.samples > 0 then + if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then + cur = { at } + table.insert(idx.offsets, cur) + table.insert(idx.starts, h.index - initial) + table.insert(idx.samples, h.samples) + if idx.first < 0 then + idx.first = at + end + else + table.insert(cur, at) + end + if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then + cur = nil + end + else + idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) + end + at += h.size + end + if idx.first < 0 then + return nil, "no audio blocks" + end + return idx, nil +end + +local function correctionFile(opts: OpenOptions?): buffer? + if not opts then + return nil + end + local c = opts.correction + if type(c) == "string" then + return buffer.fromstring(c) + elseif type(c) == "buffer" then + return c + end + if type(opts.resolve) == "function" and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") + if base then + local ok, b = pcall(opts.resolve, base .. "c") + if ok and type(b) == "buffer" then + return b + end + end + end + return nil +end + +-- open(r, opts?) -> Decoder | nil, Err +function WavPack.open(r: Bytes.Reader, opts: OpenOptions?): (Types.Decoder?, Err.Err?) + if type(r) == "buffer" then + r = Bytes.reader(r :: any) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = if tagInfo then tagInfo.start else limit + local idx, ierr = index(buf, base, stop) + if not idx then + return nil, Err.from(ierr, base) + end + local info, err = WavPackCodec.info(buf, idx.first, stop) + if not info then + return nil, err + end + if info.channels > 256 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels") + end + local count = #idx.offsets + local last = idx.starts[count] + idx.samples[count] + local frames = if idx.total >= 0 then math.min(idx.total, last) else last + -- the correction file: its frames by start sample + local cbuf = if info.hybrid then correctionFile(opts) else nil + local cfor: { [number]: { number } } = {} + if cbuf then + local cidx = index(cbuf, 0, buffer.len(cbuf)) + if cidx then + for i, offs in cidx.offsets do + cfor[cidx.starts[i]] = offs + end + else + cbuf = nil + end + end + local codec = WavPackCodec.decoder(info.channels) + local dec: any = { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = if frames > 0 then math.floor((stop - base) * 8 * info.sampleRate / frames) else 0, + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + hybrid = info.hybrid, + lossless = not info.hybrid or cbuf ~= nil, + channelMask = info.channelMask, + md5 = idx.md5, + source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, + } + local starts, offsets = idx.starts, idx.offsets + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return if i > count then last else starts[i] + end, + decode = function(i: number): (number?, Err.Err?) + local co = if cbuf then cfor[starts[i]] else nil + return codec:frame(buf, offsets[i], if co then cbuf else nil, co) + end, + pcm = function(): { number } + return codec.pcm + end, + reset = function() end, + stop = frames, + scale = if info.float then 1 else 1 / 2 ^ (info.bytesPerSample * 8 - 1), + ints = not info.float, + }) +end + +return WavPack +end +__FILES["cad/step"] = function() + +-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). +-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / +-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and +-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; +-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to +-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, +-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / +-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same +-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). +-- +-- B-rep bodies and tessellation come from an injected kernel, never required by rosetta: +-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, +-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } +-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } +-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / +-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / +-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, +-- millimetres (meta.unit = 0.001). +-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), +-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("cad/step/Parse") +local Write = __include("cad/step/Write") +local Brep = __include("cad/step/Brep") + +-- ------------------------------------------------------------------------------------------------ contract +local Step = { + name = "step", + category = "cad", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 2^30) + maxEntities: number?, -- refuse more instances (default 2^24) +} +type EncodeOptions = { + schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA + name: string?, -- FILE_NAME name (default: the header's, else "model") + timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00") + crlf: boolean?, -- CRLF line ends (default LF) +} +type BrepOptions = { + brep: any?, -- the plug-in (else opts.plugins.brep) + plugins: { [string]: any }?, + chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead + tess: { [string]: any }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +Step.NULL = table.freeze({ null = true }) -- $ +Step.DERIVED = table.freeze({ derived = true }) -- * + +local SCHEMAS = { + AP203 = "CONFIG_CONTROL_DESIGN", + AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", + AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", +} +Step.SCHEMAS = SCHEMAS + +-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself +local function schemaOf(name: string): string + local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) + if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then + return "AP203" + elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then + return "AP214" + elseif string.find(n, "^AP242") then + return "AP242" + end + return n +end +Step.schemaOf = schemaOf + +-- ------------------------------------------------------------------------------------------------ sniff +function Step.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256) + head = string.gsub(head, "^%s*/%*.-%*/", "") + if string.find(head, "^%s*ISO%-10303%-21%s*;") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?) + local size = r.limit - r.base + if size > (opts and opts.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "file over maxBytes") + end + local s = buffer.readstring(r.buf, r.base, size) + local bom = 0 + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + bom = 3 + end + local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) + if not res then + local off = if at then r.base + bom + at - 1 else nil + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) + end + local m = msg or "parse error" + if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then + return nil, Err.new(Err.TRUNCATED, m, off) + end + return nil, Err.new(Err.CORRUPT, m, off) + end + local fs = res.header.FILE_SCHEMA + local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else "" + local cad: Types.Cad = { + kind = "cad", + schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown", + header = res.header, + entities = res.entities, + meta = { + count = res.count, + headerOrder = res.headerOrder, + source = { + format = "step", + schemaName = schemaName, + sections = res.sections, + extra = if #res.extra > 0 then res.extra else nil, + duplicates = if res.duplicates > 0 then res.duplicates else nil, + terminated = res.terminated, + }, + }, + } + return cad, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } } + local h = if type(cad.header) == "table" then cad.header else {} + local out: { [string]: { any } } = {} + for k, v in h do + out[k] = v + end + if type(out.FILE_DESCRIPTION) ~= "table" then + out.FILE_DESCRIPTION = { { "rosetta" }, "2;1" } + end + if type(out.FILE_NAME) ~= "table" then + out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "rosetta", "rosetta", "" } + end + local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil) + if schema then + out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } + end + return out +end + +function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") + end + local o: EncodeOptions = opts or {} + local nl = if o.crlf then "\r\n" else "\n" + local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } + local out = ctx.out + table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) + local header = headerArgs(cad, o) + local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } + local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } + local meta: any = if type(cad.meta) == "table" then cad.meta else {} + local rest = {} + for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do + if type(k) == "string" and header[k] and not seen[k] then + seen[k] = true + table.insert(order, k) + end + end + for k in header do + if type(k) == "string" and not seen[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + table.insert(order, k) + end + for _, k in order do + if not Write.record(ctx, k, header[k]) then + return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + table.insert(out, "ENDSEC;" .. nl) + local source = if type(meta.source) == "table" then meta.source else {} + if type(source.extra) == "table" then + for _, x in source.extra do + if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then + table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) + end + end + end + -- entities by section, in id order + local ids = {} + for id, e in cad.entities do + if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then + return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") + end + table.insert(ids, id) + end + table.sort(ids) + local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} } + for si, sec in sections do + if #sections > 1 then + table.insert(out, "DATA") + local params = {} + if sec.name ~= nil then + params[1] = sec.name + params[2] = if sec.schema ~= nil then sec.schema else {} + if not Write.list(ctx, params, 0) then + return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) + end + end + table.insert(out, ";" .. nl) + else + table.insert(out, "DATA;" .. nl) + end + for _, id in ids do + local e: any = cad.entities[id] + local esec = if type(e.section) == "number" then e.section else 1 + if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then + table.insert(out, string.format("#%.0f=", id)) + if e.type == "COMPLEX" or type(e.parts) == "table" then + if type(e.parts) ~= "table" or #e.parts == 0 then + return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") + end + table.insert(out, "(") + for _, p in e.parts do + if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) + end + end + table.insert(out, ")") + elseif not Write.record(ctx, e.type, e.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + end + table.insert(out, "ENDSEC;" .. nl) + end + table.insert(out, "END-ISO-10303-21;" .. nl) + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- get(cad, id | { ref = id }) -> the entity +function Step.get(cad: Types.Cad, id: any): Types.StepEntity? + if type(id) == "table" then + id = id.ref + end + return cad.entities[id] +end + +-- ids(cad) -> the instance ids in ascending order +function Step.ids(cad: Types.Cad): { number } + local out = {} + for id in cad.entities do + table.insert(out, id) + end + table.sort(out) + return out +end + +-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending +function Step.byType(cad: Types.Cad, name: string): { number } + local n = string.upper(name) + local out = {} + for id, e in cad.entities do + if e.type == n then + table.insert(out, id) + elseif e.parts then + for _, p in e.parts do + if p.type == n then + table.insert(out, id) + break + end + end + end + end + table.sort(out) + return out +end + +-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) +function Step.part(e: Types.StepEntity?, name: string): { any }? + if not e then + return nil + end + if e.type == name then + return e.args + end + if e.parts then + for _, p in e.parts do + if p.type == name then + return p.args + end + end + end + return nil +end + +-- add(cad, type, args) -> id: a new instance after the highest id +function Step.add(cad: Types.Cad, type: string, args: { any }): number + local top = 0 + for id in cad.entities do + if id > top then + top = id + end + end + local id = top + 1 + cad.entities[id] = { id = id, type = string.upper(type), args = args } + cad.meta.count = (cad.meta.count or 0) + 1 + return id +end + +-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) +function Step.real(t: { [any]: any }, key: any): { [any]: any } + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true + return t +end + +-- new(schema?) -> an empty Cad ("AP214" by default) +function Step.new(schema: string?): Types.Cad + return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } +end + +-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason +Step.plugin = Brep.plugin + +local function textOf(cad: Types.Cad): (string?, Err.Err?) + local buf, err = Step.encode(cad) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err +function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = textOf(cad) + if not text then + return nil, err + end + local bodies, res, rerr = Brep.read(plug, text, opts) + if not bodies then + return nil, rerr + end + return bodies, res +end + +-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err +function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a list of bodies") + end + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = Brep.write(plug, bodies, opts) + if not text then + return nil, err + end + return Step.decode(Bytes.reader(buffer.fromstring(text))) +end + +-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err +function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local bodies = value + if type(value) == "table" and value.kind == "cad" then + local b, err = Step.toBodies(value, opts) + if not b then + return nil, err + end + bodies = b + end + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") + end + return Brep.scene(plug, bodies, opts) +end + +return Step +end +__FILES["cad/step/Brep"] = function() + +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises +-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a +-- Scene. Interpreted on purpose: the plug-in's errors unwind through here. +-- +-- The interface (every function may throw; results are checked): +-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, +-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) +-- write(bodies: { Body }, opts) -> string bodies -> STEP text +-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based +-- triples }, faceOf = { [triangle] = Face (face.color?) }? } +-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = +-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +local Err = __include("core/Err") +local Types = __include("Types") + +local Brep = {} + +type Plugin = { + read: (text: string, opts: any) -> any, + write: ((bodies: { any }, opts: any) -> string)?, + tessellate: ((body: any, opts: any) -> any)?, +} + +local function rgbOf(c: any): (number?, number?, number?) + if c == nil then + return nil, nil, nil + end + local ok, r, g, b = pcall(function(): (any, any, any) + if type(c) == "table" then + return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] + end + return (c :: any).R, (c :: any).G, (c :: any).B -- Color3 + end) + if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then + return r, g, b + end + return nil, nil, nil +end + +-- plugin(p) -> the normalised interface, or nil + the reason +function Brep.plugin(p: any): (Plugin?, string?) + if type(p) ~= "table" then + return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" + end + if type(p.read) == "function" then + return { + read = p.read, + write = if type(p.write) == "function" then p.write else nil, + tessellate = if type(p.tessellate) == "function" then p.tessellate else nil, + }, nil + end + local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess + if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then + return { + read = function(text: string, opts: any): any + return SB.read(S.parse(text), opts) + end, + write = if type(SW) == "table" and type(SW.write) == "function" + then function(bodies: { any }, opts: any): string + local o = if type(opts) == "table" then table.clone(opts) else {} + if o.colors == nil then + local colors = {} + for i, b in bodies do + local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) + if r then + colors[i] = { r, g, bl } + end + end + o.colors = colors + end + return SW.write(bodies, o) + end + else nil, + tessellate = if type(Tess) == "table" and type(Tess.body) == "function" + then function(body: any, opts: any): any + return Tess.body(body, opts) + end + else nil, + }, nil + end + return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" +end + +-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep +function Brep.find(opts: any): (Plugin?, Err.Err?) + local p = nil + if type(opts) == "table" then + p = opts.brep + if p == nil and type(opts.plugins) == "table" then + p = opts.plugins.brep + end + end + local plug, why = Brep.plugin(p) + if not plug then + return nil, Err.new(Err.UNSUPPORTED, why :: string) + end + return plug, nil +end + +-- read(plug, text, opts) -> bodies, result | nil, Err +function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) + local ok, res = pcall(plug.read, text, opts) + if not ok then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) + end + if type(res) ~= "table" or type(res.bodies) ~= "table" then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") + end + return res.bodies, res, nil +end + +-- write(plug, bodies, opts) -> text | nil, Err +function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) + local w = plug.write + if not w then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") + end + local ok, res = pcall(w, bodies, opts) + if not ok then + return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) + end + if type(res) ~= "string" then + return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") + end + return res, nil +end + +local function xyz(p: any): (number, number, number) + if type(p) == "table" then + return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 + end + return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3 +end + +local function linear(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end + +-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by +-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) + local tess = plug.tessellate + if not tess then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") + end + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.001 + local tessOpts = if type(opts) == "table" and type(opts.tess) == "table" + then opts.tess + else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 } + local matByKey: { [string]: number } = {} + local function material(r: number?, g: number?, b: number?): number + local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default" + local m = matByKey[key] + if m then + return m + end + local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default") + if r then + mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 } + mat.extras = { color = { r, g, b } } + else + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + end + mat.metallic, mat.roughness = 0, 0.5 + table.insert(scene.materials, mat) + matByKey[key] = #scene.materials + return #scene.materials + end + for bi, body in bodies do + local ok, mesh = pcall(tess, body, tessOpts) + if not ok then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) + end + if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") + end + local cok, prims = pcall(function(): { Types.Primitive } + local P, N, I = mesh.positions, mesh.normals, mesh.indices + local nv = #P + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil + for i = 1, nv do + local x, y, z = xyz(P[i]) + buffer.writef32(pos.data, (i - 1) * 12, x) + buffer.writef32(pos.data, (i - 1) * 12 + 4, y) + buffer.writef32(pos.data, (i - 1) * 12 + 8, z) + if nrm then + local a, b, c = xyz(N[i]) + buffer.writef32(nrm.data, (i - 1) * 12, a) + buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) + buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) + end + end + local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) + -- triangles grouped by colour, in first-seen order + local groups: { { mat: number, tris: { number } } } = {} + local byMat: { [number]: { mat: number, tris: { number } } } = {} + local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} + local nt = #I // 3 + for t = 1, nt do + local f = faceOf[t] + local r, g, b = rgbOf(type(f) == "table" and f.color or nil) + if not r then + r, g, b = br, bg, bb + end + local m = material(r, g, b) + local grp = byMat[m] + if not grp then + grp = { mat = m, tris = {} } + byMat[m] = grp + table.insert(groups, grp) + end + table.insert(grp.tris, t) + end + local out: { Types.Primitive } = {} + for _, grp in groups do + local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) + for k, t in grp.tris do + for c = 0, 2 do + local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 + buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + if nrm then + attrs.NORMAL = nrm + end + table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat }) + end + return out + end) + if not cok then + return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) + end + local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi + table.insert(scene.meshes, { name = name, primitives = prims }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } + return scene, nil +end + +return Brep +end +__FILES["cad/step/Parse"] = @native function() + + +-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass +-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), +-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every +-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, +-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. +-- +-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; +-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) +-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so +-- the writer prints it back as a real; integral numbers without that mark are written as integers. +local Parse = {} + +local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor + +local MAX_DEPTH = 100 + +type Ctx = { + s: string, + n: number, + err: string?, + errAt: number?, + null: any, + derived: any, +} + +@native local function fail(ctx: Ctx, msg: string, at: number): nil + if not ctx.err then + ctx.err, ctx.errAt = msg, at + end + return nil +end + +-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) +@native local function skip(ctx: Ctx, i: number): number + local s, n = ctx.s, ctx.n + while i <= n do + local c = sbyte(s, i) + if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then + i += 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, e = sfind(s, "*/", i + 2, true) + if not e then + fail(ctx, "unterminated comment", i) + return n + 1 + end + i = e + 1 + else + return i + end + end + return i +end + +@native local function isAlpha(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end +@native local function isWord(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) +end + +-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none +@native local function keyword(ctx: Ctx, i: number): (string?, number) + local s, n = ctx.s, ctx.n + local j = i + if j <= n and sbyte(s, j) == 33 then -- '!' user-defined + j += 1 + end + if j > n or not isAlpha(sbyte(s, j) :: number) then + return nil, i + end + j += 1 + while j <= n and isWord(sbyte(s, j) :: number) do + j += 1 + end + return string.upper(ssub(s, i, j - 1)), j +end + +-- UTF-8 of a code point +@native local function utf8char(cp: number): string + if cp < 0x80 then + return schar(cp) + elseif cp < 0x800 then + return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) + elseif cp < 0x10000 then + return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + elseif cp < 0x110000 then + return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + end + return "\239\191\189" +end +Parse.utf8char = utf8char + +@native local function hexAt(s: string, i: number, k: number): number? + local h = ssub(s, i, i + k - 1) + if #h ~= k or sfind(h, "[^%x]") then + return nil + end + return tonumber(h, 16) +end + +-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, +-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) +-- pass through. +@native function Parse.unescape(raw: string): string + if not sfind(raw, "[\\']") then + return raw + end + local out = {} + local i, n = 1, #raw + local plain = 1 + while i <= n do + local c = sbyte(raw, i) + if c == 39 then -- '' -> ' + table.insert(out, ssub(raw, plain, i)) + i += 2 + plain = i + elseif c == 92 then + table.insert(out, ssub(raw, plain, i - 1)) + local d = sbyte(raw, i + 1) + if d == 92 then + table.insert(out, "\\") + i += 2 + elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c + table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256)) + i += 4 + elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page + i += 4 + elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh + local h = hexAt(raw, i + 3, 2) + if h then + table.insert(out, utf8char(h)) + i += 5 + else + table.insert(out, "\\") + i += 1 + end + elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then + local k = if sbyte(raw, i + 2) == 50 then 4 else 8 + local j = i + 4 + local hi: number? = nil + while j <= n do + if sbyte(raw, j) == 92 then + break + end + local cp = hexAt(raw, j, k) + if not cp then + break + end + if k == 4 and cp >= 0xD800 and cp < 0xDC00 then + hi = cp + elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then + table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) + hi = nil + else + table.insert(out, utf8char(cp)) + hi = nil + end + j += k + end + if ssub(raw, j, j + 3) == "\\X0\\" then + j += 4 + end + i = j + else + table.insert(out, "\\") + i += 1 + end + plain = i + else + i += 1 + end + end + table.insert(out, ssub(raw, plain, n)) + return table.concat(out) +end + +@native local function markReal(t: { [any]: any }, key: any) + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true +end + +-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) +local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) + +@native local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) + -- i is just past "(" + local s = ctx.s + local out = {} + i = skip(ctx, i) + if sbyte(s, i) == 41 then + return out, i + 1 + end + local k = 0 + while true do + local v, j, intReal = value(ctx, i, depth + 1) + if v == nil then + return nil, j + end + k += 1 + out[k] = v + if intReal then + markReal(out, k) + end + j = skip(ctx, j) + local c = sbyte(s, j) + if c == 44 then + i = skip(ctx, j + 1) + elseif c == 41 then + return out, j + 1 + elseif c == nil then + return fail(ctx, "truncated list", j), j + else + return fail(ctx, "expected , or ) in a list", j), j + end + end +end +Parse.list = list + +value = @native function(ctx: Ctx, i: number, depth: number): (any, number, boolean) + if depth > MAX_DEPTH then + return fail(ctx, "lists nested too deeply", i), i, false + end + local s = ctx.s + i = skip(ctx, i) + local c = sbyte(s, i) + if c == nil then + return fail(ctx, "truncated parameter", i), i, false + elseif c == 35 then -- #ref + local _, e = sfind(s, "^%d+", i + 1) + if not e then + return fail(ctx, "bad entity reference", i), i, false + end + return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false + elseif c == 39 then -- 'string' + local j = i + 1 + while true do + local q = sfind(s, "'", j, true) + if not q then + return fail(ctx, "unterminated string", i), i, false + end + if sbyte(s, q + 1) == 39 then + j = q + 2 + else + return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false + end + end + elseif c == 36 then + return ctx.null, i + 1, false + elseif c == 42 then + return ctx.derived, i + 1, false + elseif c == 40 then + local l, j = list(ctx, i + 1, depth) + return l, j, false + elseif c == 46 then -- .ENUM. + local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) + if not e then + return fail(ctx, "bad enumeration", i), i, false + end + return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif c == 34 then -- "binary" + local _, e = sfind(s, "^[0-3]%x*\"", i + 1) + if not e then + return fail(ctx, "bad binary literal", i), i, false + end + return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then + local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) + local tok = ssub(s, i, e :: number) + local num = tonumber(if c == 43 then ssub(tok, 2) else tok) + if num == nil then + -- "1.E" without digits and the like + local core = string.match(tok, "^[+-]?%d*%.?%d*") + num = core and tonumber(if c == 43 then ssub(core, 2) else core) + if num == nil then + return fail(ctx, "bad number", i), i, false + end + e = i + #(core :: string) - 1 + end + local real = sfind(tok, "[.eE]") ~= nil + local nv = num :: number + return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv + elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) + local word, j = keyword(ctx, i) + j = skip(ctx, j) + if word == nil or sbyte(s, j) ~= 40 then + return fail(ctx, "expected a parameter", i), i, false + end + local v, k, intReal = value(ctx, j + 1, depth + 1) + if v == nil then + return nil, k, false + end + k = skip(ctx, k) + if sbyte(s, k) ~= 41 then + return fail(ctx, "expected ) after a typed parameter", k), k, false + end + local t = { typed = word, value = v } + if intReal then + markReal(t, "value") + end + return t, k + 1, false + end + return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false +end +Parse.value = value + +-- the simple record at i: NAME(params) -> type, args, next +@native local function record(ctx: Ctx, i: number): (string?, { any }?, number) + local word, j = keyword(ctx, i) + if not word then + return fail(ctx, "expected an entity name", i), nil, i + end + j = skip(ctx, j) + if sbyte(ctx.s, j) ~= 40 then + return fail(ctx, "expected ( after " .. word, j), nil, j + end + local args, k = list(ctx, j + 1, 0) + if not args then + return nil, nil, k + end + return word, args, k +end + +-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil +@native local function expect(ctx: Ctx, i: number, ch: number, what: string): number? + i = skip(ctx, i) + if sbyte(ctx.s, i) ~= ch then + if i > ctx.n then + return fail(ctx, "truncated: expected " .. what, i) + end + return fail(ctx, "expected " .. what, i) + end + return i + 1 +end + +@native local function at(s: string, i: number, word: string): boolean + return ssub(s, i, i + #word - 1) == word +end + +type Result = { + header: { [string]: { any } }, + headerOrder: { string }, + entities: { [number]: any }, + count: number, + sections: { { name: any?, schema: any? } }, + extra: { { name: string, text: string } }, + duplicates: number, + terminated: boolean, +} + +-- parse(s, opts) -> Result | nil, message, offset (1-based position in s) +@native function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) + local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } + local res: Result = { + header = {}, + headerOrder = {}, + entities = {}, + count = 0, + sections = {}, + extra = {}, + duplicates = 0, + terminated = false, + } + local i = skip(ctx, 1) + if not at(s, i, "ISO-10303-21") then + return nil, "no ISO-10303-21 magic", i + end + local ni = expect(ctx, i + 12, 59, ";") + if not ni then + return nil, ctx.err, ctx.errAt + end + i = ni + local sawData = false + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + if i > ctx.n then + if not sawData then + return nil, "truncated: no DATA section", i + end + break + end + if at(s, i, "END-ISO-10303-21") then + res.terminated = true + local e = expect(ctx, i + 16, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + break + end + local word, j = keyword(ctx, i) + if word == "HEADER" then + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + if i > ctx.n then + return nil, "truncated header", i + end + local t, args, k = record(ctx, i) + if not t then + return nil, ctx.err, ctx.errAt + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if res.header[t] == nil then + table.insert(res.headerOrder, t) + end + res.header[t] = args :: { any } + i = e2 + end + elseif word == "DATA" then + sawData = true + local sec: { name: any?, schema: any? } = {} + j = skip(ctx, j) + if sbyte(s, j) == 40 then + local params, k = list(ctx, j + 1, 0) + if not params then + return nil, ctx.err, ctx.errAt + end + sec.name, sec.schema = params[1], params[2] + j = k + end + table.insert(res.sections, sec) + local secIndex = #res.sections + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + local c = sbyte(s, i) + if c == nil then + return nil, "truncated: the DATA section has no ENDSEC", i + end + if c ~= 35 then + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + return nil, "expected an entity instance (#id = ...)", i + end + local _, idEnd = sfind(s, "^%d+", i + 1) + if not idEnd then + return nil, "bad entity instance name", i + end + local id = tonumber(ssub(s, i + 1, idEnd)) :: number + local k = expect(ctx, idEnd + 1, 61, "=") + if not k then + return nil, ctx.err, ctx.errAt + end + k = skip(ctx, k) + local ent: any + if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) + local parts = {} + k = skip(ctx, k + 1) + while sbyte(s, k) ~= 41 do + if k > ctx.n then + return nil, "truncated complex instance", k + end + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + table.insert(parts, { type = t, args = args }) + k = skip(ctx, k2) + end + if #parts == 0 then + return nil, "empty complex instance", k + end + ent = { id = id, type = "COMPLEX", args = {}, parts = parts } + k += 1 + else + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + ent = { id = id, type = t, args = args } + k = k2 + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if secIndex > 1 then + ent.section = secIndex + end + if res.entities[id] then + res.duplicates += 1 + else + res.count += 1 + if res.count > maxEntities then + return nil, "LIMIT", i + end + end + res.entities[id] = ent + i = e2 + end + elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then + -- kept as raw text (to the ENDSEC outside strings) + local k = j + local stop: number? = nil + while k <= ctx.n do + local c = sbyte(s, k) + if c == 39 then + local q = k + 1 + while true do + local p = sfind(s, "'", q, true) + if not p then + return nil, "unterminated string", k + end + if sbyte(s, p + 1) == 39 then + q = p + 2 + else + k = p + 1 + break + end + end + elseif c == 69 and at(s, k, "ENDSEC") then + stop = k + break + else + k += 1 + end + end + if not stop then + return nil, "truncated " .. word .. " section", i + end + table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) + local e2 = expect(ctx, stop + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + else + return nil, "unknown section " .. tostring(word), i + end + end + if not sawData then + return nil, "no DATA section", i + end + return res, nil, nil +end + +return Parse +end +__FILES["cad/step/Write"] = @native function() + + +-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings +-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid +-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: +-- failures return nil, message. +local Write = {} + +local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge + +local MAX_DEPTH = 100 + +-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +@native function Write.real(v: number): string? + if v ~= v or v == huge or v == -huge then + return nil + end + local s = sformat("%.15g", v) + if tonumber(s) ~= v then + s = sformat("%.16g", v) + if tonumber(s) ~= v then + s = sformat("%.17g", v) + end + end + s = string.upper(s) + local e = sfind(s, "E", 1, true) + if not sfind(s, ".", 1, true) then + if e then + s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) + else + s ..= "." + end + end + return s +end + +local HEX = "0123456789ABCDEF" +@native local function hex(v: number, k: number): string + local out = table.create(k) + for i = k, 1, -1 do + local d = v % 16 + out[i] = ssub(HEX, d + 1, d + 1) + v = floor(v / 16) + end + return table.concat(out) +end + +-- a string's Part 21 literal (with the quotes) +@native function Write.str(s: string): string + if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ + return "'" .. s .. "'" + end + local out = { "'" } + local i, n = 1, #s + local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run + @native local function close() + if wide then + table.insert(out, "\\X0\\") + wide = nil + end + end + while i <= n do + local c = sbyte(s, i) :: number + if c >= 32 and c < 127 then + close() + if c == 39 then + table.insert(out, "''") + elseif c == 92 then + table.insert(out, "\\\\") + else + table.insert(out, string.char(c)) + end + i += 1 + else + -- a UTF-8 sequence -> code point + local cp: number? = nil + local len = 1 + if c >= 0xC2 and c < 0xE0 then + local c2 = sbyte(s, i + 1) + if c2 and c2 >= 0x80 and c2 < 0xC0 then + cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 + end + elseif c >= 0xE0 and c < 0xF0 then + local c2, c3 = sbyte(s, i + 1, i + 2) + if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then + local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) + if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then + cp, len = v, 3 + end + end + elseif c >= 0xF0 and c < 0xF5 then + local c2, c3, c4 = sbyte(s, i + 1, i + 3) + if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then + local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) + if v >= 0x10000 and v < 0x110000 then + cp, len = v, 4 + end + end + end + if cp == nil then + close() + table.insert(out, "\\X\\" .. hex(c, 2)) + i += 1 + else + local k = if cp >= 0x10000 then 8 else 4 + if wide ~= k then + close() + table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\") + wide = k + end + table.insert(out, hex(cp, k)) + i += len + end + end + end + close() + table.insert(out, "'") + return table.concat(out) +end + +@native local function isName(s: any): boolean + return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil +end +Write.isName = isName + +type Ctx = { out: { string }, null: any, derived: any, err: string? } + +local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean + +@native local function reals(t: any): { [any]: boolean }? + local mt = getmetatable(t) + return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil +end + +@native local function list(ctx: Ctx, t: { any }, depth: number): boolean + local out = ctx.out + table.insert(out, "(") + local marks = reals(t) + local n = #t + for i = 1, n do + if i > 1 then + table.insert(out, ",") + end + if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then + return false + end + end + table.insert(out, ")") + return true +end +Write.list = list + +value = @native function(ctx: Ctx, v: any, real: boolean, depth: number): boolean + local out = ctx.out + if depth > MAX_DEPTH then + ctx.err = "values nested too deeply (or a cycle)" + return false + end + local tv = type(v) + if tv == "number" then + if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then + table.insert(out, sformat("%.0f", v)) + return true + end + local r = Write.real(v) + if not r then + ctx.err = "a number that STEP cannot hold (nan / inf)" + return false + end + table.insert(out, r) + return true + elseif tv == "string" then + table.insert(out, Write.str(v)) + return true + elseif tv == "boolean" then + table.insert(out, if v then ".T." else ".F.") + return true + elseif tv == "table" then + if v == ctx.null then + table.insert(out, "$") + return true + elseif v == ctx.derived then + table.insert(out, "*") + return true + end + local ref = v.ref + if ref ~= nil then + if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then + ctx.err = "bad entity reference " .. tostring(ref) + return false + end + table.insert(out, sformat("#%.0f", ref)) + return true + end + local enum = v.enum + if enum ~= nil then + if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then + ctx.err = "bad enumeration " .. tostring(enum) + return false + end + table.insert(out, "." .. string.upper(enum) .. ".") + return true + end + local bin = v.binary + if bin ~= nil then + if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then + ctx.err = "bad binary literal" + return false + end + table.insert(out, "\"" .. string.upper(bin) .. "\"") + return true + end + local typed = v.typed + if typed ~= nil then + if not isName(typed) then + ctx.err = "bad typed parameter name " .. tostring(typed) + return false + end + if v.value == nil then + ctx.err = "typed parameter " .. typed .. " without a value" + return false + end + local marks = reals(v) + table.insert(out, string.upper(typed) .. "(") + if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then + return false + end + table.insert(out, ")") + return true + end + return list(ctx, v, depth) + end + ctx.err = "cannot write a " .. tv .. " value" + return false +end +Write.value = value + +-- record(ctx, type, args) -> appends TYPE(args) +@native function Write.record(ctx: Ctx, t: any, args: any): boolean + if not isName(t) then + ctx.err = "bad entity type " .. tostring(t) + return false + end + if type(args) ~= "table" then + ctx.err = "entity " .. t .. " without an args list" + return false + end + table.insert(ctx.out, string.upper(t)) + return list(ctx, args, 0) +end + +return Write +end +__FILES["codecs/audio/Aac"] = function() + +-- 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/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("@rosetta/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, ... } +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bits = __include("core/Bits") +local Decode = __include("codecs/audio/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP: { [number]: { number } } = { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + +type Config = { + objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) + sfIndex: number, + sampleRate: number, -- the core rate + channelConfig: number, + channels: number, + sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + ps: boolean, + extensionRate: number?, -- the SBR output rate + frameLength: number, +} + +local function rateIndex(rate: number): number + -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + local best, bi = math.huge, 4 + for i, r in Aac.RATES do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br: Bits.BitReader): number + local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br: Bits.BitReader): (number, number) + local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- pce(br) -> channels (program_config_element) +local function pce(br: Bits.BitReader): number + br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels += if br:read(1) == 1 then 2 else 1 + br:read(4) + end + channels += lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig +function Aac.config(asc: buffer): (Config?, Err.Err?) + if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate: number? = nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig +function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer + local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +type Adts = { + headerSize: number, -- 7, or 9 with a CRC + frameSize: number, -- the whole frame, header included + objectType: number, + sfIndex: number, + sampleRate: number, + channelConfig: number, + blocks: number, -- raw_data_blocks in the frame (1 .. 4) + protected: boolean, +} + +-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) +function Aac.adts(b: buffer, o: number, limit: number): Adts? + if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = if protected then 9 else 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Decoder = { + config: Config, + channels: number, + sampleRate: number, + frameLength: number, + pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order + sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + -- an empty frame (only fill elements): silence + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self: Decoder) + for _, c in self.state.ch do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err +function Aac.decoder(asc: any): (Decoder?, Err.Err?) + local cfg: Config + if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } :: Config + else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac +end +__FILES["codecs/audio/Aac/Decode"] = @native function() + + + +-- 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/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 = __include("codecs/audio/Mdct") +local Tables = __include("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 + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- ------------------------------------------------------------------------------------------------ bit reader +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B: buffer = buffer.create(16) +local BP = 0 -- bit position +local BL = 0 -- bit limit +local OVER = false + +@native local function getBits(n: number): number -- 1 .. 25 + local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +@native local function peekBits(n: number): number + local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +@native local function getLong(n: number): number + if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +-- ------------------------------------------------------------------------------------------------ Huffman +local PEEK = 10 +type Book = { tab: { number }, map: { [number]: number }, maxLen: number } + +@native local function book(codes: { number }, bits: { number }): Book + local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK: { Book } = {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +-- the next symbol of a book, -1 for an invalid code +@native local function huff(bk: Book): number + local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP += band(e, 31) + return rshift(e, 5) + end + -- a code longer than PEEK bits + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +-- per codebook: dimension, unsigned, modulus, offset +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +-- ------------------------------------------------------------------------------------------------ windows +local SINE_LONG = Mdct.window("sine", 2048) :: { number } +local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } +local SINE_SHORT = Mdct.window("sine", 256) :: { number } +local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } +local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan +local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ state +type Channel = { + spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows) + overlap: { number }, -- 1024 samples carried to the next frame + prevShape: number, + -- this frame's ics + windowSequence: number, + windowShape: number, + maxSfb: number, + numGroups: number, + groupLen: { number }, + bandType: { number }, -- [g * maxSfb + sfb + 1] + sf: { number }, + -- tns + tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter +} + +type State = { + sfIndex: number, + channels: number, -- configured channels (0: as found) + frameLength: number, + ch: { Channel }, + pcm: { number }, -- interleaved output floats + random: number, -- PNS generator state + time: { number }, -- 2048 IMDCT scratch + frame: { number }, -- 2048 windowed frame scratch + short: { number }, -- 256 scratch + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + extensions: number, -- extension payloads seen (SBR / PS / ...) + sbr: boolean, -- an SBR payload was seen + map: { number }?, -- element channel order -> output channel (1-based) +} + +@native local function newChannel(): Channel + return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +-- ------------------------------------------------------------------------------------------------ ics +@native local function icsInfo(st: State, c: Channel): string? + if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng] += 1 + else + ng += 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +@native local function sectionData(c: Channel): string? + local long = c.windowSequence ~= EIGHT_SHORT + local bits = if long then 5 else 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len += inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k += len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +@native local function scaleFactors(c: Channel, globalGain: number): string? + local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is += d - 60 + sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise += getBits(9) - 256 + firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise += d - 60 + end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv += d - 60 + if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +@native local function tnsData(st: State, c: Channel): string? + local short = c.windowSequence == EIGHT_SHORT + local nw = if short then 8 else 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(if short then 1 else 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(if short then 4 else 6) + local order = getBits(if short then 3 else 5) + local f = { length, order, 0 } + if order > (if short then 7 else 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v -= 2 ^ nb + end + tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +@native local function applyTns(st: State, c: Channel) + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] + local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] + local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in c.tnsFilters do + local bottom = numSwb + for _, f in list do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = if m < order then m else order + for i = 1, lim do + y -= spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p += inc + end + end + end + end + end +end + +-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) +@native local function spectralData(st: State, c: Channel, pulses: { number }?): string? + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + -- zeros (intensity bands are filled from the other channel later) + continue + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = if r >= 2147483648 then r - 4294967296 else r + spec[base + k] = v + energy += v * v + end + st.random = r + local m = if energy > 0 then scale / sqrt(energy) else 0 + for k = 1, width do + spec[base + k] *= m + end + end + continue + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1: number, vals2: number, vals3: number, vals4: number + if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = if e == 1 then vals1 else vals2 + if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n += 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k += dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = if q < 0 then -v else v + end + end + end + end + end + win += glen + end + if pulses then + -- long window: add the pulses to the quantised values, then dequantise every band + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] + end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = if q < 0 then -v else v + end + end + end + end + end + return nil +end + +-- individual_channel_stream +@native local function ics(st: State, c: Channel, commonWindow: boolean): string? + local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses: { number }? = nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos += getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +-- ------------------------------------------------------------------------------------------------ stereo +@native local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) + local short = l.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win += glen + end +end + +@native local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) + local short = r.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = if cb == INTENSITY_HCB then 1 else -1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win += glen + end +end + +-- ------------------------------------------------------------------------------------------------ filterbank +@native local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT + local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT + for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = if w == 0 then rise0 else wcur + local base = 448 + w * 128 + for n = 1, 128 do + frame[base + n] += tmp[n] * rise[n] + frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] + end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + -- left half + if seq == LONG_STOP then + local rise = if prev == 1 then KBD_SHORT else SINE_SHORT + for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = if prev == 1 then KBD_LONG else SINE_LONG + for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + -- right half + if seq == LONG_START then + local fall = if shape == 1 then KBD_SHORT else SINE_SHORT + for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = if shape == 1 then KBD_LONG else SINE_LONG + for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p += stride + end + c.prevShape = shape +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. +@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order: { Channel } = {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh += 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh += 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count += getBits(8) + end + if align == 1 then + BP = (BP + 7) // 8 * 8 + end + BP += count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count += getBits(8) - 1 + end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions += 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in order do + local o = if map and map[i] then map[i] else i + filterbank(st, c, pcm, n, o) + end + return n, nil +end + +@native function Decode.state(sfIndex: number): State + return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode +end +__FILES["codecs/audio/Aac/Tables"] = function() + +-- 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. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables +end +__FILES["codecs/audio/Ac3"] = function() + +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the +-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 +-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through +-- containers/AudioWrap. +-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase +-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, +-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: +-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). +-- +-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } +-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local T = __include("codecs/audio/Ac3/Tables") +local Decode = __include("codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +type Header = { + sampleRate: number, + frameSize: number, -- bytes + bitrate: number, -- bits per second + channels: number, + acmod: number, + lfeon: boolean, + bsid: number, +} + +-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) +-- come back with frameSize from their own frmsiz field so a scanner can step over them. +function Ac3.header(b: buffer, o: number, limit: number): Header? + if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then + return nil + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = if fs < 3 then T.RATES[fs + 1] else 0, + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip += 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip += 2 + end + if acmod == 2 then + skip += 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = if bsid > 8 then bsid - 8 else 0 + return { + sampleRate = T.RATES[fscod + 1] // 2 ^ shift, + frameSize = words * 2, + bitrate = T.BITRATES[frmsizecod // 2 + 1] * 1000 // 2 ^ shift, + channels = NFCHANS[acmod] + (if lfeon then 1 else 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +end + +-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of +-- everything after the sync word is 0 +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = if c >= 0x8000 then bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) else c * 2 + end + CRC[i + 1] = c +end + +function Ac3.crc(b: buffer, o: number, n: number): number + local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Options = { + drc: number?, -- dynamic range control: 0 = off (default, like ffmpeg -drc_scale 0), 1 = as the stream says + crc: boolean?, -- check crc2 (default true): a mismatch is Err.CHECKSUM +} + +type Decoder = { + pcm: { number }, -- the last frame: 1536 * channels interleaved floats, WAVE order + channels: number, + sampleRate: number, + blocks: { number }, -- the bit offset of each audio block in the last frame (tools: stream editing, analysis) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), +} + +function Ac3.decoder(opts: Options?): Decoder + local o: Options = opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec: Decoder + dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self: Decoder) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 +end +__FILES["codecs/audio/Ac3/Decode"] = @native function() + + + +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 +-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with +-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 +-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state +-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / +-- assert: failures return nil, "message". +local T = __include("codecs/audio/Ac3/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN +local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB + +-- 2^-e for the exponents 0 .. 24 +local POW2 = table.create(32, 0) +for e = 0, 31 do + POW2[e + 1] = 2 ^ -e +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +@native local function levels(n: number): { number } + local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +local WINDOW = Mdct.window("kbd", 512, 5) :: { number } +local PLAN512 = Mdct.new(512) :: Mdct.Plan +local PLAN256 = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 + +@native local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +-- ------------------------------------------------------------------------------------------------ state +type State = { + -- the frame header + fscod: number, + acmod: number, + lfeon: boolean, + nfchans: number, + channels: number, -- output channels + map: { number }, -- output index of slots 1 .. 6 + drc: number, -- the dynamic range scale (0 = off) + -- per channel slot (1 .. 7) + exp: { { number } }, + bap: { { number } }, + coef: { { number } }, + delay: { { number } }, + endmant: { number }, + chexpstr: { number }, + blksw: { boolean }, + dithflag: { boolean }, + fsnroffst: { number }, + fgaincod: { number }, + dbaOn: { boolean }, + dbaOffst: { { number } }, + dbaLen: { { number } }, + dbaBa: { { number } }, + -- coupling + cplinu: boolean, + chincpl: { boolean }, + phsflginu: boolean, + cplbegf: number, + cplendf: number, + cplbndstrc: { boolean }, -- [sbnd + 1], sbnd = 0 .. 17 (absolute sub-band) + cplco: { { number } }, -- [ch][sbnd + 1] + phsflg: { boolean }, -- [sbnd + 1] + cplfleak: number, + cplsleak: number, + rematflg: { boolean }, + -- bit allocation parameters + sdcycod: number, + fdcycod: number, + sgaincod: number, + dbpbcod: number, + floorcod: number, + csnroffst: number, + dynrng: { number }, -- gain for Ch1 / Ch2 + seed: number, -- dither generator + -- scratch + psd: { number }, + bndpsd: { number }, + excite: { number }, + mask: { number }, + y: { number }, + pcm: { number }, + blocks: { number }, -- the bit offset of each audio block in the last frame (for tools) +} + +@native local function arrays(n: number, size: number, v: any): { any } + local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +@native function Decode.state(): State + return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +end + +-- reset(st): forget the overlap (before a seek) +@native function Decode.reset(st: State) + for _, d in st.delay do + for i = 1, 256 do + d[i] = 0 + end + end +end + +-- ------------------------------------------------------------------------------------------------ exponents +-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize +-- bins per delta; false when an exponent leaves 0 .. 24 +@native local function exponents(e: { number }, absexp: number, ngrps: number, grpsize: number, first: number): boolean + local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = g // 25 + local d2 = (g % 25) // 5 + local d3 = g % 5 + for m = 1, 3 do + local d = if m == 1 then d1 elseif m == 2 then d2 else d3 + prev += d - 2 + if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k += 1 + end + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ bit allocation +@native local function logadd(a: number, b: number): number + local c = a - b + local adr = min(rshift(if c >= 0 then c else -c, 1), 255) + return if c >= 0 then a + LATAB[adr + 1] else b + LATAB[adr + 1] +end + +@native local function lowcomp(a: number, b0: number, b1: number, bin: number): number + if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +@native local function allocate(st: State, ch: number, start: number, stop: number, fgain: number, snroffset: number, isLfe: boolean) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor -= 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j += 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j += 1 + end + bndpsd[k + 1] = v + k += 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x += (dbknee - p) // 4 + end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b += offs[seg] + local ba = bas[seg] + local delta = if ba >= 4 then (ba - 3) * 128 else (ba - 4) * 128 + for _ = 1, lens[seg] do + if b < 50 then + mask[b + 1] += delta + end + b += 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = (psd[i + 1] - m) // 32 + bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i += 1 + end + j += 1 + until stop <= lastbin +end + +-- ------------------------------------------------------------------------------------------------ mantissas +-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) +local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) +local n1, n2, n4 = 0, 0, 0 + +@native local function dither(st: State): number + local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + return (s / 2147483648 - 1) * 0.707 +end + +-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) +@native local function mantissas(st: State, ch: number, start: number, stop: number, out: { number }, dith: boolean) + local e, bap = st.exp[ch], st.bap[ch] + for bin = start, stop - 1 do + local b = bap[bin + 1] + local v + if b == 0 then + v = if dith then dither(st) else 0 + elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[g // 9 + 1], Q1[(g % 9) // 3 + 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 -= 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[g // 25 + 1], Q2[(g % 25) // 5 + 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 -= 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[g // 11 + 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 -= 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m -= 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ audio block +@native local function readDba(st: State, ch: number) + local nseg = bits(3) + 1 + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +@native local function audblk(st: State, blk: number, limit: number): (boolean?, string?) + local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, if acmod == 0 then 2 else 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x -= 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = if st.drc == 1 then g else g ^ st.drc + elseif blk == 0 then + st.dynrng[i] = 1 + end + end + -- coupling strategy + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = if acmod == 2 then bits(1) == 1 else false + st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = if ex == 15 then mant / 16 else (mant + 16) / 32 + v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + end + end + end + -- rematrixing + if acmod == 2 then + if bits(1) == 1 then + local n = if not cplinu or cplbegf > 2 then 4 elseif cplbegf > 0 then 3 else 2 + for r = 1, 4 do + st.rematflg[r] = if r <= n then bits(1) == 1 else false + end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + -- exponent strategies + local chexpstr = st.chexpstr + chexpstr[CPL] = if cplinu then bits(2) else 0 + for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = if st.lfeon then bits(1) else 0 + if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + -- exponents + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL]] + if not exponents(st.exp[CPL], abs, (cplend - cplstrt) // grp, grp // 3, cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = (endmant[ch] - 1) // 3 + elseif s == 2 then + ngrps = (endmant[ch] - 1 + 3) // 6 + else + ngrps = (endmant[ch] - 1 + 9) // 12 + end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, grp // 3, 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation parameters + if bits(1) == 1 then + st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) + elseif blk == 0 then + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + st.cplfleak, st.cplsleak = bits(3), bits(3) + end + end + -- delta bit allocation + if bits(1) == 1 then + local modes = table.create(7, 0) + if cplinu then + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in { 1, 2, 3, 4, 5, CPL } do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + st.dbaOn[ch] = false + end + end + -- skip field + if bits(1) == 1 then + P += bits(9) * 8 + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation + local zero = st.csnroffst == 0 + if zero then + for ch = 1, nf do + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + @native local function alloc(ch: number, start: number, stop: number, isLfe: boolean) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + -- mantissas + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = if dith then dither(st) * POW2[cexp[k] + 1] else 0 + end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = if cplinu then cplstrt else min(endmant[1], endmant[2]) + local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] +@native local function synth(st: State, ch: number, short: boolean, gain: number, out: { number }, base: number, step: number) + local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW + if short then + -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) + local z = st.psd -- 256 scratch + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p += step + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds +local ORDER: { [number]: { number } } = { + [0] = { 1, 2 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +local HAS_C = { [0] = false, true, false, true, false, true, false, true } + +-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) +-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). +@native function Decode.frame(st: State, buf: buffer, len: number, drc: number): (number?, string?) + if len < 8 or buffer.len(buf) < len + Decode.PAD then + return nil, "truncated frame" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (if bsid > 10 then " (E-AC-3)" else " (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, if acmod == 0 then 2 else 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P += (bits(6) + 1) * 8 + end + local nf = NFCHANS[acmod] + local channels = nf + (if lfeon then 1 else 0) + if st.acmod ~= acmod or st.lfeon ~= lfeon then + -- a new channel layout: build the output map and forget the overlap + local order = ORDER[acmod] + local map = table.create(6, 0) + local nfront = if HAS_C[acmod] then 3 elseif acmod == 1 then 1 else 2 + for ch = 1, nf do + local o = order[ch] + map[ch] = if lfeon and o > nfront then o + 1 else o + end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[if acmod == 0 and ch == 2 then 2 else 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode +end +__FILES["codecs/audio/Ac3/Tables"] = function() + +-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression +-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, +-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window +-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five +-- decimals. No third-party code. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } +T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } +T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } + +-- the 50 bit allocation bands: first bin and width (Table 7.12) +T.BNDTAB = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, +} +T.BNDSZ = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, +} +-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +} + +-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod: number, frmsizecod: number): number + local kbps = T.BITRATES[frmsizecod // 2 + 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return kbps * 1536000 // 705600 + frmsizecod % 2 +end + +return T +end +__FILES["codecs/audio/Adpcm"] = @native function() + + + +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and +-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo +-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: +-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 +-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. +-- +-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running +-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), +-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). +-- +-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... +-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples +-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) +-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block +-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples +-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 +-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples +-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples +-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) +-- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length +-- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes +-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) +-- +-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are +-- documented on each). Never throws. +local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 +local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift +local floor = math.floor + +local Adpcm = {} + +-- ------------------------------------------------------------------------------------------------ IMA +local IMA_STEP = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, +} +local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } +-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as +-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) +local IMA_DIFF = table.create(89 * 8, 0) +-- IMA_NEXT[index * 16 + nibble + 1]: the next step index +local IMA_NEXT = table.create(89 * 16, 0) +for i = 0, 88 do + local step = IMA_STEP[i + 1] + for n = 0, 7 do + local d = rshift(step, 3) + if band(n, 1) ~= 0 then + d += rshift(step, 2) + end + if band(n, 2) ~= 0 then + d += rshift(step, 1) + end + if band(n, 4) ~= 0 then + d += step + end + IMA_DIFF[i * 8 + n + 1] = d + end + for n = 0, 15 do + IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) + end +end +Adpcm.IMA_STEP = IMA_STEP + +-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is +-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes +-- p .. p + (q0 + (count - 1) * qs) // 2. +@native function Adpcm.ima(src: buffer, p: number, q0: number, qs: number, count: number, hi: boolean, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + local o = d * 4 + local os = ds * 4 + for _ = 1, count do + local b = readu8(src, p + rshift(q, 1)) + local nib + if (band(q, 1) == 0) == hi then + nib = rshift(b, 4) + else + nib = band(b, 15) + end + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o, pred / 32768) + o += os + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step +-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while +-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet +-- (zeros before the first). +@native function Adpcm.imaQt(src: buffer, p: number, st: buffer, so: number, dst: buffer, d: number, ds: number) + local h = readu8(src, p) * 256 + readu8(src, p + 1) + local pred = band(h, 0xFF80) + if pred >= 32768 then + pred -= 65536 + end + local index = band(h, 0x7F) + if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then + writei32(st, so, pred) + writei32(st, so + 4, index) + end + Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) +end + +-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the +-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the +-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float +-- index d; returns the frame count (<= spb). +@native function Adpcm.imaWav(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number): number + if avail < 4 * ch then + return 0 + end + local groups = (avail - 4 * ch) // (4 * ch) + local frames = math.min(spb, 1 + groups * 8) + local o = d * 4 + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = math.min(readu8(src, off + c * 4 + 2), 88) + writef32(dst, o + c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + local k = 0 + while k < 8 and f < frames do + local b = readu8(src, p + rshift(k, 1)) + local nib = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred -= diff + if pred < -32768 then + pred = -32768 + end + else + pred += diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o + (f * ch + c) * 4, pred / 32768) + f += 1 + k += 1 + end + g += 1 + end + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ MS ADPCM +local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } +Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } +Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } + +-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for +-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x +-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from +-- float index d; returns the frame count (<= spb). +@native function Adpcm.msBlock(src: buffer, off: number, avail: number, ch: number, spb: number, dst: buffer, d: number, + coefs: buffer, ncoef: number, state: buffer): number + local hdr = 7 * ch + if avail < hdr or ncoef < 1 then + return 0 + end + local frames = math.min(spb, 2 + ((avail - hdr) * 2) // ch) + local o = d * 4 + for c = 0, ch - 1 do + local pi = math.min(readu8(src, off + c), ncoef - 1) + local idelta = readi16(src, off + ch + c * 2) + local s1 = readi16(src, off + 3 * ch + c * 2) + local s2 = readi16(src, off + 5 * ch + c * 2) + local so = c * 20 + writei32(state, so, readi32(coefs, pi * 8)) + writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) + writei32(state, so + 8, idelta) + writei32(state, so + 12, s1) + writei32(state, so + 16, s2) + writef32(dst, o + c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, o + (ch + c) * 4, s1 / 32768) + end + end + local total = (frames - 2) * ch + for k = 0, total - 1 do + local b = readu8(src, off + hdr + rshift(k, 1)) + local nib = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + local so = (k % ch) * 20 + local c1, c2 = readi32(state, so), readi32(state, so + 4) + local idelta = readi32(state, so + 8) + local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + p += (if nib >= 8 then nib - 16 else nib) * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = (MS_ADAPT[nib + 1] * idelta) // 256 + if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768 + idelta = 2796202 + end + writei32(state, so + 8, idelta) + writei32(state, so + 12, p) + writei32(state, so + 16, s1) + writef32(dst, o + (2 * ch + k) * 4, p / 32768) + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ CRI ADX +local F32 = buffer.create(4) +@native local function f32(x: number): number + writef32(F32, 0, x) + return readf32(F32, 0) +end + +-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the +-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +@native function Adpcm.adxCoefs(cutoff: number, rate: number): (number, number) + if rate <= 0 then + return 0, 0 + end + local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) + local a = f32(math.sqrt(2) - z) + local b = f32(math.sqrt(2) - 1) + local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) + local c1 = c * 8192 + local c2 = f32(c * c) * -4096 + c1 = if c1 >= 0 then floor(c1) else -floor(-c1) + c2 = if c2 >= 0 then floor(c2) else -floor(-c2) + return c1, c2 +end + +-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from +-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as +-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +@native function Adpcm.adx(src: buffer, p: number, pstride: number, nframes: number, c1: number, c2: number, v3: boolean, + st: buffer, so: number, dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) + if scale == 0x8001 then + scale = 0 + elseif scale >= 32768 then + scale -= 65535 -- the signed value + 1 + else + scale += 1 + end + for k = 0, 31 do + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s + if v3 then + s = n * scale + (c1 * h1) // 4096 + (c2 * h2) // 4096 + else + s = n * scale + (c1 * h1 + c2 * h2) // 4096 + end + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ PS-ADPCM +local PSX1 = { 0, 60, 115, 98, 122 } +local PSX2 = { 0, 0, -52, -55, -60 } + +-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: +-- exact in integers while the products fit a float's 24 bits +@native local function psxPred(f: number, h1: number, h2: number): number + local x = PSX1[f] * h1 + PSX2[f] * h2 + if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then + return 4 * x + end + local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 + return if v >= 0 then floor(v) else -floor(-v) +end + +-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart +-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The +-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +@native function Adpcm.psx(src: buffer, p: number, pstride: number, nframes: number, st: buffer, so: number, dst: buffer, + d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local head = readu8(src, fp) + local filter = rshift(head, 4) + local shift = band(head, 15) + if filter > 4 then + filter = 0 + end + if shift > 12 then + shift = 9 + end + local mul = 2 ^ (20 - shift) + local fi = filter + 1 + local silent = band(readu8(src, fp + 1), 15) == 7 + for k = 0, 27 do + local s = 0 + if not silent then + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = if band(k, 1) == 0 then band(b, 15) else rshift(b, 4) + if n >= 8 then + n -= 16 + end + s = (n * mul + psxPred(fi, h1, h2)) // 256 + end + h2 = h1 + h1 = s + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + writef32(dst, o, s / 32768) + o += os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ Nintendo DSP +-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). +-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. +-- p + ceil(count / 14) * 8 - 1. +@native function Adpcm.dsp(src: buffer, p: number, count: number, coefs: buffer, co: number, st: buffer, so: number, + dst: buffer, d: number, ds: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + local done = 0 + local fp = p + while done < count do + local head = readu8(src, fp) + local pi = math.min(rshift(head, 4), 7) + local scale = 2 ^ band(head, 15) * 2048 + local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) + local n14 = math.min(14, count - done) + for k = 0, n14 - 1 do + local b = readu8(src, fp + 1 + rshift(k, 1)) + local n = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + if n >= 8 then + n -= 16 + end + local s = (n * scale + 1024 + c1 * h1 + c2 * h2) // 2048 + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o += os + end + done += n14 + fp += 8 + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ encoders +-- the nearest s16 to x * 32768 (NaN -> 0) +@native local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end +Adpcm.toS16 = toS16 + +-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) +@native local function imaNibble(x: number, pred: number, index: number): number + local base = index * 8 + 1 + local best, bestErr = 0, math.huge + for m = 0, 7 do + local diff = IMA_DIFF[base + m] + local up = math.min(pred + diff, 32767) + local e = math.abs(x - up) + if e < bestErr then + best, bestErr = m, e + end + local down = math.max(pred - diff, -32768) + e = math.abs(x - down) + if e < bestErr then + best, bestErr = m + 8, e + end + end + return best +end + +-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... +-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. +-- p + (q0 + (count - 1) * qs) // 2. +@native function Adpcm.imaEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, q0: number, qs: number, hi: boolean) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + for i = 0, count - 1 do + local v = toS16(readf32(x, (xi + i * xs) * 4)) + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = p + rshift(q, 1) + local b = readu8(out, bp) + if (band(q, 1) == 0) == hi then + b = bor(band(b, 0x0F), lshift(nib, 4)) + else + b = bor(band(b, 0xF0), nib) + end + writeu8(out, bp, b) + q += qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames +-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch +-- bytes carrying the step index from block to block. +@native function Adpcm.imaWavEncode(x: buffer, xf: number, n: number, ch: number, spb: number, st: buffer, out: buffer, off: number) + local groups = (spb - 1) // 8 + for c = 0, ch - 1 do + local so = c * 8 + local first = if n > 0 then toS16(readf32(x, (xf * ch + c) * 4)) else 0 + writei32(st, so, first) + local index = math.clamp(readi32(st, so + 4), 0, 88) + writei32(st, so + 4, index) + buffer.writei16(out, off + c * 4, first) + writeu8(out, off + c * 4 + 2, index) + writeu8(out, off + c * 4 + 3, 0) + local pred = first + for g = 0, groups - 1 do + local gp = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + local f = 1 + g * 8 + k + local v = if f < n then toS16(readf32(x, ((xf + f) * ch + c) * 4)) else pred + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = if nib >= 8 then math.max(pred - diff, -32768) else math.min(pred + diff, 32767) + index = IMA_NEXT[index * 16 + nib + 1] + local bp = gp + rshift(k, 1) + if band(k, 1) == 0 then + writeu8(out, bp, nib) + else + writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) + end + end + end + writei32(st, so + 4, index) + end +end + +-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first +-- delta; returns the squared error and the nibbles in nibs (when given) +@native local function msTrial(xs: { number }, n: number, c1: number, c2: number, delta0: number, nibs: { number }?): number + local s1, s2 = xs[2], xs[1] + local idelta = delta0 + local err = 0 + for i = 3, n do + local p = s1 * c1 + s2 * c2 + p = if p >= 0 then p // 256 else -((-p) // 256) + local e = xs[i] - p + local nib = if e >= 0 then (e + idelta // 2) // idelta else -((-e + idelta // 2) // idelta) + nib = math.clamp(nib, -8, 7) + local v = math.clamp(p + nib * idelta, -32768, 32767) + err += (xs[i] - v) * (xs[i] - v) + if nibs then + nibs[i] = band(nib, 15) + end + idelta = math.clamp((MS_ADAPT[band(nib, 15) + 1] * idelta) // 256, 16, 2796202) + s2 = s1 + s1 = v + end + return err +end + +-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf +-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel +-- takes the predictor with the least error. +@native function Adpcm.msEncode(x: buffer, xf: number, n: number, ch: number, spb: number, out: buffer, off: number) + local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local xs = table.create(spb, 0) + local nibs = table.create(spb, 0) + local all = table.create(spb * ch, 0) + for c = 0, ch - 1 do + for i = 1, spb do + xs[i] = if i <= n then toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) else 0 + end + -- the first delta from the first steps + local sum = 0 + for i = 3, math.min(spb, 10) do + sum += math.abs(xs[i] - xs[i - 1]) + end + local delta0 = math.clamp(sum // 16, 16, 32767) + local best, bestErr = 1, math.huge + for k = 1, 7 do + local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) + if e < bestErr then + best, bestErr = k, e + end + end + msTrial(xs, spb, C1[best], C2[best], delta0, nibs) + writeu8(out, off + c, best - 1) + writeu16(out, off + ch + c * 2, delta0) + buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) + buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) + for i = 3, spb do + all[(i - 3) * ch + c + 1] = nibs[i] + end + end + local total = (spb - 2) * ch + for k = 0, total - 1, 2 do + writeu8(out, off + 7 * ch + k // 2, all[k + 1] * 16 + (all[k + 2] or 0)) + end +end + +-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and +-- the nibbles in nibs when given; returns the error and the new history +@native local function adxTrial(xs: { number }, scale: number, c1: number, c2: number, h1: number, h2: number, nibs: { number }?): (number, number, number) + local err = 0 + for k = 1, 32 do + local pred = (c1 * h1 + c2 * h2) // 4096 + local e = xs[k] - pred + local n = if e >= 0 then (e + scale // 2) // scale else -((-e + scale // 2) // scale) + n = math.clamp(n, -8, 7) + local s = math.clamp(n * scale + pred, -32768, 32767) + err += (xs[k] - s) * (xs[k] - s) + if nibs then + nibs[k] = band(n, 15) + end + h2 = h1 + h1 = s + end + return err, h1, h2 +end + +-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame +-- past count is padded with silence. State as Adpcm.adx. +@native function Adpcm.adxEncode(x: buffer, xi: number, xs: number, count: number, c1: number, c2: number, st: buffer, so: number, + out: buffer, p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(32, 0) + local nibs = table.create(32, 0) + for f = 0, (count + 31) // 32 - 1 do + local peak = 0 + local a, b = h1, h2 + for k = 1, 32 do + local i = f * 32 + k - 1 + local s = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + v[k] = s + peak = math.max(peak, math.abs(s - (c1 * a + c2 * b) // 4096)) + b = a + a = s + end + -- the scale that covers the open-loop residual peak, and a few around it, closed loop + local base = math.max(1, (peak + 6) // 7) + local best, bestErr = base, math.huge + for _, m in { 1, 0.75, 1.25, 0.5, 1.6 } do + local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) + local e = adxTrial(v, sc, c1, c2, h1, h2, nil) + if e < bestErr then + best, bestErr = sc, e + end + end + local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) + h1, h2 = n1, n2 + local fp = p + f * pstride + writeu8(out, fp, rshift(best - 1, 8)) + writeu8(out, fp + 1, band(best - 1, 255)) + for k = 0, 15 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM +-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is +-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. +@native function Adpcm.psxEncode(x: buffer, xi: number, xs: number, count: number, st: buffer, so: number, out: buffer, + p: number, pstride: number) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(28, 0) + local nibs = table.create(28, 0) + for f = 0, (count + 27) // 28 - 1 do + for k = 1, 28 do + local i = f * 28 + k - 1 + v[k] = if i < count then toS16(readf32(x, (xi + i * xs) * 4)) else 0 + end + local bestErr, bestHead = math.huge, 0 + for fi = 1, 5 do + for shift = 0, 12 do + local mul = 2 ^ (20 - shift) + local a, b = h1, h2 + local err = 0 + for k = 1, 28 do + local pred = psxPred(fi, a, b) + local n = floor((v[k] * 256 - pred) / mul + 0.5) + n = if n > 7 then 7 elseif n < -8 then -8 else n + local s = (n * mul + pred) // 256 + local c = if s > 32767 then 32767 elseif s < -32768 then -32768 else s + err += (v[k] - c) * (v[k] - c) + if err >= bestErr then + break + end + b = a + a = s + end + if err < bestErr then + bestErr, bestHead = err, (fi - 1) * 16 + shift + end + end + end + -- the winner again, for its nibbles and history + local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) + local mul = 2 ^ (20 - shift) + for k = 1, 28 do + local pred = psxPred(fi, h1, h2) + local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) + nibs[k] = band(n, 15) + h2 = h1 + h1 = (n * mul + pred) // 256 + end + local fp = p + f * pstride + writeu8(out, fp, bestHead) + writeu8(out, fp + 1, 0) + for k = 0, 13 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ ModPlug +-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at +-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). +-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +@native function Adpcm.modplug(src: buffer, p: number, count: number, dst: buffer, d: number) + local tab = table.create(16, 0) + for k = 0, 15 do + tab[k + 1] = buffer.readi8(src, p + k) + end + local v = 0 + for i = 0, count - 1 do + local b = readu8(src, p + 16 + rshift(i, 1)) + local nib = if band(i, 1) == 0 then band(b, 15) else rshift(b, 4) + v = (v + tab[nib + 1] + 128) % 256 - 128 + writef32(dst, (d + i) * 4, v / 128) + end +end + +-- ------------------------------------------------------------------------------------------------ Flash ADPCM +-- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of +-- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step +-- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in +-- the top bit, the magnitude bits adding step, step/2, ... and the final step/2^(bits-1) (as ffmpeg's adpcm_swf and +-- the spec's reference decoder do); the step index moves by SWF_INDEX[bits]. The last block may be short. +local SWF_INDEX: { { number } } = { + { -1, 2 }, + { -1, -1, 2, 4 }, + { -1, -1, -1, -1, 2, 4, 6, 8 }, + { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, +} + +-- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1) +@native function Adpcm.swfFrames(src: buffer, p: number, n: number, ch: number): number + if n < 1 or ch < 1 then + return 0 + end + local bits = rshift(readu8(src, p), 6) + 2 + local total = n * 8 - 2 + local hdr = 22 * ch + local block = hdr + bits * ch * 4095 + local blocks = total // block + local left = total - blocks * block + local frames = blocks * 4096 + if left >= hdr then + frames += 1 + (left - hdr) // (bits * ch) + end + return frames +end + +-- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0 +@native local function msb(src: buffer, p: number, e: number, pos: number, k: number): number + local q = p + rshift(pos, 3) + local v = readu8(src, q) * 65536 + if q + 1 < e then + v += readu8(src, q + 1) * 256 + end + if q + 2 < e then + v += readu8(src, q + 2) + end + return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) +end + +-- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns +-- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only. +@native function Adpcm.swf(src: buffer, p: number, n: number, ch: number, dst: buffer, d: number): number + local frames = Adpcm.swfFrames(src, p, n, ch) + if frames == 0 then + return 0 + end + local e = p + n + local bits = rshift(readu8(src, p), 6) + 2 + local tab = SWF_INDEX[bits - 1] + local k0 = lshift(1, bits - 2) + local sign = lshift(1, bits - 1) + local mask = sign - 1 + local pred = table.create(ch, 0) + local index = table.create(ch, 0) + local pos = 2 + local o = d * 4 + local done = 0 + while done < frames do + for c = 1, ch do + local v = msb(src, p, e, pos, 16) + if v >= 32768 then + v -= 65536 + end + pred[c] = v + index[c] = msb(src, p, e, pos + 16, 6) + pos += 22 + writef32(dst, o, v / 32768) + o += 4 + end + done += 1 + local m = math.min(4095, frames - done) + for _ = 1, m do + for c = 1, ch do + local code = msb(src, p, e, pos, bits) + pos += bits + local step = IMA_STEP[math.clamp(index[c], 0, 88) + 1] + local diff = 0 + local k = k0 + while k > 0 do + if band(code, k) ~= 0 then + diff += step + end + step = rshift(step, 1) + k = rshift(k, 1) + end + diff += step + local v = pred[c] + if band(code, sign) ~= 0 then + v -= diff + else + v += diff + end + v = math.clamp(v, -32768, 32767) + pred[c] = v + index[c] = math.clamp(index[c] + tab[band(code, mask) + 1], 0, 88) + writef32(dst, o, v / 32768) + o += 4 + end + end + done += m + end + return frames +end + +return Adpcm +end +__FILES["codecs/audio/Adpcm/Decoder"] = function() + +-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the +-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus +-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it +-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else +-- decodes forward from the nearest earlier snapshot. New in rosetta. +-- +-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) +-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) +-- frames = total, -- output frames +-- state = st, -- the codec state buffer decode advances +-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 +-- restore = function(i) return false end, -- optional: set st for packet i, true if it could +-- }) +-- +-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: +-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every +-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) +-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) +-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes +-- per channel), raw or inside AIFF-C / CAF +-- +-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +local Err = __include("core/Err") +local Stream = __include("codecs/audio/Stream") +local Adpcm = __include("codecs/audio/Adpcm") + +local Decoder = {} + +type Spec = { + count: number, + packetFrames: number, + frames: number, + state: buffer, + decode: (i: number, out: buffer) -> (number?, Err.Err?), + restore: ((i: number) -> boolean)?, +} + +function Decoder.packets(dec: any, spec: Spec): (any, Err.Err?) + local ch = dec.channels + local pf = spec.packetFrames + local st = spec.state + local out = buffer.create(pf * ch * 4) + local decodeP = spec.decode + local restore = spec.restore + local snaps: { [number]: buffer } = {} + local nextPacket = 1 + local function snap(i: number) + if not snaps[i] then + local b = buffer.create(buffer.len(st)) + buffer.copy(b, 0, st) + snaps[i] = b + end + end + snap(1) + local function decode(i: number): (number?, Err.Err?) + if i ~= nextPacket then + if snaps[i] then + buffer.copy(st, 0, snaps[i]) + elseif restore and restore(i) then + -- the format set the state (BRSTM's seek table) + else + local j = i - 1 + while j > 1 and not snaps[j] do + j -= 1 + end + buffer.copy(st, 0, snaps[j]) + for k = j, i - 1 do + local n, e = decodeP(k, out) + if not n then + return nil, e + end + snap(k + 1) + end + end + end + local n, e = decodeP(i, out) + if n then + nextPacket = i + 1 + snap(i + 1) + end + return n, e + end + return Stream.packets(dec, { + count = spec.count, + start = function(i: number): number + return (i - 1) * pf + end, + decode = decode, + pcm = function(): buffer + return out + end, + reset = function() end, + stop = spec.frames, + }) +end + +-- ------------------------------------------------------------------------------------------------ layouts +local FRAME: { [string]: number } = { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame +local SPF: { [string]: number } = { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame + +-- PCM samples of one channel into every ds-th float of dst from float d +local function pcm(kind: string, src: buffer, p: number, n: number, dst: buffer, d: number, ds: number) + if kind == "s8" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) + end + elseif kind == "s16le" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) + end + else + for k = 0, n - 1 do + local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) + buffer.writef32(dst, (d + k * ds) * 4, (if v >= 32768 then v - 65536 else v) / 32768) + end + end +end + +type InterleavedSpec = { + kind: "psx" | "adx" | "dsp" | "s16be" | "s16le" | "s8", -- ADPCM frames, or PCM samples laid out the same way + buf: buffer, + offset: number, -- the first row + size: number, -- data bytes (rows past it are cut; a truncated file decodes its whole frames) + interleave: number, -- bytes per channel per row (a multiple of the frame size; mono: any multiple) + lastInterleave: number?, -- bytes per channel in the last row (BRSTM's padded last block), default interleave + frames: number?, -- frames to output (default: what the data holds) + c1: number?, -- adx: the predictor (Adpcm.adxCoefs) + c2: number?, + v3: boolean?, -- adx: version 3 rounding + coefs: buffer?, -- dsp: 16 i32 per channel + hist: { number }?, -- initial history, h1 / h2 per channel (default 0) + restore: ((row: number, st: buffer) -> boolean)?, -- the exact history at the start of a row (BRSTM ADPC) +} + +-- interleaved(dec, spec) -> Decoder | nil, Err +function Decoder.interleaved(dec: any, spec: InterleavedSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local fsize, spf = FRAME[kind], SPF[kind] + local il = spec.interleave + local last = spec.lastInterleave or il + if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) + end + local buf, base, size = spec.buf, spec.offset, spec.size + local rowBytes = il * ch + -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) + local rows = math.max(1, math.ceil(size / rowBytes)) + local function rowFrames(r: number): number -- the frames row r (0-based) holds whole in every channel + local width = if r == rows - 1 then last else il + -- channel c sits at c * width in the row: the last channel is the one a cut file shortens + local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) + return (per // fsize) * spf + end + local fullFrames = (il // fsize) * spf + local total = (rows - 1) * fullFrames + rowFrames(rows - 1) + local frames = math.min(spec.frames or total, total) + local st = buffer.create(8 * ch) + if spec.hist then + for c = 0, ch - 1 do + buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) + buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) + end + end + local rowsPer = if spec.restore then 1 else math.max(1, 4096 // fullFrames) + local pf = rowsPer * fullFrames + local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs + local restore = spec.restore + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / pf)), + packetFrames = pf, + frames = frames, + state = st, + restore = if restore + then function(i: number): boolean + return restore(i - 1, st) + end + else nil, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local got = 0 + for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do + local n = math.min(rowFrames(r), frames - r * fullFrames) + if n <= 0 then + break + end + local nf = math.ceil(n / spf) + local width = if r == rows - 1 then last else il + for c = 0, ch - 1 do + local p = base + r * rowBytes + c * width + local d = got * ch + c + if kind == "psx" then + Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) + elseif kind == "adx" then + Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) + elseif kind == "dsp" then + Adpcm.dsp(buf, p, n, coefs :: buffer, c * 64, st, c * 8, out, d, ch) + else + pcm(kind, buf, p, n, out, d, ch) + end + end + got += n + end + return got, nil + end, + }) +end + +type NibbleSpec = { + buf: buffer, + offset: number, + size: number, -- bytes + hi: boolean?, -- the high nibble first (DVI / KVAG); default low first + frames: number?, -- default: every whole frame of nibbles +} + +-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... +function Decoder.nibbles(dec: any, spec: NibbleSpec): (any, Err.Err?) + local ch = dec.channels + local buf, base = spec.buf, spec.offset + local frames = math.min(spec.frames or math.huge, (spec.size * 2) // ch) + local st = buffer.create(8 * ch) + local hi = spec.hi == true + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / 4096)), + packetFrames = 4096, + frames = frames, + state = st, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local f0 = (i - 1) * 4096 + local n = math.min(4096, frames - f0) + for c = 0, ch - 1 do + Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) + end + return n, nil + end, + }) +end + +type BlockSpec = { + kind: "ms" | "ima_wav" | "ima_qt", + buf: buffer, + offset: number, + size: number, + blockAlign: number?, -- ms / ima_wav: bytes per block + frames: number?, -- default: what the blocks hold + coefs: { number }?, -- ms: coefficient pairs, flat (default the 7 standard pairs) +} + +-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers +function Decoder.blockFrames(kind: string, ba: number, ch: number): number? + if kind == "ima_qt" then + return 64 + elseif kind == "ms" then + return if ba >= 7 * ch then (ba - 7 * ch) * 2 // ch + 2 else nil + end + return if ba >= 4 * ch then (ba - 4 * ch) * 2 // ch + 1 else nil +end + +-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has +function Decoder.blocks(dec: any, spec: BlockSpec): (any, Err.Err?) + local ch = dec.channels + local kind = spec.kind + local ba = if kind == "ima_qt" then 34 * ch else spec.blockAlign or 0 + local spb = Decoder.blockFrames(kind, ba, ch) + if not spb then + return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + local buf, base, size = spec.buf, spec.offset, spec.size + local full = size // ba + local rest = size - full * ba + local total = full * spb + if kind ~= "ima_qt" and rest > 0 then + -- a partial last block: the frames it holds whole + if kind == "ms" then + total += if rest >= 7 * ch then math.min(spb, 2 + ((rest - 7 * ch) * 2) // ch) else 0 + elseif rest >= 4 * ch then + total += math.min(spb, 1 + ((rest - 4 * ch) // (4 * ch)) * 8) + end + end + local frames = math.min(spec.frames or total, total) + local ncoef = 7 + local cf = spec.coefs + if cf and #cf >= 2 then + ncoef = math.min(256, #cf // 2) + end + local coefs = buffer.create(ncoef * 8) + for k = 0, ncoef - 1 do + buffer.writei32(coefs, k * 8, if cf and #cf >= 2 then cf[k * 2 + 1] else Adpcm.MS_COEF1[k + 1]) + buffer.writei32(coefs, k * 8 + 4, if cf and #cf >= 2 then cf[k * 2 + 2] else Adpcm.MS_COEF2[k + 1]) + end + local scratch = buffer.create(20 * ch) + dec.frames = frames + dec.duration = frames / dec.sampleRate + dec.blockAlign = ba + dec.samplesPerBlock = spb + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / spb)), + packetFrames = spb, + frames = frames, + state = scratch, + decode = function(i: number, out: buffer): (number?, Err.Err?) + local off = base + (i - 1) * ba + local avail = math.min(ba, base + size - off) + if kind == "ms" then + return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil + elseif kind == "ima_wav" then + return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil + end + if avail < ba then + return 0, nil + end + for c = 0, ch - 1 do + Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) + end + return 64, nil + end, + }) +end + +return Decoder +end +__FILES["codecs/audio/Alac"] = function() + +-- 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("@rosetta/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) +-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) +-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) +-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled +-- +-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Alac/Decode") +local Encode = __include("codecs/audio/Alac/Encode") + +local Alac = {} + +type Config = { + frameLength: number, -- samples per packet (4096) + compatibleVersion: number, + bitDepth: number, + pb: number, -- 40 + mb: number, -- 10 + kb: number, -- 14 + channels: number, + maxRun: number, -- 255 + maxFrameBytes: number, + avgBitRate: number, + sampleRate: number, +} + +-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count +local TO_WAV: { { number } } = { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +-- the element layout (channels per element) the encoder writes +local ELEMENTS: { { number } } = { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +-- config(buf, offset?, length?) -> Config | nil, Err +function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) + local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c: Config = { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +-- cookie(cfg) -> the 24-byte ALACSpecificConfig +function Alac.cookie(c: Config): buffer + local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Decoder = { + config: Config, + pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k]] = src[base + k] + end + end + end + return frames, nil +end + +-- decoder(cfg) -> Decoder +function Alac.decoder(cfg: Config): Decoder + return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end + +-- ------------------------------------------------------------------------------------------------ encoder +type Encoder = { + config: Config, + encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), + state: Encode.State, + bytes: number, + frames: number, +} + +local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) + local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes += n + self.frames += frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +type EncoderOptions = { + sampleRate: number, + channels: number, -- 1 .. 8 + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- default 4096 +} + +-- encoder(opts) -> Encoder | nil, Err +function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) + if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg: Config = { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac +end +__FILES["codecs/audio/Alac/Decode"] = @native function() + + + +-- 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. +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + +type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) + pred: { { number } }, -- per element channel (0, 1): residuals / predictor output + mix: { { number } }, + shift: { number }, + out: { number }, -- interleaved output samples (integers), frames * channels +} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. +@native local function bitsAt(b: buffer, pos: number, n: number): number + local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +@native local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +@native local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) + local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos += 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos += pre + 1 + if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +-- residuals: n values into out[1..n]; returns the new bit position or -1 +@native local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x += signMod + signMod = 0 + out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 + if x > 0xFFFF then + history = 0xFFFF + else + history += x * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i += run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i += 1 + end + return pos +end + +-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place +@native local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i += 1 + end + local half = if quant > 0 then POW[quant] else 0 + local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val += (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = if e > 0 then 1 else -1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + e -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the +-- ALAC element order. +@native function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 -- next output channel + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos += 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = if tag == 1 then 2 else 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos += 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos += 12 + local h = bitsAt(b, pos, 4) + pos += 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos += 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos += 16 + if mixRes >= 128 then + mixRes -= 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + 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) :: 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 + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos += 16 + coefs[c][j] = if v >= 32768 then v - 65536 else v + end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos += shift * n * nch + end + for c = 1, nch do + local p = if c == 1 then p0 else p1 + local mb = if c == 1 then m0 else m1 + pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp += shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos += bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + -- unmix + shifted bytes -> interleaved output + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch += nch + elseif tag == 4 then -- DSE + pos += 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos += 9 + if count == 255 then + count += bitsAt(b, pos, 8) + pos += 8 + end + if align == 1 then + pos = (pos + 7) // 8 * 8 + end + pos += count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos += 4 + if count == 15 then + count += bitsAt(b, pos, 8) - 1 + pos += 8 + end + pos += count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + -- missing channels: silence + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +-- the scratch state for a configuration +@native function Decode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode +end +__FILES["codecs/audio/Alac/Encode"] = @native function() + + + +-- 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 +-- input. Written for this library from the ALAC format; no third-party code. Never throws. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + out: buffer, -- packet scratch + pos: number, -- bit position in out + cap: number, -- bits available + u: { number }, + v: { number }, + err: { number }, + work: { number }, +} + +-- ------------------------------------------------------------------------------------------------ bit writer +@native local function put(st: State, v: number, n: number) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = if n < free then n else free + local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos += take + n -= take + end + st.pos = pos +end + +@native local function putBig(st: State, v: number, n: number) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +-- ------------------------------------------------------------------------------------------------ rice code +@native local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the bits of one scalar (no writing) +@native local function scalarBits(x: number, k: number, m: number, bps: number): number + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + (if r == 0 then k - 1 else k) +end + +@native local function scalar(st: State, x: number, k: number, m: number, bps: number) + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + -- pre ones and a zero + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +-- code the residuals e[1..n] (write = false: just count the bits) +@native local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = if v >= 0 then 2 * v else -2 * v - 1 + local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits += scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history += zz * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run += 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits += scalarBits(run, k, m, 16) + end + i += run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i += 1 + end + return bits +end + +-- ------------------------------------------------------------------------------------------------ prediction +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +@native local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i += 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val += (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = if r > 0 then 1 else -1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + r -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised +@native local function lpc(x: { number }, n: number, order: number, work: { number }): { number } + local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s += work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc -= a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv *= (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits +@native local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) + local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in { 4, 8 } do + if order >= n then + continue + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end + end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index +-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts +@native function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer + local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in elements do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + -- the mix with the smallest first-difference energy + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost += abs(uu - pu) + abs(vv - pv) + pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + -- header + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, if mixRes == 0 then 0 else 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = if c == 1 then u else v + local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = if c == 1 then u else v + local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch += nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + -- uncompressed frame + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in elements do + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch += nch + end + end + put(st, 7, 3) -- END + local bytes = (st.pos + 7) // 8 + local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +@native function Encode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode +end +__FILES["codecs/audio/Ape"] = function() + +-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 +-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / +-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame +-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the +-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, +-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, +-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit +-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned +-- as numbers either way). +-- +-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table +-- local dec = Ape.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Ape/Decode") + +local Ape = {} + +type Info = { + version: number, -- file version * 1000 (3990) + programVersion: number, -- 13280 (0 when not stored) + level: number, -- 1000 (fast) .. 5000 (insane) + flags: number, + channels: number, + sampleRate: number, + bitsPerSample: number, + float: boolean, + blocksPerFrame: number, + finalFrameBlocks: number, + totalFrames: number, + totalBlocks: number, + frameStart: { number }, -- byte offset of each frame + firstFrame: number, -- byte offset of frame 1 (the word alignment origin) + dataEnd: number, -- the end of the frame data + limit: number, -- the end of the file data (frames past it are truncated) + md5: string?, +} + +local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 + +-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil +function Ape.find(buf: buffer, base: number, limit: number): number? + local at = base + if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then + local size = 0 + for i = 6, 9 do + size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) + end + local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 + at += size + (if footer then 20 else 10) + if not footer then + while at < limit and buffer.readu8(buf, at) == 0 do + at += 1 + end + end + end + if at + 4 > limit then + return nil + end + local id = buffer.readstring(buf, at, 4) + if id == "MAC " or id == "MACF" then + return at + end + local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) + local k = string.find(s, "MAC ", 1, true) + return if k then at + k - 1 else nil +end + +-- info(buf, base, limit) -> Info | nil, Err +function Ape.info(buf: buffer, base: number, limit: number): (Info?, Err.Err?) + local at = Ape.find(buf, base, limit) + if not at then + return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") + end + local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) + local r = Bytes.reader(buf, at, limit - at) + r:skip(4) + local version = r:u16le() + if r.err then + return nil, r.err + end + if version < 3950 then + return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") + end + local info: any = { version = version, programVersion = 0 } + local seekCount, seekAt + if version >= 3980 then + info.programVersion = r:u16le() + local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() + local md5 = r:string(16) + r:seek(descBytes) + info.level = r:u16le() + info.flags = r:u16le() + info.blocksPerFrame = r:u32le() + info.finalFrameBlocks = r:u32le() + info.totalFrames = r:u32le() + info.bitsPerSample = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + if r.err then + return nil, r.err + end + seekAt = at + descBytes + headBytes + seekCount = seekBytes // 4 + info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 + local _ = termBytes + local hex = table.create(16, "") + local any = false + for k = 1, 16 do + local b = string.byte(md5, k) + any = any or b ~= 0 + hex[k] = string.format("%02x", b) + end + info.md5 = if any then table.concat(hex) else nil + else + info.level = r:u16le() + info.flags = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + local headerBytes = r:u32le() + r:u32le() -- terminating bytes + info.totalFrames = r:u32le() + info.finalFrameBlocks = r:u32le() + if bit32.band(info.flags, FLAG_PEAK) ~= 0 then + r:skip(4) + end + seekCount = info.totalFrames + if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then + seekCount = r:u32le() + end + if bit32.band(info.flags, FLAG_WAVHDR) == 0 then + r:skip(headerBytes) + end + if r.err then + return nil, r.err + end + info.blocksPerFrame = 73728 * 4 + info.bitsPerSample = if bit32.band(info.flags, FLAG_8) ~= 0 then 8 elseif bit32.band(info.flags, FLAG_24) ~= 0 then 24 else 16 + seekAt = r:tell() + info.dataEnd = limit + end + local C, bits = info.channels, info.bitsPerSample + if C < 1 or C > 32 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) + end + if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") + end + if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then + return nil, Err.new(Err.CORRUPT, "bad header") + end + if info.totalFrames < 1 then + return nil, Err.new(Err.CORRUPT, "no frames") + end + info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 + info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks + if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then + return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") + end + local starts = table.create(info.totalFrames, 0) + local add, prev = 0, 0 + for i = 1, info.totalFrames do + local v = buffer.readu32(buf, seekAt + (i - 1) * 4) + if v < prev then + add += 4294967296 + end + prev = v + starts[i] = base + junk + add + v + end + for i = 1, info.totalFrames do + if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then + return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) + end + end + info.frameStart = starts + info.firstFrame = starts[1] + info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) + info.limit = limit + return info :: Info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Decoder = { + info: Info, + pcm: { number }, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.totalFrames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local start = info.frameStart[i] + local rem = (start - info.firstFrame) % 4 + local want = (if i < info.totalFrames then info.frameStart[i + 1] else info.dataEnd) + 4 + local stop = math.min(want, info.limit, buffer.len(buf)) + if start + 8 > stop then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) + end + local n = if i < info.totalFrames then info.blocksPerFrame else info.finalFrameBlocks + local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) + if not n2 then + return nil, Err.from(msg, start) + end + return n2, nil +end + +-- decoder(info) -> Decoder | nil, Err +function Ape.decoder(info: Info): (Decoder?, Err.Err?) + local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) + if not st then + return nil, Err.from(msg) + end + return { + info = info, + pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), + frame = frame, + state = st, + }, nil +end + +return Ape +end +__FILES["codecs/audio/Ape/Decode"] = @native function() + + + +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. +-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, +-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the +-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 +-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp +-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +local Crc32 = __include("core/Crc32") + +local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap +local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 +local readi16, readi32 = buffer.readi16, buffer.readi32 +local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor +local sign = math.sign + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local PAD = 64 + +-- the range coder's symbol models (UnBitArrayBase.h) +local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } + +-- symbol(total) lookup buffers (RangeOverflowTable), built on first use +local OVT: { [number]: buffer } = {} +@native local function overflowTable(rt: { number }): buffer + local t = OVT[rt[2]] + if t then + return t + end + t = buffer.create(65536) + local o = 0 + for z = 0, 65535 do + if z >= rt[o + 2] then + o += 1 + end + writeu8(t, z, o) + end + OVT[rt[2]] = t + return t +end + +@native local function wrap32(v: number): number + if v >= TWO31 or v < -TWO31 then + return (v + TWO31) % TWO32 - TWO31 + end + return v +end + +-- C integer division by 2 (toward zero) +@native local function half(v: number): number + return if v >= 0 then v // 2 else -((-v) // 2) +end + +type Filter = { order: number, shift: number, M: buffer, I: buffer, D: buffer } +type State = { + version: number, + bits: number, + channels: number, + filters: { Filter }, -- per level, applied last to first on decode (as m_spNNFilter2, 1, 0) + V: { { number } }, -- per channel: the frame's values through the stages + S: buffer, -- the frame bytes, word-swapped (+ PAD zeros) + crcbuf: buffer, + scratch: buffer, + lastX: number, + rc: Rc, +} + +local FILTERS: { [number]: { number } } = { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order + [1000] = {}, + [2000] = { 16, 11 }, + [3000] = { 64, 11 }, + [4000] = { 256, 13, 32, 10 }, + [5000] = { 1280, 15, 256, 13, 16, 11 }, +} + +-- state(version, level, bits, channels) -> State | nil, message +@native function Decode.state(version: number, level: number, bits: number, channels: number): (State?, string?) + local spec = FILTERS[level] + if not spec then + return nil, "unsupported: compression level " .. level + end + local filters: { Filter } = {} + for k = 1, #spec, 2 do + local order = spec[k] + local es = if bits >= 32 then 4 else 2 + table.insert(filters, { + order = order, + shift = spec[k + 1], + M = buffer.create(order * es), + I = buffer.create((512 + order + 1) * es), + D = buffer.create((512 + order + 1) * es), + }) + end + local V = {} + for c = 1, channels do + V[c] = {} + end + return { + version = version, + bits = bits, + channels = channels, + filters = filters, + V = V, + S = buffer.create(1024), + crcbuf = buffer.create(1024), + scratch = buffer.create(4), + lastX = 0, + rc = { q = 0, low = 0, range = 0, prev = 0 }, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ entropy +-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) +type Rc = { q: number, low: number, range: number, prev: number } +@native local function rcBits(rc: Rc, S: buffer, nb: number): number + local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 2 ^ nb + local r = 0 + if range > 0 then + r = low // range + low %= range + end + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + return r +end + +-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of +-- `order` (decode order), from byte q of st.S (the range coder starts there) +@native local function values(st: State, q: number, lim: number, n: number, order: { number }, old: boolean): (number?, string?) + local S = st.S + local V = st.V + local version = st.version + -- FlushBitArray: a dummy byte, then the first byte + local prev = readu8(S, q + 1) + q += 2 + local low = rshift(prev, 1) + local range = 128 + local nch = #order + local ksum = table.create(nch, 16384) + local kk = table.create(nch, 10) + local ovt = overflowTable(if old then RT1 else RT2) + local RT = if old then RT1 else RT2 + for b = 1, n do + for ci = 1, nch do + if q > lim then + return nil, "overrun" + end + local ks = ksum[ci] + local value + -- the overflow symbol (RangeDecodeFast(16) + the model) + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + local total = low // range + if total >= 65536 then + return nil, "bad range code" + end + local ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + if not old then + local pivot = math.max(ks // 32, 1) + while ov == 63 do + -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal + local r = 0 + for _ = 1, 2 do + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + if range == 0 then + return nil, "bad range code" + end + r = r * 65536 + low // range + low %= range + end + ov = r + if ov == 1 then + pivot = 32768 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // 65536 + total = low // range + if total >= 65536 then + return nil, "bad range code" + end + ov = readu8(ovt, total) + low -= range * RT[ov + 1] + range *= RT[ov + 2] - RT[ov + 1] + else + break + end + end + local base + if pivot >= 65536 then + local pbits = 0 + while pivot // 2 ^ pbits > 0 do + pbits += 1 + end + local split = 2 ^ (if pbits >= 16 then pbits - 16 else 0) + local pa = pivot // split + 1 + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pa + local ba = low // range + low %= range + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // split + local bb = low // range + low %= range + base = ba * split + bb + else + while range <= 8388608 do + local byte = readu8(S, q) + q += 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range *= 256 + end + range = range // pivot + base = low // range + low %= range + end + value = base + ov * pivot + else + -- 3.95 - 3.98: k bits (escape: k in 5 bits) + local rc = st.rc + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + local k + if ov == 63 then + k = rcBits(rc, S, 5) + ov = 0 + else + k = math.max(kk[ci] - 1, 0) + end + if k <= 16 or version < 3910 then + value = rcBits(rc, S, k) + else + local x1 = rcBits(rc, S, 16) + value = x1 + rcBits(rc, S, k - 16) * 65536 + end + value += ov * 2 ^ k + q = rc.q + low = rc.low + range = rc.range + prev = rc.prev + end + ks = (ks + (value + 1) // 2 - (ks + 16) // 32) % TWO32 + ksum[ci] = ks + if old then + local k = kk[ci] + if ks < KMIN[k + 1] then + kk[ci] = k - 1 + elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then + kk[ci] = k + 1 + end + end + V[order[ci]][b] = if value % 2 == 1 then (value - 1) // 2 + 1 else -(value // 2) + end + end + return q, nil +end + +-- ------------------------------------------------------------------------------------------------ NN filters +-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) +@native local function negBit(v: number, p2: number, m: number): boolean + return band((v // p2) % TWO32, m) ~= 0 +end + +-- the int16 dot product of the weights and the inputs from byte b (span bytes) +@native local function dot16(M: buffer, I: buffer, b: number, span: number): number + local dot = 0 + for k = 0, span - 16, 16 do + local bb = b + k + dot += readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) + end + return dot +end + +-- the same, adapting each weight after its use: M += D * dm (int16, wrapping) +@native local function dotAdapt16(M: buffer, I: buffer, D: buffer, b: number, span: number, dm: number): number + local dot = 0 + for k = 0, span - 8, 8 do + local bb = b + k + local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) + dot += readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 + writei16(M, k, m0 + readi16(D, bb) * dm) + writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) + writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) + writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) + end + return dot +end + +-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of +-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +@native local function nnFilter(f: Filter, v: { number }, n: number, newDelta: boolean, wide: boolean) + local order, M, I, D = f.order, f.M, f.I, f.D + local es = if wide then 4 else 2 + local shift = 2 ^ f.shift + local round = shift // 2 + buffer.fill(M, 0, 0, order * es) + buffer.fill(I, 0, 0, (order + 1) * es) + buffer.fill(D, 0, 0, (order + 1) * es) + local p = order -- the current element (0-based); its history is p - order .. p - 1 + local total = 512 + order + local avg = 0 + local span = order * 2 + for t = 1, n do + local x = v[t] + local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 + local dot = 0 + if wide then + local b = (p - order) * 4 + for k = 0, order * 4 - 4, 4 do + local m = readi32(M, k) + local pr = readi32(I, b + k) * m + if pr >= TWO31 or pr < -TWO31 then + pr = (pr + TWO31) % TWO32 - TWO31 + end + dot += pr + if dm ~= 0 then + writei32(M, k, m + readi32(D, b + k) * dm) + end + end + else + local b = (p - order) * 2 + dot = if dm == 0 then dot16(M, I, b, span) else dotAdapt16(M, I, D, b, span, dm) + dot = wrap32(dot) + end + local o = x + (dot + round) // shift + if not wide then + o = wrap32(o) + end + local d = 0 + local a = if o < 0 then -o else o + if newDelta then + if a > avg * 3 then + d = if (if wide then negBit(o, 33554432, 64) else o < 0) then 32 else -32 + elseif a > (avg * 4) // 3 then + d = if (if wide then negBit(o, 67108864, 32) else o < 0) then 16 else -16 + elseif a > 0 then + d = if (if wide then negBit(o, 134217728, 16) else o < 0) then 8 else -8 + end + local dd = a - avg + avg += if dd >= 0 then dd // 16 else -((-dd) // 16) + else + d = if o == 0 then 0 elseif o < 0 then 4 else -4 + end + local sat = if o > 32767 then 32767 elseif o < -32768 then -32768 else o + if wide then + local q = p * 4 + writei32(D, q, d) + if newDelta then + writei32(D, q - 4, readi32(D, q - 4) // 2) + writei32(D, q - 8, readi32(D, q - 8) // 2) + else + writei32(D, q - 16, readi32(D, q - 16) // 2) + end + writei32(D, q - 32, readi32(D, q - 32) // 2) + writei32(I, q, sat) + else + local q = p * 2 + writei16(D, q, d) + if newDelta then + writei16(D, q - 2, readi16(D, q - 2) // 2) + writei16(D, q - 4, readi16(D, q - 4) // 2) + else + writei16(D, q - 8, readi16(D, q - 8) // 2) + end + writei16(D, q - 16, readi16(D, q - 16) // 2) + writei16(I, q, sat) + end + v[t] = o + p += 1 + if p == total then + buffer.copy(I, 0, I, (p - order) * es, order * es) + buffer.copy(D, 0, D, (p - order) * es, order * es) + p = order + end + end +end + +-- ------------------------------------------------------------------------------------------------ predictor +-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 +@native local function adaptWide(v: number): number + if v == 0 then + return 0 + end + return if (v // 1073741824) % 4 >= 2 then 1 else -1 +end + +-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the +-- block, or 0), single-channel form; stereo uses predictStereo +@native local function predictOne(st: State, v: { number }, n: number) + local wide = st.bits >= 32 + local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 + local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 + local stage = 0 + for t = 1, n do + local nA = v[t] + local A0 = lastA + A3 = A2 + A2 = A1 + A1 = A0 - prevA0 + prevA0 = A0 + local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 + local cur + if wide then + cur = nA + predA // 1024 + else + cur = wrap32(nA + wrap32(predA) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + MA0 += adaptWide(A0) * s + MA1 += adaptWide(A1) * s + MA2 += adaptWide(A2) * s + MA3 += adaptWide(A3) * s + else + MA0 += sign(A0) * s + MA1 += sign(A1) * s + MA2 += sign(A2) * s + MA3 += sign(A3) * s + end + end + stage = wrap32(cur + (stage * 31) // 32) + lastA = cur + v[t] = stage + end +end + +-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] +@native local function predictStereo(st: State, X: { number }, Y: { number }, n: number) + local wide = st.bits >= 32 + -- predictor 1 (Y) + local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 + local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 + local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 + local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 + local yStage = 0 + -- predictor 0 (X) + local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 + local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 + local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 + local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 + local xStage = 0 + local lastX = 0 + for t = 1, n do + -- Y + local nA = Y[t] + local A0 = yLast + yA3 = yA2 + yA2 = yA1 + yA1 = A0 - yPrev + yPrev = A0 + local B0 = lastX - (yBin * 31) // 32 + yBin = lastX + yB4 = yB3 + yB3 = yB2 + yB2 = yB1 + yB1 = B0 - yBprev + yBprev = B0 + local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 + local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 + local cur + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + yMA0 += adaptWide(A0) * s + yMA1 += adaptWide(yA1) * s + yMA2 += adaptWide(yA2) * s + yMA3 += adaptWide(yA3) * s + yMB0 += adaptWide(B0) * s + yMB1 += adaptWide(yB1) * s + yMB2 += adaptWide(yB2) * s + yMB3 += adaptWide(yB3) * s + yMB4 += adaptWide(yB4) * s + else + yMA0 += sign(A0) * s + yMA1 += sign(yA1) * s + yMA2 += sign(yA2) * s + yMA3 += sign(yA3) * s + yMB0 += sign(B0) * s + yMB1 += sign(yB1) * s + yMB2 += sign(yB2) * s + yMB3 += sign(yB3) * s + yMB4 += sign(yB4) * s + end + end + yStage = wrap32(cur + (yStage * 31) // 32) + yLast = cur + local yv = yStage + -- X + nA = X[t] + A0 = xLast + xA3 = xA2 + xA2 = xA1 + xA1 = A0 - xPrev + xPrev = A0 + B0 = yv - (xBin * 31) // 32 + xBin = yv + xB4 = xB3 + xB3 = xB2 + xB2 = xB1 + xB1 = B0 - xBprev + xBprev = B0 + predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 + predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 + if wide then + cur = nA + (predA + predB // 2) // 1024 + else + cur = wrap32(nA + wrap32(wrap32(predA) + wrap32(predB) // 2) // 1024) + end + s = sign(nA) + if s ~= 0 then + if wide then + s = -s + xMA0 += adaptWide(A0) * s + xMA1 += adaptWide(xA1) * s + xMA2 += adaptWide(xA2) * s + xMA3 += adaptWide(xA3) * s + xMB0 += adaptWide(B0) * s + xMB1 += adaptWide(xB1) * s + xMB2 += adaptWide(xB2) * s + xMB3 += adaptWide(xB3) * s + xMB4 += adaptWide(xB4) * s + else + xMA0 += sign(A0) * s + xMA1 += sign(xA1) * s + xMA2 += sign(xA2) * s + xMA3 += sign(xA3) * s + xMB0 += sign(B0) * s + xMB1 += sign(xB1) * s + xMB2 += sign(xB2) * s + xMB3 += sign(xB3) * s + xMB4 += sign(xB4) * s + end + end + xStage = wrap32(cur + (xStage * 31) // 32) + xLast = cur + lastX = xStage + X[t], Y[t] = xStage, yv + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first +-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: +-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) +@native function Decode.frame(st: State, buf: buffer, at: number, rem: number, stop: number, n: number, P: { number }, float: boolean, cut: boolean): (number?, string?) + local C, bits = st.channels, st.bits + local len = math.max(0, stop - at) + local words = (len + 3) // 4 + local S = st.S + if buffer.len(S) < words * 4 + PAD then + S = buffer.create(words * 4 + PAD + 4096) + st.S = S + end + buffer.fill(S, 0, 0, words * 4 + PAD) + -- the bit array: 32-bit little-endian words read MSB first + for w = 0, words - 1 do + local o = at + w * 4 + if o + 4 <= stop then + writeu32(S, w * 4, byteswap(readu32(buf, o))) + else + for k = 0, 3 do + if o + k < stop then + writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) + end + end + end + end + @native local function u32be(q: number): number + return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) + end + local q = rem + if q + 16 > words * 4 + PAD then + return nil, "truncated frame" + end + local stored = u32be(q) + q += 4 + local special = 0 + if st.version > 3820 then + if stored >= TWO31 then + special = u32be(q) + q += 4 + end + stored %= TWO31 + end + -- the values + local V = st.V + local order: { number } + local mode -- "silence", "pseudo", "stereo", "mono", "multi" + if C == 1 then + if band(special, 1) ~= 0 then + mode = "silence" + order = {} + else + mode = "mono" + order = { 1 } + end + elseif C == 2 then + if band(special, 3) == 3 then + mode = "silence" + order = {} + elseif band(special, 4) ~= 0 then + mode = "pseudo" + order = { 1 } + else + mode, order = "stereo", { 2, 1 } + end + else + mode = "multi" + order = {} + for c = 1, C do + order[c] = c + end + end + local lim = words * 4 + PAD - 40 + if #order > 0 then + local qe = values(st, q, lim, n, order, st.version < 3990) + if not qe or qe > words * 4 + 8 then + return nil, if cut then "truncated frame" else "bad frame: the values run over its data" + end + -- the NN filters (last level first), then the predictors + local newDelta = st.version >= 3980 + local filters = st.filters + for _, c in order do + for f = #filters, 1, -1 do + nnFilter(filters[f], V[c], n, newDelta, bits >= 32) + end + end + if mode == "stereo" then + predictStereo(st, V[1], V[2], n) + else + for _, c in order do + predictOne(st, V[c], n) + end + end + end + -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them + local bps = bits // 8 + local cb = st.crcbuf + if buffer.len(cb) < n * C * bps then + cb = buffer.create(n * C * bps + 1024) + st.crcbuf = cb + end + local paired: { [number]: boolean } = {} -- first channel (0-based) of an X / Y pair + if C == 2 and mode == "stereo" then + paired[0] = true + elseif C == 4 and (bits == 16 or bits == 24) then + paired[0], paired[2] = true, true + elseif C >= 6 and (bits == 16 or bits == 24) then + paired[0], paired[4] = true, true + if C >= 8 then + paired[6] = true + end + end + local o = 0 + local mono = mode == "mono" or mode == "pseudo" + local X = V[1] + for t = 1, n do + local base = (t - 1) * C + local c = 0 + while c < C do + local a: number, b2: number = 0, 0 + local pair = paired[c] + if mode == "silence" then + a = 0 + b2 = 0 + elseif mono then + a = X[t] + b2 = a + elseif pair then + local x, y = V[c + 1][t], V[c + 2][t] + a = x - half(y) + b2 = a + y + else + a = V[c + 1][t] + end + local width = if pair or (C == 2) then 2 else 1 + for k = 0, width - 1 do + local s: number = if k == 0 then a else b2 + if bits == 16 then + if s < -32768 or s > 32767 then + return nil, "sample out of range" + end + writei16(cb, o, s) + o += 2 + elseif bits == 8 then + s = (s + 128) % 256 - 128 + writeu8(cb, o, s + 128) + o += 1 + elseif bits == 24 then + s = (s + 8388608) % 16777216 - 8388608 + local u = s % 16777216 + writeu16(cb, o, u % 65536) + writeu8(cb, o + 2, u // 65536) + o += 3 + else + s = wrap32(s) + writei32(cb, o, s) + o += 4 + end + P[base + c + k + 1] = s + end + c += width + end + end + local crc = Crc32.of(cb, 0, o) + if crc // 2 ~= stored then + return nil, "checksum: frame CRC mismatch" + end + if float then + local sc = st.scratch + for k = 1, n * C do + local u = P[k] % TWO32 + local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) + if out >= TWO31 then + out = bor(bnot(out), 0x80000000) + end + writeu32(sc, 0, out) + P[k] = readf32(sc, 0) + end + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/ApeTag"] = function() + +-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and +-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no +-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer +-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, +-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several +-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. +-- Never throws. +-- +-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) +-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) +-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, +-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } +-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +local ApeTag = {} + +type Item = { key: string, value: string, kind: string } +type Info = { start: number, stop: number, version: number, items: { Item } } + +local TO_TAG: { [string]: string } = { + year = "date", + ["album artist"] = "albumartist", + albumartist = "albumartist", + tracknumber = "track", + discnumber = "disc", + description = "comment", +} +local KINDS = { [0] = "text", "binary", "link", "text" } + +-- tagKey(itemKey) -> the Types.Tags key +function ApeTag.tagKey(key: string): string + local k = string.lower(key) + return TO_TAG[k] or k +end + +-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items +-- must lie at or after `start` (default 0) +function ApeTag.parse(buf: buffer, footer: number, start: number?): ({ [string]: string }?, Info?) + local lo = start or 0 + local n = buffer.len(buf) + if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then + return nil, nil + end + local version = buffer.readu32(buf, footer + 8) + local size = buffer.readu32(buf, footer + 12) -- items + footer + local count = buffer.readu32(buf, footer + 16) + local flags = buffer.readu32(buf, footer + 20) + if size < 32 or footer + 32 - size < lo then + return nil, nil + end + local p = footer + 32 - size + local first = p + if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then + first = p - 32 + end + local stop = footer + local tags: { [string]: string } = {} + local items: { Item } = {} + for _ = 1, math.min(count, 65536) do + if p + 9 > stop then + break + end + local len = buffer.readu32(buf, p) + local iflags = buffer.readu32(buf, p + 4) + local k = p + 8 + while k < stop and buffer.readu8(buf, k) ~= 0 do + k += 1 + end + if k >= stop then + break + end + local key = buffer.readstring(buf, p + 8, k - p - 8) + local v0 = k + 1 + if len > stop - v0 then + break + end + local value = buffer.readstring(buf, v0, len) + local kind = if version >= 2000 then KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] else "text" + table.insert(items, { key = key, value = value, kind = kind }) + if kind == "text" and key ~= "" then + local tk = ApeTag.tagKey(key) + local s = (string.gsub(value, "%z+$", "")) + s = (string.gsub(s, "%z", "; ")) + local old = tags[tk] + tags[tk] = if old then old .. "; " .. s else s + end + p = v0 + len + end + return tags, { start = first, stop = footer + 32, version = version, items = items } +end + +-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte +-- ID3v1 tag ("TAG") there +function ApeTag.find(buf: buffer, start: number, limit: number): ({ [string]: string }?, Info?) + if limit > buffer.len(buf) then + limit = buffer.len(buf) + end + if limit - start >= 32 then + local tags, info = ApeTag.parse(buf, limit - 32, start) + if tags then + return tags, info + end + end + if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then + return ApeTag.parse(buf, limit - 160, start) + end + return nil, nil +end + +return ApeTag +end +__FILES["codecs/audio/Flac"] = function() + +-- 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 = __include("codecs/audio/Flac/Frame"), + Encode = __include("codecs/audio/Flac/Encode"), +} + +return Flac +end +__FILES["codecs/audio/Flac/Encode"] = @native function() + + + +-- 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/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 = __include("core/Bits") +local Md5 = __include("core/Md5") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Frame = __include("codecs/audio/Flac/Frame") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ CRCs +-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) +@native local function crc8(b: buffer, o: number, n: number): number + return Frame.crc8(b, o, o + n) +end +@native local function crc16(b: buffer, o: number, n: number): number + return Frame.crc16(b, o, o + n) +end +Encode.crc8, Encode.crc16 = crc8, crc16 + +-- ------------------------------------------------------------------------------------------------ bit writer (MSB first) +type W = Bits.RawWriter + +@native local function ensure(w: W, n: number) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +local put = Bits.msbPut + +@native local function putSigned(w: W, v: number, n: number) + put(w, if v < 0 then v + POW[n + 1] else v, n) +end + +@native local function alignByte(w: W) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +@native local function putUtf8(w: W, v: number) + if v < 0x80 then + put(w, v, 8) + return + end + local n = if v < 0x800 then 2 elseif v < 0x10000 then 3 elseif v < 0x200000 then 4 elseif v < 0x4000000 then 5 elseif v < 0x80000000 then 6 else 7 + local first = if n == 7 then 0xFE else (0xFF00 // POW[n + 1]) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ presets +type Config = { + blockSize: number, + maxLpcOrder: number, + maxPartitionOrder: number, + stereo: string, -- "independent" | "adaptive" | "exhaustive" + exhaustiveOrder: boolean, +} +local PRESETS: { Config } = { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS + +-- ------------------------------------------------------------------------------------------------ analysis +-- a subframe plan for one channel signal +type Plan = { + kind: number, -- 0 constant, 1 verbatim, 2 fixed, 3 lpc + bits: number, -- estimated size in bits (with the subframe header) + order: number, + wasted: number, + bps: number, -- sample size after removing wasted bits + res: { number }, -- residual (fixed / lpc), indices 1..n + porder: number, + params: { number }, + method: number, -- 0 Rice (4-bit params), 1 Rice2 (5-bit) + qlp: { number }, + shift: number, + precision: number, + x: { number }, -- the (shifted) samples +} + +@native local function newPlan(n: number): Plan + return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end + +-- scratch per encoder +type Scratch = { + sums: { number }, + counts: { number }, + ks: { number }, + bestKs: { number }, + tmpRes: { number }, + win: { number }, + winN: number, + wx: { number }, + autoc: { number }, + lpc: { { number } }, + err: { number }, + qlp: { number }, +} + +-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) +@native local function rice(sc: Scratch, res: { number }, n: number, order: number, maxP: number): (number, number, number) + -- the finest usable partition order + local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or n // POW[p + 1] <= order) do + p -= 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = n // parts + -- sums of zig-zag values at the finest order + for j = 0, parts - 1 do + local s = 0 + local a = if j == 0 then order + 1 else j * ps + 1 + local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s += if r >= 0 then 2 * r else -2 * r - 1 + end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total += cost + end + local method = if maxk > 14 then 1 else 0 + total += np * (if method == 1 then 5 else 4) + 2 + 4 + if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + -- merge pairs into the next coarser order + for j = 1, np // 2 do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q -= 1 + end + return bestBits, bestP, bestMethod +end + +@native local function keepRice(sc: Scratch, plan: Plan, porder: number, method: number) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +-- fixed predictor residuals +@native local function fixedResidual(x: { number }, n: number, order: number, res: { number }) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +@native local function bestFixedOrder(x: { number }, n: number): (number, number) + if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 += abs(e0) + s1 += abs(e1) + s2 += abs(e2) + s3 += abs(e3) + s4 += abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +@native local function qlpPrecision(bps: number, n: number): number + if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil +@native local function quantize(lp: { number }, order: number, precision: number, qlp: { number }): number? + local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax /= 2 + log2cmax += 1 + end + while cmax < 0.5 do + cmax *= 2 + log2cmax -= 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax -= 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err += lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err -= q + qlp[i] = q + end + return shift +end + +@native local function lpcResidual(x: { number }, n: number, order: number, qlp: { number }, shift: number, res: { number }) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s += qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order +@native local function levinson(sc: Scratch, maxOrder: number): number + local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc -= a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e *= (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) +@native local function analyze(sc: Scratch, cfg: Config, src: { number }, n: number, bps: number, plan: Plan) + local x = plan.x + -- constant? + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + -- wasted bits: the common trailing zeros + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w += 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + -- verbatim + plan.kind, plan.bits = 1, hdr + n * b + -- fixed + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + -- lpc + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + -- windowed autocorrelation + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s += wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = if e > 0 then (n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) else -math.huge + if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in orders do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ writing +@native local function writeResidual(w: W, plan: Plan, n: number) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = n // parts + local res = plan.res + local pbits = if method == 1 then 5 else 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = if j == 0 then plan.order + 1 else j * ps + 1 + local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = if r >= 0 then 2 * r else -2 * r - 1 + local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q -= 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +@native local function writeSubframe(w: W, plan: Plan, n: number) + local kind = plan.kind + local typ = if kind == 0 then 0 elseif kind == 1 then 1 elseif kind == 2 then 8 + plan.order else 32 + plan.order - 1 + put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES: { [number]: number } = { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES: { [number]: number } = { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +@native local function blockCode(n: number): (number, number) -- code, extra bits (0, 8, 16) + if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end + +-- ------------------------------------------------------------------------------------------------ encoder +type Source = { + sampleRate: number, + channels: number, + frames: number, + tags: { [string]: string }, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + level: number, + bits: number, + blockSize: number?, + seekInterval: number, -- seconds between seek points (0 = no SEEKTABLE) + padding: number, -- bytes of PADDING + vendor: string, +} + +-- encode(src, opts) -> buffer | nil, message +@native function Encode.encode(src: Source, opts: Options): (buffer?, string?) + local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + -- metadata + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + -- seek table placeholders (when the length is known) + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = (src.frames - 1) // interval + 1 + if seekPoints > 65535 // 18 * 18 then + seekPoints = 0 + end + end + -- vorbis comment + local comments = VorbisComment.fields(src.tags) + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in comments do + vcLen += 4 + #c + end + -- SEEKTABLE + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + @native local function le32(v: number) + put(w, v % 256, 8) + put(w, (v // 256) % 256, 8) + put(w, (v // 65536) % 256, 8) + put(w, v // 16777216, 8) + end + ensure(w, vcLen + 8) + put(w, if opts.padding > 0 then 0 else 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in comments do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + -- frames + local md5 = Md5.new() + local mbytes = (bps + 7) // 8 + local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X: { { number } } = table.create(ch) :: any + for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc: Scratch = { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp: buffer? = nil + local pendingBuf: buffer? = nil + local pendingN, pendingOff = 0, 0 + -- read exactly bs frames (fewer only at the end) + @native local function readBlock(): (buffer?, number) + local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf :: buffer, pendingOff * ch * 4, take * ch * 4) + got += take + pendingN -= take + pendingOff += take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = if v < 0 then v + 4294967296 else v + for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo += 1 + end + end + end + md5:update(mbuf, 0, mo) + -- channel decorrelation + local assign = ch - 1 + local chosen: { Plan } = {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + -- the frame + local need = n * ch * 4 + 64 + for _, p in chosen do + need += (p.bits // 8) + 8 + end + ensure(w, need) + local start = w.pos + -- seek points: the first frame at or after each multiple of the interval + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, n // 256) + writeu8(tb, at + 17, n % 256) + seekIdx += 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in chosen do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo += 1 + total += n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + -- unused seek points stay placeholders; STREAMINFO + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, if frameNo > 0 then minFrame else 0, maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- streaminfo(...) -> the 34-byte STREAMINFO body +@native function Encode.streaminfo(bs: number, minFrame: number, maxFrame: number, rate: number, ch: number, bps: number, total: number, md5: string): buffer + local w: W = { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode +end +__FILES["codecs/audio/Flac/Frame"] = @native function() + + + +-- 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 +-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here +-- throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, + bit32.countlz, bit32.byteswap +local floor = math.floor + +local Frame = {} +Frame.PAD = 32 + +-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 +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 band(c, 0x80) ~= 0 then band(bxor(lshift(c, 1), 0x07), 0xFF) else band(lshift(c, 1), 0xFF) + end + CRC8[i + 1] = c + local d = lshift(i, 8) + for _ = 1, 8 do + d = if band(d, 0x8000) ~= 0 then band(bxor(lshift(d, 1), 0x8005), 0xFFFF) else band(lshift(d, 1), 0xFFFF) + end + CRC16[i + 1] = d +end + +@native local function crc16(b: buffer, from: number, to: number): number + local c = 0 + for i = from, to - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +Frame.crc16 = crc16 + +@native 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 +end + +local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, + [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } +local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, + [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } +local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } + +type Header = { + offset: number, -- byte offset of the sync code + size: number, -- header bytes, CRC-8 included + blockSize: number, + sampleRate: number, + channels: number, + assignment: number, -- 0..7 independent, 8 left/side, 9 side/right, 10 mid/side + bps: number, + variable: boolean, -- variable block size: number is a sample number, else a frame number + number: number, +} + +-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults +-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. +@native function Frame.header(b: buffer, pos: number, len: number, si: any): Header? + if pos < 0 or pos + 6 > len then + return nil + end + if readu8(b, pos) ~= 0xFF then + return nil + end + local b1 = readu8(b, pos + 1) + if band(b1, 0xFE) ~= 0xF8 then + return nil + end + local b2 = readu8(b, pos + 2) + local b3 = readu8(b, pos + 3) + local bsCode, rCode = rshift(b2, 4), band(b2, 15) + local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) + if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then + return nil + end + -- UTF-8-like coded number + local p = pos + 4 + local x = readu8(b, p) + p += 1 + local num, more + if x < 0x80 then + num, more = x, 0 + elseif x >= 0xC0 and x < 0xE0 then + num, more = band(x, 0x1F), 1 + elseif x >= 0xE0 and x < 0xF0 then + num, more = band(x, 0x0F), 2 + elseif x >= 0xF0 and x < 0xF8 then + num, more = band(x, 0x07), 3 + elseif x >= 0xF8 and x < 0xFC then + num, more = band(x, 0x03), 4 + elseif x >= 0xFC and x < 0xFE then + num, more = band(x, 0x01), 5 + elseif x == 0xFE then + num, more = 0, 6 + else + return nil + end + for _ = 1, more do + local c = readu8(b, p) + p += 1 + if band(c, 0xC0) ~= 0x80 then + return nil + end + num = num * 64 + band(c, 0x3F) + end + local variable = band(b1, 1) == 1 + if not variable and more > 5 then + return nil + end + local bs = BLOCK[bsCode] + if bsCode == 6 then + bs = readu8(b, p) + 1 + p += 1 + elseif bsCode == 7 then + bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 + p += 2 + end + local rate = RATE[rCode] + if rCode == 0 then + rate = si and si.sampleRate or 0 + elseif rCode == 12 then + rate = readu8(b, p) * 1000 + p += 1 + elseif rCode == 13 then + rate = readu8(b, p) * 256 + readu8(b, p + 1) + p += 2 + elseif rCode == 14 then + rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 + p += 2 + end + local bps = BITS[sCode] + if sCode == 0 then + bps = si and si.bitsPerSample or 0 + end + if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then + return nil + end + -- CRC-8 over the header + if crc8(b, pos, p) ~= readu8(b, p) then + return nil + end + return { + offset = pos, + size = p + 1 - pos, + blockSize = bs, + sampleRate = rate or 0, + channels = if chCode < 8 then chCode + 1 else 2, + assignment = chCode, + bps = bps, + variable = variable, + number = num, + } +end + +-- The first valid header at an offset in [pos, limit) +@native function Frame.find(b: buffer, pos: number, limit: number, len: number, si: any): Header? + local lim = math.min(limit, len - 6) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0xFF then + local b1 = readu8(b, pos + 1) + if b1 == 0xF8 or b1 == 0xF9 then + local h = Frame.header(b, pos, len, si) + if h then + return h + end + end + end + pos += 1 + end + return nil +end + +-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) +@native local function bits(b: buffer, p: number, n: number): number + if n == 0 then + return 0 + elseif n <= 24 then + return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) + end + local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) + local q = p + n - 16 + return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) +end + +@native local function sbits(b: buffer, p: number, n: number): number + local v = bits(b, p, n) + if n > 0 and v >= POW2[n] then + v -= POW2[n + 1] + end + return v +end + +-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. +@native local function residual(b: buffer, p: number, lim: number, s: { number }, n: number, order: number): number + local method = bits(b, p, 2) + if method > 1 then + return -1 + end + local porder = bits(b, p + 2, 4) + p += 6 + local pbits = if method == 0 then 4 else 5 + local escape = if method == 0 then 15 else 31 + local parts = POW2[porder + 1] + local psize = rshift(n, porder) + if psize * parts ~= n or psize < order then + return -1 + end + local i = order + 1 + for part = 0, parts - 1 do + if p > lim then + return -1 + end + local k = bits(b, p, pbits) + p += pbits + local stop = (part + 1) * psize + if k == escape then + local nb = bits(b, p, 5) + p += 5 + if nb == 0 then + for j = i, stop do + s[j] = 0 + end + else + local half, full = POW2[nb], POW2[nb + 1] + for j = i, stop do + if p > lim then + return -1 + end + local v = bits(b, p, nb) + p += nb + if v >= half then + v -= full + end + s[j] = v + end + end + elseif k <= 24 then + -- the hot loop: unary quotient + k-bit remainder, zigzag + local pk = POW2[k + 1] + local rk = 32 - k + for j = i, stop do + if p > lim then + return -1 + end + local sh = band(p, 7) + local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) + local q, r + if w ~= 0 then + q = countlz(w) + local used = q + 1 + k + if used <= 32 - sh then + r = if k == 0 then 0 else rshift(lshift(w, q + 1), rk) + p += used + else + p += q + 1 + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + else + -- a long run of zeros + q = 32 - sh + p += q + while true do + if p > lim then + return -1 + end + local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w2 ~= 0 then + local z = countlz(w2) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + r = if k == 0 then 0 else rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p += k + end + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + else + -- k = 25..30 (Rice2): the remainder takes two reads + local pk = POW2[k + 1] + for j = i, stop do + if p > lim then + return -1 + end + local q = 0 + while true do + if p > lim then + return -1 + end + local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w ~= 0 then + local z = countlz(w) + q += z + p += z + 1 + break + end + local adv = 32 - band(p, 7) + q += adv + p += adv + end + local r = bits(b, p, k) + p += k + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = if h + h == u then h else -h - 1 + end + end + i = stop + 1 + end + return p +end + +@native local function fixed(s: { number }, n: number, order: number) + if order == 1 then + local a = s[1] + for i = 2, n do + a += s[i] + s[i] = a + end + elseif order == 2 then + local a, c = s[2], s[1] + for i = 3, n do + local v = s[i] + 2 * a - c + s[i] = v + c = a + a = v + end + elseif order == 3 then + local a, c, d = s[3], s[2], s[1] + for i = 4, n do + local v = s[i] + 3 * a - 3 * c + d + s[i] = v + d = c + c = a + a = v + end + elseif order == 4 then + local a, c, d, e = s[4], s[3], s[2], s[1] + for i = 5, n do + local v = s[i] + 4 * a - 6 * c + 4 * d - e + s[i] = v + e = d + d = c + c = a + a = v + end + end +end + +-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 +@native local function lpc(s: { number }, n: number, cf: { number }, order: number, shift: number) + local div = POW2[shift + 1] + local inv = 1 / div + if order <= 4 then + local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 + local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 + for i = order + 1, n do + local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) + s[i] = v + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 8 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 + local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] + local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 + for i = order + 1, n do + local v = s[i] + + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) + s[i] = v + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 12 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] + local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 + local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] + local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] + local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 + for i = order + 1, n do + local v = s[i] + + floor( + ( + c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 + ) * inv + ) + s[i] = v + s12 = s11 + s11 = s10 + s10 = s9 + s9 = s8 + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + else + for i = order + 1, n do + local sum = 0 + for j = 1, order do + sum += cf[j] * s[i - j] + end + s[i] += floor(sum * inv) + end + end +end + +-- One subframe into s[1..n]. Returns the new bit position, or -1. +@native local function subframe(b: buffer, p: number, lim: number, s: { number }, n: number, bps: number, cf: { number }): number + if p > lim then + return -1 + end + local hdr = bits(b, p, 8) + p += 8 + if hdr >= 128 then + return -1 + end + local typ = rshift(hdr, 1) + local wasted = 0 + if band(hdr, 1) == 1 then + -- unary count of wasted bits (minus one) + while true do + if p > lim or wasted > 32 then + return -1 + end + local bit = bits(b, p, 1) + p += 1 + wasted += 1 + if bit == 1 then + break + end + end + bps -= wasted + if bps < 1 then + return -1 + end + end + if typ == 0 then + local v = sbits(b, p, bps) + p += bps + for i = 1, n do + s[i] = v + end + elseif typ == 1 then + for i = 1, n do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + elseif typ >= 8 and typ <= 12 then + local order = typ - 8 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + fixed(s, n, order) + elseif typ >= 32 then + local order = typ - 31 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p += bps + end + local prec = bits(b, p, 4) + 1 + p += 4 + if prec == 16 then + return -1 + end + local shift = sbits(b, p, 5) + p += 5 + if shift < 0 then + return -1 + end + for j = 1, order do + if p > lim then + return -1 + end + cf[j] = sbits(b, p, prec) + p += prec + end + for j = order + 1, 12 do + cf[j] = 0 -- the unrolled filters read up to 12 coefficients + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + lpc(s, n, cf, order, shift) + else + return -1 + end + if wasted > 0 then + local m = POW2[wasted + 1] + for i = 1, n do + s[i] *= m + end + end + return p +end + +-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize +-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. +@native function Frame.decode(b: buffer, len: number, h: Header, chans: { { number } }, cf: { number }, checkCrc: boolean): (number?, string?) + local n = h.blockSize + local lim = len * 8 + local p = (h.offset + h.size) * 8 + local asg = h.assignment + for c = 1, h.channels do + local bps = h.bps + if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then + bps += 1 -- the side channel + end + p = subframe(b, p, lim, chans[c], n, bps, cf) + if p < 0 then + return nil, "bad subframe" + end + end + local e = rshift(p + 7, 3) -- byte align + if e + 2 > len then + return nil, "truncated frame" + end + if checkCrc then + local want = readu8(b, e) * 256 + readu8(b, e + 1) + if crc16(b, h.offset, e) ~= want then + return nil, "crc16 mismatch" + end + end + if asg >= 8 then + local l, r = chans[1], chans[2] + if asg == 8 then + for i = 1, n do + r[i] = l[i] - r[i] + end + elseif asg == 9 then + for i = 1, n do + l[i] += r[i] + end + else + for i = 1, n do + local side = r[i] + local m = l[i] * 2 + (side % 2) + l[i] = (m + side) * 0.5 + r[i] = (m - side) * 0.5 + end + end + end + return e + 2, nil +end + +return Frame +end +__FILES["codecs/audio/Hively"] = function() + +-- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats +-- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 +-- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of +-- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): +-- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. +-- +-- local Hively = require("@rosetta/codecs/audio/Hively") +-- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune +-- local song = Hively.module(tune) -- a Types.Module-shaped value with render() +-- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder +-- +-- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame +-- (hvl2wav pads each frame to 882 with stale samples). +local Err = __include("core/Err") +local Types = __include("Types") +local Load = __include("codecs/audio/Hively/Load") +local Player = __include("codecs/audio/Hively/Player") +local Pcm = __include("codecs/audio/Pcm") + +local Hively = {} + +type Tune = Load.Tune +type RenderOptions = { + sampleRate: number?, -- default 44100 (the replayer runs at any rate: 8000..192000) + subsong: number?, -- 0 = the main song (default), 1..n the subsongs + stereo: number?, -- AHX stereo separation 0..4 (0 mono, 4 = 100 % Amiga L R R L); default 0 as hvl2wav. HVL: the file's + loop: boolean?, -- keep playing past the song end (frames / duration still give one pass) + maxDuration: number?, -- seconds, default 600 (hvl2wav's 10 minute limit) +} + +-- parse(b, base?, limit?) -> Tune | nil, Err +function Hively.parse(b: buffer, base: number?, limit: number?): (Tune?, Err.Err?) + local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) + if not tune then + return nil, Err.from(msg or "corrupt", nil, kind) + end + return tune, nil +end + +local function settings(tune: Tune, opts: RenderOptions?): (number?, number, number, Err.Err?) + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") + end + local sub = o.subsong or 0 + if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) + end + return rate, sub, tonumber(o.stereo) or 0, nil +end + +-- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration +function Hively.frameCount(tune: Tune, opts: RenderOptions?): number + local rate, sub, stereo = settings(tune, opts) + local st = rate and Player.new(tune, rate :: number, stereo, sub) + if not st then + return 0 + end + local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) + local n = 0 + while n < maxFrames and not st.songEndReached do + for _ = 1, tune.speedMultiplier do + Player.irq(st, false) + end + n += 1 + end + return n +end + +-- decoder(tune, opts?) -> Types.Decoder | nil, Err +function Hively.decoder(tune: Tune, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local rate, sub, stereo, err = settings(tune, opts) + if not rate then + return nil, err + end + local sr = rate :: number + local mult = tune.speedMultiplier + local perIrq = sr // 50 // mult + local perFrame = perIrq * mult + local nframes = Hively.frameCount(tune, opts) + local frames = nframes * perFrame + local loop = opts ~= nil and opts.loop == true + local st = Player.new(tune, sr, stereo, sub) :: Player.State + local fbuf = buffer.create(perFrame * 8) + local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf + local pos = 0 + + local function nextFrame() + for k = 0, mult - 1 do + Player.irq(st, true) + Player.mix(st, fbuf, k * perIrq, perIrq) + end + fpos, ffill = 0, perFrame + end + + local dec = { + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = if tune.title ~= "" then tune.title else nil } :: Types.Tags, + } + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(n)) + if not loop then + n = math.min(n, frames - pos) + end + local b = out + if not b or buffer.len(b) < n * 8 then + b = buffer.create(math.max(n, 1) * 8) + end + local ob = b :: buffer + local done = 0 + while done < n do + if fpos >= ffill then + nextFrame() + end + local k = math.min(n - done, ffill - fpos) + buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) + fpos += k + done += k + end + pos += n + return ob, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) + if not loop then + target = math.min(target, frames) + end + if target < pos then + st = Player.new(tune, sr, stereo, sub) :: Player.State + pos, fpos, ffill = 0, 0, 0 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / sr + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +-- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, +-- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder +function Hively.module(tune: Tune): Types.Module + local patterns = {} + for t = 0, tune.trackNr do + local data = buffer.create(tune.trackLength * 6) + buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) + patterns[t + 1] = { rows = tune.trackLength, data = data } + end + local order, positions = {}, {} + for i = 0, tune.positionNr - 1 do + order[i + 1] = i + local tr, tp = {}, {} + for c = 0, tune.channels - 1 do + tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) + tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) + end + positions[i + 1] = { tracks = tr, transpose = tp } + end + local m: any = { + kind = "music", + format = tune.format, + title = tune.title, + channels = tune.channels, + speed = 6, + tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) + patterns = patterns, + order = order, + positions = positions, + restart = tune.restart, + subsongs = table.clone(tune.subsongs), + instruments = tune.instruments, + samples = {}, + meta = { + source = { + format = tune.format, + version = tune.version, + speedMultiplier = tune.speedMultiplier, + trackLength = tune.trackLength, + tracks = tune.trackNr + 1, + mixgain = if tune.format == "hvl" then tune.mixgain else nil, + stereo = if tune.format == "hvl" then tune.stereo else nil, + }, + }, + tune = tune, + } + m.render = function(self: any, opts: RenderOptions?): Types.Decoder + local dec, derr = Hively.decoder(self.tune, opts) + if dec then + return dec + end + -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err + local empty: any = Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) + empty.err = derr + return empty + end + return m :: Types.Module +end + +return Hively +end +__FILES["codecs/audio/Hively/Load"] = function() + +-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's +-- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as +-- (nil, message, kind) for core/Err.from. +local Load = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 + +type PlistEntry = { note: number, waveform: number, fixed: number, fx: { number }, param: { number } } +type Instrument = { + name: string, + volume: number, + waveLength: number, + filterLower: number, + filterUpper: number, + filterSpeed: number, + squareLower: number, + squareUpper: number, + squareSpeed: number, + vibratoDelay: number, + vibratoSpeed: number, + vibratoDepth: number, + hardCutRelease: number, + hardCutReleaseFrames: number, + envelope: { aFrames: number, aVolume: number, dFrames: number, dVolume: number, sFrames: number, rFrames: number, rVolume: number }, + plist: { speed: number, length: number, entries: { PlistEntry } }, +} +type Tune = { + format: string, -- "ahx" | "hvl" + version: number, -- the 4th byte: AHX 0..2, HVL 0..1 + title: string, + channels: number, -- 4 (AHX), 4..16 (HVL) + positionNr: number, + restart: number, + speedMultiplier: number, -- 1..4 player calls per 50 Hz frame + trackLength: number, -- rows per track, 1..64 + trackNr: number, -- the highest track number stored + instrumentNr: number, + subsongs: { number }, -- first positions of subsongs 1..n + positions: buffer, -- positionNr * 16 * 2 bytes: per channel track (u8), transpose (i8) + tracks: buffer, -- 257 * 64 * 6 bytes: per track row note, instrument, fx, param, fxb, paramb + instruments: { Instrument }, -- 1-based, as numbered in the file + mixgain: number, -- (percent * 256) / 100, HVL only (AHX: set by the stereo separation at render time) + stereo: number, -- HVL: the default stereo separation 0..4 + emptyTrack0: boolean, -- track 0 is not stored (always empty) +} + +local function cstring(b: buffer, p: number, limit: number, max: number): (string, number) + local e = p + while e < limit and e - p < max and readu8(b, e) ~= 0 do + e += 1 + end + return buffer.readstring(b, p, e - p), e +end + +-- parse(b, base, limit) -> Tune | nil, message, kind +function Load.parse(b: buffer, base: number, limit: number): (Tune?, string?, string?) + local size = limit - base + if size < 14 then + return nil, "truncated header", "truncated" + end + local function u8(o: number): number + return readu8(b, base + o) + end + local magic = buffer.readstring(b, base, 3) + local ahx = magic == "THX" and u8(3) < 3 + if not ahx and not (magic == "HVL" and u8(3) <= 1) then + return nil, "not an AHX / HVL module", nil + end + if not ahx and size < 16 then + return nil, "truncated header", "truncated" + end + local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7) + local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11) + local chnn = if ahx then 4 else bit32.rshift(u8(8), 2) + 4 + local tune: Tune = { + format = if ahx then "ahx" else "hvl", + version = u8(3), + title = "", + channels = chnn, + positionNr = posn, + restart = if ahx then u8(8) * 256 + u8(9) else bit32.band(u8(8), 3) * 256 + u8(9), + speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1, + trackLength = trkl, + trackNr = trkn, + instrumentNr = insn, + subsongs = {}, + positions = buffer.create(math.max(posn, 1) * 32), + tracks = buffer.create(257 * 64 * 6), + instruments = {}, + mixgain = if ahx then 256 else (u8(14) * 256) // 100, + stereo = if ahx then 0 else math.min(u8(15), 4), + emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0, + } + if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then + return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil + end + if chnn > 16 then + return nil, "unsupported: more than 16 channels", "unsupported" + end + if tune.restart >= posn then + tune.restart = posn - 1 + end + local nameAt = u8(4) * 256 + u8(5) + local nptr = limit + if nameAt < size then + local title, e = cstring(b, base + nameAt, limit, 128) + tune.title = title + nptr = e + 1 + end + + local p = base + (if ahx then 14 else 16) + local function need(n: number): boolean + return p + n <= limit + end + if not need(ssn * 2 + posn * chnn * 2) then + return nil, "truncated position list", "truncated" + end + for i = 1, ssn do + local s = readu8(b, p) * 256 + readu8(b, p + 1) + if s >= posn then + s = 0 + end + tune.subsongs[i] = s + p += 2 + end + for i = 0, posn - 1 do + for j = 0, chnn - 1 do + buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p)) + buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1)) + p += 2 + end + end + local tracks = tune.tracks + for i = 0, trkn do + if not (tune.emptyTrack0 and i == 0) then + for j = 0, trkl - 1 do + local o = (i * 64 + j) * 6 + if ahx then + if not need(3) then + return nil, "truncated track data", "truncated" + end + local b0, b1 = readu8(b, p), readu8(b, p + 1) + buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f)) + buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4)) + buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 2)) + p += 3 + else + if not need(1) then + return nil, "truncated track data", "truncated" + end + if readu8(b, p) == 0x3f then + p += 1 + else + if not need(5) then + return nil, "truncated track data", "truncated" + end + local fx = readu8(b, p + 2) + buffer.writeu8(tracks, o, readu8(b, p)) + buffer.writeu8(tracks, o + 1, readu8(b, p + 1)) + buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 3)) + buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf)) + buffer.writeu8(tracks, o + 5, readu8(b, p + 4)) + p += 5 + end + end + end + end + end + local plSize = if ahx then 4 else 5 + for i = 1, insn do + if not need(22) then + return nil, "truncated instrument", "truncated" + end + local function at(k: number): number + return readu8(b, p + k) + end + local name = "" + if nptr < limit then + local e + name, e = cstring(b, nptr, limit, 128) + nptr = e + 1 + end + local plen = at(21) + local ins: Instrument = { + name = name, + volume = at(0), + filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)), + waveLength = bit32.band(at(1), 7), + envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) }, + filterLower = bit32.band(at(12), 0x7f), + vibratoDelay = at(13), + hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7), + hardCutRelease = if bit32.band(at(14), 0x80) ~= 0 then 1 else 0, + vibratoDepth = bit32.band(at(14), 0x0f), + vibratoSpeed = at(15), + squareLower = at(16), + squareUpper = at(17), + squareSpeed = at(18), + filterUpper = bit32.band(at(19), 0x3f), + plist = { speed = at(20), length = plen, entries = {} }, + } + p += 22 + if not need(plen * plSize) then + return nil, "truncated instrument play list", "truncated" + end + for j = 1, plen do + local e: PlistEntry + local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + if ahx then + local k = bit32.band(bit32.rshift(b0, 5), 7) + k = if k == 6 then 12 elseif k == 7 then 15 else k + local l = bit32.band(bit32.rshift(b0, 2), 7) + l = if l == 6 then 12 elseif l == 7 then 15 else l + e = { + fx = { l, k }, + waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7), + fixed = bit32.band(bit32.rshift(b1, 6), 1), + note = bit32.band(b1, 0x3f), + param = { b2, b3 }, + } + -- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4 + if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then + e.param[1] = bit32.band(b2, 0x0f) + end + if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then + e.param[2] = bit32.band(b3, 0x0f) + end + else + e = { + fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) }, + waveform = bit32.band(b1, 7), + fixed = bit32.band(bit32.rshift(b2, 6), 1), + note = bit32.band(b2, 0x3f), + param = { b3, readu8(b, p + 4) }, + } + end + ins.plist.entries[j] = e + p += plSize + end + tune.instruments[i] = ins + end + return tune, nil, nil +end + +return Load +end +__FILES["codecs/audio/Hively/Player"] = @native function() + + +-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the +-- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, +-- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output +-- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead. +local Tables = __include("codecs/audio/Hively/Tables") +local Load = __include("codecs/audio/Hively/Load") + +local Player = {} + +local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32 +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift + +local FILTER_SET = Tables.FILTER_SET +local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04 +local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE +local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD +local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE } +local WRAP = 0x280 * 65536 +local TWO32 = 4294967296 + +local f32scratch = buffer.create(4) + +@native local function s16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +@native local function tdiv(a: number, b: number): number -- C integer division (truncates) + local q = a / b + return if q >= 0 then math.floor(q) else -math.floor(-q) +end + +@native local function period(i: number): number + return PERIOD[i] or 0 +end + +-- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated +@native local function deltaOf(p: number, freq: number): number + if p == 0 then + return 1 + end + writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float) + local d = math.floor(buffer.readf32(f32scratch, 0) / freq) + if d < 0 then + d = 0 + end + if d > WRAP then + d -= WRAP + end + if d == 0 then + d = 1 + end + return d +end + +type Voice = { [string]: any } +type State = { + tune: Load.Tune, + freq: number, + version: number, + channels: number, + voices: { Voice }, + tempo: number, + posNr: number, + posJump: number, + posJumpNote: number, + noteNr: number, + stepWaitFrames: number, + getNewPosition: boolean, + patternBreak: boolean, + songEndReached: boolean, + playingTime: number, + mixgain: number, + waves: buffer, + panL: { number }, + panR: { number }, +} + +@native local function newVoice(i: number): Voice + return { + track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, + adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, + instrument = false :: any, samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0, + waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false, + voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0, + hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0, + periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0, + periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0, + vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0, + squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0, + filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0, + filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false :: any, + audioSrc = false :: any, audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0, + audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280, + squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40, + pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0, + ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0, + ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0, + ringBuf = buffer.create(0x284), + } +end + +-- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) +@native function Player.new(tune: Load.Tune, freq: number, stereo: number, subsong: number): State? + if subsong < 0 or subsong > #tune.subsongs then + return nil + end + local t = Tables.get() + local defstereo = if tune.format == "ahx" then math.clamp(math.floor(stereo), 0, 4) else tune.stereo + local mixgain = tune.mixgain + if tune.format == "ahx" then + local defgain = { [0] = 71, 72, 76, 85, 100 } + mixgain = (defgain[defstereo] * 256) // 100 + end + local st: State = { + tune = tune, freq = freq, version = if tune.format == "hvl" then tune.version else 0, + channels = tune.channels, voices = {}, tempo = 6, posNr = if subsong > 0 then tune.subsongs[subsong] else 0, + posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false, + songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR, + } + local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo] + for i = 0, 15 do + local v = newVoice(i) + local p = if i % 4 == 0 or i % 4 == 3 then left else right + v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p] + st.voices[i + 1] = v + end + return st +end + +-- ------------------------------------------------------------------------------------------------ steps +@native local function setPan(st: State, v: Voice, p: number) + v.pan = p + v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] +end + +@native local function stepfx1(st: State, v: Voice, fx: number, param: number) + if fx == 0x0 then + local lo = band(param, 0x0f) + if lo > 0 and lo <= 9 then + st.posJump = lo + end + elseif fx == 0x5 or fx == 0xa then + v.volumeSlideDown = band(param, 0x0f) + v.volumeSlideUp = rshift(param, 4) + elseif fx == 0x7 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + v.setPan = param + 128 + elseif fx == 0xb then + st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536 + st.patternBreak = true + if st.posJump <= st.posNr then + st.songEndReached = true + end + elseif fx == 0xd then + st.posJump = st.posNr + 1 + st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10 + st.patternBreak = true + if st.posJumpNote > st.tune.trackLength then + st.posJumpNote = 0 + end + elseif fx == 0xe then + if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then + v.noteCutWait = band(param, 0x0f) + if v.noteCutWait ~= 0 then + v.noteCutOn = true + v.hardCutRelease = 0 + end + end + elseif fx == 0xf then + st.tempo = param + if param == 0 then + st.songEndReached = true + end + end +end + +@native local function stepfx2(v: Voice, fx: number, param: number, note: number): number + if fx == 0x9 then + v.squarePos = rshift(param, 5 - v.waveLength) + v.ignoreSquare = 1 + elseif fx == 0x3 or fx == 0x5 then + if fx == 0x3 and param ~= 0 then + v.periodSlideSpeed = param + end + if note ~= 0 then + local new = period(note) + local diff = period(v.trackPeriod) - new + new = diff + v.periodSlidePeriod + if new ~= 0 then + v.periodSlideLimit = s16(-diff) + end + end + v.periodSlideOn = true + v.periodSlideWithLimit = true + note = 0 + end + return note +end + +@native local function stepfx3(st: State, v: Voice, fx: number, param: number) + if fx == 0x01 then + v.periodSlideSpeed = -param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x02 then + v.periodSlideSpeed = param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x04 then + if param == 0 or param == 0x40 then + return + end + if param < 0x40 then + v.ignoreFilter = param + return + end + if param > 0x7f then + return + end + v.filterPos = param - 0x40 + elseif fx == 0x0c then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + for i = 1, st.channels do + st.voices[i].trackMasterVolume = param + end + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 0xe then + local sub, lo = rshift(param, 4), band(param, 0x0f) + if sub == 0x1 then + v.periodSlidePeriod = s16(v.periodSlidePeriod - lo) + v.plantPeriod = true + elseif sub == 0x2 then + v.periodSlidePeriod = s16(v.periodSlidePeriod + lo) + v.plantPeriod = true + elseif sub == 0x4 then + v.vibratoDepth = lo + elseif sub == 0xa then + v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40) + elseif sub == 0xb then + v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0) + elseif sub == 0xf then + if st.version >= 1 and lo == 1 then + v.overrideTranspose = v.transpose + end + end + end +end + +@native local function processStep(st: State, v: Voice) + v.volumeSlideUp, v.volumeSlideDown = 0, 0 + local tune = st.tune + local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) + local so = (track * 64 + st.noteNr) * 6 + local tracks = tune.tracks + local note, instr = readu8(tracks, so), readu8(tracks, so + 1) + local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5) + + local doneNoteDel = false + if fx == 0xe and band(fxp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + doneNoteDel = true + elseif band(fxp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + elseif band(fxbp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxbp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + + if note ~= 0 then + v.overrideTranspose = 1000 + end + stepfx1(st, v, fx, fxp) + stepfx1(st, v, fxb, fxbp) + + if instr ~= 0 and instr <= tune.instrumentNr then + local ins = tune.instruments[instr] + setPan(st, v, v.setPan) + v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0 + v.perfSubVolume = 0x40 + v.adsrVolume = 0 + v.instrument = ins + v.samplePos = 0 + local env = ins.envelope + v.aFrames = env.aFrames + v.aVolume = s16(if v.aFrames ~= 0 then tdiv(env.aVolume * 256, v.aFrames) else env.aVolume * 256) + v.dFrames = env.dFrames + v.dVolume = s16(if v.dFrames ~= 0 then tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) else env.dVolume * 256) + v.sFrames = env.sFrames + v.rFrames = env.rFrames + v.rVolume = s16(if v.rFrames ~= 0 then tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) else env.rVolume * 256) + v.waveLength = math.min(ins.waveLength, 5) + v.noteMaxVolume = ins.volume + v.vibratoCurrent = 0 + v.vibratoDelay = ins.vibratoDelay + v.vibratoDepth = ins.vibratoDepth + v.vibratoSpeed = ins.vibratoSpeed + v.vibratoPeriod = 0 + v.hardCutRelease = ins.hardCutRelease + v.hardCut = ins.hardCutReleaseFrames + v.ignoreSquare, v.squareSlidingIn = 0, false + v.squareWait, v.squareOn = 0, 0 + local lower = rshift(ins.squareLower, 5 - v.waveLength) + local upper = rshift(ins.squareUpper, 5 - v.waveLength) + if upper < lower then + lower, upper = upper, lower + end + v.squareUpperLimit, v.squareLowerLimit = upper, lower + v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0 + v.filterSlidingIn = false + local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper + v.filterSpeed = d6 + if d3 > d4 then + d3, d4 = d4, d3 + end + v.filterUpperLimit, v.filterLowerLimit = d4, d3 + v.filterPos = 32 + v.perfWait, v.perfCurrent = 0, 0 + v.perfSpeed = ins.plist.speed + v.perfList = ins.plist + v.ringMix = false + v.ringSamplePos = 0 + v.ringPlantPeriod = false + v.ringNewWaveform = false + end + + v.periodSlideOn = false + note = stepfx2(v, fx, fxp, note) + note = stepfx2(v, fxb, fxbp, note) + if note ~= 0 then + v.trackPeriod = note + v.plantPeriod = true + end + stepfx3(st, v, fx, fxp) + stepfx3(st, v, fxb, fxbp) +end + +-- ------------------------------------------------------------------------------------------------ frames +@native local function plistCommand(st: State, v: Voice, fx: number, param: number) + if fx == 0 then + if param > 0 and param < 0x40 then + if v.ignoreFilter ~= 0 then + v.filterPos = v.ignoreFilter + v.ignoreFilter = 0 + else + v.filterPos = param + end + v.newWaveform = true + end + elseif fx == 1 then + v.periodPerfSlideSpeed = param + v.periodPerfSlideOn = true + elseif fx == 2 then + v.periodPerfSlideSpeed = -param + v.periodPerfSlideOn = true + elseif fx == 3 then + if v.ignoreSquare == 0 then + v.squarePos = rshift(param, 5 - v.waveLength) + else + v.ignoreSquare = 0 + end + elseif fx == 4 then + if param == 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = 1 + else + if band(param, 0x0f) ~= 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = if band(param, 0x0f) == 0x0f then -1 else 1 + end + if band(param, 0xf0) ~= 0 then + v.filterOn = 1 - v.filterOn + v.filterInit = v.filterOn + v.filterSign = if band(param, 0xf0) == 0xf0 then -1 else 1 + end + end + elseif fx == 5 then + v.perfCurrent = param + elseif fx == 7 or fx == 8 then + if param >= 1 and param <= 0x3c then + v.ringBasePeriod = param + v.ringFixedPeriod = 1 + elseif param >= 0x81 and param <= 0xbc then + v.ringBasePeriod = param - 0x80 + v.ringFixedPeriod = 0 + else + v.ringBasePeriod = 0 + v.ringFixedPeriod = 0 + v.ringNewWaveform = false + v.ringAudioOff = -1 + v.ringMix = false + return + end + v.ringWaveform = fx - 7 + v.ringNewWaveform = true + v.ringPlantPeriod = true + elseif fx == 9 then + if param > 127 then + param -= 256 + end + setPan(st, v, param + 128) + elseif fx == 12 then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param -= 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.perfSubVolume = param + return + end + param -= 0xa0 - 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 15 then + v.perfSpeed = param + v.perfWait = param + end +end + +-- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; +-- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 +@native local function wnStep(v: Voice) + local hi, lo = v.wnHi, v.wnLo + 2239384 + if lo >= TWO32 then + lo -= TWO32 + hi = (hi + 1) % TWO32 + end + local shi = rshift(hi, 8) + if hi >= 0x80000000 then + shi = bor(shi, 0xff000000) + end + local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24)) + local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8)) + nlo += 782323 + if nlo >= TWO32 then + nlo -= TWO32 + nhi = (nhi + 1) % TWO32 + end + nlo = bit32.bxor(nlo, 75) + nlo -= 6735 + if nlo < 0 then + nlo += TWO32 + nhi = (nhi + TWO32 - 1) % TWO32 + end + v.wnHi, v.wnLo = nhi, nlo +end + +@native local function processFrame(st: State, v: Voice) + local tune = st.tune + if v.noteDelayOn then + if v.noteDelayWait <= 0 then + processStep(st, v) + else + v.noteDelayWait -= 1 + end + end + + if v.hardCut ~= 0 then + local row = st.noteNr + 1 + local nextinst + if row < tune.trackLength then + nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1) + else + nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1) + end + if nextinst ~= 0 then + local d1 = math.max(st.tempo - v.hardCut, 0) + if not v.noteCutOn then + v.noteCutOn = true + v.noteCutWait = d1 + v.hardCutReleaseF = -(d1 - st.tempo) + else + v.hardCut = 0 + end + end + end + + if v.noteCutOn then + if v.noteCutWait <= 0 then + v.noteCutOn = false + if v.hardCutRelease ~= 0 then + local ins = v.instrument + local f = v.hardCutReleaseF + v.rVolume = if f ~= 0 then s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) else 0 + v.rFrames = f + v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 + else + v.noteMaxVolume = 0 + end + else + v.noteCutWait -= 1 + end + end + + -- ADSR envelope + if v.aFrames ~= 0 then + v.adsrVolume += v.aVolume + v.aFrames -= 1 + if v.aFrames <= 0 then + v.adsrVolume = v.instrument.envelope.aVolume * 256 + end + elseif v.dFrames ~= 0 then + v.adsrVolume += v.dVolume + v.dFrames -= 1 + if v.dFrames <= 0 then + v.adsrVolume = v.instrument.envelope.dVolume * 256 + end + elseif v.sFrames ~= 0 then + v.sFrames -= 1 + elseif v.rFrames ~= 0 then + v.adsrVolume += v.rVolume + v.rFrames -= 1 + if v.rFrames <= 0 then + v.adsrVolume = v.instrument.envelope.rVolume * 256 + end + end + + -- volume slide + v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) + + -- portamento + if v.periodSlideOn then + if v.periodSlideWithLimit then + local d0 = v.periodSlidePeriod - v.periodSlideLimit + local d2 = v.periodSlideSpeed + if d0 > 0 then + d2 = -d2 + end + if d0 ~= 0 then + local sum = d0 + d2 + -- (d0 + d2) ^ d0 >= 0: the same sign (or zero) + if (sum >= 0) == (d0 >= 0) then + d0 = v.periodSlidePeriod + d2 + else + d0 = v.periodSlideLimit + end + v.periodSlidePeriod = s16(d0) + v.plantPeriod = true + end + else + v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed) + v.plantPeriod = true + end + end + + -- vibrato + if v.vibratoDepth ~= 0 then + if v.vibratoDelay <= 0 then + v.vibratoPeriod = (VIB[v.vibratoCurrent] * v.vibratoDepth) // 128 + v.plantPeriod = true + v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) + else + v.vibratoDelay -= 1 + end + end + + -- PList + local pl = v.perfList + if pl then + if v.instrument and v.perfCurrent < v.instrument.plist.length then + local overflow = v.perfWait == 128 + v.perfWait = s16(v.perfWait - 1) + local w8 = (v.perfWait + 128) % 256 - 128 + if overflow or w8 <= 0 then + local cur = v.perfCurrent + v.perfCurrent += 1 + v.perfWait = v.perfSpeed + local e = pl.entries[cur + 1] + if e then + if e.waveform ~= 0 then + v.waveform = e.waveform - 1 + v.newWaveform = true + v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0 + end + v.periodPerfSlideOn = false + plistCommand(st, v, e.fx[1], e.param[1]) + plistCommand(st, v, e.fx[2], e.param[2]) + if e.note ~= 0 then + v.instrPeriod = e.note + v.plantPeriod = true + v.fixedNote = e.fixed + end + end + end + else + if v.perfWait ~= 0 then + v.perfWait -= 1 + else + v.periodPerfSlideSpeed = 0 + end + end + end + + -- perf portamento + if v.periodPerfSlideOn then + v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) + if v.periodPerfSlidePeriod ~= 0 then + v.plantPeriod = true + end + end + + if v.waveform == 2 and v.squareOn ~= 0 then + v.squareWait -= 1 + if v.squareWait <= 0 then + local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos + if v.squareInit ~= 0 then + v.squareInit = 0 + if d3 <= d1 then + v.squareSlidingIn = true + v.squareSign = 1 + elseif d3 >= d2 then + v.squareSlidingIn = true + v.squareSign = -1 + end + end + if d1 == d3 or d2 == d3 then + if v.squareSlidingIn then + v.squareSlidingIn = false + else + v.squareSign = -v.squareSign + end + end + d3 += v.squareSign + v.squarePos = s16(d3) + v.plantSquare = true + local ins: any = v.instrument + v.squareWait = if ins then ins.squareSpeed else 0 + end + end + + if v.filterOn ~= 0 then + v.filterWait -= 1 + if v.filterWait <= 0 then + local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos + if v.filterInit ~= 0 then + v.filterInit = 0 + if d3 <= d1 then + v.filterSlidingIn = true + v.filterSign = 1 + elseif d3 >= d2 then + v.filterSlidingIn = true + v.filterSign = -1 + end + end + local fmax = if v.filterSpeed < 4 then 5 - v.filterSpeed else 1 + for _ = 1, fmax do + if d1 == d3 or d2 == d3 then + if v.filterSlidingIn then + v.filterSlidingIn = false + else + v.filterSign = -v.filterSign + end + end + d3 += v.filterSign + end + v.filterPos = math.clamp(d3, 1, 63) + v.newWaveform = true + v.filterWait = math.max(v.filterSpeed - 3, 1) + end + end + + local waves = st.waves + local fpos = math.clamp(v.filterPos, 1, 63) + if v.waveform == 2 or v.plantSquare then + -- CalcSquare + local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET + local x = v.squarePos * 2 ^ (5 - v.waveLength) + if x > 0x20 then + x = 0x40 - x + v.squareReverse = true + end + if x > 0 then + sp += (x - 1) * 128 + end + local delta = 32 // 2 ^ v.waveLength + local sb = v.squareBuf + for i = 0, 4 * 2 ^ v.waveLength - 1 do + writei8(sb, i, readi8(waves, sp)) + sp += delta + end + v.newWaveform = true + v.waveform = 2 + v.plantSquare = false + end + + if v.waveform == 3 then + v.newWaveform = true + end + + if v.ringNewWaveform then + if v.ringWaveform > 1 then + v.ringWaveform = 1 + end + v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength] + end + + if v.newWaveform and v.waveform <= 3 then + if v.waveform == 2 then + v.audioSrc, v.audioOff = v.squareBuf, 0 + else + local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET + if v.waveform < 2 then + off += OFFSETS[v.waveLength] + else + off += band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe) + wnStep(v) + end + v.audioSrc, v.audioOff = waves, off + end + end + + -- ring modulation period + if v.ringAudioOff >= 0 then + local rp = v.ringBasePeriod + if v.ringFixedPeriod == 0 then + if v.overrideTranspose ~= 1000 then + rp += v.overrideTranspose + v.trackPeriod - 1 + else + rp += v.transpose + v.trackPeriod - 1 + end + end + rp = period(math.clamp(s16(rp), 0, 60)) + if v.ringFixedPeriod == 0 then + rp += v.periodSlidePeriod + end + rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) + end + + -- the period + local ap = v.instrPeriod + if v.fixedNote == 0 then + if v.overrideTranspose ~= 1000 then + ap += v.overrideTranspose + v.trackPeriod - 1 + else + ap += v.transpose + v.trackPeriod - 1 + end + end + ap = period(math.clamp(s16(ap), 0, 60)) + if v.fixedNote == 0 then + ap += v.periodSlidePeriod + end + ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.audioPeriod = math.clamp(ap, 0x71, 0xd60) + + local vol = (v.adsrVolume // 256 * v.noteMaxVolume) // 64 + vol = (vol * v.perfSubVolume) // 64 + vol = (vol * v.trackMasterVolume) // 64 + v.audioVolume = s16(vol) +end + +-- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) +@native local function fillCycles(dst: buffer, src: buffer, off: number, len: number) + if off < 0 or off + len > buffer.len(src) then + buffer.fill(dst, 0, 0, 0x281) + return + end + buffer.copy(dst, 0, src, off, len) + local filled = len + while filled < 0x280 do + local k = math.min(filled, 0x280 - filled) + buffer.copy(dst, filled, dst, 0, k) + filled += k + end + writei8(dst, 0x280, readi8(dst, 0)) +end + +@native local function setAudio(st: State, v: Voice) + v.voiceVolume = v.audioVolume % 256 + if v.plantPeriod then + v.plantPeriod = false + v.delta = deltaOf(v.audioPeriod, st.freq) + end + local src: buffer? = v.audioSrc or nil + if v.newWaveform and src then + fillCycles(v.voiceBuf, src, v.audioOff, if v.waveform == 3 then 0x280 else 4 * 2 ^ v.waveLength) + end + if v.ringPlantPeriod then + v.ringPlantPeriod = false + v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq) + end + if v.ringNewWaveform and v.ringAudioOff >= 0 then + fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength) + v.ringMix = true + end +end + +-- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +@native function Player.irq(st: State, audio: boolean) + local tune = st.tune + local nch = st.channels + local voices = st.voices + if st.stepWaitFrames == 0 then + if st.getNewPosition then + local nextpos = if st.posNr + 1 == tune.positionNr then 0 else st.posNr + 1 + local P = tune.positions + for i = 0, nch - 1 do + local v = voices[i + 1] + v.track = readu8(P, (st.posNr * 16 + i) * 2) + v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1) + v.nextTrack = readu8(P, (nextpos * 16 + i) * 2) + v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1) + end + st.getNewPosition = false + end + for i = 1, nch do + processStep(st, voices[i]) + end + st.stepWaitFrames = st.tempo + end + for i = 1, nch do + processFrame(st, voices[i]) + end + st.playingTime += 1 + st.stepWaitFrames = s16(st.stepWaitFrames - 1) + if st.stepWaitFrames == 0 then + if not st.patternBreak then + st.noteNr += 1 + if st.noteNr >= tune.trackLength then + st.posJump = st.posNr + 1 + st.posJumpNote = 0 + st.patternBreak = true + end + end + if st.patternBreak then + st.patternBreak = false + st.posNr = st.posJump + st.noteNr = st.posJumpNote + if st.posNr >= tune.positionNr then + -- (past the end is bad data: the C code reads outside its position list) + st.songEndReached = true + st.posNr = tune.restart + end + st.posJumpNote = 0 + st.posJump = 0 + st.getNewPosition = true + end + end + if audio then + for i = 1, nch do + setAudio(st, voices[i]) + end + end +end + +-- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +@native function Player.mix(st: State, out: buffer, at: number, n: number) + local nch = st.channels + local voices = st.voices + local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} + for i = 1, nch do + local v = voices[i] + delta[i] = math.max(v.delta, 1) + vol[i] = v.voiceVolume + pos[i] = v.samplePos + src[i] = v.voiceBuf + panl[i] = v.panMultLeft + panr[i] = v.panMultRight + rdelta[i] = math.max(v.ringDelta, 1) + rpos[i] = v.ringSamplePos + rsrc[i] = if v.ringMix then v.ringBuf else false + end + local gain = st.mixgain + local o = at * 8 + local samples = n + while samples > 0 do + local loops = samples + for i = 1, nch do + if pos[i] >= WRAP then + pos[i] -= WRAP + end + local cnt = (WRAP - pos[i] - 1) // delta[i] + 1 + if cnt < loops then + loops = cnt + end + if rsrc[i] then + if rpos[i] >= WRAP then + rpos[i] -= WRAP + end + cnt = (WRAP - rpos[i] - 1) // rdelta[i] + 1 + if cnt < loops then + loops = cnt + end + end + end + samples -= loops + for _ = 1, loops do + local a, b = 0, 0 + for i = 1, nch do + local j + local r = rsrc[i] + if r then + j = ((readi8(src[i], pos[i] // 65536) * readi8(r, rpos[i] // 65536)) // 128) * vol[i] + rpos[i] += rdelta[i] + else + j = readi8(src[i], pos[i] // 65536) * vol[i] + end + a += (j * panl[i]) // 128 + b += (j * panr[i]) // 128 + pos[i] += delta[i] + end + a = (a * gain) // 256 + b = (b * gain) // 256 + if a < -32768 then + a = -32768 + elseif a > 32767 then + a = 32767 + end + if b < -32768 then + b = -32768 + elseif b > 32767 then + b = 32767 + end + writef32(out, o, a / 32768) + writef32(out, o + 4, b / 32768) + o += 8 + end + end + for i = 1, nch do + voices[i].samplePos = pos[i] + voices[i].ringSamplePos = rpos[i] + end +end + +return Player +end +__FILES["codecs/audio/Hively/Tables"] = @native function() + + +-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at +-- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of +-- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported +-- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) +-- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +local Tables = {} + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift + +-- the offsets inside `waves` (bytes) +local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform +local WHITENOISELEN = 0x280 * 3 +local WO_LOWPASSES = 0 +local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31 +local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc +local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc +local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20 +local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN +local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31 + +Tables.FILTER_SET = FILTER_SET +Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04 +Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04 +Tables.WO_SQUARES = WO_SQUARES +Tables.WO_WHITENOISE = WO_WHITENOISE +Tables.WAVES_SIZE = WAVES_SIZE +-- offset of the waveform of length 4 << n inside the triangle / sawtooth runs +Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 } + +Tables.VIB = { + [0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, + 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, + 0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255, + -253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24, +} + +Tables.PERIOD = { + [0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970, + 0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4, + 0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0, + 0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C, + 0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D, + 0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0, + 0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097, + 0x008F, 0x0087, 0x007F, 0x0078, 0x0071, +} + +Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } +Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } + +@native local function i8(v: number): number + v = v % 256 + return if v >= 128 then v - 256 else v +end + +@native local function genSawtooth(w: buffer, at: number, len: number) + local add = 256 // (len - 1) + local val = -128 + for i = 0, len - 1 do + buffer.writei8(w, at + i, i8(val)) + val += add + end +end + +@native local function genTriangle(w: buffer, at: number, len: number) + local d5 = len // 4 + local d1 = 128 // d5 + local d4 = -(len // 2) + local p = at + local val = 0 + for _ = 1, d5 do + buffer.writei8(w, p, i8(val)) + p += 1 + val += d1 + end + buffer.writei8(w, p, 0x7f) + p += 1 + if d5 ~= 1 then + val = 128 + for _ = 1, d5 - 1 do + val -= d1 + buffer.writei8(w, p, i8(val)) + p += 1 + end + end + local q = p + d4 + for _ = 1, d5 * 2 do + local c = buffer.readi8(w, q) + q += 1 + buffer.writei8(w, p, if c == 0x7f then -128 else i8(-c)) + p += 1 + end +end + +@native local function genSquare(w: buffer, at: number) + local p = at + for i = 1, 0x20 do + for _ = 1, (0x40 - i) * 2 do + buffer.writei8(w, p, -128) + p += 1 + end + for _ = 1, i * 2 do + buffer.writei8(w, p, 0x7f) + p += 1 + end + end +end + +-- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves +@native local function genWhiteNoise(w: buffer, at: number, len: number) + local hi, lo = 0, 0x41595321 + for i = 0, len - 1 do + local s = i8(band(lo, 0xff)) + if band(lo, 0x100) ~= 0 then + s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds + end + buffer.writei8(w, at + i, s) + -- ays = (ays >> 5) | (ays << 27) + local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27)) + -- (the high half is masked off next: ays & 0xffffff00 zero-extends) + lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a)) + local bx = band(lo, 0xffff) + -- ays = (ays << 2) | (ays >> 30) + lo = bor(lshift(lo, 2), rshift(lo, 30)) + local ax = band(lo, 0xffff) + bx = band(bx + ax, 0xffff) + ax = bxor(ax, bx) + lo = bor(band(lo, 0xffff0000), ax) + -- ays = (ays >> 3) | (ays << 29) + hi = rshift(lo, 3) + lo = bor(rshift(lo, 3), lshift(lo, 29)) + end +end + +local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f } +for _ = 1, 32 do + table.insert(LENTAB, 0x7f) +end +table.insert(LENTAB, 0x280 * 3 - 1) + +@native local function clip(x: number): number + if x > 127 then + return 127 + elseif x < -128 then + return -128 + end + return x +end + +@native local function trunc8(x: number): number + return if x >= 0 then math.floor(x) else -math.floor(-x) +end + +@native local function genFilterWaves(w: buffer) + local low, high = WO_LOWPASSES, WO_HIGHPASSES + local freq = 8 + for _ = 0, 30 do + local a0 = WO_TRIANGLE_04 + local fre = freq * 1.25 / 100.0 + for wv = 1, 45 do + local n = LENTAB[wv] + local mid, lo = 0, 0 + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + end + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + buffer.writei8(w, low, trunc8(lo)) + buffer.writei8(w, high, trunc8(h)) + low += 1 + high += 1 + end + a0 += n + 1 + end + freq += 3 + end +end + +local cache: { waves: buffer, panL: { number }, panR: { number } }? = nil + +-- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only +@native function Tables.get(): { waves: buffer, panL: { number }, panR: { number } } + if cache then + return cache + end + local w = buffer.create(WAVES_SIZE) + local n = 4 + for k = 0, 5 do + genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n) + genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n) + n *= 2 + end + genSquare(w, WO_SQUARES) + genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN) + genFilterWaves(w) + -- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f) + local f = buffer.create(4) + buffer.writef32(f, 0, 3.14159265) + local aa = buffer.readf32(f, 0) * 2 / 4 + local ab = 0.0 + local step = (3.14159265 * 2.0 / 4.0) / 256.0 + local pl: { number }, pr: { number } = {}, {} + for i = 0, 255 do + pl[i] = math.floor(math.sin(aa) * 255.0) + pr[i] = math.floor(math.sin(ab) * 255.0) + aa += step + ab += step + end + pl[255] = 0 + pr[0] = 0 + cache = { waves = w, panL = pl, panR = pr } + return cache :: any +end + +return Tables +end +__FILES["codecs/audio/Mdct"] = @native function() + + + +-- 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. +-- +-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 +-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 +-- +-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley +-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays +-- 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("@rosetta/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 +-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values +-- +-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller +-- sizes them). +local Fft = __include("codecs/audio/Mdct/Fft") + +local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt + +local Mdct = {} +Mdct.Fft = Fft + +type Plan = { + n: number, -- window length N + m: number, -- coefficients N / 2 + fft: Fft.Plan, -- N / 4 points + twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 + tws: { number }, + re: { number }, -- scratch + im: { number }, + c: { number }, -- DCT-IV output scratch (M) +} + +-- new(N) -> Plan | nil +@native function Mdct.new(n: number): Plan? + if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then + return nil + end + local m = n // 2 + local q = n // 4 + local fft = Fft.new(q) + if not fft then + return nil + end + local twc, tws = table.create(q, 0), table.create(q, 0) + for p = 0, q - 1 do + local a = pi * (p + 0.125) / m + twc[p + 1], tws[p + 1] = cos(a), sin(a) + end + return { + n = n, + m = m, + fft = fft, + twc = twc, + tws = tws, + re = table.create(q, 0), + im = table.create(q, 0), + c = table.create(m, 0), + } +end + +-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] +@native local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + Fft.forward(plan.fft, re, im) + for k = 0, q - 1 do + local c, s = twc[k + 1], tws[k + 1] + local tr, ti = re[k + 1], im[k + 1] + out[oi + 2 * k * os] = (tr * c + ti * s) * scale + out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale + end +end + +-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the +-- plan's M = N / 2 (its own inverse up to 2 / M) +@native function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + for p = 0, q - 1 do + local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os, scale or 1) +end + +-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] +@native function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) + local q, m = plan.n // 4, plan.m + local h = m // 2 -- N / 4 + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) + local b3 = xi + 3 * h + for p = 0, q - 1 do + local j = 2 * p + local a + if j < h then + a = -x[b3 - 1 - j] - x[b3 + j] + else + a = x[xi + j - h] - x[b3 - 1 - j] + end + j = m - 1 - 2 * p + local b + if j < h then + b = -x[b3 - 1 - j] - x[b3 + j] + else + b = x[xi + j - h] - x[b3 - 1 - j] + end + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os or 1, scale or 1) +end + +-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) +@native function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) + local m = plan.m + local h = m // 2 + local c = plan.c + Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) + -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) + for j = 0, h - 1 do + y[yi + j] = c[h + j + 1] + y[yi + h + j] = -c[m - j] + y[yi + m + j] = -c[h - j] + y[yi + 3 * h + j] = -c[j + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ windows +@native local function besselI0(x: number): number + local sum, term = 1, 1 + local k = 1 + while k < 200 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-17 then + break + end + k += 1 + end + return sum +end +Mdct.besselI0 = besselI0 + +-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 +-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +@native function Mdct.window(kind: string, n: number, alpha: number?): { number }? + if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then + return nil + end + local w = table.create(n, 0) + if kind == "sine" then + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + elseif kind == "vorbis" then + for i = 0, n - 1 do + local s = sin(pi * (i + 0.5) / n) + w[i + 1] = sin(pi / 2 * s * s) + end + elseif kind == "kbd" then + local half = n // 2 + local a = alpha or 4 + local kais = table.create(half + 1, 0) + local total = 0 + for i = 0, half do + local r = 2 * i / half - 1 + kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) + total += kais[i + 1] + end + local acc = 0 + for i = 0, half - 1 do + acc += kais[i + 1] + local v = sqrt(acc / total) + w[i + 1] = v + w[n - i] = v + end + else + return nil + end + return w +end + +-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) +@native function Mdct.fft(n: number): Fft.Plan? + return Fft.new(n) +end + +return Mdct +end +__FILES["codecs/audio/Mdct/Fft"] = @native function() + + + +-- 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. +local Fft = {} + +type Plan = { + n: number, + factors: { number }, + -- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1] + twr: { { number } }, + twi: { { number } }, + -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 + rr: { { number } }, + ri: { { number } }, + sre: { number }, -- scratch + sim: { number }, +} + +local cos, sin, pi = math.cos, math.sin, math.pi + +-- new(n) -> Plan | nil (n < 1 or not an integer) +@native function Fft.new(n: number): Plan? + if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then + return nil + end + local factors = {} + local m = n + while m % 4 == 0 do + table.insert(factors, 4) + m //= 4 + end + while m % 2 == 0 do + table.insert(factors, 2) + m //= 2 + end + local f = 3 + while m > 1 do + while m % f == 0 do + table.insert(factors, f) + m //= f + end + f += 2 + if f * f > m and m > 1 then + table.insert(factors, m) + m = 1 + end + end + local twr, twi, rr, ri = {}, {}, {}, {} + local l1 = 1 + for k, p in factors do + local ido = n // (l1 * p) + local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) + for u = 1, p - 1 do + for i = 0, ido - 1 do + local a = -2 * pi * u * i * l1 / n + tr[(u - 1) * ido + i + 1] = cos(a) + ti[(u - 1) * ido + i + 1] = sin(a) + end + end + twr[k], twi[k] = tr, ti + local cr, ci = table.create(p, 0), table.create(p, 0) + for j = 0, p - 1 do + cr[j + 1] = cos(-2 * pi * j / p) + ci[j + 1] = sin(-2 * pi * j / p) + end + rr[k], ri[k] = cr, ci + l1 *= p + end + return { + n = n, + factors = factors, + twr = twr, + twi = twi, + rr = rr, + ri = ri, + sre = table.create(n, 0), + sim = table.create(n, 0), + } +end + +-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] +@native local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) + local lp = ido * l1 + if p == 4 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 4 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] + local t0r, t0i = a0r + a2r, a0i + a2i + local t1r, t1i = a0r - a2r, a0i - a2i + local t2r, t2i = a1r + a3r, a1i + a3i + local t3r, t3i = a1r - a3r, a1i - a3i + local d = 1 + i + ido * k + br[d], bi[d] = t0r + t2r, t0i + t2i + local y1r, y1i = t1r + t3i, t1i - t3r + local y2r, y2i = t0r - t2r, t0i - t2i + local y3r, y3i = t1r - t3i, t1i + t3r + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r + end + end + end + elseif p == 2 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 2 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local d = 1 + i + ido * k + br[d], bi[d] = a0r + a1r, a0i + a1i + local yr, yi = a0r - a1r, a0i - a1i + if i == 0 then + br[d + lp], bi[d + lp] = yr, yi + else + local wr, wi = tr[i + 1], ti[i + 1] + br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr + end + end + end + elseif p == 3 then + local c = 0.86602540378443864676 -- sin(pi / 3) + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 3 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local tr_, ti_ = a1r + a2r, a1i + a2i + local sr, si = a1r - a2r, a1i - a2i + local d = 1 + i + ido * k + br[d], bi[d] = a0r + tr_, a0i + ti_ + local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ + local y1r, y1i = mr + c * si, mi - c * sr + local y2r, y2i = mr - c * si, mi + c * sr + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + end + end + end + else + -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * p * k + local d = 1 + i + ido * k + for u = 0, p - 1 do + local yr, yi = 0, 0 + local j = 0 + for v = 0, p - 1 do + local xr, xi = ar[s + v * ido], ai[s + v * ido] + local wr, wi = cr[j + 1], ci[j + 1] + yr += xr * wr - xi * wi + yi += xr * wi + xi * wr + j += u + if j >= p then + j -= p + end + end + if u > 0 and i > 0 then + local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] + yr, yi = yr * wr - yi * wi, yr * wi + yi * wr + end + br[d + u * lp], bi[d + u * lp] = yr, yi + end + end + end + end +end + +-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. +-- The inverse (without the 1 / n) is forward(plan, im, re). +@native function Fft.forward(plan: Plan, re: { number }, im: { number }) + local n = plan.n + local ar, ai, br, bi = re, im, plan.sre, plan.sim + local l1 = 1 + for k, p in plan.factors do + local ido = n // (l1 * p) + pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) + ar, ai, br, bi = br, bi, ar, ai + l1 *= p + end + if ar ~= re then + for j = 1, n do + re[j], im[j] = ar[j], ai[j] + end + end +end + +return Fft +end +__FILES["codecs/audio/MidiRender"] = function() + +-- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in +-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). +-- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that +-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. +local Err = __include("core/Err") +local Types = __include("Types") +local SoundFont = __include("codecs/audio/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + +type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number } + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev: any): number? + if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) +function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap + local changes: { { number } } = {} + for ti, t in midi.tracks do + if track == nil or track == ti then + for i, ev in t.events do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a: { number }, b: { number }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in changes do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) +function Render.seconds(map: TempoMap, tick: number): number + local div = map.division + if div < 0 then + local fps = -(div // 256) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((if fps == 29 then 29.97 else fps) * tpf) + end + local ticks = map.ticks + -- binary search for the last change at or before tick + local lo, hi = 1, #ticks + while lo < hi do + local mid = (lo + hi + 1) // 2 + if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +-- length(midi) -> seconds to the last event (format 2: the tracks one after another) +function Render.length(midi: Types.Midi): number + if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + total += Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in midi.tracks do + for _, ev in t.events do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number } + +-- timeline(midi) -> the channel messages in play order with their times in seconds +function Render.timeline(midi: Types.Midi): Timeline + local items: { { any } } = {} + local offset = 0 + local function add(map: TempoMap, ti: number, t: any, base: number) + for i, ev in t.events do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in midi.tracks do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in t.events do + last = math.max(last, ev.tick) + end + offset += Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + add(map, ti, t, 0) + end + end + table.sort(items, function(a: { any }, b: { any }): boolean + if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local tl: Timeline = { time = table.create(#items) :: { number }, status = table.create(#items) :: { number }, d1 = table.create(#items) :: { number }, d2 = table.create(#items) :: { number }, length = Render.length(midi) } + for i, it in items do + tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 + end + return tl +end + +type RenderOptions = { + sampleRate: number?, -- default 44100 + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + gain: number?, -- linear output gain, default 0.5 + tail: number?, -- seconds rendered after the last event (release tails), default 1 + maxVoices: number?, -- default 256 +} + +-- decoder(midi, opts?) -> Types.Decoder | nil, Err +function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o: RenderOptions = opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame: { number } = table.create(nev) :: { number } + for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} :: Types.Tags, + } + local mtags = type(midi.meta) == "table" and midi.meta.tags + if type(mtags) == "table" then + for k, v in mtags do + if type(k) == "string" and type(v) == "string" then + dec.tags[k] = v + end + end + end + for _, t in midi.tracks do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf :: buffer + buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv += 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos += n + return b, n + end + dec.read = read :: any + local scratch = buffer.create(4096 * 8) + dec.seek = function(_self: any, seconds: number) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end :: any + dec.position = function(_self: any): number + return pos / rate + end :: any + return (dec :: any) :: Types.Decoder, nil +end + +-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last +-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +function Render.tempoBytes(division: number, ticksPerSecond: number): { number } + local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) + return { us // 65536, (us // 256) % 256, us % 256 } +end + +-- ------------------------------------------------------------------------------------------------ durations +type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent } + +-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). +-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note +-- started earlier goes before the file's events, an off of a zero-length note after them. +function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent } + for i, o in offs do + (o :: any).seq = i + end + table.sort(offs, function(a: any, b: any): boolean + if a.tick ~= b.tick then + return a.tick < b.tick + end + return a.seq < b.seq + end) + local out: { Types.MidiEvent } = table.create(#events + #offs) :: { Types.MidiEvent } + local k = 1 + for _, ev in events do + while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do + table.insert(out, offs[k].ev) + k += 1 + end + table.insert(out, ev) + end + for j = k, #offs do + table.insert(out, offs[j].ev) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ attach +local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder + local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty: any = { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self: any, _n: number, out: buffer?): (buffer, number) + return out or buffer.create(0), 0 + end, + seek = function() end, + position = function(): number + return 0 + end, + } + return empty + end + return dec +end + +-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events +function Render.summarize(midi: Types.Midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in midi.tracks do + for _, ev in t.events do + if ev.type == "meta" then + local d = ev.data :: { number } + if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method +function Render.attach(midi: Types.Midi, source: { [string]: any }) + Render.summarize(midi) + midi.meta.source = source + midi.render = render +end + +return Render +end +__FILES["codecs/audio/Mpa"] = function() + +-- 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 = __include("codecs/audio/Mpa/Header"), + Core = __include("codecs/audio/Mpa/Core"), + Encode3 = __include("codecs/audio/Mpa/Encode3"), + Encode2 = __include("codecs/audio/Mpa/Encode2"), +} + +return Mpa +end +__FILES["codecs/audio/Mpa/Analysis"] = @native function() + + + +-- 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 +-- 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 = __include("codecs/audio/Mpa/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + +type State = { x: { number }, off: number, y: { number } } + +@native function Analysis.new(): State + return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) +@native function Analysis.run(st: State, s: { number }, si: number, out: { number }, oi: number) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc += C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc += M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis +end +__FILES["codecs/audio/Mpa/Core"] = @native function() + + + +-- 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 = __include("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 +local rf, wf = buffer.readf32, buffer.writef32 +local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create +local min, max = math.min, math.max + +local MAX_BITRESERVOIR_BYTES = 511 +local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up +local SCALE = 1 / 32768 + +---------------------------------------------------------------------------------------------------------------- +-- tables (floats rounded to f32 like the C arrays) + +local F32 = bcreate(4) +@native local function f32(x: number): number + wf(F32, 0, x) + return rf(F32, 0) +end + +@native local function fbuf(list: { [number]: number }, n: number): buffer + local b = bcreate(n * 4) + for i = 0, n - 1 do + wf(b, i * 4, list[i]) + end + return b +end + +-- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer +local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504 +local SFB = bcreate(824 + 8) +for i = 0, 183 do + wu8(SFB, SFB_LONG + i, T.g_scf_long[i]) +end +for i = 0, 319 do + wu8(SFB, SFB_SHORT + i, T.g_scf_short[i]) + wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i]) +end + +local TABS = bcreate(2164 * 2) +for i = 0, 2163 do + buffer.writei16(TABS, i * 2, T.tabs[i]) +end +local TAB32, TAB33 = T.tab32, T.tab33 +local TABINDEX, LINBITS = T.tabindex, T.g_linbits +local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp +local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) } +local PAN = {} +for i = 0, 13 do + PAN[i] = f32(T.g_pan[i]) +end +local BITALLOC_CODE = T.g_bitalloc_code_tab +local HALFRATE = T.halfrate + +-- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code +local POW43 = bcreate(8207 * 4) +do + local g = {} + for i = 0, 144 do + g[i] = f32(T.g_pow43[i]) + end + local c43, c29 = f32(4 / 3), f32(2 / 9) + for x0 = 0, 8206 do + local v + if x0 < 129 then + v = g[16 + x0] + else + local x, mult = x0, 256 + if x < 1024 then + mult = 16 + x *= 8 + end + local sign = band(2 * x, 64) + local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign)) + v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult) + end + wf(POW43, x0 * 4, v) + end +end + +-- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9 +local DEQ_L12 = {} +do + local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 } + local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) } + for i = 0, 17 do + for j = 0, 2 do + DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1]) + end + end +end + +local AA = fbuf(T.g_aa, 16) +local TWID3 = fbuf(T.g_twid3, 6) +local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based +for i = 0, 17 do + MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i]) + MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i]) +end +local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values) +for i = 0, 239 do + WINT[i + 1] = f32(T.g_win[i]) +end + +---------------------------------------------------------------------------------------------------------------- +-- scratch + +local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame) +local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 +local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 +local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32 +local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 +local ISCF = bcreate(48) -- integer scalefactors, u8 +local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] +local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 +local BA = bcreate(64) -- L12 bit allocation +local SCFCOD = bcreate(64) + +-- layer III side info, per granule x channel (0..3) +local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {} +local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {} +local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k] +for i = 0, 3 do + GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0 + GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0 + for k = 0, 2 do + GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0 + end +end +local MAXB = { [0] = -1, -1, -1 } +local SCFSIZE = { [0] = 0, 0, 0, 0 } + +-- per-stream state of the frame being decoded (set by decodeFrame) +local OVL: buffer = bcreate(4) -- mdct_overlap[2][9*32] +local QMF: buffer = bcreate(4) -- qmf_state[15*2*32] +local PCM: buffer = bcreate(4) + +---------------------------------------------------------------------------------------------------------------- +-- bit reader (bs_t): position and limit in bits + +local bsBuf: buffer = FRAME +local bsPos = 0 +local bsLimit = 0 + +-- n <= 25 +@native local function getBits(n: number): number + local pos = bsPos + bsPos = pos + n + if pos + n > bsLimit then + return 0 + end + local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7)) + return rshift(w, 32 - n) +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 + +@native local function readSideInfo(h1: number, h2: number, h3: number): number + local mono = band(h3, 0xC0) == 0xC0 + local mpeg1 = band(h1, 8) ~= 0 + local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + if srIdx ~= 0 then + srIdx -= 1 + end + local grCount = if mono then 1 else 2 + local scfsi = 0 + local mdb + if mpeg1 then + grCount *= 2 + mdb = getBits(9) + scfsi = getBits(7 + grCount) + else + mdb = rshift(getBits(8 + grCount), grCount) + end + local part23sum = 0 + for gr = 0, grCount - 1 do + if mono then + scfsi = lshift(scfsi, 4) + end + local p23 = getBits(12) + GR_P23[gr] = p23 + part23sum += p23 + local bv = getBits(9) + if bv > 288 then + return -1 + end + GR_BV[gr] = bv + GR_GAIN[gr] = getBits(8) + local sfc = getBits(if mpeg1 then 4 else 9) + GR_SFC[gr] = sfc + GR_SFB[gr] = SFB_LONG + srIdx * 23 + GR_NLONG[gr] = 22 + GR_NSHORT[gr] = 0 + local tables + local g3 = gr * 3 + if getBits(1) ~= 0 then + local bt = getBits(2) + if bt == 0 then + return -1 + end + GR_BT[gr] = bt + local mixed = getBits(1) + GR_MIXED[gr] = mixed + GR_RC[g3] = 7 + GR_RC[g3 + 1] = 255 + if bt == 2 then + scfsi = band(scfsi, 0x0F0F) + if mixed == 0 then + GR_RC[g3] = 8 + GR_SFB[gr] = SFB_SHORT + srIdx * 40 + GR_NLONG[gr] = 0 + GR_NSHORT[gr] = 39 + else + GR_SFB[gr] = SFB_MIXED + srIdx * 40 + GR_NLONG[gr] = if mpeg1 then 8 else 6 + GR_NSHORT[gr] = 30 + end + end + tables = lshift(getBits(10), 5) + GR_SBG[g3] = getBits(3) + GR_SBG[g3 + 1] = getBits(3) + GR_SBG[g3 + 2] = getBits(3) + else + GR_BT[gr] = 0 + GR_MIXED[gr] = 0 + tables = getBits(15) + GR_RC[g3] = getBits(4) + GR_RC[g3 + 1] = getBits(3) + GR_RC[g3 + 2] = 255 + end + GR_TS[g3] = rshift(tables, 10) + GR_TS[g3 + 1] = band(rshift(tables, 5), 31) + GR_TS[g3 + 2] = band(tables, 31) + GR_PRE[gr] = if mpeg1 then getBits(1) elseif sfc >= 500 then 1 else 0 + GR_SCALE[gr] = getBits(1) + GR_C1[gr] = getBits(1) + GR_SCFSI[gr] = band(rshift(scfsi, 12), 15) + scfsi = lshift(scfsi, 4) + end + if part23sum + bsPos > bsLimit + mdb * 8 then + return -1 + end + return mdb +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III scalefactors + +@native local function ldexpQ2(y: number, e: number): number + repeat + local s = if e < 120 then e else 120 + y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) + e -= s + until e <= 0 + return y +end + +-- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) +@native local function decodeScalefactors(h1: number, h3: number, istOff: number, gr: number, ch: number) + local mpeg1 = band(h1, 8) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local part = ((if nShort ~= 0 then 1 else 0) + (if nLong == 0 then 1 else 0)) * 28 + local scfShift = GR_SCALE[gr] + 1 + local scfsi = GR_SCFSI[gr] + if mpeg1 then + local p = SCFC_DECODE[GR_SFC[gr]] + local hi, lo = rshift(p, 2), band(p, 3) + SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo + else + local ist = if band(h3, 0x10) ~= 0 and ch ~= 0 then 1 else 0 + local sfc = rshift(GR_SFC[gr], ist) + local k = ist * 12 + while sfc >= 0 do + local modprod = 1 + for i = 3, 0, -1 do + SCFSIZE[i] = (sfc // modprod) % GMOD[k + i] + modprod *= GMOD[k + i] + end + sfc -= modprod + k += 4 + end + part += k + end + -- L3_read_scalefactors + local sp, ip = 0, istOff + for i = 0, 3 do + local cnt = SCF_PARTITIONS[part + i] + if cnt == 0 then + break + end + if mpeg1 and band(scfsi, 8) ~= 0 then + bcopy(ISCF, sp, IST, ip, cnt) + else + local bits = SCFSIZE[i] + if bits == 0 then + bfill(ISCF, sp, 0, cnt) + bfill(IST, ip, 0, cnt) + else + local maxScf = if mpeg1 then -1 else lshift(1, bits) - 1 + for k = 0, cnt - 1 do + local s = getBits(bits) + wu8(IST, ip + k, if s == maxScf then 255 else s) + wu8(ISCF, sp + k, s) + end + end + end + sp += cnt + ip += cnt + scfsi *= 2 + end + wu8(ISCF, sp, 0) + wu8(ISCF, sp + 1, 0) + wu8(ISCF, sp + 2, 0) + + if nShort ~= 0 then + local sh = 3 - scfShift + local g3 = gr * 3 + local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh) + for i = 0, nShort - 1, 3 do + local o = nLong + i + wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255)) + wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255)) + wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255)) + end + elseif GR_PRE[gr] ~= 0 then + for i = 0, 9 do + wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255)) + end + end + + local gainExp = GR_GAIN[gr] - 4 - 210 - (if band(h3, 0xE0) == 0x60 then 2 else 0) + local gain = ldexpQ2(2048, 44 - gainExp) + for i = 0, nLong + nShort - 1 do + wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift))) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache + +@native local function huffman(dst: number, gr: number, limit: number) + local b = bsBuf + local one = 0.0 + local ireg = 0 + local bigValCnt = GR_BV[gr] + local sfb = GR_SFB[gr] + local scf = 0 + local pos = bsPos + local nextPtr = rshift(pos, 3) + local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7)) + local sh = band(pos, 7) - 8 + nextPtr += 4 + local g3 = gr * 3 + local d = dst * 4 + + while bigValCnt > 0 do + if ireg > 2 then + break + end + local tabNum = GR_TS[g3 + ireg] + local sfbCnt = GR_RC[g3 + ireg] + ireg += 1 + local cb = TABINDEX[tabNum] + local linbits = LINBITS[tabNum] + repeat + local np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + bigValCnt = 0 + break + end + local pairs = if bigValCnt < np then bigValCnt else np + one = rf(SCF, scf) + scf += 4 + for _ = 1, pairs do + local w = 5 + local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2) + while leaf < 0 do + cache = lshift(cache, w) + sh += w + w = band(leaf, 7) + leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - leaf // 8) * 2) + end + local l = rshift(leaf, 8) + cache = lshift(cache, l) + sh += l + for _ = 1, 2 do + local lsb = band(leaf, 15) + if lsb == 15 and linbits ~= 0 then + lsb += rshift(cache, 32 - linbits) + cache = lshift(cache, linbits) + sh += linbits + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + local v = rf(POW43, lsb * 4) * one + if lsb ~= 0 then + if cache >= 0x80000000 then + v = -v + end + cache = lshift(cache, 1) + sh += 1 + end + wf(GRBUF, d, v) + d += 4 + leaf = rshift(leaf, 4) + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + end + bigValCnt -= np + sfbCnt -= 1 + until not (bigValCnt > 0 and sfbCnt >= 0) + end + + -- count1 quadruples + local np = 1 - bigValCnt + local cb1 = if GR_C1[gr] ~= 0 then TAB33 else TAB32 + local dend = 576 * 4 * 2 + while true do + local leaf = cb1[rshift(cache, 28)] + if band(leaf, 8) == 0 then + leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))] + end + local l = band(leaf, 7) + cache = lshift(cache, l) + sh += l + if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then + break + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 128) ~= 0 then + wf(GRBUF, d, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 64) ~= 0 then + wf(GRBUF, d + 4, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + np -= 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb += 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf += 4 + end + if band(leaf, 32) ~= 0 then + wf(GRBUF, d + 8, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + if band(leaf, 16) ~= 0 then + wf(GRBUF, d + 12, if cache >= 0x80000000 then -one else one) + cache = lshift(cache, 1) + sh += 1 + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr += 1 + sh -= 8 + end + d += 16 + end + bsPos = limit +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III stereo + +-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 +@native local function midside(left: number, n: number) + for i = left * 4, (left + n - 1) * 4, 4 do + local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) + wf(GRBUF, i, a + c) + wf(GRBUF, i + 2304, a - c) + end +end + +@native local function intensityStereo(h1: number, h3: number, gr: number) + local mpeg1 = band(h1, 8) ~= 0 + local ms = band(h3, 0x20) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local nSfb = nLong + nShort + local maxBlocks = if nShort ~= 0 then 3 else 1 + local sfb0 = GR_SFB[gr] + -- L3_stereo_top_band on the right channel + MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1 + local right = 576 + for i = 0, nSfb - 1 do + local n = ru8(SFB, sfb0 + i) + for k = right, right + n - 1, 2 do + if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then + MAXB[i % 3] = i + break + end + end + right += n + end + if nLong ~= 0 then + local m = max(MAXB[0], MAXB[1], MAXB[2]) + MAXB[0], MAXB[1], MAXB[2] = m, m, m + end + for i = 0, maxBlocks - 1 do + local defaultPos = if mpeg1 then 3 else 0 + local itop = nSfb - maxBlocks + i + local prev = itop - maxBlocks + wu8(IST, 39 + itop, if MAXB[i] >= prev then defaultPos else ru8(IST, 39 + prev)) + end + -- L3_stereo_process + local mpeg2sh = band(GR_SFC[gr + 1], 1) + local maxPos = if mpeg1 then 7 else 64 + local s = if ms then f32(1.41421356) else 1 + local left = 0 + local i = 0 + while true do + local n = ru8(SFB, sfb0 + i) + if n == 0 then + break + end + local ipos = ru8(IST, 39 + i) + if i > MAXB[i % 3] and ipos < maxPos then + local kl, kr + if mpeg1 then + kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1] + else + kl = 1 + kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh)) + if band(ipos, 1) ~= 0 then + kl = kr + kr = 1 + end + end + 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) + wf(GRBUF, k, v * kl) + end + elseif ms then + midside(left, n) + end + left += n + i += 1 + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III reorder, antialias, IMDCT + +@native local function reorder(g: number, sfb: number) + local src, dst = g, 0 + while true do + local len = ru8(SFB, sfb) + if len == 0 then + break + end + for i = 0, len - 1 do + local s = (src + i) * 4 + wf(SYN, dst, rf(GRBUF, s)) + wf(SYN, dst + 4, rf(GRBUF, s + len * 4)) + wf(SYN, dst + 8, rf(GRBUF, s + len * 8)) + dst += 12 + end + src += 3 * len + sfb += 3 + end + bcopy(GRBUF, g * 4, SYN, 0, dst) +end + +local AA0 = table.create(8, 0) +local AA1 = table.create(8, 0) +for i = 0, 7 do + AA0[i + 1] = rf(AA, i * 4) + AA1[i + 1] = rf(AA, 32 + i * 4) +end + +@native local function antialias(g: number, nbands: number) + local o = g * 4 + for _ = 1, nbands do + for i = 0, 7 do + local ui, di = o + (18 + i) * 4, o + (17 - i) * 4 + local u, d = rf(GRBUF, ui), rf(GRBUF, di) + local c0, c1 = AA0[i + 1], AA1[i + 1] + wf(GRBUF, ui, u * c0 - d * c1) + wf(GRBUF, di, u * c1 + d * c0) + end + o += 72 + end +end + +-- BEGIN generated by tools/gen_dsp.py + +-- L3_dct3_9 on 9 values +@native local function dct3_9(s0: number, s1: number, s2: number, s3: number, s4: number, s5: number, s6: number, s7: number, s8: number) + local t0 = s0 + s6 * 0.5 + s0 -= s6 + local t4 = (s4 + s2) * 0.939692616 + local t2 = (s8 + s2) * 0.766044438 + s6 = (s4 - s8) * 0.173648179 + s4 += s8 - s2 + s2 = s0 - s4 * 0.5 + local y4 = s4 + s0 + s8 = t0 - t2 + s6 + s0 = t0 - t4 + t2 + s4 = t0 + t4 - s6 + s3 *= 0.866025388 + t0 = (s5 + s1) * 0.98480773 + t4 = (s5 - s7) * 0.342020154 + t2 = (s1 + s7) * 0.642787635 + s1 = (s1 - s5 - s7) * 0.866025388 + s5 = t0 - s3 - t2 + s7 = t4 - s3 - t0 + s3 = t4 + s3 - t2 + return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7 +end + +-- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) +@native local function imdct36(g: number, ov: number, W: { number }, nbands: number) + local w0 = W[1] + local w1 = W[2] + local w2 = W[3] + local w3 = W[4] + local w4 = W[5] + local w5 = W[6] + local w6 = W[7] + local w7 = W[8] + local w8 = W[9] + local w9 = W[10] + local w10 = W[11] + local w11 = W[12] + local w12 = W[13] + local w13 = W[14] + local w14 = W[15] + local w15 = W[16] + local w16 = W[17] + local w17 = W[18] + for _ = 1, nbands do + local gb = g * 4 + local g0 = rf(GRBUF, gb + 0) + local g1 = rf(GRBUF, gb + 4) + local g2 = rf(GRBUF, gb + 8) + local g3 = rf(GRBUF, gb + 12) + local g4 = rf(GRBUF, gb + 16) + local g5 = rf(GRBUF, gb + 20) + local g6 = rf(GRBUF, gb + 24) + local g7 = rf(GRBUF, gb + 28) + local g8 = rf(GRBUF, gb + 32) + local g9 = rf(GRBUF, gb + 36) + local g10 = rf(GRBUF, gb + 40) + local g11 = rf(GRBUF, gb + 44) + local g12 = rf(GRBUF, gb + 48) + local g13 = rf(GRBUF, gb + 52) + local g14 = rf(GRBUF, gb + 56) + local g15 = rf(GRBUF, gb + 60) + local g16 = rf(GRBUF, gb + 64) + local g17 = rf(GRBUF, gb + 68) + local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16)) + local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2) + s1, s3, s5, s7 = -s1, -s3, -s5, -s7 + local ob = ov * 4 + do + local ovl = rf(OVL, ob + 0) + local sum = c0 * 0.675590217 + s0 * 0.737277329 + wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217) + wf(GRBUF, gb + 0, ovl * w0 - sum * w9) + wf(GRBUF, gb + 68, ovl * w9 + sum * w0) + end + do + local ovl = rf(OVL, ob + 4) + local sum = c1 * 0.60876143 + s1 * 0.793353319 + wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143) + wf(GRBUF, gb + 4, ovl * w1 - sum * w10) + wf(GRBUF, gb + 64, ovl * w10 + sum * w1) + end + do + local ovl = rf(OVL, ob + 8) + local sum = c2 * 0.537299633 + s2 * 0.843391478 + wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633) + wf(GRBUF, gb + 8, ovl * w2 - sum * w11) + wf(GRBUF, gb + 60, ovl * w11 + sum * w2) + end + do + local ovl = rf(OVL, ob + 12) + local sum = c3 * 0.4617486 + s3 * 0.887010813 + wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486) + wf(GRBUF, gb + 12, ovl * w3 - sum * w12) + wf(GRBUF, gb + 56, ovl * w12 + sum * w3) + end + do + local ovl = rf(OVL, ob + 16) + local sum = c4 * 0.382683426 + s4 * 0.923879504 + wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426) + wf(GRBUF, gb + 16, ovl * w4 - sum * w13) + wf(GRBUF, gb + 52, ovl * w13 + sum * w4) + end + do + local ovl = rf(OVL, ob + 20) + local sum = c5 * 0.300705791 + s5 * 0.953716934 + wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791) + wf(GRBUF, gb + 20, ovl * w5 - sum * w14) + wf(GRBUF, gb + 48, ovl * w14 + sum * w5) + end + do + local ovl = rf(OVL, ob + 24) + local sum = c6 * 0.216439605 + s6 * 0.976296008 + wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605) + wf(GRBUF, gb + 24, ovl * w6 - sum * w15) + wf(GRBUF, gb + 44, ovl * w15 + sum * w6) + end + do + local ovl = rf(OVL, ob + 28) + local sum = c7 * 0.130526185 + s7 * 0.991444886 + wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185) + wf(GRBUF, gb + 28, ovl * w7 - sum * w16) + wf(GRBUF, gb + 40, ovl * w16 + sum * w7) + end + do + local ovl = rf(OVL, ob + 32) + local sum = c8 * 0.0436193794 + s8 * 0.999048233 + wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794) + wf(GRBUF, gb + 32, ovl * w8 - sum * w17) + wf(GRBUF, gb + 36, ovl * w17 + sum * w8) + end + g += 18 + ov += 9 + end +end + +-- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals +@native local function dctII(g: number, n: number) + for k = 0, n - 1 do + local y = (g + k) * 4 + local t0_0, t1_0, t2_0, t3_0 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302 + t0_0 = a + b + t1_0 = (a - b) * 0.502419293 + t2_0 = d + c + t3_0 = (d - c) * 0.502419293 + end + local t0_1, t1_1, t2_1, t3_1 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932 + t0_1 = a + b + t1_1 = (a - b) * 0.522498608 + t2_1 = d + c + t3_1 = (d - c) * 0.522498608 + end + local t0_2, t1_2, t2_2, t3_2 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319 + t0_2 = a + b + t1_2 = (a - b) * 0.566944063 + t2_2 = d + c + t3_2 = (d - c) * 0.566944063 + end + local t0_3, t1_3, t2_3, t3_3 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576 + t0_3 = a + b + t1_3 = (a - b) * 0.646821797 + t2_3 = d + c + t3_3 = (d - c) * 0.646821797 + end + local t0_4, t1_4, t2_4, t3_4 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924 + t0_4 = a + b + t1_4 = (a - b) * 0.788154602 + t2_4 = d + c + t3_4 = (d - c) * 0.788154602 + end + local t0_5, t1_5, t2_5, t3_5 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976 + t0_5 = a + b + t1_5 = (a - b) * 1.06067765 + t2_5 = d + c + t3_5 = (d - c) * 1.06067765 + end + local t0_6, t1_6, t2_6, t3_6 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115 + t0_6 = a + b + t1_6 = (a - b) * 1.72244716 + t2_6 = d + c + t3_6 = (d - c) * 1.72244716 + end + local t0_7, t1_7, t2_7, t3_7 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323 + t0_7 = a + b + t1_7 = (a - b) * 5.10114861 + t2_7 = d + c + t3_7 = (d - c) * 5.10114861 + end + do -- row 0 + local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t0_0 = x0 + x1 + t0_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t0_1 = (xt + x7) * 0.509795606 + t0_2 = (x4 + x3) * 0.541196108 + t0_3 = (x0 - x5) * 0.601344883 + t0_5 = (x0 + x5) * 0.899976194 + t0_6 = (x4 - x3) * 1.30656302 + t0_7 = (xt - x7) * 2.56291556 + end + do -- row 1 + local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t1_0 = x0 + x1 + t1_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t1_1 = (xt + x7) * 0.509795606 + t1_2 = (x4 + x3) * 0.541196108 + t1_3 = (x0 - x5) * 0.601344883 + t1_5 = (x0 + x5) * 0.899976194 + t1_6 = (x4 - x3) * 1.30656302 + t1_7 = (xt - x7) * 2.56291556 + end + do -- row 2 + local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t2_0 = x0 + x1 + t2_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t2_1 = (xt + x7) * 0.509795606 + t2_2 = (x4 + x3) * 0.541196108 + t2_3 = (x0 - x5) * 0.601344883 + t2_5 = (x0 + x5) * 0.899976194 + t2_6 = (x4 - x3) * 1.30656302 + t2_7 = (xt - x7) * 2.56291556 + end + do -- row 3 + local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 + local xt = x0 - x7 + x0 += x7 + x7 = x1 - x6 + x1 += x6 + x6 = x2 - x5 + x2 += x5 + x5 = x3 - x4 + x3 += x4 + x4 = x0 - x3 + x0 += x3 + x3 = x1 - x2 + x1 += x2 + t3_0 = x0 + x1 + t3_4 = (x0 - x1) * 0.707106769 + x5 += x6 + x6 = (x6 + x7) * 0.707106769 + x7 += xt + x3 = (x3 + x4) * 0.707106769 + x5 -= x7 * 0.198912367 + x7 += x5 * 0.382683426 + x5 -= x7 * 0.198912367 + x0 = xt - x6 + xt += x6 + t3_1 = (xt + x7) * 0.509795606 + t3_2 = (x4 + x3) * 0.541196108 + t3_3 = (x0 - x5) * 0.601344883 + t3_5 = (x0 + x5) * 0.899976194 + t3_6 = (x4 - x3) * 1.30656302 + t3_7 = (xt - x7) * 2.56291556 + end + wf(GRBUF, y + 0, t0_0) + wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1) + wf(GRBUF, y + 144, t1_0 + t1_1) + wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1) + wf(GRBUF, y + 288, t0_1) + wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2) + wf(GRBUF, y + 432, t1_1 + t1_2) + wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2) + wf(GRBUF, y + 576, t0_2) + wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3) + wf(GRBUF, y + 720, t1_2 + t1_3) + wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3) + wf(GRBUF, y + 864, t0_3) + wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4) + wf(GRBUF, y + 1008, t1_3 + t1_4) + wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4) + wf(GRBUF, y + 1152, t0_4) + wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5) + wf(GRBUF, y + 1296, t1_4 + t1_5) + wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5) + wf(GRBUF, y + 1440, t0_5) + wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6) + wf(GRBUF, y + 1584, t1_5 + t1_6) + wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6) + wf(GRBUF, y + 1728, t0_6) + wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7) + wf(GRBUF, y + 1872, t1_6 + t1_7) + wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7) + wf(GRBUF, y + 2016, t0_7) + wf(GRBUF, y + 2088, t2_7 + t3_7) + wf(GRBUF, y + 2160, t1_7) + wf(GRBUF, y + 2232, t3_7) + end +end + +-- END generated + + +-- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index +@native local function imdct12(x: number, dst: buffer, d: number, ov: number) + local xb = x * 4 + local x0, x3, x6, x9, x12, x15 = + rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) + -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co + local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9) + local m1 = (c1 * 0.86602540) + local a1 = (c0 - c2 * 0.5) + local co1 = c0 + c2 + local co0, co2 = a1 + m1, a1 - m1 + -- L3_idct3(x15, x12 - x9, x6 - x3) -> si + c0, c1, c2 = x15, (x12 - x9), (x6 - x3) + m1 = (c1 * 0.86602540) + a1 = (c0 - c2 * 0.5) + local si1 = -(c0 + c2) + local si0, si2 = a1 + m1, a1 - m1 + local ob, db = ov * 4, d * 4 + for i = 0, 2 do + local co = if i == 0 then co0 elseif i == 1 then co1 else co2 + local si = if i == 0 then si0 elseif i == 1 then si1 else si2 + local ovl = rf(OVL, ob + i * 4) + local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4)) + wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4)) + wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4)) + wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4)) + end +end + +@native local function imdctShort(g: number, ov: number, nbands: number) + for _ = 1, nbands do + bcopy(TMP, 0, GRBUF, g * 4, 72) + bcopy(GRBUF, g * 4, OVL, ov * 4, 24) + imdct12(0, GRBUF, g + 6, ov + 6) + imdct12(1, GRBUF, g + 12, ov + 6) + imdct12(2, OVL, ov, ov + 6) + g += 18 + ov += 9 + end +end + +@native local function changeSign(g: number) + local o = (g + 18) * 4 + for _ = 0, 15 do + for i = 1, 17, 2 do + wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4)) + end + o += 144 + end +end + +@native local function imdctGr(g: number, ov: number, bt: number, nLongBands: number) + if nLongBands ~= 0 then + imdct36(g, ov, MDCT_WIN0, nLongBands) + g += 18 * nLongBands + ov += 9 * nLongBands + end + if bt == 2 then + imdctShort(g, ov, 32 - nLongBands) + else + imdct36(g, ov, if bt == 3 then MDCT_WIN1 else MDCT_WIN0, 32 - nLongBands) + end +end + +-- L3_decode: one granule, side info at gr = grBase + ch +@native local function l3Decode(h1: number, h2: number, h3: number, grBase: number, nch: number) + for ch = 0, nch - 1 do + local gr = grBase + ch + local limit = bsPos + GR_P23[gr] + decodeScalefactors(h1, h3, ch * 39, gr, ch) + huffman(ch * 576, gr, limit) + end + if band(h3, 0x10) ~= 0 then + intensityStereo(h1, h3, grBase) + elseif band(h3, 0xE0) == 0x60 then + midside(0, 576) + end + local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + for ch = 0, nch - 1 do + local gr = grBase + ch + local aaBands = 31 + local nLongBands = if GR_MIXED[gr] ~= 0 then (if mySr == 2 then 4 else 2) else 0 + local g = ch * 576 + if GR_NSHORT[gr] ~= 0 then + aaBands = nLongBands - 1 + reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr]) + end + antialias(g, aaBands) + imdctGr(g, ch * 288, GR_BT[gr], nLongBands) + changeSign(g) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) + + +-- mp3d_synth_pair: z = SYN float index, dst = PCM float index +@native local function synthPair(dst: number, nch: number, z: number) + local zb = z * 4 + local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 + a += (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 + a += (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 + a += (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 + a += (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 + a += (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 + a += (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 + a += rf(SYN, zb + 7 * 256) * 75038 + wf(PCM, dst * 4, a * SCALE) + zb += 8 + a = rf(SYN, zb + 14 * 256) * 104 + a += rf(SYN, zb + 12 * 256) * 1567 + a += rf(SYN, zb + 10 * 256) * 9727 + a += rf(SYN, zb + 8 * 256) * 64019 + a += rf(SYN, zb + 6 * 256) * -9975 + a += rf(SYN, zb + 4 * 256) * -45 + a += rf(SYN, zb + 2 * 256) * 146 + a += rf(SYN, zb) * -5 + wf(PCM, (dst + 16 * nch) * 4, a * SCALE) +end + +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left +-- channel's slot, dstl = PCM float index, lins = SYN float index +@native local function synth(xl: number, dstl: number, nch: number, lins: number) + local xr = xl + 576 * (nch - 1) + local dstr = dstl + (nch - 1) + local zlin = lins + 15 * 64 + local zb = zlin * 4 + local xlb, xrb = xl * 4, xr * 4 + wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4)) + wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4)) + wf(SYN, zb + 62 * 4, rf(GRBUF, xlb)) + wf(SYN, zb + 63 * 4, rf(GRBUF, xrb)) + wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4)) + wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4)) + wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4)) + wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4)) + if nch == 2 then + synthPair(dstr, nch, lins + 4 * 15 + 1) + synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1) + end + synthPair(dstl, nch, lins + 4 * 15) + synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64) + + local w = 1 + for i = 14, 0, -1 do + local zi = zb + 16 * i + local s1 = (18 * (31 - i)) * 4 + local s2 = (18 * (1 + i)) * 4 + wf(SYN, zi, rf(GRBUF, xlb + s1)) + wf(SYN, zi + 4, rf(GRBUF, xrb + s1)) + wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4)) + wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4)) + wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4)) + wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4)) + wf(SYN, zi - 248, rf(GRBUF, xlb + s2)) + wf(SYN, zi - 244, rf(GRBUF, xrb + s2)) + -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2 + local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0 + local vz, vy = zi, zi - 15 * 256 + if nch == 2 then + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) + local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + b0 += z0 * w1 + y0 * w0 + b1 += z1 * w1 + y1 * w0 + b2 += z2 * w1 + y2 * w0 + b3 += z3 * w1 + y3 * w0 + a0 += z0 * w0 - y0 * w1 + a1 += z1 * w0 - y1 * w1 + a2 += z2 * w0 - y2 * w1 + a3 += z3 * w0 - y3 * w1 + vz -= 256 + vy += 256 + 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 + b3 += z3 * w3 + y3 * w2 + a0 += y0 * w3 - z0 * w2 + a1 += y1 * w3 - z1 * w2 + a2 += y2 * w3 - z2 * w2 + a3 += y3 * w3 - z3 * w2 + vz -= 256 + vy += 256 + end + wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE) + wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE) + wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE) + wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE) + else + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w += 4 + local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) + local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + b0 += z0 * w1 + y0 * w0 + b2 += z2 * w1 + y2 * w0 + a0 += z0 * w0 - y0 * w1 + a2 += z2 * w0 - y2 * w1 + vz -= 256 + vy += 256 + 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 + a2 += y2 * w3 - z2 * w2 + vz -= 256 + vy += 256 + end + end + wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE) + wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE) + wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE) + wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE) + end +end + +@native local function synthGranule(nbands: number, nch: number, pcm: number) + for ch = 0, nch - 1 do + dctII(576 * ch, nbands) + end + bcopy(SYN, 0, QMF, 0, 15 * 64 * 4) + for i = 0, nbands - 1, 2 do + synth(i, pcm + 32 * nch * i, nch, i * 64) + end + if nch == 1 then + local src = nbands * 64 * 4 + for i = 0, 15 * 64 * 4 - 8, 8 do + wf(QMF, i, rf(SYN, src + i)) + end + else + bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layers I and II + +local ALLOC_L1 = { 76, 4, 32 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } + +local totalBands, stereoBands = 0, 0 + +@native local function l12ReadScaleInfo(h1: number, h2: number, h3: number, kbpsHdr: number) + local mode = rshift(h3, 6) + local sb = if mode == 3 then 0 elseif mode == 1 then band(rshift(h3, 4), 3) * 4 + 4 else 32 + local layer1 = band(h1, 6) == 6 + local alloc, nbands + if layer1 then + alloc, nbands = ALLOC_L1, 32 + elseif band(h1, 8) == 0 then + alloc, nbands = ALLOC_L2M2, 30 + else + local srIdx = band(rshift(h2, 2), 3) + local kbps = if mode ~= 3 then rshift(kbpsHdr, 1) else kbpsHdr + if kbps == 0 then + kbps = 192 + end + alloc, nbands = ALLOC_L2M1, 27 + if kbps < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIdx == 2 then 12 else 8 + elseif kbps >= 96 and srIdx ~= 1 then + nbands = 30 + end + end + totalBands = nbands + stereoBands = min(sb, nbands) + local k, baBits, codeOff, ai = 0, 0, 0, 1 + for i = 0, nbands - 1 do + if i == k then + codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + local ba = BITALLOC_CODE[codeOff + getBits(baBits)] + wu8(BA, 2 * i, ba) + if i < stereoBands then + ba = BITALLOC_CODE[codeOff + getBits(baBits)] + end + wu8(BA, 2 * i + 1, if stereoBands ~= 0 then ba else 0) + end + for i = 0, 2 * nbands - 1 do + wu8(SCFCOD, i, if ru8(BA, i) ~= 0 then (if layer1 then 2 else getBits(2)) else 6) + end + -- L12_read_scalefactors + local so = 0 + for i = 0, 2 * nbands - 1 do + local s = 0 + local ba = ru8(BA, i) + local mask = if ba ~= 0 then 4 + band(rshift(19, ru8(SCFCOD, i)), 3) else 0 + local m = 4 + while m ~= 0 do + if band(mask, m) ~= 0 then + local b = getBits(6) + s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), b // 3)) + end + wf(L12SCF, so, s) + so += 4 + m = rshift(m, 1) + end + end + for i = stereoBands, nbands - 1 do + wu8(BA, 2 * i + 1, 0) + end +end + +@native local function l12Dequantize(g: number, groupSize: number): number + local choff = 576 + for j = 0, 3 do + local dst = g + groupSize * j + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + local half = lshift(1, ba - 1) - 1 + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, getBits(ba) - half) + end + else + local mod = lshift(2, ba - 17) + 1 + local code = getBits(mod + 2 - rshift(mod, 3)) + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, code % mod - mod // 2) + code //= mod + end + end + end + dst += choff + choff = 18 - choff + end + end + return groupSize * 4 +end + +@native local function l12ApplyScf(scfOff: number) + local sb, tb = stereoBands, totalBands + bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) + for i = 0, tb - 1 do + local d = i * 72 + local s0 = rf(L12SCF, (scfOff + i * 6) * 4) + local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4) + for k = 0, 11 do + local p = d + k * 4 + wf(GRBUF, p, rf(GRBUF, p) * s0) + wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1) + end + end +end + +---------------------------------------------------------------------------------------------------------------- +-- API + +local Core = {} + +Core.MAX_FRAME = MAX_FRAME + +type State = { + overlap: buffer, + qmf: buffer, + reserv: buffer, + reservLen: number, + needReset: boolean, +} + +@native function Core.newState(): State + return { + overlap = bcreate(2 * 9 * 32 * 4), + qmf = bcreate(15 * 2 * 32 * 4), + reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8), + reservLen = 0, + needReset = false, + } +end + +-- memset(dec, 0): what minimp3 does whenever it has to re-sync +@native function Core.reset(st: State) + bfill(st.overlap, 0, 0) + bfill(st.qmf, 0, 0) + st.reservLen = 0 + st.needReset = false +end + +Core.lastChannels = 0 + +-- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) +@native function Core.upmix(pcm: buffer, n: number) + if buffer.len(pcm) < n * 8 then + return + end + for i = n - 1, 0, -1 do + local v = rf(pcm, i * 4) + wf(pcm, i * 8, v) + wf(pcm, i * 8 + 4, v) + end +end + +-- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm +-- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an +-- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. +@native function Core.decodeFrame(st: State, b: buffer, off: number, size: number, pcm: buffer): number + if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then + st.needReset = true + return 0 + end + if st.needReset then + Core.reset(st) + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + OVL, QMF, PCM = st.overlap, st.qmf, pcm + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + local nch = if band(h3, 0xC0) == 0xC0 then 1 else 2 + Core.lastChannels = nch + local layer = 4 - band(rshift(h1, 1), 3) + local spf = if band(h1, 6) == 6 then 384 elseif band(h1, 14) == 2 then 576 else 1152 + if buffer.len(pcm) < spf * nch * 4 then + return 0 + end + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) -- CRC + end + if layer == 3 then + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + st.needReset = true + return 0 + end + -- L3_restore_reservoir + local frameBytes = (bsLimit - bsPos) // 8 + local reserv = st.reservLen + local have = min(reserv, mdb) + if have > 0 then + bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have) + end + bcopy(MAIN, have, FRAME, bsPos // 8, frameBytes) + bfill(MAIN, have + frameBytes, 0, 8) + local success = reserv >= mdb + bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8 + if success then + local ngr = if band(h1, 8) ~= 0 then 2 else 1 + local p = 0 + for igr = 0, ngr - 1 do + bfill(GRBUF, 0, 0) + l3Decode(h1, h2, h3, igr * nch, nch) + synthGranule(18, nch, p) + p += 576 * nch + end + end + -- L3_save_reservoir + local pos = (bsPos + 7) // 8 + local remains = bsLimit // 8 - pos + if remains > MAX_BITRESERVOIR_BYTES then + pos += remains - MAX_BITRESERVOIR_BYTES + remains = MAX_BITRESERVOIR_BYTES + end + if remains > 0 and pos >= 0 then + bcopy(st.reserv, 0, MAIN, pos, remains) + end + st.reservLen = max(0, remains) + bsBuf = FRAME + return if success then spf else 0 + end + -- layers I / II + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + bfill(GRBUF, 0, 0) + local i = 0 + local p = 0 + local group = bor(layer, 1) + for igr = 0, 2 do + i += l12Dequantize(i, group) + if i == 12 then + i = 0 + l12ApplyScf(igr) + synthGranule(12, nch, p) + bfill(GRBUF, 0, 0) + p += 384 * nch + end + if bsPos > bsLimit then + st.needReset = true + return 0 + end + end + return spf +end + +-- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its +-- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. +@native function Core.probeL3(b: buffer, off: number, size: number): (number, number, number) + local n = min(size, 64) + if size < 4 or off + n > buffer.len(b) then + return -1, 0, 0 + end + bcopy(FRAME, 0, b, off, n) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + return -1, 0, 0 + end + local ngr = (if band(h3, 0xC0) == 0xC0 then 1 else 2) * (if band(h1, 8) ~= 0 then 2 else 1) + local sum = 0 + for gr = 0, ngr - 1 do + sum += GR_P23[gr] + end + return mdb, sum, (bsLimit - bsPos) // 8 +end + +-- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +@native function Core.probeL12(b: buffer, off: number, size: number): boolean + if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then + return false + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local layer = 4 - band(rshift(h1, 1), 3) + local kbps = 2 * HALFRATE[(if band(h1, 8) ~= 0 then 45 else 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band + local group = bor(layer, 1) + local bits = 0 + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + bits += ba * group + else + local mod = lshift(2, ba - 17) + 1 + bits += mod + 2 - rshift(mod, 3) + end + end + end + return bsPos + 12 * bits <= bsLimit +end + +-- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame +-- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) +@native function Core.vbrTag(b: buffer, off: number, size: number): (number, number, number, number) + if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then + return 0, 0, 0, 0 + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + if readSideInfo(h1, h2, h3) < 0 then + return 0, 0, 0, 0 + end + local t = bsPos // 8 + if t > size or size - t < 8 then + return 0, 0, 0, 0 + end + local tag = buffer.readstring(FRAME, t, 4) + if tag ~= "Xing" and tag ~= "Info" then + return 0, 0, 0, 0 + end + local flags = ru8(FRAME, t + 7) + if band(flags, 1) == 0 then + return -1, 0, 0, 0 + end + t += 8 + if size - t < 4 then + return 0, 0, 0, 0 + end + local frames = bswap(ru32(FRAME, t)) + t += 4 + if band(flags, 2) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if band(flags, 4) ~= 0 then + if size - t < 100 then + return 0, 0, 0, 0 + end + t += 100 + end + if band(flags, 8) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t += 4 + end + if size - t < 1 then + return 0, 0, 0, 0 + end + local delay, padding = 0, 0 + if ru8(FRAME, t) ~= 0 then + if size - t <= 35 then + return 0, 0, 0, 0 + end + t += 21 + local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2) + delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529 + padding = bor(lshift(band(t1, 15), 8), t2) - 529 + end + return 1, frames, delay, padding +end + +return Core +end +__FILES["codecs/audio/Mpa/EncTables"] = function() + +-- 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 +-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E +end +__FILES["codecs/audio/Mpa/Encode2"] = @native function() + + + +-- 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 (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 Bits = __include("core/Bits") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +@native local function levels(ba: number): number + if ba >= 17 then + return if ba == 17 then 3 elseif ba == 18 then 5 else 9 + end + return POW[ba + 1] - 1 +end +-- bits for the 3 samples of one granule +@native local function tripleBits(ba: number): number + if ba >= 17 then + return if ba == 17 then 5 elseif ba == 18 then 7 else 10 + end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR: { [number]: number } = {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +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 = Bits.RawWriter +local put = Bits.msbPut + +type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { bitrate: number, mode: string, prefix: buffer? } + +-- encode(src, opts) -> buffer | nil, message +@native function Encode2.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = if opts.mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + -- the allocation table (the decoder's choice from the header) + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = if nch == 2 then kbps // 2 else kbps + alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, if srIndex == 2 then 12 else 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai += 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps: { { { number } } } = {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part + local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local slot = 144000 * kbps + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + pcm[1][got + i + 1] = if inCh > 1 then (l + r) * 0.5 else l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx -= 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx += 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + -- the frame size and the bits left for scalefactors and samples + local frameBytes = slot // rate + rest += slot % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail -= bandBits[b] * nch + end + -- greedy allocation: the band with the most noise gets its next step while it fits + local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = if st == 0 then 0 else s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (if st == 0 then 0 else SNR[cur]) + local cost = 12 * tripleBits(nxt) - (if st == 0 then 0 else 12 * tripleBits(cur)) + if st == 0 then + cost += 2 + 18 -- scfsi + three scalefactors + end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end + bal[bestC][bestB] += 1 + avail -= bestCost + end + -- write the frame + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if nch == 1 then 3 else 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + -- bit allocation + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, if st == 0 then 0 else steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = gr // 4 + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + @native local function quant(x: number): number + 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 = 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)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 +end +__FILES["codecs/audio/Mpa/Encode3"] = @native function() + + + +-- 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 (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 (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. +local Bits = __include("core/Bits") +local E = __include("codecs/audio/Mpa/EncTables") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ Huffman codes +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE: { [number]: { number } } = {} +local LEN: { [number]: { number } } = {} +local XLEN: { [number]: number } = {} + +@native local function walk(tree: { number }, codes: { number }, lens: { number }, p: number, code: number, len: number) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q += bit32.rshift(tree[q + 1], 8) + end + q += bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q += bit32.band(tree[q + 1], 0xFF) + end + q += bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = if t >= 16 and t <= 23 then 16 elseif t >= 24 and t <= 31 then 24 else t + local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = (idx - 1) // 16 + if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +-- the tables that hold values up to m (m <= 15), smallest first +local SMALL: { [number]: { number } } = {} +for m = 0, 15 do + local list = {} + for _, t in { 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 } do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end + +-- ------------------------------------------------------------------------------------------------ bit writer +type W = Bits.RawWriter + +local put = Bits.msbPut +Encode3.put = put + +-- ------------------------------------------------------------------------------------------------ constants +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 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 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +-- alias reduction coefficients +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end + +-- ------------------------------------------------------------------------------------------------ Huffman planning +type Plan = { + bits: number, + bigValues: number, -- pairs + count1: number, -- quadruples + tables: { number }, -- 3 region tables + region0: number, + region1: number, + c1table: number, -- 0 = A (table 32), 1 = B (33) + addr1: number, -- coefficient index where region 1 starts + addr2: number, +} + +@native local function newPlan(): Plan + return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) +@native local function pairBits(ix: { number }, a: number, b: number, t: number): number + if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra += lb + end + if y > 14 then + y = 15 + extra += lb + end + bits += lens[x * 16 + y + 1] + extra + if x ~= 0 then + bits += 1 + end + if y ~= 0 then + bits += 1 + end + end + return bits +end + +-- the best table for the pairs ix[a .. b): table, bits +@native local function chooseTable(ix: { number }, a: number, b: number): (number, number) + if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in SMALL[m] do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in { 16, 24 } do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) +@native local function plan(ix: { number }, bounds: { number }, p: Plan) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i -= 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i -= 4 + c1 += 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = bv // 2, c1 + -- count1 bits, table A vs B + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba += lensA[v * 8 + w * 4 + x * 2 + y + 1] + s + bb += 4 + s + end + p.c1table = if bb < ba then 1 else 0 + local bits = if bb < ba then bb else ba + -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j += 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +@native local function writePairs(w: W, ix: { number }, sign: { boolean }, a: number, b: number, t: number) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = if x > 14 then 15 else x, if y > 14 then 15 else y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, if sign[i + 1] then 1 else 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, if sign[i + 2] then 1 else 0, 1) + end + end +end + +@native local function writeHuffman(w: W, ix: { number }, sign: { boolean }, p: Plan) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, if sign[o + k] then 1 else 0, 1) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ quantization +type Unit = { + xr: { number }, -- 576 MDCT coefficients + xa: { number }, -- |xr|^(3/4) + ix: { number }, + sign: { boolean }, + plan: Plan, + gain: number, +} + +@native local function newUnit(): Unit + return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +@native local function quantize(u: Unit, g: number): boolean + local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +-- the finest global gain whose Huffman size fits budget bits +@native local function rateLoop(u: Unit, budget: number, bounds: { number }) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + -- the gain where the largest value quantizes to 0: an upper bound + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = (lo + hi) // 2 + if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end + +-- ------------------------------------------------------------------------------------------------ encoder +type Source = { + sampleRate: number, + channels: number, + frames: number, + read: (self: any, n: number, out: buffer?) -> (buffer, number), + err: any, +} +type Options = { + bitrate: number, -- kbps, valid for the version + mode: string, -- "stereo" | "joint" | "mono" + prefix: buffer?, -- bytes written before the first frame (an ID3v2 tag) +} + +-- encode(src, opts) -> buffer | nil, message +@native function Encode3.encode(src: Source, opts: Options): (buffer?, string?) + local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = if mpeg1 then 2 else 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = if mode == "mono" then 1 else 2 + local kbps = opts.bitrate + local list = if mpeg1 then BITRATES_V1 else BITRATES_V2 + local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = if mpeg1 then (if nch == 1 then 17 else 32) else (if nch == 1 then 9 else 17) + local slotNum = (if mpeg1 then 144000 else 72000) * kbps -- frame bytes * rate + -- scalefactor band starts (long blocks) + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc += T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w: W = { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix :: buffer + local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp: buffer? = nil + local pending: buffer? = nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending :: buffer + for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = if inCh > 1 then buffer.readf32(pb, base + 4) else l + if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got += take + pendN -= take + pendOff += take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + -- analysis + MDCT per granule and channel + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc += MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + -- the frame size + local frameBytes = slotNum // rate + rest += slotNum % rate + local padding = 0 + if rest >= rate then + rest -= rate + padding = 1 + frameBytes += 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, left // (nUnits - done)) + local u = units[g][c] + rateLoop(u, budget, bounds) + left -= u.plan.bits + done += 1 + end + end + -- header + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, if mode == "mono" then 3 elseif mode == "joint" then 1 else 0, 2) + put(w, if mode == "joint" then 2 else 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + -- side info + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, if nch == 1 then 5 else 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, if nch == 1 then 1 else 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, if mpeg1 then 4 else 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + -- main data + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos += 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 +end +__FILES["codecs/audio/Mpa/Header"] = @native function() + + + +-- 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 = __include("codecs/audio/Mpa/Tables") + +local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +local ru8 = buffer.readu8 + +local HALFRATE = T.halfrate +local HZ = { [0] = 44100, 48000, 32000 } + +local H = {} + +H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 +H.MAX_FRAME_SYNC_MATCHES = 10 + +-- hdr_valid +@native function H.valid(b: buffer, o: number): boolean + if ru8(b, o) ~= 0xFF then + return false + end + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2) + and band(rshift(h1, 1), 3) ~= 0 + and rshift(h2, 4) ~= 15 + and band(rshift(h2, 2), 3) ~= 3 +end +local valid = H.valid + +-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +@native function H.compare(b: buffer, o1: number, o2: number): boolean + if not valid(b, o2) then + return false + end + local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2) + local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2) + return band(bxor(a1, c1), 0xFE) == 0 + and band(bxor(a2, c2), 0x0C) == 0 + and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0) +end +local compare = H.compare + +-- from the header bytes h1 = byte 1, h2 = byte 2 +@native function H.bitrateKbps(h1: number, h2: number): number + local mpeg1 = if band(h1, 8) ~= 0 then 1 else 0 + local layer = band(rshift(h1, 1), 3) + return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] +end +local bitrateKbps = H.bitrateKbps + +@native function H.sampleRate(h1: number, h2: number): number + local hz = HZ[band(rshift(h2, 2), 3)] + if band(h1, 8) == 0 then + hz //= 2 + end + if band(h1, 0x10) == 0 then + hz //= 2 + end + return hz +end +local sampleRate = H.sampleRate + +@native function H.frameSamples(h1: number): number + if band(h1, 6) == 6 then + return 384 + elseif band(h1, 14) == 2 then + return 576 + end + return 1152 +end +local frameSamples = H.frameSamples + +-- hdr_frame_bytes (without padding); free format = 0 -> freeSize +@native function H.frameBytes(b: buffer, o: number, freeSize: number): number + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + local hz = sampleRate(h1, h2) + local fb = frameSamples(h1) * bitrateKbps(h1, h2) * 125 // hz + if band(h1, 6) == 6 then + fb = band(fb, 0xFFFFFFFC) + end + return if fb ~= 0 then fb else freeSize +end +local frameBytes = H.frameBytes + +@native function H.padding(b: buffer, o: number): number + if band(ru8(b, o + 2), 2) == 0 then + return 0 + end + return if band(ru8(b, o + 1), 6) == 6 then 4 else 1 +end +local padding = H.padding + +-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal +@native local function matchFrame(b: buffer, o: number, n: number, fb: number): boolean + local i = 0 + for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do + i += frameBytes(b, o + i, fb) + padding(b, o + i) + if i + 4 > n then + return nmatch > 0 + end + if not compare(b, o, o + i) then + return false + end + end + return true +end + +-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +@native function H.findFrame(b: buffer, base: number, n: number, ffb: number): (number, number, number) + for i = 0, n - 5 do + local o = base + i + if valid(b, o) then + local fb = frameBytes(b, o, ffb) + local fap = fb + padding(b, o) + local k = 4 + while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do + if compare(b, o, o + k) then + local f = k - padding(b, o) + local nextfb = f + padding(b, o + k) + if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then + fap = k + fb = f + ffb = f + end + end + k += 1 + end + if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then + return i, fap, ffb + end + ffb = 0 + end + end + return n, 0, ffb +end + +return H +end +__FILES["codecs/audio/Mpa/Tables"] = function() + +-- 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, + 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, + 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24, + 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, + 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, +} +T.g_bitalloc_code_tab = { [0] = 0, + 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +T.g_scf_long = { [0] = 6, + 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, + 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, + 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, + 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6, + 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, + 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, + 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, + 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, +} +T.g_scf_short = { [0] = 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, + 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, + 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, + 42, 42, 42, 12, 12, 12, 0, +} +T.g_scf_mixed = { [0] = 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, + 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, + 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, + 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4, + 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, + 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, + 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, + 42, 42, 12, 12, 12, 0, 0, +} +T.g_expfrac = { [0] = 9.31322575e-10, + 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, +} +T.g_scf_partitions = { [0] = 6, + 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, + 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, + 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12, + 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, +} +T.g_scfc_decode = { [0] = 0, + 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, +} +T.g_mod = { [0] = 5, + 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, +} +T.g_preamp = { [0] = 1, + 1, 1, 1, 2, 2, 3, 3, 3, 2, +} +T.g_pow43 = { [0] = 0, + -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000, + 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, + 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292, + 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, + 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, + 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578, +} +T.tabs = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, + 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, + 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, + 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, + 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784, + 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291, + 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076, + 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, + 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, + 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, + 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, + 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533, + 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041, + 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, + 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, + -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, + 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, + 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351, + -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136, + 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534, + 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252, + -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, + 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, + 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, + 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726, + -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, + -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322, + 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495, + 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, + 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, + 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, + 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, + 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, + 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, + 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412, + 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342, + 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, + 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, + 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, + -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025, + 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, + -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, + 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, + 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475, + 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480, + 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, + 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, + 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, + 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081, + -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898, + 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368, + 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, + 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, + -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, + 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734, + -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686, + 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, + -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, + 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223, + 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963, + 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844, + 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, + 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, + 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, + 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392, + 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, + 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, + 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, + 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024, + 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623, + 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974, + 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, + -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, + 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, + 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402, + 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, + 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, + 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, + 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384, + 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849, + -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, + 290, 288, 258, +} +T.tab32 = { [0] = 130, + 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, + 61, 173, 205, +} +T.tab33 = { [0] = 252, + 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, +} +T.tabindex = { [0] = 0, + 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842, + 1842, 1842, 1842, 1842, 1842, 1842, 1842, +} +T.g_linbits = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, + 5, 6, 7, 8, 9, 11, 13, +} +T.g_pan = { [0] = 0, + 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0, +} +T.g_aa = { [0] = 0.85749293, + 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, +} +T.g_twid9 = { [0] = 0.73727734, + 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, +} +T.g_twid3 = { [0] = 0.79335334, + 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, +} +T.g_mdct_window = { [0] = 0.99904822, + 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486, + 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, +} +T.g_sec = { [0] = 10.19000816, + 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, +} +T.g_win = { [0] = -1, + 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952, + 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, + 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, + 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, + 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414, + 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2, + 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, + 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, + 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, + 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290, +} +return T +end +__FILES["codecs/audio/Musepack"] = function() + +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped +-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the +-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec +-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are +-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed +-- instead), chapters. +-- +-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) +-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the +-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Musepack/Decode") + +local Musepack = {} + +local RATES = { 44100, 48000, 37800, 32000 } +local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD +local readu8 = buffer.readu8 + +type Stream = { + version: number, + sampleRate: number, + channels: number, + frames: number, -- output sample frames (gapless) + maxBand: number, + ms: boolean, + profile: number, -- SV7: the profile index (7 telephone .. 13 braindead); SV8: the quality (0 .. 15.875) + encoder: number, -- encoder version (SV7: one byte; SV8: major * 2^24 + minor * 2^16 + build * 2^8) + gapless: boolean, + pns: boolean?, + gain: { titleGain: number, titlePeak: number, albumGain: number, albumPeak: number }?, + blockFrames: number, -- frames per packet (SV7: 1; SV8: 2^block_pwr) + bytes: number, -- the stream's size in bytes (for the bitrate) + -- the codecs/audio/Stream spec + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number }, + reset: () -> (), + skip: number, + stop: number, + preroll: number, +} + +-- ------------------------------------------------------------------------------------------------ SV7 +-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy +local function swapped(buf: buffer, p: number, limit: number): buffer + local n = limit - p + local words = (n + 3) // 4 + local out = buffer.create(words * 4 + PAD) + buffer.copy(out, 0, buf, p, n) + for i = 0, words - 1 do + buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) + end + return out +end + +local function sv7(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + if limit - start < 32 then + return nil, Err.new(Err.TRUNCATED, "SV7 header", start) + end + local ver = bit32.band(readu8(buf, start + 3), 15) + if ver ~= 7 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) + end + local s = swapped(buf, start + 4, limit) + local totalBits = (limit - start - 4) * 8 + local at = Decode.bitsAt + local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) + local ms = at(s, 33, 1) == 1 + local maxBand = at(s, 34, 6) + local profile = at(s, 40, 4) + local rate = RATES[at(s, 46, 2) + 1] + local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) + local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) + local gapless = at(s, 128, 1) == 1 + local last = at(s, 129, 11) + local encoder = at(s, 160, 8) + if maxBand == 0 or maxBand >= 32 then + return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) + end + if last == 0 then + last = FRAME + elseif last > FRAME then + return nil, Err.new(Err.CORRUPT, "bad last frame length", start) + end + if frames == 0 then + return nil, Err.new(Err.CORRUPT, "no frames", start) + end + if frames > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) + end + local samples = frames * FRAME - (if gapless then FRAME - last else DELAY) + -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) + local offs: { number }, sizes: { number } = {}, {} + local pos = 168 + for i = 1, frames do + if pos + 20 > totalBits then + break + end + local size = at(s, pos, 20) + local stop = pos + 20 + size + (if i == frames then 11 else 0) + if stop > totalBits then + break -- a truncated last frame + end + offs[i], sizes[i] = pos + 20, size + pos = stop + end + local have = #offs + if have == 0 then + return nil, Err.new(Err.TRUNCATED, "no complete frame", start) + end + -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence + local need = math.min((samples + DELAY + FRAME - 1) // FRAME, have + 1) + local stopAt = math.min(samples + DELAY, have * FRAME + (if have < frames then 0 else FRAME)) + local st = Decode.state(7, maxBand, ms, 2) + local pcm = table.create(FRAME * 2, 0) + local prev = 0 + local out: Stream = { + version = 7, + sampleRate = rate, + channels = 2, + frames = math.max(0, stopAt - DELAY), + maxBand = maxBand, + ms = ms, + profile = profile, + encoder = encoder, + gapless = gapless, + gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, + blockFrames = 1, + bytes = limit - start, + count = need, + start = function(i: number): number + return (i - 1) * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + if i ~= prev + 1 then + Decode.reset(st, if i == 1 then 0 else 0x01010101) + end + prev = i + local o: number? = offs[i] + if o == nil then + Decode.frame(st, s, -1, 0, false, pcm, 1) + return FRAME, nil + end + local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) + if not e then + return nil, Err.from(msg, start + 4 + o // 8) + end + if e ~= o + sizes[i] then + return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + o // 8) + end + return FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + prev = -1 + end, + skip = DELAY, + stop = stopAt, + preroll = 32, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +-- a packet size: 7 bits per byte, most significant first, bit 7 = more +local function varint(buf: buffer, p: number, limit: number): (number, number) + local v = 0 + for k = 0, 7 do + if p + k >= limit then + return -1, p + end + local b = readu8(buf, p + k) + v = v * 128 + bit32.band(b, 127) + if b < 128 then + return v, p + k + 1 + end + end + return -1, p +end + +local function sv8(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local p = start + 4 + local sh: { [string]: any }? = nil + local gain, pns, profile, encoder = nil, nil, 0, 0 + local apOff: { number }, apSize: { number } = {}, {} + while p + 2 < limit do + local k1, k2 = readu8(buf, p), readu8(buf, p + 1) + if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then + return nil, Err.new(Err.CORRUPT, "bad packet key", p) + end + local key = buffer.readstring(buf, p, 2) + local size, body = varint(buf, p + 2, limit) + if size < 0 or size < body - p then + return nil, Err.new(Err.CORRUPT, "bad packet size", p) + end + local stop = p + size + if stop > limit then + if key == "AP" then + break -- a truncated last packet + end + return nil, Err.new(Err.TRUNCATED, key .. " packet", p) + end + if key == "SH" then + if stop - body < 6 then + return nil, Err.new(Err.CORRUPT, "short stream header", p) + end + local crc = buffer.readu32(buf, body) + crc = bit32.byteswap(crc) + if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then + return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) + end + if readu8(buf, body + 4) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) + end + local samples, q = varint(buf, body + 5, stop) + local silence, q2 = varint(buf, q, stop) + if samples < 0 or silence < 0 or q2 + 2 > stop then + return nil, Err.new(Err.CORRUPT, "bad stream header", p) + end + local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) + sh = { + samples = samples, + silence = silence, + rate = RATES[bit32.rshift(b0, 5) + 1], + maxBand = bit32.band(b0, 31) + 1, + channels = bit32.rshift(b1, 4) + 1, + ms = bit32.band(b1, 8) ~= 0, + blockPwr = bit32.band(b1, 7) * 2, + } + elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then + local function u16(o: number): number + return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) + end + gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } + elseif key == "EI" and stop - body >= 4 then + local b = readu8(buf, body) + profile = bit32.rshift(b, 1) / 8 + pns = bit32.band(b, 1) == 1 + encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 + elseif key == "AP" then + table.insert(apOff, body) + table.insert(apSize, stop - body) + elseif key == "SE" then + break + end + p = stop + end + if not sh then + return nil, Err.new(Err.CORRUPT, "no stream header", start) + end + local h = sh :: { [string]: any } + local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels + if maxBand >= 32 or channels > 2 or silence > samples then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) + end + if samples > 2 ^ 34 then + return nil, Err.new(Err.LIMIT, "too many samples", start) + end + if #apOff == 0 then + return nil, Err.new(Err.CORRUPT, "no audio packet", start) + end + local per = 2 ^ h.blockPwr + if per * FRAME * channels > 2 ^ 22 then + return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) + end + local needFrames = (samples + DELAY + FRAME - 1) // FRAME + local count = math.min(#apOff, (needFrames + per - 1) // per) + local stopAt = math.min(samples + DELAY, count * per * FRAME) + local st = Decode.state(8, maxBand, h.ms, channels) + local pcm = table.create(per * FRAME * channels, 0) + local scratch = buffer.create(0) + local out: Stream = { + version = 8, + sampleRate = h.rate, + channels = channels, + frames = math.max(0, stopAt - DELAY - silence), + maxBand = maxBand, + ms = h.ms, + profile = profile, + encoder = encoder, + gapless = true, + pns = pns, + gain = gain, + blockFrames = per, + bytes = limit - start, + count = count, + start = function(i: number): number + return (i - 1) * per * FRAME + end, + decode = function(i: number): (number?, Err.Err?) + local o: number, size: number = apOff[i], apSize[i] + if buffer.len(scratch) < size + PAD then + scratch = buffer.create(size + PAD) + end + buffer.copy(scratch, 0, buf, o, size) + local nf = math.min(per, needFrames - (i - 1) * per) + local pos = 0 + for f = 1, nf do + local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) + if not e then + return nil, Err.from(msg, o) + end + pos = e + end + if nf == per and size * 8 - pos > 7 then + return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) + end + return nf * FRAME, nil + end, + pcm = function(): { number } + return pcm + end, + reset = function() + Decode.reset(st, 0) + end, + skip = DELAY + silence, + stop = stopAt, + preroll = 1, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) +function Musepack.magic(buf: buffer, p: number, limit: number): number + if p + 4 > limit then + return 0 + end + local m = buffer.readstring(buf, p, 4) + if m == "MPCK" then + return 8 + end + if string.sub(m, 1, 3) == "MP+" then + return 7 + end + return 0 +end + +-- open(buf, start, limit) -> Stream | nil, Err +function Musepack.open(buf: buffer, start: number, limit: number): (Stream?, Err.Err?) + local v = Musepack.magic(buf, start, limit) + if v == 8 then + return sv8(buf, start, limit) + elseif v == 7 then + return sv7(buf, start, limit) + end + return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) +end + +return Musepack +end +__FILES["codecs/audio/Musepack/Decode"] = @native function() + + + +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band +-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), +-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c, +-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over +-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the +-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +local T = __include("codecs/audio/Musepack/Tables") + +local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = + buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor +local abs = math.abs + +local Decode = {} +Decode.PAD = 8192 +Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY +Decode.FRAME = 1152 + +-- ------------------------------------------------------------------------------------------------ tables +local L = T.lut +local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) +local Q7: { { T.Lut } } = { + { L(T.HuffQ1_0), L(T.HuffQ1_1) }, + { L(T.HuffQ2_0), L(T.HuffQ2_1) }, + { L(T.HuffQ3_0), L(T.HuffQ3_1) }, + { L(T.HuffQ4_0), L(T.HuffQ4_1) }, + { L(T.HuffQ5_0), L(T.HuffQ5_1) }, + { L(T.HuffQ6_0), L(T.HuffQ6_1) }, + { L(T.HuffQ7_0), L(T.HuffQ7_1) }, +} +local BANDS8 = L(T.H_Bands, T.S_Bands) +local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } +local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } +local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } +local Q1_8 = L(T.H_Q1, T.S_Q1) +local Q9UP = L(T.H_Q9up, T.S_Q9up) +-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] +local Q8: { [number]: { T.Lut } } = { + [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, + [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, + [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, + [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, + [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, +} +local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } +local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } +local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT +local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST + +-- the f32 rounding of the C tables (libmpcdec decodes in single precision) +local F32 = buffer.create(4) +@native local function f32(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +for i, v in CC do + CC[i] = f32(v) +end + +-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 +-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) +local SCF = table.create(256, 0) +do + local f1 = 1 / 32768 + local f2 = f1 + SCF[2] = f32(f1) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + for n = 1, 128 do + SCF[band(1 + n, 255) + 1] = f32(f1) + SCF[band(1 - n, 255) + 1] = f32(f2) + f1 *= 0.83298066476582673961 + f2 *= 1 / 0.83298066476582673961 + end +end + +-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major +local DW = table.create(512, 0) +for i, v in T.DI do + DW[i] = f32(v / 65536) +end + +-- ------------------------------------------------------------------------------------------------ bit reader +local B: buffer = buffer.create(0) +local P = 0 -- bit position + +@native local function bits(n: number): number + if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P += n + return v +end + +@native local function peek16(): number + local w = bswap(readu32(B, rshift(P, 3))) + return extract(w, 16 - band(P, 7), 16) +end + +-- a table-driven Huffman symbol (plain or canonical) +@native local function huff(t: T.Lut): number + local code = peek16() + local k = rshift(code, 8) + 1 + local n = t.len[k] + if n > 0 then + P += n + return t.val[k] + end + local j = t.val[k] + local codes = t.codes + while code < codes[j] do + j += 1 + end + n = t.lens[j] + P += n + local sym = t.sym + if sym then + return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 + end + return t.vals[j] +end + +-- mpc_bits_log_dec: 0 .. max +@native local function logDec(max: number): number + if max <= 0 then + return 0 + end + local v = 0 + local len, lost = LOG2[max], LOG2_LOST[max] + if len > 1 then + v = bits(len - 1) + end + if v >= lost then + v = v * 2 + bits(1) - lost + end + return v +end + +-- mpc_bits_enum_dec: an n-bit word with k bits set +@native local function enumDec(k: number, n: number): number + local out = 0 + local code = bits(CNK_LEN[k][n] - 1) + local lost = CNK_LOST[k][n] + if code >= lost then + code = code * 2 + bits(1) - lost + end + repeat + n -= 1 + local c = CNK[k][n + 1] + if code >= c then + out = bor(out, lshift(1, n)) + code -= c + k -= 1 + end + until k <= 0 or n <= 0 + return out +end + +-- mpc_random_int: two polynomial counters, XORed +local PARITY = table.create(256, 0) +for i = 0, 255 do + local p, v = 0, i + while v > 0 do + p = bxor(p, band(v, 1)) + v = rshift(v, 1) + end + PARITY[i + 1] = p +end + +-- ------------------------------------------------------------------------------------------------ synthesis +-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing +-- through Byeong Gi Lee's fast DCT) +@native local function newV(Y: { number }, y: number, V: { number }, o: number) + local A00 = Y[y] + Y[y + 31] + local A01 = Y[y + 1] + Y[y + 30] + local A02 = Y[y + 2] + Y[y + 29] + local A03 = Y[y + 3] + Y[y + 28] + local A04 = Y[y + 4] + Y[y + 27] + local A05 = Y[y + 5] + Y[y + 26] + local A06 = Y[y + 6] + Y[y + 25] + local A07 = Y[y + 7] + Y[y + 24] + local A08 = Y[y + 8] + Y[y + 23] + local A09 = Y[y + 9] + Y[y + 22] + local A10 = Y[y + 10] + Y[y + 21] + local A11 = Y[y + 11] + Y[y + 20] + local A12 = Y[y + 12] + Y[y + 19] + local A13 = Y[y + 13] + Y[y + 18] + local A14 = Y[y + 14] + Y[y + 17] + local A15 = Y[y + 15] + Y[y + 16] + local B00 = A00 + A15 + local B01 = A01 + A14 + local B02 = A02 + A13 + local B03 = A03 + A12 + local B04 = A04 + A11 + local B05 = A05 + A10 + local B06 = A06 + A09 + local B07 = A07 + A08 + local B08 = (A00 - A15) * 0.5024192929 + local B09 = (A01 - A14) * 0.5224986076 + local B10 = (A02 - A13) * 0.5669440627 + local B11 = (A03 - A12) * 0.6468217969 + local B12 = (A04 - A11) * 0.7881546021 + local B13 = (A05 - A10) * 1.0606776476 + local B14 = (A06 - A09) * 1.7224471569 + local B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = B00 + B01 + A01 = (B00 - B01) * 0.7071067691 + A02 = B02 + B03 + A03 = (B02 - B03) * 0.7071067691 + A04 = B04 + B05 + A05 = (B04 - B05) * 0.7071067691 + A06 = B06 + B07 + A07 = (B06 - B07) * 0.7071067691 + A08 = B08 + B09 + A09 = (B08 - B09) * 0.7071067691 + A10 = B10 + B11 + A11 = (B10 - B11) * 0.7071067691 + A12 = B12 + B13 + A13 = (B12 - B13) * 0.7071067691 + A14 = B14 + B15 + A15 = (B14 - B15) * 0.7071067691 + V[o + 48] = -A00 + V[o] = A01 + V[o + 8] = A03 + V[o + 40] = -A02 - A03 + V[o + 12] = A07 + local t = A05 + A07 + V[o + 4] = t + V[o + 36] = -(t + A06) + V[o + 44] = -A04 - A06 - A07 + V[o + 14] = A15 + t = A11 + A15 + V[o + 10] = t + V[o + 6] = t + A13 + t = A09 + A13 + A15 + V[o + 2] = t + t = -t - A14 + V[o + 34] = t + V[o + 38] = t + A09 - A10 - A11 + t = -(A12 + A14 + A15) + V[o + 46] = t - A08 + V[o + 42] = t - A10 - A11 + A00 = (Y[y] - Y[y + 31]) * 0.5006030202 + A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 + A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 + A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 + A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 + A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 + A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 + A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 + A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 + A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 + A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 + A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 + A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 + A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 + A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 + A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 + B00 = A00 + A15 + B01 = A01 + A14 + B02 = A02 + A13 + B03 = A03 + A12 + B04 = A04 + A11 + B05 = A05 + A10 + B06 = A06 + A09 + B07 = A07 + A08 + B08 = (A00 - A15) * 0.5024192929 + B09 = (A01 - A14) * 0.5224986076 + B10 = (A02 - A13) * 0.5669440627 + B11 = (A03 - A12) * 0.6468217969 + B12 = (A04 - A11) * 0.7881546021 + B13 = (A05 - A10) * 1.0606776476 + B14 = (A06 - A09) * 1.7224471569 + B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = (B00 + B01) + A01 = (B00 - B01) * 0.7071067691 + A02 = (B02 + B03) + A03 = (B02 - B03) * 0.7071067691 + A04 = (B04 + B05) + A05 = (B04 - B05) * 0.7071067691 + A06 = (B06 + B07) + A07 = (B06 - B07) * 0.7071067691 + A08 = (B08 + B09) + A09 = (B08 - B09) * 0.7071067691 + A10 = (B10 + B11) + A11 = (B10 - B11) * 0.7071067691 + A12 = (B12 + B13) + A13 = (B12 - B13) * 0.7071067691 + A14 = (B14 + B15) + A15 = (B14 - B15) * 0.7071067691 + V[o + 15] = A15 + t = A07 + A15 + V[o + 13] = t + t += A11 + V[o + 11] = t + V[o + 5] = t + A05 + A13 + t = A03 + A11 + A15 + V[o + 9] = t + V[o + 7] = t + A13 + t = A01 + A09 + A13 + A15 + V[o + 1] = t + V[o + 33] = -t - A14 + t = A05 + A07 + A09 + A13 + A15 + V[o + 3] = t + V[o + 35] = -t - A06 - A14 + t = -(A10 + A11 + A13 + A14 + A15) + V[o + 37] = t - A05 - A06 - A07 + V[o + 39] = t - A02 - A03 + t += A13 - A12 + V[o + 41] = t - A02 - A03 + V[o + 43] = t - A04 - A06 - A07 + t = -(A08 + A12 + A14 + A15) + V[o + 47] = t - A00 + V[o + 45] = t - A04 - A06 - A07 + for i = 0, 15 do + V[o + 32 - i] = -V[o + i] + end + for i = 33, 47 do + V[o + 96 - i] = V[o + i] + end +end +-- ------------------------------------------------------------------------------------------------ state +type State = { + version: number, -- 7 | 8 + maxBand: number, -- the highest band index (0 .. 31) + ms: boolean, + channels: number, + resL: { number }, -- [band + 1] + resR: { number }, + scfL: { number }, -- [band * 3 + m + 1] + scfR: { number }, + scfiL: { number }, + scfiR: { number }, + dscfL: { boolean }, + dscfR: { boolean }, + msf: { boolean }, + qL: { number }, -- [band * 36 + k + 1] + qR: { number }, + yL: { number }, -- [n * 32 + band + 1], n = 0 .. 35 + yR: { number }, + vL: { number }, -- synthesis history, 2304 + 960 + vR: { number }, + r1: number, + r2: number, + lastMaxBand: number, +} + +@native function Decode.state(version: number, maxBand: number, ms: boolean, channels: number): State + local st: State = { + version = version, + maxBand = maxBand, + ms = ms, + channels = channels, + resL = table.create(33, 0), + resR = table.create(33, 0), + scfL = table.create(99, 0), + scfR = table.create(99, 0), + scfiL = table.create(33, 0), + scfiR = table.create(33, 0), + dscfL = table.create(33, false), + dscfR = table.create(33, false), + msf = table.create(33, false), + qL = table.create(32 * 36, 0), + qR = table.create(32 * 36, 0), + yL = table.create(36 * 32, 0), + yR = table.create(36 * 32, 0), + vL = table.create(2304 + 960, 0), + vR = table.create(2304 + 960, 0), + r1 = 1, + r2 = 1, + lastMaxBand = 0, + } + return st +end + +-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the +-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek +-- decodes like libmpcdec seeking in a freshly opened stream. +@native function Decode.reset(st: State, scf: number) + for i = 1, 99 do + st.scfL[i] = scf + st.scfR[i] = scf + end + for i = 1, 33 do + st.resL[i], st.resR[i] = 0, 0 + st.dscfL[i], st.dscfR[i] = false, false + st.msf[i] = false + end + for i = 1, 2304 + 960 do + st.vL[i], st.vR[i] = 0, 0 + end + st.lastMaxBand = 0 + st.r1, st.r2 = 1, 1 +end + +@native local function noise(st: State, q: { number }, o: number) + local r1, r2 = st.r1, st.r2 + for k = 0, 35 do + local t1 = PARITY[band(r1, 0xF5) + 1] + local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] + r1 = bor(rshift(r1, 1), lshift(t1, 31)) + r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) + local t = bxor(r1, r2) + q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 + end + st.r1, st.r2 = r1, r2 +end + +-- ------------------------------------------------------------------------------------------------ SV7 +-- mpc_decoder_read_bitstream_sv7 -> true | nil, message +@native local function readSv7(st: State, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxUsed = 0 + local ms = st.ms + resL[1] = bits(4) + resR[1] = bits(4) + if resL[1] ~= 0 or resR[1] ~= 0 then + if ms then + msf[1] = bits(1) == 1 + end + maxUsed = 1 + end + for n = 1, st.maxBand do + local idx = huff(HDR) + resL[n + 1] = if idx ~= 4 then resL[n] + idx else bits(4) + idx = huff(HDR) + resR[n + 1] = if idx ~= 4 then resR[n] + idx else bits(4) + local l, r = resL[n + 1], resR[n + 1] + if l < -1 or l > 17 or r < -1 or r > 17 then + return nil, "bad band resolution" + end + if l ~= 0 or r ~= 0 then + if ms then + msf[n + 1] = bits(1) == 1 + end + maxUsed = n + 1 + end + end + if resL[1] > 17 or resR[1] > 17 then + return nil, "bad band resolution" + end + -- SCFI + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + if resL[n] ~= 0 then + scfiL[n] = huff(SCFI7) + end + if resR[n] ~= 0 then + scfiR[n] = huff(SCFI7) + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local o = (n - 1) * 3 + local idx = huff(DSCF7) + local s0 = if idx ~= 8 then scf[o + 3] + idx else bits(6) + local s1, s2 + if scfi == 1 then + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + s2 = s1 + elseif scfi == 3 then + s1, s2 = s0, s0 + elseif scfi == 2 then + s1 = s0 + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + else + idx = huff(DSCF7) + s1 = if idx ~= 8 then s0 + idx else bits(6) + idx = huff(DSCF7) + s2 = if idx ~= 8 then s1 + idx else bits(6) + end + scf[o + 1] = if s0 > 1024 then 0x8080 else s0 + scf[o + 2] = if s1 > 1024 then 0x8080 else s1 + scf[o + 3] = if s2 > 1024 then 0x8080 else s2 + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == -1 then + noise(st, q, o) + elseif res == 1 then + local tab = Q7[1][bits(1) + 1] + for k = 0, 35, 3 do + local idx = huff(tab) + q[o + k] = idx % 3 - 1 + q[o + k + 1] = (idx // 3) % 3 - 1 + q[o + k + 2] = idx // 9 - 1 + end + elseif res == 2 then + local tab = Q7[2][bits(1) + 1] + for k = 0, 35, 2 do + local idx = huff(tab) + q[o + k] = idx % 5 - 2 + q[o + k + 1] = idx // 5 - 2 + end + elseif res >= 3 and res <= 7 then + local tab = Q7[res][bits(1) + 1] + for k = 0, 35 do + q[o + k] = huff(tab) + end + elseif res >= 8 then + local nb, dc = RES_BIT[res], DC[res + 2] + for k = 0, 35 do + q[o + k] = bits(nb) - dc + end + end + if P > limit then + return nil, "truncated frame" + end + end + end + -- bands above maxUsed: silent + for n = maxUsed + 1, st.maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +@native local function readSv8(st: State, key: boolean, limit: number): (boolean?, string?) + local resL, resR, msf = st.resL, st.resR, st.msf + local maxBand = st.maxBand + local maxUsed + if key then + maxUsed = logDec(maxBand + 1) + else + maxUsed = st.lastMaxBand + huff(BANDS8) + if maxUsed > 32 then + maxUsed -= 33 + end + end + if maxUsed > maxBand + 1 then + return nil, "bad band count" + end + st.lastMaxBand = maxUsed + if maxUsed > 0 then + local l, r = huff(RES8[1]), huff(RES8[1]) + resL[maxUsed] = if l > 15 then l - 17 else l + resR[maxUsed] = if r > 15 then r - 17 else r + for n = maxUsed - 1, 1, -1 do + l = huff(RES8[if resL[n + 1] > 2 then 2 else 1]) + resL[n + 1] + resL[n] = if l > 15 then l - 17 else l + r = huff(RES8[if resR[n + 1] > 2 then 2 else 1]) + resR[n + 1] + resR[n] = if r > 15 then r - 17 else r + end + if st.ms then + local tot = 0 + for n = 1, maxUsed do + if resL[n] ~= 0 or resR[n] ~= 0 then + tot += 1 + end + end + local cnt = logDec(tot) + local tmp = 0 + if cnt ~= 0 and cnt ~= tot then + tmp = enumDec(math.min(cnt, tot - cnt), tot) + end + if cnt * 2 > tot then + tmp = bnot(tmp) + end + for n = maxUsed, 1, -1 do + if resL[n] ~= 0 or resR[n] ~= 0 then + msf[n] = band(tmp, 1) == 1 + tmp = rshift(tmp, 1) + end + end + end + end + for n = maxUsed + 1, maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + -- SCFI + local dscfL, dscfR = st.dscfL, st.dscfR + if key then + for n = 1, 32 do + dscfL[n], dscfR[n] = true, true + end + end + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + local cnt = -1 + if resL[n] ~= 0 then + cnt += 1 + end + if resR[n] ~= 0 then + cnt += 1 + end + if cnt >= 0 then + local tmp = huff(SCFI8[cnt + 1]) + if resL[n] ~= 0 then + scfiL[n] = rshift(tmp, 2 * cnt) + end + if resR[n] ~= 0 then + scfiR[n] = band(tmp, 3) + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + if res ~= 0 then + local scf = if c == 1 then st.scfL else st.scfR + local scfi = if c == 1 then scfiL[n] else scfiR[n] + local dscf = if c == 1 then dscfL else dscfR + local o = (n - 1) * 3 + if dscf[n] then + scf[o + 1] = bits(7) - 6 + dscf[n] = false + else + local tmp = huff(DSCF8[2]) + if tmp == 64 then + tmp += bits(6) + end + scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 + end + for m = 0, 1 do + if band(lshift(scfi, m), 2) == 0 then + local tmp = huff(DSCF8[1]) + if tmp == 31 then + tmp = 64 + bits(6) + end + scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 + else + scf[o + m + 2] = scf[o + m + 1] + end + end + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = if c == 1 then resL[n] else resR[n] + local q = if c == 1 then st.qL else st.qR + local o = (n - 1) * 36 + 1 + if res == 2 then + local tabs = Q8[2] + local thres = 3 + local idx = 6 + for k = 0, 35, 3 do + local tmp = huff(tabs[if idx > thres then 2 else 1]) + local a, b, cc = tmp % 5 - 2, (tmp // 5) % 5 - 2, tmp // 25 - 2 + q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc + idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) + end + elseif res == 1 then + local k = 0 + while k < 36 do + local kmax = k + 18 + local cnt = huff(Q1_8) + local idx = 0 + if cnt > 0 and cnt < 18 then + idx = enumDec(if cnt <= 9 then cnt else 18 - cnt, 18) + end + if cnt > 9 then + idx = bnot(idx) + end + while k < kmax do + q[o + k] = 0 + if band(idx, 0x20000) ~= 0 then + q[o + k] = bits(1) * 2 - 1 + end + idx = lshift(idx, 1) + k += 1 + end + end + elseif res == -1 then + noise(st, q, o) + elseif res == 3 or res == 4 then + local tab = Q34[res - 2] + for k = 0, 35, 2 do + local s = band(huff(tab), 255) + local s1, s2 = band(s, 15), rshift(s, 4) + q[o + k] = if s1 >= 8 then s1 - 16 else s1 + q[o + k + 1] = if s2 >= 8 then s2 - 16 else s2 + end + elseif res >= 5 and res <= 8 then + local tabs = Q8[res] + local thres = THRES[res] + local idx = 2 * thres + for k = 0, 35 do + local v = huff(tabs[if idx > thres then 2 else 1]) + q[o + k] = v + idx = rshift(idx, 1) + abs(v) + end + elseif res >= 9 then + local sh = res - 9 + local dc = DC[res + 2] + for k = 0, 35 do + local v = band(huff(Q9UP), 255) + if sh > 0 then + v = v * 2 ^ sh + bits(sh) + end + q[o + k] = v - dc + end + elseif res < -1 then + return nil, "bad band resolution" + end + if P > limit then + return nil, "truncated frame" + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ requantisation +@native local function requant(st: State) + local resL, resR, msf = st.resL, st.resR, st.msf + local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR + for b = 1, st.maxBand + 1 do + local rl, rr = resL[b], resR[b] + local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 + local ms = msf[b] + local o = (b - 1) * 36 + 1 + for part = 0, 2 do + local fl = if rl ~= 0 then f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local fr = if rr ~= 0 then f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) else 0 + local y = part * 12 * 32 + b + local qo = o + part * 12 + if ms then + for k = 0, 11 do + local l, r = fl * qL[qo + k], fr * qR[qo + k] + yL[y], yR[y] = l + r, l - r + y += 32 + end + else + for k = 0, 11 do + yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] + y += 32 + end + end + end + end +end + + +-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +@native local function synth(V: { number }, Y: { number }, out: { number }, base: number, step: number) + table.move(V, 1, 960, 2305) + local o = 2304 + 1 + local dw = DW + local p = base + for n = 0, 35 do + o -= 64 + newV(Y, n * 32 + 1, V, o) + for k = 0, 31 do + local v = o + k + local d = k * 16 + 1 + out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] + p += step + end + end +end + +-- ------------------------------------------------------------------------------------------------ frames +-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one +-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). +-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). +@native function Decode.frame(st: State, buf: buffer, bitPos: number, limitBits: number, key: boolean, out: { number }, base: number): (number?, string?) + if bitPos >= 0 then + if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then + return nil, "truncated frame" + end + B, P = buf, bitPos + local ok, err + if st.version == 8 then + ok, err = readSv8(st, key, limitBits) + else + ok, err = readSv7(st, limitBits) + end + B = buffer.create(0) + if not ok then + return nil, err + end + else + for b = 1, st.maxBand + 1 do + st.resL[b], st.resR[b] = 0, 0 + end + end + local pos = P + requant(st) + local ch = st.channels + synth(st.vL, st.yL, out, base, ch) + if ch > 1 then + synth(st.vR, st.yR, out, base + 1, ch) + end + return if bitPos >= 0 then pos else bitPos, nil +end + +-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps +-- bitPos / 8 + 4 inside buf +@native function Decode.bitsAt(buf: buffer, bitPos: number, n: number): number + local w = bswap(readu32(buf, rshift(bitPos, 3))) + return extract(w, 32 - band(bitPos, 7) - n, n) +end + +return Decode +end +__FILES["codecs/audio/Musepack/Tables"] = function() + +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation +-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; +-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script. +-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; +-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the +-- 8-bit first-level lookup the decoder uses. +local T = {} + +T.HuffHdr = { + 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, +} +T.HuffSCFI = { + 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, +} +T.HuffDSCF = { + 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, + 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, +} +T.HuffQ1_0 = { + 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, + 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, + 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, +} +T.HuffQ1_1 = { + 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, + 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, + 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, +} +T.HuffQ2_0 = { + 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, + 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, + 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, +} +T.HuffQ2_1 = { + 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, + 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, + 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, +} +T.HuffQ3_0 = { + 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, +} +T.HuffQ3_1 = { + 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, +} +T.HuffQ4_0 = { + 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, +} +T.HuffQ4_1 = { + 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, +} +T.HuffQ5_0 = { + 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, + 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, +} +T.HuffQ5_1 = { + 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, + 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, +} +T.HuffQ6_0 = { + 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, + 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, + 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, + 0, 4, -3, +} +T.HuffQ6_1 = { + 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, + 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, + 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, + 0, 3, 0, +} +T.HuffQ7_0 = { + 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, + 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, + 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, + 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, + 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, + 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, + 4096, 5, -6, 2048, 5, 6, 0, 5, -7, +} +T.HuffQ7_1 = { + 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, + 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, + 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, + 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, + 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, + 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, + 6144, 5, -10, 4096, 5, 11, 0, 4, 1, +} +T.H_SCFI_1 = { + 32768, 1, 1, 16384, 2, 2, 0, 3, 3, +} +T.H_SCFI_2 = { + 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, +} +T.H_DSCF_1 = { + 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, + 24, 13, 60, 0, 14, 63, +} +T.H_DSCF_2 = { + 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, + 32, 13, 57, 12, 14, 61, 0, 15, 64, +} +T.H_Bands = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, + 16, 12, 31, 0, 13, 32, +} +T.H_Res_1 = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, + 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, +} +T.H_Res_2 = { + 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, + 16, 12, 13, 0, 14, 16, +} +T.H_Q1 = { + 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, +} +T.H_Q2_1 = { + 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, +} +T.H_Q2_2 = { + 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, +} +T.H_Q3 = { + 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, +} +T.H_Q4 = { + 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, +} +T.H_Q5_1 = { + 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, +} +T.H_Q5_2 = { + 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, +} +T.H_Q6_1 = { + 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, +} +T.H_Q6_2 = { + 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, +} +T.H_Q7_1 = { + 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, +} +T.H_Q7_2 = { + 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, +} +T.H_Q8_1 = { + 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, + 0, 12, 126, +} +T.H_Q8_2 = { + 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, +} +T.H_Q9up = { + 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, +} +T.S_SCFI_1 = { + 2, 3, 1, 0, +} +T.S_SCFI_2 = { + 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, +} +T.S_DSCF_1 = { + 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, + 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, +} +T.S_DSCF_2 = { + 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, + 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, + 0, +} +T.S_Bands = { + 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, + 13, +} +T.S_Res_1 = { + 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, +} +T.S_Res_2 = { + 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, +} +T.S_Q1 = { + 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, +} +T.S_Q2_1 = { + 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, + 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, + 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q2_2 = { + 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, + 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, + 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q3 = { + 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, + -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, +} +T.S_Q4 = { + 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, + -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, + -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} +T.S_Q5_1 = { + 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q5_2 = { + 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q6_1 = { + 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, +} +T.S_Q6_2 = { + 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, +} +T.S_Q7_1 = { + 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, + -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, +} +T.S_Q7_2 = { + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, + -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, +} +T.S_Q8_1 = { + 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, + -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, + 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, + -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, +} +T.S_Q8_2 = { + 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, + 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, +} +T.S_Q9up = { + -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, + -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, + -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, + 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, +} + +-- Di_opt[32][16] (times 65536) +T.DI = { + 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, + -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, + -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, + -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, + -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, + -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, + -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, + -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, + -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, + -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, + -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, + -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, + -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, + -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, + -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, + -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, + -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, + -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, + -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, + -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, + -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, + -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, + -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, + -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, + -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, + -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, + -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, + -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, + -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, + -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, + -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, + -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, +} + +-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per +-- sample of the plain quantisers (res 8 .. 17) +T.CC = { + 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, + 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, + 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, + 2.000061037018, 1.000015259021, +} +T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } +T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } + +-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) +T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } +T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } + +-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused +-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) +T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} +do + for k = 1, 16 do + local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) + for n = 0, 32 do + local v = 0 + if n >= k then + v = 1 + for i = 1, k do + v = v * (n - k + i) / i + end + v = math.floor(v + 0.5) + end + if n <= 31 then + c[n + 1] = v + end + if n >= 1 then + local bits = 0 + while 2 ^ bits < v do + bits += 1 + end + l[n] = bits + lost[n] = if v > 0 then 2 ^ bits - v else 0 + end + end + T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost + end + T.CNK_LOST[16][32] = 0 +end + +type Lut = { + len: { number }, -- 256 entries: code length when the 8-bit prefix decides the symbol, else 0 + val: { number }, -- the symbol, or the 1-based table entry to scan from + codes: { number }, + lens: { number }, + vals: { number }, + sym: { number }?, +} + +-- lut(table, sym?) -> Lut +function T.lut(tab: { number }, sym: { number }?): Lut + local codes, lens, vals = {}, {}, {} + for i = 1, #tab, 3 do + table.insert(codes, tab[i]) + table.insert(lens, tab[i + 1]) + table.insert(vals, tab[i + 2]) + end + local function find(code: number): number + local j = 1 + while code < codes[j] do + j += 1 + end + return j + end + local function symbol(j: number, code: number): number + if sym then + local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) + return sym[idx + 1] or 0 + end + return vals[j] + end + local len, val = table.create(256, 0), table.create(256, 0) + for p = 0, 255 do + local lo, hi = find(p * 256), find(p * 256 + 255) + if lo == hi and lens[lo] <= 8 then + len[p + 1] = lens[lo] + val[p + 1] = symbol(lo, p * 256) + else + len[p + 1] = 0 + val[p + 1] = hi + end + end + return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } +end + +return T +end +__FILES["codecs/audio/Opus"] = function() + +-- 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 = __include("codecs/audio/Opus/Packet"), + Decoder = __include("codecs/audio/Opus/Decoder"), + Celt = __include("codecs/audio/Opus/Celt"), + Silk = __include("codecs/audio/Opus/Silk"), + CeltEncoder = __include("codecs/audio/Opus/CeltEncoder"), +} + +return Opus +end +__FILES["codecs/audio/Opus/Celt"] = @native function() + + + +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local Mdct = __include("codecs/audio/Opus/Mdct") +local T = __include("codecs/audio/Opus/CeltTables") + +local Celt = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos +local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint +local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update +local tell, tellFrac = RD.tell, RD.tellFrac + +local NB_EBANDS = 21 +local EFF_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local MAX_LM = 3 +local DECODE_BUFFER_SIZE = 2048 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local QTHETA_OFFSET_TWOPHASE = 16 +local SPREAD_AGGRESSIVE = 3 +local PREEMPH = 0.85000610 +local COMBFILTER_MINPERIOD = 15 +local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 + +-- eBands (1-based: EB[i + 1] is eBands[i]) +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, 3.750000, 3.750000, 3.750000, 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag] + { 0, -1, 0, -1, 0, -1, 0, -1 }, + { 0, -1, 0, -2, 1, 0, 1, -1 }, + { 0, -2, 0, -3, 2, 0, 1, -1 }, + { 0, -2, 0, -3, 3, 0, 1, -1 }, +} +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local TAPSET_ICDF = { 2, 1, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } +local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } +local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } +local COMB_GAINS = { + { 0.3066406250, 0.2170410156, 0.1296386719 }, + { 0.4638671875, 0.2680664062, 0.0 }, + { 0.7998046875, 0.1000976562, 0.0 }, +} + +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +Celt.window = WINDOW + +-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end + +-- shared workspace (decoding is not re-entrant) +local NORM_BASE = 1920 +local W = table.create(4096, 0) +local TMP = table.create(256, 0) +local IY = table.create(256, 0) +local FREQ = table.create(960, 0) +local FREQ2 = table.create(960, 0) +local COLLAPSE = table.create(42, 0) +local TF_RES = table.create(21, 0) +local CAP = table.create(21, 0) +local OFFSETS = table.create(21, 0) +local FINE_QUANT = table.create(21, 0) +local PULSES = table.create(21, 0) +local FINE_PRIORITY = table.create(21, 0) +local BITS1 = table.create(21, 0) +local BITS2 = table.create(21, 0) +local THRESH = table.create(21, 0) +local TRIM_OFFSET = table.create(21, 0) + +@native local function imin(a: number, b: number): number + return if a < b then a else b +end +@native local function imax(a: number, b: number): number + return if a > b then a else b +end +-- C integer division (truncates toward zero) +@native local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end + +@native local function exp2(x: number): number + return exp(0.6931471805599453094 * x) +end + +@native local function lcg(seed: number): number + return (1664525 * seed + 1013904223) % 4294967296 +end + +@native local function signed32(x: number): number + return if x >= 2147483648 then x - 4294967296 else x +end + +@native local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end + +@native local function bitexactCos(x: number): number + local tmp = (4096 + x * x) // 8192 + local x2 = tmp + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end + +@native local function bitexactLog2tan(isin: number, icos: number): number + local lc = RD.ilog(icos) + local ls = RD.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- --------------------------------------------------------------------------------------------------------------- +-- energy (quant_bands.c, laplace.c) + +@native local function laplaceDecode(dec: RD.Dec, fs: number, decay: number): number + local val = 0 + local fm = decDecodeBin(dec, 15) + local fl = 0 + if fm >= fs then + val += 1 + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 + 1 + while fs > 1 and fm >= fl + 2 * fs do + fs *= 2 + fl += fs + fs = ((fs - 2) * decay) // 32768 + fs += 1 + val += 1 + end + if fs <= 1 then + local di = rshift(fm - fl, 1) + val += di + fl += 2 * di + end + if fm < fl + fs then + val = -val + else + fl += fs + end + end + decUpdate(dec, fl, imin(fl + fs, 32768), 32768) + return val +end + +@native local function unquantCoarseEnergy(st: any, start: number, endb: number, intra: boolean, dec: RD.Dec, C: number, LM: number) + local oldE = st.oldBandE + local probBase = LM * 84 + (if intra then 42 else 0) -- e_prob_model[LM][intra], 0-based + local coef, beta + if intra then + coef = 0 + beta = BETA_INTRA + else + beta = BETA_COEF[LM + 1] + coef = PRED_COEF[LM + 1] + end + local prev0, prev1 = 0, 0 + local budget = dec.storage * 8 + for i = start, endb - 1 do + for c = 0, C - 1 do + local t = tell(dec) + local qi + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) + qi = if band(qi, 1) ~= 0 then -rshift(qi, 1) - 1 else rshift(qi, 1) + elseif budget - t >= 1 then + qi = if decBitLogp(dec, 1) then -1 else 0 + else + qi = -1 + end + local q = qi + local k = i + c * NB_EBANDS + 1 + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + oldE[k] = coef * e + prev + q + prev = prev + q - beta * q + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +@native local function unquantFineEnergy(st: any, start: number, endb: number, fineQuant: { number }, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for i = start, endb - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(dec) + C * extra > dec.storage * 8 then + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[i + c * NB_EBANDS + 1] += offset + end + end +end + +@native local function unquantEnergyFinalise(st: any, start: number, endb: number, fineQuant: { number }, finePriority: { number }, bitsLeft: number, dec: RD.Dec, C: number) + local oldE = st.oldBandE + for prio = 0, 1 do + local i = start + while i < endb and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local q2 = decBits(dec, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[i + c * NB_EBANDS + 1] += offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bit allocation (rate.c) + +@native local function bits2pulses(bandI: number, LM: number, bits: number): number + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +@native local function pulses2bits(bandI: number, LM: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +@native local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +@native local function computeAllocation(start: number, endb: number, offsets: { number }, cap: { number }, allocTrim: number, + total: number, pulses: { number }, ebits: { number }, finePriority: { number }, C: number, LM: number, ec: RD.Dec) + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local N = EB[j + 2] - EB[j + 1] + local bitsj = (C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local N = EB[j + 2] - EB[j + 1] + local bits1j = (C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + if decBitLogp(ec, 1) then + break + end + psum += 8 + bandBits -= 8 + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = start + decUint(ec, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = decBitLogp(ec, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local N = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if N > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * N + (if C == 2 and N > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if N == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- --------------------------------------------------------------------------------------------------------------- +-- PVQ (cwrs.c, vq.c) + +@native local function cwrsi(n: number, k: number, i: number, iy: { number }): number + local yy = 0 + local idx = 1 + local p, k0, val + while n > 2 do + if k >= n then + local rowBase = n * UK + 1 + p = U[rowBase + k + 1] + local neg = i >= p + if neg then + i -= p + end + k0 = k + local q = U[rowBase + n] + if q > i then + k = n + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + else + p = U[rowBase + k] + while p > i do + k -= 1 + p = U[rowBase + k] + end + end + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + else + p = U[k * UK + n + 1] + local q = U[(k + 1) * UK + n + 1] + if p <= i and i < q then + i -= p + iy[idx] = 0 + idx += 1 + else + local neg = i >= q + if neg then + i -= q + end + k0 = k + repeat + k -= 1 + p = U[k * UK + n + 1] + until p <= i + i -= p + val = if neg then k - k0 else k0 - k + iy[idx] = val + idx += 1 + yy += val * val + end + end + n -= 1 + end + -- n == 2 + p = 2 * k + 1 + local neg = i >= p + if neg then + i -= p + end + k0 = k + k = rshift(i + 1, 1) + if k ~= 0 then + i -= 2 * k - 1 + end + val = if neg then k - k0 else k0 - k + iy[idx] = val + yy += val * val + -- n == 1 + val = if i ~= 0 then -k else k + iy[idx + 1] = val + yy += val * val + return yy +end + +@native local function expRotation1(X: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = X + 1 + for _ = 0, len - stride - 1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p += 1 + end + p = X + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p -= 1 + end +end + +local SPREAD_FACTOR = { 15, 10, 5 } +@native local function expRotation(X: number, len: number, dir: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = X + i * len + if dir < 0 then + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, c) + end + expRotation1(x, len, 1, c, s) + else + expRotation1(x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, -c) + end + end + end +end + +@native local function renormaliseVector(X: number, N: number, gain: number) + local E = 1e-15 + for i = X + 1, X + N do + local v = W[i] + E += v * v + end + local g = gain / sqrt(E) + for i = X + 1, X + N do + W[i] *= g + end +end + +@native local function algUnquant(X: number, N: number, K: number, spread: number, B: number, dec: RD.Dec, gain: number): number + local iy = IY + local ft = U[N * UK + K + 1] + U[N * UK + K + 2] + local Ryy = cwrsi(N, K, decUint(dec, ft), iy) + local g = gain / sqrt(Ryy) + for i = 1, N do + W[X + i] = iy[i] * g + end + expRotation(X, N, -1, B, K, spread) + if B <= 1 then + return 1 + end + local N0 = N // B + local mask = 0 + for i = 0, B - 1 do + for j = 1, N0 do + if iy[i * N0 + j] ~= 0 then + mask = bor(mask, lshift(1, i)) + break + end + end + end + return mask +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bands (bands.c) + +type Ctx = { + i: number, + intensity: number, + spread: number, + tf_change: number, + ec: RD.Dec, + remaining_bits: number, + seed: number, + disable_inv: boolean, + avoid_split_noise: boolean, +} +local ctx: Ctx = { + i = 0, + intensity = 0, + spread = 0, + tf_change = 0, + ec = (nil :: any), + remaining_bits = 0, + seed = 0, + disable_inv = false, + avoid_split_noise = false, +} + +@native local function haar1(X: number, N0: number, stride: number) + N0 = rshift(N0, 1) + local s = 0.70710678 + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + local a = X + stride * 2 * j + i + 1 + local b = a + stride + local t1 = s * W[a] + local t2 = s * W[b] + W[a] = t1 + t2 + W[b] = t1 - t2 + end + end +end + +@native local function deinterleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[o + j + 1] = W[X + j * stride + i + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +@native local function interleaveHadamard(X: number, N0: number, stride: number, hadamard: boolean) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + o + j + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +@native local function computeQn(N: number, b: number, offset: number, pulseCap: number, stereo: boolean): number + local N2 = 2 * N - 1 + if stereo and N == 2 then + N2 -= 1 + end + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- returns b, fill, inv, imid, iside, delta, itheta, qalloc +@native local function computeTheta(N: number, b: number, B: number, B0: number, LM: number, stereo: boolean, fill: number) + local i = ctx.i + local ec = ctx.ec + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - (if stereo and N == 2 then QTHETA_OFFSET_TWOPHASE else QTHETA_OFFSET) + local qn = computeQn(N, b, offset, pulseCap, stereo) + if stereo and i >= ctx.intensity then + qn = 1 + end + local t0 = tellFrac(ec) + local itheta = 0 + local inv = false + if qn ~= 1 then + if stereo and N > 2 then + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + local fs = decDecode(ec, ft) + local x + if fs < (x0 + 1) * p0 then + x = fs // p0 + else + x = x0 + 1 + (fs - (x0 + 1) * p0) + end + if x <= x0 then + decUpdate(ec, p0 * x, p0 * (x + 1), ft) + else + decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) + end + itheta = x + elseif B0 > 1 or stereo then + itheta = decUint(ec, qn + 1) + else + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fm = decDecode(ec, ft) + local fs, fl + if fm < rshift(h * (h + 1), 1) then + itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) + fs = itheta + 1 + fl = rshift(itheta * (itheta + 1), 1) + else + itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) + fs = qn + 1 - itheta + fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + end + decUpdate(ec, fl, fl + fs, ft) + end + itheta = (itheta * 16384) // qn + elseif stereo then + if b > 16 and ctx.remaining_bits > 16 then + inv = decBitLogp(ec, 2) + end + if ctx.disable_inv then + inv = false + end + itheta = 0 + end + local qalloc = tellFrac(ec) - t0 + b -= qalloc + local imid, iside, delta + if itheta == 0 then + imid = 32767 + iside = 0 + fill = band(fill, lshift(1, B) - 1) + delta = -16384 + elseif itheta == 16384 then + imid = 0 + iside = 32767 + fill = band(fill, lshift(lshift(1, B) - 1, B)) + delta = 16384 + else + imid = bitexactCos(itheta) + iside = bitexactCos(16384 - itheta) + delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) + end + return b, fill, inv, imid, iside, delta, itheta, qalloc +end + +@native local function quantBandN1(X: number, Y: number, lowbandOut: number): number + local x = X + local ec = ctx.ec + for _ = 0, (if Y >= 0 then 1 else 0) do + local sign = 0 + if ctx.remaining_bits >= 8 then + sign = decBits(ec, 1) + ctx.remaining_bits -= 8 + end + W[x + 1] = if sign ~= 0 then -1 else 1 + x = Y + end + if lowbandOut >= 0 then + W[lowbandOut + 1] = W[X + 1] + end + return 1 +end + +@native local function quantPartition(X: number, N: number, b: number, B: number, lowband: number, LM: number, gain: number, fill: number): number + local i = ctx.i + local B0 = B + local cm = 0 + local split = false + if LM ~= -1 and N > 2 then + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + N = rshift(N, 1) + local Y = X + N + LM -= 1 + if B == 1 then + fill = bor(band(fill, 1), lshift(fill, 1)) + end + B = rshift(B + 1, 1) + local _inv, imid, iside, delta, itheta, qalloc + b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) + local mid = imid / 32768 + local side = iside / 32768 + if B0 > 1 and band(itheta, 0x3fff) ~= 0 then + if itheta > 8192 then + delta -= delta // 2 ^ (4 - LM) + else + delta = imin(0, delta + (N * 8) // 2 ^ (5 - LM)) + end + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local nextLowband2 = if lowband >= 0 then lowband + N else -1 + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) + else + cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) + end + else + local q = bits2pulses(i, LM, b) + local currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + while ctx.remaining_bits < 0 and q > 0 do + ctx.remaining_bits += currBits + q -= 1 + currBits = pulses2bits(i, LM, q) + ctx.remaining_bits -= currBits + end + if q ~= 0 then + cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) + else + local cmMask = lshift(1, B) - 1 + fill = band(fill, cmMask) + if fill == 0 then + for j = X + 1, X + N do + W[j] = 0 + end + else + local seed = ctx.seed + if lowband < 0 then + for j = X + 1, X + N do + seed = lcg(seed) + W[j] = signed32(seed) // 1048576 + end + cm = cmMask + else + for j = 0, N - 1 do + seed = lcg(seed) + local tmp = if band(seed, 0x8000) ~= 0 then 1 / 256 else -1 / 256 + W[X + j + 1] = W[lowband + j + 1] + tmp + end + cm = fill + end + ctx.seed = seed + renormaliseVector(X, N, gain) + end + end + end + return cm +end + +@native local function quantBand(X: number, N: number, b: number, B: number, lowband: number, LM: number, lowbandOut: number, + gain: number, lowbandScratch: number, fill: number): number + local N0 = N + local NB = N + local B0 = B + local timeDivide = 0 + local recombine = 0 + local longBlocks = B0 == 1 + local tfChange = ctx.tf_change + NB = NB // B + if N == 1 then + return quantBandN1(X, -1, lowbandOut) + end + if tfChange > 0 then + recombine = tfChange + end + if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then + for j = 1, N do + W[lowbandScratch + j] = W[lowband + j] + end + lowband = lowbandScratch + end + for k = 0, recombine - 1 do + if lowband >= 0 then + haar1(lowband, rshift(N, k), lshift(1, k)) + end + fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) + end + B = rshift(B, recombine) + NB = lshift(NB, recombine) + while band(NB, 1) == 0 and tfChange < 0 do + if lowband >= 0 then + haar1(lowband, NB, B) + end + fill = bor(fill, lshift(fill, B)) + B = lshift(B, 1) + NB = rshift(NB, 1) + timeDivide += 1 + tfChange += 1 + end + B0 = B + local NB0 = NB + if B0 > 1 and lowband >= 0 then + deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) + if B0 > 1 then + interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + NB = NB0 + B = B0 + for _ = 0, timeDivide - 1 do + B = rshift(B, 1) + NB = lshift(NB, 1) + cm = bor(cm, rshift(cm, B)) + haar1(X, NB, B) + end + for k = 0, recombine - 1 do + cm = BIT_DEINTERLEAVE[cm + 1] + haar1(X, rshift(N0, k), lshift(1, k)) + end + B = lshift(B, recombine) + if lowbandOut >= 0 then + local n = sqrt(N0) + for j = 1, N0 do + W[lowbandOut + j] = n * W[X + j] + end + end + return band(cm, lshift(1, B) - 1) +end + +@native local function stereoMerge(X: number, Y: number, mid: number, N: number) + local xp, side = 0, 0 + for j = 1, N do + local y = W[Y + j] + xp += y * W[X + j] + side += y * y + end + xp = mid * xp + local mm = mid * mid + local El = mm + side - 2 * xp + local Er = mm + side + 2 * xp + if Er < 6e-4 or El < 6e-4 then + for j = 1, N do + W[Y + j] = W[X + j] + end + return + end + local lgain = 1 / sqrt(El) + local rgain = 1 / sqrt(Er) + for j = 1, N do + local l = mid * W[X + j] + local r = W[Y + j] + W[X + j] = lgain * (l - r) + W[Y + j] = rgain * (l + r) + end +end + +@native local function quantBandStereo(X: number, Y: number, N: number, b: number, B: number, lowband: number, LM: number, + lowbandOut: number, lowbandScratch: number, fill: number): number + if N == 1 then + return quantBandN1(X, Y, lowbandOut) + end + local origFill = fill + local inv, imid, iside, delta, itheta, qalloc + b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) + local mid = imid / 32768 + local side = iside / 32768 + local cm + if N == 2 then + local mbits = b + local sbits = 0 + if itheta ~= 0 and itheta ~= 16384 then + sbits = 8 + end + mbits -= sbits + local c = itheta > 8192 + ctx.remaining_bits -= qalloc + sbits + local x2, y2 = X, Y + if c then + x2, y2 = Y, X + end + local sign = 0 + if sbits ~= 0 then + sign = decBits(ctx.ec, 1) + end + sign = 1 - 2 * sign + cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) + W[y2 + 1] = -sign * W[x2 + 2] + W[y2 + 2] = sign * W[x2 + 1] + local x0, x1 = mid * W[X + 1], mid * W[X + 2] + local y0, y1 = side * W[Y + 1], side * W[Y + 2] + W[X + 1] = x0 - y0 + W[Y + 1] = x0 + y0 + W[X + 2] = x1 - y1 + W[Y + 2] = x1 + y1 + else + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits -= qalloc + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) + else + cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) + end + end + if N ~= 2 then + stereoMerge(X, Y, mid, N) + end + if inv then + for j = Y + 1, Y + N do + W[j] = -W[j] + end + end + return cm +end + +@native local function quantAllBands(start: number, endb: number, hasY: boolean, N: number, collapse: { number }, + pulses: { number }, shortBlocks: boolean, spread: number, dualStereo: boolean, intensity: number, + tfRes: { number }, totalBits: number, balance: number, ec: RD.Dec, LM: number, codedBands: number, + seed: number, disableInv: boolean): number + local M = lshift(1, LM) + local B = if shortBlocks then M else 1 + local normOffset = M * EB[start + 1] + local C = if hasY then 2 else 1 + local norm = NORM_BASE + local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset + local lowbandScratch = M * EB[EFF_EBANDS] + local lowbandOffset = 0 + local updateLowband = true + ctx.ec = ec + ctx.intensity = intensity + ctx.seed = seed + ctx.spread = spread + ctx.disable_inv = disableInv + ctx.avoid_split_noise = B > 1 + for i = start, endb - 1 do + ctx.i = i + local last = i == endb - 1 + local X = M * EB[i + 1] + local Y = if hasY then N + M * EB[i + 1] else -1 + local Nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(ec) + if i ~= start then + balance -= t + end + local remainingBits = totalBits - t - 1 + ctx.remaining_bits = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then + lowbandOffset = i + end + if i == start + 1 then + local n1 = M * (EB[start + 2] - EB[start + 1]) + local n2 = M * (EB[start + 3] - EB[start + 2]) + for k = 0, n2 - n1 - 1 do + W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] + end + if dualStereo then + for k = 0, n2 - n1 - 1 do + W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] + end + end + end + local tfChange = tfRes[i + 1] + ctx.tf_change = tfChange + if last then + lowbandScratch = -1 + end + local effectiveLowband = -1 + local xcm, ycm + if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then + effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) + local foldStart = lowbandOffset + repeat + foldStart -= 1 + until M * EB[foldStart + 1] <= effectiveLowband + normOffset + local foldEnd = lowbandOffset - 1 + repeat + foldEnd += 1 + until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) + xcm, ycm = 0, 0 + local fi = foldStart + repeat + xcm = bor(xcm, collapse[fi * C + 1]) + ycm = bor(ycm, collapse[fi * C + C]) + fi += 1 + until fi >= foldEnd + else + xcm = lshift(1, B) - 1 + ycm = xcm + end + if dualStereo and i == intensity then + dualStereo = false + for j = 1, M * EB[i + 1] - normOffset do + W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) + end + end + if dualStereo then + xcm = quantBand(X, Nb, b // 2, B, if effectiveLowband ~= -1 then norm + effectiveLowband else -1, LM, + if last then -1 else norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) + ycm = quantBand(Y, Nb, b // 2, B, if effectiveLowband ~= -1 then norm2 + effectiveLowband else -1, LM, + if last then -1 else norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) + else + local lb = if effectiveLowband ~= -1 then norm + effectiveLowband else -1 + local lo = if last then -1 else norm + M * EB[i + 1] - normOffset + if hasY then + xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) + else + xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) + end + ycm = xcm + end + collapse[i * C + 1] = band(xcm, 255) + collapse[i * C + C] = band(ycm, 255) + balance += pulses[i + 1] + t + updateLowband = b > Nb * 8 + ctx.avoid_split_noise = false + end + return ctx.seed +end + +@native local function antiCollapse(st: any, C: number, size: number, LM: number, start: number, endb: number, + collapse: { number }, pulses: { number }, seed: number) + local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 + for i = start, endb - 1 do + local N0 = EB[i + 2] - EB[i + 1] + local depth = rshift((1 + pulses[i + 1]) // N0, LM) + local thresh = 0.5 * exp2(-0.125 * depth) + local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) + for c = 0, C - 1 do + local k0 = c * NB_EBANDS + i + 1 + local prev1 = prev1logE[k0] + local prev2 = prev2logE[k0] + if C == 1 then + prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) + prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) + end + local Ediff = max(0, logE[k0] - min(prev1, prev2)) + local r = 2 * exp2(-Ediff) + if LM == 3 then + r *= 1.41421356 + end + r = min(thresh, r) * sqrt1 + local X = c * size + EB[i + 1] * 2 ^ LM + local renorm = false + local cmask = collapse[i * C + c + 1] + for k = 0, 2 ^ LM - 1 do + if band(cmask, lshift(1, k)) == 0 then + for j = 0, N0 - 1 do + seed = lcg(seed) + W[X + j * 2 ^ LM + k + 1] = if band(seed, 0x8000) ~= 0 then r else -r + end + renorm = true + end + end + if renorm then + renormaliseVector(X, N0 * 2 ^ LM, 1) + end + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- synthesis + +@native local function denormaliseBands(X: number, freq: { number }, logE: { number }, eoff: number, start: number, endb: number, M: number, silence: boolean) + local N = M * SHORT_MDCT + local bound = M * EB[endb + 1] + if silence then + bound = 0 + start = 0 + endb = 0 + end + local f = 1 + local x = X + M * EB[start + 1] + if start ~= 0 then + for _ = 1, M * EB[start + 1] do + freq[f] = 0 + f += 1 + end + end + for i = start, endb - 1 do + local bandEnd = M * EB[i + 2] + local lg = logE[eoff + i + 1] + E_MEANS[i + 1] + local g = exp2(min(32, lg)) + for _ = M * EB[i + 1], bandEnd - 1 do + freq[f] = W[x + 1] * g + f += 1 + x += 1 + end + end + for k = bound + 1, N do + freq[k] = 0 + end +end + +@native local function celtSynthesis(st: any, C: number, CC: number, start: number, effEnd: number, isTransient: boolean, LM: number, silence: boolean, N: number) + local M = lshift(1, LM) + local B, NB, shift + if isTransient then + B = M + NB = SHORT_MDCT + shift = MAX_LM + else + B = 1 + NB = SHORT_MDCT * M + shift = MAX_LM - LM + end + local outBase = DECODE_BUFFER_SIZE - N + 1 + local oldE = st.oldBandE + local freq = FREQ + if CC == 2 and C == 1 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + for c = 1, 2 do + local mem = st.mem[c] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + elseif CC == 1 and C == 2 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) + local f2 = FREQ2 + for k = 1, N do + freq[k] = 0.5 * freq[k] + 0.5 * f2[k] + end + local mem = st.mem[1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + else + for c = 0, CC - 1 do + denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) + local mem = st.mem[c + 1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + end +end + +-- comb_filter, in place on mem (1-based base index of sample 0) +@native local function combFilter(mem: { number }, base: number, T0: number, T1: number, N: number, g0: number, g1: number, + tapset0: number, tapset1: number, overlap: number) + if g0 == 0 and g1 == 0 then + return + end + T0 = imax(T0, COMBFILTER_MINPERIOD) + T1 = imax(T1, COMBFILTER_MINPERIOD) + local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] + local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] + local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] + local x1 = mem[base - T1 + 1] + local x2 = mem[base - T1] + local x3 = mem[base - T1 - 1] + local x4 = mem[base - T1 - 2] + if g0 == g1 and T0 == T1 and tapset0 == tapset1 then + overlap = 0 + end + local i = 0 + while i < overlap do + local p = base + i + local x0 = mem[p - T1 + 2] + local w = WINDOW[i + 1] + local f = w * w + local of = 1 - f + mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + i += 1 + end + if g1 == 0 then + return + end + -- constant part (comb_filter_const) + local p = base + i + x4 = mem[p - T1 - 2] + x3 = mem[p - T1 - 1] + x2 = mem[p - T1] + x1 = mem[p - T1 + 1] + for q = p, base + N - 1 do + local x0 = mem[q - T1 + 2] + mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + end +end + +@native local function deemphasis(st: any, CC: number, N: number, pcm: { number }, pbase: number, accum: boolean) + local coef0 = PREEMPH + local xbase = DECODE_BUFFER_SIZE - N + for c = 0, CC - 1 do + local x = st.mem[c + 1] + local m = st.preemph[c + 1] + local y = pbase + c + if accum then + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] += tmp * (1 / 32768) + y += CC + end + else + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] = tmp * (1 / 32768) + y += CC + end + end + st.preemph[c + 1] = m + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- decoder state + +@native local function resetState(st: any) + st.rng = 0 + st.error = 0 + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NONE + st.skip_plc = true + st.postfilter_period = 0 + st.postfilter_period_old = 0 + st.postfilter_gain = 0 + st.postfilter_gain_old = 0 + st.postfilter_tapset = 0 + st.postfilter_tapset_old = 0 + st.preemph[1] = 0 + st.preemph[2] = 0 + for c = 1, st.channels do + local m = st.mem[c] + for k = 1, DECODE_BUFFER_SIZE + OVERLAP do + m[k] = 0 + end + end + for k = 1, 2 * NB_EBANDS do + st.oldBandE[k] = 0 + st.oldLogE[k] = -28 + st.oldLogE2[k] = -28 + st.backgroundLogE[k] = 0 + end +end + +-- celt_decoder_init(48000, channels) +@native function Celt.new(channels: number): any + local st = { + channels = channels, + stream_channels = channels, + start = 0, + ["end"] = EFF_EBANDS, + disable_inv = channels == 1, + mem = {}, + preemph = { 0, 0 }, + oldBandE = table.create(2 * NB_EBANDS, 0), + oldLogE = table.create(2 * NB_EBANDS, -28), + oldLogE2 = table.create(2 * NB_EBANDS, -28), + backgroundLogE = table.create(2 * NB_EBANDS, 0), + } + for c = 1, channels do + st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) + end + resetState(st) + return st +end + +Celt.reset = resetState + +-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) +@native local function decodeLost(st: any, N: number, LM: number) + local C = st.channels + local start = st.start + local endb = st["end"] + local effEnd = imax(start, imin(endb, EFF_EBANDS)) + for c = 1, C do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + local decay = 2 ^ LM * 0.0625 + if st.last_frame_type ~= FRAME_PLC_NOISE then + decay += max(1, imin(160, st.loss_duration) * 0.0625) + end + local oldE, bg = st.oldBandE, st.backgroundLogE + for c = 0, C - 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + oldE[k] = max(bg[k], oldE[k] - decay) + end + end + local seed = st.rng + for c = 0, C - 1 do + for i = start, effEnd - 1 do + local boffs = N * c + EB[i + 1] * 2 ^ LM + local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + for j = 1, blen do + seed = lcg(seed) + W[boffs + j] = signed32(seed) // 1048576 + end + renormaliseVector(boffs, blen, 1) + end + end + st.rng = seed + celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, C do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, + st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.skip_plc = true + st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) + st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) + st.last_frame_type = FRAME_PLC_NOISE +end + +-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over +-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +@native function Celt.decode(st: any, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, + dec: RD.Dec?, accum: boolean): number + local CC = st.channels + local C = st.stream_channels + local start = st.start + local endb = st["end"] + local LM = 0 + while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do + LM += 1 + end + if LM > MAX_LM then + return -1 + end + local M = lshift(1, LM) + if len < 0 or len > 1275 then + return -1 + end + local N = M * SHORT_MDCT + local effEnd = imin(endb, EFF_EBANDS) + if buf == nil or len <= 1 then + decodeLost(st, N, LM) + deemphasis(st, CC, N, pcm, pbase, accum) + return frameSize + end + if st.loss_duration == 0 then + st.skip_plc = false + end + if dec == nil then + dec = RD.new(buf :: buffer, off, len) + end + local ec = dec :: RD.Dec + local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) + end + end + local totalBits = len * 8 + local t = tell(ec) + local silence + if t >= totalBits then + silence = true + elseif t == 1 then + silence = decBitLogp(ec, 15) + else + silence = false + end + if silence then + t = len * 8 + ec.nbits_total += t - tell(ec) + end + local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 + if start == 0 and t + 16 <= totalBits then + if decBitLogp(ec, 1) then + local octave = decUint(ec, 6) + postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 + local qg = decBits(ec, 3) + if tell(ec) + 2 <= totalBits then + postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) + end + postfilterGain = 0.09375 * (qg + 1) + end + t = tell(ec) + end + local isTransient = false + if LM > 0 and t + 3 <= totalBits then + isTransient = decBitLogp(ec, 3) + t = tell(ec) + end + local shortBlocks = isTransient + local intraEner = if t + 3 <= totalBits then decBitLogp(ec, 3) else false + if not intraEner and st.loss_duration ~= 0 then + local missing = imin(10, rshift(st.loss_duration, LM)) + local safety = if LM == 0 then 1.5 elseif LM == 1 then 0.5 else 0 + for c = 0, 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then + local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] + local slope = max(E1 - E0, 0.5 * (E2 - E0)) + slope = min(slope, 2) + E0 -= max(0, (1 + missing) * slope) + oldBandE[k] = max(-20, E0) + else + oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) + end + oldBandE[k] -= safety + end + end + end + unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) + + -- tf_decode + local tfRes = TF_RES + do + local budget = ec.storage * 8 + local tt = tell(ec) + local logp = if isTransient then 2 else 4 + local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget + if tfSelectRsv then + budget -= 1 + end + local tfChanged, curr = 0, 0 + for i = start, endb - 1 do + if tt + logp <= budget then + if decBitLogp(ec, logp) then + curr = bit32.bxor(curr, 1) + end + tt = tell(ec) + tfChanged = bor(tfChanged, curr) + end + tfRes[i + 1] = curr + logp = if isTransient then 4 else 5 + end + local tfSelect = 0 + local row = TF_SELECT[LM + 1] + local ti = if isTransient then 4 else 0 + if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then + tfSelect = if decBitLogp(ec, 1) then 1 else 0 + end + for i = start, endb - 1 do + tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] + end + end + + t = tell(ec) + local spread = 2 + if t + 4 <= totalBits then + spread = decIcdf(ec, SPREAD_ICDF, 1, 5) + end + local cap = CAP + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = OFFSETS + local dynallocLogp = 6 + totalBits *= 8 + t = tellFrac(ec) + for i = start, endb - 1 do + local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM + local quanta = imin(width * 8, imax(48, width)) + local loopLogp = dynallocLogp + local boost = 0 + while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do + local flag = decBitLogp(ec, loopLogp) + t = tellFrac(ec) + if not flag then + break + end + boost += quanta + totalBits -= quanta + loopLogp = 1 + end + offsets[i + 1] = boost + if boost > 0 then + dynallocLogp = imax(2, dynallocLogp - 1) + end + end + local allocTrim = if t + 48 <= totalBits then decIcdf(ec, TRIM_ICDF, 1, 7) else 5 + local bits = len * 64 - tellFrac(ec) - 1 + local antiCollapseRsv = if isTransient and LM >= 2 and bits >= (LM + 2) * 8 then 8 else 0 + bits -= antiCollapseRsv + local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY + local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, + pulses, fineQuant, finePriority, C, LM, ec) + unquantFineEnergy(st, start, endb, fineQuant, ec, C) + + -- shift the decoder memory by one frame + for c = 1, CC do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + + local collapse = COLLAPSE + st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, + len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) + + local antiCollapseOn = false + if antiCollapseRsv > 0 then + antiCollapseOn = decBits(ec, 1) ~= 0 + end + unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) + if antiCollapseOn then + antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) + end + if silence then + for i = 1, C * NB_EBANDS do + oldBandE[i] = -28 + end + end + + celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, CC do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, + st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.postfilter_period = postfilterPitch + st.postfilter_gain = postfilterGain + st.postfilter_tapset = postfilterTapset + if LM ~= 0 then + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + end + + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[NB_EBANDS + i] = oldBandE[i] + end + end + if not isTransient then + for i = 1, 2 * NB_EBANDS do + oldLogE2[i] = oldLogE[i] + oldLogE[i] = oldBandE[i] + end + else + for i = 1, 2 * NB_EBANDS do + oldLogE[i] = min(oldLogE[i], oldBandE[i]) + end + end + local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 + for i = 1, 2 * NB_EBANDS do + bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) + end + for c = 0, 1 do + for i = 0, start - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + for i = endb, NB_EBANDS - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + end + st.rng = ec.rng + deemphasis(st, CC, N, pcm, pbase, accum) + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NORMAL + if tell(ec) > 8 * len then + return -3 + end + if ec.error ~= 0 then + st.error = 1 + end + return frameSize +end + +return Celt +end +__FILES["codecs/audio/Opus/CeltEncoder"] = @native function() + + + +-- 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 codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. +-- Never throws. +local RE = __include("codecs/entropy/RangeCoder/Encoder") +local T = __include("codecs/audio/Opus/CeltTables") +local Mdct = __include("codecs/audio/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +-- the MDCT window (the decoder's) and plan +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + 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 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] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +@native local function pvqU(n: number, k: number): number + return U[n * UK + k + 1] +end + +@native local function imin(a: number, b: number): number + return if a < b then a else b +end +@native local function imax(a: number, b: number): number + return if a > b then a else b +end +@native local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end +@native local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end +@native local function bitexactCos(x: number): number + local x2 = (4096 + x * x) // 8192 + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +@native local function bitexactLog2tan(isin: number, icos: number): number + local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ------------------------------------------------------------------------------------------------ energy +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +@native local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number + local fl = 0 + local val = value + if val ~= 0 then + local s = if val < 0 then -1 else 0 + val = if val < 0 then -val else val + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 + local i = 1 + while fs > 0 and i < val do + fs *= 2 + fl += fs + 2 + fs = (fs * decay) // 32768 + i += 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl += (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = if s ~= 0 then -(i + di) else i + di + else + fs += 1 + if s == 0 then + fl += fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +type State = { + channels: number, + oldBandE: { number }, -- the decoder's view (2 * 21) + preMem: { number }, + inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + frames: number, + X: { { number } }, -- per channel 960 normalised coefficients + bandLogE: { number }, + bandE: { number }, -- linear band amplitudes (intensity stereo weights) + error: { number }, + work: { number }, + tmp: { number }, + iy: { number }, + remaining: number, + spread: number, + dual: boolean, -- stereo: L / R coded independently (default false: mid / side) +} + +-- new(channels) -> State +@native function CeltEncoder.new(channels: number): State + local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +@native local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (if intra then 42 else 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi += tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +@native local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(enc) + C * extra > enc.storage * 8 then + continue + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k] += offset + err[k] -= offset + end + end +end + +@native local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = if err[k] < 0 then 0 else 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k] += offset + err[k] -= offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ allocation +@native local function bits2pulses(bandI: number, lm: number, bits: number): number + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +@native local function pulses2bits(bandI: number, lm: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +@native local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +@native local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, + pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if Nw == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- ------------------------------------------------------------------------------------------------ PVQ +-- icwrs: the index of the pulse vector iy[1..n] +@native local function icwrs(n: number, iy: { number }): number + local j = n -- 1-based position of _y[n - 1] + local i = if iy[j] < 0 then 1 else 0 + local k = math.abs(iy[j]) + repeat + j -= 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i += pvqU(nn, k) + k += math.abs(iy[j]) + if iy[j] < 0 then + i += pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +@native local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p += 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p -= 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +@native local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +@native local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = if v < 0 then -v else v + sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum += absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy += p * p + xy += absx[j] * p + sign[j] = 2 * p + pulsesLeft -= p + end + end + if pulsesLeft > n + 3 then + yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] + iy[1] += pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy += 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy += absx[best] + yy += sign[best] + sign[best] += 2 + iy[best] += 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +@native local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) + -- rotate a copy (the original band stays for nothing else, but keep it intact) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +-- ------------------------------------------------------------------------------------------------ bands +@native local function computeQn(n: number, b: number, offset: number, pulseCap: number): number + local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +@native local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm -= 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid += X[xo + j] * X[xo + j] + eside += X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = (it * qn + 8192) // 16384 + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta + local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + encEncode(enc, fl, fl + fs, ft) + itheta = (itheta * 16384) // qn + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + while st.remaining < 0 and q > 0 do + st.remaining += currBits + q -= 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +@native local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid += m * m + eside += sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + @native local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = (itheta * qn + 8192) // 16384 + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = (itheta * 16384) // qn + if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +@native local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, + balance: number, enc: RE.Enc, codedBands: number, intensity: number) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance -= t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) + quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance += pulses[i + 1] + t + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel +-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) +@native function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer + local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s += X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k] *= g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + -- silence + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total += totalBits - tell(enc) + RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames += 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget -= 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames += 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder +end +__FILES["codecs/audio/Opus/CeltTables"] = function() + +-- 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, +}, +cache_index50 = { + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, + 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, + 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, + 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, + 343, 343, 343, 351, 351, 370, 376, 382, 387, +}, +cache_bits50 = { + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, + 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, + 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, + 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, + 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, + 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, + 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, + 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +}, +cache_caps50 = { + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, + 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, + 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, + 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, + 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, + 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, + 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +}, +e_prob_model = { + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, + 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, + 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, + 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, + 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, + 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, + 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, + 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, + 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, + 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, + 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, + 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, + 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +}, +} +end +__FILES["codecs/audio/Opus/Decoder"] = @native function() + + + +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") + +local Decoder = {} + +local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY +local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB +local F20, F10, F5, F2_5 = 960, 480, 240, 120 +local min, max = math.min, math.max +local readu8 = buffer.readu8 + +local WINDOW = Celt.window +local TRANS = table.create(F5 * 2, 0) +local REDUND = table.create(F5 * 2, 0) +local SILKTMP = table.create(F10 * 2, 0) +local SILENCE = buffer.create(2) +buffer.writeu8(SILENCE, 0, 0xFF) +buffer.writeu8(SILENCE, 1, 0xFF) +local EMPTY_EC = RD.new(buffer.create(0), 0, 0) +local OFFS = table.create(48, 0) +local SIZES = table.create(48, 0) + +type State = { + channels: number, + celt: any, + silk: any, + ctrl: any, + stream_channels: number, + frame_size: number, + mode: number, + bandwidth: number, + prev_mode: number, + prev_redundancy: boolean, + last_packet_duration: number, + rangeFinal: number, +} + +@native function Decoder.new(channels: number): State + return { + channels = channels, + celt = Celt.new(channels), + silk = Silk.new(channels), + ctrl = { + nChannelsAPI = channels, + nChannelsInternal = channels, + API_sampleRate = 48000, + internalSampleRate = 16000, + payloadSize_ms = 20, + }, + stream_channels = channels, + frame_size = 120, + mode = 0, + bandwidth = 0, + prev_mode = 0, + prev_redundancy = false, + last_packet_duration = 0, + rangeFinal = 0, + } +end + +@native function Decoder.reset(st: State) + Celt.reset(st.celt) + Silk.reset(st.silk) + st.stream_channels = st.channels + st.frame_size = 120 + st.mode = 0 + st.bandwidth = 0 + st.prev_mode = 0 + st.prev_redundancy = false + st.last_packet_duration = 0 + st.rangeFinal = 0 +end + +-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel +@native local function smoothFade(in1: { number }, b1: number, in2: { number }, b2: number, out: { number }, bo: number, overlap: number, ch: number) + for c = 0, ch - 1 do + for i = 0, overlap - 1 do + local w = WINDOW[i + 1] + w *= w + local k = i * ch + c + out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] + end + end +end + +@native local function decodeFrame(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local ch = st.channels + local celt = st.celt + if frameSize < F2_5 then + return -2 + end + frameSize = min(frameSize, 2880) + local data = buf + if len <= 1 then + data = nil + frameSize = min(frameSize, st.frame_size) + end + local audiosize, mode, bandwidth + local dec = EMPTY_EC + if data then + audiosize = st.frame_size + mode = st.mode + bandwidth = st.bandwidth + dec = RD.new(data, off, len) + else + audiosize = frameSize + mode = if st.prev_redundancy then MODE_CELT else st.prev_mode + bandwidth = 0 + if mode == 0 then + for i = 0, audiosize * ch - 1 do + pcm[pbase + i] = 0 + end + return audiosize + end + if audiosize > F20 then + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) + if ret < 0 then + return ret + end + pbase += ret * ch + audiosize -= ret + until audiosize <= 0 + return frameSize + elseif audiosize < F20 then + if audiosize > F10 then + audiosize = F10 + elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then + audiosize = F5 + end + end + end + local celtAccum = mode ~= MODE_CELT + local transition = false + if data and st.prev_mode > 0 + and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) + or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then + transition = true + end + if transition and mode == MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if audiosize > frameSize then + return -1 + end + frameSize = audiosize + + -- SILK + if mode ~= MODE_CELT then + local tooSmall = frameSize < F10 + local sarr, sbase = pcm, pbase + if tooSmall then + sarr, sbase = SILKTMP, 1 + end + if st.prev_mode == MODE_CELT then + Silk.reset(st.silk) + end + local ctrl = st.ctrl + ctrl.payloadSize_ms = max(10, 1000 * audiosize // 48000) + if data then + ctrl.nChannelsInternal = st.stream_channels + if mode == MODE_SILK then + ctrl.internalSampleRate = if bandwidth == BW_NB then 8000 elseif bandwidth == BW_MB then 12000 else 16000 + else + ctrl.internalSampleRate = 16000 + end + end + local lost = if data == nil then 1 else 0 + local decoded = 0 + repeat + local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) + if ret ~= 0 or n <= 0 then + if lost ~= 0 or n <= 0 then + n = frameSize - decoded + for i = 0, n * ch - 1 do + sarr[sbase + decoded * ch + i] = 0 + end + else + return -3 + end + end + decoded += n + until decoded >= frameSize + if tooSmall then + for i = 0, frameSize * ch - 1 do + pcm[pbase + i] = SILKTMP[i + 1] + end + end + end + + local startBand = 0 + local redundancy, celtToSilk = false, false + local redundancyBytes = 0 + if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (if mode == MODE_HYBRID then 20 else 0) <= 8 * len then + if mode == MODE_HYBRID then + redundancy = RD.bitLogp(dec, 12) + else + redundancy = true + end + if redundancy then + celtToSilk = RD.bitLogp(dec, 1) + redundancyBytes = if mode == MODE_HYBRID then RD.uint(dec, 256) + 2 else len - bit32.rshift(RD.tell(dec) + 7, 3) + len -= redundancyBytes + if len * 8 < RD.tell(dec) then + len = 0 + redundancyBytes = 0 + redundancy = false + end + dec.storage -= redundancyBytes + end + end + if mode ~= MODE_CELT then + startBand = 17 + end + if redundancy then + transition = false + end + if transition and mode ~= MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if bandwidth ~= 0 then + celt["end"] = if bandwidth == BW_NB then 13 elseif bandwidth == BW_MB or bandwidth == BW_WB then 17 elseif bandwidth == BW_SWB then 19 else 21 + end + celt.stream_channels = st.stream_channels + local redundantRng = 0 + if redundancy and celtToSilk then + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + end + celt.start = startBand + local celtRet = 0 + if mode ~= MODE_SILK then + local celtFrameSize = min(F20, frameSize) + if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then + Celt.reset(celt) + end + celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, if data then dec else nil, celtAccum) + st.rangeFinal = celt.rng + else + if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then + celt.start = 0 + Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) + end + st.rangeFinal = if data then dec.rng else 0 + end + if redundancy and not celtToSilk then + Celt.reset(celt) + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + local b = pbase + ch * (frameSize - F2_5) + smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) + end + if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then + for i = 0, F2_5 * ch - 1 do + pcm[pbase + i] = REDUND[1 + i] + end + smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + end + if transition then + if audiosize >= F5 then + for i = 0, ch * F2_5 - 1 do + pcm[pbase + i] = TRANS[1 + i] + end + smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + else + smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) + end + end + if len <= 1 then + st.rangeFinal = 0 + else + st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) + end + st.prev_mode = mode + st.prev_redundancy = redundancy and not celtToSilk + if celtRet < 0 then + return celtRet + end + return audiosize +end + +-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. +-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +@native function Decoder.decode(st: State, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number, selfDelimited: boolean?): (number, number) + local ch = st.channels + if buf == nil or len == 0 then + if frameSize % 120 ~= 0 then + return -1, 0 + end + local count = 0 + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) + if ret <= 0 then + return if ret < 0 then ret else -3, 0 + end + count += ret + until count >= frameSize + st.last_packet_duration = count + return count, 0 + end + local b = buf :: buffer + local toc = readu8(b, off) + local packetMode = Packet.mode(toc) + local packetBandwidth = Packet.bandwidth(toc) + local packetFrameSize = Packet.samplesPerFrame(toc, 48000) + local packetChannels = Packet.channels(toc) + local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) + if count < 0 then + return -4, 0 + end + if count * packetFrameSize > frameSize then + return -2, 0 + end + st.mode = packetMode + st.bandwidth = packetBandwidth + st.frame_size = packetFrameSize + st.stream_channels = packetChannels + local nb = 0 + for i = 1, count do + local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) + if ret < 0 then + return ret, 0 + end + nb += ret + end + st.last_packet_duration = nb + return nb, packetOffset +end + +-- --------------------------------------------------------------------------------------------------------------- +-- multistream (channel mapping families 0 / 1 / 255) + +type MS = { + channels: number, + streams: number, + coupled: number, + mapping: { number }, + decoders: { State }, + tmp: { number }, +} + +@native function Decoder.newMultistream(channels: number, streams: number, coupled: number, mapping: { number }): MS + local decs = {} + for s = 0, streams - 1 do + decs[s + 1] = Decoder.new(if s < coupled then 2 else 1) + end + return { + channels = channels, + streams = streams, + coupled = coupled, + mapping = mapping, + decoders = decs, + tmp = table.create(5760 * 2, 0), + } +end + +@native function Decoder.resetMultistream(ms: MS) + for _, d in ms.decoders do + Decoder.reset(d) + end +end + +-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` +@native local function copyOut(ms: MS, id: number, src: { number }, sc: number, sstride: number, pcm: { number }, pbase: number, n: number) + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == id then + local o = pbase + c + local s = 1 + sc + for _ = 1, n do + pcm[o] = src[s] + o += nch + s += sstride + end + end + end +end + +-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +@native function Decoder.decodeMultistream(ms: MS, buf: buffer?, off: number, len: number, pcm: { number }, pbase: number, frameSize: number): number + local doPlc = buf == nil or len == 0 + frameSize = min(frameSize, 5760) + if not doPlc and len < 2 * ms.streams - 1 then + return -4 + end + local tmp = ms.tmp + for s = 0, ms.streams - 1 do + local d = ms.decoders[s + 1] + if not doPlc and len <= 0 then + return -3 + end + local ret, packetOffset = Decoder.decode(d, if doPlc then nil else buf, off, if doPlc then 0 else len, tmp, 1, frameSize, s ~= ms.streams - 1) + if not doPlc then + off += packetOffset + len -= packetOffset + end + if ret <= 0 then + return if ret < 0 then ret else -3 + end + frameSize = ret + if s < ms.coupled then + copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) + copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) + else + copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) + end + end + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == 255 then + local o = pbase + c + for _ = 1, frameSize do + pcm[o] = 0 + o += nch + end + end + end + return frameSize +end + +-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o +@native function Decoder.writeF32(src: { number }, base: number, count: number, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + if gain == 1 then + for i = base + 1, base + count do + writef32(out, o, src[i]) + o += 4 + end + else + for i = base + 1, base + count do + writef32(out, o, src[i] * gain) + o += 4 + end + end +end + +-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the +-- left / right weights of channel c. Writes f32 to out from byte offset o. +@native function Decoder.writeDownmix(src: { number }, base: number, n: number, srcCh: number, matrix: { number }, gain: number, out: buffer, o: number) + local writef32 = buffer.writef32 + local p = base + for _ = 1, n do + local l, r = 0, 0 + for c = 0, srcCh - 1 do + local v = src[p + c + 1] + l += v * matrix[c * 2 + 1] + r += v * matrix[c * 2 + 2] + end + writef32(out, o, l * gain) + writef32(out, o + 4, r * gain) + o += 8 + p += srcCh + end +end + +return Decoder +end +__FILES["codecs/audio/Opus/Mdct"] = @native function() + + + +-- 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 + +type Plan = { + n: number, -- FFT size (N / 4) + factors: { number }, + bitrev: { number }, + twr: { number }, + twi: { number }, + trig: { number }, -- MDCT twiddles: (-sin, cos) pairs, N / 2 values + fr: { number }, + fi: { number }, +} + +local FACTORS = { + [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, + [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, + [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, + [3] = { 5, 12, 3, 4, 4, 1 }, +} + +@native local function bitrevTable(f: { number }, fout: number, fpos: number, fstride: number, factors: { number }, fi: number) + local p = factors[fi] + local m = factors[fi + 1] + if m == 1 then + for j = 0, p - 1 do + f[fpos + 1] = fout + j + fpos += fstride + end + else + for j = 0, p - 1 do + bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) + fpos += fstride + fout += m + end + end +end + +local plans: { Plan } = {} +for shift = 0, 3 do + local N = 1920 // 2 ^ shift + local n = N // 4 + local factors = FACTORS[shift] + local bitrev = table.create(n, 0) + bitrevTable(bitrev, 0, 0, 1, factors, 1) + local twr, twi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local ph = -2 * pi * k / n + twr[k + 1] = cos(ph) + twi[k + 1] = sin(ph) + end + local N2, N4 = N // 2, N // 4 + local trig = table.create(N2, 0) + for i = 0, N4 - 1 do + trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) + trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) + end + plans[shift + 1] = { + n = n, + factors = factors, + bitrev = bitrev, + twr = twr, + twi = twi, + trig = trig, + fr = table.create(n, 0), + fi = table.create(n, 0), + } +end + +@native local function bfly2(fr: { number }, fi: { number }, N: number) + local tw = 0.7071067812 + local p = 1 + for _ = 1, N do + -- k = 0 + local tr, ti = fr[p + 4], fi[p + 4] + fr[p + 4] = fr[p] - tr + fi[p + 4] = fi[p] - ti + fr[p] += tr + fi[p] += ti + -- k = 1 + local a, b = fr[p + 5], fi[p + 5] + tr = (a + b) * tw + ti = (b - a) * tw + fr[p + 5] = fr[p + 1] - tr + fi[p + 5] = fi[p + 1] - ti + fr[p + 1] += tr + fi[p + 1] += ti + -- k = 2 + tr = fi[p + 6] + ti = -fr[p + 6] + fr[p + 6] = fr[p + 2] - tr + fi[p + 6] = fi[p + 2] - ti + fr[p + 2] += tr + fi[p + 2] += ti + -- k = 3 + a, b = fr[p + 7], fi[p + 7] + tr = (b - a) * tw + ti = -(b + a) * tw + fr[p + 7] = fr[p + 3] - tr + fi[p + 7] = fi[p + 3] - ti + fr[p + 3] += tr + fi[p + 3] += ti + p += 8 + end +end + +@native local function bfly4(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + if m == 1 then + local p = 1 + for _ = 1, N do + local r0, i0 = fr[p], fi[p] + local r1, i1 = fr[p + 1], fi[p + 1] + local r2, i2 = fr[p + 2], fi[p + 2] + local r3, i3 = fr[p + 3], fi[p + 3] + local s0r, s0i = r0 - r2, i0 - i2 + r0 += r2 + i0 += i2 + local s1r, s1i = r1 + r3, i1 + i3 + fr[p + 2] = r0 - s1r + fi[p + 2] = i0 - s1i + fr[p] = r0 + s1r + fi[p] = i0 + s1i + s1r, s1i = r1 - r3, i1 - i3 + fr[p + 1] = s0r + s1i + fi[p + 1] = s0i - s1r + fr[p + 3] = s0r - s1i + fi[p + 3] = s0i + s1r + p += 4 + end + else + local m2, m3 = 2 * m, 3 * m + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2, t3 = 1, 1, 1 + for _ = 0, m - 1 do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m3], fi[p + m3] + wr, wi = twr[t3], twi[t3] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local f0r, f0i = fr[p], fi[p] + local s5r, s5i = f0r - s1r, f0i - s1i + f0r += s1r + f0i += s1i + local s3r, s3i = s0r + s2r, s0i + s2i + local s4r, s4i = s0r - s2r, s0i - s2i + fr[p + m2] = f0r - s3r + fi[p + m2] = f0i - s3i + t1 += fstride + t2 += fstride * 2 + t3 += fstride * 3 + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m] = s5r + s4i + fi[p + m] = s5i - s4r + fr[p + m3] = s5r - s4i + fi[p + m3] = s5i + s4r + p += 1 + end + end + end +end + +@native local function bfly3(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local m2 = 2 * m + local epi3i = twi[fstride * m + 1] + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2 = 1, 1 + for _ = 1, m do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local s3r, s3i = s1r + s2r, s1i + s2i + local s0r, s0i = s1r - s2r, s1i - s2i + t1 += fstride + t2 += fstride * 2 + local f0r, f0i = fr[p], fi[p] + local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 + s0r *= epi3i + s0i *= epi3i + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m2] = fmr + s0i + fi[p + m2] = fmi - s0r + fr[p + m] = fmr - s0i + fi[p + m] = fmi + s0r + p += 1 + end + end +end + +@native local function bfly5(fr: { number }, fi: { number }, fstride: number, twr: { number }, twi: { number }, m: number, N: number, mm: number) + local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] + local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] + for i = 0, N - 1 do + local p0 = i * mm + 1 + local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m + for u = 0, m - 1 do + local s0r, s0i = fr[p0], fi[p0] + local k = u * fstride + local ar, ai = fr[p1], fi[p1] + local wr, wi = twr[k + 1], twi[k + 1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p2], fi[p2] + wr, wi = twr[2 * k + 1], twi[2 * k + 1] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p3], fi[p3] + wr, wi = twr[3 * k + 1], twi[3 * k + 1] + local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p4], fi[p4] + wr, wi = twr[4 * k + 1], twi[4 * k + 1] + local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr + + local s7r, s7i = s1r + s4r, s1i + s4i + local s10r, s10i = s1r - s4r, s1i - s4i + local s8r, s8i = s2r + s3r, s2i + s3i + local s9r, s9i = s2r - s3r, s2i - s3i + + fr[p0] = s0r + (s7r + s8r) + fi[p0] = s0i + (s7i + s8i) + + local s5r = s0r + (s7r * yar + s8r * ybr) + local s5i = s0i + (s7i * yar + s8i * ybr) + local s6r = s10i * yai + s9i * ybi + local s6i = -(s10r * yai + s9r * ybi) + fr[p1] = s5r - s6r + fi[p1] = s5i - s6i + fr[p4] = s5r + s6r + fi[p4] = s5i + s6i + + local s11r = s0r + (s7r * ybr + s8r * yar) + local s11i = s0i + (s7i * ybr + s8i * yar) + local s12r = s9i * yai - s10i * ybi + local s12i = s10r * ybi - s9r * yai + fr[p2] = s11r + s12r + fi[p2] = s11i + s12i + fr[p3] = s11r - s12r + fi[p3] = s11i - s12i + + p0 += 1 + p1 += 1 + p2 += 1 + p3 += 1 + p4 += 1 + end + end +end + +-- in-place forward FFT of bit-reversed input (opus_fft_impl) +@native local function fftImpl(pl: Plan) + local factors = pl.factors + local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi + local fstride = { 1 } + local L = 0 + local m + repeat + local p = factors[2 * L + 1] + m = factors[2 * L + 2] + fstride[L + 2] = fstride[L + 1] * p + L += 1 + until m == 1 + m = factors[2 * L] + for i = L - 1, 0, -1 do + local m2 = if i ~= 0 then factors[2 * i] else 1 + local radix = factors[2 * i + 1] + if radix == 2 then + bfly2(fr, fi, fstride[i + 1]) + elseif radix == 4 then + bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + elseif radix == 3 then + bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + else + bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + end + m = m2 + end +end + +-- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of +-- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first +-- `overlap` samples (out[outBase] is sample 0). +@native function Mdct.backward(inp: { number }, inBase: number, out: { number }, outBase: number, window: { number }, overlap: number, shift: number, stride: number) + local pl = plans[shift + 1] + local N4 = pl.n + local N2 = N4 * 2 + local trig = pl.trig + local bitrev = pl.bitrev + local fr, fi = pl.fr, pl.fi + -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) + local xp1 = inBase + local xp2 = inBase + stride * (N2 - 1) + for i = 0, N4 - 1 do + local x1 = inp[xp1] + local x2 = inp[xp2] + local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] + local rev = bitrev[i + 1] + 1 + fi[rev] = x2 * t1 + x1 * t0 + fr[rev] = x1 * t1 - x2 * t0 + xp1 += 2 * stride + xp2 -= 2 * stride + end + fftImpl(pl) + -- post-rotate + local h = outBase + (overlap // 2) + for k = 0, N4 - 1 do + local re = fi[k + 1] + local im = fr[k + 1] + local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] + out[h + 2 * k] = re * t1 + im * t0 + out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 + end + -- mirror on both sides for TDAC + local xp = outBase + overlap - 1 + local yp = outBase + for i = 0, overlap // 2 - 1 do + local x1 = out[xp] + local x2 = out[yp] + local w1 = window[i + 1] + local w2 = window[overlap - i] + out[yp] = x2 * w2 - x1 * w1 + out[xp] = x2 * w1 + x1 * w2 + xp -= 1 + yp += 1 + end +end + +return Mdct +end +__FILES["codecs/audio/Opus/Packet"] = @native function() + + + +-- 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 +local band, rshift = bit32.band, bit32.rshift + +Packet.MODE_SILK_ONLY = 1000 +Packet.MODE_HYBRID = 1001 +Packet.MODE_CELT_ONLY = 1002 + +-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) +Packet.BW_NB = 1101 +Packet.BW_MB = 1102 +Packet.BW_WB = 1103 +Packet.BW_SWB = 1104 +Packet.BW_FB = 1105 + +@native function Packet.mode(toc: number): number + if band(toc, 0x80) ~= 0 then + return Packet.MODE_CELT_ONLY + elseif band(toc, 0x60) == 0x60 then + return Packet.MODE_HYBRID + else + return Packet.MODE_SILK_ONLY + end +end + +@native function Packet.bandwidth(toc: number): number + if band(toc, 0x80) ~= 0 then + local bw = 1102 + band(rshift(toc, 5), 3) + if bw == 1102 then + bw = 1101 + end + return bw + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x10) ~= 0 then 1105 else 1104 + else + return 1101 + band(rshift(toc, 5), 3) + end +end + +@native function Packet.channels(toc: number): number + return if band(toc, 4) ~= 0 then 2 else 1 +end + +-- samples per frame at rate Fs +@native function Packet.samplesPerFrame(toc: number, Fs: number): number + if band(toc, 0x80) ~= 0 then + local a = band(rshift(toc, 3), 3) + return bit32.lshift(Fs, a) // 400 + elseif band(toc, 0x60) == 0x60 then + return if band(toc, 0x08) ~= 0 then Fs // 50 else Fs // 100 + else + local a = band(rshift(toc, 3), 3) + if a == 3 then + return Fs * 60 // 1000 + end + return bit32.lshift(Fs, a) // 100 + end +end + +-- total samples of a packet at 48 kHz, or -1 if invalid +@native function Packet.samples(buf: buffer, off: number, len: number): number + if len < 1 then + return -1 + end + local toc = readu8(buf, off) + local c = band(toc, 3) + local count + if c == 0 then + count = 1 + elseif c ~= 3 then + count = 2 + else + if len < 2 then + return -1 + end + count = band(readu8(buf, off + 1), 0x3F) + end + local n = count * Packet.samplesPerFrame(toc, 48000) + if n * 25 > 48000 * 3 then + return -1 + end + return n +end + +@native local function parseSize(buf: buffer, p: number, len: number): (number, number) + if len < 1 then + return -1, -1 + end + local b0 = readu8(buf, p) + if b0 < 252 then + return 1, b0 + elseif len < 2 then + return -1, -1 + end + return 2, 4 * readu8(buf, p + 1) + b0 +end + +-- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and +-- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in +-- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +@native function Packet.parse(buf: buffer, off: number, len: number, offsets: { number }, sizes: { number }, selfDelimited: boolean?): (number, number, number) + if len < 1 then + return -1, 0, 0 + end + local toc = readu8(buf, off) + local framesize = Packet.samplesPerFrame(toc, 48000) + local p = off + 1 + len -= 1 + local lastSize = len + local count + local cbr = false + local pad = 0 + local c = band(toc, 3) + if c == 0 then + count = 1 + elseif c == 1 then + count = 2 + cbr = true + if not selfDelimited then + if band(len, 1) ~= 0 then + return -1, toc, 0 + end + lastSize = len // 2 + sizes[1] = lastSize + end + elseif c == 2 then + count = 2 + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[1] = s + p += bytes + lastSize = len - s + else + if len < 1 then + return -1, toc, 0 + end + local ch = readu8(buf, p) + p += 1 + count = band(ch, 0x3F) + if count <= 0 or framesize * count > 5760 then + return -1, toc, 0 + end + len -= 1 + if band(ch, 0x40) ~= 0 then + local pb + repeat + if len <= 0 then + return -1, toc, 0 + end + pb = readu8(buf, p) + p += 1 + len -= 1 + local tmp = if pb == 255 then 254 else pb + len -= tmp + pad += tmp + until pb ~= 255 + end + if len < 0 then + return -1, toc, 0 + end + cbr = band(ch, 0x80) == 0 + if not cbr then + lastSize = len + for i = 1, count - 1 do + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[i] = s + p += bytes + lastSize -= bytes + s + end + if lastSize < 0 then + return -1, toc, 0 + end + elseif not selfDelimited then + lastSize = len // count + if lastSize * count ~= len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = lastSize + end + end + end + if selfDelimited then + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len -= bytes + if s < 0 or s > len then + return -1, toc, 0 + end + p += bytes + sizes[count] = s + if cbr then + if s * count > len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = s + end + elseif bytes + s > lastSize then + return -1, toc, 0 + end + else + if lastSize > 1275 then + return -1, toc, 0 + end + sizes[count] = lastSize + end + for i = 1, count do + offsets[i] = p + p += sizes[i] + end + return count, toc, pad + (p - off) +end + +return Packet +end +__FILES["codecs/audio/Opus/Silk"] = @native function() + + + +-- 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/. +-- +-- local st = Silk.new(apiChannels) +-- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) +-- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } +-- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array +-- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. +-- +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local T = __include("codecs/audio/Opus/SilkTables") + +local icdf = RD.icdf +local bitLogp = RD.bitLogp +local countlz = bit32.countlz +local floor = math.floor + +local Silk = {} + +local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +for s = 1, 63 do + P2[s] = 2 ^ s +end +@native local function p2(s: number): number + if s == 0 then + return 1 + end + return P2[s] +end + +-- C helpers ----------------------------------------------------------------------------------------------------- + +@native local function s16(x: number): number + x = x % 65536 + if x >= 32768 then + return x - 65536 + end + return x +end + +@native local function i32(x: number): number + x = x % 4294967296 + if x >= 2147483648 then + return x - 4294967296 + end + return x +end + +@native local function sat16(x: number): number + if x > 32767 then + return 32767 + elseif x < -32768 then + return -32768 + end + return x +end + +@native local function addSat32(a: number, b: number): number + local s = a + b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +@native local function subSat32(a: number, b: number): number + local s = a - b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +-- silk_CLZ32 of a non-negative int32 +@native local function clz32(x: number): number + return countlz(x) +end + +-- silk_SMULWW (64-bit form): (a * b) >> 16, exact +@native local function mulww(a: number, b: number): number + return a * (b // 65536) + (a * (b % 65536)) // 65536 +end + +-- floor(a * b / 2^s) for int32 a, b and s >= 16, exact +@native local function mulshr(a: number, b: number, s: number): number + local t = a * (b // 65536) + (a * (b % 65536)) // 65536 + if s == 16 then + return t + end + return t // P2[s - 16] +end + +@native local function smmul(a: number, b: number): number + return mulshr(a, b, 32) +end + +-- silk_RSHIFT_ROUND (shift >= 1) +@native local function rround(a: number, s: number): number + return (a + p2(s - 1)) // P2[s] +end + +@native local function lshiftSat32(a: number, sh: number): number + if sh == 0 then + return a + end + local m = P2[sh] + local lo, hi = -2147483648 // m, 2147483647 // m + if a < lo then + a = lo + elseif a > hi then + a = hi + end + return a * m +end + +-- C integer division (truncation toward zero) +@native local function tdiv(a: number, b: number): number + local q = a / b + if q >= 0 then + return floor(q) + end + return -floor(-q) +end + +-- low 32 bits of a * b, as int32 +@native local function imul32(a: number, b: number): number + a = a % 4294967296 + local ah, al = a // 65536, a % 65536 + return i32(((ah * b) % 65536) * 65536 + al * b) +end + +@native local function silkRand(seed: number): number + return i32(907633515 + imul32(seed, 196314165)) +end + +@native local function rshift(a: number, s: number): number + if s == 0 then + return a + end + return a // P2[s] +end + +@native local function silkINVERSE32_varQ(b32: number, Qres: number): number + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = b32_inv * 65536 + local err_Q32 = i32((536870912 - (b32_nrm * b32_inv) // 65536) * 8) + result = i32(result + mulww(err_Q32, b32_inv)) + local lshift = 61 - b_headrm - Qres + if lshift <= 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return result // P2[lshift] + end + return 0 +end + +@native local function silkDIV32_varQ(a32: number, b32: number, Qres: number): number + local a_headrm = clz32(math.abs(a32)) - 1 + local a32_nrm = a32 * p2(a_headrm) + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, b32_nrm // 65536) + local result = (a32_nrm * s16(b32_inv)) // 65536 + a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) + result = result + (a32_nrm * s16(b32_inv)) // 65536 + local lshift = 29 + a_headrm - b_headrm - Qres + if lshift < 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return rshift(result, lshift) + end + return 0 +end + +@native local function silkLog2lin(inLog_Q7: number): number + if inLog_Q7 < 0 then + return 0 + elseif inLog_Q7 >= 3967 then + return 2147483647 + end + local out = p2(inLog_Q7 // 128) + local frac_Q7 = inLog_Q7 % 128 + local t = frac_Q7 + (frac_Q7 * (128 - frac_Q7) * -174) // 65536 + if inLog_Q7 < 2048 then + out = out + (out * t) // 128 + else + out = out + (out // 128) * t + end + return out +end + +@native local function silkSQRT_APPROX(x: number): number + if x <= 0 then + return 0 + end + local lz = clz32(x) + local rot = 24 - lz + local r + if rot == 0 then + r = x + elseif rot < 0 then + r = bit32.lrotate(x, -rot) + else + r = bit32.rrotate(x, rot) + end + local frac_Q7 = bit32.band(r, 0x7f) + local y = if bit32.band(lz, 1) ~= 0 then 32768 else 46214 + y = y // p2(lz // 2) + y = y + (y * (213 * frac_Q7)) // 65536 + return y +end + +-- silk_sum_sqr_shift: energy, shift +@native local function sumSqrShift(x: { number }, xo: number, len: number): (number, number) + local shft = 31 - clz32(len) + local nrg = len + local i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + shft = math.max(0, shft + 3 - clz32(nrg)) + nrg = 0 + i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i += 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + return nrg, shft +end + +-- LPC helpers --------------------------------------------------------------------------------------------------- + +-- silk_bwexpander (int16 coefficients), ar 1-based +@native local function bwexpander(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = s16((chirp_Q16 * ar[i] + 32768) // 65536) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = s16((chirp_Q16 * ar[d] + 32768) // 65536) +end + +@native local function bwexpander32(ar: { number }, d: number, chirp_Q16: number) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = i32(mulww(chirp_Q16, ar[i])) + chirp_Q16 += (chirp_Q16 * chirp_minus_one_Q16 + 32768) // 65536 + end + ar[d] = i32(mulww(chirp_Q16, ar[d])) +end + +-- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) +@native local function lpcFit(a_QOUT: { number }, a_QIN: { number }, QOUT: number, QIN: number, d: number) + local sh = QIN - QOUT + local idx = 0 + local i = 0 + while i < 10 do + local maxabs = 0 + for k = 1, d do + local absval = math.abs(a_QIN[k]) + if absval > maxabs then + maxabs = absval + idx = k - 1 + end + end + maxabs = rround(maxabs, sh) + if maxabs > 32767 then + maxabs = math.min(maxabs, 163838) + local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, (maxabs * (idx + 1)) // 4) + bwexpander32(a_QIN, d, chirp_Q16) + else + break + end + i += 1 + end + if i == 10 then + for k = 1, d do + a_QOUT[k] = sat16(rround(a_QIN[k], sh)) + a_QIN[k] = a_QOUT[k] * P2[sh] + end + else + for k = 1, d do + a_QOUT[k] = s16(rround(a_QIN[k], sh)) + end + end +end + +local A_LIMIT = 16773022 +local INV_GAIN_MIN = 107374 +local Atmp_QA = table.create(16, 0) + +-- RSHIFT_ROUND64(SMULL(a, b), Q) +@native local function mulRound(a: number, b: number, Q: number): number + if Q == 1 then + local p = a * b + return p // 2 + p % 2 + end + if Q - 1 >= 16 then + return (mulshr(a, b, Q - 1) + 1) // 2 + end + return ((a * b) // P2[Q - 1] + 1) // 2 +end + +@native local function lpcInversePredGainQA(A_QA: { number }, order: number): number + local invGain_Q30 = 1073741824 + local k = order - 1 + while k > 0 do + local ak = A_QA[k + 1] + if ak > A_LIMIT or ak < -A_LIMIT then + return 0 + end + local rc_Q31 = -(ak * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) + local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) + for n = 0, (k + 1) // 2 - 1 do + local tmp1 = A_QA[n + 1] + local tmp2 = A_QA[k - n] + local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[n + 1] = t64 + t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[k - n] = t64 + end + k -= 1 + end + local a0 = A_QA[1] + if a0 > A_LIMIT or a0 < -A_LIMIT then + return 0 + end + local rc_Q31 = -(a0 * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + return invGain_Q30 +end + +@native local function lpcInversePredGain(A_Q12: { number }, order: number): number + local DC_resp = 0 + for k = 1, order do + DC_resp += A_Q12[k] + Atmp_QA[k] = A_Q12[k] * 4096 + end + if DC_resp >= 4096 then + return 0 + end + return lpcInversePredGainQA(Atmp_QA, order) +end + +local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } +local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } +local cos_LSF_QA = table.create(16, 0) +local polyP = table.create(9, 0) +local polyQ = table.create(9, 0) +local a32_QA1 = table.create(16, 0) +local LSFCos = T.LSFCosTab_FIX_Q12 + +-- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 +@native local function findPoly(out: { number }, cLSF: { number }, c0: number, dd: number) + out[1] = 65536 + out[2] = -cLSF[c0 + 1] + for k = 1, dd - 1 do + local ftmp = cLSF[c0 + 2 * k + 1] + out[k + 2] = out[k] * 2 - (ftmp * out[k + 1] + 32768) // 65536 + for n = k, 2, -1 do + out[n + 1] += out[n - 1] - (ftmp * out[n] + 32768) // 65536 + end + out[2] -= ftmp + end +end + +-- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) +@native local function nlsf2a(a_Q12: { number }, NLSF: { number }, d: number) + local ordering = if d == 16 then ordering16 else ordering10 + for k = 1, d do + local nl = NLSF[k] + local f_int = nl // 256 + local f_frac = nl - f_int * 256 + local cos_val = LSFCos[f_int + 1] + local delta = LSFCos[f_int + 2] - cos_val + cos_LSF_QA[ordering[k] + 1] = (cos_val * 256 + delta * f_frac + 8) // 16 + end + local dd = d // 2 + findPoly(polyP, cos_LSF_QA, 0, dd) + findPoly(polyQ, cos_LSF_QA, 1, dd) + for k = 0, dd - 1 do + local Ptmp = polyP[k + 2] + polyP[k + 1] + local Qtmp = polyQ[k + 2] - polyQ[k + 1] + a32_QA1[k + 1] = -Qtmp - Ptmp + a32_QA1[d - k] = Qtmp - Ptmp + end + lpcFit(a_Q12, a32_QA1, 12, 17, d) + local i = 0 + while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do + bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) + for k = 1, d do + a_Q12[k] = s16((a32_QA1[k] + 16) // 32) + end + i += 1 + end +end + +-- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 +@native local function lpcAnalysisFilter(out: { number }, oo: number, inp: { number }, io: number, B: { number }, len: number, d: number) + for ix = d, len - 1 do + local base = io + ix - 1 + local acc = 0 + for j = 0, d - 1 do + acc += inp[base - j] * B[j + 1] + end + local out32_Q12 = i32(inp[base + 1] * 4096 - acc) + out[oo + ix] = sat16((out32_Q12 + 2048) // 4096) + end + for j = 0, d - 1 do + out[oo + j] = 0 + end +end + +-- NLSF ---------------------------------------------------------------------------------------------------------- + +local CB_NB_MB = { + nVectors = 32, + order = 10, + quantStepSize_Q16 = 11796, + CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, + pred_Q8 = T.NLSF_PRED_NB_MB_Q8, + ec_sel = T.NLSF_CB2_SELECT_NB_MB, + ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, +} +local CB_WB = { + nVectors = 32, + order = 16, + quantStepSize_Q16 = 9830, + CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_WB, + pred_Q8 = T.NLSF_PRED_WB_Q8, + ec_sel = T.NLSF_CB2_SELECT_WB, + ec_iCDF = T.NLSF_CB2_iCDF_WB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, +} + +local ec_ix = table.create(16, 0) +local pred_Q8 = table.create(16, 0) +local res_Q10 = table.create(16, 0) + +@native local function nlsfUnpack(CB: any, CB1_index: number) + local order = CB.order + local sel = CB.ec_sel + local pq = CB.pred_Q8 + local p = CB1_index * order // 2 + for i = 0, order - 1, 2 do + p += 1 + local entry = sel[p] + ec_ix[i + 1] = (bit32.band(entry // 2, 7)) * 9 + pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] + ec_ix[i + 2] = (bit32.band(entry // 32, 7)) * 9 + pred_Q8[i + 2] = pq[i + bit32.band(entry // 16, 1) * (order - 1) + 2] + end +end + +@native local function nlsfStabilize(NLSF: { number }, NDeltaMin: { number }, L: number) + local loops = 0 + while loops < 20 do + local min_diff = NLSF[1] - NDeltaMin[1] + local I = 0 + for i = 1, L - 1 do + local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) + if diff < min_diff then + min_diff = diff + I = i + end + end + local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) + if diff < min_diff then + min_diff = diff + I = L + end + if min_diff >= 0 then + return + end + if I == 0 then + NLSF[1] = NDeltaMin[1] + elseif I == L then + NLSF[L] = 32768 - NDeltaMin[L + 1] + else + local min_center = 0 + for k = 0, I - 1 do + min_center += NDeltaMin[k + 1] + end + min_center += NDeltaMin[I + 1] // 2 + local max_center = 32768 + for k = L, I + 1, -1 do + max_center -= NDeltaMin[k + 1] + end + max_center -= NDeltaMin[I + 1] // 2 + local c = (NLSF[I] + NLSF[I + 1] + 1) // 2 + -- silk_LIMIT_32(c, min_center, max_center) + if min_center > max_center then + if c > min_center then + c = min_center + elseif c < max_center then + c = max_center + end + else + if c > max_center then + c = max_center + elseif c < min_center then + c = min_center + end + end + c = s16(c) + NLSF[I] = s16(c - NDeltaMin[I + 1] // 2) + NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) + end + loops += 1 + end + -- fall back: insertion sort, then clamp + for i = 2, L do + local value = NLSF[i] + local j = i - 1 + while j >= 1 and value < NLSF[j] do + NLSF[j + 1] = NLSF[j] + j -= 1 + end + NLSF[j + 1] = value + end + NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) + for i = 2, L do + NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) + end + NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) + for i = L - 1, 1, -1 do + NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) + end +end + +-- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) +@native local function nlsfDecode(pNLSF_Q15: { number }, NLSFIndices: { number }, CB: any) + nlsfUnpack(CB, NLSFIndices[1]) + local order = CB.order + local step = CB.quantStepSize_Q16 + local out_Q10 = 0 + for i = order - 1, 0, -1 do + local pred = (out_Q10 * pred_Q8[i + 1]) // 256 + out_Q10 = NLSFIndices[i + 2] * 1024 + if out_Q10 > 0 then + out_Q10 -= 102 + elseif out_Q10 < 0 then + out_Q10 += 102 + end + out_Q10 = pred + (out_Q10 * step) // 65536 + res_Q10[i + 1] = out_Q10 + end + local base = NLSFIndices[1] * order + local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 + for i = 1, order do + local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 + if v < 0 then + v = 0 + elseif v > 32767 then + v = 32767 + end + pNLSF_Q15[i] = v + end + nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) +end + +-- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- + +local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 +local up2_hq_0 = { 1746, 14986, 39083 - 65536 } +local up2_hq_1 = { 6854, 25769, 55542 - 65536 } +local FIR12 = T.resampler_frac_FIR_12 +local delay_matrix_dec = { + { 4, 0, 2, 0, 0, 0 }, + { 0, 9, 4, 7, 4, 4 }, + { 0, 3, 12, 7, 7, 7 }, +} + +@native local function rateID(R: number): number + local a = R // 4096 - (if R > 16000 then 1 else 0) + if R > 24000 then + a = a // 2 + end + return math.min(5, a - 1) +end + +@native local function newResampler(): any + return { + sIIR = table.create(6, 0), + sFIR = table.create(8, 0), + delayBuf = table.create(96, 0), + buf = table.create(2 * 160 + 8, 0), + resampler_function = RES_COPY, + batchSize = 0, + invRatio_Q16 = 0, + inputDelay = 0, + Fs_in_kHz = 0, + Fs_out_kHz = 0, + } +end + +@native local function copyResampler(dst: any, src: any) + for i = 1, 6 do + dst.sIIR[i] = src.sIIR[i] + end + for i = 1, 8 do + dst.sFIR[i] = src.sFIR[i] + end + for i = 1, 96 do + dst.delayBuf[i] = src.delayBuf[i] + end + dst.resampler_function = src.resampler_function + dst.batchSize = src.batchSize + dst.invRatio_Q16 = src.invRatio_Q16 + dst.inputDelay = src.inputDelay + dst.Fs_in_kHz = src.Fs_in_kHz + dst.Fs_out_kHz = src.Fs_out_kHz +end + +@native local function resamplerInit(S: any, Fs_Hz_in: number, Fs_Hz_out: number): number + table.clear(S.sIIR) + table.clear(S.sFIR) + table.clear(S.delayBuf) + for i = 1, 6 do + S.sIIR[i] = 0 + end + for i = 1, 8 do + S.sFIR[i] = 0 + end + for i = 1, 96 do + S.delayBuf[i] = 0 + end + if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then + return -1 -- the decoder only upsamples (or copies) + end + S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 + S.Fs_in_kHz = Fs_Hz_in // 1000 + S.Fs_out_kHz = Fs_Hz_out // 1000 + S.batchSize = S.Fs_in_kHz * 10 + local up2x = 0 + if Fs_Hz_out > Fs_Hz_in then + if Fs_Hz_out == Fs_Hz_in * 2 then + S.resampler_function = RES_UP2 + else + S.resampler_function = RES_IIR_FIR + up2x = 1 + end + else + S.resampler_function = RES_COPY + end + local inv = (Fs_Hz_in * p2(14 + up2x)) // Fs_Hz_out * 4 + while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do + inv += 1 + end + S.invRatio_Q16 = inv + return 0 +end + +-- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] +@native local function up2HQ(S: { number }, out: { number }, oo: number, inp: { number }, io: number, len: number) + local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] + local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] + local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] + for k = 0, len - 1 do + local in32 = inp[io + k] * 1024 + local Y = in32 - s0 + local X = (Y * c00) // 65536 + local out32_1 = s0 + X + s0 = in32 + X + Y = out32_1 - s1 + X = (Y * c01) // 65536 + local out32_2 = s1 + X + s1 = out32_1 + X + Y = out32_2 - s2 + X = Y + (Y * c02) // 65536 + out32_1 = s2 + X + s2 = out32_2 + X + out[oo + 2 * k] = sat16((out32_1 + 512) // 1024) + Y = in32 - s3 + X = (Y * c10) // 65536 + out32_1 = s3 + X + s3 = in32 + X + Y = out32_1 - s4 + X = (Y * c11) // 65536 + out32_2 = s4 + X + s4 = out32_1 + X + Y = out32_2 - s5 + X = Y + (Y * c12) // 65536 + out32_1 = s5 + X + s5 = out32_2 + X + out[oo + 2 * k + 1] = sat16((out32_1 + 512) // 1024) + end + S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 +end + +-- returns the next output index +@native local function iirFirInterpol(out: { number }, oo: number, buf: { number }, max_index_Q16: number, incr: number): number + local index_Q16 = 0 + while index_Q16 < max_index_Q16 do + local ti = ((index_Q16 % 65536) * 12) // 65536 + local b = index_Q16 // 65536 + 1 -- buf is 1-based + local f0 = ti * 4 + local f1 = (11 - ti) * 4 + local res_Q15 = buf[b] * FIR12[f0 + 1] + + buf[b + 1] * FIR12[f0 + 2] + + buf[b + 2] * FIR12[f0 + 3] + + buf[b + 3] * FIR12[f0 + 4] + + buf[b + 4] * FIR12[f1 + 4] + + buf[b + 5] * FIR12[f1 + 3] + + buf[b + 6] * FIR12[f1 + 2] + + buf[b + 7] * FIR12[f1 + 1] + out[oo] = sat16((res_Q15 + 16384) // 32768) + oo += 1 + index_Q16 += incr + end + return oo +end + +@native local function iirFir(S: any, out: { number }, oo: number, inp: { number }, io: number, inLen: number) + local buf = S.buf + local sFIR = S.sFIR + for i = 1, 8 do + buf[i] = sFIR[i] + end + local incr = S.invRatio_Q16 + local nSamplesIn + while true do + nSamplesIn = math.min(inLen, S.batchSize) + up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) + oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) + io += nSamplesIn + inLen -= nSamplesIn + if inLen > 0 then + local o = nSamplesIn * 2 + for i = 1, 8 do + buf[i] = buf[o + i] + end + else + break + end + end + local o = nSamplesIn * 2 + for i = 1, 8 do + sFIR[i] = buf[o + i] + end +end + +@native local function resampleBlock(S: any, out: { number }, oo: number, inp: { number }, io: number, len: number) + local f = S.resampler_function + if f == RES_IIR_FIR then + iirFir(S, out, oo, inp, io, len) + elseif f == RES_UP2 then + up2HQ(S.sIIR, out, oo, inp, io, len) + else + for i = 0, len - 1 do + out[oo + i] = inp[io + i] + end + end +end + +-- silk_resampler: out[1..] from inp[io .. io + inLen - 1] +@native local function resampler(S: any, out: { number }, inp: { number }, io: number, inLen: number) + local fin = S.Fs_in_kHz + local delay = S.inputDelay + local nSamples = fin - delay + local db = S.delayBuf + for i = 0, nSamples - 1 do + db[delay + i + 1] = inp[io + i] + end + resampleBlock(S, out, 1, db, 1, fin) + resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) + for i = 0, delay - 1 do + db[i + 1] = inp[io + inLen - delay + i] + end +end + +-- Decoder state ------------------------------------------------------------------------------------------------- + +@native local function newChannel(): any + return { + prev_gain_Q16 = 65536, + exc_Q14 = table.create(320, 0), + sLPC_Q14_buf = table.create(16, 0), + outBuf = table.create(480, 0), + lagPrev = 0, + LastGainIndex = 0, + fs_kHz = 0, + fs_API_hz = 0, + nb_subfr = 0, + frame_length = 0, + subfr_length = 0, + ltp_mem_length = 0, + LPC_order = 0, + prevNLSF_Q15 = table.create(16, 0), + first_frame_after_reset = 1, + pitch_lag_low_bits_iCDF = T.uniform4_iCDF, + pitch_contour_iCDF = T.pitch_contour_iCDF, + nFramesDecoded = 0, + nFramesPerPacket = 0, + ec_prevSignalType = 0, + ec_prevLagIndex = 0, + VAD_flags = { 0, 0, 0 }, + LBRR_flag = 0, + LBRR_flags = { 0, 0, 0 }, + resampler_state = newResampler(), + psNLSF_CB = CB_NB_MB, + indices = { + signalType = 0, + quantOffsetType = 0, + GainsIndices = { 0, 0, 0, 0 }, + NLSFIndices = table.create(17, 0), + NLSFInterpCoef_Q2 = 0, + lagIndex = 0, + contourIndex = 0, + PERIndex = 0, + LTPIndex = { 0, 0, 0, 0 }, + LTP_scaleIndex = 0, + Seed = 0, + }, + sCNG = { + CNG_exc_buf_Q14 = table.create(320, 0), + CNG_smth_NLSF_Q15 = table.create(16, 0), + CNG_synth_state = table.create(16, 0), + CNG_smth_Gain_Q16 = 0, + rand_seed = 3176576, + fs_kHz = 0, + }, + lossCnt = 0, + prevSignalType = 0, + sPLC = { + pitchL_Q8 = 0, + LTPCoef_Q14 = table.create(5, 0), + prevLPC_Q12 = table.create(16, 0), + last_frame_lost = 0, + rand_seed = 0, + randScale_Q14 = 0, + conc_energy = 0, + conc_energy_shift = 0, + prevLTP_scale_Q14 = 0, + prevGain_Q16 = { 65536, 65536 }, + fs_kHz = 0, + nb_subfr = 2, + subfr_length = 20, + }, + -- per-frame decoder control (silk_decoder_control) and scratch + ctrl = { + pitchL = { 0, 0, 0, 0 }, + Gains_Q16 = { 0, 0, 0, 0 }, + PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, + LTPCoef_Q14 = table.create(20, 0), + LTP_scale_Q14 = 0, + }, + pulses = table.create(336, 0), + out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] + } +end + +@native local function decoderSetFs(ch: any, fs_kHz: number, fs_API_Hz: number): number + local ret = 0 + ch.subfr_length = 5 * fs_kHz + local frame_length = ch.nb_subfr * ch.subfr_length + if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then + ret += resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) + ch.fs_API_hz = fs_API_Hz + end + if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then + if fs_kHz == 8 then + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_NB_iCDF else T.pitch_contour_10_ms_NB_iCDF + else + ch.pitch_contour_iCDF = if ch.nb_subfr == 4 then T.pitch_contour_iCDF else T.pitch_contour_10_ms_iCDF + end + if ch.fs_kHz ~= fs_kHz then + ch.ltp_mem_length = 20 * fs_kHz + if fs_kHz == 8 or fs_kHz == 12 then + ch.LPC_order = 10 + ch.psNLSF_CB = CB_NB_MB + else + ch.LPC_order = 16 + ch.psNLSF_CB = CB_WB + end + if fs_kHz == 16 then + ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF + elseif fs_kHz == 12 then + ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF + else + ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF + end + ch.first_frame_after_reset = 1 + ch.lagPrev = 100 + ch.LastGainIndex = 10 + ch.prevSignalType = 0 + local ob, sl = ch.outBuf, ch.sLPC_Q14_buf + for i = 1, 480 do + ob[i] = 0 + end + for i = 1, 16 do + sl[i] = 0 + end + end + ch.fs_kHz = fs_kHz + ch.frame_length = frame_length + end + return ret +end + +-- Bitstream: indices and pulses --------------------------------------------------------------------------------- + +local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } +local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } +local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } + +@native local function decodeIndices(ch: any, d: any, FrameIndex: number, decode_LBRR: boolean, condCoding: number) + local ind = ch.indices + local Ix + if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then + Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 + else + Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) + end + local signalType = Ix // 2 + ind.signalType = signalType + ind.quantOffsetType = Ix % 2 + local gi = ind.GainsIndices + if condCoding == 2 then + gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) + else + gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 + gi[1] += icdf(d, T.uniform8_iCDF, 1, 8) + end + for i = 2, ch.nb_subfr do + gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) + end + local CB = ch.psNLSF_CB + local ni = ind.NLSFIndices + ni[1] = icdf(d, CB.CB1_iCDF, (signalType // 2) * CB.nVectors + 1, 8) + nlsfUnpack(CB, ni[1]) + for i = 1, CB.order do + Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) + if Ix == 0 then + Ix -= icdf(d, T.NLSF_EXT_iCDF, 1, 8) + elseif Ix == 8 then + Ix += icdf(d, T.NLSF_EXT_iCDF, 1, 8) + end + ni[i + 1] = Ix - 4 + end + if ch.nb_subfr == 4 then + ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) + else + ind.NLSFInterpCoef_Q2 = 4 + end + if signalType == 2 then + local absolute = true + if condCoding == 2 and ch.ec_prevSignalType == 2 then + local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) + if delta > 0 then + ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) + absolute = false + end + end + if absolute then + ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (ch.fs_kHz // 2) + ind.lagIndex += icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) + end + ch.ec_prevLagIndex = ind.lagIndex + ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) + ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) + local tab = LTP_gain_iCDF[ind.PERIndex + 1] + for k = 1, ch.nb_subfr do + ind.LTPIndex[k] = icdf(d, tab, 1, 8) + end + if condCoding == 0 then + ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) + else + ind.LTP_scaleIndex = 0 + end + end + ch.ec_prevSignalType = signalType + ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) +end + +local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 +local shellOff = T.shell_code_table_offsets + +@native local function split(d: any, p: number, tab: { number }): (number, number) + if p > 0 then + local a = icdf(d, tab, shellOff[p + 1] + 1, 8) + return a, p - a + end + return 0, 0 +end + +@native local function shellDecoder(out: { number }, o: number, d: any, pulses4: number) + local p3a, p3b = split(d, pulses4, shell3) + local p2a, p2b = split(d, p3a, shell2) + local p1a, p1b = split(d, p2a, shell1) + out[o], out[o + 1] = split(d, p1a, shell0) + out[o + 2], out[o + 3] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 4], out[o + 5] = split(d, p1a, shell0) + out[o + 6], out[o + 7] = split(d, p1b, shell0) + p2a, p2b = split(d, p3b, shell2) + p1a, p1b = split(d, p2a, shell1) + out[o + 8], out[o + 9] = split(d, p1a, shell0) + out[o + 10], out[o + 11] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 12], out[o + 13] = split(d, p1a, shell0) + out[o + 14], out[o + 15] = split(d, p1b, shell0) +end + +local sum_pulses = table.create(20, 0) +local nLshifts = table.create(20, 0) +local signIcdf = { 0, 0 } + +-- pulses[1 .. frame_length (rounded up to 16)] +@native local function decodePulses(d: any, pulses: { number }, signalType: number, quantOffsetType: number, frame_length: number) + local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (signalType // 2) * 9 + 1, 8) + local iter = frame_length // 16 + if iter * 16 < frame_length then + iter += 1 + end + local ppb = T.pulses_per_block_iCDF + for i = 1, iter do + nLshifts[i] = 0 + local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) + while s == 17 do + nLshifts[i] += 1 + s = icdf(d, ppb, 9 * 18 + 1 + (if nLshifts[i] == 10 then 1 else 0), 8) + if nLshifts[i] > 30 then + break -- corrupt stream guard + end + end + sum_pulses[i] = s + end + for i = 1, iter do + local o = (i - 1) * 16 + 1 + if sum_pulses[i] > 0 then + shellDecoder(pulses, o, d, sum_pulses[i]) + else + for k = 0, 15 do + pulses[o + k] = 0 + end + end + end + local lsb = T.lsb_iCDF + for i = 1, iter do + local nLS = nLshifts[i] + if nLS > 0 then + local o = (i - 1) * 16 + 1 + for k = 0, 15 do + local abs_q = pulses[o + k] + for _ = 1, nLS do + abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) + end + pulses[o + k] = abs_q + end + sum_pulses[i] += nLS * 32 + end + end + -- silk_decode_signs + local signTab = T.sign_iCDF + local base = 7 * (quantOffsetType + signalType * 2) + local blocks = (frame_length + 8) // 16 + for i = 1, blocks do + local p = sum_pulses[i] + if p > 0 then + signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] + local o = (i - 1) * 16 + 1 + for j = 0, 15 do + local q = pulses[o + j] + if q > 0 then + pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) + end + end + end + end +end + +-- Parameters ---------------------------------------------------------------------------------------------------- + +local pNLSF_Q15 = table.create(16, 0) +local pNLSF0_Q15 = table.create(16, 0) + +@native local function gainsDequant(gain_Q16: { number }, ind: { number }, ch: any, conditional: boolean, nb_subfr: number) + local prev = ch.LastGainIndex + for k = 1, nb_subfr do + if k == 1 and not conditional then + prev = math.max(ind[k], prev - 16) + else + local ind_tmp = ind[k] - 4 + local thr = 8 + prev + if ind_tmp > thr then + prev += ind_tmp * 2 - thr + else + prev += ind_tmp + end + end + if prev < 0 then + prev = 0 + elseif prev > 63 then + prev = 63 + end + gain_Q16[k] = silkLog2lin(math.min((1907825 * prev) // 65536 + 2090, 3967)) + end + ch.LastGainIndex = prev +end + +local CB_lags = { + [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, + [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, +} + +@native local function decodeParameters(ch: any, ctrl: any, condCoding: number) + local ind = ch.indices + gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) + local order = ch.LPC_order + nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) + nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) + if ch.first_frame_after_reset == 1 then + ind.NLSFInterpCoef_Q2 = 4 + end + local prevNLSF = ch.prevNLSF_Q15 + if ind.NLSFInterpCoef_Q2 < 4 then + local c = ind.NLSFInterpCoef_Q2 + for i = 1, order do + pNLSF0_Q15[i] = prevNLSF[i] + (c * (pNLSF_Q15[i] - prevNLSF[i])) // 4 + end + nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) + else + local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] + for i = 1, order do + a[i] = b[i] + end + end + for i = 1, order do + prevNLSF[i] = pNLSF_Q15[i] + end + if ch.lossCnt ~= 0 then + bwexpander(ctrl.PredCoef_Q12[1], order, 63570) + bwexpander(ctrl.PredCoef_Q12[2], order, 63570) + end + if ind.signalType == 2 then + -- silk_decode_pitch + local fs = ch.fs_kHz + local cbinfo = CB_lags[if fs == 8 then 8 else 0][ch.nb_subfr] + local cb, cbk_size = cbinfo[1], cbinfo[2] + local min_lag, max_lag = 2 * fs, 18 * fs + local lag = min_lag + ind.lagIndex + for k = 0, ch.nb_subfr - 1 do + local v = lag + cb[k * cbk_size + ind.contourIndex + 1] + if v < min_lag then + v = min_lag + elseif v > max_lag then + v = max_lag + end + ctrl.pitchL[k + 1] = v + end + local vq = LTP_vq_Q7[ind.PERIndex + 1] + for k = 0, ch.nb_subfr - 1 do + local Ix = ind.LTPIndex[k + 1] + for i = 1, 5 do + ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 + end + end + ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] + else + for k = 1, ch.nb_subfr do + ctrl.pitchL[k] = 0 + end + for k = 1, 5 * ch.nb_subfr do + ctrl.LTPCoef_Q14[k] = 0 + end + ind.PERIndex = 0 + ctrl.LTP_scale_Q14 = 0 + end +end + +-- Core synthesis ------------------------------------------------------------------------------------------------ + +local sLTP = table.create(320, 0) +local sLTP_Q15 = table.create(640, 0) +local res_Q14 = table.create(80, 0) +local sLPC_Q14 = table.create(96, 0) +local A_Q12_tmp = table.create(16, 0) +local QuantOffsets = { { 100, 240 }, { 32, 100 } } + +-- silk_decode_core: xq[xo .. xo + frame_length - 1] +@native local function decodeCore(ch: any, ctrl: any, xq: { number }, xo: number, pulses: { number }) + local ind = ch.indices + local exc = ch.exc_Q14 + local offset_Q10 = QuantOffsets[ind.signalType // 2 + 1][ind.quantOffsetType + 1] + local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 + local frame_length = ch.frame_length + local subfr_length = ch.subfr_length + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local outBuf = ch.outBuf + + local rand_seed = ind.Seed + for i = 1, frame_length do + rand_seed = silkRand(rand_seed) + local p = pulses[i] + local e = p * 16384 + if e > 0 then + e -= 1280 + elseif e < 0 then + e += 1280 + end + e += offset_Q10 * 16 + if rand_seed < 0 then + e = -e + end + exc[i] = e + rand_seed = i32(rand_seed + p) + end + + local sl = ch.sLPC_Q14_buf + for i = 1, 16 do + sLPC_Q14[i] = sl[i] + end + local pexc = 0 -- C offset into exc + local pxq = xo + local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 + local lag = 0 + for k = 0, ch.nb_subfr - 1 do + local A_Q12 = ctrl.PredCoef_Q12[k // 2 + 1] + for i = 1, order do + A_Q12_tmp[i] = A_Q12[i] + end + local Bo = k * 5 -- C offset into LTPCoef_Q14 + local B = ctrl.LTPCoef_Q14 + local signalType = ind.signalType + local gain = ctrl.Gains_Q16[k + 1] + local Gain_Q10 = gain // 64 + local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) + local gain_adj_Q16 + if gain ~= ch.prev_gain_Q16 then + gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) + for i = 1, 16 do + sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) + end + else + gain_adj_Q16 = 65536 + end + ch.prev_gain_Q16 = gain + if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then + for i = 1, 5 do + B[Bo + i] = 0 + end + B[Bo + 3] = 4096 + signalType = 2 + ctrl.pitchL[k + 1] = ch.lagPrev + end + if signalType == 2 then + lag = ctrl.pitchL[k + 1] + if k == 0 or (k == 2 and NLSF_interpolation_flag) then + local start_idx = ltp_mem_length - lag - order - 2 + if start_idx < 1 then + start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) + end + if k == 2 then + for i = 0, 2 * subfr_length - 1 do + outBuf[ltp_mem_length + i + 1] = xq[xo + i] + end + end + lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) + if k == 0 then + inv_gain_Q31 = ((inv_gain_Q31 * ctrl.LTP_scale_Q14) // 65536) * 4 + end + for i = 0, lag + 1 do + sLTP_Q15[sLTP_buf_idx - i] = (inv_gain_Q31 * sLTP[ltp_mem_length - i]) // 65536 + end + else + if gain_adj_Q16 ~= 65536 then + for i = 0, lag + 1 do + local j = sLTP_buf_idx - i + sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) + end + end + end + end + local presArr, presOff + if signalType == 2 then + local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] + local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] + for i = 1, subfr_length do + local pred = 2 + pred += (sLTP_Q15[pl] * b0) // 65536 + pred += (sLTP_Q15[pl - 1] * b1) // 65536 + pred += (sLTP_Q15[pl - 2] * b2) // 65536 + pred += (sLTP_Q15[pl - 3] * b3) // 65536 + pred += (sLTP_Q15[pl - 4] * b4) // 65536 + pl += 1 + local r = exc[pexc + i] + pred * 2 + res_Q14[i] = r + sLTP_buf_idx += 1 + sLTP_Q15[sLTP_buf_idx] = r * 2 + end + presArr, presOff = res_Q14, 0 + else + presArr, presOff = exc, pexc + end + local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = + A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], + A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] + local wide = order == 16 + local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] + for i = 1, subfr_length do + local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 + local pred = order // 2 + pred += (sLPC_Q14[j - 1] * a0) // 65536 + pred += (sLPC_Q14[j - 2] * a1) // 65536 + pred += (sLPC_Q14[j - 3] * a2) // 65536 + pred += (sLPC_Q14[j - 4] * a3) // 65536 + pred += (sLPC_Q14[j - 5] * a4) // 65536 + pred += (sLPC_Q14[j - 6] * a5) // 65536 + pred += (sLPC_Q14[j - 7] * a6) // 65536 + pred += (sLPC_Q14[j - 8] * a7) // 65536 + pred += (sLPC_Q14[j - 9] * a8) // 65536 + pred += (sLPC_Q14[j - 10] * a9) // 65536 + if wide then + pred += (sLPC_Q14[j - 11] * a10) // 65536 + pred += (sLPC_Q14[j - 12] * a11) // 65536 + pred += (sLPC_Q14[j - 13] * a12) // 65536 + pred += (sLPC_Q14[j - 14] * a13) // 65536 + pred += (sLPC_Q14[j - 15] * a14) // 65536 + pred += (sLPC_Q14[j - 16] * a15) // 65536 + end + pred = i32(pred) + local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) + sLPC_Q14[j] = v + xq[pxq + i - 1] = sat16((mulww(v, Gain_Q10) + 128) // 256) + end + for i = 1, 16 do + sLPC_Q14[i] = sLPC_Q14[subfr_length + i] + end + pexc += subfr_length + pxq += subfr_length + end + for i = 1, 16 do + sl[i] = sLPC_Q14[i] + end +end + +-- PLC / CNG ----------------------------------------------------------------------------------------------------- + +local HARM_ATT_Q15 = { 32440, 31130 } +local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } +local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } + +@native local function plcReset(ch: any) + local plc = ch.sPLC + plc.pitchL_Q8 = ch.frame_length * 128 + plc.prevGain_Q16[1] = 65536 + plc.prevGain_Q16[2] = 65536 + plc.subfr_length = 20 + plc.nb_subfr = 2 +end + +@native local function cngReset(ch: any) + local step = tdiv(32767, ch.LPC_order + 1) + local acc = 0 + local cng = ch.sCNG + for i = 1, ch.LPC_order do + acc += step + cng.CNG_smth_NLSF_Q15[i] = acc + end + cng.CNG_smth_Gain_Q16 = 0 + cng.rand_seed = 3176576 +end + +@native local function plcUpdate(ch: any, ctrl: any) + local plc = ch.sPLC + local nb = ch.nb_subfr + ch.prevSignalType = ch.indices.signalType + local LTP_Gain_Q14 = 0 + local coef = plc.LTPCoef_Q14 + if ch.indices.signalType == 2 then + local j = 0 + while j * ch.subfr_length < ctrl.pitchL[nb] do + if j == nb then + break + end + local t = 0 + local o = (nb - 1 - j) * 5 + for i = 1, 5 do + t += ctrl.LTPCoef_Q14[o + i] + end + if t > LTP_Gain_Q14 then + LTP_Gain_Q14 = t + for i = 1, 5 do + coef[i] = ctrl.LTPCoef_Q14[o + i] + end + plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 + end + j += 1 + end + for i = 1, 5 do + coef[i] = 0 + end + coef[3] = LTP_Gain_Q14 + if LTP_Gain_Q14 < 11469 then + local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q10)) // 1024 + end + elseif LTP_Gain_Q14 > 15565 then + local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = (s16(coef[i]) * s16(scale_Q14)) // 16384 + end + end + else + plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 + for i = 1, 5 do + coef[i] = 0 + end + end + local p = ctrl.PredCoef_Q12[2] + for i = 1, ch.LPC_order do + plc.prevLPC_Q12[i] = p[i] + end + plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 + plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] + plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] + plc.subfr_length = ch.subfr_length + plc.nb_subfr = nb +end + +local excBuf = table.create(160, 0) +local plcLTP = table.create(320, 0) +local plcLTP_Q14 = table.create(640, 0) +local A_plc = table.create(16, 0) + +@native local function plcConceal(ch: any, ctrl: any, frame: { number }, fo: number) + local plc = ch.sPLC + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local prevGain_Q10_0 = plc.prevGain_Q16[1] // 64 + local prevGain_Q10_1 = plc.prevGain_Q16[2] // 64 + if ch.first_frame_after_reset ~= 0 then + for i = 1, 16 do + plc.prevLPC_Q12[i] = 0 + end + end + -- silk_PLC_energy + local sl, nb = ch.subfr_length, ch.nb_subfr + local exc = ch.exc_Q14 + for k = 0, 1 do + local g = if k == 0 then prevGain_Q10_0 else prevGain_Q10_1 + for i = 0, sl - 1 do + excBuf[k * sl + i + 1] = sat16(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) // 256) + end + end + local energy1, shift1 = sumSqrShift(excBuf, 1, sl) + local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) + local rand_off -- C offset into exc_Q14 + if rshift(energy1, shift2) < rshift(energy2, shift1) then + rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) + else + rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) + end + local B = plc.LTPCoef_Q14 + local rand_scale_Q14 = plc.randScale_Q14 + local att = math.min(1, ch.lossCnt) + 1 + local harm_Gain_Q15 = HARM_ATT_Q15[att] + local rand_Gain_Q15 = if ch.prevSignalType == 2 then PLC_RAND_ATTENUATE_V_Q15[att] else PLC_RAND_ATTENUATE_UV_Q15[att] + bwexpander(plc.prevLPC_Q12, order, 64881) + for i = 1, order do + A_plc[i] = plc.prevLPC_Q12[i] + end + if ch.lossCnt == 0 then + rand_scale_Q14 = 16384 + if ch.prevSignalType == 2 then + for i = 1, 5 do + rand_scale_Q14 -= B[i] + end + rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) + rand_scale_Q14 = s16((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) // 16384) + else + local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) + local down = math.min(1073741824 // 8, invGain_Q30) + down = math.max(1073741824 // 256, down) + down = down * 8 + rand_Gain_Q15 = ((down * s16(rand_Gain_Q15)) // 65536) // 16384 + end + end + local rand_seed = plc.rand_seed + local lag = (plc.pitchL_Q8 + 128) // 256 + local sLTP_buf_idx = ltp_mem_length + local idx = ltp_mem_length - lag - order - 2 + if idx < 1 then + idx = 1 + end + lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) + local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) + inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) + for i = idx + order, ltp_mem_length - 1 do + plcLTP_Q14[i + 1] = (inv_gain_Q30 * plcLTP[i + 1]) // 65536 + end + for _ = 0, ch.nb_subfr - 1 do + local pl = sLTP_buf_idx - lag + 2 + 1 + local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] + for _ = 1, sl do + local pred = 2 + pred += (plcLTP_Q14[pl] * b0) // 65536 + pred += (plcLTP_Q14[pl - 1] * b1) // 65536 + pred += (plcLTP_Q14[pl - 2] * b2) // 65536 + pred += (plcLTP_Q14[pl - 3] * b3) // 65536 + pred += (plcLTP_Q14[pl - 4] * b4) // 65536 + pl += 1 + rand_seed = silkRand(rand_seed) + local ri = (rand_seed // 33554432) % 128 + sLTP_buf_idx += 1 + plcLTP_Q14[sLTP_buf_idx] = i32((pred + (exc[rand_off + ri + 1] * s16(rand_scale_Q14)) // 65536) * 4) + end + for j = 1, 5 do + B[j] = (harm_Gain_Q15 * s16(B[j])) // 32768 + end + rand_scale_Q14 = (s16(rand_scale_Q14) * s16(rand_Gain_Q15)) // 32768 + plc.pitchL_Q8 = plc.pitchL_Q8 + (plc.pitchL_Q8 * 655) // 65536 + plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) + lag = (plc.pitchL_Q8 + 128) // 256 + end + -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 + local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr + local slb = ch.sLPC_Q14_buf + for i = 1, 16 do + plcLTP_Q14[base + i] = slb[i] + end + for i = 0, ch.frame_length - 1 do + local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] + local pred = order // 2 + for t = 1, order do + pred += (plcLTP_Q14[j - t] * A_plc[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) + plcLTP_Q14[j] = v + frame[fo + i] = sat16((mulww(v, prevGain_Q10_1) + 128) // 256) + end + for i = 1, 16 do + slb[i] = plcLTP_Q14[base + ch.frame_length + i] + end + plc.rand_seed = rand_seed + plc.randScale_Q14 = s16(rand_scale_Q14) + for i = 1, 4 do + ctrl.pitchL[i] = lag + end +end + +@native local function plcGlueFrames(ch: any, frame: { number }, fo: number, length: number) + local plc = ch.sPLC + if ch.lossCnt ~= 0 then + plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) + plc.last_frame_lost = 1 + else + if plc.last_frame_lost ~= 0 then + local energy, energy_shift = sumSqrShift(frame, fo, length) + if energy_shift > plc.conc_energy_shift then + plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) + elseif energy_shift < plc.conc_energy_shift then + energy = rshift(energy, plc.conc_energy_shift - energy_shift) + end + if energy > plc.conc_energy then + local LZ = clz32(plc.conc_energy) - 1 + plc.conc_energy = i32(plc.conc_energy * p2(LZ)) + energy = rshift(energy, math.max(24 - LZ, 0)) + local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) + local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 + local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 + for i = 0, length - 1 do + frame[fo + i] = (gain_Q16 * frame[fo + i]) // 65536 + gain_Q16 += slope_Q16 + if gain_Q16 > 65536 then + break + end + end + end + end + plc.last_frame_lost = 0 + end +end + +local A_cng = table.create(16, 0) +local CNG_sig = table.create(336, 0) + +@native local function cng(ch: any, ctrl: any, frame: { number }, fo: number, length: number) + local c = ch.sCNG + if ch.fs_kHz ~= c.fs_kHz then + cngReset(ch) + c.fs_kHz = ch.fs_kHz + end + local order = ch.LPC_order + if ch.lossCnt == 0 and ch.prevSignalType == 0 then + local sm = c.CNG_smth_NLSF_Q15 + for i = 1, order do + sm[i] += ((ch.prevNLSF_Q15[i] - sm[i]) * 16348) // 65536 + end + local max_Gain_Q16, subfr = 0, 0 + for i = 0, ch.nb_subfr - 1 do + if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then + max_Gain_Q16 = ctrl.Gains_Q16[i + 1] + subfr = i + end + end + local eb = c.CNG_exc_buf_Q14 + local sl = ch.subfr_length + for i = (ch.nb_subfr - 1) * sl, 1, -1 do + eb[sl + i] = eb[i] + end + for i = 1, sl do + eb[i] = ch.exc_Q14[subfr * sl + i] + end + for i = 1, ch.nb_subfr do + local g = ctrl.Gains_Q16[i] + c.CNG_smth_Gain_Q16 += ((g - c.CNG_smth_Gain_Q16) * 4634) // 65536 + if mulww(c.CNG_smth_Gain_Q16, 46396) > g then + c.CNG_smth_Gain_Q16 = g + end + end + end + if ch.lossCnt ~= 0 then + local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) + if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then + gain_Q16 = (gain_Q16 // 65536) * (gain_Q16 // 65536) + gain_Q16 = i32((c.CNG_smth_Gain_Q16 // 65536) * (c.CNG_smth_Gain_Q16 // 65536) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) + else + gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) + gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) + end + local gain_Q10 = gain_Q16 // 64 + -- silk_CNG_exc + local exc_mask = 255 + while exc_mask > length do + exc_mask //= 2 + end + local seed = c.rand_seed + for i = 1, length do + seed = silkRand(seed) + local idx = bit32.band((seed // 16777216) % 256, exc_mask) + CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] + end + c.rand_seed = seed + nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) + for i = 1, 16 do + CNG_sig[i] = c.CNG_synth_state[i] + end + for i = 0, length - 1 do + local j = 16 + i + 1 + local pred = order // 2 + for t = 1, order do + pred += (CNG_sig[j - t] * A_cng[t]) // 65536 + end + pred = i32(pred) + local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) + CNG_sig[j] = v + frame[fo + i] = sat16(frame[fo + i] + sat16((mulww(v, gain_Q10) + 128) // 256)) + end + for i = 1, 16 do + c.CNG_synth_state[i] = CNG_sig[length + i] + end + else + for i = 1, order do + c.CNG_synth_state[i] = 0 + end + end +end + +-- Frame decode -------------------------------------------------------------------------------------------------- + +-- silk_decode_frame: writes frame_length samples to out[fo ..] +@native local function decodeFrame(ch: any, d: any, out: { number }, fo: number, lostFlag: number, condCoding: number): number + local L = ch.frame_length + local ctrl = ch.ctrl + ctrl.LTP_scale_Q14 = 0 + if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then + local pulses = ch.pulses + decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) + decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) + decodeParameters(ch, ctrl, condCoding) + decodeCore(ch, ctrl, out, fo, pulses) + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + -- silk_PLC (update) + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcUpdate(ch, ctrl) + ch.lossCnt = 0 + ch.prevSignalType = ch.indices.signalType + ch.first_frame_after_reset = 0 + else + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcConceal(ch, ctrl, out, fo) + ch.lossCnt += 1 + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + end + cng(ch, ctrl, out, fo, L) + plcGlueFrames(ch, out, fo, L) + ch.lagPrev = ctrl.pitchL[ch.nb_subfr] + return L +end + +-- Stereo -------------------------------------------------------------------------------------------------------- + +@native local function stereoDecodePred(d: any, pred_Q13: { number }) + local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) + local ix02 = n // 5 + local ix12 = n - 5 * ix02 + local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) + local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) + local q = T.stereo_pred_quant_Q13 + for c = 1, 2 do + local a = if c == 1 then ix00 + 3 * ix02 else ix10 + 3 * ix12 + local b = if c == 1 then ix01 else ix11 + local low_Q13 = q[a + 1] + local step_Q13 = ((q[a + 2] - low_Q13) * 6554) // 65536 + pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) + end + pred_Q13[1] -= pred_Q13[2] +end + +-- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) +@native local function stereoMSToLR(state: any, x1: { number }, x2: { number }, pred_Q13: { number }, fs_kHz: number, frame_length: number) + x1[1], x1[2] = state.sMid[1], state.sMid[2] + x2[1], x2[2] = state.sSide[1], state.sSide[2] + state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] + state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] + local pred0 = state.pred_prev_Q13[1] + local pred1 = state.pred_prev_Q13[2] + local interp = 8 * fs_kHz + local denom_Q16 = tdiv(65536, interp) + local delta0 = (s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) // 65536 + local delta1 = (s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) // 65536 + for n = 0, frame_length - 1 do + if n < interp then + pred0 += delta0 + pred1 += delta1 + elseif n == interp then + pred0 = pred_Q13[1] + pred1 = pred_Q13[2] + end + local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 + sum = x2[n + 2] * 256 + (sum * s16(pred0)) // 65536 + sum = sum + ((x1[n + 2] * 2048) * s16(pred1)) // 65536 + x2[n + 2] = sat16((sum + 128) // 256) + end + if frame_length <= interp then + -- the second loop never ran; the C code still ends with pred = pred_Q13 + end + state.pred_prev_Q13[1] = pred_Q13[1] + state.pred_prev_Q13[2] = pred_Q13[2] + for n = 0, frame_length - 1 do + local a, b = x1[n + 2], x2[n + 2] + x1[n + 2] = sat16(a + b) + x2[n + 2] = sat16(a - b) + end +end + +-- API ----------------------------------------------------------------------------------------------------------- + +type State = any + +@native function Silk.new(apiChannels: number): State + return { + ch = { newChannel(), newChannel() }, + sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, + nChannelsAPI = 0, + nChannelsInternal = 0, + prev_decode_only_middle = 0, + MS_pred_Q13 = { 0, 0 }, + resampOut = table.create(960, 0), + apiChannels = apiChannels, + } +end + +-- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) +@native function Silk.reset(st: State) + st.ch[1] = newChannel() + st.ch[2] = newChannel() + for _, ch in st.ch do + cngReset(ch) + plcReset(ch) + end + st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } + st.prev_decode_only_middle = 0 +end + +@native local function initChannel(st: State, n: number) + local ch = newChannel() + cngReset(ch) + plcReset(ch) + st.ch[n] = ch +end + +@native function Silk.decode(st: State, ctrl: any, lostFlag: number, firstFrame: boolean, d: any, out: { number }, outBase: number): (number, number) + local ret = 0 + local nInt = ctrl.nChannelsInternal + local nAPI = ctrl.nChannelsAPI + local chs = st.ch + local decode_only_middle = 0 + local MS_pred_Q13 = st.MS_pred_Q13 + MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 + if nInt ~= 1 and nInt ~= 2 then + return -200, 0 + end + if firstFrame then + for n = 1, nInt do + chs[n].nFramesDecoded = 0 + end + end + if nInt > st.nChannelsInternal then + initChannel(st, 2) + end + local ch1 = chs[1] + local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz + if ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + local ms = ctrl.payloadSize_ms + if ms == 0 or ms == 10 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 2 + elseif ms == 20 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 4 + elseif ms == 40 then + ch.nFramesPerPacket = 2 + ch.nb_subfr = 4 + elseif ms == 60 then + ch.nFramesPerPacket = 3 + ch.nb_subfr = 4 + else + return -203, 0 + end + local fs_kHz_dec = ctrl.internalSampleRate // 1024 + 1 + if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then + return -200, 0 + end + ret += decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) + end + end + if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then + local s = st.sStereo + s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 + s.sSide[1], s.sSide[2] = 0, 0 + copyResampler(chs[2].resampler_state, ch1.resampler_state) + end + st.nChannelsAPI = nAPI + st.nChannelsInternal = nInt + if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then + return -200, 0 + end + if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + for i = 1, ch.nFramesPerPacket do + ch.VAD_flags[i] = if bitLogp(d, 1) then 1 else 0 + end + ch.LBRR_flag = if bitLogp(d, 1) then 1 else 0 + end + for n = 1, nInt do + local ch = chs[n] + ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 + if ch.LBRR_flag ~= 0 then + if ch.nFramesPerPacket == 1 then + ch.LBRR_flags[1] = 1 + else + local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 + for i = 0, ch.nFramesPerPacket - 1 do + ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) + end + end + end + end + if lostFlag == 0 then + -- skip all LBRR data + for i = 0, ch1.nFramesPerPacket - 1 do + for n = 1, nInt do + local ch = chs[n] + if ch.LBRR_flags[i + 1] ~= 0 then + if nInt == 2 and n == 1 then + stereoDecodePred(d, MS_pred_Q13) + if chs[2].LBRR_flags[i + 1] == 0 then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + end + end + local condCoding = if i > 0 and ch.LBRR_flags[i] ~= 0 then 2 else 0 + decodeIndices(ch, d, i, true, condCoding) + decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) + end + end + end + end + end + if nInt == 2 then + local fd = ch1.nFramesDecoded + if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then + stereoDecodePred(d, MS_pred_Q13) + if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + else + decode_only_middle = 0 + end + else + MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] + MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] + end + end + if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then + local c2 = chs[2] + for i = 1, 480 do + c2.outBuf[i] = 0 + end + for i = 1, 16 do + c2.sLPC_Q14_buf[i] = 0 + end + c2.lagPrev = 100 + c2.LastGainIndex = 10 + c2.prevSignalType = 0 + c2.first_frame_after_reset = 1 + end + local has_side + if lostFlag == 0 then + has_side = decode_only_middle == 0 + else + has_side = st.prev_decode_only_middle == 0 + or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) + end + local nSamplesOutDec = ch1.frame_length + for n = 1, nInt do + local ch = chs[n] + if n == 1 or has_side then + local FrameIndex = ch1.nFramesDecoded - (n - 1) + local condCoding + if FrameIndex <= 0 then + condCoding = 0 + elseif lostFlag == 2 then + condCoding = if ch.LBRR_flags[FrameIndex] ~= 0 then 2 else 0 + elseif n > 1 and st.prev_decode_only_middle ~= 0 then + condCoding = 1 + else + condCoding = 2 + end + nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) + else + local o = ch.out + for i = 3, nSamplesOutDec + 2 do + o[i] = 0 + end + end + ch.nFramesDecoded += 1 + end + local o1 = ch1.out + if nAPI == 2 and nInt == 2 then + stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) + else + local sMid = st.sStereo.sMid + o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] + end + local nSamplesOut = (nSamplesOutDec * ctrl.API_sampleRate) // (ch1.fs_kHz * 1000) + local ro = st.resampOut + local scale = 1 / 32768 + for n = 1, math.min(nAPI, nInt) do + resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) + if nAPI == 2 then + local b = outBase + n - 1 + for i = 0, nSamplesOut - 1 do + out[b + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + i] = ro[i + 1] * scale + end + end + end + if nAPI == 2 and nInt == 1 then + if stereo_to_mono then + resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = out[outBase + 2 * i] + end + end + end + if lostFlag == 1 then + for i = 1, st.nChannelsInternal do + chs[i].LastGainIndex = 10 + end + else + st.prev_decode_only_middle = decode_only_middle + end + return ret, nSamplesOut +end + +-- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced +@native function Silk.prevPitchLag(st: State): number + local ch = st.ch[1] + if ch.prevSignalType == 2 then + local mult = { 6, 4, 3 } + return ch.lagPrev * mult[(ch.fs_kHz - 8) // 4 + 1] + end + return 0 +end + +return Silk +end +__FILES["codecs/audio/Opus/SilkTables"] = function() + + +-- 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 = { + 179, 99, 0, +} +T.LTP_gain_iCDF_0 = { + 71, 56, 43, 30, 21, 12, 6, 0, +} +T.LTP_gain_iCDF_1 = { + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +} +T.LTP_gain_iCDF_2 = { + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, + 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +} +T.LTP_gain_vq_0 = { + 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, +} +T.LTP_gain_vq_1 = { + 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, +} +T.LTP_gain_vq_2 = { + -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, +} +T.NLSF_CB1_WB_Q8 = { + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, + 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, + 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, + 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, + 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, + 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, + 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, + 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, + 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, + 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, + 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, + 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, + 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, + 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, + 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, + 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, + 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, + 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, + 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, + 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +} +T.NLSF_CB1_WB_Wght_Q9 = { + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, + 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, + 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, + 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, + 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, + 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, + 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, + 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, + 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, + 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, + 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, + 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, + 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, + 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, + 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, + 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, + 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, + 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, + 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, + 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +} +T.NLSF_CB1_iCDF_WB = { + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, + 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, + 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, + 5, 4, 3, 0, +} +T.NLSF_CB2_SELECT_WB = { + 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, + 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, + 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, + 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, + 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, + 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, + 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, +} +T.NLSF_CB2_iCDF_WB = { + 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, + 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, + 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, + 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, +} +T.NLSF_PRED_WB_Q8 = { + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, + 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +} +T.NLSF_DELTA_MIN_WB_Q15 = { + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, +} +T.NLSF_CB1_NB_MB_Q8 = { + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +} +T.NLSF_CB1_Wght_Q9 = { + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +} +T.NLSF_CB1_iCDF_NB_MB = { + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, + 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, + 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, + 12, 11, 5, 0, +} +T.NLSF_CB2_SELECT_NB_MB = { + 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, +} +T.NLSF_CB2_iCDF_NB_MB = { + 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, + 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, + 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, + 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, +} +T.NLSF_PRED_NB_MB_Q8 = { + 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, +} +T.NLSF_DELTA_MIN_NB_MB_Q15 = { + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +} +T.pitch_lag_iCDF = { + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, + 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} +T.pitch_delta_iCDF = { + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, + 0, +} +T.pitch_contour_iCDF = { + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, + 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, +} +T.pitch_contour_NB_iCDF = { + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +} +T.pitch_contour_10_ms_iCDF = { + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +} +T.pitch_contour_10_ms_NB_iCDF = { + 113, 63, 0, +} +T.stereo_pred_quant_Q13 = { + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +} +T.stereo_pred_joint_iCDF = { + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, + 11, 10, 9, 7, 0, +} +T.stereo_only_code_mid_iCDF = { + 64, 0, +} +T.LBRR_flags_2_iCDF = { + 203, 150, 0, +} +T.LBRR_flags_3_iCDF = { + 215, 195, 166, 125, 110, 82, 0, +} +T.lsb_iCDF = { + 120, 0, +} +T.LTPscale_iCDF = { + 128, 64, 0, +} +T.type_offset_VAD_iCDF = { + 232, 158, 10, 0, +} +T.type_offset_no_VAD_iCDF = { + 230, 0, +} +T.NLSF_interpolation_factor_iCDF = { + 243, 221, 192, 181, 0, +} +T.LTPScales_table_Q14 = { + 15565, 12288, 8192, +} +T.uniform3_iCDF = { + 171, 85, 0, +} +T.uniform4_iCDF = { + 192, 128, 64, 0, +} +T.uniform5_iCDF = { + 205, 154, 102, 51, 0, +} +T.uniform6_iCDF = { + 213, 171, 128, 85, 43, 0, +} +T.uniform8_iCDF = { + 224, 192, 160, 128, 96, 64, 32, 0, +} +T.NLSF_EXT_iCDF = { + 100, 40, 16, 7, 3, 1, 0, +} +T.gain_iCDF = { + 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, + 61, 11, 2, 0, +} +T.delta_gain_iCDF = { + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, + 0, +} +T.LSFCosTab_FIX_Q12 = { + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, + 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, + 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, + 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, + -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, + -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, +} +T.pulses_per_block_iCDF = { + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, + 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, + 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, + 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, + 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, + 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, + 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, + 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +} +T.rate_levels_iCDF = { + 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, +} +T.shell_code_table0 = { + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, + 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, + 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, + 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, + 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, + 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, + 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, +} +T.shell_code_table1 = { + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, + 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, + 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, + 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, + 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, + 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, + 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, +} +T.shell_code_table2 = { + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, + 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, + 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, + 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, + 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, + 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, + 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, +} +T.shell_code_table3 = { + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, + 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, + 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, + 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, + 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, + 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, + 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, +} +T.shell_code_table_offsets = { + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, +} +T.sign_iCDF = { + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, + 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, + 95, 102, +} +T.CB_lags_stage2_10_ms = { + 0, 1, 0, 0, 0, 1, +} +T.CB_lags_stage3_10_ms = { + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, + -2, 3, -2, 3, +} +T.CB_lags_stage2 = { + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, + 0, 0, -1, -1, +} +T.CB_lags_stage3 = { + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, + 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, + -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, + -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, + 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +} +T.resampler_frac_FIR_12 = { + 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, + -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, + -71, 611, -2143, 5784, -46, 425, -1375, 2996, +} +return T +end +__FILES["codecs/audio/Pcm"] = function() + +-- 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. +-- +-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else +-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- 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/audio/Pcm/Convert) +-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] +-- local x = Pcm.fromInt(s16, 16) -- s / 32768 +-- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. +-- Never throws (a decoder's read that throws is caught and ends the stream). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Convert = __include("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 +} + +type Source = { + sampleRate: number, + channels: number, + frames: number, -- total frames, 0 = unknown (a streaming decoder without an index) + tags: Types.Tags, + -- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end) + read: (self: Source, n: number, out: buffer?) -> (buffer, number), + err: Err.Err?, -- set when the underlying decoder failed mid-stream +} + +local function audioRead(self: any, n: number, out: buffer?): (buffer, number) + local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + 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) + buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos += n + return b, n +end + +local function decoderRead(self: any, n: number, out: buffer?): (buffer, number) + if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = buffer.len(b) // (ch * 4) + end + return b, got +end + +-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) +function Pcm.source(v: any): (Source?, Err.Err?) + if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil + end + if type(v.read) == "function" then + local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0 + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) +function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?) + local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + 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 + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total += n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + 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) +function Pcm.rawDecoder(buf: buffer, offset: number, frames: number, channels: number, sampleRate: number, fmt: string, tags: Types.Tags?): (Types.Decoder?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes) + if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos += n + end + return b, n + end + function dec.seek(_self: any, seconds: number) + local f = math.floor(seconds * sampleRate + 0.5) + pos = if f ~= f then 0 else math.clamp(f, 0, frames) + end + function dec.position(_self: any): number + return pos / sampleRate + end + return dec :: any, nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a: Types.Audio): Types.Decoder + local d = Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) :: any + d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Err?) + local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp: buffer? = nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total += n + end + if src.err then + return nil, src.err + end + return total, nil +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) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- fromInt(v, bits) -> v / 2^(bits-1) +function Pcm.fromInt(v: number, bits: number): number + return v / 2 ^ (bits - 1) +end + +return Pcm +end +__FILES["codecs/audio/Pcm/Convert"] = @native function() + + + +-- 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). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE: { [string]: number } = { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t += 8 + elseif seg == 1 then + t += 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = if bit32.band(a, 0x80) ~= 0 then t else -t + -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = if bit32.band(u, 0x80) ~= 0 then 0x84 - m else m - 0x84 +end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +@native local function segment(v: number, ends: { number }): number + for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +@native local function alawEncode(pcm: number): number + local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval += bit32.band(floor(v / 2), 0x0F) + else + aval += bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +@native local function ulawEncode(pcm: number): number + local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v += 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +@native function Convert.decode(src: buffer, so: number, fmt: string, count: number, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v -= 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v -= 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +@native local function q(x: number, s: number): number + local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +@native function Convert.encode(src: buffer, so: number, count: number, fmt: string, dst: buffer, d: number): boolean + if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + v // 256) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v // 65536) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v // 65536) + writeu8(dst, p + 1, (v // 256) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert +end +__FILES["codecs/audio/Qoa"] = @native function() + + + +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale +-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic +-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force +-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). +-- The 64-bit slices are handled as two 32-bit halves. +-- +-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message +-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d +-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] +-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) +-- +-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local readi32, writei32 = buffer.readi32, buffer.writei32 +local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Qoa = {} + +Qoa.SLICE_LEN = 20 +Qoa.SLICES_PER_FRAME = 256 +Qoa.FRAME_LEN = 256 * 20 +Qoa.MAX_CHANNELS = 255 + +local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code +local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } +-- DEQ[sf * 8 + q + 1] +local DEQ = { + 1, -1, 3, -3, 5, -5, 7, -7, + 5, -5, 18, -18, 32, -32, 49, -49, + 16, -16, 53, -53, 95, -95, 147, -147, + 34, -34, 113, -113, 203, -203, 315, -315, + 63, -63, 210, -210, 378, -378, 588, -588, + 104, -104, 345, -345, 621, -621, 966, -966, + 158, -158, 528, -528, 950, -950, 1477, -1477, + 228, -228, 760, -760, 1368, -1368, 2128, -2128, + 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, + 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, + 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, + 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, + 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, + 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, + 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, + 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, +} + +@native local function be32(b: buffer, p: number): number + return byteswap(readu32(b, p)) +end + +@native local function s16(v: number): number + return if v >= 32768 then v - 65536 else v +end + +-- frameSize(channels, slices) -> bytes +@native function Qoa.frameSize(ch: number, slices: number): number + return 8 + 16 * ch + 8 * slices * ch +end + +type FrameInfo = { channels: number, rate: number, samples: number, size: number } + +-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message +@native function Qoa.frameInfo(b: buffer, p: number, avail: number): (FrameInfo?, string?) + if avail < 8 then + return nil, "truncated frame header" + end + local hi, lo = be32(b, p), be32(b, p + 4) + local ch = rshift(hi, 24) + local rate = band(hi, 0xFFFFFF) + local samples = rshift(lo, 16) + local size = band(lo, 0xFFFF) + if ch == 0 or rate == 0 or samples == 0 then + return nil, "bad frame header" + end + local slices = (samples + 19) // 20 + local head = 8 + 16 * ch + if slices > 256 or size < head or slices * ch > (size - head) // 8 then + return nil, "bad frame size" + end + if size > avail then + return nil, "truncated frame" + end + return { channels = ch, rate = rate, samples = samples, size = size }, nil +end + +-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state +-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) +@native function Qoa.decodeFrame(b: buffer, p: number, avail: number, dst: buffer, d: number): (number?, number | string) + local info, msg = Qoa.frameInfo(b, p, avail) + if not info then + return nil, msg :: string + end + local ch, samples = info.channels, info.samples + for c = 0, ch - 1 do + local lp = p + 8 + c * 16 + local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) + local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) + local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) + local sp = p + 8 + 16 * ch + c * 8 + local o = (d + c) * 4 + local os = ch * 4 + local s0 = 0 + while s0 < samples do + local hi, lo = be32(b, sp), be32(b, sp + 4) + local base = rshift(hi, 28) * 8 + 1 + local n = math.min(20, samples - s0) + for k = 0, n - 1 do + local q + if k < 9 then + q = band(rshift(hi, 25 - 3 * k), 7) + elseif k == 9 then + q = band(hi, 1) * 4 + rshift(lo, 30) + else + q = band(rshift(lo, 57 - 3 * k), 7) + end + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + writef32(dst, o, r / 32768) + o += os + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + end + s0 += 20 + sp += 8 * ch + end + end + return samples, info.size +end + +-- ------------------------------------------------------------------------------------------------ encoder +-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +@native function Qoa.newLms(ch: number): buffer + local st = buffer.create(32 * ch) + for c = 0, ch - 1 do + writei32(st, c * 32 + 24, -8192) + writei32(st, c * 32 + 28, 16384) + end + return st +end + +-- the nearest s16 to x * 32768 (NaN -> 0) +@native local function toS16(x: number): number + local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end + +-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which +-- wraps for big residuals at scale factor 0), rounding away from zero +@native local function qdiv(v: number, sf: number): number + local x = v * RECIP[sf + 1] + 32768 + if x >= 2147483648 or x < -2147483648 then + x = (x + 2147483648) % 4294967296 - 2147483648 + end + local n = x // 65536 + local sv = if v > 0 then 1 elseif v < 0 then -1 else 0 + local sn = if n > 0 then 1 elseif n < 0 then -1 else 0 + return n + sv - sn +end + +-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x +-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames +@native function Qoa.encodeFrame(x: buffer, xf: number, n: number, ch: number, rate: number, lms: buffer, out: buffer, p: number): number + local slices = (n + 19) // 20 + local size = Qoa.frameSize(ch, slices) + writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) + writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) + for c = 0, ch - 1 do + local so = c * 32 + -- the history and weights as big-endian i16 x 4 + for i = 0, 3 do + local hv = band(readi32(lms, so + i * 4), 0xFFFF) + local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) + buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) + end + end + local xs = table.create(20, 0) + local codes = table.create(20, 0) + local best = table.create(20, 0) + local prevSf = table.create(ch, 0) + local sp = p + 8 + 16 * ch + for s = 0, slices - 1 do + local len = math.min(20, n - s * 20) + for c = 0, ch - 1 do + for k = 1, len do + xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) + end + local so = c * 32 + local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) + local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) + local bestRank, bestSf = math.huge, 0 + local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 + for sfi = 0, 15 do + local sf = (sfi + prevSf[c + 1]) % 16 + local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 + local rank = 0 + local base = sf * 8 + 1 + for k = 1, len do + local v = xs[k] + local pred = (w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) // 8192 + local res = v - pred + local sc = qdiv(res, sf) + if sc > 8 then + sc = 8 + elseif sc < -8 then + sc = -8 + end + local q = QUANT[sc + 9] + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 + if sq >= 2147483648 then -- C int arithmetic + sq = (sq + 2147483648) % 4294967296 - 2147483648 + end + local pen = sq // 262144 - 0x8ff + if pen < 0 then + pen = 0 + end + local e = v - r + rank += e * e + pen * pen + if rank > bestRank then + break + end + local delta = dq // 16 + w0 += if h0 < 0 then -delta else delta + w1 += if h1 < 0 then -delta else delta + w2 += if h2 < 0 then -delta else delta + w3 += if h3 < 0 then -delta else delta + h0, h1, h2, h3 = h1, h2, h3, r + codes[k] = q + end + if rank < bestRank then + bestRank, bestSf = rank, sf + b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 + for k = 1, len do + best[k] = codes[k] + end + end + end + prevSf[c + 1] = bestSf + writei32(lms, so, b0) + writei32(lms, so + 4, b1) + writei32(lms, so + 8, b2) + writei32(lms, so + 12, b3) + writei32(lms, so + 16, bw0) + writei32(lms, so + 20, bw1) + writei32(lms, so + 24, bw2) + writei32(lms, so + 28, bw3) + -- the slice: sf in the top 4 bits, then the codes, unused codes 0 + local hi, lo = bestSf * 268435456, 0 + for k = 0, 19 do + local q = if k < len then best[k + 1] else 0 + if k < 9 then + hi += q * 2 ^ (25 - 3 * k) + elseif k == 9 then + hi += rshift(q, 2) + lo += band(q, 3) * 1073741824 + else + lo += q * 2 ^ (57 - 3 * k) + end + end + writeu32(out, sp, byteswap(hi)) + writeu32(out, sp + 4, byteswap(lo)) + sp += 8 + end + end + return size +end + +return Qoa +end +__FILES["codecs/audio/Resample"] = @native function() + + + +-- 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 rosetta (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 = {} + +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) +} + +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 + +@native 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 + +@native 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). +@native 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) +@native 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 + +@native 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 + +@native 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 +@native 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 +@native 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 +@native 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 + @native 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 +end +__FILES["codecs/audio/SoundFont"] = function() + +-- 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("@rosetta/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) +-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Parse = __include("codecs/audio/SoundFont/Parse") +local Synth = __include("codecs/audio/SoundFont/Synth") +local Fallback = __include("codecs/audio/SoundFont/Fallback") + +local SoundFont = {} + +type SoundFont = Parse.SoundFont +type State = Synth.State + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +-- sniff(r) -> true when r starts with RIFF....sfbk +function SoundFont.sniff(r: Bytes.Reader): boolean + return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), +-- opts.maxSamples (default 2^28) +function SoundFont.parse(src: any, opts: Parse.Options?): (SoundFont?, Err.Err?) + local r: Bytes.Reader + if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +-- fallback() -> the built-in General MIDI waveform set +function SoundFont.fallback(): SoundFont + return Fallback.build() +end + +-- isSoundFont(v) -> true for a parsed / fallback SoundFont value +function SoundFont.isSoundFont(v: any): boolean + return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) +function SoundFont.synth(sf: SoundFont?, sampleRate: number?, opts: { gain: number?, maxVoices: number? }?): State + return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont +end +__FILES["codecs/audio/SoundFont/Fallback"] = function() + +-- 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 = __include("codecs/audio/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz: number): number + return 1200 * math.log(hz / 8.176, 2) +end + +local cached: any = nil + +-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) +function Fallback.build(): any + if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts: { [string]: number } = {} + for w, name in waves do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = if ph < 0.25 then 4 * ph elseif ph < 0.75 then 2 - 4 * ph else 4 * ph - 4 + elseif name == "square" then + v = if ph < 0.5 then 0.6 else -0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave: string, fields: { [string]: number }): { [string]: number } + local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in fields do + r[k] = v + end + return r + end + + -- the 16 GM families: wave + envelope / filter / vibrato + local families: { { any } } = { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[program // 8 + 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + -- the drum kit (bank 128, every program): one region per key + local kit = {} + -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 + local function drum(lo: number, hi: number, wave: string, fields: { [string]: number }) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate *= 2 ^ ((fields.semis or 0) / 12) + r.semis = nil :: any + table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a: { [string]: number }, b: { [string]: number }): { [string]: number } + local c = table.clone(a) + for k, v in b do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in { 41, 43, 45, 47, 48, 50 } do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "rosetta fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback +end +__FILES["codecs/audio/SoundFont/Parse"] = function() + +-- 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) +-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped +-- so the synth never reads outside the sample buffer. +-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); +-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). +-- Never throws: a bad file returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Parse = {} + +-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level +type Region = { [string]: number } + +type Preset = { name: string, preset: number, bank: number, regions: { Region } } + +type SoundFont = { + kind: "soundfont", + info: { [string]: string }, + samples: buffer, -- f32 mono, sampleCount + 1 floats (a zero pad sample past the end) + sampleCount: number, + presets: { Preset }, -- sorted by bank, then preset number + sampleHeaders: { { [string]: any } }, + instruments: { { name: string, zones: number } }, + meta: { [string]: any }, +} + +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN: { [number]: { any } } = { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +-- the merged fields: value generators once each (several ops share a field), then the four address fields +local MERGE: { { any } } = {} +do + local seen: { [string]: boolean } = {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1]] then + seen[g[1]] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +local function clear(relative: boolean): Region + local r: Region = {} + for _, f in FIELDS do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r: Region): Region + local c: Region = {} + for k, v in r do + c[k] = v + end + return c +end + +-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from +function Parse.defaultRegion(): Region + local r = clear(false) + r.keycenter = 60 + for _, p in { "a", "m" } do + for _, s in { "Delay", "Attack", "Hold", "Decay", "Release" } do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r: Region, op: number, lo: number, hi: number, s: number, w: number) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1]] = s + elseif mode == "a" then + r[g[1]] += s + elseif mode == "a15" then + r[g[1]] += s * 32768 + elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = if m == 3 then 2 elseif m == 1 then 1 else 0 + elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z: Region, p: Region) + for _, g in MERGE do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v *= lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r: Region, p: string, sustainIsGain: boolean) + for _, s in { "Delay", "Attack", "Release" } do + local v = r[p .. s] + r[p .. s] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = if v < -11950 then 0 else tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = if v < -11950 then 0 else tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = if -sus / 10 > -100 then 10 ^ (-sus / 10 * 0.05) else 0 + else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end + +-- ------------------------------------------------------------------------------------------------ RIFF +type Hydra = { [string]: { { number } } } + +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) +local LAYOUT: { [string]: { number } } = { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +type Options = { maxRegions: number?, maxSamples: number? } + +-- parse(r, opts?) -> SoundFont | nil, Err +function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) + local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info: { [string]: string } = {} + local hydra: Hydra = {} + local smpl: Bytes.Reader? = nil + local sm24: Bytes.Reader? = nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid]] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = sub:remaining() // rs + local recs = table.create(n) :: { { number } } + for i = 1, n do + local rec = {} + for _, w in layout do + if w == 20 then + table.insert(rec, 0) -- the name is read separately + sub:skip(20) + elseif w == 4 then + table.insert(rec, sub:u32le()) + elseif w == 2 then + table.insert(rec, sub:u16le()) + elseif w == -2 then + table.insert(rec, sub:i16le()) + elseif w == 1 then + table.insert(rec, sub:u8()) + else + table.insert(rec, sub:i8()) + end + end + recs[i] = rec + end + hydra[sid] = recs + if sid == "phdr" or sid == "inst" or sid == "shdr" then + local names = table.create(n) + for i = 0, n - 1 do + names[i + 1] = sub:sub(i * rs, 20):fixed(20) + end + hydra[sid .. "Names"] = names :: any + end + end + end + end + end + end + if not smpl then + return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") + end + for _, k in { "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" } do + if not hydra[k] or #hydra[k] == 0 then + return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") + end + end + -- samples + local sr = smpl :: Bytes.Reader + local count = sr:remaining() // 2 + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) + end + local samples = buffer.create((count + 1) * 4) + do + local b, p = sr.buf, sr.pos + local readi16, writef32 = buffer.readi16, buffer.writef32 + local s24 = sm24 + if s24 and s24:remaining() >= count then + local q = s24.pos + local readu8 = buffer.readu8 + for i = 0, count - 1 do + writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) + end + else + s24 = nil + for i = 0, count - 1 do + writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) + end + end + sm24 = s24 + end + -- presets (tsf_load_presets) + local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen + local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr + local phdrNames, instNames, shdrNames = (hydra :: any).phdrNames, (hydra :: any).instNames, (hydra :: any).shdrNames + local nInst = #inst - 1 -- the last record of each list is the terminal one + local nShdr = #shdr - 1 + local function range(list: { { number } }, i: number, field: number, limit: number): (number, number) + -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) + local a = list[i][field] + 1 + local b = if list[i + 1] then list[i + 1][field] + 1 else a + return math.max(1, a), math.min(b, limit + 1) + end + local presets: { Preset } = {} + local regionTotal = 0 + for pi = 1, #phdr - 1 do + local ph = phdr[pi] + local preset: Preset = { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } + local globalRegion = clear(true) + local b0, b1 = range(phdr, pi, 4, #pbag) + for bi = b0, b1 - 1 do + local presetRegion = copy(globalRegion) + local hadInstrument = false + local g0, g1 = range(pbag, bi, 1, #pgen) + for gi = g0, g1 - 1 do + local pg = pgen[gi] + local op, amount = pg[1], pg[2] + local lo, hi = amount % 256, amount // 256 + local s = if amount >= 32768 then amount - 65536 else amount + if op == GEN_INSTRUMENT then + hadInstrument = true + if amount < nInst then + local instRegion = clear(false) + local ib0, ib1 = range(inst, amount + 1, 2, #ibag) + for ibi = ib0, ib1 - 1 do + local zone = copy(instRegion) + local hadSample = false + local ig0, ig1 = range(ibag, ibi, 1, #igen) + for igi = ig0, ig1 - 1 do + local ig = igen[igi] + local iop, iamt = ig[1], ig[2] + if iop == GEN_SAMPLEID then + hadSample = true + if iamt >= nShdr then + break + end + local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) + and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) + if ok then + local z = copy(zone) + z.lokey = math.max(z.lokey, presetRegion.lokey) + z.hikey = math.min(z.hikey, presetRegion.hikey) + z.lovel = math.max(z.lovel, presetRegion.lovel) + z.hivel = math.min(z.hivel, presetRegion.hivel) + merge(z, presetRegion) + envToSecs(z, "a", true) + envToSecs(z, "m", false) + z.delayModLFO = if z.delayModLFO < -11950 then 0 else tc2s(z.delayModLFO) + z.delayVibLFO = if z.delayVibLFO < -11950 then 0 else tc2s(z.delayVibLFO) + local sh = shdr[iamt + 1] + local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] + z.offset = math.clamp(z.offset + sStart, 0, count) + local stop = z.stop + sEnd + if stop > 0 and stop < count then + stop += 1 + else + stop = count + end + z.stop = math.clamp(stop, 0, count) + z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) + local le = z.loopEnd + sLoopEnd + if sLoopEnd > 0 then + le -= 1 + end + z.loopEnd = math.clamp(le, 0, count) + if z.keycenter == -1 then + z.keycenter = sh[7] + end + z.tune += sh[8] + z.sampleRate = sh[6] + z.sampleIndex = iamt + regionTotal += 1 + if regionTotal > maxRegions then + return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") + end + table.insert(preset.regions, z) + end + break -- sampleID ends a zone's generator list + else + local ilo, ihi = iamt % 256, iamt // 256 + operator(zone, iop, ilo, ihi, if iamt >= 32768 then iamt - 65536 else iamt, iamt) + end + end + if ibi == ib0 and not hadSample then + instRegion = zone -- the instrument's global zone + end + end + end + break -- instrument ends a preset zone's generator list + else + operator(presetRegion, op, lo, hi, s, amount) + end + end + if bi == b0 and not hadInstrument then + globalRegion = presetRegion -- the preset's global zone + end + end + table.insert(presets, preset) + end + -- sorted by bank, then preset, then file order (tsf's sortedIndex) + for i, p in presets do + (p :: any)._order = i + end + table.sort(presets, function(a: Preset, b: Preset): boolean + if a.bank ~= b.bank then + return a.bank < b.bank + end + if a.preset ~= b.preset then + return a.preset < b.preset + end + return (a :: any)._order < (b :: any)._order + end) + for _, p in presets do + (p :: any)._order = nil + end + local headers = table.create(nShdr) :: { { [string]: any } } + for i = 1, nShdr do + local sh = shdr[i] + headers[i] = { + name = shdrNames[i], + start = sh[2], + stop = sh[3], + loopStart = sh[4], + loopEnd = sh[5], + sampleRate = sh[6], + originalPitch = sh[7], + pitchCorrection = sh[8], + link = sh[9], + type = sh[10], + } + end + 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 + local sf: SoundFont = { + kind = "soundfont", + info = info, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = headers, + instruments = instruments, + meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, + } + return sf, nil +end + +return Parse +end +__FILES["codecs/audio/SoundFont/Synth"] = @native function() + + +-- 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 +-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with +-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, +-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not +-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. +-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, +-- the sample buffer has a zero pad sample, the output range is checked before mixing). +local Synth = {} + +local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len +local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor + +local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 +local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block +local FASTRELEASE = 0.01 +local PI = math.pi +local LOOP_NONE, LOOP_SUSTAIN = 0, 2 + +type Env = { + segment: number, + isExp: boolean, + isAmp: boolean, + vel: number, + level: number, + slope: number, + untilNext: number, + delay: number, + attack: number, + hold: number, + decay: number, + sustain: number, + release: number, +} +type Lfo = { untilStart: number, level: number, delta: number } +type Voice = { + preset: number, -- 1-based preset index, -1 = idle + key: number, + channel: number, + held: boolean, -- note off while sustain was down + region: { [string]: number }, + pitchIn: number, -- timecents + pitchOut: number, + pos: number, + gainDB: number, + panL: number, + panR: number, + playIndex: number, + loopStart: number, + loopEnd: number, + amp: Env, + mod: Env, + lpActive: boolean, + qinv: number, + a0: number, + a1: number, + b1: number, + b2: number, + z1: number, + z2: number, + modlfo: Lfo, + viblfo: Lfo, +} +type Channel = { + preset: number, + bank: number, + pitchWheel: number, + midiPan: number, + midiVolume: number, + midiExpression: number, + midiRPN: number, + midiData: number, + sustain: boolean, + panOffset: number, + gainDB: number, + pitchRange: number, + tuning: number, +} +type State = { + presets: { { regions: { { [string]: number } }, preset: number, bank: number } }, + lookup: { [number]: number }, -- bank * 128 + preset -> preset index + samples: buffer, + rate: number, + gainDB: number, + voices: { Voice }, + maxVoices: number, + playIndex: number, + channels: { Channel }, -- [1..16] = MIDI channels 0..15 +} + +@native local function tc2s(tc: number): number + return 2 ^ (tc / 1200) +end +@native local function cents2Hz(c: number): number + return 8.176 * 2 ^ (c / 1200) +end +@native local function db2gain(db: number): number + return if db > -100 then 10 ^ (db * 0.05) else 0 +end +@native local function gain2db(g: number): number + return if g <= 0.00001 then -100 else 20 * math.log10(g) +end + +-- ------------------------------------------------------------------------------------------------ envelope +@native local function releaseSamples(e: Env, rate: number): number + return floor((if e.release <= 0 then FASTRELEASE else e.release) * rate) +end + +@native local function nextSegment(e: Env, active: number, rate: number) + local seg = active + if seg == NONE then + e.untilNext = floor(e.delay * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 + return + end + seg = DELAY + end + if seg == DELAY then + e.untilNext = floor(e.attack * rate) + if e.untilNext > 0 then + if not e.isAmp then + -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) + e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) + end + e.segment, e.isExp, e.level = ATTACK, false, 0 + e.slope = if e.untilNext > 0 then 1 / e.untilNext else 1 + return + end + seg = ATTACK + end + if seg == ATTACK then + e.untilNext = floor(e.hold * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 + return + end + seg = HOLD + end + if seg == HOLD then + e.untilNext = floor(e.decay * rate) + if e.untilNext > 0 then + e.segment, e.level = DECAY, 1 + if e.isAmp then + local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) + e.slope = exp(mystery) + e.isExp = true + if e.sustain > 0 then + e.untilNext = floor(log(e.sustain) / mystery) + end + else + e.slope = -1 / e.untilNext + e.untilNext = floor(e.decay * (1 - e.sustain) * rate) + e.isExp = false + end + return + end + seg = DECAY + end + if seg == DECAY then + e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false + return + end + if seg == SUSTAIN then + e.segment = RELEASE + e.untilNext = math.max(1, releaseSamples(e, rate)) + if e.isAmp then + e.slope = exp(-9.226 / e.untilNext) + e.isExp = true + else + e.slope = -e.level / e.untilNext + e.isExp = false + end + return + end + e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF +end + +@native local function envSetup(e: Env, r: { [string]: number }, p: string, key: number, vel: number, isAmp: boolean, rate: number) + e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] + e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] + local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] + if kh ~= 0 then + local h = e.hold + kh * (60 - key) + e.hold = if h < -10000 then 0 else tc2s(h) + end + if kd ~= 0 then + local d = e.decay + kd * (60 - key) + e.decay = if d < -10000 then 0 else tc2s(d) + end + e.vel, e.isAmp = vel, isAmp + nextSegment(e, NONE, rate) +end + +@native local function envProcess(e: Env, n: number, rate: number) + local slope = e.slope + if slope ~= 0 then + if e.isExp then + e.level *= slope ^ n + else + e.level += slope * n + end + end + e.untilNext -= n + if e.untilNext <= 0 then + nextSegment(e, e.segment, rate) + end +end + +@native local function newEnv(): Env + return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } +end + +-- ------------------------------------------------------------------------------------------------ filter / lfo +@native local function lowpassSetup(v: Voice, fc: number) + -- the biquad from earlevel.com (as tsf.h) + local k = tan(PI * fc) + local kk = k * k + local norm = 1 / (1 + k * v.qinv + kk) + v.a0 = kk * norm + v.a1 = 2 * v.a0 + v.b1 = 2 * (kk - 1) * norm + v.b2 = (1 - k * v.qinv + kk) * norm +end + +@native local function lfoSetup(l: Lfo, delay: number, freqCents: number, rate: number) + l.untilStart = floor(delay * rate) + l.delta = 4 * cents2Hz(freqCents) / rate + l.level = 0 +end + +@native local function lfoProcess(l: Lfo, n: number) + if l.untilStart > n then + l.untilStart -= n + return + end + l.level += l.delta * n + if l.level > 1 then + l.delta = -l.delta + l.level = 2 - l.level + elseif l.level < -1 then + l.delta = -l.delta + l.level = -2 - l.level + end +end + +-- ------------------------------------------------------------------------------------------------ voices +@native local function calcPitch(v: Voice, shift: number, rate: number) + local r = v.region + local note = v.key + r.transpose + r.tune / 100 + local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift + v.pitchIn = adjusted * 100 + v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) +end + +@native local function setPan(v: Voice, pan: number) + if pan <= -0.5 then + v.panL, v.panR = 1, 0 + elseif pan >= 0.5 then + v.panL, v.panR = 0, 1 + else + v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) + end +end + +@native local function channelShift(c: Channel): number + return if c.pitchWheel == 8192 then c.tuning else (c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning +end + +@native local function voiceEnd(s: State, v: Voice) + nextSegment(v.amp, SUSTAIN, s.rate) + nextSegment(v.mod, SUSTAIN, s.rate) + if v.region.loopMode == LOOP_SUSTAIN then + v.loopEnd = v.loopStart -- keep playing, stop looping + end +end + +@native local function voiceEndQuick(s: State, v: Voice) + v.amp.release = 0 + nextSegment(v.amp, SUSTAIN, s.rate) + v.mod.release = 0 + nextSegment(v.mod, SUSTAIN, s.rate) +end + +@native local function newVoice(): Voice + return { + preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, + panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), + lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, + modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, + } +end + +@native local function newChannel(): Channel + return { + preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, + midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, + } +end + +-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). +-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) +@native function Synth.new(sf: any, rate: number, gain: number?, maxVoices: number?): State + local lookup: { [number]: number } = {} + for i, p in sf.presets do + local k = p.bank * 128 + p.preset + if lookup[k] == nil then + lookup[k] = i + end + end + local s: State = { + presets = sf.presets, + lookup = lookup, + samples = sf.samples, + rate = rate, + gainDB = gain2db(gain or 0.5), + voices = {}, + maxVoices = maxVoices or 256, + playIndex = 0, + channels = {}, + } + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end + return s +end + +@native local function presetIndex(s: State, bank: number, preset: number): number + return s.lookup[bank * 128 + preset] or -1 +end + +-- noteOn(s, channel, key, velocity 0..127) +@native function Synth.noteOn(s: State, ch: number, key: number, velocity: number) + local c = s.channels[ch + 1] + if not c then + return + end + if velocity <= 0 then + Synth.noteOff(s, ch, key) + return + end + local pi = c.preset + local preset = s.presets[pi] + if not preset then + return + end + local vel = math.min(velocity, 127) / 127 + local midiVel = floor(vel * 127) + local rate = s.rate + local voices = s.voices + local playIndex = s.playIndex + s.playIndex += 1 + for _, region in preset.regions do + if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then + continue + end + local voice: Voice? = nil + if region.group ~= 0 then + for _, v in voices do + if v.preset == pi and v.region.group == region.group then + voiceEndQuick(s, v) + elseif v.preset == -1 and not voice then + voice = v + end + end + else + for _, v in voices do + if v.preset == -1 then + voice = v + break + end + end + end + if not voice then + if #voices < s.maxVoices then + local v = newVoice() + table.insert(voices, v) + voice = v + else + local best = -1e18 + for _, v in voices do + if v.amp.segment == RELEASE then + local done = releaseSamples(v.amp, rate) - v.amp.untilNext + if done > best then + best, voice = done, v + end + end + end + if not voice then + continue + end + end + end + local v = voice :: Voice + v.region = region + v.preset = pi + v.key = key + v.channel = ch + v.playIndex = playIndex + v.held = false + v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB + calcPitch(v, channelShift(c), rate) + setPan(v, region.pan + c.panOffset) + v.pos = region.offset + local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd + v.loopStart = if doLoop then region.loopStart else 0 + v.loopEnd = if doLoop then region.loopEnd else 0 + envSetup(v.amp, region, "a", key, midiVel, true, rate) + envSetup(v.mod, region, "m", key, midiVel, false, rate) + local fc = if region.filterFc <= 13500 then cents2Hz(region.filterFc) / rate else 1 + v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) + v.z1, v.z2 = 0, 0 + v.lpActive = fc < 0.499 + if v.lpActive then + lowpassSetup(v, fc) + end + lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) + lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) + end +end + +-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down +@native function Synth.noteOff(s: State, ch: number, key: number) + local c = s.channels[ch + 1] + if not c then + return + end + local first = -1 + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then + if first == -1 or v.playIndex < first then + first = v.playIndex + end + end + end + if first == -1 then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then + if c.sustain then + v.held = true + else + voiceEnd(s, v) + end + end + end +end + +@native local function applyPitch(s: State, ch: number, c: Channel) + local shift = channelShift(c) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + calcPitch(v, shift, s.rate) + end + end +end + +@native local function setVolume(s: State, ch: number, c: Channel, volume: number) + local db = gain2db(volume) + if db == c.gainDB then + return + end + local change = db - c.gainDB + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + v.gainDB += change + end + end + c.gainDB = db +end + +@native local function setChannelPan(s: State, ch: number, c: Channel, pan: number) + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch then + setPan(v, v.region.pan + pan - 0.5) + end + end + c.panOffset = pan - 0.5 +end + +@native local function setTuning(s: State, ch: number, c: Channel, tuning: number) + if c.tuning ~= tuning then + c.tuning = tuning + applyPitch(s, ch, c) + end +end + +@native local function setPitchRange(s: State, ch: number, c: Channel, range: number) + if c.pitchRange ~= range then + c.pitchRange = range + if c.pitchWheel ~= 8192 then + applyPitch(s, ch, c) + end + end +end + +@native local function setSustain(s: State, ch: number, c: Channel, on: boolean) + if c.sustain == on then + return + end + c.sustain = on + if on then + return + end + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then + voiceEnd(s, v) + end + end +end + +-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +@native function Synth.program(s: State, ch: number, program: number) + local c = s.channels[ch + 1] + if not c then + return + end + local bank = c.bank % 32768 + local idx + if ch == 9 then + idx = presetIndex(s, 128 + bank, program) + if idx == -1 then + idx = presetIndex(s, 128, program) + end + if idx == -1 then + idx = presetIndex(s, 128, 0) + end + if idx == -1 then + idx = presetIndex(s, bank, program) + end + else + idx = presetIndex(s, bank, program) + end + if idx == -1 then + idx = presetIndex(s, 0, program) + end + if idx ~= -1 then + c.preset = idx + end +end + +-- pitchBend(s, channel, 0..16383) +@native function Synth.pitchBend(s: State, ch: number, value: number) + local c = s.channels[ch + 1] + if not c or c.pitchWheel == value then + return + end + c.pitchWheel = value + applyPitch(s, ch, c) +end + +-- control(s, channel, controller, value 0..127) +@native function Synth.control(s: State, ch: number, cc: number, value: number) + local c = s.channels[ch + 1] + if not c then + return + end + local volume, pan, data = false, false, false + if cc == 7 then + c.midiVolume = c.midiVolume % 128 + value * 128 + volume = true + elseif cc == 39 then + c.midiVolume = c.midiVolume - c.midiVolume % 128 + value + volume = true + elseif cc == 11 then + c.midiExpression = c.midiExpression % 128 + value * 128 + volume = true + elseif cc == 43 then + c.midiExpression = c.midiExpression - c.midiExpression % 128 + value + volume = true + elseif cc == 10 then + c.midiPan = c.midiPan % 128 + value * 128 + pan = true + elseif cc == 42 then + c.midiPan = c.midiPan - c.midiPan % 128 + value + pan = true + elseif cc == 6 then + c.midiData = c.midiData % 128 + value * 128 + data = true + elseif cc == 38 then + c.midiData = c.midiData - c.midiData % 128 + value + data = true + elseif cc == 0 then + c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) + elseif cc == 32 then + c.bank = (if c.bank >= 0x8000 then (c.bank % 128) * 128 else 0) + value + elseif cc == 101 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn % 128 + value * 128 + elseif cc == 100 then + local rpn = if c.midiRPN == 0xFFFF then 0 else c.midiRPN + c.midiRPN = rpn - rpn % 128 + value + elseif cc == 98 or cc == 99 then + c.midiRPN = 0xFFFF + elseif cc == 64 then + setSustain(s, ch, c, value >= 64) + elseif cc == 120 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then + voiceEndQuick(s, v) + end + end + elseif cc == 123 then + for _, v in s.voices do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then + voiceEnd(s, v) + end + end + elseif cc == 121 then + c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 + setVolume(s, ch, c, 1) + setChannelPan(s, ch, c, 0.5) + setPitchRange(s, ch, c, 2) + setTuning(s, ch, c, 0) + end + if volume then + -- the cube gives a decent MIDI volume curve (tsf.h) + setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) + elseif pan then + setChannelPan(s, ch, c, c.midiPan / 16383) + elseif data then + if c.midiRPN == 0 then + setPitchRange(s, ch, c, c.midiData // 128 + 0.01 * (c.midiData % 128)) + elseif c.midiRPN == 1 then + local t = c.tuning + setTuning(s, ch, c, (if t < 0 then math.ceil(t) else floor(t)) + (c.midiData - 8192) / 8192) + elseif c.midiRPN == 2 and cc == 6 then + local t = c.tuning + setTuning(s, ch, c, (value - 64) + (t - (if t < 0 then math.ceil(t) else floor(t)))) + end + end +end + +-- midi(s, status, d1, d2): one channel message +@native function Synth.midi(s: State, status: number, d1: number, d2: number) + local kind, ch = status // 16, status % 16 + if kind == 9 then + Synth.noteOn(s, ch, d1, d2) + elseif kind == 8 then + Synth.noteOff(s, ch, d1) + elseif kind == 11 then + Synth.control(s, ch, d1, d2) + elseif kind == 12 then + Synth.program(s, ch, d1) + elseif kind == 14 then + Synth.pitchBend(s, ch, d1 + d2 * 128) + end +end + +-- reset(s): all voices off, channels back to their defaults +@native function Synth.reset(s: State) + for _, v in s.voices do + v.preset = -1 + end + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end +end + +-- active(s) -> the number of sounding voices +@native function Synth.active(s: State): number + local n = 0 + for _, v in s.voices do + if v.preset ~= -1 then + n += 1 + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ render +@native local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSamples: number) + local region = v.region + local input = s.samples + local rate = s.rate + local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc + local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume + local vibLfoToPitch = region.vibLfoToPitch + local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 + local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) + local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 + local loopStart, loopEnd = v.loopStart, v.loopEnd + local isLooping = loopStart < loopEnd + local endD = region.stop + local loopEndD = loopEnd + 1 + local loopLen = loopEnd - loopStart + 1 + local pos = v.pos + local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 + local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 + local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 + local dynamicGain = modLfoToVolume ~= 0 + local filterFc = region.filterFc + local pitchRatio = if dynamicPitch then 0 else tc2s(v.pitchIn) * v.pitchOut + local noteGain = if dynamicGain then 0 else db2gain(v.gainDB) + local o = frame * 8 + while numSamples > 0 do + local block = if numSamples > BLOCK then BLOCK else numSamples + numSamples -= block + if dynamicLowpass then + local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc + local fc = if fres <= 13500 then cents2Hz(fres) / rate else 1 + lpActive = fc < 0.499 + if lpActive then + lowpassSetup(v, fc) + a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 + end + end + if dynamicPitch then + pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut + end + if dynamicGain then + noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) + end + local gainMono = noteGain * v.amp.level + envProcess(v.amp, block, rate) + if updateModEnv then + envProcess(v.mod, block, rate) + end + if updateModLfo then + lfoProcess(v.modlfo, block) + end + if updateVibLfo then + lfoProcess(v.viblfo, block) + end + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono + local k = block + while k > 0 and pos < endD do + k -= 1 + local ip = floor(pos) + local np = if ip >= loopEnd and isLooping then loopStart else ip + 1 + local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) + o += 8 + pos += pitchRatio + if pos >= loopEndD and isLooping then + pos -= loopLen + end + end + o += k * 8 + if not (pos < endD) or v.amp.segment == DONE then + v.preset = -1 + return + end + end + v.pos = pos + v.lpActive, v.z1, v.z2 = lpActive, z1, z2 +end + +-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range +-- requests are clipped to the buffer +@native function Synth.render(s: State, out: buffer, frame: number, n: number) + local room = blen(out) // 8 - frame + if frame < 0 or room <= 0 then + return + end + if n > room then + n = room + end + if n <= 0 then + return + end + -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here + -- once so a hand-made SoundFont cannot index outside it) + local count = blen(s.samples) // 4 - 1 + for _, v in s.voices do + if v.preset ~= -1 then + local r = v.region + if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then + v.preset = -1 + else + voiceRender(s, v, out, frame, n) + end + end + end +end + +return Synth +end +__FILES["codecs/audio/Stream"] = function() + +-- 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 rosetta +-- (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; or a buffer of f32) 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) +-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) +-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the +-- }) -- same frames as read() as i32 (bit-exact checks) +-- +-- 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 = __include("core/Err") + +local Stream = {} + +type Spec = { + count: number, + start: (i: number) -> number, + decode: (i: number) -> (number?, Err.Err?), + pcm: () -> { number } | buffer, -- a buffer: interleaved f32 from byte 0 + 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) + scale: number?, -- read() writes pcm() values times this (default 1) + ints: boolean?, -- pcm() values are integers: dec:readInt(n, out?) returns them as i32 +} + +-- 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 + + local scale = spec.scale or 1 + local function pull(n: number, out: buffer?, asInt: boolean): (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, writei32 = buffer.writef32, buffer.writei32 + 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 + if type(src) == "buffer" then + if scale == 1 and not asInt then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 0, take * ch - 1 do + local v = buffer.readf32(src, (s + k) * 4) + if asInt then + writei32(ob, q, v) + else + writef32(ob, q, v * scale) + end + q += 4 + end + end + elseif asInt then + for k = 1, take * ch do + writei32(ob, q, src[s + k]) + q += 4 + end + elseif scale == 1 then + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q += 4 + end + else + for k = 1, take * ch do + writef32(ob, q, src[s + k] * scale) + q += 4 + end + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, false) + end + if spec.ints then + function dec.readInt(_self: any, n: number, out: buffer?): (buffer, number) + return pull(n, out, true) + end + 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 +end +__FILES["codecs/audio/Tracker"] = function() + +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders +-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in +-- codecs/audio/Tracker/Load). The 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("@rosetta/codecs/audio/Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from +-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four +-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", +-- music/669: "s3m", ...) and set the quirks they need in flags. +-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), +-- amigaLimits (MOD), and the quirks of the other formats (any family): +-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in +-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), +-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), +-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), +-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), +-- envRowHold (MED: envelopes do not advance on a row's first tick) } +-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, +-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } +-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note +-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; +-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency +-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). +-- Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = __include("core/Err") +local Types = __include("Types") +local Player = __include("codecs/audio/Tracker/Player") +local Mixer = __include("codecs/audio/Tracker/Mixer") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + +type Envelope = { + enabled: boolean, + ticks: { number }, + values: { number }, + loop: boolean, + loopStart: number, + loopEnd: number, + sustain: boolean, + susStart: number, + susEnd: number, + carry: boolean?, + filter: boolean?, + raw: any?, -- format-specific fields kept for a faithful re-save (XM) +} + +type Pattern = { rows: number, data: buffer } + +type RenderOptions = { + sampleRate: number?, -- default 44100 + interpolation: ("linear" | "none")?, -- default "linear" + stereoSeparation: number?, -- 0..200 % (default 100: the panning as stored; 200 doubles every distance from centre) + loop: boolean?, -- keep playing past the song's end (frames / duration still give one pass); default false + maxDuration: number?, -- seconds; the render stops there (default 3600) +} + +local CELL = 5 + +-- engine extension effects (see the Module notes above) +Tracker.EXT = Player.EXT + +-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte +Tracker.st2Tempo = Tables.st2Tempo + +local FAMILIES = { mod = true, s3m = true, xm = true, it = true } + +-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as +function Tracker.family(m: any): string? + local f = m.engine or m.format + return if type(f) == "string" and FAMILIES[f] then f else nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family +-- (engine, default format) +function Tracker.newModule(format: string, channels: number, engine: string?): any + local fam = engine or format + local m = { + kind = "music", + format = format, + engine = engine, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = fam == "xm" or fam == "it", + instrumentMode = fam == "xm" or fam == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if fam == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = if k == 0 or k == 3 then 64 else 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows: number, channels: number): Pattern + return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name: string?): any + return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil :: number?, + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope(): Envelope + return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name: string?): any + local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil :: Envelope?, + panEnv = nil :: Envelope?, + pitchEnv = nil :: Envelope?, + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil :: number?, + pps = 0, + ppc = 60, + cutoff = nil :: number?, + resonance = nil :: number?, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m: any, pattern: number, row: number, channel: number): (number?, number, number, number, number) + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m: any, pattern: number, row: number, channel: number, note: number, ins: number, vol: number, fx: number, param: number): boolean + local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e: any): (any, string?) + if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v: any): number + return if num(v, 1, math.max(1, n)) then math.floor(v) else 1 + end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s0: any, e0: any, t0: any, len: number): (number, number, number) + if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then + return 0, 0, 0 + end + local s: number = math.floor(math.clamp(s0, 0, len)) + local e: number = math.floor(math.clamp(e0, 0, len)) + local t: number = math.floor(t0) + if e - s < 1 or t == 0 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m: any): (boolean?, Err.Err?) + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if not Tracker.family(m) then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) + end + if m.preamp ~= nil and not num(m.preamp, 0, 256) then + m.preamp = nil + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = if type(m.instruments) == "table" then m.instruments else {} + m.flags = if type(m.flags) == "table" then m.flags else {} + m.channelPan = if type(m.channelPan) == "table" then m.channelPan else {} + m.channelVolume = if type(m.channelVolume) == "table" then m.channelVolume else {} + m.channelMute = if type(m.channelMute) == "table" then m.channelMute else {} + for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = if num(m.speed, 1, 255) then math.floor(m.speed) else 6 + m.tempo = if num(m.tempo, 1, 1000) then m.tempo else 125 + m.globalVolume = if num(m.globalVolume, 0, 128) then m.globalVolume else 128 + m.mixVolume = if num(m.mixVolume, 0, 256) then m.mixVolume else 48 + m.restart = if num(m.restart, 0, 1e6) then math.floor(m.restart) else 0 + for i, o in m.order do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in m.patterns do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in m.samples do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = if s.channels == 2 then 2 else 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = if num(s.volume, 0, 64) then s.volume else 64 + s.globalVolume = if num(s.globalVolume, 0, 64) then s.globalVolume else 64 + if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = if num(s.c5speed, 1, 1e7) then s.c5speed else 8363 + s.relativeNote = if num(s.relativeNote, -128, 127) then s.relativeNote else 0 + s.finetune = if num(s.finetune, -128, 127) then s.finetune else 0 + end + for i, ins in m.instruments do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = if num(ins.fadeout, 0, 65535) then ins.fadeout else 0 + ins.globalVolume = if num(ins.globalVolume, 0, 128) then ins.globalVolume else 128 + if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m: any, opts: RenderOptions?): (number?, Err.Err?) + local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames += f + end + return math.min(frames, maxFrames) / sr, nil +end + +local function newPlayer(self: any) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m: any, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local o: RenderOptions = opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil :: any, + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self :: any, nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self: any, opts: RenderOptions?): Types.Decoder + local dec = Tracker.render(self, opts) + return dec :: any +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self: any, out: buffer?, n: number): number + local st = self.st + local done = 0 + while done < n do + if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then + continue + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left -= k + done += k + end + self.pos += done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self: any, n: number, out: buffer?): (buffer, number) + n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o :: buffer, got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self: any, seconds: number) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in self.st.voices do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self: any): number + return self.pos / self.sampleRate +end + +return Tracker +end +__FILES["codecs/audio/Tracker/Load"] = function() + +-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the +-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders +-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter +-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers +-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, +-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +local Err = __include("core/Err") +local Player = __include("codecs/audio/Tracker/Player") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Load = {} + +local EXT = Player.EXT + +-- the S3M / IT letter code of each effect name (engine extension effects included) +local IT: { [string]: number } = { + speed = 1, + jump = 2, + ["break"] = 3, + volslide = 4, + portadown = 5, + portaup = 6, + toneporta = 7, + vibrato = 8, + tremor = 9, + arpeggio = 10, + vibratovol = 11, + toneportavol = 12, + chanvol = 13, + chanvolslide = 14, + offset = 15, + panslide = 16, + retrig = 17, + tremolo = 18, + s3mex = 19, + tempo = 20, + finevibrato = 21, + globalvol = 22, + globalvolslide = 23, + panning8 = 24, + panbrello = 25, + noteslideup = EXT.NOTE_SLIDE_UP, + noteslidedown = EXT.NOTE_SLIDE_DOWN, + noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, + noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, + autoportaup = EXT.AUTO_PORTA_UP, + autoportadown = EXT.AUTO_PORTA_DOWN, + freqadjust = EXT.FREQ_ADJUST, +} +Load.IT = IT + +-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits +local WEIGHT: { [string]: number } = {} +for i, n in + { + "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", + "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", + "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", + "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", + "speed", "jump", "break", + } +do + WEIGHT[n] = i +end + +local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } + +-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +function Load.isGlobal(name: string?, param: number): boolean + if name == nil then + return false + end + if GLOBAL[name] then + return true + end + local x = param // 16 + if name == "modex" then + return x == 0 or x == 6 or x == 0xE + elseif name == "s3mex" then + return x == 6 or x == 0xB or x == 0xE + end + return false +end + +-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +local MODFX: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", + [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", + [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", + [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", +} +function Load.modCommand(cmd: number, param: number): (string?, number) + if cmd == 0 and param == 0 then + return nil, 0 + elseif cmd == 0xF and param < 0x20 then + return "speed", param + end + local n = MODFX[cmd] + if n == "break" then + param = (param // 16) * 10 + param % 16 + end + return n, param +end + +-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, +-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +function Load.itVolume(name: string?, param: number, force: boolean): number? + if name == "volume" then + return math.min(param, 64) + 1 + elseif name == "volume8" then + if not force and param % 4 ~= 0 then + return nil + end + return (param + 3) // 4 + 1 + elseif name == "portaup" or name == "portadown" then + if not force and (param % 4 ~= 0 or param >= 0xE0) then + return nil + end + return (if name == "portaup" then 115 else 105) + math.min(param // 4, 9) + 1 + elseif name == "toneporta" then + if param >= 0xF0 then + return 193 + 9 + 1 + end + for n = 0, 9 do + local v = Tables.IT_VOLPORTA[n + 1] + if (force and param <= v) or param == v then + return 193 + n + 1 + end + end + return nil + elseif name == "vibrato" then + if force then + param = math.min(param % 16, 9) + elseif param % 16 > 9 or param >= 16 then + return nil + end + return 203 + param % 16 + 1 + elseif name == "panning8" then + return 128 + (if param == 255 then 64 else param // 4) + 1 + elseif name == "volslide" then + local x, y = param // 16, param % 16 + if param == 0 then + return nil + elseif y == 0 then + return 85 + math.min(x, 9) + 1 + elseif x == 0 then + return 95 + math.min(y, 9) + 1 + elseif y == 0xF then + return 65 + math.min(x, 9) + 1 + elseif x == 0xF then + return 75 + math.min(y, 9) + 1 + end + return nil + elseif name == "s3mex" and param // 16 == 8 then + return 128 + (param % 16) * 4 + 2 + 1 + end + return nil +end + +-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's +-- extended E commands become their S3M equivalents) +function Load.itEffect(name: string?, param: number): (number, number) + if name == nil then + return 0, 0 + end + if name == "modex" then + local x, y = param // 16, param % 16 + if x == 1 then + return IT.portaup, 0xF0 + y + elseif x == 2 then + return IT.portadown, 0xF0 + y + elseif x == 9 then + return IT.retrig, y + elseif x == 0xA then + return IT.volslide, y * 16 + 0xF + elseif x == 0xB then + return IT.volslide, 0xF0 + y + end + local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] + if s then + return IT.s3mex, s * 16 + y + end + return 0, 0 + end + local code = IT[name] + if code == nil then + return 0, 0 + end + return code, param +end + +-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, +-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the +-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +function Load.fillTwo(e1: string?, p1: number, e2: string?, p2: number): (number, string?, number, string?, number) + if e1 ~= nil and e1 == e2 then + e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) + end + for n = 0, 3 do + local v = Load.itVolume(e1, p1, n > 1) + if e1 == nil or v then + if v == nil and (e2 == "volume" or e2 == "volume8") then + -- the engine's IT family sets volumes in the volume column only + return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 + end + return v or 0, e2, p2, nil, 0 + end + e1, p1, e2, p2 = e2, p2, e1, p1 + end + if (WEIGHT[e1 :: string] or 0) > (WEIGHT[e2 :: string] or 0) then + e1, p1, e2, p2 = e2, p2, e1, p1 + end + return 0, e2, p2, e1, p1 +end + +-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect +-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or +-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's +-- CPattern::WriteEffect). +function Load.writeEffect(m: any, pattern: number, row: number, fx: number, param: number, retry: string?, channel: number?, multiple: boolean?): boolean + local p = m.patterns[pattern + 1] + if not p then + return false + end + local fam = m.engine or m.format + local modLike = fam == "mod" or fam == "xm" + local nch = m.channels + local d = p.data + local guard = 0 + while row >= 0 and row < p.rows and guard < 1024 do + guard += 1 + local c0, c1 = 1, nch + if channel then + c0, c1 = channel, channel + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then + return true + end + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if f == 0 and (not modLike or q == 0) then + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + return true + end + end + if retry == "next" then + row += 1 + elseif retry == "prev" then + row -= 1 + else + return false + end + end + return false +end + +-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm +-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames +-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). +function Load.readSample(buf: buffer, offset: number, frames: number, spec: any, s: any, budget: { left: number }): (boolean?, Err.Err?) + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) + local avail = math.max(0, limit - offset) // (nch * bps) + local n = math.max(0, math.min(math.floor(frames), avail)) + budget.left -= n * nch * 4 + if budget.left < 0 then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, offset, n, spec) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", offset) + end + s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch + return true, nil +end + +-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +function Load.bcd(n: number): number + n = math.clamp(math.floor(n), 0, 99) + return (n // 10) * 16 + n % 10 +end + +return Load +end +__FILES["codecs/audio/Tracker/Mixer"] = @native function() + + +-- 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/audio/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +@native local function mixVoice(v: any, out: buffer?, off: number, n: number, linear: boolean, ramp: number) + local data: buffer = v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do + guard += 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = if t == 2 then e - 1 else e + if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p + continue + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 + continue + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i += m + continue + end + local wrapJ = if t == 1 then s else e - 1 + local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl += dl + gr += dr + rl -= 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o += 8 + p += step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i += m + end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +@native function Mixer.mix(st: any, out: buffer?, off: number, n: number, linear: boolean) + for _, v in st.voices do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer +end +__FILES["codecs/audio/Tracker/Pcm"] = @native function() + + +-- 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). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +type Spec = { + bits: number, -- 8 | 16 + signed: boolean, + delta: boolean?, -- each value is the difference to the previous one (XM, IT 2.15 "delta" flag) + channels: number?, -- 1 (default) | 2 + planar: boolean?, -- stereo stored as all left then all right (XM, IT); default interleaved + bigEndian: boolean?, +} + +-- bytes(frames, spec) -> the size of the raw data +@native function Pcm.bytes(frames: number, spec: Spec): number + return frames * (spec.channels or 1) * (spec.bits // 8) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +@native function Pcm.decode(buf: buffer, off: number, frames: number, spec: Spec): buffer? + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = if planar then c * frames + i else i * nch + c + local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v -= 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v -= 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +@native function Pcm.encode(samples: buffer, frames: number, spec: Spec): buffer + local nch = spec.channels or 1 + local bps = spec.bits // 8 + local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = buffer.len(samples) // 4 + for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = if si < avail then readf32(samples, si * 4) else 0 + local k = if planar then c * frames + i else i * nch + c + if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = if spec.signed then v % 256 else v + 128 + end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w -= 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +@native function Pcm.bitsNeeded(samples: buffer): number + for i = 0, buffer.len(samples) // 4 - 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm +end +__FILES["codecs/audio/Tracker/Player"] = @native function() + + +-- 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/audio/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = __include("codecs/audio/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +-- engine extension effects: format-specific commands of the other tracker formats, in any family (see +-- codecs/audio/Tracker) +local EXT = { + NOTE_SLIDE_UP = 0x40, + NOTE_SLIDE_DOWN = 0x41, + NOTE_SLIDE_UP_RETRIG = 0x42, + NOTE_SLIDE_DOWN_RETRIG = 0x43, + AUTO_PORTA_UP = 0x44, + AUTO_PORTA_DOWN = 0x45, + FREQ_ADJUST = 0x46, + TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) +} +Player.EXT = EXT + +local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions + +-- ------------------------------------------------------------------------------------------------ state +@native local function newVoice(): any + return { + active = false, + chan = 0, + bg = false, + data = nil :: buffer?, + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil :: any, + smpIdx = 0, + ins = nil :: any, + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + owner = 0, -- the channel whose foreground voice this is (0: free or background) + order = 0, -- allocation age + } +end + +@native local function newChannel(i: number, pan: number, vol: number): any + return { + idx = i, + voice = nil :: any, + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil :: any, + vol = 0, + pan = pan, + basePan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil :: number?, + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down + autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) + slideCount = 0, -- note slides: ticks to the next step + mNoteSlide = 0, + tonePortaRow = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +@native function Player.new(m: any, sampleRate: number, opts: any): any + local fmt = FAMILY[m.engine or m.format] or MOD + local flags = m.flags + local ptPeriods = fmt == MOD or flags.periods == "amiga" + local st: any = { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = flags.fastSlides or false, + amigaLimits = flags.amigaLimits or false, + ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) + hz = flags.periods == "hz", -- periods are frequencies in Hz + hzScale = if type(flags.hzSlide) == "number" then flags.hzSlide else 1, + hzTone = if type(flags.hzTonePorta) == "number" then flags.hzTonePorta else 1, + fastPortas = flags.fastPortas or false, + autoTonePorta = flags.autoTonePorta or false, + autoReset = flags.autoReset or false, + st2Tempo = flags.st2Tempo or false, + oktSlides = flags.oktSlides or false, + ft2Pan = flags.panLaw == "ft2", + envHold = flags.envRowHold or false, + ord = 0, + row = 0, + tick = 0, + pat = nil :: any, + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + ft2BreakPos = 0, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} :: { [number]: boolean }, + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = if ptPeriods then AMIGA_PAL else AMIGA, + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.basePan = pan + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, m.channels + BG_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +@native function Player.masterGain(m: any, fmt: number): number + if type(m.preamp) == "number" then + return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader + end + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 + end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +@native function Player.startOrder(st: any, ord: number, row: number) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard += 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o += 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = if row < st.pat.rows then row else 0 + return + end + end +end + +@native local function advanceRow(st: any) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = if st.jumpOrd >= 0 then st.jumpOrd else st.ord + 1 + local r = if st.breakRow >= 0 then st.breakRow else 0 + st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row += 1 + if st.row >= st.pat.rows then + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = if st.fmt == XM then st.ft2BreakPos else 0 + st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces) +@native 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 + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.hz then + -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 + return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base + end + if st.ptPeriods then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + local n = note + (if st.fmt == MOD or st.fmt == XM then smp.relativeNote or 0 else 0) + return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +@native local function arpPeriod(st: any, period: number, semis: number): number + if semis == 0 then + return period + end + if st.hz then + return period * 2 ^ (semis / 12) + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +@native local function clampPeriod(st: any, c: any) + if st.hz then + c.period = clamp(c.period, 1, 1e6) + elseif st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency +-- moves units * hzSlide Hz the other way +@native local function slide(st: any, c: any, units: number) + if st.hz then + c.period -= units * st.hzScale + else + c.period += units + end + clampPeriod(st, c) +end + +-- ------------------------------------------------------------------------------------------------ voices +@native local function allocVoice(st: any): any + local best, bestScore = nil, math.huge + for _, v in st.voices do + if not v.active and v.owner == 0 then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway + for _, v in st.voices do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] -- unreachable: there are more voices than channels +end + +@native local function keyOff(st: any, v: any) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +@native local function noteFade(v: any) + if v and v.active then + v.fading = true + end +end + +@native local function cutVoice(v: any) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +@native local function startVoice(st: any, c: any, smp: any, smpIdx: number, ins: any, insIdx: number, note: number, period: number, base: number, keepEnv: any) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + v.owner = c.idx + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age += 1 + v.order = st.age + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +@native local function newNoteAction(st: any, c: any, ins: any, insIdx: number, note: number, smpIdx: number) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in st.voices do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = if v.ins then (v.ins.nna or 0) else 0 + end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + v.owner = 0 + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +@native local function isPorta(st: any, fx: number, vcmd: number): boolean + local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +@native local function resolve(st: any, insIdx: number, note: number): (any, number, any, number) + local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +@native local function setInstrumentDefaults(st: any, c: any, smp: any, ins: any) + if smp then + c.vol = smp.volume + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then + c.surround = false + end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false + end + if ins and st.fmt == IT then + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +@native local function sampleOffset(st: any, c: any, v: any) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = (if f == XM then c.mOffset else param) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + (if f == IT then c.mHighOffset * 65536 else 0) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +@native local function trigger(st: any, c: any, note: number, insIdx: number, vcmd: number) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = if st.insMode then m.instruments[insIdx] ~= nil else m.samples[insIdx] ~= nil + if valid then + c.insIdx = insIdx + local n = if hasNote then note else c.note + local smp, _, ins = resolve(st, insIdx, if n > 0 then n else 61) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep: any = false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = if c.voice.ins == ins then true else "release" + end + c.triggered = true + c.hzAdd = 0 + c.tremorOn = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.basePan = c.pan + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +@native local function volSlideMod(c: any, param: number) + local x, y = param // 16, param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +@native local function tonePorta(st: any, c: any, speed: number) + if c.period == c.target then + return + end + if st.hz then + speed *= st.hzScale * st.hzTone + end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +@native local function vibrato(st: any, c: any, scale: number) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +@native local function tremolo(c: any, scale: number) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +@native local function retrigVoice(st: any, c: any) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +@native local function retrigVolume(c: any, x: number) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol += Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +@native local function dSlide(value: number, param: number, tick: number, fast: boolean, hi: number): number + local x, y = param // 16, param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +@native local function fxModXm(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = param // 16, param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = if k == 1 then x elseif k == 2 then y else 0 + end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 or st.fastPortas then + slide(st, c, -(if xm then c.mPortaUp else param) * 4) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 or st.fastPortas then + slide(st, c, (if xm then c.mPortaDn else param) * 4) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.basePan = c.pan + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + slide(st, c, -(if xm then c.mFineUp else y) * 4) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + slide(st, c, (if xm then c.mFineDn else y) * 4) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + st.ft2BreakPos = c.loopRow + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + (if xm then c.mFineVolUp else y)) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - (if xm then c.mFineVolDn else y)) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = p // 16, p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = p // 16, p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + c.basePan = c.pan + else + c.pan = max(0, c.pan - py) + c.basePan = c.pan + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (c.mRetrig // 16) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount += 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, c.mRetrig // 16) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + slide(st, c, -c.mXFineUp) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + slide(st, c, c.mXFineDn) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 or st.fastSlides then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 or st.fastSlides then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = c.mTremor // 16 + 1, c.mTremor % 16 + 1 + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +@native local function volColXm(st: any, c: any, tick: number) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = v // 16, v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + c.basePan = c.pan + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + c.basePan = c.pan + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +@native local function mem(st: any, c: any, field: string, param: number): number + if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +@native local function portaS3m(st: any, c: any, p: number, tick: number, sign: number) + if p >= 0xF0 then + if tick == 0 then + slide(st, c, sign * (p % 16) * 4) + end + elseif p >= 0xE0 then + if tick == 0 then + slide(st, c, sign * (p % 16)) + end + elseif tick > 0 or st.fastPortas then + slide(st, c, sign * p * 4) + end +end + +@native local function fxS3mIt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + if st.st2Tempo then + st.speed, st.tempo = Tables.st2Tempo(param) + else + st.speed = param + end + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = if it then param else (param // 16) * 10 + param % 16 + end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = p // 16, p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount %= on + off + c.tremorOn = c.tremorCount < on + c.tremorCount += 1 + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = if k == 1 then p // 16 elseif k == 2 then p % 16 else 0 + elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = p // 16, p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.basePan = c.pan + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount -= 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, p // 16) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if param // 16 > 0 then + c.tremSpeed = param // 16 + end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = if it then mem(st, c, "mS", param) else mem(st, c, "mS", param) + local x, y = p // 16, p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay += y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in st.voices do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount -= 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = if y == 0 and it then 1 else y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.basePan = c.pan + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.basePan = c.pan + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if param // 16 > 0 then + c.panbSpeed = param // 16 + end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, c.panbPos // 4) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if param // 16 > 0 then + c.vibSpeed = param // 16 + end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = if fx == 21 then 2 / 255 else 8 / 255 + if it and not st.oldFx then + scale /= 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +@native local function volColIt(st: any, c: any, tick: number) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, c.mEF * 4) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, -c.mEF * 4) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, if st.oldFx then 8 / 255 else 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ extension effects +-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family +@native local function fxExt(st: any, c: any, tick: number) + local fx, param = c.fx, c.param + if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then + -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): + -- 1x = every tick, 5x = once on the first tick + if tick == 0 then + if param // 16 > 0 then + c.mNoteSlide = (param // 16) * 16 + c.mNoteSlide % 16 + end + if param % 16 > 0 then + c.mNoteSlide = (c.mNoteSlide // 16) * 16 + param % 16 + end + c.slideCount = c.mNoteSlide // 16 + end + local p = c.mNoteSlide + local go + if st.oktSlides then + go = p // 16 == 1 or tick == 0 + else + go = false + if tick > 0 then + c.slideCount -= 1 + go = c.slideCount == 0 + end + end + if go and c.smp and c.realNote > 0 then + c.slideCount = p // 16 + local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG + c.realNote = clamp(c.realNote + (if up then p % 16 else -(p % 16)), 1, 120) + c.period = notePeriod(st, c.realNote, c.smp, c.finetune) + if fx >= EXT.NOTE_SLIDE_UP_RETRIG then + retrigVoice(st, c) + end + end + elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then + if tick == 0 then + c.autoPorta = (if fx == EXT.AUTO_PORTA_UP then -param else param) * 4 + end + elseif fx == EXT.FREQ_ADJUST then + if tick == 0 then + c.hzAdd = param * 80 + end + elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then + if tick == 0 then + st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param + end + end + -- auto slides: every tick (fast portamentos) or every tick but the first + if tick > 0 or st.fastPortas then + if c.autoPorta ~= 0 then + slide(st, c, c.autoPorta) + end + if c.autoTone and not c.tonePortaRow then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +@native local function noteDelayOf(st: any, fx: number, param: number): number + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and param // 16 == 0xD then + return param % 16 + end + return 0 +end + +@native local function finetuneOf(st: any, fx: number, param: number): number? + if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and param // 16 == 5 then + local y = param % 16 + if st.fmt == MOD then + return (if y >= 8 then y - 16 else y) * 16 + end + return (y - 8) * 16 + end + return nil +end + +@native local function runEffects(st: any, c: any, tick: number) + c.vibDelta, c.arp = 0, 0 + if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then + fxExt(st, c, tick) + end + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +@native local function processRow(st: any) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows += 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + if st.autoReset and fx ~= 0 and fx ~= 255 then + -- 669: any effect stops the auto slides + c.autoPorta, c.autoTone = 0, false + end + local tp = isPorta(st, fx, vcmd) + c.tonePortaRow = tp + if tp and st.autoTonePorta then + c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) + end + c.triggered = false + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +@native local function updateEnvelope(env: any, pos: number, keyOn: boolean, it: boolean): (number, number, boolean) + -- returns value, next position, ended + local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i += 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = if it then 1 else 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and le and pos <= le and nextPos >= le + over then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +@native local function updateVoice(st: any, v: any) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) + envVol, v.volEnvPos = val, if hold then v.volEnvPos else np + if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) + envPan, v.panEnvPos = val, if hold then v.panEnvPos else np + end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) + v.pitchEnvPos = if hold then v.pitchEnvPos else np + if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade -= if it then fo * 64 else fo * 2 + if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = if it then v.smp else ins + local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.hz then + freq = max(0, P + (v.hzAdd or 0)) + elseif st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = if P > 0 then st.amiga / P else 0 + end + if envPitch ~= 0 then + freq *= 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, + -- sets them) + vol *= v.chanVol / 64 * (if smp then (smp.globalVolume or 64) / 64 else 1) * (if ins then (ins.globalVolume or 128) / 128 else 1) + if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan += envPan * range / 32 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + elseif st.ft2Pan then + -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 + local p = min(pan, 255) + v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +@native function Player.tick(st: any): number + if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, if t == 0 then 1 else t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + (if st.hz then -c.vibDelta * st.hzScale else c.vibDelta) + v.period, v.periodOut, v.base = c.period, P, c.base + v.hzAdd = c.hzAdd + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in st.voices do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) + -- advance + st.tick += 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep += 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player +end +__FILES["codecs/audio/Tracker/Tables"] = @native function() + + +-- 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). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM: { number } = {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (s // 65536) % 511 - 255 + end +end +@native function Tables.wave64(kind: number, pos: number): number + local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return if p < 32 then 255 else -255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return if p >= 32 then -v else v +end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256: { number } = {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +@native function Tables.autoWave(kind: number, pos: number, it: boolean): number + local p = pos % 256 + if it then + if kind == 1 then + return 64 - (p + 1) // 2 + elseif kind == 2 then + return if p < 128 then 64 else -64 + elseif kind == 3 then + return RANDOM[(p % 64) + 1] // 4 + end + return SINE256[p + 1] + end + if kind == 1 then + return if p < 128 then 64 else -64 + elseif kind == 2 then + return 64 - (p + 1) // 2 + elseif kind == 3 then + return (p + 1) // 2 - 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +@native function Tables.periodToNote(period: number): number + if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +@native function Tables.noteToPeriod(note: number): number + local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) +-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } +@native function Tables.st2Tempo(byte: number): (number, number) + local hi, lo = byte // 16, byte % 16 + local d = 50 - (ST2_FACTOR[hi + 1] * lo) // 16 -- never 0; negative at tempo 06..0F (C integer division truncates) + local spt = if d > 0 then 23863 // d else -(23863 // -d) + if spt <= 0 then + spt += 65536 + end + return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 +end + +return Tables +end +__FILES["codecs/audio/Tta"] = function() + +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description +-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); +-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain +-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 +-- (password-protected: UNSUPPORTED), TTA2. +-- +-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table +-- local dec = Tta.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Tta/Decode") + +local Tta = {} + +type Info = { + format: number, + channels: number, + bitsPerSample: number, + sampleRate: number, + samples: number, -- per channel + frameLength: number, -- samples per frame (256 * rate / 245) + frames: number, + offsets: { number }, -- each frame's byte offset + sizes: { number }, +} + +-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` +function Tta.info(buf: buffer, at: number, limit: number): (Info?, Err.Err?) + if at + 22 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + if buffer.readstring(buf, at, 4) ~= "TTA1" then + return nil, Err.new(Err.CORRUPT, "no TTA1 header") + end + if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) + end + local format = buffer.readu16(buf, at + 4) + local info: Info = { + format = format, + channels = buffer.readu16(buf, at + 6), + bitsPerSample = buffer.readu16(buf, at + 8), + sampleRate = buffer.readu32(buf, at + 10), + samples = buffer.readu32(buf, at + 14), + frameLength = 0, + frames = 0, + offsets = {}, + sizes = {}, + } + if format == 2 then + return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") + elseif format ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) + end + local bits = info.bitsPerSample + if bits ~= 8 and bits ~= 16 and bits ~= 24 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") + end + if info.channels < 1 or info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + info.frameLength = (256 * info.sampleRate) // 245 + if info.frameLength < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + local frames = (info.samples + info.frameLength - 1) // info.frameLength + info.frames = frames + local st = at + 22 + if st + frames * 4 + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated seek table") + end + if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then + return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) + end + local o = st + frames * 4 + 4 + for i = 1, frames do + local size = buffer.readu32(buf, st + (i - 1) * 4) + info.offsets[i] = o + info.sizes[i] = size + o += size + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Decoder = { + info: Info, + pcm: { number }, + limit: number, + frame: (self: Decoder, buf: buffer, i: number) -> (number?, Err.Err?), + state: Decode.State, +} + +local function frame(self: Decoder, buf: buffer, i: number): (number?, Err.Err?) + local info = self.info + if i < 1 or i > info.frames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local o, size = info.offsets[i], info.sizes[i] + if o + size > self.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) + end + local n = if i < info.frames then info.frameLength else info.samples - (info.frames - 1) * info.frameLength + local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) + if not got then + return nil, Err.from(msg, o) + end + return got, nil +end + +-- decoder(info, limit) -> Decoder (limit: the end of the file data) +function Tta.decoder(info: Info, limit: number): Decoder + return { + info = info, + pcm = table.create(info.frameLength * info.channels, 0), + limit = limit, + frame = frame, + state = Decode.state(info.channels, info.bitsPerSample // 8), + } +end + +return Tta +end +__FILES["codecs/audio/Tta/Decode"] = @native function() + + + +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio +-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the +-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked +-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +local Crc32 = __include("core/Crc32") + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, rshift = bit32.band, bit32.rshift +local min, max, floor = math.min, math.max, math.floor + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local INV31 = 1 / TWO31 +local PAD = 16 +local P2: { number } = table.create(40, 0) -- P2[k + 1] = 2^k +for i = 0, 39 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v //= 2 + end + ONES[b + 1] = n +end + +-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) +@native local function longUnary(S: buffer, pos: number, lim: number): (number?, number) + local unary = 0 + while pos <= lim do + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + return unary + ones, pos + ones + 1 + end + unary += 8 + pos += 8 + end + return nil, pos +end + +type State = { + channels: number, + bytes: number, -- 1 .. 3 + S: buffer, -- the frame's bits (+ PAD zeros) + -- per channel: rice k0, k1, sum0, sum1; filter error, Q (weights), X (steps), L (delay line) x 8; the last value + R: { number }, + Q: { number }, + X: { number }, + L: { number }, + E: { number }, + last: { number }, + cur: { number }, +} + +@native function Decode.state(channels: number, bytes: number): State + return { + channels = channels, + bytes = bytes, + S = buffer.create(4096), + R = table.create(channels * 4, 0), + Q = table.create(channels * 8, 0), + X = table.create(channels * 8, 0), + L = table.create(channels * 8, 0), + E = table.create(channels, 0), + last = table.create(channels, 0), + cur = table.create(channels, 0), + } +end + +-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per +-- channel, into P (interleaved integers) +@native function Decode.frame(st: State, buf: buffer, o: number, len: number, n: number, P: { number }): (number?, string?) + if len < 4 then + return nil, "truncated frame" + end + local dlen = len - 4 + if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then + return nil, "checksum: frame CRC mismatch" + end + local S = st.S + if buffer.len(S) < dlen + PAD then + S = buffer.create(dlen + PAD + 4096) + st.S = S + end + buffer.copy(S, 0, buf, o, dlen) + buffer.fill(S, dlen, 0, PAD) + local C, bytes = st.channels, st.bytes + local shift = if bytes == 2 then 9 else 10 -- the filter's precision per sample size + local fdiv = 2 ^ shift + local round = fdiv // 2 + local pk = if bytes == 1 then 16 else 32 -- the fixed predictor: last * (pk - 1) / pk + local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur + for c = 0, C - 1 do + R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 + E[c + 1], last[c + 1] = 0, 0 + for i = 1, 8 do + Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 + end + end + local pos = 0 -- bit position + local lim = dlen * 8 + local c = 0 -- the channel of the sample at idx + for idx = 1, n * C do + do + if pos > lim then + return nil, "truncated frame" + end + -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) + local unary + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + unary = ones + pos += ones + 1 + else + local u, p2 = longUnary(S, pos, lim) + if not u then + return nil, "truncated frame" + end + unary, pos = u, p2 + end + local rb = c * 4 + local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] + local deep = unary > 0 + local k + if deep then + k = k1 + unary -= 1 + else + k = k0 + end + local value = unary + if k > 0 then + local bits + if k <= 24 then + bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) + else + local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) + local p2 = pos + 16 + bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 + end + pos += k + value = unary * P2[k + 1] + bits + end + if deep then + s1 += value - s1 // 16 + if k1 > 0 and s1 < P2[k1 + 5] then + k1 -= 1 + elseif s1 > P2[k1 + 6] then + k1 += 1 + end + value += P2[k0 + 1] + end + s0 += value - s0 // 16 + if k0 > 0 and s0 < P2[k0 + 5] then + k0 -= 1 + elseif s0 > P2[k0 + 6] then + k0 += 1 + end + R[rb + 1] = math.min(k0, 31) + R[rb + 2] = math.min(k1, 31) + R[rb + 3] = s0 + R[rb + 4] = s1 + local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) + value = (value + odd) // 2 * (2 * odd - 1) + -- the adaptive filter: the weights step toward the sign of the last residual + local fb = c * 8 + local err = E[c + 1] + -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) + local dq = max(-1, min(1, err)) + local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] + local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] + local q1 = Q[fb + 1] + x1 * dq + local q2 = Q[fb + 2] + x2 * dq + local q3 = Q[fb + 3] + x3 * dq + local q4 = Q[fb + 4] + x4 * dq + local q5 = Q[fb + 5] + x5 * dq + local q6 = Q[fb + 6] + x6 * dq + local q7 = Q[fb + 7] + x7 * dq + local q8 = Q[fb + 8] + x8 * dq + Q[fb + 1] = q1 + Q[fb + 2] = q2 + Q[fb + 3] = q3 + Q[fb + 4] = q4 + Q[fb + 5] = q5 + Q[fb + 6] = q6 + Q[fb + 7] = q7 + Q[fb + 8] = q8 + local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] + local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] + local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 + if sum >= TWO31 or sum < -TWO31 then + sum = (sum + TWO31) % TWO32 - TWO31 + end + -- the steps follow the delay line's signs (x 1, 2, 2, 4) + X[fb + 1] = x2 + X[fb + 2] = x3 + X[fb + 3] = x4 + X[fb + 4] = x5 + X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) + X[fb + 6] = 2 + 4 * floor(l6 * INV31) + X[fb + 7] = 2 + 4 * floor(l7 * INV31) + X[fb + 8] = 4 + 8 * floor(l8 * INV31) + E[c + 1] = value + value += sum // fdiv + -- the delay line: the last value and its first and second differences + local n7 = value - l8 + local n6 = n7 - l7 + L[fb + 1] = l2 + L[fb + 2] = l3 + L[fb + 3] = l4 + L[fb + 4] = l5 + L[fb + 5] = n6 - l6 + L[fb + 6] = n6 + L[fb + 7] = n7 + L[fb + 8] = value + -- the fixed predictor + value += (last[c + 1] * (pk - 1)) // pk + last[c + 1] = value + cur[c + 1] = value + end + c += 1 + if c == C then + -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences + c = 0 + local o = idx - C + if C == 1 then + P[idx] = cur[1] + elseif C == 2 then + local a = cur[1] + local b = cur[2] + (if a >= 0 then a // 2 else -((-a) // 2)) + P[o + 1], P[o + 2] = b - a, b + else + local a = cur[C - 1] + cur[C] += if a >= 0 then a // 2 else -((-a) // 2) + for r = C - 1, 1, -1 do + cur[r] = cur[r + 1] - cur[r] + end + for k = 1, C do + P[o + k] = cur[k] + end + end + end + end + if pos > lim then + return nil, "truncated frame" + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/Vorbis"] = function() + +-- 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 = __include("codecs/audio/Vorbis/Setup"), + Codebook = __include("codecs/audio/Vorbis/Codebook"), + Packet = __include("codecs/audio/Vorbis/Packet"), + Tables = __include("codecs/audio/Vorbis/Tables"), +} + +return Vorbis +end +__FILES["codecs/audio/Vorbis/Codebook"] = @native function() + + + +-- 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 +-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. +-- +-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); +-- an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit reader +type Br = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits (LSB first) + cnt: number, + pad: number, -- how many of the top bits of acc are past the end of the packet + eop: boolean, -- read past the end of the packet +} + +@native function Codebook.reader(buf: buffer, offset: number, size: number): Br + return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +-- bits(br, n) -> the next n (0..32) bits as an unsigned number +@native local function bits(br: Br, n: number): number + if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt -= n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog(x): the number of bits needed to hold x (0 for x <= 0) +@native local function ilog(x: number): number + local n = 0 + while x > 0 do + n += 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +@native local function float32Unpack(x: number): number + local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return if sign then -v else v +end + +-- ------------------------------------------------------------------------------------------------ codebooks +type Book = { + dims: number, + entries: number, + fastBits: number, + fastLen: { number }, -- per fastBits-bit prefix: code length (> 0), 0 = continue in the tree, -1 = invalid + fastSym: { number }, -- symbol, or the tree node to continue from + c0: { number }, -- tree: child for bit 0 / 1: > 0 node, < 0 leaf (-symbol - 1), 0 none + c1: { number }, + lookup: number, -- 0, 1, 2 + vq: { number }?, -- entries * dims values (lookup 1 / 2, expanded) + used: number, -- entries with a codeword +} + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +@native local function lookup1Values(entries: number, dims: number): number + local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r += 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +@native local function build(book: Book, lengths: { number }): string? + local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code: number + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z -= 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- walk the MSB-first code into the tree + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = if bit == 0 then c0[node] else c1[node] + if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes += 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used += 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = if bit == 0 then c0[node] else c1[node] + if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break -- invalid (-1) + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +-- read(br) -> Book | nil, message: one codebook from the setup header +@native function Codebook.read(br: Br): (Book?, string?) + if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur += num + len += 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book: Book = { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div *= nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) +@native local function decode(br: Br, book: Book): number + local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc += readu8(b, p) * POW[cnt + 1] + p += 1 + else + br.pad += 8 + end + cnt += 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt -= l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = if bits(br, 1) == 0 then c0[node] else c1[node] + if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook +end +__FILES["codecs/audio/Vorbis/Packet"] = @native function() + + + +-- 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 +-- granule positions count exactly the samples returned (the first packet returns none). +-- +-- local st = Packet.new(ident, setup) +-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet +-- 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 = __include("codecs/audio/Vorbis/Codebook") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Tables = __include("codecs/audio/Vorbis/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + +type State = { + channels: number, + n0: number, + n1: number, + setup: Setup.Setup, + plans: { [number]: Mdct.Plan }, + slopes: { [number]: { number } }, -- rising half-window of overlap length L (= blocksize / 2) + spec: { { number } }, -- per channel: n/2 spectral values (residue, then times the floor) + frame: { { number } }, -- per channel: n windowed time samples + tail: { { number } }, -- per channel: the previous frame from its centre on + tailLen: number, + prevN: number, -- the previous block size, 0 = no previous frame + out: { { number } }, -- per channel: the returned samples + finalY: { { number } }, + step2: { number }, + inter: { number }, -- residue type 2 interleaved scratch + zero: { boolean }, + reallyZero: { boolean }, + partClass: { { { number } } }, +} + +@native function Packet.new(id: Setup.Ident, setup: Setup.Setup): State? + local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans: { [number]: Mdct.Plan } = {} + local slopes: { [number]: { number } } = {} + for _, n in { n0, n1 } do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = Mdct.window("vorbis", n) :: { number } + local half = table.create(n // 2, 0) + for i = 1, n // 2 do + half[i] = w[i] + end + slopes[n // 2] = half + end + @native local function arrays(len: number): { { number } } + local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(n1 // 2), + frame = arrays(n1), + tail = arrays(n1 // 2), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(n1 // 2 * ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +@native function Packet.reset(st: State) + st.prevN = 0 + st.tailLen = 0 +end + +-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) +@native function Packet.blocksize(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return if mode.blockflag == 1 then st.n1 else st.n0 +end + +-- ------------------------------------------------------------------------------------------------ floor 1 +@native local function predict(x: number, x0: number, x1: number, y0: number, y1: number): number + local dy = y1 - y0 + local adx = x1 - x0 + local off = ((if dy < 0 then -dy else dy) * (x - x0)) // adx + return if dy < 0 then y0 - off else y0 + off +end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +@native local function drawLine(out: { number }, x0: number, y0: number, x1: number, y1: number, n: number) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = if dy < 0 then -dy else dy + local base = if dy < 0 then -(ady // adx) else ady // adx + local sy = if dy < 0 then base - 1 else base + 1 + ady -= (if base < 0 then -base else base) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + while x < x1 do + err += ady + if err >= adx then + err -= adx + y += sy + else + y += base + end + out[x + 1] *= INV_DB[y % 256 + 1] + x += 1 + end + end +end + +-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent +@native local function floorDecode(st: State, br: Codebook.Br, g: Setup.Floor1, finalY: { number }): boolean + if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = cval // csub + if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset += 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = if highroom < lowroom then highroom * 2 else lowroom * 2 + if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - (val + 1) // 2 + else + finalY[j + 1] = pred + val // 2 + end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +@native local function floorCurve(g: Setup.Floor1, finalY: { number }, target: { number }, n2: number) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j] *= v + end + end +end + +-- ------------------------------------------------------------------------------------------------ residue +-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) +@native local function partition(br: Codebook.Br, book: Codebook.Book, target: { number }, offset: number, psize: number, rtype: number, limit: number): boolean + local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = psize // dims + for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then + target[at + 1] += vq[base + i + 1] + end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then + target[at + i + 1] += vq[base + i + 1] + end + end + k += dims + end + end + return true +end + +-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each +@native local function residue(st: State, br: Codebook.Br, r: Setup.Residue, targets: { { number } | false }, ch: number, n2: number) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t :: { number })[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = (le - lb) // psize + local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i += 1 + pcount += 1 + end + if done then + break + end + classSet += 1 + end + end + -- de-interleave into the channels that are decoded + for j = 1, ch do + local t = targets[j] + if t then + local tt = t :: { number } + local v = j + for i = 1, n2 do + tt[i] = inter[v] + v += ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = (le - lb) // psize + local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t :: { number }, r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i += 1 + pcount += 1 + end + classSet += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ packet +-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet +@native function Packet.decode(st: State, b: buffer, off: number, size: number): number + if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = n // 2 + local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = (n - n0) // 4, (n + n0) // 4 + else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = (n * 3 - n0) // 4, (n * 3 + n0) // 4 + else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + -- floors + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + -- residues, per submap + for i = 1, map.submaps do + local targets: { { number } | false } = {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k += 1 + targets[k] = if zero[c] then false else spec[c] + end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + -- inverse coupling + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + -- floor curves, IMDCT, windows + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do + fr[leftStart + j + 1] *= lslope[j + 1] + end + local R = rightEnd - rightStart + for j = 0, R - 1 do + fr[rightStart + j + 1] *= rslope[R - j] + end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = prevN // 4 + n // 4 + local o = prevN // 4 - n // 4 -- this frame starts o samples after the previous centre + local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = if j < tl then tail[j + 1] else 0 + local fi = j - o + if fi >= 0 then + v += fr[fi + 1] + end + out[j + 1] = v + end + end + end + -- the new tail: this frame from its centre to the end of its window + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet +end +__FILES["codecs/audio/Vorbis/Setup"] = @native function() + + +-- 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 = __include("codecs/audio/Vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + +type Ident = { + channels: number, + sampleRate: number, + bitrateMax: number, + bitrateNominal: number, + bitrateMin: number, + blocksize0: number, + blocksize1: number, +} + +type Floor1 = { + partitions: number, + partitionClass: { number }, -- 1-based list of class numbers (0-based values) + classDims: { number }, -- [class + 1] + classSubs: { number }, + classMaster: { number }, + subBooks: { { number } }, -- [class + 1][sub + 1] = book (0-based) or -1 + multiplier: number, + xlist: { number }, -- [j + 1] + values: number, + sorted: { number }, -- point indices (0-based) by increasing x + low: { number }, -- neighbours, [j + 1] (0-based indices) + high: { number }, +} + +type Residue = { + type: number, + begin: number, + finish: number, + partSize: number, + classifications: number, + classbook: number, + books: { { number } }, -- [class + 1][pass + 1] = book or -1 + classdata: { { number } }, -- [classbook entry + 1][k + 1] = class +} + +type Mapping = { + submaps: number, + couplingSteps: number, + magnitude: { number }, -- [step + 1] channel (0-based) + angle: { number }, + mux: { number }, -- [channel + 1] submap (0-based) + submapFloor: { number }, + submapResidue: { number }, +} + +type Mode = { blockflag: number, mapping: number } + +type Setup = { + books: { Codebook.Book }, + floors: { Floor1 }, + residues: { Residue }, + mappings: { Mapping }, + modes: { Mode }, + modeBits: number, + maxFloorValues: number, +} + +@native local function isVorbis(b: buffer, o: number, n: number, kind: number): boolean + return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +-- ident(buf, offset, size) -> Ident | nil, message +@native function Setup.ident(b: buffer, o: number, n: number): (Ident?, string?) + if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, bs // 16 + if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message +@native function Setup.comment(b: buffer, o: number, n: number): (string?, { string }?) + if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p += 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p += vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p += 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p += 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p += len + end + return vendor, list +end + +-- setup(buf, offset, size, ident) -> Setup | nil, message +@native function Setup.setup(b: buffer, o: number, n: number, id: Ident): (Setup?, string?) + if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + -- codebooks + local books: { Codebook.Book } = {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + -- floors + local floors: { Floor1 } = {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, @native function(a: number, c: number): boolean + return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + -- residues + local residues: { Residue } = {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = if bits(br, 1) == 1 then bits(br, 5) else 0 + cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = c // 2 + end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = tmp // ncls + end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + -- mappings + local mappings: { Mapping } = {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = if bits(br, 1) == 1 then bits(br, 4) + 1 else 1 + local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + -- modes + local modes: { Mode } = {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup +end +__FILES["codecs/audio/Vorbis/Tables"] = function() + +-- 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, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) +end +__FILES["codecs/audio/VorbisComment"] = function() + +-- 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 rosetta (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 = {} + +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 +end +__FILES["codecs/audio/WavPack"] = function() + +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec +-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in +-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 +-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo +-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross +-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). +-- +-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) +-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) +-- local dec = WavPack.decoder(info.channels) +-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) +-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Block = __include("codecs/audio/WavPack/Block") + +local WavPack = {} + +type Header = { + size: number, -- the whole block (ckSize + 8) + version: number, + index: number, -- the first sample of the block (40 bits) + total: number, -- total samples of the file (-1: unknown) + samples: number, + flags: number, + crc: number, +} + +local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } +WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 +WavPack.DSD = 0x80000000 + +-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit +function WavPack.header(buf: buffer, at: number, limit: number?): (Header?, string?) + local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) + if at < 0 or at + 32 > lim then + return nil, "truncated block header" + end + if buffer.readstring(buf, at, 4) ~= "wvpk" then + return nil, "no block header" + end + local ck = buffer.readu32(buf, at + 4) + local version = buffer.readu16(buf, at + 8) + if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then + return nil, "bad block size" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. string.format("0x%x", version) + end + local total = buffer.readu32(buf, at + 12) + local tu8 = buffer.readu8(buf, at + 11) + local h: Header = { + size = ck + 8, + version = version, + index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, + total = if total == 0xFFFFFFFF then -1 else total + tu8 * 4294967296 - tu8, + samples = buffer.readu32(buf, at + 20), + flags = buffer.readu32(buf, at + 24), + crc = buffer.readu32(buf, at + 28), + } + if at + h.size > lim then + return nil, "truncated block" + end + return h, nil +end + +type Info = { + channels: number, + channelMask: number, + sampleRate: number, + bitsPerSample: number, -- the source depth (container bytes * 8 - shift) + bytesPerSample: number, -- the container: 1 .. 4 + float: boolean, + hybrid: boolean, + md5: string?, -- 32 hex digits when stored + version: number, +} + +-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` +function WavPack.info(buf: buffer, at: number, limit: number?): (Info?, Err.Err?) + local h, herr = WavPack.header(buf, at, limit) + if not h then + return nil, Err.from(herr, at) + end + local m, merr = Block.meta(buf, at, h.size) + if not m then + return nil, Err.from(merr, at) + end + local flags = h.flags + if bit32.band(flags, WavPack.DSD) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "DSD audio") + end + local bytes = bit32.band(flags, 3) + 1 + local info: Info = { + channels = if bit32.band(flags, WavPack.MONO) ~= 0 then 1 else 2, + channelMask = 0, + sampleRate = 44100, + bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), + bytesPerSample = bytes, + float = bit32.band(flags, WavPack.FLOAT) ~= 0, + hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, + version = h.version, + } + info.channelMask = if info.channels == 1 then 4 else 3 + local sr = bit32.band(bit32.rshift(flags, 23), 15) + if sr < 15 then + info.sampleRate = RATES[sr + 1] + end + local o = m[0x27] -- ID_SAMPLE_RATE + if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then + local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 + if m[0x27 + 256] == 4 then + rate += bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 + end + info.sampleRate = rate + end + o = m[0xD] -- ID_CHANNEL_INFO + if o then + local len = m[0xD + 256] + if len == 0 or len > 7 then + return nil, Err.new(Err.CORRUPT, "bad channel info", o) + end + local mask = 0 + if len >= 6 then + info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 + mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 + if len == 7 then + mask += buffer.readu8(buf, o + 6) * 16777216 + end + else + info.channels = buffer.readu8(buf, o) + for k = 1, len - 1 do + mask += buffer.readu8(buf, o + k) * 256 ^ (k - 1) + end + end + info.channelMask = mask + end + if info.channels < 1 then + return nil, Err.new(Err.CORRUPT, "no channels") + end + if info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + return info, nil +end + +-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` +function WavPack.md5(buf: buffer, at: number, limit: number?): string? + local h = WavPack.header(buf, at, limit) + if not h then + return nil + end + local m = Block.meta(buf, at, h.size) + if not m then + return nil + end + local o = m[0x26] + if not o or m[0x26 + 256] ~= 16 then + return nil + end + local hex = table.create(16, "") + for k = 0, 15 do + hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) + end + return table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ decoder +type Decoder = { + channels: number, + pcm: { number }, -- the last frame's samples, interleaved (integers in the container range, or floats) + frame: (self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?) -> (number?, Err.Err?), + state: Block.State, +} + +-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per +-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) +local function frame(self: Decoder, buf: buffer, blocks: { number }, cbuf: buffer?, cblocks: { number }?): (number?, Err.Err?) + local C = self.channels + local n = -1 + local c0 = 0 + for i, at in blocks do + if c0 >= C then + break + end + local h, herr = WavPack.header(buf, at) + if not h then + return nil, Err.from(herr, at) + end + if n < 0 then + n = h.samples + if n * C > 16777216 then + return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) + end + if #self.pcm < n * C then + self.pcm = table.create(n * C, 0) + end + elseif h.samples ~= n then + return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) + end + local cb, cp, cs = nil, nil, nil + if cbuf and cblocks and cblocks[i] then + local ch = WavPack.header(cbuf, cblocks[i]) + if ch and ch.samples == h.samples and ch.index == h.index then + cb, cp, cs = cbuf, cblocks[i], ch.size + end + end + local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) + if not got then + return nil, Err.from(msg, at) + end + c0 += got + end + if n < 0 then + return 0, nil + end + if c0 < C then + return nil, Err.new(Err.CORRUPT, "a frame is missing channels") + end + return n, nil +end + +-- decoder(channels) -> Decoder +function WavPack.decoder(channels: number): Decoder + return { + channels = channels, + pcm = table.create(4096 * channels, 0), + frame = frame, + state = Block.state(), + } +end + +WavPack.checksum = Block.checksum +WavPack.meta = Block.meta + +return WavPack +end +__FILES["codecs/audio/WavPack/Block"] = @native function() + + + +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from +-- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint +-- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), +-- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, +-- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block +-- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. +-- Never throws: returns nil, message. +local Tables = __include("codecs/audio/WavPack/Tables") + +local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 +local writeu32, readf32 = buffer.writeu32, buffer.readf32 +local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz +local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight +local sign, clamp = math.sign, math.clamp + +local Block = {} + +local TWO32 = 4294967296 +local P2: { number } = table.create(34, 0) -- P2[k + 1] = 2^k +for i = 0, 33 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the number of trailing 1 bits of the byte b +local ONES: { number } = table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n += 1 + v = v // 2 + end + ONES[b + 1] = n +end + +-- header flags +local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 +local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 +local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 +local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer +local MAX_SAMPLES = 2 ^ 20 -- per block +local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front + +-- ------------------------------------------------------------------------------------------------ metadata +type Meta = { [number]: number } -- id -> offset; id + 256 -> byte length + +-- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) +@native function Block.meta(buf: buffer, p: number, size: number): (Meta?, string?) + local m: Meta = {} + local q, stop = p + 32, p + size + while stop - q >= 2 do + local id = readu8(buf, q) + local len = readu8(buf, q + 1) * 2 + q += 2 + if band(id, 0x80) ~= 0 then + if stop - q < 2 then + return nil, "truncated metadata" + end + len += readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 + q += 2 + id -= 0x80 + end + local odd = 0 + if band(id, 0x40) ~= 0 then + if len == 0 then + return nil, "odd-sized empty metadata" + end + id -= 0x40 + len -= 1 + odd = 1 + end + if stop - q < len + odd then + return nil, "truncated metadata" + end + m[id] = q + m[id + 256] = len + q += len + odd + end + return m, nil +end + +-- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches +@native function Block.checksum(buf: buffer, p: number, m: Meta): boolean + local o = m[0x2F] + if not o then + return true + end + local len = m[0x2F + 256] + if len ~= 2 and len ~= 4 then + return false + end + local words = (o - 2 - p) // 2 + local csum = TWO32 - 1 + for i = 0, words - 1 do + csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 + end + if len == 4 then + return readu32(buf, o) == csum + end + csum = bit32.bxor(csum, rshift(csum, 16)) + return readu16(buf, o) == band(csum, 0xFFFF) +end + +-- ------------------------------------------------------------------------------------------------ state +type Reader = { b: buffer, p: number, e: number, n: number } +type State = { [string]: any } + +@native function Block.state(): State + return { + W = table.create(D2 + 2 * 4096, 0), + term = table.create(16, 0), + delta = table.create(16, 0), + wA = table.create(16, 0), + wB = table.create(16, 0), + sA = table.create(16 * 8, 0), + sB = table.create(16 * 8, 0), + med = table.create(6, 0), + slow = { 0, 0 }, + limit = { 0, 0 }, + bacc = { 0, 0 }, + bdelta = { 0, 0 }, + sacc = { 0, 0 }, + sdelta = { 0, 0 }, + err = { 0, 0 }, + R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } :: Reader, + scratch = buffer.create(4), + } +end + +-- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them +@native local function openReader(R: Reader, buf: buffer, o: number, len: number) + if buffer.len(R.b) < len + PAD then + R.b = buffer.create(len + PAD + 1024) + else + buffer.fill(R.b, len, 0, PAD) + end + buffer.copy(R.b, 0, buf, o, len) + R.p = 0 + R.e = len * 8 + R.n = len + PAD +end + +-- ------------------------------------------------------------------------------------------------ bit reading +-- bits(R, n) -> the next n (<= 32) bits, LSB first +@native local function bits(R: Reader, n: number): number + if n <= 0 then + return 0 + end + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 -- overrun: the caller's end check fails + return 0 + end + local b = R.b + if n <= 25 then + R.p = p + n + return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) + end + local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) + p += 16 + R.p = p + n - 16 + return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 +end + +@native local function bit(R: Reader): number + return bits(R, 1) +end + +-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 +-- after them when fewer than max +@native local function trailing(R: Reader, max: number): number + local c = 0 + while c < max do + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return max + end + local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] + if ones < 8 then + if c + ones >= max then + R.p = p + (max - c) + return max + end + R.p = p + ones + 1 + return c + ones + end + c += 8 + R.p = p + 8 + end + -- (max reached inside a run of 8: give back the extra ones) + R.p -= c - max + return max +end + +-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) +@native local function gamma(R: Reader): number? + local c = trailing(R, 33) + if c == 33 then + return nil + end + if c < 2 then + return c + end + return bits(R, c - 1) + P2[c] +end + +-- readCode(R, maxcode) -> 0 .. maxcode (read_code) +@native local function readCode(R: Reader, maxcode: number): number + if maxcode < 2 then + return if maxcode == 1 then bits(R, 1) else 0 + end + local bc = 32 - countlz(maxcode) + local extras = P2[bc + 1] - maxcode - 1 + local code = bits(R, bc - 1) + if code >= extras then + code = code * 2 - extras + bits(R, 1) + end + return code +end + +-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) +@native local function onesCount(R: Reader): number? + local c = trailing(R, 17) + if c == 17 then + return nil + end + if c == 16 then + local g = gamma(R) + if not g then + return nil + end + c = g + 16 + end + return c +end + +-- ------------------------------------------------------------------------------------------------ lossless entropy +-- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot +-- loop of get_words_lossless, with the bit reader in locals) +@native local function wordsLossless(st: State, count: number, d: number): boolean + local R: Reader = st.R1 + local b, pos, lim = R.b, R.p, R.e + local W = st.W + local med = st.med + local stereo = d == D2 + -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo + local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] + if not stereo then + a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 + end + local hz, ho, za = 0, 0, 0 + for idx = d, d + count - 1 do + if stereo then + a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 + end + if pos > lim then + return false + end + if hz ~= 0 then + hz = 0 + local maxcode = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local low, used = 0, 0 + if maxcode < 2 then + if maxcode == 1 then + low, used = band(w, 1), 1 + end + else + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low = readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + low = band(w, P2[bc] - 1) + if low >= extras then + low = low * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + continue + end + if a0 < 2 and ho == 0 and c0 < 2 then + if za > 0 then + za -= 1 + if za > 0 then + W[idx] = 0 + continue + end + else + R.p = pos + local g = gamma(R) + pos = R.p + if not g then + return false + end + za = g + if za > 0 then + a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 + W[idx] = 0 + continue + end + end + end + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones == 8 then + ones = 8 + ONES[band(rshift(w, 8), 255) + 1] + end + if ones < 16 then + pos += ones + 1 + else + if band(w, 0x10000) ~= 0 then + return false + end + R.p = pos + 17 + local g = gamma(R) + pos = R.p + if not g then + return false + end + ones = g + 16 + end + local hold = ho + ho = band(ones, 1) + hz = 1 - ho + ones = ones // 2 + hold + local low, high + if ones == 0 then + low = 0 + high = a0 // 16 + a0 -= ((a0 + 126) // 128) * 2 + else + low = a0 // 16 + 1 + a0 += ((a0 + 128) // 128) * 5 + if ones == 1 then + high = low + a1 // 16 + a1 -= ((a1 + 62) // 64) * 2 + else + low += a1 // 16 + 1 + a1 += ((a1 + 64) // 64) * 5 + if ones == 2 then + high = low + a2 // 16 + a2 -= ((a2 + 30) // 32) * 2 + else + low += (ones - 2) * (a2 // 16 + 1) + high = low + a2 // 16 + a2 += ((a2 + 32) // 32) * 5 + end + end + end + local maxcode = high - low + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local used = 0 + if maxcode < 2 then + if maxcode == 1 then + low += band(w, 1) + used = 1 + end + else + if maxcode >= 536870912 then + return false + end + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low += readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + local code = band(w, P2[bc] - 1) + if code >= extras then + code = code * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + low += code + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos += used + 1 + end + R.p = pos + return pos <= lim +end + +-- ------------------------------------------------------------------------------------------------ hybrid entropy +@native local function updateErrorLimit(st: State, flags: number, mono: boolean) + local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit + bacc[1] = (bacc[1] + bdelta[1]) % TWO32 + local br0 = bacc[1] // 65536 + if mono then + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + end + return + end + bacc[2] = (bacc[2] + bdelta[2]) % TWO32 + local br1 = bacc[2] // 65536 + if band(flags, HBITRATE) ~= 0 then + local sl0 = (slow[1] + 128) // 256 + local sl1 = (slow[2] + 128) // 256 + if band(flags, HBALANCE) ~= 0 then + local balance = (sl1 - sl0 + br1 + 1) // 2 + if balance > br0 then + br1 = br0 * 2 + br0 = 0 + elseif -balance > br0 then + br0 = br0 * 2 + br1 = 0 + else + br1 = br0 + balance + br0 = br0 - balance + end + end + limit[1] = if sl0 - br0 > -256 then exp2s(sl0 - br0 + 256) % TWO32 else 0 + limit[2] = if sl1 - br1 > -256 then exp2s(sl1 - br1 + 256) % TWO32 else 0 + else + limit[1] = exp2s(br0) % TWO32 + limit[2] = exp2s(br1) % TWO32 + end +end + +-- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +@native local function getWord(st: State, chan: number, flags: number, mono: boolean): (number?, number) + local R: Reader = st.R1 + local med = st.med + local mb = chan * 3 + local correction = 0 + if R.p > R.e then + return nil, 0 + end + if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then + if st.za > 0 then + st.za -= 1 + if st.za > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + return 0, 0 + end + else + local g = gamma(R) + if not g then + return nil, 0 + end + st.za = g + if g > 0 then + local s = st.slow + s[chan + 1] -= (s[chan + 1] + 128) // 256 + for k = 1, 6 do + med[k] = 0 + end + return 0, 0 + end + end + end + local ones + if st.hz ~= 0 then + ones = 0 + st.hz = 0 + else + local c = onesCount(R) + if not c then + return nil, 0 + end + ones = c + if st.ho ~= 0 then + st.ho = band(ones, 1) + ones = ones // 2 + 1 + else + st.ho = band(ones, 1) + ones = ones // 2 + end + st.hz = 1 - st.ho + end + if band(flags, HYBRID) ~= 0 and chan == 0 then + updateErrorLimit(st, flags, mono) + end + local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] + local low, high + if ones == 0 then + low = 0 + high = m0 // 16 + m0 -= ((m0 + 126) // 128) * 2 + else + low = m0 // 16 + 1 + m0 += ((m0 + 128) // 128) * 5 + if ones == 1 then + high = low + m1 // 16 + m1 -= ((m1 + 62) // 64) * 2 + else + low += m1 // 16 + 1 + m1 += ((m1 + 64) // 64) * 5 + if ones == 2 then + high = low + m2 // 16 + m2 -= ((m2 + 30) // 32) * 2 + else + low += (ones - 2) * (m2 // 16 + 1) + high = low + m2 // 16 + m2 += ((m2 + 32) // 32) * 5 + end + end + end + med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 + low = band(low % TWO32, 0x7FFFFFFF) + high = band(high % TWO32, 0x7FFFFFFF) + if low > high then + high = low + end + local mid = (high + low + 1) // 2 + local limit = st.limit[chan + 1] + if limit == 0 then + mid = readCode(R, high - low) + low + else + while high - low > limit do + if R.p > R.e then + return nil, 0 + end + if bits(R, 1) == 1 then + low = mid + mid = (high + low + 1) // 2 + else + high = mid - 1 + mid = (high + low + 1) // 2 + end + end + end + local sign = bits(R, 1) + if st.wvc and limit ~= 0 then + local value = readCode(st.R2, high - low) + low + correction = if sign == 1 then mid - value else value - mid + end + if band(flags, HBITRATE) ~= 0 then + local s = st.slow + s[chan + 1] = s[chan + 1] - (s[chan + 1] + 128) // 256 + log2(mid) + end + return if sign == 1 then -mid - 1 else mid, correction +end + +-- ------------------------------------------------------------------------------------------------ decorrelation +-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass +@native local function passesStereo(st: State, n: number) + local W = st.W + local last = D2 + 2 * n - 2 + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + for t = 1, st.nterms do + local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D2, last, 2 do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + sam = b0 + (b0 - b1) // dv + x = W[i + 1] + o = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + b1, b0 = b0, o + W[i + 1] = o + end + elseif term > 0 then + for j = 0, term - 1 do + W[D2 + 2 * (j - term)] = sA[so + j + 1] + W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] + end + local back = 2 * term + for i = D2, last, 2 do + local sam = W[i - back] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + sam = W[i + 1 - back] + x = W[i + 1] + W[i + 1] = (wB * sam + 512) // 1024 + x + wB += delta * sign(sam * x) + end + elseif term == -1 then + local sa = sA[so + 1] + for i = D2, last, 2 do + local x = W[i] + local sam = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + W[i] = sam + x = W[i + 1] + sa = x + (wB * sam + 512) // 1024 + wB = clamp(wB + delta * sign(sam * x), -1024, 1024) + W[i + 1] = sa + end + elseif term == -2 then + local sb = sB[so + 1] + for i = D2, last, 2 do + local x = W[i + 1] + local sam = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i + 1] = sam + x = W[i] + sb = x + (wA * sam + 512) // 1024 + wA = clamp(wA + delta * sign(sam * x), -1024, 1024) + W[i] = sb + end + else -- -3 + local sa, sb = sA[so + 1], sB[so + 1] + for i = D2, last, 2 do + local x = W[i] + local samA = x + (wA * sa + 512) // 1024 + wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + x = W[i + 1] + local samB = x + (wB * sb + 512) // 1024 + wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i], W[i + 1] = samA, samB + sa, sb = samB, samA + end + end + end +end + +-- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass +@native local function passesMono(st: State, n: number) + local W = st.W + local last = D1 + n - 1 + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + for t = 1, st.nterms do + local term, delta, wA = terms[t], deltas[t], wAs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1 = sA[so + 1], sA[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D1, last do + local sam = a0 + (a0 - a1) // dv + local x = W[i] + local o = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + end + else + for j = 0, term - 1 do + W[D1 + j - term] = sA[so + j + 1] + end + for i = D1, last do + local sam = W[i - term] + local x = W[i] + W[i] = (wA * sam + 512) // 1024 + x + wA += delta * sign(sam * x) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ hybrid lossless +@native local function shaped(st: State, c: number, flags: number, correction: number): number + -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) + local sacc, sdelta, err = st.sacc, st.sdelta, st.err + sacc[c] = (sacc[c] + sdelta[c]) % TWO32 + local sw = sacc[c] // 65536 + if sw >= 32768 then + sw -= 65536 + end + local temp = -((sw * err[c] + 512) // 1024) + if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then + if temp == err[c] then + temp = if temp < 0 then temp + 1 else temp - 1 + end + err[c] = temp - correction + else + err[c] = -correction + end + return temp +end + +@native local function hybridMono(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + for i = 0, n - 1 do + local word, corr = getWord(st, 0, flags, true) + if not word then + return false + end + local rw = word + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + local sam, k + if term > 8 then + sam = if term % 2 == 1 then 2 * sA[so + 1] - sA[so + 2] else (3 * sA[so + 1] - sA[so + 2]) // 2 + sA[so + 2] = sA[so + 1] + k = 0 + else + sam = sA[so + m + 1] + k = band(m + term, 7) + end + local temp = (wAs[t] * sam + 512) // 1024 + rw + wAs[t] += deltas[t] * sign(sam * rw) + sA[so + k + 1] = temp + rw = temp + end + m = band(m + 1, 7) + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, corr) + rw += corr - temp + else + rw += corr + end + crc = (crc * 3 + rw) % TWO32 + W[D1 + i] = rw + end + st.crcv = crc + return true +end + +@native local function hybridStereo(st: State, n: number, flags: number): boolean + local W = st.W + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + local cross = band(flags, CROSS) ~= 0 + local joint = band(flags, JOINT) ~= 0 + for i = 0, n - 1 do + local left, corr0 = getWord(st, 0, flags, false) + if not left then + return false + end + local right, corr1 = getWord(st, 1, flags, false) + if not right then + return false + end + local leftc, rightc = 0, 0 + if cross then + leftc, rightc = left + corr0, right + corr1 + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + if term > 0 then + local samA, samB + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + end + leftc += (wAs[t] * samA + 512) // 1024 + rightc += (wBs[t] * samB + 512) // 1024 + elseif term == -1 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + rightc += (wBs[t] * leftc + 512) // 1024 + else + rightc += (wBs[t] * sB[so + 1] + 512) // 1024 + if term == -3 then + leftc += (wAs[t] * sA[so + 1] + 512) // 1024 + else + leftc += (wAs[t] * rightc + 512) // 1024 + end + end + end + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + for t = 1, nterms do + local term, delta, so = terms[t], deltas[t], (t - 1) * 8 + if term > 0 then + local samA, samB, k + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = (3 * sA[so + 1] - sA[so + 2]) // 2 + samB = (3 * sB[so + 1] - sB[so + 2]) // 2 + end + sA[so + 2] = sA[so + 1] + sB[so + 2] = sB[so + 1] + k = 0 + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + k = band(m + term, 7) + end + local left2 = (wAs[t] * samA + 512) // 1024 + left + local right2 = (wBs[t] * samB + 512) // 1024 + right + wAs[t] += delta * sign(samA * left) + wBs[t] += delta * sign(samB * right) + left, right = left2, right2 + sA[so + k + 1], sB[so + k + 1] = left, right + elseif term == -1 then + local sa = sA[so + 1] + local left2 = left + (wAs[t] * sa + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) + left = left2 + local right2 = right + (wBs[t] * left2 + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) + right = right2 + sA[so + 1] = right + else + local sb = sB[so + 1] + local right2 = right + (wBs[t] * sb + 512) // 1024 + wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) + right = right2 + if term == -3 then + right2 = sA[so + 1] + sA[so + 1] = right + end + local left2 = left + (wAs[t] * right2 + 512) // 1024 + wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) + left = left2 + sB[so + 1] = left + end + end + m = band(m + 1, 7) + if not cross then + leftc, rightc = left + corr0, right + corr1 + if joint then + rightc -= leftc // 2 + leftc += rightc + end + end + if joint then + right -= left // 2 + left += right + end + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, leftc - left) + left = leftc - temp + temp = shaped(st, 2, flags, rightc - right) + right = rightc - temp + else + left, right = leftc, rightc + end + crc = (crc * 9 + left * 3 + right) % TWO32 + W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right + end + st.crcv = crc + return true +end + +-- ------------------------------------------------------------------------------------------------ metadata -> state +@native local function readMeta(st: State, buf: buffer, m: Meta, flags: number, version: number): string? + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local o = m[2] + if o then -- decorrelation terms + local cnt = m[2 + 256] + if cnt > 16 then + return "too many decorrelation terms" + end + st.nterms = cnt + for i = 0, cnt - 1 do + local v = readu8(buf, o + i) + local t = cnt - i + local term = band(v, 0x1F) - 5 + if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then + return "bad decorrelation term" + end + st.term[t] = term + st.delta[t] = band(rshift(v, 5), 7) + end + end + local nterms = st.nterms + o = m[3] + if o then -- weights, from the last pass back + for t = 1, nterms do + st.wA[t], st.wB[t] = 0, 0 + end + local cnt = m[3 + 256] + if not mono then + cnt //= 2 + end + if cnt > nterms then + return "too many decorrelation weights" + end + local q = o + for t = nterms, nterms - cnt + 1, -1 do + st.wA[t] = restoreWeight(readi8(buf, q)) + q += 1 + if not mono then + st.wB[t] = restoreWeight(readi8(buf, q)) + q += 1 + end + end + end + local sA, sB = st.sA, st.sB + o = m[4] + if o then -- decorrelation samples, from the last pass back + for k = 1, nterms * 8 do + sA[k], sB[k] = 0, 0 + end + local q, stop = o, o + m[4 + 256] + if version == 0x402 and band(flags, HYBRID) ~= 0 then + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + st.err[1] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + st.err[2] = exp2s(readi16(buf, q)) + q += 2 + end + end + local t = nterms + while t >= 1 and q < stop do + local term, so = st.term[t], (t - 1) * 8 + if term > 8 then + if q + (if mono then 4 else 8) > stop then + return "bad decorrelation samples" + end + sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + if not mono then + sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + end + elseif term < 0 then + if q + 4 > stop then + return "bad decorrelation samples" + end + sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q += 4 + else + for k = 1, term do + if q + (if mono then 2 else 4) > stop then + return "bad decorrelation samples" + end + sA[so + k] = exp2s(readi16(buf, q)) + q += 2 + if not mono then + sB[so + k] = exp2s(readi16(buf, q)) + q += 2 + end + end + end + t -= 1 + end + if q ~= stop then + return "bad decorrelation samples" + end + end + o = m[5] + if o then -- entropy medians + if m[5 + 256] ~= (if mono then 6 else 12) then + return "bad entropy variables" + end + for k = 0, (if mono then 2 else 5) do + st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 + end + end + o = m[6] + if o then -- hybrid profile + local q, stop = o, o + m[6 + 256] + local w = if mono then 2 else 4 + if band(flags, HBITRATE) ~= 0 then + if q + w > stop then + return "bad hybrid profile" + end + st.slow[1] = exp2s(readu16(buf, q)) % TWO32 + if not mono then + st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 + end + q += w + end + if q + w > stop then + return "bad hybrid profile" + end + st.bacc[1] = readu16(buf, q) * 65536 + if not mono then + st.bacc[2] = readu16(buf, q + 2) * 65536 + end + q += w + if q < stop then + if q + w > stop then + return "bad hybrid profile" + end + st.bdelta[1] = exp2s(readi16(buf, q)) + if not mono then + st.bdelta[2] = exp2s(readi16(buf, q + 2)) + end + q += w + if q < stop then + return "bad hybrid profile" + end + end + end + o = m[7] + if o then -- noise shaping + local len = m[7 + 256] + if len == 2 then + st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 + st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 + elseif len >= (if mono then 4 else 8) then + st.err[1] = exp2s(readi16(buf, o)) + st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 + if not mono then + st.err[2] = exp2s(readi16(buf, o + 4)) + st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 + end + local q = o + (if mono then 4 else 8) + if len == (if mono then 6 else 12) then + st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 + if not mono then + st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 + end + end + else + return "bad shaping weights" + end + end + o = m[8] + if o then + if m[8 + 256] ~= 4 then + return "bad float info" + end + st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) + end + o = m[9] + if o then + if m[9 + 256] ~= 4 then + return "bad int32 info" + end + st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ fixup + output +-- the float conversion of one value (float_values; R = the wvx stream or nil) +@native local function floatValue(st: State, v: number, R: Reader?): number + local fflags, exp = st.fflags, st.fmaxexp + local mant, e, sign = 0, 0, 0 + if v == 0 then + if R then + if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + if exp >= 25 then + e = bits(R, 8) + end + sign = bits(R, 1) + elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then + sign = bits(R, 1) + end + end + end + else + v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 + if v >= 2147483648 then + v -= TWO32 + end + if v < 0 then + v = -v + sign = 1 + end + if R then + if v == 0x1000000 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + end + e = 255 + else + local shift = 0 + if exp > 0 then + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + end + shift = band(shift, 31) + if shift > 0 then + if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then + v += P2[shift + 1] - 1 + elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then + local mask = P2[shift + 1] - 1 + local zeros = 0 + local maxOnes, minZeros = st.fmaxones, st.fminzeros + if maxOnes > 0 and shift > maxOnes then + zeros = shift - maxOnes + end + if minZeros > zeros then + zeros = if minZeros > shift then shift else minZeros + end + local sc = shift - zeros + if sc > 0 then + v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) + end + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + else + if v >= 0x1000000 then + while band(v, 0xF000000) ~= 0 do + v //= 2 + exp += 1 + end + elseif exp > 0 then + local shift = 0 + while v < 0x800000 do + exp -= 1 + if exp == 0 then + break + end + shift += 1 + v *= 2 + end + shift = band(shift, 31) + if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then + v += P2[shift + 1] - 1 + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + end + if R then + st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 + end + local sc = st.scratch + writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) + return readf32(sc, 0) +end + +-- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +@native local function emit(st: State, flags: number, n: number, d: number, P: { number }, c0: number, C: number, lossy: boolean) + local W = st.W + local s = if d == D2 then 2 else 1 + local count = n * s + local R: Reader? = if st.wvx then st.R3 else nil + if band(flags, FLOAT) ~= 0 then + for k = 0, count - 1 do + W[d + k] = floatValue(st, W[d + k], R) + end + else + local shift = band(rshift(flags, 13), 31) + if band(flags, INT32) ~= 0 then + local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) + if R then + local maxw = st.imaxw + local crc = st.crcx + for k = d, d + count - 1 do + local v = W[k] + if sent > 0 then + if maxw > 0 then + local pv = if v < 0 then -v - 1 else v + local width = (32 - countlz(pv)) + sent + local btr = sent + if width > maxw then + btr -= width - maxw + end + if width <= maxw or btr > 0 then + v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] + else + v *= P2[sent + 1] + end + else + v = v * P2[sent + 1] + bits(R, sent) + end + end + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + v %= TWO32 + if v >= 2147483648 then + v -= TWO32 + end + crc = (crc * 9 + (v % 65536) * 3 + (v // 65536) % 65536) % TWO32 + W[k] = v + end + st.crcx = crc + elseif sent == 0 and zeros + ones + dups > 0 then + while lossy and band(flags, 3) == 3 and shift < 8 do + if zeros > 0 then + zeros -= 1 + elseif ones > 0 then + ones -= 1 + elseif dups > 0 then + dups -= 1 + else + break + end + shift += 1 + end + for k = d, d + count - 1 do + local v = W[k] + if zeros > 0 then + v *= P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + W[k] = v + end + else + shift += zeros + sent + ones + dups + end + end + shift = band(shift, 31) + if lossy then + local bytes = band(flags, 3) + local top = if bytes == 0 then 127 elseif bytes == 1 then 32767 elseif bytes == 2 then 8388607 else 2147483647 + local minv, maxv = (-top - 1) // P2[shift + 1], top // P2[shift + 1] + local mul = P2[shift + 1] + for k = d, d + count - 1 do + local v = W[k] + if v < minv then + v = minv + elseif v > maxv then + v = maxv + end + W[k] = v * mul + end + elseif shift > 0 then + local mul = P2[shift + 1] + for k = d, d + count - 1 do + W[k] *= mul + end + end + end + -- interleave + if s == 2 then + if c0 == 0 and C == 2 then + for k = 0, count - 1 do + P[k + 1] = W[d + k] + end + elseif c0 + 2 <= C then + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + P[i * C + c0 + 2] = W[d + 2 * i + 1] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + end + end + elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then + for i = 0, n - 1 do + local v = W[d + i] + P[i * C + c0 + 1] = v + P[i * C + c0 + 2] = v + end + elseif C == 1 then + for k = 0, n - 1 do + P[k + 1] = W[d + k] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + i] + end + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p +-- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given +@native function Block.decode(st: State, buf: buffer, p: number, size: number, P: { number }, c0: number, C: number, cbuf: buffer?, cp: number?, csize: number?): (number?, string?) + local version = readu16(buf, p + 8) + local n = readu32(buf, p + 20) + local flags = readu32(buf, p + 24) + local crcWant = readu32(buf, p + 28) + if band(flags, DSD) ~= 0 then + return nil, "unsupported: DSD audio" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. version + end + if n > MAX_SAMPLES then + return nil, "limit: block of " .. n .. " samples" + end + if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then + return nil, "bad block flags" + end + local mm, merr = Block.meta(buf, p, size) + if not mm then + return nil, merr + end + local m: Meta = mm + local cm: Meta = {} + local cb: buffer = buf + local hasC = false + if cbuf and cp and csize then + local cmeta, cerr = Block.meta(cbuf, cp, csize) + if not cmeta then + return nil, cerr + end + cm, cb, hasC = cmeta, cbuf, true + crcWant = readu32(cbuf, cp + 28) + end + -- reset + st.nterms = 0 + local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB + for k = 1, 128 do + sA[k], sB[k] = 0, 0 + end + for t = 1, 16 do + wA[t], wB[t] = 0, 0 + end + local med = st.med + for k = 1, 6 do + med[k] = 0 + end + st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 + st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 + st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 + st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 + st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 + st.hz, st.ho, st.za = 0, 0, 0 + st.crcx = TWO32 - 1 + st.wvc, st.wvx = false, false + local e = readMeta(st, buf, m, flags, version) + if e then + return nil, e + end + if hasC then + e = readMeta(st, cb, cm, flags, version) + if e then + return nil, e + end + end + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local out = if band(flags, MONO_FLAG) ~= 0 then 1 else 2 + if n == 0 then + return out, nil + end + -- bitstreams + local o = m[0xA] + if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then + return nil, "no audio bitstream" + end + openReader(st.R1, buf, o, m[0xA + 256]) + if hasC then + local co = cm[0xB] + if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then + openReader(st.R2, cb, co, cm[0xB + 256]) + st.wvc = true + end + end + -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) + local xb, xm = buf, m + if hasC and (cm[0xC] or cm[0x2C]) then + xb, xm = cb, cm + end + local xid = if xm[0x2C] then 0x2C elseif xm[0xC] then 0xC else nil + if xid then + local xo, xl = xm[xid], xm[xid + 256] + if xl <= 4 or xl % 2 == 1 then + return nil, "bad wvx bitstream" + end + st.crcwvx = readu32(xb, xo) + openReader(st.R3, xb, xo + 4, xl - 4) + st.wvx = true + if xid == 0x2C then + if band(flags, FLOAT) ~= 0 then + st.fminzeros = bits(st.R3, 5) + st.fmaxones = bits(st.R3, 5) + else + st.imaxw = bits(st.R3, 5) + end + end + end + local hybrid = band(flags, HYBRID) ~= 0 + local d = if mono then D1 else D2 + local W = st.W + if #W < d + 2 * n then + W = table.create(d + 2 * n + 64, 0) + st.W = W + end + local crc = TWO32 - 1 + if not st.wvc then + if hybrid then + if mono then + for i = 0, n - 1 do + local v = getWord(st, 0, flags, true) + if not v then + return nil, "bad audio bitstream" + end + W[d + i] = v + end + else + for i = 0, n - 1 do + local l = getWord(st, 0, flags, false) + local r = l and getWord(st, 1, flags, false) + if not l or not r then + return nil, "bad audio bitstream" + end + W[d + 2 * i], W[d + 2 * i + 1] = l, r + end + end + elseif not wordsLossless(st, if mono then n else 2 * n, d) then + return nil, "bad audio bitstream" + end + if mono then + passesMono(st, n) + for k = d, d + n - 1 do + crc = (crc * 3 + W[k]) % TWO32 + end + else + passesStereo(st, n) + local last = d + 2 * n - 2 + if band(flags, JOINT) ~= 0 then + for k = d, last, 2 do + local l = W[k] + local r = W[k + 1] - l // 2 + l += r + W[k], W[k + 1] = l, r + crc = (crc * 9 + l * 3 + r) % TWO32 + end + else + for k = d, last, 2 do + crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 + end + end + end + else + local ok = if mono then hybridMono(st, n, flags) else hybridStereo(st, n, flags) + if not ok then + return nil, "bad audio bitstream" + end + crc = st.crcv + end + if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then + return nil, "truncated audio bitstream" + end + if crc ~= crcWant then + return nil, "checksum: block CRC mismatch" + end + emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) + if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then + return nil, "checksum: wvx CRC mismatch" + end + return out, nil +end + +Block.bits = bits +Block.bit = bit + +return Block +end +__FILES["codecs/audio/WavPack/Tables"] = @native function() + + + +-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, +-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz + +local Tables = {} + +-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 +local LOG2: { number } = { + 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, + 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, + 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, + 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, + 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, +} +local EXP2: { number } = { + 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, + 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, + 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, + 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, + 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, +} + +-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) +@native function Tables.exp2s(lg: number): number + if lg < 0 then + local v = Tables.exp2s(-lg) + v = -(if v >= 2147483648 then v - 4294967296 else v) + return if v >= 2147483648 then v - 4294967296 else v + end + local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) + local k = lg // 256 + local r = if k <= 9 then rshift(value, 9 - k) else lshift(value, band(k - 9, 31)) + return if r >= 2147483648 then r - 4294967296 else r +end + +-- log2(v) -> wp_log2 of the uint32 v +@native function Tables.log2(v: number): number + v = (v + rshift(v, 9)) % 4294967296 + if v < 256 then + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] + end + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] +end + +-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) +@native function Tables.restoreWeight(w: number): number + local r = w * 8 + if r > 0 then + r += (r + 64) // 128 + end + return r +end + +return Tables +end +__FILES["codecs/compress/Brotli"] = function() + +-- 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("@rosetta/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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") +local Decode = __include("codecs/compress/Brotli/Decode") +local StaticData = __include("codecs/compress/Brotli/Static") + +local Brotli = {} + +type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true) +} + +-- ------------------------------------------------------------------------------------------------ static data +-- the tables are base64 text (trusted, generated by tools/brotli_static.py) +local function unbase64(s: string): buffer + return Base64.decode(s) or buffer.create(0) +end + +local static: Decode.Static? = nil + +-- tables() -> the decoded static data (inflated once, on first use) +local function tables(): (Decode.Static?, Err.Err?) + if static then + return static, nil + end + local z = unbase64(table.concat(StaticData.dictionary)) + local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize) + if not dict then + return nil, err + end + if Crc32.of(dict) ~= StaticData.dictionaryCrc then + return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged") + end + static = { + dictionary = dict, + context = unbase64(table.concat(StaticData.context)), + prefixSuffix = unbase64(StaticData.prefixSuffix), + prefixSuffixMap = StaticData.prefixSuffixMap, + transforms = StaticData.transforms, + } + return static, nil +end + +-- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) +function Brotli.dictionary(): buffer? + local s = tables() + return if s then s.dictionary else nil +end + +-- ------------------------------------------------------------------------------------------------ decompress + +-- 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, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) + if not b then + return nil, aerr + end + 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") + end + local large = not (opts and opts.largeWindow == false) + if l == 0 then + return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o) + end + local S, serr = tables() + if not S then + return nil, serr + end + local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) + if not out then + local e = Err.from(size, o) + e.message = "brotli: " .. e.message + return nil, e + end + local res = out + if buffer.len(out) ~= size then + res = buffer.create(size) + buffer.copy(res, 0, out, 0, size) + end + return res, consumed +end + +return Brotli +end +__FILES["codecs/compress/Brotli/Decode"] = @native function() + + + +-- 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 +-- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and +-- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. +-- +-- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next +-- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. +-- +-- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each +-- meta-block before it is decoded); bad data returns nil, message. +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill + +local Decode = {} + +type Static = { + dictionary: buffer, -- 122784 bytes + context: buffer, -- 2048 bytes: 4 modes x (256 for p1, 256 for p2) + prefixSuffix: buffer, -- length-prefixed strings + prefixSuffixMap: { number }, + transforms: { number }, -- 121 x (prefix id, type, suffix id) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } +local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } +local BL_OFF = { + 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625, +} +local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 } +local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 } +local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 } +local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 } +local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 } +local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 } +local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 } +-- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets +local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 } +local DOFF = table.create(25, 0) +do + local o = 0 + for l = 4, 24 do + DOFF[l + 1] = o + o += l * 2 ^ NDBITS[l + 1] + end +end +local NTRANSFORMS = 121 +local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC + +-- 8-bit reversal +local REV8 = bcreate(256) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + writeu8(REV8, i, r) +end +@native local function reverse(code: number, len: number): number + -- len <= 15 + local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) + return rshift(r, 16 - len) +end + +-- ------------------------------------------------------------------------------------------------ prefix tables +local count = table.create(16, 0) +local nextc = table.create(16, 0) +local subBits = table.create(256, 0) +local subOff = table.create(256, 0) + +-- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. +-- Also leaves count / nextc / subBits ready for build(). +@native local function prepare(lens: buffer, n: number): number + for l = 1, 16 do + count[l] = 0 + end + local used = 0 + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + count[l] += 1 + used += 1 + end + end + if used <= 1 then + return 256 + end + local left = 1 + for l = 1, 15 do + left = left * 2 - count[l] + if left < 0 then + return -1 + end + end + -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2 + local code = 0 + for l = 1, 15 do + nextc[l] = code + code = (code + count[l]) * 2 + end + for i = 1, 256 do + subBits[i] = 0 + end + local nc = table.clone(nextc) + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 8 then + local c = nc[l] + nc[l] = c + 1 + local pre = band(reverse(c, l), 255) + local k = l - 8 + if k > subBits[pre + 1] then + subBits[pre + 1] = k + end + elseif l > 0 then + nc[l] += 1 + end + end + local size = 256 + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + subOff[i] = size + size += lshift(1, k) + end + end + return size +end + +-- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) +@native local function build(lens: buffer, n: number, T: buffer, at: number) + local single = -1 + local used = 0 + for s = 0, n - 1 do + if readu8(lens, s) > 0 then + used += 1 + single = s + end + end + if used <= 1 then + local e = (if single < 0 then 0 else single) * 32 + for i = 0, 255 do + writeu32(T, (at + i) * 4, e) + end + return + end + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k) + end + end + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local rev = reverse(c, l) + local e = s * 32 + l + if l <= 8 then + local step = lshift(1, l) + local i = rev + while i < 256 do + writeu32(T, (at + i) * 4, e) + i += step + end + else + local pre = band(rev, 255) + local sb = subBits[pre + 1] + local base = at + subOff[pre + 1] + local step = lshift(1, l - 8) + local i = rshift(rev, 8) + local lim = lshift(1, sb) + while i < lim do + writeu32(T, (base + i) * 4, e) + i += step + end + end + end + end +end + +-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference +-- decoder's BrotliCalculateDistanceCodeLimit +@native local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number + if maxDistance <= ndirect then + return maxDistance + 16 + end + local offset = maxDistance + 1 - ndirect - 1 + offset = rshift(offset, npostfix) + 4 + local ndistbits = 0 + local tmp = offset // 2 + while tmp ~= 0 do + ndistbits += 1 + tmp = rshift(tmp, 1) + end + ndistbits -= 1 + local half = band(rshift(offset, ndistbits), 1) + local group = bor(lshift(ndistbits - 1, 1), half) + if group == 0 then + return ndirect + 16 + end + group -= 1 + local postfix = lshift(1, npostfix) - 1 + return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 +end + +-- ------------------------------------------------------------------------------------------------ decoder +-- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message +@native function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?) + local lim = off + len + local ip = off + local bb, bc = 0, 0 + + @native local function fill() + while bc <= 24 do + local byte = 0 + if ip < lim then + byte = readu8(src, ip) + end + ip += 1 + bb = bor(bb, lshift(byte, bc)) + bc += 8 + end + end + @native local function bits(n: number): number + if bc < n then + fill() + end + local v = band(bb, lshift(1, n) - 1) + bb = rshift(bb, n) + bc -= n + return v + end + @native local function bitsLong(n: number): number + if n <= 24 then + return bits(n) + end + local lo = bits(16) + return lo + bits(n - 16) * 65536 + end + @native local function overrun(): boolean + return (ip - lim) * 8 > bc + end + + -- prefix tables of the current meta-block: T (u32 entries), tpos entries used + local T = bcreate(4096 * 4) + local tpos = 0 + local LENS = bcreate(1128) + local CLL = bcreate(18) + local CLT = bcreate(256 * 4) + + @native local function decodeSym(base: number): number + if bc < 15 then + fill() + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + return rshift(e, 5) + end + + -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 + @native local function install(n: number): number + local size = prepare(LENS, n) + if size < 0 then + return -1 + end + local need = (tpos + size) * 4 + if need > blen(T) then + local nt = bcreate(math.max(blen(T) * 2, need)) + bcopy(nt, 0, T, 0, tpos * 4) + T = nt + end + build(LENS, n, T, tpos) + local base = tpos + tpos += size + return base + end + + -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) + @native local function readCode(alphabetMax: number, limit: number): number + bfill(LENS, 0, 0, limit) + local hskip = bits(2) + if hskip == 1 then + local nsym = bits(2) + 1 + local maxBits = 0 + local x = alphabetMax - 1 + while x > 0 do + maxBits += 1 + x = rshift(x, 1) + end + local s1, s2, s3, s4 = -1, -1, -1, -1 + for i = 1, nsym do + local v = bits(maxBits) + if v >= limit then + return -1 + end + if i == 1 then + s1 = v + elseif i == 2 then + s2 = v + elseif i == 3 then + s3 = v + else + s4 = v + end + end + if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then + return -1 + end + if nsym == 1 then + writeu8(LENS, s1, 1) + elseif nsym == 2 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 1) + elseif nsym == 3 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + else + if bits(1) == 0 then + writeu8(LENS, s1, 2) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + writeu8(LENS, s4, 2) + else + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 3) + writeu8(LENS, s4, 3) + end + end + return install(limit) + end + -- complex: the code length code + bfill(CLL, 0, 0, 18) + local space, num = 32, 0 + for i = hskip + 1, 18 do + if bc < 4 then + fill() + end + local ix = band(bb, 15) + local v = CLP_VAL[ix + 1] + local dl = CLP_LEN[ix + 1] + bb = rshift(bb, dl) + bc -= dl + writeu8(CLL, CL_ORDER[i], v) + if v ~= 0 then + space -= rshift(32, v) + num += 1 + if space <= 0 then + break + end + end + end + if not (num == 1 or space == 0) then + return -1 + end + -- its table (lengths <= 5) + do + local size = prepare(CLL, 18) + if size ~= 256 then + return -1 + end + build(CLL, 18, CLT, 0) + end + -- the symbol code lengths + local sym, prev, rep, repLen = 0, 8, 0, 0 + space = 32768 + while sym < limit and space > 0 do + if bc < 15 then + fill() + end + local e = readu32(CLT, band(bb, 255) * 4) + local l = band(e, 31) + bb = rshift(bb, l) + bc -= l + local cl = rshift(e, 5) + if cl < 16 then + rep = 0 + writeu8(LENS, sym, cl) + if cl ~= 0 then + prev = cl + space -= rshift(32768, cl) + end + sym += 1 + else + local extra = if cl == 16 then 2 else 3 + local d = bits(extra) + local newLen = if cl == 16 then prev else 0 + if repLen ~= newLen then + rep = 0 + repLen = newLen + end + local old = rep + if rep > 0 then + rep = (rep - 2) * lshift(1, extra) + end + rep += d + 3 + local delta = rep - old + if sym + delta > limit then + return -1 + end + if repLen ~= 0 then + bfill(LENS, sym, repLen, delta) + space -= delta * rshift(32768, repLen) + end + sym += delta + end + if overrun() then + return -1 + end + end + if space ~= 0 then + return -1 + end + return install(limit) + end + + @native local function varLen8(): number + if bits(1) == 0 then + return 0 + end + local n = bits(3) + if n == 0 then + return 1 + end + return bits(n) + lshift(1, n) + end + + @native local function blockLen(base: number): number + local code = decodeSym(base) + return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) + end + + -- readContextMap(size) -> ntrees, map buffer | -1 + @native local function readContextMap(size: number): (number, buffer) + local ntrees = varLen8() + 1 + local map = bcreate(size) + if ntrees < 2 then + return ntrees, map + end + local rleMax = 0 + if bits(1) == 1 then + rleMax = bits(4) + 1 + end + local base = readCode(ntrees + rleMax, ntrees + rleMax) + if base < 0 then + return -1, map + end + local i = 0 + while i < size do + local code = decodeSym(base) + if code == 0 then + i += 1 + elseif code > rleMax then + writeu8(map, i, code - rleMax) + i += 1 + else + local reps = lshift(1, code) + bits(code) + if i + reps > size then + return -1, map + end + i += reps -- zeros (map is zero-filled) + end + if overrun() then + return -1, map + end + end + if bits(1) == 1 then -- inverse move-to-front + local mtf = table.create(256, 0) + for k = 1, 256 do + mtf[k] = k - 1 + end + for k = 0, size - 1 do + local idx = readu8(map, k) + local v = mtf[idx + 1] + writeu8(map, k, v) + if idx > 0 then + table.move(mtf, 1, idx, 2) + mtf[1] = v + end + end + end + return ntrees, map + end + + -- ------------------------------------------------------------------ stream header + fill() + local wbits + local large = false + if bits(1) == 0 then + wbits = 16 + else + local n = bits(3) + if n ~= 0 then + wbits = 17 + n + else + local m = bits(3) + if m == 1 then + if not largeWindow then + return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)" + end + if bits(1) == 1 then + return nil, "bad window bits" + end + large = true + wbits = bits(6) + if wbits < 10 or wbits > 30 then + return nil, "bad large window bits" + end + elseif m ~= 0 then + wbits = 8 + m + else + wbits = 17 + end + end + end + local maxBackward = 2 ^ wbits - 16 + + local dict = S.dictionary + local LUT = S.context + local PS = S.prefixSuffix + local PSMAP = S.prefixSuffixMap + local TRANS = S.transforms + local WORD = bcreate(64) + + local out = bcreate(math.max(256, math.min(len * 4, maxBytes))) + local op = 0 + -- distance ring buffer: last, second, third, fourth + local d0, d1, d2, d3 = 4, 11, 15, 16 + + while true do + -- ---------------------------------------------------------------- meta-block header + if overrun() then + return nil, "truncated stream" + end + local isLast = bits(1) == 1 + if isLast and bits(1) == 1 then + break -- ISLASTEMPTY + end + local mn = bits(2) + local mlen = 0 + if mn == 3 then + -- metadata + if bits(1) ~= 0 then + return nil, "reserved bit set" + end + local nbytes = bits(2) + for i = 0, nbytes - 1 do + local b = bits(8) + if i + 1 == nbytes and nbytes > 1 and b == 0 then + return nil, "exuberant metadata length byte" + end + mlen += b * 2 ^ (8 * i) + end + if nbytes > 0 then + mlen += 1 + end + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated metadata" + end + ip += mlen + if isLast then + break + end + continue + end + local nib = mn + 4 + for i = 0, nib - 1 do + local v = bits(4) + if i + 1 == nib and nib > 4 and v == 0 then + return nil, "exuberant nibble" + end + mlen += v * 2 ^ (4 * i) + end + mlen += 1 + local uncompressed = false + if not isLast then + uncompressed = bits(1) == 1 + end + if op + mlen > maxBytes then + return nil, "limit: output over " .. maxBytes .. " bytes" + end + if op + mlen + 8 > blen(out) then + local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8)) + bcopy(nb, 0, out, 0, op) + out = nb + end + if uncompressed then + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip -= rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, ip, mlen) + ip += mlen + op += mlen + if isLast then + break + end + continue + end + + -- ---------------------------------------------------------------- compressed meta-block + tpos = 0 + -- block types / counts: 1 = literals, 2 = commands, 3 = distances + local nbtL, nbtI, nbtD = 1, 1, 1 + local btTreeL, btTreeI, btTreeD = 0, 0, 0 + local blTreeL, blTreeI, blTreeD = 0, 0, 0 + local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824 + for c = 1, 3 do + local nbt = varLen8() + 1 + local btt, blt, cnt = 0, 0, 1073741824 + if nbt >= 2 then + btt = readCode(nbt + 2, nbt + 2) + if btt < 0 then + return nil, "bad block type code" + end + blt = readCode(26, 26) + if blt < 0 then + return nil, "bad block count code" + end + cnt = blockLen(blt) + end + if c == 1 then + nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt + elseif c == 2 then + nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt + else + nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt + end + end + if overrun() then + return nil, "truncated meta-block header" + end + local npostfix = bits(2) + local ndirect = lshift(bits(4), npostfix) + local postMask = lshift(1, npostfix) - 1 + local modes = table.create(nbtL, 0) + for i = 1, nbtL do + modes[i] = bits(2) + end + local ntreesL, cmapL = readContextMap(64 * nbtL) + if ntreesL < 0 then + return nil, "bad literal context map" + end + local ntreesD, cmapD = readContextMap(4 * nbtD) + if ntreesD < 0 then + return nil, "bad distance context map" + end + -- the tree groups + local litBase = table.create(ntreesL, 0) + for i = 1, ntreesL do + local b = readCode(256, 256) + if b < 0 then + return nil, "bad literal code" + end + litBase[i] = b + end + local cmdBase = table.create(nbtI, 0) + for i = 1, nbtI do + local b = readCode(704, 704) + if b < 0 then + return nil, "bad insert-and-copy code" + end + cmdBase[i] = b + end + local distMax = 16 + ndirect + lshift(if large then 62 else 24, npostfix + 1) + local distLimit = if large then distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) else distMax + local distBase = table.create(ntreesD, 0) + for i = 1, ntreesD do + local b = readCode(distMax, distLimit) + if b < 0 then + return nil, "bad distance code" + end + distBase[i] = b + end + if overrun() then + return nil, "truncated meta-block header" + end + -- context map slices resolved to table bases + local litMap = table.create(64 * nbtL, 0) + for i = 0, 64 * nbtL - 1 do + litMap[i + 1] = litBase[readu8(cmapL, i) + 1] + end + local distMap = table.create(4 * nbtD, 0) + for i = 0, 4 * nbtD - 1 do + distMap[i + 1] = distBase[readu8(cmapD, i) + 1] + end + + -- block state: current type, previous type + local typeL, prevL = 0, 1 + local typeI, prevI = 0, 1 + local typeD, prevD = 0, 1 + local lutBase = modes[1] * 512 + local litSlice = 0 + local cmdTree = cmdBase[1] + local distSlice = 0 + + local remaining = mlen + while remaining > 0 do + if ip > lim + 4 then + return nil, "truncated stream" + end + -- command block switch + if cntI == 0 then + local t = decodeSym(btTreeI) + if t == 1 then + t = typeI + 1 + elseif t == 0 then + t = prevI + else + t -= 2 + end + if t >= nbtI then + t -= nbtI + end + prevI, typeI = typeI, t + cntI = blockLen(blTreeI) + cmdTree = cmdBase[t + 1] + end + cntI -= 1 + local cmd = decodeSym(cmdTree) + local cell = rshift(cmd, 6) + local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7) + local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7) + local insLen = INS_BASE[insCode + 1] + local ie = INS_EXTRA[insCode + 1] + if ie > 0 then + insLen += bits(ie) + end + local cpyLen = CPY_BASE[cpyCode + 1] + local ce = CPY_EXTRA[cpyCode + 1] + if ce > 0 then + cpyLen += bits(ce) + end + -- literals + if insLen > remaining then + return nil, "insert past the meta-block end" + end + if insLen > 0 then + local p1 = if op > 0 then readu8(out, op - 1) else 0 + local p2 = if op > 1 then readu8(out, op - 2) else 0 + for _ = 1, insLen do + if cntL == 0 then + local t = decodeSym(btTreeL) + if t == 1 then + t = typeL + 1 + elseif t == 0 then + t = prevL + else + t -= 2 + end + if t >= nbtL then + t -= nbtL + end + prevL, typeL = typeL, t + cntL = blockLen(blTreeL) + lutBase = modes[t + 1] * 512 + litSlice = t * 64 + end + cntL -= 1 + local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2)) + local base = litMap[litSlice + ctx + 1] + if bc < 16 then + if ip + 2 <= lim then + bb = bor(bb, lshift(readu16(src, ip), bc)) + ip += 2 + bc += 16 + else + fill() + end + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc -= l + local lit = rshift(e, 5) + writeu8(out, op, lit) + op += 1 + p2 = p1 + p1 = lit + end + remaining -= insLen + if remaining == 0 then + break + end + end + -- distance + local dist + local push = true + if cell < 2 then + dist = d0 + push = false + else + if cntD == 0 then + local t = decodeSym(btTreeD) + if t == 1 then + t = typeD + 1 + elseif t == 0 then + t = prevD + else + t -= 2 + end + if t >= nbtD then + t -= nbtD + end + prevD, typeD = typeD, t + cntD = blockLen(blTreeD) + distSlice = t * 4 + end + cntD -= 1 + local dctx = if cpyLen > 4 then 3 else cpyLen - 2 + local dcode = decodeSym(distMap[distSlice + dctx + 1]) + if dcode < 16 then + if dcode == 0 then + dist = d0 + push = false + elseif dcode == 1 then + dist = d1 + elseif dcode == 2 then + dist = d2 + elseif dcode == 3 then + dist = d3 + elseif dcode < 10 then + local k = (dcode - 2) // 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 + dist = if dcode % 2 == 0 then d0 - k else d0 + k + else + local k = (dcode - 8) // 2 -- 10,11 -> 1; ... + dist = if dcode % 2 == 0 then d1 - k else d1 + k + end + if dist <= 0 then + return nil, "bad distance" + end + elseif dcode < 16 + ndirect then + dist = dcode - 15 + else + local x = dcode - ndirect - 16 + local ndistbits = 1 + rshift(x, npostfix + 1) + local hcode = rshift(x, npostfix) + local lcode = band(x, postMask) + local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4 + dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1 + end + end + local maxDist = if op < maxBackward then op else maxBackward + if dist > maxDist then + -- a static dictionary word + if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then + return nil, "bad dictionary reference" + end + local nb = NDBITS[cpyLen + 1] + local addr = dist - maxDist - 1 + local widx = band(addr, lshift(1, nb) - 1) + local tidx = rshift(addr, nb) + if tidx >= NTRANSFORMS then + return nil, "bad dictionary transform" + end + local woff = DOFF[cpyLen + 1] + widx * cpyLen + -- transform into WORD + local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1] + local ttype = TRANS[tidx * 3 + 2] + local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1] + local w = 0 + local pl = readu8(PS, pfx) + for k = 1, pl do + writeu8(WORD, w, readu8(PS, pfx + k)) + w += 1 + end + local wl = cpyLen + local wo = woff + if ttype <= 9 then + wl -= ttype + elseif ttype >= 12 and ttype <= 20 then + local skip = ttype - 11 + wo += skip + wl -= skip + end + local ws = w + if wl > 0 then + bcopy(WORD, w, dict, wo, wl) + w += wl + end + if ttype == 10 then + -- uppercase the first character + local c = readu8(WORD, ws) + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, ws, c - 32) + end + elseif c < 0xE0 then + writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32)) + else + writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5)) + end + elseif ttype == 11 then + local p = ws + local left = wl + while left > 0 do + local c = readu8(WORD, p) + local step + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, p, c - 32) + end + step = 1 + elseif c < 0xE0 then + writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32)) + step = 2 + else + writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5)) + step = 3 + end + p += step + left -= step + end + end + local sl = readu8(PS, sfx) + for k = 1, sl do + writeu8(WORD, w, readu8(PS, sfx + k)) + w += 1 + end + if w == 0 and dist <= 120 then + return nil, "empty dictionary word" + end + if w > remaining then + return nil, "dictionary word past the meta-block end" + end + bcopy(out, op, WORD, 0, w) + op += w + remaining -= w + else + if cpyLen > remaining then + return nil, "copy past the meta-block end" + end + if push then + d3, d2, d1, d0 = d2, d1, d0, dist + end + local from = op - dist + if dist >= cpyLen then + bcopy(out, op, out, from, cpyLen) + else + for k = 0, cpyLen - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += cpyLen + remaining -= cpyLen + end + end + if isLast then + break + end + end + -- the final byte's padding bits must be zero + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding at the end" + end + ip -= rshift(bc, 3) + if ip > lim then + return nil, "truncated stream" + end + return out, op, ip +end + +return Decode +end +__FILES["codecs/compress/Brotli/Static"] = function() + +-- 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 { + dictionarySize = 122784, + dictionaryCrc = 1362545412, + dictionary = { + "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", + "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", + "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", + "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", + "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", + "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", + "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", + "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", + "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", + "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ixouj6t9A", + "025UrW3Kd+S62lWPSbAQAXbDx8uwPlXwWb7kF7EGiWvMX0qxquEN4bulpDPGfmCMSYB5GuWjO+XhHQ72L+iLyiFopL8axZib", + "SdZ/va3NA112tRd6qlEUFzhvrOHX+d78IOimAn7dXN3X+Sn2MlZh/yD6HlQhaCggMXn/7PhXZ1WlwSDW26Sx/l8b1v9xUPlJ", + "BXsD2jOlSJsSeAJbU6piLO+0tTkB6CcN/QT7xn76QYeVQciPfZUgZ8jTmOLmjuo+LB3GPoj5RkExCtGnHxhVxLfoWVWNCzkQ", + "o+9iEA0WVKFmqio04Iv3MN4P8APWMaD9BHwXDPr9PmRCYhIQTuxj+qX2ADw4qFV/gr3YDZkDvseahAZ72I/trsVpaPrSoAZJ", + "1r8J/ZUiFZQgAgzep72S9r3unNGJeR/f5fvMX97DmP2is8FEEfYRcgJ0mKQFvV+TGkKMQ3ug6QTcHGHrQF5xZdNH1X0uZEAZ", + "617AOPaDlgciLLIytRg8C5oMqhijj/VyQf9b8K4+7H2iSqbgJwa0FYD5kn4IsBC024UFLmHR/tr75RdemtS+oHxRga5FKdY9", + "wRL5YZ/av9+lbKppU/RNeXBwMB/7Bn0WTDXWA5swD/ytN2Ni28GPHsaxpaNjYwF7DirA2OIQssQrRPvyReXHAcaD9WLfcV+K", + "OWu37Bc3vFMFnekBP/hfG3KgibgS4FkP9FCFfN7Y0dHBWXqxGiynYIpqlBTT0CuAj8qxLkKyBP26ZhL0UQa9g/ch13WwCcRo", + "Uj/Bo8FXvb05inzsSe3jXXtzWDOtfNAch+R7BkvbGaqBWgkMkfhV88c///nPGAdko1cDv5vWTueHarn6F8juAHwdDELB7C9v", + "zf6zfV2LA+EEeRXkW1q2fYh+qqkpQ5MkWJpOFzTwn+1d7WVouA+xRpAxSQwZ5rz7rgNtEmA/oV1AVRhExYeM6verCfYfOgr6", + "IdAl0EwVm/Ee1nRdy7oWl/QNmZDHYLoKcY8Gg1aw16XUh5wOsFEGrwaTKEqkqNLuV0rv/vGjzUEKXYt+sZSdIKpaCfRWTiqU", + "EoEXp6XdX+3aFUI+hVjDv4BYA1Ih1n6AOgC8hfVzQP9xrINaATrIgFa8tF+HyihXVfUgaKOUBsW9m7dsLYPWQPdJCTIFwh+6", + "L40hr2qbMP/161s7WztzPRUDoeWDf/zYM5AvBQ3OgRzfu+mjrdh6QwbA/IMPsIhF0MP/HbpoClHNQIbk0UVuz5e9ewsYTz/2", + "rrXzhx+gvGpYN2/D1//V+m2qPOxNvQ0Ktw3/g9Cv4pl1wB3J3k1/3jrgu5B+Xs3ThaQHE4MsC0LNcUaDezd9sNWDbNMDKti7", + "6cOtAdYfdAtyVEEV/BNGAwr8YEo61M7/HTpjoiJkU0Unvshx01XeAtmYxkXggCp0SVcS90Dn+q3fv7MB/9UYV7MAeoJ8iTs6", + "WjsrftDvtLX1+HEUAud4HnhrEPtkIj+opolp7zPtwAa1vZs3b/20d/sXezd3bFWeqmCt8K7NPX0Qgus3OuuhYpO9mzdtdTAf", + "6FmIel9VIFu62qs9JkqDzz79Yhf4EXglxhq8t7WrvKnnI6wtREDXn0Gnezve21oB1tr63gf/AA1oP3TL/wPMBfLimFfWt7aC", + "rmPsSUlDp4K0QuCe0Nu65cN/fBMVv1n/r9ZO0NZGtG0kkIk14oZoMCiAF7a+/8E//qoG1Ba8r+X7H1r+Y8eW/9i65b1/9Oli", + "cdf/s+dTyNLygA91B9I2wBfoY/XblDoU/AD6ga5KsHb5AujQA72WgUUgL4CRwmTrlg/+8cnevXvaNndsKkbQ1Ohj1xc7nX0Q", + "OFvff+8f27/c+T8e+uhs+aFF7/PR/v1/QL8Z0E6y/ofWTmCRBKzeqYDmfvihq/2f/r/yn0H/9Ff+z6NBvCcBzSnPM5AWAdhx", + "X2fLH36AyIpC7GUeiqGj4/1WrEWtD6LegKjAsZCzURFr0eps7ugAjYOHsRiAf8Cp4Im45mJfkxooSwNT+FGYhzJzoedKeC90", + "Yv59rNOecn4n5AGgnuCrEHzdD1qBplEh9OE+0IkLum/xoHPdwK+2Qvh8iOewDh07/7bTfPivnq4EfEkE7P/pT62D2DeAjKgK", + "5RFVE6j8QO/e9t8GdBK2bf5gb0B5Dlr/+qvPnEIaAJdH/Z0/rGv5ZNe2neC5VlUoQF6rcMOmP38EfFamUOhq90FbkCUpcTRw", + "gl/V37e1vNPRsbk1BND/56Z/df7zX50tn0UlB3olWdfyhz9AX5agUysFyKfW79a1dJAmsA/90db/D3INa92zzmxtb3fwIKQi", + "8W1pQ+t3LWjqQG+ux/SqXqqg/1SS/+uej1uxsd+mUYL/toDHISF/WAdSeA8/7+PnA/x8iJ+P8PPnzR3yzyb8bMbPFvyg3Wa0", + "24x2m9FuM9ptRrstaLcF7bag3Ra024J2W9BuC9ptYX/4bBO+24Q2m9C2A8904NkOfNeBNh1o24Fn0AEWAz9oh3+B0PDzEX4+", + "xM8H+HkfP+/hZwt+NuNnE37Q7iO0+wjtPkK7j9DuI7T7CO0+QruP0O4jtPsI7T5Euw/R7kO0+xDtPkS7D9HuQ7T7EO0+RLsP", + "0e4DtPsA7T5Auw/Q7gO0+wDtPkC7D9DuA7T7AO3eR7v30e59tHsf7d5Hu/fR7n20ex/t3ke79zHjDs76vU1b/gy1hMnjf8Cs", + "UeXVdVgTiSboqgLHJJEXlYHLXQgs9Wo2KvgQ0K+mlDKvpgZ8D3rDEHFFkEsRLRL8rlzsref3RbDdIuDUELqYFgWkKTg2KEXf", + "pq/uE9WG6BM6AlAAnAMdVFB9fB/JOVKlVFVTQMwwAksCe0OGBalPVQcjpxbBnlAQjnHVx/sLeGfABkHk+RH4Iua4/NfPXz98", + "/RI/S69f/Dr0+uGvQ78e+vWgfPb09TI+XcJfc2j1Er8/kb+WXj/Dd0v4ZO7X4deX0fYp/pn99Sh6OPr6x1+P/noA3z7C74/w", + "38vs4/Xs66v49yJ6wlOvr72+hc+fvr6EtgfR7op8+gL9P3x9Hj9n8HP510P4fBbve/r6At7/9PX865f47AX+uYHnDr1+9vbA", + "2/E3N9+OvB1+cxc/828PvT2Mv8fezL6ZwTd38f2Rt6Nvx94efjuMn0P4hL+Pvrn35jF+P/zmNp4dlT7G3x7EM6P47Bf0dI+/", + "Sdtx/H4YbfnfQ2+eSK/DaD/8duTNz/hsHG1G3kzJE8P45gne/gTY3STYeB0FsKYTmOWwg7E7QHW0+gk5CsSHMb811P607AF/", + "QEOwLXy36MNyJqiMqzRzoaKB8mBtAZHBTIdIiD3gP6MBatMqPQaG7gIDcqQRB3N/EL/QZIutAAYwpOUOO7sKiQ7sg/fqOIZh", + "HEL3qkKUJvQLAFgmAa3BQMz+BDYJpBmMUKDDuCTuBSO2OamHsNmFWeqmxoXRE9PoCwo0YwjRYIMIlSl6JWC3K9o7Fby75lOz", + "0ltgAL9D2qHsHq8H2oCeARwCPoCSfxeAsRPzgIkdxa6uUkHTkIZGK/mhKuIJ6FI/AZZMNb0Z+AK4BqpT70siQFciZPSMT/Fs", + "mADEG1NI/SAR0xdKQAN9pV4NzOjRvA49Q1MT/8XSlWEK0+ViwJpQa1DHaAzoQ1eARz9FiFUb0EC5plz098G8xoDCCOgvpucF", + "2BQ4CzpSBTEM7JgWrfk2hX7GklR1Oa2oEFqargtf/AvQztD2XgEc6cK0cSlasOLA6OUAdlEoxs8gRI2mQ8fQm2I8dg0REesC", + "pg9rPk3KMJPwLF5nsNhJeZDuGU7aA+m5xGIJlzOtJLAnKFTihM6U2g5Ihn5acDF9S9hQWKqBqmkij7jGd9RSMdO5TC4WNsHm", + "xQ5ALemqmlZpHhtVrQa1T7m/BeCqUlqFcKSfhNSEXrCmhua4wQbFEFDYWgrCfrpaaKYRcAMamBSPVZU8i+5JWyG9LiGJhr4j", + "7e0lsXLg5mNyAERbCHxAb06EhS0q0C/9SjWVggi5WwbTDzR9Fe2coEdvlvEAd2uwygIaSyrpS2G+JmX6KGBXmpCDLtBN4Eb0", + "J9AZxwlqekSMW3P5b4BjOlgMJWv/ILcZeE6HVV+7hPV+UMRENc1Kch70vF+ByapIHT6MQMIeNAcp02WnST1gv9QtF7jOcVQD", + "KjL9GpsHFIP5kSzAYA5XAmA9KcuOEl3VomIRJOFGVc3FhIkFFgd64E5brxzEQkx/CPRHnMREUwq2OKYahdhQETIwMQh3eyky", + "PiPVgVartch1YWrqYrIVuN2UQcUJ1wAmJRmHfjeTxoA7Rb6SBIyN5lqlSdSJ3Ul0nvZXhUwCY08F/0PKMXgZpgp0iyUexKd4", + "L83eEFLQp3PCLX/F/uiKhISM3TLBj6anz9DNaLwoLcCSqoVuAm6iFR4NYi91sUY2gPUCs5h2KShhABsK3qW30uwgX/ZSchF4", + "1/rE0wg7KgDOc3UHLfBeis0q+DOg3wUglxJBJDUMeApz6wQ19PQYuuSMonMCm2c0kSvleCiDxgZUsYT4M6GL1dDHxm9rZDDY", + "5Nh8Q18vBXdM7g5LMKC39HDLSgTd7ZUU8peb7O0hc6Jd6CURpA9ghO9toAO0QI8IPX7spQgjzSd5B4F4fGvFNf8ajCa0ddrb", + "YYIpjwZaqVZNdlHK01rt3EVipS8459K6g3QME3HlwrzI9ZCJgfjVAJ0YsIT9/dqUADwSDPe9njiiYxjf1tjBRtEdhDSeG1N3", + "+CUY0YOQ0J4CAWNBjO6hR0aH33zd++4ft/y5k1h33zckaigCDC3sA+X3qX15RavBgGXKdL059B0TvEOehtCmoRrI9dAJEIrX", + "i95EkAVWA/I+inupe4gysYMQCvQTmz5VFfEQwOz2QXPglFhR5WAem3sUbDhgLzAjuChWubb29r/TBWrohzJ0HJs9ZGLMMilT", + "54V0TvzFYAAJmJckCPBFCZfQ/VrEzmiossFcD9YfjB2nlLFQ9H+jPt9NyZAPdcItaYH5XHO+a6FHkh5zQ7cWSQWr7YEGvuVi", + "J7H4DAtRTMc/ZAeGC2FLv0hCqtR+vJkmlfiz6dMzO8jY4G5IOEp0nhMYOpToCMVa0+ddIbtQq1Ge+kbc215K0az3KVOMwe10", + "j2z8/nsxVKo5jBWbR7dELqJ7oasQt/cUMa/Y0Cfn6WpSduwJANjUpZTnaYM4LzshY0oh3VRmkKPiaDshXLpzdF9DZWFGn2Pm", + "Tj6f72oHdA1LBU6ahyAOPYedPFYAecdxDdICxK6L1BUl/Q3PQfIV0gZgiMK32K4qT1DkoKCrPYl76P4xHLyjQCEUQDR1A4iw", + "feASOg3KPKUxVLgufc2OgRA3gGqhuIaNswGUSie69w0xBF2fRrA7SahfTmKEGcnnHp0AnYNUJ5ib0RtaO3POdsIjPJru66M7", + "vgqZGNDJ09Pa6Rc3tFHIegrAEfDK6N2EVpg9z132abOXqhJKgpPRlZ6CinM9eRO73QklAwRYd84lOiyD1mqb3xPRl6RVH3RZ", + "Iw6rgukxCZCG+KoNZUceAl3z+EAH9A+adteYdp5AdPKIAgIlLRYLPjqlZ9/Q/dfRD05TsGPXtdCrD0yjU93tfPdD50fiBeSR", + "yne0fxUPm1zO1wdZlXm85cTkZ4JUQ89yrqbKUdRKZ/k2IlCeVhkw4qYe2EBpiQ5msdK7abOYH1qxgnR0dlYpVehSNDxfMB37", + "Pujo4KlBTvy4BaqORGHBKj5EGdFbAAbraqdzGTOCcGrj5pGk8phHyx8qZBIH9v6fd2/77672OCrpuEi3/g7yzGY6THnIY+hJ", + "6gJjJgl98WYzxwIIFva3Ot9/7wT0DPI0J/hjB0SaA3JyeG7nDXLFKeA6+9TW//eg8UHVXfTcx4AONR57wH4j/MWCVRPqme2U", + "na3OO92OR8xKrwddLRWoo35dq8C8DHiilqcb26kSO4Onwxo9iYYIJ7eJyzFIQE4PVqV377av9pK2HB84NtzowJanO6GFADc/", + "4AMMiCsV8iUEX0LL8ACM0DoKq+Rf8kxL1AbcwlMJOWox1JQOnW8hvS7fKS8q6PXcTN/r3tRBhdDJ4zonvzlf8XmIlqPbG1AD", + "27ODmKsAcag3c6TY5NY/8Zfv6cQG/0ETl8nimzZ35ByqWIi+nnUtVBDdng8QQI7HF1hwys6WPxaLRTARIAsRXo7wAcoaj7XS", + "+7xJeAE4qxpahzPsIW7FIR5VuFzEHCctp0OmDbzW5tHQank3SDrpeTVb3/voH108u22LUzAaT54cKkig9X4xFaqm28nlOqEM", + "oI+4apt4IgHxr0K60SNKw+6o+z8273YojWCaF3SXXyk5+Mn1bHSKfYa/OTmu3+d7o+p2ntjlQj0Y1HZiT/rd/Vqwsh8QK5NJ", + "3u8pqm9zPfvLbW64qQO72bYp19pJFN7N00LotzSoUZYYOpM6sXpd79BjETg89ICyWye77/TRliDHO9ytPDh3XcsgcQnPPkxK", + "cePxqKMApulPyFvgo5zDM1rgZwyNThDw97eg0TSq+CaCLQIZ6mk526FnxFRTGqCvZiM6TV5dT3xIXKCARNEnIjCep5OgzBRy", + "hn6UmENT6KwCkQq4WoHKitS36aspelWMefU4iFQt9VRR8/iB3hAAo4R2ZoRRJZGhh8UIBfOMNlL0dgRpiUdktYhHk9YBghUh", + "AgBdGPpUOT6FAb2aMhyLAkBLPXHa0HqPgHx1SLwIu8kjwxLs6fjVdcAiztj1477IiNtGxURWgBZpNSrTjSpkgLdBZwCaR1Dv", + "yoQ8xic005yqAgdqHq354geCKHF9VQS05PGRD7iHha1CUkSFFNMkuo4VSCzgn4ooEign3o9+CzTiMASQAV706nEl4iSjPv4J", + "XPNqocwmXIMa4L+rKmkfMDLQUFxMqUjwoqgE+0D5JeDiAa4LHVgAfFh87iWWt4L3gLagr7F3dFmFYQQBBgDlYszgHrpgDRbH", + "p1OqDE0WmwigFyuFVQUzvnocQnLtj+hYEN+UGeCYVTWqYaQhQRYYjp9FLtg5luMj2EgYC4WIy8fo1jL0koQkmvDVddp8vthA", + "sJ1ARq4MV9GWDEgbmDvsAAwDqwF0rQmTdRWaGGqR3eBpxkLQLQZ0Sy8aaKgU0PPGV2MhKgoimdaxXcDQB1V/a99hFI0gNyrT", + "qTfgqz4IXyDoV/epc0jyMWxi0E2fAnmDnmF+qYAaWQeaZjDQnJI9BFiNTJDyuB6bjK4CrhueoIUd008ohMQwBpcHnQN4OUYF", + "IvGiAWAmQ7efUZVCxENbj+18RWwrvKBMCqsdALkPqwvZTyMO0/NdhcV4NdUX8VXYMqWFpygKwAZ+bFIdcASRKYrHhh5GbrdM", + "kOsIy53+KO6qgkUWEZYp0m5C3RBon+EXhSigCxOrBiIE+OKAXh2QfXMZB4MnYGuAGNgjB3SdO40OeC5F1yclyH1SJ5mdfIKZ", + "UCkpAmb85oq9lYDh0RUlC2ithnXDJgUVoMuIAFKcqTQrgFB8TIvTh+wCZWMSEPiUJcDzVXHGisGmRKgZn8e43DLaGwDmEDz4", + "WNN900fkqBVdsuZd2qqdXkQtjY6h8Al6UutUAw0ZOudqhsMXdVHgoUwca4HhLk+v0yoNX5AeDFvKnrQCtYWnQpi6lDyENaBA", + "WAbVtAB9iacYLwM8ZUjnFbBgrBgkROeYAZ/GLiYUyyFrLB4nWBVaoIRmKI5bFvcE9odOx1iXMCo/YZwL2BaWEscJ3o2CtBLS", + "0oohFmlxi8OwR/v0XABIl5JyEfINZmdMFzgWDrgOVAxZSy7GBLR4x9JKBStAyzzm6mqvap1N+2CeeVXIOrcmKiChlU8WBYS3", + "0gR6F5IE1hywRMkT41IcXUachEBSPnZ6UMz1qgYxajJeqQYJmRLr0pFQBHPHjDNCD65QUlQsAgaDDTFAOhChYtNChW4I+gLF", + "yWrSKqN/gNECmEt0E3ni4AU8K/OkOpX+y6DUQRANZio+W/NloU+7ibgFjfX2gqwhW9xyLHFbFYwQBE+fXVloLKSyxTgxR4h7", + "kBrnCn77NlV05CWUOXSwGToguYOchcS08KAK44dZSSsbaxXxcBkWFPrB0n9GmYPpJHRKYW0ptitE8BqyWTNqSHtJVCoFWtzQ", + "oGueHpNufdeFIgUVEVdVatRkgypJYI3I4XVSFCd3WbAlo5tyPYxp0x7ovZgGwsk1sVXFY8J9By2AtlwMh9KpZP2QRu9zGYZC", + "D0CJ+4rxlGUxilDzibjErYfbYL8wNigH6CfGeUTxAClTfyUrRjYHgZEpCS6oh13MxDB6AIBbNiPnEPzRKaOTknh4yFMkINAk", + "0FmRIKEGERpURNDQW+zCTCa3+qHE2ylSyw5x3kWyy+LPhVTxvEDv4gkkxeEgHZgl5dYqwuPY7LRUZmyXFrCt6YMv+SHHraCZ", + "fL4LCsElFocAkbMCT/xkhPaMfVEcfyTnqUI/NTERGQ4BNefS3oQcAL+XPU1JHQstgWOJAVKIi6TCWMGaL55J4TUtrnvzhcgW", + "L6V8sN5EOTswjPrSHiGFdSzBFPIDcC5Wr0RvO893C8I7dOUxGgusYz4W2UWfLC0jelZdWauCeFmBYmNVBR1g96wvDMKDdA5I", + "l9QwC9JeFZZj0mYHUaW8rTDkp0SPIxR8CnEMWc/4FoAf9N3rxn41wRjonCeR0qqByPN8ciodYSR7zrFNvAhYR6wDqBACQQkN", + "8CRFe3SuaG+HrCEWmA60Mp0VKmB8IeMJcw7sG8gNrgls9+/otcEAi/6+SI4LPhE6zzM8ZoML4UEKIL4AXMPkAwXUVf5KJGEi", + "M+I5Bvk8gQzyhP63C6fD+kiTmriGKd9KUdIrEkxR0gOpCUVDKnG0ViOIRZxwB2PNbz4XCS9aCLRN93yv6AIR84Yj0N67YcFU", + "O+nUN1oMcYeqOvS66LZ1eD7uy3lNdw7MCmwh0X3ASgMSPUFraKuzt6wdjx61kpxLme27Pv70C+dzsAT1Mh31rtgDZZHMSkyK", + "T+UtFDyJ2VXBZutekaXgd3CDh7/dxB4LgHfA6b3CF/mWli9DcepojyZLrmcPcLhfFWeWKUtkAnYNPXwpUiKWtRciNqH4E3tF", + "2niaThu6b4Oas0HnS/mCLjPuIiKdYCIgHJ4DaIkCxA9PncS1mxjCQpmVb+zxk7eFBv73hHSeorfVrfEECEpOYl9h0O9nlB6l", + "vdBPT0HXIP3axP9P6VRNRBt6xDOh3h1FdAgoRn+KQ6TlG4rsnHhgRQ4bk3PaYcPlxRqLJDJVKCH+ch+j0Tg+bDCkmT8gnBsW", + "Jcpqp3XH0h7NqWqV2gzMk+uRw0XDGNd+wwhgMcFcemyhbTBnjFZvg1IHSuSyEQRjP/eIhu0qxBjLIJVLLKd04pfR3vff0y3E", + "+ed6fKvFwGOqRs7P9TDWCPJEh7A/IddSyhCAuFDc/GYTPYPfi/rhGuIjOU3J0XODt5OIOjkTJbpMBZvkjIGfgMhjHpQUsRzJ", + "VnE8OHLild8mWkAOloyxx32UG94n1rlPf2D89d7dbR/l5OjR2S5aIO/8HeiGB4V+JP5i4LeQsUEx0GbS99+pRKqQPsXXAgQF", + "AZ8ABYEPYNmUuONkTXpJnO98EysstKoJenHxSnoNcz1lkRhcDB7mkb/lCMnIeWqnLIMnztcuWArC3dzDtjZGtkJC+UkNk2G0", + "CJ5XqXjDnE1ymhEVEvqnidOMElfXRufT0KWjRHs14SAHOgT6RQ6O85To2pMTodo3JNb8bkF0dFxr73PRmIHRjl/cI5gNe92v", + "a62dEksrpnVJsJkcL5udgoF/YJDud2AfNN+OPrvai0LhcrKZLwoeljMK0yWeXh7cOB1VfFZRIDoMS0zgGGYAbDfBJ56cxxlG", + "zfjh++KMolMInEU7IMwTEG1QAyoRGwCr941MSSjBCG8qOSneWBTtJuhLYtFpAWOYG4Q74l7BgaRd9uzVcj0t/0lht7fMbYbm", + "wUz7CGlqjGXvaudRb7EGHIsufNgzcU2OcLt3iBQVR5yj5ITlG4FxPIZVHuXSAHSxi7WV85aWXrEOnJ10BrsEJrGc/BvxaHvb", + "6L52GMEb1Lx/ny/nepgDwHFS4MlpuqHZnBqJR6CT8p//6pQ4hHwphfETAx8w0pUj3MrTWe19SXDh8Fgj50DKpTyRwSbDROBh", + "mJw1Y5UAU4rALtBoO6wlBoMZUlSOhHtF+7S0/B1SOVEgm1iiA7biQUZXx0QniaxertX5k5OTHe8ppOQIOcc1n4uOpsYhkqwK", + "BKRM5jFVrmdAwg7EBo7lLBMaCmCFlmBC11oi2B6bB80UqoGefoY/G8qNXI8cTZtuOR+WA2GnLL11WIZvafk0dBwJk9gDO7Xf", + "b5NFxDsgB7eLxpezQadNaGmzyBzmSOR6OsTl+qVIuTYRTxXSFQiDdMt4RqdD2NGR4Agj1kGrFuuP6NuPGRuXcxxrJEjPbcL8", + "0F+79lW3ypEqcyb8kEY7ECMDOYyca6yTo2+n5Q/kwR4Gh/0Bn3s9LfJtS0GVGTcUc5NKjLQFT5Zg0VZljiau4t8SMTO2MjdV", + "PzfamB5aeXm6MX9g9ZczK8vX6wdm8Hk2+bI+dmpl8cHK3NDK3M/Z8INsYq4xfb1xcqQ5vZBdnswmZlYWb9cvHc/Gr9fPP1s9", + "/wTNVhYWVhbuZqcPNEd/zp7Prrw4sDL3U/3q7calo9nz2ysvLzUPnGk8Xqw/ul6/dKTx8lTjl4v1I0P4vTlzGN3yvcuHOKRf", + "rjXO3KuPPV+9c271+lM+ODRcH0fLmdXz06s3LjQm57LhxytzR5svX9ZPXmo8ubHychmPNF9iVM+yS/caC8src4to2Xx6uH7u", + "YvPuyOqNU9nklezW8frje9nIMb598VL9zLPm+YlsZDibnq+fuNc8fjKbO5hdWqg/G8M6NO4vYF7ZxKls7tDK4tDK/Fh2+2U2", + "cbRx5mr9yWI2udQ4MspvZ89mdw7Wr1yqHzlax7PnHq6eX6xfGsIv9XPz2YuJ7Nj5lYUH9YmTK0uTHPbCifrkk+zWT83li1g0", + "LEhj8Wrj6u3VA6frc3P1sYlsfjk7NZ4NP1tZPIf+m9fvZdNHsuF7jQeyHS9+yk5daC5PNq8faxycz0YXG0fG6pcPNc48zaZO", + "rsyda5w91pxeak5fz4aPN5/M189ebB58lI1fy4Zvc9jj99AtdjY7O4Kdyo7/lE3faJx4iEVbmRuvP32Ouay8PJs9f9RYnGjg", + "2XtDzZk7jcWRxq2l7NhC4+Ji9vJs/dID7N3qpaHmnQMri8/r117Uz8zUjx0A2axeHF49vVQ/cRu/Z9PPssUFDKYOApg4unph", + "uDmzWH98Nls6uvLyeOPlNF5Rf3pidehI/eh9rEb92vPs5ensyPFsbKQxu1g/8SPmmE1eW5kDXd2qXziNVc1Onli9+nhlHjM9", + "3jz0cnUIyziKZqC0xt1TIBJQJj7HS7Nbo9nJMRBPdusuRoLxY+ka18407j9bmTuN9ljS1UP3Vq/PNyan8fbV0WPN5Qv1CzPZ", + "i6Hs7tH6oeFs5ClWtXn4FGiSdHX6QOPIsWxuOhu/j0+yY+dIXQsn2f/UHfx/Zf5adulhdnmo/nSieXesPn4WDUD5jXtHsVD1", + "2YP1oROgIvBLNnQxG7+KcYJK8RUGgFmjcXN6Jrt6AkQIysFCcU9fztaPTjYPXMhuPqxfOLGyuMjdOXA7W3heP/uwfny6sXSC", + "3Dr7svnyzsri0cbi8ZWXI5gFV+zpAdAqWBJcBm7lXGYu1y8sNW4tkJAWJrPjZ7ERYFtQFNa8fuUkxz+5VD8/DFLEyLPh55gX", + "OgGVZmPnwTXYx2zuHCgtmxlpXDsAtiLdnribjT3js8cWsqsLIA+sLUaF9iCq1dHjnCOod+FYdu5S/cENUC+oEV1hkckFC5PN", + "oUPNmbOgdpLi1fnm9BQGTII8s5wtXKqPYbsXGidmshuHVu9crM/NZCePcRnvzYIS8NTqEETNUDb9E/du4hQ3/fSB+rXRbHRE", + "XneiefdmNvIYI8TCikw7iv6zifHmk5tY0vrYOUgYMAJkzsriTXBc4+4MFiS7DW5dwDpzpmeGsjPT2SiG8bBxZxESJls4A5mD", + "ZUF7UCOG1HhxrrkEwXIV3Ae515y5QSrF1l8C/z6mcLhyOFsaA+/Xf5yqn1lqLB5uLI5ijo2pc43JJ+AakEQ2Plm/fBt0Vb94", + "cPXcaQrPsYeNQ1Or5++hk9Uz06BerPPq5SvZ3Fzz6GxzZqpxcSlbuJPNHatfmiQ93H5cnznTXDrU4BhGmncPc2XIidMk+PP3", + "6odBnwcaj5ayl/fr5yHGKZ1Wf7lAaXMPgmt+9fIN7OPq6Kns1mHIfIiX1YsnQYqQeKunn4HdyCmY1NjIysIvjSP3yRqLE82T", + "t+vPIWGucYTTz7CzjbvHQXIih59jUmS68evUJqfGm9MPIUmofRaPNp/cWx2daJx5TlJ8OZudPp69OEsVMH4bLTFm7sXyL6tD", + "V7Mf72FVufUPf4Ikx0QaZx43Z0il9WvXsSPNmdvZiZFs4lE28TO4oLl8BmK/+WRqZf5hdvJ44+5DESYjoCgy4MwT8hTE8sKZ", + "bOq+yM/T1C/3jmYLE6CT5tiD+qVD2enr7I2b+CybPrSyfLk+fqs5BJlzZmVxPLt1v/Hz+WziJkRrfehAY/wZ/31kPhv7pTl9", + "C6/LlodXry9C5kMjZA8n+NKxU9kQqZTf/vwj9G92bLh+9MHqwZuQD3gvJSHk58gwxdFJTG2enA7+vTuCma5evAHGpN5cHsVQ", + "G2dmoVNIqJCcowuyzsfxVX3qJqQ6Jli/cLV+dnhl4Sjoh/r32ijmSPk/fr25dBqciDeC/LDjjetD0BcUZQsjZJnFhcYU6Pk0", + "tBsV0MlDkLckKiiXsR+zmXm8t3kE/D5DjTxyjPwLWXHpauOnw3z2l6ONqSONhbsQ5tkViKaJ1Z+PZdNXyONjzzB9DBVQAeNp", + "TC0Jvx/NTlzNxibr569RTUADAhIMHSWuAHePjdaPjWbHz5MLzk+tTo5kkzdEJwpzQa1PXqtP3WoM3wWV1p/PZpceY44kOejT", + "51eEzq+CyDEe6JHmMub1AgqCzE55eBqcK3qEuoZqZeYwVFvz7pFs6Tw55fgJqrOFqWz6GIinfvgqv5o+0rw5jAbg0NWD09QR", + "EIMLd1ZvXiUKuviycfhZ8+UDopTx2+xt+iGRDGT7dbz3GBifu/bwFMXIaUiwS83by+BEbOLq8I/Zwnk8Dn23snih/mAJEgDq", + "nlILuzx9jAKWyOQcNB006eqNkWzmBVEW5ntsERQCucH/L05kw3Nc1clr2fzjbAJccBhcmd24Aj6tXz4JdESyvHFlZf4o3tU8", + "QE1aPzuGHSdtzz8BMIOyI8WCIMG2M0eAN6C2Vpan62fms4mDK3Mn6kdOZ8cfgkMhjSnlbjxs3j1IcDJ1gWDs0VLj9pXmieey", + "UPcx2cbi3cbi1MrLa8AhlP/QifeuAylBlBFvQAbeuro6Ody8eKJ+Gurs0urNE8AY5Menz6HlSZ8vTwPVNK5OEbJevo6Vrz9a", + "bJw731w+SYSzcBezgLqHxMOyNMeAYMdAmcSfk1eBEMhWZydWgaBI24fxCqLHh4cotB+PEjECwY7faz65CgWRjYBP0dUywCeo", + "t37uJeHNxPnm9D0sDnkWCHni+OqdMaKsFwsUv0N3m8cOZWB5IOSjF1denFo9/wjrCSKklrl0vHl3iIJ94iAeAbNASJIHsb/L", + "l5szwFFLK/N3wODciKdHoRkbd4ncwOBcHCiy6Z+aB683blPv1M9NAYkBXVAHYYXHr4B3sJvArqujo5zXydtQXkQj2LvJabLb", + "2Cw0b/3UYaKLS0eof2+NNm++JKqBIL20gKWD1sumzoO8sdGQnxTyI2DYU0RNl2+QI4AeKQ+vQLCwt4dPQGCgXuGmcWCY5sMb", + "+H/94jS4iVJlDmQzvvLiGqXB2C/1qWP1yUf1o7dFj0wSNg8fJwdN/EyNef4ZFfHj0ea98ebSEvgLnMIdnL5BGDl0AL0BeONd", + "MBlolTx5AundePYIuJTIHxpq9GewD5gd74KWAdQBua5evs/9WqCGpRwG3b6AAroJ/Z6NXVu9eIuLPzbXHD+IhQJuwY7UH1yv", + "n52Dys4enqImHfsROA2asX5ERgV+PHmCCHD4nrz3KWTLysvHUDqNqTNQDUQay5dXf7oEoYcX1W8OgcawF9g76AJMs/7oR240", + "ZPXcXOPMT83RxxzPyRFiQiA96EpAmluAxM/w0uaV49n8XOPOBDE/UNbLG1RkoyPAupQngKywccYe1ocu1w+BCE9QjxyfABdA", + "E2FqxM+3X4I7aMIcOwJRSVKEBJuHuXSJBPbiF9AMtpvGyxFIj8MgRWx3/fIyaBUgDSILjEZz6cJpzI6QbxycMkkRDZvi+CgW", + "nGp64Q7368h98tTZJwCiGN7q0DVKTtLY+dWr9yFPmk/m2A8miK2cnFs9f4nSGNrh5Sw1HawqyHPgmel5rjCWa1yspMvXIQ9p", + "KgI9TnNrQPACcp5ls8NgHEjO5vIVMCkUUHYcduISHqRp8Pxudvs2RAStGGg9GLCXb1uTFjQM2iPNQJlC6UDaj1/h4oOp74xB", + "o2GDwF+rZy5iozmFk2PAexDp2dALEBgnO3mqcfkm9DJEE62whZ+hnlYvUJ1Roh5Zrh8dhphdPbssHLdAFAGLCVoYtsniE3AZ", + "hHN9fil7fiebeAzuXll8CRKCpgCLwaqC9oeso1EG2jhzNTsF8+omuAnwlTY46OcFqGK+eeQRSA7zwr7TVAQ3QWLAwD8M+jlO", + "UT98l9sHTQrBuHySZAOhtHy++fgmMdszAPLR7NJVQuWnF+uzV2HZUQGduEfoC6MP4788RX165C6tM5Dl0DVIG4IWtJlfFlty", + "oT4x0Vx+mE1cgJVEll+8Sn4/Irxw8X5zZokQ6xglNnEjLDi89MQiddCR47DKaR3MPwEV1S8fxNhAAytzL0G9VN8Xod1G6pd+", + "5hwhb2mkwM69CQlDLHRkLLt8vrnwC3YB880WRjBs4HYSnvAL7fFLV5uz8vkh2AKXCHcPTjemZwEtaKfPHoQSzCbOQZZSG8JQ", + "nZzDyoO1iYrHRlZ/vAq7Bn82rk8TV0NWLx2lZXR5CFZD/QoshYvNGSCiaaKg6cvNJ5chUQlabp7A3OsnxFqHhTXzYzZ9DTwC", + "sUO4df9s85dzjXNL+AqGCSUDRgLB+8tFatLDy41fbtdnJkSkTGW3LEeP4BNqn1v3609ug62IJCceNg7cBEUBo2LK9J/M/Qx9", + "lE1foDsCJgOQ/+Qc1fTYhcbZ24S+eGoJZt0YjaOlZQLpySlQIO3QseVs9mj92gTFEYxErDbIZvRJ4+cDpKgDpwWIPhB3ymkw", + "Rf36TVLs+GMIk2ziTnbrHPl3+BDwPE0AAoYLwGzZ5KRo5+vNn4HST6z+dLJx9wDWist19zBUZ/3ZWPPJfDY8Cy7Lli8AONFJ", + "BSN07g73/eRxTLZx8QV9Iy+GYElRjVKznxdNQUqDxIBNQctRLDj8jt5grYiJehU6moCfaJM+KKIUIIHLV6GqsNfgAsqxYfoo", + "sDhURi8uNO4OYRkB/LAmEKGrB8brY49IRRM36dtZuJU9nCXqWL4M81wsCDDyQbyasoWYii6ybHaWJAd1efgquLU+PU6Kun6l", + "fvJS9vBoNgtleoIG2tjz5pMbtJVuPly9CthGdxA+IZy7/BPlxvwjmEWYHUUcMNXkOC3oi6fwySr4/dgwpLr40J7REnw6SQgH", + "Q+DopAicYxgMZdqFmcalF43L2AtAlCfZPSiISSJJrM/xX+g6eHGhfugayDK7OUphODzbPDJDJ9jwMF00D+5gx1cvAic/w1yI", + "XoBAJmZgk+J10JL0PMBygXVJG2SJHoMbL9DPyovzAL318xP0g8FaxKZg47DRU+hwBpSzOnSQAvbEVew1QBfFIDo5NwpaArRu", + "LC5DyjXuEQU1FsewYjQ6jtyHHUcfy8lLjaMAgZPY8ZW52xR6D+eay5eykYuc8qUjsGQbv2Cdj8B+ac5eB5lhoTjy2y8bi5fx", + "YXb8AA3b5UPN5UlMCoYA9BGdTi8uZOPLbInBP7jZfDqRzcNCOUNnJnACmOvkKdEODymogbuml4AVIXP4lqeHgWDJNdeerP40", + "0bg8ROl06y6dgRdm6jNnSSEXFyirj50jl00fI+Ngs66egPCk+QPxC6V/5DTkbePMDfo37hwUD9U9Wn/LlxuAWJPXGk+uUT4A", + "WwJ7H7xHXDS5RG/k4UlRPeCRm1BbAplo41ODTx+pn/ixDuA3e2R19JhIuUmYbzRs7y+s3jkH8EyL49zh1fuzRNdzR9GG6zAC", + "6578AjN8Zf7I6oXH2fAR7D79US8OrixMZyMABkcbJ+5Txy3dwr4TQz48BaUMOqE9fm+WWnv4ObptnFkEaCF6eUyjFeqeWBRA", + "+tBL0DYdd9cfUEfDsrh0tD43XL/9U/3klcaDU/QSXzuwukhUBsoh2c9ebR6dwHYTnc4tNqavr154Vp9+2ry3mI2MN5YXmzOn", + "IITBONmBn4iIXrxYmT9Bo296hlv2/Hbj6FB9+OjKPADnXOPEDJn6KsTRItd8+SnRyBU6e4HiuJKwlI8tYzpuyjAOHQ74jOvz", + "Yt+TEMnYD33XjxJfV6pRNYq/TbWbMlCFJ55eJAGzoQRsGtY7iJUEzoZhVCnEWuJnw6qOmYSlGL8qIaXG9VNPeXLOHqk0RJ/S", + "j/HkE4maj6uxxnuNLr1aCCWO1AxEjOWQwFLDdJJQlVWBucslOUhjSK6R0EIOm9Eo36Z+1QY+GomtNSoopaFyozjWkU3uZEiv", + "H6s49guMPkRvZRm55gE4DzI4TlUp+GsRiYw7Zai5YaDfq6lQK8btuNoG4UrsqITmFhRDcGOJhcV4UsbpSWxPVGHAZjDAaEB+", + "jvnKKhkJwDUSpBtKVQAlkbyG51CMZuYpu6eZzx0VecYmkZ5G4mEiZk74SoIzOUesmBtVqjZzWxuJ9uGuxXiBL+GZPL+1kZCx", + "xH8aj/E3mGPs+qoaeRgEs7WTyPM5UPxeCCSomFECmGvA+h1+5Ma+8bGbzEPCTqXsAb/rIikEqxJjZSW9SmsGRkUSQC0Ryp6S", + "HlRU5OphBdBUt/HgnCujjJyVG4lVixizZPtnNChWKpK4QSNR1waT9Rlly5wRCaM2sdr/6jHeWfA505QxblGgvSjRIfYXk321", + "YCQ6j9GyfqgY14TxcmWUy7CmyH113fP3S9wnY//wlGR7Ke7+flK4H0TYRY6ZJB+/ur/PxztePa7q/aQqTw28mvJ0pAd4dllV", + "zAKuaIaQM5SVaUBMlyi+uu76gasKeEgigiV81UOfeDrqU1XMQoJhTUEoRCKnjYTRxhItHBZltbHX3HGG+hpJ1+VMMfeCHxRU", + "RI4A4ZArDWOYlMQ3etHrJ68Xf534dVSy5BdeP8TPHLPefz0unzz69YDkyj/G78u/DuHzg9Lm6a9H8HNI8up/kk9m8dtzyalf", + "tJn2r3+UZ5clC3+KvUmPL34dxacvmK2Pvxf5b2bx49klyep/jNZr378+w7G9vsr38jv0Jxn8kmH/4vWC9PdY+n/E3mVsL15f", + "f33v9Un89yGevWtnIc8+km/xJMZ9Q8b8RD7jW1/IfGXW+PZH+QRv+XVYZs2+WWOALZ/gn5fo+Uf7xrWxMdf/x99HiGcPrPXA", + "NkPocfbfFQPm8MRLWdMr8g/XekTe/lDa2DoGrCywJJUDltAzx2nrFyz9egC9Pfnt1tnfbo/+dmv+t9tj8vvQb7fm5JOzv91a", + "kk+O/nbrzG+3Hv5262f59z35dkIa4P/Lv92akqdG+SA/QZtb8tS8/HtEHpyXNjP8hf9eYhs2vo3f+xR5Wlpe4v/51PBvtx78", + "duuO/H7+t1tj8tWS/D4hnUzLG+/9duvpWp8c1e3f/413XZCRXPq9nyF5nfTD359Ky3vyyb3f+0T7IzKL6d9XYFpaYgyP5JM5", + "6W1anrojn5yWp0bkwwfSYEo+eSDd/sQH+dU9aXNe1nZIeht6M//28Nsjb27z329H3zx8c/fNjTfTb2bfzL+ZwT93f/8cP0+l", + "rsPC2/E3s1LJYYT1GdCeNRhG0H72zTO0O/z20NtR/H0Xn469HX57UOo8zEslh7vyOVuwYsPP6Pkgqzug36k399ET3vv2AD57", + "jt7u4e2z0vI2R4XfhtHiLlrOcLRSW2JcKknMv3mGb8ffHsDvU29+kbdybKPo9ybf+ObB2kxG8ftj1qLAeEbezMiYHsu7ZjE7", + "zpRVJR6ylgRa3pTaFMPo0Y74Z5kJRoCnWKPiKZ56gp8pfDIm1SpYDeOujJZP8D2znNfvz2KEN9H3GOZ5F0/fXPt8hG+TsXAm", + "Y/jnIMeLliNvprna8tvP0ucw3nj3zXWZ3bi0Yeun3BtZn9m3B1kdg6vENZZ9mZFx3JT2WGfs3c9cXTwxgs8eoI9hGcPP3JM3", + "D/DbfazSCFqO463DaM9ZLLx5hE9GMIfH3HEZz2Gp0sEVtqM7iPW5J/O+yxVGTzeFRli14zr3RMYxvLZ3h1jRA9+S5n7GNxzV", + "vX+v+mNZmUPyrnmhihmMD+OSt3Id5qW3Uel/lDMH3cy+ec4xSGyY5AYxRpKxp2mQlBnkGhRtBLbAOgY8pVWJRpQwJY+VNaS6", + "g0SqFZUp+1HYZWPsJeQkrgHuSE6vRNMzXZ+622YCmDgNQ8l+jvg4qxEwkldik5ldwzzOQR1I0UXgMzfQaSilF0LNrPZ+ohsV", + "1rwa1KpNyzcS0Deg3Br6ZLR5r50Ry9GgU8+X3IhYS3ZyLPPFGwosP1H2pWiEzQMwa+HKfAvDXXXMeFdGyLD4QJmR0YGNu88r", + "T3IepbKH9ga1RDsLtnSZVO2lLsvc8C+AGYZ8Mp3NVaFNnvBMKtMV0MzcIrfMtIU0ljoWzDJhwZECwEVNopSldKdivqcUbouZ", + "mIDvKopp7tqGJRpZAgKCkFgBgygxzg8gRyc1m48ha81UMonJ9xJAnxLTFBhpaxiWyXi4QHJ3CdZCQneGKNcI4jFcpowzzEmC", + "vphSV5XUhICxTDaXZGMfOsMjeLtsJ+uuoW/7pd7H4FmzlltRYLymq3dxpqa8w9JZUo4ZcrVHwqUdYERb9oGh8YkakOg7GgiY", + "u6QblXQvSIGV7ohn45qnXUY2MVmVySO+4f6x7geWmMUT/IR1Nhm8WJKEuoD0wZQBLS2NDXSS+hisUSH5rizeCHhtsxyMTcow", + "Nj6bRbu4ZiQw7ABjgH3JDiFpeH6JyLzqu1yebbbmSoXGBldeMeg3sDtt02SsRaQCEC4p0mZPtNuweCNxnQCNWuLGGCnL+aUm", + "cQraZnaYv1lqTZlsENQ0k8485kgwYI0B/sJjA34ESImFxOccpSQdCM13tadBz7oWBr2yqEAgdUkkns8PGcHH0E2m8pW0slNh", + "ATSAeonA115V0gzC1L5/p527qySt+++W1RhJmzIpB2zkgsrBI9rbxvIhTMmgfQPSKHGrHBvnZoN6GcdHatiWMussKelE5i6p", + "LYZDwV977Ba7SvjXJsgwz0CSXYjqXc38AW6wrLUh1cEy6d4kb/rECgGn2wn1oLPD7oNNbfJ6SSEq+MLKHsoQX0o4kEnA1+SH", + "HcxuK0k9ogILMjJk0xS05JJILLj2duo0MUzpCUnzEr8f2zo7LCaTDOq15P6gZuz8QFKcdK9lX8iXKslzX9kv+AkTft9pa9th", + "hYfUwGFC9QD3IUolCnQt72UtOWaDFVrVlDagFjndnbMh9w4DzqUwh1DIp2JLck9ABcwiApvVbGKLadvEmoItkogQV3ZYYcXi", + "tKHNCiKBVZlaU2KBFIZJWsEpMfza+5jUH0IKMwvIY2htXOnxYbmknh4sa0tSzATxeu2OuSphoP42qwNsTpEt8ARuCH0+L9JG", + "15jngpXfwezAUlRmyRFV+9hyODOGQLQbrQgSkgIpatalLpEZB0i7hoGJknsFwqcACmr5lhYmC+C1DojMA+2AA7ZDMmBzd1Dq", + "QkliiR2Wm/TRSn8aSy3qnCMZ2DaNw9C+9aUoM7MVPrMivZxKwqMfOmwFSaD82OzACjKdmRmGKijENjzblzyrQFqXtrIOb3fO", + "Zk84a0lKjPTHmoGZK37KLJB+zHZbhWVI1S5PcuP/Zef+udXaTEtxkkgiO7tzVKaB3seoaVJBIpkHBUbODmip+KXjNpt+Z9Pp", + "DGsy4HGW98Xcd4MZitE+KjcGJkNX0WgWYQWVtc+vpJWyFXKQK74X1CCfK1KFFFQCBY9xsuy3xHsbqW2FqWAE2uZWp6z2GiqT", + "1ECeeKvTa3FIzAzFVFOWRJXaVxZWYM1EN1ImU8ChZ7xPCXnn7RJss6hkl0eN7BhdIhd/FUGUJ45N5zB7lOtb0czcgLTqDEr5", + "Ioa7bh3UDst+bxMtuZalYb6x2XosuYRJK1cEBCsoY9+l6Ib2tjoSyptYMFSg1jVJATtR9BPGRWOAvVbAszIp1gwSGB2aSiTy", + "hXXy8B/fOCxozrnHRounBFvB+tTdOVF1IGhWFhpgzD9TEbgPUrm0ormi+/D+is0HjrVNDNqqxa3mYZEc1gVieLYCD4tKHlQ1", + "LrmzLWUeq80yMzss+LJZZUaKwEGPs2iakdQQDEIqYKxrqbKmNTR6LKmRLuuNVxPBbgwkjiVZzQZt2zROFgJjipyzfj0ZDwKE", + "c4cyDSSHFcIcMsSqeQuwtAJZgimZVi3igslqpjUvST6Sceyu5SFBk4hrx/rCPBvU79gcnFiKrjFOn7WK9C4J8ocwFm2/lmS5", + "w0I/X3xmQQhZTuiQyjZ+Y1MimNJBOmNAdK6HQjwgLJTOqAjwXRsgZ/9aGpn2/pqyPDL1UVUqxEELV8zeMlSccSrRfqIbbqMv", + "ZVmY1qgtM0PAU9xtFYraWGb5Le19GdQqABrfWCFpE1mNFKfCxACpQt9dy6K06YyMzwdSFB9uIsJDdsTmx0qRsaBWsomwUiIL", + "9GeL1FDxsRurFC3l51mVouxXWbDHZ2qtiC7JziFMYUEiL01kq5gdymxECxkT+b4kvBYwGYE5hNstngf65Xt/cKQwzx4LJ6Ei", + "Ka1Ysh4kthuEAUFv0xONZNJpbxd5hxqnSG3PVFwAHt5XAGnTq2UubXaVdlsozTyyqMgiJiwfJKWLqK5D5lyyXNaGjtZ2lpLu", + "k+raFBfWjOhNdLWsQyYQ6NCJCmJUSHmmdS2fS+aZwxXDUHOOFL2xKcsGemU3iLyl5XOwkWNzs4zE8mMfrNQr+gLJWCQDQ6PD", + "VMobMusCFoqsEgsmuT6MEYB0Y/osLX2sWSzA2c4iOWnFlibqSQZ9QWYREzNqrO7O8nMKuDzWjk2jYA0Z2mPlmE5EMi3ZUXKy", + "BFxClLJq8boWZ4c17kDr4EmW9DcYIN/uKCNv98E+klrYRbbo6WLlewAJQQ7rWmy+nrFj0XZBthLMohfXIuNNNv1Ayou1OMbu", + "WMHWzLIJp86glrS8jg5brw30DiIEDKUEk8ofEJ4+VbhT8HmtQo3XWzgsaupwA1kcHX+9GyuohE5e18DK26y8FpY2WOLdiX8B", + "VTF5j/TpMzWEpYD4hm1WlPwNsAz25wCIkV+mFDLGZQlCFYhqdbr/boWHVAmDiHVEndpkFa9LSWIvE5GwmM42yN/YFx1X1jt/", + "N1cTKBKP6S4DnBHTljsLioLFsDA3RwYJSKMYIgNrSh3uKNqUtD6BR9nZX5mSCMghmSaS8EY1YdM0bBqIs1tyXRyiGbJvrUpy", + "k9KHLm3Fii91EUPHL1qjKbEJYR4JCK9tt1KgYLNt2sRu2cqKnGL3My07L/lTuR6MDG9NYIMEWqw90rzk/OA7LHLqJ7vlsgGP", + "eU/kC+oBZaQ+Xq4Hs+Q62zRZAEjeGNDDazGcgtwygk1VjkitCg3UuNYumVP5ooUAHvYE6ozFaaDZXIvZpeSB2DK0vvxEtH2Y", + "ikj6q9RQd0RUmoTQD38WpfgkZQG4kmW9WHvTChRnsBxxuCTSlEU0pDCFAcjHeGXpWDJT8t1tQrfplZoFDsv4czejCreTSAlE", + "Rf2HF9mkxa5CjZvpfGEh6h7r7LApryynSfZg4hJ0eS/YA/1JTbegtoeaCRIycniCRcsmpZVMo9TYKgnMGaZ2MpKVbHiFCpaJ", + "9YRoZSnJa6LFDqFjkwg3tNlELDEjcj20ehK/2mtNZ1vpwOxN434MQgqn6jgvJTQ3CC5oaSlYGpTSdbyGg3maa5Ufur9iXYzY", + "k2zyoFblPSi+mMX+7ylELZLqtPWPaSAMJIdmRi5SEAkGU8CV8vACHbSbrvlDjBRTxcR2WieXXdaWrY5UApS6bzzGSiEcKmJQ", + "YavonsL49kl1O0lvXddiqxzk/7KvEjgDcq+N2GqsAMc6Atwk3qmANhr4uK2tpzUPjo032Iw9w8tV8ADrQOF/Ylbv139jGigI", + "RdJEQeOx251r32N9SB6zy+lJEsyXWCC4R0ppOLy1xvHDv7JyW1neTIBpbbUuyUbvUY7AYN7bEK6XK0Xijc4u6+EpwrYjKiPD", + "RPEnKc2h2jY/tjUOZCogG1oun0uZlcDm+pk9a46ljUBVnuPYvME19w9L1EomfREs3WJLYJiP5SYdZ5u1c/hsRYmes5UxABBr", + "LHEnOkBEM9sbSi8gXt+wdhwsc9bJj5iEBhycxDtstZLPUwNkYv5uzSsYVBXBpuK9o7bGen4qeaIbpXZmUGunnfuNAsvInQJS", + "i2DDtlTKLJJFQW7Wu7Xx01A4DpCYO/aJdnhJj00FN9vkMLbW8oc/sOLYThiVGkLI2mqSDJfrYWo3WEZwz369DXZfWVU22NIR", + "31kGqqbSdauosQ0267Fl57a92/7p/CdxInCF2EU0KhKMXhLX6YVjdcWa843U+1svYgayTFI5jV/cQNjwaSLDfZeX0HQ6uR6p", + "Q8sbbkAvX1ofp7ZAl1fiiOxh7mZYEvTjRKGU+xVYUay5lHzkKuuXSqDzB0Na1az5GQ6QPIVRwxI3DN/xChCQcM6BRdyd85iy", + "HVXtGxLMgRRgM2QNjH+OgtUpwc0qcGm8t3aKpLDJggoYgnJ+QNS/+A6hXrdZ7ytr8+o0VtaHJEfaYJUgICYaXJuYqBkjzr9i", + "TQSRVF8p+mRtDNpNdlqsSJMVy9Mie+rYgiuSj4lePpOSB852atioSG0o7sWQF8dQDYJS+umk7E8kOXm9TYzMObaUTfeglabU", + "8l/5pc4WmR/LYXCG27BRGx03TqV+Desa5Hrox0S/UnDTsJgdjWwaBunvhqaxWcEO2JAuCsGK3U7LOil6mURSZOAra7HvsX7h", + "3RZr7KGjgKV5pHTF3/yYpLVWkGGHdWvtsWjU5sJ3VgkVWOtC0eX5mVirjq1jYraFAExhzep35yvr2tllrXJrfhjXUjk2HZRi", + "oRgdKGL1tNlCNF9YPCi5oACZv1eHUCwnZEtyGN6yRHAixYKMSL5CjfpW6nbH/egT9AmCrAF80hXI79C5svKMF0Zh41paeqEo", + "nfVSBXm9rbph+nWNBcNF9wcBU9TRUirWtnbSO6kHHVutx5Fa2RCmscMEZiml0Lk22k7xvUIfSZ63sQmwDr0ROij2Wq/Kbi1J", + "2wOihLXUQzJlemChlhL6l4BkXamZQHXusEoUtafZmfZTKtoyQRvFIPaTQSvyeAsRNkA5kmKc25orJ0mVbwYn2qoTLVJ2KKjZ", + "WjSxaw0HMjp7F1wX9trjBPo78aKA5ZyTWtHaFhTyADXa2lUmpaNJ94oV6ZQtXX8lJU5CqR9gkm0B3SlKlI14PWheCfbN9eQF", + "hnpeJDiraBeE9VfRhv4QlZR3Wo23w7qObc0b02qVDYawBtN4IxxRghVd9Ml9ag3Nol9MNC/BcXgZW15Kd+blWoLQK9py8rDV", + "WEoIPBVIvnYJ8tvtdj7Hy/NiZEP6WWRctQVAlCN1rVl/DUvACvYUAuL/cgpitsS82cyh9Uw177BWgsPgFsH6sVQlWStyxAoK", + "iWinROoBB1HqFWO6WtDZ5+Ks2MTDLvp7YEFC6W237mGi/kgeYIjRgOVbqRAP8Cw17DxeswKRYWs6OFJoRHufWb/3J1IQypEb", + "n2q8OAh/1cTbBGkqBTMkaogQg5Xocz1GRlDiVT+gwe2Sld3KqnXY7NjWXvoYyphnZ9gAB5omZe01z9YjMCwO7IBYrEuPZTa5", + "xdSNWAkldo6lSCkAgEehubzITWUhy6ytL8X0WZmmmFoPlGOLXvTsZrk3U6O2FzjVh830vrbHHhyuuBQiHvLYM0VHnAGuTgVc", + "OJ9be9rm87doGhNhUtDiW4Ms2MH6aP4+EhG1fcV3/9gh/yPhxfRLeYCmji005oi2BWIBscgKAps63VJfmOdArNph9lhQynsM", + "iCMTeW8xFef0gNy5VLK1mKADxMZnbBQsWanirdfqvBjymKaXTjSKuNFc8gercNjSZ228JYb+AhWSWWxmPZbSIRprzUNrbmgV", + "p1FrpxQOtoxHrW2lDU9TqY5in3X5bMkjw/Kr+LGeWfC6Q2G3Q9C2sdWnnO2pGJprNYz2WqsA7Cv0XdWsWlGKPFal26tKpM9t", + "wlRbqbYgWL6SCi2gdIZgyQ2UEEi29MG7n7EgUBAOaocsscOex/01hVQ3FWuv0LVCXSUnEw4kvuFYIOJowEnV8PUbhfhgTUVs", + "HbSIhmQ5WtYnobVBq3ANJkBVEIba8la2apjZzhoPsdT/4QE4+R6i2dIgL890WH4+ht6Od1s3Ux9Pr2F9ii7P5615TGgSstyN", + "w6tTbGki1sMB34fyn8TGJOYcOb6JHdYIpgTF68JIbigTqoMMqVVAgWIQ8HYLHXfYshCEB0C/Fo/n2v/T6XrnnzvESHO6I3GO", + "OLRdwUdytZvnWPRLs8X8W70YxxoXEIZ4YFAOB11jq5/x2kqWTuGNkBSAmD+Xbs1HKtLNcWypuB/Ea7fBFhIss9haIdo3aFWd", + "nZjHWm37wWOOF8E0ia1zPO+Igh4czOewnwUxiEtS8T3aynXDWucdcZxZd5H5/vvvfugc9AUCREVTC+3y8JzUSE1STQ8niZ1V", + "V/bGKhVB6hhbwM4aKl1gp15ApW3WC27N3Ly1BpMd1hoUgsw5f/cDgI+KSWHFFnjnWIrdKvhSWzcvVwJssMUQHVt30EidmKgY", + "siaaCnbYk2zWsguU3FWABZHbAIJam3XxtNkii13tgd/T0pJ3xL0IxiMVQ/zS0b9rzScudb6cAV+JrVZltcoApEfPXpwGgp5j", + "cca5lhsJClivLw0oCMtk+qjfVk/c2G2JaMNa4TTxswIBS5F31mrG8n0ulUuc/+I9q15trRoUi/ezM/Gle9vlilcj1fu72gnq", + "iG1sPUcCeEjhsl8h1dCMKGAbxY7Ls84/S4PD3uS1jpxWEpm8vefRE+dDlcXSkpqlr62+EHTtM3vSqxxhhU90XBAejf1+ULKt", + "h5hfK/coxf/Wjr6rvAQS7CSetNix8tOhjxMmHdAF73ikUxRMEltMJGfjjsNTjwrvLvVjkbTQcX7yXxb5AwtHoR/Zeo3OWnnA", + "NT1hSxLSNUpvaK6VF6ltEGdAwMNtShRbVW1t0Bv32KgBLCPvGHToE+/OOVaf+aE4A7rsMYatbPO3nq7/3Q6RSBcQT6QtWDcs", + "yBoD3ooSljtWlHmn21mPv+kOlWtr4wQrYWvBbN0WqwKQHKUw5u5adxGri3G2cgrYZisGbgQpUW+w+jK+o8oEq+0IuHIhS6nR", + "GVcSfWudt1IVn2Jm7SzSajxMnbW4d1gL0xavMj3WbJWVoNcP2LMQ2JJ6jkRWYCpiFeSrZmvO+Ytjb45JQE486mLJdmyqrbdo", + "pMg+RsY7ROjG8Eg3hBWCEtB5d46KyJ5JMc5juyrAngnt+diamBF3A89gEzmC22YEvtpKdIbc58dkXfoJaXaDfj5hxeEo3Lzm", + "uXRdogtbJNRhOX4enVqY1iq36G2oUpqhe+uTBZv9NQ1qWMY/OTkiXB5w0u0KtEanE+hRLGG6+hy57XT9n9ZDHVpE7NgaalQ2", + "HI6ts2d4uTJ3hWfeaq0QqNNlSYpgSw4h2XIDS7aBEUguMDHAtLwSOu/IuZpcYCIlOvF7rd3yb6EkyAeKgRv+qb3zQi4bAfSz", + "8GBzdZ+zpbqvT24zycutSI6yFVTzMFSIWCw9t3WLT66T9EnVJAVj87ZPR1Sk021rt26krcOb6WxhQFtgik4yBiDxOkxHGVuz", + "1JMCgrGtzd/iUAlHUmWViLpo6YX6MaTH16Hbg0tOdWXPDwctrBgsixeWZ13g4kLcw/s+rS/HsSfE3aKkgCBS2vbaN+I/U7JF", + "zjav4sfi7t2nvU5b/db53MYo7SFdb3QoSWI/IpbiEWIsChb8ztKJ3Tm59oSFoOxhMNGvkpmIkBX0K8JYbj1wsFgVIn/ei+Ww", + "phl4Mk0M5JIp1tBtUYoIAr9A9kRipNlCaUaIL6TDDOxfIWziwYovINHzxam9m4ezMF7FM7fBFs+kP7KKbmych0NioFKgNcEj", + "V547G3ctzIDFrH4vJtdGQw1bBSsZurlma0+adqtGd8QRBqwcW++RVzBwYomYgyIgsA9aNF3rd4wdg4wTgBVYU4+XVUGj7Zb/", + "5SxP5+SKB+UwySOqGSIph3fF8BKN0B4GxxUrwdKCXMEQa4llIxQDRVqY1iPBj5iYlht2v7BHBn5oywFHshh/Z0nW9eYLe6wq", + "RSZVKMcJtANEO0JmEbTZcr01Iiu5Hlc0nq3L+R1hPysBSg1V8KBEhuSt79+RSmEb5N6mXE/KGvq5HqeXDmU6LQZEBUD7QltB", + "f2L/CH1Z8BjCBpO2p3KOY48j6DIBWW3I7fzy8x2RDTgUPmdchJg5zn/ZsA1bU5CHyBJPFFH9DloI3WlhWuKtCWqRIWEFBhV9", + "HszqIR4Wz5elnvWiRaHBpb6vt50hXLBvo8SWCpNaYdYu3lwSX0x1hw0hya/VobZlXyVYocwDWJ47MuiQss6VXkS38aTCsSFc", + "jB0wNBXKUsyQ8VmcAGSDjYXrLlg/Hw0paMzubodulS5Lri1SbpRnWXJUK8y4Vnw0Lxg9CqnYoT7z1ofIMyxaNqDfYhTbArGO", + "rVWIacs9Y5GVkbboX55yUEhMIrR2WG+9sZWAOWjMhkQKjibKwo5acc+9IwmTTnzMyJ7/YWFZlJG0C/gnJQwZeiIwzR5bfVOw", + "8AA4mFc9fGrBui0BvlE5cobDx7EUX0j9P0duANExb31n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", + "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", + "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", + "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", + "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", + "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", + "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", + "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", + "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", + "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", + "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", + "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1bDiim5rsUq+3zZcoeMkKdgPo9ncmTOXE9UAH5i+WKe", + "aEc5qoeiL4oda7SLwVowxKSaux+KJU/ZDNJXLCKf6L/yNi8d/w997+84hFNYbYYgSPgv5bRjbJQeRkqg8RcbjGrzJdbUtVPw", + "5e5KUbDdOSyGzCgRu/orSbfYaCtAO7aAtmPjUQblHlhQJ/0myqlan1VkBXyb3cBOG3pki6k7tiqyja/Qg1Wri+WCJkfKnmPS", + "ypF4ig2+KLc1x0KnPfvW4f4ag5PEMUF5RfL5zh4LcZSqWsMwyFf07IhXnT77FrlojTpQfOn/O+3o2LJDic/QURLp8Ic/2GhV", + "4UxI0q7eHV99umfvVzaAxVZbb5eg82jf9tqn3obcPkkANRsH7TEnxmKEKIsOuMyW5XcsQDXO13ToytlhWUk5cuyRbHGhxvLa", + "PFCzBx3WsPXabSF+ez1XOBAFxCh4A0/5lGXYgj2+/9Qew4vHuBTxwB4DtWzk2DiyLuuzUJ0sC93VbsugG4mvUolFDjYFINaO", + "rQEu/N1eVo7Y7FUbXfsJ9VE3PWRcZ+ZFAwn8TUnIX/c//9W5oZja2uSmvUfc4XS9QaN+atdF+KHrHXsAZBwbErJd+30SWQUl", + "+OqaZ8P2JSNbpxCo/ZDRJaX9ACYKhCP+to43RVNL9WlmP+D9ib0EpsLUYDeqvrpektsoYXIwSFouVIncJOUVVKmECLMLkr80", + "UPYuBya1m39nxCuefb66z/gJ11fGfqdsDlVk0/FZpZ3pvjbuQoWvFvBcpJj77TFLmLG6FQyiwEsfqdlsSnxkb5KCPdwnNpFg", + "4nK0lm8uWUVexHLqJcaIyqUbTCXnFX68nZE4f8CGq3Kc0asFXsUcie6IjE1timySkL3CSbJOYhag57VOfoQB8ZakiuS4RzZj", + "3GjrDJJrtZj3gqWKaX3qV7NRImE6vDLK80uRXEnhyT6gM3EN+EpZZxxWgtlTpZQO/NgWADBrtQX4l6/FzOeFREzkgvB7NZWk", + "vEgp5L1MzDrnDUgUvX1RUfSKkmwrnrfxOyURchDSkuFusGAMhsbo/VePQwmbSiRfFgO0Sfn2ygPDW39cVi9wXbaE7YOpx3Jx", + "l9yfy6hEXuoTv7pOWyf21yoTmMravjNLfwo4D3QTKrvkUpQBY+HtQj7vtqowc5wS59VCKFeERXIhWIXXhGFZlVQEkHh/xlrI", + "bdkVe20zbTGe1vMwnX8T5DMuCzypgKPW0pB4aaacAPKki04XuaM45h2i9paA32+y0fts2o145LEfdKJSSnKrEjnZ9xiCU1tL", + "RDRrUw7WEunM/jaJdti6lnYDnFBk7o22yQsJ78di2j0rrici32zKiFnL1vGIX/mgBO7KfH3J26L/iY5HRpGRnplZxVB0G0em", + "Ahr3RJ826EjHa7lcQI9GEuhoy4M6Al7fTKy/lrsjwo7qdC2XzkgyAYFGWJN0JVUwEl0pOXo81x2wt3HDmFf7GTsmERSML7TH", + "9OL1xIsHrGxzutbOkmmAMzaDxw8MREuikojCtaQcryC3B7Ee/aBYGmv7Jp42OvLMWnbSZ2v7bL07zJu0+W1y6zXfD3nLGIkK", + "OJCBM78nFliFHdTkYJ0ZNHK7a0y2UFQGRS73ALNZtLhvJSpUbqaRGPuEaUb/P1tv2iTXeV4JyrtR3eh9X69T7WZhXKgC5OkJ", + "N6pQDhAkRcgkxRAgq2c8PYpblbeqLpmVWZ03s4CkpAgQJLiJFGVbpGSZNkURJCEIAEGAAAFw+wD7q4L8ZDDmizuCpKiJmd8w", + "85xznue9b6JHC6oql3vf+67Pcp5z0DaQVSBOp2TsKmQieVywWq6kghTLn7y6s+nbVkQmeoeiQaHMRiwqxbpKoXSWtyCNYi8w", + "zsj6U4yuzVMY+PZ923aoHAh/H2YRVVqHlLjcxPgDaoroHKx+zANi8W1uRnUjggB25RGyiJiPfC57Zs/PTQjfsiGUtkHV3a86", + "EMQ2ZxHXUA4FXoW0ETCfx5j6XaIcJmU9XIV6rEJVnG9ElaFyBshIr55qHGje3Rg0RE0AsIP2A+QKN6zc2sI5sOFFndKGWV6y", + "TWnMMJkKBjqF79I9baJmXXgRosfgJ4Spr9mHKhaerouXH3BsxJhXR0KK2X3X690rdX/BC85iHWq6sb5Ixoi329YLDhubAMes", + "7xEgIt4NoqNdPCSWg0TeVlfZNff6OgFggAuMGif9dQ/wLTsav7uviMLTEeXYgeDHAjoc+4dUAYaIrLP+E0pa66MN1T7bPGcY", + "kUBU7qOoq0XYQoW6qxPKxYPeHgvVPklh0rXK91XOT8YqNiB8gJ5E5Fjrf9DDQKs6rIt5ayt2pIBMpxBCGqLFEyZtvFSokSJP", + "qJr0JgCAYL0q12j7HBB5W6iVMy91hK2D86NLZXQiurRP/wfBm+YdhbS6vGQG59IINTDcj1TqVUHQmaE2thYl3o66pXihPfvd", + "1nmwzLyWuvEC7QbBTEQpBZnAOG4OsJ9H3TgCAnaKVkqOdZZhjcEVUulrXX5NdTNF4aWK9/i+IY6h1REPa6p2aF+D1wO72QN9", + "M17j29A+NwuRtVKQ9uur3EnKBNZ1jMH3HB0PnCUN7obnnSoCuV98JfZ/1cl0vWy7QV4H+8FKbfse8itQBavWhbWqgV4ilBtQ", + "BaZ//ZyZMKFj8+5+GWo9AkZQcE77TavL5lZX+igLy17n3bC8ZKYoHLLWuHrdJCrfHEHelVYX1r9QqACHYp+3VWYeqO1fdjc8", + "o+aNzTczDoTAY7h+mS6wjQwl2/k/7Jhm8WDQrdMc5bZwj0o3CulIdZY7hfSXilmtO2g24n4elZ3h+T1cRbjSOqsudX5gEGru", + "k4teZweTG7p/tBqwroEKAUrD3D5s5V5sLO2QfcXnVarUkKWAMSnbf/U84x4yWUteOeKYA4CoeA7TT7KfS72a85plTTZ01O1m", + "4R0CV6vVkiJ7y5p/iC8KFiqUQ7ULAVycew6ULjYlfThahYdp93Yc2T6uPzuPHSnQ6dUPcYZ5GLHY5W6jF1t1pZszM8PFZguH", + "6sebkHPvc144i0DjsHmGE7An4ZxEtY9HFCc4i3HePzDusuLRS7DnkYbGdQpfwKpxh+IeQfIduE2luUkSeqO024jlGTw/oYFU", + "8pyaLxQW7dYEqxQqfVitdsv8290pVLnqwCgWEWL7c+ieOwmqfiRQqpK7yH3GFqRXJYNxioahzJ/eZF9xG3OAtwkMdBufNlTh", + "sM8Si4aaMtZuFDpX1yZ3mQ+DM59BYBuhqOJxFHTj5bN9ohoI8N/m/PgaCprLzSjsGn7d2TG0D6xOnD8AgQqu7LVedQx25UG3", + "k3vl0SHnk9q7LN1JKlxxvIusZBbryZxWTONlp7MwN30TUJi+E0UU1PHCCaD6xGbBgwILbgCLzgL7znA0XvfCpP2dDueh/XEU", + "uzNxGdxou1QEs/WjrGen8H20i921Udkf98X/CLXoemsR1fJ32LN13EuH7wCdauHZOgXmFmaQkC0oizQLXKqP3PcwXAjdOs9D", + "w1L0Qd04rHFmh3OKOBGHHR62OmyfRUgJ+xvKVWkDM/dAxUaGKFWFwnWwBUdvf0fwnTsdJON2YiP1zE5RDb06vOsxzsnmFtDf", + "IC1BFA8OG+pT/HxZopofDhgBexsnEZmH7hliLIXiS/uDPEXbR2d53gHI2vfAAlKrEm7cW8cRNe9pKG9/10vYCy+ebe5U/SNU", + "jjAPmy/7Pt9xkLyWG3Uth4iLOuNJU7odxBpJa+AdbjfRQbUHmC9U7D4hoqG35jClwkyyjdq8FufoKFgxtFLD04cfN2G2lPX+", + "2g+RDUPQVLsYqhT5/IVjjxsHChdeR1bt/r3f+0//effeDion4Eu68z4sgquDyo379ngGYQQfCXPZCUGa3V6DxBCA9aNjfQq6", + "ce15b9MGQXFUuzDf0vH9bd7Pi66XKjfrqGg0f3Rm5gABCtBAwj7G4NESSABWB92E1+wsI7qEc8kJZgDcHmGjecAmN4JoBGXb", + "cziIfR7kJKzltH0c+6hXKzYqlpzZoeIdzAux7Xg0fnE0EDJjaYE46uXBgz3EA0ovfkM8jlXde7zU1BkQmq/4vHXui24xe9Q2", + "uo1ivtDzwQ7BPkZ7qi22HjrFSuHzqfACi44TVhTOr4IgDe3DRackWPTirEBDaF8re3M+/wJBP6/SiY55Fyy5WfbwHlACq7a7", + "A/UGborRhs1He5AuHZqm+o8wve125tMRlkfxWrs/VxvbL2IUB5MGmqZgs8ruwEtfOohjmJ3TW/J0uNcSLi15EuXroIzZar7p", + "1CGNk0fEtCy8srOg7HYf9r3ynEsrik/2vByq8A238Kp5r19ulhRLLYJnwZlYUBZoe7xAWbCr5N/3JrucjGJUHmNpBcpA8L63", + "e8Y5Jxrs8uMbZxppMx8ZFO6oan7tnDGzCfqqE9s1rQvrhl612dFrNsknQGgOhr3ubUA39bqo1PDh2h/0OO5vb24dWwToe3fh", + "ddlO+tP483S3S9nrdm5sblEFWfEBpHlYVKXy8dgm9/A+nN9CRy95QeXBiO8ggLJWH5vxheLHW7HkG77TZDTMjwE2LzqYonDD", + "ys2bgiXmtm8z/QNqA2eDiVpEZsIwj8T7sx7V7oJ12HecRqmwnjebYFl2EPK40t/DoqF9pOJSxSXQVE3Lxveteal2HqI2qfX/", + "BE5BvG/37jhf0i5mSeqmcFaPhv1k4+TUA5g35qP04fTaZm8zUtig/djpYCM+UCLjiywQ+FEa51DpLK+Xm7qhypYLZEuw3nw+", + "FUiqE/2KXYhxpa19e7eOFfP+Aa9WaRxr/IVe+dAEO2sfcTbrIPYv61+4DXRo7dh5LqDW0oK7m/7+vi8seKDPucMK91sLZbY7", + "hRPeeDradgqHkTmJzMyspOB2zUoMbteGGTej5sG6drtxONi88eP+Xz0yuvHO8MEbr1VggAOzG0OkN37SJ0rMzEoP4rt2NzTT", + "GQlv+ogsY4LTDqsHPo4Dj/bHuijXBys1HCQP4zce4IaKHgyrEvsQzk+EbMY3fmLXp72N70/IkKpuGGzduA633NZ6MwBvqOwL", + "nLvcJxA37SHsQI3EPuJRCEaPEPWmf4HIBrhoPV6Ghoxqa50nFBraWzcu0c8wz9SMKUbkm3Lzxk9g+G4zWmIbA9iHuqQr3aKj", + "xoLVcuhFmIMtFKyhMgT3tedh0gJhUF/gnmxo+D1w6d64NOyaa/IQsiiDh8pIjAiASxVRG1gx/KB9Zc9OHICflDLRdmzj5HFf", + "Kmvic/536UmDxvuvJHdsvT0o8Ye1kZzG9lz4g7yoykPAjwfnTCQrzC4k8gS4jgHC7CU6sV+XiEvifp7isL16lYy6pbW6RwXs", + "mu+vIcqC1xmBh10T/gZDRY0KDDjuyN40KyXDW1UwcskPK4cejxkoSoO/4Vlq/sHAe+DGpW0kDBR/Gw1GN36yCgPD3n8ARMnU", + "lLf2Kx1VwnUdw31CAgQNUHUqihes926cQ5Jgm/0jHjv/HuYRMzuIuw4wn0nOAXXkiqWn2BPwi83PG5fMgRkg0sN+Y3kRROGx", + "yuBfiZ3XdiT2E8fD+mmwpf5nHqHG/WnvDlBMuW3XgRokrgewSr1SDz0uWNKu4boiQLYsNU3tUzfOIRDZvXEJZZTOj4F1x4wK", + "OKlvnBsg9b0Kzhtbudh3ze6BvWwOAvpnBZEYMDsBds7ifTsPS40//C70I8XMh+ulyrMHNM4wuxjvBPpQ4+GZnHPmHGyTZ5g0", + "YA+BRhqUUSPGu1n9p0QT0Ck3zoEdmEzZFZfv+tg+v42vWbtsmYLxONh9G3smOxseYn7mxhsl8iOAO3sCSvG2iicBlVE9v9io", + "ZNLWpS1ewKX1HIAcif9ZJb+V57psHqh/SmffvfDB5Q8fBpMtfn544sOnEw+w/cTfzib8zgfP6XOJuRd8vGDTJc/whyf9c9d4", + "TXAL6zpXdR8w3/Lzfj37v96/QKbhN+w6aM1V+wT/xmfJ2Pse+XivWUsedRbid8VpTFbg96w9+nkNd/rwONpsf+H+4j9+R+9/", + "+B22/Qm//1WwAztr8pvOASzW3gvO83uBbX+D9yTvsH0DjMDPgtEXf/GpT4Bx2a6NluP53uY18P3L/J49l7fP2qPPkEMZ7Wc7", + "0D68QgZk3OfbHz7Gfvo2RoOtAH/wm9ZuMSdf5tXe5HOqny7a7094f73D8blqz3bBGZsfIQvyBfsW2Yrtt/f4xBd8XL79wVvk", + "Z/4O+YovYZzIenzJ+++at/oE2aXftc/o++/5817wn5g9x9mjV+1anBd87WnMG84jMUWTs9nae5U8sI+KD/bmGbCzfnSSvLBi", + "jP0JX79ARtRHyX571k77p8Rue/PHYteFBQAuV7LFXv7oYed8bVlo8c2n7N0n7JU3wcFq74tLV5yzr/HbT4Bn9ubL9u5P7Yrn", + "ybir/58jeyyu8ig5ep8AV+vNKzev33zL2szrOgPwI3wH98dVXycD8KP2qdPe/kduvkl2WXAFnwTHrjPRvgZeXbTL3nsVHL1o", + "qf18i8yy4Islm67aj1Zbi8Xi+4a1/KQ/78NgsP3oBLl5T/J6F52V9ydgyLWfrztj7VPsUbDhiuP4J2CSxXfJtotvnkV/2Gdf", + "Jkfxk84g/Brvfc566Br74Yr99abf45J951H1J3h8+e3Xyb37mnhv7W4/CR5esvNeEWcyx/Rh3d+5es/Y+w/fvMLrovfOs28x", + "Lqe9fa/pfbITg8eYPL3k30Wfn5RVaKP1svfv6+Rsfs3H9DE8D/mbz3BkTpJ/+Dx+07h8zv/zS/7fX/b//qr/93O/9Mu/8qu/", + "9uu/8Ru//mu/+iu//Euf+80dM3/n7+78e3//7/+9nX/378zs+M1/8A//0T/+J//0n/3zf/7P/uk/+cf/6B/+g3/xL//Vv/43", + "//bf/ft//+/+7b/51//qX/6L/9f+E/fA779kP3/Z//9L/v9f4Xvxp//2m/7fz7FRv2JN+bXP/frnfiPiWoqyogIlMuSST1Cs", + "eHMTFUATO3zqHqIsJFeC4X7HkTsWjpGDiZAycxRQpol6TygdVKONtjq7GirmRWKpFR7j5sm5W4/gNUCyw044zOZnMOa8TGoO", + "GPGdwqt17LweKy3DpCUgegMPaylsUfcm8ufE2dtDTKhyEgrQ5qNCEJxgnmMu4pdGvMJggx0Nx0z0A/TCDH4nMlFbqNRHmRBA", + "5GqG55CdWc08QFQvMVKY4BPVMQA6wPCLmDYzafJcds4QnY3vI6VB4q3b6wHzRpNvBfAy0m8NMW1woA+4Y9kEkqLpwpFFLLsp", + "yRIzapOjzjRgFgxxVmZMELcASL85tj1GZJ0Na2lBXJ+gLlTs0W7DpKa11kbMmoH0L17BpQSdeqjqxi26pKzro27MnoWYutGG", + "+cx9mzr3eTKtmF+zljWzuxZhv/NxNut1jVfZh1GzGhR95jKKMYWkrg2raUDNB/dzuxKSDe4/gilIPCJ1gMTgRPHEOkXKwTtp", + "swexaeWo62aTXDX4TEWVdTPXDvSqYwzdl1uKvHUDiNIQt43QlLOj2URaW0OsEskthdmXWcGK9wUutl8WItCI8h4mHxxtu7+z", + "EqPMzN1R0PyxbsY+AyjnjdfKurnbJvbk6GCA/F0pj9uBOI0tEBL8zLCaAbe/w2xZ+N4okSOKoXvQ3A8W04AzDhdubnecDwJ/", + "a2NccHnGQ+zhWgbfEUAGFWnFCkaFUPZON29NqvaOBa4Qc9hCuaoyFTMBeWhYZYPB9fxC2RP5LWkDHQfg5RadBQflV907Y1lt", + "oQLqUH80CzkVBpXHfa8ntXuxyTNKU1oz7rPJQuxgxcQr6KvFpFd1R0cHBRgbGhXFjIQVZOW6Ux13lllD3i9RlqM8Z/d2IpZZ", + "FT1Uin7EhCDK5OEzIEhMHlLUFsbTNHfCmVqxGyw5WHI5EuX23WZMhG7Uoy6qINyu88XKZwJcIaZ/zU2yizPvvsnCqyaAUfN1", + "n1gC0p8JA3Qw9mcHL42bQNmQzgXkf1XgnRoWRmA4+wKUo2B2XUSbnDWi3WWp/ArgzUzXTJwSrjdBdSfHNBLEi0IKOERJ6TXR", + "Zdu+Yfs6eVPwBc7ymhkru7J4OEHJgNWGEC25nvCoABRubQxARVltWudtVQEOaohqAoxiV8SbQcnHKyshRz6pzcEqUnEs+uf0", + "OzbSdtGMPSvo0XWk8ZWGbNIZ4PdC+WDd5YyyNqO6YyV4ym3jti1OUUzPUncDXtVE/nymGTfKuHsGo9jTbNVDnFy9yIXPbNag", + "7TBPTVly6zFn10A8GVWzNoFEYWaN94DXA2Rrq0A77jTM2HsFcupi0+eO7aRaZK/VgBEAgQcUOTVS+mCPiaKVMY7+L3mwsCDS", + "npQOHn7tlr11nLQbmwFwaoBJIbmzsOH9irmR8VBgLSyDyL4ojS48jJekEdinzNNsQEUETZPBIPL8XYxKrm4UgRbp7o686F3V", + "yhCshkUkcIvIJO4j5AGbnS1A5rpx+KKCDpZMD5GK/R3NzFUwuZY6gA44YK6QPQR2g2Neanw3OuMP8E9kjQNlU2wSoGBHCeE7", + "JGddW9Nki8jkDg+xk8eDx/G8zVknS2OBbYkixYF1+9GNQeAUPTDUqE6lhpOuVCVzkUJBYgJsY0/riu23BiTAA7LzTtAy61R2", + "QIIgc2EtxDoj5WLCPOETDD9FFq4LUmAaHLtji6z6GCMA4Xs+NxziBozCskinImleOLds1b3Pw8FFnFZLawA3wLI65AjAohj0", + "V3rjodl1Y2aX+YD1lrhAGnKRFfda/7GKplwZyMxwdl+vLwRsvUIXwLwQpbTtWn2QHxDl190mG2WzdcyB/6u+MXbNKN3fMXum", + "4wg7SlSI1LYIcKSrXAyGgRZrPN1XdQ8DvYcnLLtdJqRmY44UHqKvWNpCLiQ3SsEdbc+B7f1wbO/gLrJuoWjWiOxuwerWdWjX", + "sPkSwup4PPAesFBF2xe4tTyd6jVx1loAnhFYskdZqUEeQijIOmy1o2SkBg/HsUUnctyoQH4PBibCRcfDyL5VkeDr2jFR9sXb", + "4FsTcnc1cKBUIUB7VIlsK+IOh/VMfO+lsAIIj8wwE4GlmeiEpBHzJGxWo8IuVOc7inc+ttOlNaLxQJWB1Q1CKNCPNySWIkF+", + "jcJ71AfZEVQEaoaoHBCe8MSCQQ6LrxSwVF1YjPvOAWjr9EESbXQKp6+LZFclehZySm9WZJ4K3NJkBTsnUh1l4dznHB3MSuwA", + "/dHy0sJ9g+FRO2RhMhNdxGGyLc5xtfBOhrOBpIA9D2T2xDmAQc40kpVM6BbRDX7czLtaAjZ8eTdDm1jbHDggKDTK5jKwllG1", + "lKCrF2EnKphXBNMppaxgi5enln3mQHsEECkEeT6HAh6ohzh3bZKxzg11mWKl2K5QcI4OrpysoR6R68UzWzjBRBoL2oset7gu", + "lDiGg6Nkh+LujrIsUUzYfAv8bbM56IEypWqIwbc9jLYoLXHQa7LCkuDzDbOWWS5HvoXKNzRSo29hFybbKPAILCBi1ZYgvKog", + "AwMIk/oYZe4tuE4/zEvhNe1id8a5TAI1THzK+zWaopt0Iu4XuLzskSQd4489cxUWmjmqIB0ewqQRPkLUVoDL/NYfHSQHZGfZ", + "URiHHVxWOMuCbZUVzmv71nxxiBxKyLWp01TwMEIKVlDCeWGgBIoiKLFxUuzeZHc4qLLZaPyPnBjHxn+3YDZrbmQjV4hOWK9G", + "B1lNSq8f47W0oMTiMkugNr3YuRYlpyzqRkwDNB2BBaapxv2+PyLLIdJ7giXV1dGv1W68mf2nJxUfg50ReFqyffyhbXoPjW0v", + "nRWBQ29CmwzutNJ38OuExwR7z7ZtawUY9bY1bb5WP1hvYbbKuiC4RJRqE1kdR1EoYs3HSR95aAeQwT4UV3M5YgKNpwzZkYYo", + "6eyJ3ser3WnXkZq3q5or2GOV8wUuR0r0EO0xPMIR0Z6y2JWblBcobTYs5sKBcRd2HTtsSUzB05w2NvYphOzZMPSKKHIxazGm", + "R8LsUXkDcorYhDF7+rbvrwMx5Al12xy2UAMGTCTZ3EkJ3FPlp5jBQfQf5zpa3AV5n6Yi9o3SSyydVQX07kqCF+L1BJ2GfZqb", + "flk4B3gP+1hDuiSGZgZrX/ZJWzj1ka1l+ne1dJw2cXCYmdvjOid8paFZ4moo5MMgpz2FA2wufSOwmCqlJkvfuu7lkk5I3DIh", + "af7g5roANeSaA2UX7G9wT1bSn+HXI0mOk3xUbm5BYIN7Lwbli0PS8q6X9JJQ2Cz1DRCSdIsSVYMYsUGfFLgYOHzra/DRvAKc", + "tqjwyEc2aJ8PQykKCCQUJgMq7xDaRjxs9q2DYfvFc3WdtLrCWqxI2b8UyEZHtu2ccTduFQg5HSUBSlguWahvvxdFSDw4zhQ4", + "kDXaSLsDwu6Ui6CSmogFhdw7A+s6mqY4NMU5jJ1R1eZgARiy1LH5angK7gHZPr/OCrRRRR4ALFFUKOqQxKaOiztX+lwAQDrL", + "fi9CxxXWq0T6aEuYghbcE4A2ECcjvEqzcpEHhg17cAMUYDVYO1Q5YDOVCD9wtDU1FjOS9nr2mYApKIZGAgkP05FApjQDg3Em", + "RiFIMbENBxy86XZBsDA+CDUDrGkUh4TggFm5oDcDyL0M6MyS2RE9cDyohZvg0UMA1zaZmRmnLnYuvdFAZTkIXnndRLMcFURh", + "CTu0W1JR4y2OBVJ/GCYq2sLuLh2412PJr287YMI66hpbNHedpeqgjezKSoUu8H0jqkSao4iKmF3Yj0hFlNLuI5feCuIboka3", + "bziBfbEXBhWCgstuafUm4rDFnMTOj2M7ANxFVLSxyphNjbhLIa4qcNlUtq+gV5sIDdmeNTywLoC0wj5ikN/aMEstaklszq4D", + "ZRRFGHNrZrsxxESDAdZH4JSWQELFbRBrhxp2IiyAxUiD4cEKxQBmRCOiCLsFG35Ee+bEc2QPeJgSXzoHETQ3m4SVXLCA4xAP", + "8LRZMhqB5ZEzOKEMWgsiALhN+ETdI2GvglSPW2UMyn6xWQBSjKMfRo5TpoJtpSHUP1Ua2C08ShQx6kkC5a5yywSJoYeIrKO6", + "fda3Y+DInlVEqV8M9xdYY4/rlEWrQqY4m3vHg6FopICOAbmhTfAi0g1gMyFEa0Z23ai7LHujIPU1UbIzZlusunUB5lPUlUcQ", + "bASSO8gsyBjAwRZndoCklpacuWFZ9dnWhsDp9ANovRynzR4SXHB79xq9OQa+UcHMQ5xejRnkpMuVehd2LS+onGM8WjSNgk4X", + "EYPd57TXvclBHp92UuCCot9FdTv6CNOPRy3eovktiKAY2MWMAR6eJg03wu3h0UOzRG6Ik01vVPfaUhlvkiwYVFe2ymcjLrYJ", + "4YJmMCq3ogyzLHzE7kByAFcUfTRPT5ekkGCLNRGsyt/EccRidBlUdjNsT52C5obZJLDy0BuOZ61TRVHj5A+rg4h5FlEcVJIb", + "QaVGYAKySVmyGp66EQ65dE7TesTFCmxcEeD7WBeF2Ghshgge77hGmruMhWPf5QRAC3dGgH2/E2XOdyvZ1VWgzgsFE7BL2HWo", + "hbO04BUn3qma4SAmqViDhzbY0tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN", + "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu", + "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn", + "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f", + "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf", + "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx", + "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C", + "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ", + "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz", + "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk", + "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi", + "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUuAo0kX/vaVE9QvP83PnOfvp/j7T/n1CxRHv8oXT0WTLoZsue7+WNziQqiG", + "X4m3rCXP85WLvJ2a9FzcSyLlZ6mnftybil9+yKd4mndUj10MhfLnKXD+ZOiUv8r/nZLOOq+gTrgSeucn+d3v86bn4i7fD7l3", + "9eSFTK9dA/dkiMRz4LyfraMedplzvPWi9zYe8NsUYn8uOuFk3Ov7Idx+ir2R1NZfjI46wQ+rPd+Nm56PHlPL34tBtz+fCpX6", + "H8a9vhtdpAtKEv59vqjevsi+0nw4GwOtx9FcfS969Tg74Sybd5qt1dcfj4Y9htddV17zWXNVo/MkW3suZOwvxFO84FPF+/m8", + "PxfePcN/X4gHfCXudZztvxaq9mrkj+JPffhhPrJW0Cm+mGbLqWjeq2yzfj/jDUabn+YjXIn2vBpT6/W4qZr6OgeXN/I2H3f+", + "Dgh8QT6GxS6RXd85czBwLMUD5XapksUEYKEym9gslrYCm8PEGiXXYANJu2GpjHfFKIktzHVpvrBnL658WFcOEFADtoju6nC8", + "uQJr0jZks66B9HkIu1NPjiquchCSLlDILJ1voyYS2kM/9ymkVfMI6MtW9mi2/dZP7yo+WmZPvrQZdRadIiWxQzFR3ygFKnGV", + "CTMTxyCaL2776oHdw1Qtn1BIDYIOimSzLXSUv1aSg3g0aINv80UyEmtWEOAbCCqsDJHRUH6XPJrytuvEvLu/8/nA3JPnzQ05", + "NxXwvNXRRrLIzhmCvkLitha2RupU9daRNIL3Q8y6dATYVsmI9bgXYzlPx/jLa7MduMo9Ykk8fc1+9iRsIwU++IVfSVnFrydM", + "GNP/5jINuv2Bl8QuMYLNq6A4Ti4pSaG26M2CdtPusr+zlAU46VxQerJu5ml6e0rMrnJw0Hefju4V/N8RBm03LfyUGIemxVjl", + "nJEy0RPZOWNNBWOGqq5n4xyeI29m6atnGAriAI7g7dvTCnCFSaRw+hyAuqlmKdQC+uqUgeoEy0qncBSDnd/JpF9IaJWZ0B5n", + "y8zOA7Z969iiu5pb5jKiwmNjEond1ci7i84OYBrWyHtCsLuVoB8gChPTa4QTK8YJVmBsTDYmWwOKxDbzykbP7lokSxdD2ESN", + "uHowODrxvHexh9ingUHrkNByy1lgnB8D9QZj1eZFdBd9imzJSLlQkSl2603PJ9o8OCggVdQwIt0DJ44m0urqeEvDOoDDtsZy", + "LtRIUtp+OHCUmdeD12JIQJEDuEVil1p3YE692kmVTFSRo6xVyrEvdKsY/dU017bGYEbBVaoeuR9URezjQTVbAQa2wo/nRsI5", + "yapUtiC5it2NvbHywCguVInDD1bF1slp0CBuu8Jc8BfTPjkzcwe91GKU8oTwOGr5f0jHsD5p5LGcEep2N30NMhLB51hKGQGF", + "lRAzug8CPlREW6kmA415cCVVXa8KtL8cSSTGEl8LYgSo+p2EDtg5E7woi4VjdFjTSdliVJ2S2xVE+gn8FHEtcC0xg8+WOhZt", + "50yRIB+BxygKRdD4bCvOu0tWOoWLSPrJ/gvOgqp/P6vnxyhrQsaUiXpgJcyPQT3oZrBHERfCDGjZY2AHlZzHigbFuMXnGQ5h", + "PMNZG8B+2S8cVuSoxIcwEwF4RGAC1ccUtmwiygZGB2Td8HiMeRJQuvGFmBu2WzhOdTYFtckqinmEE4zy8eAh6jh3etfTzMMJ", + "kW5bwgjFTr3Wrt9jiZtDcIi1cS9wVMMG9WhgGhtvEl7C3Crap/hEf2CHoh2yo0Xn/0BgV4xfNQvjhBtyFXBMj3E/ohMB6Fud", + "pNAcSMSRTMEg2f5MNeUh1q8ME5/jZOforSooTW5GrvOezU5PZGMsSXe/J2GLA/Bke06vN1b2cA2MxwzvcvZx679fu5l9eW/6", + "7laDeDROTiKzmENRuSieyGY2XkDmeUAtANvAQONacc0kwHETeYbeZDmBCAdkSwazMYJvQ/ZuvUnMLMS91woJEcyVEo+we9yT", + "LIWv9gOHiTioko0zCfpcK/ho7x4cRGKUYABKPdwv4VNi7kgLhCxnoBGKwxGFnxPLA+thBcuxq+xMN4HdIwDnSFSs1j7ML6BT", + "bB9S9t6BZLqy+HfBx/M/pWx4QJdXQTnp7q6CvrBpYnUvLSS75LbajKk9i0VdLAUcd5XIJoFfEvi3UTQY6y3YjnqT0UA8vURl", + "owZshHDzbif//dZM7Fhefw5bRRXVD5FDqNJ+ABA7H23Z1wzxHAMPSd5blX1W3c7FWqiEQWANOgLOEs4QJgOhxCPJigSUUTjX", + "lbJ5sCKXGwGPpPX2WCjjkoXHYJdSKlOQA8w1asTRvkKgYaMSw5GnvBtFb7G5Ouue7RFKbDUkBaUEMNhhUy4pnfHNl7Tz88R2", + "/FpYHmQ3wkZDzA96kSQ0O9o5iYAS+3Q5OSAJ898wbMskSWR4quaOtIclMH2jPOWYujEqH0WfFJ5dIBUjqaYTlngHAwpEwbh5", + "ir2zCp3SFsnkXN8cHVYpYnknWLfS+MjkJLRz4WgY6+h7xsfMdrPOWQ+mkRJRnEITS5klZNw6MoY7uxYdSHG0FBqNSu4soTDz", + "a39HsIk7ETV2hh6bX75z9iYOQYPXMdjyU3ec9oNUWdH/cna6xB474zBVJIRpJ5Lrl8hem+QwabSOHDJvG7nkqtH5B9IMWwPo", + "gnvnTEqOOiKEIX/UgxKU+Luxi+qka4gq6rmHJpgT/TemtLGPz8Z8mU2o4EZCENgVUh6mWSInLUxoHUHIk5A9hVhueTakcmQW", + "BO9LqYmnn98CpxWBZbRuth107vp/2L1Jf4z7eknKQ7D11pxkgOTLtBSxs9rVbXfn/EPgstoKkFBBNhmSwQKyrisnnOsXgnli", + "sNYcdcDVvHtP1v19Jg1gbxwdIpvbL1YmCUzTJFjoXuw73WF5tOyt9QblaB/IfGtI2hD3kvDnLay/kZI2TqQ7knW9Ag0xWqpb", + "yUeELSCQAe2rPgvKnUUSMEsviCgEGsMqww4nUB880hI5lNJ51XqYa16Y0pCN0qY9QcM67bv3J1+8V8fMOSzPAexdesHMDuzy", + "NJiahE2kfp9EGO5BFbMiBEjGCyogIUamy4mQF0RDeK3ugbRqU4Z38x6BOQfDSYK7fiEVrUB92O0ceJoVR1B9D1m+sMtxN3Bs", + "oCcJS1wxVxGImp6Uhg4n+96Z/KxjQG3mp66zY3SQ8C2UJwABsyelhWaqBKElfGjOddI4Ex3cMbNFtUqgOWTDIfOc8uE214JD", + "LhmWRVtcVRYIpg9ZpOFw8A7gQhDA0gro0/K1HdgZOVL2shDSHriQVMBQSCmVx4FYLcyCJ7qpLNaqo+DPF8ZJ8wf9JxQy0CwJ", + "GbF8AKr0lGYr0pTQHkFCeOfErMhwXJOvI0UhZhTzR55e6H/c404qJhfV+noCfoPZAOlY20HuTzGZg8kKCghxZzldeedCCymQ", + "EpPNiN0PNE33wdt27Vp01RX6Bi27LdYnfHZ/BfcIYEqTMMhFSYg++HQSttIsc8TvMKfuT7EgO09cpPP+FCsQkyBjChUlvK0F", + "LrFAsMpR6iRuVAlYnPDsBGOD9GfPnj0gRRsU66iySh6kYwZgj5NsxWe7AFbdxp5gNwCJa4P+g9WEe8hi6K7uu7sK+1SFIpQA", + "jmKUQpqw9IOGqy5qHpbWdpVAHUXCbBXOTwnLSEyPiJ9IFRQeKTOr2CSA7hNoKRh2duxg3yMqEvaVTVTnvwP6mDYQ8joQmBAN", + "XndcudKdJJsxqrDIxOVnthQonhwmJjkul5ez145EkdIc0lmyn7/ibJ1lX4gBFH/cmayCB20o5eeldRmVf4yMVfrGEJ7rOvD8", + "TVuRCV+oNr91SGbKrRoFNOJApWJYv+uovhJt7tJyC+ywrwBcfDX5EKjdQRzJrE336GGNbJGLUj4sPZ8yrP/tSsLO5KRxjt3e", + "RJ4SQj2ek7P2sSdX0QL6phwjWpFmd1YjWz1jrTMeizqYk/s5m8qpDmZ+aOEoB84wblUQaRjRbbPRcsqmgF1gCvry/f0Ee51x", + "XWIbVZyNiiwGN1BRdoooM7inrqwvwNgzk5B3AowTjaBhJhSjC/FcASErPSV3ecmJDdfHlWNJbAnQgg+gyG2Nc+7S0xxuyv9V", + "JcV4C4xMQOCuqwz3AaHUEgqdPNjyU+YTiux2ISI4+tYrFBZPVZUUJGVdZtW0529UpM2vSsQZ0M1+IV0wGfS7j/qclD1wmCB+", + "PLnbQzVMEZ+d+6gbCgGHgauhYL3eVx0t/lfA4sowS5o6VX1207k6jrrRwObY1gEgIg/YMiLg2xXRfyDxVh0uWd8OCgBljx9V", + "rbBFyu7kMOEnji2mjFKsjyZwJIQbqqQDJotOq2Qp0O4cwUdEZYNwXHNFsDGp1gLnfoLKYh9x0knn8Mb4AhvC430hRSHWq4i3", + "M0EjH6zqydKpUgFwgQoy7XCgc0xkZWYD7zeDjMBVDhcU42pK2oH7RSBx2AcAHYBvkWsVKx5I4aSVJ39Ge854CH8+GEMHrt4i", + "RKV2i6NRbVKkouq5yNRwpx5rPyC8jthv3EOyX6lCu0kgteIO7btAGAtUuHfPHkKneXOXMAtMDBmKXTEbG/Kg8FunqgZCb+6C", + "zbXhmGFoFTqTemcZqlsyYSKKU/bcj+qON11IDou+iJ0NcHet/iLBm1ON7TwSErtZ90JrrlfaoeX4InvsbiqR70lKryhHYofG", + "ZUrKVxGEhU14ILEBFTsKHy8Usx+CxUDgTJ5MCZmaPPDtStg52JgNdlvSwWuUIbLpUsgFbCqopmAOgItTKjzwZ4a1WIcHW46C", + "FBJZa58TtewLSI1zhrkYBgCTdSPhRErYKS5FVuIJ8bFMDMGgwDqg+DhlSlUwhXdXhgFd9zgrXAzWf3AXXfU4HIV7Gl3F56QY", + "XwU2w2yHug3Y8DHTuuAOkNCz1vmqcLN7ir3VJv6/eHuKySykAAdOEjhLdCA9I7GQWAUgNiO7cJRiBbZzjmxrGa5vJBt9Z/DG", + "zq6JXxOCjq43ywgfbZWdM4V5CaWiTStC4sMIAUe6lwRJ3YAxRmIkC4d5YYwOxt4+1xacoAQbrSPzN02dcZMoCArHrdovy+lU", + "S/XpSx40g/Qd4iiErs1L+q+zsACmc8+RkugOMMdge7ezFj7YaulVj0LQd4sAGvZT9kH8tmA+/Jsf/80f/83pv/mzvznz0cNk", + "ebv0fz4NAqUh3Er4+5UUNrnTEJ7TwFNzRBNZzWy68uzhu+OV2j8n26t2NjQiaVpkUJN21kraF3gtobpQxUn3F3PfgVnINzpL", + "GaNbvEdAeOsBVVd4t6g1qwfkO1BbBisOvkpl11UCbzWMQOILjfLx2KHDfkmaHWTTUsaYWXOzDXAeiXlfT6lYUA0tr549j726", + "Ap5CuN6l0F+CW0l7w9oceLQmeOhQ9uOgpcYr/6qHyiBVqKJfAL+y5t+4BNGFRC4BvRdrptk6DykWWTPt7rAxzzZTPCVtvGtI", + "V4iBDTUS4lgLWoWKIql0WchXdIVMRG+IXerDE/4afrsIDqYP3vnwWbIoXeerj5MTCbxTb9jPt+39yx+8Rz6mxEtFVqTr/Ake", + "q/fJM/V2YpO61PJRicmJd3kruJM+PJHeBQfWVXIrXSVr0xVyYLGl+NwHLzp31XX7zJvOlOQMUeK2+vBZewd8WI/oKROP1DVn", + "nMJvaN9x9sE7/FecXuKeupYYsk4mDqgL3hvgy3pHjF/4BFuIb3mbrS3B8oS7PWI9B4ap9/1537Qnv8DvXo3fnN9JfFn4Hlip", + "2vui9e+x19VmMYqRQYx3fpx98Tb/5nfttUfwCpmoNCJvk/tLHFJvpue47KMWo/U4+a9ejHHzz13NrnwtnpqcW3wXbF7ip7L7", + "vUSOquvOOAYurHc++GG6x3WO6CVv73voU2e0wni866MfrGRXxT+GsbQ+xbixD1L/vcf7XiZ/2A/Jn4U+ORX3BZ8Z2uIjJU6y", + "92PmWAvBEvasXU1j+eyHjzl72An75gle400yrF0gs9jJdL0LH/xF6g22hU8SM+KCPTl4zZ7mGF3AtXyUj/Np43OaZ9f5u7N6", + "2Zi/o1krdjP2+1X99uF3fG68w3l0iXMXHGRsH9nKnkmsZRjbd/E0ad6/w3Zr7n7X2nTSrnoRLFo3z9x8/aMnb76Ck8JZwfRT", + "HGLXwAoldinxfpGF6+TNs2TWeuqjJ8C0ZZ8TH1awjMV3r9irr5Cv6mG99tGJm5f8G9ecj+scmMvIIPUoT6wz+M3+PWGtAlvX", + "6+QPwzfeJPcUmLXIZmXvvmX3f8p+c5Ywu7I9B65i93kLrFrkKCOX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", + "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", + "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", + "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", + "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", + "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", + "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", + "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", + "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", + "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", + "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", + "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhiIIy3cDltOspFhlAWV5X2R3tGsoeKts", + "Zc23ACABTYXQTDjAxlOQTHk7Kowd1Z8UigN1U5ypkPCSYo8DwgOQcrmXMhEF8kZLLcC13XfsOpTJxiWiQoYbSBFkbijn6AuN", + "yEiSAlXhzEExzuNqqMRDUl6+dOIb7E2oLWgTrT+a7G6TfSBf94GVTCtnB3rfNpYeamMHgBP0MRMJpqwZGxAakSCnr9hkqRHX", + "sG27SDgnh4RhekpLwhP4hBD4GHcrFW8SktIMV/d3FpZaeKOnOIKkxWeqe6rIrC8tpARfyCdif6jJRqW6ZRYHkg4OB9Wq5w48", + "X1AVEqlmMHBeB9p9qAVeH9bSv6sOtPtOUrAETJmxb1Y/KqrHQFuqmy1mWwg2+teT7k6ys3fPnt9GDMU5L5ZayAPLPDHK+zu7", + "5hORUFrzg/6X+5GhKkKwD7kJZyVCAHoo/I7KDbPEgiJn5HrqlcNbwBTNofYYD1g65688dspyFtzZifJJGe9249rbRv8LSeXw", + "CrsWbZFqsidCEGgcgvkN0u59B5AiYgSkc1/bZ0KFd5ZbnD6Dry7fhC84vuG3UrxlcevYYuFnZ8jgIdLouRTGczedH6Lb5gUK", + "B9Apm98MPGS9tPE/x7B0SVexqj5zGoGVSVt90NaDYgsqIvl/VASDisdtAZKGCFu5+t/GtR+siocxuEvForFQi8Kf2K/foLQG", + "sGT74gAogEZCJBqImKqt1ehyUwCiB6iWLrY18t4kIH7UnHECJeT6fOLE600OZZv5qAjORy+cmzB2yop8QA1dloxPD6xjSRC6", + "xOwc0a1QDKGjw8idYb3ZXzhBMFie3OW2qVgjQuPOaFOScoe2T4h5IBaaUJEFhF4UnG5CLVQMGd4l0oQDNR/ZOFL2rBLgmXyd", + "ZYp7RoLeDCKb0mD0G0AdSmqjAgitubYQo9gabtbhCl2hzZ+qFdbUwOs0A96UTVfKACXHodIJxhyicllCH5o/hOxQLJ39IAZS", + "dPWhw18OnSSS3wyGAMm16axC7CJkE3HBLpKU2keDQI0Vy5yW+xLV4SwmHLvEbGVHjcdOIAqhhQeaENqwi0VBNNnCKmGW2rgw", + "qB3dGGmPuhmPTWNy7ZwJEZolhwUf0bm5VWvfAWzLE3Mhmwn6mEAoUCzOGTxoEPUFPxRZoXKgRHMJdDUomnLCQbizNcrKIgGR", + "giMVR12ChzbOxUFen2SyNqEaZ1e4W0JfWE2RjWdqTJSgdW8iRhTBXYNupzcJXTCkSeEPlMRVrvn+jvnr8D372oZKHQQ2C0hY", + "E8qttt5CvMcGlstfRlmzgaWjEvdSVKUgAWKSjC+HphiWNEGKzEp1WpgxMQXYQJt9pNDT12yui/pvo2rR24XT4yL/MOCJz3wv", + "OQ6i6VR8FRuuQKvI7jqlmjVvQ9YkODbsKD/kgnSdsO+sVf2U423BkpwwXmwxM5PZk4kytT17llS7cOc2IWuS6rK7dgok0Cs7", + "vr4OmcdaT0FZNofzSfQJi4aZ15rvHGxPp6iNsadQoorT895xMiJxSCFVYX+2h+UXsKP7B9x6xV+b9bEg8lipRkcrkWeE0Bum", + "RiKa7iWXdhtGTIBAI0FAtK2fWdvVwh1H7ij+C1gBnKyVkB4um/7qRKg7cgXa1xwihvXbbe31NqFfhBNkDZ1PbAMFiSdkShxo", + "jSfsUa7/ExArniJkpQaWjPum+CnmWtcnSl2snfdPRQS8OK8JNtDayTJ043JlBWeD0tLrERFoUo6oaL3xItRQw04VPpP5eZmL", + "Afbm8RVn8N4Q8bav3d1uushWueyqNnpOFMgEk7do6JYCNzEOgKBqLcY8Azo3WpDk5YCZRKjbStXW59ldv3jvEWnAHWitbRjQ", + "bq3cmUIGc/QAaVAm3V/cC9NwhRlhzRIUjm2QrGWDtlhUY7nzWgm1eC/NWwEiATvxjkqomb6I/WgOt8hKwg09Q2+rkVgLO4IO", + "tfZkoAlJwwN9xC52OWxhnvBLfvd2VsvXFG1dKfc+na6aUcypJsob2vckuqjy+iMyyhTy0fhADiHaUBachG5I7daU1dpIaIqV", + "SRrjKDjDCjfHfrQbRKhJQs6MC7d0sQiUvq5REzhorXiccwAJlF2FQ+yWYiMmeQBqToQuwJRrDc65pYV0slbyz+lWpx3mdw+1", + "/kVbIdrQB9jNPN18kSIjIdFFKtdktamUicdXaGqDQQqAZBlwWaWj7T9Rh8NbaOm5FCbGOxGjo5TYSfasEV4PB/ldMNwJSx8k", + "zzKmbfUSB0DRtiidhGETqCdFOIqSGEP739ZWnZj5e9BUDQXnFda8smUkFOLMOKp6AnbAZmXmp1SLj0RNiDkECTrfHGldowDR", + "kaHHK1KREk6zpK3vbKL4CDnvMnmLdiJiYpHIRxrKkExtIaG/n7BxdT/x7lddx0HCUdFPzp1U9UcYG7kt7Lr3ModMGyXohDMs", + "GIz0xjkYbdK25YzBOshyuFR0GuV1D8HmknY29nXnxSSesVs40oigNa0T0Nw1gobIOeG43U+GCupukzvK6zJHye7jksYyACK7", + "oIkG3kEW6bF1ZIEU8WYQpZrNdShVBM21EMRmRDojOm42U8MISXG5speCmmUv5YjNjSJ3kk1nTiOUoj+oOUmHzUYyqU0UZXFs", + "s9dv9g3W95vdksrcUy38sdHBVGvoJOLsNqAUQdMIwCfLqQhKblHcMyHCgT3VmuM+CruTFLRloDrIf7tZ+TaoqBpPnLZID8Rc", + "sGCw0zOGp/6l2dzw4MKB4zCkNlSx2Jbyz8lRJ4bH2vBgVW1pjKPSucEGWFADvdFMhiZI56A78TZeoZNpo8mAK0GYi47BxZIS", + "8oxRMQ+nQS7TGgTyQEyNUJSlKcGJyBpr7wey+gM+Qo7bUCH/bx3qHKjIblAWQmsQaCR2rmIB6C1BHnqTO9ucxM62/MWH0KbD", + "3HJrcO5paypwW6dBdOg+xigqGdzRdfqc0B+fAjoCQQsmeQcQeilHs69vJ8YiKQKX6IAWoDEnratAorL7sLYG8AQws8xDE4yL", + "BgUPd8HGvGQcEyZEE9AlhGoOqDif6tKKQxHfH7HG1AtUE3ctqgy0VdjOrWdjLL1e09mKYLttCmuqKCpt4o8UsNo5s0Nu984Z", + "9K+fZGsC1edqudheuS5o8HmNDtf8oEi2t0IR7LOj8n5xSAwTEJI+jRITQ2rjem6mCK5AcjM28oPIYkiWwLYio1htz6ygzcNC", + "Cfd5VxanKUjQOOg7Csu93yVqK6iCo2XQ2BfQUPAQBPObncFQOqxXhvV4kxXyOupqZ0i1JQ1WUd9T2wJYxh+Am4M+97AK9CkN", + "SD1rSGJjEwMRoG+vcOIVcQnGjLrlPaW+yXryh8xZpqoyJq1iWHZtH/Xd3XKSWP1ROKkDEui7sXTgweXRpszkk2kdN94YIMKB", + "IRdcO3Hju1YE2d25BUn9Q14Axo/AW8faD/r3YgV8GScRYGSqwAxdV+s+8EQhb2J+gSYtFY7Ds9QJGSeZTl7GB8oi8Wajf70N", + "iWe0HnlxAfnPyZtHUwhT3adBoB8ZxiL1Rrt42bKkuKPDx1GLAei2z97fes3S7PDVkrDuR8EWus7q+JWJusZh+w4/dWYuRxFv", + "oRDJHj7q/V29Y6TiG96KZOC9Nqo2z6WnwkGnnIYxEr5YoWIV+KaE+XH9fHX+cHAkTKExQQ7ci0zbWksIgO/4OZ5kOAC3LzZA", + "YEpEKVXbu+Te9KgMM406BAdrwrS6oeWxldFgr3XBnbapAq0pFxXGaWI/Q1bZa0AL7WCad2RPVXrHLw+fLxSESRJbBem7G4Xc", + "jbrdu8QyVsVuv1FvcV16LNMDgsqkht0r3DEpDJX6tt/shKR+NmcJu5RbVJEwuxvaaVV8GBsTRrMXEaDERYNJ626CnV3oVPiv", + "ELNIhXGlR384Qg4HVexVEeS6H1zVo+5y3y2nWtTTJC8GjWJi8aEHyOxLyjStjPoQJfeOCgQ1NokNGVRMgyk9zIi3rDds0KDl", + "bWeJh8jusV3QX01llDiEGyxLkNLe2YZOQokci6EN9bQMM3OufTD0heMWFgk0lSpKsXjls3jk1H3gMB/UlgULz4WLk8zObdA3", + "LRA8ZvXCGs5gFG248DXGonXwwP3T936QrSIXrcXHt5xBZA/1Eg5EDX1yLccJu2OH112pfKuIWjIPhJHM1bwd8fHZ3R6I3Six", + "ZfYnLZfDXAixjKE7sxURARQ3uWYIGGZ9CNysa6aqIEBs86CHFFGvjxB8r17WoiqgNU5jhPprXcnjfg0GliOyWTzdRgRSGBcn", + "juhUyRzcxA6ONeHjBjs8ppyOWo68bB3OXY9XYbIqbCIqYAEwpEexSgN6KJkwVaQtt24SrX/92jJWzYWyTYFJW4b00ah1Mpng", + "SMWmYZ+yxqU6iO0/hWxtWKrkQx5uLf6W32nOqzSEiw6up8ZJ2Onlk4Cf+5kK8PkOTXcvXlHxGSZoVH2gz1wEysyDBBPB6e/a", + "GGBwwPzmiuUiO8b4Vnr4mkaO2yVYTm6tiJ6G642V06IpcCMfpNVtny6wUIM0kRP3UHGuiTuXWS/hIBLlrafV4Yf7EzvRPSxi", + "8Uy4aRlkZvNcsWRA6LsciptfkYugQSLjVEsSrMBwdPveffwAocm9RD2LSi7Fz2yWwzD2EfKngOmzeWsqOe1yX1NzjrQRLakz", + "0Hg63Pr+wXHzheKbjEcVDMCECcRkyFYEKEQzw20w6kLoGqWCi1AFkn0GyZGeYsVwX0hCoeqfPinwuWDMgCQnuz9Jf1BEYs4Z", + "WRolOBREtVOEuyWU7SuWPWyidn/BzTo47e4wwYFVOKSRoklwmszRkJVLw88qSMFp1Jf6W7QX6iNpt1ftFKc9gFGx9IrE373Z", + "hvB9B4fv39LMzZGeHnk2M7fStj3vPBBNHnGp+zsyiNCordpxsm4shiY5TCnhhdhNSh26Ep+o07cjZ+mrkF2icwW/7siIwiCr", + "wCLdrtsaEguidUF9C+6TiMk2WC0enWZloHYk2IgD7RwesURZY3tYzh/0Cg1zj/wWUsUpe04PwvCNIi64m23VCPiUrbyWQvNS", + "iivHfboE3Fa2fd9xYA3WZKpMkmfpNlfKlhwdOOMGEyfyVmHhtat7jj3qNBp9Gnsuz+B79bwX8mJOJJjj6iTRytv2NihA16M0", + "GNO9yg+loBnXRc+XU+IhUR4dcZYB6MkPiZwmcmob4KQtYpdnfLkCp12jfYfJYqcd5L6+ns7NI23ynI1UnNSLcilPmkz3OTfH", + "vyYhpImXQzc9m6r9v3oGRPSpKqYJorhuqe5TiUdL2tvyRCLlssoA0Y1zpeavl8n0o5qlJOxCgunqB2iHt/UnTRTcoI6QIgo8", + "FgEGKTdrEpJVdnWhQ0JBindz0z1IGXmLtgInFeNYI+GxIp7dLbtuWuITq2DO1S0Sca/tNmOXl2/gjoKnl/S9qTamEd3Pqtec", + "jLt1qUIewgXgGor7kR+wVd41W+iBEtzrUVfUDDxXyv71ZCpoUphqXrNnQ5XbUM1B5NisITxx8EeyJ+FncQDo3WqEBLgFJw9L", + "kRxzo8gWf+3bFrCexoKkNnYTkIsF/TejGaJ92Ncp9iWGsAzh2yBcHPpYIbWAHWVhIRE1zXxZmrDCEgXe0X4Hb52nKvYl4U5z", + "jboV2NV3M5zGHTO4zDKAafSglHNbfMFCFm504kwUIM4WGT4oa/9CC8BarRYWjh49Or8+GKz3XGHnoZAVHoS1nGWxFXseel0k", + "HT5FGZXZrNTVwiEBbLtv7++ZfSlxxQmI86JBGdCvzV4S59hm81zxR1hUkFN42/b+5+yaoVFiJ2KW/+5+YU/7md0ZporHM7Je", + "KzZeyy0IBlI7a95BtyX6jtt23TVmMg2ewhxxEdsekkr53/2IogyGfgJ1QfTtPpjQFaGXqrphDrcdWF5d31DWqoDoCWrv24D1", + "/VW/30x629YB5YHWLJ5bwig7Jx+QwwsOHQZLStD8Ay1iS6dnP8sWINObZIi0GYcfCWid0J5lz9yIA0H2leGYmhQIr8WJFUm8", + "/Vkk0CWtpVM83x11oaRjDW4ZJMvewUE78LfNZTCcUCMFai2l0WHWtY3IQJFNFnXcWxYtq8xSW7LaudMOr1XKXdel0B0CWmZo", + "u678LYH0Ez+oPeMd9hlvdJP121ISU7MxTTLfOHRgiK4p2tJyhiGq0hotcSrPfvXwLvjR/S79m1kHGymfOF9kDkagBVarToYy", + "EpadaYLFg4wdHqWnAZBsRPeSdU6Xxn0TiK1l3lKV9c9ilup/YGxmcFAijtwQs/mRp3cOgTdAhsVchs7/HeeVdPw4edQV5GmK", + "JKU97LTcvAmE7kh4lAJgPvurqpZPdbzWn9gfPOnQshcDK7kJPeyQO9/c8n2VRRP7O/ZVMz6jypZ2v6OdGJGQ4NFwXC0eZrX2", + "wsKd91mPY1xcbEU8UkqqIUwce0WGHi0Sy5vNn4NZGxJ3CbjtfuuPIC239l93717+Vhv/n0muB5XcE2hwziWl5Cl7LbnSzkzN", + "cnBkWyoqOBv0CUqzwocmkHbcb5lBKfUaoibBuWh9kp0jRZIyL5id7ce4Z07+QmAlxHaLoKzziYmeSohDnBeutrOUZZm/OKaF", + "K7d0m4DRHkK7HsCN1INcSVtuczPzfeRD6Zu0gH1yBTq6dCbHdiq0ZJvD1rEiS1HsTerk9rxZvcveTQDg0pi25yNhM+6LrzMc", + "qLizeQE4CyStG3U+1v4vJSbvTtHHMqaD0jQtzHC1uj1U1O3zy1k0MTumZrJhLBILWJJo0e6CzSzQ/dlaMEentxb7c2YMF3Er", + "QnGDLy7LfUyU2ImiBfMtR3CBeoS9wlEXS6/tRcc2e/t0BrWsGmC1RfpSki2JPJWOVJUGLAfPJtFte8Iv2fHWuAN+f7bPo/4j", + "yC0Qw9rNm+wbZkfHLneFuL7g0tp2izmMrGaiaIHcH0TJCRNoisSBI34eet8LWeShoIryRt21SbBoQ2rXXyEOV3udmLCSfjfG", + "BQF8d0jx/VD23ZFVR7mabSkmcgGRqNQJcIOixA2F7OukOio1H1sn9w2gDs6pNJdVejUzO1qf1/byFOqpWugcqRiD5HfWXN6C", + "Goa75jtFy1eyle0z+Hw8Msfd8+I72nTOzEzm2COQ1gsOuRYoWdztWY274PW2Z0STwey1r6atGINxG4Z5QXDOYJwtUiiZ09RD", + "Hd9oYVD7soBikYW2i6TcKrRVb+DFIaGPXOXxWXv9QNGCWzNocJGhFbpCban9y3lJizJ1jK+utDl5IsuF76li3JlfjSAzQzbd", + "btVGMdoKtbasp+wdhsTMqPgqxFLsycP66HpYmnfvU7ZVuRBy+ESSuw1rFll5YHOoT63MOeZs29uW9Wbr74BShNOf8JkUHAKt", + "9CD8ha0sF8VNrnf7eAXfyQ7ILMhXyOPnUuoO26iuqGus+T0SpBSJ1u1QZgvRiPN9L3On2klbQMg3jddwY2x/SfqYvlucX/55", + "4rwY7BlqAmVx3yIYzciYxOsQptKwn73N5bBKCUD8HoDzZpNymzovCpUrAQJPIUtHvgJ9FzBlG9CEL3f4AWEQXCNe/UngfyX2", + "j8OkqsTOX/ZbT2bnTEDzHNaS1Ktxwfs8E5QW7xa2V7gW2odbxjqIGJYg/B83nuYLvBQ4F+PMZa7WnzcyRggV6azRv23cr1OI", + "F2mL66g/KFLebVhFiWhvEvse5upyhphnMs1zcvxi6DBmNljkMJRFS0BAduYhbJu1AMTUZVCIDm9RG9LTVnzhYOZ3ZEkFrzXU", + "asZtuKeTj9mNQ4Y/BTCy/fdY1KjiubLtqsjOMuXpnH0WdkbhuSOBeRQCJgebl6ukvLvOGsZOJSzo+SumLomraZCQ9XofbhNJ", + "qzTAQp5ymM38uEOjliwQGdE4f61ZXOKww5V7EsL4QOaDO9KQ0zgr22syG6YvbjG1M0kJgzmKvrCnMktWVPEwMWsjcQQd1Vpf", + "GfS6i4lbTqqayPcSLpQKlbCnteV1tbQmFPGgtGzxtXJYHDo04gohuWoT6zhD73NbLp1ljzn8FqHO+RyhS667hpHfItYg+rq1", + "pVcmwhQp+n0wxVIkzAprohu+iZ8FWf69AEN04Q7N/W3AOdv3Bn3PlBMgk8E3WTMTe4u8ZeFeApjoqDqiNrtZCaPOL1eZV9h3", + "K2op/Gxl37i9TbRWVssetajcNJmZ8h0iAz84S7UqwpI4JtaRzb7YG5ezwylVPHl9pZfINlk5fdPJYjs6H4kXsH219VlCB4Ix", + "B+bQCk7YATZ5N6KdDa4zGmx1Eis4ka8JCZ0jkncGjyuSDW63EK6g7DXzBo0riIwkQp0qexppGkY/u/AI8gHqTy+Oamv6uB96", + "KSB9NI97qFRYfhYaEEDKVC9kV9Ne4XV7OOur4MGT1m7YsUQQl0OKacbewTPUF0GS/WVGMBVrNswh+9o0fwokZl9erVo/EnmA", + "4F/DXAo/BmtTQHbNHCYUjoY/G3W+jjH262flXr5PSiqDh06Cb7VBq8ztnsHnSUEqrlmqtGeJF25JDbTi4Ozs6Sy3nPNikpPe", + "PAsApEhL/9cewGkOHJgVyacmEPjBld3Hrh6s6sgQrsrawKJK2WOWHVQpCYv1Fnn7OmPBD4ycP+8o1g7sVSSB4C9kAP0ZXV0x", + "hEGIJdsuBISlxwf30zNKaCJXKWVfpTN3Lhj9uI4a4OckS9FkcZ4o/58wN2qHraeZQ54W5kgnWTDUJyGpWM5DMPGMWULdZOdU", + "Yn3A1uFrFgFowqloMkBMp5fmvO1vLG5GjLG1EggL39RBTtn0hMg5Sk13rY3AaABd5HhbFqK3+zDYWMcpt+p9y8WfhLxRR0N7", + "8iu0S6PiMecFlh6TKzNgD0Z0uFLpZMriBvzJK31cmJY2AfqtZJ7fy8H9+lpfkONY9zWutmauaiO0h3YwZR512GXb8JqqTGR8", + "aI/V3h702zjyvFLCIyhtTDKzM4cMz/jBHsj0CctZQ22gs/wVWPTFnZuAdkc+XntLEdnFuWQXMRtfJIpk9A+3kXqtms3KnJez", + "B87gh0WVIP5mk5jpE/t5qrzS3ujF2/0B9xwsGtlGseNUycGx8TrUgtzmVrL4j3TqtZ6TrjSsSoGauJ9sUjHCc63al1R5uBqe", + "SW8CYhUW9CGGhlFxOPd2varetI6ZzQLZLXsz8hRu52DDjbhNyXxN6hauWX+yqEEjbtdrVDjPh5rjR1H5MdhMVSIobAj/16uY", + "/CxLe8g89c5Go+D8hh3eCK2QfNW5KPfBuDjkmvXQYTsxzhMK46rRLciSwH1DMwJrQPukelKH+KjncYBR4CzCrm/asgd2Qct2", + "UVNOurX9ErhXMvduK7b1Tk1FvyAkyNNarvuJLkJx+wTrUgHWyNe7g6Csy+zpVAPrWCIHuUzirJbygqq3j9gi0t6lsz+qTX2f", + "GUectiSgy21vooJrgqfTodD2g9lZTZXgbaDCRlx64NrNkWuw0122MTgX0D+t33TYk9gTVXhXguSuVBn3z96F/+N/b37nm/b/", + "/7CwXu36BjyBo0X1rUW3SXiWoyAr8WQHogTC3xuDVEyTylvIAFymOTyE6r1KCJsdWQFQqk5P9o/2ooxHCSzRnsf5g11VltP5", + "4AXy610i095LHx7/4H2yE14lQ93/+Pt7wS8GRq5Pz738i59+7+Or5z59/nGpQvvv1x5Ov3/6wpO/+LPvQnz52asfX7/+6YU/", + "/vR7739y/YVf/OD9Xzz+9CdvvWn/+/mp9z5+54cfX33742tPfvqnz3z87gs/v/T2z99+0T7583PPf3rpuc9ee9TXHdPg1hND", + "wQxCWwUggtWBx+uUKrctknGwLrVxBwEa8HwcPxNMmGUXNZS4/o2XJMocrw8aKdMxugzloZXygZIiy0KBl0rWT6DBrOsDGWCf", + "uKdeGdIepuqwmdpiYnDezTGM18BJRKG4c3k2daT6G/JggmGzfcYykBm4jgSD0IzuQHHaeC7wreh32xfT77hY5M4qyN1tVg5X", + "iHjdIEeJhPSzwCEpgg+0xUrIj5Zk7gNnIBj6fkRmw4fB/NfyQgbv5odPi00S7H/OxdjydoJd8jhZH8nKKPZJu8Jl8m8GW2Gw", + "cYKRMd3rw2cxhzk7L+bXcd5Ocg2KjTLuzb/f/eBdclW+yZl/BX8l5kKwFaZr2qdwxTfIU3ktu1fGjUh+xavkFNU9gxPzcrr+", + "ZbIjBrflVb5HZk3ru78k66ZYDhNPpn267cNHwHNJzsi37XnxLGA0fRKsoc7YeSnjCr3kPXwBDJ1gF/U+AQdly2552Z6e/WPj", + "En0D9saL6Fd7oredefECWUy/bc9+0V5zBtAPLvEq79v3vp1xSF7Onv0C+0nMnW87iyi5J8li+ra37k3xsHLE9JmrfKY3nEcV", + "MwBPRh5P8kGKLfNdu8N1tuCqX8fHEcyVZJa0e9sT4u/H2QLMz9S2D37czlvxYHJuvWM/T/isuZZ9F8/yPvk33wPzJUfxCjhl", + "OQP55Pbd98lpeoH9o/aKm/V9zXUbr6uJKRbvvu88tO/wOfwzU8/yXjYWV3U/zrn32jnMO2sGXI31RX7OEx+8lK2dd8QRCy7R", + "xKJ6ifPoXTwfn7ZdL5fR1zbCXF8ZB+jlliPU2vIIP33RWvGseFR9TYnhVuP7LtcA5u13bOa+y3Vz3H57x/l3n8jbz/V4wVfg", + "NY7/BbLEnuB1cN+37F7tHMY4tuso8aFq1rG/sf/8uXPZWv9k2twnqMJ8IbSkT7r+uDTQITkd0tIuIS2NbPvAM3zrufjlvVDH", + "ts+81EqQt9eRkPSr2TXPhHw5Zabx+gm+ci7UtE9l7TlOifb32s/j38tt2yDqndS6dd9rVPc+Hdd/Lj5zNvTQk0Q1BcT983qK", + "F1zBXNd06fYX23u195WE95P85Tl+/vVMFPsqb6fW6rne4r+P8bmeC1Xu90Oa/AobJiH4aDZe/wE758XpZzzePpe0s11zPPXS", + "cyGA/lpIvZ/M9OWlO6+HPc/7/kV8S/3/cvRJel4b2Xd43/SMJ+IzL/JBrlA1/pkQ6U5j/UKM4Ono27jmK09kguZn4u5prI+H", + "IPjp0Cg/Ec9+JsbouGvEe1/FOOL1s7z+j3jZ1OdqyQW2860Y8RN8MX3m2yHdfnFqPni/XWPXnfJffF2kOXA8nlrC7q/GvV7g", + "k56AXry3/2powV9tHznNW78C+x+ffyHrq8uxgq7ysqejP0+7wH3bZvXVD0JC/WL7XN6rx9mex+PzbB6ufIptvsCePMFeutiO", + "na+j90JK/rFs37gcr59u57D6DXPsbHzlWnxen7ka6/Qam3eKn9R80/x/MfrkVAzKlZgDavMVb7DGvZ2rqQ8fj/X+BK92Jfrk", + "1Wx/OJ49Y7bn+BNFl+K+qT0XqFaf9hneF1c7n82fND+Pxyy9zLcoZO/j9Xw2x07GnHmFN01rTWvh+en98zi/pbV2ns/+flxH", + "81+b/HPTe/61+Myr2ZzRxL6Y7QM/jT45Gzv5Kd+j8JXz0bDv84nS9S/ECnqn7Qe89Vi8dSZG/HSMAluibmnX+/NTe0U7uLHW", + "fJ5f9odN+4P/qbHQ3Hua1+e08V36QnvG+fOmfj7JP6/yM2ejkc/6M/pnrsYAXcye8fH493le4TJffys7Ky/4d7Fv6Lx7JY07", + "2aLBi/0UGZLfJJ/0I4n1+dLNt4Kx+aOHwS790Um+foWMyC1Xs5iUT968SDbvxAOeGJZfyziWX7crvA5ecPBpBzM4Xp3iEH9U", + "zNi430cn/F7hAZNVmrzXev0s2uRs0xecdRy/n8Nn/ZrnPjrBK6k9b5D3Oq75mr13EozUdp2r/nkwdD/GT4Hf+vHgKCeL9MuJ", + "m/yNmz/mU4Br/HR23yfIz822OcO5GKkvkbVbjN/g5j6J52efBjP2G+Q3f0x84+KuJo/4JfJP6/VHyGJ+xvvtMT7laTFW3zyD", + "58d1+OoV8qU/xdfBYn4GfZC+S45u5+s+zW+87tcXb7nag2u/5c943ubBUzcv8YpvJL7un2b/XiaDtvd5y3VuM6Ptk/PgQ/dx", + "P+vs2i13/OPxehpT8Htfw9yLsYhnvPkqWqN+sKs647j112NkLg927xgXzLw3fP68br89wStj/l+3v8CTfpktiLlxmozvZ7xt", + "V/E644qI/MFtb+VEEfnfn8HMxA3u2FNSaqyPhx697LfvkG46wsokH0Y13mBzdheTIeJrmQDFg8ieRLRW6+HqeNMjjvM5NjjH", + "5DdLtyAx29x2RmYFnAd4EDxn2/IpBZ11J4m8B5cmK9C3Iak7b/90gkh0qFR70CciHHYv8jurG2PQnqjYwjO/+5n8i8wMg+wR", + "ht0aQtbaExoZBuLzawFCZ6XAXRnqtdhUFqrsV/YoxLknYHAIjDvhTxZMQZ6kIxBZh6FniSrt7yCymZjODo+3kB4sDkKTK4cW", + "F62uaW8ydx8D3g6T3Tq22Da8pfqrq+bOfO7Mjwb3ICt70LpstkUgkVmghdc5TbIH/e/KQCRzHslW0STGIdF9O0Z5DSwc4Alv", + "yEIC5ed7UV+IKF6/KpFNHJaixRhmuTgJ3aXkYyHFPu8qxraDTM1JbIlFcZrBDaFO2rpt0ntkGKCUw2Yqwvlg55HOYNY4UkGH", + "be7eBRY7wE1zvElLKMMyR1yINZ2A+SRmeGtOkNFwhTm4QZH2xNbrUAqHDSeqa+GwKVqdhGVnc5j1kQwKg6wX0xc2NVTs0CTi", + "4cRFZ698EWlFsvKiPDFPmiKfss0cNapGW9r9/Z3FIitceGDctEUnXlziRGxjpgCU1nPonlAdKHZsQQLCGWsLyHq0+AZTQJGO", + "nMkD3EWOGg6egUrcFYFhsr52hQKJ2pct1krMAs5H7VxVntKw6TJU2oEE60POS6fPJC7BMSIZf/nSgqQVYuvMqzSc7SdgkCzS", + "WrHZ9SAZk4auzlqkynfcJyu97k1aWWZbC8y9iAtkOAUWWsyQoyAuTbR3vYnQa9/MoWzebo52wAKWcrzFIC9uaPn8pdtM2hP7", + "zPq+hWO7mw17lqM2G3e39Shcp+KoZzblvgxBPucoCOFJMnxR1dLZOSrTJRY57bO8S4txRLI3R4zEVh1CsUOKWoJ9KMe4zbUJ", + "TfvoghNh87hLNHki9Aht854TdpSrQhm0lMyA94gX3nPe/YyjMhVSkKoFqU58CryqG4NNxNUlA64C/lIg3jSjsCXl6M9G21nC", + "1Yhrh0DBVCFJFHzVap43OVTv870g/lFCUgydOumKDCPcKVo+i+WpRGoCDjn/UAxe1VWKzGFIh+xs2R2Aku1xr+/DK21wIhaD", + "HDrh14n5DrBYUgM9CLCEJqTgA8HpKXyKnXxJ7rfdYeuy7wQrEnV3iJP+yB+uaIvBbFuez8tMxMEevCKB08LQZ3UvO2cOBSEG", + "4emEPBacL1WOA513YWNJAPv6qaMTnSETs9Px3sxKJ6IA7FGBJBWEL7Go4sOZ5EVCIjeOvNLK8jLIjUFstxmetDfBHr+1FazC", + "ThjO04X7W8Lkm2lFTCo+tjSFPnbgt6rglQZVhvUIksVBoiJaa8q3IgvpEs68pBaviARC55STIhVVERGCiogZL4lIkB9s3y07", + "pkitnPOyplqcK/kmiv0gzbBtIskzt6Vk9jFxZDtVNlKzKY+t2qAoTIhimU3yT+N0DAhnWyLQKWKZidssAWtsIhzId/8WtGct", + "2JEXzmYsf71JXknaxDnJPYR4ZK9z7RaZ3k7R6sg452Ui9Snb2jdS6hBOwx5NG11Ar2VeTNcSWHNEVIeTwU7FtlIAhHeTPjQh", + "WYuW+BswdxKZJKaY9Iudx6/I8fAsXa5LHYetkHFG2VbAPhgNBg8WgfEJ7ijOnaxgqDdZ8j2VP4IsW1snuGxjKhBgVaAE1T6R", + "EQiCQTQKWm3Ltdddz8f+yQt053LzuAke8YlqFXweOHsZBYMJgGw1PW213+HVik742dZyNUfIVupILhiAga7ddzCD480dmnZf", + "/Dxlr2A4Q2LG6Yz8DMZMszvxPFwZmEkd9FezeQlohkbrFBm5JwDhTd0k5qpE5+xQlCgZb4J+lAA4lVe11EMsGOLsycs2m9YS", + "4gV9wo3NKMEhcQSrUMwMvRYTl2EDSTxO+jK6qWt1b7MIhu3dqkJUgW+oJnBSRCGldorWKKkbF70PMj7XZMbe7oA1AcnGqCNZ", + "rajkCQhXy9jWiorYRRwrVhAFXofQsh/vZosFPtBZmbgiWyFeu9qOvBQR52nCimG/7tVetHp3BrQvDuTLOZHs42NOm6GTKVPk", + "KkpWFlWp5CvmNfG3wTsDcz9IBEQ+7AxSMFenbM9Us9qItkOsHEDzfbFlzxqstUTRxF5tVwl8FR1PACAReCqFtA7J69S2a7A+", + "/f8U288JwkZ0JEQfbGFESQT2kHTaUisnqYI0hVfT2yqhY1Zl7DJQ8mGrl/PK7cyBQnminyOofwn+PBa05UQDBZWRo/Q+zjmA", + "HJuc1b6ayQ8JWe7+Ryob8HrlFrqVyOeJLIxKBnGax3Sz+8xMzarEKkq2BqFc+YPciMEF1VpCACETcbzbp3NeCstyIM70phIT", + "7ZaLD6RiW5w/2YS1PbEKTXj360UjBEINovo8ppNvVdrDA1s8kw9J2ePWJTJaLJlUWtmSYcOMiFjAxMkkU4VPzuDQeDgJTGb9", + "bsiPkBcGZWx+tNX9rHBoYVlwrChXzskbMnr2RqdC0H25365dLI+ebXqxHsS8udW07PRewqThx/6caNN79baqpHz2hgJIb3LX", + "IMMKfyW3/TNiO9IatQeacJy+2KOW2gGBAel2Yvgwi5ZbaqsaqNoQCnMeJeBr6QzLn6PvNmoE/xPJ0CRcX3rSsJLTruZ8oOKU", + "yUtZSheueogreCGvsC3z+mKCtEKbJPQ7iDtGUYdcSGujK22VXXCPH0kQYrMY7cXtOjZvB1fK3yR6MXz0ln4KG74L+TEs4gXK", + "qnjMKpntsROU0vHSCZBt79ZsGWa9mGjJ1kg4WXJF5oSzTINVBGbTZrwqcTQpcquG7kuKfvUGZfegWZBmDZO7vY0zi8JLPZXX", + "sJQ9EV16JYoIl3DIEOWZSq6gbp55lMlKxXgx3huqIgHBJ3fLXVW3PSRIhRWA1OR0kcO4yAr40Wf3R4EOQ0Duo3ShBF+gjuco", + "MG2y+QJzGTU2DqJPYNHSNpIEW1/MajKW8rqHSaZmhcOCCNqj1dAsypwcsvxqcHdgI0jbICq6g5yZrU7vwLIjkjv8IevcuhcO", + "L3fYft9eRLkF/Mngrckfu1n20A/jqMF8J+Psji8X9335SHHgniN3fsVJ4mV5sl6lWfj9xq63X0eoQ1VbqK1NwY08MBDA2zGV", + "Z1om6N6kjchg70ucAYMmcxFsVwI/12Zw4Tn1oKZ/zj/Tp7EQhkUL/VYpblQZN9ViXr3Y7sg2cRYzZYp98lyDgTXxu4j4r80Q", + "+Pmis1w9699ZKa0XyuJe25kn4/5g2DxoFt+Dmzde6emP/oQ/xeH11y+RxcvTEKtSigFnXUu+pTxIgoSi4fzDJRlbxbNyc6Ve", + "H3N13DHAmQlt2NvmitvKrrTpPbhWb6JEhTkKMzlCsd05JDJ/IhIq8hH2OTbb/ZicEcRWwXJuRCQSK6ftXkOdg/d3cvIVPpb4", + "qN9hKQ/OLe+Hb/jbv3vgt79wl/1vaSo1Ej9tcph3sjCVBvrWrnxZzjcZNdDsgame2F/0zas4MByWExQZTMV6pk6cxa8CGzwa", + "Uy5jMtdZzjkppu6+vP82zgzbO6vRbYWrT7mNPFfkwfulXp2xklDYMykXZpSi2KtHlFbyJ1L6QwJCnWJmKoCeZFtLl3HbLFTZ", + "BiLOkKRIso5trfA8Gz3vD11MBStEJxG8/BnXPHlJE3FJdzI/FccuDuYpvEYjFY2JGklFgXbvzvv+fpA6FVLCIEmlHwxIrsB4", + "KhKdj0RikqjXVHyCFVTJiFEnp0rasq1cFqNia8eEd7zqvdTO1m1Ws7VH1tQKmFGMrXHrdGpfx06fcQkWU6kV3ySxQUUtYlp/", + "OcOD7Tx5OmJ3pgVn4357qylhV5tydWeWplISGVMv6h5cxUHfW9IU88wMy8xSBbkkD8NmqNtYEiqgdy0WDzTzdbfYbzO+VVfY", + "s+e3O1PbaaF6qIPmbA4AYmf0PIKTa7kxWkxlWPaO8nAI1HWtoSmajTmSVFy2OHs2ffbMP9BkSycTeqV6F7e3yIyz2u5O7Vuz", + "R+cz/bFZmeyjLv4ZLqe4FaZSeSjP5c4VU1GTgw9VdvaE1pynzv8AIk6DzTbrBBsFyT+aJHSsxYkXteOzUyEwMA+2ClkZP15K", + "jkQtXJuaY9KLz3WbeuI25x+yHWhmCSzCtoCSv7o8dRnXTXSHZnYqRb5jagtbnsootdWVaGum2IejPi9PXhaxc8SGPDbne89q", + "OVwhRZVtK91qZsoLjudkpmD3wlTAONO1kxBkthMtTSVkw1GUesqR+r9ff99u/Yf1f3/78ZHCP40byb7wKFG57/N7plILU2mc", + "JRqMzk5UdSO3D+ujU0wdTjNTzm5RrZrl29SlqIFlzUakqmW7QH8uTfkzZGohr2wYZDLBERmt6ZeGJOZUtKFw/94T2Yopx+7m", + "sXQflc6U4zoVfitcAsxHumnfSGTVu7GJA3uBiVhEbsEdCN9fAlQh9EbGtRO7InS29AKnW6q8dslWO1j7g1HrmGGitpWesKjN", + "6wOziYMGpKgZafLWzMSsS5z3xBu0GRs0NCO6c5+sFXw/kKeeikznx9zZdJLQ/1uaOpqLKXNGenLRHvoOie6AO6aXe9cyfFNS", + "u91RyHwSfoDq5LTepFy9TMao5Jgx3IFXGF8DdUsNZhsu8ixabdNjyg7ZObWKi0xpliGU2Ktx0Z1T69bVnv00mUo2izttGDz6", + "1HhLiYksJAFXssi58DLRjxR7WImjxFe4Fm7upYH3I54UplnYVNrBYCXXaXttpRYQYclEsSkvCaBQL4Xd6mwFFEVuGU/hboop", + "X7JYnMIvZUwNXAEZ6Klp2aGIHgA8IAlZZ9ztNo1arjJabFM7eybdd+vZURdTE2bKLgc0yomi0ULy9lOKEnMw0sBiexpWPId9", + "H2EPphz5H0IvLrnlUneMfgOLCicuo6b8XvJkM1K8vVvHMh4NjxY6nzfCA6KY8HW7Y/oB8zgpNkjbi3oe6fEgn9zBJsQTVGM7", + "5eilALGCdhnPp7OAZPW0zs3k0b4UhRHXSx7OnWrmaHYKiSfYCsttUWfbRtgkceqs3lhV5NhIQZx89TVVpP7UL3szNkHP86S+", + "9spxDxs4bb67/ZnuoPd8m5edmUppZrKELuDBjB1TL20dLfYyD8GkvHUizCcKRKlhz8X4kkagaN9KpkgFvqVWl4lCJAgjQdsW", + "K+DrME9boEu5VY/KWLc7ZzK8UePMlEmihGiOsdKkx+695247fb5SkaKEecgEU2uwo3VDu52WVerPqYRJ04yHa1JISZZc4lID", + "csAWIGN3q5Ov29nZevQpFR2U85mhd2jKLg8vK+kWZMp9UhMKdnJGkr2Lq+4dreJ8rNsqQrsHp/wjnaI4zDBqXEpJ6m1qJq9m", + "7Dr2ySmndWe9JpFrCl+tgS9augNBk1+nNHzCxXE03aK+z/tTc8Jp1QZtPgvxuK0qG/cDLVOF3WVmanuL0167APslnSuzU8t/", + "CrDXTMvVStg6xC6UVYsdemE5n2jFFESS62g8BOgztDUSb86iW55ra2vfmpmfmd4oWkEZRi+T9ixSVFMTm4mXtC/RgkgBO/cU", + "wyNqdcXtKlOpAqa4W+zuVFNWMu1G6xHZ9uI/sUNvEMlDCd7kLvRURG23q4+1e0HkGTwD5wRjPBsDtyVGrSQIbndPJHJilGmz", + "sfZJ2eqB4aRWY7Lk/OjBgkeAYaMqsusyux4sNTnUwH7keIkiM5Zmds5Mxcil5pXkcRK8k7ti1k5bM23I3WckUiiOdDjq4goy", + "+F2ZxPee9poQYetM4S0y5doChy33rIjYu/Th/k5/0Ckk9BbSy4cOzZn9a+2iI4+2tFLAEYath5BvapOnHLEcrSgwa/I3SwYZ", + "AqFh/ZKpxSYSt2Ducunu4BZqk1w5m54d7Z7yrptWj8lzYGXSYSAaONHCDAYuQNP2vvw2eQGZj8cfU2cjNo/Mymu9KAmmJaFy", + "sxRammzZZ0zaeVaVvloSeAx8aqZQk84rRrCc39RmgZ/MTfL/WjbQLKgIyzg6XVp6gyIjTHNosq+VEE31ZVbkJ7qiMYH7yPyc", + "Daq8rko6WwL0VZH4ySctmj09EbZkSjxN7SFb8pVDCXTHjlvv3sqbZ8eW9e4ULDAStG6fedbCF8VU8Hw1dgEl5Kbw+XMtRxYg", + "f1P++9IUhtxW2Fbz4GAD3HjNgzbd81jCBz9C7b/YND64htrl9q9k3Wc8C/WW/mJ1OuvRWef9HlkIogI/f+8a68jf9hr563lV", + "ur37F6pF/x+/BwaA9pofPv3BRXIMiAUh+6S9/6xzL5BvgH9dV3W8V3nnd3jZWoB68KusT8+YF+yv9ppgI3h4igsgq4H/8Dtk", + "HQGfA655kXwHqjEHN8LD6Rrvsg798dQrZJNgb7zLevg/ZXX7RVaSP+u98h5ZBq5O1e6DNeAyq9HfJafES1PPh0r9ZxIvw8Pk", + "gnjzw0dwt5blAJ/0yv4LXhl/nfX1aM+7vGu6A0Yp64nL/HmJte/+vfTeOx/8iJ9+m6wGF7wa7bGbZ26+/tGT6benokKIVVxX", + "WMnl9VRtdZuq5lId2xusO3qV1WRRcRd1Ri/bZ67YXy9NVXGpnurMzctZddJr+SfZGrumV1W9rGoqr3tCjd9Z+96j/t4J1kzp", + "KlduXkd1lz/Dw6gBs08+4d97g9Vjp6cq2aItqGCLtrx88zzr397wmq2Hswqyl6f+OsPnfQp1g/jroxNtrVbUgPn9zrNi7C1d", + "kz15xv695pVcT6EKzu+nerRzdpVr9l3VsD3qNWJngjXH+/OJrJ7tZdQhtnfPn8HudAb1a+m966oHhCia2YMC1AwXkxCmTqJQ", + "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", + "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", + "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", + "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", + "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", + "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", + "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", + "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", + "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", + "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", + "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", + "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", + "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", + "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", + "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", + "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", + "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", + "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", + "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", + "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", + "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", + "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJeZ6XDB", + "CgpXM3zN5OOS/6Gz3LnFo5opiqm0Ki689z9lhR2eb7qjWivNDptVQVeiUClunzwkVXDnqwdx0DdHG/b+N9F/39wGfDVzDbNf", + "BXS5xQ/JMLDAeTQ5Lzi+cFhZpyRpk+sNqwZHy8ftxH2O1EgG5FTJCK7JXugPZCt2luWqtFjJvMSR411M40GnZ9eePb4+dpt5", + "WELwQ0WaKHlRfCjzo0k6Quc/09aDFusqZvCq3PDOtMO/+y4W0DLDXDaD/twty2FHc/vkSLmOjP9ss+uP9vzXW0zbpflbXmhn", + "ggJkt7FZt93mfsNtWX6MHehBoRQEbPF9jmvfou9RFEv65RYfZOThjDR/V27ZXxLHuEStd/3suZ+9bf9962fv/uzaz67/7Oz/", + "V9e19UZ1XeHnjMR/OJkosq16ZqBEVYPHExmbNFRJQKlRUvWhGs+MzcDYQ+eMsa2oUoyBkqSERAolQlVCCgmOG6gDcRgIxlL7", + "B/Abj/BSqf+ie932XvvCiy8z57ova6+91re+b/ccsAFjzJzyIA8w0r2DEfABRuDvINcxRtjN788xUwGRfOT79fMdzPl7j77F", + "s79AhmDgE97GnMCXmEXYwm8pY0GMysj5jL/943UEnvmUmQN3sHse8xiQHdji7MQWZwUe4RNc2j3HPLzEGg05mB3kG14jNlvz", + "/Px+u5/w+21jvgSZss0ZW3574NHb+KzUPltBdmTTRfcVJx7zkqm49nmIdHNcWUX84aeNX/+gMglrwNT2ZJ3Pv/vkPnDm0fWe", + "3AKWMryD4yajsz6yXH0XkO9Nvsf7I9/ehuQRPJ6zb8wTnKVPgmd0nHd8v153ptvXYi02l0+53GLN1VAyYVk1XKPQxiHIjS1d", + "OKmqlhgK0DJds7gi14+a+znZYRVQDCdSVSuFYPE3RQwQ9EJ/EggesToLHFnjSK7sRouBeXPYOYvQX4KUaMsZfFSd7y7gFMbJ", + "LOqe2SGQlOwZi1j2mBv2FLxIC9QqV/3MKKw6EnPmJvTcFoDE21O4Y4oij2N/6yASmR7pF0H1+lxJ5ohC6H2wLXVwQK5dEG9m", + "vDgBonmj2Rutzmmsdx3FftFZEBfC4JNdETvu/M1iw5h/8wNCI7Wq56GB6lOATQYZNIhu2hqgKFExVGU09HhxsT9b+nWxVnAo", + "TQtIPN2qd1RYEsJY1JtZ3sLoeLjaZaE7hEAfieshxkSXU8GjA4JjliSXaBnwK28QkKCKxlXdKuLuZtvLxVrQtXsKUGrTKjVB", + "l52IMSgWDG8GCyogGWcziqNOGo/LLFr1HFTlW9nJdgeQNT2gEgxcR8IaNfp2xFg+JAnCHT3exRBWNsGKuaLgYV+fcwId+y4H", + "Wwsn6qBcAuxuJ82DmG9bJXCxoNXm6vMtth+ukscc/C4JQLGClmgoZeIcHO11EYT1G/PPwgxUDGsiHAHMIioH2ZEQ8aKowAgW", + "hegUrabKzG6SG5Eth4uPS0xNIJgCDnHevTV9GFPMK1KaZtuDZaXAx8LoY+6XQgEyiDxUF8ZEColFKMuDUol2I/eYvzBmymBv", + "Em+qz3V5Hu+RibwndAsKgB/LtNCzGTOjmbYIHi0U3OWtttkKQSFv9i5mMnNXA8G20MHQeBwoZ4ZMm8cfhu3RJTgciCRh8Bxk", + "nagTmahSiCkUlMnfQpSNa9dAqJiIIbXzbsdWxSAyWBd/S0DziPGILdkJV7k67fM26C8KHoXYA6jWxl5US2BjPfQ8YvLafVtW", + "oIV4WUnHDBNW2CTQoi1aqYCCI+iutfyk1ERopL0TYFVsgCgS4J5laPeXuiXj8/asMOPUIsvhAVILVAmb8gFcrtfuNv1Chowa", + "yN9YMT8e5+06Kx4poZBjWeZJWHZRmLCn7IfHX4cIXBw9FC/HpvY4NyFvYTcm9ZkciBPMniw0wjbIfUDi4WNqV0obpbET9WUz", + "32dyjidU9pVdikqqjagzVJy7wtNauz/ogoCVLyERyXjR2PPT9YbZfiGKGJa/1nDx5f2TqsxvKHrm2hGl+4YimqNqJ0i+0i+r", + "Djwpa6ki3TCb4nr/gFnQzLoFeDSZhNHcL0QOWR43kPaeiDsni0aeQ2eKwmMxCx21YrSjVLxmfHt4rFcqna6xy1w92VQDlAak", + "qwQUrwDZ7DorioxDdBJdHdZY5ATqRDnh3TxyQzweaijqzRUkWaBqND8VBOuw9S+sq5p5CRXa6yLlGEmo4o69+uLUkcnp3x89", + "lElXaNIe+lmshTEpr4MxquLj/eBm45GjAXg6Idtc7EBVaWBcjK3wq56gX9+o98zzNnVExzlVXDVNrjLU10ow4MgySHvpZZu9", + "8pOtFcQKmBnDb6FGmtopcH3mLDJNdFQNsR7h5J5nkdvu12RgdUe00JSj1duvpUCL3oFx0lHJdUCu4qi3rB/gE/qVjcIc5epO", + "ZFEj6bDZPhMVCiNVprVAnXuhK9yogM6bouAwNny0KNUI6qOg3+tZGGOajp452tf0Hb4YAlGtXrfHJD5mIe4s5kgg4RVfYvRF", + "q7PRbs8MNSoRttw3k4cnONz0uhkrM93uSYsNcEwZCzRy6jZ3K3XXzihj2WtrXlXvI9NWvwPxswYpxlLy27yJhI9GpS9YW1hh", + "1ckK5Iz4P9LvK9XIWmQiJxayINWuyE4s3SdsYBZ7ziWY7C7QkDZuAm2GYbTMGS9nMedSvPwogH2Bt2POJcQ1qtryBwGdiwMY", + "EEhg3lXn6ExohhuCevNEHTE1doxh3MsLCBsnP2cCIst6qjhhienGXBcNrU3MHydiUmEox3pGRkrYcOsURB7Rh5JabEsLnFGF", + "qtAa6UolqSJ1jMTkRGreBIhHdns6qoalY3R1KsBqIG0IDWAzPHpI8QsEhwI78zYFdlrZaCN4N9CcXcL8mPFlYTBZ/XnroNsp", + "eW7tkmm1POBCMPOU8U4KoXKwC5YXCGGYPS8PasjMlk5BAnlkBrXw4JhTDSX0b7cPxR+5qG0KBRPw8yjed9wn+NW/RNwd7jPt", + "vYFBYLl86vipAGtnRl9kaAuOHVOoj+pAztVFE8F7XT9KC7KOPsYca1GZCMr58dO6wgHfXeB1Rbp5cWTM0fi0iV+25UHtsIlx", + "Uc00RRyXaWFIhrjV9o5lQTLK5yfBcYgrLO71KssliAirm3A/ZtF2Xn9LUTSbfrB/kM3E5znVRk6Xx5/tfvT4Z8Auo14Y6ZSF", + "n9wgFTBEkp+H+C4ruz0IVNhE1Y5jnP4nu5c4qnqXFd4grgpx3R38nyPDj3/AM3cIVY546of4F0V5N839KBp7D1HlHGNGhDfj", + "uvnuFFH+GXX9SNeM7g647wf8FsHzQEwZI7jbHDH+6+4niDw/h7j5Acd6QdnuB44mbyP6exs12rbw/vSmcAzh8OWTB/QWrNIG", + "d/8Uj3+AmnLboPKH+daLAhjYlITsBcyormJu+g5meym/bAEMSneMJZzOySnfSrr2vqTXL0q2mlK6Xyutq28VEoDy3VqBS9AR", + "8LmcBXnnq/j3V4ziYC0hQlxcVcnfMyrtvo7PsKrUfx6p97JoGfsWA7nOZ3jKHdE+WxdwyKbgCj7A629y3pyxBISrIVmcWwIR", + "eSiveQFP0WdRy6h25jbckFOUCo/DGFyUfLoGV+wo5MaGNPKH0hH3FT5HtaEDkFgsgYaCPJKuFzSCQ+P83UEIPM27VYVC+Ukh", + "Z65Li+1I79wTUIQCF3lIj4uigbWBf+wgwuQR6ze5pz0janqEHrnqQ1PuyME38cQz7k3dvTakRy7jWbcZoMJifDTAbkqb3BYF", + "Lmq6GyKzJZpufPfb3uhlPbsL2JIfIHCFYAwfCyiIRO7oef6m2v+8PN5fZDzbdv6ecSkOVvRQRu+6TJ91kaCyY0xQN+4T6qZ1", + "1c5b7joEDuF5sS4zzgpvreMT/kuJwaFiIPx7214nziN5tSmuImXNHLWO1RwbtqpB1IzgmPvm9788dR73ieg0hfmh77hO5AJm", + "qH7ELBVdGWpa1lGxiJ9HNI7UJ3cx23XWZqa+x+dahWoO1vG5Gd4Lj92Sv9SGUkIwS/vL3d5cZd+rr75aWUYSH9gjhEEh3PbC", + "t2OZTQVEURhhbVL6HEVgbxHW7/Fid3a2qCntmMZvDOQ2IFUvoH/jsUQBpeyloD4E3ECdsuIcjvWyXiqmBHz4ZC3owR8VqlE+", + "plI59HYx0zdcAtKSZuvYO4cnocR0Ab0lvuEJ43XTJQ6EiWfUGA9yKnnDRnUyG4/TdFZ82yz27uL9uOeQ8Y3jrs3ACw0iWpKo", + "wHanQFQl0bdx4AlbAjuZkkKv1QpLURrktSD1hrEVzPV718qiHeuBON5SwGihp+7Rr8YhqSwdKwnA7CowIyf74xtfypOQIFYH", + "r+Ac+cIyn8LAhey9gL8ux5aGDp8JwtU+ZBlOVuRLMkSzKJe4z9aZYETOTIS5GdDz5qCA2UvPAaIlmgjteQFVqS3MRKPebM1T", + "XIKQI7mKJAmqR+8q+fHLZtDwJuLgyuHmcLs5QkxyJwSYDVti2WYItdfIGDPOeH0bu+gFr58pRlaLI8aCVW65KheGiaPwBXNg", + "aE0HTl17GXD6GVuOtqcGQWHFgCuM6Aag7NkTfoBUHOz+F+b6QKw4VZ4sx+O+RDwMwgUBgY1RLU0m7B5uV9hU5dZB2ZBKmEmo", + "kyvEIP8n8ccsDkDOt3Nfnq07a3mqRrPjvCnM4+jmpDFj8zPturpYa9kMSCZF4eKUxZzUCVS7cSDQy/5CuMYP2tVnZ0F0oa9e", + "CLHn3MY8rVzwTjHERSFwCazAcYfhEgtNDXXkmeaycHa3rSUDeHIfkdzlUmvGvHMLmUXqkGzs9V3RIq12EAOySTfAGUlc0WZb", + "hQTBsly8zpFd9cgMZdIKQMwKr4fJ22Y/7PqL2B90iVMd7U6jfqougiSOBU0Hbr0hB6UpNORmF3s4TpUdc+1FKgZQ3yFyFs6U", + "QghsxbTBHBDAEbFZ3EFVPzX0XunYROnU8ZWc0A5WpAZwgGZJBRMmo8/GphrwRQPQdsPyGi45imYAGx5xI/SOObNy2DgX15xZ", + "jwZUeXT4hwKRIHXVQ44pmCaYzsB+bIC2YA+IIqBdXt5/6OX9kzzGzD/FkZGxMCIFK6RHUigxbDOs/hjUPYb4WoBZBkYaoZdx", + "nu29EvDITpmZNDwCRnu6PW/+yuIQTNFbVtizcB6S83mCglxUpbPvoFwjpKqV2cX2XI4bUm3gl84y3tjCcVQWL+EycYRe26e+", + "OEj6zkzN6rsioKy3NI0cw3VYrld46E3a0kjsAa13J4bHA9/yjXzuDi7qCXDOTFsx16vPI/7FIiC0wJGAl+z1HNrCK6yV4xIr", + "drx8/qlYTTg0ajmyPqqXv+CjqZWDnvpVrQovqoewMMrpEYhOXVCJHeKtsT43izPJxcS6mfDeitSXfa8v84Tnt6cQP18tNfDZ", + "GIggHeiPjSUWDccY5gRTrHKVqJO0QcyAZRs0Bpsw/x7AKsh8VuGnpybBeTF6H5/9WE290912c3jvyFjRYxy3pc7xVs3lHJzp", + "riVcbh9/SH8FFeoILiEMFGqOEucdvK9itpLJUI2DzA3OasPK0WnPYvOOejqIAkaJTVjmOCjhOHIPmu1THSIWtQw2ueP1ce+L", + "AyPAv2WJNuDkdS4+DuYXE+6jp3alXDdPros4vqIdHUmpYbbb/qWlm0SVwozgfphZMT7uSRqJbmw1RSyC7ZcFnYkgErep1epR", + "x3Fey9seBQXSCCXAPj0NOCKgQW4BO1JOnt0pyHdapqthu0F2ewjVVjYj6liwnX+U6KJalthAIgaHQAkIHIJnI/kyHw6BIxJl", + "gRy+UqlTob+y1M4BS4fZdJyGUp4M9iW4uV94SfOS9MNamFNsN+n9+IXgH5t1tFk1tUBAh3TnzchVjpcnl8g9MJuwL4jHZFko", + "xgchmf7i3OJ/NvJsmHLriyPCh7N75fH27ipmOzYxhxB89vgaZg1WkSOIciP3w9wFIczNOWcxC/BQ8inmepIFcTmEbeIMkuwD", + "cOvE5zJWPvzsGmVRzHUBwz6wGH3Kh2xZVp74ep/Q88ITO64dc39iB9rEz5APR/hNMOb3PSqvn+f42o8cKVxT2PEz9NmTW/CZ", + "v0Ydm34dbElO3pcxlKoWxi/dZTlWz+rIaEJak/FsCMeaGPvI7IBHFUSyKDqUp/ysYmoxUBhxZ5KsN1JQ7ghOt3D6VVNOinzp", + "eTiuKkSYwIzHFfmMcOEMOMjbjZPeKjcsnq1ybP+sCEPF0ylmR9F1H8r1virLUg556GijNx8t01SS4i1d9Cu07erI4OdLwPsJ", + "0/F9M5VLXLZVSPm4RFpT88lraPEKwhFyaEEfG7gUheqLpdIffAKPiXYPnqRWSLRIyjNdejq49nRw5+ngO/h5/+zTwZWng388", + "W/vm2dqnz9auPVu78mzt+rO1q8/Wvvjvrev/++fntuT8/qr5b0TyYpuSvKAsw9cYt/+QU2Cc6JGsDVdcXpR0m60qDTI4Nj1h", + "kwK2CnVDikAHnIWEsy67QlFXO2wri23x7BWVvgkSgh9LEfSO5LC+lMc7J/WkmyrJaKuGbb5yXQp+deJmNSrNvswVppwU0/ms", + "oEz7hhTzXuSidW6Tdayf3ZGvNiRBdlmO3JGU31fqdGqfM/jM+sMNqd71q+D5aTdVFvKGyhDZfqezrsuJt6VVzd2/9oRL7S44", + "RhMC/kC5EaosLRr28It3J6EHAWQr6jZSf4MGK9xfplb9Yi20gTRdEnH55fmOOtYZs4BeSqyn4qRRuxmzCiR8qJQ/XKmFIQ3a", + "1ZTTllvtON2k14bUWdcYfwnmM9iGcjWosu5qi1eqVN7dP1mpTE1PZe+9Mf3Wm9m+8t7M33RJRCbY8DBVlnlc5mnCrRvUSJiG", + "Knirp5ziIhm/NY3+O270VDvmB+dS+78saCze0eJdhoLeHIpjUAgg8q/A/Zoll6zxoV8kMlDV5JJZgETPaNYH5k549VFMvamq", + "L1WO5teRyzhLmv70BPCXM+sgpCJFpud77XqJusC8eW/RbJT+fa9KbR/Og8743jGqQ1fu0ftq449D+0AGzEjJgXr8hRdS8bR6", + "HxTkwyepJZf/5Fuk19VWshnGe8nbtcZTzor2xpvd7GDPOOmdEcW1OEDeRsLy3EFMEPjIPzn8jsc7eUeqMbH28i6xRypMU+IK", + "5lO4wiXihwSED9We+tYzO3rs4JuHJ7PiQr80HRAZQPfFMZVJ+B6iMQw70/lVssTGEC7kuu3T5mDa/Eu2c1+p711QubbT7/Ah", + "lYSHbGbjmK6AVEsLhor6b5tJVqa6lYMIf03aj4X6iTwes+ZKdjs7UkY8PA/e2IfFE3AMx2tNHHXEr1ORLrO7VauCduqr6dUi", + "jlrhQ6k1RFPuJTABOEvSljKOjmAj18vJzUqyWedbx9OvyQpR4WjR4wSHySvlvfuyaX/1twnH59yz+pzuKWbpFSzx8pj2HE+2", + "YX94KEuvC89pr2Iz7cTkgAzuJOAQ8fvT3Kim3RPIJye/wLlUjls6mss88wM3wi6Oz+nCwnOas5qy0/Bez2m2GqIzLykLxdaL", + "MJhSO8+7fod8HDCK0tahA/oSbeUOIhrtdQRrNhB31XrrlwXtdUXBygY+xu1jxQpD3v1NBVyyiLwdRfCzw9dMuPO0cbmMFFOE", + "29oUrNZXqX3Ghr8TuigkT48Q+TXwvXvGjv0foSWBhw==", + }, + context = { + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwABAgMEBQYH", + "CAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8AAQIDBAUGBwgJCgsMDQ4P", + "EBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/AAECAwQFBgcICQoLDA0ODxAREhMUFRYX", + "GBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAQEBAQICAgIDAwMDBAQEBAUFBQUGBgYGBwcHBwgICAgJCQkJCgoKCgsLCwsMDAwMDQ0NDQ4ODg4PDw8P", + "EBAQEBERERESEhISExMTExQUFBQVFRUVFhYWFhcXFxcYGBgYGRkZGRoaGhobGxsbHBwcHB0dHR0eHh4eHx8fHyAgICAhISEh", + "IiIiIiMjIyMkJCQkJSUlJSYmJiYnJycnKCgoKCkpKSkqKioqKysrKywsLCwtLS0tLi4uLi8vLy8wMDAwMTExMTIyMjIzMzMz", + "NDQ0NDU1NTU2NjY2Nzc3Nzg4ODg5OTk5Ojo6Ojs7Ozs8PDw8PT09PT4+Pj4/Pz8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAAEAAAAAAAAAAAAAAAAAAAAAAAACAwQDAwUDBAYHAwMIAwkDCwsLCwsLCws", + "LCwgIBgoHAwMMDQ0NDA0NDQwNDQ0NDQwNDQ0NDQwNDQ0NDQYDBwMDAw4PDw8ODw8PDg8PDw8PDg8PDw8PDg8PDw8PBgMHAwA", + "AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQIDAgMCAwID", + "AgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC", + "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC", + "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", + "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", + "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB", + "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD", + "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF", + "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=", + }, + prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==", + prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 }, + transforms = { + 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49, + 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8, + 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16, + 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49, + 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26, + 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49, + 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10, + 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5, + 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21, + 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33, + 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33, + 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34, + 0, 10, 34, + }, +} +end +__FILES["codecs/compress/Bzip2"] = function() + +-- 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("@rosetta/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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Bzip2/Decode") + +local Bzip2 = {} + +type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} + +-- 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, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) + if not b then + return nil, aerr + end + 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.from("bzip2: " .. tostring(nOut), o, consumed) + end + local res = out + if buffer.len(out) ~= nOut then + res = buffer.create(nOut) + buffer.copy(res, 0, out, 0, nOut) + end + return res, consumed +end + +-- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) +function Bzip2.crc(buf: buffer, offset: number?, length: number?): number + local CT = Decode.crcTable + local o = offset or 0 + local e = o + (length or (buffer.len(buf) - o)) + local c = 0xFFFFFFFF + for i = o, e - 1 do + c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) + end + return bit32.bxor(c, 0xFFFFFFFF) +end + +return Bzip2 +end +__FILES["codecs/compress/Bzip2/Decode"] = @native function() + + + +-- 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 +-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is +-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. +-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). +-- +-- Never throws: every buffer access is in range by construction; failures return nil, message, kind +-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +local Crc32 = __include("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: core/Crc32) +local CT = Crc32.MSB_TABLE +Decode.crcTable = CT + +local MASK = table.create(33, 0) +for i = 0, 32 do + MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 +end + +local PBITS = 10 -- primary lookup width +local PSIZE = 1024 +local MAXGROUPS = 6 +local MAXALPHA = 258 +local MAXLEN = 20 + +-- scratch tables, reused across calls (single-threaded) +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LENS = bcreate(MAXGROUPS * MAXALPHA) +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length +local MAXL = table.create(MAXGROUPS, 0) +local CFTAB = table.create(257, 0) +local MTF = table.create(256, 0) +local SEQ = table.create(256, 0) + +-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed +@native local function buildGroup(g: number, n: number): boolean + local lbase = g * MAXALPHA + local cbase = g * (MAXLEN + 1) + for l = 0, MAXLEN do + COUNT[cbase + l + 1] = 0 + end + local maxLen = 0 + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + COUNT[cbase + l + 1] += 1 + if l > maxLen then + maxLen = l + end + end + MAXL[g + 1] = maxLen + -- canonical codes: by length, then symbol + local code, idx = 0, 0 + for l = 1, MAXLEN do + FIRST[cbase + l + 1] = code + OFFS[cbase + l + 1] = idx + local c = COUNT[cbase + l + 1] + code += c + idx += c + if code > 2 ^ l then + return false + end + code *= 2 + end + -- perm + lookup + local pbase = g * MAXALPHA + local tbase = g * PSIZE * 4 + bfill(LOOK, tbase, 0, PSIZE * 4) + local next = table.create(MAXLEN + 1, 0) + for l = 1, MAXLEN do + next[l + 1] = OFFS[cbase + l + 1] + end + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + local k = next[l + 1] + next[l + 1] = k + 1 + PERM[pbase + k + 1] = s + if l <= PBITS then + local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) + local shift = PBITS - l + local from = lshift(c, shift) + local entry = s * 32 + l + for j = from, from + lshift(1, shift) - 1 do + writeu32(LOOK, tbase + j * 4, entry) + end + end + end + return true +end + +@native local function grow(out: buffer, op: number, need: number): buffer + local nb = bcreate(math.max(blen(out) * 2, need, 65536)) + bcopy(nb, 0, out, 0, op) + return nb +end + +-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind +@native function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) + local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) + local op = 0 + local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local bb, bc = 0, 0 + local tt: buffer? = nil + local ttSize = 0 + local streams = 0 + local consumedEnd = o + + while true do + -- stream header (byte aligned) + if streams > 0 then + if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + break -- trailing data after a stream is ignored, as bzip2 -d does + end + end + if p + 4 > e then + return nil, "truncated stream header", "truncated" + end + if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + return nil, "bad magic", "corrupt" + end + local level = readu8(b, p + 3) - 0x30 + if level < 1 or level > 9 then + return nil, "bad block size", "corrupt" + end + local maxBlock = level * 100000 + if ttSize < maxBlock then + tt = bcreate(maxBlock * 4) + ttSize = maxBlock + end + local T = tt :: buffer + p += 4 + bb, bc = 0, 0 + local combined = 0 + + while true do + -- 48-bit magic + 32-bit CRC + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local c1 = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 + bc -= 16 + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block header", "truncated" + end + if m1 == 0x177245 and m2 == 0x385090 then + if storedCrc ~= combined then + return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" + end + -- align to the byte after the stream + p -= bc // 8 + bb, bc = 0, 0 + break + end + if m1 ~= 0x314159 or m2 ~= 0x265359 then + return nil, "bad block magic", "corrupt" + end + + -- randomised bit, origPtr, symbol map + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local rnd = band(rshift(bb, bc - 1), 1) + bc -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + if rnd ~= 0 then + return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" + end + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local used = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + local nInUse = 0 + for i = 0, 15 do + if band(used, lshift(1, 15 - i)) ~= 0 then + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local bits = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + for j = 0, 15 do + if band(bits, lshift(1, 15 - j)) ~= 0 then + SEQ[nInUse + 1] = i * 16 + j + nInUse += 1 + end + end + end + end + if nInUse == 0 then + return nil, "no symbols in use", "corrupt" + end + local alphaSize = nInUse + 2 + + -- groups and selectors + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local nGroups = band(rshift(bb, bc - 3), 7) + bc -= 3 + local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) + bc -= 15 + if nGroups < 2 or nGroups > 6 then + return nil, "bad number of Huffman groups", "corrupt" + end + if nSelectors < 1 then + return nil, "no selectors", "corrupt" + end + local selectors = buffer.create(nSelectors) + local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 + for i = 0, nSelectors - 1 do + local j = 0 + while true do + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + j += 1 + if j >= nGroups then + return nil, "bad selector", "corrupt" + end + end + -- move-to-front over the group list + local v + if j == 0 then + v = mtfg0 + elseif j == 1 then + v = mtfg1 + mtfg1 = mtfg0 + elseif j == 2 then + v = mtfg2 + mtfg2, mtfg1 = mtfg1, mtfg0 + elseif j == 3 then + v = mtfg3 + mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 + elseif j == 4 then + v = mtfg4 + mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 + else + v = mtfg5 + mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 + end + mtfg0 = v + writeu8(selectors, i, v) + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated selectors", "truncated" + end + + -- code lengths (delta coded) + for g = 0, nGroups - 1 do + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local len = band(rshift(bb, bc - 5), 31) + bc -= 5 + for s = 0, alphaSize - 1 do + while true do + if len < 1 or len > MAXLEN then + return nil, "bad code length", "corrupt" + end + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + len += 1 + else + len -= 1 + end + end + writeu8(LENS, g * MAXALPHA + s, len) + end + if not buildGroup(g, alphaSize) then + return nil, "over-subscribed Huffman code", "corrupt" + end + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated code lengths", "truncated" + end + + -- MTF / RUNA / RUNB symbols -> T low bytes + for i = 0, 255 do + CFTAB[i + 1] = 0 + MTF[i + 1] = i + end + local eob = alphaSize - 1 + local nblock = 0 + local selIdx = 0 + local left = 0 + local g = 0 + local tbase, pbase, cbase, gmax = 0, 0, 0, 0 + local runLen, runBit = 0, 1 + while true do + if left == 0 then + if selIdx >= nSelectors then + return nil, "ran out of selectors", "corrupt" + end + g = readu8(selectors, selIdx) + selIdx += 1 + left = 50 + tbase = g * PSIZE * 4 + pbase = g * MAXALPHA + cbase = g * (MAXLEN + 1) + gmax = MAXL[g + 1] + end + left -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) + local sym + if ent ~= 0 then + bc -= band(ent, 31) + sym = rshift(ent, 5) + else + -- a code longer than PBITS: canonical search + local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) + sym = -1 + for l = PBITS + 1, gmax do + local c = rshift(v, gmax - l) + local f = FIRST[cbase + l + 1] + local k = c - f + if k >= 0 and k < COUNT[cbase + l + 1] then + sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] + bc -= l + break + end + end + if sym < 0 then + return nil, "bad Huffman code", "corrupt" + end + end + if sym <= 1 then + -- RUNA / RUNB: bijective base-2 run length of the front symbol + runLen += runBit * (sym + 1) + runBit *= 2 + if runLen > maxBlock then + return nil, "run past the block size", "corrupt" + end + else + if runLen > 0 then + if nblock + runLen > maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local ch = SEQ[MTF[1] + 1] + CFTAB[ch + 1] += runLen + for k = nblock, nblock + runLen - 1 do + writeu32(T, k * 4, ch) + end + nblock += runLen + runLen, runBit = 0, 1 + end + if sym == eob then + break + end + local idx = sym - 1 + if idx >= nInUse then + return nil, "bad MTF index", "corrupt" + end + if nblock >= maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local v = MTF[idx + 1] + for k = idx, 1, -1 do + MTF[k + 1] = MTF[k] + end + MTF[1] = v + local ch = SEQ[v + 1] + CFTAB[ch + 1] += 1 + writeu32(T, nblock * 4, ch) + nblock += 1 + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block data", "truncated" + end + end + if origPtr >= nblock then + return nil, "bad BWT origin pointer", "corrupt" + end + + -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position + local sum = 0 + for i = 0, 255 do + local c = CFTAB[i + 1] + CFTAB[i + 1] = sum + sum += c + end + for i = 0, nblock - 1 do + local ch = band(readu32(T, i * 4), 255) + local k = CFTAB[ch + 1] + CFTAB[ch + 1] = k + 1 + writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) + end + + -- walk, undo RLE1, CRC + if op + nblock + 4096 > blen(out) then + out = grow(out, op, op + nblock + 4096) + end + local cap = blen(out) + local crc = 0xFFFFFFFF + local tPos = rshift(readu32(T, origPtr * 4), 8) + local last, run = -1, 0 + local i = 0 + while i < nblock do + local v = readu32(T, tPos * 4) + local ch = band(v, 255) + tPos = rshift(v, 8) + i += 1 + if run == 4 then + -- ch is a repeat count for the previous byte + if ch > 0 then + if op + ch > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + if op + ch + 256 > cap then + out = grow(out, op, op + ch + nblock - i + 4096) + cap = blen(out) + end + bfill(out, op, last, ch) + op += ch + for _ = 1, ch do + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) + end + end + run = 0 + last = -1 + else + if ch == last then + run += 1 + else + run = 1 + last = ch + end + if op + 256 > cap then + if op >= maxBytes then + return nil, "output larger than maxBytes", "limit" + end + out = grow(out, op, op + nblock - i + 4096) + cap = blen(out) + end + writeu8(out, op, ch) + op += 1 + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) + end + end + if op > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + crc = bxor(crc, 0xFFFFFFFF) + if crc ~= storedCrc then + return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" + end + combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) + end + streams += 1 + consumedEnd = p + if p >= e then + break + end + end + return out, op, consumedEnd +end + +return Decode +end +__FILES["codecs/compress/Deflate"] = function() + +-- 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("@rosetta/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.inflate(buf, off, len, size, dict) -- with a preset dictionary +-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) +-- local out, err = Deflate.zlib(buf) -- checks the Adler-32 +-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members +-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw +-- +-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Adler32 = __include("core/Adler32") +local Inflate = __include("codecs/compress/Deflate/Inflate") +local Compress = __include("codecs/compress/Deflate/Compress") + +local Deflate = {} + +Deflate.version = "1.1.0" + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function shrink(out: buffer, n: number): buffer + if buffer.len(out) == n then + return out + end + local b = buffer.create(n) + buffer.copy(b, 0, out, 0, n) + return b +end + +local function inflateErr(msg: string, at: number?): Err.Err + local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return Err.new(code, "inflate: " .. msg, at) +end + +-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. +-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream +-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. +-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may +-- reach into it; the result holds only the new bytes. +function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) + local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) + if not b then + return nil, aerr + end + local exact = expectedSize ~= nil + local cap + if exact then + if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize)) + end + cap = expectedSize + else + cap = math.max(1024, l * 4) + end + if dict ~= nil and type(dict) ~= "buffer" then + return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict) + if not out then + return nil, inflateErr(tostring(n), o) + end + if dict then + local d = buffer.len(dict) + n -= d + local res = buffer.create(n) + buffer.copy(res, 0, out, d, n) + out = res + end + if exact and n ~= expectedSize then + return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) + end + return shrink(out, n), consumed +end + +-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err +function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) + local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) + if not b then + return nil, aerr + end + if l < 6 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o) + end + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 ~= 8 or cmf // 16 > 7 then + return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o) + end + if (cmf * 256 + flg) % 31 ~= 0 then + return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o) + end + if bit32.band(flg, 0x20) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o) + end + local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize) + if not out then + return nil, consumed + end + if consumed + 4 > o + l then + return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed) + end + local want = bit32.byteswap(buffer.readu32(b, consumed)) + local got = Adler32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + return out, consumed + 4 +end + +-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err +local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + +-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is +-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. +function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local parts, total = {}, 0 + local p = o + repeat + if p + 18 > e then + if #parts > 0 then + break + end + return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p) + end + if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then + if #parts > 0 then + break -- trailing garbage after a member: ignored, as gzip -d does + end + return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p) + end + if buffer.readu8(b, p + 2) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) + end + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr + end + local out, consumed = Deflate.inflate(b, q, e - q) + if not out then + return nil, consumed + end + if consumed + 8 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed) + end + local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4) + local got = Crc32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + if buffer.len(out) % 4294967296 ~= isize then + return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4) + end + table.insert(parts, out) + total += buffer.len(out) + p = consumed + 8 + -- skip zero padding + local z = p + while z < e and buffer.readu8(b, z) == 0 do + z += 1 + end + if z == e then + break + end + until p >= e + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to +-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating +-- the rest or checking checksums: for sniffing compressed files cheaply. +function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q :: number, e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + +type CompressOptions = { + level: number?, -- 0 (stored) .. 9 (best); default 6 +} + +local function level(opts: CompressOptions?): number? + local lv = if opts and opts.level ~= nil then opts.level else 6 + if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then + return nil + end + return lv +end + +-- compress(buf, opts?) -> raw deflate buffer | nil, Err +function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9") + end + return Compress.raw(b, 0, buffer.len(b), lv), nil +end + +-- zlibCompress(buf, opts?) -> zlib stream | nil, Err +function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 6) + local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3 + local cmf = 0x78 + local flg = flevel * 64 + flg += 31 - (cmf * 256 + flg) % 31 + buffer.writeu8(out, 0, cmf) + buffer.writeu8(out, 1, flg) + buffer.copy(out, 2, raw, 0, n) + buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b)))) + return out, nil +end + +-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err +function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?) + local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 18) + buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0") + buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0) + buffer.writeu8(out, 9, 255) + buffer.copy(out, 10, raw, 0, n) + buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b))) + buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296) + return out, nil +end + +-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x +-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that +-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the +-- blocks' output concatenated. +function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?) + local total = 0 + for _, b in blocks do + if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then + return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range") + end + total += b.size + end + local out = buffer.create(total) + local o = 0 + for _, b in blocks do + if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then + return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset) + end + local dict: buffer? = nil + if o > 0 then + local d = math.min(o, 32768) + dict = buffer.create(d) + buffer.copy(dict :: buffer, 0, out, o - d, d) + end + local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict) + if not part then + return nil, err + end + buffer.copy(out, o, part, 0, b.size) + o += b.size + end + return out, nil +end + +-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) +Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Crc32.of(b, offset, length, crc) +end +Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number + local b = toBuffer(buf) or buffer.create(0) + return Adler32.of(b, offset, length, adler) +end + +return Deflate +end +__FILES["codecs/compress/Deflate/Compress"] = @native function() + + + +-- 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 = __include("codecs/entropy/Huffman") + +local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local WSIZE = 32768 +local HSIZE = 65536 +local MAXMATCH = 258 +local BLOCKSYMS = 16384 -- symbols per block + +-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no +-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are +-- greedy (no lazy matching). +local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } +local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } +local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } +local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } + +-- length 3..258 -> code 257..285 (index len), its extra bits and base +local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +for c = 1, 29 do + local base = LBASE[c] + local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1 + for len = base, top do + LCODE[len] = 256 + c + LEXTRA[len] = LEXT[c] + LBASEOF[len] = base + end +end +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above +local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) +for c = 1, 30 do + local base = DBASE[c] + local top = if c == 30 then 32768 else DBASE[c + 1] - 1 + for d = base, math.min(top, 256) do + DSMALL[d] = c - 1 + end + if top > 256 then + for k = math.max(base, 257), top, 128 do + DLARGE[(k - 1) // 128 + 1] = c - 1 + end + end +end +@native local function dcode(d: number): number + if d <= 256 then + return DSMALL[d] + end + return DLARGE[(d - 1) // 128 + 1] +end + +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- fixed codes +local FIXLEN = table.create(288, 0) +for i = 1, 288 do + FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8 +end +local FIXDLEN = table.create(30, 5) + +-- reversed (LSB-first) canonical codes for lengths +@native local function revCodes(lens: { number }): { number } + local codes = Huffman.codes(lens) + for i, l in lens do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return codes +end +local FIXCODE = revCodes(FIXLEN) +local FIXDCODE = revCodes(FIXDLEN) + +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ bit output +type Out = { buf: buffer, op: number, acc: number, cnt: number } + +@native local function ensure(o: Out, n: number) + if o.op + n > blen(o.buf) then + local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) + bcopy(nb, 0, o.buf, 0, o.op) + o.buf = nb + end +end + +-- put(v, n): n <= 24 bits, LSB first +@native local function put(o: Out, v: number, n: number) + local acc = o.acc + v * POW[o.cnt + 1] + local cnt = o.cnt + n + if cnt >= 8 then + ensure(o, 4) + local buf, op = o.buf, o.op + while cnt >= 8 do + local byte = acc % 256 + writeu8(buf, op, byte) + op += 1 + acc = (acc - byte) / 256 + cnt -= 8 + end + o.op = op + end + o.acc, o.cnt = acc, cnt +end + +@native local function alignOut(o: Out) + if o.cnt > 0 then + put(o, 0, 8 - o.cnt) + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) +@native local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean) + local p = s + repeat + local n = math.min(65535, e - p) + local last = final and p + n >= e + put(o, if last then 1 else 0, 3) + alignOut(o) + ensure(o, 4 + n) + writeu16(o.buf, o.op, n) + writeu16(o.buf, o.op + 2, 65535 - n) + bcopy(o.buf, o.op + 4, src, p, n) + o.op += 4 + n + p += n + until p >= e +end + +@native local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number }) + for i = 1, nsym do + local l = L[i] + if l < 256 then + put(o, lcode[l + 1], llen[l + 1]) + else + local len = l - 256 + local c = LCODE[len] + put(o, lcode[c + 1], llen[c + 1]) + local xb = LEXTRA[len] + if xb > 0 then + put(o, len - LBASEOF[len], xb) + end + local d = D[i] + local dc = dcode(d) + put(o, dcodes[dc + 1], dlen[dc + 1]) + xb = DEXT[dc + 1] + if xb > 0 then + put(o, d - DBASE[dc + 1], xb) + end + end + end + put(o, lcode[257], llen[257]) -- end of block +end + +@native local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean) + local lf = table.create(286, 0) + local df = table.create(30, 0) + local extra = 0 + for i = 1, nsym do + local l = L[i] + if l < 256 then + lf[l + 1] += 1 + else + local len = l - 256 + lf[LCODE[len] + 1] += 1 + extra += LEXTRA[len] + local dc = dcode(D[i]) + df[dc + 1] += 1 + extra += DEXT[dc + 1] + end + end + lf[257] = 1 + local llen = Huffman.lengths(lf, 15) + local dlen = Huffman.lengths(df, 15) + local hlit = 286 + while hlit > 257 and llen[hlit] == 0 do + hlit -= 1 + end + local hdist = 30 + while hdist > 1 and dlen[hdist] == 0 do + hdist -= 1 + end + if dlen[1] == 0 and hdist == 1 then + dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) + end + -- code-length symbols: RLE of the hlit + hdist lengths + local all = table.create(hlit + hdist, 0) + for i = 1, hlit do + all[i] = llen[i] + end + for i = 1, hdist do + all[hlit + i] = dlen[i] + end + local cs, cx = {}, {} -- symbol, extra value + local cf = table.create(19, 0) + local i = 1 + local total = hlit + hdist + while i <= total do + local v = all[i] + local run = 1 + while i + run <= total and all[i + run] == v do + run += 1 + end + if v == 0 and run >= 3 then + local r = math.min(run, 138) + if r >= 11 then + table.insert(cs, 18) + table.insert(cx, r - 11) + cf[19] += 1 + else + table.insert(cs, 17) + table.insert(cx, r - 3) + cf[18] += 1 + end + i += r + elseif v ~= 0 and run >= 4 then + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + local r = math.min(run - 1, 6) + table.insert(cs, 16) + table.insert(cx, r - 3) + cf[17] += 1 + i += 1 + r + else + table.insert(cs, v) + table.insert(cx, 0) + cf[v + 1] += 1 + i += 1 + end + end + local clen = Huffman.lengths(cf, 7) + local hclen = 19 + while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do + hclen -= 1 + end + -- costs in bits + local dyn = 17 + 3 * hclen + extra + for k = 1, 19 do + dyn += cf[k] * clen[k] + end + dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7 + local fix = 3 + extra + for k = 1, 286 do + dyn += lf[k] * llen[k] + fix += lf[k] * FIXLEN[k] + end + for k = 1, 30 do + dyn += df[k] * dlen[k] + fix += df[k] * 5 + end + local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 + if stored <= dyn and stored <= fix then + storedBlock(o, src, s, e, final) + return + end + if fix <= dyn then + put(o, if final then 3 else 2, 3) + emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) + return + end + put(o, if final then 5 else 4, 3) + put(o, hlit - 257, 5) + put(o, hdist - 1, 5) + put(o, hclen - 4, 4) + for k = 1, hclen do + put(o, clen[CLORDER[k] + 1], 3) + end + local ccode = revCodes(clen) + for k = 1, #cs do + local c = cs[k] + put(o, ccode[c + 1], clen[c + 1]) + if c == 16 then + put(o, cx[k], 2) + elseif c == 17 then + put(o, cx[k], 3) + elseif c == 18 then + put(o, cx[k], 7) + end + end + emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) +end + +-- ------------------------------------------------------------------------------------------------ LZ77 +local Compress = {} + +@native function Compress.raw(src: buffer, off: number, len: number, level: number): buffer + local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 } + local e = off + len + if level == 0 or len == 0 then + if len == 0 then + put(o, 3, 3) -- one empty fixed block + put(o, 0, 7) + else + storedBlock(o, src, off, e, true) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out + end + local maxChain = CHAIN[level] + local nice = NICE[level] + local good = GOOD[level] + local lazyMax = LAZY[level] + local head = table.create(HSIZE, -1) + local prev = table.create(WSIZE, -1) + local L = table.create(BLOCKSYMS, 0) + local D = table.create(BLOCKSYMS, 0) + local nsym = 0 + local blockStart = off + + @native local function hash(p: number): number + return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE + end + @native local function insert(p: number) + local h = hash(p) + 1 + prev[p % WSIZE + 1] = head[h] + head[h] = p + end + -- longest match at p among earlier positions: len (0 if < 3), dist + @native local function find(p: number, steps: number): (number, number) + local maxLen = math.min(MAXMATCH, e - p) + if maxLen < 3 then + return 0, 0 + end + local best, bestDist = 2, 0 + local c = head[hash(p) + 1] + local limit = p - WSIZE + while c >= 0 and c > limit and steps > 0 do + if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then + local k = 1 + while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do + k += 1 + end + if k > best then + best, bestDist = k, p - c + if k >= nice or k >= maxLen then + break + end + end + end + local nc = prev[c % WSIZE + 1] + if nc >= c then + break -- the slot was reused by a newer position: the chain ends here + end + c = nc + steps -= 1 + end + if best < 3 then + return 0, 0 + end + return best, bestDist + end + @native local function flush(upto: number, final: boolean) + block(o, src, blockStart, upto, L, D, nsym, final) + nsym = 0 + blockStart = upto + end + + local p = off + local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + while p < e do + local mlen, mdist = 0, 0 + if p <= stop3 then + mlen, mdist = find(p, maxChain) + insert(p) + if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then + local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain) + if l2 > mlen then + -- a literal now, the longer match from p + 1 + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + insert(p) + mlen, mdist = l2, d2 + end + end + end + if mlen >= 3 then + nsym += 1 + L[nsym] = 256 + mlen + D[nsym] = mdist + local q = p + 1 + local qe = math.min(p + mlen, stop3 + 1) + while q < qe do + insert(q) + q += 1 + end + p += mlen + else + nsym += 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p += 1 + end + if nsym >= BLOCKSYMS - 2 then + flush(p, p >= e) + end + end + if nsym > 0 or blockStart < e then + flush(e, true) + elseif blockStart == e and o.op == 0 and o.cnt == 0 then + put(o, 3, 3) + put(o, 0, 7) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out +end + +return Compress +end +__FILES["codecs/compress/Deflate/Inflate"] = @native function() + + + +-- 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 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 = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local LITBITS, DISTBITS, CLBITS = 10, 8, 7 +local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 + +-- length codes 257..285 and distance codes 0..29: base value, extra bits +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- the order code-length code lengths are sent in +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case +local LITCAP = Huffman.capacity(288, LITBITS, 15) +local DISTCAP = Huffman.capacity(32, DISTBITS, 15) +local CLCAP = Huffman.capacity(19, CLBITS, 7) + +-- fixed Huffman tables +local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) +local FLITS: number, FDISTS: number +do + local l = bcreate(288) + bfill(l, 0, 8, 144) + bfill(l, 144, 9, 112) + bfill(l, 256, 7, 24) + bfill(l, 280, 8, 8) + FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS) + local d = bcreate(30) + bfill(d, 0, 5, 30) + FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS) +end + +local Inflate = {} + +-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. +@native local function grow(out: buffer, op: number, need: number): (buffer, number) + local cap = math.max(blen(out) * 2, need, 1024) + local nb = bcreate(cap) + bcopy(nb, 0, out, 0, op) + return nb, cap +end + +-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in +-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and +-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). +-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, +-- distances may reach into it, and outLen includes it (cap does not). +-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. +@native function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) + local op = 0 + if dict then + op = blen(dict) + cap += op + end + local out = bcreate(cap) + if dict then + bcopy(out, 0, dict, 0, op) + end + local pos = start + local bitbuf, bitcnt, over = 0, 0, 0 + local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer + local clt = bcreate(CLCAP * 4) + local lens = bcreate(320) + local final = 0 + repeat + -- block header (3 bits); also up to 14 bits of a dynamic header + if bitcnt < 17 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + final = band(bitbuf, 1) + local btype = band(rshift(bitbuf, 1), 3) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + if btype == 0 then + -- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer + local k = band(bitcnt, 7) + bitcnt -= k + local real = rshift(bitcnt, 3) - over + if real < 0 then + return nil, "truncated input" + end + pos -= real + bitbuf, bitcnt, over = 0, 0, 0 + if pos + 4 > endpos then + return nil, "truncated input" + end + local n = readu16(src, pos) + if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then + return nil, "stored block length mismatch" + end + pos += 4 + if pos + n > endpos then + return nil, "truncated input" + end + if op + n > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + n) + end + bcopy(out, op, src, pos, n) + op += n + pos += n + continue + end + 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) :: buffer + end + local hlit = band(bitbuf, 31) + 257 + local hdist = band(rshift(bitbuf, 5), 31) + 1 + local hclen = band(rshift(bitbuf, 10), 15) + 4 + bitbuf = rshift(bitbuf, 14) + bitcnt -= 14 + if hlit > 286 or hdist > 30 then + return nil, "too many length or distance symbols" + end + bfill(lens, 0, 0, 19) + for i = 1, hclen do + if bitcnt < 3 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + writeu8(lens, CLORDER[i], band(bitbuf, 7)) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + end + if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then + return nil, "invalid code lengths set" + end + local total = hlit + hdist + local i = 0 + while i < total do + if bitcnt < 14 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(clt, band(bitbuf, CLMASK) * 4) + local l = band(e, 31) + if l == 0 then + return nil, "invalid code lengths set" + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 16 then + writeu8(lens, i, sym) + i += 1 + else + local rep, val + if sym == 16 then + if i == 0 then + return nil, "repeat with no first length" + end + val = readu8(lens, i - 1) + rep = 3 + band(bitbuf, 3) + bitbuf = rshift(bitbuf, 2) + bitcnt -= 2 + elseif sym == 17 then + val = 0 + rep = 3 + band(bitbuf, 7) + bitbuf = rshift(bitbuf, 3) + bitcnt -= 3 + else + val = 0 + rep = 11 + band(bitbuf, 127) + bitbuf = rshift(bitbuf, 7) + bitcnt -= 7 + end + if i + rep > total then + return nil, "too many code lengths" + end + bfill(lens, i, val, rep) + i += rep + end + end + if readu8(lens, 256) == 0 then + return nil, "missing end-of-block code" + end + lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS) + dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS) + if lsub < 0 or dsub < 0 then + return nil, "invalid literal/length or distance code set" + end + else + return nil, "invalid block type" + end + local lsmask = lshift(1, lsub) - 1 + local dsmask = lshift(1, dsub) - 1 + -- the symbol loop + while true do + if bitcnt < 15 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local e = readu32(lt, band(bitbuf, LITMASK) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid literal/length code" + end + e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid literal/length code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local sym = rshift(e, 5) + if sym < 256 then + if op >= cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + 1) + end + writeu8(out, op, sym) + op += 1 + elseif sym == 256 then + break + else + sym -= 256 + if sym > 29 then + return nil, "invalid literal/length code" + end + -- up to 5 length extra bits + a 15-bit distance code + if bitcnt < 20 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + local len = LBASE[sym] + local xb = LEXT[sym] + if xb > 0 then + len += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + e = readu32(dt, band(bitbuf, DISTMASK) * 4) + l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid distance code" + end + e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid distance code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt -= l + local dsym = rshift(e, 5) + 1 + if dsym > 30 then + return nil, "invalid distance code" + end + local dist = DBASE[dsym] + xb = DEXT[dsym] + if xb > 0 then + if bitcnt < 13 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos += nb + bitcnt += nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos += 1 + else + over += 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt += 8 + end + end + end + dist += band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt -= xb + end + if dist > op then + return nil, "invalid distance too far back" + end + if op + len > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + len) + end + local s = op - dist + if dist >= len then + if len <= 16 and op + 16 <= cap then + -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which + -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + writeu32(out, op, readu32(out, s)) + writeu32(out, op + 4, readu32(out, s + 4)) + writeu32(out, op + 8, readu32(out, s + 8)) + writeu32(out, op + 12, readu32(out, s + 12)) + elseif len <= 16 then + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, s + k)) + end + else + bcopy(out, op, out, s, len) + end + op += len + elseif dist == 1 then + bfill(out, op, readu8(out, s), len) + op += len + else + -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks + local rem = len + while rem > 0 do + local k = math.min(op - s, rem) + bcopy(out, op, out, s, k) + op += k + rem -= k + end + end + end + end + until final == 1 + local consumed = pos + over - rshift(bitcnt, 3) + if consumed > endpos then + return nil, "truncated input" + end + return out, op, consumed +end + +return Inflate +end +__FILES["codecs/compress/Explode"] = @native function() + + + +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ +-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented +-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length +-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the +-- decoder itself is new code. +-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops +-- early at maxOut bytes (MPQ sectors whose stream has no end code). +-- +-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err +-- +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Explode = {} + +local MAXBITS = 13 + +-- blast.c's tables: each byte is (count - 1) << 4 | code length +local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, + 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, + 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, + 61, 12, 45, 44, 173 } +local LENLEN = { 2, 35, 36, 53, 38, 23 } +local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } +local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } +local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } + +type Code = { count: { number }, symbol: { number } } + +-- canonical code from run-length coded lengths +@native local function construct(rep: { number }): Code + local lengths: { number } = {} + for _, b in rep do + local len = b % 16 + for _ = 0, b // 16 do + table.insert(lengths, len) + end + end + local count = table.create(MAXBITS + 1, 0) + for _, l in lengths do + count[l + 1] += 1 + end + local offs = table.create(MAXBITS + 2, 0) + for l = 1, MAXBITS do + offs[l + 2] = offs[l + 1] + count[l + 1] + end + local symbol = table.create(#lengths, 0) + for s, l in lengths do + if l ~= 0 then + offs[l + 1] += 1 + symbol[offs[l + 1]] = s - 1 + end + end + return { count = count, symbol = symbol } +end + +local LIT = construct(LITLEN) +local LEN = construct(LENLEN) +local DIST = construct(DISTLEN) + +-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err +@native function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local src: buffer = b + local p, stop = o, o + l + if l < 2 then + return nil, Err.new(Err.TRUNCATED, "implode header", 0) + end + local lit, dict = readu8(src, p), readu8(src, p + 1) + p += 2 + if lit > 1 then + return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) + end + if dict < 4 or dict > 6 then + return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) + end + local limit = maxOut or 2 ^ 30 + local cap = math.max(64, math.min(limit, l * 8)) + local out = buffer.create(cap) + local n = 0 + local bitbuf, bitcnt = 0, 0 + local truncated = false + + @native local function bits(need: number): number + while bitcnt < need do + if p >= stop then + truncated = true + return 0 + end + bitbuf += readu8(src, p) * 2 ^ bitcnt + p += 1 + bitcnt += 8 + end + local v = bitbuf % 2 ^ need + bitbuf = (bitbuf - v) / 2 ^ need + bitcnt -= need + return v + end + + @native local function decode(h: Code): number + local code, first, index = 0, 0, 0 + local count, symbol = h.count, h.symbol + for len = 1, MAXBITS do + local bit = bits(1) + if truncated then + return -1 + end + code += 1 - bit + local c = count[len + 1] + if code < first + c then + return symbol[index + code - first + 1] + end + index += c + first = (first + c) * 2 + code *= 2 + end + return -2 + end + + while n < limit do + local flag = bits(1) + if truncated then + break + end + if flag == 1 then + local sym = decode(LEN) + if sym < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad length code", p - o) + end + local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) + if truncated then + break + end + if len == 519 then + break + end + local shift = if len == 2 then 2 else dict + local d = decode(DIST) + if d < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) + end + local dist = d * 2 ^ shift + bits(shift) + 1 + if truncated then + break + end + if dist > n then + return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) + end + if n + len > limit then + len = limit - n + end + if n + len > cap then + cap = math.max(cap * 2, n + len) + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + local from = n - dist + for k = 0, len - 1 do + writeu8(out, n + k, readu8(out, from + k)) + end + n += len + else + local sym = if lit == 1 then decode(LIT) else bits(8) + if truncated then + break + end + if sym < 0 then + return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) + end + if n >= cap then + cap *= 2 + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + writeu8(out, n, sym) + n += 1 + end + end + if truncated and n < limit and not maxOut then + return nil, Err.new(Err.TRUNCATED, "no end code", l) + end + local res = buffer.create(n) + buffer.copy(res, 0, out, 0, n) + return res, nil +end + +return Explode +end +__FILES["codecs/compress/Lz4"] = @native function() + + + +-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder +-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, +-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. +-- +-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err +-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err +-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) +-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room +-- Lz4.bound(n) -- worst-case block size for n bytes +-- +-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default +-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or +-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Lz4 = {} + +type Options = { + maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28) +} + +local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len +local band, rshift = bit32.band, bit32.rshift + +local MINMATCH = 4 +local LASTLITERALS = 5 -- the last 5 bytes are always literals +local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end +local MAX_OFFSET = 65535 +local HASH_BITS = 13 +local HASH_SIZE = 2 ^ HASH_BITS + +-- ------------------------------------------------------------------------------------------------ decode +@native function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?) + local lo = histStart or d + if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then + return nil, "corrupt: bad ranges" + end + if p >= limit then + return nil, "truncated: empty block" + end + while true do + if p >= limit then + return nil, "truncated" + end + local token = readu8(src, p) + p += 1 + local lit = rshift(token, 4) + if lit == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + lit += b + end + end + if lit > 0 then + if p + lit > limit then + return nil, "truncated: literals past the end" + end + if d + lit > dstLimit then + return nil, "limit: output larger than expected" + end + bcopy(dst, d, src, p, lit) + p += lit + d += lit + end + if p >= limit then + return d, nil -- the last sequence has no match + end + if p + 2 > limit then + return nil, "truncated" + end + local off = readu16(src, p) + p += 2 + if off == 0 or d - off < lo then + return nil, "corrupt: bad match offset" + end + local ml = band(token, 15) + if ml == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p += 1 + ml += b + end + end + ml += MINMATCH + if d + ml > dstLimit then + return nil, "limit: output larger than expected" + end + local s = d - off + if off >= ml then + bcopy(dst, d, dst, s, ml) + d += ml + elseif off == 1 then + buffer.fill(dst, d, readu8(dst, s), ml) + d += ml + else + -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time + local n = ml + while n > 0 do + local c = d - s + if c > n then + c = n + end + bcopy(dst, d, dst, s, c) + d += c + n -= c + end + end + end +end + +-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be +-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. +@native function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + if outSize ~= nil then + if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize") + end + local out = bcreate(outSize) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize) + if not e then + return nil, Err.from(msg, o) + end + if e ~= outSize then + return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o) + end + return out, nil + end + local max = (opts and opts.maxBytes) or 2 ^ 28 + local size = math.min(math.max(l * 4, 256), max) + while true do + local out = bcreate(size) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size) + if e then + local res = bcreate(e) + bcopy(res, 0, out, 0, e) + return res, nil + end + if not (msg and string.sub(msg, 1, 6) == "limit:") then + return nil, Err.from(msg, o) + end + if size >= max then + return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o) + end + size = math.min(size * 4, max) + end +end + +-- ------------------------------------------------------------------------------------------------ encode +-- bound(n) -> the largest block n input bytes can produce +@native function Lz4.bound(n: number): number + return n + n // 255 + 16 +end + +-- writes a length's 255-run extension at o; returns the next offset +@native local function extend(dst: buffer, o: number, n: number): number + while n >= 255 do + writeu8(dst, o, 255) + o += 1 + n -= 255 + end + writeu8(dst, o, n) + return o + 1 +end + +-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +@native local function hash(v: number): number + local vl, vh = band(v, 0xFFFF), rshift(v, 16) + local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 + return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1 +end + +local hashTable: { number } = table.create(HASH_SIZE, -1e9) + +-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) +@native function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number + local op = d + local anchor = p + local iend = p + n + local ht = hashTable + for i = 1, HASH_SIZE do + ht[i] = -1e9 + end + if n >= MFLIMIT + 1 then + local mflimit = iend - MFLIMIT -- a match starts before this + local matchEnd = iend - LASTLITERALS -- and ends at or before this + local ip = p + local skip = 64 + while ip < mflimit do + local v = readu32(src, ip) + local h = hash(v) + local ref = ht[h] + ht[h] = ip + if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then + -- back over equal bytes before the match (into the pending literals) + while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do + ip -= 1 + ref -= 1 + end + local a = ip + MINMATCH + local bpos = ref + MINMATCH + while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do + a += 4 + bpos += 4 + end + while a < matchEnd and readu8(src, a) == readu8(src, bpos) do + a += 1 + bpos += 1 + end + local ml = a - ip + local lit = ip - anchor + local tok = op + op += 1 + local tl = if lit >= 15 then 15 else lit + if lit >= 15 then + op = extend(dst, op, lit - 15) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + writeu16(dst, op, ip - ref) + op += 2 + local m = ml - MINMATCH + local tm = if m >= 15 then 15 else m + if m >= 15 then + op = extend(dst, op, m - 15) + end + writeu8(dst, tok, tl * 16 + tm) + ip = a + anchor = ip + skip = 64 + -- index the position just before the next one (better ratio at no cost) + if ip - 2 >= p and ip - 2 < mflimit then + local w = readu32(src, ip - 2) + ht[hash(w)] = ip - 2 + end + else + ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) + skip += 1 + end + end + end + -- the last literals + local lit = iend - anchor + local tok = op + op += 1 + if lit >= 15 then + op = extend(dst, op, lit - 15) + writeu8(dst, tok, 0xF0) + else + writeu8(dst, tok, lit * 16) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op += lit + end + return op - d +end + +-- compress(src, offset?, length?) -> buffer (one block) | nil, Err +@native function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) + if not b then + return nil, aerr + end + local tmp = bcreate(Lz4.bound(l)) + local n = Lz4.encodeInto(b, o, l, tmp, 0) + local out = bcreate(n) + bcopy(out, 0, tmp, 0, n) + return out, nil +end + +return Lz4 +end +__FILES["codecs/compress/Lzh"] = @native function() + + + +-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: +-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset +-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") +-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length +-- offset prefixes, 4 KB window +-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) +-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) +-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill +-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. +-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, +-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead +-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). +-- +-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message +-- +-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes +-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. +local Huffman = __include("codecs/entropy/Huffman") + +local Lzh = {} + +local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local floor = math.floor + +-- ------------------------------------------------------------------------------------------------ bit reader +-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and +-- over counts them +type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number } + +@native local function reader(src: buffer, off: number, len: number): Reader + return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } +end + +@native local function fill(r: Reader) + while r.cnt <= 24 do + local b = 0 + if r.pos < r.limit then + b = readu8(r.src, r.pos) + r.pos += 1 + else + r.over += 8 + end + r.acc = r.acc * 256 + b + r.cnt += 8 + end +end + +@native local function peek(r: Reader, n: number): number + if r.cnt < n then + fill(r) + end + return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n +end + +@native local function skip(r: Reader, n: number) + if r.cnt < n then + fill(r) + end + r.cnt -= n + r.acc = r.acc % 2 ^ r.cnt +end + +@native local function bits(r: Reader, n: number): number + if n == 0 then + return 0 + end + local v = peek(r, n) + skip(r, n) + return v +end + +-- ------------------------------------------------------------------------------------------------ static Huffman +type Table = { tab: buffer, P: number, S: number, single: number } + +@native local function newTable(nsym: number, P: number): Table + return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } +end + +@native local function build(t: Table, lens: buffer, n: number): boolean + t.single = -1 + local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) + if S < 0 then + return false + end + t.S = S + return true +end + +@native local function decodeSym(r: Reader, t: Table): number + if t.single >= 0 then + return t.single + end + local P, S = t.P, t.S + local e = readu32(t.tab, peek(r, P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = peek(r, P + S) + e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + skip(r, l) + return rshift(e, 5) +end + +local lens = buffer.create(512) + +@native local function lengthValue(r: Reader): number + local len = bits(r, 3) + if len == 7 then + while bits(r, 1) == 1 do + len += 1 + if len > 16 then + return 17 + end + end + end + return len +end + +-- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table +@native local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean + local n = bits(r, nbits) + if n == 0 then + t.single = bits(r, nbits) + return true + end + n = math.min(n, maxN) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local l = lengthValue(r) + if l > 16 then + return false + end + writeu8(lens, i, l) + if i == special then + local z = bits(r, 2) + i += z -- zeros (already zero) + end + i += 1 + end + return build(t, lens, math.min(i, maxN)) +end + +@native local function readCodes(r: Reader, temp: Table, codes: Table): boolean + local n = bits(r, 9) + if n == 0 then + codes.single = bits(r, 9) + return true + end + n = math.min(n, 510) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local c = decodeSym(r, temp) + if c < 0 then + return false + end + if c <= 2 then + local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20 + i += count + else + if c - 2 > 16 then + return false + end + writeu8(lens, i, c - 2) + i += 1 + end + end + return build(codes, lens, n) +end + +local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } + +@native local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string? + local r = reader(src, off, len) + local obits = OFFSET_BITS[method] + local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) + local o = 0 + local remaining = 0 + while o < n do + if remaining == 0 then + remaining = bits(r, 16) + if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then + return if r.over > 0 then "truncated" else "bad Huffman table" + end + if r.over > 32 then + return "truncated" + end + if remaining == 0 then + return "empty block" + end + end + remaining -= 1 + local c = decodeSym(r, codes) + if c < 0 then + return "bad code" + end + if c < 256 then + writeu8(out, o, c) + o += 1 + else + local count = c - 256 + 3 + local p = decodeSym(r, offs) + if p < 0 then + return "bad offset code" + end + if p > 1 then + p = lshift(1, p - 1) + bits(r, p - 1) + end + local from = o - p - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ lh1 +local NUM_CODES = 314 +local NUM_NODES = NUM_CODES * 2 - 1 +local REORDER = 32 * 1024 +local FDIST = { 1, 3, 8, 12, 24, 16 } + +local offsetLookup = table.create(256, 0) +local offsetLength = table.create(64, 0) +do + local code, offset = 0, 0 + for i, count in FDIST do + local l = i - 1 + 3 + local iter = lshift(1, 8 - l) + for _ = 1, count do + for k = 0, iter - 1 do + offsetLookup[code + k + 1] = offset + end + offsetLength[offset + 1] = l + code += iter + offset += 1 + end + end +end + +@native local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + -- node arrays (0-based indexes stored at [i + 1]) + local leaf = table.create(NUM_NODES, false) + local child = table.create(NUM_NODES, 0) + local parent = table.create(NUM_NODES, 0) + local freq = table.create(NUM_NODES, 0) + local group = table.create(NUM_NODES, 0) + local leafNodes = table.create(NUM_CODES, 0) + local groups = table.create(NUM_NODES, 0) + local leader = table.create(NUM_NODES, 0) + local numGroups = 0 + @native local function initGroups() + for i = 0, NUM_NODES - 1 do + groups[i + 1] = i + end + numGroups = 0 + end + @native local function allocGroup(): number + local g = groups[numGroups + 1] + numGroups += 1 + return g + end + @native local function freeGroup(g: number) + numGroups -= 1 + groups[numGroups + 1] = g + end + initGroups() + do + local ni = NUM_NODES - 1 + local lg = allocGroup() + for i = 0, NUM_CODES - 1 do + leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg + leader[lg + 1] = ni + leafNodes[i + 1] = ni + ni -= 1 + end + local c = NUM_NODES - 1 + while ni >= 0 do + leaf[ni + 1], child[ni + 1] = false, c + parent[c + 1], parent[c] = ni, ni + freq[ni + 1] = freq[c + 1] + freq[c] + if freq[ni + 1] == freq[ni + 2] then + group[ni + 1] = group[ni + 2] + else + group[ni + 1] = allocGroup() + end + leader[group[ni + 1] + 1] = ni + ni -= 1 + c -= 2 + end + end + @native local function makeLeader(ni: number): number + local g = group[ni + 1] + local li = leader[g + 1] + if li == ni then + return ni + end + leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1] + child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1] + for _, x in { ni, li } do + if leaf[x + 1] then + leafNodes[child[x + 1] + 1] = x + else + parent[child[x + 1] + 1] = x + parent[child[x + 1]] = x + end + end + return li + end + @native local function incrementNode(ni: number) + freq[ni + 1] += 1 + if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then + leader[group[ni + 1] + 1] += 1 + if freq[ni + 1] == freq[ni] then + group[ni + 1] = group[ni] + else + group[ni + 1] = allocGroup() + leader[group[ni + 1] + 1] = ni + end + elseif freq[ni + 1] == freq[ni] then + freeGroup(group[ni + 1]) + group[ni + 1] = group[ni] + end + end + @native local function reconstruct() + -- leaves to the front, halved + local li = 0 + for i = 0, NUM_NODES - 1 do + if leaf[i + 1] then + leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2 + li += 1 + end + end + local lp = NUM_CODES - 1 + local c = NUM_NODES - 1 + local i = NUM_NODES - 1 + while i >= 0 do + while c - i < 2 do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i -= 1 + lp -= 1 + end + local f = freq[c + 1] + freq[c] + while lp >= 0 and f >= freq[lp + 1] do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i -= 1 + lp -= 1 + end + leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c + parent[c + 1], parent[c] = i, i + i -= 1 + c -= 2 + end + initGroups() + local g = allocGroup() + group[1] = g + leader[g + 1] = 0 + for k = 1, NUM_NODES - 1 do + if freq[k + 1] == freq[k] then + group[k + 1] = group[k] + else + g = allocGroup() + group[k + 1] = g + leader[g + 1] = k + end + end + end + local o = 0 + while o < n do + local ni = 0 + local guard = 0 + while not leaf[ni + 1] do + ni = child[ni + 1] - bits(r, 1) + guard += 1 + if guard > NUM_NODES or ni < 0 then + return "bad tree" + end + end + local code = child[ni + 1] + -- increment_for_code + if freq[1] >= REORDER then + reconstruct() + end + freq[1] += 1 + local x = leafNodes[code + 1] + while x ~= 0 do + x = makeLeader(x) + incrementNode(x) + x = parent[x + 1] + end + if code < 256 then + writeu8(out, o, code) + o += 1 + else + local future = peek(r, 8) + local hi = offsetLookup[future + 1] + skip(r, offsetLength[hi + 1]) + local offset = hi * 64 + bits(r, 6) + local count = code - 256 + 3 + local from = o - offset - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 +-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) +@native local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + local ring = buffer.create(2048) + buffer.fill(ring, 0, 0x20) + local rp = 2048 - 17 + local o = 0 + while o < n do + if bits(r, 1) == 1 then + local b = bits(r, 8) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o += 1 + else + local pos = bits(r, 11) + local l = bits(r, 4) + 2 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (pos + k) % 2048) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +local LZ5_INIT = buffer.create(4096) +do + local p = 0 + for i = 0, 255 do + for _ = 1, 13 do + writeu8(LZ5_INIT, p, i) + p += 1 + end + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, i) + p += 1 + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, 255 - i) + p += 1 + end + p += 128 + for _ = 1, 110 do + writeu8(LZ5_INIT, p, 0x20) + p += 1 + end +end + +@native local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string? + local ring = buffer.create(4096) + buffer.copy(ring, 0, LZ5_INIT) + local rp = 4096 - 18 + local p = off + local limit = math.min(off + len, buffer.len(src)) + local o = 0 + while o < n do + if p >= limit then + return "truncated" + end + local flags = readu8(src, p) + p += 1 + for bit = 0, 7 do + if o >= n then + break + end + if band(flags, lshift(1, bit)) ~= 0 then + if p >= limit then + return "truncated" + end + local b = readu8(src, p) + p += 1 + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o += 1 + else + if p + 2 > limit then + return "truncated" + end + local c0, c1 = readu8(src, p), readu8(src, p + 1) + p += 2 + local start = lshift(band(c1, 0xF0), 4) + c0 + local l = band(c1, 15) + 3 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (start + k) % 4096) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o += 1 + end + end + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ ARJ method 4 +@native local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string? + local r = reader(src, off, len) + @native local function prefixed(start: number, stop: number): number + local plus, pwr = 0, lshift(1, start) + local width = start + while width < stop do + if bits(r, 1) == 0 then + break + end + plus += pwr + pwr *= 2 + width += 1 + end + return (if width ~= 0 then bits(r, width) else 0) + plus + end + local o = 0 + while o < n do + local c = prefixed(0, 7) + if c == 0 then + writeu8(out, o, bits(r, 8)) + o += 1 + else + local count = c - 1 + 3 + local pos = prefixed(9, 13) + local from = o - pos - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, if from >= 0 then readu8(out, from) else 0) + o += 1 + from += 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ api +Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } + +-- decode(src, off, len, outSize, method) -> buffer | nil, message +@native function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?) + if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then + return nil, "bad arguments" + end + local out = buffer.create(outSize) + if outSize == 0 then + return out, nil + end + local err: string? + if OFFSET_BITS[method] then + err = decodeNew(src, off, len, out, outSize, method) + elseif method == "lh1" then + err = decodeLh1(src, off, len, out, outSize) + elseif method == "lzs" then + err = decodeLzs(src, off, len, out, outSize) + elseif method == "lz5" then + err = decodeLz5(src, off, len, out, outSize) + elseif method == "arj4" then + err = decodeArj4(src, off, len, out, outSize) + else + return nil, "unsupported: method " .. tostring(method) + end + if err then + return nil, err + end + return out, nil +end + +return Lzh +end +__FILES["codecs/compress/Lzma"] = function() + +-- 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("@rosetta/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 +-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) +-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) +-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) +-- +-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default +-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/compress/Lzma/Decode") +local Filters = __include("codecs/compress/Lzma/Filters") +local Crc64 = __include("codecs/compress/Lzma/Crc64") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Lzma = {} + +local DEFAULT_MAX = 2 ^ 30 + +type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} +type Props = { lc: number, lp: number, pb: number, dictSize: number? } + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function maxOf(opts: Options?): number + local m = opts and opts.maxBytes + return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX +end + +-- a decoder message -> Err +local function fail(msg: any, at: number?): Err.Err + local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 5) == "limit" then + code = Err.LIMIT + elseif string.find(s, "truncated", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, at) +end + +-- props byte -> lc, lp, pb | nil +local function propsByte(d: number): (number?, number, number) + if d >= 225 then + return nil, 0, 0 + end + return d % 9, (d // 9) % 5, d // 45 +end +Lzma.propsByte = propsByte + +-- ------------------------------------------------------------------------------------------------ LZMA +-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) +local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) + local ip, ierr = Decode.rcInit(st, b, o, e) + if not ip then + return nil, fail(ierr, o) + end + local target = if unpackSize then st.op + unpackSize else math.huge + if unpackSize and target > st.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) + end + if unpackSize and not Decode.ensure(st, target) then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + local status, res = Decode.run(st, b, ip, e, target) + if not status then + return nil, fail(res, o) + end + if unpackSize and st.op ~= target then + return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) + end + return res :: number, nil +end + +-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) + if not b then + return nil, aerr + end + local lc, lp, pb + if type(props) == "table" then + lc, lp, pb = props.lc, props.lp, props.pb + else + local pbuf = toBuffer(props) + if not pbuf or buffer.len(pbuf) < 1 then + return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") + end + lc, lp, pb = propsByte(readu8(pbuf, 0)) + if not lc then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") + end + end + if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") + end + if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") + end + local max = maxOf(opts) + local st = Decode.new(if unpackSize then unpackSize else l * 4, max) + local ok, perr = Decode.setProps(st, lc, lp, pb) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(perr)) + end + local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) + if not consumed then + return nil, err + end + return Decode.finish(st), consumed +end + +-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.alone", buf, offset, length) + if not b then + return nil, aerr + end + if l < 13 then + return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) + end + local lo, hi = readu32(b, o + 5), readu32(b, o + 9) + local size: number? = nil + if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then + if hi >= 2 ^ 21 then + return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) + end + size = hi * 4294967296 + lo + end + return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) +end + +-- ------------------------------------------------------------------------------------------------ LZMA2 +-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte +local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + local p = o + local needDict, needProps = true, true + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) + end + local c = readu8(b, p) + if c == 0 then + return p + 1, nil + end + if c == 1 or c == 2 then + if p + 3 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + if c == 1 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if p + 3 + n > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) + end + local ok, cerr = Decode.copy(st, n, b, p + 3) + if not ok then + return nil, fail(cerr, p) + end + st.remLen = 0 + p += 3 + n + elseif c >= 0x80 then + if p + 5 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 + local mode = (c // 32) % 4 + local q = p + 5 + if mode == 3 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if mode >= 2 then + if q >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) + end + local lc, lp, pb = propsByte(readu8(b, q)) + if not lc or lc + lp > 4 then + return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) + end + Decode.setProps(st, lc, lp, pb) + needProps = false + q += 1 + elseif needProps then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) + elseif mode == 1 then + Decode.resetState(st) + end + if q + psize > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) + end + local target = st.op + usize + if target > st.maxBytes then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + Decode.ensure(st, target) + local ip, ierr = Decode.rcInit(st, b, q, q + psize) + if not ip then + return nil, fail(ierr, q) + end + local status, res = Decode.run(st, b, ip, q + psize, target) + if not status then + return nil, fail(res, q) + end + if status ~= "full" or st.op ~= target then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) + end + p = q + psize + else + return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) + end + end +end + +-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) + if not b then + return nil, aerr + end + local max = maxOf(opts) + local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max) + local consumed, err = decodeLzma2(st, b, o, o + l) + if not consumed then + return nil, err + end + if type(unpackSize) == "number" and st.op ~= unpackSize then + return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) + end + return Decode.finish(st), consumed +end + +-- ------------------------------------------------------------------------------------------------ filters +-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) +Lzma.FILTER = table.freeze({ + delta = 0x03, + x86 = 0x04, + powerpc = 0x05, + ia64 = 0x06, + arm = 0x07, + armthumb = 0x08, + sparc = 0x09, + arm64 = 0x0A, + riscv = 0x0B, + lzma2 = 0x21, +}) +local BCJ: { [number]: (buffer, number, number, number) -> () } = { + [0x04] = Filters.x86, + [0x05] = Filters.powerpc, + [0x07] = Filters.arm, + [0x08] = Filters.armthumb, + [0x09] = Filters.sparc, + [0x0A] = Filters.arm64, +} + +-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the +-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) + local pb = toBuffer(props) + local plen = if pb then buffer.len(pb) else 0 + if id == 0x03 then + if plen ~= 1 then + return nil, Err.new(Err.CORRUPT, "bad delta filter properties") + end + Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) + return true, nil + end + local f = BCJ[id] + if not f then + return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) + end + local start = 0 + if plen == 4 then + start = readu32(pb :: buffer, 0) + elseif plen ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") + end + f(b, o, n, start) + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ xz +local XZ_MAGIC = "\253" .. "7zXZ\0" +local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } + +-- vli(b, p, e) -> value, next | nil +local function vli(b: buffer, p: number, e: number): (number?, number) + local v, mul = 0, 1 + for i = 0, 8 do + if p + i >= e then + return nil, p + end + local c = readu8(b, p + i) + v += (c % 128) * mul + if c < 128 then + if c == 0 and i > 0 then + return nil, p -- non-minimal encoding + end + return v, p + i + 1 + end + mul *= 128 + end + return nil, p +end +Lzma.vli = vli + +local function crc(b: buffer, o: number, n: number): number + return Crc32.raw(b, o, n) +end + +-- one xz stream at o -> next offset | nil, Err (blocks appended to st) +local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + if o + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) + end + if buffer.readstring(b, o, 6) ~= XZ_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad xz magic", o) + end + if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then + return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) + end + if crc(b, o + 6, 2) ~= readu32(b, o + 8) then + return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) + end + local check = readu8(b, o + 7) + local csize = CHECK_SIZE[check] + local p = o + 12 + local records: { { number } } = {} + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) + end + local hs = readu8(b, p) + if hs == 0 then + break -- the index + end + local hsize = (hs + 1) * 4 + if p + hsize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) + end + if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then + return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) + end + local flags = readu8(b, p + 1) + if flags % 64 >= 4 then + return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) + end + local nfilters = flags % 4 + 1 + local q = p + 2 + local he = p + hsize - 4 + local csz, usz: number? = nil, nil + if flags >= 128 or (flags // 64) % 2 == 1 then + if (flags // 64) % 2 == 1 then + local v + v, q = vli(b, q, he) + if not v or v == 0 then + return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) + end + csz = v + end + if flags >= 128 then + local v + v, q = vli(b, q, he) + if not v then + return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) + end + usz = v + end + end + local filters: { { id: number, props: buffer } } = {} + for _ = 1, nfilters do + local id, psz + id, q = vli(b, q, he) + if not id then + return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) + end + psz, q = vli(b, q, he) + if not psz or q + psz > he then + return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) + end + local pr = buffer.create(psz) + buffer.copy(pr, 0, b, q, psz) + q += psz + table.insert(filters, { id = id, props = pr }) + end + for k = q, he - 1 do + if readu8(b, k) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) + end + end + local last = filters[nfilters] + if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) + end + for k = 1, nfilters - 1 do + local id = filters[k].id + if id ~= 0x03 and not BCJ[id] then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) + end + end + -- data + local dstart = p + hsize + local ostart = st.op + local dend = if csz then dstart + csz else e + if dend > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) + end + local cend, derr = decodeLzma2(st, b, dstart, dend) + if not cend then + return nil, derr + end + if csz and cend ~= dend then + return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) + end + local un = st.op - ostart + if usz and un ~= usz then + return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) + end + for k = nfilters - 1, 1, -1 do + local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) + if not ok then + return nil, ferr + end + end + local unpadded = hsize + (cend - dstart) + csize + local pe = cend + while (pe - p) % 4 ~= 0 do + if pe >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) + end + if readu8(b, pe) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) + end + pe += 1 + end + if pe + csize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) + end + if check == 1 then + if crc(st.out, ostart, un) ~= readu32(b, pe) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) + end + elseif check == 4 then + local hi, lo = Crc64.of(st.out, ostart, un) + if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) + end + end + table.insert(records, { unpadded, un }) + p = pe + csize + end + -- index + local ip = p + local count, q = vli(b, p + 1, e) + if not count or count ~= #records then + return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) + end + for i = 1, count do + local a, u + a, q = vli(b, q, e) + if not a then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + u, q = vli(b, q, e) + if not u then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if a ~= records[i][1] or u ~= records[i][2] then + return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) + end + end + while (q - ip) % 4 ~= 0 do + if q >= e or readu8(b, q) ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) + end + q += 1 + end + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if crc(b, ip, q - ip) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) + end + q += 4 + local isize = q - ip + -- footer + if q + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) + end + if crc(b, q + 4, 6) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) + end + if (readu32(b, q + 4) + 1) * 4 ~= isize then + return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) + end + if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then + return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) + end + return q + 12, nil +end + +-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range +function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.xz", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local st = Decode.new(l * 4, maxOf(opts)) + local p = o + local nstreams = 0 + while true do + local nxt, err = xzStream(st, b, p, e) + if not nxt then + return nil, err + end + nstreams += 1 + p = nxt + -- stream padding: zero bytes in multiples of 4 + local z = p + while z < e and readu8(b, z) == 0 do + z += 1 + end + if z == e then + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + break + end + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + end + return Decode.finish(st), p +end + +-- isXz(buf, offset?) -> true when the bytes start an xz stream +function Lzma.isXz(b: buffer, o: number?): boolean + local off = o or 0 + return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC +end + +return Lzma +end +__FILES["codecs/compress/Lzma/Crc64"] = @native function() + + + +-- 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 + +local THI, TLO = table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local hi, lo = 0, n + for _ = 1, 8 do + local low = band(lo, 1) + lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) + hi = rshift(hi, 1) + if low ~= 0 then + hi = bxor(hi, 0xC96C5795) + lo = bxor(lo, 0xD7870F42) + end + end + THI[n + 1], TLO[n + 1] = hi, lo +end + +local Crc64 = {} + +-- of(buf, offset, length) -> hi, lo +@native function Crc64.of(b: buffer, o: number, n: number): (number, number) + local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF + for i = o, o + n - 1 do + local idx = band(bxor(lo, readu8(b, i)), 255) + 1 + lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) + hi = bxor(THI[idx], rshift(hi, 8)) + end + return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) +end + +return Crc64 +end +__FILES["codecs/compress/Lzma/Decode"] = @native function() + + + +-- 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. +-- +-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last +-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep +-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by +-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. +-- +-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as +-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local rshift, band = bit32.rshift, bit32.band + +-- probability offsets (u16 entries) +local IS_MATCH = 0 -- 12 states x 16 pos states +local IS_REP = 192 +local IS_REP_G0 = 204 +local IS_REP_G1 = 216 +local IS_REP_G2 = 228 +local IS_REP0_LONG = 240 -- 12 x 16 +local POS_SLOT = 432 -- 4 x 64 +local SPEC_POS = 688 -- 115 +local ALIGN = 803 -- 16 +local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 +local REP_LEN = 1333 +local LITERAL = 1847 -- 0x300 << (lc + lp) + +local TOP = 16777216 -- 2^24 + +local Decode = {} + +type State = { + out: buffer, + cap: number, + op: number, -- bytes decoded so far (the next write offset) + dictStart: number, -- the last dictionary reset: matches may not reach before it + maxBytes: number, + probs: buffer, + nprobs: number, + lc: number, + lp: number, + pb: number, + state: number, + rep0: number, + rep1: number, + rep2: number, + rep3: number, + remLen: number, -- a match cut by outEnd, finished by the next run + range: number, + code: number, +} + +-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap +@native function Decode.new(cap: number, maxBytes: number): State + local c = math.max(64, math.min(cap, maxBytes)) + return { + out = bcreate(c), + cap = c, + op = 0, + dictStart = 0, + maxBytes = maxBytes, + probs = bcreate(2), + nprobs = 0, + lc = 0, + lp = 0, + pb = 0, + state = 0, + rep0 = 0, + rep1 = 0, + rep2 = 0, + rep3 = 0, + remLen = 0, + range = 0xFFFFFFFF, + code = 0, + } +end + +-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) +@native function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) + if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then + return false, "bad lc / lp / pb" + end + st.lc, st.lp, st.pb = lc, lp, pb + local n = LITERAL + 0x300 * 2 ^ (lc + lp) + if blen(st.probs) < n * 2 then + st.probs = bcreate(n * 2) + end + st.nprobs = n + Decode.resetState(st) + return true, nil +end + +-- resetState(st): probabilities to 1/2, LZ state and reps to 0 +@native function Decode.resetState(st: State) + local p = st.probs + for i = 0, st.nprobs - 1 do + writeu16(p, i * 2, 1024) + end + st.state = 0 + st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 + st.remLen = 0 +end + +-- resetDict(st): matches may no longer reach before the current position +@native function Decode.resetDict(st: State) + st.dictStart = st.op + st.remLen = 0 +end + +-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes +@native function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) + if ip + 5 > iend then + return nil, "truncated range coder init" + end + if readu8(b, ip) ~= 0 then + return nil, "bad range coder init byte" + end + st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) + st.range = 0xFFFFFFFF + if st.code == st.range then + return nil, "bad range coder init" + end + return ip + 5, nil +end + +-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) +@native local function ensure(st: State, need: number): boolean + if need <= st.cap then + return true + end + if need > st.maxBytes then + return false + end + local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) + local nb = bcreate(c) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + st.cap = c + return true +end +Decode.ensure = ensure + +-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range +@native function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) + if not ensure(st, st.op + n) then + return false, "limit: output over maxBytes" + end + bcopy(st.out, st.op, b, ip, n) + st.op += n + return true, nil +end + +-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT +-- traces stay valid across calls; run() is not re-entrant, and never yields) +local EMPTY = bcreate(2) +local probs: buffer = EMPTY +local inb: buffer = EMPTY +local range, code, ip, iend, over = 0, 0, 0, 0, 0 + +-- decode one bit with the probability at index i +@native local function bit(i: number): number + local p = i * 2 + local prob = readu16(probs, p) + local bound = rshift(range, 11) * prob + local r + if code < bound then + range = bound + writeu16(probs, p, prob + rshift(2048 - prob, 5)) + r = 0 + else + range -= bound + code -= bound + writeu16(probs, p, prob - rshift(prob, 5)) + r = 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + return r +end + +@native local function tree(base: number, nbits: number): number + local m = 1 + for _ = 1, nbits do + m = m * 2 + bit(base + m) + end + return m - 2 ^ nbits +end + +@native local function reverse(base: number, nbits: number): number + local m = 1 + local sym = 0 + for i = 0, nbits - 1 do + local b = bit(base + m) + m = m * 2 + b + sym += b * 2 ^ i + end + return sym +end + +@native local function direct(nbits: number): number + local res = 0 + for _ = 1, nbits do + range = rshift(range, 1) + local b = 0 + if code >= range then + code -= range + b = 1 + end + res = res * 2 + b + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + return res +end + +@native local function length(base: number, posState: number): number + if bit(base) == 0 then + return tree(base + 2 + posState * 8, 3) + end + if bit(base + 1) == 0 then + return 8 + tree(base + 130 + posState * 8, 3) + end + return 16 + tree(base + 258, 8) +end + +-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end +-- marker). The range coder must have been initialised (rcInit). +@native function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) + probs = st.probs + inb = inb0 + iend = iend0 + local out = st.out + local cap = st.cap + local op = st.op + local dictStart = st.dictStart + range, code = st.range, st.code + ip = ip0 + over = 0 + local state = st.state + local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 + local lc = st.lc + local lcShift = 2 ^ (8 - lc) + local lpMask = 2 ^ st.lp - 1 + local pbMask = 2 ^ st.pb - 1 + local lcMul = 2 ^ lc + + local status: string? = nil + local msg: string? = nil + + -- a pending match from the previous call + local remLen = st.remLen + if remLen > 0 then + local n = math.min(remLen, outEnd - op) + if n > 0 then + if op + n > cap then + st.op = op + if not ensure(st, op + n) then + probs, inb = EMPTY, EMPTY + return nil, "limit: output over maxBytes" + end + out, cap = st.out, st.cap + end + local src = op - rep0 - 1 + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + op += n + remLen -= n + end + end + + while true do + if op >= outEnd then + status = "full" + break + end + if over > 0 then + msg = "truncated" + break + end + if op + 273 > cap then + st.op = op + if not ensure(st, math.min(op + 273, outEnd)) then + msg = "limit: output over maxBytes" + break + end + out, cap = st.out, st.cap + end + local pos = op - dictStart + local posState = band(pos, pbMask) + -- is match? (inlined bit) + local pidx = (IS_MATCH + state * 16 + posState) * 2 + local prob = readu16(probs, pidx) + local bound = rshift(range, 11) * prob + if code < bound then + range = bound + writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + -- literal + local prev = if op > dictStart then readu8(out, op - 1) else 0 + local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) + local sym = 1 + if state >= 7 then + local mpos = op - rep0 - 1 + local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 + repeat + local matchBit = band(rshift(matchByte, 7), 1) + matchByte *= 2 + local b = bit(base + (1 + matchBit) * 256 + sym) + sym = sym * 2 + b + if matchBit ~= b then + break + end + until sym >= 256 + end + while sym < 256 do + local p2 = (base + sym) * 2 + local pr = readu16(probs, p2) + local bd = rshift(range, 11) * pr + if code < bd then + range = bd + writeu16(probs, p2, pr + rshift(2048 - pr, 5)) + sym = sym * 2 + else + range -= bd + code -= bd + writeu16(probs, p2, pr - rshift(pr, 5)) + sym = sym * 2 + 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + writeu8(out, op, sym - 256) + op += 1 + state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 + else + range -= bound + code -= bound + writeu16(probs, pidx, prob - rshift(prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + local len + if bit(IS_REP + state) == 0 then + -- simple match + len = length(LEN, posState) + state = if state < 7 then 7 else 10 + rep3, rep2, rep1 = rep2, rep1, rep0 + local lenState = if len < 3 then len else 3 + local slot = tree(POS_SLOT + lenState * 64, 6) + if slot < 4 then + rep0 = slot + else + local nd = slot // 2 - 1 + local dist = (2 + slot % 2) * 2 ^ nd + if slot < 14 then + dist += reverse(SPEC_POS + dist - slot, nd) + else + dist += direct(nd - 4) * 16 + dist += reverse(ALIGN, 4) + end + rep0 = dist + end + if rep0 == 0xFFFFFFFF then + status = "eos" + break + end + else + if bit(IS_REP_G0 + state) == 0 then + if bit(IS_REP0_LONG + state * 16 + posState) == 0 then + -- short rep: one byte at rep0 + if op == dictStart or rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + state = if state < 7 then 9 else 11 + writeu8(out, op, readu8(out, op - rep0 - 1)) + op += 1 + continue + end + else + local dist + if bit(IS_REP_G1 + state) == 0 then + dist = rep1 + else + if bit(IS_REP_G2 + state) == 0 then + dist = rep2 + else + dist = rep3 + rep3 = rep2 + end + rep2 = rep1 + end + rep1 = rep0 + rep0 = dist + end + len = length(REP_LEN, posState) + state = if state < 7 then 8 else 11 + end + -- copy len + 2 bytes from rep0 + 1 back + if rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + local n = len + 2 + local room = outEnd - op + if n > room then + remLen = n - room + n = room + end + local src = op - rep0 - 1 + if rep0 + 1 >= n then + bcopy(out, op, out, src, n) + else + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + end + op += n + end + end + st.op = op + st.range, st.code = range, code + st.state = state + st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 + st.remLen = remLen + probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + if msg then + return nil, msg + end + if over > 0 then + return nil, "truncated" + end + return status, ip +end + +-- finish(st) -> a buffer of exactly the decoded bytes +@native function Decode.finish(st: State): buffer + if st.cap == st.op then + return st.out + end + local b = bcreate(st.op) + bcopy(b, 0, st.out, 0, st.op) + return b +end + +return Decode +end +__FILES["codecs/compress/Lzma/Filters"] = @native function() + + + +-- 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). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap + +local TWO32 = 4294967296 + +local Filters = {} + +local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } +local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } + +@native local function msbyte(b: number): boolean + return b == 0 or b == 0xFF +end + +-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) +@native function Filters.x86(b: buffer, o: number, n: number, start: number) + if n <= 4 then + return + end + local size = n - 4 + local prevPos = -1 + local prevMask = 0 + local i = 0 + while i < size do + local c = readu8(b, o + i) + if band(c, 0xFE) ~= 0xE8 then + i += 1 + continue + end + local d = i - prevPos + if d > 3 then + prevMask = 0 + else + prevMask = band(lshift(prevMask, d - 1), 7) + if prevMask ~= 0 then + local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) + if not MASK_ALLOWED[prevMask] or msbyte(bb) then + prevPos = i + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + continue + end + end + end + prevPos = i + if msbyte(readu8(b, o + i + 4)) then + local src = readu32(b, o + i + 1) + local dest + while true do + dest = (src - (start + i + 5)) % TWO32 + if prevMask == 0 then + break + end + local j = MASK_BITNUM[prevMask] * 8 + local bb = band(rshift(dest, 24 - j), 0xFF) + if not msbyte(bb) then + break + end + src = bxor(dest, 2 ^ (32 - j) - 1) + end + dest = band(dest, 0x01FFFFFF) + if band(dest, 0x01000000) ~= 0 then + dest = bor(dest, 0xFF000000) + end + writeu32(b, o + i + 1, dest) + i += 5 + else + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + end + end +end + +@native function Filters.arm(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + if readu8(b, o + i + 3) == 0xEB then + local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 + addr = (addr * 4 - (start + i + 8)) % TWO32 + addr = rshift(addr, 2) + writeu8(b, o + i, band(addr, 255)) + writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) + writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) + end + i += 4 + end +end + +@native function Filters.armthumb(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) + if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then + local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) + addr = (addr * 2 - (start + i + 4)) % TWO32 + addr = rshift(addr, 1) + writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) + writeu8(b, o + i, band(rshift(addr, 11), 255)) + writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) + writeu8(b, o + i + 2, band(addr, 255)) + i += 4 + else + i += 2 + end + end +end + +@native function Filters.powerpc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + if band(instr, 0xFC000003) == 0x48000001 then + instr = band(instr, 0x03FFFFFC) + instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) + instr = bor(instr, 0x48000001) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +@native function Filters.sparc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + local top = rshift(instr, 22) + if top == 0x100 or top == 0x1FF then + instr = (instr * 4) % TWO32 + instr = (instr - (start + i)) % TWO32 + instr = rshift(instr, 2) + instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +@native function Filters.arm64(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local pc = (start + i) % TWO32 + local instr = readu32(b, o + i) + if rshift(instr, 26) == 0x25 then + local src = instr + local p = (TWO32 - rshift(pc, 2)) % TWO32 + writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) + elseif band(instr, 0x9F000000) == 0x90000000 then + local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) + if band(src + 0x00020000, 0x001C0000) == 0 then + local p = (TWO32 - rshift(pc, 12)) % TWO32 + local dest = (src + p) % TWO32 + local v = band(instr, 0x9000001F) + v = bor(v, lshift(band(dest, 3), 29)) + v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) + v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) + writeu32(b, o + i, v) + end + end + i += 4 + end +end + +-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +@native function Filters.delta(b: buffer, o: number, n: number, dist: number) + for i = dist, n - 1 do + writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) + end +end + +return Filters +end +__FILES["codecs/compress/Lzw"] = @native function() + + + +-- 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). +-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code +-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is +-- detected by its first bytes (0x00 then an odd byte) and decoded too. +-- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only). +-- +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo") +-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer +-- local codes = Lzw.encode(data, off, len, "tiff") +-- +-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of +-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or +-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that +-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local blen = buffer.len + +local Lzw = {} + +local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) +local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) + +-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) +local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends +local suffix = buffer.create(TABLE) -- u8: its last byte +local first = buffer.create(TABLE) -- u8: its first byte +local length = buffer.create(TABLE * 2) -- u16: its length + +-- ------------------------------------------------------------------------------------------------ decode +-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) +@native local function emit(out: buffer, o: number, c: number, l: number, lim: number) + local p = o + l - 1 + if p < lim then + while p >= o do + writeu8(out, p, readu8(suffix, c)) + c = readu16(prefix, c * 2) + p -= 1 + end + else + while p >= o do + if p < lim then + writeu8(out, p, readu8(suffix, c)) + end + c = readu16(prefix, c * 2) + p -= 1 + end + end +end + +@native function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff: number, maxOut: number, variant: string, minCodeSize: number?): (number, string?) + local n = blen(src) + if off < 0 or off > n then + return 0, "corrupt" + end + local e = math.min(off + math.max(0, len), n) + local lim = math.min(outOff + math.max(0, maxOut), blen(out)) + if outOff < 0 then + return 0, "corrupt" + end + local msb = variant == "tiff" + local early = 0 -- 1 for TIFF's early change + local min = minCodeSize or 8 + local maxCodes, maxBits = MAX_CODES, 12 + if variant == "zoo" then + min, maxCodes, maxBits = 8, TABLE, 13 + end + if msb then + min = 8 + early = 1 + -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check) + if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then + msb = false + early = 0 + end + end + if min < 1 or min > 11 then + return 0, "corrupt" + end + local clear = lshift(1, min) + local eoi = clear + 1 + for i = 0, clear - 1 do + writeu16(prefix, i * 2, 0) + writeu8(suffix, i, band(i, 255)) + writeu8(first, i, band(i, 255)) + writeu16(length, i * 2, 1) + end + local size = min + 1 + local mask = lshift(1, size) - 1 + local nextc = clear + 2 + local prev = -1 + local o = outOff + local p = off + local acc, nb = 0, 0 + while true do + -- refill (at most 13 + 7 bits held: below 2^21) + while nb < size do + if p >= e then + return o - outOff, "truncated" + end + if msb then + acc = acc * 256 + readu8(src, p) + else + acc += lshift(readu8(src, p), nb) + end + p += 1 + nb += 8 + end + local c + if msb then + nb -= size + c = band(rshift(acc, nb), mask) + acc = band(acc, lshift(1, nb) - 1) + else + c = band(acc, mask) + acc = rshift(acc, size) + nb -= size + end + if c == clear then + size = min + 1 + mask = lshift(1, size) - 1 + nextc = clear + 2 + prev = -1 + elseif c == eoi then + return o - outOff, nil + else + if o >= lim then + return o - outOff, nil -- full: the rest (normally just EOI) is ignored + end + if prev < 0 then + if c >= clear then + return o - outOff, "corrupt" + end + writeu8(out, o, readu8(suffix, c)) + o += 1 + prev = c + else + local l + if c < nextc then + l = readu16(length, c * 2) + emit(out, o, c, l, lim) + if nextc < maxCodes then + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, readu8(first, c)) + writeu8(first, nextc, readu8(first, prev)) + writeu16(length, nextc * 2, readu16(length, prev * 2) + 1) + nextc += 1 + end + elseif c == nextc and nextc < maxCodes then + -- KwKwK: the new entry is prev + first(prev) + local f = readu8(first, prev) + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, f) + writeu8(first, nextc, f) + l = readu16(length, prev * 2) + 1 + writeu16(length, nextc * 2, l) + nextc += 1 + emit(out, o, c, l, lim) + else + return o - outOff, "corrupt" + end + o = math.min(o + l, lim) + prev = c + end + if nextc + early >= lshift(1, size) and size < maxBits then + size += 1 + mask = lshift(1, size) - 1 + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ encode +local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries +local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) +local hval = buffer.create(HASH * 2) -- u16 code + +-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in +-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). +@native function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer + local msb = variant == "tiff" + local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11) + local early = if msb then 1 else 0 + local symMask = lshift(1, min) - 1 + local clear = lshift(1, min) + local eoi = clear + 1 + local n = blen(data) + off = math.clamp(off, 0, n) + local e = math.clamp(off + len, off, n) + local cap = (e - off) * 2 + 64 + local out = buffer.create(cap) + local op = 0 + local acc, nb = 0, 0 + local size = min + 1 + @native local function put(code: number) + if op + 4 > cap then + cap *= 2 + local nbuf = buffer.create(cap) + buffer.copy(nbuf, 0, out, 0, op) + out = nbuf + end + if msb then + acc = acc * lshift(1, size) + code + nb += size + while nb >= 8 do + nb -= 8 + writeu8(out, op, rshift(acc, nb)) + op += 1 + acc = band(acc, lshift(1, nb) - 1) + end + else + acc += lshift(code, nb) + nb += size + while nb >= 8 do + writeu8(out, op, band(acc, 255)) + op += 1 + acc = rshift(acc, 8) + nb -= 8 + end + end + end + buffer.fill(hkey, 0, 0, HASH * 4) + local nextc = clear + 2 + put(clear) + if e > off then + local cur = band(readu8(data, off), symMask) + for i = off + 1, e - 1 do + local b = band(readu8(data, i), symMask) + local key = cur * 256 + b + 1 + local h = band(cur * 31 + b * 4099, HASH - 1) + local found = -1 + while true do + local k = buffer.readi32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu16(hval, h * 2) + break + end + h = band(h + 1, HASH - 1) + end + if found >= 0 then + cur = found + else + put(cur) + if nextc >= MAX_CODES - 2 then + put(clear) + size = min + 1 + nextc = clear + 2 + buffer.fill(hkey, 0, 0, HASH * 4) + else + buffer.writei32(hkey, h * 4, key) + writeu16(hval, h * 2, nextc) + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + cur = b + end + end + put(cur) + -- the decoder adds an entry for this last code too: its width may grow before EOI + if nextc < MAX_CODES then + nextc += 1 + if nextc + early > lshift(1, size) and size < 12 then + size += 1 + end + end + end + put(eoi) + if nb > 0 then + writeu8(out, op, if msb then band(lshift(acc, 8 - nb), 255) else band(acc, 255)) + op += 1 + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res +end + +return Lzw +end +__FILES["codecs/compress/Lzx"] = @native function() + + + +-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, +-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and +-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), +-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the +-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets +-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification +-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from +-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). +-- +-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message +-- +-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact +-- uncompressed size. Never throws: bad or truncated data returns nil, message. +local Huffman = __include("codecs/entropy/Huffman") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local writeu8, writei32 = buffer.writeu8, buffer.writei32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Lzx = {} + +local FRAME = 32768 +local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6 +local MAXMAIN = 256 + 8 * 50 +local NLEN = 249 +local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder) + +-- position slots: footer bits and base of each formatted offset slot +local EXTRA = table.create(51, 0) +local BASE = table.create(51, 0) +do + local b = 0 + for i = 0, 50 do + local e = if i < 4 then 0 else math.min(i // 2 - 1, 17) + EXTRA[i + 1] = e + BASE[i + 1] = b + b += lshift(1, e) + end +end +local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } + +-- ------------------------------------------------------------------------------------------------ bit reader +-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the +-- end, zero words are read and over counts their bits. +type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } + +@native local function refill(s: State) + while s.cnt <= 16 do + local p = s.pos + local w = 0 + if p + 2 <= s.stop then + w = readu16(s.src, p) + s.pos = p + 2 + elseif p < s.stop then + w = readu8(s.src, p) + s.pos = p + 1 + s.over += 8 + else + s.over += 16 + end + s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) + s.cnt += 16 + end +end + +-- bits(s, n) -> the next n (1..17) bits +@native local function bits(s: State, n: number): number + if s.cnt < n then + refill(s) + end + local v = rshift(s.bb, 32 - n) + s.bb = lshift(s.bb, n) + s.cnt -= n + return v +end + +-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code +@native local function sym(s: State, tab: buffer, P: number, S: number): number + if s.cnt < 16 then + refill(s) + end + local e = readu32(tab, rshift(s.bb, 32 - P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + s.bb = lshift(s.bb, l) + s.cnt -= l + return rshift(e, 5) +end + +-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +@native local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean + for i = 0, 19 do + writeu8(preLens, i, bits(s, 4)) + end + local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP) + if S < 0 then + return false + end + local cap = blen(lens) + local x = first + while x < last do + local z = sym(s, pre, PREP, S) + if z < 0 then + return false + end + if z == 17 or z == 18 then + local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20 + for _ = 1, run do + if x < cap then + writeu8(lens, x, 0) + end + x += 1 + end + elseif z == 19 then + local run = bits(s, 1) + 4 + local d = sym(s, pre, PREP, S) + if d < 0 or d > 16 then + return false + end + local v = (readu8(lens, x) - d + 17) % 17 + for _ = 1, run do + if x < cap then + writeu8(lens, x, v) + end + x += 1 + end + else + writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) + x += 1 + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ decode +-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +@native local function translate(out: buffer, n: number, size: number) + local base = 0 + local frame = 0 + while base < n and frame < 32768 do + local fs = math.min(FRAME, n - base) + if fs > 10 then + local i = base + local stop = base + fs - 10 + while i < stop do + if readu8(out, i) == 0xE8 then + local abs = readi32(out, i + 1) + if abs >= -i and abs < size then + writei32(out, i + 1, if abs >= 0 then abs - i else abs + size) + end + i += 5 + else + i += 1 + end + end + end + base += fs + frame += 1 + end +end + +@native function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) + local nslots = SLOTS[windowBits] + if not nslots then + return nil, "unsupported: LZX window 2^" .. tostring(windowBits) + end + if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad arguments" + end + local windowSize = lshift(1, windowBits) + local mainN = 256 + 8 * nslots + local out = bcreate(outSize) + local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20) + local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4) + local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4) + local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4) + local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4) + local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } + local R0: number, R1: number, R2: number = 1, 1, 1 + local intel = 0 + local started = false + local btype, bremain, bsize = 0, 0, 0 + local mainS, lenS, alignS = 0, 0, 0 + local op = 0 + while op < outSize do + local frameEnd = math.min(op + FRAME, outSize) + while op < frameEnd do + if bremain == 0 then + -- a new block + if btype == 3 and band(bsize, 1) == 1 then + s.pos += 1 + end + if not started then + started = true + if bits(s, 1) == 1 then + local hi = bits(s, 16) + intel = hi * 65536 + bits(s, 16) + end + end + btype = bits(s, 3) + local hi = bits(s, 16) + bsize = hi * 256 + bits(s, 8) + bremain = bsize + if s.over > s.cnt then + return nil, "truncated input" + end + if bsize == 0 then + return nil, "empty block" + end + if btype == 2 then + for i = 0, 7 do + writeu8(alignLens, i, bits(s, 3)) + end + alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP) + if alignS < 0 then + return nil, "bad aligned offset tree" + end + end + if btype == 1 or btype == 2 then + if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then + return nil, "bad main tree" + end + mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP) + if mainS < 0 then + return nil, "bad main tree" + end + if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then + return nil, "bad length tree" + end + lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP) + if lenS < 0 then + return nil, "bad length tree" + end + elseif btype == 3 then + -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes + local k = s.cnt % 16 + if k == 0 then + k = 16 + end + local p = s.pos - (s.cnt - k) // 8 + s.bb, s.cnt = 0, 0 + if s.over > 0 or p + 12 > s.stop then + return nil, "truncated uncompressed block" + end + R0 = readu32(src, p) + R1 = readu32(src, p + 4) + R2 = readu32(src, p + 8) + s.pos = p + 12 + else + return nil, "bad block type " .. btype + end + if s.over > s.cnt then + return nil, "truncated input" + end + end + local runEnd = op + math.min(bremain, frameEnd - op) + if btype == 3 then + local n = runEnd - op + local p = s.pos + if p + n > s.stop then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, p, n) + s.pos = p + n + op += n + bremain -= n + else + local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over + local stop = s.stop + local aligned = btype == 2 + local start = op + while op < runEnd do + -- refill to at least 17 bits + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + elseif pos < stop then + w = readu8(src, pos) + pos += 1 + over += 8 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "bad main code" + end + e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "bad main code" + end + end + bb = lshift(bb, l) + cnt -= l + local m = rshift(e, 5) + if m < 256 then + writeu8(out, op, m) + op += 1 + else + m -= 256 + local len = band(m, 7) + if len == 7 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4) + local ll = band(le, 31) + if ll == 0 then + if le == 0 then + return nil, "bad length code" + end + le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4) + ll = band(le, 31) + if ll == 0 then + return nil, "bad length code" + end + end + bb = lshift(bb, ll) + cnt -= ll + len += rshift(le, 5) + end + len += 2 + local slot = rshift(m, 3) + local dist: number + if slot == 0 then + dist = R0 + elseif slot == 1 then + dist = R1 + R1 = R0 + R0 = dist + elseif slot == 2 then + dist = R2 + R2 = R0 + R0 = dist + else + local ex = EXTRA[slot + 1] + dist = BASE[slot + 1] - 2 + if ex > 0 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + if aligned and ex >= 3 then + if ex > 3 then + dist += lshift(rshift(bb, 35 - ex), 3) + bb = lshift(bb, ex - 3) + cnt -= ex - 3 + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + end + local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4) + local al = band(ae, 31) + if al == 0 then + return nil, "bad aligned offset code" + end + bb = lshift(bb, al) + cnt -= al + dist += rshift(ae, 5) + else + dist += rshift(bb, 32 - ex) + bb = lshift(bb, ex) + cnt -= ex + end + end + R2 = R1 + R1 = R0 + R0 = dist + end + if dist < 1 or dist > op or dist > windowSize then + return nil, "match offset before the start of the data" + end + if op + len > runEnd then + return nil, "match past the end of its block or frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += len + end + end + s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over + bremain -= op - start + end + end + -- the end of a frame: realign to 16 bits + local k = s.cnt % 16 + s.bb = lshift(s.bb, k) + s.cnt -= k + if s.over > s.cnt then + return nil, "truncated input" + end + end + if intel ~= 0 then + translate(out, outSize, intel) + end + return out, nil +end + +return Lzx +end +__FILES["codecs/compress/PackBits"] = @native function() + + + +-- 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) +@native 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) +@native 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 +end +__FILES["codecs/compress/Quantum"] = @native function() + + + +-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft +-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with +-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the +-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the +-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and +-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the +-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the +-- models and the window persist across the frames of a folder. Written from the public descriptions of the format +-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. +-- +-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message +-- +-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is +-- their total. Never throws: bad or truncated data returns nil, message. + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local Quantum = {} + +-- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) +local PBASE = table.create(42, 0) +local PEXTRA = table.create(42, 0) +do + local b = 0 + for i = 0, 41 do + local e = if i < 4 then 0 else i // 2 - 1 + PEXTRA[i + 1] = e + PBASE[i + 1] = b + b += lshift(1, e) + end +end +local LEXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local LBASE = table.create(27, 0) +do + local b = 0 + for i = 1, 27 do + LBASE[i] = b + b += lshift(1, LEXTRA[i]) + end +end + +-- ------------------------------------------------------------------------------------------------ models +-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +type Model = { n: number, sym: { number }, cum: { number }, shifts: number } + +@native local function model(first: number, n: number): Model + local sym = table.create(n, 0) + local cum = table.create(n + 1, 0) + for i = 1, n do + sym[i] = first + i - 1 + cum[i] = n - i + 1 + end + cum[n + 1] = 0 + return { n = n, sym = sym, cum = cum, shifts = 4 } +end + +@native local function rescale(m: Model) + local n, sym, cum = m.n, m.sym, m.cum + m.shifts -= 1 + if m.shifts > 0 then + for i = n, 1, -1 do + local c = rshift(cum[i], 1) + if c <= cum[i + 1] then + c = cum[i + 1] + 1 + end + cum[i] = c + end + return + end + m.shifts = 50 + -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) + for i = 1, n do + cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) + end + -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) + for i = 1, n - 1 do + for j = i + 1, n do + if cum[i] < cum[j] then + cum[i], cum[j] = cum[j], cum[i] + sym[i], sym[j] = sym[j], sym[i] + end + end + end + for i = n, 1, -1 do + cum[i] += cum[i + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the coder and bit reader of one frame +type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } + +@native local function bit(c: Coder): number + if c.cnt == 0 then + local p = c.pos + if p < c.stop then + c.acc = readu8(c.src, p) + c.pos = p + 1 + else + c.acc = 0 + c.over += 1 + end + c.cnt = 8 + end + c.cnt -= 1 + return band(rshift(c.acc, c.cnt), 1) +end + +-- raw(c, n) -> the next n (0..19) bits, most significant first +@native local function raw(c: Coder, n: number): number + local v = 0 + for _ = 1, n do + v = v * 2 + bit(c) + end + return v +end + +@native local function symbol(c: Coder, m: Model): number + local cum = m.cum + local H, L, C = c.H, c.L, c.C + local range = H - L + 1 + local total = cum[1] + if range <= 0 or C < L or C > H then + -- only corrupt registers get here (the decoder keeps L <= C <= H) + c.bad = true + return 0 + end + local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) + local n = m.n + local i = 2 + while i <= n and cum[i] > f do + i += 1 + end + -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) + local s = m.sym[i - 1] + H = L + floor(cum[i - 1] * range / total) - 1 + L = L + floor(cum[i] * range / total) + for k = 1, i - 1 do + cum[k] += 8 + end + if cum[1] > 3800 then + rescale(m) + end + while true do + if band(bxor(L, H), 0x8000) ~= 0 then + if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then + -- underflow: L and H straddle the middle + C = bxor(C, 0x4000) + L = band(L, 0x3FFF) + H = bor(H, 0x4000) + else + break + end + end + L = band(lshift(L, 1), 0xFFFF) + H = bor(band(lshift(H, 1), 0xFFFF), 1) + C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) + end + c.H, c.L, c.C = H, L, C + return s +end + +@native function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) + if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then + return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) + end + if outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad output size" + end + local total = 0 + for _, b in blocks do + if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then + return nil, "bad block range" + end + total += b.size + end + if total ~= outSize then + return nil, "block sizes do not add up to the output size" + end + local window = lshift(1, windowBits) + local slots = windowBits * 2 + local selector = model(0, 7) + local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } + local m3 = model(0, math.min(slots, 24)) + local m4 = model(0, math.min(slots, 36)) + local m5 = model(0, slots) + local mlen = model(0, 27) + local out = bcreate(outSize) + local op = 0 + for _, b in blocks do + local frameEnd = op + b.size + local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } + c.C = raw(c, 16) + while op < frameEnd do + local sel = symbol(c, selector) + if c.bad then + return nil, "bad arithmetic code" + end + if sel < 4 then + writeu8(out, op, symbol(c, lit[sel + 1])) + op += 1 + else + local len, slot + if sel == 4 then + len = 3 + slot = symbol(c, m3) + elseif sel == 5 then + len = 4 + slot = symbol(c, m4) + elseif sel == 6 then + local ls = symbol(c, mlen) + len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 + slot = symbol(c, m5) + else + return nil, "bad selector" + end + local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 + if dist > op or dist > window then + return nil, "match offset before the start of the data" + end + if op + len > frameEnd then + return nil, "match past the end of its frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += len + end + if c.bad then + return nil, "bad arithmetic code" + end + if c.over > 4 then + return nil, "truncated frame" + end + end + end + return out, nil +end + +return Quantum +end +__FILES["codecs/compress/UnixCompress"] = @native function() + + + +-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code +-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are +-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the +-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width +-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder +-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked +-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read +-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws. +-- +-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file +-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local UnixCompress = {} + +type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30) +type EncodeOptions = { maxBits: number? } -- 9..16, default 16 + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local MAXCODES = 65536 +local CHECK_GAP = 10000 + +-- decoder tables (per call state lives in locals; the tables are reused: decode never yields) +local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends +local suffix = bcreate(MAXCODES) -- u8: its last byte +local first = bcreate(MAXCODES) -- u8: its first byte +local length = bcreate(MAXCODES * 4) -- u32: its length + +-- ------------------------------------------------------------------------------------------------ decode +-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err +@native function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + if n < 3 then + return nil, Err.new(Err.TRUNCATED, "header past the end", o) + end + if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then + return nil, Err.new(Err.CORRUPT, "bad magic", o) + end + local flags = readu8(b, o + 2) + local maxbits = band(flags, 0x1F) + local block = band(flags, 0x80) ~= 0 + if maxbits < 9 or maxbits > 16 then + return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2) + end + if band(flags, 0x60) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2) + end + local maxmax = lshift(1, maxbits) + for i = 0, 255 do + writeu32(prefix, i * 4, 0) + writeu8(suffix, i, i) + writeu8(first, i, i) + writeu32(length, i * 4, 1) + end + local cap = math.min(math.max(n * 3, 1024), maxBytes) + local out = bcreate(cap) + local op = 0 + local totalBits = (n - 3) * 8 + local base = o + 3 + local pos = 0 -- bit position from the first code + local gbase = 0 -- where the current group sequence starts + local nbits = 9 + local mask = 511 + local maxcode = 511 + local freeEnt = if block then 257 else 256 + local prev = -1 + while pos + nbits <= totalBits do + if freeEnt > maxcode then + local g = nbits * 8 + pos = gbase + (pos - gbase + g - 1) // g * g + gbase = pos + nbits += 1 + maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1 + mask = lshift(1, nbits) - 1 + continue + end + -- the code: up to 23 bits from three bytes + local q = base + rshift(pos, 3) + local acc = readu8(b, q) + if q + 1 < o + n then + acc = bor(acc, lshift(readu8(b, q + 1), 8)) + end + if q + 2 < o + n then + acc = bor(acc, lshift(readu8(b, q + 2), 16)) + end + local c = band(rshift(acc, band(pos, 7)), mask) + pos += nbits + if c == 256 and block then + local g = nbits * 8 + pos = gbase + (pos - gbase + g - 1) // g * g + gbase = pos + nbits = 9 + mask = 511 + maxcode = 511 + freeEnt = 257 + prev = -1 + continue + end + local l + if prev < 0 then + if c >= 256 then + return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3)) + end + l = 1 + elseif c < freeEnt then + l = readu32(length, c * 4) + elseif c == freeEnt then + l = readu32(length, prev * 4) + 1 + else + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + if op + l > cap then + if op + l > maxBytes then + return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes") + end + local ncap = math.min(math.max(cap * 2, op + l), maxBytes) + local nb = bcreate(ncap) + bcopy(nb, 0, out, 0, op) + out, cap = nb, ncap + end + -- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it + if prev >= 0 and freeEnt < maxmax then + local f = if c == freeEnt then readu8(first, prev) else readu8(first, c) + writeu32(prefix, freeEnt * 4, prev) + writeu8(suffix, freeEnt, f) + writeu8(first, freeEnt, readu8(first, prev)) + writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1) + freeEnt += 1 + elseif prev >= 0 then + if c == freeEnt then + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + end + local p = op + l - 1 + local k = c + while p >= op do + writeu8(out, p, readu8(suffix, k)) + k = readu32(prefix, k * 4) + p -= 1 + end + op += l + prev = c + end + local res = bcreate(op) + bcopy(res, 0, out, 0, op) + return res, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries +local hkey = bcreate(HSIZE * 4) +local hval = bcreate(HSIZE * 4) + +-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err +@native function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) + if not b then + return nil, aerr + end + local maxbits = (opts and opts.maxBits) or 16 + if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxBits must be 9..16") + end + -- at most 17 bits per input byte, plus group padding (< one group per width change / clear) + local cap = 3 + n * 2 + 64 + local out = bcreate(cap) + writeu8(out, 0, 0x1F) + writeu8(out, 1, 0x9D) + writeu8(out, 2, bor(maxbits, 0x80)) + local outbits = 24 + local boff = 24 + local acc, nb = 0, 0 -- pending bits not yet written (below 2^24) + local nbits = 9 + local extcode = 513 + local maxmax = lshift(1, maxbits) + local stcode = true + local freeEnt = 257 + local ratio = 0 + local checkpoint = CHECK_GAP + buffer.fill(hkey, 0, 0, HSIZE * 4) + @native local function put(code: number) + acc = bor(acc, lshift(code, nb)) + nb += nbits + outbits += nbits + while nb >= 8 do + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + acc = rshift(acc, 8) + nb -= 8 + end + end + @native local function align() + -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros + local g = nbits * 8 + local nbits2 = boff + (outbits - boff + g - 1) // g * g + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + acc, nb = 0, 0 + outbits = nbits2 + boff = nbits2 + end + if n == 0 then + local res = bcreate(3) + bcopy(res, 0, out, 0, 3) + return res, nil + end + local ent = readu8(b, o) + local e = o + n + local i = o + 1 + -- checks happen with a one-byte current string, right after an output (and at the start) + @native local function checks(consumed: number) + if freeEnt >= extcode then + if nbits < maxbits then + align() + nbits += 1 + extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits) + else + extcode = math.huge + stcode = false + end + end + if not stcode and consumed >= checkpoint then + checkpoint = consumed + CHECK_GAP + local outBytes = rshift(outbits, 3) + local rat + if consumed > 0x7FFFFF then + local d = rshift(outBytes, 8) + rat = if d == 0 then 0x7FFFFFFF else consumed // d + else + rat = (consumed * 256) // outBytes + end + if rat >= ratio then + ratio = rat + else + ratio = 0 + buffer.fill(hkey, 0, 0, HSIZE * 4) + put(256) + align() + nbits = 9 + extcode = 513 + freeEnt = 257 + stcode = true + end + end + end + checks(1) + while i < e do + local c = readu8(b, i) + i += 1 + local key = ent * 256 + c + 1 + local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1) + local found = -1 + while true do + local k = readu32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu32(hval, h * 4) + break + end + h = band(h + 1, HSIZE - 1) + end + if found >= 0 then + ent = found + else + put(ent) + if stcode then + writeu32(hkey, h * 4, key) + writeu32(hval, h * 4, freeEnt) + freeEnt += 1 + end + ent = c + checks(i - o) + end + if rshift(outbits, 3) + 8 > cap then + -- grow (rare: only incompressible input passes 2 bytes per byte) + local ncap = cap * 2 + local nbuf = bcreate(ncap) + bcopy(nbuf, 0, out, 0, cap) + out, cap = nbuf, ncap + end + end + put(ent) + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + local size = rshift(outbits + 7, 3) + local res = bcreate(size) + bcopy(res, 0, out, 0, math.min(size, cap)) + return res, nil +end + +-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file +@native function UnixCompress.isCompress(b: buffer, o: number?): boolean + local p = o or 0 + return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D +end + +return UnixCompress +end +__FILES["codecs/compress/Xxh32"] = @native function() + + + +-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content +-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. +-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). +-- +-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +local Xxh32 = {} + +local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 +local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 + +-- a * b mod 2^32 (a, b below 2^32) +@native local function mul(a: number, b: number): number + local a0 = a % 65536 + local a1 = (a - a0) / 65536 + return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 +end + +@native local function rotl(x: number, r: number): number + return bor(lshift(x, r), rshift(x, 32 - r)) +end + +@native local function round(acc: number, lane: number): number + return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) +end + +-- hash(buf, offset?, length?, seed?) -> XXH32 +@native function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number + local n0 = buffer.len(b) + local o = math.clamp(offset or 0, 0, n0) + local n = math.clamp(length or (n0 - o), 0, n0 - o) + local s = (seed or 0) % T32 + local p = o + local e = o + n + local h + if n >= 16 then + local v1 = (s + P1 + P2) % T32 + local v2 = (s + P2) % T32 + local v3 = s + local v4 = (s - P1) % T32 + local last = e - 16 + while p <= last do + v1 = round(v1, readu32(b, p)) + v2 = round(v2, readu32(b, p + 4)) + v3 = round(v3, readu32(b, p + 8)) + v4 = round(v4, readu32(b, p + 12)) + p += 16 + end + h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32 + else + h = (s + P5) % T32 + end + h = (h + n) % T32 + while p + 4 <= e do + h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4) + p += 4 + end + while p < e do + h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) + p += 1 + end + h = mul(bxor(h, rshift(h, 15)), P2) + h = mul(bxor(h, rshift(h, 13)), P3) + return bxor(h, rshift(h, 16)) +end + +return Xxh32 +end +__FILES["codecs/compress/Zstd"] = function() + +-- 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("@rosetta/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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Zstd/Decode") + +local Zstd = {} + +type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + verify: boolean?, -- check the content checksum when a frame has one (default true) +} + +-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) +Zstd.MAGIC = "\40\181\47\253" + +-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there +function Zstd.isFrame(buf: buffer, offset: number?): boolean + local o = offset or 0 + if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then + return false + end + local m = buffer.readu32(buf, o) + return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 +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, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) + if not b then + return nil, aerr + end + 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)) + end + 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.from(consumed, at, len) + end + if buffer.len(out) ~= len then + local r = buffer.create(len) + buffer.copy(r, 0, out, 0, len) + out = r + end + return out, consumed +end + +-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves +function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) + local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + return Decode.hash(buf, o, l) +end + +return Zstd +end +__FILES["codecs/compress/Zstd/Decode"] = @native function() + + + +-- 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). +-- +-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's +-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at +-- 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 = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local MAGIC = 0xFD2FB528 +local BLOCK_MAX = 131072 + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ tables +-- literal length / match length codes: baseline, extra bits (index = code + 1) +local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } +local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } +local ML_BASE = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, +} +local ML_BITS = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } +local ML_DEFAULT = { + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, +} +local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } + +-- highest set bit of 1..2048 +local HB = table.create(2048, 0) +do + local v = 0 + for i = 1, 2048 do + if i >= lshift(2, v) then + v += 1 + end + HB[i] = v + end +end + +-- ------------------------------------------------------------------------------------------------ bit readers +-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros +@native local function peek(b: buffer, s: number, o: number, n: number): number + if n <= 0 then + return 0 + end + local lo = o - n + if lo >= 0 then + local byte = s + rshift(lo, 3) + local bl = blen(b) + if byte + 4 <= bl then + return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) + end + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < bl then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) + end + if o <= 0 then + return 0 + end + return lshift(peek(b, s, o, o), -lo) +end + +-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty +@native local function streamBits(b: buffer, s: number, e: number): number + if e <= s then + return -1 + end + local last = readu8(b, e - 1) + if last == 0 then + return -1 + end + return (e - 1 - s) * 8 + HB[last] +end + +-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros +@native local function getF(b: buffer, p: number, e: number, bp: number, n: number): number + local byte = p + rshift(bp, 3) + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < e then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ FSE +-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 +local symTmp = bcreate(512) + +-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +@native local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) + local size = lshift(1, al) + local high = size - 1 + local next = table.create(nsym, 0) + for s = 0, nsym - 1 do + local c = norm[s + 1] + if c == -1 then + if high < 0 then + return nil, "bad FSE distribution" + end + writeu8(symTmp, high, s) + high -= 1 + next[s + 1] = 1 + else + next[s + 1] = c + end + end + local pos = 0 + local step = rshift(size, 1) + rshift(size, 3) + 3 + local mask = size - 1 + for s = 0, nsym - 1 do + local c = norm[s + 1] + for _ = 1, c do + writeu8(symTmp, pos, s) + local guard = 0 + repeat + pos = band(pos + step, mask) + guard += 1 + until pos <= high or guard > size + if guard > size then + return nil, "bad FSE distribution" + end + end + end + if pos ~= 0 then + return nil, "bad FSE distribution" + end + for u = 0, size - 1 do + local s = readu8(symTmp, u) + local ns = next[s + 1] + if ns < 1 or ns > 2048 then + return nil, "bad FSE distribution" + end + next[s + 1] = ns + 1 + local nb = al - HB[ns] + if nb < 0 then + return nil, "bad FSE distribution" + end + writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) + end + return true, nil +end + +-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description +@native local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) + if p >= e then + return nil, "truncated FSE table" + end + local al = getF(b, p, e, 0, 4) + 5 + if al > maxAL then + return nil, "FSE accuracy log too large" + end + local bp = 4 + local remaining = lshift(1, al) + 1 + local threshold = lshift(1, al) + local nbBits = al + 1 + local sym = 0 + local prev0 = false + while remaining > 1 and sym <= maxSym do + if prev0 then + local n0 = sym + while true do + local v = getF(b, p, e, bp, 2) + bp += 2 + if v == 3 then + n0 += 3 + if n0 > maxSym or bp > (e - p) * 8 then + return nil, "bad FSE table" + end + else + n0 += v + break + end + end + if n0 > maxSym then + return nil, "bad FSE table" + end + while sym < n0 do + norm[sym + 1] = 0 + sym += 1 + end + end + local max = 2 * threshold - 1 - remaining + local count + local low = getF(b, p, e, bp, nbBits - 1) + if low < max then + count = low + bp += nbBits - 1 + else + count = getF(b, p, e, bp, nbBits) + if count >= threshold then + count -= max + end + bp += nbBits + end + count -= 1 + remaining -= if count < 0 then -count else count + if remaining < 1 then + return nil, "bad FSE table" + end + norm[sym + 1] = count + sym += 1 + prev0 = count == 0 + while remaining < threshold do + nbBits -= 1 + threshold = rshift(threshold, 1) + end + end + if remaining ~= 1 then + return nil, "bad FSE table" + end + local used = rshift(bp + 7, 3) + if p + used > e then + return nil, "truncated FSE table" + end + for s = sym, maxSym do + norm[s + 1] = 0 + end + return al, used, sym +end + +@native local function predefined(dist: { number }, al: number): buffer + local t = bcreate(lshift(1, al) * 4) + buildFse(dist, #dist, al, t) + return t +end +local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) + +-- ------------------------------------------------------------------------------------------------ Huffman +-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +local weights = bcreate(256) +local wfse = bcreate(64 * 4) +@native local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) + if p >= e then + return nil, "truncated Huffman table" + end + local hdr = readu8(b, p) + local n = 0 + local used + if hdr >= 128 then + n = hdr - 127 + used = 1 + rshift(n + 1, 1) + if p + used > e then + return nil, "truncated Huffman table" + end + for i = 0, n - 1 do + local byte = readu8(b, p + 1 + rshift(i, 1)) + writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15)) + end + else + used = 1 + hdr + if p + used > e then + return nil, "truncated Huffman table" + end + local q, qe = p + 1, p + 1 + hdr + local norm = st.norm + local al, nb = ncount(b, q, qe, 255, 6, norm) + if not al then + return nil, nb + end + local ok, msg = buildFse(norm, 256, al, wfse) + if not ok then + return nil, msg + end + local ss = q + nb + local off = streamBits(b, ss, qe) + if off < 0 then + return nil, "bad Huffman weight stream" + end + local s1 = peek(b, ss, off, al) + off -= al + local s2 = peek(b, ss, off, al) + off -= al + while true do + if n > 254 then + return nil, "too many Huffman weights" + end + local e1 = readu32(wfse, s1 * 4) + writeu8(weights, n, band(e1, 255)) + n += 1 + local k = band(rshift(e1, 8), 255) + s1 = rshift(e1, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) + n += 1 + break + end + local e2 = readu32(wfse, s2 * 4) + writeu8(weights, n, band(e2, 255)) + n += 1 + k = band(rshift(e2, 8), 255) + s2 = rshift(e2, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) + n += 1 + break + end + end + end + -- the last weight is implied: the total must reach the next power of two + local total = 0 + for i = 0, n - 1 do + local w = readu8(weights, i) + if w > 11 then + return nil, "bad Huffman weight" + end + if w > 0 then + total += lshift(1, w - 1) + end + end + if total == 0 or total >= 2048 then + return nil, "bad Huffman weights" + end + local maxBits = HB[total] + 1 + local rest = lshift(1, maxBits) - total + if band(rest, rest - 1) ~= 0 then + return nil, "bad Huffman weights" + end + writeu8(weights, n, HB[rest] + 1) + local nsym = n + 1 + -- codes: the longest first, in symbol order within a length + local rankCount = table.create(13, 0) + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + rankCount[bits + 1] += 1 + end + end + local rankIdx = table.create(13, 0) + rankIdx[maxBits + 1] = 0 + for i = maxBits, 1, -1 do + rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) + end + if rankIdx[1] ~= lshift(1, maxBits) then + return nil, "bad Huffman weights" + end + local t = st.huf + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + local code = rankIdx[bits + 1] + local len = lshift(1, maxBits - bits) + local v = i + bits * 256 + for k = code, code + len - 1 do + writeu16(t, k * 2, v) + end + rankIdx[bits + 1] = code + len + end + end + st.hufBits = maxBits + return used, nil +end + +-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message +@native local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? + local off = streamBits(b, s, e) + if off < 0 then + return "bad Huffman stream" + end + local mmask = lshift(1, mb) - 1 + local fastEnd = blen(b) - 4 + for k = dp, dp + cnt - 1 do + local lo = off - mb + local idx + if lo >= 0 then + local byte = s + rshift(lo, 3) + if byte <= fastEnd then + idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) + else + idx = peek(b, s, off, mb) + end + else + idx = peek(b, s, off, mb) + end + local v = readu16(t, idx * 2) + writeu8(lit, k, v) + off -= rshift(v, 8) + end + if off ~= 0 then + return "Huffman stream size mismatch" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ frames +-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) +@native local function grow(st: any, need: number): boolean + if need > st.maxBytes then + return false + end + local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) + local nb = bcreate(cap) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + return true +end + +-- a compressed block [p, e): nil (ok) | code, message +@native local function block(b: buffer, p: number, e: number, st: any): (string?, string?) + -- literals section + local b0 = readu8(b, p) + local ltype = band(b0, 3) + local sf = band(rshift(b0, 2), 3) + local regen + local litSrc, litPos + local lit = st.lit + if ltype <= 1 then + if sf == 0 or sf == 2 then + regen = rshift(b0, 3) + p += 1 + elseif sf == 1 then + if p + 2 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + p += 2 + else + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 + p += 3 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if ltype == 0 then + if p + regen > e then + return "TRUNCATED", "truncated raw literals" + end + litSrc, litPos = b, p + p += regen + else + if p + 1 > e then + return "TRUNCATED", "truncated RLE literals" + end + bfill(lit, 0, readu8(b, p), regen) + litSrc, litPos = lit, 0 + p += 1 + end + else + local csize + if sf <= 1 then + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 + regen = band(rshift(v, 4), 0x3FF) + csize = band(rshift(v, 14), 0x3FF) + p += 3 + elseif sf == 2 then + if p + 4 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFF) + csize = rshift(v, 18) + p += 4 + else + if p + 5 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFFF) + csize = rshift(v, 22) + readu8(b, p + 4) * 1024 + p += 5 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if p + csize > e then + return "TRUNCATED", "truncated compressed literals" + end + local hs, he = p, p + csize + p = he + if ltype == 2 then + local used, herr = hufTable(b, hs, he, st) + if not used then + return "CORRUPT", herr + end + hs += used + elseif not st.hufBits then + return "CORRUPT", "treeless literals without a previous Huffman table" + end + local t, mb = st.huf, st.hufBits + if sf == 0 then + local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) + if herr then + return "CORRUPT", herr + end + else + if hs + 6 > he then + return "CORRUPT", "truncated jump table" + end + local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) + local s1 = hs + 6 + local s2 = s1 + l1 + local s3 = s2 + l2 + local s4 = s3 + l3 + if s4 > he then + return "CORRUPT", "bad jump table" + end + local seg = rshift(regen + 3, 2) + local last = regen - 3 * seg + if last < 0 then + return "CORRUPT", "bad 4-stream literals size" + end + local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) + or hufStream(b, s2, s3, t, mb, lit, seg, seg) + or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) + or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) + if herr then + return "CORRUPT", herr + end + end + litSrc, litPos = lit, 0 + end + + -- sequences section header + if p >= e then + return "TRUNCATED", "missing sequences header" + end + local nbSeq = readu8(b, p) + p += 1 + if nbSeq >= 128 then + if nbSeq == 255 then + if p + 2 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = readu16(b, p) + 0x7F00 + p += 2 + else + if p + 1 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = (nbSeq - 128) * 256 + readu8(b, p) + p += 1 + end + end + local op = st.op + if nbSeq == 0 then + if p ~= e then + return "CORRUPT", "data after an empty sequences section" + end + if op + regen > blen(st.out) then + if not grow(st, op + regen) then + return "LIMIT", "output over the size limit" + end + end + bcopy(st.out, op, litSrc, litPos, regen) + st.op = op + regen + return nil, nil + end + if p >= e then + return "TRUNCATED", "missing compression modes" + end + local modes = readu8(b, p) + p += 1 + if band(modes, 3) ~= 0 then + return "CORRUPT", "reserved bits set in compression modes" + end + -- the three tables, in the order LL, OF, ML + local tabs = st.tabs + for k = 1, 3 do + local mode = band(rshift(modes, 8 - 2 * k), 3) + local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52 + local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9 + if mode == 0 then + tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE + tabs[k + 3] = if k == 2 then 5 else 6 + elseif mode == 1 then + if p >= e then + return "TRUNCATED", "truncated RLE table" + end + local sym = readu8(b, p) + p += 1 + if sym > maxSym then + return "CORRUPT", "bad RLE symbol" + end + local t = st.rle[k] + writeu32(t, 0, sym) + tabs[k] = t + tabs[k + 3] = 0 + elseif mode == 2 then + local norm = st.norm + local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) + if not al then + return "CORRUPT", used + end + p += used + local t = st.dyn[k] + local ok, msg = buildFse(norm, nsym :: number, al, t) + if not ok then + return "CORRUPT", msg + end + tabs[k] = t + tabs[k + 3] = al + else + if not tabs[k] then + return "CORRUPT", "repeated table without a previous one" + end + end + end + local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer + local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number + + -- the sequences bitstream + local s = p + local off = streamBits(b, s, e) + if off < 0 then + return "CORRUPT", "bad sequences bitstream" + end + local llS = peek(b, s, off, llAL) + off -= llAL + local ofS = peek(b, s, off, ofAL) + off -= ofAL + local mlS = peek(b, s, off, mlAL) + off -= mlAL + local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 + local out = st.out + local cap = blen(out) + local frameStart = st.frameStart + local lp, litEnd = litPos, litPos + regen + local fastEnd = blen(b) - 4 + for i = 1, nbSeq do + local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) + local ofCode = band(ofE, 255) + local mlCode = band(mlE, 255) + 1 + local llCode = band(llE, 255) + 1 + -- offset bits, then match length bits, then literal length bits + local ofv + if ofCode > 24 then + local hiN = ofCode - 24 + local hi = peek(b, s, off, hiN) + off -= hiN + ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) + off -= 24 + elseif ofCode > 0 then + local lo = off - ofCode + local v + if lo >= 0 and s + rshift(lo, 3) <= fastEnd then + v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) + else + v = peek(b, s, off, ofCode) + end + off = lo + ofv = lshift(1, ofCode) + v + else + ofv = 1 + end + local ml = ML_BASE[mlCode] + local nb = ML_BITS[mlCode] + if nb > 0 then + ml += peek(b, s, off, nb) + off -= nb + end + local ll = LL_BASE[llCode] + nb = LL_BITS[llCode] + if nb > 0 then + ll += peek(b, s, off, nb) + off -= nb + end + -- repeat offsets + local offset + if ofv > 3 then + offset = ofv - 3 + rep3 = rep2 + rep2 = rep1 + rep1 = offset + else + local idx = ofv - 1 + if ll == 0 then + idx += 1 + end + if idx == 0 then + offset = rep1 + else + if idx == 1 then + offset = rep2 + elseif idx == 2 then + offset = rep3 + else + offset = rep1 - 1 + end + if idx > 1 then + rep3 = rep2 + end + rep2 = rep1 + rep1 = offset + end + end + -- state updates (not after the last sequence): LL, ML, OF + if i < nbSeq then + nb = band(rshift(llE, 8), 255) + llS = rshift(llE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(mlE, 8), 255) + mlS = rshift(mlE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(ofE, 8), 255) + ofS = rshift(ofE, 16) + peek(b, s, off, nb) + off -= nb + end + -- execute + if lp + ll > litEnd then + return "CORRUPT", "literal length past the literals" + end + local need = op + ll + ml + if need > cap then + st.op = op + if not grow(st, need) then + return "LIMIT", "output over the size limit" + end + out = st.out + cap = blen(out) + end + if ll > 0 then + bcopy(out, op, litSrc, lp, ll) + op += ll + lp += ll + end + if offset > op - frameStart or offset < 1 then + return "CORRUPT", "match offset before the frame start" + end + local from = op - offset + if offset >= ml then + bcopy(out, op, out, from, ml) + op += ml + elseif offset == 1 then + bfill(out, op, readu8(out, from), ml) + op += ml + else + -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) + local left = ml + while left > 0 do + local n = if left < offset then left else offset + bcopy(out, op, out, from, n) + op += n + from += n + left -= n + end + end + end + if off ~= 0 then + return "CORRUPT", "sequences bitstream size mismatch" + end + local rest = litEnd - lp + if rest > 0 then + if op + rest > cap then + st.op = op + if not grow(st, op + rest) then + return "LIMIT", "output over the size limit" + end + out = st.out + end + bcopy(out, op, litSrc, lp, rest) + op += rest + end + st.op = op + st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 + return nil, nil +end + +-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset +@native function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) + local st: any = { + out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), + op = 0, + maxBytes = maxBytes, + lit = bcreate(BLOCK_MAX + 64), + huf = bcreate(2048 * 2), + hufBits = nil, + norm = table.create(256, 0), + tabs = {}, + rle = { bcreate(4), bcreate(4), bcreate(4) }, + dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, + frameStart = 0, + rep1 = 1, + rep2 = 4, + rep3 = 8, + } + local pos = start + local frames = 0 + if stop - start < 4 then + return nil, "TRUNCATED", "not a zstd stream (too short)", start + end + while pos < stop do + if pos + 4 > stop then + return nil, "TRUNCATED", "truncated frame magic", pos + end + local magic = readu32(b, pos) + if band(magic, 0xFFFFFFF0) == 0x184D2A50 then + if pos + 8 > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + local size = readu32(b, pos + 4) + if pos + 8 + size > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + pos += 8 + size + frames += 1 + continue + end + if magic ~= MAGIC then + return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos + end + pos += 4 + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local fhd = readu8(b, pos) + pos += 1 + local fcsFlag = rshift(fhd, 6) + local single = band(fhd, 0x20) ~= 0 + if band(fhd, 8) ~= 0 then + return nil, "CORRUPT", "reserved frame header bit set", pos - 1 + end + local checksum = band(fhd, 4) ~= 0 + local didFlag = band(fhd, 3) + local didSize = if didFlag == 3 then 4 else didFlag + local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag) + local hsize = (if single then 0 else 1) + didSize + fcsSize + if pos + hsize > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local windowSize = 0 + if not single then + local wd = readu8(b, pos) + pos += 1 + local wlog = 10 + rshift(wd, 3) + if wlog > 41 then + return nil, "CORRUPT", "bad window size", pos - 1 + end + local base = 2 ^ wlog + windowSize = base + base / 8 * band(wd, 7) + end + local did = 0 + if didSize == 1 then + did = readu8(b, pos) + elseif didSize == 2 then + did = readu16(b, pos) + elseif didSize == 4 then + did = readu32(b, pos) + end + pos += didSize + if did ~= 0 then + return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize + end + local fcs = -1 + if fcsSize == 1 then + fcs = readu8(b, pos) + elseif fcsSize == 2 then + fcs = readu16(b, pos) + 256 + elseif fcsSize == 4 then + fcs = readu32(b, pos) + elseif fcsSize == 8 then + fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 + end + pos += fcsSize + if single then + windowSize = fcs + end + local blockMax = math.min(windowSize, BLOCK_MAX) + local frameStart = st.op + if fcs >= 0 then + if frameStart + fcs > st.maxBytes then + return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos + end + if frameStart + fcs > blen(st.out) then + grow(st, frameStart + fcs) + end + end + st.frameStart = frameStart + st.rep1, st.rep2, st.rep3 = 1, 4, 8 + st.hufBits = nil + table.clear(st.tabs) + -- blocks + local last = false + repeat + if pos + 3 > stop then + return nil, "TRUNCATED", "truncated block header", pos + end + local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 + last = band(bh, 1) ~= 0 + local btype = band(rshift(bh, 1), 3) + local bsize = rshift(bh, 3) + pos += 3 + if bsize > blockMax then + return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 + end + if btype == 0 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated raw block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bcopy(st.out, st.op, b, pos, bsize) + st.op += bsize + pos += bsize + elseif btype == 1 then + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated RLE block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bfill(st.out, st.op, readu8(b, pos), bsize) + st.op += bsize + pos += 1 + elseif btype == 2 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated compressed block", pos + end + if bsize == 0 then + return nil, "CORRUPT", "empty compressed block", pos + end + local code, msg = block(b, pos, pos + bsize, st) + if code then + return nil, code, msg, pos + end + pos += bsize + else + return nil, "CORRUPT", "reserved block type", pos - 3 + end + until last + local size = st.op - frameStart + if fcs >= 0 and size ~= fcs then + return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos + end + if checksum then + if pos + 4 > stop then + return nil, "TRUNCATED", "missing content checksum", pos + end + if verify then + local _, lo = Xxh64.hash(st.out, frameStart, size) + local want = readu32(b, pos) + if lo ~= want then + return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos + end + end + pos += 4 + end + frames += 1 + end + return st.out, st.op, pos +end + +Decode.hash = Xxh64.hash + +return Decode +end +__FILES["codecs/compress/Zstd/Xxh64"] = @native function() + + + +-- 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). +local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 + +local P1H, P1L = 0x9E3779B1, 0x85EBCA87 +local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F +local P3H, P3L = 0x165667B1, 0x9E3779F9 +local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 +local P5H, P5L = 0x27D4EB2F, 0x165667C5 + +-- (ah, al) * (bh, bl) mod 2^64 +@native local function mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0 = al % 65536 + local a1 = (al - a0) / 65536 + local b0 = bl % 65536 + local b1 = (bl - b0) / 65536 + local mid = a1 * b0 + a0 * b1 + local mid0 = mid % 65536 + local lo = a0 * b0 + mid0 * 65536 + local lo32 = lo % T32 + local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 + hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) + return hi % T32, lo32 +end + +@native local function add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local h = ah + bh + if l >= T32 then + l -= T32 + h += 1 + end + return h % T32, l +end + +-- rotl by r in 1..31 +@native local function rotl(h: number, l: number, r: number): (number, number) + return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) +end + +local P1L0, P1L1 = P1L % 65536, P1L // 65536 +local P2L0, P2L1 = P2L % 65536, P2L // 65536 + +-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +@native local function round(ah: number, al: number, ih: number, il: number): (number, number) + local a0 = il % 65536 + local a1 = (il - a0) / 65536 + local mid = a1 * P2L0 + a0 * P2L1 + local mid0 = mid % 65536 + local lo = a0 * P2L0 + mid0 * 65536 + local ml = lo % T32 + local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 + local l = al + ml + local h = ah + mh + if l >= T32 then + l -= T32 + h += 1 + end + h %= T32 + -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) + local hb, lb = h % 2, l % 2 + local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 + a0 = rl % 65536 + a1 = (rl - a0) / 65536 + mid = a1 * P1L0 + a0 * P1L1 + mid0 = mid % 65536 + lo = a0 * P1L0 + mid0 * 65536 + ml = lo % T32 + mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 + return mh % T32, ml +end + +@native local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) + local rh, rl = round(0, 0, vh, vl) + hh, hl = bxor(hh, rh), bxor(hl, rl) + hh, hl = mul(hh, hl, P1H, P1L) + return add(hh, hl, P4H, P4L) +end + +local Xxh64 = {} + +-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) +@native function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) + local p = offset + local e = offset + length + local hh, hl = 0, 0 + if length >= 32 then + local v1h, v1l = add(P1H, P1L, P2H, P2L) + local v2h, v2l = P2H, P2L + local v3h, v3l = 0, 0 + local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) + local limit = e - 32 + while p <= limit do + v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) + v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) + v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) + v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) + p += 32 + end + local ah, al = rotl(v1h, v1l, 1) + local bh, bl = rotl(v2h, v2l, 7) + hh, hl = add(ah, al, bh, bl) + bh, bl = rotl(v3h, v3l, 12) + hh, hl = add(hh, hl, bh, bl) + bh, bl = rotl(v4h, v4l, 18) + hh, hl = add(hh, hl, bh, bl) + hh, hl = merge(hh, hl, v1h, v1l) + hh, hl = merge(hh, hl, v2h, v2l) + hh, hl = merge(hh, hl, v3h, v3l) + hh, hl = merge(hh, hl, v4h, v4l) + else + hh, hl = P5H, P5L + end + 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) :: number + hh, hl = rotl(hh, hl, 27) + hh, hl = mul(hh, hl, P1H, P1L) + hh, hl = add(hh, hl, P4H, P4L) + p += 8 + end + if p + 4 <= e then + local kh, kl = mul(0, readu32(b, p), P1H, P1L) + 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) + p += 4 + end + while p < e do + local kh, kl = mul(0, readu8(b, p), P5H, P5L) + hh, hl = bxor(hh, kh), bxor(hl, kl) :: number + hh, hl = rotl(hh, hl, 11) + hh, hl = mul(hh, hl, P1H, P1L) + p += 1 + end + -- 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))) :: number -- h ^= h >> 29 + hh, hl = mul(hh, hl, P3H, P3L) + hl = bxor(hl, hh) -- h ^= h >> 32 + return hh, hl +end + +return Xxh64 +end +__FILES["codecs/entropy/Huffman"] = @native function() + + +-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. +-- +-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: +-- entry = symbol * 32 + length a code of `length` <= P bits +-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) +-- entry = 0 no code (incomplete code set): the stream is corrupt +-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables +-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. +-- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a +-- core/Bits reader. +-- +-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. +-- Never throws: bad code sets return -1 / nil. +local Bits = __include("core/Bits") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local MAXLEN = 16 + +local Huffman = {} +Huffman.MAXLEN = MAXLEN + +-- 8-bit reversal +local REV = table.create(256, 0) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = v // 2 + end + REV[i + 1] = r +end + +-- reverse(code, len) -> the low len bits of code reversed (len <= 16) +@native local function reverse(code: number, len: number): number + return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) +end +Huffman.reverse = reverse + +-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen +@native function Huffman.capacity(nsym: number, P: number, maxLen: number): number + return 2 ^ P + (if maxLen > P then nsym * 2 ^ (maxLen - P) else 0) +end + +local count = table.create(MAXLEN + 1, 0) +local nextc = table.create(MAXLEN + 1, 0) + +@native local function build(lens: buffer, off: number, n: number, tab: buffer, P: number, msb: boolean): number + for i = 1, MAXLEN + 1 do + count[i] = 0 + end + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > MAXLEN then + return -1 + end + count[l + 1] += 1 + end + count[1] = 0 + local left = 1 + local maxLen = 0 + for l = 1, MAXLEN do + left = left * 2 - count[l + 1] + if left < 0 then + return -1 + end + if count[l + 1] > 0 then + maxLen = l + end + end + local code = 0 + for l = 1, MAXLEN do + code = (code + count[l]) * 2 + nextc[l] = code + end + local psize = lshift(1, P) + bfill(tab, 0, 0, psize * 4) + local S = if maxLen > P then maxLen - P else 0 + local ssize = lshift(1, S) + local nextSub = psize + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local entry = s * 32 + l + if l <= P then + if msb then + -- the code is the top l bits of the P-bit index: fill every completion of the low bits + local first = lshift(c, P - l) + local last = first + lshift(1, P - l) - 1 + for i = first, last do + writeu32(tab, i * 4, entry) + end + else + local step = lshift(1, l) + local i = reverse(c, l) + while i < psize do + writeu32(tab, i * 4, entry) + i += step + end + end + else + local pre, rest + if msb then + pre = rshift(c, l - P) + rest = band(c, lshift(1, l - P) - 1) + else + local rev = reverse(c, l) + pre = band(rev, psize - 1) + rest = rshift(rev, P) + end + local e = readu32(tab, pre * 4) + local sub + if e == 0 then + sub = nextSub + nextSub += ssize + bfill(tab, sub * 4, 0, ssize * 4) + writeu32(tab, pre * 4, sub * 32) + else + sub = rshift(e, 5) + end + local k = l - P -- bits of the code in the subtable index + if msb then + local first = lshift(rest, S - k) + for i = first, first + lshift(1, S - k) - 1 do + writeu32(tab, (sub + i) * 4, entry) + end + else + local step = lshift(1, k) + local i = rest + while i < ssize do + writeu32(tab, (sub + i) * 4, entry) + i += step + end + end + end + end + end + return S +end + +-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next +-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an +-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. +@native function Huffman.buildLsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, false) +end + +-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first +@native function Huffman.buildMsb(lens: buffer, off: number, n: number, tab: buffer, P: number): number + return build(lens, off, n, tab, P, true) +end + +-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) +@native function Huffman.decodeLsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) +@native function Huffman.decodeMsb(br: Bits.BitReader, tab: buffer, P: number, S: number): number + local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). +-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. +@native function Huffman.codes(lengths: { number }): { number } + local cnt = table.create(MAXLEN + 1, 0) + for _, l in lengths do + if l > 0 then + cnt[l + 1] += 1 + end + end + local nxt = table.create(MAXLEN + 1, 0) + local code = 0 + for l = 1, MAXLEN do + code = (code + cnt[l]) * 2 + nxt[l + 1] = code + end + local out = table.create(#lengths, 0) + for i, l in lengths do + if l > 0 then + out[i] = nxt[l + 1] + nxt[l + 1] += 1 + end + end + return out +end + +-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without +-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. +@native function Huffman.lengths(freqs: { number }, maxLen: number): { number } + local n = #freqs + local out = table.create(n, 0) + -- leaves sorted by frequency (ties by symbol, for determinism) + local syms = {} + for i = 1, n do + if freqs[i] > 0 then + table.insert(syms, i) + end + end + if #syms == 0 then + return out + end + if #syms == 1 then + out[syms[1]] = 1 + return out + end + table.sort(syms, @native function(a: number, b: number): boolean + if freqs[a] ~= freqs[b] then + return freqs[a] < freqs[b] + end + return a < b + end) + -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) + local m = #syms + local weight = table.create(2 * m, 0) + local parent = table.create(2 * m, 0) + for i = 1, m do + weight[i] = freqs[syms[i]] + end + local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node + @native local function take(): number + if li <= m and (ni >= nn or weight[li] <= weight[ni]) then + li += 1 + return li - 1 + end + ni += 1 + return ni - 1 + end + for _ = 1, m - 1 do + local a = take() + local b = take() + weight[nn] = weight[a] + weight[b] + parent[a] = nn + parent[b] = nn + nn += 1 + end + -- depths: the root is nn - 1 + local depth = table.create(2 * m, 0) + for i = nn - 2, 1, -1 do + depth[i] = depth[parent[i]] + 1 + end + -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + local bl = table.create(m + maxLen + 2, 0) + local deepest = 0 + for i = 1, m do + bl[depth[i]] += 1 + deepest = math.max(deepest, depth[i]) + end + for l = deepest, maxLen + 1, -1 do + while bl[l] > 0 do + local j = l - 2 + while j > 0 and bl[j] == 0 do + j -= 1 + end + bl[l] -= 2 + bl[l - 1] += 1 + bl[j + 1] += 2 + bl[j] -= 1 + end + end + -- the longest codes go to the least frequent symbols (syms is sorted ascending) + local k = 1 + for l = math.min(deepest, maxLen), 1, -1 do + for _ = 1, bl[l] do + out[syms[k]] = l + k += 1 + end + end + return out +end + +return Huffman +end +__FILES["codecs/entropy/RangeCoder"] = function() + +-- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): +-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and +-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). +-- +-- local RD = require("@rosetta/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... +-- local RE = require("@rosetta/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +local RangeCoder = { + Decoder = __include("codecs/entropy/RangeCoder/Decoder"), + Encoder = __include("codecs/entropy/RangeCoder/Encoder"), +} + +return RangeCoder +end +__FILES["codecs/entropy/RangeCoder/Decoder"] = @native function() + + + +-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus +-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice +-- backwards. +-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +local RangeDecoder = {} + +type Dec = { + buf: buffer, + base: number, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local SYM_BITS = 8 +local CODE_BITS = 32 +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 +local SYM_MAX = 255 +local UINT_BITS = 8 +local WINDOW_SIZE = 32 + +local countlz = bit32.countlz +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8 = buffer.readu8 + +@native local function ilog(x: number): number + return 32 - countlz(x) +end +RangeDecoder.ilog = ilog + +@native local function normalize(d: Dec) + local rng, val, rem = d.rng, d.val, d.rem + while rng <= CODE_BOT do + d.nbits_total += SYM_BITS + rng = rng * 256 + local sym = rem + local offs = d.offs + if offs < d.storage then + rem = readu8(d.buf, d.base + offs) + d.offs = offs + 1 + else + rem = 0 + end + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) + end + d.rng, d.val, d.rem = rng, val, rem +end + +@native function RangeDecoder.new(buf: buffer, base: number, storage: number): Dec + local d: Dec = { + buf = buf, + base = base, + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) // SYM_BITS) * SYM_BITS, + rng = 128, -- 1 << CODE_EXTRA + val = 0, + rem = 0, + ext = 0, + error = 0, + } + local rem = 0 + if storage > 0 then + rem = readu8(buf, base) + d.offs = 1 + end + d.rem = rem + d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) + normalize(d) + return d +end + +-- ec_decode: the cumulative frequency of the next symbol, for a total of ft +@native function RangeDecoder.decode(d: Dec, ft: number): number + local ext = d.rng // ft + d.ext = ext + local s = d.val // ext + return ft - math.min(s + 1, ft) +end + +@native function RangeDecoder.decodeBin(d: Dec, bits: number): number + local ext = rshift(d.rng, bits) + d.ext = ext + local s = d.val // ext + local ft = lshift(1, bits) + return ft - math.min(s + 1, ft) +end + +@native function RangeDecoder.update(d: Dec, fl: number, fh: number, ft: number) + local s = d.ext * (ft - fh) + d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) + if fl > 0 then + d.rng = d.ext * (fh - fl) + else + d.rng -= s + end + normalize(d) +end + +@native function RangeDecoder.bitLogp(d: Dec, logp: number): boolean + local r = d.rng + local v = d.val + local s = rshift(r, logp) + local ret = v < s + if ret then + d.rng = s + else + d.val = v - s + d.rng = r - s + end + normalize(d) + return ret +end + +-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) +@native function RangeDecoder.icdf(d: Dec, icdf: { number }, off: number, ftb: number): number + local s = d.rng + local v = d.val + local r = rshift(s, ftb) + local ret = -1 + local t + repeat + t = s + ret += 1 + s = r * icdf[off + ret] + until v >= s + d.val = v - s + d.rng = t - s + normalize(d) + return ret +end + +@native function RangeDecoder.bits(d: Dec, bits: number): number + local window = d.end_window + local available = d.nend_bits + if available < bits then + repeat + local b = 0 + local eo = d.end_offs + if eo < d.storage then + eo += 1 + d.end_offs = eo + b = readu8(d.buf, d.base + d.storage - eo) + end + window = bor(window, lshift(b, available)) + available += SYM_BITS + until available > WINDOW_SIZE - SYM_BITS + end + local ret = band(window, lshift(1, bits) - 1) + if bits == 32 then + ret = window + end + window = rshift(window, bits) + available -= bits + d.end_window = window + d.nend_bits = available + d.nbits_total += bits + return ret +end + +@native function RangeDecoder.uint(d: Dec, ft0: number): number + local ft = ft0 - 1 + local ftb = ilog(ft) + if ftb > UINT_BITS then + ftb -= UINT_BITS + local ft1 = rshift(ft, ftb) + 1 + local s = RangeDecoder.decode(d, ft1) + RangeDecoder.update(d, s, s + 1, ft1) + local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) + if t <= ft then + return t + end + d.error = 1 + return ft + else + local s = RangeDecoder.decode(d, ft0) + RangeDecoder.update(d, s, s + 1, ft0) + return s + end +end + +@native function RangeDecoder.tell(d: Dec): number + return d.nbits_total - ilog(d.rng) +end + +local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +@native function RangeDecoder.tellFrac(d: Dec): number + local nbits = d.nbits_total * 8 + local l = ilog(d.rng) + local r = rshift(d.rng, l - 16) + local b = rshift(r, 12) - 8 + if r > correction[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +return RangeDecoder +end +__FILES["codecs/entropy/RangeCoder/Encoder"] = @native function() + + + +-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded +-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain +-- numbers. Never throws: running out of room sets `error`. +local RangeEncoder = {} + +type Enc = { + buf: buffer, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +@native local function ilog(x: number): number + return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes +@native function RangeEncoder.new(storage: number): Enc + return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +@native local function writeByte(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs += 1 +end + +@native local function writeByteAtEnd(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs += 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +@native local function carryOut(e: Enc, c: number) + if c ~= SYM_MAX then + local carry = if c >= 256 then 1 else 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext -= 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext += 1 + end +end + +@native local function normalize(e: Enc) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng *= 256 + e.nbits_total += 8 + end +end + +-- encode(fl, fh, ft): the symbol [fl, fh) of ft +@native function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- encodeBin(fl, fh, bits): ft = 2^bits +@native function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp +@native function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) + local r = e.rng + local s = floor(r / 2 ^ logp) + r -= s + if v then + e.val += r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total +@native function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val += e.rng - r * icdf[s] + e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng -= r * icdf[s + 1] + end + normalize(e) +end + +-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame +@native function RangeEncoder.bits(e: Enc, fl: number, n: number) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + until used < 8 + end + window += fl * 2 ^ used + used += n + e.end_window = window + e.nend_bits = used + e.nbits_total += n +end + +-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 +@native function RangeEncoder.uint(e: Enc, fl: number, ft: number) + ft -= 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb -= 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +@native function RangeEncoder.tell(e: Enc): number + return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +@native function RangeEncoder.tellFrac(e: Enc): number + local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +-- done(): flush; the frame is e.buf (storage bytes) +@native function RangeEncoder.done(e: Enc) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l += 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l -= 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder +end +__FILES["codecs/font/Bitmap"] = function() + +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike +-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels +-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's +-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, +-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an +-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row +-- packing every bitmap font format shares. New code. +-- +-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) +-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized +-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 +-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) +-- +-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +local Err = __include("core/Err") +local Types = __include("Types") + +local Bitmap = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ bits +-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left +-- pixel unless lsbFirst); bytes past the end of buf read as 0 +function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer + local out = buffer.create(math.max(0, w * h)) + local n = buffer.len(b) + for y = 0, h - 1 do + local row = off + y * stride + for x = 0, w - 1 do + local p = row + bit32.rshift(x, 3) + if p >= 0 and p < n then + local byte = readu8(b, p) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then + writeu8(out, y * w + x, 255) + end + end + end + end + return out +end + +-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on +function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer + local s = stride or math.ceil(w / 8) + local out = buffer.create(math.max(0, s * h)) + local n = buffer.len(px) + for y = 0, h - 1 do + for x = 0, w - 1 do + local i = y * w + x + if i < n and readu8(px, i) >= 128 then + local p = y * s + bit32.rshift(x, 3) + local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7) + writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn))) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ font +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._index[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local gl = self.bitmap.glyphs[g + 1] + return if gl then gl.advance else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face.outline(_self: any, _g: number): { any }? + return nil +end + +-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1] + if not gl or gl.width < 0 or gl.height < 0 then + return nil + end + local img = Types.Image.new(gl.width, gl.height, "alpha8") + local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels)) + if n > 0 then + buffer.copy(img.pixels, 0, gl.pixels, 0, n) + end + img.meta.left = gl.left + img.meta.top = gl.top + img.meta.advance = gl.advance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1 + return img +end + +-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) +function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any + local index: { [number]: number } = {} + for i, gl in strike.glyphs do + local cp = gl.codepoint + if cp and index[cp] == nil then + index[cp] = i - 1 + end + end + if strike.map then + for cp, g in strike.map do + if index[cp] == nil and g >= 0 and g < #strike.glyphs then + index[cp] = g + end + end + end + local f = setmetatable({ + kind = "font", + info = info or {}, + unitsPerEm = strike.size, + ascent = strike.ascent, + descent = -strike.descent, + lineGap = 0, + numGlyphs = #strike.glyphs, + bitmap = strike, + meta = meta or {}, + _index = index, + }, Face) + if strike.default then + setmetatable(index, { __index = function() + return strike.default + end }) + end + return f +end + +-- ------------------------------------------------------------------------------------------------ strike +type StrikeOptions = { + px: number?, -- pixel size for outline fonts (default 16) + chars: (string | { number })?, -- code points for outline fonts (default 32..126) + threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128) +} + +local function codepoints(chars: (string | { number })?): { number } + if type(chars) == "table" then + return chars + end + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + return out + end + for c = 32, 126 do + table.insert(out, c) + end + return out +end + +-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px +function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then + return font.bitmap, nil + end + if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "font has no glyphs to rasterize") + end + local o: StrikeOptions = opts or {} + local px = o.px or 16 + if type(px) ~= "number" or px < 1 or px > 1024 then + return nil, Err.new(Err.ARG, "px must be 1..1024") + end + local threshold = o.threshold or 128 + local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px + local scale = px / upm + local ascent = math.ceil((font.ascent or upm) * scale) + local descent = math.ceil(math.abs(font.descent or 0) * scale) + local glyphs: { Types.BitmapGlyph } = {} + local function add(cp: number?, g: number) + local ok, img = pcall(font.rasterize, font, g, px) + local adv = 0 + local aok, a = pcall(font.advance, font, g) + if aok and type(a) == "number" then + adv = math.floor(a * scale + 0.5) + end + local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) } + if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then + local n = img.width * img.height + local pxs = buffer.create(n) + for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do + if readu8(img.pixels, i) >= threshold then + writeu8(pxs, i, 255) + end + end + gl.width, gl.height, gl.pixels = img.width, img.height, pxs + gl.left = math.floor(img.meta.left or 0) + gl.top = math.floor(img.meta.top or 0) + if type(img.meta.advance) == "number" then + gl.advance = math.floor(img.meta.advance + 0.5) + end + end + table.insert(glyphs, gl) + end + add(nil, 0) + for _, cp in codepoints(o.chars) do + local ok, g = pcall(font.glyphIndex, font, cp) + if ok and type(g) == "number" and g > 0 then + add(cp, g) + end + end + return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil +end + +return Bitmap +end +__FILES["codecs/font/Cff"] = function() + +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts +-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed +-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands +-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 +-- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, +-- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage +-- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). +-- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. +-- +-- local cff, err = Cff.parse(buf, offset, length) +-- local cmds, err = Cff.outline(cff, glyphIndex) +-- +-- Never throws: malformed data returns nil, message. +local Cff = {} + +local readu8 = buffer.readu8 +local blen = buffer.len + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function uN(b: buffer, o: number, n: number): number + local v = 0 + for i = 0, n - 1 do + v = v * 256 + u8(b, o + i) + end + return v +end + +type Index = { count: number, offSize: number, offsets: number, data: number, next: number } +type Font = { + buf: buffer, + base: number, + limit: number, + charStrings: Index, + gsubrs: Index, + subrs: Index?, -- name-keyed fonts + fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict + fdSelect: number?, -- absolute offset of FDSelect + numGlyphs: number, + cid: boolean, + fontMatrix: { number }?, +} + +-- INDEX at absolute offset p (within [base, limit)) -> Index | nil +local function index(b: buffer, p: number, limit: number): Index? + if p + 2 > limit then + return nil + end + local count = uN(b, p, 2) + if count == 0 then + return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 } + end + local offSize = u8(b, p + 2) + if offSize < 1 or offSize > 4 then + return nil + end + local offsets = p + 3 + local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based + if data + 1 > limit then + return nil + end + local last = uN(b, offsets + count * offSize, offSize) + if data + last > limit then + return nil + end + return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } +end + +-- item(idx, i) -> absolute start, length (nil when out of range / corrupt) +local function item(b: buffer, idx: Index, i: number): (number?, number) + if i < 0 or i >= idx.count then + return nil, 0 + end + local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize) + local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize) + if s < 1 or e < s or idx.data + e > idx.next then + return nil, 0 + end + return idx.data + s, e - s +end +Cff.item = item + +-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +local function dict(b: buffer, p: number, n: number): { [number]: { number } } + local out: { [number]: { number } } = {} + local ops: { number } = {} + local e = p + n + while p < e do + local b0 = u8(b, p) + if b0 <= 21 then + local op = b0 + p += 1 + if b0 == 12 then + op = 1200 + u8(b, p) + p += 1 + end + out[op] = ops + ops = {} + elseif b0 == 28 then + local v = uN(b, p + 1, 2) + table.insert(ops, if v >= 32768 then v - 65536 else v) + p += 3 + elseif b0 == 29 then + local v = uN(b, p + 1, 4) + table.insert(ops, if v >= 2147483648 then v - 4294967296 else v) + p += 5 + elseif b0 == 30 then -- real number: BCD nibbles + local s = {} + p += 1 + local done = false + while p < e and not done do + local byte = u8(b, p) + p += 1 + for _, nib in { byte // 16, byte % 16 } do + if nib <= 9 then + table.insert(s, tostring(nib)) + elseif nib == 10 then + table.insert(s, ".") + elseif nib == 11 then + table.insert(s, "E") + elseif nib == 12 then + table.insert(s, "E-") + elseif nib == 14 then + table.insert(s, "-") + elseif nib == 15 then + done = true + break + end + end + end + table.insert(ops, tonumber(table.concat(s)) or 0) + elseif b0 >= 32 and b0 <= 246 then + table.insert(ops, b0 - 139) + p += 1 + elseif b0 >= 247 and b0 <= 250 then + table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) + p += 2 + elseif b0 >= 251 and b0 <= 254 then + table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) + p += 2 + else + p += 1 -- reserved + end + if #ops > 48 then + return out + end + end + return out +end + +local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index? + local pr = d[18] + if not pr or #pr < 2 then + return nil + end + local size, off = pr[1], pr[2] + local ps = base + off + if size < 0 or off < 0 or ps + size > limit then + return nil + end + local pd = dict(b, ps, size) + local s = pd[19] + if not s or #s < 1 then + return nil + end + return index(b, ps + s[1], limit) +end + +-- parse(buf, offset, length) -> Font | nil, message +function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?) + local base, limit = offset, math.min(offset + length, blen(b)) + if limit - base < 4 then + return nil, "truncated CFF header" + end + local major, hdrSize = u8(b, base), u8(b, base + 2) + if major == 2 then + return nil, "unsupported: CFF2 (variable font outlines)" + end + if major ~= 1 then + return nil, "bad CFF version " .. major + end + local names = index(b, base + hdrSize, limit) + if not names then + return nil, "bad name INDEX" + end + local tops = index(b, names.next, limit) + if not tops or tops.count < 1 then + return nil, "bad Top DICT INDEX" + end + local strings = index(b, tops.next, limit) + if not strings then + return nil, "bad String INDEX" + end + local gsubrs = index(b, strings.next, limit) + if not gsubrs then + return nil, "bad global subrs INDEX" + end + local ts, tl = item(b, tops, 0) + if not ts then + return nil, "bad Top DICT" + end + local top = dict(b, ts, tl) + local cso = top[17] + if not cso or #cso < 1 then + return nil, "no CharStrings" + end + local cst = top[1206] + if cst and cst[1] ~= 2 then + return nil, "unsupported: charstring type " .. tostring(cst[1]) + end + local charStrings = index(b, base + cso[1], limit) + if not charStrings then + return nil, "bad CharStrings INDEX" + end + local f: Font = { + buf = b, + base = base, + limit = limit, + charStrings = charStrings, + gsubrs = gsubrs, + subrs = nil, + fdSubrs = nil, + fdSelect = nil, + numGlyphs = charStrings.count, + cid = top[1230] ~= nil, + fontMatrix = top[1207], + } + if f.cid then + local fda, fds = top[1236], top[1237] + if not fda or not fds then + return nil, "CID font without FDArray / FDSelect" + end + local fdArray = index(b, base + fda[1], limit) + if not fdArray then + return nil, "bad FDArray" + end + local list: { Index? } = {} + for i = 0, math.min(fdArray.count, 256) - 1 do + local s, l = item(b, fdArray, i) + list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil + end + f.fdSubrs = list + f.fdSelect = base + fds[1] + else + f.subrs = privateSubrs(b, base, limit, top) + end + return f, nil +end + +local function bias(count: number): number + return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768 +end + +-- the local subrs of glyph g (CID fonts: through FDSelect) +local function localSubrs(f: Font, g: number): Index? + if not f.cid then + return f.subrs + end + local b, p = f.buf, f.fdSelect :: number + local fmt = u8(b, p) + local fd = -1 + if fmt == 0 then + fd = u8(b, p + 1 + g) + elseif fmt == 3 then + local n = uN(b, p + 1, 2) + local first = uN(b, p + 3, 2) + for i = 0, n - 1 do + local q = p + 5 + i * 3 + local v = u8(b, q) + local nxt = uN(b, q + 1, 2) + if g >= first and g < nxt then + fd = v + break + end + first = nxt + end + end + local list = f.fdSubrs :: { Index? } + return list[fd + 1] +end + +local BUDGET = 200000 -- operators per glyph (subroutine bombs) + +-- outline(f, g) -> path commands | nil, message +function Cff.outline(f: Font, g: number): ({ any }?, string?) + local b = f.buf + local p, len = item(b, f.charStrings, g) + if not p then + return nil, "bad glyph index " .. tostring(g) + end + local e = p + len + local cmds: { any } = {} + local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count + local sp = 0 + local trans = table.create(32, 0) :: { number } + local x, y = 0, 0 + local open = false + local maskbits = 0 + local inHeader = true + local stack: { { number } } = {} -- return addresses { p, e } + local subrs: Index? = nil + local haveSubrs = false + local ops = 0 + local seed = 12345 + + local function moveTo(dx: number, dy: number) + if open then + table.insert(cmds, { op = "close" }) + end + x += dx + y += dy + table.insert(cmds, { op = "moveTo", x, y }) + open = true + end + local function lineTo(dx: number, dy: number) + if not open then + moveTo(0, 0) + end + x += dx + y += dy + table.insert(cmds, { op = "lineTo", x, y }) + end + local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number) + if not open then + moveTo(0, 0) + end + local x1, y1 = x + dx1, y + dy1 + local x2, y2 = x1 + dx2, y1 + dy2 + x, y = x2 + dx3, y2 + dy3 + table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) + end + local function S(i: number): number -- operand i (0-based), 0 past the stack + return s[i + 1] or 0 + end + + while true do + if p >= e then + -- the end of a subroutine without return, or of the charstring without endchar + if #stack > 0 then + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + continue + end + break + end + ops += 1 + if ops > BUDGET then + return nil, "charstring too long (subroutine loop?)" + end + local b0 = u8(b, p) + p += 1 + local clear = true + local i = 0 + if b0 == 19 or b0 == 20 then -- hintmask, cntrmask + if inHeader then + maskbits += sp // 2 + end + inHeader = false + p += (maskbits + 7) // 8 + elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm + maskbits += sp // 2 + elseif b0 == 21 then -- rmoveto + inHeader = false + if sp < 2 then + return nil, "rmoveto stack" + end + moveTo(S(sp - 2), S(sp - 1)) + elseif b0 == 4 then -- vmoveto + inHeader = false + if sp < 1 then + return nil, "vmoveto stack" + end + moveTo(0, S(sp - 1)) + elseif b0 == 22 then -- hmoveto + inHeader = false + if sp < 1 then + return nil, "hmoveto stack" + end + moveTo(S(sp - 1), 0) + elseif b0 == 5 then -- rlineto + if sp < 2 then + return nil, "rlineto stack" + end + while i + 1 < sp do + lineTo(S(i), S(i + 1)) + i += 2 + end + elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate + if sp < 1 then + return nil, "hlineto stack" + end + local horiz = b0 == 6 + while i < sp do + if horiz then + lineTo(S(i), 0) + else + lineTo(0, S(i)) + end + horiz = not horiz + i += 1 + end + elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate + if sp < 4 then + return nil, "hvcurveto stack" + end + local horiz = b0 == 31 + while i + 3 < sp do + local last = if sp - i == 5 then S(i + 4) else 0 + if horiz then + curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3)) + else + curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last) + end + horiz = not horiz + i += 4 + end + elseif b0 == 8 then -- rrcurveto + if sp < 6 then + return nil, "rrcurveto stack" + end + while i + 5 < sp do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + elseif b0 == 24 then -- rcurveline + if sp < 8 then + return nil, "rcurveline stack" + end + while i + 5 < sp - 2 do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i += 6 + end + lineTo(S(i), S(i + 1)) + elseif b0 == 25 then -- rlinecurve + if sp < 8 then + return nil, "rlinecurve stack" + end + while i + 1 < sp - 6 do + lineTo(S(i), S(i + 1)) + i += 2 + end + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto + if sp < 4 then + return nil, "vv/hhcurveto stack" + end + local f0 = 0 + if sp % 2 == 1 then + f0 = S(0) + i = 1 + end + while i + 3 < sp do + if b0 == 27 then + curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0) + else + curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3)) + end + f0 = 0 + i += 4 + end + elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr + if b0 == 10 and not haveSubrs then + subrs = localSubrs(f, g) + haveSubrs = true + end + if sp < 1 then + return nil, "callsubr stack" + end + local idx = if b0 == 10 then subrs else f.gsubrs + if not idx then + return nil, "no subroutines" + end + local n = math.floor(S(sp - 1)) + bias(idx.count) + sp -= 1 + if #stack >= 10 then + return nil, "subroutine recursion limit" + end + local sp0, sl = item(b, idx, n) + if not sp0 then + return nil, "subroutine " .. n .. " not found" + end + table.insert(stack, { p, e }) + p, e = sp0, sp0 + sl + clear = false + elseif b0 == 11 then -- return + if #stack == 0 then + return nil, "return outside a subroutine" + end + local r = table.remove(stack) :: { number } + p, e = r[1], r[2] + clear = false + elseif b0 == 14 then -- endchar + if open then + table.insert(cmds, { op = "close" }) + end + return cmds, nil + elseif b0 == 12 then -- escape + local b1 = u8(b, p) + p += 1 + if b1 == 34 then -- hflex + if sp < 7 then + return nil, "hflex stack" + end + curveTo(S(0), 0, S(1), S(2), S(3), 0) + curveTo(S(4), 0, S(5), -S(2), S(6), 0) + elseif b1 == 35 then -- flex + if sp < 13 then + return nil, "flex stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), S(10), S(11)) + elseif b1 == 36 then -- hflex1 + if sp < 9 then + return nil, "hflex1 stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), 0) + curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7))) + elseif b1 == 37 then -- flex1 + if sp < 11 then + return nil, "flex1 stack" + end + local dx = S(0) + S(2) + S(4) + S(6) + S(8) + local dy = S(1) + S(3) + S(5) + S(7) + S(9) + local dx6, dy6 = S(10), S(10) + if math.abs(dx) > math.abs(dy) then + dy6 = -dy + else + dx6 = -dx + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), dx6, dy6) + else + -- arithmetic and storage operators: they leave results on the stack + clear = false + local top = sp + local a, c = S(top - 2), S(top - 1) + local function set(n: number, v: number) + -- pop n operands, push v + sp = math.max(0, sp - n) + sp += 1 + s[sp] = v + end + if b1 == 3 then + set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and + elseif b1 == 4 then + set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or + elseif b1 == 5 then + set(1, if c == 0 then 1 else 0) -- not + elseif b1 == 9 then + set(1, math.abs(c)) + elseif b1 == 10 then + set(2, a + c) + elseif b1 == 11 then + set(2, a - c) + elseif b1 == 12 then + set(2, if c ~= 0 then a / c else 0) + elseif b1 == 14 then + set(1, -c) + elseif b1 == 15 then + set(2, if a == c then 1 else 0) + elseif b1 == 18 then + sp = math.max(0, sp - 1) -- drop + elseif b1 == 20 then -- put: val i + local k = math.floor(c) + if k >= 0 and k < 32 then + trans[k + 1] = a + end + sp = math.max(0, sp - 2) + elseif b1 == 21 then -- get + local k = math.floor(c) + set(1, if k >= 0 and k < 32 then trans[k + 1] else 0) + elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2 + local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1) + set(4, if v1 <= v2 then s1 else s2) + elseif b1 == 23 then -- random (deterministic) + seed = (seed * 1103515245 + 12345) % 2147483648 + set(0, (seed % 65535 + 1) / 65536) + elseif b1 == 24 then + set(2, a * c) + elseif b1 == 26 then + set(1, math.sqrt(math.max(0, c))) + elseif b1 == 27 then + set(0, c) -- dup + elseif b1 == 28 then -- exch + if sp >= 2 then + s[sp - 1], s[sp] = s[sp], s[sp - 1] + end + elseif b1 == 29 then -- index + local k = math.floor(c) + local v = if k < 0 then S(top - 2) else S(top - 2 - k) + set(1, v) + elseif b1 == 30 then -- roll: n j + local n, j = math.floor(a), math.floor(c) + sp = math.max(0, sp - 2) + if n > 0 and n <= sp then + local base = sp - n + local tmp = table.create(n, 0) + for k = 0, n - 1 do + tmp[((k + j) % n) + 1] = s[base + k + 1] + end + for k = 0, n - 1 do + s[base + k + 1] = tmp[k + 1] + end + end + else + return nil, "unknown operator 12 " .. b1 + end + if sp > 48 then + return nil, "stack overflow" + end + end + elseif b0 >= 32 or b0 == 28 then -- operands + local v + if b0 == 28 then + v = uN(b, p, 2) + if v >= 32768 then + v -= 65536 + end + p += 2 + elseif b0 <= 246 then + v = b0 - 139 + elseif b0 <= 250 then + v = (b0 - 247) * 256 + u8(b, p) + 108 + p += 1 + elseif b0 <= 254 then + v = -(b0 - 251) * 256 - u8(b, p) - 108 + p += 1 + else -- 255: 16.16 fixed + v = uN(b, p, 4) + if v >= 2147483648 then + v -= 4294967296 + end + v /= 65536 + p += 4 + end + if sp >= 48 then + return nil, "operand stack overflow" + end + sp += 1 + s[sp] = v + clear = false + else + return nil, "reserved operator " .. b0 + end + if clear then + sp = 0 + end + end + return nil, "no endchar" +end + +return Cff +end +__FILES["codecs/font/GlyphNames"] = function() + +-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a +-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: +-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and +-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). +-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. +-- +-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) +-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +local GlyphNames = {} + +-- AGLFN: "name hex" pairs +local AGL = "" .. + "A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " .. + "Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " .. + "106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " .. + "2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " .. + "Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " .. + "F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " .. + "25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " .. + "CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " .. + "Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " .. + "Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " .. + "4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " .. + "Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " .. + "D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " .. + "250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " .. + "251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " .. + "2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " .. + "255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " .. + "2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " .. + "2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " .. + "Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " .. + "16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " .. + "Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " .. + "1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " .. + "Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " .. + "103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " .. + "3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " .. + "aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " .. + "21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " .. + "2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " .. + "asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " .. + "braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " .. + "caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " .. + "A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " .. + "colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " .. + "dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " .. + "dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " .. + "237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " .. + "egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " .. + "14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " .. + "etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " .. + "FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " .. + "215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " .. + "gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " .. + "greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " .. + "hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " .. + "iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " .. + "integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " .. + "invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " .. + "129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " .. + "140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " .. + "longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " .. + "B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " .. + "39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " .. + "obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " .. + "omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " .. + "2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " .. + "ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " .. + "parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " .. + "perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " .. + "220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " .. + "BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " .. + "201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " .. + "reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " .. + "2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " .. + "seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " .. + "263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " .. + "tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " .. + "tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " .. + "25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " .. + "FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " .. + "universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " .. + "upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " .. + "weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " .. + "1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " .. + "" + +-- StandardEncoding: 256 names, "-" = .notdef +local STD = "" .. + "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " .. + "dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " .. + "zero one two three four five six seven eight nine colon semicolon less equal greater question at A " .. + "B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " .. + "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " .. + "asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " .. + "sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " .. + "guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " .. + "quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " .. + "circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " .. + "- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " .. + "- - - dotlessi - - lslash oslash oe germandbls - - - - " .. + "" + +local byName: { [string]: number }? = nil + +local function load(): { [string]: number } + local t: { [string]: number } = {} + for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do + t[name] = tonumber(hex, 16) :: number + end + byName = t + return t +end + +local STANDARD: { [number]: string } = {} +do + local i = 0 + for name in string.gmatch(STD, "%S+") do + if name ~= "-" then + STANDARD[i] = name + end + i += 1 + end +end +GlyphNames.STANDARD = STANDARD + +-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil +function GlyphNames.unicode(name: string): number? + local base = string.match(name, "^([^%.]+)") or name + local t = byName or load() + local v = t[base] + if v then + return v + end + local hex = string.match(base, "^uni(%x%x%x%x)") + if hex then + local c = tonumber(hex, 16) :: number + return if c >= 0xD800 and c < 0xE000 then nil else c + end + hex = string.match(base, "^u(%x%x%x%x%x?%x?)$") + if hex then + local c = tonumber(hex, 16) :: number + return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c + end + local first = string.match(base, "^([^_]+)_") + if first then + return GlyphNames.unicode(first) + end + return nil +end + +return GlyphNames +end +__FILES["codecs/font/TrueType"] = function() + +-- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +-- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines +-- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), +-- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all +-- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean +-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. +-- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), +-- colour layers (COLR), GSUB substitutions. +-- +-- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err +-- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units +-- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo +-- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) +-- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) +-- +-- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +local Err = __include("core/Err") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Cff = __include("codecs/font/Cff") +local Glyf = __include("codecs/font/TrueType/Glyf") +local Tables = __include("codecs/font/TrueType/Tables") + +local TrueType = {} + +local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32 + +local function tag(b: buffer, o: number): string + if o < 0 or o + 4 > buffer.len(b) then + return "" + end + return buffer.readstring(b, o, 4) +end + +-- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) +function TrueType.count(b: buffer, offset: number?): number + local o = offset or 0 + local t = tag(b, o) + if t == "ttcf" then + return u32(b, o + 8) + end + if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then + return 1 + end + return 0 +end + +-- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir +function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?) + local n = u16(b, dir + 4) + if dir + 12 + n * 16 > limit then + return nil, "table directory past the end" + end + local out: { [string]: { number } } = {} + for i = 0, n - 1 do + local r = dir + 12 + i * 16 + local t = tag(b, r) + local off, len = u32(b, r + 8), u32(b, r + 12) + if file + off + len <= limit then + out[t] = { file + off, len } + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ the Font value +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return Tables.glyph(self._cmap, cp) +end + +function Face.advance(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh = self._numHMetrics + if nh == 0 then + return 0 + end + local h = self._hmtx + return u16(self._buf, h + 4 * math.min(g, nh - 1)) +end + +function Face.leftSideBearing(self: any, g: number): number + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh, h = self._numHMetrics, self._hmtx + if g < nh then + return i16(self._buf, h + 4 * g + 2) + end + return i16(self._buf, h + 4 * nh + 2 * (g - nh)) +end + +function Face.kern(self: any, a: number, b: number): number + if type(a) ~= "number" or type(b) ~= "number" then + return 0 + end + local key = a * 65536 + b + local cache = self._kernCache + local v = cache[key] + if v then + return v + end + v = 0 + if self._gpos then + v = Tables.gposKern(self._gpos, a, b) + end + if v == 0 and self._kern then + v = self._kern[key] or 0 + end + cache[key] = v + return v +end + +-- kernCodepoints(a, b) -> kern between two code points +function Face.kernCodepoints(self: any, a: number, b: number): number + return self:kern(self:glyphIndex(a), self:glyphIndex(b)) +end + +function Face.outline(self: any, g: number): { any }? + if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then + return nil + end + local ok, cmds, err = pcall(function() + if self._cff then + return Cff.outline(self._cff, g) + end + return Glyf.outline(self._glyf, g) + end) + if not ok then + self.meta.lastError = tostring(cmds) + return nil + end + if not cmds then + self.meta.lastError = err + end + return cmds +end + +-- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph +function Face.bounds(self: any, g: number): (number?, number, number, number) + local cmds = self:outline(g) + if not cmds then + return nil, 0, 0, 0 + end + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, c in cmds do + for i = 1, #c - 1, 2 do + local x, y = c[i], c[i + 1] + x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y) + end + end + if x0 > x1 then + return nil, 0, 0, 0 + end + return x0, y0, x1, y1 +end + +-- scale(px) -> pixels per font unit for an em of px pixels +function Face.scale(self: any, px: number): number + return px / self.unitsPerEm +end + +type RasterOptions = { + scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise + scaleY: number?, + shiftX: number?, -- subpixel shift (pixels) + shiftY: number?, +} + +-- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; +-- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty +-- glyphs give a 0 x 0 image. +function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image? + if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local cmds = self:outline(g) + if not cmds then + return nil + end + local o: RasterOptions = opts or {} + local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm + local sy = if type(o.scaleY) == "number" then o.scaleY else sx + local tx, ty = o.shiftX or 0, o.shiftY or 0 + local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left = 0 + img.meta.top = 0 + end + img.meta.advance = self:advance(g) * sx + img.meta.glyph = g + return img +end + +-- ------------------------------------------------------------------------------------------------ parsing +type Options = { index: number? } -- the font in a collection (default 0) + +-- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err +function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?) + local b = buf + local file = offset or 0 + local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file))) + if limit - file < 12 then + return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file) + end + local dir = file + local index = (opts and opts.index) or 0 + local count = TrueType.count(b, file) + if tag(b, file) == "ttcf" then + if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count)) + end + dir = file + u32(b, file + 12 + index * 4) + if dir + 12 > limit then + return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file) + end + elseif count == 0 then + return nil, Err.new(Err.CORRUPT, "not an sfnt font", file) + end + local sfntTag = tag(b, dir) + if sfntTag == "typ1" then + return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir) + end + local t, terr = TrueType.tables(b, file, dir, limit) + if not t then + return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir) + end + for _, need in { "head", "hhea", "maxp", "hmtx" } do + if not t[need] then + return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir) + end + end + local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1] + if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then + return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir) + end + local upem = u16(b, head + 18) + if upem < 16 or upem > 16384 then + return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18) + end + local numGlyphs = u16(b, maxp + 4) + local nh = math.min(u16(b, hhea + 34), numGlyphs) + if nh * 4 > t.hmtx[2] then + nh = t.hmtx[2] // 4 + end + local font: any = setmetatable({ + kind = "font", + info = {}, + unitsPerEm = upem, + ascent = i16(b, hhea + 4), + descent = i16(b, hhea + 6), + lineGap = i16(b, hhea + 8), + numGlyphs = numGlyphs, + bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) }, + pages = nil, + meta = {}, + _buf = b, + _hmtx = hmtx, + _numHMetrics = nh, + _kernCache = {}, + }, Face) + -- outlines + if t.glyf and t.loca then + font._glyf = { + buf = b, + glyf = t.glyf[1], + glyfLen = t.glyf[2], + loca = t.loca[1], + locaLen = t.loca[2], + longLoca = i16(b, head + 50) ~= 0, + numGlyphs = numGlyphs, + } + font.meta.outlines = "truetype" + elseif t["CFF "] then + local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2]) + if not cff then + local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1]) + end + font._cff = cff + font.meta.outlines = "cff" + elseif t.CFF2 then + return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir) + else + return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) + end + -- cmap, kerning, names, OS/2, post + if t.cmap then + font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) + end + if t.kern then + font._kern = Tables.kern(b, t.kern[1], t.kern[2]) + end + if t.GPOS then + font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2]) + end + if t.name then + local names = Tables.names(b, t.name[1], t.name[2]) + for k, v in names do + font.info[k] = v + end + font.info.family = names.typographicFamily or names.family + font.info.style = names.typographicStyle or names.style + end + if t["OS/2"] and t["OS/2"][2] >= 10 then + font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2]) + end + if t.post and t.post[2] >= 16 then + local p = t.post[1] + font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536 + font.meta.underlinePosition = i16(b, p + 8) + font.meta.underlineThickness = i16(b, p + 10) + font.meta.fixedPitch = u32(b, p + 12) ~= 0 + end + local tags = {} + for k in t do + table.insert(tags, k) + end + table.sort(tags) + font.meta.tables = tags + font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType" + font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil + return font, nil +end + +return TrueType +end +__FILES["codecs/font/TrueType/Glyf"] = function() + +-- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and +-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / +-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 +-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point +-- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the +-- spec do not). No hinting. +-- +-- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +local Glyf = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end + +type Face = { + buf: buffer, + glyf: number, -- absolute offset of the glyf table + glyfLen: number, + loca: number, + locaLen: number, + longLoca: boolean, + numGlyphs: number, + [string]: any, +} + +-- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index +function Glyf.range(f: Face, g: number): (number?, number) + if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then + return nil, 0 + end + local a, z + if f.longLoca then + if (g + 2) * 4 > f.locaLen then + return nil, 0 + end + a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4) :: number + else + if (g + 2) * 2 > f.locaLen then + return nil, 0 + end + a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2 + end + if z <= a or z > f.glyfLen then + return nil, 0 + end + return f.glyf + a, z - a +end + +-- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) +function Glyf.bounds(f: Face, g: number): (number?, number, number, number) + local o, n = Glyf.range(f, g) + if not o or n < 10 then + return nil, 0, 0, 0 + end + local b = f.buf + return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) +end + +-- contours: { { xs, ys, on } } point lists in font units +type Contour = { x: { number }, y: { number }, on: { boolean } } + +local MAX_POINTS = 65536 + +local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?) + local e = o + len + local ends = table.create(nc) :: { number } + local p = o + 10 + if p + nc * 2 + 2 > e then + return nil, "glyph header past the end" + end + local last = -1 + for i = 1, nc do + local v = u16(b, p) + if v < last then + return nil, "contour end points out of order" + end + ends[i] = v + last = v + p += 2 + end + local n = last + 1 + if n > MAX_POINTS then + return nil, "too many points" + end + local ins = u16(b, p) + p += 2 + ins + if p > e then + return nil, "instructions past the end" + end + -- flags + local flags = table.create(n, 0) + local i = 1 + while i <= n do + if p >= e then + return nil, "flags past the end" + end + local fl = readu8(b, p) + p += 1 + flags[i] = fl + i += 1 + if band(fl, 8) ~= 0 then + if p >= e then + return nil, "flags past the end" + end + local rep = readu8(b, p) + p += 1 + for _ = 1, rep do + if i > n then + break + end + flags[i] = fl + i += 1 + end + end + end + -- coordinates + local xs = table.create(n, 0) + local x = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 2) ~= 0 then + if p >= e then + return nil, "x coordinates past the end" + end + local d = readu8(b, p) + p += 1 + x += if band(fl, 16) ~= 0 then d else -d + elseif band(fl, 16) == 0 then + if p + 2 > e then + return nil, "x coordinates past the end" + end + x += i16(b, p) + p += 2 + end + xs[k] = x + end + local ys = table.create(n, 0) + local y = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 4) ~= 0 then + if p >= e then + return nil, "y coordinates past the end" + end + local d = readu8(b, p) + p += 1 + y += if band(fl, 32) ~= 0 then d else -d + elseif band(fl, 32) == 0 then + if p + 2 > e then + return nil, "y coordinates past the end" + end + y += i16(b, p) + p += 2 + end + ys[k] = y + end + local out = table.create(nc) :: { Contour } + local s = 1 + for c = 1, nc do + local z = ends[c] + 1 + local cx, cy, con = {}, {}, {} + for k = s, z do + table.insert(cx, xs[k]) + table.insert(cy, ys[k]) + table.insert(con, band(flags[k], 1) ~= 0) + end + out[c] = { x = cx, y = cy, on = con } + s = z + 1 + end + return out, nil +end + +local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?) + +local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?) + local b = f.buf + local e = o + len + local p = o + 10 + local out: { Contour } = {} + local total = 0 + while true do + if p + 4 > e then + return nil, "component past the end" + end + local flags = u16(b, p) + local gi = u16(b, p + 2) + p += 4 + local a1, a2 + if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS + if p + 4 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = i16(b, p), i16(b, p + 2) :: number + else + a1, a2 = u16(b, p), u16(b, p + 2) :: number + end + p += 4 + else + if p + 2 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = readi8(b, p), readi8(b, p + 1) :: number + else + a1, a2 = readu8(b, p), readu8(b, p + 1) :: number + end + p += 2 + end + local m1, m2, m3, m4 = 1, 0, 0, 1 + if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE + m1 = i16(b, p) / 16384 + m4 = m1 + p += 2 + elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE + m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384 + p += 4 + elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO + m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384 + p += 8 + end + if p > e then + return nil, "component past the end" + end + local child, err = contours(f, gi, depth + 1) + if not child then + return nil, err + end + -- transform the child's points + local tc = table.create(#child) :: { Contour } + for i, c in child do + local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number } + for k = 1, #c.x do + local x, y = c.x[k], c.y[k] + nx[k] = m1 * x + m3 * y + ny[k] = m2 * x + m4 * y + end + tc[i] = { x = nx, y = ny, on = c.on } + end + local dx, dy + if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES + dx, dy = a1, a2 + if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET + dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2 + end + else + -- point matching: parent point a1 (in what is composed so far) meets child point a2 + local function pt(list: { Contour }, idx: number): (number?, number) + local k = idx + for _, c in list do + local n = #c.x + if k < n then + return c.x[k + 1], c.y[k + 1] + end + k -= n + end + return nil, 0 + end + local px, py = pt(out, a1) + local cx, cy = pt(tc, a2) + if not px or not cx then + return nil, "component point index out of range" + end + dx, dy = px - cx, py - (cy :: number) + end + for _, c in tc do + for k = 1, #c.x do + c.x[k] += dx + c.y[k] += dy + end + total += #c.x + table.insert(out, c) + end + if total > MAX_POINTS then + return nil, "too many points" + end + if band(flags, 0x20) == 0 then -- MORE_COMPONENTS + break + end + end + return out, nil +end + +contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?) + if depth > 8 then + return nil, "composite glyphs nested too deep" + end + local o, len = Glyf.range(f, g) + if not o then + return {}, nil -- empty glyph (space) + end + if len < 10 then + return nil, "glyph header past the end" + end + local nc = i16(f.buf, o) + if nc >= 0 then + return simple(f.buf, o, len, nc) + end + return composite(f, o, len, depth) +end + +-- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message +function Glyf.outline(f: Face, g: number): ({ any }?, string?) + local cs, err = contours(f, g, 0) + if not cs then + return nil, err + end + local cmds = {} + for _, c in cs do + local n = #c.x + if n < 2 then + continue + end + local xs, ys, on = c.x, c.y, c.on + -- the start: the first on-curve point, or the midpoint of the first two off-curve points + local s = 0 + for k = 1, n do + if on[k] then + s = k + break + end + end + local sx, sy + if s == 0 then + sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2 + s = 1 + -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1 + table.insert(cmds, { op = "moveTo", sx, sy }) + local cx, cy = xs[1], ys[1] + for k = 2, n do + local x, y = xs[k], ys[k] + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + cx, cy = x, y + end + table.insert(cmds, { op = "quadTo", cx, cy, sx, sy }) + table.insert(cmds, { op = "close" }) + continue + end + sx, sy = xs[s], ys[s] + table.insert(cmds, { op = "moveTo", sx, sy }) + local off = false + local cx, cy = 0, 0 + for i = 1, n do + local k = (s + i - 1) % n + 1 + local x, y, isOn = xs[k], ys[k], on[k] + if i == n then + x, y, isOn = sx, sy, true -- back to the start + end + if isOn then + if off then + table.insert(cmds, { op = "quadTo", cx, cy, x, y }) + elseif i < n then + table.insert(cmds, { op = "lineTo", x, y }) + end + off = false + else + if off then + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + end + cx, cy = x, y + off = true + end + end + table.insert(cmds, { op = "close" }) + end + return cmds, nil +end + +-- points(f, g) -> the number of points and contours (for tests) +function Glyf.counts(f: Face, g: number): (number, number) + local cs = contours(f, g, 0) + if not cs then + return 0, 0 + end + local n = 0 + for _, c in cs do + n += #c.x + end + return n, #cs +end + +return Glyf +end +__FILES["codecs/font/TrueType/Tables"] = function() + +-- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode +-- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair +-- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), +-- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public +-- domain / MIT) as a reference for cmap 4 and the GPOS walk. +-- +-- Never throws: every read is range-checked (out of range reads as 0). +local Text = __include("codecs/text/Text") +local Tables = {} + +local readu8 = buffer.readu8 +local blen = buffer.len +local band = bit32.band + +local function u8(b: buffer, o: number): number + if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b: buffer, o: number): number + if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b: buffer, o: number): number + local v = u16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function u32(b: buffer, o: number): number + return u16(b, o) * 65536 + u16(b, o + 2) +end +Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 + +-- ------------------------------------------------------------------------------------------------ cmap +type Cmap = { buf: buffer, at: number, format: number, symbol: boolean } + +-- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac +function Tables.cmap(b: buffer, o: number, n: number): Cmap? + local count = u16(b, o + 2) + local best, bestRank, symbol = -1, 0, false + for i = 0, count - 1 do + local r = o + 4 + i * 8 + if r + 8 > o + n then + break + end + local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4) + local at = o + off + if off >= n then + continue + end + local fmt = u16(b, at) + local rank = 0 + if pid == 3 and eid == 10 then + rank = 6 + elseif pid == 0 and (eid == 4 or eid == 6) then + rank = 5 + elseif pid == 3 and eid == 1 then + rank = 4 + elseif pid == 0 and fmt ~= 14 then + rank = 3 + elseif pid == 3 and eid == 0 then + rank = 2 + elseif pid == 1 and eid == 0 then + rank = 1 + end + if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then + rank = 0 + end + if rank > bestRank then + best, bestRank, symbol = at, rank, pid == 3 and eid == 0 + end + end + if best < 0 then + return nil + end + return { buf = b, at = best, format = u16(b, best), symbol = symbol } +end + +local function lookup(c: Cmap, cp: number): number + local b, t, fmt = c.buf, c.at, c.format + if fmt == 0 then + return if cp < 256 then u8(b, t + 6 + cp) else 0 + elseif fmt == 6 then + local first, count = u16(b, t + 6), u16(b, t + 8) + if cp >= first and cp < first + count then + return u16(b, t + 10 + (cp - first) * 2) + end + return 0 + elseif fmt == 10 then + local first, count = u32(b, t + 12), u32(b, t + 16) + if cp >= first and cp < first + count then + return u16(b, t + 20 + (cp - first) * 2) + end + return 0 + elseif fmt == 4 then + if cp > 0xFFFF then + return 0 + end + local segX2 = u16(b, t + 6) + local segs = segX2 // 2 + local ends = t + 14 + -- binary search for the first segment whose end >= cp + local lo, hi = 0, segs - 1 + while lo < hi do + local mid = (lo + hi) // 2 + if u16(b, ends + mid * 2) < cp then + lo = mid + 1 + else + hi = mid + end + end + if segs == 0 or u16(b, ends + lo * 2) < cp then + return 0 + end + local starts = ends + segX2 + 2 + local start = u16(b, starts + lo * 2) + if cp < start then + return 0 + end + local deltaAt = starts + segX2 + lo * 2 + local delta = u16(b, deltaAt) + local rangeAt = deltaAt + segX2 + local ro = u16(b, rangeAt) + if ro == 0 then + return (cp + delta) % 65536 + end + local g = u16(b, rangeAt + ro + (cp - start) * 2) + if g == 0 then + return 0 + end + return (g + delta) % 65536 + elseif fmt == 12 or fmt == 13 then + local n = u32(b, t + 12) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local g = t + 16 + mid * 12 + local s, e = u32(b, g), u32(b, g + 4) + if cp < s then + hi = mid - 1 + elseif cp > e then + lo = mid + 1 + else + local gid = u32(b, g + 8) + return if fmt == 12 then gid + cp - s else gid + end + end + return 0 + end + return 0 +end + +-- glyph(cmap, codepoint) -> glyph index (0 = .notdef) +function Tables.glyph(c: Cmap?, cp: number): number + if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then + return 0 + end + local g = lookup(c, cp) + if g == 0 and c.symbol and cp < 256 then + g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes + end + return g +end + +-- ------------------------------------------------------------------------------------------------ kern +-- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } +function Tables.kern(b: buffer, o: number, n: number): { [number]: number } + local pairs: { [number]: number } = {} + local e = o + n + local apple = u32(b, o) == 0x00010000 + local count = if apple then u32(b, o + 4) else u16(b, o + 2) + local p = if apple then o + 8 else o + 4 + for _ = 1, math.min(count, 64) do + if p + 6 > e then + break + end + local len, fmt, horizontal, cross, minimum, hdr + if apple then + len = u32(b, p) + local cov = u16(b, p + 4) + fmt = band(cov, 0xFF) + horizontal = band(cov, 0x8000) == 0 + cross = band(cov, 0x4000) ~= 0 + minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable + hdr = 8 + else + len = u16(b, p + 2) + local cov = u16(b, p + 4) + fmt = cov // 256 + horizontal = band(cov, 1) ~= 0 + minimum = band(cov, 2) ~= 0 + cross = band(cov, 4) ~= 0 + hdr = 6 + end + if fmt == 0 and horizontal and not cross and not minimum then + local np = u16(b, p + hdr) + local q = p + hdr + 8 + for k = 0, np - 1 do + local r = q + k * 6 + if r + 6 > e then + break + end + local key = u16(b, r) * 65536 + u16(b, r + 2) + pairs[key] = (pairs[key] or 0) + i16(b, r + 4) + end + end + if len < hdr then + break + end + -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then + if not apple and len < hdr + 8 then + break + end + p += len + end + return pairs +end + +-- ------------------------------------------------------------------------------------------------ GPOS +local function popcount(v: number): number + local c = 0 + while v ~= 0 do + c += band(v, 1) + v = bit32.rshift(v, 1) + end + return c +end + +-- coverage index of glyph g in the Coverage table at t, or -1 +local function coverage(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local v = u16(b, t + 4 + mid * 2) + if g < v then + hi = mid - 1 + elseif g > v then + lo = mid + 1 + else + return mid + end + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + g - s + end + end + end + return -1 +end + +local function classOf(b: buffer, t: number, g: number): number + local fmt = u16(b, t) + if fmt == 1 then + local s, n = u16(b, t + 2), u16(b, t + 4) + if g >= s and g < s + n then + return u16(b, t + 6 + (g - s) * 2) + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + end + end + end + return 0 +end + +-- the x advance adjustment in a value record with format vf at r +local function xAdvance(b: buffer, r: number, vf: number): number + if band(vf, 4) == 0 then + return 0 + end + return i16(b, r + 2 * popcount(band(vf, 3))) +end + +-- one PairPos subtable: (applies, value) +local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number) + local fmt = u16(b, t) + local ci = coverage(b, t + u16(b, t + 2), l) + if ci < 0 then + return false, 0 + end + local vf1, vf2 = u16(b, t + 4), u16(b, t + 6) + local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF)) + if fmt == 1 then + local count = u16(b, t + 8) + if ci >= count then + return false, 0 + end + local ps = t + u16(b, t + 10 + ci * 2) + local n = u16(b, ps) + local rec = 2 + s1 + s2 + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = (lo + hi) // 2 + local q = ps + 2 + mid * rec + local g = u16(b, q) + if r < g then + hi = mid - 1 + elseif r > g then + lo = mid + 1 + else + return true, xAdvance(b, q + 2, vf1) + end + end + return false, 0 + elseif fmt == 2 then + local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10) + local n1, n2 = u16(b, t + 12), u16(b, t + 14) + local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r) + if c1 >= n1 or c2 >= n2 then + return false, 0 + end + local q = t + 16 + (c1 * n2 + c2) * (s1 + s2) + return true, xAdvance(b, q, vf1) + end + return false, 0 +end + +type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets + +-- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) +function Tables.gpos(b: buffer, o: number, n: number): Gpos? + if n < 10 or u16(b, o) ~= 1 then + return nil + end + local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8) + local want: { [number]: boolean } = {} + local any = false + local nf = u16(b, fl) + for i = 0, nf - 1 do + local r = fl + 2 + i * 6 + if u32(b, r) == 0x6B65726E then -- "kern" + local f = fl + u16(b, r + 4) + for k = 0, u16(b, f + 2) - 1 do + want[u16(b, f + 4 + k * 2)] = true + any = true + end + end + end + if not any then + return nil + end + local lookups: { { number } } = {} + local nl = u16(b, ll) + for i = 0, nl - 1 do + if want[i] then + local lt = ll + u16(b, ll + 2 + i * 2) + local ty = u16(b, lt) + local subs: { number } = {} + for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do + local st = lt + u16(b, lt + 6 + k * 2) + local sty = ty + if ty == 9 and u16(b, st) == 1 then -- extension + sty = u16(b, st + 2) + st += u32(b, st + 4) + end + if sty == 2 then + table.insert(subs, st) + end + end + if #subs > 0 then + table.insert(lookups, subs) + end + end + end + if #lookups == 0 then + return nil + end + return { buf = b, subtables = lookups } +end + +-- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) +function Tables.gposKern(g: Gpos, l: number, r: number): number + local total = 0 + for _, subs in g.subtables do + for _, st in subs do + local applies, v = pairPos(g.buf, st, l, r) + if applies then + total += v + break + end + end + end + return total +end + +-- ------------------------------------------------------------------------------------------------ name, OS/2 +local MAC_ROMAN_HIGH = { + 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, + 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, + 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8, + 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8, + 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, + 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7, +} + +local function utf16be(b: buffer, o: number, n: number): string + return Text.utf16(b, o, n, true) +end + +local function macRoman(b: buffer, o: number, n: number): string + local out = {} + for k = 0, n - 1 do + local c = u8(b, o + k) + table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127])) + end + return table.concat(out) +end + +local NAME_IDS: { [number]: string } = { + [0] = "copyright", + [1] = "family", + [2] = "style", + [3] = "uniqueId", + [4] = "fullName", + [5] = "version", + [6] = "postScriptName", + [7] = "trademark", + [8] = "manufacturer", + [9] = "designer", + [10] = "description", + [11] = "vendorUrl", + [12] = "designerUrl", + [13] = "license", + [14] = "licenseUrl", + [16] = "typographicFamily", + [17] = "typographicStyle", +} + +-- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) +function Tables.names(b: buffer, o: number, n: number): { [string]: string } + local out: { [string]: string } = {} + local rank: { [string]: number } = {} + local count, strings = u16(b, o + 2), o + u16(b, o + 4) + for i = 0, math.min(count, 4096) - 1 do + local r = o + 6 + i * 12 + if r + 12 > o + n then + break + end + local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6) + local len, off = u16(b, r + 8), u16(b, r + 10) + local key = NAME_IDS[nid] + if key and strings + off + len <= o + n then + local rk: number, s: string? = 0, nil + if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then + rk = if lang == 0x409 then 4 else 2 + s = utf16be(b, strings + off, len) + elseif pid == 0 then + rk = 3 + s = utf16be(b, strings + off, len) + elseif pid == 1 and eid == 0 then + rk = if lang == 0 then 1 else 0.5 + s = macRoman(b, strings + off, len) + end + if s and rk > (rank[key] or 0) then + out[key] = s + rank[key] = rk + end + end + end + return out +end + +-- os2(OS/2 table) -> the commonly used fields +function Tables.os2(b: buffer, o: number, n: number): { [string]: number } + local t: { [string]: number } = { + version = u16(b, o), + xAvgCharWidth = i16(b, o + 2), + weightClass = u16(b, o + 4), + widthClass = u16(b, o + 6), + fsType = u16(b, o + 8), + } + if n >= 78 then + t.fsSelection = u16(b, o + 62) + t.firstChar = u16(b, o + 64) + t.lastChar = u16(b, o + 66) + t.typoAscender = i16(b, o + 68) + t.typoDescender = i16(b, o + 70) + t.typoLineGap = i16(b, o + 72) + t.winAscent = u16(b, o + 74) + t.winDescent = u16(b, o + 76) + end + if n >= 96 and t.version >= 2 then + t.xHeight = i16(b, o + 86) + t.capHeight = i16(b, o + 88) + end + return t +end + +return Tables +end +__FILES["codecs/image/Bcn"] = @native function() + + + +-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): +-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, +-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). +-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. +-- +-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) +-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) +-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) +-- +-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by +-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below +-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +local Decode = __include("codecs/image/Bcn/Decode") +local Encode = __include("codecs/image/Bcn/Encode") + +local Bcn = {} + +-- kind -> bytes per 4x4 block +Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } +-- kinds that decode to rgbaf32 +Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { + bc1 = Decode.bc1, + bc2 = Decode.bc2, + bc3 = Decode.bc3, + bc4 = Decode.bc4, + bc4s = Decode.bc4s, + bc5 = Decode.bc5, + bc5s = Decode.bc5s, + bc7 = Decode.bc7, + bc6h = @native function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, false) + end, + bc6hs = @native function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, true) + end, +} + +-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) +@native function Bcn.size(kind: string, w: number, h: number): number? + local b = Bcn.BLOCK[kind] + if not b then + return nil + end + return ((w + 3) // 4) * ((h + 3) // 4) * b +end + +-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. +-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. +@native function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) + local fn = BLOCKS[kind] + if not fn then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Bcn.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local float = Bcn.FLOAT[kind] == true + local bpp = if float then 16 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local bytes = Bcn.BLOCK[kind] + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + fn(src, p, blk) + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + if cols == 4 and not float then + for y = 0, rows - 1 do + local d, s = base + y * rowBytes, y * 16 + writeu32(dst, d, readu32(blk, s)) + writeu32(dst, d + 4, readu32(blk, s + 4)) + writeu32(dst, d + 8, readu32(blk, s + 8)) + writeu32(dst, d + 12, readu32(blk, s + 12)) + end + else + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + end + return dst, nil +end + +type EncodeOptions = { + alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque) +} + +-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. +@native function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) + if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then + return nil, "unsupported: no encoder for " .. tostring(kind) + end + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then + return nil, "needs w x h rgba8 pixels" + end + local t = opts and opts.alphaThreshold or 128 + return Encode.run(kind, px, w, h, t), nil +end + +return Bcn +end +__FILES["codecs/image/Bcn/Decode"] = @native function() + + + +-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's +-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where +-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit +-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate +-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte +-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +local Half = __include("codecs/image/Half") + +local Decode = {} + +local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 +local pal = buffer.create(16) -- 4 rgba8 colours + +@native local function c565(c: number): (number, number, number) + local r = rshift(band(c, 0xF800), 8) + local g = rshift(band(c, 0x7E0), 3) + local b = lshift(band(c, 0x1F), 3) + return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) +end + +-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +@native local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) + local c0, c1 = readu16(src, p), readu16(src, p + 2) + local r0, g0, b0 = c565(c0) + local r1, g1, b1 = c565(c1) + writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) + writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) + if c0 > c1 or fourColour then + writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000) + writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000) + else + writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000) + writeu32(pal, 12, 0) + end + local idx = readu32(src, p + 4) + for i = 0, 15 do + writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) + end +end + +-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals +local vals = table.create(8, 0) +@native local function ramp8(a0: number, a1: number) + vals[1], vals[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + vals[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + vals[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + vals[7], vals[8] = 0, 255 + end +end + +-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 +@native local function ramp8s(u0: number, u1: number) + local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) + local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) + vals[1], vals[2] = s0 + 128, s1 + 128 + if s0 > s1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 + end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 + end + vals[7], vals[8] = 1, 255 + end +end + +-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) +@native local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) + if signed then + ramp8s(readu8(src, p), readu8(src, p + 1)) + else + ramp8(readu8(src, p), readu8(src, p + 1)) + end + local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 + local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 + for i = 0, 15 do + local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7) + local v = vals[sel + 1] + local o = i * 4 + if spread then + writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) + else + writeu8(blk, o + channel, v) + end + end +end + +@native function Decode.bc1(src: buffer, p: number, blk: buffer) + colour(src, p, blk, false) +end + +@native function Decode.bc2(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + for i = 0, 15 do + local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) + writeu8(blk, i * 4 + 3, a * 17) + end +end + +@native function Decode.bc3(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + single(src, p, blk, 3, false, false) +end + +@native function Decode.bc4(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, false, true) +end + +@native function Decode.bc4s(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, true, true) +end + +@native local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) + for i = 0, 15 do + writeu32(blk, i * 4, 0xFF000000) + end + single(src, p, blk, 0, signed, false) + single(src, p + 8, blk, 1, signed, false) +end +@native function Decode.bc5(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, false) +end +@native function Decode.bc5s(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, true) +end + +-- ------------------------------------------------------------------------------------------------ BPTC tables +-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices +local SI2 = { + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, + 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, + 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +} +local SI3 = { + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, + 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, + 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, + 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +} +local AI0 = { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +} +local AI1 = { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +} +local AI2 = { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +} +local W2 = { [0] = 0, 21, 43, 64 } +local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } +local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } +local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } +Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS + +@native local function subset(ns: number, part: number, i: number): number + if ns == 2 then + return band(rshift(SI2[part + 1], i), 1) + elseif ns == 3 then + return band(rshift(SI3[part + 1], 2 * i), 3) + end + return 0 +end + +-- the 128-bit block as four u32 words: bits(at, n) for n <= 16 +local w0, w1, w2, w3 = 0, 0, 0, 0 +@native local function load(src: buffer, p: number) + w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) +end +@native local function word(i: number): number + return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 +end +@native local function bits(at: number, n: number): number + if n == 0 then + return 0 + end + local wi, sh = rshift(at, 5), band(at, 31) + local v = rshift(word(wi), sh) + if sh + n > 32 and wi < 3 then + v = bor(v, lshift(word(wi + 1), 32 - sh)) + end + return band(v, lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ BC7 +-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 +local MODES7 = { + { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, + { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, + { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, + { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, + { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, + { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, + { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, + { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, +} +local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) + +@native local function expand(v: number, n: number): number + v = band(lshift(v, 8 - n), 255) + return bor(v, rshift(v, n)) +end + +@native function Decode.bc7(src: buffer, p: number, blk: buffer) + local m0 = readu8(src, p) + if m0 == 0 then + buffer.fill(blk, 0, 0, 64) + return + end + load(src, p) + local mode = 0 + while band(m0, lshift(1, mode)) == 0 do + mode += 1 + end + local info = MODES7[mode + 1] + local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] + local bit = mode + 1 + local part = bits(bit, pb) + bit += pb + local rot = bits(bit, rb) + bit += rb + local sel = bits(bit, isb) + bit += isb + local nep = ns * 2 + for i = 1, nep do + er[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eg[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eb[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + if ab > 0 then + ea[i] = bits(bit, ab) + bit += ab + else + ea[i] = 255 + end + end + if epb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep do + local v = bits(bit, 1) + bit += 1 + er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v + if ab > 0 then + ea[i] = ea[i] * 2 + v + end + end + end + if spb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep, 2 do + local v = bits(bit, 1) + bit += 1 + for j = i, i + 1 do + er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v + if ab > 0 then + ea[j] = ea[j] * 2 + v + end + end + end + end + for i = 1, nep do + er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) + if ab > 0 then + ea[i] = expand(ea[i], ab) + end + end + local cw = WEIGHTS[ib] + local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw + local cbit = bit + local abit = cbit + 16 * ib - ns + local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1 + local a2 = if ns == 3 then AI2[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 2 + 1 + local n = ib + if i == 0 or i == a1 or i == a2 then + n -= 1 + end + local i0 = bits(cbit, n) + cbit += n + local wc, wa + if ab > 0 and ib2 > 0 then + local n2 = if i == 0 then ib2 - 1 else ib2 + local i1 = bits(abit, n2) + abit += n2 + if sel == 1 then + wc, wa = aw[i1], cw[i0] + else + wc, wa = cw[i0], aw[i1] + end + else + wc, wa = cw[i0], cw[i0] + end + local tc, ta = 64 - wc, 64 - wa + local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) + local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) + local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) + local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) + if rot == 1 then + r, a = a, r + elseif rot == 2 then + g, a = a, g + elseif rot == 3 then + b, a = a, b + end + writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end +end + +-- ------------------------------------------------------------------------------------------------ BC6H +-- ns, transformed, pb, epb, rb, gb, bb +local MODES6 = { + { 2, 1, 5, 10, 5, 5, 5 }, + { 2, 1, 5, 7, 6, 6, 6 }, + { 2, 1, 5, 11, 5, 4, 4 }, + { 2, 1, 5, 11, 4, 5, 4 }, + { 2, 1, 5, 11, 4, 4, 5 }, + { 2, 1, 5, 9, 5, 5, 5 }, + { 2, 1, 5, 8, 6, 5, 5 }, + { 2, 1, 5, 8, 5, 6, 5 }, + { 2, 1, 5, 8, 5, 5, 6 }, + { 2, 0, 5, 6, 6, 6, 6 }, + { 1, 0, 0, 10, 10, 10, 10 }, + { 1, 1, 0, 11, 9, 9, 9 }, + { 1, 1, 0, 12, 8, 8, 8 }, + { 1, 1, 0, 16, 4, 4, 4 }, +} +-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) +local PACK6 = { + { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, +} +local ep = table.create(12, 0) +local uq = table.create(12, 0) + +@native local function signExtend(v: number, n: number): number + v = band(v, lshift(1, n) - 1) + return if v >= lshift(1, n - 1) then v - lshift(1, n) else v +end + +@native local function unquantize(x: number, n: number, signed: boolean): number + if not signed then + if n >= 15 or x == 0 then + return x + elseif x == lshift(1, n) - 1 then + return 0xFFFF + end + return rshift(x * 32768 + 0x4000, n - 1) + end + if n >= 16 then + return x + end + local neg = x < 0 + if neg then + x = -x + end + if x ~= 0 then + if x >= lshift(1, n - 1) - 1 then + x = 0x7FFF + else + x = rshift(x * 32768 + 0x4000, n - 1) + end + end + return if neg then -x else x +end + +@native local function finish(v: number, signed: boolean): number + if signed then + if v < 0 then + return -HALF[(-v * 31) // 32] + end + return HALF[(v * 31) // 32] + end + return HALF[(v * 31) // 64] +end + +-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) +@native function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) + load(src, p) + local m = band(w0, 31) + local mode, bit, epbits, ib + local low = band(m, 3) + if low < 2 then + mode, bit, epbits, ib = low, 2, 75, 3 + elseif low == 2 then + mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 + else + mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 + end + if mode >= 14 then + for i = 0, 15 do + local o = i * 16 + writef32(blk, o, 0) + writef32(blk, o + 4, 0) + writef32(blk, o + 8, 0) + writef32(blk, o + 12, 1) + end + return + end + local info = MODES6[mode + 1] + local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] + local nep = if ns == 2 then 12 else 6 + for i = 1, 12 do + ep[i] = 0 + end + local pack = PACK6[mode + 1] + for i = 1, epbits do + local d = pack[i] + local e = rshift(d, 4) + 1 + ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) + end + bit += epbits + local part = bits(bit, pb) + bit += pb + local mask = lshift(1, epb) - 1 + if signed then + ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) + end + if signed or tr == 1 then + for i = 4, nep, 3 do + ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) + end + end + if tr == 1 then + for i = 4, nep, 3 do + for c = 0, 2 do + local v = band(ep[i + c] + ep[1 + c], mask) + ep[i + c] = if signed then signExtend(v, epb) else v + end + end + end + for i = 1, nep do + uq[i] = unquantize(ep[i], epb, signed) + end + local w = WEIGHTS[ib] + local a1 = if ns == 2 then AI0[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 6 + 1 + local n = if i == 0 or i == a1 then ib - 1 else ib + local wt = w[bits(bit, n)] + bit += n + local t = 64 - wt + local o = i * 16 + -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would + writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed)) + writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed)) + writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed)) + writef32(blk, o + 12, 1) + end +end + +return Decode +end +__FILES["codecs/image/Bcn/Encode"] = @native function() + + + +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in rosetta; the approach follows stb_dxt by +-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the +-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping +-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as +-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +local Encode = {} + +local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +@native local function exp5(v: number): number + return bor(lshift(v, 3), rshift(v, 2)) +end +@native local function exp6(v: number): number + return bor(lshift(v, 2), rshift(v, 4)) +end + +-- ------------------------------------------------------------------------------------------------ single colours +-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) +-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit +local OM: { { number } }? = nil +@native local function singleTables(): { { number } } + local om = OM + if om then + return om + end + local t: { { number } } = {} + for k = 1, 4 do + local bitsN = if k <= 2 then 5 else 6 + local maxq = lshift(1, bitsN) - 1 + local exp: (number) -> number = if bitsN == 5 then exp5 else exp6 + local best = table.create(256, 1e9) + local pick = table.create(256, 0) + for a = 0, maxq do + local ea = exp(a) + for b = 0, maxq do + local eb = exp(b) + local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2 + -- prefer endpoints close to each other (less error if the colour shifts) + local e = math.abs(ea - eb) * 0.01 + for target = math.max(0, v - 8), math.min(255, v + 8) do + local err = (target - v) ^ 2 + e + if err < best[target + 1] then + best[target + 1] = err + pick[target + 1] = a * 256 + b + end + end + end + end + t[k] = pick + end + OM = t + return t +end + +-- ------------------------------------------------------------------------------------------------ BC1 colour +local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) +local USE = table.create(16, true) +local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) +local IDX = table.create(16, 0) +local BEST = table.create(16, 0) + +@native local function palette(c0: number, c1: number, four: boolean) + local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) + local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) + PR[1], PG[1], PB[1] = r0, g0, b0 + PR[2], PG[2], PB[2] = r1, g1, b1 + if four then + PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3 + PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3 + else + PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2 + PR[4], PG[4], PB[4] = 0, 0, 0 + end +end + +-- indices for the palette into IDX (0-based); returns the squared error of the used pixels +@native local function assign(four: boolean): number + local n = if four then 4 else 3 + local total = 0 + for i = 1, 16 do + if USE[i] then + local r, g, b = R[i], G[i], B[i] + local bi, be = 0, math.huge + for k = 1, n do + local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] + local e = dr * dr + dg * dg + db * db + if e < be then + be, bi = e, k - 1 + end + end + IDX[i] = bi + total += be + else + IDX[i] = 3 + end + end + return total +end + +@native local function q565(r: number, g: number, b: number): number + local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) + local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) + local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) + return qr * 2048 + qg * 32 + qb +end + +-- the endpoint weights of index k (the e0 share) +local W4 = { 1, 0, 2 / 3, 1 / 3 } +local W3 = { 1, 0, 0.5, 0 } + +-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate +@native local function refine(four: boolean): (number?, number?) + local W = if four then W4 else W3 + local aa, bb, ab = 0, 0, 0 + local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + local w = W[IDX[i] + 1] + local v = 1 - w + aa += w * w + bb += v * v + ab += w * v + ar += w * R[i] + ag += w * G[i] + ab_ += w * B[i] + br += v * R[i] + bg += v * G[i] + bb_ += v * B[i] + end + end + local det = aa * bb - ab * ab + if math.abs(det) < 1e-9 then + return nil, nil + end + local f = 1 / det + local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f + local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f + return q565(r0, g0, b0), q565(r1, g1, b1) +end + +-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode +-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels +@native local function colourBlock(out: buffer, o: number, four: boolean) + local n, mr, mg, mb = 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + n += 1 + mr += R[i] + mg += G[i] + mb += B[i] + end + end + if n == 0 then + writeu16(out, o, 0) + writeu16(out, o + 2, 0) + writeu32(out, o + 4, 0xFFFFFFFF) + return + end + mr, mg, mb = mr / n, mg / n, mb / n + local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 + local same = true + local fr, fg, fb = -1, -1, -1 + for i = 1, 16 do + if USE[i] then + if fr < 0 then + fr, fg, fb = R[i], G[i], B[i] + elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then + same = false + end + local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb + crr += dr * dr + cgg += dg * dg + cbb += db * db + crg += dr * dg + crb += dr * db + cgb += dg * db + end + end + local c0, c1 + if same then + local t = singleTables() + local k = if four then 0 else 1 + local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] + c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) + c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) + local i2 = 2 + if c0 == c1 then + i2 = 0 + end + -- index 2 everywhere (or 0 for an exact endpoint); order fixed below + for i = 1, 16 do + IDX[i] = if USE[i] then i2 else 3 + end + else + -- principal axis + local vr, vg, vb = 1, 1, 1 + for _ = 1, 8 do + local nr = crr * vr + crg * vg + crb * vb + local ng = crg * vr + cgg * vg + cgb * vb + local nb = crb * vr + cgb * vg + cbb * vb + local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) + if m < 1e-9 then + break + end + vr, vg, vb = nr / m, ng / m, nb / m + end + local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 + for i = 1, 16 do + if USE[i] then + local d = R[i] * vr + G[i] * vg + B[i] * vb + if d < lo then + lo, li = d, i + end + if d > hi then + hi, hi_ = d, i + end + end + end + c0 = q565(R[hi_], G[hi_], B[hi_]) + c1 = q565(R[li], G[li], B[li]) + palette(c0, c1, four) + local err = assign(four) + for i = 1, 16 do + BEST[i] = IDX[i] + end + for _ = 1, 2 do + local n0, n1 = refine(four) + if not n0 or not n1 then + break + end + palette(n0, n1, four) + local e2 = assign(four) + if e2 < err then + err, c0, c1 = e2, n0, n1 + for i = 1, 16 do + BEST[i] = IDX[i] + end + else + break + end + end + for i = 1, 16 do + IDX[i] = BEST[i] + end + end + -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 + if four then + if c0 < c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2 + end + elseif c0 == c1 then + for i = 1, 16 do + IDX[i] = 0 + end + end + elseif c0 > c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v + end + end + writeu16(out, o, c0) + writeu16(out, o + 2, c1) + local bitsv = 0 + for i = 16, 1, -1 do + bitsv = bitsv * 4 + IDX[i] + end + writeu32(out, o + 4, bitsv) +end + +-- ------------------------------------------------------------------------------------------------ BC4 channel +local V = table.create(16, 0) +local RAMP = table.create(8, 0) +local SEL = table.create(16, 0) +local SELB = table.create(16, 0) + +@native local function ramp(a0: number, a1: number) + RAMP[1], RAMP[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + RAMP[7], RAMP[8] = 0, 255 + end +end + +@native local function pick(): number + local total = 0 + for i = 1, 16 do + local v = V[i] + local bi, be = 0, math.huge + for k = 1, 8 do + local d = v - RAMP[k] + local e = d * d + if e < be then + be, bi = e, k - 1 + end + end + SEL[i] = bi + total += be + end + return total +end + +-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] +@native local function channelBlock(out: buffer, o: number) + local lo, hi = 255, 0 + local lo2, hi2 = 255, 0 + for i = 1, 16 do + local v = V[i] + lo, hi = math.min(lo, v), math.max(hi, v) + if v > 0 and v < 255 then + lo2, hi2 = math.min(lo2, v), math.max(hi2, v) + end + end + local a0, a1 + if lo == hi then + a0, a1 = lo, lo + ramp(a0, a1) + pick() + else + -- 8-value ramp, then a few nudged endpoints + local bestErr, b0, b1 = math.huge, hi, lo + for d0 = 0, 1 do + for d1 = 0, 1 do + local x0, x1 = hi - d0, lo + d1 + if x0 > x1 then + ramp(x0, x1) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, x0, x1 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + end + end + end + -- 6-value ramp with the 0 / 255 extremes + if lo2 > hi2 then + lo2, hi2 = lo, lo + end + ramp(lo2, hi2) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, lo2, hi2 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + a0, a1 = b0, b1 + for i = 1, 16 do + SEL[i] = SELB[i] + end + end + writeu8(out, o, a0) + writeu8(out, o + 1, a1) + local lo24, hi24 = 0, 0 + for i = 8, 1, -1 do + lo24 = lo24 * 8 + SEL[i] + hi24 = hi24 * 8 + SEL[i + 8] + end + writeu8(out, o + 2, band(lo24, 255)) + writeu8(out, o + 3, band(rshift(lo24, 8), 255)) + writeu8(out, o + 4, rshift(lo24, 16)) + writeu8(out, o + 5, band(hi24, 255)) + writeu8(out, o + 6, band(rshift(hi24, 8), 255)) + writeu8(out, o + 7, rshift(hi24, 16)) +end + +-- ------------------------------------------------------------------------------------------------ whole images +-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) +@native local function gather(px: buffer, w: number, h: number, bx: number, by: number) + for y = 0, 3 do + local sy = math.min(by * 4 + y, h - 1) + for x = 0, 3 do + local sx = math.min(bx * 4 + x, w - 1) + local s = (sy * w + sx) * 4 + local i = y * 4 + x + 1 + R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) + end + end +end + +-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) +@native function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 + local out = buffer.create(bw * bh * bytes) + local o = 0 + for by = 0, bh - 1 do + for bx = 0, bw - 1 do + gather(px, w, h, bx, by) + if kind == "bc1" then + local any = false + for i = 1, 16 do + local u = A[i] >= threshold + USE[i] = u + any = any or not u + end + colourBlock(out, o, not any) + elseif kind == "bc3" then + for i = 1, 16 do + USE[i] = true + V[i] = A[i] + end + channelBlock(out, o) + colourBlock(out, o + 8, true) + elseif kind == "bc4" then + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + else + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + for i = 1, 16 do + V[i] = G[i] + end + channelBlock(out, o + 8) + end + o += bytes + end + end + return out +end + +return Encode +end +__FILES["codecs/image/Blend"] = @native function() + + +-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable +-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer +-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the +-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. +-- +-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) +-- Blend.MODES.multiply -> true +-- +-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge +-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion +-- subtract divide hue saturation color luminosity. Unknown names composite as normal. +local Blend = {} + +local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len +local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs + +local IDS: { [string]: number } = { + normal = 0, + dissolve = 1, + darken = 2, + multiply = 3, + colorBurn = 4, + linearBurn = 5, + darkerColor = 6, + lighten = 7, + screen = 8, + colorDodge = 9, + linearDodge = 10, + add = 10, + lighterColor = 11, + overlay = 12, + softLight = 13, + hardLight = 14, + vividLight = 15, + linearLight = 16, + pinLight = 17, + hardMix = 18, + difference = 19, + exclusion = 20, + subtract = 21, + divide = 22, + hue = 23, + saturation = 24, + color = 25, + luminosity = 26, +} +local MODES: { [string]: boolean } = {} +for k in IDS do + MODES[k] = true +end +Blend.MODES = table.freeze(MODES) + +@native local function burn(cb: number, cs: number): number + if cb >= 1 then + return 1 + elseif cs <= 0 then + return 0 + end + return 1 - min(1, (1 - cb) / cs) +end +@native local function dodge(cb: number, cs: number): number + if cb <= 0 then + return 0 + elseif cs >= 1 then + return 1 + end + return min(1, cb / (1 - cs)) +end + +-- B(cb, cs) of a separable mode +@native local function sep(m: number, cb: number, cs: number): number + if m == 3 then + return cb * cs + elseif m == 8 then + return cb + cs - cb * cs + elseif m == 2 then + return min(cb, cs) + elseif m == 7 then + return max(cb, cs) + elseif m == 12 then -- overlay = hardLight(cs, cb) + if cb <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cb - 1 + return cs + c - cs * c + elseif m == 14 then + if cs <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cs - 1 + return cb + c - cb * c + elseif m == 13 then + if cs <= 0.5 then + return cb - (1 - 2 * cs) * cb * (1 - cb) + end + local d = if cb <= 0.25 then ((16 * cb - 12) * cb + 4) * cb else sqrt(cb) + return cb + (2 * cs - 1) * (d - cb) + elseif m == 9 then + return dodge(cb, cs) + elseif m == 4 then + return burn(cb, cs) + elseif m == 5 then + return max(0, cb + cs - 1) + elseif m == 10 then + return min(1, cb + cs) + elseif m == 15 then + if cs <= 0.5 then + return burn(cb, 2 * cs) + end + return dodge(cb, 2 * cs - 1) + elseif m == 16 then + return max(0, min(1, cb + 2 * cs - 1)) + elseif m == 17 then + if cs <= 0.5 then + return min(cb, 2 * cs) + end + return max(cb, 2 * cs - 1) + elseif m == 18 then + return if cb + cs >= 1 then 1 else 0 + elseif m == 19 then + return abs(cb - cs) + elseif m == 20 then + return cb + cs - 2 * cb * cs + elseif m == 21 then + return max(0, cb - cs) + elseif m == 22 then + if cs <= 0 then + return if cb <= 0 then 0 else 1 + end + return min(1, cb / cs) + end + return cs +end + +-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat +@native local function lum(r: number, g: number, b: number): number + return 0.3 * r + 0.59 * g + 0.11 * b +end +@native local function clipColor(r: number, g: number, b: number): (number, number, number) + local l = lum(r, g, b) + local n = min(r, g, b) + local x = max(r, g, b) + if n < 0 and l - n > 1e-12 then + r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n) + end + if x > 1 and x - l > 1e-12 then + r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l) + end + return r, g, b +end +@native local function setLum(r: number, g: number, b: number, l: number): (number, number, number) + local d = l - lum(r, g, b) + return clipColor(r + d, g + d, b + d) +end +@native local function setSat(r: number, g: number, b: number, s: number): (number, number, number) + local mx = max(r, g, b) + local mn = min(r, g, b) + if mx - mn <= 1e-12 then + return 0, 0, 0 + end + local k = s / (mx - mn) + return (r - mn) * k, (g - mn) * k, (b - mn) * k +end + +-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 +-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: +-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). +@native local function composite(dst: buffer, dw: number, dh: number, src: buffer, sw: number, sh: number, x: number, y: number, opacity: number, mode: string?, opts: { clip: boolean?, mask: any? }?) + x, y = floor(x), floor(y) + if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then + return + end + if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then + return + end + local op = min(1, opacity) + local m = IDS[mode or "normal"] or 0 + local clip = opts ~= nil and opts.clip == true + local mask = if opts ~= nil then opts.mask else nil + local mbuf: buffer? = nil + local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 + if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then + mw, mh = floor(mask.width), floor(mask.height) :: number + if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then + mbuf = mask.pixels + end + mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) :: number + mdef = (tonumber(mask.default) or 255) / 255 + elseif type(mask) == "table" then + mdef = (tonumber(mask.default) or 255) / 255 + end + local x0, y0 = max(0, x), max(0, y) + local x1, y1 = min(dw, x + sw), min(dh, y + sh) + for py = y0, y1 - 1 do + local so = ((py - y) * sw + (x0 - x)) * 4 + local do_ = (py * dw + x0) * 4 + for px = x0, x1 - 1 do + local sa8 = readu8(src, so + 3) + if sa8 ~= 0 then + local sa = sa8 / 255 * op + if mbuf ~= nil or mdef ~= 1 then + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + sa *= mv + end + if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows + local h = (px * 73856093 + py * 19349663) % 65536 / 65536 + sa = if h < sa then 1 else 0 + end + local ba8 = readu8(dst, do_ + 3) + if sa > 0 and not (clip and ba8 == 0) then + local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 + if ba8 == 0 then + -- empty backdrop: the source as it is (alpha scaled) + writeu32(dst, do_, readu32(src, so)) + writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) + else + local ba = ba8 / 255 + local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 + local mr, mg, mb = sr, sg, sb + if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then + mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), sep(m, bb, sb) :: number + elseif m == 6 then + if lum(sr, sg, sb) >= lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 11 then + if lum(sr, sg, sb) < lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 23 then + local s = max(br, bg, bb) - min(br, bg, bb) + local r1, g1, b1 = setSat(sr, sg, sb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 24 then + local s = max(sr, sg, sb) - min(sr, sg, sb) + local r1, g1, b1 = setSat(br, bg, bb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 25 then + mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb)) + elseif m == 26 then + mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb)) + end + local orr, og, ob, oa + if clip then + -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque + orr = sa * mr + (1 - sa) * br + og = sa * mg + (1 - sa) * bg + ob = sa * mb + (1 - sa) * bb + oa = ba + else + oa = sa + ba * (1 - sa) + local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba + orr = (ws * sr + wm * mr + wb * br) / oa + og = (ws * sg + wm * mg + wb * bg) / oa + ob = (ws * sb + wm * mb + wb * bb) / oa + end + writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5)) + writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5)) + writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5)) + writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5)) + end + end + end + so += 4 + do_ += 4 + end + end +end + +-- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); +-- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is +-- also scaled by the mask value of each pixel +@native local function lerp(dst: buffer, from: buffer, t: number, n: number, w: number?, mask: any?) + if blen(dst) < n * 4 or blen(from) < n * 4 then + return + end + if mask == nil or w == nil or w <= 0 then + for i = 0, n * 4 - 1 do + local a = readu8(from, i) + writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + end + return + end + local mbuf: buffer? = mask.pixels + local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0) + local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + local mdef = (tonumber(mask.default) or 255) / 255 + if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then + mbuf = nil + end + for p = 0, n - 1 do + local px, py = p % w, p // w + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + local tt = t * mv + local o = p * 4 + for k = o, o + 3 do + local a = readu8(from, k) + writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5)) + end + end +end +Blend.composite = composite +Blend.lerp = lerp + +-- ------------------------------------------------------------------------------------------------ layer trees +@native local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +@native local function maskOf(l: any): any + local m = l.mask + if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then + return nil + end + local img = m.image + local px = img.pixels + if img.format == "rgba8" then -- use the red channel + local n = img.width * img.height + local g = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + px = g + end + return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } +end + +@native local function compose(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + local i = 1 + while i <= #layers do + local l = layers[i] + i += 1 + if type(l) ~= "table" or (l.visible == false and not hidden) then + -- clipped layers above a hidden base are hidden too + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + i += 1 + end + continue + end + local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) + local mode = if type(l.blend) == "string" then l.blend else "normal" + -- the layer's own pixels, as an isolated w x h buffer + local src: buffer? = nil + if type(l.children) == "table" then + if mode == "passThrough" then + local before = buffer.create(w * h * 4) + buffer.copy(before, 0, canvas, 0, w * h * 4) + compose(l.children, canvas, w, h, hidden) + -- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop) + local gm = maskOf(l) + if opacity < 1 or gm ~= nil then + lerp(canvas, before, opacity, w * h, w, gm) + end + continue + end + src = buffer.create(w * h * 4) + compose(l.children, src :: buffer, w, h, hidden) + elseif isImage(l.image) then + if l.image.width > 0 and l.image.height > 0 then + local b = buffer.create(w * h * 4) + composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal") + src = b + end + end + -- clipping layers above this one: composited onto it with their alpha limited to it + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + local c = layers[i] + i += 1 + if src and (c.visible ~= false or hidden) and isImage(c.image) then + composite(src :: buffer, w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) }) + end + end + if src then + composite(canvas, w, h, src :: buffer, w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) + end + end +end + +-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: +-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group +-- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. +-- hidden = true includes invisible layers. +@native function Blend.flatten(layers: { any }, canvas: buffer, w: number, h: number, hidden: boolean) + if blen(canvas) >= w * h * 4 then + compose(layers, canvas, w, h, hidden) + end +end + +return Blend +end +__FILES["codecs/image/Dct"] = @native function() + + + +-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). +-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with +-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the +-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). +-- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces +-- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md). +-- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv. +-- +-- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component +-- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples) +-- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples +local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16 +local clamp = math.clamp + +local Dct = {} + +local ws = table.create(64, 0) + +@native local function idct8(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (13 - p1) + local h1 = s1 / 2 + local s2 = 2 ^ (16 + p1) + local h2 = s2 / 2 + center * s2 + local dcm = 2 ^ p1 + for c = 0, 7 do + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + ws[c + 33] = dc + ws[c + 41] = dc + ws[c + 49] = dc + ws[c + 57] = dc + else + -- even part + local z2 = c2 * readu16(q, qo + 32) + local z3 = c6 * readu16(q, qo + 96) + local z1 = (z2 + z3) * 4433 + local tmp2 = z1 - z3 * 15137 + local tmp3 = z1 + z2 * 6270 + z2 = readi16(coef, o) * readu16(q, qo) + z3 = c4 * readu16(q, qo + 64) + local tmp0 = (z2 + z3) * 8192 + local tmp1 = (z2 - z3) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + -- odd part + local t0 = c7 * readu16(q, qo + 112) + local t1 = c5 * readu16(q, qo + 80) + local t2 = c3 * readu16(q, qo + 48) + local t3 = c1 * readu16(q, qo + 16) + z1 = t0 + t3 + z2 = t1 + t2 + z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 *= 2446 + t1 *= 16819 + t2 *= 25172 + t3 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 += z1 + z3 + t1 += z2 + z4 + t2 += z2 + z3 + t3 += z1 + z4 + ws[c + 1] = (tmp10 + t3 + h1) // s1 + ws[c + 57] = (tmp10 - t3 + h1) // s1 + ws[c + 9] = (tmp11 + t2 + h1) // s1 + ws[c + 49] = (tmp11 - t2 + h1) // s1 + ws[c + 17] = (tmp12 + t1 + h1) // s1 + ws[c + 41] = (tmp12 - t1 + h1) // s1 + ws[c + 25] = (tmp13 + t0 + h1) // s1 + ws[c + 33] = (tmp13 - t0 + h1) // s1 + end + end + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 7 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + for i = 0, 14, 2 do + writeu16(plane, o + i, v) + end + else + local z1 = (w2 + w6) * 4433 + local tmp2 = z1 - w6 * 15137 + local tmp3 = z1 + w2 * 6270 + local tmp0 = (w0 + w4) * 8192 + local tmp1 = (w0 - w4) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local t0, t1, t2, t3 = w7, w5, w3, w1 + z1 = t0 + t3 + local z2 = t1 + t2 + local z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 *= 2446 + t1 *= 16819 + t2 *= 25172 + t3 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 += z1 + z3 + t1 += z2 + z4 + t2 += z2 + z3 + t3 += z1 + z4 + writeu16(plane, o, clamp((tmp10 + t3 + h2) // s2, 0, maxv)) + writeu16(plane, o + 14, clamp((tmp10 - t3 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp11 + t2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 12, clamp((tmp11 - t2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 4, clamp((tmp12 + t1 + h2) // s2, 0, maxv)) + writeu16(plane, o + 10, clamp((tmp12 - t1 + h2) // s2, 0, maxv)) + writeu16(plane, o + 6, clamp((tmp13 + t0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 8, clamp((tmp13 - t0 + h2) // s2, 0, maxv)) + end + end +end + +@native local function idct4(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (14 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 4 then + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + else + local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384 + local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + local z1 = c7 * readu16(q, qo + 112) + local z2 = c5 * readu16(q, qo + 80) + local z3 = c3 * readu16(q, qo + 48) + local z4 = c1 * readu16(q, qo + 16) + tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697 + tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995 + ws[c + 1] = (tmp10 + tmp2 + h1) // s1 + ws[c + 25] = (tmp10 - tmp2 + h1) // s1 + ws[c + 9] = (tmp12 + tmp0 + h1) // s1 + ws[c + 17] = (tmp12 - tmp0 + h1) // s1 + end + end + end + local s2 = 2 ^ (17 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 3 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + writeu16(plane, o + 4, v) + writeu16(plane, o + 6, v) + else + local tmp0 = w0 * 16384 + local tmp2 = w2 * 15137 - w6 * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697 + tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995 + writeu16(plane, o, clamp((tmp10 + tmp2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 6, clamp((tmp10 - tmp2 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp12 + tmp0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 4, clamp((tmp12 - tmp0 + h2) // s2, 0, maxv)) + end + end +end + +@native local function idct2(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + local s1 = 2 ^ (15 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 2 and c ~= 4 and c ~= 6 then + local o = off + c * 2 + local qo = c * 2 + local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48) + local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112) + if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + else + local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768 + local tmp0 = c7 * readu16(q, qo + 112) * -5906 + + c5 * readu16(q, qo + 80) * 6967 + + c3 * readu16(q, qo + 48) * -10426 + + c1 * readu16(q, qo + 16) * 29692 + ws[c + 1] = (tmp10 + tmp0 + h1) // s1 + ws[c + 9] = (tmp10 - tmp0 + h1) // s1 + end + end + end + local s2 = 2 ^ (18 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 1 do + local b = r * 8 + local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then + local v = clamp((w0 + hd) // sd, 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + else + local tmp10 = w0 * 32768 + local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692 + writeu16(plane, o, clamp((tmp10 + tmp0 + h2) // s2, 0, maxv)) + writeu16(plane, o + 2, clamp((tmp10 - tmp0 + h2) // s2, 0, maxv)) + end + end +end + +-- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block +-- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x +-- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top. +-- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here). +@native function Dct.idctComponent(coef: buffer, q: buffer, bpl: number, bpc: number, size: number, plane: buffer, p1: number, center: number, maxv: number, hook: (() -> ())?) + local stride = bpl * size + for by = 0, bpc - 1 do + if hook and by > 0 then + pcall(hook) + end + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + local out = by * size * stride + bx * size + if size == 8 then + idct8(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 4 then + idct4(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 2 then + idct2(coef, off, q, plane, out, stride, p1, center, maxv) + else + local v = (readi16(coef, off) * readu16(q, 0) + 4) // 8 + center + writeu16(plane, out * 2, clamp(v, 0, maxv)) + end + end + end +end + +-- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte +-- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row +@native function Dct.idctBlock(coef: buffer, off: number, q: buffer, plane: buffer, out: number, stride: number, p1: number, center: number, maxv: number) + idct8(coef, off, q, plane, out, stride, p1, center, maxv) +end + +-- ------------------------------------------------------------------------------------------------ forward +local fw = table.create(64, 0) + +@native local function quant(coef: buffer, off: number, div: buffer, v: number, i: number) + local qv = readu16(div, i * 2) * 8 + local h = qv // 2 + if v < 0 then + writei16(coef, off + i * 2, -((h - v) // qv)) + else + writei16(coef, off + i * 2, (v + h) // qv) + end +end + +-- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes +-- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then +-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes +-- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid. +@native function Dct.fdctQuantize(src: buffer, stride: number, x: number, y: number, w: number, h: number, div: buffer, coef: buffer, off: number) + local lastX, lastY = w - 1, h - 1 + for r = 0, 7 do + local row = math.min(y + r, lastY) * stride + local d0: number, d1: number, d2: number, d3: number, d4: number, d5: number, d6: number, d7: number + if x + 7 <= lastX then + local p = row + x + d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) :: number + d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), readu8(src, p + 7) :: number + else + d0 = readu8(src, row + math.min(x, lastX)) + d1 = readu8(src, row + math.min(x + 1, lastX)) + d2 = readu8(src, row + math.min(x + 2, lastX)) + d3 = readu8(src, row + math.min(x + 3, lastX)) + d4 = readu8(src, row + math.min(x + 4, lastX)) + d5 = readu8(src, row + math.min(x + 5, lastX)) + d6 = readu8(src, row + math.min(x + 6, lastX)) + d7 = readu8(src, row + math.min(x + 7, lastX)) + end + d0 -= 128 + d1 -= 128 + d2 -= 128 + d3 -= 128 + d4 -= 128 + d5 -= 128 + d6 -= 128 + d7 -= 128 + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local b = r * 8 + 1 + fw[b] = (tmp10 + tmp11) * 4 + fw[b + 4] = (tmp10 - tmp11) * 4 + local z1 = (tmp12 + tmp13) * 4433 + fw[b + 2] = (z1 + tmp13 * 6270 + 1024) // 2048 + fw[b + 6] = (z1 - tmp12 * 15137 + 1024) // 2048 + z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 *= 2446 + tmp5 *= 16819 + tmp6 *= 25172 + tmp7 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + fw[b + 7] = (tmp4 + z1 + z3 + 1024) // 2048 + fw[b + 5] = (tmp5 + z2 + z4 + 1024) // 2048 + fw[b + 3] = (tmp6 + z2 + z3 + 1024) // 2048 + fw[b + 1] = (tmp7 + z1 + z4 + 1024) // 2048 + end + for c = 1, 8 do + local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24] + local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56] + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local o0 = (tmp10 + tmp11 + 2) // 4 + local o4 = (tmp10 - tmp11 + 2) // 4 + local z1 = (tmp12 + tmp13) * 4433 + local o2 = (z1 + tmp13 * 6270 + 16384) // 32768 + local o6 = (z1 - tmp12 * 15137 + 16384) // 32768 + z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 *= 2446 + tmp5 *= 16819 + tmp6 *= 25172 + tmp7 *= 12299 + z1 *= -7373 + z2 *= -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + local o7 = (tmp4 + z1 + z3 + 16384) // 32768 + local o5 = (tmp5 + z2 + z4 + 16384) // 32768 + local o3 = (tmp6 + z2 + z3 + 16384) // 32768 + local o1 = (tmp7 + z1 + z4 + 16384) // 32768 + local cc = c - 1 + quant(coef, off, div, o0, cc) + quant(coef, off, div, o1, cc + 8) + quant(coef, off, div, o2, cc + 16) + quant(coef, off, div, o3, cc + 24) + quant(coef, off, div, o4, cc + 32) + quant(coef, off, div, o5, cc + 40) + quant(coef, off, div, o6, cc + 48) + quant(coef, off, div, o7, cc + 56) + end +end + +return Dct +end +__FILES["codecs/image/Etc"] = @native function() + + + +-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar +-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 +-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new +-- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. +-- +-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels +-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) +-- Etc.size("etc1", w, h) -- bytes of the block data +-- +-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), +-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +local Etc = {} + +Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number } + +local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap + +-- ------------------------------------------------------------------------------------------------ tables +local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b + { 2, 8, -2, -8 }, + { 5, 17, -5, -17 }, + { 9, 29, -9, -29 }, + { 13, 42, -13, -42 }, + { 18, 60, -18, -60 }, + { 24, 80, -24, -80 }, + { 33, 106, -33, -106 }, + { 47, 183, -47, -183 }, +} +local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances +local EAC = { + { -3, -6, -9, -15, 2, 5, 8, 14 }, + { -3, -7, -10, -13, 2, 6, 9, 12 }, + { -2, -5, -8, -13, 1, 4, 7, 12 }, + { -2, -4, -6, -13, 1, 3, 5, 12 }, + { -3, -6, -8, -12, 2, 5, 7, 11 }, + { -3, -7, -9, -11, 2, 6, 8, 10 }, + { -4, -7, -8, -11, 3, 6, 7, 10 }, + { -3, -5, -8, -11, 2, 4, 7, 10 }, + { -2, -6, -8, -10, 1, 5, 7, 9 }, + { -2, -5, -8, -10, 1, 4, 7, 9 }, + { -2, -4, -8, -10, 1, 3, 7, 9 }, + { -2, -5, -7, -10, 1, 4, 6, 9 }, + { -3, -4, -7, -10, 2, 3, 6, 9 }, + { -1, -2, -3, -10, 0, 1, 2, 9 }, + { -4, -6, -8, -9, 3, 5, 7, 8 }, + { -3, -5, -7, -9, 2, 4, 6, 8 }, +} + +@native local function clamp8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end +@native local function rgb(r: number, g: number, b: number): number + return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 +end + +-- ------------------------------------------------------------------------------------------------ colour blocks +-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) +local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) + +@native local function be32(src: buffer, p: number): number + return byteswap(readu32(src, p)) +end + +-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) +@native local function pix(lo: number, i: number): number + return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) +end + +-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +@native local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) + local hi, lo = be32(src, p), be32(src, p + 4) + local diffBit = band(rshift(hi, 1), 1) + local flip = band(hi, 1) + local opaque = not punch or diffBit == 1 + local r1, g1, b1, r2, g2, b2 + if not punch and diffBit == 0 then + r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17 + g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17 + else + local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31) + local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7) + if dR >= 4 then + dR -= 8 + end + if dG >= 4 then + dG -= 8 + end + if dB >= 4 then + dB -= 8 + end + local R2, G2, B2 = R + dR, G + dG, B + dB + if etc2 and (R2 < 0 or R2 > 31) then + -- T mode + local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3) + local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17 + local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1] + P[1] = rgb(c1r, c1g, c1b) + P[2] = rgb(c2r + d, c2g + d, c2b + d) + P[3] = rgb(c2r, c2g, c2b) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (G2 < 0 or G2 > 31) then + -- H mode + local q1r = band(rshift(hi, 27), 15) + local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1) + local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7) + local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15) + local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0 + local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1] + local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17 + P[1] = rgb(c1r + d, c1g + d, c1b + d) + P[2] = rgb(c1r - d, c1g - d, c1b - d) + P[3] = rgb(c2r + d, c2g + d, c2b + d) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (B2 < 0 or B2 > 31) then + -- planar (always opaque) + local ro = band(rshift(hi, 25), 63) + local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63) + local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7) + local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1) + local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63) + local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63) + ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4) + go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6) + bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4) + for y = 0, 3 do + for x = 0, 3 do + local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4 + local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4 + local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4 + writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b)) + end + end + return + else + r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2) + r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) + end + if not r1 then + -- T / H: the paint colours by index + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local idx = pix(lo, i) + local c = if not opaque and idx == 2 then 0 else P[idx + 1] + writeu32(blk, (y * 4 + x) * 4, c) + end + return + end + end + local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1] + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local second = if flip == 0 then x >= 2 else y >= 2 + local idx = pix(lo, i) + local c + if not opaque and idx == 2 then + c = 0 + else + local m = if second then t2[idx + 1] else t1[idx + 1] + if not opaque and idx == 0 then + m = 0 + end + if second then + c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m) + else + c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m) + end + end + writeu32(blk, (y * 4 + x) * 4, c) + end +end + +-- ------------------------------------------------------------------------------------------------ EAC +local VALS = table.create(16, 0) + +-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) +@native local function eac(src: buffer, p: number, mode: string) + local base = readu8(src, p) + local b1 = readu8(src, p + 1) + local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] + -- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits + local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4) + local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7) + if mode == "s11" then + if base >= 128 then + base -= 256 + end + if base == -128 then + base = -127 + end + end + for i = 0, 15 do + local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7) + local m = tab[idx + 1] + local v + if mode == "alpha" then + v = clamp8(base + m * mult) + elseif mode == "u11" then + v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8 + v = if v < 0 then 0 elseif v > 2047 then 2047 else v + else + v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8 + v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v + end + VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v + end +end + +-- 11-bit values -> 8 / 16 bits +@native local function to8(v: number, signed: boolean): number + if signed then + return math.floor(v * 127 / 1023 + 0.5) + 128 + end + return math.floor(v * 255 / 2047 + 0.5) +end +@native local function to16(v: number, signed: boolean): number + if signed then + return math.floor((v + 1023) * 65535 / 2046 + 0.5) + end + return v * 32 + rshift(v, 6) +end + +-- ------------------------------------------------------------------------------------------------ decode +-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind +@native function Etc.size(kind: string, w: number, h: number): number? + local b = Etc.BLOCK[kind] + return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil +end + +-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC +-- kinds when wide is true. +@native function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) + local bytes = Etc.BLOCK[kind] + if not bytes then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Etc.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local isEac = string.sub(kind, 1, 3) == "eac" + local w16 = isEac and wide == true + local bpp = if w16 then 8 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local signed = kind == "eac_r11s" or kind == "eac_rg11s" + local two = kind == "eac_rg11" or kind == "eac_rg11s" + local mode11 = if signed then "s11" else "u11" + local etc2 = kind ~= "etc1" + local punch = kind == "etc2_rgba1" + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + if isEac then + eac(src, p, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + local q = to16(v, signed) + writeu16(blk, i * 8, q) + writeu16(blk, i * 8 + 2, if two then 0 else q) + writeu16(blk, i * 8 + 4, if two then 0 else q) + writeu16(blk, i * 8 + 6, 65535) + else + local q = to8(v, signed) + writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000) + end + end + if two then + eac(src, p + 8, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + writeu16(blk, i * 8 + 2, to16(v, signed)) + else + writeu8(blk, i * 4 + 1, to8(v, signed)) + end + end + end + elseif kind == "etc2_rgba" then + colour(src, p + 8, blk, true, false) + eac(src, p, "alpha") + for i = 0, 15 do + writeu8(blk, i * 4 + 3, VALS[i + 1]) + end + else + colour(src, p, blk, etc2, punch) + end + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + return dst, nil +end + +return Etc +end +__FILES["codecs/image/Half"] = @native function() + + + +-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, +-- OpenEXR HALF channels). New in rosetta. Never throws. +-- +-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) +-- local f = Half.toFloat(h) -- the same, computed +-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +local Half = {} + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +-- toFloat(h) -> number (h a 16-bit pattern) +@native local function toFloat(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = band(rshift(h, 10), 31) + local m = band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1024 + m) * 2 ^ (e - 25) +end +Half.toFloat = toFloat + +local TABLE: { [number]: number } = table.create(65536, 0) +for h = 0, 65535 do + TABLE[h] = toFloat(h) +end +Half.TABLE = TABLE + +local scratch = buffer.create(4) + +-- fromFloat(f) -> the nearest half bit pattern (ties to even) +@native function Half.fromFloat(f: number): number + if f ~= f then + return 0x7E00 + end + buffer.writef32(scratch, 0, f) + local x = buffer.readu32(scratch, 0) + local sign = band(rshift(x, 16), 0x8000) + local e = band(rshift(x, 23), 0xFF) + local m = band(x, 0x7FFFFF) + if e == 255 then + return bor(sign, 0x7C00) + end + local ne = e - 112 + if ne >= 31 then + return bor(sign, 0x7C00) + elseif ne <= 0 then + if ne < -10 then + return sign + end + m = bor(m, 0x800000) + local shift = 14 - ne + local hm = rshift(m, shift) + local rem = band(m, lshift(1, shift) - 1) + local halfway = lshift(1, shift - 1) + if rem > halfway or (rem == halfway and band(hm, 1) == 1) then + hm += 1 + end + return sign + hm + end + local hm = rshift(m, 13) + local rem = band(m, 0x1FFF) + if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then + hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should + end + return sign + ne * 1024 + hm +end + +return Half +end +__FILES["codecs/image/Jpeg"] = function() + +-- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG +-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and +-- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) +-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's +-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. +-- +-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image +-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes +-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer +-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header +-- +-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit +-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt +-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation +-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go +-- (meta.truncated = true). +-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field +-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame +-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even +-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field +-- leaves the first field alone (meta.source.fields = 1). +-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour +-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera +-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other +-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). +-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or +-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments +-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. +-- Never throws: bad data or arguments return nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Jpeg/Decode") +local Encode = __include("codecs/image/Jpeg/Encode") +local Yuv = __include("codecs/image/Jpeg/Yuv") + +local Jpeg = {} + +type DecodeOptions = { + scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) + orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only; rgba8 / gray8) + native: boolean?, -- grey files decode to gray8 (default false: rgba8) + yuv: boolean?, -- 8-bit YCbCr / grey frames decode to yuv420p (default false); see the header for the layouts + fields: boolean?, -- two JPEGs back to back are two fields of one frame (default: when the AVI1 segment says so) + raw: boolean?, -- no colour conversion: 3 / 4 components as R, G, B (, A) bytes (default false; BLP1 BGRA JPEGs) + maxPixels: number?, -- refuse larger images (default 2^26) + -- a cooperative yield point, run after every MCU row of a scan, every block row of the IDCT and every 8 output + -- rows: e.g. a function that calls coroutine.yield() when a time budget is spent, so one image is decoded over + -- several frames (decode then runs inside a coroutine). Errors in it are ignored. + yield: (() -> ())?, +} +type EncodeOptions = { + quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables + subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420"; yuv420p input is always 4:2:0) + progressive: boolean?, -- default false + optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) + gray: boolean?, -- a one-component file (default: true for gray8 images) + restart: number?, -- restart interval in MCUs (default 0 = none) + jfif: boolean?, -- write the JFIF APP0 header (default true) + density: { unit: number, x: number, y: number }?, -- the JFIF density (default unit 0, 1 x 1) + segments: { { marker: number, data: buffer } }?, -- APPn / COM segments written after the JFIF header +} + +type Info = { + width: number, + height: number, + components: number, + progressive: boolean, + arithmetic: boolean, + precision: number, + colorSpace: string, + sampling: { { number } }, -- { h, v } per component + orientation: number, + adobe: number?, + jfif: boolean, + avi1: number?, -- the AVI1 field polarity, when the segment comes before the frame header +} + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) + return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) +end + +-- the marker parser over [o, o + l): State | nil, Err +local function parse(buf: buffer, o: number, l: number, opts: any, headerOnly: boolean): (Decode.State?, Err.Err?) + local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) + end + if not st then + return nil, Err.from(msg or "decode failed", o, code) + end + return st, nil +end + +local function samplingOf(f: any): { { number } } + local sampling = {} + for _, c in f.comps do + table.insert(sampling, { c.h, c.v }) + end + return sampling +end + +-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(buf: buffer, off: number?, len: number?): (Info?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + local o, l = range(buf, off, len) + local st, err = parse(buf, o, l, nil, true) + if not st then + return nil, err + end + local f = st.frame + return { + width = f.width, + height = f.height, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + precision = f.precision, + colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), + sampling = samplingOf(f), + orientation = st.orientation, + adobe = st.adobe, + jfif = st.jfif, + avi1 = st.avi1, + }, + nil +end + +-- the EXIF orientation applied to rgba8 pixels: buffer, width, height +local function orient(px: buffer, w: number, h: number, o: number): (buffer, number, number) + if o <= 1 or o > 8 then + return px, w, h + end + local swap = o >= 5 + local ow, oh = if swap then h else w, if swap then w else h + local out = buffer.create(ow * oh * 4) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for y = 0, oh - 1 do + for x = 0, ow - 1 do + local col, row + if o == 2 then + col, row = w - 1 - x, y + elseif o == 3 then + col, row = w - 1 - x, h - 1 - y + elseif o == 4 then + col, row = x, h - 1 - y + elseif o == 5 then + col, row = y, x + elseif o == 6 then + col, row = y, h - 1 - x + elseif o == 7 then + col, row = w - 1 - y, h - 1 - x + else + col, row = w - 1 - y, x + end + writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) + end + end + return out, ow, oh +end + +-- one JPEG at [o, o + l): Image, State | nil, Err +local function decodeOne(buf: buffer, o: number, l: number, opts: DecodeOptions?): (Types.Image?, any) + local st, err = parse(buf, o, l, opts, false) + if not st then + return nil, err + end + local s = st :: Decode.State + local img = Types.Image.new(0, 0) + local space, mode = nil, nil + if opts and opts.yuv then + local ok, w, h, px, m = pcall(Decode.outputYuv, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if w then + img.width, img.height, img.pixels, img.format = w, h :: number, px :: buffer, "yuv420p" + mode = m + space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) + end + end + if not mode then + local ok, w, h, px, sp = pcall(Decode.output, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if not w then + return nil, Err.from(px, o, h) + end + space = sp + if opts and opts.orient then + px, w, h = orient(px, w, h, s.orientation) + end + img.width, img.height, img.pixels = w, h, px + if opts and opts.native and space == "gray" then + local g = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + img.pixels, img.format = g, "gray8" + end + end + local f = s.frame + local meta = img.meta + meta.orientation = s.orientation + meta.oriented = (opts and opts.orient and not mode) or false + meta.exif = s.exif + meta.icc = s.icc + if #s.comments > 0 then + meta.text = { comment = table.concat(s.comments, "\n") } + end + if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then + local k = if s.density.unit == 2 then 2.54 else 1 + meta.dpi = { x = s.density.x * k, y = s.density.y * k } + end + meta.truncated = s.truncated + meta.source = { + format = "jpeg", + bitDepth = f.precision, + colorType = space, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + sampling = samplingOf(f), + scale = s.scale, + adobe = s.adobe, + jfif = s.jfif, + avi1 = s.avi1, + yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + range = if mode then "full" else nil, + fields = 1, + } + return img, s +end + +-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +local function nextSoi(buf: buffer, p: number, e: number): number + local readu8 = buffer.readu8 + while p + 3 <= e do + if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then + return p + end + p += 1 + end + return -1 +end + +-- two fields (same size and format) -> one frame of twice the height, field a on the even rows +local function weave(a: Types.Image, b: Types.Image): Types.Image + local w, hf = a.width, a.height + local h = hf * 2 + local out = Types.Image.new(w, h, a.format) + local dst = out.pixels + if a.format == "yuv420p" then + local cw, chf = (w + 1) // 2, (hf + 1) // 2 + local ch = (h + 1) // 2 -- = hf + Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) + for k = 0, 1 do + Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) + end + else + local bpp = Types.Image.bpp(a.format) or 4 + Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) + end + out.meta = a.meta + return out +end + +-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) +function Jpeg.decode(buf: buffer, off: number?, len: number?, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o, l = range(buf, off, len) + local img, st = decodeOne(buf, o, l, opts) + if not img then + return nil, st + end + local s = st :: Decode.State + local wantFields = if opts and opts.fields ~= nil then opts.fields else (s.avi1 == 1 or s.avi1 == 2) + if wantFields and not (opts and opts.orient) then + local e = o + l + local p = nextSoi(buf, s.endPos, e) + if p >= 0 then + local o2 = table.clone(opts or {}) :: any + if o2.maxPixels then + o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) + end + local b = decodeOne(buf, p, e - p, o2) + if b and b.width == img.width and b.height == img.height and b.format == img.format then + local truncated = img.meta.truncated or b.meta.truncated + img = weave(img, b) + img.meta.truncated = truncated + local source: any = img.meta.source + source.fields = 2 + end + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } + +-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local bpp = BPP[img.format] + if not bpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") + end + local w, h = img.width, img.height + local need = if bpp == 0 then w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) else w * h * bpp + if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local quality = o.quality or 90 + if type(quality) ~= "number" or quality < 1 or quality > 100 then + return nil, Err.new(Err.ARG, "quality must be 1..100") + end + local sub = o.subsampling or "420" + if sub ~= "420" and sub ~= "422" and sub ~= "444" then + return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") + end + if bpp == 0 then + sub = "420" + end + local restart = o.restart or 0 + if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then + return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") + end + local gray = o.gray + if gray == nil then + gray = img.format == "gray8" + end + local segments = {} + if o.segments ~= nil then + if type(o.segments) ~= "table" then + return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") + end + for _, sg in o.segments do + if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then + return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") + end + if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then + return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") + end + table.insert(segments, sg) + end + end + local density = o.density + if density ~= nil then + if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then + return nil, Err.new(Err.ARG, "bad density") + end + density = { + unit = math.clamp(math.floor(density.unit), 0, 2), + x = math.clamp(math.floor(density.x), 1, 65535), + y = math.clamp(math.floor(density.y), 1, 65535), + } + end + local out = Encode.run(img.pixels, w, h, bpp, { + quality = quality, + sampling = sub, + progressive = o.progressive == true, + optimize = o.optimize == true, + gray = gray, + restart = restart, + segments = segments, + jfif = o.jfif ~= false, + density = density, + }) + return out, nil +end + +return Jpeg +end +__FILES["codecs/image/Jpeg/Arith"] = @native function() + + + +-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised +-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's +-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. +-- +-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded); +-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a +-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of +-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5 +-- bin at [1280]. +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local band, bxor = bit32.band, bit32.bxor + +local Arith = {} + +-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS +local TAB = buffer.create(114 * 4) +do + local raw = { + { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 }, + { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 }, + { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 }, + { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 }, + { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 }, + { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 }, + { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 }, + { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 }, + { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 }, + { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 }, + { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 }, + { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 }, + { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 }, + { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 }, + { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 }, + { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 }, + { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 }, + { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 }, + { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 }, + { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 }, + { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 }, + { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 }, + { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 }, + } + for i, e in raw do + buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe + writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS + writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS + end +end + +local ZZ: buffer = buffer.create(80) -- set by Arith.init (Scan.ZIGZAG) + +local STATS = 1281 +local POW2 = buffer.create(8) +for i = 0, 7 do + writeu8(POW2, i, 2 ^ i) +end +local FIXED = 1280 + +-- decoder state (one scan at a time; never yields) +local D: buffer = buffer.create(0) +local P = 0 -- next byte +local SEGEND = 0 -- reads at or past this return 0 +local OVER = 0 -- zero bytes supplied past the end +local C, A, CT = 0, 0, -16 +local st: buffer = buffer.create(STATS) + +@native local function decode(s: number): number + while A < 0x8000 do + CT -= 1 + if CT < 0 then + local data = 0 + if P < SEGEND then + data = readu8(D, P) + P += 1 + else + OVER += 1 + end + C = C * 256 + data + CT += 8 + if CT < 0 then + CT += 1 + if CT == 0 then + A = 0x8000 + end + end + end + A *= 2 + end + local sv = readu8(st, s) + local t = band(sv, 0x7F) * 4 + local qe = buffer.readu16(TAB, t) + local nl = readu8(TAB, t + 2) + local nm = readu8(TAB, t + 3) + local temp = A - qe + A = temp + temp *= readu8(POW2, CT) + if C >= temp then + C -= temp + if A < qe then + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nm)) + else + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + end + elseif A < 0x8000 then + if A < qe then + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + else + writeu8(st, s, bxor(band(sv, 0x80), nm)) + end + end + return if sv >= 0x80 then 1 else 0 +end + +@native local function i16(v: number): number + v = band(v, 0xFFFF) + return if v >= 0x8000 then v - 0x10000 else v +end + +type ArithComp = { + coef: buffer, + bpl: number, + h: number, + v: number, + bw: number, + bh: number, + dcTbl: number, -- 0..3 + acTbl: number, + pred: number, + ctx: number, +} + +type ArithParams = { + comps: { ArithComp }, + mcusX: number, + mcusY: number, + ri: number, + mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + ss: number, + se: number, + al: number, + dcL: { number }, -- conditioning per table (DAC), 1-based by table + 1 + dcU: { number }, + acK: { number }, +} + +-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code +@native local function dcDiff(c: ArithComp, L: number, U: number): number? + local base = c.dcTbl * 64 + local s = base + c.ctx + if decode(s) == 0 then + c.ctx = 0 + return c.pred + end + local sign = decode(s + 1) + s = s + 2 + sign + local m = decode(s) + if m ~= 0 then + s = base + 20 + while decode(s) ~= 0 do + m *= 2 + if m == 0x8000 then + return nil + end + s += 1 + end + end + if m < 2 ^ L // 2 then + c.ctx = 0 + elseif m > 2 ^ U // 2 then + c.ctx = 12 + sign * 4 + else + c.ctx = 4 + sign * 4 + end + local v = m + s += 14 + m = m // 2 + while m > 0 do + if decode(s) ~= 0 then + v += m + end + m = m // 2 + end + v += 1 + if sign ~= 0 then + v = -v + end + return band(c.pred + v, 0xFFFF) +end + +-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code +@native local function acFirst(coef: buffer, off: number, tbl: number, ss: number, se: number, K: number, mul: number): boolean + local base = 256 + tbl * 256 + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if decode(s) ~= 0 then + break -- EOB + end + while decode(s + 1) == 0 do + s += 3 + k += 1 + if k > se then + return false + end + end + local sign = decode(FIXED) + s += 2 + local m = decode(s) + if m ~= 0 then + if decode(s) ~= 0 then + m *= 2 + s = base + (if k <= K then 189 else 217) + while decode(s) ~= 0 do + m *= 2 + if m == 0x8000 then + return false + end + s += 1 + end + end + end + local v = m + s += 14 + m = m // 2 + while m > 0 do + if decode(s) ~= 0 then + v += m + end + m = m // 2 + end + v += 1 + if sign ~= 0 then + v = -v + end + writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul)) + k += 1 + end + return true +end + +@native local function acRefine(coef: buffer, off: number, tbl: number, ss: number, se: number, al: number): boolean + local base = 256 + tbl * 256 + local p1 = 2 ^ al + local m1 = -p1 + local kex = se + while kex > 0 do + if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then + break + end + kex -= 1 + end + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if k > kex then + if decode(s) ~= 0 then + break + end + end + while true do + local o = off + readu8(ZZ, k) * 2 + local cv = readi16(coef, o) + if cv ~= 0 then + if decode(s + 2) ~= 0 then + writei16(coef, o, i16(if cv < 0 then cv + m1 else cv + p1)) + end + break + end + if decode(s + 1) ~= 0 then + writei16(coef, o, i16(if decode(FIXED) ~= 0 then m1 else p1)) + break + end + s += 3 + k += 1 + if k > se then + return false + end + end + k += 1 + end + return true +end + +@native function Arith.init(zigzag: buffer) + ZZ = zigzag +end + +-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout) +@native function Arith.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, Pm: ArithParams): boolean + local comps = Pm.comps + local nc = #comps + local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = Pm.mcusX + units = ux * Pm.mcusY + end + local resetDc = mode == 0 or mode == 1 + local resetAc = mode == 0 or mode == 3 or mode == 4 + @native local function reset() + for i = 1, nc do + local c = comps[i] + if resetDc then + buffer.fill(st, c.dcTbl * 64, 0, 64) + c.pred = 0 + c.ctx = 0 + end + if resetAc then + buffer.fill(st, 256 + c.acTbl * 256, 0, 256) + end + end + C, A, CT = 0, 0, -16 + end + D = d + P = 0 + SEGEND = if nrst >= 1 then math.min(rst[1], cleanLen) else cleanLen + OVER = 0 + writeu8(st, FIXED, 113) + reset() + local rstIdx = 0 + local bad = false + local truncated = false + local mul = 2 ^ al + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx += 1 + if rstIdx <= nrst then + P = math.min(rst[rstIdx], cleanLen) + SEGEND = if rstIdx + 1 <= nrst then math.min(rst[rstIdx + 1], cleanLen) else cleanLen + bad = false + else + truncated = true + break + end + reset() + end + if not bad then + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred)) + if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then + bad = true + end + end + elseif mode == 1 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred * mul)) + end + elseif mode == 2 then + if decode(FIXED) ~= 0 then + local cv = readi16(coef, off) + if band(cv, mul) == 0 then + writei16(coef, off, i16(cv + mul)) + end + end + elseif mode == 3 then + if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then + bad = true + end + else + if not acRefine(coef, off, c.acTbl, ss, se, al) then + bad = true + end + end + if bad then + break + end + end + if bad then + break + end + end + if bad then + break + end + end + end + end + D = buffer.create(0) + return truncated +end + +return Arith +end +__FILES["codecs/image/Jpeg/Color"] = @native function() + + + +-- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never +-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's +-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). +-- +-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults: +-- FULL the component is at output resolution +-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4 +-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16 +-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row) +-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample +-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows. +-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and +-- YCCK (Adobe inverted CMYK: R = C * K / 255). +local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32 +local clamp, min, max = math.clamp, math.min, math.max + +local Color = {} + +Color.FULL = 0 +Color.REPLICATE = 1 +Color.H2V1 = 2 +Color.H2V2 = 3 +Color.H1V2 = 4 + +Color.GRAY = 0 +Color.YCC = 1 +Color.RGB = 2 +Color.CMYK = 3 +Color.YCCK = 4 +Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted +Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) + +type Comp = { + plane: buffer, -- u16 samples, stride per row + stride: number, + rows: number, -- plane height + downW: number, -- real samples across / down (the rest is block padding) + downH: number, + method: number, + hIn: number, + hOut: number, + vIn: number, + vOut: number, + row: buffer, -- scratch row (u16, at least max(outW, 2 * downW) + 8 samples) +} + +type Params = { + comps: { Comp }, + space: number, + outW: number, + outH: number, + maxv: number, + pixels: buffer, + -- YCbCr tables (maxv + 1 i32 entries) + crr: buffer, + cbb: buffer, + crg: buffer, + cbg: buffer, + toByte: buffer?, -- maxv + 1 u8 entries (12-bit), nil for 8-bit + hook: (() -> ())?, -- a cooperative yield point every 8 rows (pcall'ed: it can't throw through here) +} + +-- jdcolor.c build_ycc_rgb_table +@native function Color.tables(maxv: number): (buffer, buffer, buffer, buffer) + local n = maxv + 1 + local center = n // 2 + local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) + @native local function fix(x: number): number + return math.floor(x * 65536 + 0.5) + end + for i = 0, maxv do + local x = i - center + buffer.writei32(crr, i * 4, (fix(1.40200) * x + 32768) // 65536) + buffer.writei32(cbb, i * 4, (fix(1.77200) * x + 32768) // 65536) + buffer.writei32(crg, i * 4, -fix(0.71414) * x) + buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768) + end + return crr, cbb, crg, cbg +end + +-- fills c.row with output row y; returns the buffer and byte offset of the row's samples +@native local function fetch(c: Comp, y: number, outW: number): (buffer, number) + local method = c.method + local plane, stride, row = c.plane, c.stride, c.row + if method == 0 then + return plane, min(y, c.rows - 1) * stride * 2 + elseif method == 2 then + local w = c.downW + local b = min(y, c.rows - 1) * stride * 2 + local cur = readu16(plane, b) + writeu16(row, 0, cur) + local nxt = readu16(plane, b + 2) + writeu16(row, 2, (cur * 3 + nxt + 2) // 4) + local prev = cur + cur = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b + (i + 1) * 2) + local v3 = cur * 3 + writeu16(row, i * 4, (v3 + prev + 1) // 4) + writeu16(row, i * 4 + 2, (v3 + nxt + 2) // 4) + prev = cur + cur = nxt + end + writeu16(row, (w - 1) * 4, (cur * 3 + prev + 1) // 4) + writeu16(row, (w - 1) * 4 + 2, cur) + return row, 0 + elseif method == 3 then + local w = c.downW + local iy = min(y // 2, c.downH - 1) + local oy = if y % 2 == 0 then max(iy - 1, 0) else min(iy + 1, c.downH - 1) + local b0, b1 = iy * stride * 2, oy * stride * 2 + local this = readu16(plane, b0) * 3 + readu16(plane, b1) + local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2) + writeu16(row, 0, (this * 4 + 8) // 16) + writeu16(row, 2, (this * 3 + nxt + 7) // 16) + local last = this + this = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2) + local t3 = this * 3 + writeu16(row, i * 4, (t3 + last + 8) // 16) + writeu16(row, i * 4 + 2, (t3 + nxt + 7) // 16) + last = this + this = nxt + end + writeu16(row, (w - 1) * 4, (this * 3 + last + 8) // 16) + writeu16(row, (w - 1) * 4 + 2, (this * 4 + 7) // 16) + return row, 0 + elseif method == 4 then + local iy = min(y // 2, c.downH - 1) + local oy, bias + if y % 2 == 0 then + oy, bias = max(iy - 1, 0), 1 + else + oy, bias = min(iy + 1, c.downH - 1), 2 + end + local b0, b1 = iy * stride * 2, oy * stride * 2 + for x = 0, outW - 1 do + writeu16(row, x * 2, (readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) // 4) + end + return row, 0 + else + local hIn, hOut = c.hIn, c.hOut + local iy = min((y * c.vIn) // c.vOut, c.rows - 1) + local b = iy * stride * 2 + local last = stride - 1 + for x = 0, outW - 1 do + writeu16(row, x * 2, readu16(plane, b + min((x * hIn) // hOut, last) * 2)) + end + return row, 0 + end +end + +@native function Color.run(P: Params) + local comps = P.comps + local nc = #comps + local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels + local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg + local toByte = P.toByte + local o = 0 + local hook = P.hook + for y = 0, outH - 1 do + if hook and y > 0 and y % 8 == 0 then + pcall(hook) + end + local s0, b0 = fetch(comps[1], y, outW) + if space == 0 or nc < 3 then + for x = 0, outW - 1 do + local v = readu16(s0, b0 + x * 2) + if toByte then + v = readu8(toByte, v) + end + writeu32(out, o, 0xFF000000 + v * 0x10101) + o += 4 + end + else + local s1, b1 = fetch(comps[2], y, outW) + local s2, b2 = fetch(comps[3], y, outW) + local s3, b3 = s0, b0 + if nc >= 4 then + s3, b3 = fetch(comps[4], y, outW) + end + if space == 6 then + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local c3 = if nc >= 4 then readu16(s3, b3 + i) else maxv + if toByte then + c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3) + end + writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216) + o += 4 + end + continue + end + if space == 1 and not toByte then + -- the common case: 8-bit YCbCr + for x = 0, outW - 1 do + local i = x * 2 + local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r = clamp(yv + readi32(crr, cr * 4), 0, 255) + local g = clamp(yv + (readi32(cbg, cb * 4) + readi32(crg, cr * 4)) // 65536, 0, 255) + local b = clamp(yv + readi32(cbb, cb * 4), 0, 255) + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o += 4 + end + continue + end + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r, g, b + if space == 2 then + r, g, b = c0, c1, c2 + elseif space == 3 or space == 5 then + local k = readu16(s3, b3 + i) + if space == 5 then + c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k + end + r = (c0 * k + maxv // 2) // maxv + g = (c1 * k + maxv // 2) // maxv + b = (c2 * k + maxv // 2) // maxv + else + r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv) + g = clamp(c0 + (readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) // 65536, 0, maxv) + b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv) + if space == 4 then + -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored + local k = readu16(s3, b3 + i) + r = ((maxv - r) * k + maxv // 2) // maxv + g = ((maxv - g) * k + maxv // 2) // maxv + b = ((maxv - b) * k + maxv // 2) // maxv + end + end + if toByte then + r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b) + end + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o += 4 + end + end + end +end + +return Color +end +__FILES["codecs/image/Jpeg/Decode"] = function() + +-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / +-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: +-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM +-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a +-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows +-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats. +local Scan = __include("codecs/image/Jpeg/Scan") +local Arith = __include("codecs/image/Jpeg/Arith") +local Color = __include("codecs/image/Jpeg/Color") +local Tables = __include("codecs/image/Jpeg/Tables") +local Yuv = __include("codecs/image/Jpeg/Yuv") +local Dct = __include("codecs/image/Dct") + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local Decode = {} + +Arith.init(Scan.ZIGZAG) + +local function be16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +local stdBuilt: { [string]: buffer } = {} +local function stdTable(class: string, slot: number): buffer? + local key = class .. slot + if not stdBuilt[key] then + local def = (if class == "dc" then Tables.DC else Tables.AC)[slot + 1] + if not def then + return nil + end + stdBuilt[key] = Scan.buildTable(def.counts, def.symbols) + end + return stdBuilt[key] +end + +-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e) +local function exif(b: buffer, p: number, e: number): (number?, number?) + if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then + return nil, nil + end + local t = p + 6 + local le + local bo = buffer.readstring(b, t, 2) + if bo == "II" then + le = true + elseif bo == "MM" then + le = false + else + return nil, nil + end + local function r16(at: number): number + if le then + return readu8(b, at) + readu8(b, at + 1) * 256 + end + return readu8(b, at) * 256 + readu8(b, at + 1) + end + local function r32(at: number): number + if le then + return r16(at) + r16(at + 2) * 65536 + end + return r16(at) * 65536 + r16(at + 2) + end + local ifd = t + r32(t + 4) + if ifd + 2 > e then + return t, nil + end + local count = r16(ifd) + for i = 0, count - 1 do + local en = ifd + 2 + i * 12 + if en + 12 > e then + return t, nil + end + if r16(en) == 0x0112 then + local v = r16(en + 8) + return t, if v >= 1 and v <= 8 then v else nil + end + end + return t, nil +end + +type Comp = { + id: number, + h: number, + v: number, + tq: number, + bpl: number, + bpc: number, + bw: number, + bh: number, + coef: buffer?, + quant: buffer?, -- latched at the component's first scan + dct: buffer?, + act: buffer?, + dcTbl: number, + acTbl: number, + pred: number, + ctx: number, +} + +type Frame = { + width: number, + height: number, + precision: number, + progressive: boolean, + arithmetic: boolean, + comps: { Comp }, + hmax: number, + vmax: number, + mcusX: number, + mcusY: number, +} + +local SOF_REFUSED = { + [0xC3] = "lossless", + [0xC5] = "hierarchical", + [0xC6] = "hierarchical", + [0xC7] = "hierarchical", + [0xCB] = "lossless arithmetic-coded", + [0xCD] = "hierarchical arithmetic-coded", + [0xCE] = "hierarchical arithmetic-coded", + [0xCF] = "hierarchical arithmetic-coded", +} + +-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated" +local function parseSof(b: buffer, p: number, e: number, m: number): (Frame?, string?, string?) + if e - p < 6 then + return nil, "corrupt", "short SOF" + end + local prec = readu8(b, p) + local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5) + if prec ~= 8 and prec ~= 12 then + return nil, "unsupported", "sample precision " .. prec + end + if width == 0 or height == 0 then + if height == 0 and width > 0 then + return nil, "unsupported", "DNL (height 0 in the frame header)" + end + return nil, "corrupt", "bad size " .. width .. "x" .. height + end + if nf ~= 1 and nf ~= 3 and nf ~= 4 then + return nil, "unsupported", "component count " .. nf + end + if e - p < 6 + nf * 3 then + return nil, "corrupt", "short SOF" + end + local comps: { Comp } = {} + local hmax, vmax = 1, 1 + for i = 0, nf - 1 do + local q = p + 6 + i * 3 + local hv = readu8(b, q + 1) + local h, v, tq = rshift(hv, 4), band(hv, 15), readu8(b, q + 2) :: number + if h < 1 or h > 4 or v < 1 or v > 4 then + return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v + end + if tq > 3 then + return nil, "corrupt", "bad quantisation table selector " .. tq + end + local id = readu8(b, q) + for _, c in comps do + if c.id == id then + return nil, "corrupt", "duplicate component id " .. id + end + end + hmax, vmax = math.max(hmax, h), math.max(vmax, v) :: number + table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } :: Comp) + end + local mcusX = math.ceil(width / (8 * hmax)) + local mcusY = math.ceil(height / (8 * vmax)) + for _, c in comps do + c.bpl = mcusX * c.h + c.bpc = mcusY * c.v + c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8) + c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8) + end + return { + width = width, + height = height, + precision = prec, + progressive = m == 0xC2 or m == 0xCA, + arithmetic = m == 0xC9 or m == 0xCA, + comps = comps, + hmax = hmax, + vmax = vmax, + mcusX = mcusX, + mcusY = mcusY, + }, nil, nil +end + +local function colorSpaceOf(frame: Frame, adobe: number?, jfif: boolean): string + local n = #frame.comps + if n == 1 then + return "gray" + elseif n == 3 then + if adobe ~= nil then + return if adobe == 0 then "rgb" else "ycbcr" + end + local c = frame.comps + if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then + return "rgb" + end + return "ycbcr" + end + return if adobe == 2 then "ycck" else "cmyk" +end +Decode.colorSpaceOf = colorSpaceOf + +-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT +-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions). +local function idctSize(f: Frame, c: Comp, scale: number): number + local minSize = 8 // scale + local ssize = minSize + while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do + ssize *= 2 + end + return ssize +end + +type State = { + frame: any, + adobe: number?, + jfif: boolean, + density: { unit: number, x: number, y: number }?, + orientation: number, + exif: buffer?, + icc: buffer?, + comments: { string }, + truncated: boolean, + raw: boolean, -- opts.raw: no colour conversion + scale: number, + avi1: number?, -- the AVI1 APP0 field polarity (0 = progressive, 1 / 2 = interlaced: two fields back to back) + endPos: number, -- the byte after the EOI marker (or the end of the data) + hook: (() -> ())?, -- opts.yield: the cooperative yield point (scans, IDCT, colour conversion) +} + +-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with +-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients. +function Decode.parse(b: buffer, base: number, n: number, opts: any, headerOnly: boolean): (State?, string?, string?) + if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then + return nil, "corrupt", "not a JPEG file (no SOI marker)" + end + local scale = (opts and opts.scale) or 1 + if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then + return nil, "arg", "scale must be 1, 2, 4 or 8" + end + local maxPixels: number = (opts and opts.maxPixels) or 2 ^ 26 + local quant: { [number]: buffer } = {} + local dcT: { [number]: buffer } = {} + local acT: { [number]: buffer } = {} + local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 } + local frame: Frame? = nil + local st: State = { + frame = nil, + adobe = nil, + jfif = false, + density = nil, + orientation = 1, + exif = nil, + icc = nil, + comments = {}, + truncated = false, + raw = opts ~= nil and opts.raw == true, + scale = scale, + avi1 = nil, + endPos = n, + hook = if opts and type(opts.yield) == "function" then opts.yield else nil, + } + local iccChunks: { buffer } = {} + local ri = 0 + local scans = 0 + local clean: buffer? = nil + local rst = {} + local pos = base + 2 + while pos < n do + -- find the next marker (tolerate garbage and fill bytes) + if readu8(b, pos) ~= 0xFF then + pos += 1 + continue + end + while pos < n and readu8(b, pos) == 0xFF do + pos += 1 + end + if pos >= n then + break + end + local m = readu8(b, pos) + pos += 1 + if m == 0xD9 then + st.endPos = pos + break -- EOI + elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then + continue -- standalone markers (or stray stuffing) + end + if pos + 2 > n then + st.truncated = true + break + end + local len = be16(b, pos) + if len < 2 then + return nil, "corrupt", string.format("bad segment length for marker %02X", m) + end + local p, e = pos + 2, pos + len + if e > n then + if m == 0xDA and frame and not headerOnly then + e = n -- a truncated SOS header still fails below + else + st.truncated = true + break + end + end + pos = e + if m == 0xE0 then + if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then + st.jfif = true + st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) } + elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then + st.avi1 = readu8(b, p + 4) + end + elseif m == 0xE1 then + local t, o = exif(b, p, e) + if t and not st.exif then + local x = buffer.create(e - t) + buffer.copy(x, 0, b, t, e - t) + st.exif = x + end + if o then + st.orientation = o + end + elseif m == 0xE2 then + -- ICC_PROFILE\0, sequence number, count, data + if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then + local seq = readu8(b, p + 12) + local x = buffer.create(e - p - 14) + buffer.copy(x, 0, b, p + 14, e - p - 14) + if seq >= 1 then + iccChunks[seq] = x + end + end + elseif m == 0xEE then + if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then + st.adobe = readu8(b, p + 11) + end + elseif m == 0xFE then + table.insert(st.comments, buffer.readstring(b, p, e - p)) + elseif m == 0xDB then + -- DQT + while p < e do + local pt = readu8(b, p) + local pq, tq = rshift(pt, 4), band(pt, 15) + local size = if pq == 0 then 64 else 128 + if tq > 3 or pq > 1 or p + 1 + size > e then + return nil, "corrupt", "bad DQT segment" + end + local q = buffer.create(128) + for k = 0, 63 do + local v = if pq == 0 then readu8(b, p + 1 + k) else be16(b, p + 1 + k * 2) + buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v) + end + quant[tq] = q + p += 1 + size + end + elseif m == 0xC4 then + -- DHT + while p < e do + if p + 17 > e then + return nil, "corrupt", "bad DHT segment" + end + local tc = readu8(b, p) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DHT table class / slot" + end + local counts, total = {}, 0 + for l = 1, 16 do + counts[l] = readu8(b, p + l) + total += counts[l] + end + if total > 256 or p + 17 + total > e then + return nil, "corrupt", "bad DHT segment" + end + local syms = {} + for i = 1, total do + syms[i] = readu8(b, p + 16 + i) + end + local t = Scan.buildTable(counts, syms) + if class == 0 then + dcT[slot] = t + else + acT[slot] = t + end + p += 17 + total + end + elseif m == 0xCC then + -- DAC: arithmetic conditioning + while p + 2 <= e do + local tc, v = readu8(b, p), readu8(b, p + 1) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DAC segment" + end + if class == 0 then + local L, U = band(v, 15), rshift(v, 4) + if L > U then + return nil, "corrupt", "bad DAC value" + end + dcL[slot + 1], dcU[slot + 1] = L, U + else + if v < 1 or v > 63 then + return nil, "corrupt", "bad DAC value" + end + acK[slot + 1] = v + end + p += 2 + end + elseif m == 0xDD then + if e - p < 2 then + return nil, "corrupt", "bad DRI segment" + end + ri = be16(b, p) + elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then + if frame then + return nil, "corrupt", "more than one frame header" + end + local f, code, err = parseSof(b, p, e, m) + if not f then + return nil, code, err + end + if f.width * f.height > maxPixels then + return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels) + end + frame = f + st.frame = f + if headerOnly then + return st, nil, nil + end + elseif SOF_REFUSED[m] then + return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" + elseif m == 0xDA then + if headerOnly then + break + end + if not frame then + return nil, "corrupt", "scan before the frame header" + end + local f = frame :: Frame + local ns = if p < e then readu8(b, p) else 0 + if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then + return nil, "corrupt", "bad SOS segment" + end + local sc: { Comp } = {} + local blocks = 0 + for i = 0, ns - 1 do + local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2) + local comp = nil + for _, c in f.comps do + if c.id == id then + comp = c + end + end + if not comp or table.find(sc, comp) then + return nil, "corrupt", "scan names an unknown component " .. id + end + local td, ta = rshift(t, 4), band(t, 15) + if td > 3 or ta > 3 then + return nil, "corrupt", "bad entropy table selector" + end + comp.dcTbl, comp.acTbl = td, ta + if not f.arithmetic then + comp.dct = dcT[td] or stdTable("dc", td) + comp.act = acT[ta] or stdTable("ac", ta) + end + blocks += comp.h * comp.v + table.insert(sc, comp) + end + local q = p + 1 + ns * 2 + local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + local ah, al = rshift(a, 4), band(a, 15) + if ns > 1 and blocks > 10 then + return nil, "corrupt", "more than 10 blocks per MCU" + end + local mode + if not f.progressive then + mode = 0 + ss, se, ah, al = 0, 63, 0, 0 + else + if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then + return nil, "corrupt", "bad progressive scan parameters" + end + if ss == 0 then + mode = if ah == 0 then 1 else 2 + else + mode = if ah == 0 then 3 else 4 + end + end + for _, c in sc do + if not f.arithmetic then + if (mode == 0 or mode == 1) and not c.dct then + return nil, "corrupt", "missing DC Huffman table" + end + if (mode == 0 or mode == 3 or mode == 4) and not c.act then + return nil, "corrupt", "missing AC Huffman table" + end + end + if not c.coef then + c.coef = buffer.create(c.bpl * c.bpc * 128) + end + if not c.quant then + c.quant = quant[c.tq] + end + end + if not clean then + clean = buffer.create(n - base + Scan.PAD) + end + local cb = clean :: buffer + local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst) + if nextPos >= n then + st.truncated = true -- no EOI + end + -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans + if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then + local params = { + comps = sc :: any, + mcusX = f.mcusX, + mcusY = f.mcusY, + ri = ri, + mode = mode, + ss = ss, + se = se, + al = al, + hook = st.hook, + dcL = dcL, + dcU = dcU, + acK = acK, + } + local short + if f.arithmetic then + short = Arith.run(cb, cleanLen, rst, nrst, params) + else + local _ + _, short = Scan.run(cb, cleanLen, rst, nrst, params) + end + st.truncated = st.truncated or short + end + scans += 1 + pos = nextPos + end + end + if not frame then + return nil, if st.truncated then "truncated" else "corrupt", "no frame header" + end + if #iccChunks > 0 then + local total = 0 + for _, c in iccChunks do + total += buffer.len(c) + end + local icc = buffer.create(total) + local o = 0 + for _, c in iccChunks do + buffer.copy(icc, o, c) + o += buffer.len(c) + end + st.icc = icc + end + if headerOnly then + return st, nil, nil + end + if scans == 0 then + return nil, "truncated", "no image data" + end + return st, nil, nil +end + +local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } + +local tableCache: { [number]: { buffer } } = {} +local function yccTables(maxv: number): { buffer } + local t = tableCache[maxv] + if not t then + local a, b, c, d = Color.tables(maxv) + t = { a, b, c, d } + tableCache[maxv] = t + end + return t +end + +local toByte12: buffer? = nil + +-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message +function Decode.output(st: State): (number?, any, any, string?) + local f: Frame = st.frame + local scale = st.scale + local minSize = 8 // scale + local maxv = if f.precision == 12 then 4095 else 255 + local center = (maxv + 1) // 2 + local p1 = if f.precision == 12 then 1 else 2 + local outW = math.ceil(f.width * minSize / 8) + local outH = math.ceil(f.height * minSize / 8) + local fancy = minSize > 1 + local ccomps = {} + local zeroQ = buffer.create(128) + for _, c in f.comps do + local ssize = idctSize(f, c, scale) + local stride, rows = c.bpl * ssize, c.bpc * ssize + local plane = buffer.create(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + if c.coef then + return nil, "corrupt", "missing quantisation table " .. c.tq + end + q = zeroQ -- the component never appeared in a scan: mid grey + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, ssize, plane, p1, center, maxv, st.hook) + local hIn, hOut = c.h * ssize // minSize, f.hmax + local vIn, vOut = c.v * ssize // minSize, f.vmax + local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8)) + local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8)) + local method + if hIn == hOut and vIn == vOut then + method = Color.FULL + elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then + method = Color.H2V2 + elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then + method = Color.H2V1 + elseif hIn == hOut and vIn * 2 == vOut and fancy then + method = Color.H1V2 + else + method = Color.REPLICATE + end + table.insert(ccomps, { + plane = plane, + stride = stride, + rows = rows, + downW = downW, + downH = downH, + method = method, + hIn = hIn, + hOut = hOut, + vIn = vIn, + vOut = vOut, + row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), + }) + c.coef = nil -- free the coefficients early + end + local space = colorSpaceOf(f, st.adobe, st.jfif) + local spaceId = SPACE_IDS[space] + if space == "cmyk" and st.adobe == nil then + spaceId = Color.CMYK_PLAIN + end + if st.raw then + spaceId = Color.RAW + end + local t = yccTables(maxv) + local tb = nil + if maxv == 4095 then + if not toByte12 then + local tbuf = buffer.create(4096) + for v = 0, 4095 do + buffer.writeu8(tbuf, v, (v * 255 + 2047) // 4095) + end + toByte12 = tbuf + end + tb = toByte12 + end + local pixels = buffer.create(outW * outH * 4) + Color.run({ + comps = ccomps, + space = spaceId, + outW = outW, + outH = outH, + maxv = maxv, + pixels = pixels, + crr = t[1], + cbb = t[2], + crg = t[3], + cbg = t[4], + toByte = tb, + hook = st.hook, + }) + return outW, outH, pixels, space +end + +-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the +-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion +-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half +-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma +-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": +-- chroma 128). Full scale only (opts.scale = 1). +-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes +-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +local scratch: buffer? = nil +local function scratchPlane(n: number): buffer + local sc = scratch + if sc and buffer.len(sc) >= n then + return sc + end + local b = buffer.create(n) + if n <= 4 * 1024 * 1024 then + scratch = b + end + return b +end + +function Decode.outputYuv(st: State): (number?, number?, buffer?, string?) + local f: Frame = st.frame + if st.scale ~= 1 or f.precision ~= 8 then + return nil, nil, nil, nil + end + local comps = f.comps + local space = colorSpaceOf(f, st.adobe, st.jfif) + local mode = nil + if space == "gray" then + mode = "gray" + elseif space == "ycbcr" then + -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) + local l, cb, cr = comps[1], comps[2], comps[3] + if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then + local rh, rv = f.hmax // cb.h, f.vmax // cb.v + if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then + mode = nil + elseif rh == 2 and rv == 2 then + mode = "420" + elseif rh == 2 and rv == 1 then + mode = "422" + elseif rh == 1 and rv == 1 then + mode = "444" + end + end + end + if not mode then + return nil, nil, nil, nil + end + for _, c in comps do + if c.coef and not c.quant then + return nil, nil, nil, nil -- output() reports the missing table + end + end + local w, h = f.width, f.height + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local out = buffer.create(w * h + 2 * cw * ch) + local zeroQ: buffer? = nil + for i, c in comps do + local stride, rows = c.bpl * 8, c.bpc * 8 + local plane = scratchPlane(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey + q = zeroQ + end + Dct.idctComponent(coef, q :: buffer, c.bpl, c.bpc, 8, plane, 2, 128, 255, st.hook) + if i == 1 then + Yuv.crop(plane, stride, w, h, out, 0) + elseif mode == "420" then + Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) + elseif mode == "422" then + Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) + else + Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) + end + c.coef = nil + end + if mode == "gray" then + buffer.fill(out, w * h, 128, 2 * cw * ch) + end + return w, h, out, mode +end + +return Decode +end +__FILES["codecs/image/Jpeg/Encode"] = @native function() + + + +-- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman +-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr +-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG +-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's +-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c +-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), +-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, +-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. +local Dct = __include("codecs/image/Dct") +local Tables = __include("codecs/image/Jpeg/Tables") + +local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16 +local band, countlz = bit32.band, bit32.countlz + +local Encode = {} + +-- natural order index of zigzag position k +local ZZ = buffer.create(64) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + end + end +end +Encode.ZIGZAG = ZZ + +-- ------------------------------------------------------------------------------------------------ output +local OUT = buffer.create(0) +local OP = 0 +local CAP = 0 +local ACC, NB = 0, 0 +local GATHER = false + +@native local function grow(n: number) + if OP + n > CAP then + local c = math.max(CAP * 2, OP + n + 1024) + local nb = buffer.create(c) + buffer.copy(nb, 0, OUT, 0, OP) + OUT = nb + CAP = c + end +end + +@native local function byte(v: number) + grow(1) + writeu8(OUT, OP, v) + OP += 1 +end + +@native local function u16be(v: number) + byte(v // 256) + byte(v % 256) +end + +-- n bits of v (n <= 16), MSB first, with 0xFF stuffing +@native local function bits(v: number, n: number) + if GATHER or n == 0 then + return + end + local p = 2 ^ n + ACC = ACC * p + band(v, p - 1) + NB += n + while NB >= 8 do + NB -= 8 + local d = 2 ^ NB + local b = ACC // d + ACC -= b * d + grow(2) + writeu8(OUT, OP, b) + OP += 1 + if b == 0xFF then + writeu8(OUT, OP, 0) + OP += 1 + end + end +end + +@native local function flushBits() + if NB > 0 then + bits(0x7F, 8 - NB) -- pad with ones + end + ACC, NB = 0, 0 +end + +@native local function nbits(v: number): number + return if v == 0 then 0 else 32 - countlz(v) +end + +-- ------------------------------------------------------------------------------------------------ Huffman tables +-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) +type Derived = { code: buffer, size: buffer } + +@native local function derive(counts: { number }, symbols: { number }): Derived + local code, size = buffer.create(512), buffer.create(256) + local c, k = 0, 1 + for l = 1, 16 do + for _ = 1, counts[l] or 0 do + local s = symbols[k] + if s then + writeu16(code, s * 2, c) + writeu8(size, s, l) + end + k += 1 + c += 1 + end + c *= 2 + end + return { code = code, size = size } +end + +-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols +@native local function optimal(freqIn: { number }): ({ number }, { number }) + local freq = table.create(257, 0) + local bitsT = table.create(34, 0) + local codesize = table.create(257, 0) + local others = table.create(257, -1) + local nz = table.create(257, 0) + local n = 0 + for i = 0, 256 do + local f = if i == 256 then 1 else freqIn[i + 1] + if f > 0 then + n += 1 + nz[n] = i + freq[n] = f + end + end + while true do + local c1, c2 = -1, -1 + local v, v2 = 1e9, 1e9 + for i = 1, n do + local f = freq[i] + if f <= v2 then + if f <= v then + c2 = c1 + v2 = v + v = f + c1 = i + else + v2 = f + c2 = i + end + end + end + if c2 < 0 then + break + end + freq[c1] += freq[c2] + freq[c2] = 1000000001 + codesize[c1] += 1 + while others[c1] >= 0 do + c1 = others[c1] + codesize[c1] += 1 + end + others[c1] = c2 + codesize[c2] += 1 + while others[c2] >= 0 do + c2 = others[c2] + codesize[c2] += 1 + end + end + for i = 1, n do + local cs = math.min(codesize[i], 32) + bitsT[cs + 1] += 1 + end + local bitPos = table.create(34, 0) + local p = 0 + for i = 1, 32 do + bitPos[i + 1] = p + p += bitsT[i + 1] + end + local i = 32 + while i > 16 do + while bitsT[i + 1] > 0 do + local j = i - 2 + while bitsT[j + 1] == 0 do + j -= 1 + end + bitsT[i + 1] -= 2 + bitsT[i] += 1 + bitsT[j + 2] += 2 + bitsT[j + 1] -= 1 + end + i -= 1 + end + while bitsT[i + 1] == 0 do + i -= 1 + end + bitsT[i + 1] -= 1 + local counts = table.create(16, 0) + for l = 1, 16 do + counts[l] = bitsT[l + 1] + end + local symbols = table.create(n, 0) + for k = 1, n - 1 do + local cs = math.min(codesize[k], 32) + symbols[bitPos[cs + 1] + 1] = nz[k] + bitPos[cs + 1] += 1 + end + local total = 0 + for l = 1, 16 do + total += counts[l] + end + local out = table.create(total, 0) + for k = 1, total do + out[k] = symbols[k] + end + return counts, out +end +Encode.optimal = optimal + +-- ------------------------------------------------------------------------------------------------ entropy coding state +local dcTab: { Derived } = {} +local acTab: { Derived } = {} +local dcFreq: { { number } } = {} +local acFreq: { { number } } = {} + +@native local function symbol(t: Derived, freq: { number }, s: number) + if GATHER then + freq[s + 1] += 1 + else + bits(readu16(t.code, s * 2), readu8(t.size, s)) + end +end + +type Comp = { + id: number, + h: number, + v: number, + tq: number, + td: number, -- DC table slot + ta: number, -- AC table slot + bw: number, -- real blocks across / down + bh: number, + bpl: number, -- MCU-padded block grid + bpc: number, + coef: buffer, -- i16, 64 per block, natural order + last: number, -- DC predictor +} + +@native local function dcDiff(c: Comp, diff: number) + local t = diff + local t2 = diff + if t < 0 then + t = -t + t2 -= 1 + end + local n = nbits(t) + symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n) + if n > 0 then + bits(t2, n) + end +end + +-- jchuff.c encode_one_block +@native local function blockSeq(c: Comp, off: number) + local coef = c.coef + local dc = readi16(coef, off) + dcDiff(c, dc - c.last) + c.last = dc + local at, af = acTab[c.ta + 1], acFreq[c.ta + 1] + local r = 0 + for k = 1, 63 do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + if v == 0 then + r += 1 + else + while r > 15 do + symbol(at, af, 0xF0) + r -= 16 + end + local t, t2 = v, v + if t < 0 then + t = -t + t2 -= 1 + end + local n = nbits(t) + symbol(at, af, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + symbol(at, af, 0) + end +end + +-- progressive state (jcphuff.c) +local EOBRUN = 0 +local BE = 0 +local CORR = table.create(1000, 0) :: { number } +local curAc: Derived = { code = buffer.create(512), size = buffer.create(256) } +local curAcFreq: { number } = {} + +@native local function emitEobrun() + if EOBRUN > 0 then + local n = nbits(EOBRUN) - 1 + symbol(curAc, curAcFreq, n * 16) + if n > 0 then + bits(EOBRUN, n) + end + EOBRUN = 0 + if not GATHER then + for i = 1, BE do + bits(CORR[i], 1) + end + end + BE = 0 + end +end + +@native local function blockDcFirst(c: Comp, off: number, al: number) + local t2 = readi16(c.coef, off) // 2 ^ al + dcDiff(c, t2 - c.last) + c.last = t2 +end + +@native local function blockAcFirst(c: Comp, off: number, ss: number, se: number, al: number) + local coef = c.coef + local d = 2 ^ al + local r = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t, t2 + if v < 0 then + t = (-v) // d + t2 = -t - 1 -- ~t + else + t = v // d + t2 = t + end + if t == 0 then + r += 1 + else + emitEobrun() + while r > 15 do + symbol(curAc, curAcFreq, 0xF0) + r -= 16 + end + local n = nbits(t) + symbol(curAc, curAcFreq, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + EOBRUN += 1 + if EOBRUN == 0x7FFF then + emitEobrun() + end + end +end + +local absv = table.create(64, 0) + +@native local function blockAcRefine(c: Comp, off: number, ss: number, se: number, al: number) + local coef = c.coef + local d = 2 ^ al + local eob = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t = (if v < 0 then -v else v) // d + absv[k + 1] = t + if t == 1 then + eob = k + end + end + local r = 0 + local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..] + local brStart = BE + for k = ss, se do + local t = absv[k + 1] + if t == 0 then + r += 1 + continue + end + while r > 15 and k <= eob do + emitEobrun() + symbol(curAc, curAcFreq, 0xF0) + r -= 16 + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + end + if t > 1 then + br += 1 + CORR[brStart + br] = t % 2 + continue + end + emitEobrun() + symbol(curAc, curAcFreq, r * 16 + 1) + bits(if readi16(coef, off + readu8(ZZ, k) * 2) < 0 then 0 else 1, 1) + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + r = 0 + end + if r > 0 or br > 0 then + EOBRUN += 1 + BE += br + if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then + emitEobrun() + end + end +end + +-- ------------------------------------------------------------------------------------------------ scans +type ScanSpec = { comps: { number }, ss: number, se: number, ah: number, al: number } + +-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0 +@native local function walk(comps: { Comp }, mcusX: number, mcusY: number, ri: number, onRestart: (number) -> (), fn: (Comp, number) -> ()) + local nc = #comps + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = mcusX + units = ux * mcusY + end + local rn = 0 + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + onRestart(rn) + rn = (rn + 1) % 8 + end + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + if nc == 1 then + fn(c, (my * c.bpl + mx) * 128) + else + for by = my * c.v, my * c.v + c.v - 1 do + for bx = mx * c.h, mx * c.h + c.h - 1 do + fn(c, (by * c.bpl + bx) * 128) + end + end + end + end + end +end + +@native local function dht(class: number, slot: number, counts: { number }, symbols: { number }) + byte(0xFF) + byte(0xC4) + u16be(2 + 17 + #symbols) + byte(class * 16 + slot) + for l = 1, 16 do + byte(counts[l]) + end + for _, s in symbols do + byte(s) + end +end + +@native local function sos(comps: { Comp }, ss: number, se: number, ah: number, al: number, dcOnly: boolean, acOnly: boolean) + byte(0xFF) + byte(0xDA) + u16be(6 + 2 * #comps) + byte(#comps) + for _, c in comps do + byte(c.id) + local td = if acOnly then 0 else c.td + local ta = if dcOnly then 0 else c.ta + byte(td * 16 + ta) + end + byte(ss) + byte(se) + byte(ah * 16 + al) +end + +-- ------------------------------------------------------------------------------------------------ planes +-- jccolor.c rgb_ycc_start tables (16-bit fixed point) +@native local function fix(x: number): number + return math.floor(x * 65536 + 0.5) +end +local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400) +local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) +local CRG, CRB = fix(0.41869), fix(0.08131) +local OFF = 128 * 65536 + 32768 - 1 + +-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output) +@native local function planes(px: buffer, w: number, h: number, bpp: number, gray: boolean): (buffer, buffer?, buffer?) + local n = w * h + local Y = buffer.create(n) + if bpp == 1 then + buffer.copy(Y, 0, px, 0, n) + if gray then + return Y, nil, nil + end + local Cb = buffer.create(n) + buffer.fill(Cb, 0, 128, n) + local Cr = buffer.create(n) + buffer.fill(Cr, 0, 128, n) + return Y, Cb, Cr + end + if gray then + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) + end + return Y, nil, nil + end + local Cb, Cr = buffer.create(n), buffer.create(n) + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, (YR * r + YG * g + YB * b + 32768) // 65536) + writeu8(Cb, i, (-CBR * r - CBG * g + HALF * b + OFF) // 65536) + writeu8(Cr, i, (HALF * r - CRG * g - CRB * b + OFF) // 65536) + end + return Y, Cb, Cr +end + +-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf +-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row +@native local function downsample(src: buffer, w: number, h: number, hf: number, vf: number, outW: number, outH: number): buffer + local out = buffer.create(outW * outH) + for oy = 0, outH - 1 do + local r0 = math.min(oy * vf, h - 1) * w + local r1 = math.min(oy * vf + vf - 1, h - 1) * w + local bias = if hf == 2 and vf == 2 then 1 elseif hf == 2 then 0 else (if vf == 2 then 1 else 0) + for ox = 0, outW - 1 do + local x0 = math.min(ox * hf, w - 1) + local x1 = math.min(ox * hf + hf - 1, w - 1) + local v + if hf == 2 and vf == 2 then + v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) // 4 + bias = 3 - bias + elseif hf == 2 then + v = (readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) // 2 + bias = 1 - bias + else + v = (readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) // 2 + bias = 1 - bias + end + writeu8(out, oy * outW + ox, v) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ encode +type Options = { + quality: number, -- 1..100 + sampling: string, -- "444" | "422" | "420" + progressive: boolean, + optimize: boolean, -- baseline: optimised Huffman tables (progressive always optimises) + gray: boolean, + restart: number, -- MCUs per restart interval (0 = none) + segments: { { marker: number, data: buffer } }, -- APPn / COM segments after the JFIF header + jfif: boolean, + density: { unit: number, x: number, y: number }?, +} + +-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: +-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The +-- caller validated sizes (1..65535), the buffer length and options. +@native function Encode.run(px: buffer, w: number, h: number, bpp: number, o: Options): buffer + OUT = buffer.create(math.max(1024, w * h // 2)) + CAP = buffer.len(OUT) + OP = 0 + ACC, NB = 0, 0 + GATHER = false + EOBRUN, BE = 0, 0 + + local yuv = bpp == 0 + local Y, Cb, Cr + if yuv then + local n, cn = w * h, ((w + 1) // 2) * ((h + 1) // 2) + Y = px + if not o.gray then + Cb, Cr = buffer.create(cn), buffer.create(cn) + buffer.copy(Cb :: buffer, 0, px, n, cn) + buffer.copy(Cr :: buffer, 0, px, n + cn, cn) + end + else + Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + end + local hs, vs = 1, 1 + if not o.gray then + if o.sampling == "420" then + hs, vs = 2, 2 + elseif o.sampling == "422" then + hs, vs = 2, 1 + end + end + local mcusX = math.ceil(w / (8 * hs)) + local mcusY = math.ceil(h / (8 * vs)) + local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) } + local qdiv = {} + for t = 1, 2 do + local b = buffer.create(128) + for i = 1, 64 do + writeu16(b, (i - 1) * 2, qt[t][i]) + end + qdiv[t] = b + end + + -- components and their quantised coefficients + local comps: { Comp } = {} + local srcs = if o.gray then { Y } else { Y, Cb :: buffer, Cr :: buffer } + for i, src in srcs do + local ch, cv = if i == 1 then hs else 1, if i == 1 then vs else 1 + local cw = math.ceil(w * ch / hs) + local chh = math.ceil(h * cv / vs) + local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8) + local bpl, bpc = mcusX * ch, mcusY * cv + local plane, pw, ph = src, w, h + if yuv and i > 1 then + pw, ph = (w + 1) // 2, (h + 1) // 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does + elseif ch < hs or cv < vs then + pw, ph = bw * 8, chh + plane = downsample(src, w, h, hs // ch, vs // cv, pw, ph) + end + local coef = buffer.create(bpl * bpc * 128) + local c: Comp = { + id = i, + h = ch, + v = cv, + tq = if i == 1 then 0 else 1, + td = if i == 1 then 0 else 1, + ta = if i == 1 then 0 else 1, + bw = bw, + bh = bh, + bpl = bpl, + bpc = bpc, + coef = coef, + last = 0, + } + local div = qdiv[c.tq + 1] + for by = 0, bpc - 1 do + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + if by < bh and bx < bw then + Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off) + elseif by < bh then + writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC + else + -- bottom: the DC of the MCU's last block in the row above + local lb = (bx // ch) * ch + ch - 1 + writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128)) + end + end + end + comps[i] = c + end + + -- headers + byte(0xFF) + byte(0xD8) + if o.jfif then + local d = o.density or { unit = 0, x = 1, y = 1 } + byte(0xFF) + byte(0xE0) + u16be(16) + for _, ch in { 0x4A, 0x46, 0x49, 0x46, 0 } do + byte(ch) + end + byte(1) + byte(1) + byte(d.unit) + u16be(d.x) + u16be(d.y) + byte(0) + byte(0) + end + for _, s in o.segments do + local n = buffer.len(s.data) + byte(0xFF) + byte(s.marker) + u16be(n + 2) + grow(n) + buffer.copy(OUT, OP, s.data, 0, n) + OP += n + end + for t = 1, (if o.gray then 1 else 2) do + byte(0xFF) + byte(0xDB) + u16be(67) + byte(t - 1) + for k = 0, 63 do + byte(qt[t][readu8(ZZ, k) + 1]) + end + end + byte(0xFF) + byte(if o.progressive then 0xC2 else 0xC0) + u16be(8 + 3 * #comps) + byte(8) + u16be(h) + u16be(w) + byte(#comps) + for _, c in comps do + byte(c.id) + byte(c.h * 16 + c.v) + byte(c.tq) + end + local ntab = if o.gray then 1 else 2 + + @native local function restartMarker(n: number) + flushBits() + byte(0xFF) + byte(0xD0 + n) + end + + if not o.progressive then + if o.optimize then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + for _, c in comps do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, @native function() + for _, c in comps do + c.last = 0 + end + end, blockSeq) + GATHER = false + end + for t = 1, ntab do + local dcC, dcS, acC, acS + if o.optimize then + dcC, dcS = optimal(dcFreq[t]) + acC, acS = optimal(acFreq[t]) + else + local d, a = Tables.DC[t], Tables.AC[t] + dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols + end + dcTab[t] = derive(dcC, dcS) + acTab[t] = derive(acC, acS) + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1 + dht(0, t - 1, dcC, dcS) + dht(1, t - 1, acC, acS) + end + if o.restart > 0 then + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(comps, 0, 63, 0, 0, false, false) + for _, c in comps do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, @native function(n: number) + restartMarker(n) + for _, c in comps do + c.last = 0 + end + end, blockSeq) + flushBits() + else + local script: { ScanSpec } + if o.gray then + script = { + { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + else + script = { + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + end + local driSent = false + for _, sc in script do + local sComps: { Comp } = {} + for _, ci in sc.comps do + table.insert(sComps, comps[ci]) + end + local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al + local isDc = ss == 0 + local blockFn: (Comp, number) -> () + if isDc and ah == 0 then + blockFn = @native function(c: Comp, off: number) + blockDcFirst(c, off, al) + end + elseif isDc then + blockFn = @native function(c: Comp, off: number) + bits(band(readi16(c.coef, off) // 2 ^ al, 1), 1) + end + elseif ah == 0 then + blockFn = @native function(c: Comp, off: number) + blockAcFirst(c, off, ss, se, al) + end + else + blockFn = @native function(c: Comp, off: number) + blockAcRefine(c, off, ss, se, al) + end + end + @native local function onRestart(n: number) + emitEobrun() + if not GATHER then + restartMarker(n) + end + for _, c in sComps do + c.last = 0 + end + EOBRUN, BE = 0, 0 + end + @native local function pass() + for _, c in sComps do + c.last = 0 + end + EOBRUN, BE = 0, 0 + walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) + emitEobrun() + end + -- gather statistics, then emit the optimal tables this scan uses + if not (isDc and ah > 0) then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + if not isDc then + curAcFreq = acFreq[sComps[1].ta + 1] + end + pass() + GATHER = false + local sent = {} + for _, c in sComps do + local slot = if isDc then c.td else c.ta + if not sent[slot] then + sent[slot] = true + local counts, syms = optimal(if isDc then dcFreq[slot + 1] else acFreq[slot + 1]) + dht(if isDc then 0 else 1, slot, counts, syms) + if isDc then + dcTab[slot + 1] = derive(counts, syms) + else + acTab[slot + 1] = derive(counts, syms) + end + end + end + if not isDc then + curAc = acTab[sComps[1].ta + 1] + end + end + if o.restart > 0 and not driSent then + driSent = true + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg) + pass() + flushBits() + end + end + byte(0xFF) + byte(0xD9) + local res = buffer.create(OP) + buffer.copy(res, 0, OUT, 0, OP) + OUT = buffer.create(0) + CAP = 0 + return res +end + +return Encode +end +__FILES["codecs/image/Jpeg/Scan"] = @native function() + + + +-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from +-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. +-- +-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, +-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least +-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a +-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser) +-- can consume PAD bytes. So every buffer index stays in range, even on garbage data. +-- +-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it. +-- Huffman tables (built by `buildTable`) are buffers: +-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code +-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits +-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l] +-- [1168, 1424) symbols +-- [1424, 1426) symbol count +-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code +-- and its extra bits fit in 9 bits (0 otherwise) +local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16 +local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16 +local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap + +local Scan = {} + +Scan.PAD = 4096 +Scan.TABLE_SIZE = 3476 + +local T_MAX = 1024 +local T_DELTA = 1096 +local T_VAL = 1168 +local T_COUNT = 1424 +local T_FASTAC = 1428 + +-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range +local ZZ = buffer.create(80) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i += 1 + end + end + end + for j = 64, 79 do + writeu8(ZZ, j, 63) + end +end +Scan.ZIGZAG = ZZ + +-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An +-- over-subscribed table keeps the codes that fit; the rest decode as invalid. +@native function Scan.buildTable(counts: { number }, symbols: { number }): buffer + local t = buffer.create(Scan.TABLE_SIZE) + local code, k = 0, 0 + local nsym = #symbols + local codes, sizes = {}, {} + local broken = false + for l = 1, 16 do + writei32(t, T_DELTA + l * 4, k - code) + local n = counts[l] or 0 + for _ = 1, n do + if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then + broken = true + break + end + k += 1 + codes[k] = code + sizes[k] = l + code += 1 + end + writeu32(t, T_MAX + l * 4, if broken then 0 else lshift(code, 16 - l)) + code *= 2 + end + writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF) + for i = 1, k do + writeu8(t, T_VAL + i - 1, symbols[i]) + end + writeu16(t, T_COUNT, k) + -- fast lookups + for i = 1, k do + local l = sizes[i] + if l <= 9 then + local sym = symbols[i] + local base = lshift(codes[i], 9 - l) + for j = 0, lshift(1, 9 - l) - 1 do + local idx = base + j + writeu16(t, idx * 2, l * 256 + sym) + local r, s = rshift(sym, 4), band(sym, 15) + if s ~= 0 and l + s <= 9 then + local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1) + if v < lshift(1, s - 1) then + v = v - lshift(1, s) + 1 + end + writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s) + end + end + end + end + return t +end + +-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed, +-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n), +-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed. +@native function Scan.destuff(src: buffer, pos: number, n: number, dst: buffer, rst: { number }): (number, number, number) + local o, nr = 0, 0 + while pos < n do + local b = readu8(src, pos) + if b ~= 0xFF then + writeu8(dst, o, b) + o += 1 + pos += 1 + else + local q = pos + 1 + while q < n and readu8(src, q) == 0xFF do + q += 1 + end + if q >= n then + pos = n + break + end + local m = readu8(src, q) + if m == 0 then + writeu8(dst, o, 0xFF) + o += 1 + pos = q + 1 + elseif m >= 0xD0 and m <= 0xD7 then + nr += 1 + rst[nr] = o + pos = q + 1 + else + pos = q - 1 + break + end + end + end + buffer.fill(dst, o, 0, Scan.PAD) + return pos, o, nr +end + +@native local function huff(d: buffer, pos: number, t: buffer): (number, number) + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local f = readu16(t, rshift(w, 23) * 2) + if f ~= 0 then + return band(f, 255), pos + rshift(f, 8) + end + local c = rshift(w, 16) + local l = 10 + while c >= readu32(t, T_MAX + l * 4) do + l += 1 + end + if l > 16 then + return 0, pos + 16 -- invalid code + end + local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4) + if idx < 0 or idx >= readu16(t, T_COUNT) then + return 0, pos + l + end + return readu8(t, T_VAL + idx), pos + l +end + +-- the next s bits (1 <= s <= 16) as an unsigned number +@native local function bits(d: buffer, pos: number, s: number): number + return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) +end + +@native local function extend(v: number, s: number): number + if v < lshift(1, s - 1) then + return v - lshift(1, s) + 1 + end + return v +end + +-- sequential (baseline / extended) block: returns pos, DC predictor +@native local function blockSeq(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, act: buffer, pred: number): (number, number) + local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred += extend(bits(d, pos, s), s) + pos += s + end + writei16(coef, off, pred) + local k = 1 + while k < 64 do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k += low // 16 + pos += low % 16 + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, fa // 256) + k += 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, sz = rshift(rs, 4), band(rs, 15) + if sz == 0 then + if r ~= 15 then + break + end + k += 16 + else + k += r + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz)) + pos += sz + k += 1 + end + end + end + return pos, pred +end + +@native local function blockDcFirst(d: buffer, pos: number, coef: buffer, off: number, dct: buffer, pred: number, al: number): (number, number) + local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred += extend(bits(d, pos, s), s) + pos += s + end + writei16(coef, off, pred * lshift(1, al)) + return pos, pred +end + +@native local function blockAcFirst(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) + if eobrun > 0 then + return pos, eobrun - 1 + end + local mul = lshift(1, al) + local k = ss + while k <= se do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k += low // 16 + pos += low % 16 + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, (fa // 256) * mul) + k += 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, s = rshift(rs, 4), band(rs, 15) + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun += bits(d, pos, r) + pos += r + end + break + end + k += 16 + else + k += r + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul) + pos += s + k += 1 + end + end + end + return pos, eobrun +end + +-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine) +@native local function blockAcRefine(d: buffer, pos: number, coef: buffer, off: number, act: buffer, ss: number, se: number, al: number, eobrun: number): (number, number) + local bit = lshift(1, al) + if eobrun > 0 then + for k = ss, se do + local o = off + readu8(ZZ, k) * 2 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, if p > 0 then p + bit else p - bit) + end + end + end + return pos, eobrun - 1 + end + local k = ss + while k <= se do + local rs + rs, pos = huff(d, pos, act) + local s, r = band(rs, 15), rshift(rs, 4) + local val = 0 + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun += bits(d, pos, r) + pos += r + end + r = 64 -- the rest of the block only refines + end + else + -- s must be 1; anything else is corrupt and treated as 1 + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + val = if b ~= 0 then bit else -bit + end + while k <= se do + local o = off + readu8(ZZ, k) * 2 + k += 1 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, if p > 0 then p + bit else p - bit) + end + else + if r == 0 then + if val ~= 0 then + writei16(coef, o, val) + end + break + end + r -= 1 + end + end + end + -- an EOB run that started in this block counts it already (eobrun = run length - 1) + return pos, eobrun +end + +type ScanComp = { + coef: buffer, -- i16 coefficients, 64 per block in natural order, blocks row-major on a bpl-wide grid + bpl: number, + h: number, + v: number, + bw: number, -- blocks across / down the component itself (non-interleaved scans) + bh: number, + dct: buffer?, + act: buffer?, + pred: number, +} + +type ScanParams = { + comps: { ScanComp }, + mcusX: number, + mcusY: number, + ri: number, -- restart interval in MCUs (0 = none) + mode: number, -- 0 sequential, 1 DC first, 2 DC refine, 3 AC first, 4 AC refine + ss: number, + se: number, + al: number, + hook: (() -> ())?, -- a cooperative yield point after every MCU row (pcall'ed: it can't throw through here) +} + +-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and +-- whether the data ran out (or overran) before the last MCU. +@native function Scan.run(d: buffer, cleanLen: number, rst: { number }, nrst: number, P: ScanParams): (number, boolean) + local comps = P.comps + local nc = #comps + local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri + local endBits = cleanLen * 8 + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = P.mcusX + units = ux * P.mcusY + end + for i = 1, nc do + comps[i].pred = 0 + end + local pos, eobrun, rstIdx = 0, 0, 0 + local truncated, skipping = false, false + local bit = lshift(1, al) + local hook = P.hook + for u = 0, units - 1 do + if hook and u > 0 and u % ux == 0 then + pcall(hook) + end + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx += 1 + if rstIdx <= nrst then + pos = rst[rstIdx] * 8 + skipping = false + end + for i = 1, nc do + comps[i].pred = 0 + end + eobrun = 0 + end + if pos > endBits then + truncated = true + if ri == 0 or rstIdx >= nrst then + break + end + skipping = true + end + if not skipping then + local my, mx = u // ux, u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + pos, c.pred = blockSeq(d, pos, coef, off, c.dct :: buffer, c.act :: buffer, c.pred) + elseif mode == 1 then + pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct :: buffer, c.pred, al) + elseif mode == 2 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos += 1 + if b ~= 0 then + writei16(coef, off, bor(readi16(coef, off), bit)) + end + elseif mode == 3 then + pos, eobrun = blockAcFirst(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) + else + pos, eobrun = blockAcRefine(d, pos, coef, off, c.act :: buffer, ss, se, al, eobrun) + end + end + end + end + end + end + return pos, truncated +end + +return Scan +end +__FILES["codecs/image/Jpeg/Tables"] = function() + +-- codecs/image/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline +-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation +-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table). +local Tables = {} + +local function range(t: { number }, a: number, b: number) + for v = a, b do + table.insert(t, v) + end +end + +-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2] +local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 } +local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } +local dcv = {} +range(dcv, 0, 11) +local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d } +local aclv = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, +} +range(aclv, 0x34, 0x3a) +for hi = 4, 8 do + range(aclv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 9, 13 do + range(aclv, hi * 16 + 2, hi * 16 + 10) +end +range(aclv, 0xe1, 0xea) +range(aclv, 0xf1, 0xfa) +local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 } +local accv = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, +} +range(accv, 0x35, 0x3a) +for hi = 4, 7 do + range(accv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 8, 14 do + range(accv, hi * 16 + 2, hi * 16 + 10) +end +range(accv, 0xf2, 0xfa) + +type Spec = { counts: { number }, symbols: { number } } +Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } :: { Spec } +Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } :: { Spec } + +-- K.1, natural (row-major) order +Tables.LUMA = { + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, + 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, + 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +} +Tables.CHROMA = { + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, +} + +-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline) +function Tables.quant(base: { number }, quality: number): { number } + local q = math.clamp(math.floor(quality), 1, 100) + local scale = if q < 50 then 5000 // q else 200 - q * 2 + local out = table.create(64, 1) + for i = 1, 64 do + out[i] = math.clamp((base[i] * scale + 50) // 100, 1, 255) + end + return out +end + +return Tables +end +__FILES["codecs/image/Jpeg/Yuv"] = @native function() + + + +-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 +-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 +-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). +-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. +local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 + +local Yuv = {} + +-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 +-- samples at dst[doff], w per row +@native function Yuv.crop(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local quads = w // 4 + local rest = w - quads * 4 + for y = 0, h - 1 do + local s = y * stride * 2 + local d = doff + y * w + -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write + for _ = 1, quads do + local a, b = readu32(src, s), readu32(src, s + 4) + writeu32(dst, d, a % 65536 + (a // 65536) * 256 + (b % 65536) * 65536 + (b // 65536) * 16777216) + s += 8 + d += 4 + end + for k = 0, rest - 1 do + writeu8(dst, d + k, readu16(src, s + k * 2)) + end + end +end + +-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output +-- row the rounded mean of two source rows (the last row alone when h is odd) +@native function Yuv.rows(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local oh = (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * w + for x = 0, w - 1 do + writeu8(dst, d + x, (readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) // 2) + end + end +end + +-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), +-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) +@native function Yuv.box(src: buffer, stride: number, w: number, h: number, dst: buffer, doff: number) + local ow, oh = (w + 1) // 2, (h + 1) // 2 + for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = if 2 * y + 1 < h then a + stride * 2 else a + local d = doff + y * ow + for x = 0, ow - 1 do + local x0 = 2 * x * 2 + local x1 = if 2 * x + 1 < w then x0 + 2 else x0 + writeu8(dst, d + x, (readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) // 4) + end + end +end + +-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field +-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) +@native function Yuv.weave(top: buffer, toff: number, bottom: buffer, boff: number, rowBytes: number, rows: number, dst: buffer, doff: number) + for y = 0, rows - 1 do + local k = y // 2 + if y % 2 == 0 then + buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) + else + buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) + end + end +end + +return Yuv +end +__FILES["codecs/image/Pixels"] = @native function() + + + +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, +-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / +-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / +-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops +-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every +-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each +-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). +local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift + +local Pixels = {} + +-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], +-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, +-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). +@native function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer + local pal = buffer.create(1024) + local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 + for i = 0, 255 do + local v = 0xFF000000 + if i < m then + local o = base + i * 3 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + if bgr then + r, b = b, r + end + v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) + end + writeu32(pal, i * 4, v) + end + return pal +end + +-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) +@native function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer) + local mask = lshift(1, bpp) - 1 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + if bpp == 8 then + for x = 0, w - 1 do + writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) + end + elseif bpp == 4 then + for x = 0, w - 1 do + local b = readu8(src, so + rshift(x, 1)) + local i = if band(x, 1) == 0 then rshift(b, 4) else band(b, 15) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + else + for x = 0, w - 1 do + local bit = x * bpp + local b = readu8(src, so + rshift(bit, 3)) + local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + end + end +end + +-- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding +@native function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = readu16(src, so + x * 2) + local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31) + writeu32(dst, d + x * 4, (cr * 255 + 15) // 31 + ((cg * 255 + 15) // 31) * 256 + ((cb * 255 + 15) // 31) * 65536 + 0xFF000000) + end + end +end + +-- 24 bpp BI_RGB: B, G, R +@native function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean) + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * 3 + writeu32(dst, d + x * 4, + bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) + end + end +end + +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +@native function Pixels.bgra32(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, + topDown: boolean): number + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local p = readu32(src, so + x * 4) + -- swap R and B: B G R A -> R G B A + writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) + aor = bor(aor, p) + end + end + return rshift(aor, 24) +end + +-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry +-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). +-- Returns the OR of every masked alpha value (before scaling). +@native function Pixels.masked(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, + topDown: boolean, shr: number, mr: number, tr: buffer, shg: number, mg: number, tg: buffer, shb: number, + mb: number, tb: buffer, sha: number, ma: number, ta: buffer): number + local bytes = rshift(bpp, 3) + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = (if topDown then r else h - 1 - r) * w * 4 + for x = 0, w - 1 do + local s = so + x * bytes + local p + if bytes == 2 then + p = readu16(src, s) + elseif bytes == 4 then + p = readu32(src, s) + else + p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) + end + local a = band(rshift(p, sha), ma) + aor = bor(aor, a) + local o = d + x * 4 + writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) + writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) + writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) + writeu8(dst, o + 3, readu8(ta, a)) + end + end + return aor +end + +-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +@native function Pixels.opaque(dst: buffer, n: number) + for i = 0, n - 1 do + writeu8(dst, i * 4 + 3, 255) + end +end + +-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a +-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the +-- decode and keeps what was drawn. Returns the number of pixels written. +@native function Pixels.rle(src: buffer, pos: number, stop: number, rle4: boolean, dst: buffer, w: number, h: number, + topDown: boolean, pal: buffer): number + local x, y = 0, 0 + local written = 0 + local row = (if topDown then 0 else h - 1) * w * 4 + local rowStep = if topDown then w * 4 else -w * 4 + while y < h and pos + 1 < stop do + local n = readu8(src, pos) + local v = readu8(src, pos + 1) + pos += 2 + if n > 0 then + -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) + local e = math.min(x + n, w) + if rle4 then + local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, if band(i - x, 1) == 0 then hi else lo) + end + else + local c = readu32(pal, v * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, c) + end + end + if e > x then + written += e - x + end + x += n + elseif v == 0 then + -- end of line + x = 0 + y += 1 + row += rowStep + elseif v == 1 then + break -- end of bitmap + elseif v == 2 then + -- delta: right dx, up (in file rows) dy + if pos + 1 >= stop then + break + end + local dx, dy = readu8(src, pos), readu8(src, pos + 1) + pos += 2 + x += dx + y += dy + row += rowStep * dy + else + -- absolute run of v pixels, padded to a 16-bit boundary + local nb = if rle4 then rshift(v + 1, 1) else v + if pos + nb > stop then + break + end + local e = math.min(x + v, w) + for i = x, e - 1 do + local k = i - x + local idx + if rle4 then + local b = readu8(src, pos + rshift(k, 1)) + idx = if band(k, 1) == 0 then rshift(b, 4) else band(b, 15) + else + idx = readu8(src, pos + k) + end + writeu32(dst, row + i * 4, readu32(pal, idx * 4)) + end + if e > x then + written += e - x + end + x += v + pos += nb + band(nb, 1) + end + end + return written +end + +-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) +@native function Pixels.encode24(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu8(dst, d, band(rshift(v, 16), 255)) + writeu8(dst, d + 1, band(rshift(v, 8), 255)) + writeu8(dst, d + 2, band(v, 255)) + d += 3 + end + end +end + +-- rgba8 -> 32 bpp BGRA, bottom-up +@native function Pixels.encode32(src: buffer, w: number, h: number, dst: buffer, base: number) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * w * 4 + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A + writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) + end + end +end + +-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up +@native function Pixels.encode8(src: buffer, w: number, h: number, dst: buffer, base: number, stride: number, idx: { [number]: number }) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) + end + end +end + +-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any +-- alpha is below 255; stops counting at max + 1 colours +@native function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boolean) + local seen: { [number]: boolean } = {} + local list: { number } = {} + local alpha = false + for i = 0, n - 1 do + local v = readu32(src, i * 4) + if v < 0xFF000000 then + alpha = true + end + local c = band(v, 0xFFFFFF) + if #list <= max and not seen[c] then + seen[c] = true + list[#list + 1] = c + end + end + return list, alpha +end + +return Pixels +end +__FILES["codecs/image/Quantize"] = @native function() + + + +-- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette +-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel +-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with +-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table +-- iteration order is ever relied on). +-- +-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean +-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 +-- +-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) +-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, +-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree +-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. +-- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local floor = math.floor +local blen = buffer.len + +local Quantize = {} + +type Color = { number } -- { r, g, b, a } 0..255 +type PaletteOptions = { + method: ("mediancut" | "octree")?, -- default "mediancut" +} +type MapOptions = { + dither: boolean?, -- Floyd-Steinberg error diffusion (default false) + transparentIndex: number?, -- 0-based index for pixels with alpha < 128 (default: none) +} + +local BINS = 32768 -- 5 bits per channel + +-- ------------------------------------------------------------------------------------------------ helpers +@native local function count(pixels: buffer, n: number): (buffer, buffer) + -- per bin: u32 count; f64 sums of r, g, b + local cnt = buffer.create(BINS * 4) + local sums = buffer.create(BINS * 24) + for i = 0, n - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local bin = (r // 8) * 1024 + (g // 8) * 32 + b // 8 + writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1) + local s = bin * 24 + writef64(sums, s, readf64(sums, s) + r) + writef64(sums, s + 8, readf64(sums, s + 8) + g) + writef64(sums, s + 16, readf64(sums, s + 16) + b) + end + end + return cnt, sums +end + +@native local function mean(cnt: buffer, sums: buffer, bins: { number }, lo: number, hi: number): Color + local n, r, g, b = 0, 0, 0, 0 + for i = lo, hi do + local bin = bins[i] + n += readu32(cnt, bin * 4) + r += readf64(sums, bin * 24) + g += readf64(sums, bin * 24 + 8) + b += readf64(sums, bin * 24 + 16) + end + if n == 0 then + return { 0, 0, 0, 255 } + end + return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } +end + +-- ------------------------------------------------------------------------------------------------ median cut +@native local function medianCut(cnt: buffer, sums: buffer, maxColors: number): { Color } + local bins: { number } = {} + for bin = 0, BINS - 1 do + if readu32(cnt, bin * 4) > 0 then + table.insert(bins, bin) + end + end + if #bins == 0 then + return {} + end + -- boxes: { lo, hi } ranges of the bins array + local boxes: { { number } } = {} + @native local function channel(bin: number, c: number): number + if c == 0 then + return bin // 1024 + elseif c == 1 then + return (bin // 32) % 32 + end + return bin % 32 + end + @native local function stats(box: { number }): (number, number, number) + -- returns the widest channel, its range, the pixel count + local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } + local n = 0 + for i = box[1], box[2] do + local bin = bins[i] + n += readu32(cnt, bin * 4) + for c = 0, 2 do + local v = channel(bin, c) + if v < mins[c + 1] then + mins[c + 1] = v + end + if v > maxs[c + 1] then + maxs[c + 1] = v + end + end + end + local best, range = 0, -1 + for c = 0, 2 do + local rg = maxs[c + 1] - mins[c + 1] + if rg > range then + best, range = c, rg + end + end + return best, range, n + end + @native local function scored(lo: number, hi: number): { number } + local c, range, n = stats({ lo, hi }) + return { lo, hi, c, if hi > lo then range * math.sqrt(n) else 0 } + end + boxes[1] = scored(1, #bins) + while #boxes < maxColors do + -- split the box with the largest range * sqrt(count) score (ties: the first) + local pick, pickScore = 0, 0 + for i, box in boxes do + if box[4] > pickScore then + pick, pickScore = i, box[4] + end + end + if pick == 0 then + break + end + local box = boxes[pick] + local lo, hi, c = box[1], box[2], box[3] + -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator + local keys = table.create(hi - lo + 1) :: { number } + for i = lo, hi do + keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] + end + table.sort(keys) + local total = 0 + for i = 1, #keys do + local bin = keys[i] % BINS + bins[lo + i - 1] = bin + total += readu32(cnt, bin * 4) + end + -- the weighted median, keeping both halves non-empty + local acc, cut = 0, lo + for i = lo, hi - 1 do + acc += readu32(cnt, bins[i] * 4) + cut = i + if acc * 2 >= total then + break + end + end + boxes[pick] = scored(lo, cut) + table.insert(boxes, scored(cut + 1, hi)) + end + local pal = table.create(#boxes) :: { Color } + for i, box in boxes do + pal[i] = mean(cnt, sums, bins, box[1], box[2]) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ octree +-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +@native local function octree(cnt: buffer, sums: buffer, maxColors: number): { Color } + local child: { number } = {} -- node * 8 + k -> node (0 = none) + local n: { number } = {} -- pixel count + local sr: { number }, sg: { number }, sb: { number } = {}, {}, {} + local leaf: { boolean } = {} + local level: { number } = {} + local nodes = 1 + n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0 + for k = 1, 8 do + child[k] = 0 + end + local byLevel: { { number } } = { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + table.insert(byLevel[1], 1) + local leaves = 0 + for bin = 0, BINS - 1 do + local c = readu32(cnt, bin * 4) + if c > 0 then + local r5, g5, b5 = bin // 1024, (bin // 32) % 32, bin % 32 + local node = 1 + for lv = 0, 4 do + local sh = 4 - lv + local k = ((r5 // 2 ^ sh) % 2) * 4 + ((g5 // 2 ^ sh) % 2) * 2 + (b5 // 2 ^ sh) % 2 + local slot = (node - 1) * 8 + k + 1 + local nx = child[slot] + if nx == 0 then + nodes += 1 + nx = nodes + child[slot] = nx + for j = 1, 8 do + child[(nx - 1) * 8 + j] = 0 + end + n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1 + leaf[nx] = lv == 4 + if lv == 4 then + leaves += 1 + else + table.insert(byLevel[lv + 2], nx) + end + end + node = nx + end + n[node] += c + sr[node] += readf64(sums, bin * 24) + sg[node] += readf64(sums, bin * 24 + 8) + sb[node] += readf64(sums, bin * 24 + 16) + end + end + -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain + @native local function fold(node: number): number + -- merges the children (all leaves) into node; returns how many leaves disappeared + local merged = 0 + for k = 1, 8 do + local slot = (node - 1) * 8 + k + local ch = child[slot] + if ch ~= 0 then + n[node] += n[ch] + sr[node] += sr[ch] + sg[node] += sg[ch] + sb[node] += sb[ch] + child[slot] = 0 + merged += 1 + end + end + leaf[node] = true + return merged - 1 + end + @native local function subtotal(node: number): number + local s = 0 + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + s += n[ch] + end + end + return s + end + for lv = 5, 1, -1 do + if leaves <= maxColors then + break + end + local list = byLevel[lv] + local order = table.create(#list) :: { { any } } + for i, node in list do + order[i] = { node, subtotal(node), i } + end + table.sort(order, @native function(a: { number }, b: { number }): boolean + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + for _, e in order do + if leaves <= maxColors then + break + end + leaves -= fold(e[1]) + end + end + -- collect leaves depth first in child order + local pal: { Color } = {} + @native local function walk(node: number) + if leaf[node] then + local c = n[node] + if c > 0 then + table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 }) + end + return + end + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + walk(ch) + end + end + end + walk(1) + -- the root itself can end up a leaf with everything (maxColors 1) + while #pal > maxColors do + table.remove(pal) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ palette +-- palette(pixels, w, h, maxColors, opts?) -> palette, exact +@native function Quantize.palette(pixels: buffer, w: number, h: number, maxColors: number, opts: PaletteOptions?): ({ Color }, boolean) + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then + return {}, false + end + local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) + local npx = w * h + -- exact colours, in first-seen order (stops counting past maxColors) + local seen: { [number]: boolean } = {} + local exact: { Color } = {} + local over = false + for i = 0, npx - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local key = r * 65536 + g * 256 + b + if not seen[key] then + if #exact >= maxc then + over = true + break + end + seen[key] = true + table.insert(exact, { r, g, b, 255 }) + end + end + end + if not over then + return exact, true + end + local cnt, sums = count(pixels, npx) + local method = opts and opts.method or "mediancut" + if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour + return octree(cnt, sums, maxc), false + end + return medianCut(cnt, sums, maxc), false +end + +-- ------------------------------------------------------------------------------------------------ map +-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) +@native function Quantize.map(pixels: buffer, w: number, h: number, palette: { Color }, opts: MapOptions?): buffer + if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then + return buffer.create(0) + end + local npx = w * h + local out = buffer.create(npx) + local dither = opts and opts.dither or false + local tidx = opts and opts.transparentIndex + -- the searchable entries (the transparent slot is excluded) + local pr: { number }, pg: { number }, pb: { number }, pi: { number } = {}, {}, {}, {} + for i, c in palette do + if tidx == nil or i - 1 ~= tidx then + table.insert(pr, c[1] or 0) + table.insert(pg, c[2] or 0) + table.insert(pb, c[3] or 0) + table.insert(pi, i - 1) + end + end + local np = #pr + -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best + do + local order = table.create(np) :: { number } + for k = 1, np do + order[k] = pg[k] * 65536 + k + end + table.sort(order) + local r2, g2, b2, i2 = table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number }, table.create(np) :: { number } + for k = 1, np do + local j = order[k] % 65536 + r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j] + end + pr, pg, pb, pi = r2, g2, b2, i2 + end + local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end + do + local k = 1 + for g = 0, 255 do + while k <= np and pg[k] < g do + k += 1 + end + startAt[g + 1] = k + end + end + if np == 0 then + if tidx then + buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx) + end + return out + end + local cache: { [number]: number } = {} + @native local function nearest(r: number, g: number, b: number): number + local key = r * 65536 + g * 256 + b + local hit = cache[key] + if hit then + return hit + end + local best, bd = 1, math.huge + local up = startAt[math.clamp(g, 0, 255) + 1] + local down = up - 1 + while up <= np or down >= 1 do + if up <= np then + local dg = pg[up] - g + if dg * dg * 4 >= bd then + up = np + 1 + else + local dr, db = r - pr[up], b - pb[up] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = up, d + end + up += 1 + end + end + if down >= 1 then + local dg = g - pg[down] + if dg * dg * 4 >= bd then + down = 0 + else + local dr, db = r - pr[down], b - pb[down] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = down, d + end + down -= 1 + end + end + end + cache[key] = best + return best + end + local tbyte = if tidx then math.clamp(tidx, 0, 255) else 0 + if not dither then + for i = 0, npx - 1 do + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))]) + end + end + return out + end + -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) + local rowLen = (w + 2) * 24 + local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) + for y = 0, h - 1 do + buffer.fill(nxt, 0, 0, rowLen) + for x = 0, w - 1 do + local i = y * w + x + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + local e = (x + 1) * 24 + local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255) + local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255) + local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255) + local k = nearest(r, g, b) + writeu8(out, i, pi[k]) + local er, eg, eb = r - pr[k], g - pg[k], b - pb[k] + -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right + writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375) + writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375) + writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375) + writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875) + writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875) + writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875) + writef64(nxt, e, readf64(nxt, e) + er * 0.3125) + writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125) + writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125) + writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625) + writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625) + writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625) + end + end + cur, nxt = nxt, cur + end + return out +end + +-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) +@native function Quantize.quantize(pixels: buffer, w: number, h: number, maxColors: number, opts: any?): (buffer, { Color }, boolean) + local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) + local mo = opts + if exact and opts and opts.dither then + mo = table.clone(opts) + mo.dither = false -- nothing to diffuse + end + return Quantize.map(pixels, w, h, pal, mo), pal, exact +end + +return Quantize +end +__FILES["codecs/image/Raster"] = @native function() + + + +-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and +-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / +-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an +-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed +-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. +-- +-- local R = require("@rosetta/codecs/image/Raster") +-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: +-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, +-- { op = "close" } } -- (the Font:outline() format) +-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) +-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty +-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) +-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) +-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) +-- +-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are +-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to +-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. +-- +-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the +-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +local Raster = {} + +local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt +local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8 +local bcreate = buffer.create + +type Cmd = { op: string, [number]: number } +type Path = { Cmd } +type Transform = { number } +type Mask = { x: number, y: number, width: number, height: number, coverage: buffer } +type Options = { + transform: Transform?, -- default identity + rule: ("nonzero" | "evenodd")?, -- default "nonzero" + clip: { number }?, -- { x0, y0, x1, y1 } device pixel bounds (integers); default: the path's bounds (fill: the image) + tolerance: number?, -- curve flattening tolerance in device pixels (default 0.1) + maxPixels: number?, -- largest mask (default 2^26) + opacity: number?, -- fill: multiplies the coverage (0..1, default 1) +} + +local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken + +-- ------------------------------------------------------------------------------------------------ transforms +Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) + +-- multiply(m, n) -> m * n (apply n first, then m) +@native function Raster.multiply(m: Transform, n: Transform): Transform + return { + m[1] * n[1] + m[3] * n[2], + m[2] * n[1] + m[4] * n[2], + m[1] * n[3] + m[3] * n[4], + m[2] * n[3] + m[4] * n[4], + m[1] * n[5] + m[3] * n[6] + m[5], + m[2] * n[5] + m[4] * n[6] + m[6], + } +end +@native function Raster.translate(tx: number, ty: number): Transform + return { 1, 0, 0, 1, tx, ty } +end +@native function Raster.scale(sx: number, sy: number?): Transform + return { sx, 0, 0, sy or sx, 0, 0 } +end +@native function Raster.rotate(radians: number): Transform + local c, s = math.cos(radians), math.sin(radians) + return { c, s, -s, c, 0, 0 } +end +-- invert(m) -> m^-1 | nil (singular) +@native function Raster.invert(m: Transform): Transform? + local det = m[1] * m[4] - m[2] * m[3] + if det == 0 or det ~= det then + return nil + end + local id = 1 / det + local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id + return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } +end +-- apply(m, x, y) -> x', y' +@native function Raster.apply(m: Transform, x: number, y: number): (number, number) + return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] +end + +-- ------------------------------------------------------------------------------------------------ path builder +local Builder = {} +Builder.__index = Builder +type Builder = typeof(setmetatable({} :: { cmds: Path }, Builder)) + +-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path +-- takes a builder too) +@native function Raster.path(): Builder + return setmetatable({ cmds = {} :: Path }, Builder) +end +@native function Builder.moveTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "moveTo", x, y }) + return self +end +@native function Builder.lineTo(self: Builder, x: number, y: number): Builder + table.insert(self.cmds, { op = "lineTo", x, y }) + return self +end +@native function Builder.quadTo(self: Builder, cx: number, cy: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) + return self +end +@native function Builder.cubicTo(self: Builder, c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number): Builder + table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) + return self +end +@native function Builder.close(self: Builder): Builder + table.insert(self.cmds, { op = "close" } :: Cmd) + return self +end +-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths +@native function Builder.rect(self: Builder, x: number, y: number, w: number, h: number): Builder + return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() +end +@native function Builder.ellipse(self: Builder, cx: number, cy: number, rx: number, ry: number): Builder + local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle + self:moveTo(cx + rx, cy) + self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) + self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy) + self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry) + self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy) + return self:close() +end + +@native local function commands(path: any): Path? + if type(path) ~= "table" then + return nil + end + if type(path.cmds) == "table" then + return path.cmds + end + return path +end + +-- n numeric operands of a command, or nil +@native local function operands(c: any, n: number): boolean + if type(c) ~= "table" then + return false + end + for i = 1, n do + local v = c[i] + if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ flattening +-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath +-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) +@native local function flatten(path: any, transform: Transform?, tolerance: number?, minLen: number): ({ { number } }, number?, number?, number?, number?) + local cmds = commands(path) + local polys: { { number } } = {} + if not cmds then + return polys, nil, nil, nil, nil + end + local m = transform or Raster.IDENTITY + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then + return polys, nil, nil, nil, nil + end + local tol = tolerance or 0.1 + if type(tol) ~= "number" or not (tol > 0.001) then + tol = 0.1 + end + local cur: { number }? = nil + local px, py = 0, 0 -- current point (device) + local sx, sy = 0, 0 -- subpath start (device) + local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge + @native local function point(x: number, y: number) + local poly = cur :: { number } + local n = #poly + poly[n + 1] = x + poly[n + 2] = y + if x < bx0 then + bx0 = x + end + if x > bx1 then + bx1 = x + end + if y < by0 then + by0 = y + end + if y > by1 then + by1 = y + end + end + @native local function start(x: number, y: number) + if cur and #cur >= minLen then + table.insert(polys, cur) + end + cur = {} + point(x, y) + sx, sy = x, y + px, py = x, y + end + for _, cmd in cmds do + local op = if type(cmd) == "table" then cmd.op else nil + if op == "moveTo" then + if operands(cmd, 2) then + start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f) + end + elseif op == "lineTo" then + if operands(cmd, 2) then + if not cur then + start(px, py) + end + px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + point(px, py) + end + elseif op == "quadTo" then + if operands(cmd, 4) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2 + local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2) + end + point(x2, y2) + px, py = x2, y2 + end + elseif op == "cubicTo" then + if operands(cmd, 6) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f + local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2 + local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3 + local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy)) + local n = ceil(sqrt(dd * 0.75 / tol)) + n = if n ~= n then 1 else max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t + point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3) + end + point(x3, y3) + px, py = x3, y3 + end + elseif op == "close" then + if cur then + if #cur >= minLen then + table.insert(polys, cur) + end + cur = nil + px, py = sx, sy + end + end + end + if cur and #cur >= minLen then + table.insert(polys, cur) + end + if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then + return polys, nil, nil, nil, nil + end + return polys, bx0, by0, bx1, by1 +end + +@native function Raster.flatten(path: any, transform: Transform?, tolerance: number?): ({ { number } }, number?, number?, number?, number?) + return flatten(path, transform, tolerance, 6) +end + +-- ------------------------------------------------------------------------------------------------ accumulation +-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area +-- each pixel gains (font-rs's draw_line) +@native local function line(acc: buffer, S: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 then + return + end + local W = S - 2 + local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside) + local dir = 1 + if y0 > y1 then + dir = -1 + x0, x1 = x1, x0 + y0, y1 = y1, y0 + end + if y1 <= 0 or y0 >= H then + return + end + local dxdy = (x1 - x0) / (y1 - y0) + local x = x0 + if y0 < 0 then + x -= y0 * dxdy + end + local ystart = max(0, floor(y0)) + local yend = min(H, ceil(y1)) - 1 + for y = ystart, yend do + local ls = y * S + local dy = min(y + 1, y1) - max(y, y0) + local xnext = x + dxdy * dy + if xnext < xl then + xnext = xl + elseif xnext > xr then + xnext = xr + end + if x < xl then + x = xl + elseif x > xr then + x = xr + end + local dd = dy * dir + local xa, xb = x, xnext + if xa > xb then + xa, xb = xb, xa + end + local xaf = floor(xa) + local xai = xaf + local xbc = ceil(xb) + local xbi = xbc + if xbi <= xai + 1 then + local xmf = 0.5 * (x + xnext) - xaf + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd - dd * xmf) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf) + else + local s = 1 / (xb - xa) + local x0f = xa - xaf + local a0 = 0.5 * s * (1 - x0f) * (1 - x0f) + local x1f = xb - xbc + 1 + local am = 0.5 * s * x1f * x1f + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd * a0) + if xbi == xai + 2 then + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am)) + else + local a1 = s * (1.5 - x0f) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0)) + local ds = dd * s + for xi = xai + 2, xbi - 2 do + local q = (ls + xi) * 4 + writef32(acc, q, readf32(acc, q) + ds) + end + local a2 = a1 + (xbi - xai - 3) * s + local q = (ls + xbi - 1) * 4 + writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am)) + end + local q = (ls + xbi) * 4 + writef32(acc, q, readf32(acc, q) + dd * am) + end + x = xnext + end +end + +-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the +-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still +-- applies to the row) +@native local function clampx(x: number, W: number): number + return if x < 0 then 0 elseif x > W then W else x +end +@native local function edge(acc: buffer, S: number, W: number, H: number, x0: number, y0: number, x1: number, y1: number) + if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then + return -- horizontal, or non-finite (NaN fails every comparison) + end + if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then + return + end + local dx = x1 - x0 + local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + if dx ~= 0 then + local t0 = (0 - x0) / dx + local tw = (W - x0) / dx + if t0 > 0 and t0 < 1 then + ta = t0 + end + if tw > 0 and tw < 1 then + tb = tw + end + if ta > tb then + ta, tb = tb, ta + end + end + local dy = y1 - y0 + local px, py = x0, y0 + if ta < 1 then + local qx, qy = x0 + dx * ta, y0 + dy * ta + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + if tb < 1 then + local qx, qy = x0 + dx * tb, y0 + dy * tb + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) +end + +-- ------------------------------------------------------------------------------------------------ masks +-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") +@native function Raster.mask(path: any, opts: Options?): (Mask?, string?) + local o: Options = opts or {} + local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) + if not bx0 then + return nil, nil + end + if abs(bx0 :: number) > LIMIT or abs(by0 :: number) > LIMIT or abs(bx1 :: number) > LIMIT or abs(by1 :: number) > LIMIT then + return nil, "coordinates out of range" + end + local X0, Y0, X1, Y1 = floor(bx0 :: number), floor(by0 :: number), ceil(bx1 :: number), ceil(by1 :: number) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + Y0 = max(Y0, floor(clip[2])) + Y1 = min(Y1, ceil(clip[4])) + X1 = min(X1, ceil(clip[3])) + local cx0 = floor(clip[1]) + X0 = max(X0, cx0) + end + local W, H = X1 - X0, Y1 - Y0 + if W <= 0 or H <= 0 then + return nil, nil + end + local maxPixels = if type(o.maxPixels) == "number" then o.maxPixels else 2 ^ 26 + if W * H > maxPixels then + return nil, "limit" + end + local S = W + 2 + local acc = bcreate(S * H * 4) + for _, poly in polys do + local n = #poly + local lx, ly = poly[n - 1] - X0, poly[n] - Y0 + for i = 1, n - 1, 2 do + local x, y = poly[i] - X0, poly[i + 1] - Y0 + edge(acc, S, W, H, lx, ly, x, y) + lx, ly = x, y + end + end + local cov = bcreate(W * H) + local evenodd = o.rule == "evenodd" + for y = 0, H - 1 do + local sum = 0 + local ls = y * S + local os = y * W + for x = 0, W - 1 do + sum += readf32(acc, (ls + x) * 4) + local v = abs(sum) + if evenodd then + v = v % 2 + if v > 1 then + v = 2 - v + end + elseif v > 1 then + v = 1 + end + writeu8(cov, os + x, floor(v * 255 + 0.5)) + end + end + return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil +end + +-- ------------------------------------------------------------------------------------------------ filling +-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an +-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in +-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the +-- image; opts.opacity scales the coverage. +@native function Raster.fill(img: any, path: any, paint: any, opts: Options?): (boolean, string?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return false, "fill: expected an rgba8 image" + end + local iw, ih = img.width, img.height + local px = img.pixels + if buffer.len(px) < iw * ih * 4 then + return false, "fill: image pixels too short" + end + local o: Options = table.clone(opts or {} :: Options) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } + else + o.clip = { 0, 0, iw, ih } + end + local m, why = Raster.mask(path, o) + if not m then + return why == nil, why + end + local opacity = if type(o.opacity) == "number" then math.clamp(o.opacity, 0, 1) else 1 + local fn: any = nil + local cr, cg, cb, ca = 0, 0, 0, 255 + if type(paint) == "function" then + fn = paint + elseif type(paint) == "table" then + cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0 + ca = tonumber(paint[4]) or 255 + else + return false, "fill: paint must be a colour or a function" + end + local cov = m.coverage + local mw = m.width + for y = 0, m.height - 1 do + local iy = m.y + y + for x = 0, mw - 1 do + local cv = readu8(cov, y * mw + x) + if cv > 0 then + local ix = m.x + x + local r, g, b, a = cr, cg, cb, ca + if fn then + local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5) + if not ok then + return false, "fill: paint function failed" + end + r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255 + end + local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity + if sa > 0 then + local p = (iy * iw + ix) * 4 + local da = readu8(px, p + 3) / 255 + local oa = sa + da * (1 - sa) + local k = da * (1 - sa) + writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5)) + writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5)) + writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5)) + writeu8(px, p + 3, floor(oa * 255 + 0.5)) + end + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ stroking +type StrokeOptions = { + width: number?, -- default 1 + join: ("miter" | "round" | "bevel")?, -- default "miter" + cap: ("butt" | "round" | "square")?, -- default "butt" + miterLimit: number?, -- default 4 (SVG) + tolerance: number?, -- flattening tolerance in path units (default 0.1); scale it down for magnified strokes + closed: boolean?, -- treat every subpath as closed (default: only subpaths ending with "close") +} + +-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up +-- under the nonzero rule +@native local function polygon(out: Path, pts: { number }) + local n = #pts + if n < 6 then + return + end + local area = 0 + for i = 1, n - 1, 2 do + local j = if i + 2 > n then 1 else i + 2 + area += pts[i] * pts[j + 1] - pts[j] * pts[i + 1] + end + if area == 0 then + return + end + if area > 0 then + table.insert(out, { op = "moveTo", pts[1], pts[2] }) + for i = 3, n - 1, 2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + else + table.insert(out, { op = "moveTo", pts[n - 1], pts[n] }) + for i = n - 3, 1, -2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + end + table.insert(out, { op = "close" } :: Cmd) +end + +@native local function arcPoints(cx: number, cy: number, r: number, a0: number, a1: number, tol: number, pts: { number }) + local da = a1 - a0 + local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) + local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) + for i = 0, n do + local t = a0 + da * i / n + table.insert(pts, cx + r * math.cos(t)) + table.insert(pts, cy + r * math.sin(t)) + end +end + +-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own +-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). +@native function Raster.stroke(path: any, opts: StrokeOptions?): Path + local o: StrokeOptions = opts or {} + local hw = (if type(o.width) == "number" and o.width > 0 then o.width else 1) / 2 + local join = o.join or "miter" + local cap = o.cap or "butt" + local miterLimit = if type(o.miterLimit) == "number" and o.miterLimit >= 1 then o.miterLimit else 4 + local tol = if type(o.tolerance) == "number" and o.tolerance > 0.0005 then o.tolerance else 0.1 + local out: Path = {} + local cmds = commands(path) + if not cmds then + return out + end + -- subpaths with their closed flag (flatten loses it, so split here) + local subs: { { cmds: Path, closed: boolean } } = {} + local cur: Path? = nil + local lx, ly = 0, 0 + for _, c in cmds do + local op = if type(c) == "table" then c.op else nil + if op == "moveTo" and operands(c, 2) then + cur = { c } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + lx, ly = c[1], c[2] + elseif op == "close" then + if cur then + subs[#subs].closed = true + cur = nil + end + elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then + if not cur then + cur = { { op = "moveTo", lx, ly } } + table.insert(subs, { cmds = cur :: Path, closed = o.closed == true }) + end + table.insert(cur :: Path, c) + end + end + for _, sub in subs do + local polys = flatten(sub.cmds, nil, tol, 4) + local pts = polys[1] + if not pts then + -- a degenerate subpath (a single point): round / square caps draw a dot + local m = sub.cmds[1] + if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then + local d = {} + if cap == "round" then + arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d) + else + d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw } + end + polygon(out, d) + end + continue + end + -- drop repeated points + local p: { number } = { pts[1], pts[2] } + for i = 3, #pts - 1, 2 do + if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then + table.insert(p, pts[i]) + table.insert(p, pts[i + 1]) + end + end + local closed = sub.closed + if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then + table.remove(p) + table.remove(p) + end + local n = #p // 2 + if n < 2 then + continue + end + local segs = if closed then n else n - 1 + -- segment bodies + local dirs: { number } = {} + for s = 0, segs - 1 do + local i, j = s, (s + 1) % n + local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] + local dx, dy = x1 - x0, y1 - y0 + local len = sqrt(dx * dx + dy * dy) + local ux, uy = dx / len, dy / len + dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy + local nx, ny = -uy * hw, ux * hw + polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) + end + -- joins + @native local function joinAt(k: number, s0: number, s1: number) + local x, y = p[2 * k + 1], p[2 * k + 2] + local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] + local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] + local cross = ax * by - ay * bx + if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then + return + end + -- the outer side: left normals when turning right (cross < 0) + local sgn = if cross < 0 then 1 else -1 + local n0x, n0y = -ay * hw * sgn, ax * hw * sgn + local n1x, n1y = -by * hw * sgn, bx * hw * sgn + if join == "round" then + local d = { x, y } + local a0 = math.atan2(n0y, n0x) + local a1 = math.atan2(n1y, n1x) + local da = a1 - a0 + while da > math.pi do + da -= 2 * math.pi + end + while da < -math.pi do + da += 2 * math.pi + end + arcPoints(x, y, hw, a0, a0 + da, tol, d) + polygon(out, d) + else + local cosT = ax * bx + ay * by -- angle between directions + local miter = if join == "miter" then 1 / sqrt(max(1e-12, (1 + cosT) / 2)) else math.huge + if join == "miter" and miter <= miterLimit then + local mx, my = n0x + n1x, n0y + n1y + local ml = sqrt(mx * mx + my * my) + if ml > 1e-12 then + local scale = hw * miter / ml + polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y }) + return + end + end + polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y }) + end + end + if closed then + for k = 0, n - 1 do + joinAt(k, (k - 1) % n, k) + end + else + for k = 1, n - 2 do + joinAt(k, k - 1, k) + end + -- caps + if cap ~= "butt" then + for _, endInfo in { { 0, 0, -1 }, { n - 1, segs - 1, 1 } } do + local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] + local x, y = p[2 * k + 1], p[2 * k + 2] + local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards + local nx, ny = -uy * hw, ux * hw + if cap == "square" then + polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) + else + local d = {} + local a0 = math.atan2(ny, nx) + arcPoints(x, y, hw, a0, a0 - math.pi, tol, d) + polygon(out, d) + end + end + end + end + end + return out +end + +return Raster +end +__FILES["codecs/image/Texel"] = @native function() + + + +-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers +-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named +-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, +-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: +-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other +-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. +-- +-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels +-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) +-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode +-- +-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. +-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped +-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 +-- (snorm -> -1..1, integers as their values). +local Half = __include("codecs/image/Half") + +local Texel = {} + +type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l) +type Desc = { + bytes: number, -- per texel + kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", + size: number?, -- array: bytes per component (1, 2, 4) + type: string?, -- array: unorm / snorm / uint / sint / float + order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb) + channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word +} + +local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 +local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ formats +local FORMATS: { [string]: Desc } = {} +@native local function array(name: string, size: number, typ: string, order: string) + FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } +end +for _, o in { "r", "rg", "rgb", "rgba" } do + array(o .. "8", 1, "unorm", o) + array(o .. "8s", 1, "snorm", o) + array(o .. "8ui", 1, "uint", o) + array(o .. "8i", 1, "sint", o) + array(o .. "16", 2, "unorm", o) + array(o .. "16s", 2, "snorm", o) + array(o .. "16ui", 2, "uint", o) + array(o .. "16i", 2, "sint", o) + array(o .. "16f", 2, "float", o) + array(o .. "32ui", 4, "uint", o) + array(o .. "32i", 4, "sint", o) + array(o .. "32f", 4, "float", o) +end +array("bgr8", 1, "unorm", "bgr") +array("bgra8", 1, "unorm", "bgra") +array("bgrx8", 1, "unorm", "bgrx") +array("rgbx8", 1, "unorm", "rgbx") +array("a8", 1, "unorm", "a") +array("l8", 1, "unorm", "l") +array("la8", 1, "unorm", "la") +array("l16", 2, "unorm", "l") +array("la16", 2, "unorm", "la") +array("a16", 2, "unorm", "a") + +@native local function packed(name: string, bytes: number, spec: { any }) + local ch: { Channel } = {} + for i = 1, #spec, 3 do + table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) + end + FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch } +end +packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 }) +packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 }) +packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 }) +packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 }) +packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 }) +packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 }) +packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 }) +packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 }) +packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 }) +packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 }) +packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 }) +packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 }) +packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 }) +FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" } +FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" } +-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range +FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" } +FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" } +FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" } +FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } +FORMATS.ayuv = { bytes = 4, kind = "ayuv" } +Texel.FORMATS = FORMATS + +-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: +-- the r mask is a luminance channel +@native function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? + if bytes < 1 or bytes > 4 then + return nil + end + local ch: { Channel } = {} + for i, m in { r, g, b, a } do + if m ~= 0 then + local shift = 0 + while band(m, lshift(1, shift)) == 0 and shift < 31 do + shift += 1 + end + local bits = 0 + while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do + bits += 1 + end + local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a" + table.insert(ch, { c = name, shift = shift, bits = bits }) + end + end + if #ch == 0 then + return nil + end + return { bytes = bytes, kind = "packed", channels = ch } +end + +-- size(fmt, w, h) -> bytes (rows tightly packed) | nil +@native function Texel.size(fmt: string | Desc, w: number, h: number): number? + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil + end + return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h +end + +-- ------------------------------------------------------------------------------------------------ helpers +-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 +@native local function nativeOf(d: Desc): string + if d.kind == "array" then + local t, s = d.type, d.size :: number + if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then + return "rgbaf32" + end + return if s == 1 then "rgba8" else "rgba16" + elseif d.kind == "packed" then + local wide = false + for _, c in d.channels :: { Channel } do + wide = wide or c.bits > 8 + end + return if wide then "rgba16" else "rgba8" + end + return "rgbaf32" +end +Texel.nativeOf = nativeOf + +@native local function uf11(v: number): number + local e, m = rshift(v, 6), band(v, 63) + if e == 0 then + return m / 64 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 64) * 2 ^ (e - 15) +end +@native local function uf10(v: number): number + local e, m = rshift(v, 5), band(v, 31) + if e == 0 then + return m / 32 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 32) * 2 ^ (e - 15) +end + +-- one component at q of an array format -> a float (native meaning) and its rgba8 byte +@native local function component(src: buffer, q: number, size: number, typ: string): (number, number) + if typ == "unorm" then + if size == 1 then + local v = readu8(src, q) + return v / 255, v + elseif size == 2 then + local v = readu16(src, q) + return v / 65535, (v * 255 + 32767) // 65535 + end + local v = readu32(src, q) + return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5) + elseif typ == "snorm" then + if size == 1 then + local v = math.max(readi8(src, q), -127) + return v / 127, v + 128 + elseif size == 2 then + local v = math.max(readi16(src, q), -32767) + return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128 + end + local v = math.max(readi32(src, q), -2147483647) + return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128 + elseif typ == "float" then + local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q) + local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f + return f, math.floor(c * 255 + 0.5) + elseif typ == "uint" then + local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q) + return v, math.min(v, 255) + end + local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q) + return v, math.clamp(v, 0, 255) +end + +-- BT.601 limited-range Y'CbCr -> an rgba8 u32 +@native local function ycc(y: number, u: number, v: number, a: number): number + local c, d, e = 1.164 * (y - 16), u - 128, v - 128 + local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) + local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) + local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255) + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) +@native local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer + local n = 0 + local order = d.order or "" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + if d.kind == "ayuv" then + local q = s + x * 4 + writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3))) + else + local q = s + (x // 2) * 4 + local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3) + local odd = x % 2 == 1 + if order == "yuyv" then + writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255)) + elseif order == "uyvy" then + writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255)) + elseif order == "rgbg" then + writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000) + else + writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000) + end + end + n += 4 + end + end + return dst +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, +-- message. rowPitch: bytes per source row (default tight). +@native function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil, "unsupported: unknown texel format " .. tostring(fmt) + end + local tb = d.bytes + local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w + local pitch = rowPitch or rowBytes + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then + return nil, "bad image size" + end + if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then + return nil, "truncated: texel data runs past the end" + end + local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8" + local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16 + local dst = buffer.create(w * h * bpp) + local n = 0 + if d.kind == "array" then + local order, size, typ = d.order :: string, d.size :: number, d.type :: string + -- fast paths + if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then + local swap = order == "bgra" or order == "bgrx" + local opaque = order == "bgrx" or order == "rgbx" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + if swap then + v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16) + end + if opaque then + v = band(v, 0xFFFFFF) + 0xFF000000 + end + writeu32(dst, n, v) + n += 4 + end + end + return dst, out + end + local nc = #order + local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + for i = 1, nc do + local c = string.sub(order, i, i) + map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1 + end + local f = table.create(4, 0) + local q8 = table.create(4, 0) + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + f[1], f[2], f[3], f[4] = 0, 0, 0, 1 + q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255 + for i = 1, nc do + local m = map[i] + if m >= 0 then + local fv, bv = component(src, s, size, typ) + if m == 4 then + f[1], f[2], f[3] = fv, fv, fv + q8[1], q8[2], q8[3] = bv, bv, bv + else + f[m + 1], q8[m + 1] = fv, bv + end + end + s += size + end + if out == "rgba8" then + writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216) + elseif out == "rgba16" then + for c = 0, 3 do + writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5)) + end + else + for c = 0, 3 do + writef32(dst, n + c * 4, f[c + 1]) + end + end + n += bpp + end + end + return dst, out + elseif d.kind == "packed" then + local chs = d.channels :: { Channel } + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s) + s += tb + local r, g, b, a = 0, 0, 0, 1 + for _, c in chs do + local maxv = lshift(1, c.bits) - 1 + local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv) + local k = c.c + if k == "r" then + r = x + elseif k == "g" then + g = x + elseif k == "b" then + b = x + elseif k == "a" then + a = x + else + r, g, b = x, x, x + end + end + if out == "rgba8" then + writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216) + else + writeu16(dst, n, math.floor(r * 65535 + 0.5)) + writeu16(dst, n + 2, math.floor(g * 65535 + 0.5)) + writeu16(dst, n + 4, math.floor(b * 65535 + 0.5)) + writeu16(dst, n + 6, math.floor(a * 65535 + 0.5)) + end + n += bpp + end + end + return dst, out + end + if d.kind == "pair" or d.kind == "ayuv" then + return yuv(d, src, offset, w, h, pitch, dst), out + end + -- shared-exponent / packed floats + local nine = d.kind == "rgb9e5" + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = readu32(src, s) + s += 4 + local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0 + local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047)) + local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047)) + local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22)) + if out == "rgba8" then + @native local function q(x: number): number + return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5) + end + writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) + else + writef32(dst, n, r) + writef32(dst, n + 4, g) + writef32(dst, n + 8, b) + writef32(dst, n + 12, 1) + end + n += bpp + end + end + return dst, out +end + +return Texel +end +__FILES["codecs/image/Texture"] = function() + +-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): +-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format +-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one +-- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws. +-- +-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format +-- Texture.size("etc2_rgb", w, h) -- bytes of one surface +-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them +-- local smaller = Texture.halve(img) -- box-filtered next mip level +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Etc = __include("codecs/image/Etc") +local Texel = __include("codecs/image/Texel") +local Half = __include("codecs/image/Half") + +local Texture = {} + +-- known(name) -> "bcn" | "etc" | "texel" | nil +function Texture.known(name: string): string? + if Bcn.BLOCK[name] then + return "bcn" + elseif Etc.BLOCK[name] then + return "etc" + elseif Texel.FORMATS[name] then + return "texel" + end + return nil +end + +-- size(name, w, h) -> bytes of a w x h surface | nil +function Texture.size(name: string, w: number, h: number): number? + return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) +end + +-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil +function Texture.block(name: string): (number?, number?, number?) + local b = Bcn.BLOCK[name] or Etc.BLOCK[name] + if b then + return 4, 4, b + end + local d = Texel.FORMATS[name] + if d then + return 1, 1, d.bytes + end + return nil, nil, nil +end + +-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is +-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). +function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string) + if Bcn.BLOCK[name] then + local px, err = Bcn.decode(name, src, offset, w, h) + if not px then + return nil, err or "bad block data" + end + if Bcn.FLOAT[name] then + if native then + return px, "rgbaf32" + end + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5)) + end + end + return out, "rgba8" + end + return px, "rgba8" + elseif Etc.BLOCK[name] then + local wide = native == true and string.sub(name, 1, 3) == "eac" + local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide) + if not px then + return nil, err or "bad block data" + end + return px, if wide then "rgba16" else "rgba8" + end + return Texel.decode(name, src, offset, w, h, native) +end + +-- image(pixels, pixel format, w, h) -> Types.Image +function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image + local img = Types.Image.new(0, 0, pf :: any) + img.width, img.height, img.pixels = w, h, px + return img +end + +type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } + +-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / +-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface +function Texture.assemble(list: { Surface }, layout: string): Types.Image? + local first: Types.Image? = nil + local frames: { Types.Frame } = {} + local mips: { Types.Image } = {} + for _, s in list do + if s.level == 0 then + first = first or s.image + local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + table.insert(frames, fr) + elseif s.layer == 0 and s.face == 0 and s.slice == 0 then + mips[s.level] = s.image + end + end + if not first then + return nil + end + local img = Texture.image(first.pixels, first.format, first.width, first.height) + if #frames > 1 then + img.frames = frames + end + if #mips > 0 then + img.meta.mipmaps = mips + end + img.meta.layout = layout + return img +end + +-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format +-- (rgba8 / rgba16 / rgbaf32) +function Texture.halve(img: Types.Image): Types.Image + local w, h = img.width, img.height + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local fmt = img.format + local out = Types.Image.new(nw, nh, fmt) + local src, dst = img.pixels, out.pixels + local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4 + local function get(x: number, y: number, c: number): number + local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs + return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o) + end + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local x0, y0 = x * 2, y * 2 + local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4 + local o = ((y * nw + x) * 4 + c) * cs + if cs == 1 then + buffer.writeu8(dst, o, math.floor(v + 0.5)) + elseif cs == 2 then + buffer.writeu16(dst, o, math.floor(v + 0.5)) + else + buffer.writef32(dst, o, v) + end + end + end + end + return out +end + +-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) +function Texture.toHalf(px: buffer, n: number): buffer + local out = buffer.create(n * 8) + local from = Half.fromFloat + for i = 0, n * 4 - 1 do + buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4))) + end + return out +end + +return Texture +end +__FILES["codecs/image/Vp8"] = function() + +-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the +-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals +-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. +-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; +-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with +-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / +-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error +-- concealment (a damaged frame returns an Err). +-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace +-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). +-- +-- local Vp8 = require("@rosetta/codecs/image/Vp8") +-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image +-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) +-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames +-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame +-- dec:reset() -- after a seek: the next frame must be a key frame +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Vp8/Decode") +local Yuv = __include("codecs/image/Vp8/Yuv") + +local Vp8 = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +type Options = { + maxPixels: number?, -- default 2^28 +} + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + elseif string.sub(m, 1, 13) == "unsupported: " then + return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err +function Vp8.info(buf: buffer, off: number?, len: number?): (any, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "info: expected a buffer") + end + local o, l = range(buf, off, len) + local h, err = Decode.header(buf, o, l) + if not h then + return nil, fail(err, o) + end + return h, nil +end + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta)) + +-- newDecoder() -> Decoder: decodes successive frames of one stream +function Vp8.newDecoder(): Decoder + return setmetatable({ state = Decode.new() }, DecoderMeta) +end + +-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; +-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), +-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. +function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local img = Types.Image.new(f.width, f.height, "yuv420p") + local ny = f.width * f.height + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) + local h = f.header + img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } + return img, nil +end + +-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame +function DecoderMeta.reset(self: Decoder) + Decode.reset(self.state) +end + +-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) +function Vp8.decodeFrame(buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?) + return Vp8.newDecoder():decodeFrame(buf, off, len, opts) +end + +-- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes +function Vp8.decodePlanes(buf: buffer, off: number?, len: number?, opts: Options?): (buffer?, any, buffer?, number?, number?) + if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2) + local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) + Decode.cropTo(f, y, 0, u, 0, v, 0) + return y, u, v, f.width, f.height +end + +-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height +function Vp8.planes(img: Types.Image): (number, number, number, number, number) + local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 + local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +-- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point +-- sampling (dwebp -nofancy) +function Vp8.toRgba(img: Types.Image, fancy: boolean?): (Types.Image?, Err.Err?) + if type(img) ~= "table" or img.format ~= "yuv420p" then + return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") + end + local w, h = img.width, img.height + local _, uo, vo, cw, ch = Vp8.planes(img) + local y = buffer.create(w * h) + local u = buffer.create(cw * ch) + local v = buffer.create(cw * ch) + buffer.copy(y, 0, img.pixels, 0, w * h) + buffer.copy(u, 0, img.pixels, uo, cw * ch) + buffer.copy(v, 0, img.pixels, vo, cw * ch) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels) + out.meta.source = img.meta.source + return out, nil +end + +-- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) +function Vp8.yuvToRgba(y: buffer, u: buffer, v: buffer, w: number, h: number, fancy: boolean?): buffer + return Yuv.toRgba(y, u, v, w, h, fancy ~= false) +end + +Vp8.setAlpha = Yuv.setAlpha + +return Vp8 +end +__FILES["codecs/image/Vp8/Decode"] = @native function() + + + +-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra +-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, +-- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and +-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign +-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, +-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per +-- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg +-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate +-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. +-- +-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the +-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when +-- the data ends early). +local Tables = __include("codecs/image/Vp8/Tables") +local Predict = __include("codecs/image/Vp8/Predict") + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create +local abs = math.abs + +local COEFF_PROBA0 = Tables.COEFF_PROBA0 +local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA +local BMODES_PROBA = Tables.BMODES_PROBA +local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE +local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG +local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ boolean decoder +-- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the +-- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. +type Br = { buf: buffer, pos: number, limit: number, value: number, bits: number, range: number, eof: boolean } + +-- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) +local SHIFT = table.create(256, 0) +for r = 1, 255 do + local s, v = 0, r + while v < 128 do + v *= 2 + s += 1 + end + SHIFT[r + 1] = s +end + +@native local function load(br: Br) + local p = br.pos + if p + 3 <= br.limit then + local b = br.buf + br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + br.pos = p + 3 + br.bits += 24 + elseif p < br.limit then + br.value = br.value * 256 + readu8(br.buf, p) + br.pos = p + 1 + br.bits += 8 + elseif not br.eof then + br.value *= 256 + br.bits += 8 + br.eof = true + else + br.bits = 0 + end +end + +@native local function newBr(buf: buffer, off: number, len: number): Br + local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } + load(br) + return br +end + +-- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down): +-- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits +@native local function getBit(br: Br, prob: number): number + if br.bits < 0 then + load(br) + end + local range = br.range + local pos = br.bits + local split = rshift(range * prob, 8) + local bit = rshift(split - rshift(br.value, pos), 31) + local r = split + 1 + bit * (range - split - split - 1) + br.value -= bit * lshift(split + 1, pos) + local shift = SHIFT[r + 1] + br.range = lshift(r, shift) - 1 + br.bits = pos - shift + return bit +end + +@native local function getValue(br: Br, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v += getBit(br, 0x80) * 2 ^ i + end + return v +end + +@native local function getSignedValue(br: Br, n: number): number + local v = getValue(br, n) + return if getBit(br, 0x80) == 1 then -v else v +end + +-- ------------------------------------------------------------------------------------------------ state +type Quant = { y1dc: number, y1ac: number, y2dc: number, y2ac: number, uvdc: number, uvac: number } + +-- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border +type Ref = Predict.Planes & { extended: boolean } + +type State = { + -- the frame context (saved and restored around frames that do not refresh it) + proba: { number }, -- 4 * 8 * 3 * 11 token probabilities + ymodeProb: { number }, -- 4 + uvmodeProb: { number }, -- 3 + mvProb: { number }, -- 2 * 19 + -- persistent between frames (reset by key frames) + segProba: { number }, -- 3 + useSegment: boolean, + updateMap: boolean, + absoluteDelta: boolean, + segQuant: { number }, -- 4 + segFilter: { number }, -- 4 + refLfDelta: { number }, -- 4: intra, last, golden, altref + modeLfDelta: { number }, -- 4: B_PRED, zero, nearest / near / new, split + signBias: { number }, -- 4 (by reference frame + 1) + segMap: { number }, -- the segment of every macroblock + width: number, + height: number, + mbw: number, + mbh: number, + hasKey: boolean, -- a key frame was decoded (inter frames need one) + last: Ref?, + golden: Ref?, + alt: Ref?, + pool: { Ref }, + -- the mode info of the current inter frame, (mbw + 1) x (mbh + 1) with a zero top row and left column + miRef: { number }, + miMode: { number }, + miMvR: { number }, + miMvC: { number }, + miSubR: { number }, -- 16 per macroblock + miSubC: { number }, + miN: number, -- the size of the mode info arrays (allocated by the first inter frame) + pred: buffer?, -- the inter predictions of a row +} + +@native function Decode.new(): State + return { + proba = table.clone(COEFF_PROBA0), + ymodeProb = table.clone(Tables.YMODE_PROB), + uvmodeProb = table.clone(Tables.UVMODE_PROB), + mvProb = table.clone(Tables.MV_DEFAULT), + segProba = { 255, 255, 255 }, + useSegment = false, + updateMap = false, + absoluteDelta = false, + segQuant = { 0, 0, 0, 0 }, + segFilter = { 0, 0, 0, 0 }, + refLfDelta = { 0, 0, 0, 0 }, + modeLfDelta = { 0, 0, 0, 0 }, + signBias = { 0, 0, 0, 0 }, + segMap = {}, + width = 0, + height = 0, + mbw = 0, + mbh = 0, + hasKey = false, + last = nil, + golden = nil, + alt = nil, + pool = {}, + miRef = {}, + miMode = {}, + miMvR = {}, + miMvC = {}, + miSubR = {}, + miSubC = {}, + miN = 0, + pred = nil, + } +end + +-- reset(state): drops the references; the next frame must be a key frame +@native function Decode.reset(st: State) + st.hasKey = false + st.last, st.golden, st.alt = nil, nil, nil +end + +-- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg +@native function Decode.header(buf: buffer, off: number, len: number): (any, string?) + if len < 3 then + return nil, "truncated: frame tag" + end + local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536 + local h = { + keyFrame = band(bits, 1) == 0, + profile = band(rshift(bits, 1), 7), + show = band(rshift(bits, 4), 1) == 1, + partitionLength = rshift(bits, 5), + width = 0, + height = 0, + xscale = 0, + yscale = 0, + } + if h.profile > 3 then + return nil, "bad profile " .. h.profile + end + if h.keyFrame then + if len < 10 then + return nil, "truncated: key frame header" + end + if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then + return nil, "bad VP8 start code" + end + local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256 + local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256 + h.width, h.xscale = band(w, 0x3fff), rshift(w, 14) + h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14) + end + return h, nil +end + +-- ------------------------------------------------------------------------------------------------ residuals +@native local function getLargeValue(br: Br, P: { number }, p: number): number + local v + if getBit(br, P[p + 4]) == 0 then + if getBit(br, P[p + 5]) == 0 then + v = 2 + else + v = 3 + getBit(br, P[p + 6]) + end + else + if getBit(br, P[p + 7]) == 0 then + if getBit(br, P[p + 8]) == 0 then + v = 5 + getBit(br, 159) + else + v = 7 + 2 * getBit(br, 165) + v += getBit(br, 145) + end + else + local bit1 = getBit(br, P[p + 9]) + local bit0 = getBit(br, P[p + 10 + bit1]) + local cat = 2 * bit1 + bit0 + v = 0 + for _, pr in CAT[cat + 1] do + v = v + v + getBit(br, pr) + end + v += 3 + lshift(8, cat) + end + end + return v +end + +-- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the +-- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean +-- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. +@native local function getCoeffs(br: Br, P: { number }, t: number, ctx: number, dqDc: number, dqAc: number, n: number, out: buffer, o: number): number + local tb = t * 8 + local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 + local buf, limit = br.buf, br.limit + local value, bits, range, pos = br.value, br.bits, br.range, br.pos + while n < 16 do + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 1], 8) + local more = rshift(value, bits) > split + if more then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not more then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return n + end + end + while true do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 2], 8) + local nonzero = rshift(value, bits) > split + if nonzero then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if nonzero then + break + end + n += 1 + if n == 16 then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 + end + p = (tb + BANDS[n + 1]) * 33 + end + local nb = (tb + BANDS[n + 2]) * 3 + local v + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 3], 8) + local large = rshift(value, bits) > split + if large then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if not large then + v = 1 + p = (nb + 1) * 11 + else + br.value, br.bits, br.range, br.pos = value, bits, range, pos + v = getLargeValue(br, P, p) + value, bits, range, pos = br.value, br.bits, br.range, br.pos + p = (nb + 2) * 11 + end + end + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos += 3 + bits += 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * 0x80, 8) + local neg = rshift(value, bits) > split + if neg then + range -= split + value -= lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits -= sh + if neg then + v = -v + end + end + if n > 0 then + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqAc) + else + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqDc) + end + n += 1 + end + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 +end + +@native local function nzCode(acc: number, nz: number, dcNz: number): number + return acc * 4 + (if nz > 3 then 3 elseif nz > 1 then 2 else dcNz) +end + +-- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks +local whtTmp = table.create(16, 0) +@native local function transformWHT(inp: buffer, out: buffer, o: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) + local a0 = i0 + i12 + local a1 = i4 + i8 + local a2 = i4 - i8 + local a3 = i0 - i12 + whtTmp[1 + i] = a0 + a1 + whtTmp[9 + i] = a0 - a1 + whtTmp[5 + i] = a3 + a2 + whtTmp[13 + i] = a3 - a2 + end + for i = 0, 3 do + local dc = whtTmp[1 + i * 4] + 3 + local a0 = dc + whtTmp[4 + i * 4] + local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4] + local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4] + local a3 = dc - whtTmp[4 + i * 4] + local base = o + i * 128 + writei16(out, base, (a0 + a1) // 8) + writei16(out, base + 32, (a3 + a2) // 8) + writei16(out, base + 64, (a0 - a1) // 8) + writei16(out, base + 96, (a3 - a2) // 8) + end +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side +local BPS = 32 +local Y_OFF = BPS + 8 +local U_OFF = Y_OFF + BPS * 16 + BPS +local V_OFF = U_OFF + 16 +local YUV_SIZE = BPS * 17 + BPS * 9 + +@native local function clip8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- the inverse DCT of one block (libwebp TransformOne) added to dst +local C1, C2 = 20091, 35468 +local idctTmp = table.create(16, 0) +@native local function mul1(a: number): number + return ((a * C1) // 65536) + a +end +@native local function mul2(a: number): number + return (a * C2) // 65536 +end +@native local function transformOne(c: buffer, o: number, b: buffer, dst: number) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) + local a = i0 + i8 + local bb = i0 - i8 + local cc = mul2(i4) - mul1(i12) + local d = mul1(i4) + mul2(i12) + idctTmp[i * 4 + 1] = a + d + idctTmp[i * 4 + 2] = bb + cc + idctTmp[i * 4 + 3] = bb - cc + idctTmp[i * 4 + 4] = a - d + end + for i = 0, 3 do + local dc = idctTmp[i + 1] + 4 + local a = dc + idctTmp[i + 9] + local bb = dc - idctTmp[i + 9] + local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13]) + local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13]) + local row = dst + i * BPS + writeu8(b, row, clip8(readu8(b, row) + (a + d) // 8)) + writeu8(b, row + 1, clip8(readu8(b, row + 1) + (bb + cc) // 8)) + writeu8(b, row + 2, clip8(readu8(b, row + 2) + (bb - cc) // 8)) + writeu8(b, row + 3, clip8(readu8(b, row + 3) + (a - d) // 8)) + end +end + +@native local function transformDC(c: buffer, o: number, b: buffer, dst: number) + local dc = (readi16(c, o) + 4) // 8 + for j = 0, 3 do + local row = dst + j * BPS + for i = row, row + 3 do + writeu8(b, i, clip8(readu8(b, i) + dc)) + end + end +end + +-- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only +@native local function doTransform(code: number, c: buffer, o: number, b: buffer, dst: number) + if code >= 2 then + transformOne(c, o, b, dst) + elseif code == 1 then + transformDC(c, o, b, dst) + end +end + +@native local function doUVTransform(bits: number, c: buffer, o: number, b: buffer, dst: number) + if band(bits, 0xff) ~= 0 then + if band(bits, 0xaa) ~= 0 then + transformOne(c, o, b, dst) + transformOne(c, o + 32, b, dst + 4) + transformOne(c, o + 64, b, dst + 4 * BPS) + transformOne(c, o + 96, b, dst + 4 * BPS + 4) + else + if readi16(c, o) ~= 0 then + transformDC(c, o, b, dst) + end + if readi16(c, o + 32) ~= 0 then + transformDC(c, o + 32, b, dst + 4) + end + if readi16(c, o + 64) ~= 0 then + transformDC(c, o + 64, b, dst + 4 * BPS) + end + if readi16(c, o + 96) ~= 0 then + transformDC(c, o + 96, b, dst + 4 * BPS + 4) + end + end + end +end + +-- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) +@native local function fill(b: buffer, dst: number, size: number, v: number) + for j = 0, size - 1 do + local o = dst + j * BPS + for i = o, o + size - 4, 4 do + writeu32(b, i, v * 0x01010101) + end + end +end + +@native local function trueMotion(b: buffer, dst: number, size: number) + local tl = readu8(b, dst - BPS - 1) + for y = 0, size - 1 do + local row = dst + y * BPS + local l = readu8(b, row - 1) - tl + for x = 0, size - 1 do + writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l)) + end + end +end + +@native local function predictBlock(b: buffer, dst: number, size: number, mode: number) + local shift = if size == 16 then 5 else 4 + if mode == 0 then + local dc = size + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift)) + elseif mode == 1 then + trueMotion(b, dst, size) + elseif mode == 2 then + for j = 0, size - 1 do + local o = dst + j * BPS + for i = 0, size - 4, 4 do + writeu32(b, o + i, readu32(b, dst - BPS + i)) + end + end + elseif mode == 3 then + for j = 0, size - 1 do + local o = dst + j * BPS + local v = readu8(b, o - 1) * 0x01010101 + for i = o, o + size - 4, 4 do + writeu32(b, i, v) + end + end + elseif mode == 4 then -- no top: left samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst - 1 + j * BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + elseif mode == 5 then -- no left: top samples + local dc = size // 2 + for j = 0, size - 1 do + dc += readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + else + fill(b, dst, size, 0x80) + end +end + +@native local function avg3(a: number, b: number, c: number): number + return rshift(a + 2 * b + c + 2, 2) +end +@native local function avg2(a: number, b: number): number + return rshift(a + b + 1, 1) +end + +-- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU +@native local function predict4(b: buffer, dst: number, mode: number) + if mode == 0 then + local dc = 4 + for i = 0, 3 do + dc += readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS) + end + fill(b, dst, 4, rshift(dc, 3)) + elseif mode == 1 then + trueMotion(b, dst, 4) + elseif mode == 2 then + local t = dst - BPS + local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) + local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) + for j = 0, 3 do + writeu8(b, dst + j * BPS + 0, v0) + writeu8(b, dst + j * BPS + 1, v1) + writeu8(b, dst + j * BPS + 2, v2) + writeu8(b, dst + j * BPS + 3, v3) + end + elseif mode == 3 then + local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) + local E = readu8(b, dst - 1 + 3 * BPS) + writeu32(b, dst, avg3(A, B, C) * 0x01010101) + writeu32(b, dst + BPS, avg3(B, C, D) * 0x01010101) + writeu32(b, dst + 2 * BPS, avg3(C, D, E) * 0x01010101) + writeu32(b, dst + 3 * BPS, avg3(D, E, E) * 0x01010101) + else + local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) + local t = dst - BPS + local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) + if mode == 4 then -- RD + writeu8(b, dst + 96, avg3(J, K, L)) + local v = avg3(I, J, K) + writeu8(b, dst + 97, v) + writeu8(b, dst + 64, v) + v = avg3(X, I, J) + writeu8(b, dst + 98, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 32, v) + v = avg3(A, X, I) + writeu8(b, dst + 99, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 0, v) + v = avg3(B, A, X) + writeu8(b, dst + 67, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 1, v) + v = avg3(C, B, A) + writeu8(b, dst + 35, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 3, avg3(D, C, B)) + elseif mode == 5 then -- VR + local v = avg2(X, A) + writeu8(b, dst + 0, v) + writeu8(b, dst + 65, v) + v = avg2(A, B) + writeu8(b, dst + 1, v) + writeu8(b, dst + 66, v) + v = avg2(B, C) + writeu8(b, dst + 2, v) + writeu8(b, dst + 67, v) + writeu8(b, dst + 3, avg2(C, D)) + writeu8(b, dst + 96, avg3(K, J, I)) + writeu8(b, dst + 64, avg3(J, I, X)) + v = avg3(I, X, A) + writeu8(b, dst + 32, v) + writeu8(b, dst + 97, v) + v = avg3(X, A, B) + writeu8(b, dst + 33, v) + writeu8(b, dst + 98, v) + v = avg3(A, B, C) + writeu8(b, dst + 34, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 35, avg3(B, C, D)) + elseif mode == 6 then -- LD + writeu8(b, dst + 0, avg3(A, B, C)) + local v = avg3(B, C, D) + writeu8(b, dst + 1, v) + writeu8(b, dst + 32, v) + v = avg3(C, D, E) + writeu8(b, dst + 2, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 64, v) + v = avg3(D, E, F) + writeu8(b, dst + 3, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 96, v) + v = avg3(E, F, G) + writeu8(b, dst + 35, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 97, v) + v = avg3(F, G, H) + writeu8(b, dst + 67, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 99, avg3(G, H, H)) + elseif mode == 7 then -- VL + writeu8(b, dst + 0, avg2(A, B)) + local v = avg2(B, C) + writeu8(b, dst + 1, v) + writeu8(b, dst + 64, v) + v = avg2(C, D) + writeu8(b, dst + 2, v) + writeu8(b, dst + 65, v) + v = avg2(D, E) + writeu8(b, dst + 3, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 32, avg3(A, B, C)) + v = avg3(B, C, D) + writeu8(b, dst + 33, v) + writeu8(b, dst + 96, v) + v = avg3(C, D, E) + writeu8(b, dst + 34, v) + writeu8(b, dst + 97, v) + v = avg3(D, E, F) + writeu8(b, dst + 35, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 67, avg3(E, F, G)) + writeu8(b, dst + 99, avg3(F, G, H)) + elseif mode == 8 then -- HD + local v = avg2(I, X) + writeu8(b, dst + 0, v) + writeu8(b, dst + 34, v) + v = avg2(J, I) + writeu8(b, dst + 32, v) + writeu8(b, dst + 66, v) + v = avg2(K, J) + writeu8(b, dst + 64, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 96, avg2(L, K)) + writeu8(b, dst + 3, avg3(A, B, C)) + writeu8(b, dst + 2, avg3(X, A, B)) + v = avg3(I, X, A) + writeu8(b, dst + 1, v) + writeu8(b, dst + 35, v) + v = avg3(J, I, X) + writeu8(b, dst + 33, v) + writeu8(b, dst + 67, v) + v = avg3(K, J, I) + writeu8(b, dst + 65, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 97, avg3(L, K, J)) + else -- HU + writeu8(b, dst + 0, avg2(I, J)) + local v = avg2(J, K) + writeu8(b, dst + 2, v) + writeu8(b, dst + 32, v) + v = avg2(K, L) + writeu8(b, dst + 34, v) + writeu8(b, dst + 64, v) + writeu8(b, dst + 1, avg3(I, J, K)) + v = avg3(J, K, L) + writeu8(b, dst + 3, v) + writeu8(b, dst + 33, v) + v = avg3(K, L, L) + writeu8(b, dst + 35, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 67, L) + writeu8(b, dst + 66, L) + writeu8(b, dst + 96, L) + writeu8(b, dst + 97, L) + writeu8(b, dst + 98, L) + writeu8(b, dst + 99, L) + end + end +end + +@native local function checkMode(mbx: number, mby: number, mode: number): number + if mode == 0 then + if mbx == 0 then + return if mby == 0 then 6 else 5 + end + return if mby == 0 then 4 else 0 + end + return mode +end + +-- ------------------------------------------------------------------------------------------------ loop filter +-- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to +-- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are +-- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. + +-- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter +-- value a is 0 changes nothing and is skipped before the mask (flat areas). +@native local function simpleFilter(b: buffer, p: number, step: number, along: number, thresh: number) + local t2 = 2 * thresh + 1 + for _ = 1, 16 do + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 and 4 * abs(p0 - q0) + abs(w) <= t2 then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - step, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + end + p += along + end +end + +-- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +@native local function filterEdge(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (if w < -128 then -128 elseif w > 127 then 127 else w) + if a ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + if dp > hevT or dq > hevT then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + else + if a < -128 then + a = -128 + elseif a > 127 then + a = 127 + end + local a1 = rshift(27 * a + 4159, 7) - 32 + local a2 = rshift(18 * a + 4159, 7) - 32 + local a3 = rshift(9 * a + 4159, 7) - 32 + local v = p2 + a3 + writeu8(b, p - 3 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p1 + a2 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = p0 + a1 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a2 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q2 - a3 + writeu8(b, p + 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end + end + end + end + p += vs + end +end + +-- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when +-- q0 == p0 and p1 == q1 +@native local function filterInner(b: buffer, p: number, hs: number, vs: number, size: number, thresh: number, it: number, hevT: number) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + if q0 ~= p0 or w ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + local hev = dp > hevT or dq > hevT + local a = 3 * (q0 - p0) + if hev then + a += if w < -128 then -128 elseif w > 127 then 127 else w + end + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q0 - a1 + writeu8(b, p, if v < 0 then 0 elseif v > 255 then 255 else v) + if not hev then + local a3 = rshift(a1 + 17, 1) - 8 + v = p1 + a3 + writeu8(b, p - 2 * hs, if v < 0 then 0 elseif v > 255 then 255 else v) + v = q1 - a3 + writeu8(b, p + hs, if v < 0 then 0 elseif v > 255 then 255 else v) + end + end + end + end + p += vs + end +end + +-- ------------------------------------------------------------------------------------------------ inter modes +local MODE_CTX = Tables.MODE_CONTEXTS +local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB +local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT +local BMODE_PROB = Tables.BMODE_PROB +local MV_UPDATE = Tables.MV_UPDATE + +-- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, +-- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: +local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } + +-- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) +@native local function readBMode(br: Br, P: { number }, o: number): number + if getBit(br, P[o + 1]) == 0 then + return 0 + elseif getBit(br, P[o + 2]) == 0 then + return 1 + elseif getBit(br, P[o + 3]) == 0 then + return 2 + elseif getBit(br, P[o + 4]) == 0 then + if getBit(br, P[o + 5]) == 0 then + return 3 + end + return if getBit(br, P[o + 6]) == 0 then 4 else 5 + elseif getBit(br, P[o + 7]) == 0 then + return 6 + elseif getBit(br, P[o + 8]) == 0 then + return 7 + end + return if getBit(br, P[o + 9]) == 0 then 8 else 9 +end + +-- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels +@native local function readMvComponent(br: Br, P: { number }, o: number): number + local x + if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) + x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) + for i = 9, 4, -1 do + x += getBit(br, P[o + 10 + i]) * lshift(1, i) + end + if x < 16 or getBit(br, P[o + 13]) == 1 then + x += 8 + end + elseif getBit(br, P[o + 3]) == 0 then -- short tree + if getBit(br, P[o + 4]) == 0 then + x = getBit(br, P[o + 5]) + else + x = 2 + getBit(br, P[o + 6]) + end + elseif getBit(br, P[o + 7]) == 0 then + x = 4 + getBit(br, P[o + 8]) + else + x = 6 + getBit(br, P[o + 9]) + end + if x ~= 0 and getBit(br, P[o + 2]) == 1 then + x = -x + end + return x +end + +type Rows = { + i4: { boolean }, -- no Y2 block (B_PRED or SPLITMV) + modes: { number }, -- 16 per macroblock: the 16x16 intra mode or the 4x4 ones + uv: { number }, + ref: { number }, -- 0 intra, 1 last, 2 golden, 3 altref + mode: { number }, -- 0..9 (see MODE_LF) + part: { number }, -- SPLITMV partitioning (0 16x8, 1 8x16, 2 8x8, 3 4x4) or -1 +} + +local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) + +-- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx +-- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +@native local function readInterMb(st: State, br: Br, probIntra: number, probLast: number, probGf: number, mi: number, mbx: number, mby: number, rows: Rows) + local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC + local x1 = mbx + 1 + if getBit(br, probIntra) == 0 then + local P = st.ymodeProb + local ymode + if getBit(br, P[1]) == 0 then + ymode = 0 + elseif getBit(br, P[2]) == 0 then + ymode = if getBit(br, P[3]) == 0 then 2 else 3 + else + ymode = if getBit(br, P[4]) == 0 then 1 else 4 + end + local modes = rows.modes + if ymode == 4 then + for k = mbx * 16 + 1, mbx * 16 + 16 do + modes[k] = readBMode(br, BMODE_PROB, 0) + end + else + modes[mbx * 16 + 1] = ymode + end + local U = st.uvmodeProb + if getBit(br, U[1]) == 0 then + rows.uv[x1] = 0 + elseif getBit(br, U[2]) == 0 then + rows.uv[x1] = 2 + else + rows.uv[x1] = if getBit(br, U[3]) == 0 then 3 else 1 + end + rows.i4[x1] = ymode == 4 + rows.ref[x1] = 0 + rows.mode[x1] = ymode + rows.part[x1] = -1 + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 + return + end + local ref = 1 + if getBit(br, probLast) == 1 then + ref = 2 + getBit(br, probGf) + end + -- the near motion vectors of the above, left and above-left macroblocks, sign corrected + local bias = st.signBias + local sb = bias[ref + 1] + local a = mi - (st.mbw + 1) + local l = mi - 1 + local al = a - 1 + for k = 1, 4 do + nr[k], nc[k], cnt[k] = 0, 0, 0 + end + local n = 1 + local rf = miRef[a] + if rf ~= 0 then + local r, c = miMvR[a], miMvC[a] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + n = 2 + nr[2], nc[2] = r, c + end + cnt[n] += 2 + end + rf = miRef[l] + if rf ~= 0 then + local r, c = miMvR[l], miMvC[l] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 2 + else + cnt[1] += 2 + end + end + rf = miRef[al] + if rf ~= 0 then + local r, c = miMvR[al], miMvC[al] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n += 1 + nr[n], nc[n] = r, c + end + cnt[n] += 1 + else + cnt[1] += 1 + end + end + -- clamping bounds (vp8_clamp_mv2), in eighth pixels + local mbw, mbh = st.mbw, st.mbh + local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 + local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 + local mode, mvr, mvc, part = 5, 0, 0, -1 + if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then + if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then + cnt[2] += 1 + end + if cnt[3] > cnt[2] then + cnt[2], cnt[3] = cnt[3], cnt[2] + nr[2], nr[3] = nr[3], nr[2] + nc[2], nc[3] = nc[3], nc[2] + end + local k + if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then + mode, k = 6, 2 + elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then + mode, k = 7, 3 + else + k = if cnt[2] >= cnt[1] then 2 else 1 + end + mvr, mvc = nr[k], nc[k] + if mvc < toL then + mvc = toL + elseif mvc > toR then + mvc = toR + end + if mvr < toT then + mvr = toT + elseif mvr > toB then + mvr = toB + end + if mode == 5 then + -- mvr, mvc: the best vector; new or split + local P = st.mvProb + local sc = (if miMode[a] == 9 then 2 else 0) + (if miMode[l] == 9 then 2 else 0) + (if miMode[al] == 9 then 1 else 0) + if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then + mode = 8 + mvr += readMvComponent(br, P, 0) * 2 + mvc += readMvComponent(br, P, 19) * 2 + else + mode = 9 + local bestR, bestC = mvr, mvc + local s, nump + if getBit(br, 110) == 1 then + if getBit(br, 111) == 1 then + s, nump = getBit(br, 150), 2 + else + s, nump = 2, 4 + end + else + s, nump = 3, 16 + end + part = s + local subR, subC = st.miSubR, st.miSubC + local sb0 = (mi - 1) * 16 + local lb, ab = (l - 1) * 16, (a - 1) * 16 + local splitL, splitA = miMode[l] == 9, miMode[a] == 9 + local count = SPLIT_COUNT[s + 1] + for j = 0, nump - 1 do + local b = SPLIT_OFFSET[s * 16 + j + 1] + local lr, lc, ar, ac + if b % 4 ~= 0 then + lr, lc = subR[sb0 + b], subC[sb0 + b] + elseif splitL then + lr, lc = subR[lb + b + 4], subC[lb + b + 4] + else + lr, lc = miMvR[l], miMvC[l] + end + if b >= 4 then + ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] + elseif splitA then + ar, ac = subR[ab + b + 13], subC[ab + b + 13] + else + ar, ac = miMvR[a], miMvC[a] + end + local pi = ((if ar == 0 and ac == 0 then 4 else 0) + (if lr == 0 and lc == 0 then 2 else 0) + (if lr == ar and lc == ac then 1 else 0)) * 3 + local r, c + if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then + r, c = lr, lc + elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then + r, c = ar, ac + elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then + r, c = 0, 0 + else + r = bestR + readMvComponent(br, P, 0) * 2 + c = bestC + readMvComponent(br, P, 19) * 2 + end + local fo = s * 16 + j * count + for i = fo + 1, fo + count do + local q = sb0 + SPLIT_FILL[i] + 1 + subR[q], subC[q] = r, c + end + end + mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] + end + end + end + rows.i4[x1] = mode == 9 + rows.ref[x1] = ref + rows.mode[x1] = mode + rows.part[x1] = part + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc +end + +-- ------------------------------------------------------------------------------------------------ frame +type Frame = { + width: number, + height: number, + ref: Ref, -- the decoded planes (the decoder keeps them as a reference: copy them out, see cropTo) + header: any, +} + +local BORDER = Predict.BORDER + +@native local function newRef(mbw: number, mbh: number): Ref + local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER + return { + Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), + U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + ys = ys, + uvs = uvs, + yb = BORDER * ys + BORDER, + uvb = BORDER * uvs + BORDER, + mbw = mbw, + mbh = mbh, + extended = false, + } +end + +-- a frame buffer no reference uses +@native local function freeRef(st: State): Ref + for _, r in st.pool do + if r ~= st.last and r ~= st.golden and r ~= st.alt then + return r + end + end + local r = newRef(st.mbw, st.mbh) + table.insert(st.pool, r) + return r +end + +-- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) +@native function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number) + local r = f.ref + local w, h = f.width, f.height + local cw, chh = (w + 1) // 2, (h + 1) // 2 + local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb + for j = 0, h - 1 do + bcopy(dy, oy + j * w, Y, yb + j * ys, w) + end + for j = 0, chh - 1 do + bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) + bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) + end +end + +-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream +@native function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?) + local hdr, herr = Decode.header(buf, off, len) + if not hdr then + return nil, herr + end + local key = hdr.keyFrame + local width, height, p, left + if key then + width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + p, left = off + 10, len - 10 + else + if not st.hasKey then + return nil, "inter frame without a key frame" + end + width, height = st.width, st.height + p, left = off + 3, len - 3 + end + if hdr.partitionLength > left then + return nil, "truncated: first partition" + end + local mbw, mbh = (width + 15) // 16, (height + 15) // 16 + if key then + st.hasKey = false + if width ~= st.width or height ~= st.height then + st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh + st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} + st.miN, st.pred = 0, nil + st.segMap = table.create(mbw * mbh, 0) + end + -- key frames reset the frame context, the segment and loop filter deltas + st.proba = table.clone(COEFF_PROBA0) + st.ymodeProb = table.clone(Tables.YMODE_PROB) + st.uvmodeProb = table.clone(Tables.UVMODE_PROB) + st.mvProb = table.clone(Tables.MV_DEFAULT) + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, false + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + st.refLfDelta = { 0, 0, 0, 0 } + st.modeLfDelta = { 0, 0, 0, 0 } + st.signBias = { 0, 0, 0, 0 } + end + local br = newBr(buf, p, hdr.partitionLength) + p += hdr.partitionLength + left -= hdr.partitionLength + if key then + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + end + -- segment header + st.useSegment = getValue(br, 1) == 1 + if st.useSegment then + st.updateMap = getValue(br, 1) == 1 + if getValue(br, 1) == 1 then + st.absoluteDelta = getValue(br, 1) == 1 + for s = 1, 4 do + st.segQuant[s] = if getValue(br, 1) == 1 then getSignedValue(br, 7) else 0 + end + for s = 1, 4 do + st.segFilter[s] = if getValue(br, 1) == 1 then getSignedValue(br, 6) else 0 + end + end + if st.updateMap then + for s = 1, 3 do + st.segProba[s] = if getValue(br, 1) == 1 then getValue(br, 8) else 255 + end + end + else + st.updateMap = false + end + if br.eof then + return nil, "truncated: segment header" + end + -- filter header + local simple = getValue(br, 1) == 1 + local level = getValue(br, 6) + local sharpness = getValue(br, 3) + local useLfDelta = getValue(br, 1) == 1 + if useLfDelta then + if getValue(br, 1) == 1 then + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.refLfDelta[i] = getSignedValue(br, 6) + end + end + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.modeLfDelta[i] = getSignedValue(br, 6) + end + end + end + end + local filterType = if level == 0 then 0 elseif simple then 1 else 2 + if br.eof then + return nil, "truncated: filter header" + end + -- partitions + local numParts = lshift(1, getValue(br, 2)) + local lastPart = numParts - 1 + if left < 3 * lastPart then + return nil, "truncated: partition sizes" + end + local parts: { Br } = {} + local partStart = p + lastPart * 3 + local sizeLeft = left - lastPart * 3 + for k = 0, lastPart - 1 do + local q = p + k * 3 + local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536 + if psize > sizeLeft then + psize = sizeLeft + end + parts[k + 1] = newBr(buf, partStart, psize) + partStart += psize + sizeLeft -= psize + end + parts[numParts] = newBr(buf, partStart, sizeLeft) + if partStart >= off + len then + return nil, "truncated: partitions" + end + -- quantizers + local baseQ = getValue(br, 7) + local dqy1dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2dc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dqy2ac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvdc = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local dquvac = if getValue(br, 1) == 1 then getSignedValue(br, 4) else 0 + local quants: { Quant } = {} + for s = 1, 4 do + local q + if st.useSegment then + q = st.segQuant[s] + if not st.absoluteDelta then + q += baseQ + end + else + q = baseQ + end + @native local function cq(v: number, m: number): number + return if v < 0 then 0 elseif v > m then m else v + end + local y2ac = (AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) // 65536 + if y2ac < 8 then + y2ac = 8 + end + quants[s] = { + y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1], + y1ac = AC_TABLE[cq(q, 127) + 1], + y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2, + y2ac = y2ac, + uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1], + uvac = AC_TABLE[cq(q + dquvac, 127) + 1], + } + end + -- reference updates (inter frames) + local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 + if not key then + refreshGolden = getValue(br, 1) == 1 + refreshAlt = getValue(br, 1) == 1 + copyToGolden = if refreshGolden then 0 else getValue(br, 2) + copyToAlt = if refreshAlt then 0 else getValue(br, 2) + st.signBias[3] = getValue(br, 1) + st.signBias[4] = getValue(br, 1) + end + -- a frame that does not refresh the context decodes with the updates below, then the context comes back + local saved: { { number } }? = nil + if getValue(br, 1) == 0 then + saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } + end + local refreshLast = key or getValue(br, 1) == 1 + -- token probabilities + local P = st.proba + for i = 1, 1056 do + if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then + P[i] = getValue(br, 8) + end + end + local useSkip = getValue(br, 1) == 1 + local skipP = if useSkip then getValue(br, 8) else 0 + local probIntra, probLast, probGf = 0, 0, 0 + if not key then + probIntra = getValue(br, 8) + probLast = getValue(br, 8) + probGf = getValue(br, 8) + if getValue(br, 1) == 1 then + for i = 1, 4 do + st.ymodeProb[i] = getValue(br, 8) + end + end + if getValue(br, 1) == 1 then + for i = 1, 3 do + st.uvmodeProb[i] = getValue(br, 8) + end + end + local M = st.mvProb + for i = 1, 38 do + if getBit(br, MV_UPDATE[i]) == 1 then + local x = getValue(br, 7) + M[i] = if x == 0 then 1 else x * 2 + end + end + end + @native local function fail(msg: string): (Frame?, string?) + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return nil, msg + end + if br.eof then + return fail("truncated: frame header") + end + + -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold + local lvlTab = table.create(64, 0) + local ilTab, hevTab = table.create(64, 0), table.create(64, 0) + if filterType > 0 then + for s = 0, 3 do + local base + if st.useSegment then + base = st.segFilter[s + 1] + if not st.absoluteDelta then + base += level + end + else + base = level + end + for rf = 0, 3 do + for m = 0, 3 do + local lv = base + if useLfDelta then + lv += st.refLfDelta[rf + 1] + if rf > 0 or m == 0 then + lv += st.modeLfDelta[m + 1] + end + end + lvlTab[s * 16 + rf * 4 + m + 1] = if lv < 0 then 0 elseif lv > 63 then 63 else lv + end + end + end + for lv = 1, 63 do + local il = lv + if sharpness > 0 then + il = rshift(il, if sharpness > 4 then 2 else 1) + if il > 9 - sharpness then + il = 9 - sharpness + end + end + ilTab[lv] = if il < 1 then 1 else il + if key then + hevTab[lv] = if lv >= 40 then 2 elseif lv >= 15 then 1 else 0 + else + hevTab[lv] = if lv >= 40 then 3 elseif lv >= 20 then 2 elseif lv >= 15 then 1 else 0 + end + end + end + + -- the frame buffer (macroblock aligned, with a border) and the references + local cur = freeRef(st) + cur.extended = false + local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb + local refs: { Ref } = {} + local bil, full = hdr.profile > 0, hdr.profile == 3 + if not key then + local rl, rg, ra = st.last :: Ref, st.golden :: Ref, st.alt :: Ref + refs[1], refs[2], refs[3] = rl, rg, ra + for k = 1, 3 do + local r = refs[k] + if not r.extended then + Predict.extend(r) + r.extended = true + end + end + end + local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) + local yuv = bcreate(YUV_SIZE) + local pred = yuv + if not key then + local nmi = (mbw + 1) * (mbh + 1) + if st.miN ~= nmi then + -- zero top row and left column: never written, they read as intra macroblocks without motion + st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) + st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) + st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) + st.miN = nmi + st.pred = bcreate(YUV_SIZE * mbw) + end + pred = st.pred :: buffer + end + local coeffs = bcreate(mbw * 768) + local dcb = bcreate(32) + -- per macroblock column / row state + local intraT = table.create(mbw * 4, 0) + local intraL = table.create(4, 0) + local topNz = table.create(mbw, 0) + local topNzDc = table.create(mbw, 0) + local rows: Rows = { + i4 = table.create(mbw, false), + modes = table.create(mbw * 16, 0), + uv = table.create(mbw, 0), + ref = table.create(mbw, 0), + mode = table.create(mbw, 0), + part = table.create(mbw, -1), + } + local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part + local mbSeg = table.create(mbw, 0) + local mbSkip = table.create(mbw, 0) + local mbNzY = table.create(mbw, 0) + local mbNzUv = table.create(mbw, 0) + -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock + local fLimit = table.create(mbw * mbh, 0) + local fIlevel = table.create(mbw * mbh, 0) + local fInner = table.create(mbw * mbh, 0) + local fHev = table.create(mbw * mbh, 0) + local segProba = st.segProba + local segMap = st.segMap + local updateMap = st.updateMap + local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC + + for mby = 0, mbh - 1 do + local tbr = parts[band(mby, lastPart) + 1] + -- modes of the row (first partition) + for k = 1, 4 do + intraL[k] = 0 + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local si = mby * mbw + x1 + local seg + if updateMap then + if getBit(br, segProba[1]) == 0 then + seg = getBit(br, segProba[2]) + else + seg = getBit(br, segProba[3]) + 2 + end + segMap[si] = seg + elseif key then + seg = 0 + segMap[si] = 0 + else + seg = segMap[si] + end + mbSeg[x1] = seg + mbSkip[x1] = 0 + if useSkip then + mbSkip[x1] = getBit(br, skipP) + end + if not key then + readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) + continue + end + mbRef[x1] = 0 + mbPart[x1] = -1 + local i4 = getBit(br, 145) == 0 + mbI4[x1] = i4 + local t0 = mbx * 4 + if not i4 then + local ymode + if getBit(br, 156) == 1 then + ymode = if getBit(br, 128) == 1 then 1 else 3 + else + ymode = if getBit(br, 163) == 1 then 2 else 0 + end + mbModes[mbx * 16 + 1] = ymode + mbMode[x1] = ymode + for k = 1, 4 do + intraT[t0 + k] = ymode + intraL[k] = ymode + end + else + mbMode[x1] = 4 + for y = 0, 3 do + local ymode = intraL[y + 1] + for x = 0, 3 do + local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9 + if getBit(br, BMODES_PROBA[pr + 1]) == 0 then + ymode = 0 + elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then + ymode = 1 + elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then + ymode = 2 + elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then + if getBit(br, BMODES_PROBA[pr + 5]) == 0 then + ymode = 3 + elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then + ymode = 4 + else + ymode = 5 + end + elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then + ymode = 6 + elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then + ymode = 7 + elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then + ymode = 8 + else + ymode = 9 + end + intraT[t0 + x + 1] = ymode + mbModes[mbx * 16 + y * 4 + x + 1] = ymode + end + intraL[y + 1] = ymode + end + end + if getBit(br, 142) == 0 then + mbUv[x1] = 0 + elseif getBit(br, 114) == 0 then + mbUv[x1] = 2 + else + mbUv[x1] = if getBit(br, 183) == 1 then 1 else 3 + end + end + if br.eof then + return fail("truncated: first partition (modes)") + end + + -- residuals (token partition) + local leftNz, leftNzDc = 0, 0 + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local q = quants[mbSeg[x1] + 1] + local skip = mbSkip[x1] + local i4 = mbI4[x1] + if skip == 0 then + local co = mbx * 768 + bfill(coeffs, co, 0, 768) + local first, acType + local dcNz = 0 + if not i4 then + bfill(dcb, 0, 0, 32) + local ctx = topNzDc[x1] + leftNzDc + local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) + dcNz = if nz > 0 then 1 else 0 + topNzDc[x1] = dcNz + leftNzDc = dcNz + if nz > 1 then + transformWHT(dcb, coeffs, co) + else + local dc0 = (readi16(dcb, 0) + 3) // 8 + for i = 0, 15 do + writei16(coeffs, co + i * 32, dc0) + end + end + first, acType = 1, 0 + else + first, acType = 0, 3 + end + local tnz = band(topNz[x1], 0x0f) + local lnz = band(leftNz, 0x0f) + local nzY = 0 + local dst = co + for _ = 0, 3 do + local l = band(lnz, 1) + local acc = 0 + for _ = 0, 3 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst) + l = if nz > first then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 128) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 4) + lnz = bor(rshift(lnz, 1), l * 128) + nzY = nzY * 256 + acc + end + local outT = tnz + local outL = rshift(lnz, 4) + local nzUv = 0 + for ch = 0, 2, 2 do + local acc = 0 + tnz = band(rshift(topNz[x1], 4 + ch), 255) + lnz = band(rshift(leftNz, 4 + ch), 255) + for _ = 0, 1 do + local l = band(lnz, 1) + for _ = 0, 1 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst) + l = if nz > 0 then 1 else 0 + tnz = bor(rshift(tnz, 1), l * 8) + acc = nzCode(acc, nz, if readi16(coeffs, dst) ~= 0 then 1 else 0) + dst += 32 + end + tnz = rshift(tnz, 2) + lnz = bor(rshift(lnz, 1), l * 32) + end + nzUv = bor(nzUv, lshift(acc, 4 * ch)) + outT = bor(outT, lshift(lshift(tnz, 4), ch)) + outL = bor(outL, lshift(band(lnz, 0xf0), ch)) + end + topNz[x1] = band(outT, 255) + leftNz = band(outL, 255) + mbNzY[x1] = nzY + mbNzUv[x1] = nzUv + -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter + skip = if nzY == 0 and nzUv == 0 and dcNz == 0 then 1 else 0 + else + topNz[x1] = 0 + leftNz = 0 + if not i4 then + topNzDc[x1] = 0 + leftNzDc = 0 + end + mbNzY[x1] = 0 + mbNzUv[x1] = 0 + end + if filterType > 0 then + local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] + local fi = mby * mbw + x1 + if lv > 0 then + local il = ilTab[lv] + fLimit[fi] = 2 * lv + il + fIlevel[fi] = il + fHev[fi] = hevTab[lv] + else + fLimit[fi] = 0 + end + fInner[fi] = if i4 or skip == 0 then 1 else 0 + end + if tbr.eof then + return fail("truncated: token partition") + end + end + + -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) + if not key then + Predict.row(refs :: any, mby, mbw, mbRef, mbPart, miMvR, miMvC, miSubR, miSubC, (mby + 1) * (mbw + 1) + 1, pred, YUV_SIZE, Y_OFF, U_OFF, V_OFF, bil, full) + end + for j = 0, 15 do + writeu8(yuv, Y_OFF + j * BPS - 1, 129) + end + for j = 0, 7 do + writeu8(yuv, U_OFF + j * BPS - 1, 129) + writeu8(yuv, V_OFF + j * BPS - 1, 129) + end + if mby > 0 then + writeu8(yuv, Y_OFF - 1 - BPS, 129) + writeu8(yuv, U_OFF - 1 - BPS, 129) + writeu8(yuv, V_OFF - 1 - BPS, 129) + else + bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1) + bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1) + bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1) + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local co = mbx * 768 + local bits = mbNzY[x1] + local rf = mbRef[x1] + if rf == 0 and mbx > 0 then + -- the left context of an intra macroblock: the previous macroblock's last columns + for j = -1, 15 do + writeu32(yuv, Y_OFF + j * BPS - 4, readu32(yuv, Y_OFF + j * BPS + 12)) + end + for j = -1, 7 do + writeu32(yuv, U_OFF + j * BPS - 4, readu32(yuv, U_OFF + j * BPS + 4)) + writeu32(yuv, V_OFF + j * BPS - 4, readu32(yuv, V_OFF + j * BPS + 4)) + end + end + if mby > 0 then + local t = mbx * 16 + writeu32(yuv, Y_OFF - BPS, readu32(topY, t)) + writeu32(yuv, Y_OFF - BPS + 4, readu32(topY, t + 4)) + writeu32(yuv, Y_OFF - BPS + 8, readu32(topY, t + 8)) + writeu32(yuv, Y_OFF - BPS + 12, readu32(topY, t + 12)) + t = mbx * 8 + writeu32(yuv, U_OFF - BPS, readu32(topU, t)) + writeu32(yuv, U_OFF - BPS + 4, readu32(topU, t + 4)) + writeu32(yuv, V_OFF - BPS, readu32(topV, t)) + writeu32(yuv, V_OFF - BPS + 4, readu32(topV, t + 4)) + end + if rf > 0 then + -- the prediction (Predict.row): luma rows 0..15, then the chroma rows (U and V side by side) + local o = mbx * YUV_SIZE + bcopy(yuv, Y_OFF, pred, o + Y_OFF, 15 * BPS + 16) + bcopy(yuv, U_OFF, pred, o + U_OFF, 7 * BPS + 24) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + else + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + writeu32(yuv, tr, readu8(topY, mbx * 16 + 15) * 0x01010101) + else + writeu32(yuv, tr, readu32(topY, mbx * 16 + 16)) + end + end + local trv = readu32(yuv, tr) + writeu32(yuv, tr + 4 * BPS, trv) + writeu32(yuv, tr + 8 * BPS, trv) + writeu32(yuv, tr + 12 * BPS, trv) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (n // 4) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) + end + local buv = mbNzUv[x1] + doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) + doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) + if mby < mbh - 1 then + local t = mbx * 16 + local r = Y_OFF + 15 * BPS + writeu32(topY, t, readu32(yuv, r)) + writeu32(topY, t + 4, readu32(yuv, r + 4)) + writeu32(topY, t + 8, readu32(yuv, r + 8)) + writeu32(topY, t + 12, readu32(yuv, r + 12)) + t = mbx * 8 + r = U_OFF + 7 * BPS + writeu32(topU, t, readu32(yuv, r)) + writeu32(topU, t + 4, readu32(yuv, r + 4)) + writeu32(topV, t, readu32(yuv, r + 16)) + writeu32(topV, t + 4, readu32(yuv, r + 20)) + end + local yo = yb + mby * 16 * ys + mbx * 16 + for j = 0, 15 do + local d, r = yo + j * ys, Y_OFF + j * BPS + writeu32(Y, d, readu32(yuv, r)) + writeu32(Y, d + 4, readu32(yuv, r + 4)) + writeu32(Y, d + 8, readu32(yuv, r + 8)) + writeu32(Y, d + 12, readu32(yuv, r + 12)) + end + local uo = uvb + mby * 8 * uvs + mbx * 8 + for j = 0, 7 do + local d, r = uo + j * uvs, U_OFF + j * BPS + writeu32(U, d, readu32(yuv, r)) + writeu32(U, d + 4, readu32(yuv, r + 4)) + writeu32(V, d, readu32(yuv, r + 16)) + writeu32(V, d + 4, readu32(yuv, r + 20)) + end + end + end + + -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter) + if filterType > 0 then + for mby = 0, mbh - 1 do + for mbx = 0, mbw - 1 do + local fi = mby * mbw + mbx + 1 + local limit = fLimit[fi] + if limit ~= 0 then + local inner = fInner[fi] == 1 + local yp = yb + mby * 16 * ys + mbx * 16 + if filterType == 1 then + if mbx > 0 then + simpleFilter(Y, yp, 1, ys, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k, 1, ys, limit) + end + end + if mby > 0 then + simpleFilter(Y, yp, ys, 1, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit) + end + end + else + local il, hev = fIlevel[fi], fHev[fi] + local up = uvb + mby * 8 * uvs + mbx * 8 + if mbx > 0 then + filterEdge(Y, yp, 1, ys, 16, limit + 4, il, hev) + filterEdge(U, up, 1, uvs, 8, limit + 4, il, hev) + filterEdge(V, up, 1, uvs, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k, 1, ys, 16, limit, il, hev) + end + filterInner(U, up + 4, 1, uvs, 8, limit, il, hev) + filterInner(V, up + 4, 1, uvs, 8, limit, il, hev) + end + if mby > 0 then + filterEdge(Y, yp, ys, 1, 16, limit + 4, il, hev) + filterEdge(U, up, uvs, 1, 8, limit + 4, il, hev) + filterEdge(V, up, uvs, 1, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev) + end + filterInner(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + filterInner(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + end + end + end + end + end + end + + -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) + if key then + st.last, st.golden, st.alt = cur, cur, cur + st.hasKey = true + else + local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt + if refreshGolden then + st.golden = cur + elseif copyToGolden == 1 then + st.golden = oldLast + elseif copyToGolden == 2 then + st.golden = oldAlt + end + if refreshAlt then + st.alt = cur + elseif copyToAlt == 1 then + st.alt = oldLast + elseif copyToAlt == 2 then + st.alt = oldGolden + end + if refreshLast then + st.last = cur + end + end + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return { width = width, height = height, ref = cur, header = hdr }, nil +end + +return Decode +end +__FILES["codecs/image/Vp8/Predict"] = @native function() + + + +-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the +-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the +-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels +-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the +-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a +-- block whose taps leave it is first copied with clamped coordinates. Never throws. +local Tables = __include("codecs/image/Vp8/Tables") + +local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local rshift, band = bit32.rshift, bit32.band +local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR + +local Predict = {} + +local BORDER = 32 +Predict.BORDER = BORDER + +-- the work buffer stride (codecs/image/Vp8/Decode: BPS) +local BPS = 32 + +local emu = bcreate(32 * 32) -- a block with its taps, edges replicated +local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter + +-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads +-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator). +@native local function sixH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for _ = 1, h do + for i = so - 2, so + w - 3 do + local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3 + + readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64 + writeu8(dst, d + i - so + 2, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +-- the six-tap filter along columns +@native local function sixV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + local s1, s2, s3 = ss, 2 * ss, 3 * ss + for _ = 1, h do + local p = so - s2 + for i = 0, w - 1 do + local q = p + i + local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3 + + readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64 + writeu8(dst, d + i, if v < 0 then 0 elseif v >= 32768 then 255 else rshift(v, 7)) + end + so += ss + d += ds + end +end + +-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 +@native local function bilH(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +@native local function bilV(src: buffer, so: number, ss: number, dst: buffer, d: number, ds: number, w: number, h: number, f: number) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7)) + end + so += ss + d += ds + end +end + +-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel +-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, +-- hmax: the last pixel column / row of the (macroblock aligned) plane. +@native local function block(src: buffer, stride: number, base: number, wmax: number, hmax: number, x: number, y: number, mvx: number, mvy: number, w: number, h: number, dst: buffer, d: number, bil: boolean) + local fx, fy = band(mvx, 7), band(mvy, 7) + local px, py = x + (mvx - fx) // 8, y + (mvy - fy) // 8 + local sb, so, ss = src, 0, stride + if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then + so = base + py * stride + px + else + for r = 0, h + 4 do + local sy = py - 2 + r + if sy < 0 then + sy = 0 + elseif sy > hmax then + sy = hmax + end + local row = base + sy * stride + local o = r * 32 + for c = 0, w + 4 do + local sx = px - 2 + c + if sx < 0 then + sx = 0 + elseif sx > wmax then + sx = wmax + end + writeu8(emu, o + c, readu8(src, row + sx)) + end + end + sb, so, ss = emu, 66, 32 + end + if fx == 0 then + if fy == 0 then + for _ = 1, h do + for i = 0, w - 4, 4 do + writeu32(dst, d + i, readu32(sb, so + i)) + end + so += ss + d += BPS + end + elseif bil then + bilV(sb, so, ss, dst, d, BPS, w, h, fy) + else + sixV(sb, so, ss, dst, d, BPS, w, h, fy) + end + elseif fy == 0 then + if bil then + bilH(sb, so, ss, dst, d, BPS, w, h, fx) + else + sixH(sb, so, ss, dst, d, BPS, w, h, fx) + end + elseif bil then + bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) + bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) + else + sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) + sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) + end +end + +@native local function chroma16(v: number): number + -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero + if v < 0 then + return -((1 - v) // 2) + end + return (v + 1) // 2 +end + +@native local function chroma4(s: number): number + -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero + if s < 0 then + return -((4 - s) // 8) + end + return (s + 4) // 8 +end + +type Planes = { + Y: buffer, + U: buffer, + V: buffer, + ys: number, -- luma stride + uvs: number, -- chroma stride + yb: number, -- offset of luma pixel (0, 0) + uvb: number, + mbw: number, + mbh: number, +} + +-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter +-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; +-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). +@native function Predict.mb(ref: Planes, mbx: number, mby: number, mvr: number, mvc: number, part: number, subR: { number }, subC: { number }, sb: number, dst: buffer, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb + local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 + local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 + local x, y = mbx * 16, mby * 16 + local cx, cy = mbx * 8, mby * 8 + if part < 0 then + block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) + local cr, cc = chroma16(mvr), chroma16(mvc) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) + block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) + return + end + if part < 3 then + for q = 0, 3 do + local bx, by = (q % 2) * 8, (q // 2) * 8 + local k = sb + by + bx // 4 + 1 + block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) + end + else + for b = 0, 15, 2 do + local k = sb + b + 1 + local bx, by = (b % 4) * 4, (b // 4) * 4 + local r0, c0 = subR[k], subC[k] + if r0 == subR[k + 1] and c0 == subC[k + 1] then + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) + else + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) + block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) + end + end + end + for i = 0, 1 do + local rr, rc = 0, 0 + for j = 0, 1 do + local k = sb + i * 8 + j * 2 + 1 + local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) + local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) + if full then + cr -= band(cr, 7) + cc -= band(cc, 7) + end + if j == 0 then + rr, rc = cr, cc + elseif cr == rr and cc == rc then + -- both 4x4 chroma blocks of the row share one vector: one 8x4 block + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) + else + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) + block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) + block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) + end + end + end +end + +-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the +-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo; +-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder). +@native function Predict.row(refs: { Planes }, mby: number, mbw: number, ref: { number }, part: { number }, miMvR: { number }, miMvC: { number }, miSubR: { number }, miSubC: { number }, mi0: number, pred: buffer, chunk: number, yo: number, uo: number, vo: number, bil: boolean, full: boolean) + for mbx = 0, mbw - 1 do + local rf = ref[mbx + 1] + if rf > 0 then + local mi = mi0 + mbx + 1 + local o = mbx * chunk + Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full) + end + end +end + +-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels +@native local function extend(P: buffer, stride: number, base: number, w: number, h: number) + for r = 0, h - 1 do + local o = base + r * stride + bfill(P, o - BORDER, readu8(P, o), BORDER) + bfill(P, o + w, readu8(P, o + w - 1), BORDER) + end + local top = base - BORDER + local bottom = base + (h - 1) * stride - BORDER + for r = 1, BORDER do + bcopy(P, top - r * stride, P, top, stride) + bcopy(P, bottom + r * stride, P, bottom, stride) + end +end + +@native function Predict.extend(ref: Planes) + extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) + extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) + extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) +end + +return Predict +end +__FILES["codecs/image/Vp8/Tables"] = function() + +-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 +-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables +-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from +-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; +-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. +local Tables = {} + +-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 +Tables.COEFF_PROBA0 = { + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128, + 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128, + 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128, + 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128, + 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128, + 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128, + 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128, + 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128, + 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128, + 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1, + 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128, + 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128, + 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128, + 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128, + 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128, + 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128, + 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128, + 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128, + 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128, + 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128, + 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128, + 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128, + 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128, + 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128, + 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128, + 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128, + 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128, + 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128, + 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128, + 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128, + 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128, + 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128, + 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128, + 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128, + 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128, + 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128, + 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128, + 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128, + 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128, + 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, +} +-- token probability update probabilities, same layout +Tables.COEFF_UPDATE_PROBA = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255, + 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255, + 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255, + 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} +-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1 +Tables.BMODES_PROBA = { + 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80, + 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10, + 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55, + 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29, + 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102, + 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166, + 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87, + 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197, + 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61, + 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171, + 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43, + 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78, + 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21, + 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43, + 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1, + 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51, + 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82, + 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175, + 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24, + 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6, + 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70, + 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10, + 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32, + 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205, + 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95, + 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102, + 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114, + 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102, + 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243, + 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19, + 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32, + 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8, + 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133, + 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22, + 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60, + 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171, + 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99, + 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128, + 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60, + 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81, + 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24, +} +-- DC dequantization factors, index q + 1 (q 0..127) +Tables.DC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, + 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, + 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +} +-- AC dequantization factors, index q + 1 +Tables.AC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, + 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, + 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, + 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +} +-- coefficient band of each position (with a sentinel for position 16) +Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 } +-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1] +Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +-- extra bits probabilities for the DCT_CAT3..6 tokens +Tables.CAT3 = { 173, 148, 140 } +Tables.CAT4 = { 176, 155, 140, 135 } +Tables.CAT5 = { 180, 157, 141, 134, 130 } +Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } + +-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones +Tables.YMODE_PROB = { 112, 86, 140, 37 } +Tables.UVMODE_PROB = { 162, 101, 204 } +Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } + +-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) +Tables.MV_DEFAULT = { + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, +} +Tables.MV_UPDATE = { + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, +} + +-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 +Tables.MODE_CONTEXTS = { + 7, 1, 1, 143, + 14, 18, 14, 107, + 135, 64, 57, 68, + 60, 56, 128, 65, + 159, 134, 128, 34, + 234, 188, 128, 28, +} + +-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] +Tables.SUB_MV_REF_PROB = { + 147, 136, 18, + 223, 1, 34, + 106, 145, 1, + 208, 1, 1, + 179, 121, 1, + 223, 1, 34, + 179, 121, 1, + 208, 1, 1, +} + +-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each +-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition +Tables.SPLIT_OFFSET = { + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_FILL = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_COUNT = { 8, 8, 4, 1 } + +-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) +Tables.SIXTAP = { + 0, 0, 128, 0, 0, 0, + 0, -6, 123, 12, -1, 0, + 2, -11, 108, 36, -8, 1, + 0, -9, 93, 50, -6, 0, + 3, -16, 77, 77, -16, 3, + 0, -6, 50, 93, -9, 0, + 1, -8, 36, 108, -11, 2, + 0, -1, 12, 123, -6, 0, +} +Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } + +return Tables +end +__FILES["codecs/image/Vp8/Yuv"] = @native function() + + + +-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the +-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 +-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +local rshift = bit32.rshift +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create + +local Yuv = {} + +@native local function clip(v: number): number + -- VP8Clip8: v in 14-bit fixed point + if v >= 0 and v < 16384 then + return rshift(v, 6) + end + return if v < 0 then 0 else 255 +end + +-- (v * coeff) >> 8 for non-negative v +@native local function mulHi(v: number, c: number): number + return rshift(v * c, 8) +end + +-- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) +@native local function rgba(y: number, u: number, v: number): number + local yy = mulHi(y, 19077) + local r = clip(yy + mulHi(v, 26149) - 14234) + local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) + local b = clip(yy + mulHi(u, 33050) - 17685) + return r + g * 256 + b * 65536 + 0xff000000 +end +Yuv.rgba = rgba + +-- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows +-- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +@native local function upsamplePair(Y: buffer, U: buffer, V: buffer, ty: number, by: number, tu: number, cu: number, out: buffer, dt: number, db: number, len: number) + local last = rshift(len - 1, 1) + local tlu, tlv = readu8(U, tu), readu8(V, tu) + local lu, lv = readu8(U, cu), readu8(V, cu) + do + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt, rgba(readu8(Y, ty), u0, v0)) + end + if by >= 0 then + local u0 = rshift(3 * lu + tlu + 2, 2) + local v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db, rgba(readu8(Y, by), u0, v0)) + end + for x = 1, last do + local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x) + local u1, v1 = readu8(U, cu + x), readu8(V, cu + x) + local avgU = tlu + tu1 + lu + u1 + 8 + local avgV = tlv + tv1 + lv + v1 + 8 + local d12u = rshift(avgU + 2 * (tu1 + lu), 3) + local d03u = rshift(avgU + 2 * (tlu + u1), 3) + local d12v = rshift(avgV + 2 * (tv1 + lv), 3) + local d03v = rshift(avgV + 2 * (tlv + v1), 3) + local px = 2 * x + writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1))) + writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1))) + if by >= 0 then + writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1))) + writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1))) + end + tlu, tlv, lu, lv = tu1, tv1, u1, v1 + end + if len % 2 == 0 then + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0)) + if by >= 0 then + u0 = rshift(3 * lu + tlu + 2, 2) + v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0)) + end + end +end + +-- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). +@native function Yuv.toRgba(Y: buffer, U: buffer, V: buffer, w: number, h: number, fancy: boolean, out: buffer?): buffer + local o = out or bcreate(w * h * 4) + local cw = (w + 1) // 2 + local stride = w * 4 + if fancy then + -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two + -- chroma rows, then the last row of an even height alone + upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w) + local y = 1 + local cu = 0 + while y + 1 < h do + upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w) + cu += cw + y += 2 + end + if h % 2 == 0 and h > 1 then + upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w) + end + else + for y = 0, h - 1 do + local cu = (y // 2) * cw + local yo = y * w + local oo = y * stride + for x = 0, w - 1 do + local c = cu + x // 2 + writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) + end + end + end + return o +end + +-- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes +@native function Yuv.setAlpha(o: buffer, a: buffer, n: number) + for i = 0, n - 1 do + writeu8(o, i * 4 + 3, readu8(a, i)) + end +end + +return Yuv +end +__FILES["codecs/image/Vp8L"] = function() + +-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): +-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. +-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new +-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel +-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, +-- one prefix code group per image or meta codes for big images). +-- +-- local Vp8L = require("@rosetta/codecs/image/Vp8L") +-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 +-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) +-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +local Err = __include("core/Err") +local Decode = __include("codecs/image/Vp8L/Decode") +local Encode = __include("codecs/image/Vp8L/Encode") + +local Vp8L = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +local function fail(msg: string?, offset: number?): Err.Err + local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end +Vp8L.fail = fail + +local function range(buf: buffer, off: number?, len: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header +function Vp8L.info(buf: buffer, off: number?, len: number?): ({ width: number, height: number, alpha: boolean }?, Err.Err?) + local o, l = range(buf, off, len) + local w, h, alpha, err = Decode.header(buf, o, l) + if not w then + return nil, fail(err, o) + end + return { width = w, height = h, alpha = alpha }, nil +end + +-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err +function Vp8L.decodeArgb(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local o, l = range(buf, off, len) + local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) + if not px then + return nil, fail(err, o) + end + return px, w, h, alpha +end + +-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err +function Vp8L.decode(buf: buffer, off: number?, len: number?, maxPixels: number?): (buffer?, any, number?, boolean?) + local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) + if not px then + return nil, w + end + return Decode.toRgba(px, w * (h :: number)), w, h, alpha +end + +-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err +function Vp8L.decodeAlpha(buf: buffer, off: number?, len: number?, width: number, height: number): (buffer?, Err.Err?) + local o, l = range(buf, off, len) + local px, err = Decode.stream(buf, o, l, width, height) + if not px then + return nil, fail(err, o) + end + return Decode.green(px, width * height), nil +end + +-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels +Vp8L.toRgba = Decode.toRgba + +type EncodeOptions = { + effort: number?, -- 0..9, default 5: more = smaller and slower (0: no transforms, no LZ77 search) + exact: boolean?, -- default false: keep the RGB of fully transparent pixels (otherwise they may be zeroed) + alphaHint: boolean?, -- the header's "alpha is used" bit; default: any alpha < 255 +} + +-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err +function Vp8L.encode(rgba: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then + return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") + end + if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: size must be 1..16384") + end + if buffer.len(rgba) < width * height * 4 then + return nil, Err.new(Err.ARG, "encode: pixel buffer too small") + end + local o: EncodeOptions = opts or {} :: EncodeOptions + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "encode: effort must be 0..9") + end + return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil +end + +-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) +function Vp8L.encodeAlpha(a8: buffer, width: number, height: number, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(a8) ~= "buffer" or buffer.len(a8) < width * height then + return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") + end + local rgba = buffer.create(width * height * 4) + for i = 0, width * height - 1 do + buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256) + end + local effort = opts and opts.effort or 5 + return Encode.encode(rgba, width, height, effort, true, false, true), nil +end + +return Vp8L +end +__FILES["codecs/image/Vp8L/Decode"] = @native function() + + + +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, +-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, +-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. +-- +-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every +-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Decode = {} + +local ROOT_BITS = 8 +local MAX_LEN = 15 +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_CACHE_BITS = 11 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image +Decode.CODE_TO_PLANE = CODE_TO_PLANE + +-- ------------------------------------------------------------------------------------------------ bit reader +-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are +-- left in the buffer than phantom bits were added (bitcnt < over * 8). +type State = { + buf: buffer, + pos: number, + limit: number, + bitbuf: number, + bitcnt: number, + over: number, + -- prefix code tables (u32 entries value * 32 + bits), shared by every group of every level + tab: buffer, + tabUsed: number, + maxPixels: number, +} + +@native local function fill(d: State) + local bitbuf, bitcnt = d.bitbuf, d.bitcnt + while bitcnt <= 24 do + local p = d.pos + local b = 0 + if p < d.limit then + b = readu8(d.buf, p) + d.pos = p + 1 + else + d.over += 1 + end + bitbuf += lshift(b, bitcnt) + bitcnt += 8 + end + d.bitbuf, d.bitcnt = bitbuf, bitcnt +end + +-- readBits(d, n) n <= 24 +@native local function readBits(d: State, n: number): number + if d.bitcnt < n then + fill(d) + end + local v = band(d.bitbuf, lshift(1, n) - 1) + d.bitbuf = rshift(d.bitbuf, n) + d.bitcnt -= n + return v +end + +@native local function eos(d: State): boolean + return d.bitcnt < d.over * 8 +end + +-- ------------------------------------------------------------------------------------------------ prefix codes +local count = table.create(MAX_LEN + 1, 0) +local offset = table.create(MAX_LEN + 2, 0) + +@native local function ensure(d: State, n: number) + local cap = blen(d.tab) // 4 + if d.tabUsed + n > cap then + local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) + bcopy(nb, 0, d.tab, 0, d.tabUsed * 4) + d.tab = nb + end +end + +@native local function replicate(tab: buffer, at: number, step: number, size: number, entry: number) + local e = size + repeat + e -= step + writeu32(tab, (at + e) * 4, entry) + until e <= 0 +end + +@native local function nextKey(key: number, len: number): number + local step = lshift(1, len - 1) + while band(key, step) ~= 0 do + step = rshift(step, 1) + end + return if step ~= 0 then band(key, step - 1) + step else key +end + +-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp +-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +local sorted = table.create(2400, 0) +@native local function build(d: State, lens: { number }, n: number): number + for l = 0, MAX_LEN do + count[l + 1] = 0 + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > MAX_LEN then + return -1 + end + count[l + 1] += 1 + end + if count[1] == n then + return -1 + end + offset[2] = 0 + for len = 1, MAX_LEN - 1 do + if count[len + 1] > lshift(1, len) then + return -1 + end + offset[len + 2] = offset[len + 1] + count[len + 1] + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > 0 then + sorted[offset[l + 1] + 1] = s + offset[l + 1] += 1 + end + end + local long = 0 + for len = ROOT_BITS + 1, MAX_LEN do + long += count[len + 1] + end + ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS)) + local tab = d.tab + local root = d.tabUsed + local totalSize = lshift(1, ROOT_BITS) + if offset[MAX_LEN + 1] == 1 then + replicate(tab, root, 1, totalSize, sorted[1] * 32) + d.tabUsed = root + totalSize + return root + end + local key = 0 + local numNodes, numOpen = 1, 1 + local tableBits = ROOT_BITS + local tableSize = lshift(1, tableBits) + local tableAt = root + local low = -1 + local mask = totalSize - 1 + local symbol = 1 + local step = 2 + for len = 1, ROOT_BITS do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + step = 2 + for len = ROOT_BITS + 1, MAX_LEN do + numOpen *= 2 + numNodes += numOpen + numOpen -= count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + if band(key, mask) ~= low then + tableAt += tableSize + -- NextTableBitSize + local l2 = len + local left = lshift(1, l2 - ROOT_BITS) + while l2 < MAX_LEN do + left -= count[l2 + 1] + if left <= 0 then + break + end + l2 += 1 + left *= 2 + end + tableBits = l2 - ROOT_BITS + tableSize = lshift(1, tableBits) + totalSize += tableSize + low = band(key, mask) + writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS) + end + replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS) + symbol += 1 + key = nextKey(key, len) + count[len + 1] -= 1 + end + step *= 2 + end + if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then + return -1 + end + d.tabUsed = root + totalSize + return root +end + +-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) +@native local function readSymbol(d: State, at: number): number + if d.bitcnt < MAX_LEN then + fill(d) + end + local tab = d.tab + local bitbuf = d.bitbuf + local idx = at + band(bitbuf, 255) + local e = readu32(tab, idx * 4) + local nb = band(e, 31) + if nb > ROOT_BITS then + bitbuf = rshift(bitbuf, ROOT_BITS) + d.bitcnt -= ROOT_BITS + e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4) + nb = band(e, 31) + end + d.bitbuf = rshift(bitbuf, nb) + d.bitcnt -= nb + return rshift(e, 5) +end + +local codeLengths = table.create(2400, 0) +local clLens = table.create(19, 0) + +-- readCode(d, alphabetSize) -> table offset, or -1 +@native local function readCode(d: State, size: number): number + for i = 1, size do + codeLengths[i] = 0 + end + if readBits(d, 1) == 1 then + local numSymbols = readBits(d, 1) + 1 + local first = readBits(d, 1) + local s = readBits(d, if first == 0 then 1 else 8) + if s < size then + codeLengths[s + 1] = 1 + end + if numSymbols == 2 then + s = readBits(d, 8) + if s < size then + codeLengths[s + 1] = 1 + end + end + else + for i = 1, 19 do + clLens[i] = 0 + end + local numCodes = readBits(d, 4) + 4 + for i = 1, numCodes do + clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3) + end + local mark = d.tabUsed + local clt = build(d, clLens, 19) + if clt < 0 then + return -1 + end + local maxSymbol = size + if readBits(d, 1) == 1 then + local nbits = 2 + 2 * readBits(d, 3) + maxSymbol = 2 + readBits(d, nbits) + if maxSymbol > size then + return -1 + end + end + local prev = 8 + local s = 0 + while s < size do + if maxSymbol == 0 then + break + end + maxSymbol -= 1 + local cl = readSymbol(d, clt) + if cl < 16 then + codeLengths[s + 1] = cl + s += 1 + if cl ~= 0 then + prev = cl + end + else + local rep, len + if cl == 16 then + rep, len = readBits(d, 2) + 3, prev + elseif cl == 17 then + rep, len = readBits(d, 3) + 3, 0 + else + rep, len = readBits(d, 7) + 11, 0 + end + if s + rep > size then + return -1 + end + for k = s + 1, s + rep do + codeLengths[k] = len + end + s += rep + end + end + d.tabUsed = mark -- the code length table is temporary + end + if eos(d) then + return -1 + end + return build(d, codeLengths, size) +end + +-- ------------------------------------------------------------------------------------------------ pixel data +@native local function subSample(size: number, bits: number): number + return rshift(size + lshift(1, bits) - 1, bits) +end +Decode.subSample = subSample + +@native local function cacheKey(argb: number, shift: number): number + -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles + local lo = argb % 65536 + local hi = (argb - lo) / 65536 + local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 + return rshift(m, shift) +end +Decode.cacheKey = cacheKey + +-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) +@native local function decodeData(d: State, data: buffer, w: number, h: number, cacheBits: number, groups: { number }, himg: buffer?, hbits: number, hxs: number): (boolean, string?) + local total = w * h + local cache: buffer? = if cacheBits > 0 then bcreate(lshift(1, cacheBits) * 4) else nil + local cshift = 32 - cacheBits + local lenLimit = NUM_LITERAL + NUM_LENGTH + local cacheLimit = lenLimit + (if cacheBits > 0 then lshift(1, cacheBits) else 0) + local hmask = if himg then lshift(1, hbits) - 1 else -1 + local i, col, row = 0, 0, 0 + local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] + @native local function setGroup() + if himg then + local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 + gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] + end + end + while i < total do + if band(col, hmask) == 0 then + setGroup() + end + local code = readSymbol(d, gG) + if code < NUM_LITERAL then + local r = readSymbol(d, gR) + local b = readSymbol(d, gB) + local a = readSymbol(d, gA) + if d.bitcnt < d.over * 8 then + break + end + local argb = a * 16777216 + r * 65536 + code * 256 + b + writeu32(data, i * 4, argb) + if cache then + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + elseif code < lenLimit then + local ls = code - NUM_LITERAL + local length + if ls < 4 then + length = ls + 1 + else + local eb = rshift(ls - 2, 1) + length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1 + end + local ds = readSymbol(d, gD) + local dc + if ds < 4 then + dc = ds + 1 + else + local eb = rshift(ds - 2, 1) + dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1 + end + local dist + if dc > 120 then + dist = dc - 120 + else + local v = CODE_TO_PLANE[dc] + dist = rshift(v, 4) * w + 8 - band(v, 15) + if dist < 1 then + dist = 1 + end + end + if d.bitcnt < d.over * 8 then + break + end + if i < dist or total - i < length then + return false, "bad backward reference" + end + if dist >= length then + bcopy(data, i * 4, data, (i - dist) * 4, length * 4) + else + for k = i, i + length - 1 do + writeu32(data, k * 4, readu32(data, (k - dist) * 4)) + end + end + if cache then + for k = i, i + length - 1 do + local argb = readu32(data, k * 4) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + end + i += length + col += length + while col >= w do + col -= w + row += 1 + end + if band(col, hmask) ~= 0 then + setGroup() + end + elseif code < cacheLimit and cache then + if d.bitcnt < d.over * 8 then + break + end + local argb = readu32(cache, (code - lenLimit) * 4) + writeu32(data, i * 4, argb) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + i += 1 + col += 1 + if col >= w then + col = 0 + row += 1 + end + else + return false, "bad symbol" + end + end + if eos(d) then + return false, "truncated: pixel data" + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +@native local function addPixels(a: number, b: number): number + return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) +end +Decode.addPixels = addPixels + +@native local function average2(a: number, b: number): number + return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end +Decode.average2 = average2 + +@native local function clip255(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +@native local function sub3(a: number, b: number, c: number): number + local pb, pa = b - c, a - c + return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) +end + +-- select(T, L, TL) +@native local function select3(a: number, b: number, c: number): number + local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) + + sub3(band(a, 255), band(b, 255), band(c, 255)) + return if s <= 0 then a else b +end + +@native local function clampedFull(c0: number, c1: number, c2: number): number + local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) + local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) + local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) + local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +@native local function half(a: number, b: number): number + local dd = a - b + -- C division truncates toward zero + local q = if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1) + return clip255(a + q) +end + +@native local function clampedHalf(c0: number, c1: number, c2: number): number + local ave = average2(c0, c1) + local a = half(rshift(ave, 24), rshift(c2, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255)) + local b = half(band(ave, 255), band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number + if mode == 0 then + return ARGB_BLACK + elseif mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + return select3(T, L, TL) + elseif mode == 12 then + return clampedFull(L, T, TL) + elseif mode == 13 then + return clampedHalf(L, T, TL) + end + return ARGB_BLACK +end +Decode.predict = predict + +@native local function inversePredictor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + -- first row: black, then L + writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + local up = row - w + writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4))) + local trow = rshift(y, bits) * tw + local x = 1 + while x < w do + local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + local L = readu32(data, (row + x - 1) * 4) + if mode == 1 then + for k = x, xe - 1 do + L = addPixels(readu32(data, (row + k) * 4), L) + writeu32(data, (row + k) * 4, L) + end + elseif mode == 2 then + for k = x, xe - 1 do + writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4))) + end + else + for k = x, xe - 1 do + local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4)) + L = addPixels(readu32(data, (row + k) * 4), p) + writeu32(data, (row + k) * 4, L) + end + end + x = xe + end + end +end + +@native local function sint8(v: number): number + return if v >= 128 then v - 256 else v +end + +@native local function inverseCrossColor(data: buffer, w: number, h: number, bits: number, sub: buffer) + local tw = subSample(w, bits) + for y = 0, h - 1 do + local trow = rshift(y, bits) * tw + local x = 0 + while x < w do + local m = readu32(sub, (trow + rshift(x, bits)) * 4) + local g2r = sint8(band(m, 255)) + local g2b = sint8(band(rshift(m, 8), 255)) + local r2b = sint8(band(rshift(m, 16), 255)) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + for k = y * w + x, y * w + xe - 1 do + local argb = readu32(data, k * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(band(rshift(argb, 16), 255) + ((g2r * g) // 32), 255) + local b = band(band(argb, 255) + ((g2b * g) // 32) + ((r2b * sint8(r)) // 32), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) + end + x = xe + end + end +end + +@native local function inverseSubtractGreen(data: buffer, n: number) + for k = 0, n - 1 do + local argb = readu32(data, k * 4) + local g = band(rshift(argb, 8), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff)) + end +end + +-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h +@native local function inverseColorIndexing(src: buffer, sw: number, w: number, h: number, bits: number, map: buffer): buffer + local out = bcreate(w * h * 4) + if bits == 0 then + for k = 0, w * h - 1 do + writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4)) + end + return out + end + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + local vmask = lshift(1, bpp) - 1 + for y = 0, h - 1 do + local packed = 0 + local s = y * sw + local o = y * w + for x = 0, w - 1 do + if band(x, cmask) == 0 then + packed = band(rshift(readu32(src, s * 4), 8), 255) + s += 1 + end + writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) + packed = rshift(packed, bpp) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ image stream +type Transform = { kind: number, xsize: number, bits: number, data: buffer? } + +local decodeStream: (d: State, xs: number, ys: number, level0: boolean) -> (buffer?, string?) + +-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width +@native local function readCodes(d: State, xs: number, ys: number, cacheBits: number, level0: boolean): ({ number }?, buffer?, number, number, string?) + local himg: buffer? = nil + local hbits, hxs = 0, 0 + local numGroups = 1 + local mapping: { number }? = nil + local numMax = 1 + if level0 and readBits(d, 1) == 1 then + hbits = readBits(d, 3) + 2 + hxs = subSample(xs, hbits) + local hys = subSample(ys, hbits) + local img, err = decodeStream(d, hxs, hys, false) + if not img then + return nil, nil, 0, 0, err + end + local n = hxs * hys + for k = 0, n - 1 do + local g = band(rshift(readu32(img, k * 4), 8), 0xffff) + writeu32(img, k * 4, g) + if g >= numMax then + numMax = g + 1 + end + end + if numMax > 1000 or numMax > xs * ys then + -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept + local map = table.create(numMax, -1) :: { number } + numGroups = 0 + for k = 0, n - 1 do + local g = readu32(img, k * 4) + if map[g + 1] == -1 then + map[g + 1] = numGroups + numGroups += 1 + end + writeu32(img, k * 4, map[g + 1]) + end + mapping = map + else + numGroups = numMax + end + himg = img + end + if eos(d) then + return nil, nil, 0, 0, "truncated: meta codes" + end + local groups = table.create(numGroups * 5, 0) :: { number } + local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 + for i = 0, numMax - 1 do + local slot = if mapping then mapping[i + 1] else i + local mark = d.tabUsed + for j = 0, 4 do + local size = if j == 0 then NUM_LITERAL + NUM_LENGTH + cacheSize elseif j == 4 then NUM_DISTANCE else NUM_LITERAL + local at = readCode(d, size) + if at < 0 then + return nil, nil, 0, 0, if eos(d) then "truncated: prefix code" else "bad prefix code" + end + if slot >= 0 then + groups[slot * 5 + j + 1] = at + end + end + if slot < 0 then + d.tabUsed = mark + end + end + return groups, himg, hbits, hxs, nil +end + +decodeStream = @native function(d: State, xs: number, ys: number, level0: boolean): (buffer?, string?) + local transforms: { Transform } = {} + local seen = 0 + local txs = xs + if level0 then + while readBits(d, 1) == 1 do + local kind = readBits(d, 2) + if band(seen, lshift(1, kind)) ~= 0 then + return nil, "repeated transform" + end + seen = bor(seen, lshift(1, kind)) + local t: Transform = { kind = kind, xsize = txs, bits = 0, data = nil } + if kind == 0 or kind == 1 then + t.bits = readBits(d, 3) + 2 + local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false) + if not sub then + return nil, err + end + t.data = sub + elseif kind == 3 then + local num = readBits(d, 8) + 1 + local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 + t.bits = bits + local pal, err = decodeStream(d, num, 1, false) + if not pal then + return nil, err + end + local final = lshift(1, rshift(8, bits)) + local map = bcreate(final * 4) + local prev = 0 + for k = 0, num - 1 do + prev = addPixels(readu32(pal, k * 4), prev) + writeu32(map, k * 4, prev) + end + t.data = map + txs = subSample(txs, bits) + end + table.insert(transforms, t) + if eos(d) then + return nil, "truncated: transforms" + end + end + end + local cacheBits = 0 + if readBits(d, 1) == 1 then + cacheBits = readBits(d, 4) + if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then + return nil, "bad colour cache size" + end + end + local mark = d.tabUsed + local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0) + if not groups then + return nil, err + end + local data = bcreate(txs * ys * 4) + local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs) + if not ok then + return nil, derr + end + d.tabUsed = mark + -- inverse transforms, last read first + for k = #transforms, 1, -1 do + local t = transforms[k] + if t.kind == 0 then + inversePredictor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 1 then + inverseCrossColor(data, t.xsize, ys, t.bits, t.data :: buffer) + elseif t.kind == 2 then + inverseSubtractGreen(data, t.xsize * ys) + else + data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data :: buffer) + end + end + return data, nil +end + +@native local function newState(buf: buffer, off: number, len: number, maxPixels: number): State + return { + buf = buf, + pos = off, + limit = off + len, + bitbuf = 0, + bitcnt = 0, + over = 0, + tab = bcreate(4096 * 4), + tabUsed = 0, + maxPixels = maxPixels, + } +end + +-- header(buf, off, len) -> width, height, alphaHint | nil, message +@native function Decode.header(buf: buffer, off: number, len: number): (number?, number, boolean, string?) + if len < 5 then + return nil, 0, false, "truncated: header" + end + if readu8(buf, off) ~= 0x2f then + return nil, 0, false, "bad VP8L signature" + end + local v = readu32(buf, off + 1) + local w = band(v, 0x3fff) + 1 + local h = band(rshift(v, 14), 0x3fff) + 1 + local alpha = band(rshift(v, 28), 1) == 1 + if rshift(v, 29) ~= 0 then + return nil, 0, false, "bad VP8L version" + end + return w, h, alpha, nil +end + +-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message +@native function Decode.argb(buf: buffer, off: number, len: number, maxPixels: number): (buffer?, number, number, boolean, string?) + local w, h, alpha, err = Decode.header(buf, off, len) + if not w then + return nil, 0, 0, false, err + end + if w * h > maxPixels then + return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels" + end + local d = newState(buf, off + 5, len - 5, maxPixels) + local data, derr = decodeStream(d, w, h, true) + if not data then + return nil, w, h, alpha, derr + end + return data, w, h, alpha, nil +end + +-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) +@native function Decode.stream(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, string?) + local d = newState(buf, off, len, w * h) + return decodeStream(d, w, h, true) +end + +-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes +@native function Decode.toRgba(argb: buffer, n: number, out: buffer?, outOff: number?): buffer + local o = out or bcreate(n * 4) + local base = outOff or 0 + for k = 0, n - 1 do + local v = readu32(argb, k * 4) + -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A + writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return o +end + +-- green(argb, n) -> the green channel as bytes (alpha planes) +@native function Decode.green(argb: buffer, n: number): buffer + local o = bcreate(n) + for k = 0, n - 1 do + writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) + end + return o +end + +return Decode +end +__FILES["codecs/image/Vp8L/Encode"] = @native function() + + + +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). +-- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode +-- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash +-- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy +-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. +-- Never throws (the init module validates the arguments). +local Huffman = __include("codecs/entropy/Huffman") + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local log = math.log + +local Encode = {} + +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_LENGTH = 4096 +local WINDOW = 1048576 - 120 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset +local PLANE_TO_CODE = table.create(128, 0) +for i, v in CODE_TO_PLANE do + PLANE_TO_CODE[v + 1] = i +end + +-- ------------------------------------------------------------------------------------------------ bit writer +type W = { buf: buffer, pos: number, acc: number, cnt: number } + +@native local function newWriter(cap: number): W + return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } +end + +-- put(w, v, n): the n <= 24 low bits of v, LSB first +@native local function put(w: W, v: number, n: number) + local acc = w.acc + v * 2 ^ w.cnt + local cnt = w.cnt + n + if cnt >= 8 then + local pos = w.pos + local buf = w.buf + if pos + 8 > blen(buf) then + local nb = bcreate(blen(buf) * 2) + bcopy(nb, 0, buf, 0, pos) + buf = nb + w.buf = nb + end + repeat + local byte = acc % 256 + writeu8(buf, pos, byte) + pos += 1 + acc = (acc - byte) / 256 + cnt -= 8 + until cnt < 8 + w.pos = pos + end + w.acc, w.cnt = acc, cnt +end + +@native local function finish(w: W): buffer + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = bcreate(w.pos) + bcopy(out, 0, w.buf, 0, w.pos) + return out +end + +-- ------------------------------------------------------------------------------------------------ helpers +@native local function subSample(size: number, bits: number): number + return rshift(size + lshift(1, bits) - 1, bits) +end + +-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift +@native local function mulHash(v: number): number + local lo = v % 65536 + local hi = (v - lo) / 65536 + return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 +end + +-- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1 +@native local function prefix(v: number): (number, number, number) + local d = v - 1 + if d < 4 then + return d, 0, 0 + end + local hb = 0 + local t = d + while t >= 2 do + t = rshift(t, 1) + hb += 1 + end + local second = band(rshift(d, hb - 1), 1) + local eb = hb - 1 + return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) +end + +-- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120) +@native local function distCode(xs: number, dist: number): number + local yo = dist // xs + local xo = dist - yo * xs + if xo <= 8 and yo < 8 then + return PLANE_TO_CODE[yo * 16 + 8 - xo + 1] + elseif xo > xs - 8 and yo < 7 then + return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1] + end + return dist + 120 +end + +@native local function subPixels(a: number, b: number): number + return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) +end + +@native local function average2(a: number, b: number): number + return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end + +@native local function clip255(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +@native local function sub3(a: number, b: number, c: number): number + local pb, pa = b - c, a - c + return (if pb < 0 then -pb else pb) - (if pa < 0 then -pa else pa) +end + +@native local function half(x: number, y: number): number + local dd = x - y + return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) +end + +-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) +@native local function predict(mode: number, L: number, T: number, TR: number, TL: number): number + if mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24)) + + sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255)) + + sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255)) + + sub3(band(T, 255), band(L, 255), band(TL, 255)) + return if s <= 0 then T else L + elseif mode == 12 then + local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24)) + local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255)) + local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255)) + local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + elseif mode == 13 then + local ave = average2(L, T) + local a = half(rshift(ave, 24), rshift(TL, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255)) + local b = half(band(ave, 255), band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + end + return ARGB_BLACK +end + +-- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap) +local COST = table.create(256, 0) +for v = 0, 255 do + local m = math.min(v, 256 - v) + COST[v + 1] = log(1 + m) / log(2) +end + +@native local function residualCost(r: number): number + return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] +end + +-- ------------------------------------------------------------------------------------------------ transforms +local MODES_FAST = { 1, 2, 11 } +local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } +local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } + +-- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals +@native local function predictorTransform(px: buffer, w: number, h: number, bits: number, effort: number): buffer + local tw, th = subSample(w, bits), subSample(h, bits) + local modesImg = bcreate(tw * th * 4) + local modes = if effort <= 2 then MODES_FAST elseif effort <= 6 then MODES_MID else MODES_ALL + local ts = lshift(1, bits) + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local best, bestCost = 1, math.huge + for _, m in modes do + local cost = 0 + for y = math.max(y0, 1), y1 - 1 do + local row = y * w + for x = math.max(x0, 1), x1 - 1 do + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + cost += residualCost(subPixels(readu32(px, i * 4), p)) + end + if cost >= bestCost then + break + end + end + if cost < bestCost then + best, bestCost = m, cost + end + end + writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256) + end + end + -- residuals with the chosen modes (and the decoder's fixed first row and column) + local res = bcreate(w * h * 4) + writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4))) + local trow = rshift(y, bits) * tw + for x = 1, w - 1 do + local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15) + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + writeu32(res, i * 4, subPixels(readu32(px, i * 4), p)) + end + end + bcopy(px, 0, res, 0, w * h * 4) + return modesImg +end + +@native local function sint8(v: number): number + return if v >= 128 then v - 256 else v +end + +@native local function clampM(v: number): number + local m = math.floor(v + 0.5) + return if m < -128 then -128 elseif m > 127 then 127 else m +end + +-- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the +-- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost +@native local function crossColorTransform(px: buffer, w: number, h: number, bits: number): buffer + local tw, th = subSample(w, bits), subSample(h, bits) + local img = bcreate(tw * th * 4) + local ts = lshift(1, bits) + @native local function tileCost(x0: number, y0: number, x1: number, y1: number, g2r: number, g2b: number, r2b: number): number + local c = 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - ((g2r * g) // 32), 255) + local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) + c += COST[nr + 1] + COST[nb + 1] + end + end + return c + end + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = sint8(band(rshift(argb, 16), 255)) + local b = sint8(band(argb, 255)) + sgg += g * g + sgr += g * r + sgb += g * b + srr += r * r + srb += r * b + end + end + local g2r, g2b, r2b = 0, 0, 0 + if sgg > 0 then + g2r = clampM(32 * sgr / sgg) + local det = sgg * srr - sgr * sgr + if det > 0 then + g2b = clampM(32 * (sgb * srr - srb * sgr) / det) + r2b = clampM(32 * (srb * sgg - sgb * sgr) / det) + else + g2b = clampM(32 * sgb / sgg) + end + end + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then + g2r, g2b, r2b = 0, 0, 0 + end + end + writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255)) + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local k = (y * w + x) * 4 + local argb = readu32(px, k) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - ((g2r * g) // 32), 255) + local nb = band(b - ((g2b * g) // 32) - ((r2b * sint8(r)) // 32), 255) + writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb) + end + end + end + end + end + return img +end + +-- ------------------------------------------------------------------------------------------------ LZ77 +-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] +local HASH_BITS = 16 + +@native local function hash2(a: number, b: number): number + return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) +end + +@native local function matchLen(px: buffer, i: number, j: number, max: number): number + local n = 0 + while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do + n += 1 + end + return n +end + +@native local function lz77(px: buffer, xs: number, n: number, effort: number): ({ number }, { number }) + local L: { number } = {} + local D: { number } = {} + if effort == 0 then + for i = 0, n - 1 do + L[i + 1] = readu32(px, i * 4) + D[i + 1] = 0 + end + return L, D + end + local head = table.create(lshift(1, HASH_BITS), -1) + local prev = table.create(n, -1) + local maxIter = if effort <= 2 then 4 elseif effort <= 5 then 16 elseif effort <= 7 then 48 else 128 + @native local function insert(i: number) + if i + 1 < n then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + prev[i + 1] = head[h] + head[h] = i + end + end + -- best(i) -> length, distance (0, 0 when no useful match) + @native local function best(i: number): (number, number) + local max = math.min(MAX_LENGTH, n - i) + if max < 2 then + return 0, 0 + end + local bl, bd, bc = 0, 0, math.huge + @native local function try(j: number) + local d = i - j + if d < 1 or d > WINDOW then + return + end + local l = matchLen(px, i, j, max) + if l >= 2 then + local c = distCode(xs, d) + if l > bl or (l == bl and c < bc) then + bl, bd, bc = l, d, c + end + end + end + if i >= 1 then + try(i - 1) + end + if i >= xs then + try(i - xs) + end + if bl < max then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + local j = head[h] + local it = 0 + while j >= 0 and it < maxIter and i - j <= WINDOW do + if j ~= i - 1 and j ~= i - xs then + try(j) + if bl >= max then + break + end + end + j = prev[j + 1] + it += 1 + end + end + -- a 2-pixel copy only pays with a short 2-D distance code + if bl == 2 and bc > 120 then + return 0, 0 + end + return bl, bd + end + local i = 0 + local k = 0 + local lazy = effort >= 4 + local nl, nd = 0, 0 + local haveNext = false + while i < n do + local l, d + if haveNext then + l, d = nl, nd + haveNext = false + else + l, d = best(i) + end + if l >= 2 and lazy and l < 64 and i + 1 < n then + insert(i) + nl, nd = best(i + 1) + if nl > l + 1 then + -- a literal now, the longer match next + k += 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i += 1 + haveNext = true + else + k += 1 + L[k] = -l + D[k] = distCode(xs, d) + for t = i + 1, i + l - 1 do + insert(t) + end + i += l + end + elseif l >= 2 then + k += 1 + L[k] = -l + D[k] = distCode(xs, d) + local stop = i + l + if effort <= 2 and l > 16 then + insert(i) + insert(stop - 1) + else + for t = i, stop - 1 do + insert(t) + end + end + i = stop + else + insert(i) + k += 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i += 1 + end + end + return L, D +end + +-- ------------------------------------------------------------------------------------------------ prefix codes +@native local function entropy(h: { number }): number + local total = 0 + for _, c in h do + total += c + end + if total == 0 then + return 0 + end + local bits = 0 + local lt = log(total) + for _, c in h do + if c > 0 then + bits += c * (lt - log(c)) + end + end + return bits / log(2) +end + +-- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost +@native local function chooseCache(px: buffer, L: { number }, effort: number): number + if effort < 2 then + return 0 + end + local cands = if effort < 5 then { 0, 4, 7, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } + local caches: { { number } } = {} + local hg: { { number } } = {} + local hr: { { number } } = {} + local hb: { { number } } = {} + local ha: { { number } } = {} + for c, bits in cands do + caches[c] = table.create(lshift(1, bits), -1) + hg[c] = table.create(256 + lshift(1, bits), 0) + hr[c] = table.create(256, 0) + hb[c] = table.create(256, 0) + ha[c] = table.create(256, 0) + end + local pos = 0 + for _, t in L do + if t >= 0 then + local hsh = mulHash(t) + for c, bits in cands do + local cache = caches[c] + local key = if bits > 0 then rshift(hsh, 32 - bits) else 0 + if bits > 0 and cache[key + 1] == t then + hg[c][257 + key] += 1 + else + hg[c][band(rshift(t, 8), 255) + 1] += 1 + hr[c][band(rshift(t, 16), 255) + 1] += 1 + hb[c][band(t, 255) + 1] += 1 + ha[c][rshift(t, 24) + 1] += 1 + end + if bits > 0 then + cache[key + 1] = t + end + end + pos += 1 + else + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + local hsh = mulHash(v) + for c, bits in cands do + if bits > 0 then + caches[c][rshift(hsh, 32 - bits) + 1] = v + end + end + end + pos -= t + end + end + local bestBits, bestCost = 0, math.huge + for c, bits in cands do + -- + a rough price for the longer green code lengths + local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5 + if cost < bestCost then + bestBits, bestCost = bits, cost + end + end + return bestBits +end + +type Code = { lens: { number }, codes: { number }, single: boolean } + +-- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each) +@native local function buildCode(freqs: { number }, maxLen: number): Code + local lens = Huffman.lengths(freqs, maxLen) + local used = 0 + for _, l in lens do + if l > 0 then + used += 1 + end + end + local codes = Huffman.codes(lens) + for i, l in lens do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return { lens = lens, codes = codes, single = used <= 1 } +end + +@native local function emit(w: W, c: Code, sym: number) + if not c.single then + put(w, c.codes[sym + 1], c.lens[sym + 1]) + end +end + +@native local function zeroRun(tok: { number }, ext: { number }, run: number) + local r = run + while r > 0 do + if r >= 11 then + local k = math.min(r, 138) + table.insert(tok, 18) + table.insert(ext, k - 11) + r -= k + elseif r >= 3 then + table.insert(tok, 17) + table.insert(ext, r - 3) + r = 0 + else + table.insert(tok, 0) + table.insert(ext, 0) + r -= 1 + end + end +end + +-- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded) +@native local function writeCode(w: W, c: Code, size: number) + local syms: { number } = {} + for s = 0, size - 1 do + if (c.lens[s + 1] or 0) > 0 then + table.insert(syms, s) + if #syms > 2 then + break + end + end + end + if #syms == 0 then + -- an unused alphabet: the simple code of symbol 0 + put(w, 1, 1) + put(w, 0, 1) + put(w, 0, 1) + put(w, 0, 1) + return + end + if #syms <= 2 and syms[#syms] < 256 then + put(w, 1, 1) + put(w, #syms - 1, 1) + if syms[1] <= 1 then + put(w, 0, 1) + put(w, syms[1], 1) + else + put(w, 1, 1) + put(w, syms[1], 8) + end + if #syms == 2 then + put(w, syms[2], 8) + end + return + end + -- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the + -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) + local tok: { number } = {} + local ext: { number } = {} + local keep = 0 -- tokens up to the last non-zero length + local prev = 8 + local s = 1 + while s <= size do + local l = c.lens[s] or 0 + local run = 1 + while s + run <= size and (c.lens[s + run] or 0) == l do + run += 1 + end + if l == 0 then + zeroRun(tok, ext, run) + else + local r = run + if l ~= prev then + table.insert(tok, l) + table.insert(ext, 0) + r -= 1 + prev = l + end + while r > 0 do + if r >= 3 then + local k = math.min(r, 6) + table.insert(tok, 16) + table.insert(ext, k - 3) + r -= k + else + table.insert(tok, l) + table.insert(ext, 0) + r -= 1 + end + end + keep = #tok + end + s += run + end + local ntok = #tok + local trim = keep < ntok and keep >= 2 + if trim then + ntok = keep + end + local hist = table.create(19, 0) + for i = 1, ntok do + hist[tok[i] + 1] += 1 + end + local cl = buildCode(hist, 7) + local nc = 19 + while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do + nc -= 1 + end + put(w, 0, 1) + put(w, nc - 4, 4) + for i = 1, nc do + put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3) + end + if trim then + put(w, 1, 1) + local v = ntok - 2 + local nbits = 0 + while lshift(1, nbits) <= v do + nbits += 1 + end + local pairs = math.max(1, (nbits + 1) // 2) + put(w, pairs - 1, 3) + put(w, v, pairs * 2) + else + put(w, 0, 1) + end + for i = 1, ntok do + local t = tok[i] + emit(w, cl, t) + if t == 16 then + put(w, ext[i], 2) + elseif t == 17 then + put(w, ext[i], 3) + elseif t == 18 then + put(w, ext[i], 7) + end + end +end + +-- ------------------------------------------------------------------------------------------------ image data +-- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels +@native local function writeImage(w: W, px: buffer, xs: number, n: number, effort: number, level0: boolean) + local L, D = lz77(px, xs, n, effort) + local cacheBits = if level0 then chooseCache(px, L, effort) else 0 + if cacheBits > 0 then + put(w, 1, 1) + put(w, cacheBits, 4) + else + put(w, 0, 1) + end + if level0 then + put(w, 0, 1) -- no meta prefix codes + end + local cacheSize = if cacheBits > 0 then lshift(1, cacheBits) else 0 + local cshift = 32 - cacheBits + local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0) + local hr = table.create(256, 0) + local hb = table.create(256, 0) + local ha = table.create(256, 0) + local hd = table.create(NUM_DISTANCE, 0) + -- token kinds after the cache: 0 literal, 1 cache hit, 2 copy + local cache: { number }? = if cacheBits > 0 then table.create(cacheSize, -1) else nil + local K = table.create(#L, 0) + local pos = 0 + for i, t in L do + if t >= 0 then + local hit = false + if cache then + local key = rshift(mulHash(t), cshift) + if cache[key + 1] == t then + hit = true + hg[NUM_LITERAL + NUM_LENGTH + key + 1] += 1 + end + cache[key + 1] = t + end + if hit then + K[i] = 1 + else + hg[band(rshift(t, 8), 255) + 1] += 1 + hr[band(rshift(t, 16), 255) + 1] += 1 + hb[band(t, 255) + 1] += 1 + ha[rshift(t, 24) + 1] += 1 + end + pos += 1 + else + K[i] = 2 + hg[NUM_LITERAL + prefix(-t) + 1] += 1 + hd[prefix(D[i]) + 1] += 1 + if cache then + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + cache[rshift(mulHash(v), cshift) + 1] = v + end + end + pos -= t + end + end + local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15) + writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize) + writeCode(w, cr, 256) + writeCode(w, cb, 256) + writeCode(w, ca, 256) + writeCode(w, cd, NUM_DISTANCE) + for i, t in L do + local k = K[i] + if k == 0 then + emit(w, cg, band(rshift(t, 8), 255)) + emit(w, cr, band(rshift(t, 16), 255)) + emit(w, cb, band(t, 255)) + emit(w, ca, rshift(t, 24)) + elseif k == 1 then + emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift)) + else + local lc, leb, lev = prefix(-t) + emit(w, cg, NUM_LITERAL + lc) + if leb > 0 then + put(w, lev, leb) + end + local dc, deb, dev = prefix(D[i]) + emit(w, cd, dc) + if deb > 0 then + put(w, dev, deb) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ encode +-- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0. +@native local function toArgb(rgba: buffer, n: number, exact: boolean): (buffer, boolean) + local px = bcreate(n * 4) + local alpha = false + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + local a = rshift(v, 24) + if a ~= 255 then + alpha = true + end + if a == 0 and not exact then + v = 0 + end + -- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB + writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return px, alpha +end + +-- palette(px, n) -> the sorted colours when there are at most 256, else nil +@native local function palette(px: buffer, n: number): { number }? + local seen: { [number]: boolean } = {} + local list: { number } = {} + for i = 0, n - 1 do + local v = readu32(px, i * 4) + if not seen[v] then + if #list == 256 then + return nil + end + seen[v] = true + table.insert(list, v) + end + end + table.sort(list) + return list +end + +type Config = { palette: { number }?, pbits: number, cc: boolean, ccbits: number } + +-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) +@native local function stream(px: buffer, w: number, h: number, effort: number, cfg: Config, bw: W) + local n = w * h + local xs = w + local sub = math.min(effort, 3) + local pal = cfg.palette + if pal then + local num = #pal + local bits = if num > 16 then 0 elseif num > 4 then 1 elseif num > 2 then 2 else 3 + put(bw, 1, 1) + put(bw, 3, 2) + put(bw, num - 1, 8) + local pimg = bcreate(num * 4) + local prevc = 0 + local index: { [number]: number } = {} + for i, c in pal do + writeu32(pimg, (i - 1) * 4, subPixels(c, prevc)) + prevc = c + index[c] = i - 1 + end + writeImage(bw, pimg, num, num, sub, false) + xs = subSample(w, bits) + local packed = bcreate(xs * h * 4) + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + for y = 0, h - 1 do + local acc = 0 + local o = y * xs + for x = 0, w - 1 do + local sh = band(x, cmask) + acc += index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh) + if sh == cmask or x == w - 1 then + writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256) + acc = 0 + end + end + end + px = packed + elseif cfg.pbits > 0 then + -- subtract green + put(bw, 1, 1) + put(bw, 2, 2) + for i = 0, n - 1 do + local v = readu32(px, i * 4) + local g = band(rshift(v, 8), 255) + writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff)) + end + -- predictor + local pbits = cfg.pbits + local modes = predictorTransform(px, w, h, pbits, effort) + put(bw, 1, 1) + put(bw, 0, 2) + put(bw, pbits - 2, 3) + writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false) + -- cross colour + if cfg.cc then + local cbits = cfg.ccbits + local cimg = crossColorTransform(px, w, h, cbits) + put(bw, 1, 1) + put(bw, 1, 2) + put(bw, cbits - 2, 3) + writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false) + end + end + put(bw, 0, 1) -- no more transforms + writeImage(bw, px, xs, xs * h, effort, true) +end + +-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, +-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. +@native function Encode.encode(rgba: buffer, w: number, h: number, effort: number, exact: boolean, alphaHint: boolean?, headerless: boolean): buffer + local n = w * h + local px, usesAlpha = toArgb(rgba, n, exact) + local pal = if effort > 0 then palette(px, n) else nil + local configs: { Config } = {} + if effort == 0 then + table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) + else + local pbits = if effort >= 5 then 4 else 5 + local plain: Config = { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = if effort >= 6 then 4 else 5 } + if pal then + table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) + if effort >= 6 then + table.insert(configs, plain) + end + else + table.insert(configs, plain) + end + if effort >= 9 then + table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 }) + table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 }) + end + end + local best: buffer? = nil + for k, cfg in configs do + local bw = newWriter(n + 256) + if not headerless then + put(bw, 0x2f, 8) + put(bw, w - 1, 14) + put(bw, h - 1, 14) + local hint = if alphaHint == nil then usesAlpha else alphaHint + put(bw, if hint then 1 else 0, 1) + put(bw, 0, 3) + end + local work = px + if k < #configs then + work = bcreate(n * 4) + bcopy(work, 0, px, 0, n * 4) + end + stream(work, w, h, effort, cfg, bw) + local out = finish(bw) + if not best or blen(out) < blen(best) then + best = out + end + end + return best :: buffer +end + +return Encode +end +__FILES["codecs/image/Yuv"] = @native function() + + + +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. +-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the +-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma +-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). +-- +-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) +-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) +-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image +-- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per +-- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) +local Types = __include("Types") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create +local floor = math.floor + +local Yuv = {} + +-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u +-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 +local MATRIX: { [string]: { kr: number, kb: number } } = { + bt601 = { kr = 0.299, kb = 0.114 }, + bt709 = { kr = 0.2126, kb = 0.0722 }, +} + +type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number } + +local cache: { [string]: Coeffs } = {} +@native local function coeffs(range: string?, matrix: string?): Coeffs + local key = (range or "limited") .. (matrix or "bt601") + local c = cache[key] + if c then + return c + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ys = if full then 1 else 255 / 219 + local cs = if full then 1 else 255 / 224 + c = { + ys = floor(ys * 65536 + 0.5), + yo = if full then 0 else 16, + crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), + cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), + cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), + cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), + cs = cs, + } + cache[key] = c + return c +end + +-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 +local CLIP = bcreate(2304) +for i = 0, 2303 do + writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) +end + +-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with +-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) +@native function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer + local dst = out or bcreate(w * h * 4) + local c = coeffs(range, matrix) + local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu + local ch = (h + 1) // 2 + if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then + return dst + end + for y = 0, h - 1 do + local yrow = y * w + local crow = (y // 2) * cw + local o = yrow * 4 + for x = 0, w - 1, 2 do + local ci = crow + (x // 2) + local u = readu8(src, uo + ci) - 128 + local v = readu8(src, vo + ci) - 128 + local rv = (crv * v + 32768) // 65536 + local gv = (cgu * u + cgv * v + 32768) // 65536 + local bu = (cbu * u + 32768) // 65536 + local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + if x + 1 < w then + yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024 + writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + end + o += 8 + end + end + return dst +end + +-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p +@native function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + local dst = out or bcreate(w * h + 2 * cw * ch) + if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then + return dst + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ysc = if full then 1 else 219 / 255 + local csc = if full then 1 else 224 / 255 + local yof = if full then 0.5 else 16.5 + -- fixed point x 65536 + local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) + local yoff = floor(yof * 65536) + local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ub = floor(0.5 * csc * 65536 + 0.5) + local vr = ub + local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) + local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) + local coff4 = floor(128.5 * 65536) * 4 + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024)) + end + for cy = 0, ch - 1 do + local y0 = cy * 2 + local y1 = if y0 + 1 < h then y0 + 1 else y0 + for cx = 0, cw - 1 do + local x0 = cx * 2 + local x1 = if x0 + 1 < w then x0 + 1 else x0 + local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 + local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) + local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) + local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) + local i = cy * cw + cx + writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024)) + writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024)) + end + end + return dst +end + +-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent +@native local function info(img: Types.Image): (string, string) + local m = img.meta + local y = m and m.yuv + if type(y) == "table" then + return y.range or "limited", y.matrix or "bt601" + end + local src = m and m.source + if type(src) == "table" and src.range == "full" then + return "full", "bt601" + end + return "limited", "bt601" +end +Yuv.info = info + +-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer +@native function Yuv.planes(w: number, h: number): (number, number, number, number) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return w * h, w * h + cw * ch, cw, ch +end + +-- FULL_Y / FULL_C: limited -> full range sample maps +local FULL_Y = bcreate(256) +local FULL_C = bcreate(256) +for v = 0, 255 do + writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255)) + writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) +end + +-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned) +@native function Yuv.toFullRange(img: Types.Image): Types.Image + if img.format ~= "yuv420p" or info(img) == "full" then + return img + end + local w, h = img.width, img.height + local out = Types.Image.new(w, h, "yuv420p") + local src, dst = img.pixels, out.pixels + local ny = w * h + local n = math.min(buffer.len(src), buffer.len(dst)) + for i = 0, math.min(ny, n) - 1 do + writeu8(dst, i, readu8(FULL_Y, readu8(src, i))) + end + for i = ny, n - 1 do + writeu8(dst, i, readu8(FULL_C, readu8(src, i))) + end + out.meta.yuv = { range = "full", matrix = select(2, info(img)) } + out.meta.source = img.meta.source + return out +end + +-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) +@native function Yuv.imageToRgba(img: Types.Image): Types.Image? + if img.format == "rgba8" then + return img + end + if img.format ~= "yuv420p" then + return nil + end + local w, h = img.width, img.height + local uo, vo, cw = Yuv.planes(w, h) + local range, matrix = info(img) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) + out.meta.source = img.meta.source + return out +end + +-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) +@native function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image? + if img.format == "yuv420p" then + return img + end + if img.format ~= "rgba8" then + return nil + end + local out = Types.Image.new(img.width, img.height, "yuv420p") + Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) + out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } + out.meta.source = img.meta.source + return out +end + +-- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) +@native local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) + local fx, fy = sw / dw, sh / dh + for y = 0, dh - 1 do + local sy = (y + 0.5) * fy - 0.5 + if sy < 0 then + sy = 0 + end + local y0 = floor(sy) + if y0 > sh - 1 then + y0 = sh - 1 + end + local y1 = if y0 < sh - 1 then y0 + 1 else y0 + local wy = floor((sy - y0) * 256) + local r0, r1 = so + y0 * sw, so + y1 * sw + local o = d0 + y * dw + for x = 0, dw - 1 do + local sx = (x + 0.5) * fx - 0.5 + if sx < 0 then + sx = 0 + end + local x0 = floor(sx) + if x0 > sw - 1 then + x0 = sw - 1 + end + local x1 = if x0 < sw - 1 then x0 + 1 else x0 + local wx = floor((sx - x0) * 256) + local a = readu8(src, r0 + x0) * (256 - wx) + readu8(src, r0 + x1) * wx + local b = readu8(src, r1 + x0) * (256 - wx) + readu8(src, r1 + x1) * wx + writeu8(dst, o + x, (a * (256 - wy) + b * wy + 32768) // 65536) + end + end +end + +-- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). +-- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). +@native function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer + local dw: number = math.max(1, floor(width)) + local dh: number = math.max(1, floor(height)) + local cw: number = (w + 1) // 2 + local ch: number = (h + 1) // 2 + local dcw: number = (dw + 1) // 2 + local dch: number = (dh + 1) // 2 + local size = dw * dh + 2 * dcw * dch + local dst = if out and buffer.len(out) >= size then out else bcreate(size) + if w < 1 or h < 1 or buffer.len(src) < w * h + 2 * cw * ch then + return dst + end + scalePlane(src, 0, w, h, dst, 0, dw, dh) + scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch) + scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch) + return dst +end + +@native function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image + local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p") + Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels) + out.meta = table.clone(img.meta or {}) + return out +end + +return Yuv +end +__FILES["codecs/model/Draco"] = function() + +-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). +-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. +-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions +-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology +-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / +-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, +-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal +-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the +-- dequantization). +-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). +-- +-- local Draco = require("@rosetta/codecs/model/Draco") +-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string +-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) +-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, +-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } +-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) +-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } +-- +-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Attributes = __include("codecs/model/Draco/Attributes") + +local Draco = {} + +local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" } +local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" } +Draco.ATTRIBUTE_NAMES = NAMES +Draco.DATA_TYPES = TYPES + +type Attribute = { + name: string, + typeId: number, + uniqueId: number, + components: number, + type: string, + normalized: boolean, + data: buffer, +} +type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? } +type Geometry = { + kind: "mesh" | "points", + version: string, + method: string, + numPoints: number, + numFaces: number, + indices: buffer?, + attributes: { Attribute }, + metadata: Metadata?, +} +type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } + +-- sniff(buf, off?) -> whether the bytes start with "DRACO" +function Draco.sniff(buf: buffer, off: number?): boolean + local o = off or 0 + return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" +end + +local function header(d: Reader.D): (Header?, string?) + if Reader.remaining(d) < 11 then + return nil, "truncated header" + end + if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then + return nil, "not Draco data" + end + d.pos += 5 + local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + local flags = Reader.u16(d) + if kind > 1 then + return nil, "unsupported: geometry type " .. kind + end + return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil +end + +-- info(buf, off?, len?) -> the header +function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local d = Reader.new(buf, o, o + l, 0) + local h, err = header(d) + if not h then + return nil, Err.from(err, 0) + end + return h, nil +end + +local function metadataElement(d: Reader.D, depth: number): Metadata? + if depth > 1000 then + return nil + end + local m: Metadata = { entries = {}, children = {} } + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + for _ = 1, n do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local size = Reader.varint(d) + if d.bad or size == 0 or size > Reader.remaining(d) then + return nil + end + local v = buffer.create(size) + buffer.copy(v, 0, d.b, d.pos, size) + d.pos += size + m.entries[name] = v + end + local subs = Reader.varint(d) + if d.bad or subs > Reader.remaining(d) then + return nil + end + for _ = 1, subs do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local child = metadataElement(d, depth + 1) + if not child then + return nil + end + m.children[name] = child + end + return m +end + +local function metadata(d: Reader.D): Metadata? + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + local atts: { [number]: Metadata } = {} + for _ = 1, n do + local id = Reader.varint(d) + local m = metadataElement(d, 0) + if not m then + return nil + end + atts[id] = m + end + local m = metadataElement(d, 0) + if not m then + return nil + end + m.attributes = atts + return m +end + +local WRITE: { [number]: (buffer, number, number) -> () } = { + [1] = buffer.writei8, + [2] = buffer.writeu8, + [3] = buffer.writei16, + [4] = buffer.writeu16, + [5] = buffer.writei32, + [6] = buffer.writeu32, + [9] = buffer.writef32, + [11] = buffer.writeu8, +} + +-- per point output buffer of an attribute +local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) + local size = Attributes.DT_LENGTH[a.dataType] + local comps = a.comps + local stride = size * comps + local out = buffer.create(numPoints * stride) + local map = a.map + local n = a.numValues + if a.raw then + local raw = a.raw :: buffer + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + buffer.copy(out, p * stride, raw, e * stride, stride) + end + return out, nil + end + local vals = a.values :: { number } + local w = WRITE[a.dataType] + if not w then + return nil, "unsupported: data type " .. a.dataType + end + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + local o = p * stride + local k = e * comps + for c = 1, comps do + w(out, o, vals[k + c]) + o += size + end + end + return out, nil +end + +local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?) + local d = Reader.new(buf, o, o + l, 0) + local h, herr = header(d) + if not h then + return nil, herr, nil + end + local ver = h.major * 256 + h.minor + local maxVer = if h.kind == "points" then 0x0203 else 0x0202 + if h.major < 1 or ver > maxVer then + return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil + end + d.ver = ver + local maxPoints = (opts and opts.maxPoints) or 2 ^ 24 + local maxFaces = (opts and opts.maxFaces) or 2 ^ 24 + local meta: Metadata? = nil + if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then + meta = metadata(d) + if not meta then + return nil, d.bad or "bad metadata", nil + end + end + local mesh: Connectivity.Mesh? = nil + local numPoints = 0 + local method + if h.kind == "mesh" then + if h.method == 0 then + method = "sequential" + local m, err = Connectivity.sequential(d) + if not m then + return nil, err, nil + end + mesh = m + elseif h.method == 1 then + method = "edgebreaker" + local kind = Reader.u8(d) + if d.bad then + return nil, d.bad, nil + end + if kind > 2 then + return nil, "unknown edgebreaker traversal " .. kind, nil + end + local m, err = Connectivity.edgebreaker(d, kind) + if not m then + return nil, err, nil + end + mesh = m + else + return nil, "unsupported: mesh encoding method " .. h.method, nil + end + local m = mesh :: Connectivity.Mesh + if m.numFaces > maxFaces then + return nil, "too many faces", "limit" + end + numPoints = m.numPoints + else + if h.method > 1 then + return nil, "unsupported: point cloud encoding method " .. h.method, nil + end + method = if h.method == 1 then "kdtree" else "sequential" + numPoints = Reader.i32(d) + if d.bad then + return nil, d.bad, nil + end + if numPoints < 0 then + return nil, "bad point count", nil + end + end + if numPoints > maxPoints then + return nil, "too many points", "limit" + end + local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" }) + if not attrs then + return nil, aerr, nil + end + local g: Geometry = { + kind = h.kind, + version = h.major .. "." .. h.minor, + method = method, + numPoints = numPoints, + numFaces = 0, + indices = nil, + attributes = {}, + metadata = meta, + } + if mesh then + local nf = mesh.numFaces + local idx = buffer.create(nf * 12) + local faces = mesh.faces + for i = 1, nf * 3 do + local v = faces[i] + if v < 0 or v >= numPoints then + return nil, "face index out of range", nil + end + buffer.writeu32(idx, (i - 1) * 4, v) + end + g.numFaces = nf + g.indices = idx + end + for _, a in attrs do + local data, err = expand(a, numPoints) + if not data then + return nil, err, nil + end + table.insert(g.attributes, { + name = NAMES[a.type] or "GENERIC", + typeId = a.type, + uniqueId = a.uniqueId, + components = a.comps, + type = TYPES[a.dataType], + normalized = a.normalized, + data = data, + }) + end + return g, nil, nil +end + +-- decode(src, off?, len?, opts?) -> Geometry | nil, Err +function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local ok, g, msg, kind = pcall(decode, buf, o, l, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g)) + end + if not g then + return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil)) + end + return g, nil +end + +-- attribute(g, uniqueId) -> the attribute with that unique id +function Draco.attribute(g: Geometry, uniqueId: number): Attribute? + for _, a in g.attributes do + if a.uniqueId == uniqueId then + return a + end + end + return nil +end + +return Draco +end +__FILES["codecs/model/Draco/Attributes"] = function() + +-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear +-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute +-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to +-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream +-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ +-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; +-- Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Predict = __include("codecs/model/Draco/Predict") +local KdTree = __include("codecs/model/Draco/KdTree") + +local Attributes = {} + +type D = Reader.D + +-- data type ids (draco::DataType) -> byte length +local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 } +Attributes.DT_LENGTH = DT_LENGTH + +type Attr = { + id: number, -- 0-based attribute id + type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types) + dataType: number, + comps: number, + normalized: boolean, + uniqueId: number, + seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals + map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity + numValues: number, + portable: { number }?, -- the integer (portable) values + values: { number }?, -- the final values (numbers), flat + raw: buffer?, -- generic attributes: the raw values + quant: { min: { number }, range: number, bits: number }?, + octBits: number?, + scheme: Predict.Scheme?, +} + +type Decoder = { + attrs: { Attr }, + traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?, + md: Predict.MeshData?, + points: { number }?, +} + +-- the geometry the attributes decode against +type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } + +local function zigzag(v: number): number + if v % 2 == 1 then + return -(v // 2) - 1 + end + return v // 2 +end + +-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to +-- integers unless the scheme works in floats) +local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent? + local old = ver < 0x0200 + local vals = if old then pos.values else pos.portable + if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then + return nil + end + local map = pos.map + local trunc = old and not floats + return function(point: number): (number, number, number) + local e = if map then (map[point + 1] or 0) else point + local o = e * 3 + local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0 + if trunc then + x = if x < 0 then math.ceil(x) else math.floor(x) + y = if y < 0 then math.ceil(y) else math.floor(y) + z = if z < 0 then math.ceil(z) else math.floor(z) + end + return x, y, z + end +end + +local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?) + local comps = if a.seqType == 3 then 2 else a.comps + local n = #points + local numValues = n * comps + if n == 0 then + return false, "no values" + end + local compressed = Reader.u8(d) + if d.bad then + return false, d.bad + end + local vals: { number } + if compressed > 0 then + local s = Reader.symbols(d, numValues, comps) + if not s then + return false, d.bad or "bad values" + end + vals = s + else + local nb = Reader.u8(d) + if d.bad then + return false, d.bad + end + if nb < 1 or nb > 4 then + return false, "bad value byte count" + end + if Reader.remaining(d) < nb * numValues then + return false, "truncated values" + end + vals = table.create(numValues, 0) + local b, p = d.b, d.pos + if nb == 4 then + for i = 1, numValues do + vals[i] = buffer.readu32(b, p) + p += 4 + end + elseif nb == 1 then + for i = 1, numValues do + vals[i] = buffer.readu8(b, p) + p += 1 + end + elseif nb == 2 then + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + p += 2 + end + else + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 + p += 3 + end + end + d.pos = p + end + if not scheme or not scheme.tr.positive then + for i = 1, numValues do + vals[i] = zigzag(vals[i]) + end + else + local i32 = Predict.i32 + for i = 1, numValues do + vals[i] = i32(vals[i]) + end + end + if scheme then + if not Predict.decodeData(scheme, d) then + return false, d.bad or "bad prediction data" + end + local ok, err = Predict.compute(scheme, vals, n, comps, points) + if not ok then + return false, err + end + end + a.portable = vals + a.numValues = n + return true, nil +end + +local function decodeQuantInfo(d: D, a: Attr): boolean + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false + end + a.quant = { min = mins, range = range, bits = bits } + return true +end + +-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors +local function storeValues(a: Attr): (boolean, string?) + local src = a.portable :: { number } + local n = a.numValues + local fround = Predict.fround + if a.seqType == 1 then + local dt = a.dataType + local out = table.create(n * a.comps, 0) + for i = 1, n * a.comps do + local v = src[i] + if dt == 1 then + v = (v + 128) % 256 - 128 + elseif dt == 2 or dt == 11 then + v %= 256 + elseif dt == 3 then + v = (v + 32768) % 65536 - 32768 + elseif dt == 4 then + v %= 65536 + elseif dt == 6 then + v %= 4294967296 + elseif dt ~= 5 then + return false, "unsupported: integer attribute of data type " .. dt + end + out[i] = v + end + a.values = out + elseif a.seqType == 2 then + local q = a.quant + if not q then + return false, "no quantization data" + end + local maxQ = 2 ^ q.bits - 1 + local delta = fround(q.range / fround(maxQ)) + local comps = a.comps + local mins = q.min + local out = table.create(n * comps, 0) + local k = 1 + for _ = 1, n do + for c = 1, comps do + out[k] = fround(fround(fround(src[k]) * delta) + mins[c]) + k += 1 + end + end + a.values = out + elseif a.seqType == 3 then + local o = Predict.octahedron(a.octBits or 0) + if not o then + return false, "bad normal quantization" + end + local out = table.create(n * 3, 0) + for i = 0, n - 1 do + local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2]) + out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z + end + a.values = out + end + return true, nil +end + +-- decodes every attribute; returns them in attribute id order +function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) + local ver = d.ver + local numDecoders = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local mesh = g.mesh + local decoders: { Decoder } = {} + for i = 0, numDecoders - 1 do + local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil } + if g.edgebreaker and mesh then + local attDataId = Reader.i8(d) + local decoderType = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local ad = nil + if attDataId >= 0 then + ad = mesh.attrData[attDataId + 1] + if not ad or ad.decoderId >= 0 then + return nil, "bad attribute data id" + end + ad.decoderId = i + else + if mesh.posDecoderId >= 0 then + return nil, "two position decoders" + end + mesh.posDecoderId = i + end + local method = 0 + if ver >= 0x0102 then + method = Reader.u8(d) + if d.bad or method >= 2 then + return nil, "bad traversal method" + end + end + local ct = mesh.ct :: Connectivity.CT + local enc + if decoderType == 0 then + if ad then + enc = ad.enc + ad.used = false + else + enc = mesh.posEnc :: Connectivity.Enc + end + dec.traversal = { ct = ct, enc = enc, method = method } + else + if method ~= 0 or not ad then + return nil, "bad corner attribute decoder" + end + local cad = ad :: Connectivity.AttrData + enc = cad.enc + dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } + end + -- prediction data: the attribute's own corner table when its seams are in use + local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct + dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } + end + decoders[i + 1] = dec + end + -- the attribute descriptors + local all: { Attr } = {} + for _, dec in decoders do + local n = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if n == 0 or n > 5 * Reader.remaining(d) then + return nil, "bad attribute count" + end + for _ = 1, n do + local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + if d.bad then + return nil, d.bad + end + if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then + return nil, "bad attribute descriptor" + end + local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d) + local a: Attr = { + id = #all, + type = attType, + dataType = dataType, + comps = comps, + normalized = normalized > 0, + uniqueId = uniqueId, + seqType = 0, + map = nil, + numValues = 0, + } + table.insert(all, a) + table.insert(dec.attrs, a) + end + for _, a in (if g.kdTree then {} else dec.attrs) do + local t = Reader.u8(d) + if d.bad then + return nil, d.bad + end + if t > 3 then + return nil, "unknown attribute decoder " .. t + end + if (t == 2 or t == 3) and a.dataType ~= 9 then + return nil, "quantized attribute is not f32" + end + if t == 3 and a.comps ~= 3 then + return nil, "normal attribute without 3 components" + end + a.seqType = t + end + end + if d.bad then + return nil, d.bad + end + local function named(t: number): Attr? + for _, a in all do + if a.type == t then + return a + end + end + return nil + end + -- decode + for _, dec in decoders do + if g.kdTree then + local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) + if not ok then + return nil, err + end + continue + end + local points: { number } + local trav = dec.traversal + if trav then + local faces = (mesh :: Connectivity.Mesh).faces + local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method) + if not p then + return nil, "bad attribute traversal" + end + points = p + local numPoints = (mesh :: Connectivity.Mesh).numPoints + for _, a in dec.attrs do + local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints) + if not m then + return nil, "bad attribute mapping" + end + a.map = m + end + else + points = table.create(g.numPoints, 0) + for i = 1, g.numPoints do + points[i] = i - 1 + end + end + dec.points = points + -- portable values + for _, a in dec.attrs do + if a.seqType == 0 then + local stride = DT_LENGTH[a.dataType] * a.comps + local size = #points * stride + if Reader.remaining(d) < size then + return nil, "truncated attribute values" + end + local raw = buffer.create(size) + buffer.copy(raw, 0, d.b, d.pos, size) + d.pos += size + a.raw = raw + a.numValues = #points + continue + end + local psm = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if psm < -2 or psm >= 7 then + return nil, "bad prediction scheme" + end + local scheme: Predict.Scheme? = nil + if psm ~= -2 then + local ptt = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if ptt < -1 or ptt >= 4 then + return nil, "bad prediction transform" + end + if a.seqType == 3 then + if ptt == 2 or ptt == 3 then + scheme = Predict.new(psm, Predict.transform(ptt), dec.md) + end + elseif ptt == 1 then + scheme = Predict.new(psm, Predict.transform(1), dec.md) + end + end + if scheme and Predict.needsParent(scheme) then + local pos = named(0) + local getter = pos and parentGetter(ver, pos, scheme.method == 3) + if not getter then + return nil, "prediction needs the decoded positions" + end + scheme.parent = getter + end + if ver < 0x0200 then + if a.seqType == 2 and not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + local ok, err = decodeIntegerValues(d, a, points, scheme) + if not ok then + return nil, err + end + a.scheme = scheme + if ver < 0x0200 then + local ok2, err2 = storeValues(a) + if not ok2 then + return nil, err2 + end + end + end + -- data needed by the transforms + if ver >= 0x0200 then + for _, a in dec.attrs do + if a.seqType == 2 then + if not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + end + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + if d.bad then + return nil, d.bad + end + for _, a in dec.attrs do + if a.seqType ~= 0 then + local ok, err = storeValues(a) + if not ok then + return nil, err + end + end + end + end + end + return all, nil +end + +return Attributes +end +__FILES["codecs/model/Draco/Connectivity"] = function() + +-- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) +-- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute +-- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers +-- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 +-- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, +-- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, +-- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +local Reader = __include("codecs/model/Draco/Reader") + +local Connectivity = {} + +type D = Reader.D + +-- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner +type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } +-- encoding data of one attribute connectivity: vertex -> value index, value index -> corner +type Enc = { v2e: { number }, e2c: { number }, numValues: number } +type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } +type Mesh = { + faces: { number }, -- corner -> point + numFaces: number, + numPoints: number, + ct: CT?, -- Edgebreaker only + attrData: { AttrData }, + posEnc: Enc?, + posDecoderId: number, +} + +local TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E = 0, 1, 3, 5, 7 +local SYMBOL_TO_TOPOLOGY = { [0] = TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E } + +local function nextC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 2 then c - 2 else c + 1 +end +local function prevC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 0 then c + 2 else c - 1 +end +Connectivity.next = nextC +Connectivity.prev = prevC + +local function newEnc(nv: number): Enc + return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } +end + +-- ------------------------------------------------------------------------------------------------ sequential +function Connectivity.sequential(d: D): (Mesh?, string?) + local numFaces, numPoints + if d.ver < 0x0202 then + numFaces, numPoints = Reader.u32(d), Reader.u32(d) + else + numFaces, numPoints = Reader.varint(d), Reader.varint(d) + end + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 or numFaces > Reader.remaining(d) // 3 then + return nil, "too many faces" + end + local method = Reader.u8(d) + local n = numFaces * 3 + local faces = table.create(n, 0) + if method == 0 then + local sym = Reader.symbols(d, n, 1) + if not sym then + return nil, d.bad or "bad indices" + end + local last = 0 + for i = 1, n do + local e = sym[i] + local diff = e // 2 + if e % 2 == 1 then + if diff > last then + return nil, "bad index delta" + end + diff = -diff + elseif diff > 0x7fffffff - last then + return nil, "bad index delta" + end + last += diff + faces[i] = last + end + else + local b = d.b + if numPoints < 256 then + if d.pos + n > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu8(b, d.pos + i - 1) + end + d.pos += n + elseif numPoints < 65536 then + if d.pos + n * 2 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu16(b, d.pos + (i - 1) * 2) + end + d.pos += n * 2 + elseif numPoints < 2 ^ 21 and d.ver >= 0x0202 then + for i = 1, n do + faces[i] = Reader.varint(d) + end + else + if d.pos + n * 4 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu32(b, d.pos + (i - 1) * 4) + end + d.pos += n * 4 + end + end + if d.bad then + return nil, d.bad + end + return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil +end + +-- ------------------------------------------------------------------------------------------------ edgebreaker +-- the traversal decoders: symbols, start face configurations, attribute seam bits +type Trav = { + decodeSymbol: () -> number, + newActiveCorner: (corner: number) -> (), + mergeVertices: (dest: number, src: number) -> (), + startFace: () -> boolean, + seam: (i: number) -> boolean, +} + +-- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. +-- Returns the decoder state and the buffer after them. +local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) + local st: any = {} + if withSymbols then + local sym = Reader.copy(buf) + local size = Reader.startBits(sym, true) + if sym.bad then + buf.bad = sym.bad + return nil, buf + end + buf = Reader.copy(sym) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "traversal symbols past the end") + return nil, buf + end + buf.pos += size + st.sym = sym + end + if buf.ver < 0x0202 then + local sf = Reader.copy(buf) + local size = Reader.startBits(sf, true) + if sf.bad then + buf.bad = sf.bad + return nil, buf + end + buf = Reader.copy(sf) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "start faces past the end") + return nil, buf + end + buf.pos += size + st.startBuf = sf + else + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.startDec = bd + end + st.seams = {} + for i = 1, numAttributeData do + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.seams[i] = bd + end + return st, buf +end + +local function standardSymbol(sym: D): number + local s = Reader.bits(sym, 1) + if s == TOPOLOGY_C then + return s + end + return s + Reader.bits(sym, 2) * 2 +end + +-- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D) + local ver = buf.ver + local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) + if not st then + return nil, out + end + local function startFace(): boolean + if st.startBuf then + return Reader.bits(st.startBuf, 1) == 1 + end + return Reader.bit(st.startDec) + end + local function seam(i: number): boolean + return Reader.bit(st.seams[i + 1]) + end + local valences = table.create(numVertices, 0) + local c2v = ct.c2v + local function vtx(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function addValence(v: number, k: number) + if v >= 0 and v < numVertices then + valences[v + 1] += k + end + end + local function mergeVertices(dest: number, src: number) + if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then + valences[dest + 1] += valences[src + 1] + end + end + local lastSymbol = -1 + local function updateValences(corner: number) + local nx, pv = nextC(corner), prevC(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_S then + addValence(vtx(nx), 1) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_R then + addValence(vtx(corner), 1) + addValence(vtx(nx), 1) + addValence(vtx(pv), 2) + elseif lastSymbol == TOPOLOGY_L then + addValence(vtx(corner), 1) + addValence(vtx(nx), 2) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_E then + addValence(vtx(corner), 2) + addValence(vtx(nx), 2) + addValence(vtx(pv), 2) + end + end + + if kind == 0 then + local sym = st.sym + return { + decodeSymbol = function(): number + return standardSymbol(sym) + end, + newActiveCorner = function(_c: number) end, + mergeVertices = function(_a: number, _b: number) end, + startFace = startFace, + seam = seam, + }, out + elseif kind == 1 then + -- predictive (deprecated): a bit says whether the predicted symbol (from the pivot's valence) is right + local n = Reader.i32(out) + if out.bad or n < 0 or n >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local pred = Reader.bitDecoder(out) + if not pred then + return nil, out + end + local sym = st.sym + local predicted = -1 + return { + decodeSymbol = function(): number + if predicted ~= -1 and Reader.bit(pred) then + lastSymbol = predicted + return predicted + end + lastSymbol = standardSymbol(sym) + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then + local pivot = vtx(nextC(corner)) + local val = if pivot >= 0 and pivot < numVertices then valences[pivot + 1] else 0 + predicted = if val < 6 then TOPOLOGY_R else TOPOLOGY_C + else + predicted = -1 + end + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out + end + -- valence: per-context symbol streams chosen by the valence of the next vertex + local minValence, maxValence = 2, 7 + if ver < 0x0202 then + local nSplit = Reader.count(out, 0x0200) + if out.bad or nSplit >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local mode = Reader.i8(out) + if out.bad or mode ~= 0 then + Reader.fail(out, "unsupported valence mode") + return nil, out + end + end + local contexts: { { number } } = {} + local counters: { number } = {} + for i = 1, maxValence - minValence + 1 do + local n = Reader.varint(out) + if out.bad then + return nil, out + end + if n > numFaces then + Reader.fail(out, "too many context symbols") + return nil, out + end + counters[i] = n + contexts[i] = {} + if n > 0 then + -- C++ ignores a failure here (the symbols stay zero) + local save = out.bad + local syms = Reader.symbols(out, n, 1) + if syms then + contexts[i] = syms + else + out.bad = save + end + end + end + local active = -1 + local sym = st.sym + return { + decodeSymbol = function(): number + if active ~= -1 then + local k = counters[active + 1] - 1 + counters[active + 1] = k + if k < 0 then + return -1 + end + local id = contexts[active + 1][k + 1] or 0 + if id > 4 then + return -1 + end + lastSymbol = SYMBOL_TO_TOPOLOGY[id] + elseif ver < 0x0202 then + lastSymbol = standardSymbol(sym) + else + lastSymbol = TOPOLOGY_E + end + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + local v = vtx(nextC(corner)) + local val = if v >= 0 and v < numVertices then valences[v + 1] else 0 + if val < minValence then + val = minValence + elseif val > maxValence then + val = maxValence + end + active = val - minValence + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out +end + +-- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil +local function splitEvents(eb: D, numFaces: number): { any }? + local ver = eb.ver + local n = Reader.count(eb, 0x0200) + if eb.bad then + return nil + end + local splits = {} + if n > 0 then + if n > numFaces then + Reader.fail(eb, "too many topology splits") + return nil + end + if ver < 0x0102 then + for i = 1, n do + local split = Reader.u32(eb) + local source = Reader.u32(eb) + local edge = Reader.u8(eb) % 2 + splits[i] = { source = source, split = split, edge = edge } + end + else + local last = 0 + for i = 1, n do + local source = Reader.varint(eb) + last + local delta = Reader.varint(eb) + if eb.bad then + return nil + end + if delta > source then + Reader.fail(eb, "bad topology split") + return nil + end + splits[i] = { source = source, split = source - delta, edge = 0 } + last = source + end + Reader.startBits(eb, false) + for i = 1, n do + local e = Reader.bits(eb, if ver < 0x0202 then 2 else 1) + splits[i].edge = e % 2 + end + Reader.endBits(eb) + end + end + -- hole events (before 2.1): read and ignored + local holes = 0 + if ver < 0x0200 then + holes = Reader.u32(eb) + elseif ver < 0x0201 then + holes = Reader.varint(eb) + end + if eb.bad then + return nil + end + if holes > Reader.remaining(eb) then + Reader.fail(eb, "too many hole events") + return nil + end + for _ = 1, holes do + if ver < 0x0102 then + Reader.i32(eb) + else + Reader.varint(eb) + end + end + if eb.bad then + return nil + end + return splits +end + +-- MeshAttributeCornerTable from the seam corners (InitEmpty, AddSeamEdge, RecomputeVertices) +local function attributeTable(ct: CT, seams: { number }): CT? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nc = ct.nf * 3 + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local edgeSeam: { [number]: boolean } = {} + local vertSeam: { [number]: boolean } = {} + for _, c in seams do + edgeSeam[c] = true + vertSeam[V(nextC(c))] = true + vertSeam[V(prevC(c))] = true + local o = if c < 0 then -1 else (opp[c + 1] or -1) + if o ~= -1 then + edgeSeam[o] = true + vertSeam[V(nextC(o))] = true + vertSeam[V(prevC(o))] = true + end + end + local aopp = table.create(nc, -1) + for c = 0, nc - 1 do + aopp[c + 1] = if edgeSeam[c] then -1 else (opp[c + 1] or -1) + end + local ac2v = table.create(nc, -1) + local almc: { number } = {} + local num = 0 + local function swingLeftA(c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else aopp[n + 1] + return nextC(o) + end + local function swingRight(c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (opp[p + 1] or -1) + return prevC(o) + end + for v = 0, ct.nv - 1 do + local c = lmc[v + 1] or -1 + if c ~= -1 then + local id = num + num += 1 + local first = c + if vertSeam[v] then + local act = swingLeftA(first) + while act ~= -1 do + first = act + act = swingLeftA(act) + if act == c then + return nil + end + end + end + ac2v[first + 1] = id + table.insert(almc, first) + local act = swingRight(first) + local guard = 0 + while act ~= -1 and act ~= first do + if edgeSeam[nextC(act)] then + id = num + num += 1 + table.insert(almc, act) + end + ac2v[act + 1] = id + act = swingRight(act) + guard += 1 + if guard > nc then + return nil + end + end + end + end + return { c2v = ac2v, opp = aopp, lmc = almc, nv = num, nf = ct.nf, vertSeam = vertSeam } :: any +end + +-- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) +function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) + local ver = d.ver + if ver < 0x0202 then + Reader.count(d, 0x0200) -- num_new_vertices (unused) + end + local numEncodedVertices = Reader.count(d, 0x0200) + local numFaces = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 then + return nil, "too many faces" + end + if numEncodedVertices > numFaces * 3 then + return nil, "more vertices than corners" + end + local minEdges = (3 * numFaces) // 2 + local maxEdges = numEncodedVertices * (numEncodedVertices - 1) / 2 + if numEncodedVertices == 0 then + maxEdges = 0 + end + if maxEdges < minEdges then + return nil, "too few vertices for the faces" + end + local numAttributeData = Reader.u8(d) + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces < numSymbols or numFaces > numSymbols + numSymbols // 3 then + return nil, "bad symbol count" + end + local numSplitSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numSplitSymbols > numSymbols then + return nil, "bad split symbol count" + end + local maxVertices = numEncodedVertices + numSplitSymbols + + -- the corner table (filled lazily: nil = invalid) + local c2v: { number } = {} + local opp: { number } = {} + local lmc: { number } = {} + local nv = 0 + local ct: CT = { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } + local notHole: { [number]: boolean } = {} + + local splits: { any }? + local splitBytes = 0 + if ver < 0x0202 then + local size = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if size == 0 or size > Reader.remaining(d) then + return nil, "bad connectivity size" + end + local eb = Reader.new(d.b, d.pos + size, d.limit, ver) + splits = splitEvents(eb, numFaces) + if not splits then + return nil, eb.bad or "bad split events" + end + splitBytes = eb.pos - (d.pos + size) + else + splits = splitEvents(d, numFaces) + if not splits then + return nil, d.bad or "bad split events" + end + end + local splitData = splits :: { any } + + local trav, after = makeTraversal(traversalKind, Reader.copy(d), numAttributeData, maxVertices, numFaces, ct) + if not trav then + return nil, after.bad or "bad traversal data" + end + + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function setOpp(a: number, b: number) + if a >= 0 then + opp[a + 1] = b + end + if b >= 0 then + opp[b + 1] = a + end + end + local function setLmc(v: number, c: number) + if v >= 0 then + lmc[v + 1] = c + end + end + local function LMC(v: number): number + return if v < 0 then -1 else (lmc[v + 1] or -1) + end + local function addVertex(): number + nv += 1 + lmc[nv] = -1 + return nv - 1 + end + local function swingLeft(c: number): number + return nextC(O(nextC(c))) + end + local function swingRight(c: number): number + return prevC(O(prevC(c))) + end + + -- the symbols + local stack: { number } = {} + local sp = 0 + local splitActive: { [number]: number } = {} + local invalidVerts: { number } = {} + local removeInvalid = numAttributeData == 0 + local nf = 0 + for symbolId = 0, numSymbols - 1 do + local face = nf + nf += 1 + local checkSplit = false + local symbol = trav.decodeSymbol() + local corner = 3 * face + if symbol == TOPOLOGY_C then + if sp == 0 then + return nil, "bad traversal (C)" + end + local a = stack[sp] + local vx = V(nextC(a)) + local b = nextC(LMC(vx)) + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (C)" + end + setOpp(a, corner + 1) + setOpp(b, corner + 2) + local vap, vbn = V(prevC(a)), V(nextC(b)) + if vx == vap or vx == vbn then + return nil, "bad traversal (C)" + end + c2v[corner + 1] = vx + c2v[corner + 2] = vbn + c2v[corner + 3] = vap + setLmc(vap, corner + 2) + notHole[vx] = true + stack[sp] = corner + elseif symbol == TOPOLOGY_R or symbol == TOPOLOGY_L then + if sp == 0 then + return nil, "bad traversal (R / L)" + end + local a = stack[sp] + if O(a) ~= -1 then + return nil, "bad traversal (R / L)" + end + local oc, cl, cr + if symbol == TOPOLOGY_R then + oc, cl, cr = corner + 2, corner + 1, corner + else + oc, cl, cr = corner + 1, corner, corner + 2 + end + setOpp(oc, a) + local nvx = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + c2v[oc + 1] = nvx + setLmc(nvx, oc) + local vr = V(prevC(a)) + c2v[cr + 1] = vr + setLmc(vr, cr) + c2v[cl + 1] = V(nextC(a)) + stack[sp] = corner + checkSplit = true + elseif symbol == TOPOLOGY_S then + if sp == 0 then + return nil, "bad traversal (S)" + end + local b = stack[sp] + stack[sp] = nil + sp -= 1 + local pushed = splitActive[symbolId] + if pushed then + sp += 1 + stack[sp] = pushed + end + if sp == 0 then + return nil, "bad traversal (S)" + end + local a = stack[sp] + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (S)" + end + setOpp(a, corner + 2) + setOpp(b, corner + 1) + local vp = V(prevC(a)) + c2v[corner + 1] = vp + c2v[corner + 2] = V(nextC(a)) + local vbp = V(prevC(b)) + c2v[corner + 3] = vbp + setLmc(vbp, corner + 2) + local cn = nextC(b) + local vn = V(cn) + trav.mergeVertices(vp, vn) + setLmc(vp, LMC(vn)) + local first = cn + while cn ~= -1 do + c2v[cn + 1] = vp + cn = swingLeft(cn) + if cn == first then + return nil, "bad traversal (S loop)" + end + end + setLmc(vn, -1) + if removeInvalid then + table.insert(invalidVerts, vn) + end + stack[sp] = corner + elseif symbol == TOPOLOGY_E then + local v0 = addVertex() + c2v[corner + 1] = v0 + c2v[corner + 2] = addVertex() + c2v[corner + 3] = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + setLmc(v0, corner) + setLmc(v0 + 1, corner + 1) + setLmc(v0 + 2, corner + 2) + sp += 1 + stack[sp] = corner + checkSplit = true + else + return nil, "bad traversal symbol" + end + ct.nv = nv + trav.newActiveCorner(stack[sp]) + if checkSplit then + local encId = numSymbols - symbolId - 1 + while true do + local top = splitData[#splitData] + if not top then + break + end + if top.source > encId then + return nil, "bad split symbol id" + end + if top.source ~= encId then + break + end + splitData[#splitData] = nil + local act = stack[sp] + local newActive = if top.edge == 1 then nextC(act) else prevC(act) + splitActive[numSymbols - top.split - 1] = newActive + end + end + end + if nv > maxVertices then + return nil, "too many vertices" + end + + -- start faces: interior faces that close the remaining holes + local initFaces = {} + while sp > 0 do + local corner = stack[sp] + stack[sp] = nil + sp -= 1 + if trav.startFace() then + if nf >= numFaces then + return nil, "too many faces" + end + local vn = V(nextC(corner)) + local b = nextC(LMC(vn)) + local vx = V(nextC(b)) + local c = nextC(LMC(vx)) + if corner == b or corner == c or b == c or O(corner) ~= -1 or O(b) ~= -1 or O(c) ~= -1 then + return nil, "bad start face" + end + local vp = V(nextC(c)) + local nc = 3 * nf + nf += 1 + setOpp(nc, corner) + setOpp(nc + 1, b) + setOpp(nc + 2, c) + c2v[nc + 1] = vx + c2v[nc + 2] = vp + c2v[nc + 3] = vn + for k = 0, 2 do + notHole[V(nc + k)] = true + end + table.insert(initFaces, nc) + end + end + if nf ~= numFaces then + return nil, "face count mismatch" + end + + -- compact the vertices removed by S symbols (no attribute data only) + local numVertices = nv + for _, inv in invalidVerts do + local src = numVertices - 1 + while src >= 0 and LMC(src) == -1 do + numVertices -= 1 + src = numVertices - 1 + end + if src >= inv then + -- every corner of src (VertexCornersIterator: left, then right) + local start = LMC(src) + local corners = {} + local cc = start + local left = true + local guard = 0 + while cc ~= -1 do + table.insert(corners, cc) + guard += 1 + if guard > numFaces * 3 + 3 then + return nil, "bad vertex fan" + end + if left then + cc = swingLeft(cc) + if cc == -1 then + cc = swingRight(start) + left = false + elseif cc == start then + cc = -1 + end + else + cc = swingRight(cc) + end + end + for _, cid in corners do + if V(cid) ~= src then + return nil, "bad vertex fan" + end + c2v[cid + 1] = inv + end + setLmc(inv, LMC(src)) + setLmc(src, -1) + notHole[inv] = notHole[src] + notHole[src] = true + numVertices -= 1 + end + end + + -- continue after the traversal data (and the split events before 2.2) + d.pos = after.pos + d.bad = after.bad + if ver < 0x0202 then + d.pos += splitBytes + end + + -- attribute seams + local attrData: { AttrData } = {} + for i = 1, numAttributeData do + attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } + end + if numAttributeData > 0 then + for f = 0, numFaces - 1 do + local base = 3 * f + for k = 0, 2 do + local c = if k == 0 then base elseif k == 1 then base + 1 else base + 2 + local o = O(c) + if o == -1 then + for i = 1, numAttributeData do + table.insert(attrData[i].seams, c) + end + elseif ver < 0x0201 or o // 3 >= f then + for i = 1, numAttributeData do + if trav.seam(i - 1) then + table.insert(attrData[i].seams, c) + end + end + end + end + end + end + ct.nv = nv + for i = 1, numAttributeData do + local act = attributeTable(ct, attrData[i].seams) + if not act then + return nil, "bad attribute seams" + end + attrData[i].ct = act + attrData[i].enc = newEnc(math.max(act.nv, nv)) + end + local posEnc = newEnc(nv) + + -- AssignPointsToCorners + local faces = table.create(numFaces * 3, 0) + local numPoints + if numAttributeData == 0 then + for c = 0, numFaces * 3 - 1 do + faces[c + 1] = V(c) + end + numPoints = numVertices + else + numPoints = 0 + for v = 0, nv - 1 do + local c = LMC(v) + if c ~= -1 then + local first = c + if notHole[v] then + for i = 1, numAttributeData do + local act = attrData[i].ct :: any + if act.vertSeam[V(c)] then + local vid = act.c2v[c + 1] + local a = swingRight(c) + local found = false + while a ~= c do + if a == -1 then + return nil, "bad seam fan" + end + if act.c2v[a + 1] ~= vid then + first = a + found = true + break + end + a = swingRight(a) + end + if found then + break + end + end + end + end + c = first + faces[c + 1] = numPoints + numPoints += 1 + local pc = c + c = swingRight(c) + local guard = 0 + while c ~= -1 and c ~= first do + local seam = false + for i = 1, numAttributeData do + local ac2v = (attrData[i].ct :: CT).c2v + if ac2v[c + 1] ~= ac2v[pc + 1] then + seam = true + break + end + end + if seam then + faces[c + 1] = numPoints + numPoints += 1 + else + faces[c + 1] = faces[pc + 1] + end + pc = c + c = swingRight(c) + guard += 1 + if guard > numFaces * 3 then + return nil, "bad vertex fan" + end + end + end + end + end + for k = 1, nv do + if not lmc[k] then + lmc[k] = -1 + end + end + return { + faces = faces, + numFaces = numFaces, + numPoints = numPoints, + ct = ct, + attrData = attrData, + posEnc = posEnc, + posDecoderId = -1, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ traversal +-- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). +-- method 0 = depth first, 1 = max prediction degree. +function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nf, nvt = ct.nf, ct.nv + local faceVisited = table.create(nf, false) + local vertVisited = table.create(nvt, false) + local points: { number } = {} + local v2e, e2c = enc.v2e, enc.e2c + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function faceSeen(c: number): boolean + if c < 0 then + return true + end + return faceVisited[c // 3 + 1] == true + end + local function visit(v: number, c: number): boolean + if v < 0 or v >= nvt then + return false + end + vertVisited[v + 1] = true + table.insert(points, faces[c + 1]) + table.insert(e2c, c) + v2e[v + 1] = enc.numValues + enc.numValues += 1 + return true + end + local function onBoundary(v: number): boolean + local c = if v < 0 then -1 else (lmc[v + 1] or -1) + return nextC(O(nextC(c))) == -1 + end + if method == 0 then + local stack: { number } = {} + for f = 0, nf - 1 do + local start = 3 * f + if not faceSeen(start) then + stack[1] = start + for k = #stack, 2, -1 do + stack[k] = nil + end + local nx, pv = V(nextC(start)), V(prevC(start)) + if nx == -1 or pv == -1 then + return nil + end + if not vertVisited[nx + 1] and not visit(nx, nextC(start)) then + return nil + end + if not vertVisited[pv + 1] and not visit(pv, prevC(start)) then + return nil + end + while #stack > 0 do + local c = stack[#stack] + if c == -1 or faceSeen(c) then + stack[#stack] = nil + continue + end + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v == -1 then + return nil + end + if not vertVisited[v + 1] then + local boundary = onBoundary(v) + if not visit(v, c) then + return nil + end + if not boundary then + c = O(nextC(c)) + if c == -1 then + -- C++ would index face -1 here; treat as done + stack[#stack] = nil + break + end + continue + end + end + local rc, lc = O(nextC(c)), O(prevC(c)) + if faceSeen(rc) then + if faceSeen(lc) then + stack[#stack] = nil + break + end + c = lc + elseif faceSeen(lc) then + c = rc + else + stack[#stack] = lc + table.insert(stack, rc) + break + end + end + end + end + end + return points + end + -- max prediction degree + if nvt == 0 then + return points + end + local degree = table.create(nvt, 0) + local stacks: { { number } } = { {}, {}, {} } + local best = 0 + local function priority(c: number): number + local v = V(c) + if v < 0 or v >= nvt then + return 0 + end + local p = 0 + if not vertVisited[v + 1] then + degree[v + 1] += 1 + p = if degree[v + 1] > 1 then 1 else 2 + end + return p + end + for f = 0, nf - 1 do + local start = 3 * f + table.insert(stacks[1], start) + best = 0 + local nx, pv, tip = V(nextC(start)), V(prevC(start)), V(start) + for _, pair in { { nx, nextC(start) }, { pv, prevC(start) }, { tip, start } } do + local v = pair[1] + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, pair[2]) + end + end + while true do + local c = -1 + for i = best, 2 do + local s = stacks[i + 1] + if #s > 0 then + c = s[#s] + s[#s] = nil + best = i + break + end + end + if c == -1 then + break + end + if not faceSeen(c) then + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, c) + end + local rc, lc = O(nextC(c)), O(prevC(c)) + local rSeen, lSeen = faceSeen(rc), faceSeen(lc) + if not lSeen then + local p = priority(lc) + if rSeen and p <= best then + c = lc + continue + end + table.insert(stacks[p + 1], lc) + if p < best then + best = p + end + end + if not rSeen then + local p = priority(rc) + if p <= best then + c = rc + continue + end + table.insert(stacks[p + 1], rc) + if p < best then + best = p + end + end + break + end + end + end + end + return points +end + +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }? + local map = table.create(numPoints, 0) + local c2v, v2e = ct.c2v, enc.v2e + for c = 0, ct.nf * 3 - 1 do + local p = faces[c + 1] + local v = c2v[c + 1] or -1 + if v == -1 then + return nil + end + local e = v2e[v + 1] or 0 + if p >= numPoints or e >= numPoints then + return nil + end + map[p + 1] = e + end + return map +end + +return Connectivity +end +__FILES["codecs/model/Draco/Int64"] = function() + +-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / +-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both +-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +local Int64 = {} + +local P32 = 4294967296 +local P31 = 2147483648 + +function Int64.from(n: number): (number, number) + if n >= 0 then + return (n // P32) % P32, n % P32 + end + local h, l = Int64.from(-n) + return Int64.neg(h, l) +end + +function Int64.neg(h: number, l: number): (number, number) + if l == 0 then + return (P32 - h) % P32, 0 + end + return P32 - 1 - h, P32 - l +end + +function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local c = 0 + if l >= P32 then + l -= P32 + c = 1 + end + return (ah + bh + c) % P32, l +end + +function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number) + local nh, nl = Int64.neg(bh, bl) + return Int64.add(ah, al, nh, nl) +end + +-- the product mod 2^64 (the same bits for signed and unsigned operands) +function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536 + local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536 + local c0 = a0 * b0 + local c1 = a1 * b0 + a0 * b1 + local c2 = a2 * b0 + a1 * b1 + a0 * b2 + local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3 + local lo = c0 + (c1 % 65536) * 65536 + local carry = lo // P32 + lo %= P32 + local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32 + return hi, lo +end + +function Int64.isNeg(h: number): boolean + return h >= P31 +end + +-- the signed value as a number (exact below 2^53 in magnitude) +function Int64.signed(h: number, l: number): number + if h >= P31 then + return (h - P32) * P32 + l + end + return h * P32 + l +end + +-- the unsigned value as a number (rounded past 2^53) +function Int64.unsigned(h: number, l: number): number + return h * P32 + l +end + +-- unsigned compare: -1, 0, 1 +function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number + if ah ~= bh then + return if ah < bh then -1 else 1 + end + if al ~= bl then + return if al < bl then -1 else 1 + end + return 0 +end + +-- signed compare: -1, 0, 1 +function Int64.cmp(ah: number, al: number, bh: number, bl: number): number + local sa = if ah >= P31 then ah - P32 else ah + local sb = if bh >= P31 then bh - P32 else bh + if sa ~= sb then + return if sa < sb then -1 else 1 + end + return Int64.ucmp(0, al, 0, bl) +end + +-- unsigned division (b ~= 0): quotient, remainder +function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number) + if ah == 0 and bh == 0 then + return 0, al // bl, 0, al % bl + end + local qh, ql, rh, rl = 0, 0, 0, 0 + for i = 63, 0, -1 do + -- r = r * 2 + bit i of a + local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2 + local over = rh >= P31 + rh = (rh * 2 + rl // P31) % P32 + rl = (rl * 2) % P32 + bit + if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then + rh, rl = Int64.sub(rh, rl, bh, bl) + if i >= 32 then + qh += 2 ^ (i - 32) + else + ql += 2 ^ i + end + end + end + return qh, ql, rh, rl +end + +-- signed division truncating toward zero (b ~= 0) +function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) + local na, nb = ah >= P31, bh >= P31 + if na then + ah, al = Int64.neg(ah, al) + end + if nb then + bh, bl = Int64.neg(bh, bl) + end + local qh, ql = Int64.udivmod(ah, al, bh, bl) + if na ~= nb then + return Int64.neg(qh, ql) + end + return qh, ql +end + +-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included) +function Int64.isqrt(h: number, l: number): (number, number) + if h == 0 and l == 0 then + return 0, 0 + end + local acth, actl = h, l + local sh, sl = 0, 1 + while Int64.ucmp(acth, actl, 0, 2) >= 0 do + sh, sl = Int64.add(sh, sl, sh, sl) + acth, actl = Int64.udivmod(acth, actl, 0, 4) + end + repeat + local qh, ql = Int64.udivmod(h, l, sh, sl) + local th, tl = Int64.add(sh, sl, qh, ql) + sh, sl = Int64.udivmod(th, tl, 0, 2) + if sh == 0 and sl == 0 then + return 0, 0 + end + local pph, ppl = Int64.mul(sh, sl, sh, sl) + until Int64.ucmp(pph, ppl, h, l) <= 0 + return sh, sl +end + +return Int64 +end +__FILES["codecs/model/Draco/KdTree"] = function() + +-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder +-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the +-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from +-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ +-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, +-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +local Reader = __include("codecs/model/Draco/Reader") +local Predict = __include("codecs/model/Draco/Predict") + +local KdTree = {} + +type D = Reader.D + +-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out +type Src = { next: () -> number, bits: (n: number) -> number? } + +local function direct(d: D): Src? + local size = Reader.u32(d) + if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then + Reader.fail(d, "kd-tree: bad direct bits") + return nil + end + local b, base, words = d.b, d.pos, size // 4 + d.pos += size + local pos, used = 0, 0 + return { + next = function(): number + if pos >= words then + return 0 + end + local w = buffer.readu32(b, base + pos * 4) + local bit = bit32.extract(w, 31 - used) + used += 1 + if used == 32 then + pos += 1 + used = 0 + end + return bit + end, + bits = function(n: number): number? + local remaining = 32 - used + if n <= remaining then + if pos >= words then + return nil + end + local w = buffer.readu32(b, base + pos * 4) + local v = bit32.extract(w, 32 - used - n, n) + used += n + if used == 32 then + pos += 1 + used = 0 + end + return v + end + if pos + 1 >= words then + return nil + end + local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining) + local lo = n - remaining + pos += 1 + used = lo + local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo) + return hiBits * 2 ^ lo + loBits + end, + } +end + +local function rans(d: D): Src? + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + local function nextBit(): number + return if Reader.bit(bd) then 1 else 0 + end + return { + next = nextBit, + bits = function(n: number): number? + local v = 0 + for _ = 1, n do + v = v * 2 + nextBit() + end + return v + end, + } +end + +local function folded(d: D): Src? + local parts: { Reader.Bits } = {} + for i = 1, 32 do + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + parts[i] = bd + end + local main = Reader.bitDecoder(d) + if not main then + return nil + end + return { + next = function(): number + return if Reader.bit(main :: Reader.Bits) then 1 else 0 + end, + bits = function(n: number): number? + local v = 0 + for i = 1, n do + v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0) + end + return v + end, + } +end + +local function msb(n: number): number + local k = -1 + while n >= 1 do + n = n // 2 + k += 1 + end + return k +end + +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?) + local bitLength = Reader.u32(d) + local numPoints = Reader.u32(d) + if d.bad then + return nil, d.bad + end + if bitLength > 32 then + return nil, "kd-tree: bad bit length" + end + if numPoints ~= expected then + return nil, "kd-tree: point count mismatch" + end + local out: { { number } } = {} + if numPoints == 0 then + return out, nil + end + local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d) + local remainingBits = numbers and direct(d) + local axisDec = remainingBits and direct(d) + local half = axisDec and direct(d) + if not numbers or not remainingBits or not axisDec or not half then + return nil, d.bad or "kd-tree: bad bit decoders" + end + local selectAxis = level >= 6 + local zero = table.create(dim, 0) + local baseStack: { { number } } = { table.clone(zero) } + local levelStack: { { number } } = { table.clone(zero) } + local stack = { { numPoints, 0, 0 } } + local decoded = 0 + local p = table.create(dim, 0) + while #stack > 0 do + local st = stack[#stack] + stack[#stack] = nil + local n, lastAxis, sp = st[1], st[2], st[3] + local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1] + if n > numPoints then + return nil, "kd-tree: bad point count" + end + local axis + if not selectAxis then + axis = if lastAxis == dim - 1 then 0 else lastAxis + 1 + elseif n < 64 then + axis = 0 + for a = 1, dim - 1 do + if levels[axis + 1] > levels[a + 1] then + axis = a + end + end + else + axis = (axisDec :: Src).bits(4) or 0 + end + if axis >= dim then + return nil, "kd-tree: bad axis" + end + local lvl = levels[axis + 1] + if bitLength - lvl == 0 then + for _ = 1, n do + table.insert(out, table.clone(oldBase)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if n <= 2 then + for _ = 1, n do + local a = axis + for _ = 1, dim do + local rb = bitLength - levels[a + 1] + local v = 0 + if rb > 0 then + local got = remainingBits.bits(rb) + if got == nil then + return nil, "kd-tree: remaining bits run out" + end + v = got + end + p[a + 1] = bit32.bor(oldBase[a + 1], v) + a = if a == dim - 1 then 0 else a + 1 + end + table.insert(out, table.clone(p)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + local rbits = bitLength - lvl + local modifier = 2 ^ (rbits - 1) + local nb = table.clone(oldBase) + nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296 + baseStack[sp + 2] = nb + local number = numbers.bits(msb(n)) or 0 + local first = n // 2 + if first < number then + return nil, "kd-tree: bad split" + end + first -= number + local second = n - first + if first ~= second and half.next() == 0 then + first, second = second, first + end + levels[axis + 1] += 1 + levelStack[sp + 2] = table.clone(levels) + if sp + 2 > 32 * dim + 1 then + return nil, "kd-tree: too deep" + end + if first > 0 then + table.insert(stack, { first, axis, sp }) + end + if second > 0 then + table.insert(stack, { second, axis, sp + 1 }) + end + end + if decoded ~= expected then + return nil, "kd-tree: point count mismatch" + end + return out, nil +end + +local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } + +-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) +function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?) + if d.ver < 0x0203 then + return false, "unsupported: kd-tree point clouds before bitstream 2.3" + end + local level = Reader.u8(d) + if d.bad then + return false, d.bad + end + if level > 6 then + return false, "kd-tree: bad compression level" + end + local dim = 0 + for _, a in attrs do + local dt = a.dataType + if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then + return false, "unsupported: kd-tree attribute of data type " .. dt + end + dim += a.comps + end + local points, err = decodePoints(d, level, dim, numPoints) + if not points then + return false, err + end + -- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types + local off = 0 + for _, a in attrs do + local comps = a.comps + local vals = table.create(numPoints * comps, 0) + local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296 + local raw = a.dataType == 9 + for i, pt in points do + for c = 1, comps do + local v = pt[off + c] + vals[(i - 1) * comps + c] = if raw then v else v % mod + end + end + a.portable = vals + a.values = vals + a.numValues = numPoints + a.map = nil + off += comps + end + -- the data needed by the transforms: f32 quantization, then the signed minima + for _, a in attrs do + if a.dataType == 9 then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false, d.bad or "kd-tree: bad quantization" + end + a.quant = { min = mins, range = range, bits = bits } + end + end + for _, a in attrs do + if SIGNED[a.dataType] then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + local v = Reader.varint(d) + mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2 + end + if d.bad then + return false, d.bad + end + a.signedMin = mins + end + end + -- back to the original values + local fround = Predict.fround + for _, a in attrs do + local vals = a.portable :: { number } + local comps = a.comps + if a.dataType == 9 then + local q = a.quant + local delta = fround(q.range / fround(2 ^ q.bits - 1)) + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local v = vals[i] + if v >= 2147483648 then + v -= 4294967296 + end + out[i] = fround(fround(fround(v) * delta) + q.min[c]) + end + a.values = out + elseif SIGNED[a.dataType] then + -- the C++ reads the stored (already narrowed) unsigned values back + local bits = SIGNED[a.dataType] + local mins = a.signedMin + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local u = vals[i] + if u > 2147483647 then + return false, "kd-tree: signed value out of range" + end + local s = Predict.i32(u + mins[c]) + local m = 2 ^ bits + out[i] = (s + m / 2) % m - m / 2 + end + a.values = out + end + end + return true, nil +end + +return KdTree +end +__FILES["codecs/model/Draco/Predict"] = function() + +-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference +-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and +-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. +-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; +-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 +-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, +-- licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Int64 = __include("codecs/model/Draco/Int64") + +local Predict = {} + +type D = Reader.D +type CT = Connectivity.CT + +local nextC, prevC = Connectivity.next, Connectivity.prev + +local F32 = buffer.create(4) +local function fround(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +Predict.fround = fround + +local function i32(x: number): number + return (x + 2147483648) % 4294967296 - 2147483648 +end +Predict.i32 = i32 + +local function tdiv(a: number, b: number): number + local q = a / b + return if q < 0 then math.ceil(q) else math.floor(q) +end + +-- static_cast of a float with the decoder's NaN / range guard (INT_MIN) +local function truncInt(x: number): number + if x ~= x or x > 2147483647 or x < -2147483648 then + return -2147483648 + end + return tdiv(x, 1) +end + +-- exact a * b = p + e (Dekker), for integers below 2^53 +local SPLIT = 134217729 +local function twoProd(a: number, b: number): (number, number) + local p = a * b + local t = SPLIT * a + local ah = t - (t - a) + local al = a - ah + t = SPLIT * b + local bh = t - (t - b) + local bl = b - bh + return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl +end + +-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0) +local function mulDiv(a: number, b: number, c: number): number + local neg = (a < 0) ~= (b < 0) + a, b = math.abs(a), math.abs(b) + local p = a * b + local q + if p < 9007199254740992 then + q = p // c + else + q = math.floor(p / c) + local ph, pl = twoProd(a, b) + local qh, ql = twoProd(q, c) + local r = (ph - qh) + (pl - ql) + while r < 0 do + q -= 1 + r += c + end + while r >= c do + q += 1 + r -= c + end + end + return if neg then -q else q +end + +-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 +local function isqrtProd(a: number, b: number): number + if a == 0 or b == 0 then + return 0 + end + local s = math.floor(math.sqrt(a) * math.sqrt(b)) + local ph, pl = twoProd(a, b) + local function le(x: number): boolean -- x * x <= a * b + local xh, xl = twoProd(x, x) + if xh ~= ph then + return xh < ph + end + return xl <= pl + end + while s > 0 and not le(s) do + s -= 1 + end + while le(s + 1) do + s += 1 + end + return s +end + +-- ------------------------------------------------------------------------------------------------ octahedron toolbox +type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } + +function Predict.octahedron(bits: number): Oct? + if bits < 2 or bits > 30 then + return nil + end + local maxQ = 2 ^ bits - 1 + local maxV = maxQ - 1 + return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) } +end + +local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number) + local maxV, center = o.maxV, o.center + if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then + return maxV, maxV + elseif s == 0 and t > center then + t = center - (t - center) + elseif s == maxV and t < center then + t = center + (center - t) + elseif t == maxV and s < center then + s = center + (center - s) + elseif t == 0 and s > center then + s = center - (s - center) + end + return s, t +end + +local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number) + local s, t + local center, maxV = o.center, o.maxV + if x >= 0 then + s, t = y + center, z + center + else + s = if y < 0 then math.abs(z) else maxV - math.abs(z) + t = if z < 0 then math.abs(y) else maxV - math.abs(y) + end + return canonicalizeCoords(o, s, t) +end + +local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number) + local sum = math.abs(x) + math.abs(y) + math.abs(z) + local center = o.center + if sum == 0 then + return center, y, z + end + x = mulDiv(x, center, sum) + y = mulDiv(y, center, sum) + if z >= 0 then + z = center - math.abs(x) - math.abs(y) + else + z = -(center - math.abs(x) - math.abs(y)) + end + return x, y, z +end + +local function invertDiamond(o: Oct, s: number, t: number): (number, number) + local signS, signT + if s >= 0 and t >= 0 then + signS, signT = 1, 1 + elseif s <= 0 and t <= 0 then + signS, signT = -1, -1 + else + signS = if s > 0 then 1 else -1 + signT = if t > 0 then 1 else -1 + end + local cs, ctv = signS * o.center, signT * o.center + local us, ut = s + s - cs, t + t - ctv + if signS * signT >= 0 then + us, ut = -ut, -us + else + us, ut = ut, us + end + return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2) +end + +local function modMax(o: Oct, x: number): number + if x > o.center then + return x - o.maxQ + elseif x < -o.center then + return x + o.maxQ + end + return x +end + +-- quantized octahedral (s, t) -> unit vector, in f32 like the C++ +function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number) + local y = fround(fround(fround(s) * o.scale) - 1) + local z = fround(fround(fround(t) * o.scale) - 1) + local x = fround(fround(1 - math.abs(y)) - math.abs(z)) + local xo = -x + if xo < 0 then + xo = 0 + end + y = fround(if y < 0 then y + xo else y - xo) + z = fround(if z < 0 then z + xo else z - xo) + local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z)) + if n2 < 1e-6 then + return 0, 0, 0 + end + local dd = fround(1 / fround(math.sqrt(n2))) + return fround(x * dd), fround(y * dd), fround(z * dd) +end + +-- ------------------------------------------------------------------------------------------------ transforms +-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values +type Transform = { + kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized + positive: boolean, -- corrections are stored without the zig-zag sign mapping + min: number, + max: number, + maxDif: number, + oct: Oct?, +} + +function Predict.transform(kind: number): Transform + return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } +end + +function Predict.decodeTransform(tr: Transform, d: D): boolean + if tr.kind == 1 then + local mn, mx = Reader.i32(d), Reader.i32(d) + if d.bad or mn > mx then + return false + end + local dif = mx - mn + if dif >= 2147483647 then + return false + end + tr.min, tr.max, tr.maxDif = mn, mx, dif + 1 + return true + end + local maxQ = Reader.i32(d) + if tr.kind == 3 or d.ver < 0x0202 then + Reader.i32(d) -- center value (unused) + end + if d.bad or maxQ <= 0 or maxQ % 2 == 0 then + return false + end + local bits = 0 + while 2 ^ bits <= maxQ do + bits += 1 + end + local o = Predict.octahedron(bits) + if not o then + return false + end + tr.oct = o + return true +end + +-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] +local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number) + if tr.kind == 1 then + local mn, mx, dif = tr.min, tr.max, tr.maxDif + for c = 1, comps do + local p = pred[c] + if p > mx then + p = mx + elseif p < mn then + p = mn + end + local v = i32(p + data[off + c]) + if v > mx then + v -= dif + elseif v < mn then + v += dif + end + data[off + c] = v + end + return + end + local o = tr.oct :: Oct + local center = o.center + local ps, pt = pred[1] - center, pred[2] - center + local cs, ct = data[off + 1], data[off + 2] + local inDiamond = math.abs(ps) + math.abs(pt) <= center + if not inDiamond then + ps, pt = invertDiamond(o, ps, pt) + end + local os_: number, ot: number = 0, 0 + if tr.kind == 2 then + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + else + local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0) + local rot = 0 + if ps == 0 then + rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1 + elseif ps > 0 then + rot = if pt >= 0 then 2 else 1 + else + rot = if pt <= 0 then 0 else 3 + end + local function rotate(x: number, y: number, r: number): (number, number) + if r == 1 then + return y, -x + elseif r == 2 then + return -x, -y + elseif r == 3 then + return -y, x + end + return x, y + end + if not bottomLeft then + ps, pt = rotate(ps, pt, rot) + end + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + if not bottomLeft then + os_, ot = rotate(os_, ot, (4 - rot) % 4) + end + end + if not inDiamond then + os_, ot = invertDiamond(o, os_, ot) + end + data[off + 1] = os_ + center + data[off + 2] = ot + center +end +Predict.apply = apply + +-- ------------------------------------------------------------------------------------------------ schemes +-- the mesh data of a scheme: corner table, value -> corner, vertex -> value +type MeshData = { ct: CT, e2c: { number }, v2e: { number } } +-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) +type Parent = (point: number) -> (number, number, number) + +type Scheme = { + method: number, + tr: Transform, + md: MeshData?, + parent: Parent?, + -- per-scheme decoded data + crease: { { boolean } }?, + orient: { boolean }?, + flips: Reader.Bits?, + areaMode: boolean, + ver: number, +} + +local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 +Predict.GEOMETRIC_NORMAL = GEONORMAL + +-- whether the scheme needs the position attribute +function Predict.needsParent(s: Scheme): boolean + return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) +end + +-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta +function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme + local m = method + if not md then + m = DELTA + elseif tr.kind ~= 1 then + if m ~= GEONORMAL then + m = DELTA + md = nil + end + elseif m < PARALLELOGRAM or m > GEONORMAL then + m = DELTA + md = nil + end + return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 } +end + +-- DecodePredictionData +function Predict.decodeData(s: Scheme, d: D): boolean + local m = s.method + s.ver = d.ver + if m == CONSTRAINED then + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode ~= 0 then + return false + end + end + local md = s.md :: MeshData + local crease = {} + for i = 1, 4 do + local n = Reader.varint(d) + if d.bad or n > md.ct.nf * 3 then + return false + end + local flags = table.create(n, false) + if n > 0 then + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + for j = 1, n do + flags[j] = Reader.bit(bd) + end + end + crease[i] = flags + end + s.crease = crease + elseif m == TEXPORT then + local n = Reader.i32(d) + if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == TEXDEP then + local n = Reader.count(d, 0x0202) + local md = s.md :: MeshData + if d.bad or n == 0 or n > md.ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == GEONORMAL then + if not Predict.decodeTransform(s.tr, d) then + return false + end + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode > 1 then + return false + end + s.areaMode = mode == 1 + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + s.flips = bd + return true + end + return Predict.decodeTransform(s.tr, d) +end + +local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean + local ct = md.ct + local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1) + if oci == -1 then + return false + end + local c2v, v2e = ct.c2v, md.v2e + local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1 + if vo < 0 or vn < 0 or vp < 0 then + return false + end + local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0 + if eo < p and en < p and ep < p then + for c = 1, comps do + out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c]) + end + return true + end + return false +end + +local function swingRight(ct: CT, c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (ct.opp[p + 1] or -1) + return prevC(o) +end +local function swingLeft(ct: CT, c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else (ct.opp[n + 1] or -1) + return nextC(o) +end + +-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor +-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate +-- edge: predict from a neighbour); or "fail", message. +local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any) + local pnx, pny, pnz = qx - nx, qy - ny, qz - nz + local cnx, cny, cnz = tx - nx, ty - ny, tz - nz + local pnu, pnv = pu - nu, pv - nv + local B = 67108864 -- 2^26: below it every product and sum stays exact in a double + local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B + if small then + local pn2 = pnx * pnx + pny * pny + pnz * pnz + local dot = pnx * cnx + pny * cny + pnz * cnz + if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then + if pn2 == 0 then + return "fallback" + end + local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv + local dx = tx - (nx + tdiv(dot * pnx, pn2)) + local dy = ty - (ny + tdiv(dot * pny, pn2)) + local dz = tz - (nz + tdiv(dot * pnz, pn2)) + local cx2 = dx * dx + dy * dy + dz * dz + if cx2 < B then + local norm = isqrtProd(cx2, pn2) + local cxu, cxv = pnv * norm, -pnu * norm + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + if o then + return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2)) + end + return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2)) + end + end + end + -- the general case: int64 + local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div + local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number) + local xh, xl = from(ax) + local yh, yl = from(ay) + local zh, zl = from(az) + local uh, ul = from(bx) + local vh, vl = from(by) + local wh, wl = from(bz) + local h1, l1 = mul(xh, xl, uh, ul) + local h2, l2 = mul(yh, yl, vh, vl) + local h3, l3 = mul(zh, zl, wh, wl) + h1, l1 = add(h1, l1, h2, l2) + return add(h1, l1, h3, l3) + end + local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz) + if p2h == 0 and p2l == 0 then + return "fallback" + end + local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz) + local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX + local function absmax(...: number): (number, number) + local m = 0 + for _, x in { ... } do + m = math.max(m, math.abs(x)) + end + return from(m) + end + local function absI(h: number, l: number): (number, number) + if Int64.isNeg(h) then + return Int64.neg(h, l) + end + return h, l + end + -- the overflow guards (unsigned divisions as in the C++) + local nmh, nml = absmax(nu, nv) + local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l) + if Int64.ucmp(nmh, nml, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local adh, adl = absI(dh, dl) + local pmh, pml = absmax(pnu, pnv) + lh, ll = Int64.div(MAXH, MAXL, pmh, pml) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local nuh, nul = from(nu) + local nvh, nvl = from(nv) + local puh, pul = from(pnu) + local pvh, pvl = from(pnv) + local xuh, xul + do + local ah, al = mul(nuh, nul, p2h, p2l) + local bh, bl = mul(dh, dl, puh, pul) + xuh, xul = add(ah, al, bh, bl) + end + local xvh, xvl + do + local ah, al = mul(nvh, nvl, p2h, p2l) + local bh, bl = mul(dh, dl, pvh, pvl) + xvh, xvl = add(ah, al, bh, bl) + end + local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz)) + local pah, pal = from(pam) + lh, ll = Int64.div(MAXH, MAXL, pah, pal) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + -- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos + local function proj(n: number, pc: number, t: number): (number, number) + local ph, pl = from(pc) + local mh, ml = mul(dh, dl, ph, pl) + local qh, ql = div(mh, ml, p2h, p2l) + local nh, nl = from(n) + local xh, xl = add(nh, nl, qh, ql) + local th, tl = from(t) + return sub(th, tl, xh, xl) + end + local ax, axl = proj(nx, pnx, tx) + local ay, ayl = proj(ny, pny, ty) + local az, azl = proj(nz, pnz, tz) + local c2h, c2l = mul(ax, axl, ax, axl) + do + local h, l = mul(ay, ayl, ay, ayl) + c2h, c2l = add(c2h, c2l, h, l) + h, l = mul(az, azl, az, azl) + c2h, c2l = add(c2h, c2l, h, l) + end + local prh, prl = mul(c2h, c2l, p2h, p2l) + local sh, sl = Int64.isqrt(prh, prl) + -- cx_uv = (pn_uv.v, -pn_uv.u) * norm + local cuh, cul = mul(pvh, pvl, sh, sl) + local nh, nl = Int64.neg(puh, pul) + local cvh, cvl = mul(nh, nl, sh, sl) + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + local uh, ul, vh, vl + if o then + uh, ul = add(xuh, xul, cuh, cul) + vh, vl = add(xvh, xvl, cvh, cvl) + else + uh, ul = sub(xuh, xul, cuh, cul) + vh, vl = sub(xvh, xvl, cvh, cvl) + end + uh, ul = div(uh, ul, p2h, p2l) + vh, vl = div(vh, vl, p2h, p2l) + -- static_cast: the low 32 bits + return "ok", i32(ul), i32(vl) +end + +-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?) + local tr = s.tr + local m = s.method + local pred = table.create(math.max(comps, 3), 0) + if m == DELTA then + if numEntries == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + for e = 1, numEntries - 1 do + local off = e * comps + for c = 1, comps do + pred[c] = data[off - comps + c] + end + apply(tr, pred, data, off, comps) + end + return true, nil + end + local md = s.md :: MeshData + local e2c = md.e2c + local n = #e2c + if n ~= numEntries then + return false, "prediction: value count mismatch" + end + local ct = md.ct + local function previous(p: number) + local off = (p - 1) * comps + for c = 1, comps do + pred[c] = data[off + c] + end + end + if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then + if n == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + local para = table.create(comps, 0) + local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) } + local creasePos = { 0, 0, 0, 0 } + local nc = ct.nf * 3 + for p = 1, n - 1 do + local start = e2c[p + 1] + local off = p * comps + if m == PARALLELOGRAM then + if parallelogram(md, p, start, data, comps, pred) then + apply(tr, pred, data, off, comps) + else + previous(p) + apply(tr, pred, data, off, comps) + end + elseif m == MULTI then + for c = 1, comps do + pred[c] = 0 + end + local count = 0 + local ci = start + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, para) then + for c = 1, comps do + pred[c] = i32(pred[c] + para[c]) + end + count += 1 + end + ci = swingRight(ct, ci) + if ci == start then + ci = -1 + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + if count == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], count) + end + end + apply(tr, pred, data, off, comps) + else + local count = 0 + local ci = start + local first = true + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, preds[count + 1]) then + count += 1 + if count == 4 then + break + end + end + if first then + ci = swingLeft(ct, ci) + else + ci = swingRight(ct, ci) + end + if ci == start then + break + end + if ci == -1 and first then + first = false + ci = swingRight(ct, start) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local used = 0 + if count > 0 then + for c = 1, comps do + pred[c] = 0 + end + local crease = s.crease :: { { boolean } } + for i = 1, count do + local pos = creasePos[count] + 1 + creasePos[count] = pos + local flag = crease[count][pos] + if flag == nil then + return false, "prediction: crease flags run out" + end + if not flag then + used += 1 + for c = 1, comps do + pred[c] = i32(pred[c] + preds[i][c]) + end + end + end + end + if used == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], used) + end + end + apply(tr, pred, data, off, comps) + end + end + return true, nil + end + local parent = s.parent + if not parent then + return false, "prediction: no position attribute" + end + local c2v, v2e = ct.c2v, md.v2e + local function entryOf(c: number): number + local v = if c < 0 then -1 else (c2v[c + 1] or -1) + if v < 0 then + return math.huge + end + return v2e[v + 1] or 0 + end + local function posOf(e: number): (number, number, number) + local pt = points[e + 1] + if pt == nil then + return 0, 0, 0 + end + return parent(pt) + end + if m == TEXPORT or m == TEXDEP then + if comps ~= 2 then + return false, "prediction: tex coords need 2 components" + end + local orient = s.orient :: { boolean } + local no = #orient + for p = 0, n - 1 do + local ci = e2c[p + 1] + local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci)) + local done = false + if pe < p and ne < p then + local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2] + local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2] + if m == TEXPORT then + if pu == nu and pv == nv then + pred[1], pred[2] = pu, pv + done = true + else + local tx, ty, tz = posOf(p) + local nx, ny, nz = posOf(ne) + local qx, qy, qz = posOf(pe) + local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean? + if no == 0 then + return nil + end + local o = orient[no] + orient[no] = nil + no -= 1 + return o + end) + if status == "fail" then + return false, u :: any + elseif status == "ok" then + pred[1], pred[2] = u, v + done = true + end + end + else + local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv) + if fpu == fnu and fpv == fnv then + pred[1], pred[2] = truncInt(fpu), truncInt(fpv) + done = true + else + local tx: number, ty: number, tz: number = posOf(p) + local nx: number, ny: number, nz: number = posOf(ne) + local qx: number, qy: number, qz: number = posOf(pe) + tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz) + qx, qy, qz = fround(qx), fround(qy), fround(qz) + local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz) + local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz) + local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz)) + local sv, tv = 0, 0 + if s.ver < 0x0102 or pn2 > 0 then + local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz)) + sv = fround(dot / pn2) + local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv)) + local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez)) + tv = fround(math.sqrt(fround(e2 / pn2))) + end + local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv) + local pnus = fround(fround(pnu * sv) + fnu) + local pnut = fround(pnu * tv) + local pnvs = fround(fround(pnv * sv) + fnv) + local pnvt = fround(pnv * tv) + if no == 0 then + return false, "prediction: orientations run out" + end + local o = orient[no] + orient[no] = nil + no -= 1 + local u: number, v: number = 0, 0 + if o then + u = fround(pnus - pnvt) + v = fround(pnvs + pnut) + else + u = fround(pnus + pnvt) + v = fround(pnvs - pnut) + end + local function toInt(x: number): number + local r = math.floor(x + 0.5) + if r ~= r or r > 2147483647 or r < -2147483648 then + return -2147483648 + end + return r + end + pred[1] = toInt(u) + pred[2] = toInt(v) + done = true + end + end + end + if not done then + local off = -1 + if pe < p then + off = pe * 2 + end + if ne < p then + off = ne * 2 + elseif p > 0 then + off = (p - 1) * 2 + else + off = -1 + end + if off < 0 then + pred[1], pred[2] = 0, 0 + else + pred[1], pred[2] = data[off + 1], data[off + 2] + end + end + apply(tr, pred, data, p * 2, 2) + end + return true, nil + end + -- geometric normal + local o = tr.oct + local flips = s.flips + if not o or not flips or comps ~= 2 then + return false, "prediction: bad geometric normal setup" + end + local nc = ct.nf * 3 + for p = 0, n - 1 do + local ci = e2c[p + 1] + local cx, cy, cz = posOf(entryOf(ci)) + local sx, sy, sz = 0, 0, 0 + -- VertexCornersIterator from ci: swing left, then right from the start + local c = ci + local left = true + local guard = 0 + while c ~= -1 do + local cn, cp + if s.areaMode then + cn, cp = nextC(c), prevC(c) + else + cn, cp = nextC(ci), prevC(ci) + end + local ax, ay, az = posOf(entryOf(cn)) + local bx, by, bz = posOf(entryOf(cp)) + ax, ay, az = ax - cx, ay - cy, az - cz + bx, by, bz = bx - cx, by - cy, bz - cz + sx += ay * bz - az * by + sy += az * bx - ax * bz + sz += ax * by - ay * bx + if left then + c = swingLeft(ct, c) + if c == -1 then + c = swingRight(ct, ci) + left = false + elseif c == ci then + c = -1 + end + else + c = swingRight(ct, c) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local upper = 2 ^ 29 + local sum = math.abs(sx) + math.abs(sy) + math.abs(sz) + if sum > upper then + local q = sum // upper + sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q) + end + sx, sy, sz = i32(sx), i32(sy), i32(sz) + sx, sy, sz = canonicalizeVector(o, sx, sy, sz) + if Reader.bit(flips) then + sx, sy, sz = -sx, -sy, -sz + end + pred[1], pred[2] = intVectorToOct(o, sx, sy, sz) + apply(tr, pred, data, p * 2, 2) + end + return true, nil +end + +return Predict +end +__FILES["codecs/model/Draco/Reader"] = function() + +-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and +-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit +-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, +-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, +-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). +-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +local Reader = {} + +local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 +local band, rshift = bit32.band, bit32.rshift + +type D = { + b: buffer, + pos: number, -- absolute offset in b + limit: number, -- absolute end + ver: number, -- major * 256 + minor + bad: string?, + bitMode: boolean, + bitStart: number, -- absolute byte where the bit run starts + bitOff: number, -- bits consumed +} + +function Reader.new(b: buffer, pos: number, limit: number, ver: number): D + return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 } +end + +-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards) +function Reader.copy(d: D): D + return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff } +end + +function Reader.fail(d: D, msg: string): number + if not d.bad then + d.bad = msg + end + return 0 +end + +function Reader.remaining(d: D): number + return d.limit - d.pos +end + +function Reader.u8(d: D): number + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 1 + return readu8(d.b, p) +end + +function Reader.i8(d: D): number + local v = Reader.u8(d) + return if v >= 128 then v - 256 else v +end + +function Reader.u16(d: D): number + local p = d.pos + if p + 2 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 2 + return readu16(d.b, p) +end + +function Reader.u32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readu32(d.b, p) +end + +function Reader.i32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readi32(d.b, p) +end + +-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) +function Reader.u64(d: D): number + local p = d.pos + if p + 8 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 8 + return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296 +end + +function Reader.f32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readf32(d.b, p) +end + +-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts +function Reader.varint(d: D, wide: boolean?): number + local maxBytes = if wide then 10 else 5 + local v, mul = 0, 1 + for _ = 1, maxBytes do + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated varint") + end + local c = readu8(d.b, p) + d.pos = p + 1 + v += band(c, 127) * mul + if c < 128 then + if not wide then + v %= 4294967296 + end + return v + end + mul *= 128 + end + return Reader.fail(d, "varint too long") +end + +-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on +function Reader.count(d: D, fixedBefore: number): number + if d.ver < fixedBefore then + return Reader.u32(d) + end + return Reader.varint(d) +end + +-- ------------------------------------------------------------------------------------------------ bit runs +-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end +-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. +function Reader.startBits(d: D, decodeSize: boolean): number + local size = 0 + if decodeSize then + if d.ver < 0x0202 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + end + d.bitMode = true + d.bitStart = d.pos + d.bitOff = 0 + return size +end + +function Reader.bits(d: D, n: number): number + if not d.bitMode then + return Reader.fail(d, "bit decoder not active") + end + if n > 32 then + return Reader.fail(d, "bit run over 32 bits") + end + local b, start, limit = d.b, d.bitStart, d.limit + local off = d.bitOff + local v, mul = 0, 1 + for _ = 1, n do + local byte = start + rshift(off, 3) + if byte < limit then + if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then + v += mul + end + off += 1 + end + mul *= 2 + end + d.bitOff = off + return v +end + +function Reader.endBits(d: D) + d.bitMode = false + d.pos = d.bitStart + (d.bitOff + 7) // 8 +end + +-- ------------------------------------------------------------------------------------------------ rANS symbols +-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 +local function precisionBits(bitLength: number): number + local p = (3 * bitLength) // 2 + return if p < 12 then 12 elseif p > 20 then 20 else p +end + +type Rans = { + b: buffer, + base: number, -- absolute start of the coded bytes + off: number, -- bytes left (read backwards from base + off) + state: number, + lBase: number, + precBits: number, + lut: { number }, -- rem + 1 -> symbol + 1 + prob: { number }, + cum: { number }, + numSymbols: number, +} + +-- RAnsSymbolDecoder::Create: the probability table +local function ransCreate(d: D, precBits: number): Rans? + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil + end + if numSymbols // 64 > Reader.remaining(d) then + Reader.fail(d, "rans: too many symbols") + return nil + end + local prec = 2 ^ precBits + local prob = table.create(numSymbols, 0) + local i = 0 + while i < numSymbols do + local data = Reader.u8(d) + if d.bad then + return nil + end + local token = band(data, 3) + if token == 3 then + local offset = rshift(data, 2) + if i + offset >= numSymbols then + Reader.fail(d, "rans: bad zero run") + return nil + end + for j = 0, offset do + prob[i + j + 1] = 0 + end + i += offset + 1 + else + local p = rshift(data, 2) + for k = 1, token do + p += Reader.u8(d) * 2 ^ (8 * k - 2) + end + if d.bad then + return nil + end + prob[i + 1] = p + i += 1 + end + end + local lut: { number } = {} + local cum = table.create(numSymbols, 0) + if numSymbols > 0 then + lut = table.create(prec, 0) + local c, act = 0, 0 + for s = 1, numSymbols do + cum[s] = c + c += prob[s] + if c > prec then + Reader.fail(d, "rans: probabilities over the precision") + return nil + end + for j = act + 1, c do + lut[j] = s + end + act = c + end + if c ~= prec then + Reader.fail(d, "rans: probabilities do not sum to the precision") + return nil + end + end + return { + b = d.b, + base = 0, + off = 0, + state = 0, + lBase = prec * 4, + precBits = precBits, + lut = lut, + prob = prob, + cum = cum, + numSymbols = numSymbols, + } +end + +-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes +local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?) + if size < 1 then + return nil, nil + end + local x = rshift(readu8(b, base + size - 1), 6) + local off: number, state: number = 0, 0 + if x == 0 then + off = size - 1 + state = band(readu8(b, base + size - 1), 0x3F) + elseif x == 1 then + if size < 2 then + return nil, nil + end + off = size - 2 + state = band(readu16(b, base + size - 2), 0x3FFF) + elseif x == 2 then + if size < 3 then + return nil, nil + end + off = size - 3 + state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536 + else + if not allow4 or size < 4 then + return nil, nil + end + off = size - 4 + state = band(readu32(b, base + size - 4), 0x3FFFFFFF) + end + state += lBase + if state >= lBase * 256 then + return nil, nil + end + return off, state +end + +-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes +local function ransStart(d: D, r: Rans): boolean + local size + if d.ver < 0x0200 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + if d.bad then + return false + end + if size > Reader.remaining(d) then + Reader.fail(d, "rans: data past the end") + return false + end + local off, state = ansInit(d.b, d.pos, size, r.lBase, true) + if not off then + Reader.fail(d, "rans: bad initial state") + return false + end + r.base, r.off, r.state = d.pos, off, state :: number + d.pos += size + return true +end + +-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) +local function ransRead(r: Rans, n: number, out: { number }, first: number) + local b, base, off, state = r.b, r.base, r.off, r.state + local lBase, bits = r.lBase, r.precBits + local mask = 2 ^ bits - 1 + local lut, prob, cum = r.lut, r.prob, r.cum + for i = first, first + n - 1 do + while state < lBase and off > 0 do + off -= 1 + state = state * 256 + readu8(b, base + off) + end + local quo, rem = rshift(state, bits), band(state, mask) + local s = lut[rem + 1] + state = quo * prob[s] + rem - cum[s] + out[i] = s - 1 + end + r.off, r.state = off, state +end + +local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean + local tag = ransCreate(d, precisionBits(5)) + if not tag or not ransStart(d, tag) then + return false + end + if n > 0 and tag.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + Reader.startBits(d, false) + local len = { 0 } + local k = 1 + local i = 0 + while i < n do + ransRead(tag, 1, len, 1) + local bitLength = len[1] + for _ = 1, comps do + if k > n then + break + end + out[k] = Reader.bits(d, bitLength) + k += 1 + end + if d.bad then + return false + end + i += comps + end + Reader.endBits(d) + return true +end + +local function decodeRaw(d: D, n: number, out: { number }): boolean + local maxBitLength = Reader.u8(d) + if d.bad then + return false + end + if maxBitLength < 1 or maxBitLength > 18 then + Reader.fail(d, "rans: bad symbol bit length") + return false + end + local r = ransCreate(d, precisionBits(maxBitLength)) + if not r then + return false + end + if n > 0 and r.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + if not ransStart(d, r) then + return false + end + ransRead(r, n, out, 1) + return true +end + +-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +function Reader.symbols(d: D, n: number, comps: number): { number }? + local out = table.create(n, 0) + if n == 0 then + return out + end + local scheme = Reader.u8(d) + if d.bad then + return nil + end + local ok + if scheme == 0 then + ok = decodeTagged(d, n, math.max(comps, 1), out) + elseif scheme == 1 then + ok = decodeRaw(d, n, out) + else + Reader.fail(d, "rans: unknown symbol coding scheme") + ok = false + end + return if ok then out else nil +end + +-- ------------------------------------------------------------------------------------------------ binary rANS +type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number } + +-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes +function Reader.bitDecoder(d: D): Bits? + local p0 = Reader.u8(d) + local size = Reader.count(d, 0x0202) + if d.bad then + return nil + end + if size > Reader.remaining(d) then + Reader.fail(d, "rabs: data past the end") + return nil + end + local off, state = ansInit(d.b, d.pos, size, 4096, false) + if not off then + Reader.fail(d, "rabs: bad initial state") + return nil + end + local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 } + d.pos += size + return bd +end + +-- rabs_desc_read: one bit (true / false) +function Reader.bit(bd: Bits): boolean + local state, off = bd.state, bd.off + if state < 4096 and off > 0 then + off -= 1 + state = state * 256 + readu8(bd.b, bd.base + off) + bd.off = off + end + local quot, rem = rshift(state, 8), band(state, 255) + local p = bd.p + local xn = quot * p + if rem < p then + bd.state = xn + rem + return true + end + bd.state = state - xn - p + return false +end + +return Reader +end +__FILES["codecs/model/Mat4"] = function() + +-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 +-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a +-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the +-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). +-- +-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S +-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) +-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul +-- local inv = Mat4.inverse(m) -- affine inverse | nil +-- local x, y, z = Mat4.point(m, px, py, pz) +local Types = __include("Types") + +local Mat4 = {} + +type M4 = { number } + +local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad + +function Mat4.identity(): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- mul(a, b) -> a * b +Mat4.mul = Types.Scene.mul + +function Mat4.translation(x: number, y: number, z: number): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function Mat4.scaling(x: number, y: number, z: number): M4 + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) +function Mat4.rotation(axis: number, degrees: number): M4 + local a = rad(degrees) + local c, s = cos(a), sin(a) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +local AXIS = { x = 1, y = 2, z = 3 } +-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees +function Mat4.euler(x: number, y: number, z: number, order: string?): M4 + local o = order or "xyz" + local deg = { x = x, y = y, z = z } + local m = Mat4.identity() + for i = 1, 3 do + local a = string.sub(o, i, i) + m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m) + end + return m +end + +-- axisAngle(x, y, z, degrees) -> quaternion +function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } + local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local h = rad(degrees) / 2 + local s = sin(h) / l + return { x * s, y * s, z * s, cos(h) } +end + +-- fromQuat(q) -> the rotation matrix of a quaternion +function Mat4.fromQuat(q: { number }): M4 + local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) +function Mat4.quat(m: M4): { number } + local m00, m01, m02 = m[1], m[5], m[9] + local m10, m11, m12 = m[2], m[6], m[10] + local m20, m21, m22 = m[3], m[7], m[11] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = sqrt(tr + 1) * 2 + w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 + w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 + w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 + w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local n = sqrt(x * x + y * y + z * z + w * w) + if n == 0 or n ~= n then + return { 0, 0, 0, 1 } + end + return { x / n, y / n, z / n, w / n } +end + +-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion +function Mat4.eulerXYZ(q: { number }): { number } + local m = Mat4.fromQuat(q) + local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) + local y = math.asin(sy) + local x, z + if abs(sy) < 0.9999999 then + x = math.atan2(m[7], m[11]) + z = math.atan2(m[2], m[1]) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return { math.deg(x), math.deg(y), math.deg(z) } +end + +-- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4 + local m = if r then Mat4.fromQuat(r) else Mat4.identity() + if s then + for k = 0, 2 do + m[k * 4 + 1] *= s[k + 1] + m[k * 4 + 2] *= s[k + 1] + m[k * 4 + 3] *= s[k + 1] + end + end + if t then + m[13], m[14], m[15] = t[1], t[2], t[3] + end + return m +end + +local function det3(m: M4): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +local function split(m: M4, strict: boolean): ({ number }?, { number }?, { number }?) + if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then + return nil, nil, nil + end + local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then + return nil, nil, nil + end + if det3(m) < 0 then + sx = -sx + end + local ix = if sx ~= 0 then 1 / sx else 0 + local iy = if sy ~= 0 then 1 / sy else 0 + local iz = if sz ~= 0 then 1 / sz else 0 + local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } + if strict then + local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7] + local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11] + local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11] + if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then + return nil, nil, nil + end + end + return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } +end + +-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +function Mat4.decompose(m: M4): ({ number }, { number }, { number }) + local t, r, s = split(m, false) + return t :: { number }, r :: { number }, s :: { number } +end + +-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, +-- a zero scale) +function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) + return split(m, true) +end + +-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular +function Mat4.inverse(m: M4): M4? + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if det == 0 or det ~= det then + return nil + end + local k = 1 / det + local r = { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } + local tx, ty, tz = m[13], m[14], m[15] + r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) + r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) + r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) + return r +end + +-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular +function Mat4.inverseFull(m: M4): M4? + local a = m + local inv = table.create(16, 0) + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k] /= det + end + return inv +end + +-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) +function Mat4.transpose3(m: M4): M4 + return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } +end + +-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) +function Mat4.fromRows(v: { number }, at: number?): M4 + local o = (at or 1) - 1 + local m = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) + end + end + return m +end + +-- toRows(m) -> the 16 values row-major +function Mat4.toRows(m: M4): { number } + local v = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + v[r * 4 + c + 1] = m[c * 4 + r + 1] + end + end + return v +end + +-- point(m, x, y, z) -> m * (x, y, z, 1) +function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) + return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) +function Mat4.normalMatrix(m: M4): M4 + local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) + if not inv then + return Mat4.identity() + end + return Mat4.transpose3(inv) +end + +return Mat4 +end +__FILES["codecs/model/MeshFlatten"] = function() + +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), +-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring +-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, +-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one +-- (ops/MeshOps.merge is the editing-side equivalent). +-- Never throws: bad input returns nil, message. +local Types = __include("Types") + +local Flatten = {} + +local readf32, readf64 = buffer.readf32, buffer.readf64 +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32 + +local SIZE = Types.COMPONENT_SIZE +-- normalized integer types: their scale (raw / scale = the normalized value) +local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } + +type Attr = { + type: string, -- the accessor type shared by every part ("f32" when the parts disagree) + components: number, + raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers + values: { number }, -- count * components +} +type PartInfo = { + prim: Types.Primitive, + mesh: Types.Mesh?, + node: Types.Node?, + firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh + vertexCount: number, + firstFace: number, -- 0-based offset of the part's faces + faceCount: number, + identity: boolean, -- no transform was applied +} +type Merged = { + count: number, -- vertices + attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read + sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud) + corners: { number }, -- 0-based vertex indices, face after face + parts: { PartInfo }, +} + +-- ------------------------------------------------------------------------------------------------ accessors +-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg +function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?) + if type(acc) ~= "table" or type(acc.data) ~= "buffer" then + return nil, "accessor without a data buffer" + end + local t, comps, count = acc.type, acc.components, acc.count + local size = SIZE[t] + if size == nil then + return nil, "unknown accessor type " .. tostring(t) + end + if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then + return nil, "bad accessor components / count" + end + local n = count * comps + local d: buffer = acc.data + if buffer.len(d) < n * size then + return nil, "accessor data shorter than count * components" + end + local out = table.create(n) :: { number } + if t == "f32" then + for i = 0, n - 1 do + out[i + 1] = readf32(d, i * 4) + end + elseif t == "f64" then + for i = 0, n - 1 do + out[i + 1] = readf64(d, i * 8) + end + elseif t == "u8" or t == "unorm8" then + for i = 0, n - 1 do + out[i + 1] = readu8(d, i) + end + elseif t == "u16" or t == "unorm16" then + for i = 0, n - 1 do + out[i + 1] = readu16(d, i * 2) + end + elseif t == "u32" then + for i = 0, n - 1 do + out[i + 1] = readu32(d, i * 4) + end + elseif t == "i8" or t == "snorm8" then + for i = 0, n - 1 do + out[i + 1] = readi8(d, i) + end + elseif t == "i16" or t == "snorm16" then + for i = 0, n - 1 do + out[i + 1] = readi16(d, i * 2) + end + else -- i32 + for i = 0, n - 1 do + out[i + 1] = readi32(d, i * 4) + end + end + local scale = NORM[t] + if scale and not raw then + local signed = t == "snorm8" or t == "snorm16" + for i = 1, n do + local v = out[i] / scale + out[i] = if signed and v < -1 then -1 else v + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + +local mul = Types.Scene.mul -- column-major 4x4 product a * b + +local function numList(v: any, n: number): boolean + if type(v) ~= "table" then + return false + end + for i = 1, n do + if type(v[i]) ~= "number" then + return false + end + end + return true +end + +-- a node's local matrix (nil: none), or nil, message +local function localMatrix(node: any): ({ number }?, string?) + if node.matrix ~= nil then + if not numList(node.matrix, 16) then + return nil, "node matrix is not 16 numbers" + end + local m = table.create(16) :: { number } + for i = 1, 16 do + m[i] = node.matrix[i] + end + return m, nil + end + local t, q, s = node.translation, node.rotation, node.scale + if t == nil and q == nil and s == nil then + return nil, nil + end + if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then + return nil, "bad node translation / rotation / scale" + end + local x, y, z, w = 0, 0, 0, 1 + if q then + x, y, z, w = q[1], q[2], q[3], q[4] + end + local sx, sy, sz = 1, 1, 1 + if s then + sx, sy, sz = s[1], s[2], s[3] + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1], t[2], t[3] + end + return { + (1 - 2 * (y * y + z * z)) * sx, + (2 * (x * y + z * w)) * sx, + (2 * (x * z - y * w)) * sx, + 0, + (2 * (x * y - z * w)) * sy, + (1 - 2 * (x * x + z * z)) * sy, + (2 * (y * z + x * w)) * sy, + 0, + (2 * (x * z + y * w)) * sz, + (2 * (y * z - x * w)) * sz, + (1 - 2 * (x * x + y * y)) * sz, + 0, + tx, + ty, + tz, + 1, + }, + nil +end + +local function isIdentity(m: { number }): boolean + for i = 1, 16 do + if m[i] ~= IDENTITY[i] then + return false + end + end + return true +end + +type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? } + +-- the primitive instances of a scene in traversal order, or nil, message +local function instances(scene: any): ({ Instance }?, string?) + local out: { Instance } = {} + local nodes, meshes = scene.nodes, scene.meshes + if type(nodes) ~= "table" or type(meshes) ~= "table" then + return nil, "scene without nodes / meshes tables" + end + local function addMesh(mi: any, node: Types.Node?, m: { number }?): string? + local mesh = meshes[mi] + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return "node refers to a missing mesh " .. tostring(mi) + end + for _, prim in mesh.primitives do + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return "bad primitive" + end + table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m }) + end + return nil + end + local visiting: { [number]: boolean } = {} + local function visit(ni: any, parent: { number }?, depth: number): string? + local node = nodes[ni] + if type(node) ~= "table" then + return "missing node " .. tostring(ni) + end + if depth > 256 or visiting[ni] then + return "node hierarchy is cyclic or too deep" + end + visiting[ni] = true + local m, merr = localMatrix(node) + if merr then + return merr + end + local world = if m and parent then mul(parent, m) elseif m then m else parent + if node.mesh ~= nil then + local e = addMesh(node.mesh, node, world) + if e then + return e + end + end + if type(node.children) == "table" then + for _, c in node.children do + local e = visit(c, world, depth + 1) + if e then + return e + end + end + end + visiting[ni] = nil + return nil + end + local roots = scene.roots + if type(roots) == "table" and #roots > 0 then + for _, ri in roots do + local e = visit(ri, nil, 0) + if e then + return nil, e + end + end + elseif #nodes > 0 then + local isChild: { [number]: boolean } = {} + for _, n in nodes do + if type(n) == "table" and type(n.children) == "table" then + for _, c in n.children do + isChild[c] = true + end + end + end + for i = 1, #nodes do + if not isChild[i] then + local e = visit(i, nil, 0) + if e then + return nil, e + end + end + end + else + for i = 1, #meshes do + local e = addMesh(i, nil, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ faces +-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message +local function faces(prim: any, nv: number): (any, any, string?) + local mode = prim.mode or "triangles" + if mode == "points" then + return "points", nil, nil + elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then + return "skip", nil, nil + end + local idx: { number } + if prim.indices ~= nil then + local v, err = Flatten.numbers(prim.indices, true) + if not v then + return nil, nil, "indices: " .. tostring(err) + end + idx = v + else + idx = table.create(nv) :: { number } + for i = 1, nv do + idx[i] = i - 1 + end + end + for i = 1, #idx do + local v = idx[i] + if v < 0 or v >= nv or v % 1 ~= 0 then + return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv) + end + end + if mode == "triangles" then + local n = #idx - #idx % 3 + if n ~= #idx then + local c = table.create(n) :: { number } + table.move(idx, 1, n, 1, c) + idx = c + end + return false, idx, nil + elseif mode == "polygons" then + if prim.faces == nil then + return nil, nil, "polygons primitive without faces" + end + local sizes, err = Flatten.numbers(prim.faces, true) + if not sizes then + return nil, nil, "faces: " .. tostring(err) + end + local total = 0 + for i = 1, #sizes do + local s = sizes[i] + if s < 0 or s % 1 ~= 0 then + return nil, nil, "bad face size" + end + total += s + end + if total ~= #idx then + return nil, nil, "face sizes do not add up to the index count" + end + return sizes, idx, nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local c = {} + for i = 3, #idx do + if mode == "triangle_fan" then + table.insert(c, idx[1]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + elseif i % 2 == 1 then + table.insert(c, idx[i - 2]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + else + table.insert(c, idx[i - 1]) + table.insert(c, idx[i - 2]) + table.insert(c, idx[i]) + end + end + return false, c, nil + end + return nil, nil, "unknown primitive mode " .. tostring(mode) +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 +local function fill(name: string, t: string, raw: boolean): number + if string.sub(name, 1, 6) ~= "COLOR_" then + return 0 + end + return if raw and NORM[t] then NORM[t] else 1 +end + +local function f32(v: number): number + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.readf32(b, 0) +end + +-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). +-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). +function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?) + if type(scene) ~= "table" then + return nil, "not a scene" + end + local list, lerr = instances(scene) + if not list then + return nil, lerr + end + local triangulate = opts and opts.triangulate or false + -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count + local types: { [string]: string } = {} + local comps: { [string]: number } = {} + local used: { Instance } = {} + for _, inst in list do + local mode = inst.prim.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then + local pos = inst.prim.attributes.POSITION + if type(pos) ~= "table" then + return nil, "primitive without POSITION" + end + table.insert(used, inst) + for name, acc in inst.prim.attributes do + if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then + local t = acc.type + if types[name] == nil then + types[name] = t + elseif types[name] ~= t then + types[name] = "f32" + end + comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0) + end + end + end + end + if (comps.POSITION or 3) < 3 then + return nil, "POSITION needs 3 components" + end + local attrs: { [string]: Attr } = {} + for name, t in types do + local raw = NORM[t] ~= nil + if name == "POSITION" or name == "NORMAL" then + raw = false + end + attrs[name] = { type = if name == "POSITION" or name == "NORMAL" then "f32" else t, components = if name == "POSITION" or name == "NORMAL" then 3 else comps[name], raw = raw, values = {} } + end + local merged: Merged = { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } + local sizes: { number } = {} + local anyFaces = false + local corners = merged.corners + for _, inst in used do + local prim: any = inst.prim + local posAcc = prim.attributes.POSITION + local nv = tonumber(posAcc.count) or 0 + local m = inst.matrix + local identity = m == nil or isIdentity(m :: { number }) + local info: PartInfo = { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } + for name, a in attrs do + local acc = prim.attributes[name] + local dst = a.values + local n0 = #dst + local ac = a.components + if acc == nil then + local f = fill(name, a.type, a.raw) + for i = 1, nv * ac do + dst[n0 + i] = f + end + else + if acc.count ~= nv then + return nil, name .. " count differs from POSITION" + end + local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type) + if not vals then + return nil, name .. ": " .. tostring(err) + end + local sc = acc.components + if a.raw and acc.type ~= a.type then + return nil, name .. ": mixed accessor types" + end + local f = fill(name, a.type, a.raw) + if name == "POSITION" and not identity then + local mm = m :: { number } + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13]) + dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14]) + dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15]) + end + elseif name == "NORMAL" and not identity and sc >= 3 then + local mm = m :: { number } + -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction + local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11] + local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1 + local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1 + local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 + local sgn = if a1 * n11 + a2 * n12 + a3 * n13 < 0 then -1 else 1 + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n + local nx = n11 * x + n21 * y + n31 * z + local ny = n12 * x + n22 * y + n32 * z + local nz = n13 * x + n23 * y + n33 * z + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l + end + dst[n0 + i * 3 + 1] = f32(nx) + dst[n0 + i * 3 + 2] = f32(ny) + dst[n0 + i * 3 + 3] = f32(nz) + end + else + for i = 0, nv - 1 do + for c = 1, ac do + dst[n0 + i * ac + c] = if c <= sc then vals[i * sc + c] else f + end + end + end + end + end + local fs, cs, ferr = faces(prim, nv) + if ferr then + return nil, ferr + end + local flip = false + if not identity then + local mm = m :: { number } + local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6]) + flip = det < 0 + end + if fs ~= "points" and fs ~= "skip" then + anyFaces = true + local base = merged.count + local cl: { number } = cs + local p = 0 + local nf = if fs then #fs else #cl // 3 + for f = 1, nf do + local s = if fs then fs[f] else 3 + if triangulate then + for k = 2, s - 1 do + table.insert(sizes, 3) + local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1] + if flip then + b, c = c, b + end + table.insert(corners, base + a) + table.insert(corners, base + b) + table.insert(corners, base + c) + end + else + table.insert(sizes, s) + if flip then + table.insert(corners, base + cl[p + 1]) + for k = s, 2, -1 do + table.insert(corners, base + cl[p + k]) + end + else + for k = 1, s do + table.insert(corners, base + cl[p + k]) + end + end + end + p += s + end + end + info.faceCount = #sizes - info.firstFace + merged.count += nv + table.insert(merged.parts, info) + end + merged.sizes = if anyFaces then sizes else nil + return merged, nil +end + +return Flatten +end +__FILES["codecs/model/Minecraft"] = function() + +-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. +-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default +-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids +-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block +-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / +-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. +-- +-- local Mc = require("@rosetta/codecs/model/Minecraft") +-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } +-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air +-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks +-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Colors = __include("codecs/model/Minecraft/Colors") +local Legacy = __include("codecs/model/Minecraft/Legacy") +local Packed = __include("codecs/model/Minecraft/Packed") + +local Minecraft = {} + +Minecraft.Packed = Packed +Minecraft.Legacy = Legacy + +-- ------------------------------------------------------------------------------------------------ block states +-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order +function Minecraft.parseState(s: string): (string, { { string } }) + local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") + local n = name or "" + if n ~= "" and not string.find(n, ":", 1, true) then + n = "minecraft:" .. n + end + local props = {} + local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$") + if body then + for pair in string.gmatch(body, "[^,]+") do + local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if k then + table.insert(props, { k, v :: string }) + end + end + end + return n, props +end + +-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) +function Minecraft.stateString(name: string, props: { any }?): string + if not props or next(props) == nil then + return name + end + local parts = {} + if props[1] ~= nil then + for _, kv in props do + table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) + end + else + for _, k in Types.keys(props) do + table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k])) + end + end + return name .. "[" .. table.concat(parts, ",") .. "]" +end + +-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) +function Minecraft.stateFromNbt(c: any): string? + if type(c) ~= "table" or type(c.Name) ~= "string" then + return nil + end + local props = {} + if type(c.Properties) == "table" then + for _, k in Types.keys(c.Properties) do + local v = c.Properties[k] + table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) }) + end + end + return Minecraft.stateString(c.Name, props) +end + +-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) +function Minecraft.stateToNbt(s: string): { [string]: any } + local name, props = Minecraft.parseState(s) + local c = Types.object({ Name = name }, { "Name" }) + if #props > 0 then + local p, keys = {}, {} + for _, kv in props do + p[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + Types.set(c, "Properties", Types.object(p, keys)) + end + return c +end + +-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") +function Minecraft.baseName(s: string): string + local name = string.match(s, "^%s*([^%[%s]*)") or "" + return string.match(name, ":(.*)$") or name +end + +local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } +-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) +function Minecraft.isAir(s: string): boolean + return AIR[Minecraft.baseName(s)] == true +end + +-- ------------------------------------------------------------------------------------------------ colours +local function hex(h: string): { number } + local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } + if #h >= 8 then + c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 + end + return c +end +local function list(s: string): { { number } } + local out = {} + for h in string.gmatch(s, "%x+") do + table.insert(out, hex(h)) + end + return out +end + +local EXACT: { [string]: { number } } = {} +for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do + EXACT[name :: string] = hex(h :: string) +end +local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) +local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) +-- longest prefixes first, so light_blue wins over blue and dark_oak over oak +local function byLength(names: { string }): { { any } } + local out: { { any } } = {} + for i, n in names do + table.insert(out, { n, i }) + end + table.sort(out, function(a: { any }, b: { any }): boolean + return #(a[1] :: string) > #(b[1] :: string) + end) + return out +end +local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) +local SUFFIXES = { + "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", + "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", +} +local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local FALLBACK = hex("909090") + +local function mix(c: { number }, w: { number }, t: number): { number } + return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } +end + +local resolve: (string, number) -> { number }? + +local function family(n: string): { number }? + for _, d in DYES do + local pre = d[1] .. "_" + if string.sub(n, 1, #pre) == pre then + local rest = string.sub(n, #pre + 1) + local i = d[2] + if rest == "concrete" then + return CONCRETE[i] + elseif rest == "concrete_powder" then + return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) + elseif rest == "terracotta" then + return TERRACOTTA[i] + elseif string.find(rest, "glass", 1, true) then + local c = table.clone(WOOL[i]) + c[4] = 0x80 + return c + end + return WOOL[i] + end + end + local stripped = string.match(n, "^stripped_(.*)$") + for _, w in WOODS do + local pre = w[1] .. "_" + local m = stripped or n + if string.sub(m, 1, #pre) == pre then + local rest = string.sub(m, #pre + 1) + local i = w[2] + if stripped then + return PLANKS[i] + elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then + return BARK[i] + elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then + return LEAVES[i] + elseif rest == "block" and w[1] == "bamboo" then + return EXACT.bamboo_block + end + return PLANKS[i] + end + end + return nil +end + +local function keywords(n: string): { number }? + if string.find(n, "copper", 1, true) then + return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper + elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper + elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper + else EXACT.copper_block + elseif string.find(n, "coral", 1, true) then + if string.find(n, "dead", 1, true) then + return hex("857e79") + end + for k, c in CORAL do + if string.find(n, k, 1, true) then + return c + end + end + elseif string.find(n, "_ore$") then + return if string.find(n, "deepslate", 1, true) then EXACT.deepslate + elseif string.find(n, "nether", 1, true) then EXACT.netherrack + else EXACT.stone + end + for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do + if string.find(n, k, 1, true) then + local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k] + return EXACT[alias] + end + end + return nil +end + +resolve = function(n: string, depth: number): { number }? + if depth > 4 then + return nil + end + local c = EXACT[n] + if c then + return c + end + local renamed = Legacy.RENAMED[n] + if renamed then + return resolve(renamed, depth + 1) + end + for _, p in PREFIXES do + if string.sub(n, 1, #p) == p then + return resolve(string.sub(n, #p + 1), depth + 1) + end + end + c = family(n) + if c then + return c + end + for _, sfx in SUFFIXES do + if #n > #sfx and string.sub(n, -#sfx) == sfx then + local base = string.sub(n, 1, #n - #sfx) + for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do + local fc = EXACT[form] or family(form) + if fc then + return fc + end + end + return resolve(base, depth + 1) + end + end + return keywords(n) +end + +local cache: { [string]: { number } | false } = {} +-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords +function Minecraft.color(s: string): { number }? + local hit = cache[s] + if hit ~= nil then + return hit or nil + end + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local res: { number }? = nil + if not AIR[n] then + -- pre-1.13 names whose data value picks the variant + local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) + if variants then + local data = 0 + for _, kv in props do + if kv[1] == "data" then + data = tonumber(kv[2]) or 0 + end + end + local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] + res = resolve(v, 0) + end + res = res or resolve(n, 0) or FALLBACK + end + cache[s] = res or false + return res +end + +-- ------------------------------------------------------------------------------------------------ legacy ids +local REVERSE: { [string]: { number } }? = nil +local function reverse(): { [string]: { number } } + if REVERSE then + return REVERSE + end + local r: { [string]: { number } } = {} + local byName: { [string]: number } = {} + for i, n in Legacy.NAMES do + if n ~= "-" then + byName[n] = i - 1 + end + end + for legacy, modern in Legacy.RENAMED do + r[modern] = { byName[legacy], 0 } + end + for legacy, variants in Legacy.VARIANTS do + for d, v in variants do + if r[v] == nil then + r[v] = { byName[legacy], d - 1 } + end + end + end + for n, id in byName do + if r[n] == nil then + r[n] = { id, 0 } + end + end + REVERSE = r + return r +end + +-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the +-- rest of the data value kept as [data=N] so legacyId gives it back exactly) +function Minecraft.legacyState(id: number, data: number): string + local n = Legacy.NAMES[id + 1] + if n == nil or n == "-" then + return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "") + end + local variants = Legacy.VARIANTS[n] + if variants then + local idx = data % (Legacy.MASK[n] or 16) + local v = variants[idx + 1] + if v then + return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "") + end + end + return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") +end + +-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their +-- properties are not converted to data values) +function Minecraft.legacyId(s: string): (number?, number?) + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local id: number?, data = nil, 0 + local lid = string.match(n, "^legacy_(%d+)$") + if lid then + id = tonumber(lid) + else + local e = reverse()[n] + if e then + id, data = e[1], e[2] + end + end + if id == nil then + return nil, nil + end + for _, kv in props do + if kv[1] == "data" then + data = (tonumber(kv[2]) or data) % 16 + end + end + return id, data +end + +-- ------------------------------------------------------------------------------------------------ voxels +-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, +-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into +-- the nearest one) +function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels + local v = Types.Voxels.new(sx, sy, sz) + local lut = buffer.create(#states) + local slots: { [string]: number } = {} + local used = 0 + for i, s in states do + local c = Minecraft.color(s) + local slot = 0 + if c then + local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) + slot = slots[key] + if not slot then + if used < 255 then + used += 1 + slot = used + v.palette[slot] = { c[1], c[2], c[3], c[4] } + else + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot = best + end + slots[key] = slot + end + end + buffer.writeu8(lut, i - 1, slot) + end + local n = sx * sy * sz + local data, nstates = v.data, #states + for i = 0, n - 1 do + local s = buffer.readu16(indices, i * 2) + buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0) + end + v.blocks = { palette = states, data = indices } + return v +end + +-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + for _, d in Colors.DYES do + for _, kind in { "wool", "concrete", "terracotta" } do + local s = "minecraft:" .. d .. "_" .. kind + table.insert(out, { s, Minecraft.color(s) }) + end + end + for _, w in Colors.WOODS do + local s = "minecraft:" .. w .. "_planks" + table.insert(out, { s, Minecraft.color(s) }) + end + for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do + local s = "minecraft:" .. n + table.insert(out, { s, Minecraft.color(s) }) + end + CANDIDATES = out + return out +end + +-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) +function Minecraft.nearestBlock(c: { number }): string + local a = c[4] or 255 + if a < 200 then + local best, bd = "minecraft:glass", math.huge + for i, d in Colors.DYES do + local w = WOOL[i] + local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 + if dist < bd then + best, bd = "minecraft:" .. d .. "_stained_glass", dist + end + end + return best + end + local best, bd = "minecraft:stone", math.huge + for _, cand in candidates() do + local k = cand[2] + local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 + if dist < bd then + best, bd = cand[1], dist + end + end + return best +end + +-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per +-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message +function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) + local n = v.size[1] * v.size[2] * v.size[3] + local b = v.blocks + if b then + if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then + return nil, "voxels.blocks must hold a palette and a u16 per cell" + end + if #b.palette == 0 or #b.palette > 65536 then + return nil, "voxels.blocks.palette must have 1 .. 65536 states" + end + return b.palette, b.data + end + local states = { "minecraft:air" } + local slotOf: { [number]: number } = { [0] = 0 } + local byState: { [string]: number } = { ["minecraft:air"] = 0 } + local out = buffer.create(n * 2) + local data = v.data + for i = 0, n - 1 do + local p = buffer.readu8(data, i) + local s = slotOf[p] + if s == nil then + local col = v.palette[p] or { 128, 128, 128, 255 } + local st = Minecraft.nearestBlock(col) + s = byState[st] + if s == nil then + table.insert(states, st) + s = #states - 1 + byState[st] = s + end + slotOf[p] = s + end + buffer.writeu16(out, i * 2, s :: number) + end + return states, out +end + +-- ------------------------------------------------------------------------------------------------ block entities +-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat +-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +local function int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end +local function ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end +Minecraft.int = int -- the integer value of an NBT number | nil +Minecraft.ints = ints -- the numbers of an intArray or a list | nil + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Minecraft.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Minecraft.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + +return Minecraft +end +__FILES["codecs/model/Minecraft/Colors"] = function() + +-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured +-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were +-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / +-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +local Colors = {} + +Colors.BLOCKS = [[ +stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 +polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c +mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 +suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 +red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f +sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d +iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 +netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 +cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 +budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 +obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d +ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd +ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a +carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 +polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 +red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 +warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab +prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c +terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 +chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 +cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 +polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 +cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 +polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 +moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 +bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 +lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 +vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 +kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 +mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 +honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 +lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 +cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 +crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 +mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab +redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c +sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 +chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 +activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 +soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 +fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 +beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 +wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 +cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 +dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 +cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 +trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f +repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a +dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b +orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 +lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 +torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c +flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a +beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c +weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 +frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 +muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea +creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a +]] + +-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) +Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } +Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" +Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" +Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" + +-- wood types: planks, bark (log / wood), leaves +Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } +Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" +Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" +Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" + +return Colors +end +__FILES["codecs/model/Minecraft/Legacy"] = function() + +-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with +-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): +-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it +-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +local Legacy = {} + +local function words(s: string): { string } + local out = {} + for w in string.gmatch(s, "%S+") do + table.insert(out, w) + end + return out +end + +-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused +Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava +lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock +bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension +yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt +bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block +crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever +stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch +stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal +lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick +brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate +brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart +enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp +lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire +emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots +potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate +unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs +activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime +barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant +standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 +stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence +birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door +end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks +beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block +red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box +light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box +cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box +black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta +light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta +gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta +blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta +concrete concrete_powder - - structure_block]]) + +-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: +-- lit_furnace, powered_repeater, ... keep their legacy names) +Legacy.RENAMED = { + grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", + melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", + red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", + mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", + tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", + fence = "oak_fence", fence_gate = "oak_fence_gate", + wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", + wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", + wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", + silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", + monster_egg = "infested_stone", + standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", + bed = "red_bed", +} :: { [string]: string } + +-- legacy names whose data value selects the variant: the modern names by data value (0-based) +local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" +local function dyed(suffix: string): { string } + local out = {} + for i, d in words(DYED) do + out[i] = d .. "_" .. suffix + end + return out +end +Legacy.VARIANTS = { + stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, + dirt = { "dirt", "coarse_dirt", "podzol" }, + planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, + wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, + sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, + sand = { "sand", "red_sand" }, + log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 + log2 = { "acacia_log", "dark_oak_log" }, + leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, + leaves2 = { "acacia_leaves", "dark_oak_leaves" }, + sponge = { "sponge", "wet_sponge" }, + sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, + red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, + stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, + quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, + prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, + cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, + red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, + double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, + wool = dyed("wool"), + carpet = dyed("carpet"), + stained_glass = dyed("stained_glass"), + stained_glass_pane = dyed("stained_glass_pane"), + stained_hardened_clay = dyed("terracotta"), + concrete = dyed("concrete"), + concrete_powder = dyed("concrete_powder"), +} :: { [string]: { string } } +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number } + +return Legacy +end +__FILES["codecs/model/Minecraft/Packed"] = @native function() + + + +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and +-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding +-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: +-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written +-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +local Packed = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 +local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor + +-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes +@native function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number + if spanning then + return (count * bits + 63) // 64 + end + local per = 64 // bits + return (count + per - 1) // per +end + +-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte +-- 0); an index >= max is an error. bits 1 .. 16. +@native function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) + if bits < 1 or bits > 16 then + return false, "unsupported: " .. bits .. "-bit packed indices" + end + local need = Packed.longsNeeded(count, bits, spanning) + if buffer.len(longs) < need * 8 then + return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")" + end + if buffer.len(out) < count * 2 then + return false, "output too small" + end + -- a copy with 4 bytes of padding, so every 32-bit read stays in range + local n = need * 8 + local src = buffer.create(n + 4) + buffer.copy(src, 0, longs, 0, n) + if spanning then + local p = 0 + for i = 0, count - 1 do + local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + p += bits + end + else + local per = 64 // bits + local i = 0 + local base = 0 + while i < count do + local p = 0 + for _ = 1, per do + if i >= count then + break + end + local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + i += 1 + p += bits + end + base += 8 + end + end + return true, nil +end + +-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack +@native function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer + local need = Packed.longsNeeded(count, bits, spanning) + local out = buffer.create(need * 8 + 4) + local per = 64 // bits + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local at = rshift(p, 3) + local sh = band(p, 7) + -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) + local x = lshift(v, sh) + for k = 0, 2 do + local bits8 = band(rshift(x, k * 8), 0xff) + if bits8 ~= 0 then + writeu8(out, at + k, bor(readu8(out, at + k), bits8)) + end + end + end + local res = buffer.create(need * 8) + buffer.copy(res, 0, out, 0, need * 8) + return res +end + +-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) +@native function Packed.bitsFor(n: number, min: number): number + local b = min + while lshift(1, b) < n and b < 31 do + b += 1 + end + return b +end + +-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge +-- BlockData) into out (u16 LE) +@native function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) + if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then + return false, "bad varint array arguments" + end + local p, e = offset, offset + length + for i = 0, count - 1 do + local v, sh = 0, 0 + while true do + if p >= e then + return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" + end + local c = readu8(src, p) + p += 1 + v += band(c, 0x7f) * 2 ^ sh + if c < 128 then + break + end + sh += 7 + if sh > 28 then + return false, "varint too long" + end + end + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + end + return true, nil +end + +-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints +@native function Packed.toVarints(indices: buffer, count: number): buffer + local out = buffer.create(count * 3) + local p = 0 + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + while v >= 128 do + writeu8(out, p, band(v, 0x7f) + 128) + p += 1 + v = rshift(v, 7) + end + writeu8(out, p, v) + p += 1 + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res +end + +-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's +-- AddBlocks: high nibble first) +@native function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number + local b = readu8(src, offset + rshift(i, 1)) + local odd = band(i, 1) == 1 + if odd == highFirst then + return band(b, 15) + end + return rshift(b, 4) +end + +-- setNibble(dst, offset, i, v, highFirst) +@native function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) + local at = offset + rshift(i, 1) + local b = readu8(dst, at) + local odd = band(i, 1) == 1 + if odd == highFirst then + writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) + else + writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) + end +end + +-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then +-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new +-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +@native function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer + local out = dst or buffer.create(sx * sy * sz * 2) + local bx, by, bz = ox or 0, oy or 0, oz or 0 + local wx, wy = dsx or sx, dsy or sy + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 + for _ = 0, sx - 1 do + writeu16(out, d, readu16(src, i)) + i += 2 + d += 2 + end + end + end + return out +end + +-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) +@native function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer + local out = buffer.create(sx * sy * sz * 2) + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local s = (sx * (y + sy * z)) * 2 + for _ = 0, sx - 1 do + writeu16(out, i, readu16(src, s)) + i += 2 + s += 2 + end + end + end + return out +end + +return Packed +end +__FILES["codecs/model/Polygon"] = function() + +-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map +-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the +-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the +-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so +-- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method +-- (D. Eberly, Triangulation by Ear Clipping); no code taken. +-- +-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) +-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair +-- -- (1-based), counter-clockwise +-- +-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +local Polygon = {} + +type Pt = { x: number, y: number, loop: number, index: number } + +local function area(pts: { Pt }): number + local a = 0 + local n = #pts + for i = 1, n do + local p, q = pts[i], pts[i % n + 1] + a += p.x * q.y - q.x * p.y + end + return a / 2 +end + +local function inside(pts: { Pt }, x: number, y: number): boolean + local c = false + local n = #pts + local j = n + for i = 1, n do + local a, b = pts[i], pts[j] + if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then + c = not c + end + j = i + end + return c +end + +local function cross(o: Pt, a: Pt, b: Pt): number + return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +end + +-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) +local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean + if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then + return false + end + local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2) + local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2) + return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)) +end + +local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean + for _, r in rings do + local n = #r + for i = 1, n do + if crosses(m, v, r[i], r[i % n + 1]) then + return false + end + end + end + return true +end + +-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible +-- vertices; others = every ring the bridge must not cross +local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt } + local mi = 1 + for i, p in h do + if p.x > h[mi].x then + mi = i + end + end + local m = h[mi] + local best, bestD = 0, math.huge + for pass = 1, 2 do + for i, v in outer do + if pass == 2 or v.x >= m.x then + local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2 + if d < bestD and visible(m, v, others) then + best, bestD = i, d + end + end + end + if best > 0 then + break + end + end + if best == 0 then + best = 1 + end + local out: { Pt } = {} + for i = 1, best do + table.insert(out, outer[i]) + end + local n = #h + for k = 0, n do + table.insert(out, h[(mi - 1 + k) % n + 1]) + end + for i = best, #outer do + table.insert(out, outer[i]) + end + return out +end + +local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean + return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 +end + +-- ear clipping of one counter-clockwise ring +local function clip(ring: { Pt }, out: { number }) + local pts = table.clone(ring) + local guard = #pts * #pts + 16 + while #pts > 3 and guard > 0 do + guard -= 1 + local n = #pts + local found, bestI, bestScore = 0, 1, -math.huge + for i = 1, n do + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + local cr = cross(a, b, c) + if cr > 0 then + local ok = true + for k = 1, n do + local p = pts[k] + if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then + ok = false + break + end + end + if ok then + found = i + break + end + end + if cr > bestScore then + bestI, bestScore = i, cr + end + end + local i = if found > 0 then found else bestI + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + if cross(a, b, c) ~= 0 then + table.insert(out, a.loop) + table.insert(out, a.index) + table.insert(out, b.loop) + table.insert(out, b.index) + table.insert(out, c.loop) + table.insert(out, c.index) + end + table.remove(pts, i) + end + if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then + for k = 1, 3 do + table.insert(out, pts[k].loop) + table.insert(out, pts[k].index) + end + end +end + +-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) +function Polygon.triangulate(loops: { { number } }): { number } + local rings: { { Pt } } = {} + local areas: { number } = {} + for li, l in loops do + local pts: { Pt } = {} + for k = 1, #l - 1, 2 do + local x, y = l[k], l[k + 1] + if type(x) == "number" and type(y) == "number" and x == x and y == y then + table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 }) + end + end + local a = if #pts >= 3 then area(pts) else 0 + if a ~= 0 then + table.insert(rings, pts) + table.insert(areas, math.abs(a)) + if a < 0 then -- counter-clockwise for now; holes are flipped below + local r: { Pt } = {} + for k = #pts, 1, -1 do + table.insert(r, pts[k]) + end + rings[#rings] = r + end + end + end + -- nesting: the parent of a ring is the smallest ring containing its first point + local n = #rings + local depth, parent = table.create(n, 0), table.create(n, 0) + for i = 1, n do + local p = rings[i][1] + for j = 1, n do + if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then + depth[i] += 1 + if parent[i] == 0 or areas[j] < areas[parent[i]] then + parent[i] = j + end + end + end + end + local holes: { [number]: { number } } = {} + for i = 1, n do + if depth[i] % 2 == 1 and parent[i] > 0 then + local list = holes[parent[i]] or {} + holes[parent[i]] = list + table.insert(list, i) + end + end + local out: { number } = {} + for i = 1, n do + if depth[i] % 2 == 0 then + local ring = rings[i] + local hs = holes[i] + if hs then + table.sort(hs, function(a: number, b: number): boolean + local ma, mb = -math.huge, -math.huge + for _, p in rings[a] do + ma = math.max(ma, p.x) + end + for _, p in rings[b] do + mb = math.max(mb, p.x) + end + return ma > mb + end) + local flipped: { { Pt } } = {} + for _, h in hs do + local r: { Pt } = {} + local src = rings[h] + for k = #src, 1, -1 do + table.insert(r, src[k]) + end + table.insert(flipped, r) + end + for k, h in flipped do + local others: { { Pt } } = { ring } + for k2 = k + 1, #flipped do + table.insert(others, flipped[k2]) + end + ring = bridge(ring, h, others) + end + end + clip(ring, out) + end + end + return out +end + +return Polygon +end +__FILES["codecs/model/Rbx"] = function() + +-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, +-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the +-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the +-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, +-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. +-- +-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } +-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } +-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } +-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests +-- for inst, depth in Rbx.descendants(tree) do ... end +-- +-- Property values are { type = , value = } with these value forms (arrays follow the Roblox constructor +-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): +-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) +-- SharedString string (the content; writers deduplicate) +-- Bool boolean +-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) +-- Enum, BrickColor, SecurityCapabilities number +-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 +-- Axes number: bits X 1, Y 2, Z 4 +-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } +-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) +-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } +-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) +-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } +-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, +-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) +-- Ref an Instance of the tree, or nil +-- UniqueId 32 hex digits: random (16), time (8), index (8) +-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } +-- Content nil (none) | string (a URI) | an Instance (object) +-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), +-- index, count }; written back verbatim while the class keeps the same instances in the same order +-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is +-- Name is not a property here: it is inst.name. Never throws. + +local Rbx = {} + +type Value = { type: string, value: any } +type Instance = { + className: string, + name: string, + properties: { [string]: Value }, + children: { Instance }, + parent: Instance?, -- nil for roots + referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own + service: boolean?, -- a service (binary INST object format 1; rbxl roots) +} +type Tree = { + kind: "rbxtree", + roots: { Instance }, + place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model + metadata: { [string]: string }, -- binary META / XML entries (ExplicitAutoJoints, ...) + extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back + meta: { source: { format: string, [string]: any }?, [string]: any }, +} + +-- ------------------------------------------------------------------------------------------------ tree +function Rbx.tree(place: boolean?): Tree + return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } +end + +function Rbx.instance(className: string, name: string?): Instance + return { className = className, name = name or className, properties = {}, children = {} } +end + +-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance +function Rbx.add(parent: any, child: Instance): Instance + if parent.kind == "rbxtree" then + child.parent = nil + table.insert(parent.roots, child) + else + child.parent = parent + table.insert(parent.children, child) + end + return child +end + +-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) +function Rbx.set(inst: Instance, name: string, typ: string, value: any) + inst.properties[name] = { type = typ, value = value } +end + +-- get(inst, name) -> the property's value (not the Value table), nil when absent +function Rbx.get(inst: Instance, name: string): any + local v = inst.properties[name] + return if v then v.value else nil +end + +-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children +-- at depth 1) +function Rbx.descendants(root: any): () -> (Instance?, number?) + local stack: { any } = {} + local list = if root.kind == "rbxtree" then root.roots else root.children + for i = #list, 1, -1 do + table.insert(stack, { list[i], 1 }) + end + return function(): (Instance?, number?) + local top = table.remove(stack) + if not top then + return nil, nil + end + local inst, depth = top[1], top[2] + for i = #inst.children, 1, -1 do + table.insert(stack, { inst.children[i], depth + 1 }) + end + return inst, depth + end +end + +-- list(tree) -> every instance, depth first +function Rbx.list(tree: any): { Instance } + local out = {} + for inst in Rbx.descendants(tree) do + table.insert(out, inst :: Instance) + end + return out +end + +-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil +function Rbx.find(root: any, path: string): Instance? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + local list = if cur.kind == "rbxtree" then cur.roots else cur.children + local found = nil + for _, c in list do + if c.name == part then + found = c + break + end + end + if not found then + return nil + end + cur = found + end + return if cur.kind == "rbxtree" then nil else cur +end + +-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) +function Rbx.fullName(inst: Instance): string + local parts = {} + local cur: Instance? = inst + while cur do + table.insert(parts, 1, cur.name) + cur = cur.parent + end + return table.concat(parts, ".") +end + +-- ------------------------------------------------------------------------------------------------ CFrame rotation ids +-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is +-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. +local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } + +-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation +local ROTATIONS: { [number]: { number } } = {} +for a = 0, 5 do + for b = 0, 5 do + if a % 3 ~= b % 3 then + local r, u = AXES[a + 1], AXES[b + 1] + local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] } + -- columns: right, up, back (= right x up) + ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 } + end + end +end +Rbx.ROTATIONS = ROTATIONS + +local function axisIndex(x: number, y: number, z: number): number? + for i, a in AXES do + if a[1] == x and a[2] == y and a[3] == z then + return i - 1 + end + end + return nil +end + +-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned +function Rbx.rotationId(cf: { number }): number + local a = axisIndex(cf[4], cf[7], cf[10]) + local b = axisIndex(cf[5], cf[8], cf[11]) + if not a or not b then + return 0 + end + local id = 6 * a + b + 1 + local rot = ROTATIONS[id] + if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then + return 0 + end + return id +end + +-- ------------------------------------------------------------------------------------------------ values +-- binary type ids (rbx-dom docs/binary.md) by type name, and back +Rbx.TYPE_IDS = table.freeze({ + String = 0x01, + BinaryString = 0x01, + ProtectedString = 0x01, + ContentId = 0x01, + Bool = 0x02, + Int32 = 0x03, + Float32 = 0x04, + Float64 = 0x05, + UDim = 0x06, + UDim2 = 0x07, + Ray = 0x08, + Faces = 0x09, + Axes = 0x0A, + BrickColor = 0x0B, + Color3 = 0x0C, + Vector2 = 0x0D, + Vector3 = 0x0E, + Vector2int16 = 0x0F, + CFrame = 0x10, + Enum = 0x12, + Ref = 0x13, + Vector3int16 = 0x14, + NumberSequence = 0x15, + ColorSequence = 0x16, + NumberRange = 0x17, + Rect = 0x18, + PhysicalProperties = 0x19, + Color3uint8 = 0x1A, + Int64 = 0x1B, + SharedString = 0x1C, + Bytecode = 0x1D, + OptionalCFrame = 0x1E, + UniqueId = 0x1F, + Font = 0x20, + SecurityCapabilities = 0x21, + Content = 0x22, +} :: { [string]: number }) +local NAMES: { [number]: string } = {} +for name, id in Rbx.TYPE_IDS do + if NAMES[id] == nil or name == "String" then + NAMES[id] = name + end +end +Rbx.TYPE_NAMES = table.freeze(NAMES) + +-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the +-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } +function Rbx.default(typ: string): any + if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then + return "" + elseif typ == "Bool" then + return false + elseif typ == "BrickColor" then + return 194 + elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then + return { 0, 0 } + elseif typ == "UDim2" or typ == "Rect" then + return { 0, 0, 0, 0 } + elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then + return { 0, 0, 0 } + elseif typ == "Ray" then + return { 0, 0, 0, 0, 0, 0 } + elseif typ == "CFrame" then + return table.clone(IDENTITY_CF) + elseif typ == "NumberSequence" then + return { { 0, 0, 0 }, { 1, 0, 0 } } + elseif typ == "ColorSequence" then + return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } } + elseif typ == "UniqueId" then + return string.rep("0", 32) + elseif typ == "Font" then + return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" } + elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then + return nil + end + return 0 +end + +-- STRINGS: the string-valued types (one binary type, several XML tags) +Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean }) + +return Rbx +end +__FILES["codecs/model/Rbx/Binary"] = @native function() + + + +-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk +-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte +-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" +-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. +-- +-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) +-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message +-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) +-- +-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), +-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. +-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / +-- a layout it cannot read, which the format keeps raw). +local Rbx = __include("codecs/model/Rbx") +local Bytes = __include("core/Bytes") + +local Binary = {} + +local readu8, readu16, readi16, readu32, readf32, readf64 = + buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64 +local writeu32, readstring = buffer.writeu32, buffer.readstring +local writef32 = buffer.writef32 +local floor = math.floor + +local scratch = buffer.create(8) +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ transforms +-- the rotated float encoding: bits rotated left by one (sign in bit 0) +@native local function unrotate(x: number): number + writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648) + return readf32(scratch, 0) +end +@native local function rotate(v: number): number + writef32(scratch, 0, v) + local bits = readu32(scratch, 0) + return (bits * 2) % TWO32 + bits // 2147483648 +end +@native local function unzigzag(x: number): number + return if x % 2 == 0 then x // 2 else -(x + 1) // 2 +end +@native local function zigzag32(v: number): number + v = floor(v) + return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32 +end + +-- n big-endian u32 values interleaved at p (4n bytes) +@native local function u32s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + local n2, n3 = n * 2, n * 3 + for i = 0, n - 1 do + out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i) + end + return out +end +@native local function i32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unzigzag(out[i]) + end + return out +end +@native local function f32s(b: buffer, p: number, n: number): { number } + local out = u32s(b, p, n) + for i = 1, n do + out[i] = unrotate(out[i]) + end + return out +end +-- n zigzag i64 values (8n interleaved bytes), as doubles +@native local function i64s(b: buffer, p: number, n: number): { number } + local out = table.create(n, 0) + for i = 0, n - 1 do + local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) + local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i) + local half = hi * 2147483648 + lo // 2 + out[i + 1] = if lo % 2 == 0 then half else -half - 1 + end + return out +end + +-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 +@native local function putU32s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(4 * n) + local b = w.buf + for i = 0, n - 1 do + local v = vals[i + 1] % TWO32 + buffer.writeu8(b, p + i, v // 16777216) + buffer.writeu8(b, p + n + i, (v // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, v % 256) + end + w.pos = p + 4 * n +end +@native local function putI32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = zigzag32(v) + end + putU32s(w, t) +end +@native local function putF32s(w: Bytes.Writer, vals: { number }) + local t = table.create(#vals, 0) + for i, v in vals do + t[i] = rotate(v) + end + putU32s(w, t) +end +@native local function putI64s(w: Bytes.Writer, vals: { number }) + local n = #vals + local p = w:reserve(8 * n) + local b = w.buf + for i = 0, n - 1 do + local v = floor(vals[i + 1]) + local z = if v >= 0 then v * 2 else -v * 2 - 1 + local hi, lo = (z // TWO32) % TWO32, z % TWO32 + buffer.writeu8(b, p + i, hi // 16777216) + buffer.writeu8(b, p + n + i, (hi // 65536) % 256) + buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256) + buffer.writeu8(b, p + 3 * n + i, hi % 256) + buffer.writeu8(b, p + 4 * n + i, lo // 16777216) + buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256) + buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256) + buffer.writeu8(b, p + 7 * n + i, lo % 256) + end + w.pos = p + 8 * n +end + +-- referent arrays: zigzag i32, interleaved, each the difference from the previous one +@native function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number) + if n < 0 or p + 4 * n > limit then + return nil, p + end + local out = i32s(b, p, n) + local acc = 0 + for i = 1, n do + acc += out[i] + out[i] = acc + end + return out, p + 4 * n +end +@native function Binary.writeRefs(w: Bytes.Writer, refs: { number }) + local d = table.create(#refs, 0) + local prev = 0 + for i, r in refs do + d[i] = r - prev + prev = r + end + putI32s(w, d) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { + ref: ((number) -> any)?, + refOf: ((any) -> number)?, + shared: { string }?, + sharedIndex: ((string) -> number)?, +} + +-- a length-prefixed string at p: string, next p (nil when it runs past limit) +@native local function str(b: buffer, p: number, limit: number): (string?, number) + if p + 4 > limit then + return nil, p + end + local len = readu32(b, p) + if p + 4 + len > limit then + return nil, p + end + return readstring(b, p + 4, len), p + 4 + len +end + +@native local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number) + local rots: { { number } } = table.create(n) :: any + for i = 1, n do + if p >= limit then + return nil, p + end + local id = readu8(b, p) + p += 1 + if id == 0 then + if p + 36 > limit then + return nil, p + end + local m = table.create(9, 0) + for k = 0, 8 do + m[k + 1] = readf32(b, p + 4 * k) + end + rots[i] = m + p += 36 + else + local m = Rbx.ROTATIONS[id] + if not m then + return nil, -1 + end + rots[i] = m + end + end + if p + 12 * n > limit then + return nil, p + end + local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n) + local out = table.create(n) + for i = 1, n do + local m = rots[i] + out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] } + end + return out, p + 12 * n +end + +local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types + [0x02] = 1, + [0x03] = 4, + [0x04] = 4, + [0x05] = 8, + [0x06] = 8, + [0x07] = 16, + [0x08] = 24, + [0x09] = 1, + [0x0A] = 1, + [0x0B] = 4, + [0x0C] = 12, + [0x0D] = 8, + [0x0E] = 12, + [0x0F] = 4, + [0x12] = 4, + [0x13] = 4, + [0x14] = 6, + [0x17] = 8, + [0x18] = 16, + [0x1A] = 3, + [0x1B] = 8, + [0x1C] = 4, + [0x1F] = 16, + [0x21] = 8, +} + +-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message +@native function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any) + if limit > buffer.len(b) or p < 0 or n < 0 then + return nil, "corrupt: bad ranges" + end + local size = FIXED[t] + if size and p + size * n > limit then + return nil, "truncated property values" + end + if t == 0x01 or t == 0x1D then + local out = table.create(n, "") + for i = 1, n do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated string" + end + out[i] = s + p = q + end + return out, p + elseif t == 0x02 then + local out = table.create(n, false) + for i = 1, n do + out[i] = readu8(b, p + i - 1) ~= 0 + end + return out, p + n + elseif t == 0x03 then + return i32s(b, p, n), p + 4 * n + elseif t == 0x04 then + return f32s(b, p, n), p + 4 * n + elseif t == 0x05 then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readf64(b, p + 8 * (i - 1)) + end + return out, p + 8 * n + elseif t == 0x06 then + local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { s[i], o[i] } + end + return out, p + 8 * n + elseif t == 0x07 then + local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { xs[i], xo[i], ys[i], yo[i] } + end + return out, p + 16 * n + elseif t == 0x08 then + local out = table.create(n) + for i = 1, n do + local q = p + 24 * (i - 1) + out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) } + end + return out, p + 24 * n + elseif t == 0x09 or t == 0x0A then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readu8(b, p + i - 1) + end + return out, p + n + elseif t == 0x0B or t == 0x12 then + return u32s(b, p, n), p + 4 * n + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + local cols: { { number } } = table.create(k) :: any + for c = 1, k do + cols[c] = f32s(b, p + 4 * n * (c - 1), n) + end + local out = table.create(n) + for i = 1, n do + local v = table.create(k, 0) + for c = 1, k do + v[c] = cols[c][i] + end + out[i] = v + end + return out, p + 4 * k * n + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + local out = table.create(n) + for i = 1, n do + local q = p + 2 * k * (i - 1) + out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) } + end + return out, p + 2 * k * n + elseif t == 0x10 then + local out, q = cframes(b, p, limit, n) + if not out then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + return out, q + elseif t == 0x13 then + local refs, q = Binary.readRefs(b, p, limit, n) + if not refs then + return nil, "truncated referents" + end + local out = table.create(n) + local ref = ctx.ref + for i = 1, n do + out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil + end + return out, q + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + local out = table.create(n) + for i = 1, n do + if p + 4 > limit then + return nil, "truncated sequence" + end + local count = readu32(b, p) + p += 4 + if p + count * 4 * k > limit then + return nil, "truncated sequence" + end + local seq = table.create(count) + for j = 1, count do + local key = table.create(k, 0) + for c = 1, k do + key[c] = readf32(b, p + 4 * (c - 1)) + end + seq[j] = key + p += 4 * k + end + out[i] = seq + end + return out, p + elseif t == 0x17 then + local out = table.create(n) + for i = 1, n do + out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) } + end + return out, p + 8 * n + elseif t == 0x19 then + local out = table.create(n) + for i = 1, n do + if p >= limit then + return nil, "truncated physical properties" + end + local flag = readu8(b, p) + p += 1 + if flag % 2 == 1 then + local k = if flag // 2 % 2 == 1 then 6 else 5 + if p + 4 * k > limit then + return nil, "truncated physical properties" + end + local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out + for c = 1, k do + v[c] = readf32(b, p + 4 * (c - 1)) + end + out[i] = v + p += 4 * k + elseif flag ~= 0 then + return nil, "unknown" + end + end + return out, p + elseif t == 0x1A then + local out = table.create(n) + for i = 1, n do + out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) } + end + return out, p + 3 * n + elseif t == 0x1B or t == 0x21 then + return i64s(b, p, n), p + 8 * n + elseif t == 0x1C then + local idx = u32s(b, p, n) + local shared: { string } = ctx.shared or {} + local out: { string } = table.create(n, "") + for i = 1, n do + local s = shared[idx[i] + 1] + if s == nil then + return nil, "corrupt: shared string index out of range" + end + out[i] = s + end + return out, p + 4 * n + elseif t == 0x1E then + if p >= limit or readu8(b, p) ~= 0x10 then + return nil, "unknown" + end + local cfs, q = cframes(b, p + 1, limit, n) + if not cfs then + return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values" + end + if q + 1 + n > limit or readu8(b, q) ~= 0x02 then + return nil, "truncated optional CFrame flags" + end + local out = table.create(n) + for i = 1, n do + out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil + end + return out, q + 1 + n + elseif t == 0x1F then + local out = table.create(n, "") + local hex = table.create(16, "") + for i = 0, n - 1 do + local by = table.create(16, 0) + for k = 0, 15 do + by[k + 1] = readu8(b, p + k * n + i) + end + -- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it + local carry = by[16] % 2 + for k = 9, 16 do + local v = by[k] + by[k] = v // 2 + carry * 128 + carry = v % 2 + end + for k = 1, 8 do + hex[k] = string.format("%02x", by[8 + k]) + end + for k = 1, 8 do + hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)]) + end + out[i + 1] = table.concat(hex) + end + return out, p + 16 * n + elseif t == 0x20 then + local out = table.create(n) + for i = 1, n do + local fam, q = str(b, p, limit) + if not fam or q + 3 > limit then + return nil, "truncated font" + end + local weight, style = readu16(b, q), readu8(b, q + 2) + local face, q2 = str(b, q + 3, limit) + if not face then + return nil, "truncated font" + end + out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil } + p = q2 + end + return out, p + elseif t == 0x22 then + if p + 4 * n > limit then + return nil, "truncated content" + end + local kinds = i32s(b, p, n) + p += 4 * n + if p + 4 > limit then + return nil, "truncated content" + end + local nu = readu32(b, p) + p += 4 + local uris = table.create(math.min(nu, n)) + for j = 1, nu do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated content" + end + uris[j] = s + p = q + end + if p + 4 > limit then + return nil, "truncated content" + end + local no = readu32(b, p) + local objs, q = Binary.readRefs(b, p + 4, limit, no) + if not objs or q + 4 > limit then + return nil, "truncated content" + end + if readu32(b, q) ~= 0 then + return nil, "unknown" -- external objects: kept raw + end + p = q + 4 + local out = table.create(n) + local iu, io = 1, 1 + for i = 1, n do + local k = kinds[i] + if k == 1 then + if iu > nu then + return nil, "corrupt: content uri count" + end + out[i] = uris[iu] + iu += 1 + elseif k == 2 then + if io > no then + return nil, "corrupt: content object count" + end + local r = objs[io] + out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil + io += 1 + elseif k ~= 0 then + return nil, "unknown" + end + end + return out, p + end + return nil, "unknown" +end + +-- ------------------------------------------------------------------------------------------------ encode +@native local function num(v: any): number + return if type(v) == "number" and v == v then v else 0 +end +-- column c of n array values (missing components 0) +@native local function column(vals: { any }, n: number, c: number): { number } + local out = table.create(n, 0) + for i = 1, n do + local v = vals[i] + out[i] = if type(v) == "table" then num(v[c]) else 0 + end + return out +end + +@native local function putString(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +@native local function putCFrames(w: Bytes.Writer, vals: { any }, n: number) + for i = 1, n do + local v = vals[i] + local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } + local id = Rbx.rotationId(cf) + w:u8(id) + if id == 0 then + for k = 4, 12 do + w:f32le(num(cf[k])) + end + end + end + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 2)) + putF32s(w, column(vals, n, 3)) +end + +@native local function hexByte(s: string, i: number): number + return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 +end + +-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are +-- the type's none / default) +@native function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string? + if t == 0x01 or t == 0x1D then + for i = 1, n do + local v = vals[i] + putString(w, if type(v) == "string" then v else "") + end + elseif t == 0x02 then + for i = 1, n do + w:u8(if vals[i] then 1 else 0) + end + elseif t == 0x03 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI32s(w, c) + elseif t == 0x04 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putF32s(w, c) + elseif t == 0x05 then + for i = 1, n do + w:f64le(num(vals[i])) + end + elseif t == 0x06 then + putF32s(w, column(vals, n, 1)) + putI32s(w, column(vals, n, 2)) + elseif t == 0x07 then + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 3)) + putI32s(w, column(vals, n, 2)) + putI32s(w, column(vals, n, 4)) + elseif t == 0x08 then + for i = 1, n do + local v = vals[i] + for c = 1, 6 do + w:f32le(if type(v) == "table" then num(v[c]) else 0) + end + end + elseif t == 0x09 or t == 0x0A then + for i = 1, n do + w:u8(num(vals[i]) % 256) + end + elseif t == 0x0B or t == 0x12 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = floor(num(vals[i])) + end + putU32s(w, c) + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3 + for c = 1, k do + putF32s(w, column(vals, n, c)) + end + elseif t == 0x0F or t == 0x14 then + local k = if t == 0x0F then 2 else 3 + for i = 1, n do + local v = vals[i] + for c = 1, k do + local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536 + w:u16le(x) + end + end + elseif t == 0x10 then + putCFrames(w, vals, n) + elseif t == 0x13 then + local refs = table.create(n, -1) + local refOf = ctx.refOf + for i = 1, n do + refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1 + end + Binary.writeRefs(w, refs) + elseif t == 0x15 or t == 0x16 then + local k = if t == 0x15 then 3 else 5 + for i = 1, n do + local seq = vals[i] + if type(seq) ~= "table" then + seq = {} + end + w:u32le(#seq) + for _, key in seq do + for c = 1, k do + w:f32le(if type(key) == "table" then num(key[c]) else 0) + end + end + end + elseif t == 0x17 then + for i = 1, n do + local v = vals[i] + w:f32le(if type(v) == "table" then num(v[1]) else 0) + w:f32le(if type(v) == "table" then num(v[2]) else 0) + end + elseif t == 0x19 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + w:u8(0) + else + local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out) + w:u8(if acoustic then 3 else 1) + for c = 1, if acoustic then 6 else 5 do + w:f32le(num(v[c])) + end + end + end + elseif t == 0x1A then + for c = 1, 3 do + for i = 1, n do + local v = vals[i] + w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255)) + end + end + elseif t == 0x1B or t == 0x21 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI64s(w, c) + elseif t == 0x1C then + local idx = table.create(n, 0) + local si = ctx.sharedIndex + for i = 1, n do + local v = vals[i] + idx[i] = if si then si(if type(v) == "string" then v else "") else 0 + end + putU32s(w, idx) + elseif t == 0x1E then + w:u8(0x10) + putCFrames(w, vals, n) + w:u8(0x02) + for i = 1, n do + w:u8(if type(vals[i]) == "table" then 1 else 0) + end + elseif t == 0x1F then + local p = w:reserve(16 * n) + local b = w.buf + for i = 0, n - 1 do + local s = vals[i + 1] + if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then + return "a UniqueId is 32 hex digits" + end + -- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit + local by = table.create(16, 0) + for k = 1, 4 do + by[k] = hexByte(s, 12 + k) + by[4 + k] = hexByte(s, 8 + k) + end + local top = hexByte(s, 1) // 128 + for k = 1, 8 do + local v = hexByte(s, k) + local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top + by[8 + k] = (v * 2) % 256 + nxt + end + for k = 0, 15 do + buffer.writeu8(b, p + k * n + i, by[k + 1]) + end + end + w.pos = p + 16 * n + elseif t == 0x20 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + v = Rbx.default("Font") + end + putString(w, if type(v.family) == "string" then v.family else "") + w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) + w:u8(if v.style == "Italic" then 1 else 0) + putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "") + end + elseif t == 0x22 then + local kinds, uris, objs = table.create(n, 0), {}, {} + local refOf = ctx.refOf + for i = 1, n do + local v = vals[i] + if type(v) == "string" then + kinds[i] = 1 + table.insert(uris, v) + elseif type(v) == "table" then + kinds[i] = 2 + table.insert(objs, if refOf then refOf(v) else -1) + end + end + putI32s(w, kinds) + w:u32le(#uris) + for _, s in uris do + putString(w, s) + end + w:u32le(#objs) + Binary.writeRefs(w, objs) + w:u32le(0) + else + return "unknown type id " .. t + end + return nil +end + +return Binary +end +__FILES["codecs/model/Rig"] = function() + +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each +-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies +-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and +-- keyframed joint TRS tracks as animation channels. New in rosetta. +-- +-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base +-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") +-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } +-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } +-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } +-- +-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Rig = {} + +local Scene = Types.Scene +local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 + +type Joint = { + name: string?, + parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) + translation: { number }, + rotation: { number }, -- quaternion x, y, z, w + scale: { number }?, +} +type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) +type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time + +-- ------------------------------------------------------------------------------------------------ morph targets +-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL +-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as +-- many f32 x3 as the base; shorter ones are skipped (false is returned). +function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean + local pos = prim.attributes.POSITION + if not pos or pos.type ~= "f32" or pos.components ~= 3 then + return false + end + local nrm = prim.attributes.NORMAL + local n = pos.count * 3 + local targets: { { [string]: Types.Accessor } } = {} + local ok = true + for k, f in frames do + if buffer.len(f) < n * 4 then + ok = false + break + end + local t: { [string]: Types.Accessor } = {} + local d = buffer.create(n * 4) + local base = pos.data + for i = 0, n - 1 do + writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) + end + t.POSITION = Scene.accessor(d, "f32", 3, pos.count) + local fn = normals and normals[k] + if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then + local dn = buffer.create(n * 4) + for i = 0, n - 1 do + writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) + end + t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) + end + targets[k] = t + end + if ok then + prim.targets = targets + end + return ok +end + +-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on +-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR +-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. +function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) + for _, rg in ranges do + local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) + if last >= first then + local keys = last - first + 1 + local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 + local times = buffer.create(keys * 4) + local weights = buffer.create(keys * targets * 4) + for k = 0, keys - 1 do + writef32(times, k * 4, k / fps) + writef32(weights, (k * targets + first - 1 + k) * 4, 1) + end + table.insert(scene.animations, { + name = rg.name, + channels = { + { + node = node, + path = "weights" :: any, + input = Scene.accessor(times, "f32", 1, keys), + output = Scene.accessor(weights, "f32", 1, keys * targets), + interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, + }, + }, + }) + end + end +end + +-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a +-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored +-- normals cannot be used (Quake's precomputed normal table is not redistributable here). +function Rig.normals(pos: buffer, count: number, indices: { number }): buffer + local out = buffer.create(count * 12) + local acc = table.create(count * 3, 0) + for k = 1, #indices - 2, 3 do + local a, b, c = indices[k], indices[k + 1], indices[k + 2] + if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + end + for v = 0, count - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ skeletons +local function trs(j: Joint): { number } + return Mat4.compose(j.translation, j.rotation, j.scale) +end + +-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z +-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +function Rig.angles(x: number, y: number, z: number): { number } + local sy, cy = math.sin(z / 2), math.cos(z / 2) + local sp, cp = math.sin(y / 2), math.cos(y / 2) + local sr, cr = math.sin(x / 2), math.cos(x / 2) + return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } +end + +-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its +-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse +-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's +-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. +function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } }) + local n = #joints + local world: { { number } } = {} + local nodes: { number } = {} + for i, j in joints do + local p = if j.parent >= 1 and j.parent < i then j.parent else 0 + local m = trs(j) + local lt, lr, ls = j.translation, j.rotation, j.scale + if space == "world" then + world[i] = m + if p > 0 then + local inv = Mat4.inverse(world[p]) + if inv then + local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) + lt, lr, ls = t, r, s + end + end + else + world[i] = if p > 0 then Mat4.mul(world[p], m) else m + end + local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } + table.insert(scene.nodes, node) + local idx = #scene.nodes + nodes[i] = idx + if p > 0 then + table.insert(scene.nodes[nodes[p]].children, idx) + elseif root and scene.nodes[root] then + table.insert(scene.nodes[root].children, idx) + else + table.insert(scene.roots, idx) + end + end + local ibm = buffer.create(n * 64) + for i = 1, n do + local inv = Mat4.inverseFull(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) + return nodes, #scene.skins, world +end + +-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with +-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept +-- and normalised to sum 1. +function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) + local n = #lists + local jb, wb = buffer.create(n * 8), buffer.create(n * 16) + for v, l in lists do + local pairs_: { { number } } = {} + local at: { [number]: { number } } = {} + for k = 1, #l - 1, 2 do + if l[k + 1] > 0 then + local same = at[l[k]] + if same then + same[2] += l[k + 1] -- the same joint twice: one influence + else + local e = { l[k], l[k + 1] } + at[l[k]] = e + table.insert(pairs_, e) + end + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #pairs_) do + sum += pairs_[k][2] + end + for k = 1, math.min(4, #pairs_) do + writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) + writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) + end + end + return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) +end + +-- ------------------------------------------------------------------------------------------------ animations +local function floats(t: { number }, count: number, comps: number): Types.Accessor? + if #t < count * comps then + return nil + end + local b = buffer.create(count * comps * 4) + for i = 1, count * comps do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, count) +end + +-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into +-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks +-- with too few keys are skipped. Default interpolation "LINEAR". +function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number + local count = #times + local input = floats(times, count, 1) + local channels: { Types.Channel } = {} + local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" + if input then + for j, tr in tracks do + local node = nodes[j] + if node then + for _, path in { "translation", "rotation", "scale" } do + local keys = (tr :: any)[path] + local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) + if acc then + table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) + end + end + end + end + end + table.insert(scene.animations, { name = name, channels = channels }) + return #scene.animations +end + +return Rig +end +__FILES["codecs/model/Sampler"] = function() + +-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for +-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold +-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames +-- (IQM, MD5, BVH, ...). New in rosetta. +-- +-- local sample = Sampler.channel(ch) -- nil for an unreadable channel +-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights +-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique +-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } +-- +-- Never throws on bad data: unreadable channels are skipped. +local Types = __include("Types") + +local Sampler = {} + +type Sample = (t: number) -> { number } +type Pose = { [number]: { [string]: { number } } } + +local function normalize(q: { number }): { number } + local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a: { number }, b: { number }, s: number): { number } + local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +-- channel(ch) -> sample(t) | nil +function Sampler.channel(ch: Types.Channel): Sample? + local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = if cubic then 3 else 1 + local comps: number + if ch.path == "weights" then + comps = (out.count * out.components) // (n * per) + else + comps = if ch.path == "rotation" then 4 else 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = table.create(n) :: { number } + for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + -- element e (0-based, of comps values) of the flat output + local function get(e: number): { number } + local v = table.create(comps) :: { number } + for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(flat // oc, flat % oc) + end + return v + end + local function value(k: number): { number } -- key k (1-based) + return get(if cubic then (k - 1) * 3 + 1 else k - 1) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t: number): { number } + if t <= times[1] or n == 1 then + return if rot then normalize(value(1)) else value(1) + end + if t >= times[n] then + return if rot then normalize(value(n)) else value(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = if dt > 0 then (t - times[lo]) / dt else 0 + if step then + return if rot then normalize(value(lo)) else value(lo) + end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return if rot then normalize(v) else v + end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +-- times(anim) -> every key time, sorted and unique +function Sampler.times(anim: Types.Animation): { number } + local seen: { [number]: boolean } = {} + local out: { number } = {} + for _, ch in anim.channels do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table +-- (reuse it across calls for the same animation) +function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose + local cache: { [any]: any } = samplers or {} + local pose: Pose = {} + for _, ch in anim.channels do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s: Sample? = cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler +end +__FILES["codecs/model/Vrml"] = function() + +-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, +-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding +-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a +-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated +-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. +-- +-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content +-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +local Err = __include("core/Err") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local XmlCodec = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") +local VXml = __include("codecs/model/Vrml/Xml") +local Build = __include("codecs/model/Vrml/Build") +local Write = __include("codecs/model/Vrml/Write") + +local Vrml = {} + +type Graph = Parse.Graph +type Node = Parse.Node +type Options = Build.Options & { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) +} + +-- the bytes as text: gzip inflated, UTF-8 BOM dropped +local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) + local b = if type(data) == "string" then buffer.fromstring(data) else data + if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg: string): string + if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) +function Vrml.parse(s: string): (Graph?, Err.Err?) + local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +-- parseXml(text | XML document) -> the graph of an X3D XML file +function Vrml.parseXml(src: any): (Graph?, Err.Err?) + local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED +function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) + local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve +function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- build(graph, opts?) -> Scene +function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data: buffer): (any, string?) + local g, err = Vrml.graph(data, opts) + return g, if err then err.message else nil + end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +-- decode(bytes, opts?) -> Scene: graph + build +function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) + local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files +function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml +end +__FILES["codecs/model/Vrml/Build"] = function() + +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. +-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, +-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through +-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when +-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial +-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture +-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: +-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / +-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a +-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in +-- meta.source.skipped. Never throws: bad data returns nil, message. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Fields = __include("codecs/model/Vrml/Fields") +local Geometry = __include("codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + +type Options = Geometry.Options & { + fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files + load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph + format: string?, -- meta.source.format + maxInline: number?, -- Inline nesting (default 8) +} + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +-- nodes with nothing to show (not counted as skipped) +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r: { number }): { number } + return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a: { number }, b: { number }): { number } + return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q: { number }, v: { number }): { number } + local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q: { number }): boolean + return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +-- the rotation taking unit vector a onto b +local function between(a: { number }, b: { number }): { number } + local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + -- opposite: half a turn about any perpendicular axis + return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + +type Ctx = { + scene: Types.Scene, + opts: Options, + meshes: { [any]: any }, + materials: { [any]: any }, + textures: { [any]: number }, + instances: { [any]: { { node: number, center: { number }, so: { number } } } }, + skipped: { [string]: number }, + depth: number, + inline: number, + failure: string?, +} + +local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number + local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +-- ------------------------------------------------------------------------------------------------ materials +local function texture(ctx: Ctx, t: any): number? + if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex: Types.Texture = { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in urls do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px //= 256 + end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 + else + r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 + end + -- the image's first row is the bottom one + local row = h - 1 - i // w + local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? + local i = texture(ctx, t) + if not i then + return nil + end + local ref: Types.TextureRef = { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx: Ctx, app: any, solid: boolean): number? + if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache :: any)[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x: { [string]: any } = {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in slots do + local t = node(mat, field) + if t then + (m :: any)[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache :: any)[solid] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ nodes +local walk: (ctx: Ctx, n: any, parent: number?) -> () + +local function shape(ctx: Ctx, n: any, parent: number?) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false :: any + return + end + local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + if count == 0 then + -- nothing to draw (no valid faces / points) + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx: Ctx, n: any, parent: number?) + local cam: any + if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx: Ctx, n: any, parent: number?) + local t = n.type + local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd: Types.Node = { name = n.def, children = {} } + local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l :: any).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx: Ctx, n: any, parent: number?) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in CHILDREN do + for _, c in nodes(n, f) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx: Ctx, n: any, parent: number?) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer: Types.Node = { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = if isIdentityQ(qs) then qr else qmul(qr, qs) + if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx: Ctx, n: any, parent: number?) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in strs(n, "url") do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline += 1 + for _, root in g.roots do + walk(ctx, root, holder) + end + ctx.inline -= 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx: Ctx, n: any, parent: number?) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth += 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in nodes(n, "shape") do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source :: any + src.title = str(n, "title") + local info = strs(n, "info") + src.info = if #info > 0 then info else nil + elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ animation +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx: Ctx, routes: { any }) + -- interpolator -> its TimeSensor + local timer: { [any]: any } = {} + for _, r in routes do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims: { [any]: Types.Animation } = {} + local order: { any } = {} + for _, r in routes do + local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then + continue + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then + continue + end + local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = if path == "rotation" then 4 else 3 + local n = math.min(#key, #kv // comps) + if n == 0 then + continue + end + local ts = timer[it] + local cycle = if ts then num(ts, "cycleInterval", 1) else 1 + local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = if ts then ts.def else nil, channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in inst do + local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) + local prev: { number }? = nil + for i = 0, n - 1 do + local v: { number } + if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) + end + end + for _, id in order do + table.insert(ctx.scene.animations, anims[id]) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) + local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 + local h = graph.header or {} + local skipped: { [string]: number } = {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in graph.roots do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build +end +__FILES["codecs/model/Vrml/Fields"] = function() + +-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding +-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here +-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans +-- true / false). Never throws. +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted +local function mfString(s: string): { string } + local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent +function Fields.nums(node: any, name: string): { number }? + local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in gmatch(v, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in v do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in v do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, if x then 1 else 0) + end + end + return out +end + +function Fields.num(node: any, name: string, default: number): number + local v = Fields.nums(node, name) + return if v and type(v[1]) == "number" then v[1] else default +end + +-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) +function Fields.vec(node: any, name: string, default: { number }): { number } + local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out: { number } = {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node: any, name: string, default: boolean): boolean + local v = node.fields[name] + if type(v) == "string" then + local w = string.lower(string.match(v, "^%s*(%S*)") :: string) + return if w == "true" then true elseif w == "false" then false else default + end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node: any, name: string): { string } + local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node: any, name: string, default: string?): string? + local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +-- nodes(node, name) -> the nodes of an SFNode / MFNode field +function Fields.nodes(node: any, name: string): { any } + local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node: any, name: string): any + return Fields.nodes(node, name)[1] +end + +return Fields +end +__FILES["codecs/model/Vrml/Geometry"] = function() + +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no +-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face +-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets +-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, +-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, +-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, +-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to +-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +local Types = __include("Types") +local Fields = __include("codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + +type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } + +local function f32(list: { number }, comps: number, count: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + end + return a +end + +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end + +-- the colour node's values and component count (Color: 3, ColorRGBA: 4) +local function colors(n: any): ({ number }?, number) + local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = if c.type == "ColorRGBA" then 4 else 3 + return nums(c, "color") or {}, comps +end + +local function points(n: any, field: string, sub: string): { number }? + local c = node(n, field) + return if c then nums(c, sub) or {} else nil +end + +-- ------------------------------------------------------------------------------------------------ polygon meshes +-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: +-- the coordinate index) or per-face indices. +type PolyIn = { + P: { number }, -- coordinates, 3 per point + corners: { number }, -- coordinate index per corner, face after face + sizes: { number }, -- corners per face + N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, + T: { number }?, tIdx: { number }?, + ccw: boolean, +} + +local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) + local P, corners, sizes = m.P, m.corners, m.sizes + local np = #P // 3 + local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + -- the attribute index of corner k (1-based) in face f (1-based) + local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number + if perFace then + return if list and #list > 0 then (list[f] or 0) else f - 1 + end + return if list and #list > 0 then (list[k] or c) else c + end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey: { [string]: number } = {} + local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local out: { number } = {} + local outSizes: { number } = {} + local k = 0 + for f, size in sizes do + local face: { number } = {} + local valid = size >= 3 + for q = 1, size do + k += 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts: { number } = {} + for q, kk in face do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 + local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 + local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 + local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, (size + 1) // 2 do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in verts do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = if simple then np else #vsrc + if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil + local col = if C then S.accessor(nil, "f32", cc, nv) else nil + local tex = if T then S.accessor(nil, "f32", 2, nv) else nil + local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = if simple then nil else vsrc[v + 1] + local c = if s then s[1] else v + for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = if s then s[2] else v + for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = if s then s[3] else v + for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = if s then s[4] else v + local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +-- split a -1 separated index list into corners + sizes +local function split(list: { number }): ({ number }, { number }) + local corners, sizes = {}, {} + local run = 0 + for _, x in list do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run += 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list: { number }?): { number }? + if not list or #list == 0 then + return nil + end + local out = {} + for _, x in list do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), + C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), + T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts +local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local t = n.type + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local index = nums(n, "index") + local seq: { number } + if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a: number, b: number, c: number) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs(): { { number } } + local out = {} + local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in seq do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in counts do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at += c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in runs() do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in runs() do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h: { number } = nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in { a, a + nx, a + nx + 1, a + 1 } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, + } + return polyMesh(m, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ Extrusion +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function sub3(a: { number }, b: { number }): { number } + return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a: { number }): ({ number }, number) + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v: { number }, k: { number }, a: number): { number } + local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = #sp // 3, #cs // 2 + if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a: { number }, b: { number }): boolean + return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} + for i = 1, ns do + local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil + local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil + local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = if l > 1e-12 then z else nil + end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } + end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = if closedSpine then ns - 1 else ns + local nring = if closedCs then nc - 1 else nc + local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = if #sc >= i * 2 then i else 1 + local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = if #ori >= i * 4 then i else 1 + local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i: number, j: number): number + return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ lines, points +local function lines(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs: { { number } } = {} + if n.type == "LineSet" then + local at = 0 + for _, c in nums(n, "vertexCount") or {} do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at += c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in sizes do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k += s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = if perVertex then cornerList(cIdx) else nil + local vkey: { [string]: number } = {} + local src: { { number } } = {} + local out: { number } = {} + local k = 0 + for li, r in runs do + local prev: number? = nil + for _, c in r do + k += 1 + if c == nil or c < 0 or c >= np then + prev = nil + continue + end + local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) + local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v + end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = if C then S.accessor(nil, "f32", cc, #src) else nil + for v, s in src do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } +end + +local function pointSet(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +-- ------------------------------------------------------------------------------------------------ primitives +-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) +local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive + local nv = #P // 3 + if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n: any, o: Options): Types.Primitive + local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in FACES do + local nn, u, v = face[1], face[2], face[3] + for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do + for q = 1, 3 do + local h = if q == 1 then hx elseif q == 2 then hy else hz + table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in { 0, 1, 2, 0, 2, 3 } do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) +-- and runs counter-clockwise seen from +y +local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +-- a cap disc at height y facing ny (+1 / -1) +local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) + local b = #P // 3 + for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) +local function band(I: { number }, a: number, b: number, segs: number) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n: any, o: Options, segs: number): Types.Primitive + local r = num(n, "radius", 1) + local rings = math.max(2, segs // 2) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive + local r = num(n, if cone then "bottomRadius" else "radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 + ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +-- ------------------------------------------------------------------------------------------------ dispatch +-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); +-- the second value of a success is the node's solid flag +function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) + local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim: Types.Primitive?, err: string? = nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry +end +__FILES["codecs/model/Vrml/Parse"] = function() + +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into +-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are +-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, +-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO +-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside +-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, +-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are +-- returned as nil, message ("line N: ..."). +local Parse = {} + +type Node = { type: string, def: string?, fields: { [string]: any } } +type Route = { from: Node, fromField: string, to: Node, toField: string } +type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } +type Graph = { + roots: { Node }, + routes: { Route }, + header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile + meta: { [string]: string }, -- META / WorldInfo statements + components: { string }, + units: { [string]: { name: string, factor: number } }, + protos: { [string]: Proto }, +} +-- an IS reference in a PROTO body: fields[name] = { is = "protoField" } +type IsRef = { is: string } + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) +local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node + local done = memo[node] + if done then + return done + end + local out: Node = { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in node.fields do + if type(v) == "table" and type((v :: any).is) == "string" then + local name = (v :: any).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in v do + arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x + end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO +function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? + if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first: Node? = nil + for _, n in proto.body do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in proto.routes do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first :: Node + if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out: Node = { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text: string): (Graph?, string?) + local n = #text + local p = 1 + local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs: { [string]: Node } = {} + local protos: { [string]: Proto } = graph.protos + local routes: { Route } = graph.routes + local failure: string? = nil + local depth = 0 + + local function line(at: number): number + local l = 1 + for _ in gmatch(sub(text, 1, at), "\n") do + l += 1 + end + return l + end + local function fail(msg: string) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + -- the lexer: skip blanks, commas and comments; returns the next token kind and value + -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = if e then e else n + 1 + else + return + end + end + end + local function token(): (string, any) + skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p += 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e :: number) + 1 + return "num", num + end + if c == 46 then + p += 1 + return ".", nil + end + -- +inf / -nan style words: read the word + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we :: number) + 1 + local wl = string.lower(w) + local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil + if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e :: number) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek(): (string, any) + local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode: (first: string) -> (Node?, boolean) + local parseProto: (extern: boolean) -> () + local parseRoute: () -> () + + -- a field value (after its name): an array of numbers / strings / booleans / nodes + local function value(): any + local k, val = token() + if k == "[" then + local out = {} + -- fast path: a bracket of plain numbers (big coordinate arrays) + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in gmatch(seg, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do + k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then + continue + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end + end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return if node then { node } else {} + end + fail("missing field value") + return {} + end + + -- the fields of a node body, up to its "}" + local function body(node: Node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: [ | IS ] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first: string): (Node?, boolean) + if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def: string? = nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth += 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node: Node = { type = typ, def = def, fields = {} } + body(node) + depth -= 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node :: any).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path(): (string?, string?) + local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a :: string], defs[b :: string] + if from and dst then + table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern: boolean) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() -- the url list + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + -- statements + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse +end +__FILES["codecs/model/Vrml/Write"] = function() + +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, +-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; +-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, +-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> +-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material +-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of +-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or +-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> +-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and +-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). +-- Never throws: returns nil, message. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Xml = __include("codecs/text/Xml") + +local Write = {} + +type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } + +-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers +-- per line), "bool", "str", "mstr" (MFString), "node", "nodes" +type WNode = { type: string, def: string?, use: string?, fields: { { any } } } + +local format, concat = string.format, table.concat + +local function fmt(v: number): string + if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t: string, def: string?): WNode + return { type = t, def = def, fields = {} } +end +local function F(n: WNode, name: string, kind: string, value: any, per: number?) + table.insert(n.fields, { name, kind, value, per }) +end + +-- names: valid, unique DEF names +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. (if s ~= "" then "_" .. s else "") + end + local base, k = s, 1 + while used[s] do + k += 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +-- axis-angle of a quaternion (x, y, z, w) +local function axisAngle(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function values(acc: any): { number }? + return (Flatten.numbers(acc)) +end + +local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) + local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n: string): boolean + return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in m.sizes do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p += s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, if o.flipV ~= false then 1 - tt else tt) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(if rgba then "ColorRGBA" else "Color") + local vals = {} + local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 + for i = 0, m.count - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, if rgba then 4 else 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) +local function coordNode(prim: any): (WNode?, number) + local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim: any, nv: number, x3d: boolean): WNode? + local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(if rgba then "ColorRGBA" else "Color") + F(cn, "color", "mf", vals, if rgba then 4 else 3) + return cn +end + +local function lineSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind: { number } + if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in ind do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in idx do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? + if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) + o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode + local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 + end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +-- ------------------------------------------------------------------------------------------------ the tree +function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) + local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef: { [number]: string } = {} + local meshShapes: { [number]: { WNode } } = {} + local appDef: { [any]: string } = {} + local written: { [number]: string } = {} + local failure: string? = nil + + local function shapes(mi: number): { WNode } + local done = meshShapes[mi] + if done then + -- USE the shapes written before + local out = {} + for _, s in done do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do + local mode = prim.mode or "triangles" + local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil + local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting: { [number]: boolean } = {} + local function transform(ni: number): WNode? + local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids: { WNode } = {} + if type(n.mesh) == "number" then + for _, s in shapes(n.mesh) do + table.insert(kids, s) + end + end + local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil + if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = if type(n.light) == "number" then scene.lights[n.light] else nil + if l then + local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" + local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in n.children or {} do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots: { WNode } = {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + -- no roots: every node without a parent + local child = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in list do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in shapes(mi) do + table.insert(roots, s) + end + end + end + + -- animations: a TimeSensor per animation, an interpolator per channel + local routes: { { string } } = {} + for ai, anim in scene.animations or {} do + local tmax = 0 + local chans = {} + for _, ch in anim.channels or {} do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = if tmax > 0 then tmax else 1 + local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in chans do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in input do + keys[i] = tv / cycle + end + local comps = if rot then 4 else 3 + local stride = #output // #input + -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 + local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in v do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) + table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +-- ------------------------------------------------------------------------------------------------ serializers +local function numbers(vals: { number }, per: number?, indent: string): string + local out = table.create(#vals) + for i, v in vals do + out[i] = fmt(v) + end + if per == 0 then + -- index lists: one face per line + local lines, cur = {}, {} + for i, v in vals do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s: string): string + return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string + local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n") + end + local function emit(n: WNode, ind: string): string + if n.use then + return "USE " .. n.use + end + local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = if v then "TRUE" else "FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in v do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in roots do + table.insert(out, emit(r, "")) + end + for _, r in routes do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +-- the containerField a child element needs when it is not its type's default +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) + local function element(n: WNode, field: string): any + local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs :: any) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, if v then "true" else "false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in v do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs :: any, kids) + end + local sceneKids = {} + for _, r in roots do + table.insert(sceneKids, element(r, "children")) + end + for _, r in routes do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a :: any)) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "rosetta") + local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, if err then err.message else "xml" + end + return s, nil +end + +-- text(scene, opts) -> the file text +function Write.text(scene: any, o: Options): (string?, string?) + local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write +end +__FILES["codecs/model/Vrml/Xml"] = function() + +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one +-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; +-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their +-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; +-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and +-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / +-- meta, UNIT, component and the profile go into the graph header. Never throws. +local Xml = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER: { [string]: string } = { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in GEOMETRY do + CONTAINER[g] = "geometry" +end + +local function container(el: Xml.Node, typ: string): string + local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) + local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no root element" + end + local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs: { [string]: Parse.Node } = {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure: string? = nil + + local convert: (el: Xml.Node) -> Parse.Node? + local function route(el: Xml.Node) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare: (el: Xml.Node, extern: boolean) -> () + + -- the child elements of a node into its fields + local function children(el: Xml.Node, node: Parse.Node) + for _, ch in el.children do + if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then + continue + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in Xml.children(ch, "connect") do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then + continue -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, if name == "ProtoInstance" then "" else name) + local list = node.fields[f] + if type(list) ~= "table" or (list :: any).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end + end + end + + -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes + local function fieldValue(el: Xml.Node): any + if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in el.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el: Xml.Node, extern: boolean) + local name = el.attrs.name + if not name then + return + end + local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = if extern then el else Xml.child(el, "ProtoInterface") + if iface then + for _, f in Xml.children(iface, "field") do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in bodyEl.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el: Xml.Node): Parse.Node? + local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth += 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth -= 1 + return nil + end + local typ = Xml.localName(el.name) + local node: any + if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in Xml.children(el, "fieldValue") do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in a do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth -= 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in root.children do + if type(ch) ~= "table" then + continue + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in ch.children do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene: Parse.Node = { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in scene.fields do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in v do + table.insert(graph.roots, x) + end + end + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml +end +__FILES["codecs/text/Json"] = function() + +-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers +-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so +-- they write back as {}; opts.ordered makes every object a Types.object with its key order. +-- +-- local Json = require("@rosetta/codecs/text/Json") +-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input +-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err +-- for ev, x in Json.events(text) do ... end -- pull events without building the tree +-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values +-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() +-- +-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; +-- writer() builds output incrementally and flush() hands back the text so far. Never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/text/Json/Decode") +local Encode = __include("codecs/text/Json/Encode") + +local Json = {} + +type DecodeOptions = Decode.Options +type EncodeOptions = Encode.Options + +Json.null = Types.null +Json.object = Types.object +Json.keys = Types.keys +Json.set = Types.set + +local function text(src: any): (string?, Err.Err?) + if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function fail(msg: any, at: any, n: number): Err.Err + local m = tostring(msg) + local code = if string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n + then Err.TRUNCATED + elseif string.find(m, "nested deeper", 1, true) then Err.LIMIT + else Err.CORRUPT + return Err.new(code, m, at) +end + +-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is +-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. +function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?) + local s, terr = text(src) + if not s then + return nil, terr + end + local i = if string.sub(s, 1, 3) == "\239\187\191" then 4 else 1 + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + local e = string.match(s, "^[ \t\n\r]*()", ni) :: any + if e <= #s then + return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1) + end + return v, nil +end + +-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading +-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. +function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any) + local s, terr = text(src) + if not s then + return nil, terr + end + local i = string.match(s, "^[ \t\n\r]*()", pos or 1) :: any + if i > #s then + return nil, nil + end + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + return v, ni +end + +-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A +-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end +function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?) + local s, terr = text(src) + local pos = 1 + local index = 0 + local dead = false + return function(): (number?, any, Err.Err?) + if dead then + return nil + end + index += 1 + if not s then + dead = true + return index, nil, terr + end + local v, ni = Json.decodeAt(s, pos, opts) + if v == nil then + dead = true + if ni == nil then + return nil + end + return index, nil, ni + end + pos = ni + return index, v, nil + end +end + +-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), +-- "value" (a scalar), and on bad input one final "error", Err. +function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any) + local s, terr = text(src) + if not s then + local done = false + return function(): (string?, any) + if done then + return nil, nil + end + done = true + return "error", terr + end + end + local str: string = s + local i = if string.sub(str, 1, 3) == "\239\187\191" then 4 else 1 + local nextEv = Decode.events(str, i, opts) + return function(): (string?, any) + local ev, v, at = nextEv() + if ev == "error" then + return ev, fail(v, at, #str) + end + return ev, v + end +end + +-- encode(value, opts?) -> string | nil, Err +function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?) + local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return s, nil +end + +Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes +Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) + +-- ------------------------------------------------------------------------------------------------ writer +-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any +-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key +-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. +type Writer = { + err: Err.Err?, + beginObject: (self: Writer) -> Writer, + endObject: (self: Writer) -> Writer, + beginArray: (self: Writer) -> Writer, + endArray: (self: Writer) -> Writer, + key: (self: Writer, k: string) -> Writer, + value: (self: Writer, v: any) -> Writer, + flush: (self: Writer) -> string, + tostring: (self: Writer) -> (string?, Err.Err?), +} + +function Json.writer(opts: EncodeOptions?): Writer + local st = Encode.state(opts) + local ind = st.indent + local kinds: { boolean } = {} -- true = object + local counts: { number } = {} + local depth = 0 + local keyDone = false -- an object's key written, its value due + local flushed: { string } = {} + local w: any = { err = nil } + local function bad(msg: string) + if not w.err then + w.err = Err.new(Err.ARG, msg) + end + end + -- before an element: a comma / newline as needed; false when the position is wrong + local function slot(isKey: boolean): boolean + if w.err then + return false + end + if depth == 0 then + if counts[0] and counts[0] > 0 then + bad("one top-level value only") + return false + end + counts[0] = 1 + return true + end + local obj = kinds[depth] + if obj and not isKey then + if not keyDone then + bad("an object member needs a key first") + return false + end + keyDone = false + return true + end + if isKey and not obj then + bad("key outside an object") + return false + end + if isKey and keyDone then + bad("two keys in a row") + return false + end + if counts[depth] > 0 then + table.insert(st.out, ",") + end + counts[depth] += 1 + if ind then + table.insert(st.out, "\n" .. string.rep(ind, depth)) + end + return true + end + local function open(obj: boolean) + if slot(false) then + table.insert(st.out, if obj then "{" else "[") + depth += 1 + kinds[depth], counts[depth] = obj, 0 + end + return w + end + local function close(obj: boolean) + if w.err then + return w + end + if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then + bad(if obj then "unbalanced endObject" else "unbalanced endArray") + return w + end + if ind and counts[depth] > 0 then + table.insert(st.out, "\n" .. string.rep(ind, depth - 1)) + end + table.insert(st.out, if obj then "}" else "]") + depth -= 1 + return w + end + function w.beginObject(_self: Writer): Writer + return open(true) + end + function w.beginArray(_self: Writer): Writer + return open(false) + end + function w.endObject(_self: Writer): Writer + return close(true) + end + function w.endArray(_self: Writer): Writer + return close(false) + end + function w.key(_self: Writer, k: string): Writer + if type(k) ~= "string" then + bad("key must be a string") + elseif slot(true) then + table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (if ind then ": " else ":")) + keyDone = true + end + return w + end + function w.value(_self: Writer, v: any): Writer + if slot(false) then + st.n = #st.out + if not Encode.write(st, v, depth) then + bad(st.err or "cannot encode") + end + end + return w + end + function w.flush(_self: Writer): string + local s = table.concat(st.out) + table.clear(st.out) + st.n = 0 + table.insert(flushed, s) + return s + end + function w.tostring(_self: Writer): (string?, Err.Err?) + if w.err then + return nil, w.err + end + if depth ~= 0 then + return nil, Err.new(Err.ARG, "unclosed object / array") + end + return table.concat(flushed) .. table.concat(st.out), nil + end + return w :: Writer +end + +return Json +end +__FILES["codecs/text/Json/Decode"] = @native function() + + +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting +-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single +-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the +-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char +local tonumber = tonumber +local concat = table.concat + +type Options = { + ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are) + bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number") + null: any?, -- the value for null (default Types.null) + maxDepth: number?, -- nesting limit (default 1000) +} + +local ESC: { [number]: string } = { + [34] = '"', + [92] = "\\", + [47] = "/", + [98] = "\b", + [102] = "\f", + [110] = "\n", + [114] = "\r", + [116] = "\t", +} + +-- utf8 bytes of a code point (surrogates too: WTF-8) +local utf8char = Text.utf8char +Decode.utf8char = utf8char + +@native local function hex4(s: string, i: number): number? + local h = match(s, "^%x%x%x%x", i) + if not h then + return nil + end + return tonumber(h, 16) +end + +-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. +@native local function str(s: string, i: number): (string?, any, number?) + local j = find(s, '[%z\1-\31"\\]', i + 1) + if not j then + return nil, "unterminated string", #s + end + local c = byte(s, j) + if c == 34 then + return sub(s, i + 1, j - 1), j + 1 + end + local parts = {} + local np = 0 + local start = i + 1 + while true do + if c == 34 then + np += 1 + parts[np] = sub(s, start, j - 1) + return concat(parts), j + 1 + elseif c ~= 92 then + return nil, "control character in string", j - 1 + end + np += 1 + parts[np] = sub(s, start, j - 1) + local e = byte(s, j + 1) + if e == nil then + return nil, "unterminated string", #s + end + local simple = ESC[e] + if simple then + np += 1 + parts[np] = simple + start = j + 2 + elseif e == 117 then -- \u + local cp = hex4(s, j + 2) + if not cp then + return nil, "bad \\u escape", j - 1 + end + start = j + 6 + if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then + local lo = hex4(s, start + 2) + if lo and lo >= 0xDC00 and lo <= 0xDFFF then + cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00) + start += 6 + end + end + np += 1 + parts[np] = utf8char(cp) + else + return nil, "bad escape", j - 1 + end + j = find(s, '[%z\1-\31"\\]', start) + if not j then + return nil, "unterminated string", #s + end + c = byte(s, j) + end +end +Decode.string = str + +-- number(s, i) -> value, next | nil, message, offset +@native local function num(s: string, i: number, bigStrings: boolean): (any, any, number?) + local p = i + if byte(s, p) == 45 then + p += 1 + end + local c = byte(s, p) + if c == 48 then + p += 1 + elseif c and c >= 49 and c <= 57 then + p = match(s, "^%d*()", p + 1) :: any + else + return nil, if c == nil then "truncated: expected a value" elseif p == i then "unexpected character" else "bad number", p - 1 + end + local int = true + if byte(s, p) == 46 then + local q = match(s, "^%d+()", p + 1) + if not q then + return nil, "bad fraction", p + end + p = q :: any + int = false + end + c = byte(s, p) + if c == 101 or c == 69 then + p += 1 + c = byte(s, p) + if c == 43 or c == 45 then + p += 1 + end + local q = match(s, "^%d+()", p) + if not q then + return nil, "bad exponent", p - 1 + end + p = q :: any + int = false + end + local text = sub(s, i, p - 1) + local n = tonumber(text) :: number + if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow + local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)") + local mv = tonumber(m) or 0 + n = if mv == 0 then mv elseif es == "-" then mv * 0 else mv * math.huge + end + if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then + return text, p + end + return n, p +end +Decode.number = num + +-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace +-- skipped); next is the position after the value (trailing whitespace not skipped). +@native function Decode.value(s: string, i: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local ordered = o.ordered == true + local bigStrings = o.bigInts == "string" + local nullv = if o.null ~= nil then o.null else Types.null + local maxDepth = o.maxDepth or 1000 + local object = Types.object + + local stackT: { any } = {} -- containers + local stackK: { any } = {} -- object: the pending key; array: the count + local stackO: { any } = {} -- object: its key order (or true); array: false + local depth = 0 + local n = #s + local value: any + + while true do + i = match(s, "^[ \t\n\r]*()", i) :: any + local c = byte(s, i) + local haveValue = true + if c == 123 then -- { + depth += 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + local t = {} + c = byte(s, i) + if c == 125 then + i += 1 + depth -= 1 + value = object(t, {}) + elseif c == 34 then + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return nil, if i > n then "truncated object" else "expected ':'", i - 1 + end + i += 1 + stackT[depth], stackK[depth] = t, k + stackO[depth] = if ordered then {} else true + haveValue = false + else + return nil, if c == nil then "truncated object" else "expected a key", i - 1 + end + elseif c == 91 then -- [ + depth += 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + if byte(s, i) == 93 then + i += 1 + depth -= 1 + value = {} + else + stackT[depth], stackK[depth], stackO[depth] = {}, 0, false + haveValue = false + end + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return nil, ni, at + end + value, i = v, ni + elseif c == 116 then + if sub(s, i, i + 3) ~= "true" then + return nil, "bad literal", i - 1 + end + value, i = true, i + 4 + elseif c == 102 then + if sub(s, i, i + 4) ~= "false" then + return nil, "bad literal", i - 1 + end + value, i = false, i + 5 + elseif c == 110 then + if sub(s, i, i + 3) ~= "null" then + return nil, "bad literal", i - 1 + end + value, i = nullv, i + 4 + elseif c == nil then + return nil, "truncated: expected a value", n + else + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return nil, ni, at + end + value, i = v, ni + end + -- attach the value to the open containers, closing them as their ends come + while haveValue do + if depth == 0 then + return value, i + end + local t = stackT[depth] + local ord = stackO[depth] + if ord then + local k = stackK[depth] + if ord ~= true and t[k] == nil then + table.insert(ord, k) + end + t[k] = value + else + local cnt = stackK[depth] + 1 + t[cnt] = value + stackK[depth] = cnt + end + i = match(s, "^[ \t\n\r]*()", i) :: any + c = byte(s, i) + if c == 44 then -- , + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + if ord then + if byte(s, i) ~= 34 then + return nil, if i > n then "truncated object" else "expected a key", i - 1 + end + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return nil, if i > n then "truncated object" else "expected ':'", i - 1 + end + i += 1 + stackK[depth] = k + end + haveValue = false + elseif ord and c == 125 then + i += 1 + value = if ord ~= true then object(t, ord) elseif next(t) == nil then object(t, {}) else t + stackT[depth] = nil + depth -= 1 + elseif not ord and c == 93 then + i += 1 + value = t + stackT[depth] = nil + depth -= 1 + elseif c == nil then + return nil, if ord then "truncated object" else "truncated array", n + else + return nil, if ord then "expected ',' or '}'" else "expected ',' or ']'", i - 1 + end + end + end +end + +-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", +-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. +@native function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?) + local o: Options = opts or {} + local bigStrings = o.bigInts == "string" + local nullv = if o.null ~= nil then o.null else Types.null + local maxDepth = o.maxDepth or 1000 + local stack: { boolean } = {} -- true = object + local depth = 0 + -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), + -- "key" (a key expected), "done", "dead" + local state = "value" + local n = #s + @native local function fail(msg: string, at: number): (string, any, number) + state = "dead" + return "error", msg, at + end + return @native function(): (string?, any, number?) + if state == "dead" then + return nil + end + i = match(s, "^[ \t\n\r]*()", i) :: any + local c = byte(s, i) + if state == "done" then + state = "dead" + if c ~= nil then + return "error", "trailing data", i - 1 + end + return nil + end + if state == "after" then + local obj = stack[depth] + if c == 44 then + i = match(s, "^[ \t\n\r]*()", i + 1) :: any + c = byte(s, i) + state = if obj then "key" else "value" + elseif c == (if obj then 125 else 93) then + i += 1 + stack[depth] = nil + depth -= 1 + state = if depth == 0 then "done" else "after" + return if obj then "endObject" else "endArray", nil + elseif c == nil then + return fail("truncated", n) + else + return fail("expected ',' or a close", i - 1) + end + end + if state == "first" then + local obj = stack[depth] + if c == (if obj then 125 else 93) then + i += 1 + stack[depth] = nil + depth -= 1 + state = if depth == 0 then "done" else "after" + return if obj then "endObject" else "endArray", nil + end + state = if obj then "key" else "value" + end + if state == "key" then + if c ~= 34 then + return fail(if c == nil then "truncated" else "expected a key", i - 1) + end + local k, ni, at = str(s, i) + if k == nil then + return fail(ni, at :: number) + end + i = match(s, "^[ \t\n\r]*()", ni) :: any + if byte(s, i) ~= 58 then + return fail("expected ':'", i - 1) + end + i += 1 + state = "value" + return "key", k + end + -- a value + local after = if depth == 0 then "done" else "after" + if c == 123 or c == 91 then + depth += 1 + if depth > maxDepth then + return fail("nested deeper than " .. maxDepth, i - 1) + end + stack[depth] = c == 123 + i += 1 + state = "first" + return if c == 123 then "object" else "array", nil + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return fail(ni, at :: number) + end + i = ni + state = after + return "value", v + elseif c == 116 and sub(s, i, i + 3) == "true" then + i += 4 + state = after + return "value", true + elseif c == 102 and sub(s, i, i + 4) == "false" then + i += 5 + state = after + return "value", false + elseif c == 110 and sub(s, i, i + 3) == "null" then + i += 4 + state = after + return "value", nullv + elseif c == nil then + return fail("truncated: expected a value", n) + end + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return fail(ni, at :: number) + end + i = ni + state = after + return "value", v + end +end + +return Decode +end +__FILES["codecs/text/Json/Encode"] = @native function() + + +-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key +-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional +-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) +-- return nil, message. +local Types = __include("Types") + +local Encode = {} + +local byte, format, gsub = string.byte, string.format, string.gsub +local floor, huge = math.floor, math.huge +local concat = table.concat + +type Options = { + indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact + sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster) + ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is) + nan: ("error" | "null")?, -- NaN / inf: an error (default) or null + emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}") + maxDepth: number?, -- nesting limit (default 1000; also catches cycles) + escapeSlash: boolean?, -- write / as \/ (default false) +} + +local ESCAPES: { [string]: string } = { + ['"'] = '\\"', + ["\\"] = "\\\\", + ["\b"] = "\\b", + ["\f"] = "\\f", + ["\n"] = "\\n", + ["\r"] = "\\r", + ["\t"] = "\\t", + ["/"] = "\\/", +} +for c = 0, 31 do + local ch = string.char(c) + if not ESCAPES[ch] then + ESCAPES[ch] = format("\\u%04x", c) + end +end + +@native local function utf16(cp: number): string + if cp < 0x10000 then + return format("\\u%04x", cp) + end + cp -= 0x10000 + return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024) +end + +-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) +@native local function asciiSeq(seq: string): string + local out = {} + local i, n = 1, #seq + while i <= n do + local c = byte(seq, i) + local cp, len + if c < 0xC0 then + cp, len = c, 1 + elseif c < 0xE0 then + cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2 + elseif c < 0xF0 then + cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3 + else + cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4 + end + table.insert(out, utf16(cp)) + i += len + end + return concat(out) +end + +-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +@native local function quote(s: string, ascii: boolean?, slash: boolean?): string + local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]' + if string.find(s, pat) then + s = gsub(s, pat, ESCAPES) + end + if ascii and string.find(s, "[\127-\255]") then + s = gsub(s, "\127", "\\u007f") + s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq) + s = gsub(s, "[\128-\191]", asciiSeq) + end + return '"' .. s .. '"' +end +Encode.quote = quote + +local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } +-- number(x) -> the shortest text that reads back as x | nil for NaN / inf +@native local function number(x: number): string? + if x ~= x or x == huge or x == -huge then + return nil + end + if x == floor(x) and x > -1e15 and x < 1e15 then + if x == 0 and 1 / x < 0 then + return "-0" + end + return format("%d", x) + end + for _, f in FLOAT_FORMATS do + local t = format(f, x) + if tonumber(t) == x then + return t + end + end + return format("%.17g", x) +end +Encode.number = number + +@native local function keyLess(a: any, b: any): boolean + local ta, tb = type(a), type(b) + if ta ~= tb then + return ta == "number" + end + return a < b +end + +-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" +@native local function kind(t: { [any]: any }, emptyObject: boolean): string + if Types.isObject(t) then + return "object" + end + local n = #t + if n == 0 then + if next(t) == nil then + return if emptyObject then "object" else "array" + end + return "object" + end + local count = 0 + for _ in next, t do + count += 1 + end + return if count == n then "array" else "object" +end +Encode.kind = kind + +type State = { + out: { string }, + n: number, + indent: string?, + sort: boolean, + ascii: boolean, + slash: boolean, + nanNull: boolean, + emptyObject: boolean, + maxDepth: number, + null: any, + err: string?, +} + +@native local function put(st: State, s: string) + local n = st.n + 1 + st.out[n] = s + st.n = n +end + +@native local function value(st: State, v: any, depth: number): boolean + local tv = type(v) + if tv == "string" then + put(st, quote(v, st.ascii, st.slash)) + elseif tv == "number" then + local s = number(v) + if not s then + if not st.nanNull then + st.err = "cannot encode " .. tostring(v) + return false + end + s = "null" + end + put(st, s) + elseif tv == "boolean" then + put(st, if v then "true" else "false") + elseif v == nil or v == st.null or v == Types.null then + put(st, "null") + elseif tv == "table" then + if Types.Date.is(v) then + put(st, '"' .. tostring(v) .. '"') + return true + end + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + local ind = st.indent + local nl, nl2 = "", "" + if ind then + nl = "\n" .. string.rep(ind, depth + 1) + nl2 = "\n" .. string.rep(ind, depth) + end + if kind(v, st.emptyObject) == "array" then + local n = #v + if n == 0 then + put(st, "[]") + return true + end + put(st, "[") + for i = 1, n do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + if not value(st, v[i], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "]") + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + local tk = type(k) + if tk ~= "string" and tk ~= "number" then + st.err = "object key of type " .. tk + return false + end + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + put(st, "{}") + return true + end + put(st, "{") + local sep = if ind then ": " else ":" + for i, k in keys do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + local ks: string + if type(k) == "string" then + ks = k + elseif type(k) == "number" then + ks = number(k) or tostring(k) + else + st.err = "object key of type " .. type(k) + return false + end + put(st, quote(ks, st.ascii, st.slash)) + put(st, sep) + if not value(st, v[k], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "}") + end + elseif tv == "buffer" then + st.err = "cannot encode a buffer (encode it as base64 or an array first)" + return false + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +@native local function state(opts: Options?, nullv: any?): State + local o: Options = opts or {} + local ind: string? = nil + if type(o.indent) == "number" then + ind = if o.indent > 0 then string.rep(" ", o.indent) else nil + elseif type(o.indent) == "string" then + ind = o.indent + end + return { + out = {}, + n = 0, + indent = ind, + sort = o.sortKeys ~= false, + ascii = o.ascii == true, + slash = o.escapeSlash == true, + nanNull = o.nan == "null", + emptyObject = o.emptyTable == "object", + maxDepth = o.maxDepth or 1000, + null = nullv, + err = nil, + } +end +Encode.state = state +Encode.write = value + +-- encode(v, opts) -> text | nil, message +@native function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?) + local st = state(opts, nullv) + if not value(st, v, 0) then + return nil, st.err + end + return concat(st.out), nil +end + +return Encode +end +__FILES["codecs/text/Nbt"] = function() + +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, +-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat +-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ +-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers +-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order +-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. +-- +-- local Nbt = require("@rosetta/codecs/text/Nbt") +-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored +-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value +-- v.Data.Difficulty = Nbt.byte(2) +-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts +-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} +-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') +-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag +-- +-- Never throws: bad data and bad values return nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Value = __include("codecs/text/Nbt/Value") +local Binary = __include("codecs/text/Nbt/Binary") +local Snbt = __include("codecs/text/Nbt/Snbt") + +local Nbt = {} + +type Tag = Value.Tag +type Info = { + name: string, -- the root tag's name + endian: "big" | "little", + varint: boolean?, -- Bedrock network NBT + compression: "gzip" | "zlib" | "none", + header: number?, -- Bedrock level.dat: the storage version from the 8-byte header +} +type DecodeOptions = { + endian: ("big" | "little")?, -- default: detected (Java big-endian first) + varint: boolean?, -- Bedrock network NBT + nameless: boolean?, -- no root name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) +} +type EncodeOptions = { + endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + varint: boolean?, + nameless: boolean?, + name: string?, -- the root name (default: Nbt.info(value).name, else "") + compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian + header: number?, -- write the Bedrock level.dat header with this version + level: number?, -- deflate level 0..9 (default 6) +} + +Nbt.TAG = Value.IDS -- name -> id +Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any + +-- info(value) -> how a decoded root was stored (nil for values not from decode) +function Nbt.info(v: any): Info? + return if type(v) == "table" then infos[v] else nil +end +-- setInfo(value, info): what encode uses as defaults +function Nbt.setInfo(v: any, info: Info) + if type(v) == "table" then + infos[v] = info + end +end + +-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag +function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) + local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts :: any) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag +function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local out, e = Binary.write(v, opts :: any) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic +function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) + local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = if l >= 2 then buffer.readu8(b, o) else 0 + local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 + local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + +type Peek = { + compression: string, -- "gzip" | "zlib" | "none" + endian: "big" | "little", + header: boolean, -- a Bedrock level.dat header + rootType: string, -- "compound" (or "list") + name: string, -- the root name + firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + firstName: string?, + head: buffer, -- the first (up to 1024) uncompressed bytes +} + +local function plausibleName(b: buffer, p: number, n: number): string? + if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a +-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. +function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? + local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head: buffer + local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, if c0 == 0x1f then "gzip" else "zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p: number, endian: string, header: boolean): Peek? + if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q: number): number + local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return if endian == "big" then a * 256 + b else b * 256 + a + end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" -- an empty root compound + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java +-- or Bedrock) +function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) + local o: DecodeOptions = opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data: buffer, start: number, stop: number = b, s, e :: number + local function try(endian: string, from: number, varint: boolean?): (any, any, number?) + return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header: number? = nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info: Info = { + name = name, + endian = if o.varint or o.endian == "little" then "little" else "big", + varint = if o.varint then true else nil, + compression = comp :: any, + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file +function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = if o.varint ~= nil then o.varint else (info and info.varint) + local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = if o.header ~= nil then o.header else (info and info.header) + if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +-- parse(text, opts?) -> value | nil, Err: SNBT +function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) + local s = if type(text) == "buffer" then buffer.tostring(text) else text + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) +function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) + local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) +function Nbt.get(v: any, path: string): any + local cur = v + for part in string.gmatch(path, "[^%.]+") do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do + local i = tonumber(idx) :: number + if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt +end +__FILES["codecs/text/Nbt/Binary"] = function() + +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from +-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / +-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against +-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Binary = {} + +type Options = { + endian: ("big" | "little")?, -- default "big" (Java) + varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" + nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + name: string?, -- write: the root name (default "") +} + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } + +-- ------------------------------------------------------------------------------------------------ modified UTF-8 +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) +local function fromModified(s: string): string + if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i += 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i += 6 + else + table.insert(out, string.char(c)) + i += 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s: string): string + if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i += 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) + i += 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +-- ------------------------------------------------------------------------------------------------ read +local function fail(s: State, msg: string): nil + if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s: State, n: number): boolean + if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s: State): number + if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p += 1 + return v +end + +local function varuint(s: State): number -- up to 32 bits (5 bytes) + local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + v += (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul *= 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s: State): number + if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return if v >= 32768 then v - 65536 else v +end + +local function u32raw(s: State): number + if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return if s.le then v else byteswap(v) +end + +local function i32(s: State): number + if s.net then + local n = varuint(s) + return if n % 2 == 0 then n // 2 else -(n + 1) // 2 + end + local v = u32raw(s) + return if v >= 0x80000000 then v - TWO32 else v +end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s: State): number + return i32(s) +end + +local function i64(s: State): (number, number) -- hi, lo + if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo += x % TWO32 + hi = (hi + x // TWO32) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh += 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = lo // 2 + (hi % 2) * 0x80000000 + hi = hi // 2 + if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s: State): number + local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s: State): number + local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s: State): string + local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p += n + return if s.java then fromModified(v) else v +end + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, newTag) +end + +-- the smallest encoded size of one element, to bound list lengths before allocating +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload: (State, number) -> any + +local function count(s: State, n: number, size: number): boolean + if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s: State, id: number): any + if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth -= 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p += 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p += n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then + return nil + end + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth -= 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, if s.net then 1 else 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, if s.net then 1 else 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p += n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at +function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s: State = { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = if o.nameless then "" else str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end + +-- ------------------------------------------------------------------------------------------------ write +type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } + +local function wvaruint(w: Bytes.Writer, v: number) + v %= TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v //= 128 + end + w:u8(v) +end + +local function wi32(ws: WState, v: number) + v %= TWO32 -- two's complement + if ws.net then + local sv = if v >= 0x80000000 then v - TWO32 else v + wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws: WState, v: number) + v %= 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws: WState, hi: number, lo: number) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = zl // 128 + (zh % 128) * 0x2000000 + zh //= 128 + end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws: WState, s: string): string? + local v = if ws.java then toModified(s) else s + if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) + local n = if type(v) == "boolean" then (if v then 1 else 0) else v + if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload: (WState, string, any) -> string? + +local function wlist(ws: WState, v: { any }): string? + local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt :: string]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt :: string, x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws: WState, t: string, v: any): string? + local w = ws.w + local x = if Value.isTag(v) then v.value else v + if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct :: string]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct :: string, c) + if e then + return e + end + end + w:u8(0) + ws.depth -= 1 + elseif t == "list" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth -= 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo :: number) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = buffer.len(x) // 8 + wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +-- write(value, opts?) -> buffer | nil, message +function Binary.write(v: any, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t :: string]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t :: string, v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary +end +__FILES["codecs/text/Nbt/Snbt"] = function() + +-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the +-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] +-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted +-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex +-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing +-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's +-- compact form (or indented); floats print as the shortest text that reads back to the same value. +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Snbt = {} + +type ParseOptions = { maxDepth: number? } +type PrintOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes +} + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, Value.TagMeta) +end + +-- ------------------------------------------------------------------------------------------------ parse +type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } + +local function fail(p: P, msg: string): nil + if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p: P) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e :: number) + 1 +end + +local function isUnquoted(c: number): boolean + return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p: P): string? + local q = sub(p.s, p.i, p.i) + p.i += 1 + local out = {} + while true do + local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 + local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = tonumber(hex, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +-- number text -> a value, or nil when it is not a number (then it is an unquoted string) +local INT_RANGE: { [string]: { number } } = { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t: string): any + local sign, body = string.match(t, "^([+-]?)(.+)$") + body = string.gsub(body :: string, "_", "") :: string + local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m :: string, string.lower(sfx :: string) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + -- the magnitude as (hi, lo) + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 + local x = lo * radix + d + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) + elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v -= r[3] + 1 + end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t: string): any + local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) + elseif low == "nanf" or low == "nand" then + return tag(if sfx == "f" then "float" else "double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant :: string, ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs :: string) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue: (P) -> any + +local function token(p: P): string + local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j += 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p: P): string? + ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p: P, kind: string): any + local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = if t ~= "" then number(t) else nil + local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x: any = if Value.isTag(v) then (v :: any).value else v + if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i += 1 + if c == "]" then + break + elseif c ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + else + p.i += 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in items do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p: P): any + ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i += 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k :: string] == nil then + table.insert(keys, k) + end + o[k :: string] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "}" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + break + end + end + end + p.depth -= 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e :: number) + 1 + local v = array(p, ARRAY[kind]) + p.depth -= 1 + return v + end + local items = {} + local lt: string? = nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "]" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + end + p.depth -= 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +-- parse(text, opts?) -> value | nil, message, position (1-based) +function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) + local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +-- ------------------------------------------------------------------------------------------------ print +local function shortest(v: number, single: boolean): string + if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = if single then 6 else 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = tonumber(s) :: number + if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s ..= ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s: string, q: string): string + local other = if q == '"' then "'" else '"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string + if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k: string, q: string): string + if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + +type Pr = { out: { string }, indent: string?, q: string, depth: number } + +local printValue: (Pr, any, number) -> string? + +local function scalar(v: any, q: string): string? + local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return if v then "1b" else "0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return (if type(x) == "string" then x else string.format("%d", x)) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr: Pr, head: string, items: { string }, close: string) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) + end +end + +local function sub1(pr: Pr, v: any): (string?, string?) + local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr: Pr, v: any, depth: number): string? + if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = table.create(buffer.len(v)) :: { string } + for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in v.value do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in Value.longs(v) do + items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items: { string } = {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x :: string + end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) + end + seq(pr, "{", items, "}") + end + return nil +end + +-- print(value, opts?) -> text | nil, message +function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) + local o: PrintOptions = opts or {} + local ind = o.indent + local pr: Pr = { + out = {}, + indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, + q = if o.quote == "'" then "'" else '"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v: any): string + return Snbt.print(v) or "?" +end + +return Snbt +end +__FILES["codecs/text/Nbt/Value"] = function() + +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- Plain Luau values with typed numbers, so a decode / encode round trip is exact: +-- int -> number string -> string byteArray -> buffer +-- compound -> Types.object (key order kept) list -> array (element type in Value.listType) +-- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a +-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal +-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. +-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as +-- byte 1 / 0; a plain table with string keys as a compound. +local Types = __include("Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} :: { [number]: string } +Value.IDS = {} :: { [string]: number } +for id = 0, 12 do + Value.IDS[Value.NAMES[id]] = id +end + +type Tag = { type: string, value: any } + +local TagMeta: { [string]: any } = {} +Value.TagMeta = TagMeta +-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) +Value.print = function(v: any): string + return tostring(v.value) +end +TagMeta.__tostring = function(v: any): string + return Value.print(v) +end +TagMeta.__eq = function(a: any, b: any): boolean + if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any + +-- ------------------------------------------------------------------------------------------------ 64-bit integers +local TWO32 = 4294967296 + +-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the +-- two's complement int64) +function Value.fromHiLo(hi: number, lo: number): number | string + local s = if hi >= 0x80000000 then hi - TWO32 else hi + if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = hi // 10000 + local x = (hi - qh * 10000) * TWO32 + lo + local ql = x // 10000 + local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) + end + return (if neg then "-" else "") .. table.concat(parts) +end + +-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text +function Value.toHiLo(v: any): (number?, number?) + if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = v // TWO32 + local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +local function tag(name: string, v: any): Tag + return setmetatable({ type = name, value = v }, TagMeta) :: any +end +function Value.byte(n: number): Tag + return tag("byte", n) +end +function Value.short(n: number): Tag + return tag("short", n) +end +function Value.int(n: number): number + return n +end +-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) +function Value.long(v: number | string): Tag + if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo :: number) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +-- float(n) -> a float tag holding n rounded to single precision +function Value.float(n: number): Tag + buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n: number): Tag + return tag("double", n) +end +function Value.intArray(t: { number }?): Tag + return tag("intArray", t or {}) +end +-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) +function Value.longArray(t: { any } | buffer | nil): Tag + if type(t) == "buffer" then + return tag("longArray", t) + end + local list: { any } = (t or {}) :: any + local b = buffer.create(#list * 8) + for i, x in list do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +-- longs(longArray) -> { number | string }: the elements as long values +function Value.longs(a: Tag): { number | string } + local b: buffer = a.value + local out = table.create(buffer.len(b) // 8) :: { number | string } + for i = 0, buffer.len(b) // 8 - 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) +function Value.list(name: string, items: { any }?): { any } + local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } + return Types.object(t, keys) +end +-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) +function Value.listType(t: any): string? + return listTypes[t] +end +function Value.setListType(t: any, name: string) + listTypes[t] = name +end +function Value.isTag(v: any): boolean + return type(v) == "table" and getmetatable(v) == TagMeta +end + +-- typeOf(v) -> the tag name v writes as, or nil + why +function Value.typeOf(v: any): (string?, string?) + local tv = type(v) + if tv == "number" then + return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) +function Value.number(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value +end +__FILES["codecs/text/Text"] = function() + + +-- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +-- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +local Text = {} + +-- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) +function Text.utf8char(c: number): string + local char = string.char + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) +Text.CP1252 = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +function Text.trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +-- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates +-- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. +function Text.utf16(b: buffer, o: number, n: number, bigEndian: boolean?): string + local out = {} + local k = 0 + local readu16 = buffer.readu16 + local function unit(at: number): number + local v = readu16(b, at) + return if bigEndian then (v % 256) * 256 + v // 256 else v + end + while k + 1 < n do + local c = unit(o + k) + k += 2 + if c >= 0xD800 and c < 0xDC00 and k + 1 < n then + local lo = unit(o + k) + if lo >= 0xDC00 and lo < 0xE000 then + c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) + k += 2 + end + end + if c >= 0xD800 and c < 0xE000 then + c = 0xFFFD + end + table.insert(out, Text.utf8char(c)) + end + return table.concat(out) +end + +-- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 +function Text.toUtf8(text: string, warnings: { string }?): string + if string.sub(text, 1, 3) == "\239\187\191" then + text = string.sub(text, 4) + end + if utf8.len(text) then + return text + end + if warnings then + table.insert(warnings, "text is not UTF-8: read as Windows-1252") + end + local out = table.create(#text) + for i = 1, #text do + local b = string.byte(text, i) + if b < 0x80 then + out[i] = string.char(b) + else + out[i] = utf8.char(if b < 0xA0 then Text.CP1252[b] or 0xFFFD else b) + end + end + return table.concat(out) +end + +function Text.lines(text: string): { string } + text = string.gsub(text, "\r\n?", "\n") + local out = {} + for line in string.gmatch(text .. "\n", "([^\n]*)\n") do + table.insert(out, line) + end + return out +end + +return Text +end +__FILES["codecs/text/Url"] = function() + + +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +-- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI +-- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its +-- init.luau. Never throws. +local Url = {} + +type Location = { url: string, playable: boolean, reason: string?, [string]: any } + +type Parts = { + scheme: string?, + authority: string?, + path: string, + query: string?, + fragment: string?, +} + +-- Splits a URI reference into its five components (RFC 3986 appendix B). +function Url.split(ref: string): Parts + local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") + if not scheme then + rest = ref + end + local s = rest :: string + local fragment, query, authority + local i = string.find(s, "#", 1, true) + if i then + fragment = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + i = string.find(s, "?", 1, true) + if i then + query = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + if string.sub(s, 1, 2) == "//" then + local j = string.find(s, "/", 3, true) + if j then + authority = string.sub(s, 3, j - 1) + s = string.sub(s, j) + else + authority = string.sub(s, 3) + s = "" + end + end + return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } +end + +-- Recomposes components (RFC 3986 section 5.3). +function Url.join(p: Parts): string + local out = {} + if p.scheme then + table.insert(out, p.scheme .. ":") + end + if p.authority then + table.insert(out, "//" .. p.authority) + end + table.insert(out, p.path) + if p.query then + table.insert(out, "?" .. p.query) + end + if p.fragment then + table.insert(out, "#" .. p.fragment) + end + return table.concat(out) +end + +-- RFC 3986 section 5.2.4 +function Url.removeDotSegments(path: string): string + local input = path + local output = {} + while input ~= "" do + if string.sub(input, 1, 3) == "../" then + input = string.sub(input, 4) + elseif string.sub(input, 1, 2) == "./" then + input = string.sub(input, 3) + elseif string.sub(input, 1, 3) == "/./" then + input = string.sub(input, 3) + elseif input == "/." then + input = "/" + elseif string.sub(input, 1, 4) == "/../" then + input = string.sub(input, 4) + table.remove(output) + elseif input == "/.." then + input = "/" + table.remove(output) + elseif input == "." or input == ".." then + input = "" + else + -- move the first segment (with its leading "/", up to the next "/") to the output + local j = string.find(input, "/", 2, true) + local seg = if j then string.sub(input, 1, j - 1) else input + table.insert(output, seg) + input = string.sub(input, #seg + 1) + end + end + return table.concat(output) +end + +-- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +function Url.resolve(ref: string, base: string): string + local r, b = Url.split(ref), Url.split(base) + local t: Parts = { path = "" } + if r.scheme then + t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query + else + if r.authority then + t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query + else + if r.path == "" then + t.path = b.path + t.query = if r.query then r.query else b.query + else + if string.sub(r.path, 1, 1) == "/" then + t.path = Url.removeDotSegments(r.path) + else + -- merge (5.2.3) + local merged + if b.authority and b.path == "" then + merged = "/" .. r.path + else + local k = string.match(b.path, "^.*()/") + merged = (if k then string.sub(b.path, 1, k) else "") .. r.path + end + t.path = Url.removeDotSegments(merged) + end + t.query = r.query + end + t.authority = b.authority + end + t.scheme = b.scheme + end + t.fragment = r.fragment + return Url.join(t) +end + +-- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), +-- leaving existing %XX escapes and the reserved delimiters alone. +function Url.encodeUnsafe(s: string): string + return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c: string): string + return string.format("%%%02X", string.byte(c)) + end)) +end + +-- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? +function Url.isWindowsPath(s: string): boolean + return string.match(s, "^%a:[\\/]") ~= nil + or string.match(s, "^%a:$") ~= nil + or string.sub(s, 1, 2) == "\\\\" + or string.sub(s, 1, 1) == "\\" +end + +-- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. +function Url.scheme(s: string): string? + if Url.isWindowsPath(s) then + return nil + end + local scheme = string.match(s, "^([%a][%w+%.%-]*):") + return if scheme then string.lower(scheme) else nil +end + +-- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's +-- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and +-- schemes other than http(s) are not playable (reason says why). +function Url.locate(raw: string, base: string?, baseScheme: string?): Location + local loc = (string.match(raw, "^%s*(.-)%s*$") :: string) + if Url.isWindowsPath(loc) then + return { url = loc, playable = false, reason = "local path" } + end + local scheme = Url.scheme(loc) + local url = loc + if not scheme and baseScheme == "windows" and base then + -- a playlist on a Windows disk: relative entries are paths next to it + local dir = string.match(base, "^(.*[\\/])") or "" + return { url = dir .. loc, playable = false, reason = "local path" } + end + if scheme then + if scheme == "http" or scheme == "https" then + url = Url.encodeUnsafe(Url.resolve(loc, loc)) + end + elseif base and baseScheme then + -- a relative reference: Windows separators become URL ones + url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) + scheme = baseScheme + else + return { url = loc, playable = false, reason = "relative path without a base URL" } + end + if scheme == "http" or scheme == "https" then + return { url = url, playable = true } + elseif scheme == "file" then + return { url = url, playable = false, reason = "local path" } + end + return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } +end + +-- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" +-- for a Windows path); a non-absolute base is ignored (with a warning) +function Url.base(baseUrl: string?, warnings: { string }?): (string?, string?) + if type(baseUrl) ~= "string" or baseUrl == "" then + return nil, nil + end + local s = Url.scheme(baseUrl) + if s and Url.split(baseUrl).authority ~= nil or s == "file" then + return Url.encodeUnsafe(baseUrl), s + elseif Url.isWindowsPath(baseUrl) then + return baseUrl, "windows" + end + if warnings then + table.insert(warnings, "base URL is not absolute: " .. baseUrl) + end + return nil, nil +end + +return Url +end +__FILES["codecs/text/Xml"] = function() + +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +-- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal +-- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces +-- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives +-- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. +-- +-- local Xml = require("@rosetta/codecs/text/Xml") +-- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element +-- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end +-- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) +-- local s = Xml.encode(doc, { indent = 2 }) +-- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees +-- +-- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string }, +-- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and +-- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI +-- target); otherwise CDATA merges into the text and the others are dropped. Never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Parse = __include("codecs/text/Xml/Parse") + +local Xml = {} + +type Node = Types.XmlNode +type DecodeOptions = Parse.Options & { + comments: boolean?, -- keep comments as "#comment" nodes (default false) + cdata: boolean?, -- keep CDATA sections as "#cdata" nodes (default false: merged into the text) + pi: boolean?, -- keep processing instructions as "#pi" nodes (default false) + parents: boolean?, -- set node.parent (default true) +} +type EncodeOptions = { + indent: (number | string)?, -- pretty print elements that hold only elements (default none) + declaration: boolean?, -- write (default: true for a "#document") + selfClose: boolean?, -- for empty elements (default true) +} + +local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match + +local function text(src: any): (string?, Err.Err?) + if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function errCode(msg: string, at: number, n: number): string + if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then + return Err.TRUNCATED + elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then + return Err.LIMIT + elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + end + return Err.CORRUPT +end + +-- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, +-- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) +function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) + local s, terr = text(src) + local u, enc = nil, "" + if s then + u, enc = Parse.toUtf8(s) + end + if not u then + local e = terr or Err.new(if find(enc, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT, enc) + local done = false + return function(): (string?, any, any, any) + if done then + return nil + end + done = true + return "error", e + end + end + local str: string = u + local nextEv = Parse.events(str, opts) + return function(): (string?, any, any, any) + local ev, a, b, c = nextEv() + if ev == "error" then + return ev, Err.new(errCode(a, b, #str), a, b) + end + return ev, a, b, c + end +end + +-- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version, +-- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus +-- any kept comments / PIs around it. +function Xml.decode(src: string | buffer, opts: DecodeOptions?): (Node?, Err.Err?) + local o: DecodeOptions = opts or {} + local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true + local parents = o.parents ~= false + local doc: any = { name = "#document", attrs = Types.object(), children = {}, parent = nil } + local cur: any = doc + local stack = { doc } + local depth = 1 + for ev, a, b, c in Xml.events(src, o) do + if ev == "start" then + local node: any = { name = a, attrs = b, children = {}, parent = if parents then cur else nil } + if c then + node.ns = c + end + table.insert(cur.children, node) + depth += 1 + stack[depth] = node + cur = node + if depth == 2 then + doc.root = node + end + elseif ev == "end" then + stack[depth] = nil + depth -= 1 + cur = stack[depth] + elseif ev == "text" or (ev == "cdata" and not keepCdata) then + local ch = cur.children + local last = #ch + if last > 0 and type(ch[last]) == "string" then + ch[last] ..= a + else + ch[last + 1] = a + end + elseif ev == "cdata" then + table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) + elseif ev == "comment" then + if keepComments then + table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = if parents then cur else nil }) + end + elseif ev == "pi" then + if keepPi then + table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = if parents then cur else nil }) + end + elseif ev == "decl" then + doc.declaration = a + elseif ev == "doctype" then + doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities } + elseif ev == "error" then + return nil, a + end + end + return doc, nil +end + +-- ------------------------------------------------------------------------------------------------ tree helpers +-- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object; +-- children: nodes or strings; their parent is set) +function Xml.element(name: string, attrs: { [string]: string }?, children: { any }?): Node + local a = attrs or Types.object() + if not Types.isObject(a) then + local keys = {} + for k in next, a do + table.insert(keys, k) + end + table.sort(keys) + a = Types.object(a, keys) + end + local node: any = { name = name, attrs = a, children = children or {} } + for _, ch in node.children do + if type(ch) == "table" then + ch.parent = node + end + end + return node +end + +-- document(root, declaration?) -> a "#document" node around root +function Xml.document(root: Node, declaration: { [string]: string }?): Node + local doc: any = { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } + root.parent = doc + return doc +end + +-- append(parent, child) -> child (a node or a string), parent link set +function Xml.append(parent: Node, child: any): any + table.insert(parent.children, child) + if type(child) == "table" then + child.parent = parent + end + return child +end + +-- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order +function Xml.setAttr(node: Node, name: string, value: string?) + Types.set(node.attrs, name, value) +end + +-- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and +-- the child's does), in order +function Xml.children(node: Node, name: string?): { Node } + local out = {} + for _, ch in node.children do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + table.insert(out, ch) + end + end + end + return out +end + +-- child(node, name?) -> the first matching element child, or nil +function Xml.child(node: Node, name: string?): Node? + for _, ch in node.children do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + return ch + end + end + end + return nil +end + +-- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does +function Xml.descendants(node: Node, name: string?): { Node } + local out = {} + local function walk(n: Node) + for _, ch in n.children do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name :: string, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + table.insert(out, ch) + end + walk(ch) + end + end + end + walk(node) + return out +end + +-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not) +function Xml.text(node: any): string + if type(node) == "string" then + return node + end + if node.name == "#cdata" then + return node.text or "" + end + local parts = {} + local function walk(n: any) + for _, ch in n.children do + if type(ch) == "string" then + table.insert(parts, ch) + elseif ch.name == "#cdata" then + table.insert(parts, ch.text or "") + elseif string.byte(ch.name) ~= 35 then + walk(ch) + end + end + end + walk(node) + return table.concat(parts) +end + +-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect") +function Xml.prefix(name: string): string + return match(name, "^([^:]*):") or "" +end +function Xml.localName(name: string): string + return match(name, ":(.*)$") or name +end + +-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its +-- ancestors' xmlns attributes (needs parent links) +function Xml.namespace(node: Node, prefix: string?): string? + return Parse.resolve(node, prefix or Xml.prefix(node.name)) +end + +-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes +-- (unprefixed attributes have no namespace) +function Xml.clark(node: Node, attrName: string?): string + local name = attrName or node.name + local prefix = Xml.prefix(name) + if attrName and prefix == "" then + return name + end + local uri = Parse.resolve(node, prefix) + if uri then + return "{" .. uri .. "}" .. Xml.localName(name) + end + return name +end + +-- ------------------------------------------------------------------------------------------------ encode +local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } +local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } + +-- escape(s) / escapeAttr(s): text / attribute-value escaping +function Xml.escape(s: string): string + return (gsub(s, "[&<>\r]", TEXT_ESC)) +end +function Xml.escapeAttr(s: string): string + return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC)) +end + +local function badName(name: any): boolean + return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") +end + +-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...) +function Xml.encode(node: Node, opts: EncodeOptions?): (string?, Err.Err?) + local o: EncodeOptions = opts or {} + local ind: string? = nil + if type(o.indent) == "number" then + ind = if o.indent > 0 then string.rep(" ", o.indent) else nil + elseif type(o.indent) == "string" then + ind = o.indent + end + local selfClose = o.selfClose ~= false + local out: { string } = {} + local err: string? = nil + local seen: { [any]: boolean } = {} + + local write: (n: any, depth: number) -> () + function write(n: any, depth: number) + if err then + return + end + if type(n) == "string" then + table.insert(out, Xml.escape(n)) + return + end + if type(n) ~= "table" or type(n.name) ~= "string" then + err = "a child is not a node or a string" + return + end + if seen[n] then + err = "a node appears twice (a cycle?)" + return + end + seen[n] = true + local name = n.name + if name == "#comment" then + local t = n.text or "" + if find(t, "--", 1, true) or sub(t, -1) == "-" then + err = "comment text contains '--'" + return + end + table.insert(out, "") + elseif name == "#cdata" then + table.insert(out, "", "]]]]>") .. "]]>") + elseif name == "#pi" then + if badName(n.target) or find(n.text or "", "?>", 1, true) then + err = "bad processing instruction" + return + end + table.insert(out, "") + elseif name == "#doctype" then + table.insert(out, "") + elseif name == "#document" then + for i, ch in n.children do + if i > 1 and ind then + table.insert(out, "\n") + end + write(ch, 0) + end + else + if badName(name) then + err = "bad element name " .. tostring(name) + return + end + table.insert(out, "<" .. name) + local attrs = n.attrs or {} + for _, k in Types.keys(attrs) do + local v = attrs[k] + if badName(k) then + err = "bad attribute name " .. tostring(k) + return + end + if type(v) == "number" or type(v) == "boolean" then + v = tostring(v) + elseif type(v) ~= "string" then + err = "attribute " .. k .. " is not a string" + return + end + table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') + end + local ch = n.children or {} + if #ch == 0 then + table.insert(out, if selfClose then "/>" else ">") + return + end + table.insert(out, ">") + local pretty = ind ~= nil + if pretty then + for _, c in ch do + if type(c) == "string" or c.name == "#cdata" then + pretty = false + break + end + end + end + for _, c in ch do + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth + 1)) + end + write(c, depth + 1) + end + if pretty then + table.insert(out, "\n" .. string.rep(ind :: string, depth)) + end + table.insert(out, "") + end + end + + local decl = o.declaration + if decl == nil then + decl = node.name == "#document" + end + if decl then + local d: any = node.declaration or {} + table.insert(out, '") + table.insert(out, "\n") + end + if node.name == "#document" and node.doctype then + local dt: any = node.doctype + local raw = dt.raw + if raw == nil then + raw = " " .. (dt.name or (if node.root then node.root.name else "root")) + if dt.publicId then + raw ..= ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' + elseif dt.systemId then + raw ..= ' SYSTEM "' .. dt.systemId .. '"' + end + end + table.insert(out, "\n") + end + write(node, 0) + if err then + return nil, Err.new(Err.ARG, err) + end + if ind and node.name == "#document" then + table.insert(out, "\n") + end + return table.concat(out), nil +end + +return Xml +end +__FILES["codecs/text/Xml/Parse"] = @native function() + + +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the +-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, +-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, +-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: +-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), +-- validation. Never throws: errors are events. +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Parse = {} + +local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower + +type Options = { + whitespace: boolean?, -- keep whitespace-only text (default false: dropped, except inside xml:space="preserve") + namespaces: boolean?, -- resolve namespace prefixes: "start" events carry the element's URI (default false) + entities: { [string]: string }?, -- extra general entities (name -> replacement text) + maxExpansion: number?, -- total characters produced by entity expansion (default 1e7; the billion laughs guard) + maxDepth: number?, -- element nesting limit (default 10000) +} + +local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" +local PREDEF: { [string]: string } = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } + +local utf8char = Text.utf8char +Parse.utf8char = utf8char + +local CP1252: { [number]: number } = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +@native local function utf16(s: string, start: number, le: boolean): (string?, string?) + local out = table.create(#s // 2) + local n = 0 + local i = start + local len = #s + while i + 1 <= len do + local a, b = byte(s, i, i + 1) + local u = if le then a + b * 256 else a * 256 + b + i += 2 + if u >= 0xD800 and u <= 0xDBFF then + if i + 1 > len then + return nil, "truncated UTF-16 surrogate pair" + end + local c, d = byte(s, i, i + 1) + local lo = if le then c + d * 256 else c * 256 + d + if lo < 0xDC00 or lo > 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + i += 2 + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + elseif u >= 0xDC00 and u <= 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + n += 1 + out[n] = utf8char(u) + end + if i <= len then + return nil, "odd number of bytes in UTF-16 text" + end + return table.concat(out), nil +end + +-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message +@native function Parse.toUtf8(s: string): (string?, string) + local b1, b2, b3 = byte(s, 1, 3) + if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then + return sub(s, 4), "utf-8" + elseif b1 == 0xFF and b2 == 0xFE then + local t, e = utf16(s, 3, true) + return t, e or "utf-16le" + elseif b1 == 0xFE and b2 == 0xFF then + local t, e = utf16(s, 3, false) + return t, e or "utf-16be" + elseif b1 == 0x3C and b2 == 0 then + local t, e = utf16(s, 1, true) + return t, e or "utf-16le" + elseif b1 == 0 and b2 == 0x3C then + local t, e = utf16(s, 1, false) + return t, e or "utf-16be" + end + local decl = match(s, "^<%?xml[^>]-%?>") + local enc = if decl then match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") else nil + if enc then + local e = lower(enc) + if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, e + elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then + local w = e == "windows-1252" or e == "cp1252" + return (gsub(s, "[\128-\255]", @native function(c: string): string + local v = byte(c) + return utf8char(if w then CP1252[v] or v else v) + end)), e + elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then + return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes + end + return nil, "unsupported encoding " .. enc + end + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, "utf-8" +end + +-- the pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace +@native local function xmlDecl(data: string): { [string]: string }? + local p = 1 + local out: { [string]: string } = {} + for k, key in { "version", "encoding", "standalone" } do + local ws = match(data, "^[ \t\n]*()", p) :: any + local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) + if q then + if k > 1 and ws == p then + return nil -- no whitespace before + end + if (key == "version" and not match(v, "^1%.%d+$")) + or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) + or (key == "standalone" and v ~= "yes" and v ~= "no") + then + return nil + end + out[key] = v + p = e + elseif key == "version" then + return nil + end + end + if match(data, "^[ \t\n]*()", p) ~= #data + 1 then + return nil + end + return out +end + +-- the events iterator: next() -> event, a, b, c +-- "decl", { version, encoding, standalone } the declaration +-- "doctype", raw, info raw = the text between ""; info = { name, +-- publicId, systemId, entities } +-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil +-- "end", name +-- "text", s character data, entities decoded (whitespace-only dropped +-- unless opts.whitespace) +-- "cdata", s "comment", s "pi", target, data +-- "error", message, offset then the iterator ends +-- nil at the end of the document. +@native function Parse.events(s: string, opts: Options?): () -> (string?, any, any, any) + local o: Options = opts or {} + local keepWs = o.whitespace == true + local nsOn = o.namespaces == true + local maxExp = o.maxExpansion or 1e7 + local maxDepth = o.maxDepth or 10000 + local entities: { [string]: string } = {} + if o.entities then + for k, v in o.entities do + entities[k] = v + end + end + local external: { [string]: boolean } = {} + local expanded = 0 + if find(s, "\r", 1, true) then + s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") + end + local n = #s + local i = 1 + local stack: { string } = {} + local nsStack: { { [string]: string } } = {} + local preserve: { boolean } = {} + local depth = 0 + local rootSeen = false + local rootDone = false + local dead = false + local pending: { any }? = nil -- an "end" queued after a self-closing start + local errMsg: string? = nil + local errAt = 0 + + @native local function fail(msg: string, at: number): (string, string, number) + dead = true + return "error", msg, at - 1 + end + + -- decode entity / character references in raw text; nil on error (errMsg set) + local decode: (raw: string, at: number, level: number) -> string? + @native function decode(raw: string, at: number, level: number): string? + if not find(raw, "&", 1, true) then + return raw + end + local parts = {} + local np = 0 + local p = 1 + while true do + local a = find(raw, "&", p, true) + if not a then + break + end + np += 1 + parts[np] = sub(raw, p, a - 1) + local ref, e = match(raw, "^&([^;&%s<]*);()", a) + if not ref then + errMsg, errAt = "bad reference (no ';')", at + a - 1 + return nil + end + local rep: string + if byte(ref) == 35 then -- # + local cp = if byte(ref, 2) == 120 then tonumber(match(ref, "^#x(%x+)$") or "", 16) else tonumber(match(ref, "^#(%d+)$") or "") + if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then + errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 + return nil + end + rep = utf8char(cp) + else + local pre = PREDEF[ref] + if pre then + rep = pre + else + local ent = entities[ref] + if not ent then + errMsg = if external[ref] then "external entity &" .. ref .. "; not supported" else "undefined entity &" .. ref .. ";" + errAt = at + a - 1 + return nil + end + if level > 40 then + errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 + return nil + end + local r = decode(ent, at + a - 1, level + 1) + if not r then + return nil + end + rep = r + end + end + expanded += #rep + if expanded > maxExp then + errMsg, errAt = "entity expansion over the limit", at + a - 1 + return nil + end + np += 1 + parts[np] = rep + p = e :: any + end + np += 1 + parts[np] = sub(raw, p) + return table.concat(parts) + end + + @native local function lookupNs(prefix: string): string? + for d = depth, 1, -1 do + local m = nsStack[d] + if m and m[prefix] ~= nil then + return m[prefix] + end + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil + end + + -- a quoted literal at p -> its content, the position after it | nil + @native local function literal(p: number): (string?, number) + local q = byte(s, p) + if q ~= 34 and q ~= 39 then + return nil, p + end + local e = find(s, if q == 34 then '"' else "'", p + 1, true) + if not e then + return nil, p + end + return sub(s, p + 1, e - 1), e + 1 + end + -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + @native local function externalId(p: number): (string?, string?, number?) + local kw = sub(s, p, p + 5) + if kw == "SYSTEM" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil, nil, nil + end + local sys, e = literal(q) + if not sys then + return nil, nil, nil + end + return "", sys, e + elseif kw == "PUBLIC" then + local q = match(s, "^[ \t\n]+()", p + 6) :: any + if not q then + return nil, nil, nil + end + local pub, e = literal(q) + if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then + return nil, nil, nil + end + local r = match(s, "^[ \t\n]+()", e) :: any + if not r then + return nil, nil, nil + end + local sys, e2 = literal(r) + if not sys then + return nil, nil, nil + end + return pub, sys, e2 + end + return nil, nil, nil + end + -- check an entity value's references and expand its character references (the rest expand when used) + @native local function entityValue(v: string): string? + if find(v, "%", 1, true) then + return nil -- parameter-entity references are not allowed in the internal subset's markup + end + local p = 1 + local parts = {} + while true do + local a = find(v, "&", p, true) + if not a then + table.insert(parts, sub(v, p)) + break + end + table.insert(parts, sub(v, p, a - 1)) + local hex = match(v, "^&#x(%x+);", a) + local dec = match(v, "^&#(%d+);", a) + if hex or dec then + local cp = tonumber(hex or dec, if hex then 16 else 10) :: number + if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then + return nil + end + table.insert(parts, utf8char(cp)) + p = (find(v, ";", a, true) :: number) + 1 + else + local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) + if not name then + return nil + end + table.insert(parts, "&" .. name .. ";") + p = a + #name + 2 + end + end + return table.concat(parts) + end + -- the DOCTYPE at i (just past " p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then + local pub, sys, e = externalId(q) + if not pub then + return nil, "bad DOCTYPE external id" + end + info.publicId = if pub ~= "" then pub else nil + info.systemId = sys + q = match(s, "^[ \t\n]*()", e) :: any + end + if byte(s, q) == 91 then -- the internal subset + q += 1 + while true do + q = match(s, "^[ \t\n]*()", q) :: any + local c = byte(s, q) + if c == 93 then + q += 1 + break + elseif c == 37 then -- %name; + local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) + if not pe then + return nil, "bad parameter-entity reference" + end + q = pe :: any + elseif sub(s, q, q + 3) == " { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } +-- +-- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +local Err = __include("core/Err") +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") +local Flic = __include("codecs/video/Legacy/Flic") +local Cinepak = __include("codecs/video/Legacy/Cinepak") +local Msvideo1 = __include("codecs/video/Legacy/Msvideo1") +local QtRle = __include("codecs/video/Legacy/QtRle") +local Smc = __include("codecs/video/Legacy/Smc") +local Smacker = __include("codecs/video/Legacy/Smacker") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } + +type Options = { + maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + [string]: any, +} + +-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? +type Codec = { + make: (track: Types.Track) -> (any, string?), + step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), +} + +local function fail(msg: string?): Err.Err + return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean + local pal = (packet :: any).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS: { [string]: Codec } = { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = if depth > 32 then depth - 32 else depth + if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width :: number) < 4 or (t.height :: number) < 4 then + return nil, "smaller than one block" + end + local bits = if t.bitsPerPixel == 8 then 8 else 16 + return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, if msg then fail(msg) else nil + end + return Picture.image(st.pic), nil + end, + }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err +function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) + local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + -- Video.simpleDecoder, without requiring the registry (which requires this module) + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + end + return self :: any, nil +end + +return Legacy +end +__FILES["codecs/video/Legacy/Cinepak"] = @native function() + + + +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 +-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description +-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 +-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame +-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are +-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra +-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak +-- decoder. Never throws: every read is range-checked against its chunk. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + +type State = { + books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip) + filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) +} + +@native function Cinepak.state(): State + return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +@native local function be16(d: buffer, o: number): number + return readu8(d, o) * 256 + readu8(d, o + 1) +end +@native local function be24(d: buffer, o: number): number + return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +@native local function be32(d: buffer, o: number): number + return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +@native local function clip(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +@native local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = if six then 6 else 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u -= 256 + end + if v >= 128 then + v -= 256 + end + local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero) + local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p += size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +@native local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, + stop: number, x1: number, y1: number, x2: number, y2: number): boolean + local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) :: buffer + local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p += 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = if r < 2 then a else c, if r < 2 then b else e4 + writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p += 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this +-- packet (an empty frame); false + message = an error +@native function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) + local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < size * 5 // 100 then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + -- the coded area: the size rounded up to whole blocks (the picture's plane) + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p += 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- the strip's chunks: codebooks, then one vector chunk + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q += 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak +end +__FILES["codecs/video/Legacy/Flic"] = @native function() + + + +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is +-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's +-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit +-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK +-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX +-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); +-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet +-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. +-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} + +-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette +type State = { + pic: Picture.Picture, + depth: number, -- 8, 15, 16, 24 + bpp: number, -- bytes per pixel +} + +-- state(w, h, depth) -> State | nil, message +@native function Flic.state(w: number, h: number, depth: number): (State?, string?) + local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 + if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +@native local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- decode(st, data) -> true | false, message +@native function Flic.decode(st: State, d: buffer): (boolean, string?) + local pic = st.pic + local px = pic.idx :: buffer + local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + @native local function u8(): number + local v = if p < n then readu8(d, p) else 0 + p += 1 + return v + end + @native local function u16(): number + local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize -= 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p += 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at += u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + r // 64, g + g // 64, b + b // 64 + end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at += 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do + if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp -= 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) + continue + elseif lp >= 0x4000 then + continue -- undefined opcode + end + lines -= 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q += u8() * bpp + local run = s8(u8()) + if deep then + local cnt = if run < 0 then -run else run + if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p += cnt * bpp + q += cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q += 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p += run * 2 + q += run * 2 + end + end + y += stride + end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q += u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p += run + q += run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q -= run + end + end + y += stride + lines -= 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = if typ == 25 then bpp else 1 + local y = 0 + for _ = 1, h do + local q = y + p += 1 -- the packet count (unused) + local left = if typ == 25 then w else w * bpp + while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q += run + else + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + end + left -= run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p += cnt * unit + q += cnt * unit + left -= cnt + end + end + y += stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4 + local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h + if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p += padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize -= size + chunks -= 1 + end + return true, nil +end + +-- image(st) -> a fresh rgba8 Image +@native function Flic.image(st: State): Types.Image + local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx :: buffer + local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565() + local mask = if st.depth == 15 then 32768 else 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic +end +__FILES["codecs/video/Legacy/Msvideo1"] = @native function() + + + +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit +-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows +-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour +-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour +-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. +-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 +-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +@native local function quadrant(x: number, y: number): number + return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) +end + +-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) +@native function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) + local n = buffer.len(d) + local bw, bh = pic.w // 4, pic.h // 4 + if n < bw * bh // 512 then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = (if wide then pic.rgba else pic.idx) :: buffer + local lut = if wide then Picture.rgb555() else nil + local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do + if skip ~= 0 then + skip -= 1 + total -= 1 + continue + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + -- the block's bottom-left pixel; its rows go up + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p += 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p += 2 + end + end + else + eight = b >= 0x90 + local cnt = if eight then 8 else 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p += 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (if band(flags, 1) == 1 then 1 else 2) + if eight then + k += quadrant(x, y) + end + flags = flags // 2 + if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a + for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total -= 1 + end + end + return true, nil +end + +return Msvideo1 +end +__FILES["codecs/video/Legacy/Picture"] = @native function() + + + +-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame +-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, +-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past +-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication +-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +type Picture = { + w: number, + h: number, + stride: number, -- index plane: bytes per row; rgba plane: pixels per row + rows: number, + idx: buffer?, -- u8 index plane, stride * rows bytes (palettised) + rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour) + pal: buffer, -- 256 u32 entries, bytes R, G, B, A +} + +-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) +@native function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture + local pw, ph = padW or 1, padH or 1 + local stride = ((w + pw - 1) // pw) * pw + local rows = ((h + ph - 1) // ph) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +-- image(p) -> a fresh rgba8 Image of the visible w x h +@native function Picture.image(p: Picture): Types.Image + local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track +@native function Picture.setPalette(p: Picture, src: buffer) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555: buffer? = nil +local lut565: buffer? = nil + +-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries +@native function Picture.rgb555(): buffer + local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = v // 1024, (v // 32) % 32, v % 32 + r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries +@native function Picture.rgb565(): buffer + local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = v // 2048, (v // 32) % 64, v % 32 + r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +-- copy of a picture's plane (for decoders that read the previous picture while writing the next) +@native function Picture.clonePlane(p: Picture): buffer + local src = (p.idx or p.rgba) :: buffer + local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture +end +__FILES["codecs/video/Legacy/QtRle"] = @native function() + + + +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File +-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per +-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). +-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its +-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames +-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read +-- and write is range-checked (a damaged frame stops where the damage is). +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +@native local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +@native local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) + row -= stride + local q = row + lines += 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p += 2 + if code == 0 then + return + end + if skip >= 128 then + lines -= 1 + row += stride + q = row + 16 * (skip - 128) + else + q += 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q += 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p += 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +@native local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) + local group = 32 // bpp -- pixels per 4 bytes + local per = 8 // bpp -- pixels per byte + local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q += 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q += group + end + end + p += 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q += bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + end + p += bytes + end + end + row += stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +@native local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) + local bpp = depth // 8 + local lut = if depth == 16 then Picture.rgb555() else nil + for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += readu8(d, p) - 1 + p += 1 + if q < 0 or q > limit then + return + end + else + local cnt = if code < 0 then -code else code + local need = if code < 0 then bpp else bpp * cnt + if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q += 1 + if code > 0 then + p += bpp + end + end + if code < 0 then + p += bpp + end + end + end + row += stride + end +end + +-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message +@native function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) + local n = buffer.len(d) + if n < 8 then + return true, nil -- no change + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p += 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p += 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = if depth > 32 then depth - 32 else depth + local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs +@native function QtRle.palettised(depth: number): boolean + return depth <= 8 or depth > 32 +end +@native function QtRle.pad(depth: number): number + local bits = if depth > 32 then depth - 32 else depth + return if bits <= 8 then 32 // math.max(1, bits) else 1 +end + +return QtRle +end +__FILES["codecs/video/Legacy/Smacker"] = @native function() + + + +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads +-- 10 bits at a time through a lookup table into them. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +-- a bit position over buf[0, nbits / 8) +type Bits = { buf: buffer, pos: number, nbits: number } + +@native function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +@native local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +@native function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +@native local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +@native local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +@native function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, @native function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) +@native local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, @native function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +@native function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +@native local function lut(vals: { number }): buffer + local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i += -e - 1 + end + i += 1 + len += 1 + e = vals[i] + end + writeu32(t, pat * 4, i * 32 + len) + end + return t +end + +@native local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +@native function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + for _, t in { mmap, mclr, full, typ } do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree + @native local function code(t: BigTree): number + local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut :: buffer, v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i += -e - 1 + end + p += 1 + i += 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3]] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + @native local function bit(): number + local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ) + if ty < 0 then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if pos >= nbits then + return false, "truncated frame" + end + if bit() == 1 then + mode = 1 + elseif bit() == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then + return false, "truncated frame" + end + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full) + if a < 0 then + return false, "truncated frame" + end + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker +end +__FILES["codecs/video/Legacy/Smc"] = @native function() + + + +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description +-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble +-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour +-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: +-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc +-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row +-- above). Never throws: reads past the data give zeros, the block count bounds every write. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) +@native function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) + local px = pic.idx :: buffer + local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = pic.rows // 4 + local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4) + if total // 1024 > n then + return false, "frame too small" + end + local blocksWide = (pic.w + 3) // 4 + local p = 4 -- flags byte + 24-bit chunk size + -- block position: bx, by (blocks) + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + @native local function u8(): number + if p < n then + local v = readu8(d, p) + p += 1 + return v + end + return 0 + end + @native local function advance() + bx += 1 + if bx >= blocksWide then + bx = 0 + by += 1 + end + total -= 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p += 1 + local kind = rshift(op, 4) + local count: number + if kind < 8 then + count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15) + else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = if pair then 2 else 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = if pair then count * 2 else count + local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = if pair and k % 2 == 1 then srcB else srcA + local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8 + local base = if size == 2 then 0 elseif size == 4 then 512 else 1536 + local entry: number + if kind % 2 == 0 then + local i = if size == 2 then pairI elseif size == 4 then quadI else octI + for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = if k < 8 then fa else fb + local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + -- 16-colour blocks + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (k // 4) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +-- tables() -> the colour group scratch (pairs, quads, octets) +@native function Smc.tables(): buffer + return buffer.create(512 + 1024 + 2048) +end + +return Smc +end +__FILES["codecs/video/Mpeg1"] = function() + +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder +-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / +-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +local Mpeg2 = __include("codecs/video/Mpeg2") + +type Frame = Mpeg2.Frame +type Options = Mpeg2.Options +type Decoder = Mpeg2.Decoder + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2"] = function() + +-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). +-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / +-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes +-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from +-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this +-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); +-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. +-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- local dec = Mpeg2.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } +-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = __include("Types") +local Err = __include("core/Err") +local D = __include("codecs/video/Mpeg2/Decoder") + +local Mpeg2 = {} + +Mpeg2.PICTURE_I = 1 +Mpeg2.PICTURE_P = 2 +Mpeg2.PICTURE_B = 3 + +type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, -- frames returned so far (1-based) + tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) + -- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride + -- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2) + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) + fields: boolean, -- coded as two field pictures + topFieldFirst: boolean, + repeatFirstField: boolean, + clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) + concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) +} + +type Options = { + reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the + -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is + -- display order for streams without B-frames. + rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) + maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) + -- a cooperative yield point, run after every slice and every 16 rows of colour conversion: e.g. a function that + -- calls coroutine.yield() when a time budget is spent, to spread a picture over several frames (the decode call + -- then runs inside a coroutine). Don't call this decoder again while a decode is suspended. Errors in it are + -- ignored. See dec:setYield. + yield: (() -> ())?, +} + +local Decoder = {} +Decoder.__index = Decoder + +type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg2.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + if type(o.yield) == "function" then + core.setYield(o.yield) + end + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + chroma = s.chroma, + mpeg2 = s.mpeg2, + progressive = s.progressive, + fields = s.fields, + topFieldFirst = s.tff, + repeatFirstField = s.rff, + clamped = s.clamped, + concealed = s.concealed, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Sets (or clears, nil) the cooperative yield hook (Options.yield). +function Decoder.setYield(self: Decoder, hook: (() -> ())?) + self._core.setYield(if type(hook) == "function" then hook else nil) +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +-- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a +-- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes. +-- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in +-- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 .. +-- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows. +-- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many +-- rows as its luma; use frameImage(frame, true) for those.) +function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean + if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then + return false + end + local cw, w, h = tonumber(codedWidth), tonumber(width), tonumber(height) + if not cw or not w or not h or cw % 2 ~= 0 or w < 1 or h < 1 or w > cw or cw ~= math.floor(cw) or w ~= math.floor(w) or h ~= math.floor(h) then + return false + end + local r0 = math.floor(tonumber(row0) or 0) + r0 -= r0 % 2 + local r1 = math.floor(tonumber(row1) or h) + local pr = math.floor(tonumber(planeRow0) or 0) + local oo = math.floor(tonumber(outOffset) or 0) + if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then + return false + end + -- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band + local lumaRows = r1 - pr + local chromaRows = (r1 + 1) // 2 - pr // 2 + if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then + return false + end + if buffer.len(out) < oo + (r1 - r0) * w * 4 then + return false + end + -- rows relative to the planes' first row + D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil) + return true +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma +-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for +-- a value that is not a Frame. +function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local c422 = frame.chroma == 2 + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + local crows = if c422 then h else oh + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + if c422 then + D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + end + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + if not c422 then + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + else + -- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field + -- (4k + j and 4k + j + 2), so the fields do not mix + local inter = not frame.progressive + for y = 0, oh - 1 do + local a, b + if inter then + local base = (y // 2) * 4 + y % 2 + a, b = base, base + 2 + else + a, b = 2 * y, 2 * y + 1 + end + if b >= h then + b = a + end + for x = 0, ow - 1 do + buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2) + buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2) + end + end + end + end + img.meta.source = { + format = if frame.mpeg2 then "mpeg2" else "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + chroma = if c422 then "422" else "420", + interlaced = not frame.progressive, + topFieldFirst = frame.topFieldFirst, + range = if rgba then nil else "limited", + } + return img +end + +-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder +-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in +-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of +-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). +function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue: { any } = {} + local function push(f: Frame) + local img = Mpeg2.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local tag = { packet.pts } + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + while f do -- more pictures in the packet + push(f) + f = dec:decode(packet.data, 0, 0, tag) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) + for _ = 1, 8 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_: any) + dec:reset() + table.clear(queue) + end + return self :: any, nil +end + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2/Decoder"] = @native function() + + +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). +-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame +-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion +-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; +-- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser +-- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: +-- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js +-- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion +-- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), +-- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid +-- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 +-- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are +-- clamped (ffmpeg skips the prediction): both only matter for corrupt data. +-- +-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. +-- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), +-- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +local V = __include("codecs/video/Mpeg2/Vlc") +local T = __include("codecs/video/Mpeg2/Tables") +local Dsp = __include("codecs/video/Dsp") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +-- scan index -> natural position (zigzag, alternate); default matrices in natural order +local ZZ = buffer.create(64) +local ALT = buffer.create(64) +local DEF_INTRA = buffer.create(64) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(ALT, i, T.ALTERNATE_SCAN[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[i]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[i]) +end +local NON_LINEAR = buffer.create(32) +for i = 0, 31 do + buffer.writeu8(NON_LINEAR, i, T.NON_LINEAR_QSCALE[i]) +end + +local COFF = 40000 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT, DCT_B15 = V.DCT_FIRST, V.DCT_NEXT, V.DCT_B15 +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +-- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases +-- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively +local RGB_CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. +-- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional) +-- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's +-- later banded conversion.) +@native local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local r0: number = row0 or 0 + local r1: number = row1 or h + local base: number = oo or 0 + local chw = cw // 2 + local w2 = w // 2 -- whole pixel pairs per row + local stride = w * 4 + local C = RGB_CLAMP + local n = 0 + for y = r0, r1 - 1, 2 do + local yo = y * cw + local co = (y // 2) * chw + local o = base + (y - r0) * stride + local two = y + 1 < r1 + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co += 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + yo += 2 + o += 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, if two then 1 else 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + end + n += 2 + if hook and n >= 16 then + n = 0 + pcall(hook) + end + end +end +D.toRgba = toRgba + +-- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2 +@native local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + local chw = cw // 2 + for y = 0, h - 1 do + local o = y * w * 4 + for x = 0, w - 1 do + local c = y * chw + x // 2 + local cb, cr = readu8(Cb, c), readu8(Cr, c) + local yv = readu8(Y, y * cw + x) * 298 + local r = math.clamp(rshift(yv + cr * 409 + RBIAS, 8) - COFF, 0, 255) + local g = math.clamp(rshift(yv + GBIAS - cb * 100 - cr * 208, 8) - COFF, 0, 255) + local b = math.clamp(rshift(yv + cb * 516 + BBIAS, 8) - COFF, 0, 255) + writeu32(out, o + x * 4, r + g * 256 + b * 65536 + 0xFF000000) + end + end +end +D.toRgba422 = toRgba422 + +type Store = { + y: buffer, + cb: buffer, + cr: buffer, + w: number, + h: number, + cw: number, -- luma stride (coded width); chroma stride cw / 2 + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + tref: number, + ptype: number, + tag: any, + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1: true) + fields: boolean, -- coded as two field pictures + tff: boolean, -- top_field_first + rff: boolean, -- repeat_first_field + clamped: number, -- predictions from outside the reference (edge-emulated) in the last picture decoded into it + concealed: { [number]: boolean }, -- macroblock rows (of the frame) with macroblocks no slice covered (concealed) +} + +type Core = { + -- data + write: (src: buffer, off: number, n: number) -> (), + -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when + -- no picture is complete or it could not be decoded), and whether more data is needed. A frame coded as two field + -- pictures comes back once, after its second field. + nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), + toRgba: (s: Store, out: buffer) -> (), + reset: () -> (), + -- a cooperative yield point (e.g. coroutine.yield when over a time budget), run after every slice and every 16 + -- rows of colour conversion; nil = none. pcall'ed: it can't throw through the native code. + setYield: (hook: (() -> ())?) -> (), + state: { + width: number, + height: number, + codedWidth: number, + codedHeight: number, + frameRate: number, + aspect: number, + bitRate: number, + mpeg2: boolean, + chroma: number, + progressive: boolean, -- progressive_sequence + profileLevel: number, + sizeChanged: boolean, + pictures: number, + errors: number, + skipped: number, + clamped: number, -- motion vectors pointing outside the reference (clamped) + maxPixels: number, + refOld: Store?, + refNew: Store?, + }, +} + +@native function D.new(maxPixels: number?): Core + local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + mpeg2 = false, + chroma = 1, + progressive = true, + profileLevel = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil :: Store?, + refNew = nil :: Store?, + } + + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + -- sequence + local hasSeq = false + local mpeg2 = false + local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 + local progSeq = true + local mbW, mbH = 0, 0 -- frame size in macroblocks + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local lumaH, chromaH = 0, 0 -- plane heights (coded) + local intraQ = buffer.create(64) -- natural order + local nonIntraQ = buffer.create(64) + local chromaIntraQ = buffer.create(64) + local chromaNonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + buffer.copy(chromaIntraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(chromaNonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores: { Store } = {} + local bStore: Store? = nil + -- the sequence header's values, applied (and the stores allocated) once its extension has been seen + local seqW, seqH = 0, 0 + + -- picture + local ptype = 0 + local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] + local fullPelFw, fullPelBw = false, false + local dcPrec = 0 + local picStruct = 3 -- 1 top field, 2 bottom field, 3 frame + local fpfd = true -- frame_pred_frame_dct + local concealMv = false + local qScaleType = 0 + local intraVlc = false + local scan = ZZ + local tff, rff, progFrame = true, false, true + local fieldPic = false + local secondField = false + local parity = 0 -- the current field (0 top, 1 bottom) + local mbRows, mbSize = 0, 0 -- of the current picture (field pictures: half the frame's rows) + local lstride, lbase, cstride, cbase = 0, 0, 0, 0 -- plane addressing of the current picture + local cur: Store? = nil + local curY, curCb, curCr = data, data, data + local fwS: Store? = nil + local bwS: Store? = nil + local pending: Store? = nil -- a first field waiting for its second + local pendingStruct = 0 + local pendingFw: Store? = nil + local pendingBw: Store? = nil + + -- slice / macroblock + local qscale = 2 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local mbIntra = false + local motFw, motBw = false, false + local motionType = 1 -- 1 frame (field pictures: field 16x16), 2 field (frame pictures), 3 16x8, 4 dual prime + local dctType = 0 + -- vectors: MV[(d * 4 + k) * 2 + c + 1] (direction d, vector k: 0 / 1 the two fields or halves, 2 / 3 dual-prime + -- opposite-parity vectors; component c); PMV[(d * 2 + r) * 2 + c + 1]; FSEL[d * 2 + r + 1] + local MV = table.create(16, 0) + local PMV = table.create(8, 0) + local FSEL = table.create(4, 0) + local blk = buffer.create(256) + local yieldHook: (() -> ())? = nil + + @native local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + @native local function read(n: number): number + local v = rshift(peek32(), 32 - n) + pos += n + return v + end + + @native local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) - 32768 + end + + -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 + @native local function findStart(from: number, to: number): number + local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i += 3 + else + i += 1 + end + end + return -1 + end + + @native local function newStore(): Store + local y = buffer.create(cw * lumaH) + local cb = buffer.create(chw * chromaH) + local cr = buffer.create(chw * chromaH) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { + y = y, + cb = cb, + cr = cr, + w = state.width, + h = state.height, + cw = cw, + chroma = chroma, + tref = 0, + ptype = 0, + tag = nil, + mpeg2 = mpeg2, + progressive = true, + fields = false, + tff = true, + rff = false, + clamped = 0, + concealed = {}, + } + end + + @native local function loadMatrix(q: buffer) + for i = 0, 63 do + local v = read(8) + writeu8(q, readu8(ZZ, i), if v == 0 then 1 else v) + end + end + + -- the sequence (header + extension) takes effect: sizes and stores + @native local function applySequence(): boolean + local w, h = seqW, seqH + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + local mh = if mpeg2 and not progSeq then 2 * ((h + 31) // 32) else (h + 15) // 16 + if w ~= state.width or h ~= state.height or mh ~= mbH or chroma ~= state.chroma or mpeg2 ~= state.mpeg2 then + state.width = w + state.height = h + state.chroma = chroma + state.mpeg2 = mpeg2 + mbW = (w + 15) // 16 + mbH = mh + cw = mbW * 16 + chw = mbW * 8 + lumaH = mbH * 16 + chromaH = if chroma == 2 then lumaH else lumaH // 2 + state.codedWidth = cw + state.codedHeight = lumaH + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + pending = nil + state.sizeChanged = true + end + state.progressive = progSeq + hasSeq = true + return true + end + + -- sequence header at byte p (after the start code); false when invalid + @native local function sequenceHeader(p: number): boolean + pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag + if read(1) == 1 then + loadMatrix(intraQ) + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + seqW, seqH = w, h + mpeg2 = false -- until a sequence extension follows + chroma = 1 + progSeq = true + return w > 0 and h > 0 + end + + @native local function sequenceExtension() + state.profileLevel = read(8) + progSeq = read(1) == 1 + local cf = read(2) + seqW += lshift(read(2), 12) + seqH += lshift(read(2), 12) + state.bitRate += lshift(read(12), 18) * 400 + pos += 1 + 8 + 1 -- marker, vbv_buffer_size_extension, low_delay + local n = read(2) + local d = read(5) + state.frameRate = state.frameRate * (n + 1) / (d + 1) + mpeg2 = true + chroma = if cf == 2 then 2 else 1 -- 4:4:4 (3) is not supported: decoded as 4:2:0 (wrong but safe) + if cf == 3 then + state.errors += 1 + end + end + + @native local function quantMatrixExtension() + if read(1) == 1 then + loadMatrix(intraQ) + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(chromaIntraQ) + end + if read(1) == 1 then + loadMatrix(chromaNonIntraQ) + end + end + + @native local function fcode(v: number): number + return if v < 1 or v > 9 then 1 else v + end + + @native local function pictureCodingExtension() + fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4)) + dcPrec = read(2) + picStruct = read(2) + tff = read(1) == 1 + fpfd = read(1) == 1 + concealMv = read(1) == 1 + qScaleType = read(1) + intraVlc = read(1) == 1 + scan = if read(1) == 1 then ALT else ZZ + rff = read(1) == 1 + pos += 1 -- chroma_420_type + progFrame = read(1) == 1 + if picStruct == 0 then + picStruct = 3 + err = true + end + end + + -- an extension (00 00 01 B5) at byte p + @native local function extension(p: number) + pos = p * 8 + local id = read(4) + if id == 1 then + sequenceExtension() + elseif id == 3 then + quantMatrixExtension() + elseif id == 8 then + pictureCodingExtension() + end + end + + @native local function decodeMotion(f: number, pred: number): number + local code = vlc(MOTION, MOTION_BITS) + local d = code + local rsize = f - 1 + if code ~= 0 and rsize > 0 then + local r = read(rsize) + d = lshift(math.abs(code) - 1, rsize) + r + 1 + if code < 0 then + d = -d + end + end + local range = lshift(16, rsize) + return (pred + d + range) % (2 * range) - range + end + + -- ------------------------------------------------------------------------------------------------ prediction + -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: + -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the + -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the + -- first prediction. + local EDGE = buffer.create(Dsp.EDGE_SIZE) + @native local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) + local stride, sb, db, ph = cw, 0, 0, lumaH + local cs, csb, cdb = chw, 0, 0 + if sp >= 0 then + stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2 + cs, csb, cdb = 2 * chw, sp * chw, dp * chw + end + -- luma + local hx, hy = band(mvx, 1), band(mvy, 1) + local sx = mbCol * 16 + (mvx - hx) // 2 + local sy = rowY + (mvy - hy) // 2 + local dOff = db + rowY * stride + mbCol * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + h + hy > ph then + -- outside the reference (invalid in MPEG; ffmpeg's encoder writes such half-sample vectors at the right / + -- bottom edge): predicted from repeated edge samples, as the encoder meant (ffmpeg's decoder skips it) + Dsp.edge(rY, stride, sb, sx, sy, 16, h, cw, ph, EDGE) + mc(EDGE, 32, 0, curY, stride, dOff, 16, h, hx, hy, avg) + state.clamped += 1; + (cur :: Store).clamped += 1 + else + mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) + end + -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 + local mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end + local cx, cy, chh, cph, chx, chy + chx = band(mx, 1) + cx = mbCol * 8 + (mx - chx) // 2 + if chroma == 1 then + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end + chy = band(my, 1) + cy = rowY // 2 + (my - chy) // 2 + chh, cph = h // 2, ph // 2 + else + chy = band(mvy, 1) + cy = rowY + (mvy - chy) // 2 + chh, cph = h, ph + end + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then + Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) + Dsp.edge(rCr, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCr, cs, cdOff, 8, chh, chx, chy, avg) + else + local so = csb + cy * cs + cx + mc(rCb, cs, so, curCb, cs, cdOff, 8, chh, chx, chy, avg) + mc(rCr, cs, so, curCr, cs, cdOff, 8, chh, chx, chy, avg) + end + end + + -- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the + -- opposite parity from its own first field + @native local function fieldRef(d: number, fs: number): Store + if d == 0 then + if secondField and ptype == 2 and fs ~= parity then + return cur :: Store + end + return (fwS or cur) :: Store + end + return (bwS or cur) :: Store + end + + -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock + @native local function predictDir(d: number, avg: boolean) + local o = d * 8 + if not fieldPic then + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr + if motionType == 1 then + mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 2 then + mcPart(ry, rcb, rcr, FSEL[d * 2 + 1], 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, FSEL[d * 2 + 2], 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + else -- dual prime: each field from the same parity (MV 0 / 1), averaged with the opposite parity (MV 2 / 3) + mcPart(ry, rcb, rcr, 0, 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, 1, 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + mcPart(ry, rcb, rcr, 1, 0, mbRow * 8, 8, MV[o + 5], MV[o + 6], true) + mcPart(ry, rcb, rcr, 0, 1, mbRow * 8, 8, MV[o + 7], MV[o + 8], true) + end + return + end + if motionType == 1 then + local fs = FSEL[d * 2 + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 3 then + for k = 0, 1 do + local fs = FSEL[d * 2 + k + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16 + k * 8, 8, MV[o + k * 2 + 1], MV[o + k * 2 + 2], avg) + end + else -- dual prime: same parity, then the opposite one (the first field of this frame for a second field) + local r = (fwS or cur) :: Store + mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + local q = if secondField then cur :: Store else r + mcPart(q.y, q.cb, q.cr, 1 - parity, parity, mbRow * 16, 16, MV[o + 5], MV[o + 6], true) + end + end + + -- the prediction of a non-intra macroblock from the current motion state + @native local function predictMb() + if ptype == 2 then + predictDir(0, false) + elseif motFw then + predictDir(0, false) + if motBw then + predictDir(1, true) + end + elseif motBw then + predictDir(1, false) + end + end + + @native local function resetPmv() + for i = 1, 8 do + PMV[i] = 0 + end + end + + -- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the + -- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction + @native local function skipMotion() + motionType = 1 + FSEL[1], FSEL[3] = parity, parity + if ptype == 2 then + resetPmv() + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = PMV[1], PMV[2] + MV[9], MV[10] = PMV[5], PMV[6] + end + end + + -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 + -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do + -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock + -- before the gap. + local covered = 0 + local gapFw, gapBw = false, false + local GAP = table.create(16, 0) + local gapType = 1 + local hasRef = false + local SAVE = table.create(16, 0) + @native local function conceal(from: number, to: number) + if from > to or not hasRef then + return + end + local sFw, sBw, sType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, SAVE) + local f1, f2, f3, f4 = FSEL[1], FSEL[2], FSEL[3], FSEL[4] + if ptype == 3 and mpeg2 then + -- both references, zero vectors (ffmpeg's error concealment of B macroblocks, without its deblocking) + motFw, motBw, motionType = true, true, 1 + MV[1], MV[2], MV[9], MV[10] = 0, 0, 0, 0 + elseif ptype == 3 then + motFw, motBw, motionType = gapFw, gapBw, gapType + table.move(GAP, 1, 16, 1, MV) + if not motFw and not motBw then + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + end + else + motionType = 1 + if not (ptype == 2 and gapFw) then + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = GAP[1], GAP[2] + end + end + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = parity, parity, parity, parity + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + local c = (cur :: Store).concealed + for a = from, to do + mbRow = a // mbW + mbCol = a % mbW + predictMb() + if fieldPic then + c[mbRow * 2] = true + c[mbRow * 2 + 1] = true + else + c[mbRow] = true + end + end + ptype = pt + motFw, motBw, motionType = sFw, sBw, sType + table.move(SAVE, 1, 16, 1, MV) + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 + end + + -- ------------------------------------------------------------------------------------------------ blocks + -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. + -- False on a bitstream error. + @native local function decodeBlock(b: number): boolean + local n = 0 + local q: buffer + local onlyDc = true + local luma = b < 4 + local parityOdd = 1 -- MPEG-2 mismatch control: 1 while the coefficient sum is even + if mbIntra then + local dc + local size + if luma then + size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + else + size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end + end + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + if err then + return false + end + local top = lshift(256, dcPrec) - 1 + if dc < 0 or dc > top then + dc = if dc < 0 then 0 else top -- corrupt data: clamped, which also bounds the IDCT input + end + if luma then + dcY = dc + elseif b % 2 == 0 then + dcCb = dc + else + dcCr = dc + end + local v = lshift(dc, 3 - dcPrec) + writei32(blk, 0, v) + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end + n = 1 + else + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST + end + local intra = mbIntra + local qs = qscale + local m2 = mpeg2 + while true do + -- inline peek + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = nextLut + if v == EOB then + pos += l + break + end + local run, level, neg + if v == ESC then + pos += l + run = read(6) + if m2 then + -- a 12-bit signed level + level = read(12) + if level >= 2048 then + level -= 4096 + end + else + -- an 8-bit level or 0x00 / 0x80 and 8 more bits + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level -= 256 + end + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos += l + 1 + end + n += run + if n > 63 then + err = true + return false + end + local zz = readu8(scan, n) + -- dequantise the magnitude (ffmpeg's arithmetic); MPEG-1 makes it odd toward zero + local m + if intra then + m = (level * qs * readu8(q, zz)) // 16 + else + m = ((level * 2 + 1) * qs * readu8(q, zz)) // 32 + end + if not m2 then + if m == 0 then + m = -1 + elseif band(m, 1) == 0 then + m -= 1 + end + end + if neg then + m = -m + end + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end + -- saturate + if m > 2047 then + m = 2047 + elseif m < -2048 then + m = -2048 + end + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n += 1 + end + if m2 and parityOdd == 1 then + -- mismatch control: toggle the last coefficient's lowest bit + local v = readi32(blk, 252) + writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1) + onlyDc = false + end + -- reconstruction + local dst, off, stride + if luma then + dst = curY + if fieldPic then + stride = lstride + off = lbase + (mbRow * 16 + (if b >= 2 then 8 else 0)) * stride + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + elseif dctType == 1 then + stride = 2 * cw + off = (mbRow * 16 + (if b >= 2 then 1 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + else + stride = cw + off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + end + else + dst = curCr + if b % 2 == 0 then + dst = curCb + end + local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock + if chroma == 1 then + stride = cstride + off = cbase + mbRow * 8 * stride + mbCol * 8 + elseif fieldPic then + stride = cstride + off = cbase + (mbRow * 16 + k * 8) * stride + mbCol * 8 + elseif dctType == 1 then + stride = 2 * chw + off = (mbRow * 16 + k) * chw + mbCol * 8 + else + stride = chw + off = (mbRow * 16 + k * 8) * chw + mbCol * 8 + end + end + if onlyDc then + fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) + writei32(blk, 0, 0) + else + idct(blk, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + -- ------------------------------------------------------------------------------------------------ macroblocks + @native local function getQscale(code: number): number + if qScaleType == 1 then + return readu8(NON_LINEAR, code) + end + return code * 2 + end + + -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) + @native local function motionVectors(d: number) + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end + local o, p, f = d * 8, d * 4, d * 2 + if motionType == 1 and not fieldPic then + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + if (d == 0 and fullPelFw) or (d == 1 and fullPelBw) then + x *= 2 + y *= 2 + end + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 2 then + -- field prediction in a frame picture: vertical predictors in frame units + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2] // 2) + PMV[p + r * 2 + 1] = x + PMV[p + r * 2 + 2] = y * 2 + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + elseif motionType == 1 then + -- field picture, 16x16 + FSEL[f + 1] = read(1) + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 3 then + -- 16x8 (field pictures) + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2]) + PMV[p + r * 2 + 1], PMV[p + r * 2 + 2] = x, y + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + else + -- dual prime + local shift = if fieldPic then 0 else 1 + local x = decodeMotion(fh, PMV[p + 1]) + local dmx = if read(1) == 1 then 1 - 2 * read(1) else 0 + local y = decodeMotion(fv, if shift == 1 then PMV[p + 2] // 2 else PMV[p + 2]) + local dmy = if read(1) == 1 then 1 - 2 * read(1) else 0 + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y * (shift + 1), y * (shift + 1) + MV[o + 1], MV[o + 2], MV[o + 3], MV[o + 4] = x, y, x, y + -- the opposite-parity vectors: scaled by the field distance, rounded away from zero + local xp, yp = if x > 0 then 1 else 0, if y > 0 then 1 else 0 + if not fieldPic then + local m = if tff then 1 else 3 + MV[o + 5] = (x * m + xp) // 2 + dmx + MV[o + 6] = (y * m + yp) // 2 + dmy - 1 + m = 4 - m + MV[o + 7] = (x * m + xp) // 2 + dmx + MV[o + 8] = (y * m + yp) // 2 + dmy + 1 + else + MV[o + 5] = (x + xp) // 2 + dmx + MV[o + 6] = (y + yp) // 2 + dmy + (if parity == 0 then -1 else 1) + end + end + end + + -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. + @native local function decodeMacroblock(first: boolean, endBits: number): boolean + local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc += 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc += t + if first then + mbAddr += inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + skipMotion() + for _ = 2, inc do + mbAddr += 1 + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + predictMb() + end + end + mbAddr += 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + local pattern = band(mt, 2) ~= 0 + local fw = band(mt, 8) ~= 0 + local bw = band(mt, 4) ~= 0 + dctType = 0 + if mpeg2 then + if mbIntra or not (fw or bw) then + motionType = 1 + if not fieldPic and not fpfd and (mbIntra or pattern) then + dctType = read(1) + end + else + if not fieldPic and fpfd then + motionType = 1 + else + local mtc = read(2) + if fieldPic then + motionType = if mtc == 1 then 1 elseif mtc == 2 then 3 else 4 + else + motionType = if mtc == 1 then 2 elseif mtc == 2 then 1 else 4 + end + if mtc == 0 then + err = true + return false + end + if not fieldPic and pattern then + dctType = read(1) + end + end + end + else + motionType = 1 + end + if band(mt, 0x10) ~= 0 then + local code = read(5) + if code == 0 then + err = true + return false + end + qscale = getQscale(code) + end + if mbIntra then + if concealMv then + -- concealment vectors: parsed, kept as predictors + if fieldPic then + pos += 1 + end + local x = decodeMotion(fc00, PMV[1]) + local y = decodeMotion(fc01, PMV[2]) + PMV[1], PMV[3] = x, x + PMV[2], PMV[4] = y, y + pos += 1 -- marker + else + resetPmv() + end + else + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw = fw + motBw = bw + if fw then + motionVectors(0) + elseif ptype == 2 then + -- P without motion: a zero vector (field pictures: from the same parity) + resetPmv() + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + FSEL[1] = parity + end + if bw then + motionVectors(1) + end + if err then + return false + end + predictMb() + end + local nb = if chroma == 2 then 8 else 6 + local cbp + if pattern then + cbp = vlc(CBP, CBP_BITS) + if nb == 8 then + cbp = cbp * 4 + read(2) + end + if err then + return false + end + else + cbp = if mbIntra then lshift(1, nb) - 1 else 0 + end + if cbp ~= 0 then + for b = 0, nb - 1 do + if band(cbp, lshift(1, nb - 1 - b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + @native local function decodeSlice(row: number, endByte: number) + if mpeg2 and lumaH > 2800 then + row += lshift(read(3), 7) + end + if row > mbRows then + return + end + mbAddr = (row - 1) * mbW - 1 + resetPmv() + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw, motBw = false, false + local code = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos += 8 + end + if code == 0 then + return + end + qscale = getQscale(code) + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors += 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, GAP) + end + end + + -- ------------------------------------------------------------------------------------------------ pictures + -- the frame a picture completes becomes the newest reference (I / P) + @native local function finishFrame(s: Store) + if s.ptype ~= 3 then + state.refOld = state.refNew + state.refNew = s + end + end + + -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice + -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + @native local function pictureHeader(p: number, stop: number): (number?, number) + pos = p * 8 + local tref = read(10) + ptype = read(3) + pos += 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped += 1 -- D pictures and invalid types + return nil, 0 + end + fullPelFw, fullPelBw = false, false + if ptype >= 2 then + fullPelFw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc00, fc01 = c, c + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc10, fc11 = c, c + end + -- MPEG-1 semantics unless a picture coding extension follows + dcPrec, picStruct, fpfd, concealMv, qScaleType, intraVlc, scan = 0, 3, true, false, 0, false, ZZ + tff, rff, progFrame = true, false, true + err = false + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code == 0xB5 then + extension(at + 4) + elseif code ~= 0xB2 then + break + end + at = findStart(at + 4, stop) + end + if mpeg2 then + fullPelFw, fullPelBw = false, false + end + if err then + state.errors += 1 + err = false + end + return at, tref + end + + -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped + @native local function selectTarget(tref: number, tag: any): boolean + fieldPic = picStruct ~= 3 + parity = if picStruct == 2 then 1 else 0 + secondField = false + local target: Store + if fieldPic and pending and pendingStruct ~= picStruct then + secondField = true + target = pending :: Store + fwS, bwS = pendingFw, pendingBw + if ptype == 3 and (fwS == nil or bwS == nil) then + state.skipped += 1 + return false + end + else + if pending then + -- an unpaired field: its frame is done as it is + finishFrame(pending :: Store) + pending = nil + end + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + elseif ptype == 2 then + if refNew == nil and not fieldPic then + state.skipped += 1 + return false + end + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped += 1 + return false + end + target = bStore :: Store + fwS, bwS = refOld, refNew + end + target.ptype = ptype + target.tref = tref + target.tag = tag + target.mpeg2 = mpeg2 + target.progressive = progFrame + target.fields = fieldPic + target.tff = if fieldPic then picStruct == 1 else tff + target.rff = rff + target.clamped = 0 + target.concealed = {} + end + cur = target + return true + end + + -- plane addressing of the current picture + @native local function setAddressing() + local target = cur :: Store + curY, curCb, curCr = target.y, target.cb, target.cr + if fieldPic then + mbRows = mbH // 2 + lstride, lbase = 2 * cw, parity * cw + cstride, cbase = 2 * chw, parity * chw + else + mbRows = mbH + lstride, lbase = cw, 0 + cstride, cbase = chw, 0 + end + mbSize = mbW * mbRows + covered = 0 + hasRef = fwS ~= nil + gapFw, gapBw = false, false + mbIntra = false + end + + -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil + -- (skipped, or the first field of a frame). + @native local function decodePicture(p: number, stop: number, tag: any): Store? + local first, tref = pictureHeader(p, stop) + if first == nil or not selectTarget(tref, tag) then + return nil + end + setAddressing() + -- slices + local at = first :: number + while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local hook = yieldHook + if hook then + -- the hook may suspend this coroutine: the picture state is all upvalues of this core + pcall(hook) + end + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures += 1 + local target = cur :: Store + if fieldPic and not secondField then + pending = target + pendingStruct = picStruct + pendingFw, pendingBw = fwS, bwS + return nil + end + pending = nil + finishFrame(target) + return target + end + + local core = {} :: Core + core.state = state + + @native function core.write(src: buffer, off: number, n: number) + if n <= 0 then + return + end + -- drop consumed bytes, keeping the scan state relative + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen += n + buffer.fill(data, dataLen, 0, PAD) + end + + -- the sequence header unit at byte at (up to stop): the header, then its extensions + @native local function sequenceUnit(at: number, stop: number) + local ok = sequenceHeader(at + 4) + local s = findStart(at + 4, stop) + while s >= 0 do + if readu8(data, s + 3) == 0xB5 then + extension(s + 4) + end + s = findStart(s + 4, stop) + end + if not ok or not applySequence() then + state.errors += 1 + end + end + + @native function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + sequenceUnit(at, stop) + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped += 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + @native function core.toRgba(s: Store, out: buffer) + if s.chroma == 2 then + toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + else + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out, 0, s.h, 0, yieldHook) + end + end + + @native function core.setYield(hook: (() -> ())?) + yieldHook = hook + end + + @native function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + pending = nil + end + + return core +end + +return D +end +__FILES["codecs/video/Mpeg2/Tables"] = function() + +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from +-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the +-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. +local T = {} +T.PICTURE_RATE = { [0] = 0.0, + 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, +} +T.ZIG_ZAG = { [0] = 0, + 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} +T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8, + 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, + 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, + 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83, +} +T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, +} +T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0, + 0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0, + 0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99, + 102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135, + 138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1, + 144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1, + 186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0, + 0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0, + 0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0, + 0, 24, 0, 0, 23, 0, 0, 22, +} +T.MACROBLOCK_TYPE_INTRA = { [0] = 3, + 6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33, + 36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_B = { [0] = 3, + 6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0, + 0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26, +} +T.CODE_BLOCK_PATTERN = { [0] = 6, + 3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54, + 48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132, + 144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129, + 102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0, + 0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171, + 174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0, + 0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0, + 0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264, + 246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0, + 0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270, + 276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336, + 333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0, + 0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0, + 0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0, + 0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0, + 0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31, +} +T.MOTION = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36, + 33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51, + 57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108, + 105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0, + 0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156, + 141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0, + 0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0, + 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, + 0, -15, 0, 0, -11, 0, 0, -13, +} +T.DCT_COEFF = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, + 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, + 75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0, + 0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120, + 123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0, + 0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0, + 0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201, + 210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273, + 240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0, + 0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333, + 342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339, + 309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417, + 420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411, + 399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0, + 0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0, + 0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510, + 483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549, + 546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0, + 0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0, + 0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0, + 0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0, + 0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0, + 0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654, + 633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657, + 624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0, + 0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0, + 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, + 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, +} +-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size +T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } } +T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } } +-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows) +T.DCT_COEFF_B15 = { + 2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8, + 124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16, + 30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24, + 22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32, + 23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40, + 2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264, + 30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272, + 17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769, + 38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282, + 18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050, + 120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074, + 36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098, + 31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145, + 28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937, +} +-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code +T.NON_LINEAR_QSCALE = { [0] = 0, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112, +} +-- the alternate scan (Figure 7-3): scan index -> natural position +T.ALTERNATE_SCAN = { [0] = 0, + 8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58, + 35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46, + 54, 62, 39, 47, 55, 63, +} +return T +end +__FILES["codecs/video/Mpeg2/Vlc"] = function() + +-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). +-- +-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds +-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level +-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, +-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the +-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / +-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); +-- the MPEG-2 tables are built from code lists. +local T = __include("codecs/video/Mpeg2/Tables") + +local V = {} + +type Leaf = { code: number, len: number, value: number } + +local function leaves(tree: { [number]: number }): { Leaf } + local out: { Leaf } = {} + local function walk(state: number, code: number, len: number) + if tree[state] == 0 and len > 0 then + table.insert(out, { code = code, len = len, value = tree[state + 2] }) + return + end + for bit = 0, 1 do + local nxt = tree[state + bit] + if nxt ~= nil and nxt > 0 then + walk(nxt, code * 2 + bit, len + 1) + end + end + end + walk(0, 0, 0) + return out +end + +local function flatLeaves(ls: { Leaf }): (buffer, number) + local k = 0 + for _, l in ls do + k = math.max(k, l.len) + end + local lut = buffer.create(4 * 2 ^ k) + for _, l in ls do + local shift = k - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768) + end + end + return lut, k +end + +local function flat(tree: { [number]: number }): (buffer, number) + return flatLeaves(leaves(tree)) +end + +-- { { code, length } } indexed from 1 -> leaves with value = index - 1 +local function codeLeaves(codes: { { number } }): { Leaf } + local out: { Leaf } = {} + for i, c in codes do + table.insert(out, { code = c[1], len = c[2], value = i - 1 }) + end + return out +end + +V.SUB = 0x1000000 +V.ESC = 0xFFFF +V.EOB = 0xFFFE + +-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits +local function twoLevel(ls: { Leaf }): buffer + local subs: { [number]: number } = {} + local nsub = 0 + for _, l in ls do + if l.len > 8 then + local prefix = l.code // 2 ^ (l.len - 8) + if subs[prefix] == nil then + nsub += 1 + subs[prefix] = nsub + end + end + end + local lut = buffer.create(4 * 256 * (1 + nsub)) + for _, l in ls do + if l.len <= 8 then + local shift = 8 - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value) + end + else + local prefix = l.code // 2 ^ (l.len - 8) + local s = subs[prefix] + buffer.writeu32(lut, prefix * 4, V.SUB + s) + local rest = l.code % 2 ^ (l.len - 8) + local shift = 16 - l.len + local first = rest * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value) + end + end + end + return lut +end + +V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape +V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) +V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) +V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) +do + -- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma + -- pattern bits) + local ls = leaves(T.CODE_BLOCK_PATTERN) + table.insert(ls, { code = 1, len = 9, value = 0 }) + V.CBP, V.CBP_BITS = flatLeaves(ls) +end +V.MOTION, V.MOTION_BITS = flat(T.MOTION) +V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA)) +V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA)) + +do + local ls = leaves(T.DCT_COEFF) + V.DCT_FIRST = twoLevel(ls) + local nextLs: { Leaf } = {} + for _, l in ls do + if l.len == 1 and l.code == 1 then + table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10" + table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11" + else + table.insert(nextLs, l) + end + end + V.DCT_NEXT = twoLevel(nextLs) +end + +do + local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } } + local b = T.DCT_COEFF_B15 + for i = 1, #b, 3 do + table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] }) + end + V.DCT_B15 = twoLevel(ls) +end + +return V +end +__FILES["codecs/video/Theora"] = function() + +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska +-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau +-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). +-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV +-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, +-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); +-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). +-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). +-- +-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate +-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err +-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region +-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down +-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position +-- +-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +local Err = __include("core/Err") +local Types = __include("Types") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Header = __include("codecs/video/Theora/Header") +local Decoder = __include("codecs/video/Theora/Decoder") + +local Theora = {} + +type Info = Header.Info + +type Options = { + maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) +} + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil +function Theora.isHeader(b: buffer, off: number?, len: number?): number? + local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) +function Theora.splitConfig(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size += b + p += 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p += lens[k] + end + return out +end + +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + +-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) +function Theora.granuleFrame(info: Header.Info, g: number): number + if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = g // shift + local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f -= 1 + end + return f +end + +-- ------------------------------------------------------------------------------------------------ decoder +local Dec = {} +Dec.__index = Dec + +type TheoraDecoder = typeof(setmetatable( + {} :: { + info: Header.Info, + vendor: string, + comments: { string }, + tags: { [string]: string }, + width: number, -- the picture region + height: number, + frameRate: number, + pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" + aspect: number, -- pixel aspect ratio (1 when unknown) + frames: number, -- packets decoded (dupes included) + _st: Decoder.State, + _any: boolean, -- a frame was decoded + }, + Dec +)) + +-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config +function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) + local list: { buffer }? = nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from(if ok3 then serr else tostring(setup)) + end + local st = Decoder.new(info, setup) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1, + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). +function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) + local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames += 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) +function Dec.reset(self: TheoraDecoder) + local st = self._st + st.shown = st.prev +end + +local function window(self: TheoraDecoder): (number, number, number, number) + local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, +-- chroma height +function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) + local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd + local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd + cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) +function Dec.image(self: TheoraDecoder): Types.Image + local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = (w + 1) // 2, (h + 1) // 2 + buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +-- ------------------------------------------------------------------------------------------------ registry +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config +-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat +function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec :: TheoraDecoder + local pending: { any } = {} + local self: any = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora +end +__FILES["codecs/video/Theora/Decoder"] = @native function() + + + +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A +-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, +-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: +-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode +-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel +-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; +-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), +-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for +-- unrestricted motion vectors, golden / previous reference frames; +-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. +-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, +-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), +-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- +-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled +-- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +local Header = __include("codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n += 1 + end + MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + @native local function put(code: number, len: number, v: number) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +type State = { + pf: number, + hdec: number, + vdec: number, + fw: number, + fh: number, + pw: { number }, -- plane sizes in pixels, [pli + 1] + ph: { number }, + nhf: { number }, -- plane sizes in fragments + nvf: { number }, + foff: { number }, -- first fragment id - 1 of each plane + stride: { number }, + padx: { number }, + pady: { number }, + origin: { number }, -- byte offset of pixel (0, 0) + planeSize: { number }, + nfrags: number, + nsbs: number, + sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs + sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 + sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] + nmbs: number, + mbMode: { number }, -- [mbi + 1]: -1 outside the frame + mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 + mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format + -- per fragment [fi] + coded: { number }, + refi: { number }, + fmode: { number }, + mvx: { number }, + mvy: { number }, + qii: { number }, + dcv: { number }, + tis: { number }, + last: { number }, + fpos: { number }, -- byte offset of the fragment's first pixel in its plane + fpl: { number }, -- plane (0..2) + coef: buffer, -- i16 [(fi - 1) * 64 + zzi] + clist: { { number } }, -- coded fragments per plane, coded order + ncl: { number }, + act: { { number } }, + refs: { { buffer } }, -- [r][pli + 1] + gold: number, + prev: number, + shown: number, -- the reference holding the last decoded picture + dequant: buffer, + lflim: { number }, + huff: { number }, + roots: { number }, + blk: buffer, -- i16 x 64 work blocks + tmp: buffer, + bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] + keyframes: number, +} + +-- new(info, setup) -> State +@native function D.new(info: Header.Info, setup: Header.Setup): State + local pf = info.pixelFormat + local hdec = if pf % 2 == 0 then 1 else 0 + local vdec = if pf < 2 then 1 else 0 + local fw, fh = info.frameWidth, info.frameHeight + local st: any = { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(128), + tmp = buffer.create(128), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 + local w, h = fw // 2 ^ hd, fh // 2 ^ vd + local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd + st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 + st.foff[pli + 1] = nfr + nfr += (w // 8) * (h // 8) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr: { number } = {} + local sbQuadValid: { boolean } = {} + local sbPlane: { number } = {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = if q == 3 then 2 else 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi += 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 + elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 + end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi += 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } + st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st :: State +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +@native local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) + local t0 = (C4 * (x0 + x4)) // 65536 + local t1 = (C4 * (x0 - x4)) // 65536 + local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 + local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 + local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 + local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 + local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 + local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 + local r = t4 + t5 + t5 = (C4 * (t4 - t5)) // 65536 + t4 = r + r = t7 + t6 + t6 = (C4 * (t7 - t6)) // 65536 + t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +@native local function idctRows(blk: buffer, tmp: buffer) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = (C4 * x0) // 65536 + writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +@native local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) + end +end + +@native local function wrap16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +@native local function mvSplit(d: number, q: boolean): (number, number) + local div = if q then 4 else 2 + local a = if d < 0 then -((-d) // div) else d // div + local frac = d - a * div + local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 + return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added +@native local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = if mode == INTRA then 0 else 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + local fv = 0 + if last == 0 then + fv = wrap16((dc * dcq + 15) // 32) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idctRows(blk, st.tmp) + end + -- the prediction + if ri == SELF then + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u: number = readu32(ref, a) + local v: number = readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2: number = readu32(ref, a + 4) + local v2: number = readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) + end + else + for y = 0, 7 do + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) + end + end + end + -- the residual + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then + for y = 0, 7 do + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ loop filter +@native local function filterH(b: buffer, p: number, stride: number, bv: { number }) + p -= 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p += stride + end +end + +@native local function filterV(b: buffer, p: number, stride: number, bv: { number }) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +@native local function loopFilter(st: State, planes: { buffer }, flimit: number) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = if i > 0 then 2 * flimit - a else a - 2 * flimit + end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +@native local function borders(st: State, planes: { buffer }) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +@native local function dcPredict(st: State) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ frame decode +-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in +-- st.refs[st.shown]. +@native function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) + if len <= 0 then + return "dup", nil + end + -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + @native local function bits(n: number): number + if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) + pos += n + return w + end + local huff = st.huff + @native local function sbRun(): number + if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + @native local function blockRun(): number + if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n += 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total += n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial += flag + sbi += 1 + run -= 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run -= 1 + full[sbi + 1] = flag == 1 + end + sbi += 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run -= 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n += 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total += n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet: { number } + if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx: number + if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos -= 7 - e % 8 + idx = e // 8 + end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + @native local function mv(): number + if clc then + local v = bits(6) + return if v % 2 == 1 then -(v // 2) else v // 2 + end + local e = MV_VLC[bits(8) + 1] + pos -= 8 - e % 16 + return e // 16 - 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 + cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 + elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n += 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k]] = flag + nqi1 += flag + k += 1 + run -= 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k]] == 0 do + k += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run -= 1 + qii[fi] += flag + end + k += 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy: number = bits(4) + local hc: number = bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 + for pli = 1, 3 do + local sel: number = if pli == 1 then hy else hc + local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs -= 1 + t = 64 + else + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos += rshift(e, 6) + tok = band(e, 63) + break + end + pos += nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos += ex + end + if tok < 7 then + local run: number + if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = if eb == 0 then 2 ^ 31 else eb + end + eobs = run - 1 + t = 64 + else + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w += 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + dcPredict(st) + + -- reconstruction into a free reference buffer + local self = 1 + while self == st.gold or self == st.prev do + self += 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes += 1 + else + st.prev = self + end + st.shown = self + return if intra then "key" else "inter", nil +end + +-- ------------------------------------------------------------------------------------------------ output +-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose +-- top-left corner is (x0, y0) counted from the top of the plane +@native function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer + local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 +-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +@native function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) + end + end + end +end + +return D +end +__FILES["codecs/video/Theora/Header"] = function() + +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / +-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis +-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the +-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman +-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; +-- the table layout here is simpler). Never throws: bad headers return nil, message. +local Bits = __include("core/Bits") + +local H = {} + +type Info = { + versionMajor: number, + versionMinor: number, + versionSub: number, + frameWidth: number, -- coded frame size (multiples of 16) + frameHeight: number, + picWidth: number, -- the picture region (the displayed part) + picHeight: number, + picX: number, -- from the left + picY: number, -- from the bottom, as stored + fpsNum: number, + fpsDen: number, + aspectNum: number, + aspectDen: number, + colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG + bitrate: number, + quality: number, + granuleShift: number, + pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved) +} + +type Setup = { + lflim: { number }, -- [qi + 1]: loop filter limit + dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora + huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable) + roots: { number }, -- [table + 1]: the root node offset in huff +} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi +H.ZIGZAG = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} + +local function ilog(v: number): number + local n = 0 + while v > 0 do + n += 1 + v = v // 2 + end + return n +end + +-- ------------------------------------------------------------------------------------------------ identification +-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +function H.info(b: buffer, off: number, len: number): (Info?, string?) + if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info: Info = { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ comment +-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str(): string? + if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p += 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p += n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p += 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list: { string } = {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- ------------------------------------------------------------------------------------------------ Huffman trees +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br: any): ({ number }?, { number }?, { number }?) + -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len += 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves += 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + -- insert the leaf + local n = 1 + for d = 1, len do + local k = (code // 2 ^ (32 - d)) % 2 + local kids = if k == 0 then kid0 else kid1 + local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (code // cb) % 2 == 1 do + code -= cb + cb *= 2 + len -= 1 + end + if len <= 0 then + break + end + code += cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number + local heights: { [number]: number } = {} + local function height(n: number): number + local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = if kid0[n] ~= 0 then height(kid0[n]) else 0 + local c = if kid1[n] ~= 0 then height(kid1[n]) else 0 + h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n: number): number + local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = bit32.extract(i, nb - 1 - d, 1) + local nx = if bit == 0 then kid0[cur] else kid1[cur] + d += 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +-- ------------------------------------------------------------------------------------------------ setup +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +function H.setup(b: buffer, off: number, len: number): (Setup?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms: { { number } } = {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges: { { sizes: { number }, idx: { number } } } = {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = i // 3, i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi += s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in idx do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1] + while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (dcScale[qi + 1] * base[1] // 100) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi += 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz) + end + end + end + end + end + -- the 80 Huffman trees + local huff: { number } = {} + local roots: { number } = {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H +end +__FILES["codecs/video/Video"] = function() + +-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. +-- +-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them +-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a +-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / +-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs +-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). +-- +-- local Video = require("@rosetta/codecs/video/Video") +-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" +-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) +-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) +-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) +-- +-- Never throws: bad data / missing codecs come back as nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Video = {} + +type Entry = { + id: string, -- our codec id + name: string, -- a human name + fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs + matroska: { string }?, -- Matroska / WebM CodecIDs + -- new(track, opts) -> a decoder instance (nil = decode not supported) + new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, + [string]: any, +} + +-- ------------------------------------------------------------------------------------------------ simple decoders +-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no +-- picture to show, such as a hidden VP8 altref frame) +function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(decodeOne, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + if resetFn then + resetFn() + end + end + return self :: any +end + +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged +-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / +-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) +local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local bps = if bits > 8 then 2 else 1 + local shift = 2 ^ (bits - 8) + local function sample(o: number): number + if bps == 1 then + return buffer.readu8(data, o) + end + return math.min(255, buffer.readu16(data, o) // shift) + end + for i = 0, w * h - 1 do + buffer.writeu8(px, i, sample(i * bps)) + end + local scw, sch = w, h -- source chroma plane size + if pf == "yuv420p" then + scw, sch = cw, ch + elseif pf == "yuv422p" then + scw, sch = cw, h + end + local uo, vo = w * h * bps, (w * h + scw * sch) * bps + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local i = cy * cw + cx + local u, v + if pf == "gray" then + u, v = 128, 128 + elseif pf == "yuv420p" then + u, v = sample(uo + i * bps), sample(vo + i * bps) :: number + elseif pf == "yuv422p" then + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 + v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2 + else + local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps + u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4 + v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4 + end + buffer.writeu8(px, w * h + i, u) + buffer.writeu8(px, w * h + cw * ch + i, v) + end + end + return img +end + +local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = { + yuv420p = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yv12 = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yuv422p = function(w, h, cw, _ch) + return w * h + 2 * cw * h + end, + yuv444p = function(w, h) + return w * h * 3 + end, + yuva444p = function(w, h) + return w * h * 4 + end, + gray = function(w, h) + return w * h + end, +} + +local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local w, h = track.width or 0, track.height or 0 + if w <= 0 or h <= 0 or w * h > 2 ^ 26 then + return nil, Err.new(Err.CORRUPT, "raw video without a valid size") + end + local pf = track.pixelFormat or "yuv420p" + local bits = track.bitDepth or 8 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local flip = track.flip == true + local planar = PLANAR_SIZE[pf] + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local n = buffer.len(data) + if planar then + local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1) + if n < need then + return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") + end + if pf == "yuv420p" and bits == 8 then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, need) + return img, nil + elseif pf == "yv12" then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, w * h) + buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) + buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) + return img, nil + end + return rawPlanar(data, pf, bits, w, h), nil + end + local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 + local stride: number = track.stride or w * bpp + if n < stride * (h - 1) + w * bpp then + return nil, Err.new(Err.TRUNCATED, "raw frame too short") + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local bgr = pf == "bgr24" or pf == "bgra" + for y = 0, h - 1 do + local s = (if flip then h - 1 - y else y) * stride + local o = y * w * 4 + for x = 0, w - 1 do + local p = s + x * bpp + local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2) + if bgr then + a, c = c, a + end + buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) + end + end + return img, nil + end), nil +end + +local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Vp8 = __include("codecs/image/Vp8") + local dec = Vp8.newDecoder() + local o = { maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) + if not img then + return nil, err + end + local src = img.meta.source + if type(src) == "table" and src.show == false then + return nil, nil + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + return img, nil + end, function() + if dec.reset then + dec:reset() + else + dec = Vp8.newDecoder() + end + end), nil +end + +-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout +-- allows, else rgba8 +local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Jpeg = __include("codecs/image/Jpeg") + local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + local img, err = Jpeg.decode(data, 0, buffer.len(data), o) + if img and img.format == "yuv420p" then + img.meta.yuv = { range = "full", matrix = "bt601" } + end + return img, err + end), nil +end + +-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first +local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) + local Jpeg = __include("codecs/image/Jpeg") + local src = img + if img.format == "yuv420p" then + local range = Yuv.info(img) + if range ~= "full" then + src = Yuv.toFullRange(img) + end + end + return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) +end + +-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display +local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Mpeg2 = __include("codecs/video/Mpeg2") + return Mpeg2.newVideoDecoder(track, opts) +end + +-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); +-- pictures in display order with the pts of their packet +local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H264 = __include("codecs/video/H264") + return H264.newVideoDecoder(track, opts) +end + +-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering +local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local H263 = __include("codecs/video/H263") + local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) + return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) + return dec:image(data) + end, function() + dec:reset() + end), nil +end + +-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv +-- builds the same); one picture per packet, empty packets repeat the previous one +local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Theora = __include("codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + +-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) +local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) + return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + return __include("codecs/video/Legacy").newDecoder(id, track, opts) + end +end + +-- ------------------------------------------------------------------------------------------------ registry +-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +local BUILTIN: { Entry } = { + { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, + { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder }, + { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder }, + { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, + { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, + { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, + { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, + { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, + { id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder }, + { id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder }, + { id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } }, + { id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } }, + { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, + { id = "flashsv2", name = "Flash Screen Video 2" }, + { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, +} + +local byId: { [string]: Entry } = {} +local byFourcc: { [string]: string } = {} +local byMatroska: { [string]: string } = {} + +-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it +function Video.register(entry: Entry): (boolean, Err.Err?) + if type(entry) ~= "table" or type(entry.id) ~= "string" then + return false, Err.new(Err.ARG, "register: needs an entry with an id") + end + local old = byId[entry.id] + if old and entry.new == nil then + entry.new = old.new + end + byId[entry.id] = entry + for _, f in entry.fourcc or {} do + byFourcc[f] = entry.id + end + for _, m in entry.matroska or {} do + byMatroska[m] = entry.id + end + return true, nil +end +for _, e in BUILTIN do + Video.register(e) +end + +-- the registry (read only by convention): id -> Entry +Video.codecs = byId + +-- fromFourcc(fourcc) -> codec id | nil +function Video.fromFourcc(fcc: string): string? + return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] +end + +-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) +function Video.fromMatroska(id: string): string? + return byMatroska[id] +end + +-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil +function Video.entry(id: string): Entry? + return byId[id] +end + +-- canDecode(codecId) -> boolean +function Video.canDecode(id: string): boolean + local e = byId[id] + return e ~= nil and e.new ~= nil +end + +-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) +function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local e = byId[track.codec] + if not e or not e.new then + return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec)) + end + local ok, dec, err = pcall(e.new :: any, track, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec)) + end + return dec, err +end + +-- ------------------------------------------------------------------------------------------------ VideoDecoder +local function toRGBA(_self: any, f: any): Types.Image + local img = if type(f) == "table" and f.image then f.image else f + local out = Yuv.imageToRgba(img) + return out or img +end + +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p) + track: number?, -- the video track id (default: the first video track) + maxPixels: number?, + openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook + audio: boolean?, -- false: do not open the audio track + -- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before + -- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none + maxSide: number?, + -- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield) + yield: (() -> ())?, + [string]: any, +} + +-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through +-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and +-- the demuxer (remuxing) and audio work. +function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local o: OpenOptions = opts or {} + local track: Types.Track? = nil + if o.track then + for _, t in demuxer.tracks do + if t.id == o.track then + track = t + end + end + if not track then + return nil, Err.new(Err.ARG, "no track " .. tostring(o.track)) + end + else + track = demuxer:track("video") + end + local codec: Types.VideoCodecDecoder? = nil + local codecErr: Err.Err? = nil + if track then + codec, codecErr = Video.decoder(track, o) + else + codecErr = Err.new(Err.UNSUPPORTED, "no video track") + end + local v: any = { + kind = "video", + format = demuxer.format, + codec = if track then track.codec else "none", + width = if track then track.width or 0 else 0, + height = if track then track.height or 0 else 0, + frameRate = if track then track.frameRate or 0 else 0, + frames = if track then track.frames or 0 else 0, + duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration, + track = track, + demuxer = demuxer, + meta = demuxer.meta or {}, + decodeError = codecErr, + toRGBA = toRGBA, + } + if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then + v.frames = math.floor(v.duration * v.frameRate + 0.5) + end + -- audio + if o.audio ~= false then + local at = demuxer:track("audio") + if at then + if o.openAudio then + local ok, dec, err = pcall(o.openAudio, demuxer, at) + if ok and dec then + v.audio = dec + else + v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec)) + end + else + v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)") + end + end + end + local index, flushed, skipUntil = 0, false, -math.huge + local tid = if track then track.id else -1 + local scale: number = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 + local start = demuxer.startTime or 0 + v.startTime = start + local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0 + local lastPts = nil :: number? + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + if not codec then + return nil, codecErr + end + local dec = codec :: Types.VideoCodecDecoder + while true do + local img, pts, key = dec:receive() + if img then + local t = (pts or 0) / scale - start + if t + 1e-9 >= skipUntil then + if index < 0 then + -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); + -- without a frame rate, counted from the seek) + index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 + end + index += 1 + local d = defaultDur + if lastPts and t > (lastPts :: number) and defaultDur == 0 then + d = t - (lastPts :: number) + end + lastPts = t + local maxSide = o.maxSide + if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then + local hook: any = o.yield + if hook then + pcall(hook) + end + local s = maxSide / math.max(img.width, img.height) + img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5))) + end + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil + end + else + local p = demuxer:read(tid) + if p == nil then + if flushed then + return nil, nil + end + flushed = true + dec:flush() + else + local err = dec:decode(p) + if err then + return nil, err + end + end + end + end + end + function v.seek(self: any, seconds: number) + demuxer:seek(seconds + start) + if codec then + codec:reset() + end + flushed = false + skipUntil = seconds + lastPts = nil + index = -1 -- recomputed from the first frame's time + if self.audio then + pcall(self.audio.seek, self.audio, seconds) + end + end + function v.reset(self: any) + self:seek(0) + skipUntil = -math.huge + index = 0 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ frames-backed +-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after +-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. +function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) + if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then + return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") + end + local w, h = images[1].width, images[1].height + local pts: { number } = {} + local durs: { number } = {} + local t = 0 + for i, img in images do + if type(img) ~= "table" or img.width ~= w or img.height ~= h then + return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image") + end + local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1) + if type(d) ~= "number" or d ~= d or d < 0 then + d = 0.1 + end + pts[i] = t + durs[i] = d + t += d + end + local n = #images + local o = opts or {} + local v: any = { + kind = "video", + format = o.format or "frames", + codec = "frames", + width = w, + height = h, + frameRate = if t > 0 then n / t else 10, + frames = n, + duration = t, + loops = o.loops, + meta = o.meta or {}, + toRGBA = toRGBA, + images = images, + } + local i = 0 + function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?) + i += 1 + if i > n then + i = n + return nil, nil + end + local img = images[i] + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil + end + function v.seek(self: any, seconds: number) + local k = 0 + for j = 1, n do + if pts[j] <= seconds + 1e-9 then + k = j - 1 + end + end + i = k + end + function v.reset(self: any) + i = 0 + end + return v, nil +end + +return Video +end +__FILES["codecs/video/Video/Source"] = function() + +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either +-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, +-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw +-- yuv420p frames, PCM audio from the audio Decoder). New in rosetta. +-- +-- local streams, err = Source.streams(value, opts, { +-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) +-- audio = { copy = { opus = true, vorbis = true }, pcm = true }, +-- }) +-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, +-- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Source = {} + +type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer } +type Stream = { + kind: "video" | "audio", + codec: string, + copied: boolean, + width: number?, + height: number?, + frameRate: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, + track: Types.Track?, + packets: { OutPacket }, +} +type Want = { + video: { copy: { [string]: boolean }?, encode: string? }?, + audio: { copy: { [string]: boolean }?, pcm: boolean? }?, +} + +local function allows(set: { [string]: boolean }?, codec: string): boolean + return set ~= nil and (set[codec] == true or set["*"] == true) +end + +-- the packets of a source track, times in seconds +local function copyPackets(dmx: any, track: Types.Track): { OutPacket } + local out = {} + local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 + local n = dmx:count(track.id) + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data }) + end + end + return out +end + +local function trackStream(track: Types.Track, packets: { OutPacket }): Stream + return { + kind = track.kind :: any, + codec = track.codec, + copied = true, + width = track.width, + height = track.height, + frameRate = track.frameRate, + sampleRate = track.sampleRate, + channels = track.channels, + bitsPerSample = track.bitsPerSample, + config = track.config, + track = track, + packets = packets, + } +end + +-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": +-- yuv420p planes) +local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) + local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil + if codec ~= "rawvideo" then + local Video = __include("codecs/video/Video") + local e = Video.entry(codec) + encode = e and e.encode + if not encode then + return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder") + end + end + if type(v.reset) == "function" then + v:reset() + end + local packets: { OutPacket } = {} + local w, h = v.width, v.height + local maxFrames = opts.maxFrames or math.huge + while #packets < maxFrames do + local f, err = v:nextFrame() + if not f then + if err then + return nil, err + end + break + end + local img: Types.Image = f.image + if (w == 0 or h == 0) and #packets == 0 then + w, h = img.width, img.height + end + if img.width ~= w or img.height ~= h then + return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")") + end + local data: buffer? + if codec == "rawvideo" then + local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601") + if not y then + return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format) + end + data = y.pixels + else + local e2 + data, e2 = (encode :: any)(img, opts) + if not data then + return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode") + end + end + table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer }) + end + if #packets == 0 then + return nil, Err.new(Err.ARG, "no frames to write") + end + local fr = v.frameRate + if not fr or fr <= 0 then + local d = packets[1].duration + fr = if d > 0 then 1 / d else 25 + end + return { + kind = "video", + codec = codec, + copied = false, + width = w, + height = h, + frameRate = fr, + packets = packets, + } :: Stream, nil +end + +-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) +local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) + local ch, rate = dec.channels, dec.sampleRate + if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then + return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate") + end + pcall(dec.seek, dec, 0) + local chunk = opts.audioChunk or 4096 + local packets: { OutPacket } = {} + local pos = 0 + local tmp: buffer? = nil + while true do + local ok, out, n = pcall(dec.read, dec, chunk, tmp) + if not ok or not out or not n or n <= 0 then + break + end + tmp = out + local data = buffer.create(n * ch * 2) + for i = 0, n * ch - 1 do + local s = buffer.readf32(out, i * 4) + local v = math.floor(s * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + buffer.writei16(data, i * 2, v) + end + table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data }) + pos += n + end + return { + kind = "audio", + codec = "pcm_s16le", + copied = false, + sampleRate = rate, + channels = ch, + bitsPerSample = 16, + packets = packets, + } :: Stream, nil +end + +-- streams(value, opts, want) -> { Stream } | nil, Err +function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) + local o = opts or {} + if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then + return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer") + end + local dmx = if value.kind == "demuxer" then value else value.demuxer + local out: { Stream } = {} + -- video + local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) + local wv = want.video + if wv and o.video ~= false then + if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then + table.insert(out, trackStream(vt, copyPackets(dmx, vt))) + elseif value.kind == "video" and wv.encode then + local s, err = encodeFrames(value, wv.encode, o) + if not s then + return nil, err + end + table.insert(out, s) + elseif vt then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) + end + end + -- audio + local wa = want.audio + if wa and o.audio ~= false then + local at: Types.Track? = dmx and dmx:track("audio") + if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then + table.insert(out, trackStream(at, copyPackets(dmx, at))) + elseif wa.pcm and value.kind == "video" and value.audio then + local s, err = pcmFrom(value.audio, o) + if not s then + return nil, err + end + if #s.packets > 0 then + table.insert(out, s) + end + elseif at and o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container") + end + end + if #out == 0 then + return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)") + end + return out, nil +end + +-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +function Source.rational(fps: number): (number, number) + if fps ~= fps or fps <= 0 then + return 25, 1 + end + if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then + return math.floor(fps + 0.5), 1 + end + local ntsc = fps * 1001 / 1000 + if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then + return math.floor(ntsc + 0.5) * 1000, 1001 + end + return math.floor(fps * 1000 + 0.5), 1000 +end + +-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the +-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet +-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) +function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) + local fd = math.huge + for _, p in s.packets do + if p.duration and p.duration > 0 and p.duration < fd then + fd = p.duration + end + end + if fd == math.huge then + fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04 + end + fd = math.max(fd, 1 / (maxFps or 100)) + local num, den = Source.rational(1 / fd) + local step = den / num + local out: { OutPacket } = {} + local slots = 0 + local t0 = if s.packets[1] then s.packets[1].pts else 0 + for _, p in s.packets do + local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step) + local n = math.max(1, math.floor(stop / step + 0.5) - slots) + for _ = 1, n do + table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data }) + slots += 1 + end + end + return num, den, out +end + +-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its +-- own order +function Source.interleave(streams: { Stream }): { { any } } + local order = {} + local pos = table.create(#streams, 1) + while true do + local best, bt = 0, math.huge + for si, s in streams do + local p = s.packets[pos[si]] + if p then + local t = p.dts or p.pts + if best == 0 or t < bt then + best, bt = si, t + end + end + end + if best == 0 then + break + end + table.insert(order, { best, streams[best].packets[pos[best]] }) + pos[best] += 1 + end + return order +end + +return Source +end +__FILES["containers/Archive"] = function() + +-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data +-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder +-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be +-- encoded by any writable archive format through its list() / read(). +-- +-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err +-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 }) +-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end }) +-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write() +-- +-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them +-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Tar = __include("containers/Tar") + +local Archive = {} + +-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source +type Entry = { + name: string, + size: number, + compressedSize: number?, + method: string?, + mtime: number?, + dir: boolean, + data: buffer?, + load: (() -> (buffer?, Err.Err?))?, + [string]: any, +} +type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?) + +local Methods = {} +Methods.__index = Methods + +-- the public fields of an entry (no data / loader) +local function public(e: Entry): Types.ArchiveEntry + local out: any = {} + for k, v in e :: any do + if k ~= "data" and k ~= "load" then + out[k] = v + end + end + return out +end + +function Methods.list(self: any): { Types.ArchiveEntry } + local out = table.create(#self._entries) :: { Types.ArchiveEntry } + for i, e in self._entries do + out[i] = public(e) + end + return out +end + +-- read(name) -> buffer | nil, Err (directories read as an empty buffer) +function Methods.read(self: any, name: string): (buffer?, Err.Err?) + local e: Entry? = self._byName[name] + if not e then + return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) + end + if e.data then + return e.data, nil + end + if e.load then + local ok, b, err = pcall(e.load) + if not ok then + return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b)) + end + if not b then + return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") + end + return b, nil + end + return buffer.create(0), nil +end + +-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name +function Methods.add(self: any, name: string, data: buffer | string, opts: any?) + local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0) + local o = opts or {} + local e: Entry = { + name = name, + size = buffer.len(b), + dir = o.dir == true, + mtime = o.mtime, + mode = o.mode, + data = b, + } + Archive.put(self, e) +end + +-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) +function Methods.write(self: any, opts: any?): (buffer?, Err.Err?) + local enc: Encoder? = self._encode + if not enc then + return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") + end + return enc(self, opts) +end + +-- new(format, encode?) -> an empty Archive +function Archive.new(format: string, encode: Encoder?): any + return setmetatable({ + kind = "archive", + format = format, + meta = {}, + _entries = {} :: { Entry }, + _byName = {} :: { [string]: Entry }, + _encode = encode, + }, Methods) +end + +-- put(archive, entry): append (or replace by name) an entry +function Archive.put(a: any, e: Entry) + local old = a._byName[e.name] + if old then + local i = table.find(a._entries, old) + if i then + a._entries[i] = e + end + else + table.insert(a._entries, e) + end + a._byName[e.name] = e +end + +-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another +-- format's): what encoders iterate. nil when the value is not an archive. +function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }? + if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then + return nil + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" then + return nil + end + local out = {} + for _, e in list do + if type(e) == "table" and type(e.name) == "string" then + table.insert(out, { + entry = e, + read = function(): (buffer?, Err.Err?) + local rok, b, err = pcall(value.read, value, e.name) + if not rok then + return nil, Err.new(Err.CORRUPT, tostring(b)) + end + return b, err + end, + }) + end + end + return out +end + +-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) +function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, buf, at, n) + return out, nil + end +end + +-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read +-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) +function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out: { { entry: Types.ArchiveEntry, data: buffer } } = {} + for _, it in items do + local b: buffer = buffer.create(0) + if not it.entry.dir then + local d, err = it.read() + if not d then + return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed") + end + b = d + end + table.insert(out, { entry = it.entry, data = b }) + end + return out, nil +end + +-- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value, +-- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take. +function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?) + if type(value) == "buffer" or type(value) == "string" then + local b = if type(value) == "string" then buffer.fromstring(value) else value + return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local out = {} + for _, it in items do + if not it.entry.dir then + local b, err = it.read() + if not b then + return nil, err + end + table.insert(out, { name = it.entry.name, data = b, entry = it.entry }) + end + end + return out, nil +end + +-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or +-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err +function Archive.streamData(value: any): (buffer?, Err.Err?) + if type(value) == "buffer" then + return value, nil + elseif type(value) == "string" then + return buffer.fromstring(value), nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + if #items == 1 and not items[1].entry.dir then + return items[1].read() + end + local list = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and (e.type == nil or e.type == "0") then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil + table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode }) + end + return Tar.write(list) +end + +-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store +-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date +function Archive.fromDos(stamp: number): number? + local time, date = stamp % 65536, stamp // 65536 + local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) + if date == 0 or m < 1 or m > 12 or d < 1 then + return nil + end + local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 + return Types.Date.daysFromCivil(y, m, d) * 86400 + secs +end + +-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31) +function Archive.toDos(t: number?): number + if type(t) ~= "number" or t ~= t or t < 315532800 then + return 0x210000 -- 1980-01-01 00:00 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = Types.Date.civilFromDays(days) + if y > 2107 then + y, m, d, rem = 2107, 12, 31, 86398 + end + return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 +end + +-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension +-- (".tgz" -> ".tar"), else "data" +function Archive.streamName(opts: any?, exts: { string }): string + local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil + if not name then + return "data" + end + local base = string.match(name, "([^/\\]+)$") or name + local stem, ext = string.match(base, "^(.+)%.([%w]+)$") + if stem and ext then + local e = string.lower(ext) + if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then + return stem .. ".tar" + end + if table.find(exts, e) then + return stem + end + end + return base +end + +return Archive +end +__FILES["containers/AudioWrap"] = function() + +-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone +-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another +-- format). New in rosetta. +-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); +-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; +-- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV; +-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); +-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; +-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); +-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; +-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). +-- +-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mux = __include("containers/Ogg/Mux") +local Adpcm = __include("codecs/audio/Adpcm") + +local AudioWrap = {} + +type PacketSource = { + count: ((self: any, track: number) -> number)?, + get: ((self: any, track: number, k: number) -> Types.Packet?)?, +} + +local function allPackets(dmx: PacketSource, track: Types.Track): { Types.Packet } + local out: { Types.Packet } = {} + local n = if dmx.count then dmx:count(track.id) else 0 + if n > 0 and dmx.get then + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, p) + end + end + end + return out +end + +local function concat(packets: { Types.Packet }, prefix: buffer?): buffer + local total = if prefix then buffer.len(prefix) else 0 + for _, p in packets do + total += buffer.len(p.data) + end + local out = buffer.create(total) + local o = 0 + if prefix then + buffer.copy(out, 0, prefix) + o = buffer.len(prefix) + end + for _, p in packets do + buffer.copy(out, o, p.data) + o += buffer.len(p.data) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ WAV +local PCM: { [string]: { number } } = { -- tag, bits, bytes swapped (big-endian source) + pcm_u8 = { 1, 8, 0 }, + pcm_s8 = { 1, 8, 0 }, + pcm_s16le = { 1, 16, 0 }, + pcm_s24le = { 1, 24, 0 }, + pcm_s32le = { 1, 32, 0 }, + pcm_s16be = { 1, 16, 1 }, + pcm_s24be = { 1, 24, 1 }, + pcm_s32be = { 1, 32, 1 }, + pcm_f32le = { 3, 32, 0 }, + pcm_f64le = { 3, 64, 0 }, + pcm_f32be = { 3, 32, 1 }, + pcm_f64be = { 3, 64, 1 }, + pcm_alaw = { 6, 8, 0 }, + pcm_mulaw = { 7, 8, 0 }, +} + +local function wav(fmt: buffer, data: buffer): buffer + local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64) + local fl = buffer.len(fmt) + local dl = buffer.len(data) + w:string("RIFF") + w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2)) + w:string("WAVE") + w:string("fmt ") + w:u32le(fl) + w:bytes(fmt) + if fl % 2 == 1 then + w:u8(0) + end + w:string("data") + w:u32le(dl) + w:bytes(data) + if dl % 2 == 1 then + w:u8(0) + end + return w:finish() +end + +local function pcmWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local spec = PCM[track.codec] + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate") + end + local bits = spec[2] + local data = concat(packets) + if spec[3] == 1 then + local bps = bits // 8 + for i = 0, buffer.len(data) - bps, bps do + for k = 0, bps // 2 - 1 do + local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k) + buffer.writeu8(data, i + k, b) + buffer.writeu8(data, i + bps - 1 - k, a) + end + end + end + if track.codec == "pcm_s8" then + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256) + end + end + local f = Bytes.writer(16) + local align = ch * bits // 8 + f:u16le(spec[1]) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * align) + f:u16le(align) + f:u16le(bits) + return wav(f:finish(), data), nil +end + +-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV +local function swfWav(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or ch > 2 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate") + end + local frames = 0 + for _, pk in packets do + frames += Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch) + end + local data = buffer.create(frames * ch * 4) + local d = 0 + for _, pk in packets do + d += Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch + end + local f = Bytes.writer(16) + f:u16le(3) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * ch * 4) + f:u16le(ch * 4) + f:u16le(32) + return wav(f:finish(), data), nil +end + +-- ------------------------------------------------------------------------------------------------ Ogg +-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) +local function opusSamples(b: buffer): number + local n = buffer.len(b) + if n < 1 then + return 0 + end + local toc = buffer.readu8(b, 0) + local config = toc // 8 + local fs: number + if config < 12 then + fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1] + elseif config < 16 then + fs = if config % 2 == 0 then 480 else 960 + else + fs = ({ 120, 240, 480, 960 })[config % 4 + 1] + end + local c = toc % 4 + local frames = if c == 0 then 1 elseif c == 3 then (if n >= 2 then buffer.readu8(b, 1) % 64 else 0) else 2 + return fs * frames +end + +local function opusHead(track: Types.Track): buffer + local c = track.config + if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then + return c + end + local w = Bytes.writer(19) + w:string("OpusHead") + w:u8(1) + w:u8(math.clamp(track.channels or 2, 1, 2)) + w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5)) + w:u32le(math.floor(track.sampleRate or 48000)) + w:u16le(0) + w:u8(0) + return w:finish() +end + +local function opusTags(): buffer + local w = Bytes.writer(32) + w:string("OpusTags") + local vendor = "rosetta" + w:u32le(#vendor) + w:string(vendor) + w:u32le(0) + return w:finish() +end + +local function ogg(headers: { buffer }, packets: { Types.Packet }, granuleOf: (p: Types.Packet, i: number) -> number): buffer + local mux = Mux.new({ pageSize = 4096 }) + local s = mux:stream(1) + for i, h in headers do + s:packet(h, 0, { flush = i == 1 or i == #headers }) + end + for i, p in packets do + s:packet(p.data, granuleOf(p, i), { eos = i == #packets }) + end + return mux:finish() +end + +-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data) +local function xiphHeaders(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 then + return nil + end + local count = buffer.readu8(c, 0) + 1 + local p = 1 + local sizes = {} + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = n - p - total + if sizes[count] < 0 then + return nil + end + local out = {} + for k = 1, count do + local b = buffer.create(sizes[k]) + buffer.copy(b, 0, c, p, sizes[k]) + p += sizes[k] + out[k] = b + end + return out +end + +-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the +-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0, +-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4 +-- samples (the first one as if its previous block had its own size, as ffmpeg times it). +local function bit(b: buffer, k: number): number + return bit32.extract(buffer.readu8(b, k // 8), k % 8, 1) +end +local function bits(b: buffer, k: number, n: number): number + local v = 0 + for i = n - 1, 0, -1 do + v = v * 2 + bit(b, k + i) + end + return v +end + +local function vorbisModes(id: buffer, setup: buffer): ({ number }?, { boolean }?) + if buffer.len(id) < 30 or buffer.len(setup) < 8 then + return nil, nil + end + local bs = buffer.readu8(id, 28) + local sizes = { 2 ^ (bs % 16), 2 ^ (bs // 16) } + -- the framing bit: the highest set bit of the last non-zero byte + local last = buffer.len(setup) - 1 + while last > 0 and buffer.readu8(setup, last) == 0 do + last -= 1 + end + local v = buffer.readu8(setup, last) + local hb = 7 + while hb > 0 and bit32.extract(v, hb, 1) == 0 do + hb -= 1 + end + local f = last * 8 + hb + local flags: { boolean } = {} + local pos = f + while #flags < 64 and pos - 41 >= 7 * 8 do + local s0 = pos - 41 + if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then + break + end + table.insert(flags, 1, bit(setup, s0) == 1) + pos = s0 + end + -- the largest count whose 6-bit field matches + for n = #flags, 1, -1 do + local start = f - 41 * n + if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then + local out = {} + for i = #flags - n + 1, #flags do + table.insert(out, flags[i]) + end + return sizes, out + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ ADTS +local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Err.Err?) + local c = track.config + local profile, rateIndex, chanConfig + if c and buffer.len(c) >= 2 then + local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1) + profile = b0 // 8 -- audio object type + rateIndex = (b0 % 8) * 2 + b1 // 128 + chanConfig = (b1 // 8) % 16 + else + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + profile = 2 + rateIndex = 4 + for i, r in rates do + if r == math.floor((track.sampleRate or 44100) + 0.5) then + rateIndex = i - 1 + end + end + chanConfig = track.channels or 2 + end + if profile < 1 or profile > 4 or rateIndex > 12 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS") + end + local w = Bytes.writer(64) + for _, p in packets do + local len = buffer.len(p.data) + 7 + w:u8(0xFF) + w:u8(0xF1) + w:u8((profile - 1) * 64 + rateIndex * 4 + chanConfig // 4) + w:u8((chanConfig % 4) * 64 + (len // 2048) % 4) + w:u8((len // 8) % 256) + w:u8((len % 8) * 32 + 0x1F) + w:u8(0xFC) + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ trim +-- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's +-- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus +-- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding) +function AudioWrap.trim(dec: any, skip: number, length: number?): any + if skip <= 0 and length == nil then + return dec + end + skip = math.max(0, skip) + local rate = dec.sampleRate + local w: any = setmetatable({}, { __index = dec }) + w.frames = math.max(0, (dec.frames or 0) - skip) + if length then + w.frames = if (dec.frames or 0) > 0 then math.min(w.frames, length) else length + end + w.duration = w.frames / rate + local cap = length or math.huge + local delivered = 0 + local function drop() + local left = skip + while left > 0 do + local _, n = dec:read(math.min(left, 4096)) + if not n or n <= 0 then + break + end + left -= n + end + end + local started = false + function w.read(_: any, n: number, out: buffer?): (buffer, number) + if not started then + started = true + drop() + end + local want = math.min(n, cap - delivered) + if want <= 0 then + return out or buffer.create(0), 0 + end + local b, got = dec:read(want, out) + delivered += got + return b, got + end + function w.seek(_: any, seconds: number) + started = true + if seconds <= 0 then + dec:seek(0) + drop() + delivered = 0 + else + dec:seek(seconds + skip / rate) + delivered = math.floor(seconds * rate + 0.5) + end + end + function w.position(_: any): number + return math.max(0, dec:position() - skip / rate) + end + return w +end + +-- ------------------------------------------------------------------------------------------------ wrap +-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err +function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) + if type(track) ~= "table" or track.kind ~= "audio" then + return nil, nil, Err.new(Err.ARG, "not an audio track") + end + if track.unsupported then + return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported) + end + local codec = track.codec + local packets = allPackets(dmx, track) + if #packets == 0 then + return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") + end + if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then + return wav(track.waveFormat, concat(packets)), "wav", nil + end + if codec == "adpcm_swf" then + local b, err = swfWav(track, packets) + return b, if b then "wav" else nil, err + end + if PCM[codec] then + local b, err = pcmWav(track, packets) + return b, if b then "wav" else nil, err + end + if codec == "mp3" or codec == "mp2" or codec == "mp1" then + return concat(packets), "mp3", nil + end + if codec == "ac3" then + return concat(packets), "ac3", nil + end + if codec == "flac" then + local c = track.config + local prefix: buffer? = nil + if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then + prefix = c + elseif c and buffer.len(c) >= 34 then + -- metadata blocks without the marker (MP4 dfLa payload after version / flags) + local start = if buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 then 4 else 0 + local b = buffer.create(4 + buffer.len(c) - start) + buffer.writestring(b, 0, "fLaC") + buffer.copy(b, 4, c, start) + prefix = b + else + return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO") + end + return concat(packets, prefix), "flac", nil + end + if codec == "opus" then + local head = opusHead(track) + local pre = buffer.readu16(head, 10) + local g = pre + local out = ogg({ head, opusTags() }, packets, function(p: Types.Packet): number + g += opusSamples(p.data) + local d = (p :: any).discardPadding + if type(d) == "number" and d > 0 then + return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding) + end + return g + end) + return out, "opus", nil + end + if codec == "vorbis" then + local c = track.config + local headers = c and xiphHeaders(c) + if not headers or #headers ~= 3 then + return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers") + end + local sizes, modes = vorbisModes(headers[1], headers[3]) + local granule, prev = 0, nil :: number? + local rate = track.sampleRate or 44100 + local scale = track.timescale + local out = ogg(headers, packets, function(p: Types.Packet): number + if not sizes or not modes then + return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times + end + local d = p.data + if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then + return granule + end + local mb = 0 + while 2 ^ mb < #(modes :: { boolean }) do + mb += 1 + end + local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0 + local cur = sizes[if (modes :: { boolean })[m + 1] then 2 else 1] + if prev then + granule += (prev + cur) // 4 + end + prev = cur + return granule + end) + return out, "vorbis", nil + end + if codec == "aac" then + if track.adts then + return concat(packets), "aac", nil -- already ADTS (MPEG-TS) + end + local b, err = adts(track, packets) + return b, if b then "aac" else nil, err + end + return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec)) +end + +return AudioWrap +end +__FILES["containers/Avi"] = function() + +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in rosetta. +-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk +-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets +-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). +-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. +-- +-- local avi, err = Avi.read(buf, base, limit) +-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf +-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute +-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) +-- +-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Avi = {} + +type Chunk = { offset: number, size: number, key: boolean } +type Stream = { + index: number, -- 0-based stream number (the "##" of the chunk ids) + type: string, -- strh fccType: "vids", "auds", "txts", "mids" + handler: string, + flags: number, + scale: number, + rate: number, + start: number, + length: number, + suggestedBufferSize: number, + sampleSize: number, + frame: { number }, -- rcFrame left, top, right, bottom + strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...) + name: string?, + chunks: { Chunk }, +} +type File = { + avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number }, + streams: { Stream }, + odml: { totalFrames: number }?, + info: { [string]: string }, + index: string, -- "odml" | "idx1" | "scan" +} + +local function u32(b: buffer, o: number): number + return readu32(b, o) +end + +-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not +-- entered); returns where it stopped +local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number + while p + 8 <= limit do + local id = readstring(b, p, 4) + local size = u32(b, p + 4) + local data = p + 8 + local ltype: string? = nil + if (id == "LIST" or id == "RIFF") and data + 4 <= limit then + ltype = readstring(b, data, 4) + end + if data + size > limit then + size = limit - data + end + if fn(id, data, size, ltype) == false then + return p + end + p = data + size + (size % 2) + end + return p +end + +local function streamNumber(id: string): number? + local a, b = string.byte(id, 1, 2) + if not a or not b then + return nil + end + local function hex(c: number): number? + if c >= 48 and c <= 57 then + return c - 48 + elseif c >= 65 and c <= 70 then + return c - 55 + elseif c >= 97 and c <= 102 then + return c - 87 + end + return nil + end + local h, l = hex(a), hex(b) + if h and l then + return h * 16 + l + end + return nil +end +Avi.streamNumber = streamNumber + +local function parseStrl(b: buffer, data: number, size: number, index: number): Stream + local s: Stream = { + index = index, + type = "", + handler = "", + flags = 0, + scale = 1, + rate = 1, + start = 0, + length = 0, + suggestedBufferSize = 0, + sampleSize = 0, + frame = { 0, 0, 0, 0 }, + strf = buffer.create(0), + chunks = {}, + } + local indx: { number }? = nil + walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean? + if id == "strh" and n >= 48 then + s.type = readstring(b, d, 4) + s.handler = readstring(b, d + 4, 4) + s.flags = u32(b, d + 8) + s.scale = u32(b, d + 20) + s.rate = u32(b, d + 24) + s.start = u32(b, d + 28) + s.length = u32(b, d + 32) + s.suggestedBufferSize = u32(b, d + 36) + s.sampleSize = u32(b, d + 44) + if n >= 56 then + s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) } + end + elseif id == "strf" then + local f = buffer.create(n) + buffer.copy(f, 0, b, d, n) + s.strf = f + elseif id == "strn" then + local str = readstring(b, d, n) + s.name = string.match(str, "^[^%z]*") + elseif id == "indx" and n >= 24 then + indx = { d, n } + end + return nil + end) + ;(s :: any)._indx = indx + return s +end + +-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s +local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean + if n < 24 or depth > 2 then + return false + end + local longsPerEntry = readu16(b, d) + local subType = readu8(b, d + 2) + local indexType = readu8(b, d + 3) + local entries = u32(b, d + 4) + if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration } + if longsPerEntry ~= 4 then + return false + end + local p = d + 24 + for _ = 1, entries do + if p + 16 > d + n then + break + end + local off = u32(b, p) + u32(b, p + 4) * 4294967296 + local size = u32(b, p + 8) + p += 16 + if off > 0 and off + 8 <= limit then + local sz = math.min(u32(b, off + 4), limit - off - 8) + readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1) + end + end + return #s.chunks > 0 + elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs) + if n < 24 then + return false + end + local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296 + local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD + local p = d + 24 + for _ = 1, entries do + if p + per > d + n then + break + end + local off = u32(b, p) + local size = u32(b, p + 4) + p += per + local key = size < 0x80000000 + size %= 0x80000000 + local at = base + off + if at >= 0 and at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = key }) + end + end + return true + end + return false +end + +-- read(buf, base, limit) -> File | nil, Err +function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then + return nil, Err.new(Err.CORRUPT, "not an AVI file", base) + end + local file: File = { + avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 }, + streams = {}, + odml = nil, + info = {}, + index = "scan", + } + local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end } + local idx1: { number }? = nil + local hdrl = false + -- every RIFF piece (AVI, then AVIX for OpenDML files) + walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean? + if id ~= "RIFF" then + return nil + end + walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean? + if cid == "LIST" and cltype == "hdrl" and not hdrl then + hdrl = true + local si = 0 + walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean? + if hid == "avih" and hn >= 40 then + file.avih = { + microSecPerFrame = u32(b, hd), + flags = u32(b, hd + 12), + totalFrames = u32(b, hd + 16), + streams = u32(b, hd + 24), + width = u32(b, hd + 32), + height = u32(b, hd + 36), + } + elseif hid == "LIST" and hltype == "strl" then + table.insert(file.streams, parseStrl(b, hd, hn, si)) + si += 1 + elseif hid == "LIST" and hltype == "odml" then + walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean? + if oid == "dmlh" and on >= 4 then + file.odml = { totalFrames = u32(b, od) } + end + return nil + end) + end + return nil + end) + elseif cid == "LIST" and cltype == "movi" then + table.insert(movis, { cd, cd + cn }) + elseif cid == "LIST" and cltype == "INFO" then + walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean? + file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or "" + return nil + end) + elseif cid == "idx1" and not idx1 then + idx1 = { cd, cn } + end + return nil + end) + return nil + end) + if not hdrl then + return nil, Err.new(Err.CORRUPT, "no hdrl list") + end + if #file.streams == 0 then + return nil, Err.new(Err.CORRUPT, "no streams") + end + -- 1. OpenDML indexes + local odml = true + for _, s in file.streams do + local ix = (s :: any)._indx + if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then + odml = false + end + end + if odml then + file.index = "odml" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 2. idx1 + local ok = false + if idx1 and movis[1] then + local d, n = idx1[1], idx1[2] + local count = n // 16 + local moviBase = movis[1][1] -- the 'movi' fourcc + -- relative or absolute offsets: check the first entry that points at a chunk id + local rel = true + if count > 0 then + local off = u32(b, d + 8) + local ckid = readstring(b, d, 4) + local relAt, absAt = moviBase + off, base + off + if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then + rel = true + elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then + rel = false + end + end + for k = 0, count - 1 do + local e = d + k * 16 + local ckid = readstring(b, e, 4) + local flags = u32(b, e + 4) + local off = u32(b, e + 8) + local size = u32(b, e + 12) + local sn = streamNumber(ckid) + local s = sn and file.streams[sn + 1] + if s and string.sub(ckid, 3, 4) ~= "pc" then + local at = (if rel then moviBase else base) + off + 8 + if at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 }) + ok = true + end + end + end + end + if ok then + file.index = "idx1" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 3. scan the movi lists + local function scan(d0: number, e0: number) + walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean? + if id == "LIST" and ltype == "rec " then + scan(d + 4, d + n) + return nil + end + local sn = streamNumber(id) + local s = sn and file.streams[sn + 1] + if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then + table.insert(s.chunks, { offset = d, size = n, key = true }) + end + return nil + end) + end + for _, m in movis do + scan(m[1] + 4, m[2]) + end + file.index = "scan" + end + end + for _, s in file.streams do + (s :: any)._indx = nil + end + return file, nil +end + +-- ------------------------------------------------------------------------------------------------ writing +type WStream = { + type: string, -- "vids" | "auds" + handler: string, -- fccHandler (4 chars) + scale: number, + rate: number, + sampleSize: number, -- 0 = every chunk one sample (video, VBR audio) + strf: buffer, + name: string?, + width: number?, + height: number?, + quality: number?, + ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio) +} +type WOptions = { + streams: { WStream }, + microSecPerFrame: number, + width: number, + height: number, + software: string?, +} + +-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order +function Avi.write(opts: WOptions, chunks: { { any } }): buffer + local ns = #opts.streams + local lengths = table.create(ns, 0) + local maxChunk = table.create(ns, 0) + local bytes = table.create(ns, 0) + local total = 0 + for _, c in chunks do + local si, data = c[1], c[2] + local n = buffer.len(data) + local s = opts.streams[si] + if s.sampleSize > 0 then + lengths[si] += n // s.sampleSize + else + lengths[si] += 1 + end + bytes[si] += n + if n > maxChunk[si] then + maxChunk[si] = n + end + total += n + 8 + (n % 2) + end + local frames = 0 + for si, s in opts.streams do + if s.type == "vids" and frames == 0 then + frames = lengths[si] + end + end + local w = Bytes.writer(total + 4096 + #chunks * 16) + w:string("RIFF") + local riffSize = w:tell() + w:u32le(0) + w:string("AVI ") + -- hdrl + w:string("LIST") + local hdrlSize = w:tell() + w:u32le(0) + w:string("hdrl") + w:string("avih") + w:u32le(56) + local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1 + local maxBytes = 0 + for si = 1, ns do + maxBytes += bytes[si] + end + w:u32le(math.floor(opts.microSecPerFrame + 0.5)) + w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0) + w:u32le(0) -- padding granularity + w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED + w:u32le(frames) + w:u32le(0) -- initial frames + w:u32le(ns) + local suggested = 0 + for si = 1, ns do + suggested = math.max(suggested, maxChunk[si] + 8) + end + w:u32le(suggested) + w:u32le(opts.width) + w:u32le(opts.height) + for _ = 1, 4 do + w:u32le(0) + end + for si, s in opts.streams do + w:string("LIST") + local strlSize = w:tell() + w:u32le(0) + w:string("strl") + w:string("strh") + w:u32le(56) + w:string(s.type) + w:string(s.handler) + w:u32le(0) -- flags + w:u16le(0) -- priority + w:u16le(0) -- language + w:u32le(0) -- initial frames + w:u32le(s.scale) + w:u32le(s.rate) + w:u32le(0) -- start + w:u32le(lengths[si]) + w:u32le(maxChunk[si]) + w:u32le(if s.quality then s.quality else 0xFFFFFFFF) + w:u32le(s.sampleSize) + w:u16le(0) + w:u16le(0) + w:u16le(s.width or 0) + w:u16le(s.height or 0) + w:string("strf") + w:u32le(buffer.len(s.strf)) + w:bytes(s.strf) + if buffer.len(s.strf) % 2 == 1 then + w:u8(0) + end + if s.name then + local nm = s.name .. "\0" + w:string("strn") + w:u32le(#nm) + w:string(nm) + if #nm % 2 == 1 then + w:u8(0) + end + end + w:setU32le(strlSize, w:tell() - strlSize - 4) + end + -- OpenDML extended header (total frames) + w:string("LIST") + w:u32le(16) + w:string("odml") + w:string("dmlh") + w:u32le(4) + w:u32le(frames) + w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) + -- INFO + local sw = (opts.software or "rosetta") .. "\0" + if #sw % 2 == 1 then + sw ..= "\0" + end + w:string("LIST") + w:u32le(4 + 8 + #sw) + w:string("INFO") + w:string("ISFT") + w:u32le(#sw) + w:string(sw) + -- movi + w:string("LIST") + local moviSize = w:tell() + w:u32le(0) + local moviBase = w:tell() + w:string("movi") + local index = table.create(#chunks) :: { { any } } + for _, c in chunks do + local si, data, key = c[1], c[2], c[3] + local s = opts.streams[si] + local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb")) + local at = w:tell() + local n = buffer.len(data) + w:string(id) + w:u32le(n) + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n }) + end + w:setU32le(moviSize, w:tell() - moviSize - 4) + -- idx1 + w:string("idx1") + w:u32le(#index * 16) + for _, e in index do + w:string(e[1]) + w:u32le(e[2]) + w:u32le(e[3]) + w:u32le(e[4]) + end + w:setU32le(riffSize, w:tell() - 8) + return w:finish() +end + +-- ------------------------------------------------------------------------------------------------ BITMAPINFO +type BitmapInfo = { + width: number, + height: number, -- signed: > 0 = bottom-up rows + bits: number, -- biBitCount + compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB) + palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0 + extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none +} + +-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | +-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; +-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +function Avi.bitmapInfo(f: buffer): BitmapInfo? + local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info: BitmapInfo = { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, (n - 40) // 4) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at -= 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + +return Avi +end +__FILES["containers/Chunks"] = function() + +-- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional +-- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a +-- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing +-- the loop. New in rosetta (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). +-- +-- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf) +-- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG +-- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end +-- local c = Chunks.find(list, "SSND") +-- +-- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in +-- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). +-- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one +-- byte earlier). layout.resize(id, declared) can replace a declared size (RF64's ds64). Never throws. +local Chunks = {} + +type Chunk = { + id: string, + start: number, -- the chunk header's offset + offset: number, -- the body's offset + size: number, -- the body size (after layout.resize / open-ended handling) + declared: number, -- the size field as written + avail: number, -- body bytes actually present (= size unless truncated) + truncated: boolean, + streamed: boolean, -- an open-ended chunk with size 0 / 0xFFFFFFFF +} + +type Layout = { + bigEndian: boolean?, -- size fields big-endian (default little) + sizeFirst: boolean?, -- the size comes before the id (PNG) + sizeBytes: number?, -- 4 (default) or 8 + trailer: number?, -- bytes after the body that belong to the chunk (PNG: the 4-byte CRC) + pad: number?, -- bodies are padded to a multiple of this (RIFF / IFF: 2; default 1) + lenientPad: boolean?, -- detect odd bodies written without their pad byte + openEnded: { [string]: boolean }?, + resize: ((id: string, declared: number) -> number?)?, + maxChunks: number?, -- default 100000 +} + +Chunks.RIFF = table.freeze({ pad = 2, lenientPad = true }) :: Layout +Chunks.RIFX = table.freeze({ pad = 2, lenientPad = true, bigEndian = true }) :: Layout +Chunks.IFF = table.freeze({ pad = 2, bigEndian = true }) :: Layout +Chunks.PNG = table.freeze({ sizeFirst = true, bigEndian = true, trailer = 4 }) :: Layout +Chunks.CAF = table.freeze({ bigEndian = true, sizeBytes = 8 }) :: Layout + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring + +local function printable4(b: buffer, p: number, limit: number): boolean + if p + 4 > limit then + return false + end + for i = 0, 3 do + local c = readu8(b, p + i) + if c < 32 or c > 126 then + return false + end + end + return true +end +Chunks.printable4 = printable4 + +local function u32(b: buffer, o: number, be: boolean): number + local v = readu32(b, o) + return if be then bit32.byteswap(v) else v +end + +-- walk(b, p, limit, layout?) -> { Chunk } of [p, limit) +function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Chunk } + local L: Layout = layout or Chunks.RIFF + local be = L.bigEndian == true + local sizeBytes = L.sizeBytes or 4 + local head = 4 + sizeBytes + local trailer = L.trailer or 0 + local pad = L.pad or 1 + local openEnded = L.openEnded + local resize = L.resize + local maxChunks = L.maxChunks or 100000 + local list: { Chunk } = {} + limit = math.min(limit, buffer.len(b)) + while p + head <= limit and #list < maxChunks do + local idAt = if L.sizeFirst then p + sizeBytes else p + local sizeAt = if L.sizeFirst then p else p + 4 + local id = readstring(b, idAt, 4) + local declared + if sizeBytes == 8 then + local hi, lo = u32(b, sizeAt, be), u32(b, sizeAt + 4, be) + if not be then + hi, lo = lo, hi + end + declared = hi * 4294967296 + lo + else + declared = u32(b, sizeAt, be) + end + local size = declared + if resize then + size = resize(id, declared) or declared + end + local body = p + head + local avail = limit - body + local c: Chunk = { + id = id, + start = p, + offset = body, + size = size, + declared = declared, + avail = math.min(size, avail), + truncated = false, + streamed = false, + } + table.insert(list, c) + if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then + c.streamed = size == 0 or size == 0xFFFFFFFF + c.truncated = not c.streamed + c.size, c.avail = avail, avail + break + end + if size + trailer > avail then + c.truncated = true -- (the body or its trailer runs past the end) + break + end + local rem = size % pad + local nextPos = body + size + trailer + (if rem > 0 then pad - rem else 0) + if L.lenientPad and rem > 0 and not printable4(b, nextPos, limit) and printable4(b, body + size + trailer, limit) then + nextPos = body + size + trailer + end + p = nextPos + end + return list +end + +-- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index +function Chunks.find(list: { Chunk }, id: string, from: number?): (Chunk?, number?) + for i = from or 1, #list do + if list[i].id == id then + return list[i], i + end + end + return nil, nil +end + +return Chunks +end +__FILES["containers/Cpio"] = function() + +-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment), +-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the +-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the +-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar +-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks +-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as +-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The +-- archive formats (archive/cpio, archive/rpm's payload) build on it. +-- +-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err +-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" }) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Cpio = {} + +type Entry = { + name: string, + size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size) + mode: number, -- the whole st_mode (file type bits included) + type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket + dir: boolean, + uid: number, + gid: number, + nlink: number, + mtime: number, + ino: number, + devmajor: number, + devminor: number, + rdevmajor: number, + rdevminor: number, + link: string?, -- symlink target + hardlink: string?, -- the first entry of this entry's hard link group (for the later links) + offset: number, -- absolute offset of the data in the buffer + check: number?, -- crc format: the stored byte sum +} +type ReadOptions = { + maxEntries: number?, -- default 1e6 + verify: boolean?, -- crc format: check the byte sums (default true) +} +type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe" + +local S_IFMT = 0xF000 +local TYPES: { [number]: string } = { + [0x8000] = "0", + [0x4000] = "5", + [0xA000] = "2", + [0x2000] = "3", + [0x6000] = "4", + [0x1000] = "6", + [0xC000] = "s", +} +local MODES: { [string]: number } = {} +for m, t in TYPES do + MODES[t] = m +end +Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits +Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter + +local TRAILER = "TRAILER!!!" + +-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset +function Cpio.format(b: buffer, o: number): string? + local n = buffer.len(b) + if o + 6 <= n then + local m = buffer.readstring(b, o, 6) + if m == "070701" then + return "newc" + elseif m == "070702" then + return "crc" + elseif m == "070707" then + return "odc" + end + end + if o + 2 <= n then + local v = buffer.readu16(b, o) + if v == 0x71C7 then + return "bin" + elseif v == 0xC771 then + return "binbe" + end + end + return nil +end + +-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits +local function num(b: buffer, o: number, n: number, base: number): number? + local s = buffer.readstring(b, o, n) + if base == 16 then + if not string.find(s, "^%x+$") then + return nil + end + elseif not string.find(s, "^[0-7]+$") then + return nil + end + return tonumber(s, base) +end + +-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32) +function Cpio.checksum(b: buffer, o: number, n: number): number + local s = 0 + local i = o + local e = o + n + while i + 4 <= e do + local v = buffer.readu32(b, i) + s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24) + i += 4 + end + while i < e do + s += buffer.readu8(b, i) + i += 1 + end + return s % 4294967296 +end + +-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err +local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?) + local h: any = {} + local nameAt + if fmt == "newc" or fmt == "crc" then + if p + 110 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local f = {} :: { number } + for i = 1, 13 do + local v = num(b, p + 6 + (i - 1) * 8, 8, 16) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8) + end + f[i] = v + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7] + h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13] + nameAt = p + 110 + elseif fmt == "odc" then + if p + 76 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 } + local f = {} :: { number } + local q = p + 6 + for i, w in widths do + local v = num(b, q, w, 8) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", q) + end + f[i] = v + q += w + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10] + h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255) + h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255) + nameAt = p + 76 + else + if p + 26 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local be = fmt == "binbe" + local function u16(i: number): number + local v = buffer.readu16(b, p + i * 2) + return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v + end + local dev, rdev = u16(1), u16(7) + h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6) + h.mtime = u16(8) * 65536 + u16(9) + h.namesize = u16(10) + h.size = u16(11) * 65536 + u16(12) + h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255) + h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255) + nameAt = p + 26 + end + if h.namesize < 1 or nameAt + h.namesize > e then + return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt) + end + h.nameAt = nameAt + return h, nil +end + +-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err +function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) + local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local verify = not (opts and opts.verify == false) + local fmt = Cpio.format(b, o) + if not fmt or o >= e then + return nil, Err.new(Err.CORRUPT, "not a cpio archive", o) + end + local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2 + local out: { Entry } = {} + local groups: { [string]: { Entry } } = {} + local p = o + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p) + end + if Cpio.format(b, p) ~= fmt then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local h, herr = header(b, p, e, fmt) + if not h then + return nil, herr + end + local name = buffer.readstring(b, h.nameAt, h.namesize) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + local data = h.nameAt + h.namesize + data = o + (data - o + align - 1) // align * align + if name == TRAILER then + break + end + if data + h.size > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data) + end + local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0" + local entry: Entry = { + name = name, + size = h.size, + mode = h.mode, + type = typ, + dir = typ == "5", + uid = h.uid, + gid = h.gid, + nlink = h.nlink, + mtime = h.mtime, + ino = h.ino, + devmajor = h.devmajor, + devminor = h.devminor, + rdevmajor = h.rdevmajor, + rdevminor = h.rdevminor, + link = if typ == "2" then buffer.readstring(b, data, h.size) else nil, + hardlink = nil, + offset = data, + check = if fmt == "crc" then h.check else nil, + } + if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then + return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data) + end + if typ == "0" and h.nlink > 1 then + local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino + local g = groups[key] + if not g then + g = {} + groups[key] = g + else + entry.hardlink = g[1].name + end + table.insert(g, entry) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + p = data + h.size + p = o + (p - o + align - 1) // align * align + end + -- hard links: the links stored without data read the group's data (newc / crc keep it on the last link) + for _, g in groups do + local holder: Entry? = nil + for _, x in g do + if x.size > 0 then + holder = x + end + end + if holder then + for _, x in g do + if x.size == 0 then + x.size, x.offset = holder.size, holder.offset + end + end + end + end + return out, { format = fmt } +end + +-- ------------------------------------------------------------------------------------------------ writing +type WriteEntry = { + name: string, + data: buffer?, -- file data (a symlink: its target, else taken from link) + mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755) + type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir) + dir: boolean?, + link: string?, -- symlink target + uid: number?, + gid: number?, + nlink: number?, -- default 1 (2 for directories) + mtime: number?, -- unix seconds (default 0) + ino: number?, -- default: the entry's index (1, 2, ...); hard links share one + devmajor: number?, + devminor: number?, + rdevmajor: number?, + rdevminor: number?, +} +type WriteOptions = { + format: ("newc" | "crc" | "odc")?, -- default "newc" + block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding) +} + +local function hex8(v: number): string? + if v < 0 or v % 1 ~= 0 or v >= 4294967296 then + return nil + end + return string.format("%08X", v) +end + +local function oct(v: number, w: number): string? + if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then + return nil + end + local s = string.format("%o", v) + return string.rep("0", w - #s) .. s +end + +-- write(entries, opts?) -> buffer | nil, Err +function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) + local fmt = (opts and opts.format) or "newc" + if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then + return nil, Err.new(Err.ARG, "format must be newc, crc or odc") + end + local block = (opts and opts.block) or 512 + if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then + return nil, Err.new(Err.ARG, "block must be a positive integer") + end + -- newc / crc: a hard link group's data goes on its last link only + local last: { [string]: number } = {} + local prepared: { any } = table.create(#entries) + for i, e in entries do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local typ = e.type or (if e.dir then "5" else "0") + local tbits = MODES[typ] + if not tbits then + return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ)) + end + local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4) + if bit32.band(mode, S_IFMT) == 0 then + mode = bit32.bor(mode, tbits) + end + local data = e.data + if typ == "2" and not data then + data = buffer.fromstring(e.link or "") + elseif typ ~= "0" and typ ~= "2" then + data = nil + end + local nlink = e.nlink or (if typ == "5" then 2 else 1) + local ino = e.ino or i + local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ } + prepared[i] = p + if typ == "0" and nlink > 1 then + last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i + end + end + local w = Bytes.writer(1024) + local function put(name: string, p: any, data: buffer): Err.Err? + local e = p.e + local namesize = #name + 1 + local size = buffer.len(data) + if fmt == "odc" then + local dev = (e.devmajor or 0) * 256 + (e.devminor or 0) + local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0) + local fields = { + oct(dev, 6), + oct(p.ino, 6), + oct(p.mode, 6), + oct(e.uid or 0, 6), + oct(e.gid or 0, 6), + oct(p.nlink, 6), + oct(rdev, 6), + oct(math.floor(e.mtime or 0), 11), + oct(namesize, 6), + oct(size, 11), + } + for k = 1, 10 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header") + end + end + w:string("070707" .. table.concat(fields :: { string })) + w:string(name) + w:u8(0) + w:bytes(data) + else + local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0 + local fields = { + hex8(p.ino), + hex8(p.mode), + hex8(e.uid or 0), + hex8(e.gid or 0), + hex8(p.nlink), + hex8(math.floor(e.mtime or 0)), + hex8(size), + hex8(e.devmajor or 0), + hex8(e.devminor or 0), + hex8(e.rdevmajor or 0), + hex8(e.rdevminor or 0), + hex8(namesize), + hex8(check), + } + for k = 1, 13 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header") + end + end + w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string })) + w:string(name) + w:u8(0) + w:fill(0, (4 - (110 + namesize) % 4) % 4) + w:bytes(data) + w:fill(0, (4 - size % 4) % 4) + end + return nil + end + for i, p in prepared do + local data = p.data + if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then + local e = p.e + if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then + data = buffer.create(0) + end + end + local err = put(p.e.name, p, data) + if err then + return nil, err + end + end + local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0)) + if err then + return nil, err + end + w:fill(0, (block - w.pos % block) % block) + return w:finish(), nil +end + +return Cpio +end +__FILES["containers/Demux"] = function() + +-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). +-- New in rosetta. A container parses its file once into an index of packets (track, pts, dts, duration, +-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives +-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file +-- independently), a file-order cursor, keyframe seeking, packet copies on demand. +-- +-- local d = Demux.new("mkv", tracks, src, meta) +-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order +-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src +-- d:finish() -- durations, per-track indexes +-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +local Types = __include("Types") + +local Demux = {} +local D = {} +D.__index = D + +type Demux = typeof(setmetatable( + {} :: { + kind: "demuxer", + format: string, + tracks: { Types.Track }, + duration: number, + startTime: number, + meta: { [string]: any }, + src: buffer, + n: number, + tr: { number }, + pts: { number }, + dts: { number }, + dur: { number }, + key: { boolean }, + off: { number }, + len: { number }, + data: { [number]: buffer }, + extra: { [number]: { [string]: any } }, + byTrack: { [number]: { number } }, + cur: { [number]: number }, + gcur: number, + }, + D +)) + +-- new(format, tracks, src, meta?) -> an empty index +function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: { [string]: any }?): Demux + return setmetatable({ + kind = "demuxer" :: "demuxer", + format = format, + tracks = tracks, + duration = 0, + startTime = 0, + meta = meta or {}, + src = src, + n = 0, + tr = {}, + pts = {}, + dts = {}, + dur = {}, + key = {}, + off = {}, + len = {}, + data = {}, + extra = {}, + byTrack = {}, + cur = {}, + gcur = 1, + }, D) +end + +-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) +function D.add(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, offset: number, length: number) + local i = self.n + 1 + self.n = i + self.tr[i] = track + self.pts[i] = pts + self.dts[i] = dts or pts + self.dur[i] = duration or 0 + self.key[i] = keyframe + self.off[i] = offset + self.len[i] = length +end + +-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes +function D.addData(self: Demux, track: number, pts: number, dts: number?, duration: number?, keyframe: boolean, data: buffer) + self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) + self.data[self.n] = data +end + +-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) +function D.setExtra(self: Demux, key: string, value: any) + local e = self.extra[self.n] + if not e then + e = {} + self.extra[self.n] = e + end + e[key] = value +end + +-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's +-- frame rate), and the track / file durations (seconds) where the container gave none +function D.finish(self: Demux) + local byTrack: { [number]: { number } } = {} + for _, t in self.tracks do + byTrack[t.id] = {} + end + for i = 1, self.n do + local list = byTrack[self.tr[i]] + if list then + table.insert(list, i) + end + end + self.byTrack = byTrack + local total = self.duration + local start = math.huge + for _, t in self.tracks do + local list = byTrack[t.id] + local scale = if t.timescale and t.timescale > 0 then t.timescale else 1 + t.timescale = scale + local frameTicks = if t.frameRate and t.frameRate > 0 then scale / t.frameRate else 0 + -- durations from the next packet in presentation order + if #list > 0 then + local order = table.clone(list) + table.sort(order, function(a: number, b: number): boolean + return self.pts[a] < self.pts[b] + end) + for k = 1, #order do + local i = order[k] + if self.dur[i] <= 0 then + local nx = order[k + 1] + if nx and self.pts[nx] > self.pts[i] then + self.dur[i] = self.pts[nx] - self.pts[i] + elseif frameTicks > 0 then + self.dur[i] = frameTicks + elseif k > 1 then + self.dur[i] = self.dur[order[k - 1]] + end + end + end + local first, last = order[1], order[#order] + if t.kind == "video" or t.kind == "audio" then + start = math.min(start, self.pts[first] / scale) + end + local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale + if not t.duration or t.duration <= 0 then + t.duration = d + end + t.frames = t.frames or #list + end + if t.duration and t.duration > total then + total = t.duration + end + self.cur[t.id] = 1 + end + self.duration = total + -- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count + -- frame times from it + self.startTime = if start ~= math.huge and start > 0 then start else 0 +end + +-- the Packet for index entry i (a copy of its bytes) +function D._packet(self: Demux, i: number): Types.Packet + local data = self.data[i] + if not data then + local o, l = self.off[i], self.len[i] + local src = self.src + local n = buffer.len(src) + if o < 0 or o > n then + o, l = n, 0 + elseif o + l > n then + l = n - o + end + data = buffer.create(l) + buffer.copy(data, 0, src, o, l) + end + local p: any = { + track = self.tr[i], + pts = self.pts[i], + dts = self.dts[i], + duration = self.dur[i], + keyframe = self.key[i], + data = data :: buffer, + } + local e = self.extra[i] + if e then + for k, v in e do + p[k] = v + end + end + return p +end + +-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end +function D.read(self: Demux, track: number?): Types.Packet? + if track == nil then + local i = self.gcur + if i > self.n then + return nil + end + self.gcur = i + 1 + return self:_packet(i) + end + local list = self.byTrack[track] + if not list then + return nil + end + local c = self.cur[track] or 1 + local i = list[c] + if not i then + return nil + end + self.cur[track] = c + 1 + return self:_packet(i) +end + +-- packets(track?) -> an iterator of Packets from the current position (advancing it) +function D.packets(self: Demux, track: number?): () -> Types.Packet? + return function(): Types.Packet? + return self:read(track) + end +end + +-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors +function D.count(self: Demux, track: number): number + local list = self.byTrack[track] + return if list then #list else 0 +end +function D.get(self: Demux, track: number, k: number): Types.Packet? + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self:_packet(i) +end + +-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) +function D.info(self: Demux, track: number, k: number): (number?, number?, number?, boolean?, number?) + local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil, nil, nil, nil, nil + end + return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] +end + +-- rewind(track?): a track's cursor (or every cursor) back to the start +function D.rewind(self: Demux, track: number?) + if track then + self.cur[track] = 1 + return + end + for id in self.cur do + self.cur[id] = 1 + end + self.gcur = 1 +end + +-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) +function D.seek(self: Demux, seconds: number) + local g = self.n + 1 + for _, t in self.tracks do + local list = self.byTrack[t.id] + if list and #list > 0 then + local target = seconds * t.timescale + local best = 1 + for k = 1, #list do + local i = list[k] + if self.key[i] and self.pts[i] <= target + 1e-6 then + best = k + end + end + self.cur[t.id] = best + if list[best] < g then + g = list[best] + end + end + end + self.gcur = if g > self.n then 1 else g +end + +-- track(kind) -> the first default track of the kind, else the first of the kind +function D.track(self: Demux, kind: string): Types.Track? + local first = nil + for _, t in self.tracks do + if t.kind == kind then + if t.default then + return t + end + first = first or t + end + end + return first +end + +return Demux +end +__FILES["containers/Ebml"] = function() + +-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in rosetta. +-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it; +-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, +-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and +-- minimal-length value elements. +-- +-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated +-- for id, off, size in Ebml.children(buf, off, limit) do ... end +-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() +-- +-- Never throws: malformed input gives nil (readers) or stops iteration. +local Bytes = __include("core/Bytes") + +local readu8 = buffer.readu8 + +local Ebml = {} + +Ebml.UNKNOWN = -1 + +-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. +function Ebml.vint(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + if b == 0 then + return nil, nil + end + local len = 1 + local mask = 0x80 + while bit32.band(b, mask) == 0 do + len += 1 + mask = mask // 2 + end + if pos + len > limit then + return nil, nil + end + local v = bit32.band(b, mask - 1) + local allOnes = v == mask - 1 + for i = 1, len - 1 do + local c = readu8(buf, pos + i) + v = v * 256 + c + if c ~= 255 then + allOnes = false + end + end + if allOnes then + return -1, len + end + return v, len +end + +-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil +function Ebml.svint(buf: buffer, pos: number, limit: number): (number?, number?) + local v, len = Ebml.vint(buf, pos, limit) + if v == nil or len == nil then + return nil, nil + end + if v == -1 then + return nil, nil + end + return v - (2 ^ (7 * len - 1) - 1), len +end + +-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) +function Ebml.id(buf: buffer, pos: number, limit: number): (number?, number?) + if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + local len = if b >= 0x80 then 1 elseif b >= 0x40 then 2 elseif b >= 0x20 then 3 elseif b >= 0x10 then 4 else 0 + if len == 0 or pos + len > limit then + return nil, nil + end + local v = b + for i = 1, len - 1 do + v = v * 256 + readu8(buf, pos + i) + end + return v, len +end + +-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil +function Ebml.header(buf: buffer, pos: number, limit: number): (number?, number?, number?) + local id, il = Ebml.id(buf, pos, limit) + if not id or not il then + return nil, nil, nil + end + local size, sl = Ebml.vint(buf, pos + il, limit) + if not size or not sl then + return nil, nil, nil + end + return id, size, pos + il + sl +end + +-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the +-- limit is clipped; a malformed header ends the iteration) +function Ebml.children(buf: buffer, off: number, limit: number): () -> (number?, number, number) + local pos = off + return function(): (number?, number, number) + if pos >= limit then + return nil, 0, 0 + end + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + pos = limit + return nil, 0, 0 + end + if size < 0 or data + size > limit then + size = limit - data + end + pos = data + size + return id, data, size + end +end + +-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) +function Ebml.uint(buf: buffer, off: number, len: number): number + local v = 0 + for i = 0, math.min(len, 8) - 1 do + v = v * 256 + readu8(buf, off + i) + end + return v +end +function Ebml.int(buf: buffer, off: number, len: number): number + if len <= 0 then + return 0 + end + local v = Ebml.uint(buf, off, len) + local n = math.min(len, 8) + if readu8(buf, off) >= 0x80 then + v -= 2 ^ (8 * n) + end + return v +end +function Ebml.float(buf: buffer, off: number, len: number): number + local r = Bytes.reader(buf, off, len) + if len == 4 then + return r:f32be() + elseif len == 8 then + return r:f64be() + end + return 0 +end +function Ebml.string(buf: buffer, off: number, len: number): string + local s = buffer.readstring(buf, off, len) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + return s +end +function Ebml.binary(buf: buffer, off: number, len: number): buffer + local b = buffer.create(len) + buffer.copy(b, 0, buf, off, len) + return b +end + +-- ------------------------------------------------------------------------------------------------ writing +local W = {} +W.__index = W + +type Writer = typeof(setmetatable({} :: { w: Bytes.Writer }, W)) + +-- writer(capacity?) -> an EBML byte builder +function Ebml.writer(capacity: number?): Writer + return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) +end + +-- idBytes(id) -> the ID's bytes as written +local function writeId(w: Bytes.Writer, id: number) + if id >= 0x1000000 then + w:u32be(id) + elseif id >= 0x10000 then + w:u24be(id) + elseif id >= 0x100 then + w:u16be(id) + else + w:u8(id) + end +end + +-- size as a minimal vint (n bytes: force a length) +local function writeSize(w: Bytes.Writer, size: number, n: number?) + local len = n or 1 + if not n then + while size >= 2 ^ (7 * len) - 1 do + len += 1 + end + end + local v = size + 2 ^ (7 * len) -- the marker bit + local bytes = table.create(len, 0) + for i = len, 1, -1 do + bytes[i] = v % 256 + v = v // 256 + end + for i = 1, len do + w:u8(bytes[i]) + end +end +Ebml.writeSize = writeSize + +-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) +function Ebml.vintString(v: number, n: number?): string + local w = Bytes.writer(8) + writeSize(w, v, n) + return buffer.readstring(w:finish(), 0, w:tell()) +end + +function W.tell(self: Writer): number + return self.w:tell() +end + +-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder +function W.open(self: Writer, id: number): number + writeId(self.w, id) + local at = self.w:tell() + for _ = 1, 8 do + self.w:u8(0) + end + return at +end + +-- close(handle): patches the size of the element opened at handle +function W.close(self: Writer, at: number) + local w = self.w + local v = w:tell() - at - 8 + w:setU8(at, 0x01) + for i = 7, 1, -1 do + w:setU8(at + i, v % 256) + v = v // 256 + end +end + +-- unknownSize(id): a master element with an unknown size (live streams) +function W.openUnknown(self: Writer, id: number) + writeId(self.w, id) + self.w:u8(0x01) + for _ = 1, 7 do + self.w:u8(0xFF) + end +end + +function W.uint(self: Writer, id: number, v: number) + local n = 1 + while v >= 2 ^ (8 * n) and n < 8 do + n += 1 + end + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + local x = v + for i = n, 1, -1 do + bytes[i] = x % 256 + x = x // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.int(self: Writer, id: number, v: number) + local n = 1 + while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do + n += 1 + end + local u = if v < 0 then v + 2 ^ (8 * n) else v + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + for i = n, 1, -1 do + bytes[i] = u % 256 + u = u // 256 + end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.float(self: Writer, id: number, v: number) + writeId(self.w, id) + writeSize(self.w, 8) + self.w:f64be(v) +end + +function W.string(self: Writer, id: number, s: string) + writeId(self.w, id) + writeSize(self.w, #s) + self.w:string(s) +end + +-- binary(id, buf, off?, len?) +function W.binary(self: Writer, id: number, b: buffer, off: number?, len: number?) + local o = off or 0 + local n = len or (buffer.len(b) - o) + writeId(self.w, id) + writeSize(self.w, n) + self.w:bytes(b, o, n) +end + +-- raw bytes (a pre-built element, block headers) +function W.raw(self: Writer, s: string) + self.w:string(s) +end +function W.rawBuffer(self: Writer, b: buffer, off: number?, len: number?) + local o = off or 0 + self.w:bytes(b, o, len or (buffer.len(b) - o)) +end +-- element header for a binary element whose payload follows in pieces: id + size +function W.header(self: Writer, id: number, size: number) + writeId(self.w, id) + writeSize(self.w, size) +end + +-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space +function W.void(self: Writer, n: number) + self.w:u8(0xEC) + if n - 2 < 127 then + writeSize(self.w, n - 2, 1) + for _ = 1, n - 2 do + self.w:u8(0) + end + else + writeSize(self.w, n - 9, 8) + for _ = 1, n - 9 do + self.w:u8(0) + end + end +end + +function W.finish(self: Writer): buffer + return self.w:finish() +end + +return Ebml +end +__FILES["containers/Fat"] = function() + +-- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories +-- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names, +-- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images +-- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from +-- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout. +-- +-- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message +-- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/") +-- local data, err = Fat.read(vol, entry) -- buffer | nil, message +-- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image +-- +-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by +-- the cluster count (loops are errors). +local Archive = __include("containers/Archive") + +local Fat = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +type Volume = { + b: buffer, + base: number, -- byte offset of the volume (partition) in b + limit: number, + bps: number, -- bytes per sector + spc: number, -- sectors per cluster + fatOffset: number, -- byte offset of the first FAT (relative to base) + fatSize: number, -- bytes per FAT + rootOffset: number, -- FAT12 / 16: the fixed root directory + rootEntries: number, + rootCluster: number, -- FAT32 + dataOffset: number, -- byte offset of cluster 2 + clusters: number, -- data clusters + bits: number, -- 12 / 16 / 32 + label: string?, + oem: string, + media: number, + partition: number?, +} + +type Entry = { + name: string, + dir: boolean, + size: number, + mtime: number?, + cluster: number, + attr: number, + shortName: string, +} + +-- ------------------------------------------------------------------------------------------------ open +local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + local jump = readu8(b, o) + local bps = readu16(b, o + 11) + local spc = readu8(b, o + 13) + if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then + return nil, "no FAT boot sector" + end + if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then + return nil, "bad sectors per cluster" + end + local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17) + local total = readu16(b, o + 19) + if total == 0 then + total = readu32(b, o + 32) + end + local fatSectors = readu16(b, o + 22) + local fat32 = fatSectors == 0 + if fat32 then + fatSectors = readu32(b, o + 36) + end + if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then + return nil, "bad BPB" + end + local rootSectors = math.ceil(rootEntries * 32 / bps) + local dataSector = reserved + nfats * fatSectors + rootSectors + if dataSector >= total then + return nil, "bad BPB: no data area" + end + local clusters = (total - dataSector) // spc + local bits = if clusters < 4085 then 12 elseif clusters < 65525 then 16 else 32 + if fat32 and bits ~= 32 then + bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count + end + if total * bps > len then + -- images cut short at the last used sector are common: allow, reads past the end fail + total = len // bps + end + local labelAt = if bits == 32 then 71 else 43 + local sig = readu8(b, o + (if bits == 32 then 66 else 38)) + local label: string? = if sig == 0x29 then (string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) else nil + if label == "NO NAME" or label == "" then + label = nil + end + return { + b = b, + base = o, + limit = o + len, + bps = bps, + spc = spc, + fatOffset = reserved * bps, + fatSize = fatSectors * bps, + rootOffset = (reserved + nfats * fatSectors) * bps, + rootEntries = rootEntries, + rootCluster = if bits == 32 then readu32(b, o + 44) else 0, + dataOffset = dataSector * bps, + clusters = clusters, + bits = bits, + label = label, + oem = buffer.readstring(b, o + 3, 8), + media = readu8(b, o + 21), + }, nil +end + +type OpenOptions = { partition: number? } -- 1..4: the MBR partition (default: the first FAT one) + +local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true } + +function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Volume?, string?) + local o: OpenOptions = opts or {} + off = math.max(0, off) + len = math.min(len, buffer.len(b) - off) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + if not o.partition then + local v = bpbAt(b, off, len) + if v then + return v, nil + end + end + -- an MBR: 0x55AA and four partition entries + if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then + return nil, "no FAT boot sector and no partition table" + end + for i = 1, 4 do + local e = off + 446 + (i - 1) * 16 + local ptype = readu8(b, e + 4) + local lba, count = readu32(b, e + 8), readu32(b, e + 12) + if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then + if lba * 512 >= len then + return nil, "truncated: partition " .. i .. " starts past the end" + end + local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512)) + if v then + v.partition = i + end + return v, err + end + end + return nil, if o.partition then "no partition " .. o.partition else "no FAT partition" +end + +-- ------------------------------------------------------------------------------------------------ chains +local function nextCluster(v: Volume, c: number): number + local f = v.base + v.fatOffset + if v.bits == 12 then + local p = f + c + c // 2 + if p + 1 >= v.limit then + return 0xFFFFFFF + end + local w = readu16(v.b, p) + local n = if c % 2 == 0 then bit32.band(w, 0xFFF) else bit32.rshift(w, 4) + return if n >= 0xFF8 then 0xFFFFFFF elseif n == 0xFF7 then 0xFFFFFF7 else n + elseif v.bits == 16 then + local p = f + c * 2 + if p + 2 > v.limit then + return 0xFFFFFFF + end + local n = readu16(v.b, p) + return if n >= 0xFFF8 then 0xFFFFFFF elseif n == 0xFFF7 then 0xFFFFFF7 else n + end + local p = f + c * 4 + if p + 4 > v.limit then + return 0xFFFFFFF + end + return bit32.band(readu32(v.b, p), 0x0FFFFFFF) +end + +-- the clusters of a chain (nil, message when it leaves the volume or loops) +local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?) + local out = {} + local c = first + while c >= 2 and c < 0xFFFFFF7 do + if c >= v.clusters + 2 then + return nil, "cluster " .. c .. " outside the volume" + end + table.insert(out, c) + if #out > maxClusters then + return nil, "cluster chain loops" + end + c = nextCluster(v, c) + end + if c == 0xFFFFFF7 then + return nil, "bad cluster in a chain" + end + return out, nil +end + +local function clusterOffset(v: Volume, c: number): number + return v.base + v.dataOffset + (c - 2) * v.spc * v.bps +end + +-- the bytes of a chain, up to size bytes (nil = the whole chain) +local function readChain(v: Volume, first: number, size: number?): (buffer?, string?) + local csize = v.spc * v.bps + local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters + local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1)) + if not list then + return nil, err + end + local total = if size then size else #list * csize + if #list * csize < total then + return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)" + end + local out = buffer.create(total) + local o = 0 + for _, c in list do + local n = math.min(csize, total - o) + if n <= 0 then + break + end + local at = clusterOffset(v, c) + if at + n > v.limit then + return nil, "truncated: cluster " .. c .. " past the end of the image" + end + buffer.copy(out, o, v.b, at, n) + o += n + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ directories +local function latin1(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +local function shortChecksum(raw: string): number + local sum = 0 + for i = 1, 11 do + sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256 + end + return sum +end + +local function ucs2(b: buffer, o: number, n: number, out: { number }) + for k = 0, n - 1 do + table.insert(out, readu16(b, o + k * 2)) + end +end + +-- the entries of one directory's bytes +local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry } + local lfn: { [number]: { number } } = {} + local lfnSum, lfnCount = -1, 0 + local subdirs = {} + for p = 0, buffer.len(d) - 32, 32 do + local first = readu8(d, p) + if first == 0 then + break + end + local attr = readu8(d, p + 11) + if first == 0xE5 then + lfn, lfnSum, lfnCount = {}, -1, 0 + elseif attr == 0x0F then + local seq = bit32.band(first, 0x3F) + if bit32.band(first, 0x40) ~= 0 then + lfn, lfnCount = {}, seq + lfnSum = readu8(d, p + 13) + end + if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then + local chars = {} + ucs2(d, p + 1, 5, chars) + ucs2(d, p + 14, 6, chars) + ucs2(d, p + 28, 2, chars) + lfn[seq] = chars + end + else + local raw = buffer.readstring(d, p, 11) + if first == 0x05 then + raw = "\229" .. string.sub(raw, 2) + end + local long: string? = nil + if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then + local cps = {} + local complete = true + for s = 1, lfnCount do + if not lfn[s] then + complete = false + break + end + for _, c in lfn[s] do + if c == 0 or c == 0xFFFF then + break + end + table.insert(cps, c) + end + end + if complete then + local parts = table.create(#cps) + for i, c in cps do + parts[i] = utf8.char(if c >= 0xD800 and c < 0xE000 then 0xFFFD else c) + end + long = table.concat(parts) + end + end + lfn, lfnSum, lfnCount = {}, -1, 0 + local nt = readu8(d, p + 12) + local base = string.gsub(string.sub(raw, 1, 8), " +$", "") + local ext = string.gsub(string.sub(raw, 9, 11), " +$", "") + if bit32.band(nt, 0x08) ~= 0 then + base = string.lower(base) + end + if bit32.band(nt, 0x10) ~= 0 then + ext = string.lower(ext) + end + local short = latin1(if ext ~= "" then base .. "." .. ext else base) + local isDir = bit32.band(attr, 0x10) ~= 0 + local isLabel = bit32.band(attr, 0x08) ~= 0 + if not isLabel and short ~= "." and short ~= ".." then + local name = prefix .. (long or short) + local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536 + local e: Entry = { + name = if isDir then name .. "/" else name, + dir = isDir, + size = if isDir then 0 else readu32(d, p + 28), + mtime = Archive.fromDos(readu16(d, p + 24) * 65536 + readu16(d, p + 22)), + cluster = cluster, + attr = attr, + shortName = short, + } + table.insert(out, e) + if isDir then + table.insert(subdirs, e) + end + end + end + end + return subdirs +end + +-- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents) +function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?) + local out: { Entry } = {} + local limit = maxEntries or 65536 + local root: buffer?, err: string? + if v.bits == 32 then + root, err = readChain(v, v.rootCluster, nil) + else + local n = v.rootEntries * 32 + if v.base + v.rootOffset + n > v.limit then + return nil, "truncated: root directory past the end" + end + root = buffer.create(n) + buffer.copy(root :: buffer, 0, v.b, v.base + v.rootOffset, n) + end + if not root then + return nil, err + end + local seen: { [number]: boolean } = {} + local function walk(d: buffer, prefix: string, depth: number): string? + if depth > 64 then + return "directories nested too deep" + end + local start = #out + local subdirs = parseDir(d, prefix, out) + if #out > limit then + return "limit: more than maxEntries entries" + end + local _ = start + for _, s in subdirs do + if s.cluster >= 2 then + if seen[s.cluster] then + return "directory loop at cluster " .. s.cluster + end + seen[s.cluster] = true + local sd, serr = readChain(v, s.cluster, nil) + if not sd then + return s.name .. ": " .. tostring(serr) + end + local werr = walk(sd, s.name, depth + 1) + if werr then + return werr + end + end + end + return nil + end + local werr = walk(root :: buffer, "", 0) + if werr then + return nil, werr + end + return out, nil +end + +-- read(vol, entry) -> the file's bytes +function Fat.read(v: Volume, e: Entry): (buffer?, string?) + if e.dir or e.size == 0 then + return buffer.create(0), nil + end + if e.cluster < 2 then + return nil, "file without clusters" + end + return readChain(v, e.cluster, e.size) +end + +-- ------------------------------------------------------------------------------------------------ write +type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? } +type WriteOptions = { + size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440) + label: string?, -- volume label (default none) + serial: number?, -- volume serial number (default 0x12345678) +} + +local GEOMETRY = { + [360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 }, + [720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 }, + [1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 }, + [1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 }, + [2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 }, +} + +local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$" + +local function toDos(t: number?): (number, number) + local v = Archive.toDos(t) + return v // 65536, v % 65536 +end + +type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number } + +-- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed +local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean) + local base, ext = string.match(name, "^(.*)%.([^%.]*)$") + if not base or base == "" then + base, ext = name, "" + end + local b, e = base :: string, ext :: string + -- a plain 8.3 name, all upper or all lower case per part: no long name needed + if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then + local bu, eu = string.upper(b), string.upper(e) + local nt = 0 + local ok = true + if b ~= bu then + if b == string.lower(b) then + nt = bit32.bor(nt, 0x08) + else + ok = false + end + end + if e ~= eu then + if e == string.lower(e) then + nt = bit32.bor(nt, 0x10) + else + ok = false + end + end + local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu) + if ok and not used[raw] then + used[raw] = true + return raw, nt, false + end + end + local function clean(s: string): string + s = string.upper((string.gsub(s, "[%s%.]", ""))) + return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_")) + end + local cb, ce = clean(b), string.sub(clean(e), 1, 3) + if cb == "" then + cb = "_" + end + for n = 1, 999999 do + local tail = "~" .. n + local raw = string.sub(cb, 1, 8 - #tail) .. tail + raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce) + if not used[raw] then + used[raw] = true + return raw, 0, true + end + end + return " ___", 0, true +end + +-- the directory entries (32 bytes each) of a node's children +local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer + local w = {} + local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?) + local e = buffer.create(32) + buffer.writestring(e, 0, raw) + buffer.writeu8(e, 11, attr) + buffer.writeu8(e, 12, nt) + local date, time = toDos(mtime) + buffer.writeu16(e, 14, time) + buffer.writeu16(e, 16, date) + buffer.writeu16(e, 18, date) + buffer.writeu16(e, 22, time) + buffer.writeu16(e, 24, date) + buffer.writeu16(e, 26, cluster) + buffer.writeu32(e, 28, size) + table.insert(w, e) + end + if isRoot and label then + local l = string.sub(string.upper(label), 1, 11) + entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime) + end + if not isRoot then + entry(". ", 0x10, 0, n.cluster, 0, n.mtime) + entry(".. ", 0x10, 0, parentCluster, 0, n.mtime) + end + local used: { [string]: boolean } = {} + for _, c in n.children do + local raw, nt, needLong = shortName(c.name, used) + if needLong then + local cps = {} + if utf8.len(c.name) then + for _, cp in utf8.codes(c.name) do + table.insert(cps, if cp > 0xFFFF then 0x5F else cp) + end + else + for i = 1, #c.name do + table.insert(cps, (string.byte(c.name, i))) + end + end + local count = math.ceil(#cps / 13) + local sum = shortChecksum(raw) + for s = count, 1, -1 do + local e = buffer.create(32) + buffer.writeu8(e, 0, if s == count then bit32.bor(s, 0x40) else s) + buffer.writeu8(e, 11, 0x0F) + buffer.writeu8(e, 13, sum) + local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 } + for k = 1, 13 do + local i = (s - 1) * 13 + k + local v = if i <= #cps then cps[i] elseif i == #cps + 1 then 0 else 0xFFFF + buffer.writeu16(e, slots[k], v) + end + table.insert(w, e) + end + end + entry(raw, if c.dir then 0x10 else 0x20, nt, c.cluster, if c.dir then 0 else buffer.len(c.data or buffer.create(0)), c.mtime) + end + local out = buffer.create(#w * 32) + for i, e in w do + buffer.copy(out, (i - 1) * 32, e) + end + return out +end + +-- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths) +function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?) + local o: WriteOptions = opts or {} + local g = GEOMETRY[o.size or 1440] + if not g then + return nil, "size must be 360, 720, 1200, 1440 or 2880" + end + local bps = 512 + local root: Node = { name = "", dir = true, children = {}, byName = {}, cluster = 0 } + local function node(path: string, isDir: boolean): (Node?, string?) + local cur = root + local parts = string.split(path, "/") + for i, p in parts do + if p ~= "" and p ~= "." then + if p == ".." then + return nil, "'..' in a path" + end + local last = i == #parts or (i == #parts - 1 and parts[#parts] == "") + local child: Node? = cur.byName[string.lower(p)] + if not child then + local nc: Node = { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 } + cur.byName[string.lower(p)] = nc + table.insert(cur.children, nc) + child = nc + elseif not child.dir and (not last or isDir) then + return nil, p .. " is both a file and a directory" + end + cur = child :: Node + end + end + return cur, nil + end + for _, f in files do + local n, err = node(f.name, f.dir == true) + if not n then + return nil, err + end + if n ~= root then + n.mtime = f.mtime + if not n.dir then + n.data = f.data or buffer.create(0) + end + end + end + local csize = g.spc * bps + local dataSector = 1 + 2 * g.fat + g.root * 32 // bps + local clusters = (g.sectors - dataSector) // g.spc + local img = buffer.create(g.sectors * bps) + local fat = buffer.create(g.fat * bps) + local nextFree = 2 + local function setFat(c: number, v: number) + local p = c + c // 2 + local w = buffer.readu16(fat, p) + if c % 2 == 0 then + w = bit32.bor(bit32.band(w, 0xF000), v) + else + w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4)) + end + buffer.writeu16(fat, p, w) + end + local function alloc(bytes: number): number? + local n = math.max(1, math.ceil(bytes / csize)) + if nextFree + n - 1 > clusters + 1 then + return nil + end + local first = nextFree + for k = 0, n - 1 do + setFat(first + k, if k == n - 1 then 0xFFF else first + k + 1) + end + nextFree += n + return first + end + -- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first + local function place(n: Node): string? + for _, c in n.children do + if c.dir then + local size = buffer.len(dirEntries(c, 0, false, nil)) + local cl = alloc(size) + if not cl then + return "disk full" + end + c.cluster = cl + local err = place(c) + if err then + return err + end + elseif c.data and buffer.len(c.data) > 0 then + local cl = alloc(buffer.len(c.data)) + if not cl then + return "disk full" + end + c.cluster = cl + local at = (dataSector + (cl - 2) * g.spc) * bps + buffer.copy(img, at, c.data) + end + end + return nil + end + local perr = place(root) + if perr then + return nil, "limit: " .. perr + end + local function writeDirs(n: Node, parent: number): string? + for _, c in n.children do + if c.dir then + local d = dirEntries(c, parent, false, nil) + buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d) + local err = writeDirs(c, c.cluster) + if err then + return err + end + end + end + return nil + end + writeDirs(root, 0) + local rootDir = dirEntries(root, 0, true, o.label) + if buffer.len(rootDir) > g.root * 32 then + return nil, "limit: too many entries in the root directory" + end + buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir) + setFat(0, 0xF00 + g.media) + setFat(1, 0xFFF) + buffer.copy(img, bps, fat) + buffer.copy(img, (1 + g.fat) * bps, fat) + -- boot sector + buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") + buffer.writeu16(img, 11, bps) + buffer.writeu8(img, 13, g.spc) + buffer.writeu16(img, 14, 1) + buffer.writeu8(img, 16, 2) + buffer.writeu16(img, 17, g.root) + buffer.writeu16(img, 19, g.sectors) + buffer.writeu8(img, 21, g.media) + buffer.writeu16(img, 22, g.fat) + buffer.writeu16(img, 24, g.spt) + buffer.writeu16(img, 26, g.heads) + buffer.writeu8(img, 36, 0) + buffer.writeu8(img, 38, 0x29) + buffer.writeu32(img, 39, o.serial or 0x12345678) + local label = string.upper(string.sub(o.label or "NO NAME", 1, 11)) + buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ") + buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code) + buffer.writeu8(img, 510, 0x55) + buffer.writeu8(img, 511, 0xAA) + return img, nil +end + +return Fat +end +__FILES["containers/Iso9660"] = function() + +-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary, +-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross +-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is +-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names +-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the +-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE +-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock +-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog +-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet +-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns +-- the stored bytes), UDF, writing. +-- +-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err +-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents) +local Err = __include("core/Err") +local Types = __include("Types") +local Text = __include("codecs/text/Text") + +local Iso9660 = {} + +type Extent = { at: number, size: number } -- byte offset (from the image start) and length +type Entry = { + name: string, -- the path, "/" separated, no leading "/" + dir: boolean, + size: number, + extents: { Extent }, + mtime: number?, -- unix seconds + type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket + mode: number?, -- Rock Ridge: the permission bits + uid: number?, + gid: number?, + nlink: number?, + link: string?, -- Rock Ridge symlink target + rdev: number?, -- Rock Ridge PN: high * 2^32 + low + hidden: boolean?, + interleaved: boolean?, + zisofs: boolean?, +} +type ReadOptions = { + prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain) + maxEntries: number?, -- default 1e6 +} + +local SECTOR = 2048 +local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" } + +-- ------------------------------------------------------------------------------------------------ fields +local function u16(b: buffer, o: number): number + return buffer.readu16(b, o) +end +local function u32(b: buffer, o: number): number + return buffer.readu32(b, o) +end +local function str(b: buffer, o: number, n: number): string + return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", "")) +end + +-- a 7-byte directory record date -> unix seconds +local function recDate(b: buffer, o: number): number? + local y = buffer.readu8(b, o) + local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2) + if m < 1 or m > 12 or d < 1 or d > 31 then + return nil + end + local off = buffer.readi8(b, o + 6) + return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 }) +end + +-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds +local function longDate(b: buffer, o: number): number? + local s = buffer.readstring(b, o, 16) + local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$") + if not y or tonumber(y) == 0 then + return nil + end + local off = buffer.readi8(b, o + 16) + return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 }) +end + +-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge +type Susp = { [string]: any } + +-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } } +local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } } + local out = {} + while o + 4 <= e do + local sig = buffer.readstring(b, o, 2) + local len = buffer.readu8(b, o + 2) + if len < 4 or o + len > e then + break + end + if sig == "ST" then + break + elseif sig == "CE" and len >= 28 then + local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20) + local at = base + blk * bs + off + budget[1] -= 1 + if budget[1] < 0 or at < base or at + n > limit or n > 65536 then + break + end + -- the rest of this area first, then the continuation (it holds what did not fit) + local rest = suspEntries(b, base, limit, o + len, e, bs, budget) + for _, x in rest do + table.insert(out, x) + end + local cont = suspEntries(b, base, limit, at, at + n, bs, budget) + for _, x in cont do + table.insert(out, x) + end + return out + end + table.insert(out, { sig, o, len }) + o += len + end + return out +end + +-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs } +local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp + local rr: Susp = {} + local name: { string }? = nil + local slParts: { string }? = nil + local slRoot = false + local slCont = false + for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do + local sig, at, len = x[1], x[2], x[3] + if sig == "NM" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + if bit32.band(flags, 6) == 0 then + name = name or {} + table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5)) + end + elseif sig == "PX" and len >= 36 then + rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28) + elseif sig == "PN" and len >= 20 then + rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12) + elseif sig == "TF" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7 + local q = at + 5 + for bit = 0, 6 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + if q + w > at + len then + break + end + if bit == 1 then + rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q) + end + q += w + end + end + elseif sig == "SL" and len >= 5 then + slParts = slParts or {} + local parts = slParts :: { string } + local q = at + 5 + while q + 2 <= at + len do + local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1) + if q + 2 + cl > at + len then + break + end + local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl) + if bit32.band(cf, 8) ~= 0 then + slRoot = #parts == 0 + piece = "" + end + if slCont and #parts > 0 then + parts[#parts] ..= piece + elseif bit32.band(cf, 8) == 0 or #parts > 0 then + table.insert(parts, piece) + end + slCont = bit32.band(cf, 1) ~= 0 + q += 2 + cl + end + elseif sig == "CL" and len >= 12 then + rr.child = u32(b, at + 4) + elseif sig == "RE" then + rr.relocated = true + elseif sig == "ZF" then + rr.zisofs = true + end + end + if name then + rr.name = table.concat(name) + end + if slParts then + rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/") + end + return rr +end + +-- ------------------------------------------------------------------------------------------------ directories +type Record = { + name: string, + dir: boolean, + lba: number, + size: number, + ear: number, + flags: number, + interleave: boolean, + mtime: number?, + rr: Susp?, +} + +-- the records of a directory extent (without "." and "..") | nil, Err +local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?) + if at + size > limit then + return nil, Err.new(Err.TRUNCATED, "directory past the end", at) + end + local out: { Record } = {} + local p = at + local e = at + size + while p < e do + local len = buffer.readu8(b, p) + if len == 0 then + p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding + continue + end + if len < 34 or p + len > e then + return nil, Err.new(Err.CORRUPT, "bad directory record", p) + end + local nl = buffer.readu8(b, p + 32) + if 33 + nl > len then + return nil, Err.new(Err.CORRUPT, "bad name length", p + 32) + end + local raw = buffer.readstring(b, p + 33, nl) + if raw ~= "\0" and raw ~= "\1" then + local flags = buffer.readu8(b, p + 25) + local name + if joliet then + name = Text.utf16(b, p + 33, nl, true) + else + name = raw + end + name = string.gsub(name, ";%d*$", "") + if not joliet and bit32.band(flags, 2) == 0 then + name = string.gsub(name, "%.$", "") + end + local r: Record = { + name = name, + dir = bit32.band(flags, 2) ~= 0, + lba = u32(b, p + 2), + size = u32(b, p + 10), + ear = buffer.readu8(b, p + 1), + flags = flags, + interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0, + mtime = recDate(b, p + 18), + rr = nil, + } + if rrSkip then + local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip + r.rr = rockRidge(b, base, limit, su, p + len, bs) + end + table.insert(out, r) + end + p += len + end + return out, nil +end + +-- the root record of a volume descriptor at vd -> lba, size +local function root(b: buffer, vd: number): (number, number) + return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10) +end + +-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length +local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number? + local p = base + lba * bs + if p + 34 > limit then + return nil + end + local len = buffer.readu8(b, p) + local nl = buffer.readu8(b, p + 32) + local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + if len < 34 or su + 7 > p + len or p + len > limit then + return nil + end + if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then + return buffer.readu8(b, su + 6) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ El Torito +local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }? + if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then + return nil + end + local cat = u32(b, vd + 0x47) + local p = base + cat * bs + local info: { [string]: any } = { catalog = cat } + if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then + return info + end + local sum = 0 + for i = 0, 30, 2 do + sum += u16(b, p + i) + end + info.valid = sum % 65536 == 0 + info.platform = buffer.readu8(b, p + 1) + info.id = str(b, p + 4, 24) + local d = p + 32 + info.bootable = buffer.readu8(b, d) == 0x88 + info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk + info.loadSegment = u16(b, d + 2) + info.systemType = buffer.readu8(b, d + 4) + info.sectors = u16(b, d + 6) -- 512-byte virtual sectors + info.lba = u32(b, d + 8) + return info +end + +-- ------------------------------------------------------------------------------------------------ read +-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err +function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any) + local base = offset or 0 + local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base))) + local o: ReadOptions = opts or {} + local maxEntries = o.maxEntries or 1e6 + local pvd: number? = nil + local svd: number? = nil + local jolietLevel: number? = nil + local bootInfo = nil + local p = base + 16 * SECTOR + for _ = 1, 64 do + if p + SECTOR > limit then + return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p) + end + if buffer.readstring(b, p + 1, 5) ~= "CD001" then + return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p) + end + local t = buffer.readu8(b, p) + if t == 255 then + break + elseif t == 1 and not pvd then + pvd = p + elseif t == 2 then + local esc = buffer.readstring(b, p + 88, 3) + if esc == "%/@" or esc == "%/C" or esc == "%/E" then + svd = p + jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3 + end + elseif t == 0 then + bootInfo = bootInfo or { vd = p } + end + p += SECTOR + end + if not pvd then + return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR) + end + local pv = pvd :: number + local bs = u16(b, pv + 128) + if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then + return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128) + end + local info: { [string]: any } = { + blockSize = bs, + blocks = u32(b, pv + 80), + systemId = str(b, pv + 8, 32), + volumeId = str(b, pv + 40, 32), + volumeSet = str(b, pv + 190, 128), + publisher = str(b, pv + 318, 128), + preparer = str(b, pv + 446, 128), + application = str(b, pv + 574, 128), + created = longDate(b, pv + 813), + modified = longDate(b, pv + 830), + joliet = jolietLevel, + } + if bootInfo then + info.boot = boot(b, base, limit, bootInfo.vd, bs) + end + local rlba, rsize = root(b, pv) + local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs) + info.rockRidge = rrSkip ~= nil + local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660") + if tree == "joliet" and not svd then + tree = "iso9660" + elseif tree == "rockridge" and not rrSkip then + tree = "iso9660" + end + info.tree = tree + local joliet = tree == "joliet" + local useRR = if tree == "rockridge" then rrSkip else nil + if joliet then + rlba, rsize = root(b, svd :: number) + end + if tree == "joliet" then + info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", "")) + end + local out: { Entry } = {} + local visited: { [number]: boolean } = {} + local stack = { { lba = rlba, size = rsize, path = "" } } + local relocatedDirs: { [string]: boolean } = {} + while #stack > 0 do + local d = table.remove(stack) :: any + if visited[d.lba] then + continue + end + visited[d.lba] = true + local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR) + if not list then + return nil, err + end + local i = 1 + local subdirs = {} + while i <= #list do + local r = list[i] + -- multi-extent: this record and the following ones of the same name + local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } } + local total = r.size + local last = r + while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do + i += 1 + last = list[i] + table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size }) + total += last.size + end + i += 1 + if bit32.band(r.flags, 4) ~= 0 then + continue -- an associated file (resource fork) + end + local rr: any = r.rr + if rr and rr.relocated then + continue -- shown where its CL placeholder is + end + local name = if rr and rr.name then rr.name else r.name + local path = d.path .. name + local isDir = r.dir + local lba: number, size: number = r.lba, r.size + if rr and rr.child then + -- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's + isDir = true + lba = rr.child + local q = base + lba * bs + size = if q + 14 <= limit then u32(b, q + 10) else 0 + end + local typ = if isDir then "5" else "0" + if rr and rr.mode then + typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ + end + local e: Entry = { + name = path, + dir = isDir, + size = if isDir or typ ~= "0" then 0 else total, + extents = if isDir or typ ~= "0" then {} else extents, + mtime = if rr and rr.mtime then rr.mtime else r.mtime, + type = typ, + mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil, + uid = rr and rr.uid, + gid = rr and rr.gid, + nlink = rr and rr.nlink, + link = if rr and typ == "2" then rr.link else nil, + rdev = rr and rr.rdev, + hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil, + interleaved = if r.interleave then true else nil, + zisofs = if rr and rr.zisofs then true else nil, + } + table.insert(out, e) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + if isDir then + table.insert(subdirs, { lba = lba, size = size, path = path .. "/" }) + end + end + for k = #subdirs, 1, -1 do + table.insert(stack, subdirs[k]) + end + if useRR then + for _, r in list do + if r.rr and r.rr.relocated then + relocatedDirs[d.path] = true + end + end + end + end + -- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it + if useRR then + for dirPath in relocatedDirs do + local name = string.sub(dirPath, 1, -2) + local holds = false + for _, e in out do + if string.sub(e.name, 1, #dirPath) == dirPath then + holds = true + break + end + end + if not holds then + for k, e in out do + if e.name == name then + table.remove(out, k) + break + end + end + end + end + end + -- archive order: depth-first walk order is kept; directories sorted as the image stores them + return out, info +end + +-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err +function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?) + if e.interleaved then + return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name) + end + local lim = limit or buffer.len(b) + local out = buffer.create(e.size) + local q = 0 + for _, x in e.extents do + if x.at < 0 or x.at + x.size > lim then + return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at) + end + buffer.copy(out, q, b, x.at, x.size) + q += x.size + end + return out, nil +end + +-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16 +function Iso9660.valid(b: buffer, offset: number?): boolean + local p = (offset or 0) + 16 * SECTOR + return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001" +end + +return Iso9660 +end +__FILES["containers/IsoBmff"] = function() + +-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) +-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, +-- mov, heif, avif build on it. Written from the specifications; no third-party code. +-- +-- local IsoBmff = require("@rosetta/containers/IsoBmff") +-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) +-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) +-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) +-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs +-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes +-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) +-- +-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit +-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', +-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), +-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local Demux = __include("containers/IsoBmff/Demux") +local Meta = __include("containers/IsoBmff/Meta") +local Mux = __include("containers/IsoBmff/Mux") + +local IsoBmff = {} +IsoBmff.Box = Box +IsoBmff.Demux = Demux +IsoBmff.Meta = Meta + +type Track = Demux.Track +type Movie = Demux.Movie +type Items = Meta.Items +type Item = Meta.Item +type MuxSpec = Mux.MuxSpec +type MuxTrack = Mux.MuxTrack +type Picture = Meta.Picture + +local TOP: { [string]: boolean } = { + ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true, + styp = true, sidx = true, meta = true, uuid = true, PICT = true, +} + +-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, +-- nil when it is not an ISO BMFF file +function IsoBmff.sniff(r: Bytes.Reader): string? + local head = r:peek(12) + if #head < 8 then + return nil + end + local typ = string.sub(head, 5, 8) + if typ == "ftyp" then + return if #head >= 12 then string.sub(head, 9, 12) else "" + end + if TOP[typ] then + local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4) + if size == 1 or size == 0 or size >= 8 then + return "" + end + end + return nil +end + +-- parse(r, opts?) -> Movie | nil, Err +function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?) + return Demux.parse(r, opts) +end + +-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) +function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture }) + local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") + return Meta.tags(r.buf, ilst) +end + +-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) +function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) + local meta = Box.path(movie.boxes, "meta") + if not meta then + return nil, Err.new(Err.CORRUPT, "no top-level meta box") + end + return Meta.items(r.buf, meta) +end + +-- itemData(r, items, id) -> buffer | nil, Err +function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?) + return Meta.itemData(r.buf, r.base, r.limit, items, id) +end + +-- sample(r, track, i) -> a copy of sample i (1-based) +function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? + if i < 1 or i > t.sampleCount then + return nil + end + local n = t.sizes[i] + local out = buffer.create(n) + buffer.copy(out, 0, r.buf, t.offsets[i], n) + return out +end + +-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / +-- dts / duration in their track's timescale ticks and a copy of the sample bytes. +function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) + local movie, err = Demux.parse(r, opts) + if not movie then + return nil, err + end + local cursor: { [number]: number } = {} + local byId: { [number]: Track } = {} + for _, t in movie.tracks do + cursor[t.id] = 1 + byId[t.id] = t + end + local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie } + local function packet(t: Track, i: number): any + local dts = t.dts[i] + local cts = t.cts + return { + track = t.id, + dts = dts, + pts = dts + (if cts then cts[i] or 0 else 0), + duration = t.durations[i], + keyframe = t.sync == nil or (t.sync :: any)[i] == true, + data = IsoBmff.sample(r, t, i), + index = i, + } + end + function dmx.packets(_self: any, trackId: number?): () -> any + return function(): any + if trackId then + local t = byId[trackId] + if not t then + return nil + end + local i = cursor[trackId] + if i > t.sampleCount then + return nil + end + cursor[trackId] = i + 1 + return packet(t, i) + end + -- all tracks in file order + local best: Track? = nil + local bestOff = math.huge + for _, t in movie.tracks do + local i = cursor[t.id] + if i <= t.sampleCount and t.offsets[i] < bestOff then + best, bestOff = t, t.offsets[i] + end + end + if not best then + return nil + end + local i = cursor[best.id] + cursor[best.id] = i + 1 + return packet(best, i) + end + end + -- seek(seconds): every track to its last sync sample at or before the time + function dmx.seek(_self: any, seconds: number) + for _, t in movie.tracks do + local target = seconds * t.timescale + local lo, hi = 1, t.sampleCount + local found = 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if t.sync then + while found > 1 and not (t.sync :: any)[found] do + found -= 1 + end + end + cursor[t.id] = found + end + end + return dmx, nil +end + +-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) +function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?) + return Mux.mux(spec) +end + +return IsoBmff +end +__FILES["containers/IsoBmff/Box"] = function() + +-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit +-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container +-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...). +-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws. +local Err = __include("core/Err") + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring +local byteswap = bit32.byteswap + +local Box = {} + +type Box = { + type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid` + start: number, -- absolute offset of the box in the buffer + size: number, -- the whole box, header included + data: number, -- absolute offset of the payload (after size / type / largesize / uuid) + stop: number, -- absolute offset just past the box (start + size, clamped to the parent) + uuid: string?, + children: { Box }?, -- container boxes + truncated: boolean?, -- the box claims more bytes than its parent has (clamped) +} + +-- plain container boxes: their payload is a list of boxes +local CONTAINERS = { + moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true, + mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true, + schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true, + strk = true, strd = true, grpl = true, meco = true, mere = true, +} +-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes +local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 } +Box.CONTAINERS = CONTAINERS + +local function be32(b: buffer, o: number): number + return byteswap(readu32(b, o)) +end +Box.be32 = be32 + +-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes +local function isIlstItem(parentType: string?): boolean + return parentType == "ilst" +end + +-- header(buf, p, limit) -> Box (without children) | nil, Err +function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) + end + local size = be32(b, p) + local typ = readstring(b, p + 4, 4) + local data = p + 8 + if size == 1 then + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p) + end + size = be32(b, p + 8) * 4294967296 + be32(b, p + 12) + data = p + 16 + elseif size == 0 then + size = limit - p + end + local uuid: string? = nil + if typ == "uuid" then + if data + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p) + end + uuid = readstring(b, data, 16) + data += 16 + end + if size < data - p then + return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p) + end + local stop = p + size + local truncated: boolean? = nil + if stop > limit then + stop = limit + truncated = true + end + return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil +end + +-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A +-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. +function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?) + local d = depth or 0 + local out: { Box } = {} + local firstErr: Err.Err? = nil + if d > 32 then + return out, Err.new(Err.CORRUPT, "boxes nested too deep", p) + end + while p + 8 <= limit do + local box, err = Box.header(b, p, limit) + if not box then + firstErr = firstErr or err + break + end + if box.truncated then + firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p) + end + local t = box.type + local kids: { Box }? = nil + local kerr: Err.Err? = nil + if CONTAINERS[t] or isIlstItem(parentType) then + kids, kerr = Box.list(b, box.data, box.stop, t, d + 1) + elseif FULL_CONTAINERS[t] then + local q = box.data + 4 + FULL_CONTAINERS[t] + -- QuickTime writes udta/meta as a plain container: its first child box follows directly + if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then + q = box.data + end + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + elseif t == "iinf" then + if box.data + 4 <= box.stop then + local v = readu8(b, box.data) + local q = box.data + 4 + (if v == 0 then 2 else 4) + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + end + end + box.children = kids + if kerr then + firstErr = firstErr or kerr + end + table.insert(out, box) + if box.stop <= p then + break + end + p = box.stop + end + return out, firstErr +end + +-- child(box, type) -> the first child of that type +function Box.child(box: Box?, typ: string): Box? + if not box or not box.children then + return nil + end + for _, c in box.children :: { Box } do + if c.type == typ then + return c + end + end + return nil +end + +-- children(box, type) -> every child of that type +function Box.childrenOf(box: Box?, typ: string): { Box } + local out = {} + if box and box.children then + for _, c in box.children :: { Box } do + if c.type == typ then + table.insert(out, c) + end + end + end + return out +end + +-- path(boxes or box, "moov/trak/mdia") -> the first box along the path +function Box.path(root: any, path: string): Box? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + if cur == nil then + return nil + end + local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur + local found = nil + if list then + for _, c in list do + if c.type == part then + found = c + break + end + end + end + cur = found + end + return cur +end + +-- version / flags of a full box +function Box.fullHeader(b: buffer, box: Box): (number, number) + if box.data + 4 > box.stop then + return -1, 0 + end + local v = be32(b, box.data) + return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF) +end + +return Box +end +__FILES["containers/IsoBmff/Demux"] = function() + +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): +-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration +-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / +-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). +-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the +-- reader's buffer. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local QtPalette = __include("containers/IsoBmff/QtPalette") + +local readstring = buffer.readstring + +local function readu16be(b: buffer, o: number): number + return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + +local Demux = {} + +type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) + +-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the +-- sample tables and the ISO facts +type Track = { + id: number, + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc + entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...) + handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...) + timescale: number, + duration: number, -- seconds (media duration; the edit list may shorten it) + mediaDuration: number, -- ticks + language: string?, -- ISO 639-2 ("und", "eng", ...) + width: number?, + height: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) + palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) + objectType: number?, -- esds objectTypeIndication + pcm: { bits: number, float: boolean, little: boolean }?, + entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) + edits: { Edit }?, + skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming) + delay: number, -- movie ticks of an initial empty edit + playDuration: number?, -- media ticks the edit list plays (nil: all) + -- samples + sampleCount: number, + offsets: { number }, -- absolute offsets in the buffer + sizes: { number }, + dts: { number }, -- decode times in ticks + durations: { number }, + cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets + sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample) + sampleDescription: { number }?, -- stsd index per sample when there are several entries + [string]: any, +} + +type Options = { maxSamples: number? } + +local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = { + soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle", + sbtl = "subtitle", clcp = "subtitle", +} +local CODEC: { [string]: string } = { + mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3", + lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm", + ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb", + avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9", + mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1", + ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text", +} +-- esds objectTypeIndication -> codec +local OTI: { [number]: string } = { + [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1", + [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3", + [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis", +} +-- the box holding each video / audio codec's configuration +local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" } +local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true } + +local function payload(b: buffer, box: Box.Box, skip: number?): buffer + local o = box.data + (skip or 0) + local n = math.max(0, box.stop - o) + local out = buffer.create(n) + if n > 0 then + buffer.copy(out, 0, b, o, n) + end + return out +end + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +-- expandable descriptor length (ISO 14496-1 8.3.3) +local function descLen(r: Bytes.Reader): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n +end + +-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate +function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) + local r = reader(b, box) + r:skip(4) -- version / flags + if r:u8() ~= 3 then + return nil, nil, nil + end + descLen(r) + r:skip(2) -- ES_ID + local flags = r:u8() + if bit32.band(flags, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(flags, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(flags, 0x20) ~= 0 then + r:skip(2) + end + if r:u8() ~= 4 then + return nil, nil, nil + end + local dlen = descLen(r) + local dstart = r.pos + local oti = r:u8() + r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate + local avg = r:u32be() + local dsi: buffer? = nil + if r.pos < dstart + dlen and r:u8() == 5 then + local n = descLen(r) + if n > 0 and r:need(n) then + dsi = r:bytes(n) + end + end + if r.err then + return oti, nil, nil + end + return oti, dsi, avg +end + +-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t +local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) + local r = reader(b, e) + r:skip(6) + r:skip(2) -- data reference index + local typ = e.type + t.entry = typ + t.codec = CODEC[typ] or typ + local kind = t.kind + local childStart + if kind == "audio" then + local version = r:u16be() + r:skip(2 + 4) -- revision, vendor + local channels = r:u16be() + local bits = r:u16be() + r:skip(4) -- compression id, packet size + local rate = r:u32be() / 65536 + if version == 1 then + r:skip(16) + elseif version == 2 then + r:skip(4) + rate = r:f64be() + channels = r:u32be() + r:skip(4) + bits = r:u32be() + local lpcmFlags = r:u32be() + r:skip(8) + if typ == "lpcm" then + t.pcm = { + bits = bits, + float = bit32.band(lpcmFlags, 1) ~= 0, + little = bit32.band(lpcmFlags, 2) == 0, + } + end + end + t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits + if not t.pcm and t.codec == "pcm" then + local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 } + t.pcm = { + bits = B[typ] or bits, + float = typ == "fl32" or typ == "fl64", + little = typ == "sowt", + } + end + childStart = r.pos + elseif kind == "video" then + r:skip(16) + t.width = r:u16be() + t.height = r:u16be() + r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) + childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end + else + childStart = r.pos + end + if r.err then + t.entryBoxes = {} + return + end + local kids = Box.list(b, childStart, e.stop, typ) + t.entryBoxes = kids + -- QuickTime puts the codec boxes inside 'wave' + local all = table.clone(kids) + local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave") + if wave and wave.children then + for _, c in wave.children :: { Box.Box } do + table.insert(all, c) + end + end + local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any + local esds = Box.child(holder, "esds") + if esds then + local oti, dsi, avg = Demux.esds(b, esds) + t.objectType = oti + if oti and OTI[oti] then + t.codec = OTI[oti] + end + t.config = dsi + if avg and avg > 0 then + t.bitrate = avg + end + end + if typ == "alac" then + local a = Box.child(holder, "alac") + if a then + t.config = payload(b, a, 4) + end + end + for _, name in CONFIG_BOX do + local c = Box.child(holder, name) + if c then + t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0) + break + end + end +end + +-- media handler / header / sample tables of one trak -> Track | nil, Err +local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?) + local tkhd = Box.child(trak, "tkhd") + local mdia = Box.child(trak, "mdia") + if not tkhd or not mdia then + return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start) + end + local t: Track = { + id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0, + entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {}, + } + do + local r = reader(b, tkhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.id = r:u32be() + r:skip(4 + 8) + else + r:skip(8) + t.id = r:u32be() + r:skip(4 + 4) + end + r:skip(8 + 2 + 2 + 2 + 2 + 36) + local w, h = r:u32be() / 65536, r:u32be() / 65536 + if r.err then + return nil, r.err + end + if w > 0 and h > 0 then + t.width, t.height = math.floor(w), math.floor(h) + end + end + local mdhd = Box.child(mdia, "mdhd") + if mdhd then + local r = reader(b, mdhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.timescale = r:u32be() + t.mediaDuration = r:u64be() + else + r:skip(8) + t.timescale = r:u32be() + t.mediaDuration = r:u32be() + end + local lang = r:u16be() + if not r.err and lang ~= 0 and lang ~= 0x7FFF then + t.language = string.char( + 96 + bit32.band(bit32.rshift(lang, 10), 31), + 96 + bit32.band(bit32.rshift(lang, 5), 31), + 96 + bit32.band(lang, 31) + ) + end + if t.timescale == 0 then + t.timescale = 1 + end + end + local hdlr = Box.child(mdia, "hdlr") + if hdlr and hdlr.data + 12 <= hdlr.stop then + t.handler = readstring(b, hdlr.data + 8, 4) + end + t.kind = HANDLER_KIND[t.handler] or "data" + local stbl = Box.path(mdia, "minf/stbl") + if not stbl then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) + end + -- sample descriptions + local stsd = Box.child(stbl, "stsd") + if stsd and stsd.data + 8 <= stsd.stop then + local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") + if entries[1] then + sampleEntry(b, entries[1], t.handler, t) + end + t.sampleEntries = entries + end + -- edit list + local elst = Box.path(trak, "edts/elst") + if elst then + local r = reader(b, elst) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n <= (elst.stop - elst.data) // 12 then + local edits: { Edit } = {} + for _ = 1, n do + local dur: number, mt: number + if v == 1 then + dur, mt = r:u64be(), r:i64be() :: number + else + dur, mt = r:u32be(), r:i32be() :: number + end + local rate = r:i32be() / 65536 + if r.err then + break + end + table.insert(edits, { duration = dur, mediaTime = mt, rate = rate }) + end + t.edits = edits + local play = 0 + local started = false + for _, ed in edits do + if ed.mediaTime == -1 then + if not started then + t.delay += ed.duration + end + else + if not started then + t.skip = ed.mediaTime + started = true + end + play += ed.duration * t.timescale / math.max(1, movieTimescale) + end + end + if started and play > 0 then + t.playDuration = math.floor(play + 0.5) + end + end + end + -- sample sizes + local maxSamples = o.maxSamples or 2 ^ 25 + local sizes = t.sizes + local count = 0 + local stsz = Box.child(stbl, "stsz") + local stz2 = Box.child(stbl, "stz2") + if stsz then + local r = reader(b, stsz) + r:skip(4) + local fixed = r:u32be() + count = r:u32be() + if r.err then + return nil, r.err + end + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start) + end + if fixed ~= 0 then + for i = 1, count do + sizes[i] = fixed + end + else + if count * 4 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start) + end + for i = 1, count do + sizes[i] = r:u32be() + end + end + elseif stz2 then + local r = reader(b, stz2) + r:skip(4 + 3) + local fieldSize = r:u8() + count = r:u32be() + if r.err then + return nil, r.err + end + if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then + return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start) + end + if count * fieldSize / 8 > r:remaining() + 1 then + return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start) + end + for i = 1, count do + if fieldSize == 16 then + sizes[i] = r:u16be() + elseif fieldSize == 8 then + sizes[i] = r:u8() + else + local byte = r:peekU8() + if i % 2 == 1 then + sizes[i] = bit32.rshift(math.max(byte, 0), 4) + else + sizes[i] = bit32.band(math.max(byte, 0), 15) + r:skip(1) + end + end + end + end + -- decode times + local dts, durs = t.dts, t.durations + local stts = Box.child(stbl, "stts") + if stts and count > 0 then + local r = reader(b, stts) + r:skip(4) + local n = r:u32be() + if n * 8 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start) + end + local i, time = 1, 0 + for _ = 1, n do + local c, d = r:u32be(), r:u32be() + for _ = 1, c do + if i > count then + break + end + dts[i], durs[i] = time, d + time += d + i += 1 + end + end + -- fewer stts entries than samples: repeat the last duration + local last = if i > 1 then durs[i - 1] else 0 + while i <= count do + dts[i], durs[i] = time, last + time += last + i += 1 + end + else + for i = 1, count do + dts[i], durs[i] = 0, 0 + end + end + -- composition offsets + local ctts = Box.child(stbl, "ctts") + if ctts and count > 0 then + local r = reader(b, ctts) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n * 8 <= r:remaining() then + local cts = table.create(count, 0) + local i = 1 + for _ = 1, n do + local c = r:u32be() + local off = if v == 1 then r:i32be() else r:u32be() + if v == 0 and off >= 2147483648 then + off -= 4294967296 -- writers put negative offsets in version 0 too + end + for _ = 1, c do + if i > count then + break + end + cts[i] = off + i += 1 + end + end + t.cts = cts + end + end + -- sync samples + local stss = Box.child(stbl, "stss") + if stss then + local r = reader(b, stss) + r:skip(4) + local n = r:u32be() + if n * 4 <= r:remaining() then + local sync = {} + for _ = 1, n do + sync[r:u32be()] = true + end + t.sync = sync + end + end + -- chunk offsets + sample-to-chunk -> sample offsets + local stco = Box.child(stbl, "stco") + local co64 = Box.child(stbl, "co64") + local chunks: { number } = {} + if stco or co64 then + local box = (stco or co64) :: Box.Box + local r = reader(b, box) + r:skip(4) + local n = r:u32be() + local w = if co64 then 8 else 4 + if n * w > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start) + end + for i = 1, n do + chunks[i] = if co64 then r:u64be() else r:u32be() + end + end + local stsc = Box.child(stbl, "stsc") + local offsets = t.offsets + if count > 0 then + if not stsc or #chunks == 0 then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start) + end + local r = reader(b, stsc) + r:skip(4) + local n = r:u32be() + if n * 12 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) + end + local first: { number }, per: { number }, desc: { number } = {}, {}, {} + for k = 1, n do + first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() + end + local sdi: { number }? = nil + if n > 0 then + for k = 1, n do + if desc[k] ~= desc[1] then + sdi = table.create(count, 1) + end + end + end + local i = 1 + local base = 0 -- added by the caller (the file's offset in the buffer) + for k = 1, n do + local c0 = first[k] + local c1 = if k < n then first[k + 1] - 1 else #chunks + if c0 < 1 then + return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start) + end + for c = c0, math.min(c1, #chunks) do + local off = chunks[c] + base + for _ = 1, per[k] do + if i > count then + break + end + offsets[i] = off + if sdi then + sdi[i] = desc[k] + end + off += sizes[i] + i += 1 + end + if i > count then + break + end + end + if i > count then + break + end + end + if i <= count then + return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start) + end + t.sampleDescription = sdi + end + t.sampleCount = count + -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024 + -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio. + if t.kind == "audio" and count > 1 and not t.cts and not t.sync then + local fixed = sizes[1] + local uniform = fixed > 0 + for i = 1, count do + if sizes[i] ~= fixed or durs[i] ~= 1 then + uniform = false + break + end + end + if uniform then + local no, ns, nd, nu = {}, {}, {}, {} + local i = 1 + while i <= count do + local k = 1 + while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do + k += 1 + end + table.insert(no, offsets[i]) + table.insert(ns, k * fixed) + table.insert(nd, dts[i]) + table.insert(nu, k) + i += k + end + t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu + t.sampleCount = #no + t.frameSize = fixed + t.sampleDescription = nil + end + end + -- fragment defaults + t.trex = trex[t.id] + return t, nil +end + +-- the movie fragments (moof) after the moov: appends their samples to the tracks +local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err? + local maxSamples = o.maxSamples or 2 ^ 25 + for _, moof in top do + if moof.type ~= "moof" then + continue + end + local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end) + local prevEnd = moofStart + for _, traf in Box.childrenOf(moof, "traf") do + local tfhd = Box.child(traf, "tfhd") + if not tfhd then + continue + end + local r = reader(b, tfhd) + r:skip(1) + local flags = r:u24be() + local id = r:u32be() + local t = byId[id] + if r.err or not t then + continue + end + local trex = t.trex or {} + local base + if bit32.band(flags, 0x1) ~= 0 then + base = r:u64be() + elseif bit32.band(flags, 0x20000) ~= 0 then + base = moofStart + else + base = prevEnd + end + if bit32.band(flags, 0x2) ~= 0 then + r:skip(4) + end + local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0) + local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0) + local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0) + if r.err then + return r.err + end + local n0 = t.sampleCount + local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0 + local tfdt = Box.child(traf, "tfdt") + if tfdt then + local q = reader(b, tfdt) + local v = q:u8() + q:skip(3) + local bt = if v == 1 then q:u64be() else q:u32be() + if not q.err then + time = bt + end + end + local dataPos = base + for _, trun in Box.childrenOf(traf, "trun") do + local q = reader(b, trun) + local v = q:u8() + local tf = q:u24be() + local n = q:u32be() + if q.err then + return q.err + end + if t.sampleCount + n > maxSamples then + return Err.new(Err.LIMIT, "too many fragment samples", trun.start) + end + if bit32.band(tf, 0x1) ~= 0 then + dataPos = base + q:i32be() + end + local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil + local per = 0 + for _, bit in { 0x100, 0x200, 0x400, 0x800 } do + if bit32.band(tf, bit) ~= 0 then + per += 4 + end + end + if n * per > q:remaining() then + return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start) + end + for k = 1, n do + local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur + local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize + local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags) + local cto = 0 + if bit32.band(tf, 0x800) ~= 0 then + cto = if v == 1 then q:i32be() else q:u32be() + end + local i = t.sampleCount + 1 + t.sampleCount = i + t.offsets[i] = dataPos + t.sizes[i] = size + t.dts[i] = time + t.durations[i] = dur + if cto ~= 0 or t.cts then + if not t.cts then + t.cts = table.create(i - 1, 0) + end + (t.cts :: { number })[i] = cto + end + -- sample_is_non_sync_sample (bit 16) + local nonSync = bit32.band(sf, 0x10000) ~= 0 + if nonSync then + if not t.sync then + local s = {} + for j = 1, i - 1 do + s[j] = true + end + t.sync = s + end + elseif t.sync then + (t.sync :: any)[i] = true + end + time += dur + dataPos += size + end + prevEnd = dataPos + end + end + end + return nil +end + +type Movie = { + brand: string?, + minor: number?, + compatible: { string }, + timescale: number, + duration: number, -- seconds + tracks: { Track }, + boxes: { Box.Box }, + moov: Box.Box?, + fragmented: boolean, +} + +-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) +function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) + local o: Options = opts or {} + local b = r.buf + local top, terr = Box.list(b, r.base, r.limit) + if #top == 0 then + return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base) + end + local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false } + local ftyp = Box.child({ children = top } :: any, "ftyp") + if ftyp and ftyp.data + 8 <= ftyp.stop then + m.brand = readstring(b, ftyp.data, 4) + m.minor = Box.be32(b, ftyp.data + 4) + local p = ftyp.data + 8 + while p + 4 <= ftyp.stop do + table.insert(m.compatible, readstring(b, p, 4)) + p += 4 + end + end + local moov = Box.child({ children = top } :: any, "moov") + m.moov = moov + if not moov then + return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks + end + local mvhd = Box.child(moov, "mvhd") + local movieDuration = 0 + if mvhd then + local q = reader(b, mvhd) + local v = q:u8() + q:skip(3) + if v == 1 then + q:skip(16) + m.timescale = q:u32be() + movieDuration = q:u64be() + else + q:skip(8) + m.timescale = q:u32be() + movieDuration = q:u32be() + end + if q.err or m.timescale == 0 then + m.timescale = 1000 + end + end + local trex = {} + local mvex = Box.child(moov, "mvex") + if mvex then + m.fragmented = true + for _, x in Box.childrenOf(mvex, "trex") do + local q = reader(b, x) + q:skip(4) + local id = q:u32be() + q:skip(4) + local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() } + if not q.err then + trex[id] = d + end + end + end + local byId = {} + for _, trak in Box.childrenOf(moov, "trak") do + local t, err = track(b, trak, m.timescale, trex, o) + if not t then + return nil, err + end + table.insert(m.tracks, t) + byId[t.id] = t + end + if m.fragmented then + local ferr = fragments(b, r.base, top, byId, o) + if ferr then + return nil, ferr + end + end + -- durations; drop samples outside the buffer (a truncated file) but keep what is there + for _, t in m.tracks do + local n = t.sampleCount + local ticks = t.mediaDuration + if n > 0 then + ticks = math.max(ticks, t.dts[n] + t.durations[n]) + end + t.mediaDuration = ticks + t.duration = ticks / t.timescale + for i = 1, n do + local off = t.offsets[i] + if off < 0 or off + t.sizes[i] > r.limit - r.base then + t.sampleCount = i - 1 + t.truncated = true + break + end + end + -- the tables hold file offsets; make them buffer offsets + local base = r.base + if base ~= 0 then + local offs = t.offsets + for i = 1, t.sampleCount do + offs[i] += base + end + end + end + m.duration = movieDuration / m.timescale + if m.duration == 0 then + for _, t in m.tracks do + m.duration = math.max(m.duration, t.duration) + end + end + return m, nil +end + +return Demux +end +__FILES["containers/IsoBmff/Meta"] = function() + +-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc +-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC +-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn / +-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer. +-- Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Meta = {} + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +local function uint(r: Bytes.Reader, size: number): number + if size == 0 then + return 0 + elseif size == 4 then + return r:u32be() + elseif size == 8 then + return r:u64be() + elseif size == 2 then + return r:u16be() + elseif size == 1 then + return r:u8() + end + r:fail(Err.CORRUPT, "bad iloc field size " .. size) + return 0 +end + +-- ------------------------------------------------------------------------------------------------ HEIF items +type Property = { type: string, box: Box.Box, [string]: any } +type Item = { + id: number, + type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ... + name: string, + contentType: string?, + hidden: boolean, + construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item) + baseOffset: number, + extents: { { offset: number, length: number } }, + properties: { Property }, -- in ipma order + essential: { [number]: boolean }, -- by index into properties + refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...) +} +type Items = { + primary: number?, + items: { [number]: Item }, + order: { number }, -- item ids in iinf order + idat: Box.Box?, + properties: { Property }, -- ipco, in order +} + +local function property(b: buffer, box: Box.Box): Property + local p: Property = { type = box.type, box = box } + local r = reader(b, box) + local t = box.type + if t == "ispe" then + r:skip(4) + p.width, p.height = r:u32be(), r:u32be() + elseif t == "pixi" then + r:skip(4) + local n = r:u8() + local bits = {} + for i = 1, math.min(n, 16) do + bits[i] = r:u8() + end + p.bits = bits + elseif t == "colr" then + local ct = r:string(4) + p.colourType = ct + if ct == "nclx" then + p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be() + p.fullRange = bit32.band(r:u8(), 0x80) ~= 0 + elseif ct == "rICC" or ct == "prof" then + p.icc = r:bytes(r:remaining()) + end + elseif t == "irot" then + p.angle = bit32.band(r:u8(), 3) * 90 + elseif t == "imir" then + p.axis = bit32.band(r:u8(), 1) + elseif t == "clap" then + local function frac(): number + local n, d = r:i32be(), r:u32be() + return if d == 0 then 0 else n / d + end + p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac() + elseif t == "auxC" then + r:skip(4) + p.auxType = r:cstring() + else + local n = box.stop - box.data + local cfg = buffer.create(math.max(0, n)) + if n > 0 then + buffer.copy(cfg, 0, b, box.data, n) + end + p.config = cfg + end + return p +end + +-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) +function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) + local out: Items = { items = {}, order = {}, properties = {} } + local pitm = Box.child(meta, "pitm") + if pitm then + local r = reader(b, pitm) + local v = r:u8() + r:skip(3) + out.primary = if v == 0 then r:u16be() else r:u32be() + end + local iinf = Box.child(meta, "iinf") + if iinf then + for _, infe in Box.childrenOf(iinf, "infe") do + local r = reader(b, infe) + local v = r:u8() + local flags = r:u24be() + local it: Item = { + id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0, + extents = {}, properties = {}, essential = {}, refs = {}, + } + if v >= 2 then + it.id = if v == 2 then r:u16be() else r:u32be() + r:skip(2) + it.type = r:string(4) + it.name = r:cstring() + if it.type == "mime" and r:remaining() > 0 then + it.contentType = r:cstring() + end + else + it.id = r:u16be() + r:skip(2) + it.name = r:cstring() + it.contentType = r:cstring() + it.type = "mime" + end + if r.err and it.id == 0 then + return nil, r.err + end + out.items[it.id] = it + table.insert(out.order, it.id) + end + end + local iloc = Box.child(meta, "iloc") + if iloc then + local r = reader(b, iloc) + local v = r:u8() + r:skip(3) + local a, c = r:u8(), r:u8() + local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4) + local idxSize = if v >= 1 then bit32.band(c, 15) else 0 + local n = if v < 2 then r:u16be() else r:u32be() + if r.err then + return nil, r.err + end + for _ = 1, n do + local id = if v < 2 then r:u16be() else r:u32be() + local method = 0 + if v >= 1 then + method = bit32.band(r:u16be(), 15) + end + r:skip(2) -- data reference index + local base = uint(r, baseSize) + local ne = r:u16be() + if r.err then + return nil, r.err + end + if ne * (offSize + lenSize + idxSize) > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start) + end + local extents = {} + for k = 1, ne do + if idxSize > 0 then + uint(r, idxSize) + end + extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) } + end + if r.err then + return nil, r.err + end + local it = out.items[id] + if not it then + it = { + id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, + properties = {}, essential = {}, refs = {}, + } :: Item + out.items[id] = it + table.insert(out.order, id) + end + it.construction, it.baseOffset, it.extents = method, base, extents + end + end + local iref = Box.child(meta, "iref") + if iref then + local v = Box.fullHeader(b, iref) + for _, ref in (iref.children or {}) :: { Box.Box } do + local r = reader(b, ref) + local from = if v == 0 then r:u16be() else r:u32be() + local n = r:u16be() + local to = {} + for k = 1, n do + to[k] = if v == 0 then r:u16be() else r:u32be() + end + local it = out.items[from] + if it and not r.err then + it.refs[ref.type] = to + end + end + end + local ipco = Box.path(meta, "iprp/ipco") + if ipco and ipco.children then + for i, pb in ipco.children :: { Box.Box } do + out.properties[i] = property(b, pb) + end + end + local ipma = Box.path(meta, "iprp/ipma") + if ipma then + local r = reader(b, ipma) + local v = r:u8() + local flags = r:u24be() + local n = r:u32be() + for _ = 1, n do + if r.err then + break + end + local id = if v < 1 then r:u16be() else r:u32be() + local na = r:u8() + local it = out.items[id] + for _ = 1, na do + local idx, ess + if bit32.band(flags, 1) ~= 0 then + local x = r:u16be() + idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000 + else + local x = r:u8() + idx, ess = bit32.band(x, 0x7F), x >= 0x80 + end + local p = out.properties[idx] + if it and p and not r.err then + table.insert(it.properties, p) + if ess then + it.essential[#it.properties] = true + end + end + end + end + end + out.idat = Box.child(meta, "idat") + return out, nil +end + +-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit +-- bound the file in the buffer +function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?) + local it = items.items[id] + if not it then + return nil, Err.new(Err.CORRUPT, "no item " .. id) + end + local origin, stop + if it.construction == 0 then + origin, stop = base, limit + elseif it.construction == 1 then + local idat = items.idat + if not idat then + return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat") + end + origin, stop = idat.data, idat.stop + else + return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction) + end + local total = 0 + for _, e in it.extents do + local len = e.length + if len == 0 then -- the whole rest of the file + len = stop - origin - e.offset + end + if e.offset < 0 or len < 0 or origin + e.offset + len > stop then + return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end") + end + total += len + end + if total > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big") + end + local out = buffer.create(total) + local p = 0 + for _, e in it.extents do + local len = if e.length == 0 then stop - origin - e.offset else e.length + buffer.copy(out, p, b, origin + e.offset, len) + p += len + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ iTunes tags +-- ilst item -> standard tag name +local TAG: { [string]: string } = { + ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", + ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder", + ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription", + sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort", + tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate", + ["\169pub"] = "publisher", ["\169xyz"] = "location", +} +local TAG_ATOM: { [string]: string } = {} +for atom, name in TAG do + TAG_ATOM[name] = atom +end +Meta.TAG = TAG +Meta.TAG_ATOM = TAG_ATOM +-- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back +local FREEFORM: { [string]: string } = { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" } + +-- the ID3v1 genres gnre indexes (1-based in gnre) +local GENRES = { + "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", + "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", + "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", + "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", + "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", + "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", + "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", + "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", + "Musical", "Rock & Roll", "Hard Rock", +} + +type Picture = { mime: string, data: buffer } + +-- tags(buf, ilst) -> Tags, { Picture } +function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture }) + local tags: { [string]: string } = {} + local pics: { Picture } = {} + if not ilst or not ilst.children then + return tags, pics + end + for _, item in ilst.children :: { Box.Box } do + local typ = item.type + local freeName: string? = nil + if typ == "----" then + local nm = Box.child(item, "name") + if nm and nm.data + 4 <= nm.stop then + freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4) + end + end + for _, d in Box.childrenOf(item, "data") do + if d.data + 8 > d.stop then + continue + end + local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF) + local p, n = d.data + 8, d.stop - d.data - 8 + if typ == "trkn" or typ == "disk" then + if n >= 6 then + local num = Box.be32(b, p) % 65536 + local total = Box.be32(b, p + 2) % 65536 + local key = if typ == "trkn" then "track" else "disc" + if num > 0 then + tags[key] = tostring(num) + end + if total > 0 then + tags[key .. "total"] = tostring(total) + end + end + elseif typ == "gnre" then + if n >= 2 then + local g = GENRES[Box.be32(b, p - 2) % 65536] + if g and not tags.genre then + tags.genre = g + end + end + elseif typ == "tmpo" then + if n >= 2 then + tags.bpm = tostring(Box.be32(b, p - 2) % 65536) + end + elseif typ == "cpil" or typ == "pgap" then + if n >= 1 then + tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p)) + end + elseif typ == "covr" then + local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg" + local data = buffer.create(n) + buffer.copy(data, 0, b, p, n) + table.insert(pics, { mime = mime, data = data }) + elseif kind == 1 or kind == 0 then + local s = readstring(b, p, n) + local key = if freeName then string.lower(freeName) else TAG[typ] or string.lower(typ) + if typ == "\169gen" or not tags[key] then + tags[key] = s + end + end + end + end + return tags, pics +end + +-- ------------------------------------------------------------------------------------------------ ilst writer +local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ()) + local start = w:tell() + w:u32be(0) + w:string(typ) + body(w) + w:setU32be(start, w:tell() - start) +end +Meta.box = box + +local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer) + box(w, "data", function() + w:u32be(kind) + w:u32be(0) + if type(value) == "string" then + w:string(value) + else + w:bytes(value) + end + end) +end + +local function num(s: string?): number + local v = tonumber(s or "") + if not v then + return 0 + end + return math.clamp(math.floor(v), 0, 65535) +end + +-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' +-- freeform com.apple.iTunes items) and cover pictures +function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "ilst", function() + local keys = {} + for k in tags do + table.insert(keys, k) + end + table.sort(keys) + local done: { [string]: boolean } = {} + for _, k in keys do + local v = tags[k] + if type(v) ~= "string" or done[k] then + continue + end + if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then + local base = if k == "track" or k == "tracktotal" then "track" else "disc" + if done[base] then + continue + end + done[base] = true + local atom = if base == "track" then "trkn" else "disk" + local n, total = num(tags[base]), num(tags[base .. "total"]) + box(w, atom, function() + box(w, "data", function() + w:u32be(0) + w:u32be(0) + w:u16be(0) + w:u16be(n) + w:u16be(total) + if atom == "trkn" then + w:u16be(0) + end + end) + end) + elseif k == "bpm" then + box(w, "tmpo", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u16be(num(v)) + end) + end) + elseif k == "compilation" or k == "gapless" then + box(w, if k == "compilation" then "cpil" else "pgap", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u8(if num(v) ~= 0 then 1 else 0) + end) + end) + elseif TAG_ATOM[k] then + box(w, TAG_ATOM[k], function() + dataBox(w, 1, v) + end) + else + box(w, "----", function() + box(w, "mean", function() + w:u32be(0) + w:string("com.apple.iTunes") + end) + box(w, "name", function() + w:u32be(0) + w:string(FREEFORM[k] or k) + end) + dataBox(w, 1, v) + end) + end + done[k] = true + end + if pictures and #pictures > 0 then + box(w, "covr", function() + for _, p in pictures :: { Picture } do + dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data) + end + end) + end + end) +end + +-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "udta", function() + box(w, "meta", function() + w:u32be(0) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string("mdir") + w:string("appl") + w:u32be(0) + w:u32be(0) + w:u8(0) + end) + Meta.writeIlst(w, tags, pictures) + end) + end) +end + +return Meta +end +__FILES["containers/IsoBmff/Mux"] = function() + +-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak +-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks +-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample +-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + +-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Meta = __include("containers/IsoBmff/Meta") + +local Mux = {} + +type MuxTrack = { + kind: "audio" | "video" | "subtitle" | "data", + entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ... + timescale: number, -- ticks per second (audio: the sample rate) + samples: { buffer }?, -- one buffer per sample, or + data: buffer?, -- the samples back to back, with + sizes: { number }?, -- their sizes + durations: { number } | number, -- ticks per sample (or one constant) + cts: { number }?, -- composition offsets (video with B-frames) + sync: { [number]: boolean }?, -- sync samples (nil: all) + sampleRate: number?, + channels: number?, + bitsPerSample: number?, -- default 16 + width: number?, + height: number?, + config: buffer?, -- the codec configuration, written as the entry's configuration box + configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC) + objectType: number?, -- esds objectTypeIndication (default 0x40, AAC) + bitrate: number?, -- esds average bitrate + boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads) + language: string?, -- ISO 639-2, default "und" + name: string?, -- hdlr name + skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming) + playDuration: number?, -- media ticks to play (edit list) +} +type MuxSpec = { + brand: string?, -- default "isom" + minor: number?, + compatible: { string }?, + timescale: number?, -- movie timescale, default 1000 + tracks: { MuxTrack }, + tags: { [string]: string }?, + pictures: { Meta.Picture }?, + chunkDuration: number?, -- seconds of samples per chunk, default 1 +} + +local DEFAULT_CONFIG_BOX: { [string]: string } = { + mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC", + hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3", +} +local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true } +local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" } + +local box = Meta.box + +local function lang(s: string?): number + local l = s or "und" + if #l ~= 3 then + l = "und" + end + local v = 0 + for i = 1, 3 do + v = v * 32 + bit32.band(string.byte(l, i) - 96, 31) + end + return v +end + +local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ()) + local inner = Bytes.writer(64) + body(inner) + local n = inner:tell() + w:u8(tag) + -- 4-byte expandable length (the common iTunes / ffmpeg form) + w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127)) + w:u8(bit32.band(n, 127)) + w:bytes(inner.buf, 0, n) +end + +local function esds(w: Bytes.Writer, t: MuxTrack) + box(w, "esds", function() + w:u32be(0) + descriptor(w, 3, function(d) + d:u16be(0) -- ES_ID + d:u8(0) + descriptor(d, 4, function(c) + c:u8(t.objectType or 0x40) + c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1 + c:u24be(0) + c:u32be(t.bitrate or 0) + c:u32be(t.bitrate or 0) + if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info) + descriptor(c, 5, function(s) + s:bytes(t.config :: buffer) + end) + end + end) + descriptor(d, 6, function(s) + s:u8(2) + end) + end) + end) +end + +local function sampleEntry(w: Bytes.Writer, t: MuxTrack) + box(w, t.entry, function() + w:fill(0, 6) + w:u16be(1) -- data reference index + if t.kind == "audio" then + w:u16be(0) -- version + w:u16be(0) + w:u32be(0) + w:u16be(t.channels or 2) + w:u16be(t.bitsPerSample or 16) + w:u16be(0) + w:u16be(0) + local sr = t.sampleRate or t.timescale + w:u32be(if sr < 65536 then sr * 65536 else 0) + elseif t.kind == "video" then + w:fill(0, 16) + w:u16be(t.width or 0) + w:u16be(t.height or 0) + w:u32be(0x00480000) + w:u32be(0x00480000) + w:u32be(0) + w:u16be(1) -- frame count + w:fill(0, 32) -- compressor name + w:u16be(0x18) + w:i16be(-1) + end + local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry] + if t.config and cb then + if cb == "esds" then + esds(w, t) + else + box(w, cb, function() + if FULL_BOX[cb] then + w:u32be(0) + end + w:bytes(t.config :: buffer) + end) + end + end + for _, x in t.boxes or {} do + box(w, x.type, function() + w:bytes(x.data) + end) + end + end) +end + +type Chunk = { track: number, first: number, count: number, time: number, offset: number } + +-- runs of equal values: { { count, value } } +local function runs(n: number, value: (number) -> number): { { number } } + local out = {} + for i = 1, n do + local v = value(i) + local last = out[#out] + if last and last[2] == v then + last[1] += 1 + else + table.insert(out, { 1, v }) + end + end + return out +end + +type Prepared = { + t: MuxTrack, + n: number, + sizes: { number }, + dur: (number) -> number, + total: number, -- media ticks + chunks: { Chunk }, + sample: (number) -> (buffer, number), -- buffer, offset +} + +local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean) + local mts = spec.timescale or 1000 + local function toMovie(p: Prepared, ticks: number): number + return math.floor(ticks * mts / p.t.timescale + 0.5) + end + local movieDur = 0 + for _, p in prep do + local play = p.t.playDuration or (p.total - (p.t.skip or 0)) + movieDur = math.max(movieDur, toMovie(p, play)) + end + box(w, "moov", function() + box(w, "mvhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(mts) + w:u32be(movieDur) + w:u32be(0x00010000) + w:u16be(0x0100) + w:fill(0, 10) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:fill(0, 24) + w:u32be(#prep + 1) + end) + for id, p in prep do + local t = p.t + local play = t.playDuration or (p.total - (t.skip or 0)) + box(w, "trak", function() + box(w, "tkhd", function() + w:u32be(3) -- enabled, in movie + w:u32be(0) + w:u32be(0) + w:u32be(id) + w:u32be(0) + w:u32be(toMovie(p, play)) + w:fill(0, 8) + w:u16be(0) + w:u16be(0) + w:u16be(if t.kind == "audio" then 0x0100 else 0) + w:u16be(0) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:u32be((t.width or 0) * 65536) + w:u32be((t.height or 0) * 65536) + end) + if t.skip or t.playDuration then + box(w, "edts", function() + box(w, "elst", function() + w:u32be(0) + w:u32be(1) + w:u32be(toMovie(p, play)) + w:u32be(t.skip or 0) + w:u32be(0x00010000) + end) + end) + end + box(w, "mdia", function() + box(w, "mdhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(t.timescale) + w:u32be(p.total) + w:u16be(lang(t.language)) + w:u16be(0) + end) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string(HANDLER[t.kind] or "meta") + w:fill(0, 12) + w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler")) + end) + box(w, "minf", function() + if t.kind == "audio" then + box(w, "smhd", function() + w:u32be(0) + w:u32be(0) + end) + elseif t.kind == "video" then + box(w, "vmhd", function() + w:u32be(1) + w:fill(0, 8) + end) + else + box(w, "nmhd", function() + w:u32be(0) + end) + end + box(w, "dinf", function() + box(w, "dref", function() + w:u32be(0) + w:u32be(1) + box(w, "url ", function() + w:u32be(1) -- self-contained + end) + end) + end) + box(w, "stbl", function() + box(w, "stsd", function() + w:u32be(0) + w:u32be(1) + sampleEntry(w, t) + end) + local stts = runs(p.n, p.dur) + box(w, "stts", function() + w:u32be(0) + w:u32be(#stts) + for _, r in stts do + w:u32be(r[1]) + w:u32be(r[2]) + end + end) + local cts = t.cts + if cts then + local cr = runs(p.n, function(i) + return cts[i] or 0 + end) + box(w, "ctts", function() + w:u32be(0x01000000) -- version 1: signed offsets + w:u32be(#cr) + for _, r in cr do + w:u32be(r[1]) + w:i32be(r[2]) + end + end) + end + local sync = t.sync + if sync then + local list = {} + for i = 1, p.n do + if sync[i] then + table.insert(list, i) + end + end + box(w, "stss", function() + w:u32be(0) + w:u32be(#list) + for _, i in list do + w:u32be(i) + end + end) + end + local stsc = runs(#p.chunks, function(i) + return p.chunks[i].count + end) + box(w, "stsc", function() + w:u32be(0) + w:u32be(#stsc) + local c = 1 + for _, r in stsc do + w:u32be(c) + w:u32be(r[2]) + w:u32be(1) + c += r[1] + end + end) + box(w, "stsz", function() + w:u32be(0) + local fixed = p.sizes[1] or 0 + for i = 2, p.n do + if p.sizes[i] ~= fixed then + fixed = -1 + break + end + end + if fixed >= 0 and p.n > 0 then + w:u32be(fixed) + w:u32be(p.n) + else + w:u32be(0) + w:u32be(p.n) + for i = 1, p.n do + w:u32be(p.sizes[i]) + end + end + end) + box(w, if co64 then "co64" else "stco", function() + w:u32be(0) + w:u32be(#p.chunks) + for _, c in p.chunks do + if co64 then + w:u64be(c.offset) + else + w:u32be(c.offset) + end + end + end) + end) + end) + end) + end) + end + if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then + Meta.writeUdta(w, spec.tags or {}, spec.pictures) + end + end) +end + +-- mux(spec) -> buffer | nil, Err +function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) + if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then + return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") + end + local prep: { Prepared } = {} + local all: { Chunk } = {} + for k, t in spec.tracks do + if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale") + end + if not HANDLER[t.kind] then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind)) + end + local n, sizes, sample + if t.samples then + local list = t.samples + n = #list + sizes = table.create(n, 0) + for i = 1, n do + if type(list[i]) ~= "buffer" then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer") + end + sizes[i] = buffer.len(list[i]) + end + sample = function(i: number): (buffer, number) + return list[i], 0 + end + elseif t.data and t.sizes then + n = #t.sizes + sizes = t.sizes + local starts = table.create(n, 0) + local o = 0 + for i = 1, n do + starts[i] = o + o += sizes[i] + end + if o > buffer.len(t.data) then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data") + end + local data = t.data + sample = function(i: number): (buffer, number) + return data, starts[i] + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes") + end + local durs = t.durations + local dur + if type(durs) == "number" then + dur = function(_: number): number + return durs + end + elseif type(durs) == "table" then + dur = function(i: number): number + return durs[i] or 0 + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations") + end + local total = 0 + local chunks: { Chunk } = {} + local per = (spec.chunkDuration or 1) * t.timescale + local cur: Chunk? = nil + for i = 1, n do + if not cur or total - cur.time >= per then + cur = { track = k, first = i, count = 0, time = total, offset = 0 } + table.insert(chunks, cur :: Chunk) + table.insert(all, cur :: Chunk) + end + (cur :: Chunk).count += 1 + total += dur(i) + end + prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample } + end + -- interleave the chunks by time + table.sort(all, function(a: Chunk, b: Chunk): boolean + local ta = a.time / prep[a.track].t.timescale + local tb = b.time / prep[b.track].t.timescale + if ta ~= tb then + return ta < tb + end + if a.track ~= b.track then + return a.track < b.track + end + return a.first < b.first + end) + local mdatSize = 0 + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + mdatSize += p.sizes[i] + end + end + local co64 = mdatSize > 4294967295 - 2 ^ 24 + -- ftyp + local w = Bytes.writer(mdatSize + 4096) + box(w, "ftyp", function() + w:string(spec.brand or "isom") + w:u32be(spec.minor or 0x200) + for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do + w:string(string.sub(c .. " ", 1, 4)) + end + end) + -- moov twice: the first pass measures it, the second has the real chunk offsets + local probe = Bytes.writer(4096) + moov(probe, spec, prep, co64) + local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8 + local o = w:tell() + probe:tell() + mdatHeader + for _, c in all do + c.offset = o + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + o += p.sizes[i] + end + end + moov(w, spec, prep, co64) + if mdatHeader == 16 then + w:u32be(1) + w:string("mdat") + w:u64be(mdatSize + 16) + else + w:u32be(mdatSize + 8) + w:string("mdat") + end + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + local b, off = p.sample(i) + w:bytes(b, off, p.sizes[i]) + end + end + return w:finish(), nil +end + +return Mux +end +__FILES["containers/IsoBmff/QtPalette"] = function() + +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- +-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) +-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil +-- +-- Never throws. +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b: buffer, o: number): number -- big-endian + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b: buffer, o: number): number + return readu16(b, o) * 65536 + readu16(b, o + 2) +end + +local QtPalette = {} + +local function rgb(r: number, g: number, b: number): number + return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL: { [number]: { number } } = { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits: number): buffer + local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in small do + writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i += 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in RAMP do + local r = if ch == 0 or ch == 3 then v else 0 + local g = if ch == 1 or ch == 3 then v else 0 + local b = if ch == 2 or ch == 3 then v else 0 + writeu32(pal, i * 4, rgb(r, g, b)) + i += 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size +-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) + if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (raw // 32) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = 256 // (count - 1) + local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette +end +__FILES["containers/MacFile"] = function() + +-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by +-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"): +-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with +-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix +-- seconds) and comment. Writers pair them back with collect(). +-- +-- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" }) +-- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string +-- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes +-- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped) +-- New code. Never throws. +local Err = __include("core/Err") +local Archive = __include("containers/Archive") + +local MacFile = {} + +type Info = { + name: string, + data: buffer, + rsrc: buffer, + type: string, -- 4 bytes ("\0\0\0\0" when unknown) + creator: string, + flags: number, -- Finder flags (16 bits) + created: number?, -- unix seconds + modified: number?, + comment: string?, +} + +local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01 + +function MacFile.fromMac(s: number): number? + return if s == 0 then nil else s - MAC_EPOCH +end + +function MacFile.toMac(unix: number?): number + if type(unix) ~= "number" or unix ~= unix then + return 0 + end + return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF) +end + +-- Mac OS Roman bytes 0x80..0xFF +local ROMAN = { + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, + 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, + 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, + 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, + 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4, + 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7, +} +local FROM_UNICODE: { [number]: number } = {} +for i, u in ROMAN do + FROM_UNICODE[u] = 127 + i +end + +-- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through) +function MacFile.name(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + local c = string.byte(s, i) + out[i] = if c < 128 then string.char(c) else utf8.char(ROMAN[c - 127]) + end + return table.concat(out) +end + +-- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes) +function MacFile.roman(s: string): string + if not string.find(s, "[\128-\255]") or not utf8.len(s) then + return s + end + local out = {} + for _, c in utf8.codes(s) do + table.insert(out, if c < 128 then string.char(c) else string.char(FROM_UNICODE[c] or 63)) + end + return table.concat(out) +end + +local function four(s: any): string + if type(s) ~= "string" then + return "\0\0\0\0" + end + return string.sub(s .. "\0\0\0\0", 1, 4) +end + +-- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and +-- there is a resource fork) and, when non-empty, the resource fork entry +function MacFile.put(a: any, f: Info, noData: boolean?) + local common = { + macType = f.type, + macCreator = f.creator, + finderFlags = f.flags, + created = f.created, + mtime = f.modified, + comment = f.comment, + dir = false, + } + local e: any = table.clone(common) + e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data" + if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then + Archive.put(a, e) + end + if buffer.len(f.rsrc) > 0 then + local r: any = table.clone(common) + r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource" + Archive.put(a, r) + end +end + +-- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a +-- buffer or a string (one data fork named name, default "data") +function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?) + local files, err = Archive.files(value, name) + if not files then + return nil, err + end + local out: { Info } = {} + local byName: { [string]: Info } = {} + local function get(n: string, e: any): Info + local f = byName[n] + if not f then + f = { + name = n, + data = buffer.create(0), + rsrc = buffer.create(0), + type = four(e.macType), + creator = four(e.macCreator), + flags = if type(e.finderFlags) == "number" then bit32.band(e.finderFlags, 0xFFFF) else 0, + created = if type(e.created) == "number" then e.created else nil, + modified = if type(e.mtime) == "number" then e.mtime else nil, + comment = if type(e.comment) == "string" then e.comment else nil, + } + byName[n] = f + table.insert(out, f) + end + return f :: Info + end + -- data forks first, so a resource fork finds its file whatever the order + for _, it in files do + if it.entry.fork ~= "resource" then + get(it.name, it.entry).data = it.data + end + end + for _, it in files do + if it.entry.fork == "resource" then + local base = string.match(it.name, "^(.*)%.rsrc$") or it.name + get(base, it.entry).rsrc = it.data + end + end + return out, nil +end + +return MacFile +end +__FILES["containers/MpegEs"] = function() + +-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in rosetta. +-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it, +-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence +-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws. +local readu8 = buffer.readu8 + +local MpegEs = {} + +-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil +function MpegEs.findStart(b: buffer, p: number, limit: number): number? + local i = p + while i + 3 <= limit do + local c = readu8(b, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then + return i + end + i += 3 + else -- c == 0: the start code may begin at i + 1 or i + 2 + i += 1 + end + end + return nil +end + +local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } + +type Picture = { + offset: number, -- start of the access unit (its first header's start code) + size: number, + type: number, -- 1 I, 2 P, 3 B, 4 D (0 unknown) + temporal: number, -- temporal_reference + gop: boolean, -- a GOP header precedes the picture + sequence: boolean, -- a sequence header precedes the picture + structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3) + fields: number?, -- 2: a frame coded as two field pictures (both in this unit) +} +type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } + +-- info(b, off, limit) -> the first sequence header's facts | nil +function MpegEs.info(b: buffer, off: number, limit: number): Info? + local p = MpegEs.findStart(b, off, limit) + local info: Info? = nil + local count = 0 + while p and count < 64 do + count += 1 + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + if code == 0xB3 and p + 11 < limit and not info then + local w = readu8(b, p + 4) * 16 + readu8(b, p + 5) // 16 + local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6) + local fr = readu8(b, p + 7) % 16 + info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false } + elseif code == 0xB5 and info then + info.mpeg2 = true + return info + elseif code == 0x00 and info then + return info + end + p = MpegEs.findStart(b, p + 4, limit) + end + return info +end + +-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 +function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, number) + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 32 do + count += 1 + if p + 5 < limit and readu8(b, p + 3) == 0x00 then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + return (x // 8) % 8, x // 64 + end + p = MpegEs.findStart(b, p + 4, limit) + end + return 0, 0 +end + +-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture +-- coding extension (3 = frame when there is none: MPEG-1) +function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number + local q = MpegEs.findStart(b, p + 4, limit) + local count = 0 + while q and count < 8 do + count += 1 + local code = if q + 6 < limit then readu8(b, q + 3) else -1 + if code == 0xB5 then + if readu8(b, q + 4) // 16 == 8 then + local st = readu8(b, q + 6) % 4 + return if st == 0 then 3 else st + end + elseif code ~= 0xB2 then + break + end + q = MpegEs.findStart(b, q + 4, limit) + end + return 3 +end + +-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its +-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures +-- is one unit (fields = 2) +function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } + local out: { Picture } = {} + local unitStart: number? = nil + local seq, gop = false, false + local cur: Picture? = nil + local p = MpegEs.findStart(b, off, limit) + while p do + local code = if p + 3 < limit then readu8(b, p + 3) else -1 + local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3 + if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then + -- the second field of the current frame: same unit + cur.fields = 2 + elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + -- a sequence / GOP header or a picture after a picture closes it + if cur and (code ~= 0xB7) then + cur.size = p - cur.offset + table.insert(out, cur) + cur = nil + end + if code == 0xB3 then + unitStart = unitStart or p + seq = true + elseif code == 0xB8 then + unitStart = unitStart or p + gop = true + elseif code == 0x00 then + local t, tr = 0, 0 + if p + 5 < limit then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + t, tr = (x // 8) % 8, x // 64 + end + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture + unitStart, seq, gop = nil, false, false + elseif code == 0xB7 and cur then + cur.size = p + 4 - cur.offset + table.insert(out, cur) + cur = nil + end + end + p = MpegEs.findStart(b, p + 4, limit) + end + if cur then + cur.size = limit - cur.offset + table.insert(out, cur) + end + return out +end + +-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) +function MpegEs.h264Key(b: buffer, off: number, limit: number): boolean + local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 64 do + count += 1 + if p + 3 < limit then + local t = readu8(b, p + 3) % 32 + if t == 5 then + return true + elseif t == 1 then + return false + end + end + p = MpegEs.findStart(b, p + 3, limit) + end + return false +end + +return MpegEs +end +__FILES["containers/MpegPs"] = function() + +-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams: +-- .mpg / .mpeg / .vob). New in rosetta. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program +-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private +-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, +-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). +-- +-- local ps, err = MpegPs.read(buf, base, limit) +-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or +-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance +-- +-- Never throws: malformed packets are skipped and counted in ps.errors. +local Err = __include("core/Err") +local MpegEs = __include("containers/MpegEs") + +local readu8 = buffer.readu8 + +local MpegPs = {} + +type Pes = { pts: number?, dts: number?, offset: number, size: number } +type Stream = { id: number, kind: string, codec: string, streamType: number?, pes: { Pes } } +type File = { streams: { [number]: Stream }, order: { number }, mpeg2: boolean, errors: number } + +local WRAP = 8589934592 -- 2^33 + +-- PSM stream_type -> kind, codec +local TYPES: { [number]: { string } } = { + [0x01] = { "video", "mpeg1" }, + [0x02] = { "video", "mpeg2" }, + [0x03] = { "audio", "mp2" }, + [0x04] = { "audio", "mp2" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, +} + +local function ts(b: buffer, p: number): number + local a = readu8(b, p) + local v = (a // 2) % 8 + v = v * 32768 + (readu8(b, p + 1) * 256 + readu8(b, p + 2)) // 2 + v = v * 32768 + (readu8(b, p + 3) * 256 + readu8(b, p + 4)) // 2 + return v +end + +-- read(buf, base, limit) -> File | nil, Err +function MpegPs.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + local file: File = { streams = {}, order = {}, mpeg2 = false, errors = 0 } + local types: { [number]: number } = {} + local last: { [number]: number } = {} + local wrap: { [number]: number } = {} + local packs = 0 + local p = MpegEs.findStart(b, base, limit) + local function unwrap(id: number, v: number): number + local off = wrap[id] or 0 + local prev = last[id] + local t = v + off + if prev and t < prev - WRAP / 2 then + off += WRAP + wrap[id] = off + t = v + off + end + last[id] = t + return t + end + while p do + if p + 4 > limit then + break + end + local code = readu8(b, p + 3) + local nextP = p + 4 + if code == 0xBA then + packs += 1 + if p + 5 > limit then + break + end + local m = readu8(b, p + 4) + if m // 64 == 1 then -- MPEG-2 pack: 14 bytes + stuffing + file.mpeg2 = true + if p + 14 > limit then + break + end + nextP = p + 14 + readu8(b, p + 13) % 8 + else + nextP = p + 12 + end + elseif code == 0xB9 then + nextP = p + 4 + elseif code >= 0xBB then + if p + 6 > limit then + break + end + local len = readu8(b, p + 4) * 256 + readu8(b, p + 5) + local stop = p + 6 + len + if stop > limit then + stop = limit + end + nextP = stop + if code == 0xBC and len >= 10 then -- program stream map + local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9) + local q = p + 10 + infoLen + if q + 2 <= stop then + local mapLen = readu8(b, q) * 256 + readu8(b, q + 1) + q += 2 + local e = math.min(stop, q + mapLen) + while q + 4 <= e do + local st, sid = readu8(b, q), readu8(b, q + 1) + local il = readu8(b, q + 2) * 256 + readu8(b, q + 3) + types[sid] = st + q += 4 + il + end + end + elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then + -- a PES packet + local q = p + 6 + local pts, dts: number? = nil, nil + local ok = true + if q < stop and readu8(b, q) // 64 == 2 then -- MPEG-2 PES header + if q + 3 > stop then + ok = false + else + local flags = readu8(b, q + 1) + local hlen = readu8(b, q + 2) + local h = q + 3 + if flags >= 0x80 and h + 5 <= stop then + pts = ts(b, h) + if flags // 64 == 3 and h + 10 <= stop then + dts = ts(b, h + 5) + end + end + q = h + hlen + end + else -- MPEG-1 packet header + local n = 0 + while q < stop and readu8(b, q) == 0xFF and n < 16 do + q += 1 + n += 1 + end + if q < stop and readu8(b, q) // 64 == 1 then + q += 2 + end + if q < stop then + local c = readu8(b, q) // 16 + if c == 2 and q + 5 <= stop then + pts = ts(b, q) + q += 5 + elseif c == 3 and q + 10 <= stop then + pts = ts(b, q) + dts = ts(b, q + 5) + q += 10 + elseif readu8(b, q) == 0x0F then + q += 1 + else + ok = false + end + end + end + if ok and q <= stop then + local id = code + local kind, codec = "other", "unknown" + if code == 0xBD then + if q >= stop then + ok = false + else + local sub = readu8(b, q) + id = 0xBD00 + sub + if sub >= 0x80 and sub <= 0x87 then + kind, codec = "audio", "ac3" + q += 4 + elseif sub >= 0x88 and sub <= 0x8F then + kind, codec = "audio", "dts" + q += 4 + elseif sub >= 0xA0 and sub <= 0xA7 then + kind, codec = "audio", "pcm_dvd" + q += 7 + elseif sub >= 0x20 and sub <= 0x3F then + kind, codec = "subtitle", "dvdsub" + q += 1 + else + q += 1 + end + end + elseif code >= 0xE0 then + kind, codec = "video", "mpeg1" + else + kind, codec = "audio", "mp2" + end + local st = types[code] + if st and TYPES[st] then + kind, codec = TYPES[st][1], TYPES[st][2] + end + if ok and q <= stop then + local s = file.streams[id] + if not s then + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } :: Stream + file.streams[id] = s + table.insert(file.order, id) + end + table.insert(s.pes, { + pts = if pts then unwrap(id, pts) else nil, + dts = if dts then unwrap(id + 0x10000, dts) else nil, + offset = q, + size = stop - q, + }) + end + end + if not ok then + file.errors += 1 + end + end + else + -- a start code that is not a system one (stray ES data between packets): resync + file.errors += 1 + end + p = MpegEs.findStart(b, nextP, limit) + end + if packs == 0 and #file.order == 0 then + return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base) + end + return file, nil +end + +return MpegPs +end +__FILES["containers/MpegTs"] = @native function() + + +-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same +-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a +-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections +-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity +-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. +-- +-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } +-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed +-- +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is +-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. +local Crc32 = __include("core/Crc32") + +local MpegTs = {} + +type Stream = { + pid: number, + streamType: number, -- PMT stream_type (0 when the stream was found without a PMT) + kind: string, -- "video" | "audio" | "other" + codec: string, -- "mpeg1video" | "mpeg2video" | "mpegaudio" | "aac" | "h264" | "hevc" | "ac3" | "unknown" ... + program: number, -- program_number (0 without a PMT) + language: string?, -- ISO 639 language descriptor, when present +} + +type Unit = { + pid: number, + kind: string, + codec: string, + streamType: number, + streamId: number, -- PES stream_id (0xE0.. video, 0xC0.. audio) + pts: number?, -- seconds (33-bit 90 kHz clock, unwrapped per PID) + dts: number?, -- seconds; equals pts when the PES carries no DTS + pts90: number?, -- the same in 90 kHz ticks + dts90: number?, + data: buffer, -- the PES payload (one access unit for video as muxed by ffmpeg; one or more frames for audio) + ccError: boolean, -- a continuity counter gap (lost packets) happened inside this unit + randomAccess: boolean, -- the first packet's adaptation field had random_access_indicator set + discontinuity: boolean, -- the first packet's adaptation field had discontinuity_indicator set +} + +type Stats = { + packets: number, + syncLosses: number, -- resyncs (bytes skipped to find 0x47 again) + skippedBytes: number, + teiErrors: number, -- transport_error_indicator packets (dropped) + ccErrors: number, -- continuity counter gaps + duplicates: number, -- duplicate packets (same CC), dropped + crcErrors: number, -- PSI sections with a bad CRC (ignored) + pesErrors: number, -- PES units without a valid header (dropped) + scrambled: number, -- scrambled packets (dropped) + pcr: number?, -- last PCR seen, seconds +} + +type Demuxed = { + video: { Unit }, -- units of the selected video PID (first video stream of the PMT), in stream order + audio: { Unit }, -- units of the selected audio PID + streams: { Stream }, -- every elementary stream, PMT order + units: { Unit }, -- every unit of every PID, in completion order + videoPid: number?, + audioPid: number?, + stats: Stats, +} + +type PesState = { + buf: buffer, + len: number, + active: boolean, + expected: number, -- total PES bytes when PES_packet_length is set, else 0 (ends at the next unit start) + hdrChecked: boolean, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean, + lastPts: number, -- for 33-bit wrap unwrapping + wrapOffset: number, +} + +type SectionState = { buf: buffer, len: number, active: boolean } + +local TS_SIZE = 188 +local SYNC = 0x47 +local MAX_SECTION = 4096 + 188 +local WRAP = 8589934592 -- 2^33 + +local readu8 = buffer.readu8 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift + +local CODECS: { [number]: { string } } = { + [0x01] = { "video", "mpeg1video" }, + [0x02] = { "video", "mpeg2video" }, + [0x03] = { "audio", "mpegaudio" }, + [0x04] = { "audio", "mpegaudio" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x11] = { "audio", "aac_latm" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, + [0x87] = { "audio", "eac3" }, +} + +-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 +@native local function crc32(b: buffer, off: number, n: number): number + return Crc32.msb(b, off, n, 0xFFFFFFFF) +end +MpegTs.crc32 = crc32 + +@native local function u16(b: buffer, p: number): number + return readu8(b, p) * 256 + readu8(b, p + 1) +end + +-- 33-bit timestamp from the 5-byte PES encoding at p +@native local function readTs(b: buffer, p: number): number + local b0 = readu8(b, p) + local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 + local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 + local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0 + return hi + mid * 32768 + lo +end + +local Demuxer = {} +Demuxer.__index = Demuxer + +type Demuxer = typeof(setmetatable( + {} :: { + _pend: buffer, + _pendLen: number, + _pmtPids: { [number]: number }, + _streams: { [number]: Stream }, + _pes: { [number]: PesState }, + _sections: { [number]: SectionState }, + _cc: { [number]: number }, + _queue: { Unit }, + _qhead: number, + _qtail: number, + streams: { Stream }, + stats: Stats, + }, + Demuxer +)) + +@native function MpegTs.new(): Demuxer + local self = setmetatable({ + _pend = buffer.create(64 * 1024), + _pendLen = 0, + _pmtPids = {}, + _streams = {}, + _pes = {}, + _sections = {}, + _cc = {}, + _queue = {}, + _qhead = 1, + _qtail = 0, + streams = {}, + stats = { + packets = 0, + syncLosses = 0, + skippedBytes = 0, + teiErrors = 0, + ccErrors = 0, + duplicates = 0, + crcErrors = 0, + pesErrors = 0, + scrambled = 0, + pcr = nil, + } :: Stats, + }, Demuxer) + return self +end + +-- PSI --------------------------------------------------------------------------------------------------------- + +@native local function addStream(self: Demuxer, pid: number, streamType: number, program: number, language: string?) + local info = CODECS[streamType] + local s = self._streams[pid] + if s == nil then + s = { + pid = pid, + streamType = streamType, + kind = if info then info[1] else "other", + codec = if info then info[2] else "unknown", + program = program, + language = language, + } + self._streams[pid] = s + table.insert(self.streams, s) + else + s.streamType = streamType + s.kind = if info then info[1] else "other" + s.codec = if info then info[2] else "unknown" + s.program = program + s.language = language + end +end + +@native local function parseSection(self: Demuxer, pid: number, b: buffer, n: number) + -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) + if n < 12 then + return + end + if band(readu8(b, 1), 0x80) == 0 then + return -- no section_syntax_indicator: not a PAT / PMT + end + if crc32(b, 0, n) ~= 0 then + self.stats.crcErrors += 1 + return + end + if band(readu8(b, 5), 1) == 0 then + return -- current_next_indicator = 0: a future table + end + local tid = readu8(b, 0) + local stop = n - 4 + if tid == 0x00 and pid == 0 then + local p = 8 + while p + 4 <= stop do + local prog = u16(b, p) + local pmt = band(u16(b, p + 2), 0x1FFF) + if prog ~= 0 then + self._pmtPids[pmt] = prog + end + p += 4 + end + elseif tid == 0x02 and self._pmtPids[pid] ~= nil then + local program = u16(b, 3) + local p = 12 + band(u16(b, 10), 0x0FFF) + while p + 5 <= stop do + local st = readu8(b, p) + local epid = band(u16(b, p + 1), 0x1FFF) + local esl = band(u16(b, p + 3), 0x0FFF) + local d = p + 5 + local dend = math.min(d + esl, stop) + local language: string? = nil + while d + 2 <= dend do + local tag, len = readu8(b, d), readu8(b, d + 1) + if tag == 0x0A and len >= 3 and d + 5 <= dend then + language = buffer.readstring(b, d + 2, 3) + end + d += 2 + len + end + addStream(self, epid, st, program, language) + p += 5 + esl + end + end +end + +@native local function sectionBytes(self: Demuxer, pid: number, s: SectionState, src: buffer, from: number, to: number) + local n = to - from + if n <= 0 then + return + end + if s.len + n > MAX_SECTION then + s.active = false + s.len = 0 + return + end + buffer.copy(s.buf, s.len, src, from, n) + s.len += n + -- every complete section in the buffer + while s.active and s.len >= 3 do + if readu8(s.buf, 0) == 0xFF then + s.active = false -- stuffing: no more sections until the next unit start + s.len = 0 + return + end + local need = 3 + band(u16(s.buf, 1), 0x0FFF) + if s.len < need then + return + end + parseSection(self, pid, s.buf, need) + local rest = s.len - need + if rest > 0 then + buffer.copy(s.buf, 0, s.buf, need, rest) + end + s.len = rest + end +end + +@native local function sectionPayload(self: Demuxer, pid: number, pusi: boolean, b: buffer, pos: number, stop: number) + local s = self._sections[pid] + if s == nil then + s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } + self._sections[pid] = s + end + if pusi then + if pos >= stop then + return + end + local ptr = readu8(b, pos) + pos += 1 + local tail = math.min(pos + ptr, stop) + if s.active then + sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section + end + s.active = true + s.len = 0 + pos = tail + elseif not s.active then + return + end + sectionBytes(self, pid, s, b, pos, stop) +end + +-- PES --------------------------------------------------------------------------------------------------------- + +@native local function completePes(self: Demuxer, pid: number, st: PesState) + st.active = false + local b, len = st.buf, st.len + if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then + self.stats.pesErrors += 1 + return + end + local sid = readu8(b, 3) + local stop = if st.expected > 0 then math.min(st.expected, len) else len + local start = 6 + local pts: number?, dts: number? = nil, nil + if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then + if stop < 9 then + self.stats.pesErrors += 1 + return + end + if band(readu8(b, 6), 0xC0) == 0x80 then + -- MPEG-2 PES header + local flags = readu8(b, 7) + local hl = readu8(b, 8) + start = 9 + hl + if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then + pts = readTs(b, 9) + if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then + dts = readTs(b, 14) + end + end + else + -- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS + local p = 6 + local k = 0 + while p < stop and readu8(b, p) == 0xFF and k < 16 do + p += 1 + k += 1 + end + if p < stop and band(readu8(b, p), 0xC0) == 0x40 then + p += 2 + end + if p < stop then + local c = band(readu8(b, p), 0xF0) + if c == 0x20 and p + 5 <= stop then + pts = readTs(b, p) + p += 5 + elseif c == 0x30 and p + 10 <= stop then + pts = readTs(b, p) + dts = readTs(b, p + 5) + p += 10 + else + p += 1 + end + end + start = p + end + end + if start > stop then + self.stats.pesErrors += 1 + return + end + -- unwrap the 33-bit clock (per PID) + if pts ~= nil then + pts += st.wrapOffset + if st.lastPts >= 0 then + if pts < st.lastPts - WRAP / 2 then + st.wrapOffset += WRAP + pts += WRAP + elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then + st.wrapOffset -= WRAP + pts -= WRAP + end + end + st.lastPts = pts + if dts ~= nil then + dts += st.wrapOffset + if dts > pts + WRAP / 2 then + dts -= WRAP + elseif dts < pts - WRAP / 2 then + dts += WRAP + end + else + dts = pts + end + end + local n = stop - start + local data = buffer.create(n) + if n > 0 then + buffer.copy(data, 0, b, start, n) + end + local s = self._streams[pid] + local kind, codec, streamType + if s then + kind, codec, streamType = s.kind, s.codec, s.streamType + elseif sid >= 0xE0 and sid <= 0xEF then + kind, codec, streamType = "video", "unknown", 0 + elseif sid >= 0xC0 and sid <= 0xDF then + kind, codec, streamType = "audio", "mpegaudio", 0 + else + kind, codec, streamType = "other", "unknown", 0 + end + local unit: Unit = { + pid = pid, + kind = kind, + codec = codec, + streamType = streamType, + streamId = sid, + pts = if pts then pts / 90000 else nil, + dts = if dts then dts / 90000 else nil, + pts90 = pts, + dts90 = dts, + data = data, + ccError = st.ccError, + randomAccess = st.randomAccess, + discontinuity = st.discontinuity, + } + local tail = self._qtail + 1 + self._qtail = tail + self._queue[tail] = unit +end + +@native local function pesPayload( + self: Demuxer, + pid: number, + pusi: boolean, + b: buffer, + pos: number, + stop: number, + ccError: boolean, + randomAccess: boolean, + discontinuity: boolean +) + local st = self._pes[pid] + -- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored + local startCode = pusi + and stop - pos >= 3 + and readu8(b, pos) == 0 + and readu8(b, pos + 1) == 0 + and readu8(b, pos + 2) == 1 + if st == nil then + if not startCode then + return + end + st = { + buf = buffer.create(16 * 1024), + len = 0, + active = false, + expected = 0, + hdrChecked = false, + ccError = false, + randomAccess = false, + discontinuity = false, + lastPts = -1, + wrapOffset = 0, + } + self._pes[pid] = st + end + if ccError and st.active then + st.ccError = true -- packets of the unit in progress were lost + end + if pusi then + if st.active then + completePes(self, pid, st) + end + if not startCode then + if self._streams[pid] ~= nil then + self.stats.pesErrors += 1 + end + return + end + st.active = true + st.len = 0 + st.expected = 0 + st.hdrChecked = false + st.ccError = false + st.randomAccess = randomAccess + st.discontinuity = discontinuity + elseif not st.active then + return + end + local n = stop - pos + if n <= 0 then + return + end + if st.len + n > buffer.len(st.buf) then + local cap = buffer.len(st.buf) * 2 + while cap < st.len + n do + cap *= 2 + end + if cap > 64 * 1024 * 1024 then + st.active = false -- runaway unit (no unit start for 64 MB): drop it + st.len = 0 + self.stats.pesErrors += 1 + return + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, st.buf, 0, st.len) + st.buf = nb + end + buffer.copy(st.buf, st.len, b, pos, n) + st.len += n + if not st.hdrChecked and st.len >= 6 then + st.hdrChecked = true + local plen = u16(st.buf, 4) + if plen > 0 then + st.expected = 6 + plen + end + end + if st.expected > 0 and st.len >= st.expected then + completePes(self, pid, st) + end +end + +-- packets ----------------------------------------------------------------------------------------------------- + +@native local function packet(self: Demuxer, b: buffer, pk: number) + local stats = self.stats + stats.packets += 1 + local b1 = readu8(b, pk + 1) + if band(b1, 0x80) ~= 0 then + stats.teiErrors += 1 + return + end + local pusi = band(b1, 0x40) ~= 0 + local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2) + if pid == 0x1FFF then + return + end + local b3 = readu8(b, pk + 3) + if band(b3, 0xC0) ~= 0 then + stats.scrambled += 1 + return + end + local afc = band(rshift(b3, 4), 3) + local cc = band(b3, 15) + if afc == 0 then + return + end + local pos = pk + 4 + local stop = pk + TS_SIZE + local discontinuity, randomAccess = false, false + if afc >= 2 then + local afl = readu8(b, pos) + pos += 1 + if afl > 183 then + return + end + if afl > 0 then + local flags = readu8(b, pos) + discontinuity = band(flags, 0x80) ~= 0 + randomAccess = band(flags, 0x40) ~= 0 + if band(flags, 0x10) ~= 0 and afl >= 7 then + local base = readu8(b, pos + 1) * 33554432 + + readu8(b, pos + 2) * 131072 + + readu8(b, pos + 3) * 512 + + readu8(b, pos + 4) * 2 + + rshift(readu8(b, pos + 5), 7) + local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6) + stats.pcr = base / 90000 + ext / 27000000 + end + end + pos += afl + if afc == 2 then + if discontinuity then + self._cc[pid] = nil + end + return -- adaptation field only: the counter does not advance + end + end + -- continuity counter + local ccError = false + local last = self._cc[pid] + if last ~= nil and not discontinuity then + if cc == last then + stats.duplicates += 1 + return + elseif cc ~= band(last + 1, 15) then + ccError = true + stats.ccErrors += 1 + end + end + self._cc[pid] = cc + if pid == 0 or self._pmtPids[pid] ~= nil then + sectionPayload(self, pid, pusi, b, pos, stop) + elseif pid >= 0x10 then + pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity) + end +end + +-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for +-- pull(). Returns false for a bad argument. +@native function Demuxer.push(self: Demuxer, data: buffer | string, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local off = math.max(0, math.floor(offset or 0)) + local total = buffer.len(src) + if off > total then + return false + end + local n = math.min(math.floor(len or (total - off)), total - off) + if n < 0 then + return false + end + -- append to the pending bytes + local need = self._pendLen + n + if need > buffer.len(self._pend) then + local cap = buffer.len(self._pend) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, self._pend, 0, self._pendLen) + self._pend = nb + end + if n > 0 then + buffer.copy(self._pend, self._pendLen, src, off, n) + end + self._pendLen = need + local b, avail = self._pend, self._pendLen + local p = 0 + while p + TS_SIZE <= avail do + if readu8(b, p) ~= SYNC then + -- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data) + self.stats.syncLosses += 1 + local q = p + 1 + local found = -1 + local waitAt = -1 + while q < avail do + if readu8(b, q) == SYNC then + if q + TS_SIZE < avail then + if readu8(b, q + TS_SIZE) == SYNC then + found = q + break + end + elseif q + TS_SIZE == avail then + found = q + break + else + waitAt = q -- not enough bytes to confirm: wait for more + break + end + end + q += 1 + end + if found >= 0 then + self.stats.skippedBytes += found - p + p = found + elseif waitAt >= 0 then + self.stats.skippedBytes += waitAt - p + p = waitAt + break + else + self.stats.skippedBytes += avail - p + p = avail + break + end + else + packet(self, b, p) + p += TS_SIZE + end + end + local rest = avail - p + if rest > 0 and p > 0 then + buffer.copy(b, 0, b, p, rest) + end + self._pendLen = rest + return true +end + +-- The next completed unit (any PID), or nil. +@native function Demuxer.pull(self: Demuxer): Unit? + local q = self._queue + local h = self._qhead + local u = q[h] + if u == nil then + return nil + end + q[h] = nil :: any + h += 1 + if h > self._qtail then + table.clear(q) + h = 1 + self._qtail = 0 + end + self._qhead = h + return u +end + +-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next +-- unit start). Units still queue up for pull(). +@native function Demuxer.flush(self: Demuxer) + local pids = {} + for pid, st in self._pes do + if st.active then + table.insert(pids, pid) + end + end + table.sort(pids) + for _, pid in pids do + completePes(self, pid, self._pes[pid]) + end + self._pendLen = 0 +end + +-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). +@native function Demuxer.reset(self: Demuxer) + self._pendLen = 0 + for _, st in self._pes do + st.active = false + st.len = 0 + st.lastPts = -1 + st.wrapOffset = 0 + end + for _, s in self._sections do + s.active = false + s.len = 0 + end + table.clear(self._cc) + table.clear(self._queue) + self._qhead = 1 + self._qtail = 0 +end + +-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). +@native function Demuxer.streamFor(self: Demuxer, kind: string): Stream? + for _, s in self.streams do + if s.kind == kind then + return s + end + end + return nil +end + +type DemuxOptions = { videoPid: number?, audioPid: number? } + +-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / +-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / +-- audio (PES stream_id). Never throws; a bad argument gives empty lists. +@native function MpegTs.demux(data: buffer | string, opts: DemuxOptions?): Demuxed + local d = MpegTs.new() + d:push(data) + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + local videoPid = opts and opts.videoPid + local audioPid = opts and opts.audioPid + if videoPid == nil then + local s = d:streamFor("video") + videoPid = if s then s.pid else nil + end + if audioPid == nil then + local s = d:streamFor("audio") + audioPid = if s then s.pid else nil + end + for _, u in units do + if videoPid == nil and u.kind == "video" then + videoPid = u.pid + end + if audioPid == nil and u.kind == "audio" then + audioPid = u.pid + end + end + local video, audio = {}, {} + for _, u in units do + if u.pid == videoPid then + table.insert(video, u) + elseif u.pid == audioPid then + table.insert(audio, u) + end + end + return { + video = video, + audio = audio, + streams = d.streams, + units = units, + videoPid = videoPid, + audioPid = audioPid, + stats = d.stats, + } +end + +-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). +@native function MpegTs.concat(units: { Unit }): buffer + local n = 0 + for _, u in units do + n += buffer.len(u.data) + end + local out = buffer.create(n) + local p = 0 + for _, u in units do + local l = buffer.len(u.data) + buffer.copy(out, p, u.data, 0, l) + p += l + end + return out +end + +return MpegTs +end +__FILES["containers/Ogg"] = @native function() + + + +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 +-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and +-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture +-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); +-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad +-- input gives nil, err). +-- +-- local demux, err = Ogg.open(buf) +-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end +-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator +-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil +-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) +-- +-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) +-- local s = mux:stream(serial?) -- one logical stream +-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages +-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes +-- local file = mux:finish() -- every stream ends with an eos page +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") +local Mux = __include("containers/Ogg/Mux") + +local readu8 = buffer.readu8 +type PageInfo = any -- Page.Info (the sibling module is untyped here: required through `script` in Roblox) + +local Ogg = {} +Ogg.Page = Page +Ogg.Mux = Mux +Ogg.muxer = Mux.new + +type Packet = { + data: buffer, -- the packet bytes are data[offset .. offset + size - 1] + offset: number, + size: number, + granule: number, -- the page granule if this is the last packet finishing on its page, else -1 + pageGranule: number, -- the granule of the page the packet finishes on (may be -1) + bos: boolean, -- first packet of the stream + eos: boolean, -- last packet of the stream (last packet finishing on an eos page) + pageOffset: number, -- byte offset of the page the packet finishes on + gap: boolean, -- data was lost before this packet (a missing page / bad CRC in between) +} + +type Stream = { + serial: number, + codec: string, -- "opus" | "flac" | "vorbis" | "theora" | "speex" | "skeleton" | "flac-old" | "unknown" + firstPacket: buffer, -- a copy of the identification packet + bosOffset: number, -- byte offset of the bos page + lastGranule: number, -- the last known granule of the stream (-1 if none) +} + +-- Reader: the packet cursor of one logical stream +local Reader = {} +Reader.__index = Reader + +@native local function newReader(d: any, serial: number, start: number): any + return setmetatable({ + demux = d, + buf = d.buf, + serial = serial, + start = start, -- the bos page offset + pagePos = start, -- where to look for the next page + page = nil :: PageInfo?, + seg = 0, -- next segment index on the page + dataPos = 0, -- byte offset of the next segment's data + lastComplete = -1, -- index of the last segment ending a packet on this page + firstPacketOnPage = true, + parts = {} :: { number }, -- pending partial packet: offset, len pairs + partLen = 0, + lastSeq = -1, + gap = false, + ended = false, + total = 0, + }, Reader) +end + +-- Load the next page of this serial; false at the end of the data +@native function Reader._nextPage(self: any): boolean + local b, d = self.buf, self.demux + while true do + local p = Page.find(b, self.pagePos, nil, d.verify) + if not p then + return false + end + self.pagePos = p.offset + p.size + if p.serial == self.serial then + if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then + -- a page is missing: drop the partial packet + self.parts, self.partLen = {}, 0 + self.gap = true + end + self.lastSeq = p.sequence + self.page = p + self.seg = 0 + self.dataPos = p.offset + p.headerSize + self.firstPacketOnPage = true + local lc = -1 + local base = p.offset + 27 + for i = 0, p.nsegs - 1 do + if readu8(b, base + i) < 255 then + lc = i + end + end + self.lastComplete = lc + if p.continued then + if self.partLen == 0 and #self.parts == 0 then + -- the start of this packet is not ours (after a seek or a loss): skip its tail + local s = 0 + while s < p.nsegs do + local l = readu8(b, base + s) + self.dataPos += l + s += 1 + if l < 255 then + break + end + end + self.seg = s + self.firstPacketOnPage = false + end + elseif #self.parts > 0 then + -- a fresh packet while one was pending: the pending one is lost + self.parts, self.partLen = {}, 0 + self.gap = true + end + return true + end + end +end + +-- The next packet, or nil at the end of the stream +@native function Reader.nextPacket(self: any): Packet? + if self.ended then + return nil + end + local b = self.buf + while true do + local p = self.page + if p and self.seg < p.nsegs then + local base = p.offset + 27 + local start = self.dataPos + local len = 0 + local s = self.seg + local complete = false + while s < p.nsegs do + local l = readu8(b, base + s) + s += 1 + len += l + if l < 255 then + complete = true + break + end + end + self.seg = s + self.dataPos = start + len + if complete then + local data, off, size = b, start, len + local parts = self.parts + if #parts > 0 then + size = self.partLen + len + data = buffer.create(size) + off = 0 + local o = 0 + for i = 1, #parts, 2 do + buffer.copy(data, o, b, parts[i], parts[i + 1]) + o += parts[i + 1] + end + buffer.copy(data, o, b, start, len) + self.parts, self.partLen = {}, 0 + end + local last = (s - 1) == self.lastComplete + local pkt = { + data = data, + offset = off, + size = size, + granule = if last then p.granule else -1, + pageGranule = p.granule, + bos = p.bos and self.firstPacketOnPage, + eos = p.eos and last, + pageOffset = p.offset, + gap = self.gap, + } + self.firstPacketOnPage = false + self.gap = false + self.total += 1 + if pkt.eos then + self.ended = true + end + return pkt + else + -- the packet continues on a later page + table.insert(self.parts, start) + table.insert(self.parts, len) + self.partLen += len + end + else + if p and p.eos then + self.ended = true + return nil + end + if not self:_nextPage() then + self.ended = true + return nil + end + end + end +end + +-- Back to the start of the stream (the identification packet comes next) +@native function Reader.rewind(self: any) + self.pagePos = self.start + self.page = nil + self.seg = 0 + self.parts, self.partLen = {}, 0 + self.lastSeq = -1 + self.gap = false + self.ended = false +end + +-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them +@native function Reader._at(self: any, p: PageInfo) + self:rewind() + self.pagePos = p.offset + self:_nextPage() -- loads p (it is a valid page of this serial) + local b = self.buf + local base = p.offset + 27 + local dp = p.offset + p.headerSize + for i = 0, self.lastComplete do + dp += readu8(b, base + i) + end + self.seg = self.lastComplete + 1 + self.dataPos = dp + self.parts, self.partLen = {}, 0 + self.firstPacketOnPage = false + self.gap = false + self.ended = false +end + +-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last +-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the +-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start +-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +@native function Reader.seekGranule(self: any, g: number): (number?, Err.Err?) + local b, d = self.buf, self.demux + local serial = self.serial + local verify = d.verify + @native local function nextOf(pos: number, limit: number?): PageInfo? + while true do + local p = Page.find(b, pos, limit, verify) + if not p then + return nil + end + if p.serial == serial and p.granule ~= -1 then + return p + end + pos = p.offset + p.size + end + end + local lo, hi = self.start, buffer.len(b) + local best: PageInfo? = nil + while hi - lo > 65536 do + local mid = (lo + hi) // 2 + local p = nextOf(mid, hi) + if p and p.granule <= g then + best = p + lo = p.offset + else + hi = mid + end + end + local pos = lo + while true do + local p = nextOf(pos) + if not p or p.granule > g then + break + end + best = p + pos = p.offset + p.size + end + if not best then + self:rewind() + return -1, nil + end + self:_at(best) + return best.granule, nil +end + +-- Demux +local Demux = {} +Demux.__index = Demux + +-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied +-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = +-- true lists every bos page in the file (chained streams), not just the first group +@native function Ogg.open(src: any, opts: { verify: boolean?, scanAll: boolean? }?): (any, Err.Err?) + local buf: buffer + if type(src) == "buffer" then + buf = src + elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + buf = src.buf + else + local n = math.max(0, src.limit - src.base) + buf = buffer.create(n) + buffer.copy(buf, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader") + end + local verify = not (opts and opts.verify == false) + local first = Page.find(buf, 0, nil, verify) + if not first then + return nil, Err.new(Err.CORRUPT, "no Ogg page found") + end + local d = setmetatable({ + buf = buf, + size = buffer.len(buf), + verify = verify, + _streams = {} :: { Stream }, + _bySerial = {} :: { [number]: Stream }, + _readers = {} :: { [number]: any }, + _lastDone = false, + }, Demux) + -- the bos pages (at the start of the file, and later ones for chains if scanAll) + local pos = first.offset + local scanAll = opts and opts.scanAll + while true do + local p = Page.find(buf, pos, nil, verify) + if not p then + break + end + if p.bos and not d._bySerial[p.serial] then + local st = { + serial = p.serial, + codec = "unknown", + firstPacket = buffer.create(0), + bosOffset = p.offset, + lastGranule = -1, + } + table.insert(d._streams, st) + d._bySerial[p.serial] = st + local r = newReader(d, p.serial, p.offset) + local pk = r:nextPacket() + if pk then + local c = buffer.create(pk.size) + buffer.copy(c, 0, pk.data, pk.offset, pk.size) + st.firstPacket = c + st.codec = Page.codec(c, 0, pk.size) + end + elseif not p.bos and not scanAll then + break + end + pos = p.offset + p.size + end + if #d._streams == 0 then + return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page") + end + return d, nil +end + +-- Scan backwards from the end for each stream's last granule +@native function Demux._scanLast(self: any) + if self._lastDone then + return + end + self._lastDone = true + local b = self.buf + local need = #self._streams + local pos = self.size - 27 + while need > 0 do + local p = Page.findBack(b, pos, 0, self.verify) + if not p then + break + end + local st = self._bySerial[p.serial] + if st and st.lastGranule == -1 and p.granule ~= -1 then + st.lastGranule = p.granule + need -= 1 + end + pos = p.offset - 1 + end +end + +-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } +@native function Demux.streams(self: any): { Stream } + self:_scanLast() + return self._streams +end + +@native function Demux.stream(self: any, serial: number): Stream? + self:_scanLast() + return self._bySerial[serial] +end + +-- The serial of the first stream of a codec, or nil +@native function Demux.find(self: any, codec: string): number? + for _, s in self._streams do + if s.codec == codec then + return s.serial + end + end + return nil +end + +-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err +@native function Demux.reader(self: any, serial: number): (any, Err.Err?) + local r = self._readers[serial] + if r then + return r, nil + end + local st = self._bySerial[serial] + if not st then + return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial)) + end + r = newReader(self, serial, st.bosOffset) + self._readers[serial] = r + return r, nil +end + +@native function Demux.nextPacket(self: any, serial: number): Packet? + local r = self:reader(serial) + return if r then r:nextPacket() else nil +end + +@native function Demux.seekGranule(self: any, serial: number, g: number): (number?, Err.Err?) + local r, err = self:reader(serial) + if not r then + return nil, err + end + return r:seekGranule(g) +end + +@native function Demux.rewind(self: any, serial: number) + local r = self:reader(serial) + if r then + r:rewind() + end +end + +-- for p in demux:packets(serial) do ... end (continues from the stream's current position) +@native function Demux.packets(self: any, serial: number): () -> Packet? + local r = self:reader(serial) + return @native function() + return if r then r:nextPacket() else nil + end +end + +-- Copy a packet's bytes into a fresh buffer of its own +@native function Ogg.copy(p: Packet): buffer + local c = buffer.create(p.size) + buffer.copy(c, 0, p.data, p.offset, p.size) + return c +end + +return Ogg +end +__FILES["containers/Ogg/Mux"] = @native function() + + + +-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in rosetta. +-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or +-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last +-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages +-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. +-- +-- local mux = Mux.new({ pageSize = 4096 }) +-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) +-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page +-- s:packet(tags, 0, { flush = true }) +-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) +-- local out = mux:finish() -- closes every stream with an eos page +-- +-- Never throws: a bad argument returns false, Err. +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") + +local CRC = Page.CRC_TABLE +local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32 +local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift + +local Mux = {} +Mux.__index = Mux +local Stream = {} +Stream.__index = Stream + +type Options = { + pageSize: number?, -- close a page once its data reaches this many bytes (default 4096; at most 255 * 255) +} +type PacketOptions = { + flush: boolean?, -- close the page after this packet (headers; default false) + eos: boolean?, -- this is the stream's last packet (default false: finish() writes an empty eos page if needed) +} + +-- new(opts?) -> Mux +@native function Mux.new(opts: Options?): any + local size = opts and opts.pageSize or 4096 + if type(size) ~= "number" or size < 1 then + size = 4096 + end + return setmetatable({ + pageSize = math.min(size, 255 * 255), + chunks = {} :: { buffer }, + total = 0, + streams = {} :: { any }, + nextSerial = 1, + }, Mux) +end + +-- stream(serial?) -> Stream (serials must be unique in the file) +@native function Mux.stream(self: any, serial: number?): any + local sr = serial or self.nextSerial + self.nextSerial = math.max(self.nextSerial, sr + 1) + local s = setmetatable({ + mux = self, + serial = sr % 4294967296, + seq = 0, + lacing = {} :: { number }, + parts = {} :: { any }, -- buffer, offset, length triples of the page data + dataLen = 0, + granule = -1, + continued = false, -- the page being built starts with the tail of a packet + first = true, + ended = false, + lastGranule = -1, + }, Stream) + table.insert(self.streams, s) + return s +end + +-- the CRC of a page (the crc field written as zero) +@native local function crc(b: buffer, n: number): number + local c = 0 + for i = 0, n - 1 do + c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) + end + return c +end + +-- close the page being built (also when empty, for eos) +@native function Stream._flush(self: any, eos: boolean) + local nseg = #self.lacing + local n = 27 + nseg + self.dataLen + local b = buffer.create(n) + buffer.writestring(b, 0, "OggS") + local flags = (if self.continued then 1 else 0) + (if self.first then 2 else 0) + (if eos then 4 else 0) + writeu8(b, 5, flags) + local g = self.granule + if g < 0 then + writeu32(b, 6, 0xFFFFFFFF) + writei32(b, 10, -1) + else + writeu32(b, 6, g % 4294967296) + writeu32(b, 10, (g // 4294967296) % 4294967296) + end + writeu32(b, 14, self.serial) + writeu32(b, 18, self.seq % 4294967296) + writeu8(b, 26, nseg) + for i = 1, nseg do + writeu8(b, 26 + i, self.lacing[i]) + end + local o = 27 + nseg + local parts = self.parts + for i = 1, #parts, 3 do + buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2]) + o += parts[i + 2] + end + writeu32(b, 22, crc(b, n)) + local m = self.mux + table.insert(m.chunks, b) + m.total += n + self.seq += 1 + self.first = false + self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1 + self.continued = false + if eos then + self.ended = true + end +end + +-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet +-- (-1: unknown, not recommended); offset / length select a range of data. +@native function Stream.packet(self: any, data: any, granule: number, opts: PacketOptions?, offset: number?, length: number?): (boolean, Err.Err?) + if self.ended then + return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return false, Err.new(Err.ARG, "packet: data must be a buffer or a string") + end + if type(granule) ~= "number" then + return false, Err.new(Err.ARG, "packet: granule must be a number") + end + local off = offset or 0 + local len = length or (buffer.len(b) - off) + if off < 0 or len < 0 or off + len > buffer.len(b) then + return false, Err.new(Err.ARG, "packet: range outside the buffer") + end + local pageSize = self.mux.pageSize + local left = len + local pos = off + -- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255) + while true do + if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then + self:_flush(false) + self.continued = pos > off -- the next page starts inside this packet + end + local seg = math.min(left, 255) + table.insert(self.lacing, seg) + if seg > 0 then + table.insert(self.parts, b) + table.insert(self.parts, pos) + table.insert(self.parts, seg) + end + self.dataLen += seg + pos += seg + left -= seg + if seg < 255 then + break + end + end + if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page + self.granule = granule + self.lastGranule = granule + end + local eos = opts and opts.eos or false + if eos then + self:_flush(true) + elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then + self:_flush(false) + end + return true, nil +end + +-- flush(): close the current page now (if it holds anything) +@native function Stream.flush(self: any) + if not self.ended and #self.lacing > 0 then + self:_flush(false) + end +end + +-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) +@native function Mux.finish(self: any): buffer + for _, s in self.streams do + if not s.ended then + if #s.lacing == 0 then + s.granule = s.lastGranule + end + s:_flush(true) + end + end + local out = buffer.create(self.total) + local o = 0 + for _, c in self.chunks do + buffer.copy(out, o, c, 0, buffer.len(c)) + o += buffer.len(c) + end + return out +end + +return Mux +end +__FILES["containers/Ogg/Page"] = @native function() + + + +-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header +-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, +-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. +-- +-- A page header (27 bytes + segment table): +-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) +-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data +local Crc32 = __include("core/Crc32") +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 +local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift + +local Page = {} + +type Info = { + offset: number, -- byte offset of "OggS" + size: number, -- header + segment table + data + headerSize: number, -- 27 + segment count + nsegs: number, + flags: number, + continued: boolean, + bos: boolean, + eos: boolean, + granule: number, -- -1 when no packet finishes on this page + serial: number, + sequence: number, +} + +-- CRC table, MSB-first (core/Crc32) +local CRC = Crc32.MSB_TABLE +Page.CRC_TABLE = CRC + +-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc +@native local function crcRange(b: buffer, from: number, to: number, crc: number): number + for i = from, to - 1 do + crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) + end + return crc +end + +-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +@native function Page.crc32(b: buffer, offset: number?, len: number?): number + local o = offset or 0 + local n = len or (buffer.len(b) - o) + if o < 0 or n < 0 or o + n > buffer.len(b) then + return 0 + end + return crcRange(b, o, o + n, 0) +end + +-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", +-- "version", "crc"). verify = false skips the CRC check. +@native function Page.parse(b: buffer, pos: number, verify: boolean?): (Info?, string?) + local size = buffer.len(b) + if pos < 0 or pos + 27 > size then + return nil, "short" + end + if readu32(b, pos) ~= 0x5367674F then -- "OggS" + return nil, "magic" + end + if readu8(b, pos + 4) ~= 0 then + return nil, "version" + end + local nsegs = readu8(b, pos + 26) + local hsize = 27 + nsegs + if pos + hsize > size then + return nil, "short" + end + local dlen = 0 + for i = pos + 27, pos + hsize - 1 do + dlen += readu8(b, i) + end + local total = hsize + dlen + if pos + total > size then + return nil, "short" + end + if verify ~= false then + local c = crcRange(b, pos, pos + 22, 0) + for _ = 1, 4 do + c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1]) + end + c = crcRange(b, pos + 26, pos + total, c) + if c ~= readu32(b, pos + 22) then + return nil, "crc" + end + end + local flags = readu8(b, pos + 5) + return { + offset = pos, + size = total, + headerSize = hsize, + nsegs = nsegs, + flags = flags, + continued = band(flags, 1) ~= 0, + bos = band(flags, 2) ~= 0, + eos = band(flags, 4) ~= 0, + granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6), + serial = readu32(b, pos + 14), + sequence = readu32(b, pos + 18), + }, nil +end + +-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the +-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. +@native function Page.find(b: buffer, pos: number, limit: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lim = math.min(limit or size, size - 27 + 1) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos += 1 + end + return nil +end + +-- The last valid page starting at an offset in [floor, pos] (searching backwards). +@native function Page.findBack(b: buffer, pos: number, floor: number?, verify: boolean?): Info? + local size = buffer.len(b) + local lo = math.max(floor or 0, 0) + if pos > size - 27 then + pos = size - 27 + end + while pos >= lo do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos -= 1 + end + return nil +end + +-- The identification of a codec from a stream's first packet (the bos page's packet) +@native function Page.codec(b: buffer, off: number, len: number): string + @native local function is(s: string, at: number): boolean + if at + #s > len then + return false + end + for i = 1, #s do + if readu8(b, off + at + i - 1) ~= string.byte(s, i) then + return false + end + end + return true + end + if is("OpusHead", 0) then + return "opus" + elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then + return "flac" + elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then + return "vorbis" + elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then + return "theora" + elseif is("Speex ", 0) then + return "speex" + elseif is("fishead", 0) then + return "skeleton" + elseif is("fLaC", 0) then + return "flac-old" -- pre-1.1.1 Ogg FLAC mapping + end + return "unknown" +end + +return Page +end +__FILES["containers/Riff"] = function() + +-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently +-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from +-- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. +-- +-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer +-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false +-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf +-- local c = Riff.find(f, "fmt ") +-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type) +-- +-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX) +-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } }) +-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB +-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB +-- +-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past +-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a +-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of +-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Riff = {} + +type Chunk = { + id: string, + start: number, -- absolute offset of the chunk header + offset: number, -- absolute offset of the body in the file's buffer + size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks + declared: number, -- the raw size field + avail: number, -- body bytes present in the file (<= size) + truncated: boolean, -- declared past the end of the file + streamed: boolean, -- an open-ended chunk (size 0 / 0xFFFFFFFF up to the end) +} +type File = { + container: string, -- "RIFF" | "RIFX" | "RF64" (BW64 reads as RF64) + form: string, -- the form type: "WAVE", "AVI ", "WEBP", ... + bigEndian: boolean, + buf: buffer, + base: number, -- absolute offset of the file's first byte + limit: number, -- absolute offset past its last byte + size: number, -- the RIFF size field (ds64-resolved) + chunks: { Chunk }, + ds64: { riffSize: number, dataSize: number, sampleCount: number, table: { [string]: number } }?, +} +type ReadOptions = { + openEnded: { [string]: boolean }?, -- chunk ids whose size 0 / 0xFFFFFFFF means "to the end" (wav: data) + maxChunks: number?, -- stop after this many chunks (default 100000) +} + +-- ------------------------------------------------------------------------------------------------ read +local function u32(b: buffer, o: number, be: boolean): number + local v = readu32(b, o) + return if be then bit32.byteswap(v) else v +end + +-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil +function Riff.sniff(r: any): string? + local magic = r:peek(4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil + end + local form = r:peek(4, 8) + return if #form == 4 then form else nil +end + +-- walk(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2, +-- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64) +local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any): { Chunk } + local layout: Chunks.Layout = { + bigEndian = be, + pad = 2, + lenientPad = true, + openEnded = opts and opts.openEnded, + maxChunks = opts and opts.maxChunks, + resize = if ds64 + then function(id: string, declared: number): number? + if declared ~= 0xFFFFFFFF then + return nil + end + return if id == "data" then ds64.dataSize else ds64.table[id] + end + else nil, + } + return Chunks.walk(b, p, limit, layout) :: any +end + +-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. +function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) + local r = if type(src) == "buffer" then Bytes.reader(src) else src + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader") + end + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base) + end + local magic = readstring(b, base, 4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base) + end + local be = magic == "RIFX" + local f: File = { + container = if magic == "BW64" then "RF64" else magic, + form = readstring(b, base + 8, 4), + bigEndian = be, + buf = b, + base = base, + limit = limit, + size = u32(b, base + 4, be), + chunks = {}, + ds64 = nil, + } + -- RF64: the ds64 chunk comes first + if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then + local sz = readu32(b, base + 16) + local o = base + 20 + if sz >= 24 and o + 24 <= limit then + local d = { + riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296, + dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296, + sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296, + table = {} :: { [string]: number }, + } + if sz >= 28 and o + 28 <= limit then + local n = readu32(b, o + 24) + local q = o + 28 + for _ = 1, math.min(n, 1000) do + if q + 12 > limit or q + 12 > o + sz then + break + end + d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296 + q += 12 + end + end + f.ds64 = d + if f.size == 0xFFFFFFFF then + f.size = d.riffSize + end + end + end + f.chunks = walk(b, base + 12, limit, be, opts, f.ds64) + return f, nil +end + +-- find(file, id, from?) -> the first chunk with that id (after index from), and its index +function Riff.find(f: File, id: string, from: number?): (Chunk?, number?) + for i = (from or 0) + 1, #f.chunks do + if f.chunks[i].id == id then + return f.chunks[i], i + end + end + return nil, nil +end + +-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil +function Riff.listType(f: File, c: Chunk): string? + if c.avail < 4 then + return nil + end + return readstring(f.buf, c.offset, 4) +end + +-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type) +function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } + if c.avail < 4 then + return {} + end + return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) +end + +-- body(file, chunk) -> a Reader over the chunk's available body +function Riff.body(f: File, c: Chunk): Bytes.Reader + return Bytes.reader(f.buf, c.offset, c.avail) +end + +-- u16 / u32 in the file's byte order (for chunk bodies) +function Riff.u16(f: File, o: number): number + if f.bigEndian then + return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) + end + return readu16(f.buf, o) +end +function Riff.u32(f: File, o: number): number + return u32(f.buf, o, f.bigEndian) +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +type WriteOptions = { + bigEndian: boolean?, -- RIFX (default false) + rf64: (boolean | "auto")?, -- true: always RF64; false: never (sizes over 4 GiB are an error); default "auto" + sampleCount: number?, -- the ds64 sample count (RF64 WAVE: frames) + rf64Threshold: number?, -- "auto" switches to RF64 when the RIFF size would pass this (default 0xFFFFFFFF) +} + +-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file +function Riff.writer(form: string, opts: WriteOptions?): any + return setmetatable({ + form = string.sub(form .. " ", 1, 4), + be = opts and opts.bigEndian or false, + rf64 = if opts and opts.rf64 ~= nil then opts.rf64 else "auto", + sampleCount = opts and opts.sampleCount or 0, + threshold = opts and opts.rf64Threshold or 0xFFFFFFFF, + chunks = {} :: { any }, + }, Writer) +end + +-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a +-- list of buffers written one after the other (a data chunk bigger than one buffer) +function Writer.chunk(self: any, id: string, body: any, offset: number?, length: number?) + local parts = {} + local n = 0 + if type(body) == "table" then + for _, b in body do + table.insert(parts, { b, 0, buffer.len(b) }) + n += buffer.len(b) + end + else + local b: buffer = if type(body) == "string" then buffer.fromstring(body) else body + local o = offset or 0 + n = length or (buffer.len(b) - o) + parts[1] = { b, o, n } + end + table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) +end + +-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style) +function Writer.list(self: any, listType: string, items: { { any } }) + local w = Bytes.writer() + w:string(string.sub(listType .. " ", 1, 4)) + for _, it in items do + local v = it[2] + local data: buffer = if type(v) == "string" then buffer.fromstring(v .. "\0") else v + local n = buffer.len(data) + w:string(string.sub(it[1] .. " ", 1, 4)) + if self.be then + w:u32be(n) + else + w:u32le(n) + end + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + end + self:chunk("LIST", w:finish()) +end + +-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied) +function Writer.finish(self: any, opts: { parts: boolean? }?): (any, Err.Err?) + local total = 4 -- the form type + local big = false + local dataSize = 0 + for _, c in self.chunks do + total += 8 + c.length + c.length % 2 + if c.length > 0xFFFFFFFE then + big = true + end + if c.id == "data" then + dataSize = c.length + end + end + local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold)) + if not rf64 and (big or total > 0xFFFFFFFF) then + return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64") + end + if rf64 and self.be then + return nil, Err.new(Err.ARG, "RF64 is little-endian only") + end + if rf64 then + total += 36 -- ds64 + end + local asParts = opts and opts.parts + if not asParts and total + 8 > 0x40000000 then + return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })") + end + local out: { buffer } = {} + local w = Bytes.writer(if asParts then 256 else total + 8) + local function size32(v: number) + if self.be then + w:u32be(v) + else + w:u32le(v) + end + end + if rf64 then + w:string("RF64") + w:u32le(0xFFFFFFFF) + w:string(self.form) + w:string("ds64") + w:u32le(28) + w:u64le(total) + w:u64le(dataSize) + w:u64le(self.sampleCount) + w:u32le(0) -- no table: only data may be over 4 GiB + else + w:string(if self.be then "RIFX" else "RIFF") + size32(total) + w:string(self.form) + end + for _, c in self.chunks do + w:string(c.id) + if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then + w:u32le(0xFFFFFFFF) + else + size32(c.length) + end + for _, p in c.parts do + if asParts then + table.insert(out, w:finish()) + w = Bytes.writer(64) + if p[2] == 0 and p[3] == buffer.len(p[1]) then + table.insert(out, p[1]) + else + local cp = buffer.create(p[3]) + buffer.copy(cp, 0, p[1], p[2], p[3]) + table.insert(out, cp) + end + else + w:bytes(p[1], p[2], p[3]) + end + end + if c.length % 2 == 1 then + w:u8(0) + end + end + if asParts then + if w:tell() > 0 then + table.insert(out, w:finish()) + end + return out, nil + end + return w:finish(), nil +end + +return Riff +end +__FILES["containers/Tar"] = function() + +-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles +-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, +-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, +-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar +-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, +-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX +-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- +-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). +-- +-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } +-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Tar = {} + +type Entry = { + name: string, + size: number, + type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ... + dir: boolean, + mode: number, + uid: number, + gid: number, + mtime: number, + link: string?, + uname: string?, + gname: string?, + offset: number, -- absolute offset of the data in the buffer + pax: { [string]: string }?, +} + +local BLOCK = 512 + +local function zeros(b: buffer, o: number): boolean + for i = 0, BLOCK - 1, 4 do + if buffer.readu32(b, o + i) ~= 0 then + return false + end + end + return true +end + +-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte) +local function number(b: buffer, o: number, n: number): number? + local first = buffer.readu8(b, o) + if first >= 0x80 then + local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative + for i = 1, n - 1 do + v = v * 256 + buffer.readu8(b, o + i) + end + return v + end + local s = buffer.readstring(b, o, n) + s = string.match(s, "^[ %z]*([0-7]*)") or "" + if s == "" then + return 0 + end + return tonumber(s, 8) +end + +local function str(b: buffer, o: number, n: number): string + local s = buffer.readstring(b, o, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function checksum(b: buffer, o: number): (number, number) + local u, s = 0, 0 + for i = 0, BLOCK - 1 do + local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i) + u += v + s += if v >= 128 then v - 256 else v + end + return u, s +end + +-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum +function Tar.valid(b: buffer, o: number): boolean + if o + BLOCK > buffer.len(b) or zeros(b, o) then + return false + end + local want = number(b, o + 148, 8) + local u, s = checksum(b, o) + return want == u or want == s +end + +-- pax records "len key=value\n" -> { key = value } +local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean + local s = buffer.readstring(b, o, n) + local p = 1 + while p <= #s do + if string.byte(s, p) == 0 then + break + end + local len = string.match(s, "^(%d+) ", p) + if not len then + return false + end + local l = tonumber(len) :: number + if l < #len + 3 or p + l - 1 > #s then + return false + end + local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline + local eq = string.find(rec, "=", 1, true) + if not eq then + return false + end + into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1) + p += l + end + return true +end + +type ReadOptions = { maxEntries: number? } -- default 1e6 + +-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err +function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?) + local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local out: { Entry } = {} + local global: { [string]: string } = {} + local nextPax: { [string]: string }? = nil + local longName: string? = nil + local longLink: string? = nil + local p = o + while true do + if p + BLOCK > e then + if p == e then + break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning) + end + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if zeros(b, p) then + break -- end of archive (one or two zero blocks; what follows is padding) + end + local want = number(b, p + 148, 8) + local u, s = checksum(b, p) + if want ~= u and want ~= s then + return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148) + end + local typ = buffer.readstring(b, p + 156, 1) + if typ == "\0" then + typ = "0" + end + local size = number(b, p + 124, 12) + if not size or size < 0 then + return nil, Err.new(Err.CORRUPT, "bad size field", p + 124) + end + local data = p + BLOCK + local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK + local ustar = buffer.readstring(b, p + 257, 5) == "ustar" + -- meta records: pax / GNU long names + if typ == "x" or typ == "g" or typ == "L" or typ == "K" then + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "extended header past the end", data) + end + if typ == "x" or typ == "g" then + local into = if typ == "g" then global else (nextPax or {}) + if not pax(b, data, size, into) then + return nil, Err.new(Err.CORRUPT, "bad pax record", data) + end + if typ == "x" then + nextPax = into + end + elseif typ == "L" then + longName = str(b, data, size) + else + longLink = str(b, data, size) + end + p = nextHeader + continue + end + local name = str(b, p, 100) + if ustar then + local prefix = str(b, p + 345, 155) + if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times) + name = prefix .. "/" .. name + end + end + local entry: Entry = { + name = name, + size = size, + type = typ, + dir = typ == "5", + mode = number(b, p + 100, 8) or 0, + uid = number(b, p + 108, 8) or 0, + gid = number(b, p + 116, 8) or 0, + mtime = number(b, p + 136, 12) or 0, + link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil, + uname = if ustar then str(b, p + 265, 32) else nil, + gname = if ustar then str(b, p + 297, 32) else nil, + offset = data, + pax = nil, + } + if longName then + entry.name = longName + end + if longLink then + entry.link = longLink + end + local px = nextPax + for _, rec in { global, px } do + if rec then + if rec.path then + entry.name = rec.path + end + if rec.linkpath then + entry.link = rec.linkpath + end + if rec.size then + local sz = tonumber(rec.size) + if not sz or sz < 0 or sz % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad pax size", p) + end + entry.size = sz + end + if rec.mtime then + entry.mtime = tonumber(rec.mtime) or entry.mtime + end + if rec.uid then + entry.uid = tonumber(rec.uid) or entry.uid + end + if rec.gid then + entry.gid = tonumber(rec.gid) or entry.gid + end + if rec.uname then + entry.uname = rec.uname + end + if rec.gname then + entry.gname = rec.gname + end + end + end + if px then + entry.pax = px + end + if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then + entry.dir = true + end + -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir) + local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size + if typ == "5" or typ == "1" or typ == "2" then + entry.size = 0 + end + nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK + if typ ~= "5" and data + dataSize > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + nextPax, longName, longLink = nil, nil, nil + p = nextHeader + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ writing +type WriteEntry = { + name: string, + data: buffer?, + dir: boolean?, + type: string?, -- default "0" ("5" for dir) + link: string?, + mode: number?, -- default 0o644 (0o755 for directories) + uid: number?, + gid: number?, + uname: string?, + gname: string?, + mtime: number?, -- unix seconds (default 0) +} +type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed) + +local function octal(w: buffer, o: number, n: number, v: number): boolean + -- n - 1 octal digits and a NUL; false when it does not fit + local s = string.format("%o", v) + if v < 0 or v % 1 ~= 0 or #s > n - 1 then + return false + end + buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s) + buffer.writeu8(w, o + n - 1, 0) + return true +end + +local function field(w: buffer, o: number, n: number, s: string) + buffer.writestring(w, o, string.sub(s, 1, n)) +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function paxRecord(key: string, value: string): string + local body = " " .. key .. "=" .. value .. "\n" + local n = #body + 1 + while #tostring(n) + #body ~= n do + n = #tostring(n) + #body + end + return tostring(n) .. body +end + +-- one header block (the checksum filled in) +local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer + local h = buffer.create(BLOCK) + field(h, 0, 100, name) + local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4) + octal(h, 100, 8, mode % 0x200000) + octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF)) + octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF)) + octal(h, 124, 12, size) + octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1)) + field(h, 148, 8, " ") + field(h, 156, 1, typ) + field(h, 157, 100, link) + field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000") + field(h, 265, 32, e.uname or "") + field(h, 297, 32, e.gname or "") + field(h, 345, 155, prefix) + local u = checksum(h, 0) + field(h, 148, 8, string.format("%06o", u) .. "\0 ") + return h +end + +-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil +local function split(path: string): (string?, string?) + if #path <= 100 then + return "", path + end + for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile + if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then + return string.sub(path, 1, i - 1), string.sub(path, i + 1) + end + end + return nil, nil +end + +-- write(entries, opts?) -> buffer | nil, Err +function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) + local fmt = (opts and opts.format) or "pax" + local w = Bytes.writer(BLOCK * (2 * #entries + 2)) + for i, e in entries do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local data = e.data or buffer.create(0) + local typ = e.type or (if e.dir then "5" else "0") + local name: string = e.name + if typ == "5" and string.sub(name, -1) ~= "/" then + name ..= "/" + end + local size = if typ == "0" or typ == "7" then buffer.len(data) else 0 + local link = e.link or "" + -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole + local prefix, short + if fmt == "ustar" then + prefix, short = split(name) + elseif #name <= 100 then + prefix, short = "", name + end + local paxRecs: { string } = {} + -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII + local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name)) + local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link)) + if needName or needLink then + if fmt == "ustar" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar") + elseif fmt == "gnu" then + if needName then + local ln = buffer.fromstring(name .. "\0") + w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true)) + w:bytes(ln) + w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK) + end + if needLink then + local ll = buffer.fromstring(link .. "\0") + w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true)) + w:bytes(ll) + w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK) + end + else + if needName then + table.insert(paxRecs, paxRecord("path", name)) + end + if needLink then + table.insert(paxRecs, paxRecord("linkpath", link)) + end + end + end + if size >= 8 ^ 11 then + if fmt ~= "pax" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax") + end + table.insert(paxRecs, paxRecord("size", tostring(size))) + end + local mt = e.mtime or 0 + if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then + table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", ""))) + end + if #paxRecs > 0 then + local body = buffer.fromstring(table.concat(paxRecs)) + w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false)) + w:bytes(body) + w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK) + end + if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then + -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile) + local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?") + prefix, short = "", string.sub(stand, 1, 100) + end + w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu")) + if size > 0 then + w:bytes(data) + w:fill(0, (BLOCK - size % BLOCK) % BLOCK) + end + end + w:fill(0, BLOCK * 2) + return w:finish(), nil +end + +return Tar +end +__FILES["containers/Zip"] = function() + + +-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from +-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an +-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor +-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, +-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly +-- (codecs/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/Deflate compress, stored +-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. +-- +-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader +-- for _, e in zip:list() do print(e.name, e.size) end +-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked +-- +-- local w = Zip.writer() +-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds +-- local file = w:finish({ comment = "..." }) +-- +-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native +-- code it reaches (Deflate, Crc32) does not throw either. +local Err = __include("core/Err") +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +type Entry = { + name: string, -- the path with "\" turned into "/" + rawName: string, -- the name bytes as stored + index: number, -- position in the central directory, 1-based + size: number, -- uncompressed size + compressedSize: number, + crc32: number, + method: number, -- 0 stored, 8 deflate (others are listed but not readable) + flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name) + offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub) + isDir: boolean, + utf8: boolean, + comment: string, + modified: { year: number, month: number, day: number, hour: number, min: number, sec: number }, + mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC) + time: number, -- the raw DOS time and date + date: number, + attributes: number, -- external attributes + -- central-directory lengths of the name and extra field (a fallback when the local header is wrong) + cdNameLen: number, + cdExtraLen: number, +} + +-- ------------------------------------------------------------------------------------------------ read +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b: buffer, o: number, sig: number): boolean + return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name: string): string + name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name: string): string + return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name: string): boolean + local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) +function Zip.isZip(buf: buffer | string): boolean + local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf + return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b: buffer): number? + local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b: buffer): (any, Err.Err?) + local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries = table.create(math.min(count, 65536)) :: { any } + local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r += 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r += 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r += 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q += 4 + sz + end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in entries do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a +-- part of a bigger buffer) +function Zip.open(src: any): (any, Err.Err?) + local b: buffer + if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +-- every entry (directories included), in central directory order +function Archive.list(self: any): { Entry } + return self.entries +end + +-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename +-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and +-- macOS "__MACOSX/" / "._" files never match by basename. +function Archive.find(self: any, name: string): Entry? + local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) + local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, if type(err) == "table" then err.message else tostring(err) + end + return out +end + +-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers +-- get the local extra length wrong) +function Zip._starts(b: buffer, e: Entry): { number } + local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +-- read(entry | name, verify = true) -> buffer | nil, Err +function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) + local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry + if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr: string? = nil + local code = Err.CORRUPT + for _, s in starts do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) +end + +-- readString(entry | name, verify?) -> string | nil, Err +function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) + local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +type AddOptions = { + method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller) + level: number?, -- deflate level 0..9 (default 6) + mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output) + comment: string?, + utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII) + attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs) +} +type FinishOptions = { + comment: string?, -- the archive comment + zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) +} + +-- writer() -> Writer +function Zip.writer(): any + return setmetatable({ files = {} :: { any } }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local civil = Types.Date.civilFromDays +local function daysFrom(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = if m > 2 then m - 3 else m + 9 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t: number?): (number, number) + if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 + return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time: number, date: number): number + local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s: string): boolean + return string.find(s, "[\128-\255]") == nil +end + +-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) +function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) + if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o: AddOptions = opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = if n > 0 then Crc32.of(b) else 0, + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name), + attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err +function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) + local b = archive.buf + local start: number? = nil + for _, s in Zip._starts(b, e) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- finish(opts?) -> the archive | nil, Err +function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) + local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in self.files do + total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment + end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in self.files do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = if f.utf8 then 0x800 else 0 + w:u32le(SIG_LOCAL) + w:u16le(if big then 45 else 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if big then 0xFFFFFFFF else f.dataLength) + w:u32le(if big then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if big then 20 else 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in self.files do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0) + local version = if bigSize or bigOff then 45 else 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(if f.utf8 then 0x800 else 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength) + w:u32le(if bigSize then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if extra > 0 then extra + 4 else 0) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(if bigOff then 0xFFFFFFFF else off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(if z64 then 0xFFFF else count) + w:u16le(if z64 then 0xFFFF else count) + w:u32le(if z64 then 0xFFFFFFFF else cdSize) + w:u32le(if z64 then 0xFFFFFFFF else cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip +end +__FILES["core/Adler32"] = @native function() + + +-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it) +-- Adler32.string(s, adler?) -> u32 +local readu8 = buffer.readu8 + +-- Adler-32 of buf[off, off + len), continuing adler (default 1) +@native local function adler32(buf: buffer, off: number, len: number, adler: number?): number + local a0 = adler or 1 + local a, b = a0 % 65536, a0 // 65536 + local i, e = off, off + len + while i < e do + -- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far + -- more, but keeping the sums small keeps them exact and cheap. + local stop = math.min(e, i + 5552) + while i < stop do + a += readu8(buf, i) + b += a + i += 1 + end + a %= 65521 + b %= 65521 + end + return b * 65536 + a +end + +-- clamp (offset, length) to the buffer +@native local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Adler32 = {} + +@native function Adler32.of(buf: buffer, offset: number?, length: number?, adler: number?): number + local o, l = range(buf, offset, length) + return adler32(buf, o, l, adler) +end + +@native function Adler32.string(s: string, adler: number?): number + return adler32(buffer.fromstring(s), 0, #s, adler) +end + +Adler32.raw = adler32 + +return Adler32 +end +__FILES["core/Base64"] = @native function() + + +-- core/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, and data: URIs. +-- Used by tiled map data, glTF / SVG / CSS data: URIs, plist , YAML !!binary, FBX, the Brotli static tables. +-- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a +-- lone last character is an error. Never throws. +-- +-- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input) +-- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length) +-- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message" +-- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg +-- local uri = Base64.dataUri(buf, "image/png") +local Base64 = {} + +type EncodeOptions = { + url: boolean?, -- the URL-safe alphabet (- and _); default false + pad: boolean?, -- "=" padding; default true + wrap: number?, -- a "\n" after every `wrap` output characters (rounded down to a multiple of 4); default none +} + +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, 11, 12, 13, 32 } do + buffer.writeu8(DEC, c, 64) +end +buffer.writeu8(DEC, string.byte("="), 65) + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length) +@native function Base64.encode(data: buffer | string, opts: EncodeOptions?, offset: number?, length: number?): string + local buf: buffer = if type(data) == "string" then buffer.fromstring(data) else data + local total = buffer.len(buf) + local o = math.clamp(offset or 0, 0, total) + local n = math.clamp(length or (total - o), 0, total - o) + local enc = if opts and opts.url then ENC_URL else ENC + local pad = not (opts and opts.pad == false) + local wrap = if opts and opts.wrap and opts.wrap >= 4 then opts.wrap // 4 else 0 -- groups per line + local full = n // 3 + local rest = n - full * 3 + local textLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) + local groups = full + (if rest > 0 then 1 else 0) + local breaks = if wrap > 0 and groups > 0 then (groups - 1) // wrap else 0 + local out = buffer.create(textLen + breaks) + local p = 0 + local col = 0 + for i = 0, full - 1 do + if wrap > 0 then + if col == wrap then + writeu8(out, p, 10) + p += 1 + col = 0 + end + col += 1 + end + 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 + if wrap > 0 and col == wrap then + writeu8(out, p, 10) + p += 1 + end + 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 +@native function Base64.decode(s: string | buffer): (buffer?, string?) + local src: buffer = 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 scale = 2 ^ bits + local byte = acc // scale + writeu8(out, p, byte % 256) + p += 1 + acc -= byte * scale + 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:[][;params][;base64]," (percent-encoded data +-- when not base64) +@native 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)", @native function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + return buffer.fromstring(decoded), mime +end + +-- dataUri(buf, mime?) -> "data:;base64,..." +@native function Base64.dataUri(buf: buffer | string, mime: string?): string + return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) +end + +return Base64 +end +__FILES["core/Bits"] = @native function() + + +-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data +-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. +-- +-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. +-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see +-- codecs/compress/Deflate/Inflate) and uses these for headers. +-- +-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). +-- +-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader +-- local v = br:read(5); if br.err then return nil, br.err end +-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() +-- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path +-- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, blen = buffer.readu8, buffer.len +local floor = math.floor + +-- 2^n for n = 0..32 +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +local Bits = {} +Bits.POW = POW + +-- ------------------------------------------------------------------------------------------------ readers +type BitReader = { + buf: buffer, + pos: number, -- next byte to load + limit: number, + acc: number, -- loaded, unread bits + cnt: number, -- how many + err: Err.Err?, + read: (BitReader, number) -> number, + peek: (BitReader, number) -> number, + skip: (BitReader, number) -> (), + align: (BitReader) -> (), + bytePos: (BitReader) -> number, + bitsLeft: (BitReader) -> number, +} + +@native local function overrun(self: any) + if not self.err then + self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit) + end +end + +-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant +local Lsb = {} +Lsb.__index = Lsb + +@native local function lsbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + else + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +@native function Lsb.read(self: any, n: number): number + if n > 24 then + local lo = Lsb.read(self, 16) + return lo + Lsb.read(self, n - 16) * 65536 + end + if self.cnt < n then + lsbFill(self, n) + end + local m = POW[n + 1] + local v = self.acc % m + self.acc = (self.acc - v) / m + self.cnt -= n + return v +end +@native function Lsb.peek(self: any, n: number): number + if self.cnt < n then + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do -- no error for peeking past the end: the bits are zeros + if pos < self.limit then + acc += readu8(self.buf, pos) * POW[cnt + 1] + pos += 1 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return acc % POW[n + 1] + end + return self.acc % POW[n + 1] +end +@native function Lsb.skip(self: any, n: number) + while n > 24 do + Lsb.read(self, 24) + n -= 24 + end + Lsb.read(self, n) +end +-- align(): drop the bits up to the next byte boundary +@native function Lsb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Lsb.read(self, k) + end +end +-- bytePos(): the offset of the first byte not yet (even partly) consumed +@native function Lsb.bytePos(self: any): number + return self.pos - floor(self.cnt / 8) +end +@native function Lsb.bitsLeft(self: any): number + return (self.limit - self.pos) * 8 + self.cnt +end + +-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant +local Msb = {} +Msb.__index = Msb + +@native local function msbFill(self: any, n: number) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + overrun(self) + end + cnt += 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +@native function Msb.read(self: any, n: number): number + if n > 24 then + local hi = Msb.read(self, n - 16) + return hi * 65536 + Msb.read(self, 16) + end + if self.cnt < n then + msbFill(self, n) + end + local sh = POW[self.cnt - n + 1] + local v = floor(self.acc / sh) + self.acc -= v * sh + self.cnt -= n + return v +end +@native function Msb.peek(self: any, n: number): number + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos += 1 + else + acc *= 256 + end + cnt += 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return floor(acc / POW[cnt - n + 1]) +end +@native function Msb.skip(self: any, n: number) + while n > 24 do + Msb.read(self, 24) + n -= 24 + end + Msb.read(self, n) +end +@native function Msb.align(self: any) + local k = self.cnt % 8 + if k > 0 then + Msb.read(self, k) + end +end +Msb.bytePos = Lsb.bytePos +Msb.bitsLeft = Lsb.bitsLeft + +@native local function reader(meta: any, buf: buffer, offset: number?, length: number?): BitReader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) :: any +end + +-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader +@native function Bits.lsbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Lsb, buf, offset, length) +end +@native function Bits.msbReader(buf: buffer, offset: number?, length: number?): BitReader + return reader(Msb, buf, offset, length) +end + +-- ------------------------------------------------------------------------------------------------ writers +type BitWriter = { + out: Bytes.Writer, -- the bytes so far (whole bytes only) + acc: number, + cnt: number, + write: (BitWriter, number, number) -> (), + align: (BitWriter) -> (), + finish: (BitWriter) -> buffer, +} + +local LsbW = {} +LsbW.__index = LsbW +@native function LsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + LsbW.write(self, lo, 16) + LsbW.write(self, (v - lo) / 65536, n - 16) + return + end + local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1] + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local byte = acc % 256 + out:u8(byte) + acc = (acc - byte) / 256 + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +-- align(): pad with zero bits to a byte boundary +@native function LsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc) + self.acc, self.cnt = 0, 0 + end +end +@native function LsbW.finish(self: any): buffer + LsbW.align(self) + return self.out:finish() +end + +local MsbW = {} +MsbW.__index = MsbW +@native function MsbW.write(self: any, v: number, n: number) + if n > 24 then + local lo = v % 65536 + MsbW.write(self, (v - lo) / 65536, n - 16) + MsbW.write(self, lo, 16) + return + end + local acc = self.acc * POW[n + 1] + (v % POW[n + 1]) + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local sh = POW[cnt - 8 + 1] + local byte = floor(acc / sh) + out:u8(byte) + acc -= byte * sh + cnt -= 8 + end + self.acc, self.cnt = acc, cnt +end +@native function MsbW.align(self: any) + if self.cnt > 0 then + self.out:u8(self.acc * POW[8 - self.cnt + 1]) + self.acc, self.cnt = 0, 0 + end +end +@native function MsbW.finish(self: any): buffer + MsbW.align(self) + return self.out:finish() +end + +-- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, +-- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). +type RawWriter = { buf: buffer, pos: number, acc: number, cnt: number } +@native function Bits.msbPut(w: RawWriter, 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) + buffer.writeu8(b, p, byte) + p += 1 + acc -= byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter +@native function Bits.lsbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) :: any +end +@native function Bits.msbWriter(capacity: number?): BitWriter + return setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) :: any +end + +return Bits +end +__FILES["core/Bytes"] = @native function() + + +-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a +-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. +-- +-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads: +-- +-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length) +-- local magic, w, h = r:string(4), r:u32be(), r:u32be() +-- if r.err then return nil, r.err end +-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end +-- +-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) +-- w:string("abcd"); w:u32be(width); local out = w:finish() +-- +-- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking +local Err = __include("core/Err") + +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring +local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len +local byteswap = bit32.byteswap + +local TWO32 = 4294967296 +local scratch = bcreate(8) -- reinterpret casts for big-endian floats + +local Bytes = {} + +-- ------------------------------------------------------------------------------------------------ Reader +local Reader = {} +Reader.__index = Reader + +type Reader = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- absolute offset of the next byte in buf + base: number, -- absolute offset of the reader's first byte + limit: number, -- absolute offset just past the reader's last byte + err: Err.Err?, -- sticky: the first failure + }, + Reader +)) + +-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer +@native function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader + local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)` +@native function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err) + if not self.err then + self.err = Err.new(code, message, self.pos) + end + return nil, self.err :: Err.Err +end + +-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end +@native function Reader.need(self: Reader, n: number): boolean + if self.pos + n <= self.limit and n >= 0 then + return true + end + if not self.err then + self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos) + end + self.pos = self.limit + return false +end + +@native function Reader.tell(self: Reader): number + return self.pos - self.base +end +@native function Reader.size(self: Reader): number + return self.limit - self.base +end +@native function Reader.remaining(self: Reader): number + return self.limit - self.pos +end +@native function Reader.eof(self: Reader): boolean + return self.pos >= self.limit +end + +-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED +@native function Reader.seek(self: Reader, offset: number): boolean + if offset < 0 or self.base + offset > self.limit then + self.pos = self.limit + if not self.err then + self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset) + end + return false + end + self.pos = self.base + offset + return true +end + +@native function Reader.skip(self: Reader, n: number): boolean + if self:need(n) then + self.pos += n + return true + end + return false +end + +-- align(n): skip to the next multiple of n (relative to the reader's start) +@native function Reader.align(self: Reader, n: number): boolean + local r = (self.pos - self.base) % n + if r == 0 then + return true + end + return self:skip(n - r) +end + +-- integers +@native function Reader.u8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readu8(self.buf, p) +end +@native function Reader.i8(self: Reader): number + local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readi8(self.buf, p) +end +@native function Reader.u16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu16(self.buf, p) +end +@native function Reader.u16be(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1) +end +@native function Reader.i16le(self: Reader): number + local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readi16(self.buf, p) +end +@native function Reader.i16be(self: Reader): number + local v = self:u16be() + return if v >= 32768 then v - 65536 else v +end +@native function Reader.u24le(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536 +end +@native function Reader.u24be(self: Reader): number + local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2) +end +@native function Reader.u32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readu32(self.buf, p) +end +@native function Reader.u32be(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return byteswap(readu32(self.buf, p)) +end +@native function Reader.i32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readi32(self.buf, p) +end +@native function Reader.i32be(self: Reader): number + local v = self:u32be() + return if v >= 2147483648 then v - TWO32 else v +end +-- 64-bit integers as doubles (exact below 2^53) +@native function Reader.u64le(self: Reader): number + local lo = self:u32le() + return lo + self:u32le() * TWO32 +end +@native function Reader.u64be(self: Reader): number + local hi = self:u32be() + return hi * TWO32 + self:u32be() +end +@native function Reader.i64le(self: Reader): number + local lo = self:u32le() + return lo + self:i32le() * TWO32 +end +@native function Reader.i64be(self: Reader): number + local hi = self:i32be() + return hi * TWO32 + self:u32be() +end + +-- floats +@native local function half(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 31) + local m = bit32.band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end +Bytes.half = half + +@native function Reader.f16le(self: Reader): number + return half(self:u16le()) +end +@native function Reader.f16be(self: Reader): number + return half(self:u16be()) +end +@native function Reader.f32le(self: Reader): number + local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readf32(self.buf, p) +end +@native function Reader.f32be(self: Reader): number + local v = self:u32be() + writeu32(scratch, 0, v) + return readf32(scratch, 0) +end +@native function Reader.f64le(self: Reader): number + local p = self.pos + if p + 8 > self.limit then + self:need(8) + return 0 + end + self.pos = p + 8 + return readf64(self.buf, p) +end +@native function Reader.f64be(self: Reader): number + local hi = self:u32be() + local lo = self:u32be() + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end + +-- strings +@native function Reader.string(self: Reader, n: number): string + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return "" + end + self.pos = p + n + return readstring(self.buf, p, n) +end + +-- fixed(n): an n-byte field, cut at the first NUL +@native function Reader.fixed(self: Reader, n: number): string + local s = self:string(n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED +@native function Reader.cstring(self: Reader, max: number?): string + local p = self.pos + local e = if max then math.min(self.limit, p + max) else self.limit + local q = p + local buf = self.buf + while q < e and readu8(buf, q) ~= 0 do + q += 1 + end + if q >= e then + self.pos = e + self:need(1) + return readstring(buf, p, e - p) + end + self.pos = q + 1 + return readstring(buf, p, q - p) +end + +-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error +@native function Reader.match(self: Reader, s: string): boolean + local p, n = self.pos, #s + if p + n > self.limit or readstring(self.buf, p, n) ~= s then + return false + end + self.pos = p + n + return true +end + +-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error +@native function Reader.peek(self: Reader, n: number, at: number?): string + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return "" + end + return readstring(self.buf, p, math.min(n, self.limit - p)) +end + +-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end +@native function Reader.peekU8(self: Reader, at: number?): number + local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return -1 + end + return readu8(self.buf, p) +end + +-- bytes(n) -> a new buffer with a copy of the next n bytes +@native function Reader.bytes(self: Reader, n: number): buffer + local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return bcreate(0) + end + local b = bcreate(n) + bcopy(b, 0, self.buf, p, n) + self.pos = p + n + return b +end + +-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is +-- left, and the parent records TRUNCATED. +@native function Reader.slice(self: Reader, n: number): Reader + local p = self.pos + local l = math.max(0, math.min(n, self.limit - p)) + if l < n then + self:need(n) + else + self.pos = p + n + end + return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader) +end + +-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without +-- moving the cursor +@native function Reader.sub(self: Reader, offset: number, length: number?): Reader + local o = math.clamp(self.base + offset, self.base, self.limit) + local l = math.clamp(length or (self.limit - o), 0, self.limit - o) + return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader) +end + +-- ------------------------------------------------------------------------------------------------ Writer +local Writer = {} +Writer.__index = Writer + +type Writer = typeof(setmetatable( + {} :: { + buf: buffer, + pos: number, -- bytes written (the next write offset) + }, + Writer +)) + +-- writer(capacity?) -> Writer +@native function Bytes.writer(capacity: number?): Writer + return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) +end + +-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf) +@native function Writer.reserve(self: Writer, n: number): number + local p = self.pos + local cap = blen(self.buf) + if p + n > cap then + local nb = bcreate(math.max(cap * 2, p + n)) + bcopy(nb, 0, self.buf, 0, p) + self.buf = nb + end + return p +end + +@native function Writer.tell(self: Writer): number + return self.pos +end + +@native function Writer.u8(self: Writer, v: number) + local p = self:reserve(1) + writeu8(self.buf, p, v) + self.pos = p + 1 +end +@native function Writer.u16le(self: Writer, v: number) + local p = self:reserve(2) + writeu16(self.buf, p, v) + self.pos = p + 2 +end +@native function Writer.u16be(self: Writer, v: number) + local p = self:reserve(2) + writeu8(self.buf, p, bit32.rshift(v, 8)) + writeu8(self.buf, p + 1, v) + self.pos = p + 2 +end +@native function Writer.u24le(self: Writer, v: number) + local p = self:reserve(3) + writeu16(self.buf, p, v) + writeu8(self.buf, p + 2, bit32.rshift(v, 16)) + self.pos = p + 3 +end +@native function Writer.u24be(self: Writer, v: number) + local p = self:reserve(3) + writeu8(self.buf, p, bit32.rshift(v, 16)) + writeu8(self.buf, p + 1, bit32.rshift(v, 8)) + writeu8(self.buf, p + 2, v) + self.pos = p + 3 +end +@native function Writer.u32le(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, v) + self.pos = p + 4 +end +@native function Writer.u32be(self: Writer, v: number) + local p = self:reserve(4) + writeu32(self.buf, p, byteswap(v % TWO32)) + self.pos = p + 4 +end +Writer.i8 = Writer.u8 +Writer.i16le = Writer.u16le +Writer.i16be = Writer.u16be +Writer.i32le = Writer.u32le +Writer.i32be = Writer.u32be +@native function Writer.u64le(self: Writer, v: number) + self:u32le(v % TWO32) + self:u32le(math.floor(v / TWO32) % TWO32) +end +@native function Writer.u64be(self: Writer, v: number) + self:u32be(math.floor(v / TWO32) % TWO32) + self:u32be(v % TWO32) +end +Writer.i64le = Writer.u64le +Writer.i64be = Writer.u64be +@native function Writer.f32le(self: Writer, v: number) + local p = self:reserve(4) + writef32(self.buf, p, v) + self.pos = p + 4 +end +@native function Writer.f32be(self: Writer, v: number) + writef32(scratch, 0, v) + self:u32be(readu32(scratch, 0)) +end +@native function Writer.f64le(self: Writer, v: number) + local p = self:reserve(8) + writef64(self.buf, p, v) + self.pos = p + 8 +end +@native function Writer.f64be(self: Writer, v: number) + writef64(scratch, 0, v) + self:u32be(readu32(scratch, 4)) + self:u32be(readu32(scratch, 0)) +end + +@native function Writer.string(self: Writer, s: string) + local n = #s + local p = self:reserve(n) + writestring(self.buf, p, s) + self.pos = p + n +end +-- cstring(s): s and a NUL +@native function Writer.cstring(self: Writer, s: string) + self:string(s) + self:u8(0) +end +-- bytes(b, offset?, length?): copy a buffer range +@native function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?) + local o = offset or 0 + local n = length or (blen(b) - o) + local p = self:reserve(n) + bcopy(self.buf, p, b, o, n) + self.pos = p + n +end +@native function Writer.fill(self: Writer, v: number, n: number) + local p = self:reserve(n) + bfill(self.buf, p, v, n) + self.pos = p + n +end + +-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos +@native function Writer.setU32le(self: Writer, at: number, v: number) + writeu32(self.buf, at, v) +end +@native function Writer.setU32be(self: Writer, at: number, v: number) + writeu32(self.buf, at, byteswap(v % TWO32)) +end +@native function Writer.setU16le(self: Writer, at: number, v: number) + writeu16(self.buf, at, v) +end +@native function Writer.setU8(self: Writer, at: number, v: number) + writeu8(self.buf, at, v) +end + +-- finish() -> a buffer of exactly the written bytes (the writer can keep going) +@native function Writer.finish(self: Writer): buffer + local b = bcreate(self.pos) + bcopy(b, 0, self.buf, 0, self.pos) + return b +end + +Bytes.Reader = Reader +Bytes.Writer = Writer + +-- ------------------------------------------------------------------------------------------------ arguments +-- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else +@native function Bytes.toBuffer(v: any): buffer? + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +-- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string, +-- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end) +@native function Bytes.span(what: string, input: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) + local b = Bytes.toBuffer(input) + if not b then + return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(input)) + end + local n = buffer.len(b) + local o = offset or 0 + local l = length or (n - (if type(o) == "number" then o else 0)) + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 or type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) + end + if o + l > n then + l = n - o + end + return b, o, l, nil +end + +return Bytes +end +__FILES["core/Crc16"] = @native function() + + +-- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code. +-- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0, +-- MacBinary II / III headers) +-- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC) +-- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer. +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift +local readu8 = buffer.readu8 + +local MSB = table.create(256, 0) +local ARC = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 8) + for _ = 1, 8 do + c = if band(c, 0x8000) ~= 0 then bxor(band(lshift(c, 1), 0xFFFF), 0x1021) else band(lshift(c, 1), 0xFFFF) + end + MSB[n + 1] = c + local r = n + for _ = 1, 8 do + r = if band(r, 1) ~= 0 then bxor(rshift(r, 1), 0xA001) else rshift(r, 1) + end + ARC[n + 1] = r +end + +local Crc16 = {} + +@native local function clamp(buf: buffer, off: number, len: number): (number, number) + local n = buffer.len(buf) + local o = math.clamp(math.floor(off), 0, n) + return o, math.clamp(math.floor(len), 0, n - o) +end + +@native function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number + local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1]) + end + return c +end + +@native function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number + local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1]) + end + return c +end + +return Crc16 +end +__FILES["core/Crc32"] = @native function() + + +-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) +-- Crc32.string(s, crc?) -> u32 +-- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no +-- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF) +-- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2) +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local c = n + for _ = 1, 8 do + if band(c, 1) ~= 0 then + c = bxor(0xEDB88320, rshift(c, 1)) + else + c = rshift(c, 1) + end + end + T0[n + 1] = c +end +for n = 0, 255 do + local c = T0[n + 1] + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T1[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T2[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T3[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T4[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T5[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T6[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T7[n + 1] = c +end + +-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion +-- happens inside), so crc(b, crc(a)) == the CRC of a .. b. +@native local function crc32(buf: buffer, off: number, len: number, crc: number?): number + local c = bxor(crc or 0, 0xFFFFFFFF) + local i, e = off, off + len + local e8 = e - 8 + while i <= e8 do + c = bxor(c, readu32(buf, i)) + local d = readu32(buf, i + 4) + c = bxor( + T7[band(c, 255) + 1], + T6[band(rshift(c, 8), 255) + 1], + T5[band(rshift(c, 16), 255) + 1], + T4[rshift(c, 24) + 1], + T3[band(d, 255) + 1], + T2[band(rshift(d, 8), 255) + 1], + T1[band(rshift(d, 16), 255) + 1], + T0[rshift(d, 24) + 1] + ) + i += 8 + end + local e4 = e - 4 + while i <= e4 do + c = bxor(c, readu32(buf, i)) + c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1]) + i += 4 + end + while i < e do + c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8)) + i += 1 + end + return bxor(c, 0xFFFFFFFF) +end + +-- clamp (offset, length) to the buffer +@native local function range(buf: buffer, offset: number?, length: number?): (number, number) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Crc32 = {} + +@native function Crc32.of(buf: buffer, offset: number?, length: number?, crc: number?): number + local o, l = range(buf, offset, length) + return crc32(buf, o, l, crc) +end + +@native function Crc32.string(s: string, crc: number?): number + return crc32(buffer.fromstring(s), 0, #s, crc) +end + +-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) +Crc32.raw = crc32 + +-- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks +local MSB = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 24) + for _ = 1, 8 do + c = if band(c, 0x80000000) ~= 0 then bxor(lshift(c, 1), 0x04C11DB7) else lshift(c, 1) + end + MSB[n + 1] = c +end +Crc32.MSB_TABLE = MSB + +-- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range) +@native function Crc32.msb(buf: buffer, off: number, len: number, init: number?): number + local c = init or 0 + for i = off, off + len - 1 do + c = bxor(lshift(c, 8), MSB[bxor(rshift(c, 24), readu8(buf, i)) + 1]) + end + return c +end + +return Crc32 +end +__FILES["core/Err"] = function() + +-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). +-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". +-- Never throws: --!native modules may require it. +-- +-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos) +-- if err.code == Err.UNSUPPORTED then ... end +local Err = {} + +-- codes +Err.TRUNCATED = "TRUNCATED" -- the data ends early +Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field) +Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch +Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder +Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name +Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...) +Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option) +Err.IO = "IO" -- reading or writing a file failed, or the host has no file system + +type Err = { + code: string, + message: string, + offset: number?, + format: string?, +} + +local Meta = {} +Meta.__tostring = function(e: Err): string + local s = if e.format then e.format .. ": " .. e.code else e.code + if e.offset then + s ..= string.format(" at 0x%x", e.offset) + end + return s .. ": " .. e.message +end + +-- new(code, message, offset?) -> Err +function Err.new(code: string, message: string, offset: number?): Err + return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any +end + +-- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) +local KIND: { [string]: string } = {} +for _, c in { "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" } do + KIND[c] = c + KIND[string.lower(c)] = c +end + +-- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns +-- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the +-- message decides: a ": ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; +-- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; +-- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes +-- through unchanged. +function Err.from(message: any, offset: number?, kind: string?): Err + if Err.is(message) then + return message + end + local msg = if message == nil then "failed" else tostring(message) + local code: string? = kind and KIND[kind] + if not code then + local head, rest = string.match(msg, "^(%a+):%s*(.*)$") + if head and KIND[head] then + code, msg = KIND[head], rest :: string + elseif string.find(msg, "truncated", 1, true) or string.find(msg, "past the end", 1, true) or string.find(msg, "runs past", 1, true) then + code = Err.TRUNCATED + elseif string.find(msg, "^unsupported") then + code = Err.UNSUPPORTED + elseif string.find(msg, "^checksum") then + code = Err.CHECKSUM + else + code = Err.CORRUPT + end + end + return Err.new(code :: string, msg, offset) +end + +-- is(v) -> true when v is an Err +function Err.is(v: any): boolean + return type(v) == "table" and getmetatable(v) == Meta +end + +-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to +-- tag errors with the format name. +function Err.wrap(e: any, format: string?): Err + if not Err.is(e) then + e = Err.new(Err.CORRUPT, tostring(e)) + end + if e.format == nil then + e.format = format + end + return e +end + +return table.freeze(Err) +end +__FILES["core/Input"] = function() + +-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files +-- through the host adapter the API passes in (core never requires host itself). +-- +-- local buf, err, name = Input.resolve(src, opts, host) +-- +-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path +-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). +-- name: the path (for the extension fallback) or opts.name. Never throws. +local Err = __include("core/Err") + +local Input = {} + +type HostLike = { + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + exists: (path: string) -> boolean, +} + +-- looksLikePath(s) -> true for short strings without NUL / newline bytes +function Input.looksLikePath(s: string): boolean + return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") +end + +-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err +function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?) + local o = opts or {} + local t = type(src) + if t == "buffer" then + return src, nil, o.name + elseif t == "string" then + local isPath = false + if o.path == true then + isPath = true + elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then + isPath = host.exists(src) + end + if isPath then + if not host then + return nil, Err.new(Err.IO, "no host to read " .. src), nil + end + local b, err = host.readFile(src) + if not b then + return nil, err, nil + end + return b, nil, src + end + return buffer.fromstring(src), nil, o.name + end + return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil +end + +-- extension(name) -> the lower-case extension without the dot ("png"), or nil +function Input.extension(name: string?): string? + if not name then + return nil + end + local ext = string.match(name, "%.([%w_]+)$") + return if ext then string.lower(ext) else nil +end + +-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive +-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) +function Input.sibling(opts: any?, uri: string): buffer? + if type(opts) ~= "table" then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, got = pcall(opts.resolve, uri) + v = if ok then got else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +return Input +end +__FILES["core/Md5"] = @native function() + + + +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- +-- local h = Md5.new() +-- h:update(buf, offset?, length?) -- any number of times +-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) +-- Md5.hex(digest) / Md5.of(buf) -> hex string +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + +type State = { + a: number, + b: number, + c: number, + d: number, + block: buffer, -- 64-byte pending block + fill: number, + total: number, -- bytes hashed + update: (self: State, buf: buffer, offset: number?, length: number?) -> (), + digest: (self: State) -> string, +} + +local M = table.create(16, 0) + +@native local function compress(st: State, blk: buffer, o: number) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +@native local function update(self: State, buf: buffer, offset: number?, length: number?) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total += len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill += take + o += take + len -= take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o += 64 + len -= 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +@native local function digest(self: State): string + local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f += 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +@native function Md5.new(): State + return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +-- hex(digest) -> 32 lower-case hex digits +@native function Md5.hex(d: string): string + local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +-- of(buf, offset?, length?) -> hex digest +@native function Md5.of(buf: buffer, offset: number?, length: number?): string + local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 +end +__FILES["core/Sniff"] = function() + +-- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and +-- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. +-- +-- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 +-- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score +-- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped +-- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too +-- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file +local Sniff = {} + +type Peeker = { peek: (any, number, number?) -> string } + +-- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 +function Sniff.magic(r: Peeker, s: string, at: number?, score: number?): number + return if r:peek(#s, at) == s then score or 1 else 0 +end + +-- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) +function Sniff.dropBom(s: string): string + return if string.sub(s, 1, 3) == "\239\187\191" then string.sub(s, 4) else s +end + +-- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) +function Sniff.text(r: Peeker, n: number, trim: boolean?): string + local s = r:peek(n) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + if trim then + s = string.match(s, "^%s*(.*)$") :: string + end + return s +end + +return Sniff +end +__FILES["data/cbor"] = function() + +-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / +-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, +-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), +-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences +-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, +-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/cbor/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Cbor = { + name = "cbor", + category = "data", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, +} + +type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item) +} +type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, -- the value is an array of items, written as a sequence + selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Cbor.sniff(r: Bytes.Reader): number + return if r:peek(3) == "\217\217\247" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function codeOf(e: string): string + if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then + return Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then + return Err.LIMIT + end + return Err.CORRUPT +end + +function Cbor.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local w = Bytes.writer() + if opts and opts.selfDescribe then + w:string("\217\217\247") + end + local items = { value } + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of items") + end + items = value + end + for _, v in items do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.isTagged = Codec.isTagged +Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.isSimple = Codec.isSimple +Cbor.undefined = Codec.undefined + +return Cbor +end +__FILES["data/cbor/Codec"] = @native function() + + +-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, +-- message, offset. +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ value types +local TaggedMeta = { __tostring = @native function(t: any): string + return "cbor.tag(" .. t.tag .. ")" +end } +local SimpleMeta = { __tostring = @native function(s: any): string + return "cbor.simple(" .. s.value .. ")" +end } +-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret +@native function Codec.tagged(tag: number, value: any): { tag: number, value: any } + return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any +end +@native function Codec.isTagged(v: any): boolean + return type(v) == "table" and getmetatable(v) == TaggedMeta +end +-- simple(n) -> an unassigned simple value (0..19, 32..255) +@native function Codec.simple(n: number): { value: number } + return setmetatable({ value = n }, SimpleMeta) :: any +end +@native function Codec.isSimple(v: any): boolean + return type(v) == "table" and getmetatable(v) == SimpleMeta +end +Codec.undefined = table.freeze(setmetatable({}, { __tostring = @native function() + return "undefined" +end })) + +-- decimal text of a big-endian unsigned byte string (any length) +@native local function bigText(s: string): string + local limbs = {} -- base 1e7, little-endian + for i = 1, #s do + local carry = string.byte(s, i) + for k = 1, #limbs do + local v = limbs[k] * 256 + carry + limbs[k] = v % 10000000 + carry = v // 10000000 + end + while carry > 0 do + table.insert(limbs, carry % 10000000) + carry //= 10000000 + end + end + if #limbs == 0 then + return "0" + end + local out = { string.format("%d", limbs[#limbs]) } + for k = #limbs - 1, 1, -1 do + table.insert(out, string.format("%07d", limbs[k])) + end + return table.concat(out) +end +-- text + 1 for a decimal string +@native local function incText(s: string): string + local digits: { number } = table.create(#s) :: { number } + for i = 1, #s do + digits[i] = string.byte(s, i) - 48 + end + local i = #digits + while i >= 1 do + if digits[i] < 9 then + digits[i] += 1 + break + end + digits[i] = 0 + i -= 1 + end + local out: { string } = table.create(#digits) :: { string } + for k, d in digits do + out[k] = string.char(48 + d) + end + return (if i == 0 then "1" else "") .. table.concat(out) +end + +type DecodeOptions = { + bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text + null: any?, -- the value for null (default Types.null) + undefined: any?, -- the value for undefined (default Codec.undefined) + maxDepth: number?, -- default 512 + dates: boolean?, -- tags 0 / 1 as Types.Date (default true) +} + +type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } + +local BREAK = {} -- the 0xFF stop code, inside indefinite items + +-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +@native local function arg(st: St, ai: number): (number?, string?, string?) + local r = st.r + if ai < 24 then + return ai, nil, nil + elseif ai == 24 then + return r:u8(), nil, nil + elseif ai == 25 then + return r:u16be(), nil, nil + elseif ai == 26 then + return r:u32be(), nil, nil + elseif ai == 27 then + local hi, lo = r:u32be(), r:u32be() + if st.big and hi >= 0x200000 then + return hi * TWO32 + lo, bigText(string.char(hi // 16777216, (hi // 65536) % 256, (hi // 256) % 256, hi % 256, lo // 16777216, (lo // 65536) % 256, (lo // 256) % 256, lo % 256)), nil + end + return hi * TWO32 + lo, nil, nil + elseif ai == 31 then + return nil, nil, nil + end + return nil, nil, "reserved additional information " .. ai +end + +local item: (st: St, depth: number) -> (any, string?) + +@native local function chunks(st: St, major: number, depth: number): (string?, string?) + local parts = {} + while true do + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + if ib == 0xFF then + return table.concat(parts), nil + end + if ib // 32 ~= major then + return nil, "bad chunk in an indefinite string" + end + local n, _, e = arg(st, ib % 32) + if e or n == nil then + return nil, e or "nested indefinite string" + end + if r.err or not r:need(n) then + return nil, "truncated string" + end + table.insert(parts, r:string(n)) + end +end + +local half = Bytes.half + +@native local function tag(st: St, t: number, v: any): (any, string?) + if t == 0 and st.dates then + if type(v) ~= "string" then + return nil, "tag 0 needs a text string" + end + local d = Types.Date.parse(v) + if not d or not d.offset then + return nil, "tag 0: bad date-time " .. v + end + return d, nil + elseif t == 1 and st.dates then + if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then + return nil, "tag 1 needs a number" + end + return Types.Date.fromUnix(v), nil + elseif t == 2 or t == 3 then + if type(v) ~= "string" then + return nil, "bignum tag needs a byte string" + end + local s = v :: string + local n = 0 + for i = 1, #s do + n = n * 256 + string.byte(s, i) + end + if n >= 9007199254740992 then + -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + local text = bigText(s) + if t == 3 then + text = incText(text) + end + if st.big then + return if t == 2 then text else "-" .. text, nil + end + local x = tonumber(text) :: number + return if t == 2 then x else -x, nil + end + return if t == 2 then n else -1 - n, nil + elseif t == 55799 then + return v, nil + end + return Codec.tagged(t, v), nil +end + +@native function item(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + local major, ai = ib // 32, ib % 32 + if major == 7 then + if ai < 20 then + return Codec.simple(ai), nil + elseif ai == 20 then + return false, nil + elseif ai == 21 then + return true, nil + elseif ai == 22 then + return st.null, nil + elseif ai == 23 then + return st.undef, nil + elseif ai == 24 then + local n = r:u8() + if r.err then + return nil, "truncated" + end + if n < 32 then + return nil, "bad two-byte simple value" + end + return Codec.simple(n), nil + elseif ai == 25 then + local h = r:u16be() + return if r.err then nil else half(h), if r.err then "truncated" else nil + elseif ai == 26 then + local f = r:f32be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 27 then + local f = r:f64be() + return if r.err then nil else f, if r.err then "truncated" else nil + elseif ai == 31 then + return BREAK, nil + end + return nil, "reserved simple value" + end + local n, text, e = arg(st, ai) + if e then + return nil, e + end + if r.err then + return nil, "truncated" + end + if major == 0 then + if n == nil then + return nil, "indefinite integer" + end + return text or n, nil + elseif major == 1 then + if n == nil then + return nil, "indefinite integer" + end + if text then + return "-" .. incText(text), nil + end + return -1 - n, nil + elseif major == 2 or major == 3 then + local s: string + if n == nil then + local c, ce = chunks(st, major, depth) + if not c then + return nil, ce + end + s = c + else + if not r:need(n) then + return nil, "truncated string" + end + s = r:string(n) + end + if major == 2 then + return buffer.fromstring(s), nil + end + if string.find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8 in a text string" + end + return s, nil + elseif major == 4 then + if n == nil then + local t = {} + while true do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return t, nil + end + table.insert(t, v) + end + end + if (n :: number) > r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n :: number) + for k = 1, n :: number do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + t[k] = v + end + return t, nil + elseif major == 5 then + if n ~= nil and n * 2 > r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order = {} + local k = 0 + while n == nil or k < n do + k += 1 + local key, ke = item(st, depth + 1) + if ke then + return nil, ke + end + if key == BREAK then + if n == nil then + break + end + return nil, "unexpected break" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + if key ~= key then + return nil, "NaN map key" + end + if t[key] == nil then + table.insert(order, key) + end + t[key] = v + end + return Types.object(t, order), nil + else -- 6: tag + if n == nil then + return nil, "indefinite tag" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + -- bignum content arrives as a buffer: hand the tag its bytes + if (n == 2 or n == 3) and type(v) == "buffer" then + return tag(st, n, buffer.tostring(v)) + end + return tag(st, n, v) + end +end + +-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) +@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + undef = if o.undefined ~= nil then o.undefined else Codec.undefined, + maxDepth = o.maxDepth or 512, + dates = o.dates ~= false, + } + local v, e = item(st, 0) + if e then + return nil, e, r.pos - r.base + end + if v == BREAK then + return nil, "unexpected break", r.pos - r.base - 1 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type EncodeOptions = { + compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds + maxDepth: number?, -- default 512 (also catches cycles) +} + +type ESt = { w: Bytes.Writer, compact: boolean, sort: boolean, emptyMap: boolean, epoch: boolean, maxDepth: number, err: string? } + +@native local function head(w: Bytes.Writer, major: number, n: number) + local m = major * 32 + if n < 24 then + w:u8(m + n) + elseif n < 256 then + w:u8(m + 24) + w:u8(n) + elseif n < 65536 then + w:u8(m + 25) + w:u16be(n) + elseif n < TWO32 then + w:u8(m + 26) + w:u32be(n) + elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1 + w:u8(m + 27) + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + else + w:u8(m + 27) + w:u64be(n) + end +end + +-- the half-float bits of x when x is exactly representable, else nil +@native local function toHalf(x: number): number? + if x ~= x then + return 0x7E00 + end + local sign = if x < 0 or (x == 0 and 1 / x < 0) then 0x8000 else 0 + local a = math.abs(x) + if a == math.huge then + return sign + 0x7C00 + end + if a == 0 then + return sign + end + local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local exp = e - 1 + 15 + if exp >= 31 then + return nil + end + if exp <= 0 then -- subnormal: a = mant * 2^-24 + local mant = a / 2 ^ -24 + if mant ~= math.floor(mant) or mant >= 1024 then + return nil + end + return sign + mant + end + local frac = (m * 2 - 1) * 1024 + if frac ~= math.floor(frac) then + return nil + end + return sign + exp * 1024 + frac +end +Codec.toHalf = toHalf + +local keyLess = Types.keyLess + +local isArray = Types.isArray + +local scratch = buffer.create(8) + +@native local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xF6) + elseif v == Codec.undefined then + w:u8(0xF7) + elseif tv == "boolean" then + w:u8(if v then 0xF5 else 0xF4) + elseif tv == "number" then + if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then + if v >= 0 then + head(w, 0, v) + else + head(w, 1, -1 - v) + end + else + local h = if st.compact then toHalf(v) else nil + if h then + w:u8(0xF9) + w:u16be(h) + else + buffer.writef32(scratch, 0, v) + if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then + w:u8(0xFA) + w:f32be(v) + else + w:u8(0xFB) + w:f64be(v) + end + end + end + elseif tv == "string" then + head(w, 3, #v) + w:string(v) + elseif tv == "buffer" then + head(w, 2, buffer.len(v)) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isTagged(v) then + if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then + st.err = "bad tag number" + return false + end + head(w, 6, v.tag) + return enc(st, v.value, depth + 1) + elseif Codec.isSimple(v) then + local n = v.value + if n < 20 then + w:u8(0xE0 + n) + elseif n >= 32 and n < 256 then + w:u8(0xF8) + w:u8(n) + else + st.err = "bad simple value " .. tostring(n) + return false + end + elseif Types.Date.is(v) then + if st.epoch then + w:u8(0xC1) + return enc(st, Types.Date.toUnix(v), depth + 1) + end + w:u8(0xC0) + local s = tostring(v) + head(w, 3, #s) + w:string(s) + elseif isArray(v, st.emptyMap) then + local n = #v + head(w, 4, n) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + head(w, 5, #keys) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + compact = o.compactFloats == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + epoch = o.dates == "epoch", + maxDepth = o.maxDepth or 512, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/csv"] = function() + +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any +-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded +-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column +-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only +-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters +-- other than the doubled quote, multi-byte delimiters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Csv = { + name = "csv", + category = "data", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, +} + +type DecodeOptions = { + delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) + quote: string?, -- the quote byte (default '"') + header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) + numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) + maxRows: number?, -- refuse more rows (default unlimited) +} +type EncodeOptions = { + delimiter: string?, -- default "," + quote: string?, -- default '"' + newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) + quoteAll: boolean?, -- quote every field (default false: only those that need it) + columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) + header: boolean?, -- keyed rows: write the header row (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub + +local function patEscape(c: string): string + return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Csv.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if find(head, "%z") then + return 0 + end + local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)") + if not l1 or l1 == "" then + return 0 + end + for _, d in { ",", "\t", ";" } do + local _, c1 = gsub(l1, d, "") + local _, c2 = gsub(l2 :: string, d, "") + if c1 > 0 and c1 == c2 then + return 0.15 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function guess(s: string, q: string): string + local line = string.match(s, "^[^\r\n]*") or "" + line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "") + local best, bestN = ",", 0 + for _, d in { ",", ";", "\t", "|" } do + local _, n = gsub(line, patEscape(d), "") + if n > bestN then + best, bestN = d, n + end + end + return best +end + +-- rows(s, opts) -> { { string } } | nil, Err +function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) + local o: DecodeOptions = opts or {} + local q = o.quote or '"' + local d = o.delimiter or "," + if d == "auto" then + d = guess(s, q) + end + if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)") + end + local qb, db = byte(q), byte(d) + local stop = "[" .. patEscape(d) .. "\r\n]" + local maxRows = o.maxRows or math.huge + local rows: { { string } } = {} + local row: { string } = {} + local n = #s + local i = 1 + local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + while true do + local c = byte(s, i) + local field: string + if c == qb then + local k = i + 1 + local parts = {} + while true do + local j = find(s, q, k, true) + if not j then + return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1) + end + if byte(s, j + 1) == qb then + table.insert(parts, sub(s, k, j)) + k = j + 2 + else + table.insert(parts, sub(s, k, j - 1)) + i = j + 1 + break + end + end + -- text after the closing quote up to the delimiter is kept (Python's lenient reading) + local e = find(s, stop, i) or (n + 1) + if e > i then + table.insert(parts, sub(s, i, e - 1)) + end + i = e + field = table.concat(parts) + rowEmpty = false + else + local e = find(s, stop, i) or (n + 1) + field = sub(s, i, e - 1) + if e > i then + rowEmpty = false + end + i = e + end + table.insert(row, field) + c = byte(s, i) + if c == db then + rowEmpty = false + i += 1 + else + -- end of the row: CRLF / LF / CR / end of data + if c == 13 and byte(s, i + 1) == 10 then + i += 2 + elseif c ~= nil then + i += 1 + end + if not rowEmpty then + table.insert(rows, row) + if #rows > maxRows then + return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows") + end + end + row = {} + rowEmpty = true + if i > n then + break + end + end + end + return rows, nil +end + +local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$" +local function convert(v: string): any + if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then + local x = tonumber(v) + if x then + return x + end + end + return v +end + +function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + s = Sniff.dropBom(s) + local rows, err = Csv.parse(s, opts) + if not rows then + return nil, err + end + local o: DecodeOptions = opts or {} + if o.numbers then + for _, row in rows do + for k, v in row do + row[k] = convert(v) + end + end + end + if not o.header then + return rows, nil + end + local names = rows[1] or {} + local out = table.create(math.max(#rows - 1, 0)) + for k = 2, #rows do + local row = rows[k] + local obj = Types.object() + for c, name in names do + if row[c] ~= nil then + Types.set(obj, tostring(name), row[c]) + end + end + out[k - 1] = obj + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): (string?, string?) + local tv = type(v) + if tv == "string" then + return v, nil + elseif tv == "number" then + local s = Json.number(v) + if not s then + return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil + end + return s, nil + elseif tv == "boolean" then + return if v then "true" else "false", nil + elseif v == nil or v == Types.null then + return "", nil + elseif tv == "table" and Types.Date.is(v) then + return tostring(v), nil + end + return nil, "cannot write a " .. tv .. " as a field" +end + +local function isArray(t: any): boolean + if type(t) ~= "table" or Types.isObject(t) then + return false + end + local n = #t + return n > 0 or next(t) == nil +end + +function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n" + if #d ~= 1 or #q ~= 1 or d == q then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes") + end + if type(rows) ~= "table" then + return nil, Err.new(Err.ARG, "expected an array of rows") + end + local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]" + local qq = q .. q + local out: { string } = {} + local function writeRow(fields: { any }, count: number): Err.Err? + local parts = table.create(count) + for k = 1, count do + local s, e = text(fields[k]) + if not s then + return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e)) + end + if o.quoteAll or find(s, special) or (count == 1 and s == "") then + s = q .. gsub(s, patEscape(q), qq) .. q + end + parts[k] = s + end + table.insert(out, table.concat(parts, d) .. nl) + return nil + end + local keyed = rows[1] ~= nil and not isArray(rows[1]) + if keyed then + local cols = o.columns + if not cols then + local seen, list = {}, {} + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be tables") + end + for _, k in Types.keys(row) do + if not seen[k] then + seen[k] = true + table.insert(list, k) + end + end + end + cols = list + end + local cl = cols :: { any } + if o.header ~= false then + local e = writeRow(cl, #cl) + if e then + return nil, e + end + end + for _, row in rows do + local fields = table.create(#cl) + for k, name in cl do + fields[k] = row[name] + end + local e = writeRow(fields, #cl) + if e then + return nil, e + end + end + else + for _, row in rows do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be arrays of fields") + end + local e = writeRow(row, #row) + if e then + return nil, e + end + end + end + return buffer.fromstring(table.concat(out)), nil +end + +return Csv +end +__FILES["data/ini"] = function() + +-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. +-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, +-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at +-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a +-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level +-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested +-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Ini = { + name = "ini", + category = "data", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, +} + +type DecodeOptions = { + inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser) + allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error) + types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans + strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge) +} +type EncodeOptions = { + delimiter: string?, -- default " = " +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ini.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + local first = string.match(head, "^[%s]*([^\r\n]*)") + while first and string.match(first, "^[;#]") do + head = string.match(head, "^[^\n]*\n(.*)$") or "" + first = string.match(head, "^[%s]*([^\r\n]*)") + end + if first and string.match(first, "^%[[^%]]+%]%s*$") then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local BOOLS: { [string]: boolean } = { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false } + +local function typed(v: any): any + if type(v) ~= "string" then + return v + end + local b = BOOLS[string.lower(v)] + if b ~= nil then + return b + end + if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then + local n = tonumber(v) + if n then + return n + end + end + return v +end + +function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + s = Sniff.dropBom(s) + local root = Types.object() + local cur = root + local lastKey: string? = nil + local lastIndent = 0 + local lastTable: any = nil + local seenKeys: { [any]: { [string]: boolean } } = {} + local pos = 1 + local lineStart = 0 + for line in string.gmatch(s .. "\n", "([^\n]*)\n") do + lineStart = pos - 1 + pos += #line + 1 + line = string.gsub(line, "\r$", "") + local indent = #(string.match(line, "^[ \t]*") :: string) + local trimmed = string.match(line, "^%s*(.-)%s*$") :: string + if trimmed == "" then + lastKey = nil + elseif string.match(trimmed, "^[;#]") then + -- a comment line (configparser: also when indented); it does not end a continuation + elseif lastKey and indent > lastIndent then + -- continuation of the previous value + local v = trimmed + if o.inlineComments then + v = string.match(v, "^(.-)%s+[;#]") or v + end + local prev = lastTable[lastKey] + lastTable[lastKey] = (if type(prev) == "string" then prev else "") .. "\n" .. v + elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then + local name = string.match(trimmed, "^%[(.*)%]") :: string + local existing = root[name] + if existing ~= nil and type(existing) ~= "table" then + return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart) + end + if existing and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart) + end + if not existing then + existing = Types.object() + Types.set(root, name, existing) + end + cur = existing + lastKey = nil + else + local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$") + if not key then + if not o.allowNoValue then + return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart) + end + key, value = trimmed, true :: any + end + if key == "" then + return nil, Err.new(Err.CORRUPT, "empty key", lineStart) + end + if o.inlineComments and type(value) == "string" then + value = string.match(value, "^(.-)%s+[;#]") or (if string.match(value, "^[;#]") then "" else value) + end + local seen = seenKeys[cur] + if not seen then + seen = {} + seenKeys[cur] = seen + end + if seen[key :: string] and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate key " .. (key :: string), lineStart) + end + seen[key :: string] = true + if cur == root and type(root[key]) == "table" then + return nil, Err.new(Err.CORRUPT, "top-level key " .. (key :: string) .. " has the name of a section", lineStart) + end + Types.set(cur, key, value) + lastKey, lastIndent, lastTable = key, indent, cur + end + end + if o.types then + for _, k in Types.keys(root) do + local v = root[k] + if type(v) == "table" then + for _, k2 in Types.keys(v) do + v[k2] = typed(v[k2]) + end + else + root[k] = typed(v) + end + end + end + return root, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v: any): string? + local tv = type(v) + if tv == "string" then + return (string.gsub(v, "\n", "\n\t")) + elseif tv == "number" then + return Json.number(v) or tostring(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif v == Types.null then + return "" + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +function Ini.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "expected a table of sections") + end + local delim = (opts and opts.delimiter) or " = " + local out: { string } = {} + local err: string? = nil + local function keyOk(k: any): boolean + if type(k) ~= "string" and type(k) ~= "number" then + err = "keys must be strings" + return false + end + local ks = tostring(k) + if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then + err = "key " .. string.format("%q", ks) .. " cannot be written" + return false + end + return true + end + local function pairsOf(t: any, prefix: string, depth: number): boolean + if depth > 32 then + err = "sections nested too deeply (a cycle?)" + return false + end + local subs = {} + local lines = {} + for _, k in Types.keys(t) do + local v = t[k] + if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + table.insert(subs, k) + else + if not keyOk(k) then + return false + end + local s = text(v) + if not s then + err = "cannot write a " .. type(v) .. " value" + return false + end + table.insert(lines, tostring(k) .. delim .. s .. "\n") + end + end + if prefix ~= "" then + table.insert(out, "[" .. prefix .. "]\n") + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + elseif #lines > 0 then + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + end + for _, k in subs do + local name = tostring(k) + if string.find(name, "[\r\n%]]") then + err = "section name " .. string.format("%q", name) .. " cannot be written" + return false + end + if not pairsOf(t[k], if prefix == "" then name else prefix .. "." .. name, depth + 1) then + return false + end + end + return true + end + if not pairsOf(value, "", 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(table.concat(out)), nil +end + +return Ini +end +__FILES["data/json"] = function() + +-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). +-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or +-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local JsonFormat = { + name = "json", + category = "data", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, +} + +type DecodeOptions = Json.DecodeOptions & { + lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value) +} +type EncodeOptions = Json.EncodeOptions & { + lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line +} + +-- ------------------------------------------------------------------------------------------------ sniff +function JsonFormat.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 64) + local first = string.match(head, "^[ \t\r\n]*(.)") + if first == "{" then + local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)") + return if nxt == nil or nxt == '"' or nxt == "}" then 0.6 else 0.1 + elseif first == "[" then + -- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not) + local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)") + if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then + return 0.3 + end + return 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function JsonFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if opts and opts.lines then + local out = {} + for _, v, err in Json.lines(s, opts) do + if err then + return nil, err + end + table.insert(out, v) + end + return out, nil + end + return Json.decode(s, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function JsonFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.lines then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "lines: expected an array of values") + end + local o = table.clone(opts) :: any + o.indent = nil + local parts = {} + for i, v in value do + local s, err = Json.encode(v, o) + if not s then + return nil, err + end + parts[i] = s .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + local s, err = Json.encode(value, opts) + if not s then + return nil, err + end + if opts and opts.indent then + s ..= "\n" + end + return buffer.fromstring(s), nil +end + +return JsonFormat +end +__FILES["data/msgpack"] = function() + +-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the +-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as +-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a +-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for +-- non-integers unless opts.float32). Not supported: nothing in the spec. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/msgpack/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Msgpack = { + name = "msgpack", + category = "data", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, +} + +type DecodeOptions = Codec.DecodeOptions & { + all: boolean?, -- decode every concatenated value into an array (default false: exactly one value) +} +type EncodeOptions = Codec.EncodeOptions & { + all: boolean?, -- the value is an array of values, written one after another +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Msgpack.sniff(_r: Bytes.Reader): number + return 0 -- no magic: by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Msgpack.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.from(e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + local code = if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then Err.LIMIT + else Err.CORRUPT + return nil, Err.new(code, e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of values") + end + local w = Bytes.writer() + for _, v in value do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil + end + local b, e = Codec.encode(value, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + return b, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) +Msgpack.ext = Codec.ext +Msgpack.isExt = Codec.isExt + +return Msgpack +end +__FILES["data/msgpack/Codec"] = @native function() + + +-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with +-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- an extension value: { type = -128..127, data = buffer } +local ExtMeta = { __tostring = @native function(e: any): string + return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" +end } +@native function Codec.ext(t: number, data: buffer): { type: number, data: buffer } + return setmetatable({ type = t, data = data }, ExtMeta) :: any +end +@native function Codec.isExt(v: any): boolean + return type(v) == "table" and getmetatable(v) == ExtMeta +end + +-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact +@native local function u64text(hi: number, lo: number): string + if hi == 0 then + return string.format("%d", lo) + end + local digits = {} + -- long division by 10 on four 16-bit limbs + local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } + while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + l[k] + l[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + return table.concat(digits) +end +Codec.u64text = u64text + +type DecodeOptions = { + bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text + null: any?, -- the value for nil (default Types.null) + maxDepth: number?, -- nesting limit (default 512) + timestamps: boolean?, -- ext -1 as a Types.Date (default true) + ordered: boolean?, -- maps as Types.object with key order (default true) +} + +type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } + +@native local function int64(st: St, signed: boolean): any + local r = st.r + local hi, lo = r:u32be(), r:u32be() + if signed and hi >= 0x80000000 then + -- negative: two's complement + local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo + if nlo == TWO32 then + nlo = 0 + nhi += 1 + end + if st.big and nhi >= 0x200000 then + return "-" .. u64text(nhi, nlo) + end + return -(nhi * TWO32 + nlo) + end + if st.big and hi >= 0x200000 then + return u64text(hi, lo) + end + return hi * TWO32 + lo +end + +local value: (st: St, depth: number) -> (any, string?) + +@native local function ext(st: St, n: number): (any, string?) + local r = st.r + local t = r:i8() + if r.err or not r:need(n) then + return nil, "truncated ext" + end + if t == -1 and st.ts then + local secs, ns = 0, 0 + if n == 4 then + secs = r:u32be() + elseif n == 8 then + local hi, lo = r:u32be(), r:u32be() + ns = hi // 4 + secs = (hi % 4) * TWO32 + lo + elseif n == 12 then + ns = r:u32be() + secs = r:i64be() + else + return nil, "bad timestamp length" + end + if ns > 999999999 then + return nil, "bad timestamp nanoseconds" + end + local d: any = Types.Date.fromUnix(secs) + d.nanosecond = ns + return d, nil + end + return Codec.ext(t, r:bytes(n)), nil +end + +@native local function array(st: St, n: number, depth: number): (any, string?) + if n > st.r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n) + for k = 1, n do + local v, e = value(st, depth + 1) + if e then + return nil, e + end + t[k] = v + end + return t, nil +end + +@native local function map(st: St, n: number, depth: number): (any, string?) + if n * 2 > st.r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order: { any }? = if st.ordered then table.create(n) else nil + for _ = 1, n do + local k, e = value(st, depth + 1) + if e then + return nil, e + end + local v, e2 = value(st, depth + 1) + if e2 then + return nil, e2 + end + if k ~= k then + return nil, "NaN map key" + end + if order and t[k] == nil then + table.insert(order, k) + end + t[k] = v + end + return Types.object(t, order or {}), nil +end + +@native function value(st: St, depth: number): (any, string?) + if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local b = r:u8() + if r.err then + return nil, "truncated" + end + if b < 0x80 then + return b, nil + elseif b >= 0xE0 then + return b - 256, nil + elseif b < 0x90 then + return map(st, b - 0x80, depth) + elseif b < 0xA0 then + return array(st, b - 0x90, depth) + elseif b < 0xC0 then + local n = b - 0xA0 + if not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xC0 then + return st.null, nil + elseif b == 0xC2 then + return false, nil + elseif b == 0xC3 then + return true, nil + elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then + local n = if b == 0xC4 then r:u8() elseif b == 0xC5 then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated bin" + end + return r:bytes(n), nil + elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then + local n = if b == 0xC7 then r:u8() elseif b == 0xC8 then r:u16be() else r:u32be() + if r.err then + return nil, "truncated ext" + end + return ext(st, n) + elseif b == 0xCA then + local v = r:f32be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b == 0xCB then + local v = r:f64be() + return if r.err then nil else v, if r.err then "truncated" else nil + elseif b >= 0xCC and b <= 0xD3 then + local v: any + if b == 0xCC then + v = r:u8() + elseif b == 0xCD then + v = r:u16be() + elseif b == 0xCE then + v = r:u32be() + elseif b == 0xCF then + v = int64(st, false) + elseif b == 0xD0 then + v = r:i8() + elseif b == 0xD1 then + v = r:i16be() + elseif b == 0xD2 then + v = r:i32be() + else + v = int64(st, true) + end + if r.err then + return nil, "truncated" + end + return v, nil + elseif b >= 0xD4 and b <= 0xD8 then + return ext(st, 2 ^ (b - 0xD4)) + elseif b >= 0xD9 and b <= 0xDB then + local n = if b == 0xD9 then r:u8() elseif b == 0xDA then r:u16be() else r:u32be() + if r.err or not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xDC or b == 0xDD then + local n = if b == 0xDC then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return array(st, n, depth) + elseif b == 0xDE or b == 0xDF then + local n = if b == 0xDE then r:u16be() else r:u32be() + if r.err then + return nil, "truncated" + end + return map(st, n, depth) + end + return nil, string.format("reserved type byte 0x%02x", b) +end + +-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) +@native function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) + local o: DecodeOptions = opts or {} + local st: St = { + r = r, + big = o.bigInts == "string", + null = if o.null ~= nil then o.null else Types.null, + maxDepth = o.maxDepth or 512, + ts = o.timestamps ~= false, + ordered = o.ordered ~= false, + } + local v, e = value(st, 0) + if e then + return nil, e, r.pos - r.base + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type EncodeOptions = { + float32: boolean?, -- non-integer numbers as float32 (default false: float64) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + maxDepth: number?, -- default 512 (also catches cycles) + stringsAsBin: boolean?, -- strings as bin (default false: str) +} + +type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } + +@native local function writeInt(w: Bytes.Writer, v: number) + if v >= 0 then + if v < 128 then + w:u8(v) + elseif v < 256 then + w:u8(0xCC) + w:u8(v) + elseif v < 65536 then + w:u8(0xCD) + w:u16be(v) + elseif v < TWO32 then + w:u8(0xCE) + w:u32be(v) + else + w:u8(0xCF) + w:u64be(v) + end + else + if v >= -32 then + w:u8(v + 256) + elseif v >= -128 then + w:u8(0xD0) + w:u8(v + 256) + elseif v >= -32768 then + w:u8(0xD1) + w:u16be(v + 65536) + elseif v >= -2147483648 then + w:u8(0xD2) + w:u32be(v + TWO32) + else + w:u8(0xD3) + local hi = math.floor(v / TWO32) + local lo = v - hi * TWO32 + w:u32be(hi + TWO32) + w:u32be(lo) + end + end +end + +@native local function lenHeader(w: Bytes.Writer, n: number, fix: number?, fixMax: number, b8: number?, b16: number, b32: number) + if fix and n <= fixMax then + w:u8(fix + n) + elseif b8 and n < 256 then + w:u8(b8) + w:u8(n) + elseif n < 65536 then + w:u8(b16) + w:u16be(n) + else + w:u8(b32) + w:u32be(n) + end +end + +local keyLess = Types.keyLess + +local isArray = Types.isArray +Codec.isArray = isArray + +@native local function enc(st: ESt, v: any, depth: number): boolean + local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xC0) + elseif tv == "boolean" then + w:u8(if v then 0xC3 else 0xC2) + elseif tv == "number" then + if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then + writeInt(w, v) + elseif st.f32 then + w:u8(0xCA) + w:f32be(v) + else + w:u8(0xCB) + w:f64be(v) + end + elseif tv == "string" then + if st.bin then + lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6) + else + lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB) + end + w:string(v) + elseif tv == "buffer" then + lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isExt(v) then + local n = buffer.len(v.data) + if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then + w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n]) + else + lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9) + end + w:u8(v.type % 256) + w:bytes(v.data) + elseif Types.Date.is(v) then + local t = Types.Date.toUnix(v) + local secs = math.floor(t) + local ns = (v :: any).nanosecond or 0 + if ns == 0 and secs >= 0 and secs < TWO32 then + w:u8(0xD6) + w:u8(0xFF) + w:u32be(secs) + elseif secs >= 0 and secs < 2 ^ 34 then + w:u8(0xD7) + w:u8(0xFF) + w:u32be(ns * 4 + secs // TWO32) + w:u32be(secs % TWO32) + else + w:u8(0xC7) + w:u8(12) + w:u8(0xFF) + w:u32be(ns) + local hi = math.floor(secs / TWO32) + w:u32be(hi % TWO32) + w:u32be(secs - hi * TWO32) + end + elseif isArray(v, st.emptyMap) then + local n = #v + lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF) + for _, k in keys do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +@native function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) + local o: EncodeOptions = opts or {} + local st: ESt = { + w = Bytes.writer(256), + f32 = o.float32 == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + maxDepth = o.maxDepth or 512, + bin = o.stringsAsBin == true, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/nbt"] = function() + +-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and +-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and +-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / +-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression +-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. +-- Not supported: nothing in the format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +type DecodeOptions = Nbt.DecodeOptions +type EncodeOptions = Nbt.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function NbtFormat.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return if p.firstType and p.firstName then 0.6 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.Nbt = Nbt + +return NbtFormat +end +__FILES["data/plist"] = function() + +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is +-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> +-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> +-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past +-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Binary = __include("data/plist/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Plist = { + name = "plist", + category = "data", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, +} + +type DecodeOptions = { + bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + maxDepth: number?, -- default 512 +} +type EncodeOptions = { + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Plist.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 6) == "bplist" then + return 1 + end + if string.find(head, " ((opts and opts.maxDepth) or 512) then + return nil, "nested too deeply" + end + local name = node.name + if name == "dict" then + local out = Types.object() + local kids = Xml.children(node) + local i = 1 + while i <= #kids do + local k = kids[i] + if k.name ~= "key" then + return nil, "dict: expected , got <" .. k.name .. ">" + end + local v = kids[i + 1] + if not v then + return nil, "dict: without a value" + end + local val, e = xmlValue(v, opts, depth + 1) + if e then + return nil, e + end + Types.set(out, Xml.text(k), val) + i += 2 + end + return out, nil + elseif name == "array" then + local out = {} + for _, ch in Xml.children(node) do + local val, e = xmlValue(ch, opts, depth + 1) + if e then + return nil, e + end + table.insert(out, val) + end + return out, nil + elseif name == "string" then + return Xml.text(node), nil + elseif name == "integer" then + local t = string.match(Xml.text(node), "^%s*(.-)%s*$") :: string + local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$") + local n: number? + if hex then + n = tonumber(hex, 16) + if n and neg == "-" then + n = -n + end + elseif string.match(t, "^[%-%+]?%d+$") then + n = tonumber(t) + if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then + return (string.gsub(t, "^%+", "")), nil + end + end + if not n then + return nil, "bad integer " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "real" then + local t = string.lower(string.match(Xml.text(node), "^%s*(.-)%s*$") :: string) + local n = tonumber(t) + if not n then + if t == "nan" or t == "+nan" or t == "-nan" then + n = 0 / 0 + elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then + n = math.huge + elseif t == "-inf" or t == "-infinity" then + n = -math.huge + end + end + if not n then + return nil, "bad real " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "true" then + return true, nil + elseif name == "false" then + return false, nil + elseif name == "date" then + local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$"))) + if not d then + return nil, "bad date" + end + return d, nil + elseif name == "data" then + local b, e = Base64.decode(Xml.text(node)) + if not b then + return nil, e + end + return b, nil + end + return nil, "unknown element <" .. tostring(name) .. ">" +end + +function Plist.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local len = r.limit - r.base + if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then + local v, e = Binary.decode(r.buf, r.base, len, opts) + if e then + return nil, Err.from(e) + end + return v, nil + end + local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if root.name == "plist" then + local kids = Xml.children(root) + if #kids ~= 1 then + return nil, Err.new(Err.CORRUPT, " must hold exactly one value") + end + root = kids[1] + end + local v, e = xmlValue(root, opts, 0) + if e then + return nil, Err.new(Err.CORRUPT, e) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HEADER = '\n\n\n' + +local function esc(s: string): (string?, string?) + if string.find(s, "[%z\1-\8\11\12\14-\31]") then + return nil, "strings cannot contain control characters" + end + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil +end + +local function keyLess(a: any, b: any): boolean + return a < b +end + +function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local sort = not (opts and opts.sortKeys == false) + local out: { string } = { HEADER } + local err: string? = nil + local function line(level: number, s: string) + table.insert(out, string.rep("\t", level) .. s .. "\n") + end + local write: (v: any, level: number, depth: number) -> boolean + function write(v: any, level: number, depth: number): boolean + if depth > 512 then + err = "nested deeper than 512 (a cycle?)" + return false + end + local tv = type(v) + if tv == "string" then + local s, e = esc(v) + if not s then + err = e + return false + end + line(level, "" .. s .. "") + elseif tv == "boolean" then + line(level, if v then "" else "") + elseif tv == "number" then + if v == math.floor(v) and math.abs(v) < 2 ^ 63 then + line(level, "" .. string.format("%d", v) .. "") + else + local s = Json.number(v) + if not s then + s = if v ~= v then "nan" elseif v > 0 then "inf" else "-inf" + end + line(level, "" .. s .. "") + end + elseif tv == "buffer" then + line(level, "") + local maxLine = math.max(16, 76 - 8 * level) + for l in string.gmatch(Base64.encode(v, { wrap = maxLine // 4 * 4 }), "[^\n]+") do + line(level, l) + end + line(level, "") + elseif tv == "table" and Types.Date.is(v) then + local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v))) + line(level, string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", d.year :: number, d.month :: number, d.day :: number, d.hour :: number, d.minute :: number, d.second :: number)) + elseif tv == "table" and Binary.isUid(v) then + err = "UIDs can only be written to binary plists" + return false + elseif tv == "table" and v ~= Types.null then + local n = #v + local isArray = false + if not Types.isObject(v) then + local c = 0 + for _ in next, v do + c += 1 + end + isArray = c == n + end + if isArray then + if n == 0 then + line(level, "") + return true + end + line(level, "") + for k = 1, n do + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + else + local keys: { any } + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + end + for _, k in keys do + if type(k) ~= "string" then + err = "dict keys must be strings" + return false + end + end + if sort and not Types.isObject(v) then + table.sort(keys, keyLess) + end + if #keys == 0 then + line(level, "") + return true + end + line(level, "") + for _, k in keys do + local ks, e = esc(k) + if not ks then + err = e + return false + end + line(level + 1, "" .. ks .. "") + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "") + end + else + err = "cannot write " .. (if v == Types.null then "null" else "a " .. tv) .. " in a plist" + return false + end + return true + end + if not write(value, 0, 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + table.insert(out, "\n") + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.isUid = Binary.isUid + +return Plist +end +__FILES["data/plist/Binary"] = @native function() + + +-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in +-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte +-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, +-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles +-- are errors. Never throws: errors return nil, message. +local Types = __include("Types") + +local Binary = {} + +local readu8 = buffer.readu8 +local TWO32 = 4294967296 +local EPOCH_2001 = 978307200 + +local UidMeta = { __tostring = @native function(u: any): string + return "UID(" .. u.uid .. ")" +end } +@native function Binary.uid(n: number): { uid: number } + return setmetatable({ uid = n }, UidMeta) :: any +end +@native function Binary.isUid(v: any): boolean + return type(v) == "table" and getmetatable(v) == UidMeta +end + +@native local function be(b: buffer, o: number, n: number): number + local v = 0 + for k = 0, n - 1 do + v = v * 256 + readu8(b, o + k) + end + return v +end + +@native local function utf8char(c: number): string + if c < 0x80 then + return string.char(c) + elseif c < 0x800 then + return string.char(0xC0 + c // 64, 0x80 + c % 64) + elseif c < 0x10000 then + return string.char(0xE0 + c // 4096, 0x80 + (c // 64) % 64, 0x80 + c % 64) + end + return string.char(0xF0 + c // 262144, 0x80 + (c // 4096) % 64, 0x80 + (c // 64) % 64, 0x80 + c % 64) +end + +type Options = { bigInts: ("number" | "string")?, maxDepth: number? } + +-- decode(buf, base, len, opts) -> value | nil, message +@native function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) + if len < 40 then + return nil, "truncated: shorter than header + trailer" + end + local t = base + len - 32 + local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7) + local numObjects = be(b, t + 8, 8) + local top = be(b, t + 16, 8) + local tableOff = be(b, t + 24, 8) + if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then + return nil, "bad trailer sizes" + end + if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then + return nil, "bad trailer" + end + local maxDepth = (opts and opts.maxDepth) or 512 + local cache: { [number]: any } = {} + local busy: { [number]: boolean } = {} + + local object: (idx: number, depth: number) -> (any, string?) + + -- a length nibble: 0..14, or 15 = an int object follows + @native local function count(o: number, nib: number): (number?, number) + if nib < 15 then + return nib, o + 1 + end + if o + 2 > len - 32 then + return nil, 0 + end + local m = readu8(b, base + o + 1) + if m // 16 ~= 1 then + return nil, 0 + end + local w = 2 ^ (m % 16) + if w > 8 or o + 2 + w > len - 32 then + return nil, 0 + end + return be(b, base + o + 2, w), o + 2 + w + end + + @native local function ref(at: number): number + return be(b, base + at, refSize) + end + + @native function object(idx: number, depth: number): (any, string?) + local cached = cache[idx] + if cached ~= nil then + return cached, nil + end + if busy[idx] then + return nil, "object references form a cycle" + end + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth + end + if idx >= numObjects then + return nil, "object reference out of range" + end + local o = be(b, base + tableOff + idx * offSize, offSize) + if o < 8 or o >= len - 32 then + return nil, "object offset out of range" + end + local marker = readu8(b, base + o) + local hi, nib = marker // 16, marker % 16 + local v: any + if marker == 0x00 then + v = Types.null + elseif marker == 0x08 then + v = false + elseif marker == 0x09 then + v = true + elseif hi == 1 then + local w = 2 ^ nib + if w > 16 or o + 1 + w > len - 32 then + return nil, "bad integer" + end + if w == 16 then + o += 8 + w = 8 + end + if w == 8 then + local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4) + if h >= 0x80000000 and nib == 3 then + v = (h - TWO32) * TWO32 + l + elseif opts and opts.bigInts == "string" and h >= 0x200000 then + -- exact decimal text of h * 2^32 + l + local digits = {} + local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } + while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + limbs[k] + limbs[k] = cur // 10 + rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + v = table.concat(digits) + else + v = h * TWO32 + l + end + else + v = be(b, base + o + 1, w) + end + elseif hi == 2 then + if nib == 2 and o + 5 <= len - 32 then + local s = buffer.create(4) + for k = 0, 3 do + buffer.writeu8(s, k, readu8(b, base + o + 4 - k)) + end + v = buffer.readf32(s, 0) + elseif nib == 3 and o + 9 <= len - 32 then + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + v = buffer.readf64(s, 0) + else + return nil, "bad real" + end + elseif marker == 0x33 then + if o + 9 > len - 32 then + return nil, "truncated date" + end + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + local secs = buffer.readf64(s, 0) + if secs ~= secs or math.abs(secs) > 1e14 then + return nil, "bad date" + end + v = Types.Date.fromUnix(secs + EPOCH_2001) + elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local bytes = if hi == 6 then n * 2 else n + if p + bytes > len - 32 then + return nil, "string / data past the end" + end + if hi == 4 then + local d = buffer.create(bytes) + buffer.copy(d, 0, b, base + p, bytes) + v = d + elseif hi == 6 then + local parts = table.create(n) + local k = 0 + while k < n do + local u = be(b, base + p + k * 2, 2) + k += 1 + if u >= 0xD800 and u <= 0xDBFF and k < n then + local lo = be(b, base + p + k * 2, 2) + if lo >= 0xDC00 and lo <= 0xDFFF then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + k += 1 + end + end + table.insert(parts, utf8char(u)) + end + v = table.concat(parts) + else + v = buffer.readstring(b, base + p, bytes) + end + elseif hi == 8 then + if o + 2 + nib > len - 32 then + return nil, "bad UID" + end + v = Binary.uid(be(b, base + o + 1, nib + 1)) + elseif hi == 0xA or hi == 0xC or hi == 0xD then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local refs = if hi == 0xD then n * 2 else n + if p + refs * refSize > len - 32 then + return nil, "collection past the end" + end + busy[idx] = true + if hi == 0xD then + local t2 = {} + local order = table.create(n) + for k = 0, n - 1 do + local key, ke = object(ref(p + k * refSize), depth + 1) + if ke then + return nil, ke + end + if type(key) ~= "string" then + return nil, "dict key is not a string" + end + local val, ve = object(ref(p + (n + k) * refSize), depth + 1) + if ve then + return nil, ve + end + if t2[key] == nil then + table.insert(order, key) + end + t2[key] = val + end + v = Types.object(t2, order) + else + local arr = table.create(n) + for k = 0, n - 1 do + local item, ie = object(ref(p + k * refSize), depth + 1) + if ie then + return nil, ie + end + arr[k + 1] = item + end + v = arr + end + busy[idx] = nil + else + return nil, string.format("unknown object marker 0x%02x", marker) + end + cache[idx] = v + return v, nil + end + + return object(top, 0) +end + +return Binary +end +__FILES["data/snbt"] = function() + +-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over +-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt +-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +type DecodeOptions = { maxDepth: number? } +type EncodeOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- '"' (default) or "'" +} + +-- ------------------------------------------------------------------------------------------------ sniff +function SnbtFormat.sniff(r: Bytes.Reader): number + -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat +end +__FILES["data/toml"] = function() + +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, +-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range +-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules +-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / +-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to +-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral +-- values are written as integers). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("data/toml/Decode") +local Encode = __include("data/toml/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Toml = { + name = "toml", + category = "data", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, +} + +type DecodeOptions = Decode.Options +type EncodeOptions = Encode.Options + +-- ------------------------------------------------------------------------------------------------ sniff +-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, +-- so this stays low and the extension decides +function Toml.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + for line in string.gmatch(head, "[^\n]+") do + local l = string.match(line, "^[ \t]*(.-)[ \t\r]*$") :: string + if l ~= "" and string.sub(l, 1, 1) ~= "#" then + if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then + return 0.2 + end + return 0 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Toml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + local v, msg, at = Decode.decode(s, opts) + if v == nil then + local m = tostring(msg) + local code = if string.find(m, "unterminated", 1, true) then Err.TRUNCATED else Err.CORRUPT + return nil, Err.new(code, m, at) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Toml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Toml +end +__FILES["data/toml/Decode"] = function() + +-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with +-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control +-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and +-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char + +type Options = { + bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") +} + +local utf8char = Text.utf8char + +local ESC: { [number]: string } = { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" } + +-- digits with single underscores between them +local function digitsOk(d: string, class: string): boolean + return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil +end + +function Decode.decode(s: string, opts: Options?): (any, any, number?) + local bigStrings = opts ~= nil and opts.bigInts == "string" + local errMsg: string = "" + local errAt = 0 + local function fail(msg: string, at: number): nil + errMsg, errAt = msg, at - 1 + return nil + end + + -- input checks: BOM, UTF-8, control characters, bare CR + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + do + local bad = find(s, "[%z\1-\8\11\12\14-\31\127]") + if bad then + return nil, "control character", bad - 1 + end + local cr = find(s, "\r[^\n]") or (if byte(s, #s) == 13 then #s else nil) + if cr then + return nil, "carriage return without a line feed", cr - 1 + end + if find(s, "[\128-\255]") then + if not utf8.len(s) then + return nil, "invalid UTF-8", 0 + end + local sur = find(s, "\237[\160-\191]") + if sur then + return nil, "invalid UTF-8 (surrogate)", sur - 1 + end + end + if find(s, "\r", 1, true) then + s = gsub(s, "\r\n", "\n") + end + end + local n = #s + + -- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made + local kinds: { [any]: string } = {} + local sections: { [any]: number } = {} + local aot: { [any]: boolean } = {} -- arrays of tables ([[x]]); other arrays are static + local arrays: { [any]: boolean } = {} + local section = 0 + local building: { any }? = nil -- tables created inside the inline table being parsed (frozen when it closes) + + local function newTable(kind: string): any + local t = Types.object({}, {}) + kinds[t] = kind + if building then + table.insert(building, t) + end + return t + end + + local function ws(i: number): number + return match(s, "^[ \t]*()", i) :: any + end + -- whitespace, newlines and comments (inside arrays) + local function wsnl(i: number): number + while true do + i = match(s, "^[ \t\n]*()", i) :: any + if byte(s, i) == 35 then + i = find(s, "\n", i, true) or (n + 1) + else + return i + end + end + end + + local function escape(p: number, parts: { string }): number? + local e = byte(s, p + 1) + local simple = if e then ESC[e] else nil + if simple then + table.insert(parts, simple) + return p + 2 + elseif e == 117 or e == 85 then + local len = if e == 117 then 4 else 8 + local h = match(s, "^" .. string.rep("%x", len), p + 2) + if not h then + return fail("bad unicode escape", p) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + return fail("unicode escape is not a scalar value", p) + end + table.insert(parts, utf8char(cp)) + return p + 2 + len + end + return fail("bad escape", p) + end + + -- strings: value, next | nil + local function basic(i: number): (string?, number) + local parts = {} + local j = i + 1 + while true do + local p = find(s, '["\\\n]', j) + if not p or byte(s, p) == 10 then + return fail("unterminated string", p or n + 1), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + return table.concat(parts), p + 1 + end + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + local function multiBasic(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local parts = {} + while true do + local p = find(s, '["\\]', j) + if not p then + return fail("unterminated multi-line string", i), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + if sub(s, p, p + 2) == '"""' then + local q = p + 3 + local extra = 0 + while byte(s, q) == 34 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 34 then + return fail("too many quotes", q), 0 + end + table.insert(parts, string.rep('"', extra)) + return table.concat(parts), q + end + table.insert(parts, '"') + j = p + 1 + else + local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p) + if k then + j = k :: any + else + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + end + end + local function literal(i: number): (string?, number) + local e = find(s, "['\n]", i + 1) + if not e or byte(s, e) == 10 then + return fail("unterminated literal string", e or n + 1), 0 + end + return sub(s, i + 1, e - 1), e + 1 + end + local function multiLiteral(i: number): (string?, number) + local j = i + 3 + if byte(s, j) == 10 then + j += 1 + end + local e = find(s, "'''", j, true) + if not e then + return fail("unterminated multi-line literal string", i), 0 + end + local q = e + 3 + local extra = 0 + while byte(s, q) == 39 and extra < 2 do + extra += 1 + q += 1 + end + if byte(s, q) == 39 then + return fail("too many quotes", q), 0 + end + return sub(s, j, e - 1) .. string.rep("'", extra), q + end + + -- a (dotted) key: { parts }, next | nil + local function key(i: number): ({ string }?, number) + local keys: { string } = {} + while true do + i = ws(i) + local c = byte(s, i) + local k: string? + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return fail("multi-line string as a key", i), 0 + end + k, i = basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return fail("multi-line string as a key", i), 0 + end + k, i = literal(i) + else + k = match(s, "^[%w_%-]+", i) + if k then + i += #k + else + return fail("expected a key", i), 0 + end + end + if k == nil then + return nil, 0 + end + table.insert(keys, k :: string) + i = ws(i) + if byte(s, i) == 46 then + i += 1 + else + return keys, i + end + end + end + + -- numbers and datetimes + local function number(i: number): (any, number) + local tok = match(s, "^[%+%-]?[%w_%.]+", i) + if not tok then + return fail("expected a value", i), 0 + end + local last = byte(tok, #tok) + if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then + local ext = match(s, "^[%+%-][%w_]*", i + #tok) + if ext then + tok ..= ext + end + end + local nexti = i + #tok + local sign, body = match(tok, "^([%+%-]?)(.*)$") + if body == "inf" or body == "nan" then + return (if body == "nan" then 0 / 0 elseif sign == "-" then -math.huge else math.huge), nexti + end + local prefix = sub(body :: string, 1, 2) + if prefix == "0x" or prefix == "0o" or prefix == "0b" then + if sign ~= "" then + return fail("sign on a non-decimal integer", i), 0 + end + local d = sub(body :: string, 3) + local class = if prefix == "0x" then "%x" elseif prefix == "0o" then "0-7" else "01" + if not digitsOk(d, class) then + return fail("bad integer", i), 0 + end + d = gsub(gsub(d, "_", ""), "^0+", "") + local over = if prefix == "0x" then #d > 16 or (#d == 16 and (tonumber(sub(d, 1, 1), 16) :: number) >= 8) + elseif prefix == "0o" then #d > 21 + else #d > 63 + if over then + return fail("integer out of 64-bit range", i), 0 + end + if d == "" then + return 0, nexti + end + local v = tonumber(d, if prefix == "0x" then 16 elseif prefix == "0o" then 8 else 2) :: number + if bigStrings and v >= 9007199254740992 then + return prefix .. d, nexti + end + return v, nexti + end + local ip, rest = match(body :: string, "^([%d_]+)(.*)$") + if not ip or not digitsOk(ip, "%d") then + return fail("bad number", i), 0 + end + local digits = gsub(ip, "_", "") + if #digits > 1 and byte(digits, 1) == 48 then + return fail("leading zero", i), 0 + end + if rest == "" then + local limit = if sign == "-" then "9223372036854775808" else "9223372036854775807" + if #digits > 19 or (#digits == 19 and digits > limit) then + return fail("integer out of 64-bit range", i), 0 + end + local v = tonumber(digits) :: number + if bigStrings and v >= 9007199254740992 then + return (if sign == "-" then "-" else "") .. digits, nexti + end + return if sign == "-" then -v else v, nexti + end + local text: string = (sign :: string) .. digits + local frac, r2 = match(rest :: string, "^%.([%d_]*)(.*)$") + if frac then + if not digitsOk(frac, "%d") then + return fail("bad fraction", i), 0 + end + text ..= "." .. gsub(frac, "_", "") + rest = r2 + end + if rest ~= "" then + local es, ed = match(rest :: string, "^[eE]([%+%-]?)([%d_]*)$") + if not es or not digitsOk(ed :: string, "%d") then + return fail("bad float", i), 0 + end + text ..= "e" .. es .. gsub(ed :: string, "_", "") + end + local v = tonumber(text) + if v == nil then + return fail("bad float", i), 0 + end + return v, nexti + end + + local function datetime(i: number): (any, number) + local j = i + if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then + j = i + 10 + local c = byte(s, j) + if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then + j += 1 + elseif c == 84 or c == 116 then + return fail("bad datetime", i), 0 + else + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad date", i), 0 + end + return d, j + end + end + local t = match(s, "^%d%d:%d%d:%d%d", j) + if not t then + return fail("bad time (seconds are required)", j), 0 + end + j += 8 + local frac = match(s, "^%.%d+", j) + if frac then + j += #frac + elseif byte(s, j) == 46 then + return fail("bad fraction", j), 0 + end + if j - i > 19 or match(s, "^%d%d%d%d%-", i) then + local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j) + if off then + j += #off + end + end + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad datetime", i), 0 + end + return d, j + end + + local value: (i: number) -> (any, number) + local assign: (tbl: any, keys: { string }, v: any, sid: number, at: number) -> boolean + + local function array(i: number): (any, number) + local arr = {} + arrays[arr] = true + i += 1 + while true do + i = wsnl(i) + local c = byte(s, i) + if c == 93 then + return arr, i + 1 + elseif c == nil then + return fail("unterminated array", i), 0 + end + local v, ni = value(i) + if v == nil then + return nil, 0 + end + table.insert(arr, v) + i = wsnl(ni) + c = byte(s, i) + if c == 44 then + i += 1 + elseif c == 93 then + return arr, i + 1 + else + return fail(if c == nil then "unterminated array" else "expected ',' or ']'", i), 0 + end + end + end + + local function inline(i: number): (any, number) + local outer = building + local mine = {} + building = mine + local t = newTable("inline") + section += 1 + local sid = section + i = ws(i + 1) + if byte(s, i) == 125 then + building = outer + return t, i + 1 + end + while true do + local keys, ni = key(i) + if not keys then + return nil, 0 + end + i = ws(ni) + if byte(s, i) ~= 61 then + return fail("expected '='", i), 0 + end + local v, vi = value(ws(i + 1)) + if v == nil then + return nil, 0 + end + if not assign(t, keys, v, sid, i) then + return nil, 0 + end + i = ws(vi) + local c = byte(s, i) + if c == 44 then + i = ws(i + 1) + if byte(s, i) == 125 then + return fail("trailing comma in an inline table", i), 0 + end + elseif c == 125 then + break + else + return fail(if c == 10 then "newline in an inline table" else "expected ',' or '}'", i), 0 + end + end + for _, x in mine do + kinds[x] = "inline" + end + building = outer + if outer then + for _, x in mine do + table.insert(outer, x) + end + end + return t, i + 1 + end + + function value(i: number): (any, number) + local c = byte(s, i) + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return multiBasic(i) + end + return basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return multiLiteral(i) + end + return literal(i) + elseif c == 116 then + if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then + return true, i + 4 + end + elseif c == 102 then + if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then + return false, i + 5 + end + elseif c == 91 then + return array(i) + elseif c == 123 then + return inline(i) + elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then + if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then + return datetime(i) + end + return number(i) + end + return fail(if c == nil or c == 10 then "expected a value" else "bad value", i), 0 + end + + function assign(tbl: any, keys: { string }, v: any, sid: number, at: number): boolean + local t = tbl + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("dotted") + sections[nt] = sid + Types.set(t, k, nt) + t = nt + elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then + t = x + else + fail("cannot add to " .. k .. " with a dotted key (already defined)", at) + return false + end + end + local k = keys[#keys] + if t[k] ~= nil then + fail("duplicate key " .. k, at) + return false + end + Types.set(t, k, v) + return true + end + + -- after a key / value or a header: spaces, an optional comment, then a newline or the end + local function eol(i: number): number? + i = ws(i) + local c = byte(s, i) + if c == 35 then + return find(s, "\n", i, true) or (n + 1) + elseif c == 10 or c == nil then + return i + end + return fail("expected the end of the line", i) + end + + local root = newTable("explicit") + local cur = root + local i = 1 + while true do + i = ws(i) + local c = byte(s, i) + if c == nil then + break + elseif c == 10 then + i += 1 + elseif c == 35 then + i = find(s, "\n", i, true) or (n + 1) + elseif c == 91 then + local at = i + local isAot = byte(s, i + 1) == 91 + local keys, ni = key(i + (if isAot then 2 else 1)) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if isAot then + if sub(s, ni, ni + 1) ~= "]]" then + return nil, "expected ']]'", ni - 1 + end + ni += 2 + else + if byte(s, ni) ~= 93 then + return nil, "expected ']'", ni - 1 + end + ni += 1 + end + -- walk to the parent + local t = root + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("implicit") + Types.set(t, k, nt) + t = nt + elseif kinds[x] and kinds[x] ~= "inline" then + t = x + elseif aot[x] then + t = x[#x] + else + return nil, "cannot define a table under " .. k .. " (already defined)", at - 1 + end + end + local k = keys[#keys] + local x = t[k] + if isAot then + local arr = x + if arr == nil then + arr = {} + aot[arr] = true + Types.set(t, k, arr) + elseif not aot[arr] then + return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1 + end + local nt = newTable("explicit") + table.insert(arr, nt) + cur = nt + else + if x == nil then + local nt = newTable("explicit") + Types.set(t, k, nt) + cur = nt + elseif kinds[x] == "implicit" then + kinds[x] = "explicit" + cur = x + else + return nil, "table " .. k .. " defined twice", at - 1 + end + end + section += 1 + local e = eol(ni) + if not e then + return nil, errMsg, errAt + end + i = e + else + local at = i + local keys, ni = key(i) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if byte(s, ni) ~= 61 then + return nil, "expected '='", ni - 1 + end + local v, vi = value(ws(ni + 1)) + if v == nil then + return nil, errMsg, errAt + end + if not assign(cur, keys, v, section, at) then + return nil, errMsg, errAt + end + local e = eol(vi) + if not e then + return nil, errMsg, errAt + end + i = e + end + end + return root, nil, nil +end + +return Decode +end +__FILES["data/toml/Encode"] = function() + +-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables +-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as +-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date +-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, +-- message. +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +local Encode = {} + +local format, gsub, find = string.format, string.gsub, string.find + +type Options = { + inline: boolean?, -- write every sub-table as an inline table (default false: [sections]) + indent: (number | string)?, -- indent keys of nested sections (default none) +} + +local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } +for c = 0, 31 do + local ch = string.char(c) + if not ESC[ch] then + ESC[ch] = format("\\u%04X", c) + end +end + +local function quote(str: string): string + return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"' +end +Encode.quote = quote + +local function keyText(k: string): string + if find(k, "^[%w_%-]+$") then + return k + end + return quote(k) +end + +-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays +local function isMap(t: { [any]: any }): boolean + if Types.isObject(t) then + return true + end + local n = #t + if n == 0 then + return next(t) ~= nil + end + local count = 0 + for _ in next, t do + count += 1 + end + return count ~= n +end + +local function isDate(v: any): boolean + return Types.Date.is(v) +end + +-- an array of tables: non-empty, every element a map +local function isAot(v: any): boolean + if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then + return false + end + for _, x in v do + if type(x) ~= "table" or isDate(x) or not isMap(x) then + return false + end + end + return true +end + +local function keysOf(t: { [any]: any }): ({ string }?, string?) + local keys = Types.keys(t) + for _, k in keys do + if type(k) ~= "string" then + return nil, "table key of type " .. type(k) + end + end + return keys :: any, nil +end + +type State = { seen: { [any]: boolean }, err: string? } + +local inlineValue: (st: State, v: any) -> string? + +local function scalar(st: State, v: any): string? + local tv = type(v) + if v == Types.null then + st.err = "TOML has no null" + return nil + elseif tv == "string" then + return quote(v) + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + if v ~= v then + return "nan" + elseif v == math.huge then + return "inf" + elseif v == -math.huge then + return "-inf" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then + return format("%d", v) + end + local t = Json.number(v) :: string + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + elseif tv == "table" and isDate(v) then + return tostring(v) + elseif tv == "table" then + return inlineValue(st, v) + end + st.err = "cannot encode a " .. tv + return nil +end + +function inlineValue(st: State, v: any): string? + if st.seen[v] then + st.err = "a table contains itself" + return nil + end + st.seen[v] = true + local parts = {} + if isMap(v) then + local keys, kerr = keysOf(v) + if not keys then + st.err = kerr + return nil + end + for _, k in keys do + local s = scalar(st, v[k]) + if not s then + return nil + end + table.insert(parts, keyText(k) .. " = " .. s) + end + st.seen[v] = nil + return if #parts == 0 then "{}" else "{ " .. table.concat(parts, ", ") .. " }" + end + for i = 1, #v do + local s = scalar(st, v[i]) + if not s then + return nil + end + parts[i] = s + end + st.seen[v] = nil + return "[" .. table.concat(parts, ", ") .. "]" +end + +local function section(st: State, t: any, path: string, out: { string }, inlineAll: boolean, ind: string, depth: number): boolean + if st.seen[t] then + st.err = "a table contains itself" + return false + end + st.seen[t] = true + local keys, kerr = keysOf(t) + if not keys then + st.err = kerr + return false + end + local pad = string.rep(ind, depth) + local subs = {} + for _, k in keys do + local v = t[k] + if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then + table.insert(subs, k) + else + local s = scalar(st, v) + if not s then + return false + end + table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n") + end + end + for _, k in subs do + local v = t[k] + local p = (if path == "" then "" else path .. ".") .. keyText(k) + if isMap(v) then + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[" .. p .. "]\n") + if not section(st, v, p, out, inlineAll, ind, depth + 1) then + return false + end + else + for _, el in v do + table.insert(out, (if #out > 0 then "\n" else "") .. pad .. "[[" .. p .. "]]\n") + if not section(st, el, p, out, inlineAll, ind, depth + 1) then + return false + end + end + end + end + st.seen[t] = nil + return true +end + +-- encode(t, opts) -> text | nil, message +function Encode.encode(t: any, opts: Options?): (string?, string?) + if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then + return nil, "the top level must be a table with string keys" + end + local o: Options = opts or {} + local ind = if type(o.indent) == "number" then string.rep(" ", o.indent) elseif type(o.indent) == "string" then o.indent else "" + local st: State = { seen = {}, err = nil } + local out = {} + if not section(st, t, "", out, o.inline == true, ind, 0) then + return nil, st.err + end + return table.concat(out), nil +end + +return Encode +end +__FILES["data/xml"] = function() + +-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: +-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not +-- supported: external entities / DTDs, validation. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local XmlFormat = { + name = "xml", + category = "data", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, +} + +type DecodeOptions = Xml.DecodeOptions +type EncodeOptions = Xml.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function XmlFormat.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 64) + if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then + return 0.5 + end + if string.match(head, "^[ \t\r\n]*<[%a!]") then + return 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?) + return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(node) ~= "table" or type(node.name) ~= "string" then + return nil, Err.new(Err.ARG, "expected an XmlNode") + end + local s, err = Xml.encode(node, opts) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return XmlFormat +end +__FILES["data/yaml"] = function() + +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / +-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as +-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null +-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. +-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). +-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; +-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("data/yaml/Parse") +local Emit = __include("data/yaml/Emit") + +-- ------------------------------------------------------------------------------------------------ contract +local Yaml = { + name = "yaml", + category = "data", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, +} + +type DecodeOptions = Parse.Options +type EncodeOptions = Emit.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Yaml.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^%%YAML ") then + return 0.9 + end + if string.match(head, "^%-%-%-[ \r\n]") then + return 0.5 + end + local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)") + if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err +function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local docs, code, msg, at = Parse.run(text, opts) + if not docs then + return nil, Err.new(code, msg, at) + end + if opts and opts.all then + return docs, nil + end + local first = docs[1] + if first == nil then + return if opts and opts.null ~= nil then opts.null else Types.null, nil + end + return first, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) +function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Emit.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Yaml +end +__FILES["data/yaml/Emit"] = function() + +-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when +-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars +-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as +-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad +-- values (cycles, functions, collection keys) return nil, message. +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Parse = __include("data/yaml/Parse") + +local Emit = {} + +type Options = { + indent: number?, -- spaces per level (default 2) + all: boolean?, -- the value is an array of documents, written with "---" separators + explicitStart: boolean?, -- start the (first) document with "---" (default false) + sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order) + null: any?, -- the value written as null besides Types.null +} + +local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub + +local YAML11 = { + y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true, + on = true, On = true, ON = true, off = true, Off = true, OFF = true, +} + +local function number(x: number): string + if x ~= x then + return ".nan" + elseif x == math.huge then + return ".inf" + elseif x == -math.huge then + return "-.inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + if x == 0 and 1 / x < 0 then + return "-0.0" + end + return format("%d", x) + end + for _, f in { "%.15g", "%.16g", "%.17g" } do + local t = format(f, x) + if tonumber(t) == x then + if not find(t, "[%.eEn]") then + t ..= ".0" + end + return t + end + end + return format("%.17g", x) +end + +local DQ: { [string]: string } = { + ["\\"] = "\\\\", + ['"'] = '\\"', + ["\n"] = "\\n", + ["\t"] = "\\t", + ["\r"] = "\\r", + ["\0"] = "\\0", + ["\27"] = "\\e", +} +local function dquote(s: string): string + s = gsub(s, '[%z\1-\31\127\\"]', function(c: string): string + return DQ[c] or format("\\x%02x", byte(c)) + end) + -- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them + s = gsub(s, "\226\128\168", "\\L") + s = gsub(s, "\226\128\169", "\\P") + s = gsub(s, "\194\133", "\\N") + return '"' .. s .. '"' +end + +local function plainOk(s: string): boolean + if s == "" or YAML11[s] then + return false + end + if Parse.resolve(s, Types.null) ~= s then + return false + end + if find(s, "^[%s]") or find(s, "[%s]$") then + return false + end + if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then + return false + end + if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then + return false + end + if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then + return false + end + -- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not) + if find(s, "[\128-\255]") and not utf8.len(s) then + return false + end + return true +end + +-- a string as a scalar on a line at indentation ind (for block scalars) +local function str(s: string, ind: string, key: boolean): string + if plainOk(s) then + return s + end + if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $") + and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s)) + then + local trailing = #(string.match(s, "\n*$") :: string) + local body = string.sub(s, 1, #s - trailing) + local chomp = if trailing == 0 then "-" elseif trailing == 1 then "" else "+" + local lines = string.split(body, "\n") + local out = { "|" .. chomp } + for _, l in lines do + table.insert(out, if l == "" then "" else ind .. l) + end + for _ = 2, trailing do + table.insert(out, "") + end + return table.concat(out, "\n") + end + return dquote(s) +end + +local isArray = Types.isArray + +local keyLess = Types.keyLess + +type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } + +-- count references to tables (anchors for those seen twice); false on a cycle +local function count(st: St, v: any, onStack: { [any]: boolean }): boolean + if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then + return true + end + if onStack[v] then + st.err = "a cycle (YAML aliases cannot point at their own ancestors here)" + return false + end + local r = st.refs[v] + st.refs[v] = (r or 0) + 1 + if r then + return true + end + onStack[v] = true + for k, x in next, v do + if not count(st, k, onStack) or not count(st, x, onStack) then + return false + end + end + onStack[v] = nil + return true +end + +-- scalar text for a non-collection value, or nil +local function scalar(st: St, v: any, ind: string, key: boolean): string? + local tv = type(v) + if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then + return "null" + elseif tv == "boolean" then + return if v then "true" else "false" + elseif tv == "number" then + return number(v) + elseif tv == "string" then + return str(v, ind, key) + elseif tv == "buffer" then + return "!!binary " .. Base64.encode(v) + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +local write: (st: St, v: any, depth: number) -> string? + +-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) +function write(st: St, v: any, depth: number): string? + local ind = string.rep(" ", st.step * (depth + 1)) + local s = scalar(st, v, ind, false) + if s then + return " " .. s + end + if type(v) ~= "table" then + st.err = "cannot write a " .. type(v) + return nil + end + local prefix = "" + if st.refs[v] and st.refs[v] > 1 then + local a = st.anchors[v] + if a then + return " *" .. a + end + st.nextId += 1 + a = "id" .. format("%03d", st.nextId) + st.anchors[v] = a + prefix = " &" .. a + end + local pad = string.rep(" ", st.step * depth) + if isArray(v) and not Types.isObject(v) then + if #v == 0 then + return prefix .. " []" + end + local parts = {} + for _, x in v do + local t = write(st, x, depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. "-" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") + end + local keys + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + return prefix .. " {}" + end + local parts = {} + for _, k in keys do + local ks = scalar(st, k, "", true) + if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then + st.err = "mapping keys must be scalars" + return nil + end + local t = write(st, v[k], depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. ks .. ":" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") +end + +local function document(st: St, v: any): string? + local t = write(st, v, 0) + if not t then + return nil + end + -- the top level: drop the separator write() put before the first line + if string.sub(t, 1, 1) == "\n" then + return string.sub(t, 2) + end + local body = string.sub(t, 2) + if string.sub(body, 1, 1) == "&" then + -- "&id001\n- a": an anchored top-level collection + return body + end + return body +end + +-- encode(v, opts) -> text | nil, message +function Emit.encode(v: any, opts: Options?): (string?, string?) + local o: Options = opts or {} + local st: St = { + out = {}, + step = math.clamp(math.floor(o.indent or 2), 1, 10), + sort = o.sortKeys ~= false, + null = o.null, + refs = {}, + anchors = {}, + nextId = 0, + err = nil, + } + local docs = if o.all then v else { v } + if type(docs) ~= "table" then + return nil, "all: expected an array of documents" + end + local parts = {} + for i, d in docs do + st.refs, st.anchors = {}, {} + if not count(st, d, {}) then + return nil, st.err + end + local t = document(st, d) + if not t then + return nil, st.err + end + local start = i > 1 or o.explicitStart + if start then + -- a scalar / [] / {} can share the "---" line; a collection starts on the next one + local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil + local sep = if block and not string.find(t, "^&") then "---\n" else "--- " + table.insert(parts, sep .. t .. "\n") + else + table.insert(parts, t .. "\n") + end + end + return table.concat(parts), nil +end + +return Emit +end +__FILES["data/yaml/Parse"] = function() + +-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): +-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with +-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared +-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless +-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core +-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a +-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +local Text = __include("codecs/text/Text") +local Types = __include("Types") +local Base64 = __include("core/Base64") + +local Parse = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char + +type Options = { + all: boolean?, -- every document as an array (default false: the first document; none -> Types.null) + tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged + maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard + maxDepth: number?, -- nesting limit (default 500) + null: any?, -- the value for null (default Types.null) +} + +type St = { + s: string, + n: number, + anchors: { [string]: any }, + handles: { [string]: string }, + depth: number, + maxDepth: number, + aliasNodes: number, + maxAlias: number, + sizes: { [any]: number }, + ignoreTags: boolean, + null: any, +} + +local CORE = "tag:yaml.org,2002:" + +local function raise(code: string, msg: string, p: number) + error({ yamlErr = true, code = code, msg = msg, at = p - 1 }, 0) +end +local function corrupt(msg: string, p: number) + raise("CORRUPT", msg, p) +end + +-- ------------------------------------------------------------------------------------------------ helpers +local function col(s: string, p: number): number + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + return p - q +end + +local function isWsEnd(c: number?): boolean -- space, tab, newline or the end + return c == nil or c == 32 or c == 9 or c == 10 +end + +local function docMarker(s: string, p: number): boolean + if p ~= 1 and byte(s, p - 1) ~= 10 then + return false + end + local m = sub(s, p, p + 2) + return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) +end + +-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) +local function skip(s: string, p: number): number + local n = #s + while p <= n do + local c = byte(s, p) + if c == 32 or c == 9 or c == 10 then + p += 1 + elseif c == 35 and (p == 1 or isWsEnd(byte(s, p - 1))) then + local e = find(s, "\n", p, true) + if not e then + return n + 1 + end + p = e + 1 + else + return p + end + end + return p +end + +-- the number of leading spaces on p's line, and whether a tab comes before p on it +local function lineIndent(s: string, p: number): (number, boolean) + local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q -= 1 + end + local sp = (match(s, "^ *()", q) :: number) - q + return sp, find(sub(s, q, p - 1), "\t", 1, true) ~= nil +end + +-- block content at p on a new line must not be indented with tabs: a tab before p is an error when the spaces before +-- it do not already indent the line past ind (siblings: pass ind = their column - 1... any tab is an error) +local function noTabs(s: string, p: number, ind: number?) + local sp, tab = lineIndent(s, p) + if tab and (ind == nil or sp <= ind) then + error({ yamlErr = true, code = "CORRUPT", msg = "tab in indentation", at = p - 1 }, 0) + end +end + +-- skip spaces / tabs on the line +local function skipLine(s: string, p: number): number + return match(s, "^[ \t]*()", p) :: any +end + +-- after a node on its line: only spaces and a comment may follow before the line break +local function endOfLine(s: string, p: number): boolean + local q = skipLine(s, p) + local c = byte(s, q) + return c == nil or c == 10 or (c == 35 and q > p) +end + +local utf8char = Text.utf8char + +-- ------------------------------------------------------------------------------------------------ resolution +-- the core schema: a plain scalar's value +function Parse.resolve(t: string, nullv: any): any + if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then + return nullv + end + local c = byte(t) + if c == 116 or c == 84 or c == 102 or c == 70 then + if t == "true" or t == "True" or t == "TRUE" then + return true + elseif t == "false" or t == "False" or t == "FALSE" then + return false + end + return t + end + if not ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46) then + return t + end + if match(t, "^[-+]?%d+$") then + return tonumber(if c == 43 then sub(t, 2) else t) + end + local o = match(t, "^0o([0-7]+)$") + if o then + return tonumber(o, 8) + end + local x = match(t, "^0x(%x+)$") + if x then + return tonumber(x, 16) + end + if match(t, "^[-+]?%d+%.?%d*$") or match(t, "^[-+]?%.%d+$") or match(t, "^[-+]?%d+%.?%d*[eE][-+]?%d+$") or match(t, "^[-+]?%.%d+[eE][-+]?%d+$") then + local v = tonumber(if c == 43 then sub(t, 2) else t) + if v then + return v + end + end + local inf = match(t, "^([-+]?)%.[iI][nN][fF]$") + if inf and (t == inf .. ".inf" or t == inf .. ".Inf" or t == inf .. ".INF") then + return if inf == "-" then -math.huge else math.huge + end + if t == ".nan" or t == ".NaN" or t == ".NAN" then + return 0 / 0 + end + return t +end + +local function base64(t: string): buffer? + return (Base64.decode(t)) +end + +-- a scalar's value given its tag (nil = untagged, "!" = non-specific) +local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any + if tag == nil then + return if plain then Parse.resolve(raw, st.null) else raw + end + if tag == "!" or tag == CORE .. "str" then + return raw + end + if sub(tag, 1, #CORE) == CORE then + local kind = sub(tag, #CORE + 1) + local v = Parse.resolve(raw, st.null) + if kind == "null" then + if v ~= st.null then + corrupt("bad !!null " .. raw, p) + end + return v + elseif kind == "bool" then + if type(v) ~= "boolean" then + corrupt("bad !!bool " .. raw, p) + end + return v + elseif kind == "int" then + if type(v) ~= "number" or not (match(raw, "^[-+]?%d+$") or match(raw, "^0[ox]")) then + corrupt("bad !!int " .. raw, p) + end + return v + elseif kind == "float" then + if type(v) ~= "number" then + corrupt("bad !!float " .. raw, p) + end + return v + elseif kind == "binary" then + local b = base64(raw) + if not b then + corrupt("bad !!binary data", p) + end + return b + elseif kind == "timestamp" then + local d = Types.Date.parse(raw) + if not d then + corrupt("bad !!timestamp " .. raw, p) + end + return d + elseif kind == "map" or kind == "seq" then + corrupt("!!" .. kind .. " on a scalar", p) + end + end + if st.ignoreTags then + return if plain then Parse.resolve(raw, st.null) else raw + end + raise("UNSUPPORTED", "tag " .. tag, p) + return nil +end + +local function collectionTag(st: St, tag: string?, kind: string, p: number) + if tag == nil or tag == "!" or tag == CORE .. kind then + return + end + if sub(tag, 1, #CORE) == CORE then + local k = sub(tag, #CORE + 1) + if k == "map" or k == "seq" or k == "str" or k == "int" or k == "float" or k == "bool" or k == "null" or k == "binary" then + corrupt("!!" .. k .. " on a " .. kind, p) + end + end + if not st.ignoreTags then + raise("UNSUPPORTED", "tag " .. tag, p) + end +end + +-- expansion size of a value (nodes), memoized +local function size(st: St, v: any): number + if type(v) ~= "table" or v == st.null then + return 1 + end + local m = st.sizes[v] + if m then + return m + end + local total = 1 + for k, x in next, v do + total += size(st, k) + size(st, x) + end + st.sizes[v] = total + return total +end + +-- ------------------------------------------------------------------------------------------------ properties +type Props = { anchor: string?, tag: string?, at: number } + +-- anchors / tags at p -> props?, the position after them (and the spaces after them) +local function properties(st: St, p: number): (Props?, number) + local s = st.s + local props: Props? = nil + while true do + local c = byte(s, p) + if c == 38 then -- & + local name = match(s, "^&([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad anchor", p) + end + local pr: Props = props or { at = p } + props = pr + if pr.anchor then + corrupt("two anchors on one node", p) + end + pr.anchor = name + p = skipLine(s, p + 1 + #(name :: string)) + elseif c == 33 then -- ! + local pr: Props = props or { at = p } + props = pr + if pr.tag then + corrupt("two tags on one node", p) + end + local tag: string + if byte(s, p + 1) == 60 then -- ! + local v = match(s, "^!<([^>%s]+)>", p) + if not v then + corrupt("bad verbatim tag", p) + end + tag = v :: string + p += #tag + 3 + else + local handle, suffix = match(s, "^(![%w%-]*!)([^%s,%[%]{}]*)", p) + if handle then + local prefix = st.handles[handle] + if not prefix then + corrupt("undefined tag handle " .. handle, p) + end + if suffix == "" then + corrupt("empty tag", p) + end + tag = prefix .. string.gsub(suffix :: string, "%%(%x%x)", function(h: string): string + return char(tonumber(h, 16) :: number) + end) + else + local sfx = match(s, "^!([^%s,%[%]{}]*)", p) :: string + if sfx == "" then + tag = "!" + else + tag = st.handles["!"] .. sfx + end + end + p += #(match(s, "^![^%s,%[%]{}]*", p) :: string) + end + pr.tag = tag + if not isWsEnd(byte(s, p)) and byte(s, p) ~= 44 and byte(s, p) ~= 93 and byte(s, p) ~= 125 then + corrupt("bad tag", p) + end + p = skipLine(s, p) + else + return props, p + end + end +end + +local function finish(st: St, props: Props?, v: any): any + if props and props.anchor then + st.anchors[props.anchor] = v + end + return v +end + +local function alias(st: St, p: number): (any, number) + local s = st.s + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad alias", p) + end + local v = st.anchors[name :: string] + if v == nil then + corrupt("undefined alias *" .. (name :: string), p) + end + st.aliasNodes += size(st, v) + if st.aliasNodes > st.maxAlias then + raise("LIMIT", "alias expansion over " .. st.maxAlias .. " nodes", p) + end + return v, p + 1 + #(name :: string) +end + +-- ------------------------------------------------------------------------------------------------ scalars +-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. +-- Lines holding only spaces / tabs count as empty. +local function fold(s: string, p: number): (string, number) + local empties = 0 + local q = p + 1 + while true do + local r = skipLine(s, q) + if byte(s, r) == 10 then + empties += 1 + q = r + 1 + else + return (if empties == 0 then " " else string.rep("\n", empties)), q + end + end +end + +local ESC: { [number]: string } = { + [48] = "\0", + [97] = "\a", + [98] = "\b", + [116] = "\t", + [9] = "\t", + [110] = "\n", + [118] = "\v", + [102] = "\f", + [114] = "\r", + [101] = "\27", + [32] = " ", + [34] = '"', + [47] = "/", + [92] = "\\", + [78] = "\194\133", + [95] = "\194\160", + [76] = "\226\128\168", + [80] = "\226\128\169", +} + +-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote +local function quoted(st: St, p: number, ind: number): (string, number) + local s = st.s + local dq = byte(s, p) == 34 + local parts: { string } = {} + local i = p + 1 + local stop = if dq then '[\\"\n]' else "['\n]" + while true do + local j = find(s, stop, i) + if not j then + raise("TRUNCATED", "unterminated quoted scalar", p) + end + local jj = j :: number + local seg = sub(s, i, jj - 1) + local c = byte(s, jj) + if c == 10 then + table.insert(parts, (string.gsub(seg, "[ \t]+$", ""))) + local f, q = fold(s, jj) + if docMarker(s, q) then + corrupt("document marker inside a quoted scalar", q) + end + if ind >= 0 and (match(s, "^ *()", q) :: number) - q <= ind then + corrupt("a quoted scalar's continuation line is not indented", q) + end + table.insert(parts, f) + i = skipLine(s, q) + elseif dq and c == 92 then + table.insert(parts, seg) + local e = byte(s, jj + 1) + if e == 10 then -- escaped line break: joined without a space + local r = jj + 2 + while true do + local q = skipLine(s, r) + if byte(s, q) == 10 then + table.insert(parts, "\n") + r = q + 1 + else + i = q + break + end + end + elseif e == 120 or e == 117 or e == 85 then + local len = if e == 120 then 2 elseif e == 117 then 4 else 8 + local h = sub(s, jj + 2, jj + 1 + len) + if #h ~= len or not match(h, "^%x+$") then + corrupt("bad escape", jj) + end + local cp = tonumber(h, 16) :: number + if cp > 0x10FFFF then + corrupt("bad escape", jj) + end + table.insert(parts, utf8char(cp)) + i = jj + 2 + len + else + local r = if e then ESC[e] else nil + if not r then + corrupt("bad escape", jj) + end + table.insert(parts, r :: string) + i = jj + 2 + end + elseif not dq and byte(s, jj + 1) == 39 then + table.insert(parts, seg .. "'") + i = jj + 2 + else + table.insert(parts, seg) + return table.concat(parts), jj + 1 + end + end +end + +-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind +-- (block context); flow: the flow-context rules (stops at , [ ] { }). +local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) + local s = st.s + local parts: { string } = {} + local i = p + local lastEnd = p + while true do + -- one line's worth + local j = i + local stopAt = nil + while true do + local c = byte(s, j) + if c == nil or c == 10 then + break + elseif c == 58 then -- : + local d = byte(s, j + 1) + if isWsEnd(d) or (flow and (d == 44 or d == 91 or d == 93 or d == 123 or d == 125)) then + stopAt = j + break + end + elseif c == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + stopAt = j + break + elseif flow and (c == 44 or c == 91 or c == 93 or c == 123 or c == 125) then + stopAt = j + break + end + j += 1 + end + local seg = string.gsub(sub(s, i, j - 1), "[ \t]+$", "") + table.insert(parts, seg) + lastEnd = i + #seg + if stopAt or byte(s, j) == nil then + return table.concat(parts), lastEnd + end + -- a continuation line? + local f, q = fold(s, j) + local r = skipLine(s, q) + local c = byte(s, r) + if c == nil or docMarker(s, q) or c == 35 or (not flow and (match(s, "^ *()", q) :: number) - q <= ind) then + return table.concat(parts), lastEnd + end + if flow and (c == 44 or c == 93 or c == 125 or (c == 58 and isWsEnd(byte(s, r + 1)))) then + return table.concat(parts), lastEnd + end + table.insert(parts, f) + i = r + end +end + +-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it +local function blockScalar(st: St, p: number, ind: number): (string, number) + local s = st.s + local folded = byte(s, p) == 62 + local q = p + 1 + local explicit: number? = nil + local chomp = "clip" + for _ = 1, 2 do + local c = byte(s, q) + if c and c >= 49 and c <= 57 and not explicit then + explicit = c - 48 + q += 1 + elseif (c == 43 or c == 45) and chomp == "clip" then + chomp = if c == 43 then "keep" else "strip" + q += 1 + end + end + if not endOfLine(s, q) then + corrupt("bad block scalar header", q) + end + local nl = find(s, "\n", q, true) + local lines: { string } = {} + local trailing = 0 -- empty lines after the last content line + if not nl then + return "", #s + 1 + end + local ls = (nl :: number) + 1 + local indent: number + if explicit then + indent = math.max(ind + explicit, 0) -- n + the indicator (n = -1 at the top level) + else + -- auto-detect: the first non-empty line; leading empty lines may not be longer + local maxEmpty = 0 + local r = ls + indent = -1 + while true do + local sp = (match(s, "^ *()", r) :: number) - r + local c = byte(s, r + sp) + if c == 10 then + maxEmpty = math.max(maxEmpty, sp) + r = r + sp + 1 + elseif c == nil then + maxEmpty = math.max(maxEmpty, sp) + indent = math.max(maxEmpty, ind + 1) + break + else + if docMarker(s, r) then + indent = math.max(maxEmpty, ind + 1) + break + end + indent = sp + if sp < maxEmpty then + corrupt("leading empty lines indented more than the block scalar", r) + end + break + end + end + if indent <= ind then + indent = ind + 1 + end + end + -- the lines + local r = ls + local pendingEmpty = 0 + local endPos = ls + while r <= #s do + if docMarker(s, r) then + break + end + local sp = (match(s, "^ *()", r) :: number) - r + local e = find(s, "\n", r, true) or (#s + 1) + if sp >= indent then + local text = sub(s, r + indent, e - 1) + for _ = 1, pendingEmpty do + table.insert(lines, "") + end + pendingEmpty = 0 + table.insert(lines, text) + elseif r + sp == e then + pendingEmpty += 1 + else + if byte(s, r + sp) == 9 then + corrupt("tab in block scalar indentation", r + sp) + end + break + end + r = e + 1 + endPos = math.min(r, #s + 1) + end + trailing = pendingEmpty + local body: string + if #lines == 0 then + body = "" + elseif not folded then + body = table.concat(lines, "\n") + else + local out: { string } = {} + local prevMore = false + local empties = 0 + local first = true + for _, l in lines do + if l == "" then + empties += 1 + else + local more = byte(l) == 32 or byte(l) == 9 + if first then + table.insert(out, string.rep("\n", empties)) + elseif empties == 0 then + table.insert(out, if more or prevMore then "\n" else " ") + else + table.insert(out, string.rep("\n", if more or prevMore then empties + 1 else empties)) + end + table.insert(out, l) + first = false + prevMore = more + empties = 0 + end + end + trailing += empties -- empty lines after the last content line (or all of them) + body = table.concat(out) + end + if not folded then + -- literal: trailing "" lines inside `lines` are content-indented empty lines; count them as trailing + local k = #lines + while k > 0 and lines[k] == "" do + k -= 1 + trailing += 1 + end + body = table.concat(lines, "\n", 1, k) + if k == 0 then + body = "" + end + lines = table.move(lines, 1, k, 1, {}) + end + local hasContent = false + for _, l in lines do + if l ~= "" then + hasContent = true + break + end + end + if chomp == "strip" then + return body, endPos + elseif chomp == "clip" then + return (if hasContent then body .. "\n" else ""), endPos + end + return (if hasContent then body .. "\n" else "") .. string.rep("\n", trailing), endPos +end + +-- ------------------------------------------------------------------------------------------------ flow +local parseFlow: (st: St, p: number, ind: number) -> (any, number) + +local function enter(st: St, p: number) + st.depth += 1 + if st.depth > st.maxDepth then + raise("LIMIT", "nested deeper than " .. st.maxDepth, p) + end +end + +-- a flow node at p (after skip) -> value, next, wasEmpty +local function flowNode(st: St, p: number, ind: number): (any, number, boolean) + local s = st.s + local props, q = properties(st, p) + if props then + q = skip(s, q) + end + local c = byte(s, q) + local v: any + if c == 42 then -- * + if props then + corrupt("properties on an alias", q) + end + return alias(st, q) + elseif c == 91 or c == 123 then + v, q = parseFlow(st, q, ind) + collectionTag(st, props and props.tag, if c == 91 then "seq" else "map", q) + return finish(st, props, v), q, false + elseif c == 34 or c == 39 then + local t, r = quoted(st, q, ind) + return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false + elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then + -- an empty node + return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true + elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then + corrupt("unexpected character in a flow collection", q) + elseif (c == 45 or c == 63 or c == 58) and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125) then + if c == 63 then + raise("UNSUPPORTED", "explicit keys (?) in flow collections", q) + end + corrupt("unexpected '" .. char(c :: number) .. "' in a flow collection", q) + end + local t, r = plain(st, q, ind, true) + return finish(st, props, scalarValue(st, t, true, props and props.tag, q)), r, false +end + +local function checkKey(st: St, k: any, p: number): any + if type(k) == "table" and k ~= st.null and not Types.Date.is(k) then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + if k ~= k then + corrupt("NaN as a mapping key", p) + end + return k +end + +function parseFlow(st: St, p: number, ind: number): (any, number) + local s = st.s + enter(st, p) + local isMap = byte(s, p) == 123 + local close = if isMap then 125 else 93 + local t: { [any]: any } = {} + local order: { any } = {} + local count = 0 + local q = p + 1 + local function flowSkip(from: number): number + local r = skip(s, from) + if ind >= 0 and r <= #s and find(sub(s, from, r), "\n", 1, true) and (lineIndent(s, r)) <= ind then + corrupt("a flow collection's line is not indented", r) + end + return r + end + while true do + q = flowSkip(q) + local c = byte(s, q) + if c == nil then + raise("TRUNCATED", "unterminated flow collection", p) + end + if docMarker(s, q) then + corrupt("document marker inside a flow collection", q) + end + if c == close then + q += 1 + break + end + local explicitKey = false + if c == 63 and isWsEnd(byte(s, q + 1)) then + explicitKey = true + q = flowSkip(q + 1) + end + local startLine = q + local k, r, empty = flowNode(st, q, ind) + r = flowSkip(r) + local hasColon = false + if byte(s, r) == 58 then + local d = byte(s, r + 1) + local jsonLike = byte(s, q) == 34 or byte(s, q) == 39 or byte(s, q) == 91 or byte(s, q) == 123 + if isWsEnd(d) or d == 44 or d == 93 or d == 125 or jsonLike then + hasColon = true + -- an implicit key must sit on one line + if not isMap and not explicitKey and find(sub(s, startLine, r), "\n", 1, true) then + corrupt("multi-line implicit key", startLine) + end + r += 1 + end + end + if isMap then + local v: any = st.null + if hasColon then + local r2 = flowSkip(r) + local cc = byte(s, r2) + if cc ~= 44 and cc ~= 125 then + v, r = flowNode(st, r2, ind) + end + end + if empty and not hasColon and not explicitKey then + corrupt("expected a mapping entry", q) + end + k = checkKey(st, k, q) + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + else + local item = k + if hasColon or explicitKey then + local v: any = st.null + local r2 = if hasColon then flowSkip(r) else r + local cc = byte(s, r2) + if hasColon and cc ~= 44 and cc ~= 93 then + v, r = flowNode(st, r2, ind) + end + k = checkKey(st, k, q) + item = Types.object({ [k] = v }, { k }) + elseif empty then + corrupt("empty sequence entry", q) + end + count += 1 + t[count] = item + end + r = flowSkip(r) + local cc = byte(s, r) + if cc == 44 then + q = r + 1 + elseif cc == close then + q = r + 1 + break + elseif cc == nil then + raise("TRUNCATED", "unterminated flow collection", p) + else + corrupt(if isMap then "expected ',' or '}'" else "expected ',' or ']'", r) + end + end + st.depth -= 1 + if isMap then + return Types.object(t, order), q + end + return t, q +end + +-- ------------------------------------------------------------------------------------------------ block +local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) + +-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +local function implicitKey(st: St, p: number): (any, number?) + local s = st.s + local c = byte(s, p) + if c == 34 or c == 39 then + local ok, t, q = pcall(quoted, st, p, -1) + if not ok then + return nil, nil + end + if find(sub(s, p, q - 1), "\n", 1, true) then + return nil, nil + end + local r = skipLine(s, q) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return t, r + 1 + end + return nil, nil + elseif c == 42 then + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + return nil, nil + end + local r = skipLine(s, p + 1 + #name) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return true, r + 1 + end + return nil, nil + elseif c == 91 or c == 123 then + -- a flow collection used as a key? + local e = find(s, "\n", p, true) or #s + 1 + local line = sub(s, p, e - 1) + if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then + local ok, _, q = pcall(parseFlow, st, p, -1) + if ok and byte(s, skipLine(s, q)) == 58 then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + end + return nil, nil + end + if c == nil or c == 10 or c == 35 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 then + return nil, nil + end + if (c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, p + 1)) then + return nil, nil + end + local j = p + while true do + local d = byte(s, j) + if d == nil or d == 10 then + return nil, nil + elseif d == 58 and isWsEnd(byte(s, j + 1)) then + break + elseif d == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + return nil, nil + end + j += 1 + end + local t = string.gsub(sub(s, p, j - 1), "[ \t]+$", "") + return t, j + 1 +end + +local function readKey(st: St, p: number, props: Props?): (any, number) + local s = st.s + local c = byte(s, p) + local tag = props and props.tag + local k: any + local q: number + if c == 42 then + if props then + corrupt("properties on an alias", p) + end + k, q = alias(st, p) + q = skipLine(s, q) + q += 1 -- the ':' + elseif c == 34 or c == 39 then + local t, r = quoted(st, p, -1) + if find(sub(s, p, r - 1), "\n", 1, true) then + corrupt("multi-line implicit key", p) + end + k = scalarValue(st, t, false, tag, p) + q = skipLine(s, r) + 1 + else + local t, after = implicitKey(st, p) + if t == nil then + corrupt("expected a mapping key", p) + end + k = scalarValue(st, t, true, tag, p) + q = after :: number + end + k = finish(st, props, k) + return checkKey(st, k, p), q +end + +-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null +local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) + local s = st.s + local r = skip(s, p) + if r <= #s and not docMarker(s, r) then + local c = col(s, r) + if c > ind or (seqAt and c == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1))) then + noTabs(s, r, ind) + return blockNode(st, ind, r, false, mapParent) + end + end + return st.null, p +end + +-- the value after a ':' (at p, just past it) of a mapping at column mc +local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) + local s = st.s + local r = skipLine(s, p) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p) then + return nextLineNode(st, mc, r, true, true) + end + return blockNode(st, mc, r, not explicit, true) +end + +local function blockMap(st: St, mc: number, p: number, firstProps: Props?): (any, number) + local s = st.s + enter(st, p) + local t: { [any]: any } = {} + local order: { any } = {} + local q = p + local first = true + while true do + local props: Props? = nil + if first and firstProps then + props = firstProps + else + props, p = properties(st, p) + end + first = false + local c = byte(s, p) + local k: any + local v: any + if ((c == 63 and not props) or c == 58) and isWsEnd(byte(s, p + 1)) then + -- "? key" (explicit) and ": value" (an empty key) + k = st.null + q = p + if c == 63 then + local r = skipLine(s, p + 1) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p + 1) then + k, q = nextLineNode(st, mc, r, true, false) + else + k, q = blockNode(st, mc, r, false, false) + end + k = checkKey(st, k, p) + local r3 = skip(s, q) + if r3 <= #s and not docMarker(s, r3) and col(s, r3) == mc and byte(s, r3) == 58 and isWsEnd(byte(s, r3 + 1)) then + v, q = mapValue(st, mc, r3 + 1, true) + else + v = st.null + end + else + k = finish(st, props, scalarValue(st, "", true, props and props.tag, p)) + v, q = mapValue(st, mc, p + 1, true) + end + else + local after + k, after = readKey(st, p, props) + v, q = mapValue(st, mc, after, false) + end + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc3 = col(s, r3) + if cc3 == mc then + noTabs(s, r3) + if byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + corrupt("a sequence entry where a mapping key is expected", r3) + end + p = r3 + elseif cc3 < mc then + break + else + corrupt("bad indentation of a mapping entry", r3) + end + end + st.depth -= 1 + return Types.object(t, order), q +end + +local function blockSeq(st: St, sc: number, p: number): (any, number) + local s = st.s + enter(st, p) + local t: { any } = {} + local q = p + while true do + local r = skipLine(s, p + 1) + local c = byte(s, r) + local v: any + if c == nil or c == 10 or (c == 35 and r > p + 1) then + v, q = nextLineNode(st, sc, r, false, false) + else + if find(sub(s, p + 1, r - 1), "\t", 1, true) and (((c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, r + 1))) or implicitKey(st, r) ~= nil) then + corrupt("tab before a compact collection", r) + end + v, q = blockNode(st, sc, r, false, false) + end + table.insert(t, v) + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc = col(s, r3) + if cc == sc and byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + noTabs(s, r3) + p = r3 + elseif cc <= sc then + break + else + corrupt("bad indentation of a sequence entry", r3) + end + end + st.depth -= 1 + return t, q +end + +-- the node at q after its properties (props may be nil); start = where the properties began +local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local tag = props and props.tag + local c = byte(s, q) + if c == 42 then + if props then + corrupt("properties on an alias", q) + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + return blockMap(st, col(s, q), q, nil) + end + local v, e = alias(st, q) + if not endOfLine(s, e) then + corrupt("unexpected text after an alias", e) + end + return v, e + end + if c == 45 and isWsEnd(byte(s, q + 1)) then + if inline or props then + corrupt("a sequence cannot start here", q) + end + return blockSeq(st, col(s, q), q) + elseif (c == 63 or c == 58) and isWsEnd(byte(s, q + 1)) then + if inline or (props and c == 63) then + corrupt("a mapping cannot start here", q) + end + return blockMap(st, col(s, start), q, props) + elseif c == 124 or c == 62 then + local text, e = blockScalar(st, q, ind) + return finish(st, props, scalarValue(st, text, false, tag, q)), e + elseif c == 91 or c == 123 then + implicitKey(st, q) -- raises UNSUPPORTED for a flow collection used as a key + local v, e = parseFlow(st, q, ind) + collectionTag(st, tag, if c == 91 then "seq" else "map", q) + if not endOfLine(s, e) then + corrupt("unexpected text after a flow collection", e) + end + return finish(st, props, v), e + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + -- properties on the key's line belong to the first key + return blockMap(st, col(s, start), q, props) + end + if c == 34 or c == 39 then + local text, e = quoted(st, q, ind) + if not endOfLine(s, e) then + corrupt("unexpected text after a quoted scalar", e) + end + return finish(st, props, scalarValue(st, text, false, tag, q)), e + end + if c == 35 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 or c == 38 or c == 33 then + corrupt("unexpected character '" .. char(c :: number) .. "'", q) + end + local text, e = plain(st, q, ind, false) + if not endOfLine(s, e) then + corrupt("unexpected ':' (mapping values are not allowed here)", e) + end + return finish(st, props, scalarValue(st, text, true, tag, q)), e +end + +-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the +-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's +-- indentation may follow properties that end their line. +function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) + local s = st.s + local props, q = properties(st, p) + if not props then + return afterProps(st, ind, p, q, nil, inline, mapParent) + end + -- properties ending their line apply to the node on the next lines; more properties there merge in, unless + -- they start a mapping key + local c = byte(s, q) + if not (c == nil or c == 10 or (c == 35 and q > p)) then + return afterProps(st, ind, p, q, props, inline, mapParent) + end + while true do + local r = skip(s, q) + if r > #s or docMarker(s, r) then + break + end + local cr = col(s, r) + if not (cr > ind or (mapParent and cr == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1)))) then + break + end + noTabs(s, r, ind) + local cc = byte(s, r) + if cc == 38 or cc == 33 then + local p2, q2 = properties(st, r) + local c2 = byte(s, q2) + if c2 == nil or c2 == 10 or (c2 == 35 and q2 > r) then + local pr = props :: Props + if (p2 :: Props).anchor then + if pr.anchor then + corrupt("two anchors on one node", r) + end + pr.anchor = (p2 :: Props).anchor + end + if (p2 :: Props).tag then + if pr.tag then + corrupt("two tags on one node", r) + end + pr.tag = (p2 :: Props).tag + end + q = q2 + continue + end + if implicitKey(st, q2) ~= nil then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, (props :: Props).tag, "map", r) + return finish(st, props, v), e + end + -- properties then a scalar on the next line: merge + local pr = props :: Props + if (p2 :: Props).anchor and pr.anchor or (p2 :: Props).tag and pr.tag then + corrupt("two anchors or tags on one node", r) + end + pr.anchor = pr.anchor or (p2 :: Props).anchor + pr.tag = pr.tag or (p2 :: Props).tag + return afterProps(st, ind, r, q2, pr, false, mapParent) + end + local tag = (props :: Props).tag + if cc == 45 and isWsEnd(byte(s, r + 1)) then + local v, e = blockSeq(st, cr, r) + collectionTag(st, tag, "seq", r) + return finish(st, props, v), e + elseif ((cc == 63 or cc == 58) and isWsEnd(byte(s, r + 1))) or (cc ~= 91 and cc ~= 123 and implicitKey(st, r) ~= nil) then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, tag, "map", r) + return finish(st, props, v), e + elseif cc == 42 then + corrupt("properties on an alias", r) + end + return afterProps(st, ind, r, r, props, false, mapParent) + end + return finish(st, props, scalarValue(st, "", true, (props :: Props).tag, q)), q +end + +-- ------------------------------------------------------------------------------------------------ stream +local function stream(st: St): { any } + local s = st.s + local n = #s + local docs = {} + local p = 1 + local needEnd = false -- a bare document after a document must follow "..." or "---" + while true do + p = skip(s, p) + if p > n then + break + end + local sawDirective = false + st.handles = { ["!"] = "!", ["!!"] = CORE } + local yamlSeen = false + while byte(s, p) == 37 and col(s, p) == 0 do -- % + if needEnd then + corrupt("a directive needs '...' after the previous document", p) + end + local e = find(s, "\n", p, true) or n + 1 + local line = string.gsub(sub(s, p, e - 1), "%s+#.*$", "") + local name = match(line, "^%%(%S+)") + if name == "YAML" then + if yamlSeen then + corrupt("two %YAML directives", p) + end + yamlSeen = true + local v = match(line, "^%%YAML[ \t]+(%d+%.%d+)[ \t]*$") + if not v then + corrupt("bad %YAML directive", p) + end + elseif name == "TAG" then + local h, prefix = match(line, "^%%TAG[ \t]+(![%w%-]*!?)[ \t]+(%S+)[ \t]*$") + if not h then + corrupt("bad %TAG directive", p) + end + st.handles[h :: string] = prefix :: string + end + sawDirective = true + p = skip(s, e) + end + local explicit = false + if docMarker(s, p) and sub(s, p, p + 2) == "---" then + explicit = true + p += 3 + elseif sawDirective then + corrupt("directives without '---'", p) + elseif docMarker(s, p) then -- "..." + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + continue + elseif needEnd then + corrupt("a second document needs '---'", p) + end + st.anchors = {} + local q = skip(s, p) + local value: any + if q > n or docMarker(s, q) then + value = st.null + p = q + else + if explicit and not find(sub(s, p, q), "\n", 1, true) then + -- content on the "---" line + local ok, _, q2 = pcall(properties, st, q) + local c = byte(s, q2) + if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then + corrupt("a block mapping cannot start on the '---' line", q) + end + end + value, p = blockNode(st, -1, q, false, false) + local r = skip(s, p) + if r <= n and not docMarker(s, r) then + corrupt("unexpected content after the document", r) + end + p = r + end + table.insert(docs, value) + needEnd = true + if p <= n and docMarker(s, p) and sub(s, p, p + 2) == "..." then + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p += 3 + needEnd = false + elseif p <= n and docMarker(s, p) then + needEnd = false + end + end + return docs +end + +-- run(text, opts) -> docs | nil, code, message, offset +function Parse.run(text: string, opts: Options?): (any, any, any, any) + local o: Options = opts or {} + local s = text + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + if find(s, "\r", 1, true) then + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + end + local st: St = { + s = s, + n = #s, + anchors = {}, + handles = {}, + depth = 0, + maxDepth = o.maxDepth or 500, + aliasNodes = 0, + maxAlias = o.maxAliasNodes or 1e6, + sizes = setmetatable({}, { __mode = "k" }) :: any, + ignoreTags = o.tags == "ignore", + null = if o.null ~= nil then o.null else Types.null, + } + local ok, res = pcall(stream, st) + if ok then + return res, nil, nil, nil + end + if type(res) == "table" and res.yamlErr then + return nil, res.code, res.msg, res.at + end + local msg = tostring(res) + if string.find(msg, "stack overflow", 1, true) then + return nil, "LIMIT", "nested too deeply", 0 + end + return nil, "CORRUPT", "internal error: " .. msg, 0 +end + +return Parse +end +__FILES["font/bdf"] = function() + +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in +-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), +-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to +-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for +-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and +-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font +-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. +-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Bdf = { + name = "bdf", + category = "font", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 1114112 +type EncodeOptions = { + px: number?, -- pixel size for outline fonts (default 16) + chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) + name: string?, -- the FONT (XLFD) name (default built from the font's family / style) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bdf.sniff(r: Bytes.Reader): number + local head = r:peek(32) + return if string.match(head, "^STARTFONT%s+2%.%d") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unquote(v: string): any + local s = string.match(v, '^"(.*)"%s*$') + if s then + return (string.gsub(s, '""', '"')) + end + return tonumber(v) or v +end + +local function hexRow(line: string, w: number, row: buffer, rowOff: number) + local n = math.min(#line // 2, math.ceil(w / 8)) + for i = 0, n - 1 do + local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0 + buffer.writeu8(row, rowOff + i, v) + end +end + +function Bdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split(text, "\n") + local props: { [string]: any } = {} + local fontName, size = "", 0 + local fbb = { 0, 0, 0, 0 } + local fontDw = 0 + local glyphs: { Types.BitmapGlyph } = {} + local encodings: { number } = {} + local i = 1 + local n = #lines + local function line(): string + local l = string.gsub(lines[i] or "", "\r$", "") + i += 1 + return l + end + local first = line() + if not string.match(first, "^STARTFONT%s") then + return nil, Err.new(Err.CORRUPT, "no STARTFONT") + end + local ended = false + while i <= n do + local l = line() + local key, rest = string.match(l, "^(%S+)%s*(.*)$") + if key == "FONT" then + fontName = rest :: string + elseif key == "SIZE" then + size = tonumber(string.match(rest :: string, "^(%S+)")) or 0 + elseif key == "FONTBOUNDINGBOX" then + local a, b, c, d = string.match(rest :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif key == "DWIDTH" then + fontDw = tonumber(string.match(rest :: string, "^(%-?%d+)")) or 0 + elseif key == "STARTPROPERTIES" then + while i <= n do + local pl = line() + if string.match(pl, "^ENDPROPERTIES") then + break + end + local pk, pv = string.match(pl, "^(%S+)%s*(.*)$") + if pk then + props[pk :: string] = unquote(pv :: string) + end + end + elseif key == "STARTCHAR" then + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local name = rest :: string + local enc = -1 + local dw = fontDw + local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] } + local px: buffer? = nil + while i <= n do + local cl = line() + local ck, cr = string.match(cl, "^(%S+)%s*(.*)$") + if ck == "ENCODING" then + local e1, e2 = string.match(cr :: string, "^(%-?%d+)%s*(%-?%d*)") + enc = tonumber(e1) or -1 + if enc == -1 and e2 and e2 ~= "" then + enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings) + end + elseif ck == "DWIDTH" then + dw = tonumber(string.match(cr :: string, "^(%-?%d+)")) or dw + elseif ck == "BBX" then + local a, b, c, d = string.match(cr :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif ck == "BITMAP" then + local w, h = bbx[1], bbx[2] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name) + end + local stride = math.ceil(w / 8) + local rows = buffer.create(stride * h) + for y = 0, h - 1 do + local rl = string.gsub(lines[i] or "", "%s", "") + if string.match(rl, "^ENDCHAR") then + break + end + i += 1 + hexRow(rl, w, rows, y * stride) + end + px = Bitmap.unpack(rows, 0, w, h, stride) + elseif ck == "ENDCHAR" then + break + end + end + local gl: Types.BitmapGlyph = { + name = name, + codepoint = nil, + width = bbx[1], + height = bbx[2], + left = bbx[3], + top = bbx[4] + bbx[2], + advance = dw, + pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])), + } + table.insert(glyphs, gl) + table.insert(encodings, enc) + elseif key == "ENDFONT" then + ended = true + break + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no ENDFONT") + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local default: number? = nil + for k, gl in glyphs do + local enc = encodings[k] + if unicode and enc >= 0 then + gl.codepoint = enc + end + if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then + default = k - 1 + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (if fbb[2] > 0 then fbb[2] else size) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else fbb[2] + fbb[4], + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else -fbb[4], + glyphs = glyphs, + default = default, + } + local slant = props.SLANT + local weight = props.WEIGHT_NAME + local style = (if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "") + if slant == "I" or slant == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + local info = { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else fontName, + style = if style ~= "" then style else "Regular", + fullName = fontName, + } + local font = Bitmap.font(strike, info, { + properties = props, + encodings = encodings, + unicode = unicode, + fontName = fontName, + boundingBox = fbb, + source = { format = "bdf", charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }) + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function quote(s: string): string + return '"' .. string.gsub(s, '"', '""') .. '"' +end + +function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local info = if type(font.info) == "table" then font.info else {} + local family = string.gsub(tostring(info.family or "rosetta"), "[%-\n\r\"]", " ") + local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil + local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil + local px = strike.size + -- the font bounding box + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, g in strike.glyphs do + if g.width > 0 and g.height > 0 then + x0 = math.min(x0, g.left) + x1 = math.max(x1, g.left + g.width) + y0 = math.min(y0, g.top - g.height) + y1 = math.max(y1, g.top) + end + end + if x0 == math.huge then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + local name = o.name + or string.format("-rosetta-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, if bold then "bold" else "medium", if italic then "i" else "r", px, px * 10, (x1 - x0) * 10) + local out = { + "STARTFONT 2.1", + "FONT " .. name, + string.format("SIZE %d 75 75", px), + string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), + } + -- the default glyph: the strike's default, else glyph 0 + local defaultIndex = (strike.default or 0) + 1 + local props: { { any } } = { + { "FAMILY_NAME", quote(family) }, + { "WEIGHT_NAME", quote(if bold then "Bold" else "Medium") }, + { "SLANT", quote(if italic then "I" else "R") }, + { "PIXEL_SIZE", px }, + { "POINT_SIZE", px * 10 }, + { "RESOLUTION_X", 75 }, + { "RESOLUTION_Y", 75 }, + { "CHARSET_REGISTRY", quote("ISO10646") }, + { "CHARSET_ENCODING", quote("1") }, + { "FONT_ASCENT", strike.ascent }, + { "FONT_DESCENT", strike.descent }, + } + local dg = strike.glyphs[defaultIndex] + if dg and dg.codepoint then + table.insert(props, { "DEFAULT_CHAR", dg.codepoint }) + end + table.insert(out, "STARTPROPERTIES " .. #props) + for _, p in props do + table.insert(out, p[1] .. " " .. tostring(p[2])) + end + table.insert(out, "ENDPROPERTIES") + table.insert(out, "CHARS " .. #strike.glyphs) + for k, g in strike.glyphs do + local gname = g.name or (if g.codepoint then string.format("uni%04X", g.codepoint) else "glyph" .. (k - 1)) + table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_")) + table.insert(out, "ENCODING " .. (if g.codepoint then tostring(g.codepoint) else "-1")) + table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5))) + table.insert(out, string.format("DWIDTH %d 0", g.advance)) + table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height)) + table.insert(out, "BITMAP") + local stride = math.ceil(g.width / 8) + local rows = Bitmap.pack(g.pixels, g.width, g.height, stride) + for y = 0, g.height - 1 do + local hex = table.create(stride) + for x = 0, stride - 1 do + hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x)) + end + table.insert(out, table.concat(hex)) + end + table.insert(out, "ENDCHAR") + end + table.insert(out, "ENDFONT") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Bdf +end +__FILES["font/bmfont"] = function() + +-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and +-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize +-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are +-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the +-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / +-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. +-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("font/bmfont/Parse") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmfont = { + name = "bmfont", + category = "font", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, +} + +type DecodeOptions = { + pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) + loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) +} +type EncodeOptions = { + variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" + px: number?, -- fonts without a BMFont description are baked first (see bake) + chars: (string | { number })?, + file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") + name: string?, -- the destination's file name (set by the api) + files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes + -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages + encodeImage: ((img: any, format: string) -> (buffer?, any))?, +} +type BakeOptions = { + px: number?, -- pixels per em (default 32) + chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) + pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) + padding: number?, -- empty pixels around each glyph (default 1) + file: string?, -- page file name prefix (default "font"): pages are _.png +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmfont.sniff(r: Bytes.Reader): number + local head = r:peek(64) + if string.sub(head, 1, 4) == "BMF\3" then + return 1 + end + if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then + return 0.9 + end + if string.find(head, "", 1, true) or (string.find(head, "", 1, true)) then + return if string.find(r:peek(512), " true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil +function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) + local load = loader or self.meta.pageLoader + if type(load) ~= "function" then + return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))") + end + local pages = {} + for i, file in self.meta.pageFiles do + local ok, img, err = pcall(load, file, i - 1) + if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img)) + end + pages[i] = img + end + self.pages = pages + return true, nil +end + +local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 + +-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; +-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. +function Face.rasterize(self: any, g: number, px: number?): Types.Image? + local c = self._chars[g] + if not c then + return nil + end + if not self.pages and self.meta.pageLoader then + self:loadPages() + end + local page = self.pages and self.pages[c.page + 1] + local img = Types.Image.new(c.width, c.height, "alpha8") + img.meta.left = c.xoffset + img.meta.top = (self.meta.base or 0) - c.yoffset + img.meta.advance = c.xadvance + img.meta.glyph = g + img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1 + if not page then + return nil + end + local pw, ph = page.width, page.height + local bpp = Types.Image.bpp(page.format) or 4 + local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0 + if page.format == "graya8" then + ch = 1 + end + for y = 0, c.height - 1 do + local sy = c.y + y + for x = 0, c.width - 1 do + local sx = c.x + x + if sx >= 0 and sy >= 0 and sx < pw and sy < ph then + buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1))) + end + end + end + return img +end + +-- the Font value of a description +local function face(d: Parse.Desc, variant: string): any + local f: any = setmetatable({ + kind = "font", + info = { + family = d.info.face, + style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular", + fullName = d.info.face, + }, + unitsPerEm = math.abs(d.info.size or 0), + ascent = d.common.base or 0, + descent = (d.common.base or 0) - (d.common.lineHeight or 0), + lineGap = 0, + numGlyphs = #d.chars + 1, + pages = nil, + meta = { + bmfont = d, + variant = variant, + pageFiles = d.pages, + lineHeight = d.common.lineHeight, + base = d.common.base, + source = { format = "bmfont", variant = variant }, + }, + _chars = {}, + _index = {}, + _kern = {}, + }, Face) + for i, c in d.chars do + f._chars[i] = c + if f._index[c.id] == nil then + f._index[c.id] = i + end + end + for _, k in d.kernings do + f._kern[k[1] * 2097152 + k[2]] = k[3] + end + return f +end + +function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local d, err, variant + if r:peek(3) == "BMF" then + d, err = Parse.binary(r:sub(0)) + variant = "binary" + else + local s = r:peek(r:size()) + if string.find(string.sub(s, 1, 512), " 255 or c.chnl < 0 or c.chnl > 255 then + return false + end + end + for _, k in d.kernings do + if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then + return false + end + end + for _, p in d.pages do + if type(p) ~= "string" then + return false + end + end + return true +end + +function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + local d = type(font.meta) == "table" and font.meta.bmfont or nil + local pages = font.pages + if d == nil then + -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" + local file = opts and opts.file + if file == nil and opts and type(opts.name) == "string" then + file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") + if file == "" then + file = nil + end + end + local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) + if not baked then + return nil, err + end + d = baked.meta.bmfont + pages = baked.pages + end + if not validDesc(d) then + return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") + end + -- the page images into opts.files, under the names the descriptor gives them + local files = opts and opts.files + local encodeImage = opts and opts.encodeImage + if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then + for i, name in d.pages do + local img = pages[i] + if type(img) == "table" and type(name) == "string" and name ~= "" then + local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") + local bytes, eerr = encodeImage(img, ext) + if not bytes then + return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) + end + files[name] = bytes + end + end + end + local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" + if variant == "text" then + return buffer.fromstring(Parse.writeText(d)), nil + elseif variant == "xml" then + return buffer.fromstring(Parse.writeXml(d)), nil + elseif variant == "binary" then + return Parse.writeBinary(d), nil + end + return nil, Err.new(Err.ARG, "variant must be text, xml or binary") +end + +-- ------------------------------------------------------------------------------------------------ extras +local function codepoints(chars: any): { number } + local out = {} + if type(chars) == "string" then + for _, c in utf8.codes(chars) do + table.insert(out, c) + end + elseif type(chars) == "table" then + for _, c in chars do + if type(c) == "number" then + table.insert(out, c) + end + end + else + for c = 32, 126 do + table.insert(out, c) + end + end + return out +end + +-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are +-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are +-- kept (rounded to pixels). +function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) + if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "bake: expected an outline Font") + end + local o: BakeOptions = opts or {} + local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32 + local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1 + local scale = px / font.unitsPerEm + local glyphs: { { cp: number, g: number, img: Types.Image } } = {} + local area = 0 + local seen = {} + for _, cp in codepoints(o.chars) do + local g = (font :: any):glyphIndex(cp) + if (g ~= 0 or cp == 0) and not seen[cp] then + seen[cp] = true + local img: Types.Image? = (font :: any):rasterize(g, px) + if img then + table.insert(glyphs, { cp = cp, g = g, img = img }) + area += (img.width + pad) * (img.height + pad) + end + end + end + local size: number + if type(o.pageSize) == "number" then + size = o.pageSize + else + size = 64 + while size * size < area * 1.3 and size < 4096 do + size *= 2 + end + end + local order = table.clone(glyphs) + table.sort(order, function(a: any, b: any): boolean + if a.img.height ~= b.img.height then + return a.img.height > b.img.height + end + return a.cp < b.cp + end) + local ascent = math.ceil(font.ascent * scale) + local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale) + local prefix = o.file or "font" + local d: Parse.Desc = { + info = { + face = font.info and font.info.family or "font", + size = px, + bold = 0, + italic = 0, + charset = "", + unicode = 1, + stretchH = 100, + smooth = 1, + aa = 1, + padding = { 0, 0, 0, 0 }, + spacing = { pad, pad }, + outline = 0, + }, + common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 }, + pages = {}, + chars = {}, + kernings = {}, + } + local pages: { Types.Image } = {} + local page: Types.Image? = nil + local x, y, rowH = pad, pad, 0 + local placed: { [number]: Parse.Char } = {} + for _, gl in order do + local w, h = gl.img.width, gl.img.height + if w + 2 * pad > size or h + 2 * pad > size then + return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page") + end + if x + w + pad > size then + x, y, rowH = pad, y + rowH + pad, 0 + end + if not page or y + h + pad > size then + page = Types.Image.new(size, size) + table.insert(pages, page :: Types.Image) + table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1)) + x, y, rowH = pad, pad, 0 + end + local pg = page :: Types.Image + for yy = 0, h - 1 do + for xx = 0, w - 1 do + local a = buffer.readu8(gl.img.pixels, yy * w + xx) + buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216) + end + end + local c: Parse.Char = { + id = gl.cp, + x = x, + y = y, + width = w, + height = h, + xoffset = gl.img.meta.left, + yoffset = ascent - gl.img.meta.top, + xadvance = math.floor(gl.img.meta.advance + 0.5), + page = #pages - 1, + chnl = 15, + } + placed[gl.cp] = c + x += w + pad + rowH = math.max(rowH, h) + end + for _, gl in glyphs do + table.insert(d.chars, placed[gl.cp]) + end + d.common.pages = #pages + if type(font.kern) == "function" then + for _, a in glyphs do + for _, b in glyphs do + local k = font:kern(a.g, b.g) + if k ~= 0 then + local v = math.floor(k * scale + 0.5) + if v ~= 0 then + table.insert(d.kernings, { a.cp, b.cp, v }) + end + end + end + end + end + local f = face(d, "text") + f.pages = pages + return f, nil +end + +return Bmfont +end +__FILES["font/bmfont/Parse"] = function() + +-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one +-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation +-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the +-- descriptor has no nesting that matters, no text content). +-- +-- Never throws on bad input: parse functions return nil, message. +local Bytes = __include("core/Bytes") + +local Parse = {} + +type Char = { + id: number, + x: number, + y: number, + width: number, + height: number, + xoffset: number, + yoffset: number, + xadvance: number, + page: number, + chnl: number, +} +type Desc = { + info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline + common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl + pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1]) + chars: { Char }, + kernings: { { number } }, -- { first, second, amount } +} + +local LIMIT = 1000000 -- chars / kernings + +local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } +local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } +local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function list(s: string?, n: number): { number } + local out = table.create(n, 0) + if s then + local i = 1 + for v in string.gmatch(s, "-?%d+") do + if i > n then + break + end + out[i] = tonumber(v) or 0 + i += 1 + end + end + return out +end + +local function new(): Desc + return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } +end + +-- one tag's attributes (already split into key -> string) into the description +local function apply(d: Desc, tag: string, a: { [string]: string }): string? + if tag == "info" then + d.info.face = a.face or "" + d.info.charset = a.charset or "" + for _, k in INFO_NUM do + d.info[k] = tonumber(a[k]) or 0 + end + d.info.padding = list(a.padding, 4) + d.info.spacing = list(a.spacing, 2) + elseif tag == "common" then + for _, k in COMMON_NUM do + d.common[k] = tonumber(a[k]) or 0 + end + elseif tag == "page" then + local id = tonumber(a.id) + if not id or id < 0 or id > 4096 or id % 1 ~= 0 then + return "bad page id" + end + d.pages[id + 1] = a.file or "" + elseif tag == "char" then + if #d.chars >= LIMIT then + return "too many chars" + end + local c: any = {} + for _, k in CHAR_NUM do + c[k] = tonumber(a[k]) or 0 + end + table.insert(d.chars, c) + elseif tag == "kerning" then + if #d.kernings >= LIMIT then + return "too many kerning pairs" + end + table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 }) + end + return nil +end + +local function fill(d: Desc) + for i = 1, #d.pages do + d.pages[i] = d.pages[i] or "" + end +end + +-- ------------------------------------------------------------------------------------------------ text +function Parse.text(s: string): (Desc?, string?) + local d = new() + for line in string.gmatch(s, "[^\r\n]+") do + local tag, rest = string.match(line, "^%s*(%a+)(.*)$") + if tag then + local a: { [string]: string } = {} + -- key=value, key="quoted value" + local i = 1 + while i <= #(rest :: string) do + local k, q, e = string.match(rest :: string, '^%s*([%w_]+)="([^"]*)"()', i) + if k then + a[k] = q + i = e + else + local k2, v2, e2 = string.match(rest :: string, "^%s*([%w_]+)=(%S*)()", i) + if not k2 then + break + end + a[k2] = v2 + i = e2 + end + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + end + if not d.common.lineHeight then + return nil, "no common line" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ XML +local ENTITIES: { [string]: string } = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } +local function unescape(s: string): string + return ( + string.gsub(s, "&(#?x?%w+);", function(e: string): string? + if ENTITIES[e] then + return ENTITIES[e] + end + local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil + if n and n >= 0 and n <= 0x10FFFF then + return utf8.char(n) + end + return nil + end) + ) +end + +function Parse.xml(s: string): (Desc?, string?) + local d = new() + local seenFont = false + for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do + if tag == "font" then + seenFont = true + end + local a: { [string]: string } = {} + for k, q, v in string.gmatch(attrs :: string, "([%w_]+)%s*=%s*([\"'])(.-)%2") do + a[k] = unescape(v :: string) + local _ = q + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + if not seenFont or not d.common.lineHeight then + return nil, "not a BMFont XML descriptor" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ binary +function Parse.binary(r: Bytes.Reader): (Desc?, string?) + if not r:match("BMF") then + return nil, "bad signature" + end + local version = r:u8() + if version ~= 3 then + return nil, "unsupported binary version " .. version + end + local d = new() + while not r:eof() do + local kind = r:u8() + local size = r:u32le() + if r.err then + return nil, "truncated block header" + end + local b = r:slice(size) + if r.err then + return nil, "block past the end" + end + if kind == 1 then + d.info.size = b:i16le() + local bits = b:u8() + d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0 + d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0 + d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0 + d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0 + d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0 + d.info.charsetId = b:u8() + d.info.charset = "" + d.info.stretchH = b:u16le() + d.info.aa = b:u8() + d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() } + d.info.spacing = { b:u8(), b:u8() } + d.info.outline = b:u8() + d.info.face = b:cstring() + elseif kind == 2 then + d.common.lineHeight = b:u16le() + d.common.base = b:u16le() + d.common.scaleW = b:u16le() + d.common.scaleH = b:u16le() + d.common.pages = b:u16le() + d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0 + d.common.alphaChnl = b:u8() + d.common.redChnl = b:u8() + d.common.greenChnl = b:u8() + d.common.blueChnl = b:u8() + elseif kind == 3 then + while not b:eof() and #d.pages < 4096 do + table.insert(d.pages, b:cstring()) + end + elseif kind == 4 then + local n = size // 20 + if n > LIMIT then + return nil, "too many chars" + end + for _ = 1, n do + table.insert(d.chars, { + id = b:u32le(), + x = b:u16le(), + y = b:u16le(), + width = b:u16le(), + height = b:u16le(), + xoffset = b:i16le(), + yoffset = b:i16le(), + xadvance = b:i16le(), + page = b:u8(), + chnl = b:u8(), + }) + end + elseif kind == 5 then + local n = size // 10 + if n > LIMIT then + return nil, "too many kerning pairs" + end + for _ = 1, n do + table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() }) + end + end + if b.err then + return nil, "truncated block " .. kind + end + end + if not d.common.lineHeight then + return nil, "no common block" + end + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ writers +local function num(v: any): string + return string.format("%d", math.floor(tonumber(v) or 0)) +end + +local function textLines(d: Desc, quote: (string) -> string): { { any } } + local i, c = d.info, d.common + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + local lines: { { any } } = { + { + "info", + { + { "face", quote(i.face or "") }, + { "size", num(i.size) }, + { "bold", num(i.bold) }, + { "italic", num(i.italic) }, + { "charset", quote(i.charset or "") }, + { "unicode", num(i.unicode) }, + { "stretchH", num(i.stretchH or 100) }, + { "smooth", num(i.smooth) }, + { "aa", num(i.aa) }, + { "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") }, + { "spacing", num(sp[1]) .. "," .. num(sp[2]) }, + { "outline", num(i.outline) }, + }, + }, + } + local cf = {} + for _, k in COMMON_NUM do + table.insert(cf, { k, num(c[k]) }) + end + table.insert(lines, { "common", cf }) + return lines +end + +function Parse.writeText(d: Desc): string + local out = {} + local function q(s: string): string + return '"' .. string.gsub(s, '"', "") .. '"' + end + for _, l in textLines(d, q) do + local parts = { l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. "=" .. kv[2]) + end + table.insert(out, table.concat(parts, " ")) + end + for id, file in d.pages do + table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', "")))) + end + table.insert(out, "chars count=" .. #d.chars) + for _, c in d.chars do + local parts = { "char" } + for _, k in CHAR_NUM do + table.insert(parts, k .. "=" .. num((c :: any)[k])) + end + table.insert(out, table.concat(parts, " ")) + end + if #d.kernings > 0 then + table.insert(out, "kernings count=" .. #d.kernings) + for _, k in d.kernings do + table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3]))) + end + end + return table.concat(out, "\n") .. "\n" +end + +local function esc(s: string): string + return (string.gsub(s, '[&<>"]', { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """ })) +end + +function Parse.writeXml(d: Desc): string + local out = { '', "" } + for _, l in textLines(d, function(s: string): string + return s + end) do + local parts = { " <" .. l[1] } + for _, kv in l[2] do + table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " ") + for id, file in d.pages do + table.insert(out, string.format(' ', id - 1, esc(file))) + end + table.insert(out, " ") + table.insert(out, string.format(' ', #d.chars)) + for _, c in d.chars do + local parts = { " ") + end + table.insert(out, " ") + if #d.kernings > 0 then + table.insert(out, string.format(' ', #d.kernings)) + for _, k in d.kernings do + table.insert(out, string.format(' ', num(k[1]), num(k[2]), num(k[3]))) + end + table.insert(out, " ") + end + table.insert(out, "") + return table.concat(out, "\n") .. "\n" +end + +function Parse.writeBinary(d: Desc): buffer + local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10) + w:string("BMF") + w:u8(3) + local i, c = d.info, d.common + local face = i.face or "" + w:u8(1) + w:u32le(14 + #face + 1) + w:u16le((tonumber(i.size) or 0) % 65536) + local bits = 0 + if (tonumber(i.smooth) or 0) ~= 0 then + bits += 0x80 + end + if (tonumber(i.unicode) or 0) ~= 0 then + bits += 0x40 + end + if (tonumber(i.italic) or 0) ~= 0 then + bits += 0x20 + end + if (tonumber(i.bold) or 0) ~= 0 then + bits += 0x10 + end + if (tonumber(i.fixedHeight) or 0) ~= 0 then + bits += 0x08 + end + w:u8(bits) + w:u8(tonumber(i.charsetId) or 0) + w:u16le(tonumber(i.stretchH) or 100) + w:u8(tonumber(i.aa) or 1) + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + for k = 1, 4 do + w:u8(pad[k] or 0) + end + w:u8(sp[1] or 0) + w:u8(sp[2] or 0) + w:u8(tonumber(i.outline) or 0) + w:cstring(face) + w:u8(2) + w:u32le(15) + for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do + w:u16le((tonumber(c[k]) or 0) % 65536) + end + w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0) + for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do + w:u8(tonumber(c[k]) or 0) + end + if #d.pages > 0 then + local len = 0 + for _, p in d.pages do + len += #p + 1 + end + w:u8(3) + w:u32le(len) + for _, p in d.pages do + w:cstring(p) + end + end + w:u8(4) + w:u32le(#d.chars * 20) + for _, ch in d.chars do + w:u32le(ch.id) + w:u16le(ch.x) + w:u16le(ch.y) + w:u16le(ch.width) + w:u16le(ch.height) + w:u16le(ch.xoffset % 65536) + w:u16le(ch.yoffset % 65536) + w:u16le(ch.xadvance % 65536) + w:u8(ch.page) + w:u8(ch.chnl) + end + if #d.kernings > 0 then + w:u8(5) + w:u32le(#d.kernings * 10) + for _, k in d.kernings do + w:u32le(k[1]) + w:u32le(k[2]) + w:u16le(k[3] % 65536) + end + end + return w:finish() +end + +return Parse +end +__FILES["font/eot"] = function() + +-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, +-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and +-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot +-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, +-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C +-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Eot = { + name = "eot", + category = "font", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, +} + +type DecodeOptions = {} +type EncodeOptions = { + xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false) + rootString: string?, -- the URLs allowed to use the font (default "") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = 0x504C +local COMPRESSED, XOR = 0x4, 0x10000000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Eot.sniff(r: Bytes.Reader): number + local h = r:peek(36) + if #h < 36 then + return 0 + end + local ver = string.sub(h, 9, 12) + local magic = string.byte(h, 35) + string.byte(h, 36) * 256 + if magic == MAGIC and (ver == "\0\0\1\0" or ver == "\1\0\2\0" or ver == "\2\0\2\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Eot.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local eotSize, dataSize, version, flags = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local panose = r:string(10) + local charset, italic = r:u8(), r:u8() + local weight = r:u32le() + local fsType, magic = r:u16le(), r:u16le() + local ranges = { r:u32le(), r:u32le(), r:u32le(), r:u32le() } + local codepages = { r:u32le(), r:u32le() } + local checksum = r:u32le() + r:skip(16) + if r.err then + return nil, r.err + end + if magic ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic number") + end + if version ~= 0x00010000 and version ~= 0x00020001 and version ~= 0x00020002 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%08x", version)) + end + local function name(): string + r:skip(2) + local n = r:u16le() + local s = r:bytes(n) + return Text.utf16(s, 0, buffer.len(s)) + end + local eot: { [string]: any } = { + version = version, + flags = flags, + panose = panose, + charset = charset, + italic = italic ~= 0, + weight = weight, + fsType = fsType, + unicodeRange = ranges, + codePageRange = codepages, + checkSumAdjustment = checksum, + eotSize = eotSize, + } + eot.familyName, eot.styleName, eot.versionName, eot.fullName = name(), name(), name(), name() + if version >= 0x00020001 then + eot.rootString = name() + end + if version == 0x00020002 then + eot.rootStringChecksum = r:u32le() + eot.eudcCodePage = r:u32le() + r:skip(2) + r:skip(r:u16le()) -- signature + eot.eudcFlags = r:u32le() + r:skip(r:u32le()) -- EUDC font data + end + if r.err then + return nil, r.err + end + if bit32.band(flags, COMPRESSED) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "MicroType Express compressed font data") + end + local data = r:bytes(dataSize) + if r.err then + return nil, r.err + end + if bit32.band(flags, XOR) ~= 0 then + for i = 0, dataSize - 1 do + buffer.writeu8(data, i, bit32.bxor(buffer.readu8(data, i), 0x50)) + end + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + font.meta.eot = eot + font.meta.fontData = data + font.meta.source = { format = "eot", version = version, outlines = font.meta.outlines } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf16(s: string): string + local out = {} + if utf8.len(s) then + for _, c in utf8.codes(s) do + if c >= 0x10000 then + c -= 0x10000 + local hi, lo = 0xD800 + bit32.rshift(c, 10), 0xDC00 + bit32.band(c, 0x3FF) + table.insert(out, string.char(hi % 256, hi // 256, lo % 256, lo // 256)) + else + table.insert(out, string.char(c % 256, c // 256)) + end + end + end + return table.concat(out) +end + +function Eot.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local data: buffer + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + elseif type(value) == "table" and type(value.meta) == "table" and type(value.meta.fontData) == "buffer" then + data = value.meta.fontData + else + return nil, Err.new(Err.ARG, "expected TrueType bytes (or a Font read from an EOT)") + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + local tables: { [string]: { number } } = TrueType.tables(data, 0, 0, buffer.len(data)) or {} + local function tab(tagName: string): Bytes.Reader? + local t: { number }? = tables[tagName] + return if t then Bytes.reader(data, t[1], t[2]) else nil + end + -- OS/2: PANOSE, weight, fsType, ranges, selection; head: checkSumAdjustment + local panose, weight, fsType, italic, charset = string.rep("\0", 10), 400, 0, 0, 1 + local ranges, codepages = { 0, 0, 0, 0 }, { 0, 0 } + local os2 = tab("OS/2") + if os2 then + os2:seek(4) + weight = os2:u16be() + os2:seek(8) + fsType = os2:u16be() + os2:seek(32) + panose = os2:string(10) + ranges = { os2:u32be(), os2:u32be(), os2:u32be(), os2:u32be() } + os2:seek(62) + local sel = os2:u16be() + italic = if bit32.band(sel, 1) ~= 0 then 1 else 0 + os2:seek(78) + codepages = { os2:u32be(), os2:u32be() } + if os2.err then + codepages = { 0, 0 } + end + end + local head = tab("head") + local checksum = 0 + if head then + head:seek(8) + checksum = head:u32be() + end + local info = font.info or {} + local names = { info.family or "", info.style or "", info.version or "", info.fullName or "" } + local w = Bytes.writer(buffer.len(data) + 512) + w:u32le(0) -- EOTSize, patched + w:u32le(buffer.len(data)) + w:u32le(0x00020001) + w:u32le(if o.xor then XOR else 0) + w:string(panose) + w:u8(charset) + w:u8(italic) + w:u32le(weight) + w:u16le(fsType) + w:u16le(MAGIC) + for _, v in ranges do + w:u32le(v) + end + for _, v in codepages do + w:u32le(v) + end + w:u32le(checksum) + w:string(string.rep("\0", 16)) + for _, s in names do + local u = utf16(tostring(s)) + w:u16le(0) + w:u16le(#u) + w:string(u) + end + local root = utf16(o.rootString or "") + w:u16le(0) + w:u16le(#root) + w:string(root) + local start = w:tell() + w:bytes(data) + local out = w:finish() + if o.xor then + for i = start, start + buffer.len(data) - 1 do + buffer.writeu8(out, i, bit32.bxor(buffer.readu8(out, i), 0x50)) + end + end + buffer.writeu32(out, 0, buffer.len(out)) + return out, nil +end + +return Eot +end +__FILES["font/fon"] = function() + +-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the +-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE +-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first +-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI +-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). +-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- Not supported: vector FNT (Err.UNSUPPORTED), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Fon = { + name = "fon", + category = "font", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, +} + +type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first) + +-- ------------------------------------------------------------------------------------------------ sniff +local function isFnt(h: string): boolean + if #h < 4 then + return false + end + local ver = string.byte(h, 1) + string.byte(h, 2) * 256 + return ver == 0x200 or ver == 0x300 +end + +function Fon.sniff(r: Bytes.Reader): number + local h = r:peek(64) + if string.sub(h, 1, 2) == "MZ" and #h >= 64 then + local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536 + local sig = r:peek(2, lfanew) + return if sig == "NE" then 0.6 elseif sig == "PE" then 0.2 else 0 + end + if isFnt(h) and #h >= 6 then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216 + return if size == r:size() then 0.9 elseif size <= r:size() and size > 118 then 0.3 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one FNT resource -> Font +local function fnt(r: Bytes.Reader): (any, Err.Err?) + local version = r:u16le() + local total = r:u32le() + local copyright = string.match(r:string(60), "^[^%z]*") or "" + local ftype = r:u16le() + local points, vres, hres = r:u16le(), r:u16le(), r:u16le() + local ascent = r:u16le() + r:skip(4) -- internal / external leading + local italic = r:u8() + r:skip(2) + local weight = r:u16le() + local charset = r:u8() + local pixWidth, pixHeight = r:u16le(), r:u16le() + r:skip(5) -- pitch and family, average / max width + local first, last, default = r:u8(), r:u8(), r:u8() + r:skip(1 + 2 + 4) + local faceAt = r:u32le() + if r.err then + return nil, r.err + end + if version ~= 0x200 and version ~= 0x300 then + return nil, Err.new(Err.CORRUPT, "not a FNT resource") + end + if bit32.band(ftype, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "vector fonts") + end + if last < first or pixHeight == 0 or pixHeight > 1024 then + return nil, Err.new(Err.CORRUPT, "bad character range or height") + end + r:seek(if version == 0x300 then 148 else 118) + local glyphs: { Types.BitmapGlyph } = {} + for c = first, last do + local w = r:u16le() + local off = if version == 0x300 then r:u32le() else r:u16le() + if r.err then + return nil, r.err + end + if w > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph width") + end + -- column-major: byte column k holds pixels 8k .. 8k + 7 of every row + local h = pixHeight + local px = buffer.create(w * h) + local cols = math.ceil(w / 8) + local base = r.base + off + local limit = r.base + r:size() + for k = 0, cols - 1 do + for y = 0, h - 1 do + local p = base + k * h + y + if p >= 0 and p < limit then + local byte = buffer.readu8(r.buf, p) + for b = 0, 7 do + local x = k * 8 + b + if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then + buffer.writeu8(px, y * w + x, 255) + end + end + end + end + end + local cp: number? = nil + if charset == 0 then + cp = if c >= 0x80 and c < 0xA0 then Text.CP1252[c] else c + elseif c < 0x80 then + cp = c + end + table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px }) + end + local face = "" + if faceAt > 0 and faceAt < r:size() then + face = r:sub(faceAt):cstring(256) + end + local dflt = default + first + local strike: Types.BitmapStrike = { + size = pixHeight, + ascent = ascent, + descent = pixHeight - ascent, + glyphs = glyphs, + default = if dflt >= first and dflt <= last then dflt - first else nil, + } + local style = (if weight >= 600 then "Bold" else "") .. (if italic ~= 0 then " Italic" else "") + style = string.gsub(style, "^ ", "") + return Bitmap.font(strike, { family = face, style = if style ~= "" then style else "Regular", fullName = face }, { + copyright = copyright, + points = points, + resolution = { hres, vres }, + charset = charset, + weight = weight, + pixWidth = pixWidth, + firstChar = first, + source = { format = "fon", version = if version == 0x300 then 3 else 2, size = total }, + }), nil +end + +-- the RT_FONT resources of an NE executable: { { offset, length } } +local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) + local rt = r:sub(ne + 0x24, 2):u16le() + local t = r:sub(ne + rt) + local shift = t:u16le() + if shift > 16 then + return nil, "bad resource alignment" + end + local out = {} + for _ = 1, 64 do + local typeId = t:u16le() + if typeId == 0 or t.err then + break + end + local count = t:u16le() + t:skip(4) + for _ = 1, count do + local off, len = t:u16le(), t:u16le() + t:skip(8) + if typeId == 0x8008 then + table.insert(out, { off * 2 ^ shift, len * 2 ^ shift }) + end + end + end + if t.err then + return nil, "truncated resource table" + end + return out, nil +end + +-- the RT_FONT (8) resources of a PE executable: { { offset, length } } +local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) + local h = r:sub(pe + 4, 20) + h:skip(2) + local nsec = h:u16le() + h:skip(12) + local optSize = h:u16le() + local opt = r:sub(pe + 24, optSize) + local magic = opt:u16le() + local ddAt = if magic == 0x20B then 112 else 96 + opt:seek(ddAt + 2 * 8) + local rsrcRva = opt:u32le() + if opt.err or rsrcRva == 0 then + return {}, nil + end + -- the section holding the resources + local secs = r:sub(pe + 24 + optSize, nsec * 40) + local base, rva0 = -1, 0 + for _ = 1, nsec do + secs:skip(8) + local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le() + secs:skip(16) + if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then + base, rva0 = rawAt + (rsrcRva - va), va - rawAt + end + end + if base < 0 then + return nil, "no resource section" + end + local out = {} + local function dir(at: number, depth: number, isFont: boolean) + if depth > 3 then + return + end + local d = r:sub(base + at, 16) + d:skip(12) + local named, ids = d:u16le(), d:u16le() + local e = r:sub(base + at + 16, (named + ids) * 8) + for _ = 1, math.min(named + ids, 512) do + local id, target = e:u32le(), e:u32le() + if e.err then + return + end + if depth == 0 and id ~= 8 then + continue + end + if bit32.band(target, 0x80000000) ~= 0 then + dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0) + elseif isFont then + local leaf = r:sub(base + target, 8) + local dataRva, size = leaf:u32le(), leaf:u32le() + table.insert(out, { dataRva - rva0, size }) + end + end + end + dir(0, 0, false) + return out, nil +end + +function Fon.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local list: { { number } } + if r:peek(2) == "MZ" then + local lfanew = r:sub(0x3C, 4):u32le() + local sig = r:peek(2, lfanew) + local l, err + if sig == "NE" then + l, err = neFonts(r, lfanew) + elseif sig == "PE" then + l, err = peFonts(r, lfanew) + else + return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header") + end + if not l then + return nil, Err.from(err) + end + list = l + else + if r:size() < 118 then + return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header") + end + list = { { 0, r:size() } } + end + local fonts: { any } = {} + local firstErr: Err.Err? = nil + for _, res in list do + if res[1] + 118 <= r:size() then + local f, err = fnt(r:sub(res[1], res[2])) + if f then + table.insert(fonts, f) + else + firstErr = firstErr or err + end + end + end + if #fonts == 0 then + return nil, firstErr or Err.new(Err.CORRUPT, "no font resources") + end + local pick = fonts[1] + if type(o.size) == "number" then + for _, f in fonts do + if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then + pick = f + end + end + end + pick.meta.strikes = fonts + return pick, nil +end + +return Fon +end +__FILES["font/hershey"] = function() + +-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph +-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", +-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths +-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster +-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of +-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i +-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph +-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: +-- writing, the Hershey "occidental" index files (.hmp), filled rendering. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") + +-- ------------------------------------------------------------------------------------------------ contract +local Hershey = { + name = "hershey", + category = "font", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, +} + +type DecodeOptions = { + map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii") + strokeWidth: number?, -- stroke width in font units for rasterize (default 2) + maxGlyphs: number?, -- default 65536 +} + +-- ------------------------------------------------------------------------------------------------ constants +local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards) + +-- ------------------------------------------------------------------------------------------------ sniff +-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R") +local function header(line: string): (number?, number?) + if #line < 10 then + return nil, nil + end + local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", ""))) + local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", ""))) + if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then + return nil, nil + end + return id, n +end + +function Hershey.sniff(r: Bytes.Reader): number + local head = r:peek(256) + local line = string.match(head, "^([^\r\n]*)") + local id, n = header(line or "") + if not id or not n then + return 0 + end + local body = string.sub(line :: string, 9) + if string.find(body, "[^ -~]") then + return 0 + end + return if #body == math.min(2 * n, 64) or #body == 2 * n then 0.7 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Glyph = { id: number, left: number, right: number, cmds: { any } } + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._index[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local gl = self._glyphs[g + 1] + return if gl then gl.right - gl.left else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face.outline(self: any, g: number): { any }? + local gl = self._glyphs[g + 1] + if not gl then + return nil + end + local out = table.create(#gl.cmds) + for i, c in gl.cmds do + out[i] = table.clone(c) + end + return out +end + +-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) +function Face.rasterize(self: any, g: number, px: number): Types.Image? + local gl = self._glyphs[g + 1] + if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local s = px / self.unitsPerEm + local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" }) + local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = (gl.right - gl.left) * s + img.meta.glyph = g + return img +end + +function Hershey.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split((string.gsub(text, "\r", "")), "\n") + local glyphs: { Glyph } = {} + local i = 1 + while i <= #lines do + local line = lines[i] + i += 1 + if string.match(line, "^%s*$") then + continue + end + local id, n = header(line) + if not id or not n then + return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1)) + end + local data = string.sub(line, 9) + while #data < 2 * n and i <= #lines do + data ..= lines[i] + i += 1 + end + if #data < 2 * n then + return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count") + end + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local left = string.byte(data, 1) - 82 + local right = string.byte(data, 2) - 82 + local cmds: { any } = {} + local pen = false + for k = 1, n - 1 do + local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2) + if a == 32 and b == 82 then + pen = false + else + local x, y = a - 82 - left, BASELINE - (b - 82) + local cmd: any = { op = if pen then "lineTo" else "moveTo" } + cmd[1], cmd[2] = x, y + table.insert(cmds, cmd) + pen = true + end + end + table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds }) + end + if #glyphs == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + local index: { [number]: number } = {} + local byId = o.map == "id" + for k, g in glyphs do + local cp = if byId then g.id else 31 + k + if index[cp] == nil then + index[cp] = k - 1 + end + end + local font = setmetatable({ + kind = "font", + info = { family = "Hershey", style = "Regular" }, + unitsPerEm = 32, + ascent = 21, + descent = -7, + lineGap = 4, + numGlyphs = #glyphs, + meta = { + strokes = true, + strokeWidth = o.strokeWidth or 2, + ids = table.create(#glyphs, 0), + source = { format = "hershey", map = if byId then "id" else "ascii" }, + }, + _glyphs = glyphs, + _index = index, + }, Face) + for k, g in glyphs do + font.meta.ids[k] = g.id + end + return font, nil +end + +return Hershey +end +__FILES["font/pcf"] = function() + +-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), +-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad +-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. +-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets +-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver +-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcf = { + name = "pcf", + category = "font", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 1114112 + +-- ------------------------------------------------------------------------------------------------ constants +local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8 +local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256 +local COMPRESSED = 0x100 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "\1fcp" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Table = { format: number, size: number, offset: number } + +-- a reader positioned after a table's format word, with the integer readers for its byte order +type TR = { r: Bytes.Reader, format: number, big: boolean } + +local function open(r: Bytes.Reader, t: Table?): TR? + if not t or t.offset + 4 > r:size() then + return nil + end + local s = r:sub(t.offset, t.size) + local format = s:u32le() + return { r = s, format = format, big = bit32.band(format, 4) ~= 0 } +end + +local function u32(t: TR): number + return if t.big then t.r:u32be() else t.r:u32le() +end +local function i32(t: TR): number + return if t.big then t.r:i32be() else t.r:i32le() +end +local function i16(t: TR): number + return if t.big then t.r:i16be() else t.r:i16le() +end +local function u16(t: TR): number + return if t.big then t.r:u16be() else t.r:u16le() +end + +local REV = buffer.create(256) +for i = 0, 255 do + local v, rv = i, 0 + for _ = 1, 8 do + rv = rv * 2 + v % 2 + v //= 2 + end + buffer.writeu8(REV, i, rv) +end + +function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + if r:string(4) ~= "\1fcp" then + return nil, Err.new(if r.err then Err.TRUNCATED else Err.CORRUPT, "not a PCF file") + end + local count = r:u32le() + if count > 64 then + return nil, Err.new(Err.CORRUPT, "too many tables") + end + local tables: { [number]: Table } = {} + for _ = 1, count do + local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le() + tables[ty] = { format = format, size = size, offset = offset } + end + if r.err then + return nil, r.err + end + -- properties + local props: { [string]: any } = {} + local pt = open(r, tables[PROPERTIES]) + if pt then + local n = i32(pt) + if n < 0 or n > 4096 then + return nil, Err.new(Err.CORRUPT, "bad property count") + end + local raw = {} + for k = 1, n do + raw[k] = { i32(pt), pt.r:u8(), i32(pt) } + end + if n % 4 ~= 0 then + pt.r:skip(4 - n % 4) + end + local strSize = i32(pt) + local strAt = pt.r:tell() + local function str(off: number): string + if off < 0 or off >= strSize then + return "" + end + local s = pt.r:sub(strAt + off, strSize - off) + return s:cstring() + end + for _, p in raw do + props[str(p[1])] = if p[2] ~= 0 then str(p[3]) else p[3] + end + if pt.r.err then + return nil, Err.new(Err.TRUNCATED, "properties table") + end + end + -- accelerators: ascent / descent + local ascent: number?, descent: number? = nil, nil + local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) + if at then + at.r:skip(8) + ascent, descent = i32(at), i32(at) + end + -- metrics + local mt = open(r, tables[METRICS]) + if not mt then + return nil, Err.new(Err.CORRUPT, "no METRICS table") + end + local metrics = {} + local compressed = bit32.band(mt.format, COMPRESSED) ~= 0 + local nm = if compressed then u16(mt) else u32(mt) + if nm > maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + for k = 1, nm do + if compressed then + local b = mt.r + metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 } + else + metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) } + mt.r:skip(2) + end + end + if mt.r.err then + return nil, Err.new(Err.TRUNCATED, "metrics table") + end + -- bitmaps + local bt = open(r, tables[BITMAPS]) + if not bt then + return nil, Err.new(Err.CORRUPT, "no BITMAPS table") + end + local nb = u32(bt) + if nb ~= nm then + return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count") + end + local offsets = table.create(nb, 0) + for k = 1, nb do + offsets[k] = u32(bt) + end + local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) } + local padIndex = bit32.band(bt.format, 3) + local pad = bit32.lshift(1, padIndex) + local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3)) + local msbBit = bit32.band(bt.format, 8) ~= 0 + local dataAt = bt.r:tell() + local dataSize = sizes[padIndex + 1] + if bt.r.err or dataAt + dataSize > bt.r:size() then + return nil, Err.new(Err.TRUNCATED, "bitmaps table") + end + -- the bitmap data normalised to MSB-first bits and bytes + local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize) + if not msbBit then + for k = 0, dataSize - 1 do + buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k))) + end + end + if bt.big ~= msbBit and unit > 1 then + for k = 0, dataSize - unit, unit do + for j = 0, unit // 2 - 1 do + local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j) + buffer.writeu8(bits, k + j, y) + buffer.writeu8(bits, k + unit - 1 - j, x) + end + end + end + local glyphs: { Types.BitmapGlyph } = {} + for k = 1, nm do + local m = metrics[k] + local w, h = m[2] - m[1], m[4] + m[5] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph metrics") + end + local stride = math.ceil(w / (pad * 8)) * pad + local px = Bitmap.unpack(bits, offsets[k], w, h, stride) + glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } + end + -- encodings + local encodings: { [number]: number } = {} + local default: number? = nil + local et = open(r, tables[BDF_ENCODINGS]) + if et then + local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et) + if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then + return nil, Err.new(Err.CORRUPT, "bad encoding ranges") + end + for b1 = min1, max1 do + for b2 = min2, max2 do + local g = u16(et) + if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then + encodings[g + 1] = b1 * 256 + b2 + end + end + end + if et.r.err then + return nil, Err.new(Err.TRUNCATED, "encodings table") + end + local dcols = max2 - min2 + 1 + local d1, d2 = def // 256, def % 256 + if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then + local slot = (d1 - min1) * dcols + (d2 - min2) + local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2) + local g = if et.big then dr:u16be() else dr:u16le() + if g ~= 0xFFFF and g < nm then + default = g + end + end + end + -- glyph names + local nt = open(r, tables[GLYPH_NAMES]) + if nt then + local n = u32(nt) + if n == nm then + local offs = table.create(n, 0) + for k = 1, n do + offs[k] = u32(nt) + end + local strSize = u32(nt) + local strAt = nt.r:tell() + for k = 1, n do + if offs[k] < strSize then + glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring() + end + end + end + end + local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil + local cset = if props.CHARSET_ENCODING ~= nil then tostring(props.CHARSET_ENCODING) else nil + local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local encList = table.create(nm, -1) + for k = 1, nm do + local enc = encodings[k] + encList[k] = enc or -1 + if unicode and enc then + glyphs[k].codepoint = enc + end + end + local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (ascent or 0) + (descent or 0) + local strike: Types.BitmapStrike = { + size = pixelSize, + ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else ascent or 0, + descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else descent or 0, + glyphs = glyphs, + default = default, + } + local weight = props.WEIGHT_NAME + local style = if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "" + if props.SLANT == "I" or props.SLANT == "O" then + style = (if style ~= "" then style .. " " else "") .. "Italic" + end + return Bitmap.font(strike, { + family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else nil, + style = if style ~= "" then style else "Regular", + fullName = if type(props.FONT) == "string" then props.FONT else nil, + }, { + properties = props, + encodings = encList, + unicode = unicode, + source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = if registry then registry .. "-" .. tostring(cset) else nil }, + }), nil +end + +return Pcf +end +__FILES["font/psf"] = function() + +-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 +-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and +-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry +-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map +-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell +-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: +-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through +-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps +-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd +-- project's psf documentation (Andries Brouwer). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Psf = { + name = "psf", + category = "font", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 65536 +type EncodeOptions = { + version: number?, -- 1 or 2 (default 2) + px: number?, -- pixel size for outline fonts (default 16) + chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) + unicode: boolean?, -- write the Unicode table (default true) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Psf.sniff(r: Bytes.Reader): number + local h = r:peek(4) + if h == "\114\181\74\134" then + return 1 + end + if string.sub(h, 1, 2) == "\54\4" and #h >= 4 and string.byte(h, 3) <= 7 and string.byte(h, 4) > 0 then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local version, count, width, height, stride, glyphAt, hasTable + if r:peek(4) == "\114\181\74\134" then + r:skip(4) + local ver, hsize, flags = r:u32le(), r:u32le(), r:u32le() + count = r:u32le() + local charsize = r:u32le() + height, width = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PSF 2 version " .. ver) + end + stride = math.ceil(width / 8) + if width < 1 or height < 1 or width > 4096 or height > 4096 or charsize ~= stride * height then + return nil, Err.new(Err.CORRUPT, "bad glyph size") + end + version, glyphAt, hasTable = 2, hsize, bit32.band(flags, 1) ~= 0 + elseif r:peek(2) == "\54\4" then + r:skip(2) + local mode, charsize = r:u8(), r:u8() + if r.err then + return nil, r.err + end + version, width, height, stride = 1, 8, charsize, 1 + count = if bit32.band(mode, 1) ~= 0 then 512 else 256 + glyphAt, hasTable = 4, bit32.band(mode, 6) ~= 0 + if height < 1 then + return nil, Err.new(Err.CORRUPT, "zero glyph height") + end + else + return nil, Err.new(Err.CORRUPT, "not a PSF font") + end + if count < 1 or count > maxGlyphs then + return nil, Err.new(Err.LIMIT, "glyph count " .. count .. " over maxGlyphs") + end + local size = stride * height + if glyphAt + count * size > r:size() then + return nil, Err.new(Err.TRUNCATED, "glyph data past the end") + end + local glyphs: { Types.BitmapGlyph } = {} + for i = 0, count - 1 do + glyphs[i + 1] = { + width = width, + height = height, + left = 0, + top = height, + advance = width, + pixels = Bitmap.unpack(r.buf, r.base + glyphAt + i * size, width, height, stride), + } + end + local map: { [number]: number } = {} + local sequences = {} + local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order + if hasTable then + local t = r:sub(glyphAt + count * size) + for i = 0, count - 1 do + local inSeq = false + local seq: { number } = {} + local entry: { any } = {} + unicodeTable[i + 1] = entry + local function endSeq() + if #seq > 0 then + table.insert(sequences, { glyph = i, codepoints = seq }) + table.insert(entry, seq) + end + seq = {} + end + while true do + if t:eof() then + break + end + local cp + if version == 1 then + cp = t:u16le() + if cp == 0xFFFF then + break + elseif cp == 0xFFFE then + endSeq() + inSeq = true + continue + end + else + local b = t:u8() + if b == 0xFF then + break + elseif b == 0xFE then + endSeq() + inSeq = true + continue + end + -- UTF-8 + local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1 + if n < 0 then + return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") + end + cp = if n == 0 then b elseif n == 1 then bit32.band(b, 0x1F) elseif n == 2 then bit32.band(b, 0x0F) else bit32.band(b, 0x07) + for _ = 1, n do + cp = cp * 64 + bit32.band(t:u8(), 0x3F) + end + end + if inSeq then + table.insert(seq, cp) + continue + end + table.insert(entry, cp) + if map[cp] == nil then + map[cp] = i + if glyphs[i + 1].codepoint == nil then + glyphs[i + 1].codepoint = cp + end + end + end + endSeq() + end + if t.err then + return nil, Err.new(Err.TRUNCATED, "Unicode table") + end + else + for i = 0, count - 1 do + glyphs[i + 1].codepoint = i + end + end + local strike: Types.BitmapStrike = { size = height, ascent = height, descent = 0, glyphs = glyphs, map = map, default = 0 } + local defaultGlyph = map[0xFFFD] or map[0x3F] + if defaultGlyph then + strike.default = defaultGlyph + end + return Bitmap.font(strike, {}, { + unicode = hasTable, + sequences = sequences, + unicodeTable = if hasTable then unicodeTable else nil, + width = width, + height = height, + source = { format = "psf", version = version, glyphs = count }, + }), nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf8Bytes(cp: number): string + return utf8.char(cp) +end + +function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local version = o.version or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local glyphs = strike.glyphs + local n = #glyphs + if n == 0 then + return nil, Err.new(Err.ARG, "no glyphs") + end + -- the cell + local width = 0 + for _, g in glyphs do + width = math.max(width, g.advance, g.left + g.width) + end + local height = math.max(1, strike.ascent + strike.descent) + if version == 1 then + if width > 8 then + return nil, Err.new(Err.ARG, "PSF 1 glyphs are 8 pixels wide (this font needs " .. width .. ")") + end + if n > 512 then + return nil, Err.new(Err.ARG, "PSF 1 holds 256 or 512 glyphs (this font has " .. n .. ")") + end + width = 8 + end + width = math.max(width, 1) + local count = if version == 1 then (if n > 256 then 512 else 256) else n + local stride = math.ceil(width / 8) + local size = stride * height + local cells = buffer.create(count * size) + for i, g in glyphs do + local cell = buffer.create(width * height) + local x0, y0 = g.left, strike.ascent - g.top + for y = 0, g.height - 1 do + for x = 0, g.width - 1 do + local cx, cy = x0 + x, y0 + y + if cx >= 0 and cy >= 0 and cx < width and cy < height and buffer.readu8(g.pixels, y * g.width + x) >= 128 then + buffer.writeu8(cell, cy * width + cx, 255) + end + end + end + buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) + end + -- the Unicode table: each glyph's code point and the extra mappings onto it + local cps: { { number } } = {} + for i = 1, count do + cps[i] = {} + end + local seen: { [number]: boolean } = {} + for i, g in glyphs do + if g.codepoint and not seen[g.codepoint] then + seen[g.codepoint] = true + table.insert(cps[i], g.codepoint) + end + end + if strike.map then + local extra: { { number } } = {} + for cp, gi in strike.map do + if not seen[cp] and gi >= 0 and gi < count then + table.insert(extra, { cp, gi }) + end + end + table.sort(extra, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, e in extra do + seen[e[1]] = true + table.insert(cps[e[2] + 1], e[1]) + end + end + local meta = if type(font.meta) == "table" then font.meta else {} + local srcTable = if font.bitmap == strike and type(meta.unicodeTable) == "table" and #meta.unicodeTable == n then meta.unicodeTable else nil + local withTable = if o.unicode ~= nil then o.unicode else meta.unicode ~= false + local w = Bytes.writer(count * size + 64) + if version == 2 then + w:string("\114\181\74\134") + w:u32le(0) + w:u32le(32) + w:u32le(if withTable then 1 else 0) + w:u32le(count) + w:u32le(size) + w:u32le(height) + w:u32le(width) + else + w:string("\54\4") + w:u8((if count == 512 then 1 else 0) + (if withTable then 2 else 0)) + w:u8(height) + end + w:bytes(cells) + if withTable then + local function put(cp: number) + if version == 2 then + w:string(utf8Bytes(cp)) + elseif cp < 0xFFFE then + w:u16le(cp) + end + end + for i = 1, count do + -- a PSF read earlier writes its table back as it was (code points on several glyphs, sequences) + local list = if srcTable and srcTable[i] then srcTable[i] else cps[i] + for _, x in list do + if type(x) == "number" then + put(x) + end + end + for _, x in list do + if type(x) == "table" then + if version == 2 then + w:u8(0xFE) + else + w:u16le(0xFFFE) + end + for _, cp in x do + put(cp) + end + end + end + if version == 2 then + w:u8(0xFF) + else + w:u16le(0xFFFF) + end + end + end + return w:finish(), nil +end + +return Psf +end +__FILES["font/ttf"] = function() + +-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the +-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. +-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Ttf = { + name = "ttf", + category = "font", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, +} + +type DecodeOptions = { + index: number?, -- the font of a collection (default 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ttf.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) + if not font then + return nil, err + end + font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- count(r) -> the number of fonts in the file (1 unless a collection) +function Ttf.count(r: Bytes.Reader): number + return TrueType.count(r.buf, r.base) +end + +return Ttf +end +__FILES["font/type1"] = function() + +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the +-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, +-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, +-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring +-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph +-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through +-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple +-- Master and CID-keyed (Type 9 / 11) fonts, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local GlyphNames = __include("codecs/font/GlyphNames") +local Charstring = __include("font/type1/Charstring") + +-- ------------------------------------------------------------------------------------------------ contract +local Type1 = { + name = "type1", + category = "font", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, +} + +type DecodeOptions = { maxGlyphs: number? } -- default 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Type1.sniff(r: Bytes.Reader): number + local h = r:peek(64) + if string.sub(h, 1, 2) == "\128\1" then + h = string.sub(h, 7) + end + if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA +local function sections(r: Bytes.Reader): (string?, buffer?, string?) + local b = r.buf + local n = r:size() + if r:peek(2) == "\128\1" then + local clear, bin = {}, Bytes.writer() + local p = 0 + while p + 2 <= n do + local h = r:sub(p, 6) + local m, ty, len = h:u8(), h:u8(), h:u32le() + if m ~= 128 then + return nil, nil, "bad PFB segment marker" + end + if ty == 3 then + break + end + if h.err or p + 6 + len > n then + return nil, nil, "truncated PFB segment" + end + if ty == 1 then + if #clear == 0 or bin:tell() == 0 then + table.insert(clear, buffer.readstring(b, r.base + p + 6, len)) + end + elseif ty == 2 then + bin:bytes(r:sub(p + 6, len):bytes(len)) + else + return nil, nil, "bad PFB segment type " .. ty + end + p += 6 + len + end + return table.concat(clear), bin:finish(), nil + end + local text = buffer.readstring(b, r.base, n) + local e = string.find(text, "eexec", 1, true) + if not e then + return nil, nil, "no eexec section" + end + local clear = string.sub(text, 1, e + 4) + -- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex) + local rest = string.sub(text, e + 5) + local hexPart = string.match(rest, "^%s*([%x%s]+)") + if hexPart and #hexPart > 8 then + local digits = string.gsub(hexPart, "%s", "") + local out = buffer.create(#digits // 2) + for i = 0, #digits // 2 - 1 do + buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0) + end + return clear, out, nil + end + local s = string.match(rest, "^[\r\n]*(.*)$") or rest + return clear, buffer.fromstring(s), nil +end + +local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer + local r = key + local out = buffer.create(math.max(0, n - skip)) + for i = 0, n - 1 do + local c = buffer.readu8(src, off + i) + local p = bit32.bxor(c, bit32.rshift(r, 8)) + r = ((c + r) * 52845 + 22719) % 65536 + if i >= skip then + buffer.writeu8(out, i - skip, p) + end + end + return out +end + +-- binary strings of the private dictionary: " RD " / " -| " +local function binaryAt(priv: buffer, p: number, len: number): buffer? + if p < 0 or len < 0 or p + len > buffer.len(priv) then + return nil + end + local out = buffer.create(len) + buffer.copy(out, 0, priv, p, len) + return out +end + +local function psString(clear: string, key: string): string? + return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)") +end + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self: any, cp: number): number + return self._cmap[cp] or 0 +end + +function Face.advance(self: any, g: number): number + local res = self:_run(g) + return if res then res.advance else 0 +end + +function Face.kern(_self: any, _a: number, _b: number): number + return 0 +end + +function Face._run(self: any, g: number): Charstring.Result? + local cached = self._cache[g] + if cached ~= nil then + return if cached == false then nil else cached + end + local cs = self._charstrings[g + 1] + if not cs then + return nil + end + local res = Charstring.run(cs, self._ctx) + self._cache[g] = res or false + return res +end + +function Face.outline(self: any, g: number): { any }? + local res = self:_run(g) + if not res then + return nil + end + local out = table.create(#res.cmds) + for i, c in res.cmds do + out[i] = table.clone(c) + end + return out +end + +function Face.rasterize(self: any, g: number, px: number): Types.Image? + if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local res = self:_run(g) + if not res then + return nil + end + local s = px / self.unitsPerEm + local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left, img.meta.top = m.x, -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = res.advance * s + img.meta.glyph = g + return img +end + +function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local clear, enc, serr = sections(r) + if not clear or not enc then + return nil, Err.from(serr) + end + if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then + return nil, Err.new(Err.CORRUPT, "no eexec section") + end + if buffer.len(enc) < 4 then + return nil, Err.new(Err.TRUNCATED, "eexec section too short") + end + local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) + local ptext = buffer.tostring(priv) + local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 + -- Subrs + local subrs: { buffer } = {} + local function charstring(p: number, len: number): buffer? + local raw = binaryAt(priv, p, len) + if not raw then + return nil + end + if lenIV < 0 then + return raw + end + return decrypt(raw, 0, len, 4330, lenIV) + end + local sAt = string.find(ptext, "/Subrs", 1, true) + local csAt = string.find(ptext, "/CharStrings", 1, true) + if not csAt then + return nil, Err.new(Err.CORRUPT, "no CharStrings") + end + if sAt and sAt < csAt then + local p = sAt + while true do + local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p) + if not s or s > csAt then + break + end + local e = e0 :: number + local i, n = tonumber(idx) :: number, tonumber(len) :: number + if i > 65535 then + return nil, Err.new(Err.LIMIT, "too many subroutines") + end + local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end") + end + subrs[i + 1] = cs + p = e + n + end + end + -- CharStrings + local names: { string } = {} + local charstrings: { buffer } = {} + local byName: { [string]: number } = {} + local p = csAt + 12 + while true do + local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p) + if not s then + break + end + local e = e0 :: number + -- stop at the end of the dictionary + if string.find(string.sub(ptext, p, s), "%send%s") then + break + end + local n = tonumber(len) :: number + local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end") + end + if #names >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + table.insert(names, name :: string) + table.insert(charstrings, cs) + if byName[name :: string] == nil then + byName[name :: string] = #names - 1 + end + p = e + n + end + if #names == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + -- .notdef first: glyph 0 + local nd = byName[".notdef"] + if nd and nd ~= 0 then + names[1], names[nd + 1] = names[nd + 1], names[1] + charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] + byName[names[1]], byName[names[nd + 1]] = 0, nd + end + -- the encoding + local encoding: { [number]: string } = {} + if string.find(clear, "/Encoding%s+StandardEncoding") then + for code, gname in GlyphNames.STANDARD do + encoding[code] = gname + end + else + for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do + encoding[tonumber(code) :: number] = gname + end + end + local cmap: { [number]: number } = {} + for _, gname in encoding do + local g = byName[gname] + local cp = GlyphNames.unicode(gname) + if g and cp and cmap[cp] == nil then + cmap[cp] = g + end + end + for k, gname in names do + local cp = GlyphNames.unicode(gname) + if cp and cmap[cp] == nil then + cmap[cp] = k - 1 + end + end + -- font matrix / bbox + local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") + local scale = 0.001 + if fm then + local a = tonumber(string.match(fm, "^%s*(%S+)")) + if a and a > 0 then + scale = a + end + end + local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]") + local bbox = { 0, 0, 0, 0 } + if bb then + local k = 1 + for v in string.gmatch(bb, "%S+") do + bbox[k] = tonumber(v) or 0 + k += 1 + end + end + local upm = math.floor(1 / scale + 0.5) + local font = setmetatable({ + kind = "font", + info = { + family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"), + style = psString(clear, "Weight") or "Regular", + fullName = psString(clear, "FullName"), + postscriptName = string.match(clear, "/FontName%s*/(%S+)"), + }, + unitsPerEm = upm, + ascent = bbox[4], + descent = bbox[2], + lineGap = 0, + numGlyphs = #names, + meta = { + glyphNames = names, + encoding = encoding, + bbox = bbox, + italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"), + lenIV = lenIV, + source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" }, + }, + _cmap = cmap, + _charstrings = charstrings, + _cache = {}, + }, Face) + font._ctx = { + subrs = subrs, + seac = function(code: number): Charstring.Result? + local gname = GlyphNames.STANDARD[code] + local g = if gname then byName[gname] else nil + if not g then + return nil + end + local res = Charstring.run(charstrings[g + 1], { subrs = subrs }) + return res + end, + } + return font, nil +end + +return Type1 +end +__FILES["font/type1/Charstring"] = function() + +-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted +-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side +-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, +-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; +-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, +-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the +-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +local Charstring = {} + +type Result = { cmds: { any }, advance: number, sbx: number } +-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result +type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? } + +local readu8 = buffer.readu8 + +function Charstring.run(cs: buffer, ctx: Context): (Result?, string?) + local cmds: { any } = {} + local stack: { number } = {} + local sp = 0 + local ps: { number } = {} -- the PostScript stack callothersubr / pop use + local x, y = 0, 0 + local advance, sbx = 0, 0 + local open = false + local flex = false + local flexPts: { number } = {} + local budget = 200000 + local finished = false + + local function push(v: number) + if sp < 48 then + sp += 1 + stack[sp] = v + end + end + local function arg(i: number): number + return stack[i] or 0 + end + local function close() + if open then + table.insert(cmds, { op = "close" }) + open = false + end + end + local function moveTo(dx: number, dy: number) + x += dx + y += dy + if flex then + table.insert(flexPts, x) + table.insert(flexPts, y) + return + end + close() + local c: any = { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function ensureOpen() + if not open then + -- a drawing operator without a moveto starts at the current point + local c: any = { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + open = true + end + end + local function lineTo(dx: number, dy: number) + ensureOpen() + x += dx + y += dy + local c: any = { op = "lineTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number) + ensureOpen() + local x1, y1 = x + a, y + b + local x2, y2 = x1 + c, y1 + d + x, y = x2 + e, y2 + f + local cmd: any = { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y + table.insert(cmds, cmd) + end + + local function exec(b: buffer, depth: number): string? + if depth > 10 then + return "subroutines nested too deep" + end + local n = buffer.len(b) + local p = 0 + while p < n do + budget -= 1 + if budget <= 0 then + return "operation budget exceeded" + end + local v = readu8(b, p) + p += 1 + if v >= 32 then + if v <= 246 then + push(v - 139) + elseif v <= 250 then + if p >= n then + return "truncated number" + end + push((v - 247) * 256 + readu8(b, p) + 108) + p += 1 + elseif v <= 254 then + if p >= n then + return "truncated number" + end + push(-(v - 251) * 256 - readu8(b, p) - 108) + p += 1 + else + if p + 4 > n then + return "truncated number" + end + local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) + push(if u >= 0x80000000 then u - 0x100000000 else u) + p += 4 + end + continue + end + local op = v + if op == 12 then + if p >= n then + return "truncated escape" + end + op = 1200 + readu8(b, p) + p += 1 + end + if op == 13 then -- hsbw + sbx, advance = arg(1), arg(2) + x, y = sbx, 0 + sp = 0 + elseif op == 1207 then -- sbw + sbx, advance = arg(1), arg(3) + x, y = arg(1), arg(2) + sp = 0 + elseif op == 21 then + moveTo(arg(1), arg(2)) + sp = 0 + elseif op == 22 then + moveTo(arg(1), 0) + sp = 0 + elseif op == 4 then + moveTo(0, arg(1)) + sp = 0 + elseif op == 5 then + lineTo(arg(1), arg(2)) + sp = 0 + elseif op == 6 then + lineTo(arg(1), 0) + sp = 0 + elseif op == 7 then + lineTo(0, arg(1)) + sp = 0 + elseif op == 8 then + curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6)) + sp = 0 + elseif op == 30 then -- vhcurveto + curveTo(0, arg(1), arg(2), arg(3), arg(4), 0) + sp = 0 + elseif op == 31 then -- hvcurveto + curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4)) + sp = 0 + elseif op == 9 then + close() + sp = 0 + elseif op == 10 then -- callsubr + local idx = arg(sp) + sp = math.max(0, sp - 1) + local sub = ctx.subrs[idx + 1] + if not sub then + return "call of a missing subroutine " .. idx + end + local err = exec(sub, depth + 1) + if err or finished then + return err + end + elseif op == 11 then -- return + return nil + elseif op == 14 then -- endchar + close() + finished = true + return nil + elseif op == 1212 then -- div + if sp >= 2 then + local d = stack[sp] + stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0 + sp -= 1 + end + elseif op == 1216 then -- callothersubr: args... n othersubr# + local num = arg(sp) + local count = arg(sp - 1) + sp = math.max(0, sp - 2) + count = math.clamp(count, 0, sp) + local args = {} + for i = 1, count do + args[i] = stack[sp - count + i] + end + sp -= count + if num == 1 then + flex = true + table.clear(flexPts) + elseif num == 2 then + -- a flex point: the rmoveto before it already recorded the point + elseif num == 0 and flex then + flex = false + -- flexPts: the reference point, then 6 control / end points + local f = flexPts + if #f >= 14 then + -- restore the current point to before the flex sequence's moves + local function curve(i: number) + ensureOpen() + local cmd: any = { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5] + table.insert(cmds, cmd) + end + curve(3) + curve(9) + x, y = f[13], f[14] + end + table.clear(ps) + table.insert(ps, args[3] or y) + table.insert(ps, args[2] or x) + elseif num == 3 then + table.clear(ps) + table.insert(ps, 3) + else + table.clear(ps) + for i = #args, 1, -1 do + table.insert(ps, args[i]) + end + end + elseif op == 1217 then -- pop + push(table.remove(ps) or 0) + elseif op == 1233 then -- setcurrentpoint + x, y = arg(1), arg(2) + sp = 0 + elseif op == 1206 then -- seac: asb adx ady bchar achar + local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5) + sp = 0 + local seac = ctx.seac + if not seac then + return "seac without base glyphs" + end + local base = seac(bchar) + local accent = seac(achar) + if not base or not accent then + return "seac of a missing glyph" + end + close() + for _, c in base.cmds do + table.insert(cmds, c) + end + local ox, oy = adx - asb, ady + for _, c in accent.cmds do + local t: any = { op = c.op } + for i = 1, #c, 2 do + t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy + end + table.insert(cmds, t) + end + finished = true + return nil + elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then + sp = 0 -- hints + else + sp = 0 -- unknown operators clear the stack + end + end + return nil + end + + local err = exec(cs, 0) + if err then + return nil, err + end + close() + return { cmds = cmds, advance = advance, sbx = sbx }, nil +end + +return Charstring +end +__FILES["font/woff"] = function() + +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding +-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended +-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff = { + name = "woff", + category = "font", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Woff.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOFF" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err +function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) + local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local base = r.base + if not r:match("wOFF") then + return nil, Err.new(Err.CORRUPT, "bad signature", base), nil + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local total = r:u32be() + r:skip(4) + local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() + r:skip(8) + if r.err then + return nil, r.err, nil + end + if flavor == "ttcf" then + return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4), nil + end + if length > r:size() then + return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8), nil + end + if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then + return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12), nil + end + local dir = {} + for i = 1, numTables do + local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() } + dir[i] = e + end + if r.err then + return nil, r.err, nil + end + local out = buffer.create(total) + local w = Bytes.writer(12) + w:string(flavor) + w:u16be(numTables) + local es, sel = 1, 0 + while es * 2 <= numTables do + es *= 2 + sel += 1 + end + w:u16be(es * 16) + w:u16be(sel) + w:u16be(numTables * 16 - es * 16) + buffer.copy(out, 0, w.buf, 0, 12) + local p = 12 + 16 * numTables + for i, e in dir do + if e.offset + e.comp > r:size() or e.comp > e.orig then + return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20), nil + end + if p + e.orig > total then + return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16), nil + end + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, e.tag) + buffer.writeu32(out, d + 4, bit32.byteswap(e.sum)) + buffer.writeu32(out, d + 8, bit32.byteswap(p)) + buffer.writeu32(out, d + 12, bit32.byteswap(e.orig)) + if e.comp < e.orig then + local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig) + if not t then + return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset), nil + end + buffer.copy(out, p, t, 0, e.orig) + else + buffer.copy(out, p, r.buf, base + e.offset, e.orig) + end + p += e.orig + p = (p + 3) // 4 * 4 + if p > total then + p = total + end + end + local xml = nil + if metaLength > 0 and metaOffset + metaLength <= r:size() then + local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig) + if m then + xml = buffer.tostring(m) + end + end + return out, nil, xml +end + +function Woff.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err, xml = Woff.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.woffMetadata = xml + font.meta.source = { format = "woff", outlines = font.meta.outlines } + return font, nil +end + +return Woff +end +__FILES["font/woff2"] = function() + +-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx +-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF +-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") +local Rebuild = __include("font/woff2/Rebuild") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff2 = { + name = "woff2", + category = "font", + extensions = { "woff2" }, + mime = { "font/woff2" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- ------------------------------------------------------------------------------------------------ sniff +function Woff2.sniff(r: Bytes.Reader): number + return if r:peek(4) == "wOF2" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err +function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) + local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local at = r.base + local out, msg, code = Rebuild.sfnt(r, maxBytes) + if not out then + return nil, Err.from(msg or "rebuild failed", at, code or "corrupt") + end + return out, nil +end + +function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sfnt, err = Woff2.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.source = { format = "woff2", outlines = font.meta.outlines } + return font, nil +end + +return Woff2 +end +__FILES["font/woff2/Rebuild"] = function() + +-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table +-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, +-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx +-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). +-- +-- Never throws: malformed data returns nil, message. +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") + +local Rebuild = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local KNOWN = { + "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", + "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", + "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", + "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", + "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill", +} + +-- UIntBase128 from r +local function base128(r: Bytes.Reader): number? + local v = 0 + for i = 1, 5 do + local b = r:u8() + if r.err or (i == 1 and b == 0x80) then + return nil + end + if v >= 2 ^ 25 then + return nil + end + v = v * 128 + band(b, 0x7F) + if b < 0x80 then + return v + end + end + return nil +end + +-- a cursor over a stream inside the decompressed block +type Stream = { buf: buffer, p: number, e: number, bad: boolean } +local function stream(b: buffer, p: number, n: number): Stream + return { buf = b, p = p, e = p + n, bad = false } +end +local function su8(s: Stream): number + if s.p >= s.e then + s.bad = true + return 0 + end + local v = readu8(s.buf, s.p) + s.p += 1 + return v +end +local function su16(s: Stream): number + return su8(s) * 256 + su8(s) +end +local function si16(s: Stream): number + local v = su16(s) + return if v >= 32768 then v - 65536 else v +end +local function s255(s: Stream): number + local c = su8(s) + if c == 253 then + return su16(s) + elseif c == 255 then + return su8(s) + 253 + elseif c == 254 then + return su8(s) + 506 + end + return c +end + +local function withSign(flag: number, v: number): number + return if band(flag, 1) ~= 0 then v else -v +end + +-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat +local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) + local h = stream(b, p, n) + su16(h) -- reserved + local option = su16(h) + local numGlyphs = su16(h) + local indexFormat = su16(h) + local sizes = {} + for i = 1, 7 do + sizes[i] = su16(h) * 65536 + su16(h) + end + if h.bad then + return nil, "truncated glyf transform header" + end + local at = h.p + local streams: { Stream } = {} + for i = 1, 7 do + if at + sizes[i] > p + n then + return nil, "glyf transform stream past the end" + end + streams[i] = stream(b, at, sizes[i]) + at += sizes[i] + end + local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7] + local overlap: Stream? = nil + if band(option, 1) ~= 0 then + overlap = stream(b, at, (numGlyphs + 7) // 8) + if at + (numGlyphs + 7) // 8 > p + n then + return nil, "overlap bitmap past the end" + end + end + -- the bbox bitmap leads the bbox stream + local bitmapLen = 4 * ((numGlyphs + 31) // 32) + if bitmapLen > sizes[6] then + return nil, "bbox bitmap past the end" + end + local bboxBits = bboxS.p + bboxS.p += bitmapLen + local function hasBox(g: number): boolean + return band(readu8(b, bboxBits + g // 8), rshift(0x80, g % 8)) ~= 0 + end + local w = Bytes.writer(n * 2) + local loca = table.create(numGlyphs + 1, 0) + local xMins = table.create(numGlyphs, 0) + for g = 0, numGlyphs - 1 do + loca[g + 1] = w.pos + local nc = si16(nContour) + if nContour.bad then + return nil, "nContour stream truncated" + end + if nc == 0 then + if hasBox(g) then + return nil, "empty glyph with a bounding box" + end + elseif nc > 0 then + -- simple glyph + local ends = table.create(nc, 0) + local total = 0 + for c = 1, nc do + total += s255(nPoints) + ends[c] = total - 1 + end + if nPoints.bad or total > 65535 then + return nil, "bad point counts" + end + local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false) + local x, y = 0, 0 + for k = 1, total do + local fl = su8(flagS) + on[k] = rshift(fl, 7) == 0 + fl = band(fl, 0x7F) + local dx, dy + if fl < 10 then + dx = 0 + dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS)) + elseif fl < 20 then + dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)) + dy = 0 + elseif fl < 84 then + local b0 = fl - 20 + local b1 = su8(glyphS) + dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4)) + dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F)) + elseif fl < 120 then + local b0 = fl - 84 + dx = withSign(fl, 1 + (b0 // 12) * 256 + su8(glyphS)) + dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS)) + elseif fl < 124 then + local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 16 + rshift(b2, 4)) + dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3) + else + local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 256 + b2) + dy = withSign(rshift(fl, 1), b3 * 256 + b4) + end + x += dx + y += dy + xs[k], ys[k] = x, y + end + local ilen = s255(glyphS) + if flagS.bad or glyphS.bad then + return nil, "flag / glyph stream truncated" + end + local x0, y0, x1, y1 + if hasBox(g) then + x0 = si16(bboxS) + y0 = si16(bboxS) + x1 = si16(bboxS) + y1 = si16(bboxS) + else + x0, y0, x1, y1 = 32767, 32767, -32768, -32768 + for k = 1, total do + x0 = math.min(x0, xs[k]) + y0 = math.min(y0, ys[k]) + x1 = math.max(x1, xs[k]) + y1 = math.max(y1, ys[k]) + end + if total == 0 then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + end + xMins[g + 1] = x0 + w:u16be(nc % 65536) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + for c = 1, nc do + w:u16be(ends[c]) + end + w:u16be(ilen) + if instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + local ov = overlap ~= nil and band(readu8(b, (overlap :: Stream).p + g // 8), rshift(0x80, g % 8)) ~= 0 + -- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them + local fls = table.create(total, 0) + for k = 1, total do + local fl = if on[k] then 1 else 0 + if k == 1 and ov then + fl += 0x40 + end + local dx = xs[k] - (if k > 1 then xs[k - 1] else 0) + local dy = ys[k] - (if k > 1 then ys[k - 1] else 0) + if dx == 0 then + fl += 0x10 + elseif dx > -256 and dx < 256 then + fl += if dx > 0 then 0x12 else 0x02 + end + if dy == 0 then + fl += 0x20 + elseif dy > -256 and dy < 256 then + fl += if dy > 0 then 0x24 else 0x04 + end + fls[k] = fl + end + local k = 1 + while k <= total do + local fl = fls[k] + local run = 0 + while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do + run += 1 + end + if run > 1 then + w:u8(fl + 8) + w:u8(run) + k += run + 1 + else + w:u8(fl) + k += 1 + end + end + for pass = 0, 1 do + local cs = if pass == 0 then xs else ys + local short, same = if pass == 0 then 0x02 else 0x04, if pass == 0 then 0x10 else 0x20 + local prev = 0 + for q = 1, total do + local d = cs[q] - prev + prev = cs[q] + local fl = fls[q] + if band(fl, short) ~= 0 then + w:u8(math.abs(d)) + elseif band(fl, same) == 0 then + w:u16be(d % 65536) + end + end + end + elseif nc == -1 then + if not hasBox(g) then + return nil, "composite glyph without a bounding box" + end + local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + xMins[g + 1] = x0 + w:u16be(0xFFFF) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + -- copy the component records: their length follows from the flags + local start = compS.p + local instr = false + while true do + local fl = su16(compS) + su16(compS) -- glyph index + local len = if band(fl, 1) ~= 0 then 4 else 2 + if band(fl, 8) ~= 0 then + len += 2 + elseif band(fl, 0x40) ~= 0 then + len += 4 + elseif band(fl, 0x80) ~= 0 then + len += 8 + end + compS.p += len + if band(fl, 0x100) ~= 0 then + instr = true + end + if compS.bad or compS.p > compS.e then + return nil, "composite stream truncated" + end + if band(fl, 0x20) == 0 then + break + end + end + w:bytes(b, start, compS.p - start) + if instr then + local ilen = s255(glyphS) + if glyphS.bad or instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:u16be(ilen) + w:bytes(b, instrS.p, ilen) + instrS.p += ilen + end + else + return nil, "bad contour count " .. nc + end + if bboxS.bad then + return nil, "bbox stream truncated" + end + -- 4-byte alignment + while w.pos % 4 ~= 0 do + w:u8(0) + end + if w.pos > maxBytes then + return nil, "limit" + end + end + loca[numGlyphs + 1] = w.pos + if indexFormat == 0 and w.pos > 0x1FFFE then + indexFormat = 1 -- (head.indexToLocFormat is patched to match) + end + return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil +end + +-- hmtx transform (version 1): advances + the side bearings that were not dropped +local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: number, xMins: { number }): (buffer?, string?) + local s = stream(b, p, n) + local flags = su8(s) + local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2) + local adv = table.create(numH, 0) + for i = 1, numH do + adv[i] = su16(s) + end + local lsb = table.create(numGlyphs, 0) + for i = 1, numH do + lsb[i] = if band(flags, 1) == 0 then si16(s) else (xMins[i] or 0) + end + for i = numH + 1, numGlyphs do + lsb[i] = if band(flags, 2) == 0 then si16(s) else (xMins[i] or 0) + end + if s.bad then + return nil, "hmtx transform truncated" + end + for i = 1, numH do + out:u16be(adv[i]) + out:u16be(lsb[i] % 65536) + end + for i = numH + 1, numGlyphs do + out:u16be(lsb[i] % 65536) + end + return out:finish(), nil +end + +-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") +function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) + if not r:match("wOF2") then + return nil, "bad signature", "corrupt" + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local totalSfnt = r:u32be() + local totalComp = r:u32be() + r:skip(24) + if r.err then + return nil, "truncated header", "truncated" + end + if flavor == "ttcf" then + return nil, "font collections in WOFF2", "unsupported" + end + if length > r:size() then + return nil, "file shorter than its header says", "truncated" + end + if numTables == 0 or numTables > 1024 then + return nil, "bad table count", "corrupt" + end + local dir = {} + local streamTotal = 0 + for i = 1, numTables do + local flags = r:u8() + local tag = KNOWN[band(flags, 63) + 1] + if band(flags, 63) == 63 then + tag = r:string(4) + end + local version = rshift(flags, 6) + local orig = base128(r) + if not tag or not orig then + return nil, "bad table directory entry " .. i, if r.err then "truncated" else "corrupt" + end + local transformed = if tag == "glyf" or tag == "loca" then version == 0 else version ~= 0 + local tlen = orig + if transformed then + local t = base128(r) + if not t then + return nil, "bad transformLength", "corrupt" + end + tlen = t + end + if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then + return nil, "bad glyf / loca transform version", "corrupt" + end + if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then + return nil, "unknown transform of " .. tag, "unsupported" + end + dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal } + streamTotal += tlen + if streamTotal > maxBytes or orig > maxBytes then + return nil, "limit", "limit" + end + end + local compAt = r.pos + if compAt + totalComp > r.limit then + return nil, "compressed data past the end", "truncated" + end + local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) }) + if not data then + local e = berr :: any + return nil, "brotli: " .. tostring(e.message), if e.code == "LIMIT" then "limit" else "corrupt" + end + if buffer.len(data) < streamTotal then + return nil, "decompressed stream shorter than the tables", "corrupt" + end + -- the tables, glyf / loca / hmtx rebuilt + local byTag: { [string]: any } = {} + for _, e in dir do + byTag[e.tag] = e + end + local tables: { [string]: buffer } = {} + local g = byTag.glyf + local xMins: { number } = {} + local locaLong: boolean? = nil + if g and g.transformed then + if not byTag.loca then + return nil, "glyf without loca", "corrupt" + end + local res, gerr = glyf(data, g.at, g.len, maxBytes) + if not res then + return nil, "glyf: " .. tostring(gerr), if gerr == "limit" then "limit" else "corrupt" + end + tables.glyf = res.glyf + xMins = res.xMins + local short = res.indexFormat == 0 + local lw = Bytes.writer((res.numGlyphs + 1) * 4) + for _, o in res.loca do + if short then + lw:u16be(o // 2) + else + lw:u32be(o) + end + end + tables.loca = lw:finish() + locaLong = not short + end + for _, e in dir do + if e.tag == "glyf" or e.tag == "loca" then + if not e.transformed then + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + elseif e.tag == "hmtx" and e.transformed then + -- needs numGlyphs (maxp) and numberOfHMetrics (hhea) + local mp, hh = byTag.maxp, byTag.hhea + if not mp or not hh or mp.len < 6 or hh.len < 36 then + return nil, "hmtx transform without maxp / hhea", "corrupt" + end + local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5) + local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35) + if numH < 1 or numH > numGlyphs then + return nil, "bad numberOfHMetrics", "corrupt" + end + local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins) + if not t then + return nil, herr, "corrupt" + end + tables.hmtx = t + else + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + end + -- head.indexToLocFormat must agree with the rebuilt loca + if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then + buffer.writeu8(tables.head, 50, 0) + buffer.writeu8(tables.head, 51, if locaLong then 1 else 0) + end + -- the sfnt: directory sorted by tag, tables 4-byte aligned + local tags = {} + for t in tables do + table.insert(tags, t) + end + table.sort(tags) + local n = #tags + local size = 12 + 16 * n + for _, t in tags do + size += (buffer.len(tables[t]) + 3) // 4 * 4 + end + if size > maxBytes then + return nil, "limit", "limit" + end + local out = buffer.create(size) + buffer.writestring(out, 0, flavor) + local es, sel = 1, 0 + while es * 2 <= n do + es *= 2 + sel += 1 + end + local function be16(o: number, v: number) + buffer.writeu8(out, o, rshift(v, 8)) + buffer.writeu8(out, o + 1, band(v, 255)) + end + local function be32(o: number, v: number) + buffer.writeu32(out, o, bit32.byteswap(v)) + end + be16(4, n) + be16(6, es * 16) + be16(8, sel) + be16(10, n * 16 - es * 16) + local p = 12 + 16 * n + for i, t in tags do + local tb = tables[t] + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, t) + be32(d + 4, 0) -- checksums are not recomputed + be32(d + 8, p) + be32(d + 12, buffer.len(tb)) + buffer.copy(out, p, tb) + p += (buffer.len(tb) + 3) // 4 * 4 + end + local _ = totalSfnt + return out, nil, nil +end + +return Rebuild +end +__FILES["host"] = function() + +-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE +-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). +-- +-- local host = require("@rosetta/host") +-- print(host.name) -- "roblox" | "love" | "luajit" | "luau" +-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO +-- -- where there is no file system) +local Err = __include("core/Err") + +type Host = { + name: string, + hasFiles: boolean, + readFile: (path: string) -> (buffer?, Err.Err?), + writeFile: (path: string, data: buffer) -> (boolean, Err.Err?), + exists: (path: string) -> boolean, + [string]: any, +} + +local G = _G :: any +local name +if typeof(game) == "Instance" then + name = "roblox" +elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then + name = "love" +elseif G.jit ~= nil or G.io ~= nil then + name = "luajit" +else + name = "luau" +end + +local host: Host +if name == "roblox" then + host = __include("host/Roblox") :: any +elseif name == "love" then + host = __include("host/Love") :: any +elseif name == "luajit" then + host = __include("host/LuaJIT") :: any +else + host = __include("host/Luau") :: any +end +-- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine +-- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only +-- allows more traces; set _G.ROSETTA_NO_JIT_TUNE = true before requiring the library to leave them alone. +if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then + pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536") +end + +local _ = Err +return host +end +__FILES["host/Love"] = function() + +-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for +-- paths outside them; converts the standard types to LÖVE objects: +-- host.toImageData(img) -> love ImageData (rgba8) +-- host.fromImageData(imageData) -> Image (rgba8) +-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit) +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "love" +Host.hasFiles = true + +local function love(): any + return (_G :: any).love +end +local function io(): any + return (_G :: any).io +end +-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone +local function ffi(): any + local req = (_G :: any).require + local ok, m = pcall(req, "ffi") + return if ok then m else nil +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local fs = love().filesystem + if fs.getInfo(path, "file") then + local s, msg = fs.read(path) + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) + end + return buffer.fromstring(s), nil + end + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + return buffer.fromstring(s), nil +end + +-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local s = buffer.tostring(data) + if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then + local ok, msg = love().filesystem.write(path, s) + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) + end + return true, nil + end + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + f:write(s) + f:close() + return true, nil +end + +function Host.exists(path: string): boolean + if love().filesystem.getInfo(path, "file") then + return true + end + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +-- toImageData(img) -> ImageData | nil, Err +function Host.toImageData(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) + end + local n = img.width * img.height * 4 + local F: any = ffi() + local B: { toffi: ((buffer) -> any)? } = buffer :: any + if F and B.toffi then + local id = love().image.newImageData(img.width, img.height, "rgba8") + F.copy(id:getFFIPointer(), B.toffi(img.pixels), n) + return id + end + local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n)) + return love().image.newImageData(img.width, img.height, "rgba8", bytes) +end + +-- fromImageData(imageData) -> Image (rgba8 copy) +function Host.fromImageData(id: any): Types.Image + local w, h = id:getDimensions() + local img = Types.Image.new(w, h, "rgba8") + local F: any = ffi() + local B: { toffi: ((buffer) -> any)? } = buffer :: any + if F and B.toffi and id:getFormat() == "rgba8" then + F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4) + return img + end + local s = id:getString() + buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4)) + return img +end + +-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end). +function Host.toSoundData(a: any): (any, Err.Err?) + local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate + if samples == nil then + -- a Decoder: read everything + local parts, total = {}, 0 + while true do + local out, n = a:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total += n + end + samples = buffer.create(total * channels * 4) + local o = 0 + for _, p in parts do + buffer.copy(samples, o, p) + o += buffer.len(p) + end + frames = total + end + local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) + local count = frames * channels + local F: any = ffi() + if F then + local p = F.cast("int16_t*", sd:getFFIPointer()) + for i = 0, count - 1 do + local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1) + p[i] = math.floor(v * 32767 + 0.5) + end + else + for i = 0, count - 1 do + sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1)) + end + end + return sd +end + +return Host +end +__FILES["host/LuaJIT"] = function() + +-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luajit" +Host.hasFiles = true + +local function io(): any + return (_G :: any).io +end + +function Host.readFile(path: string): (buffer?, Err.Err?) + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path) + end + return buffer.fromstring(s), nil +end + +function Host.writeFile(path: string, data: buffer): (boolean, Err.Err?) + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + local ok, werr = f:write(buffer.tostring(data)) + f:close() + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr)) + end + return true, nil +end + +function Host.exists(path: string): boolean + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +return Host +end +__FILES["host/Luau"] = function() + +-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luau" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path) +end + +function Host.exists(_path: string): boolean + return false +end + +return Host +end +__FILES["host/Roblox"] = function() + +-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the +-- standard types to engine objects: +-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first) +-- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh +-- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours) +-- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh +-- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime). +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "roblox" +Host.hasFiles = false + +function Host.readFile(path: string): (buffer?, Err.Err?) + return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path: string, _data: buffer): (boolean, Err.Err?) + return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)") +end + +function Host.exists(_path: string): boolean + return false +end + +-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8". +function Host.toEditableImage(img: any): (any, Err.Err?) + if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) + end + local AssetService = (game :: any):GetService("AssetService") + local size = Vector2.new(img.width, img.height) + local ok, ei = pcall(function() + return AssetService:CreateEditableImage({ Size = size }) + end) + if not ok or not ei then + return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei)) + end + ei:WritePixelsBuffer(Vector2.zero, size, img.pixels) + return ei +end + +-- ---------------------------------------------------------------------------------------------------------- meshes +-- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One +-- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client +-- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through +-- AssetService:CreateEditableMeshAsync), destroy it, then build the next. +-- +-- local prims = F.ops.mesh.merge(scene, { byMaterial = true }) +-- for _, prim in prims do +-- for _, page in assert(F.host.meshPages(prim)) do +-- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs +-- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em)) +-- part.Position = Vector3.new(centre[1], centre[2], centre[3]) +-- end +-- end +-- +-- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y") +-- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV +-- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted. + +type MeshPage = { + first: number, -- the first triangle (0-based) of the primitive in this page + count: number, -- triangles + vertices: { number }, -- local vertex i (1-based) = source vertex vertices[i] (0-based) + corners: buffer, -- u32 local vertex (0-based) per corner, 3 per triangle + min: { number }, -- bounds of the page's positions (source units) + max: { number }, +} + +type PageData = { + vertexCount: number, + triangleCount: number, + positions: { number }, -- x, y, z per vertex: (source - origin) * scale + normals: { number }?, -- x, y, z per vertex (unit; NORMAL scaled by the inverse scale) + uvs: { number }?, -- u, v per vertex (TEXCOORD_) + colors: { number }?, -- r, g, b, a per vertex, sRGB 0..1 (from linear COLOR_0) + corners: buffer, -- as MeshPage.corners + centre: { number }, -- origin * scale: where the page's local (0, 0, 0) sits +} + +type MeshOptions = { + maxTriangles: number?, -- per page, default 20000 + maxVertices: number?, -- per page, default 60000 + doubleSided: boolean?, -- toEditableMesh adds a back face per triangle (meshPages counts them), default false + scale: (number | { number })?, -- uniform or per axis, default 1 + origin: { number }?, -- subtracted before scaling, default the page's bounds centre + texCoord: number?, -- the TEXCOORD_n set for uvs, default 0 + flipV: boolean?, -- v = 1 - v, default false + normals: boolean?, -- NORMAL when present, default true + uvs: boolean?, -- default true + colors: boolean?, -- COLOR_0 when present, default true + editableMesh: any?, -- toEditableMesh appends to this mesh instead of creating one + yield: (() -> ())?, -- toEditableMesh calls it every yieldEvery triangles (e.g. a frame budget check) + yieldEvery: number?, -- default 2000 +} + +-- the index of each corner (0-based vertex numbers) or nil, Err +local function cornerReader(prim: any): ((number) -> number)? + local idx = prim.indices + if not idx then + return function(i: number): number + return i + end + end + local get = Types.Scene.reader(idx) + if not get then + return nil + end + return function(i: number): number + return (get :: any)(i, 0) + end +end + +local function checkPrim(prim: any): (number, Err.Err?) + if type(prim) ~= "table" or type(prim.attributes) ~= "table" or type(prim.attributes.POSITION) ~= "table" then + return 0, Err.new(Err.ARG, "expected a Primitive with POSITION") + end + if (prim.mode or "triangles") ~= "triangles" then + return 0, Err.new(Err.ARG, "needs a triangle primitive (F.ops.mesh.merge or triangulate first), got " .. tostring(prim.mode)) + end + local n = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + return n // 3, nil +end + +-- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces +-- counted when doubleSided) and maxVertices. +function Host.meshPages(prim: any, opts: MeshOptions?): ({ MeshPage }?, Err.Err?) + local tris, err = checkPrim(prim) + if err then + return nil, err + end + local o: MeshOptions = opts or {} + local per = if o.doubleSided then 2 else 1 + local maxT = math.max(1, (o.maxTriangles or 20000) // per) + local maxV = math.max(3, o.maxVertices or 60000) + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + local corner = cornerReader(prim) + if not getP or not corner then + return nil, Err.new(Err.ARG, "unsupported accessor type") + end + local nv = pos.count + local pages: { MeshPage } = {} + local t = 0 + while t < tris do + local map: { [number]: number } = {} + local verts: { number } = {} + local first = t + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local cs: { number } = {} + while t < tris and t - first < maxT do + local a, b, c = corner(t * 3), corner(t * 3 + 1), corner(t * 3 + 2) + if a >= nv or b >= nv or c >= nv or a < 0 or b < 0 or c < 0 then + return nil, Err.new(Err.ARG, string.format("triangle %d: vertex index out of range", t)) + end + local fresh = (if map[a] then 0 else 1) + (if map[b] or b == a then 0 else 1) + (if map[c] or c == a or c == b then 0 else 1) + if #verts + fresh > maxV and t > first then + break + end + for _, v in { a, b, c } do + local l = map[v] + if not l then + l = #verts + verts[l + 1] = v + map[v] = l + for k = 1, 3 do + local x = (getP :: any)(v, k - 1) + if x < lo[k] then + lo[k] = x + end + if x > hi[k] then + hi[k] = x + end + end + end + cs[#cs + 1] = l + end + t += 1 + end + local corners = buffer.create(#cs * 4) + for i, l in cs do + buffer.writeu32(corners, (i - 1) * 4, l) + end + pages[#pages + 1] = { first = first, count = t - first, vertices = verts, corners = corners, min = lo, max = hi } + end + return pages, nil +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.0031308 then c * 12.92 else 1.055 * c ^ (1 / 2.4) - 0.055 +end + +-- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for +-- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours). +function Host.pageData(prim: any, page: MeshPage, opts: MeshOptions?): (PageData?, Err.Err?) + local _, err = checkPrim(prim) + if err then + return nil, err + end + if type(page) ~= "table" or type(page.vertices) ~= "table" or type(page.corners) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a MeshPage from meshPages") + end + local o: MeshOptions = opts or {} + local sc = o.scale or 1 + local sx, sy, sz + if type(sc) == "table" then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + else + sx, sy, sz = sc, sc, sc + end + local origin = o.origin + or { (page.min[1] + page.max[1]) / 2, (page.min[2] + page.max[2]) / 2, (page.min[3] + page.max[3]) / 2 } + local attrs = prim.attributes + local getP = Types.Scene.reader(attrs.POSITION) + local getN = if o.normals ~= false and attrs.NORMAL then Types.Scene.reader(attrs.NORMAL) else nil + local uvAcc = if o.uvs ~= false then attrs["TEXCOORD_" .. tostring(o.texCoord or 0)] else nil + local getT = if uvAcc then Types.Scene.reader(uvAcc) else nil + local colAcc = if o.colors ~= false then attrs.COLOR_0 else nil + local getC = if colAcc then Types.Scene.reader(colAcc) else nil + if not getP then + return nil, Err.new(Err.ARG, "unsupported POSITION accessor type") + end + local n = #page.vertices + local positions = table.create(n * 3, 0) + local normals = if getN then table.create(n * 3, 0) else nil + local uvs = if getT then table.create(n * 2, 0) else nil + local colors = if getC then table.create(n * 4, 1) else nil + local ox, oy, oz = origin[1], origin[2], origin[3] + local flip = o.flipV == true + local alpha = colAcc and colAcc.components >= 4 + for i, v in page.vertices do + local j = (i - 1) * 3 + positions[j + 1] = ((getP :: any)(v, 0) - ox) * sx + positions[j + 2] = ((getP :: any)(v, 1) - oy) * sy + positions[j + 3] = ((getP :: any)(v, 2) - oz) * sz + if normals then + -- normals of a scaled mesh scale by the inverse + local x, y, z = (getN :: any)(v, 0) / sx, (getN :: any)(v, 1) / sy, (getN :: any)(v, 2) / sz + local len = math.sqrt(x * x + y * y + z * z) + if len > 0 then + x, y, z = x / len, y / len, z / len + else + x, y, z = 0, 1, 0 + end + normals[j + 1], normals[j + 2], normals[j + 3] = x, y, z + end + if uvs then + local u, w = (getT :: any)(v, 0), (getT :: any)(v, 1) + uvs[(i - 1) * 2 + 1] = u + uvs[(i - 1) * 2 + 2] = if flip then 1 - w else w + end + if colors then + local k = (i - 1) * 4 + colors[k + 1] = toSrgb((getC :: any)(v, 0)) + colors[k + 2] = toSrgb((getC :: any)(v, 1)) + colors[k + 3] = toSrgb((getC :: any)(v, 2)) + colors[k + 4] = if alpha then math.clamp((getC :: any)(v, 3), 0, 1) else 1 + end + end + return { + vertexCount = n, + triangleCount = page.count, + positions = positions, + normals = normals, + uvs = uvs, + colors = colors, + corners = page.corners, + centre = { ox * sx, oy * sy, oz * sz }, + }, nil +end + +-- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole +-- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart +-- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then. +function Host.toEditableMesh(prim: any, page: MeshPage?, opts: MeshOptions?): (any, any) + local o: MeshOptions = opts or {} + local pg = page + if not pg then + local pages, err = Host.meshPages(prim, o) + if not pages then + return nil, err + end + if #pages ~= 1 then + return nil, Err.new(Err.LIMIT, string.format("toEditableMesh: %d pages: split with meshPages", #pages)) + end + pg = pages[1] + end + local data, err = Host.pageData(prim, pg :: MeshPage, o) + if not data then + return nil, err + end + local d = data :: PageData + local em = o.editableMesh + local own = em == nil + if own then + local AssetService = (game :: any):GetService("AssetService") + local ok, made = pcall(function() + return AssetService:CreateEditableMesh() + end) + if not ok or not made then + return nil, Err.new(Err.IO, "CreateEditableMesh failed (a client has 8 growable EditableMeshes): " .. tostring(made)) + end + em = made + end + local ok, perr = pcall(function() + local P, N, U, C = d.positions, d.normals, d.uvs, d.colors + local vids = table.create(d.vertexCount, 0) + local nids = if N then table.create(d.vertexCount, 0) else nil + local bids = if N and o.doubleSided then table.create(d.vertexCount, 0) else nil + local uids = if U then table.create(d.vertexCount, 0) else nil + local cids = if C then table.create(d.vertexCount, 0) else nil + local palette: { [string]: number } = {} + for i = 1, d.vertexCount do + local j = (i - 1) * 3 + vids[i] = em:AddVertex(Vector3.new(P[j + 1], P[j + 2], P[j + 3])) + if N and nids then + local n = Vector3.new(N[j + 1], N[j + 2], N[j + 3]) + nids[i] = em:AddNormal(n) + if bids then + bids[i] = em:AddNormal(-n) + end + end + if U and uids then + uids[i] = em:AddUV(Vector2.new(U[(i - 1) * 2 + 1], U[(i - 1) * 2 + 2])) + end + if C and cids then + local k = (i - 1) * 4 + local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4] + -- equal colours share one id (voxel palettes, flat-coloured models) + local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5)) + local id = palette[key] + if not id then + id = em:AddColor(Color3.new(r, g, b), a) + palette[key] = id + end + cids[i] = id + end + end + local corners = d.corners + local every = o.yieldEvery or 2000 + local yield = o.yield + for t = 0, d.triangleCount - 1 do + local a = buffer.readu32(corners, t * 12) + 1 + local b = buffer.readu32(corners, t * 12 + 4) + 1 + local c = buffer.readu32(corners, t * 12 + 8) + 1 + local f = em:AddTriangle(vids[a], vids[b], vids[c]) + if nids then + em:SetFaceNormals(f, { nids[a], nids[b], nids[c] }) + end + if uids then + em:SetFaceUVs(f, { uids[a], uids[b], uids[c] }) + end + if cids then + em:SetFaceColors(f, { cids[a], cids[b], cids[c] }) + end + if o.doubleSided then + local g = em:AddTriangle(vids[a], vids[c], vids[b]) + if bids then + em:SetFaceNormals(g, { bids[a], bids[c], bids[b] }) + end + if uids then + em:SetFaceUVs(g, { uids[a], uids[c], uids[b] }) + end + if cids then + em:SetFaceColors(g, { cids[a], cids[c], cids[b] }) + end + end + if yield and (t + 1) % every == 0 then + yield() + end + end + end) + if not ok then + if own then + pcall(function() + em:Destroy() + end) + end + return nil, Err.new(Err.IO, "EditableMesh: " .. tostring(perr)) + end + return em, d.centre +end + +return Host +end +__FILES["image/ani"] = function() + +-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; +-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, +-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) +-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames +-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors +-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a +-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Riff = __include("containers/Riff") + +-- ------------------------------------------------------------------------------------------------ contract +local Ani = { + name = "ani", + category = "image", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one) + maxFrames: number?, -- refuse more steps (default 10000) +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ani.sniff(r: Bytes.Reader): number + return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local f, ferr = Riff.read(r) + if not f then + return nil, ferr + end + if f.form ~= "ACON" then + return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8) + end + local anih = Riff.find(f, "anih") + if not anih or anih.avail < 36 then + return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12) + end + local a = anih.offset + local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8) + local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32) + local maxFrames = opts and opts.maxFrames or 10000 + if nSteps == 0 then + nSteps = nFrames + end + if nFrames > maxFrames or nSteps > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames", a + 4) + end + if bit32.band(flags, 1) == 0 then + return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32) + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") + end + -- the icon chunks + local icons: { Types.Image } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "fram" then + for _, ic in Riff.list(f, c) do + if ic.id == "icon" then + local sub = buffer.create(ic.avail) + buffer.copy(sub, 0, f.buf, ic.offset, ic.avail) + local ok, im, ierr = pcall(decodeImage, sub) + if not ok or not im then + return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset) + end + table.insert(icons, im :: Types.Image) + end + end + end + end + if #icons == 0 then + return nil, Err.new(Err.TRUNCATED, "no icon frames") + end + local rate = Riff.find(f, "rate") + local seq = Riff.find(f, "seq ") + local frames: { Types.Frame } = {} + for s = 0, nSteps - 1 do + local idx = s + if seq and seq.avail >= (s + 1) * 4 then + idx = Riff.u32(f, seq.offset + s * 4) + end + local im = icons[idx + 1] + if not im then + if s >= #icons and not seq then + break -- fewer icons than steps: keep what is there + end + return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) + end + local jiffies = dispRate + if rate and rate.avail >= (s + 1) * 4 then + jiffies = Riff.u32(f, rate.offset + s * 4) + end + table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame) + end + local first = frames[1].image + local img = Types.Image.new(0, 0, first.format) + img.width, img.height, img.pixels = first.width, first.height, first.pixels + img.frames = frames + img.loops = 0 + img.meta.hotspot = first.meta.hotspot + local text: { [string]: string } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, it in Riff.list(f, c) do + local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil + if key then + text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", "")) + end + end + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook") + end + local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame } + local w = Riff.writer("ACON") + local jiffies: { number } = {} + local same = true + for i, fr in frames do + jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5)) + same = same and jiffies[i] == jiffies[1] + end + local head = Bytes.writer(36) + head:u32le(36) + head:u32le(#frames) + head:u32le(#frames) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(jiffies[1]) + head:u32le(1) + w:chunk("anih", head:finish()) + if not same then + local rw = Bytes.writer(#frames * 4) + for _, j in jiffies do + rw:u32le(j) + end + w:chunk("rate", rw:finish()) + end + local items = {} + for i, fr in frames do + local im = fr.image + local ok, data, err = pcall(encodeImage, im, "ico") + if not ok or not data then + return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data)) + end + table.insert(items, { "icon", data }) + end + w:list("fram", items) + return w:finish() +end + +return Ani +end +__FILES["image/blp"] = function() + +-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written +-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. +-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: +-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual +-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); +-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); +-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha +-- type 0 / 1 / 7), uncompressed BGRA. +-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). +-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Jpeg = __include("codecs/image/Jpeg") +local Bcn = __include("codecs/image/Bcn") + +-- ------------------------------------------------------------------------------------------------ contract +local Blp = { + name = "blp", + category = "image", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxPixels: number? } -- default 2^26 +type EncodeOptions = { mips: boolean? } -- write the mip chain (default false) + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Blp.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m == "BLP1" or m == "BLP2" then 1 elseif m == "BLP0" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha +local function swap(v: number, a: number): number + local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256 + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- alpha of pixel i from a packed plane at p of depth bits +local function alphaAt(b: buffer, p: number, depth: number, i: number): number + if depth == 8 then + return readu8(b, p + i) + elseif depth == 4 then + local v = readu8(b, p + i // 2) + local n = if i % 2 == 0 then v % 16 else v // 16 + return n * 17 + elseif depth == 1 then + local v = readu8(b, p + i // 8) + return if bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 then 255 else 0 + end + return 255 +end + +function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + local magic = r:peek(4) + if magic == "BLP0" then + return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0) + end + if magic ~= "BLP1" and magic ~= "BLP2" then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local v2 = magic == "BLP2" + local headerSize = if v2 then 20 + 128 + 1024 else 28 + 128 + if size < headerSize then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG) + local compression = if v2 then readu8(b, base + 8) elseif kind == 0 then 0 else 1 + local alphaDepth = if v2 then readu8(b, base + 9) else readu32(b, base + 8) + local alphaType = if v2 then readu8(b, base + 10) else 0 + local w, h = readu32(b, base + 12), readu32(b, base + 16) + local mipsAt = if v2 then 20 else 28 + if w == 0 or h == 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local offs: { number }, lens: { number } = {}, {} + local mips = 0 + for i = 0, 15 do + offs[i + 1] = readu32(b, base + mipsAt + i * 4) + lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4) + if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then + mips += 1 + end + end + local at, len = offs[1], lens[1] + if at + len > size or len == 0 then + return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt) + end + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local src = base + at + local name: string + if (not v2 and kind == 0) or (v2 and kind == 0) then + if v2 then + return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG") + end + -- the JPEG header shared by the mips, then the mip's own data + if size < headerSize + 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize) + end + local hs = readu32(b, base + headerSize) + if hs > 0x10000 or headerSize + 4 + hs > size then + return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize) + end + local jpg = buffer.create(hs + len) + buffer.copy(jpg, 0, b, base + headerSize + 4, hs) + buffer.copy(jpg, hs, b, src, len) + local info = Jpeg.info(jpg) + local four = info ~= nil and (info :: any).components == 4 + local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local dw, dh = math.min(dec.width, w), math.min(dec.height, h) + for y = 0, dh - 1 do + for x = 0, dw - 1 do + local v = readu32(dec.pixels, (y * dec.width + x) * 4) + local a = if four and alphaDepth > 0 then v // 16777216 else 255 + writeu32(px, (y * w + x) * 4, swap(v, a)) + end + end + name = "jpeg" + elseif compression == 1 then + local palAt = base + (if v2 then 148 else headerSize) + local dataAt = src + if not v2 then + -- BLP1: the palette follows the header; the mip offsets point past it + if headerSize + 1024 > size then + return nil, Err.new(Err.TRUNCATED, "palette", headerSize) + end + end + local depth = if v2 then alphaDepth else (if alphaDepth >= 8 then 8 else 0) + local need = n + (if depth == 8 then n elseif depth == 4 then (n + 1) // 2 elseif depth == 1 then (n + 7) // 8 else 0) + if at + need > size then + return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at) + end + for i = 0, n - 1 do + local e = readu32(b, palAt + readu8(b, dataAt + i) * 4) + writeu32(px, i * 4, swap(e, if depth > 0 then alphaAt(b, dataAt + n, depth, i) else 255)) + end + name = "palette" + elseif compression == 2 then + local kindName = if alphaType == 7 then "bc3" elseif alphaType == 1 then "bc2" else "bc1" + local want: number = Bcn.size(kindName, w, h) or 0 + if len < want then + return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64) + end + local dec, err = Bcn.decode(kindName, b, src, w, h) + if not dec then + return nil, Err.from(err) + end + buffer.copy(px, 0, dec, 0, n * 4) + if kindName == "bc1" and alphaDepth == 0 then + for i = 0, n - 1 do + writeu8(px, i * 4 + 3, 255) + end + end + name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } :: { [string]: string })[kindName] + elseif compression == 3 then + if len < n * 4 then + return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64) + end + for i = 0, n - 1 do + local v = readu32(b, src + i * 4) + writeu32(px, i * 4, swap(v, v // 16777216)) + end + name = "bgra" + else + return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression)) + end + img.meta.source = { format = "blp", version = if v2 then 2 else 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(nw * nh * 4) + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + writeu8(out, (y * nw + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, nw, nh +end + +function Blp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "bad size") + end + local levels: { buffer } = { img.pixels } + local sizes: { { number } } = { { w, h } } + if opts and opts.mips then + local p, cw, ch = img.pixels, w, h + while (cw > 1 or ch > 1) and #levels < 16 do + p, cw, ch = halve(p, cw, ch) + table.insert(levels, p) + table.insert(sizes, { cw, ch }) + end + end + local out = Bytes.writer(1172 + w * h * 6) + out:string("BLP2") + out:u32le(1) + out:u8(3) -- uncompressed BGRA + out:u8(8) -- alpha depth + out:u8(8) -- alpha type + out:u8(if #levels > 1 then 1 else 0) + out:u32le(w) + out:u32le(h) + local at = 1172 + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then at else 0) + if l then + at += buffer.len(l) + end + end + for i = 1, 16 do + local l = levels[i] + out:u32le(if l then buffer.len(l) else 0) + end + out:fill(0, 1024) + for _, l in levels do + local p = out:reserve(buffer.len(l)) + local o = out.buf + for i = 0, buffer.len(l) // 4 - 1 do + local v = readu32(l, i * 4) + writeu32(o, p + i * 4, swap(v, v // 16777216)) + end + out.pos = p + buffer.len(l) + end + return out:finish(), nil +end + +return Blp +end +__FILES["image/bmp"] = function() + + +-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a +-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 +-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or +-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), +-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the +-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit +-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). +-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance +-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with +-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. +-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmp = { + name = "bmp", + category = "image", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Info = { + width: number, + height: number, + bitsPerPixel: number, + compression: number, + topDown: boolean, + headerSize: number, + os2: boolean, +} + +type DecodeOptions = { + maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx) +} +type EncodeOptions = { + bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32 + header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAX_PIXELS = 2 ^ 26 +local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" } + +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz + +-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) +local function whole(r: Bytes.Reader): buffer + if r.base == 0 and r.limit == buffer.len(r.buf) then + return r.buf + end + local n = r.limit - r.base + local b = buffer.create(n) + buffer.copy(b, 0, r.buf, r.base, n) + return b +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmp.sniff(r: Bytes.Reader): number + if r:peek(2) ~= "BM" then + return 0 + end + -- a known header size: a strong match; "BM" alone is weak + local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 + if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err +local function parseHeader(buf: buffer): (Info?, any) + local n = buffer.len(buf) + if n < 18 then + return nil, Err.new(Err.TRUNCATED, "file too short") + end + if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then + return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)") + end + local hs = readu32(buf, 14) + if hs < 12 or 14 + hs > n then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + local info: Info = { + width = 0, + height = 0, + bitsPerPixel = 0, + compression = 0, + topDown = false, + headerSize = hs, + os2 = false, + } + if hs == 12 then + info.width = readu16(buf, 18) + info.height = readu16(buf, 20) + info.bitsPerPixel = readu16(buf, 24) + info.os2 = true + else + if hs < 16 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + info.width = readi32(buf, 18) + local h = readi32(buf, 22) + info.bitsPerPixel = readu16(buf, 28) + if hs >= 20 then + info.compression = readu32(buf, 30) + end + if h < 0 then + info.topDown = true + h = -h + end + info.height = h + -- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one + info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124) + end + return info +end + +-- info(r) -> Info | nil, Err: the header without decoding the pixels +function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?) + return parseHeader(whole(r)) +end + +-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate +-- the top bits instead, which can differ by 1). m = 0 -> { empty }. +local function scaleTable(m: number, empty: number): buffer + local t = buffer.create(m + 1) + if m == 0 then + buffer.writeu8(t, 0, empty) + else + for v = 0, m do + buffer.writeu8(t, v, (v * 255) // m) + end + end + return t +end + +-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +local function channel(mask: number, empty: number): (number, number, buffer) + if mask == 0 then + return 0, 0, scaleTable(0, empty) + end + local sh = countrz(mask) + local m = rshift(mask, sh) + -- holes in the mask: use the lowest contiguous run of bits + local bits = 0 + while bits < 32 and band(m, lshift(1, bits)) ~= 0 do + bits += 1 + end + if bits > 16 then + sh += bits - 16 + bits = 16 + end + m = lshift(1, bits) - 1 + return sh, m, scaleTable(m, empty) +end + +-- decode(r, opts?) -> rgba8 Image | nil, Err +function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local buf = whole(r) + local info, herr = parseHeader(buf) + if not info then + return nil, herr + end + local n = buffer.len(buf) + local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression + if w <= 0 or h <= 0 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h) + end + local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")") + end + if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then + return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported") + end + if comp == 4 or comp == 5 then + return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (if comp == 4 then "JPEG" else "PNG") .. " is not supported") + end + if comp > 6 then + return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp) + end + local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32) + if not valid then + return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp) + end + if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then + return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp") + end + if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp") + end + + -- masks: in the v2+ header, or right after a 40-byte header + local palStart = 14 + hs + local rm: number, gm: number, bm: number, am: number = 0, 0, 0, 0 + local hasMasks = false + if comp == 3 or comp == 6 then + hasMasks = true + if hs >= 52 then + rm = readu32(buf, 54) + gm = readu32(buf, 58) + bm = readu32(buf, 62) + if hs >= 56 then + am = readu32(buf, 66) + end + else + local count = if comp == 6 then 4 else 3 + if palStart + count * 4 > n then + return nil, Err.new(Err.TRUNCATED, "truncated bit masks") + end + rm = readu32(buf, palStart) + gm = readu32(buf, palStart + 4) + bm = readu32(buf, palStart + 8) + if comp == 6 then + am = readu32(buf, palStart + 12) + end + palStart += count * 4 + end + if comp == 3 and hs < 56 then + am = 0 + end + if rm == 0 and gm == 0 and bm == 0 then + hasMasks = false -- all-zero masks: use the defaults + end + end + + -- palette + local entrySize = if hs == 12 then 3 else 4 + local declared = if hs >= 36 then readu32(buf, 46) else 0 + local palCount = 0 + if bpp <= 8 then + palCount = if declared == 0 or declared > lshift(1, bpp) then lshift(1, bpp) else declared + end + local off = readu32(buf, 10) + local pixelEnd = palStart + palCount * entrySize + if off < palStart or off >= n then + -- bad bfOffBits: the pixels start after the palette as declared + off = math.min(pixelEnd, n) + elseif bpp <= 8 and off < pixelEnd then + -- palette shorter than declared: it ends where the pixels start + palCount = (off - palStart) // entrySize + end + palCount = math.max(0, math.min(palCount, (n - palStart) // entrySize)) + local pal = buffer.create(256 * 4) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + for i = 0, palCount - 1 do + local p = palStart + i * entrySize + local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + + local img = Types.Image.new(w, h, "rgba8") + local pixels = img.pixels + img.meta.source = { + format = "bmp", + bitDepth = bpp, + compression = COMPRESSION_NAMES[comp], + topDown = info.topDown, + headerSize = hs, + paletteSize = palCount, + os2 = info.os2, + } + if bpp <= 8 and palCount > 0 then + local palette: { { number } } = {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), 255 } + end + img.meta.palette = palette + end + if hs >= 40 then + local xp, yp = readi32(buf, 38), readi32(buf, 42) + if xp > 0 and yp > 0 then + img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 } + end + end + + if comp == 1 or comp == 2 then + Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal) + return img, nil + end + + -- uncompressed: make sure every row is readable (a truncated file reads as zeros) + local stride = ((w * bpp + 31) // 32) * 4 + local need = stride * h + local src, base = buf, off + if off + need > n then + src = buffer.create(need) + buffer.copy(src, 0, buf, off, n - off) + base = 0 + end + + if bpp <= 8 then + Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal) + elseif bpp == 24 and not hasMasks then + Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown) + elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then + local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown) + if aor == 0 or (hasMasks and am == 0) then + Pixels.opaque(pixels, w * h) + end + else + if not hasMasks then + if bpp == 16 then + rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0 + else + rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0 + end + end + local shr, mr, tr = channel(rm, 0) + local shg, mg, tg = channel(gm, 0) + local shb, mb, tb = channel(bm, 0) + local sha, ma, ta = channel(am, 255) + local aor = + Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) + if ma ~= 0 and aor == 0 then + Pixels.opaque(pixels, w * h) + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(img, opts?) -> buffer | nil, Err +function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 0x7FFFFFFF or h > 0x7FFFFFFF then + return nil, Err.new(Err.ARG, "encode: bad image size") + end + if buffer.len(img.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4") + end + local want = opts and opts.bitDepth or "auto" + if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then + return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto") + end + local headerKind = opts and opts.header or "v4" + if headerKind ~= "v4" and headerKind ~= "info" then + return nil, Err.new(Err.ARG, "encode: header must be v4 or info") + end + local colours, alpha = Pixels.colours(img.pixels, w * h, 256) + local bpp: number + if want == "auto" then + bpp = if alpha then 32 elseif #colours <= 256 then 8 else 24 + else + bpp = want :: number + if bpp == 8 and #colours > 256 then + return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp") + end + end + local v4 = bpp == 32 and headerKind == "v4" + local hs = if v4 then 108 else 40 + local stride = ((w * bpp + 31) // 32) * 4 + local palCount = if bpp == 8 then #colours else 0 + local off = 14 + hs + palCount * 4 + local imageSize = stride * h + if off + imageSize > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB") + end + local out = buffer.create(off + imageSize) + local o = Bytes.writer(off) + o:string("BM") + o:u32le(off + imageSize) + o:u32le(0) + o:u32le(off) + o:u32le(hs) + o:i32le(w) + o:i32le(h) + o:u16le(1) + o:u16le(bpp) + o:u32le(if v4 then 3 else 0) -- BI_BITFIELDS / BI_RGB + o:u32le(imageSize) + local dpi = img.meta and img.meta.dpi + local xp: number, yp: number = 3780, 3780 -- 96 dpi, as Pillow + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + xp = math.floor((dpi.x :: number) * 39.3701 + 0.5) + yp = math.floor((dpi.y :: number) * 39.3701 + 0.5) + end + o:i32le(xp) + o:i32le(yp) + o:u32le(palCount) + o:u32le(palCount) + if v4 then + o:u32le(0x00FF0000) + o:u32le(0x0000FF00) + o:u32le(0x000000FF) + o:u32le(0xFF000000) + o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB') + o:fill(0, 36 + 12) -- endpoints, gamma + end + local idx: { [number]: number } = {} + for i, c in colours do + if i > palCount then + break + end + idx[c] = i - 1 + o:u8(band(rshift(c, 16), 255)) + o:u8(band(rshift(c, 8), 255)) + o:u8(band(c, 255)) + o:u8(0) + end + buffer.copy(out, 0, o.buf, 0, off) + if bpp == 8 then + Pixels.encode8(img.pixels, w, h, out, off, stride, idx) + elseif bpp == 24 then + Pixels.encode24(img.pixels, w, h, out, off, stride) + else + Pixels.encode32(img.pixels, w, h, out, off) + end + return out, nil +end + +return Bmp +end +__FILES["image/dds"] = function() + +-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new +-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / +-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the +-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the +-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six +-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there +-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / +-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by +-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. +-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 +-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the +-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), +-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Dds = { + name = "dds", + category = "image", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8) + mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) + surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) + maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface) +} +type EncodeOptions = { + pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: + -- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones + mips: boolean?, -- write a full mip chain (default false) + dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays) + cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube") + alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- DXGI_FORMAT -> texture format name, sRGB +local DXGI: { [number]: string } = { + [1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i", + [5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i", + [9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i", + [15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i", + [23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f", + [27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i", + [33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i", + [39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i", + [48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i", + [53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i", + [60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8", + [67] = "rgb9e5", [68] = "rgbg", [69] = "grgb", + [70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3", + [79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s", + [85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8", + [94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7", + [100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4", +} +local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true } +-- legacy FourCC codes (strings and D3DFMT numbers) +local FOURCC: { [string]: string } = { + DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3", + ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s", + YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb", +} +local D3DFMT: { [number]: string } = { + [36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f", + [114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s", +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } +local MAGIC = "DDS " + +local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000 +local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000 +local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000 +local MISC_CUBE = 0x4 + +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Dds.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6)) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + width: number, + height: number, + depth: number, + mips: number, + format: string, -- the texture format name (codecs/image/Texture) + layout: string, -- "2d" | "cube" | "array" | "volume" + layers: number, + faces: { string }, -- cube faces present (in file order), else { } + srgb: boolean, + dxgi: number?, + fourcc: string?, + dataOffset: number, -- relative to the file start + alphaMode: number?, + premultiplied: boolean?, + masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name) +} + +local function u32(b: buffer, o: number): number + return buffer.readu32(b, o) +end + +-- info(r) -> Info | nil, Err (the headers only) +function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o) + end + if u32(b, o + 4) ~= 124 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4) + end + local flags = u32(b, o + 8) + local h, w = u32(b, o + 12), u32(b, o + 16) + local depth = u32(b, o + 24) + local mips = u32(b, o + 28) + local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84) + local bitCount = u32(b, o + 88) + local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104) + local caps2 = u32(b, o + 112) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12) + end + if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then + mips = 1 -- a count without the flag or the caps bit: some writers leave garbage + end + mips = math.max(1, mips) + local maxMips = 1 + do + local m = math.max(w, h, depth) + while m > 1 do + m //= 2 + maxMips += 1 + end + end + if mips > maxMips then + return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28) + end + local info: Info = { + width = w, + height = h, + depth = 1, + mips = mips, + format = "", + layout = "2d", + layers = 1, + faces = {}, + srgb = false, + dataOffset = 128, + } + local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1 + if band(pfFlags, DDPF_FOURCC) ~= 0 then + local fourcc = buffer.readstring(b, o + 84, 4) + if fourcc == "DX10" then + if n < 148 then + return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128) + end + local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144) + info.dxgi = dxgi + info.dataOffset = 148 + local name = DXGI[dxgi] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128) + end + info.format = name + info.srgb = SRGB[dxgi] == true + info.alphaMode = band(misc2, 7) + info.premultiplied = band(misc2, 7) == 2 + info.layers = math.max(1, arr) + if info.layers > 4096 then + return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140) + end + if dim == 4 then + volume = true + elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132) + else + volume = false + end + if band(misc, MISC_CUBE) ~= 0 then + info.layout = "cube" + info.faces = table.clone(FACES) + elseif info.layers > 1 then + info.layout = "array" + end + else + info.fourcc = fourcc + local name = FOURCC[fourcc] or D3DFMT[fourccNum] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84) + end + info.format = name + info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4" + end + elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then + local bytes = bitCount // 8 + if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then + return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88) + end + local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0 + local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0 + local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0 + local d + if alphaOnly then + d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF) + elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then + d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC + else + d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum) + end + if not d then + return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) + end + -- the common masks map onto named texel formats (fast paths, sane names) + local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) + local named = ({ + ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", + ["32:ff0000:ff00:ff:ff000000:false"] = "bgra8", + ["32:ff0000:ff00:ff:0:false"] = "bgrx8", + ["32:ff:ff00:ff0000:0:false"] = "rgbx8", + ["24:ff0000:ff00:ff:0:false"] = "bgr8", + ["24:ff:ff00:ff0000:0:false"] = "rgb8", + ["8:ff:0:0:0:true"] = "l8", + ["16:ffff:0:0:0:true"] = "l16", + } :: { [string]: string })[key] + info.format = named or "masked" + info.masked = d + else + return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80) + end + if volume then + info.layout = "volume" + info.depth = math.max(1, depth) + if info.depth > 2048 then + return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24) + end + elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then + info.layout = "cube" + for i, f in FACES do + if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then + table.insert(info.faces, f) + end + end + if #info.faces == 0 then + info.faces = table.clone(FACES) + end + end + return info, nil +end + +-- the bytes of one surface of format f +local function surfaceSize(info: any, w: number, h: number): number + if info.format == "masked" then + return (info.masked :: Texel.Desc).bytes * w * h + end + return Texture.size(info.format, w, h) :: number +end + +function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Dds.info(r) + if not info then + return nil, ierr + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base = r.buf, r.base + local p = base + info.dataOffset + local limit = r.limit + local count = if info.layout == "cube" then #info.faces * info.layers else info.layers + local list: { Texture.Surface } = {} + local pixels = 0 + local stop = false + for layer = 0, count - 1 do + local w, h, d = info.width, info.height, info.depth + for level = 0, info.mips - 1 do + local size = surfaceSize(info, w, h) + for slice = 0, d - 1 do + local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0) + if want then + if p + size > limit then + if level > 0 or layer > 0 or slice > 0 then + stop = true -- a cut mip chain / later surface: keep what decoded + break + end + return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p) + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local px, pf + if info.format == "masked" then + px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native) + else + px, pf = Texture.decode(info.format, b, p, w, h, native) + end + if not px then + return nil, Err.from(pf, p) + end + local face = if info.layout == "cube" then layer % #info.faces else 0 + table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) }) + end + p += size + end + if stop then + break + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + if stop then + break + end + end + local img = Texture.assemble(list, info.layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset) + end + if info.layout == "cube" then + img.meta.faces = info.faces + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.source = { + format = "dds", + pixelFormat = info.format, + dxgi = info.dxgi, + fourcc = info.fourcc, + mips = info.mips, + layers = info.layers, + depth = info.depth, + premultiplied = info.premultiplied, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } +local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } + +-- the surface bytes of one image in format f +local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?) + local w, h, px = img.width, img.height, img.pixels + if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then + local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil) + if not blocks then + return nil, Err.new(Err.ARG, tostring(err)) + end + return blocks, nil + elseif f == "bgra8" then + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16)) + end + return out, nil + elseif f == "rgba16f" then + return Texture.toHalf(px, w * h), nil + end + local out = buffer.create(w * h * (BYTES_PF[f] :: number)) + buffer.copy(out, 0, px, 0, buffer.len(out)) + return out, nil +end + +local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean) + local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" + out:string(MAGIC) + out:u32le(124) + local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8) + out:u32le(flags) + out:u32le(h) + out:u32le(w) + out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number)) + out:u32le(0) + out:u32le(if mips > 1 then mips else 0) + out:fill(0, 44) + -- DDS_PIXELFORMAT + out:u32le(32) + if dx10 then + out:u32le(DDPF_FOURCC) + out:string("DX10") + out:fill(0, 20) + elseif blockFmt then + out:u32le(DDPF_FOURCC) + out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f]) + out:fill(0, 20) + else + out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS) + out:u32le(0) + out:u32le(32) + if f == "bgra8" then + out:u32le(0xFF0000) + out:u32le(0xFF00) + out:u32le(0xFF) + else + out:u32le(0xFF) + out:u32le(0xFF00) + out:u32le(0xFF0000) + end + out:u32le(0xFF000000) + end + out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0)) + out:u32le(if cube then 0xFE00 else 0) + out:fill(0, 12) + if dx10 then + out:u32le(DX10_OUT[f]) + out:u32le(3) + out:u32le(if cube then MISC_CUBE else 0) + out:u32le(if cube then layers // 6 else layers) + out:u32le(0) + end +end + +function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f") + if not DX10_OUT[f] then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8" + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + -- surfaces: the frames (array / cube faces) or the image + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and #images % 6 ~= 0 then + return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer") + end + local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6)) + local mips = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + mips += 1 + end + end + local out = Bytes.writer(img.width * img.height * 4 * #images + 200) + writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true) + for _, im in images do + local level = im + for m = 1, mips do + local data, err = surface(level, f, opts) + if not data then + return nil, err + end + out:bytes(data) + if m < mips then + level = Texture.halve(level) + end + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Dds.DXGI = DXGI + +return Dds +end +__FILES["image/exr"] = function() + +-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ +-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and +-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts +-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), +-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any +-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image +-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. +-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear +-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) +-- for colour, round(clamp(a, 0, 1) * 255) for alpha. +-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only +-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / +-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Half = __include("codecs/image/Half") +local Codec = __include("image/exr/Codec") +local Piz = __include("image/exr/Piz") + +-- ------------------------------------------------------------------------------------------------ contract +local Exr = { + name = "exr", + category = "image", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) + part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1) + layer: string?, -- read .R / .G / .B / .A instead of R / G / B / A + mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + compression: ("none" | "zips" | "zip")?, -- default "zip" + pixelType: ("half" | "float")?, -- default "half" + alpha: boolean?, -- write A (default: when some alpha is not 1) + level: number?, -- zlib level 1..9 (default 6) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\118\47\49\1" +local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" } +local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 } +local GAMMA = 1 / 2.2 + +local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Exr.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number } +type Part = { + attrs: { [string]: any }, + channels: { Channel }, + compression: number, + box: { number }, -- data window xMin, yMin, xMax, yMax + display: { number }, + tiled: boolean, + tiles: { number }?, -- xSize, ySize, mode, rounding + name: string?, + type: string?, + chunks: number, + offsets: { number }, +} + +local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number) + local q = p + while q < limit and q - p <= max do + if readu8(b, q) == 0 then + return readstring(b, p, q - p), q + 1 + end + q += 1 + end + return nil, q +end + +local function f32(b: buffer, o: number): number + return readf32(b, o) +end + +-- one attribute value of a known type +local function value(b: buffer, p: number, size: number, typ: string): any + if typ == "chlist" then + local list: { Channel } = {} + local q, stop = p, p + size + while q < stop and readu8(b, q) ~= 0 do + local name, nq = cstr(b, q, stop, 255) + if not name or nq + 16 > stop then + return nil + end + table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) }) + q = nq + 16 + end + return list + elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then + return if size >= 1 then readu8(b, p) else nil + elseif typ == "box2i" then + return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil + elseif typ == "box2f" then + return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil + elseif typ == "v2i" then + return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil + elseif typ == "v2f" then + return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil + elseif typ == "v3f" then + return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil + elseif typ == "float" then + return if size >= 4 then f32(b, p) else nil + elseif typ == "double" then + return if size >= 8 then buffer.readf64(b, p) else nil + elseif typ == "int" then + return if size >= 4 then readi32(b, p) else nil + elseif typ == "string" then + return readstring(b, p, size) + elseif typ == "tiledesc" then + if size < 9 then + return nil + end + local m = readu8(b, p + 8) + return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 } + elseif typ == "chromaticities" then + if size < 32 then + return nil + end + local t = {} + for i = 0, 7 do + t[i + 1] = f32(b, p + i * 4) + end + return t + end + local raw = buffer.create(size) + buffer.copy(raw, 0, b, p, size) + return raw +end + +-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err +local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?) + local attrs: { [string]: any } = {} + local types: { [string]: string } = {} + while true do + if p >= limit then + return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p) + end + if readu8(b, p) == 0 then + attrs._types = types + return attrs, p + 1, nil + end + local name, q = cstr(b, p, limit, 255) + if not name then + return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p) + end + local typ, q2 = cstr(b, q, limit, 255) + if not typ then + return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q) + end + if q2 + 4 > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2) + end + local size = readi32(b, q2) + if size < 0 or q2 + 4 + size > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2) + end + attrs[name] = value(b, q2 + 4, size, typ) + types[name] = typ + p = q2 + 4 + size + end +end + +-- level sizes of a tiled part +local function levelSize(n: number, l: number, roundUp: boolean): number + local d = 2 ^ l + return math.max(1, if roundUp then math.ceil(n / d) else n // d) +end +local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number) + local function count(n: number): number + local c = 1 + while levelSize(n, c - 1, roundUp) > 1 do + c += 1 + end + return c + end + if mode == 0 then + return 1, 1 + elseif mode == 1 then + local c = count(math.max(w, h)) + return c, c + end + return count(w), count(h) +end + +-- chunk count of a part (single-part files: computed) +local function chunkCount(pt: Part): number + local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 + if not pt.tiled then + return (h + LINES[pt.compression] - 1) // LINES[pt.compression] + end + local t = pt.tiles :: { number } + local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1 + local lx, ly = levelCount(w, h, mode, roundUp) + local n = 0 + if mode == 2 then + for y = 0, ly - 1 do + for x = 0, lx - 1 do + n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty) + end + end + else + for l = 0, lx - 1 do + n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty) + end + end + return n +end + +type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number } + +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base) + end + local ver = readu32(b, base + 4) + if ver % 256 ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4) + end + local flags = ver // 256 + local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0 + local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 } + local p = base + 8 + repeat + local attrs, q, herr = header(b, p, limit) + if not attrs then + return nil, herr + end + p = q + local chans = attrs.channels + local box = attrs.dataWindow + if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then + return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p) + end + local typ = attrs.type + local pt: Part = { + attrs = attrs, + channels = chans, + compression = attrs.compression, + box = box, + display = attrs.displayWindow or box, + tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag, + tiles = attrs.tiles, + name = attrs.name, + type = typ, + chunks = 0, + offsets = {}, + } + if pt.tiled and type(pt.tiles) ~= "table" then + return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p) + end + if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad data window", p) + end + if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then + return nil, Err.new(Err.CORRUPT, "bad tile size", p) + end + for _, c in chans do + if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then + return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p) + end + end + table.insert(info.parts, pt) + if #info.parts > 4096 then + return nil, Err.new(Err.LIMIT, "too many parts", p) + end + until not multi or (p < limit and readu8(b, p) == 0) + if multi then + p += 1 + end + -- offset tables + for _, pt in info.parts do + local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0) + if n < 0 or n > 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad chunk count", p) + end + pt.chunks = n + if p + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p) + end + for i = 0, n - 1 do + pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296 + end + p += n * 8 + end + info.dataStart = p - base + return info, nil +end + +-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err +function Exr.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +-- bytes of a sample kind +local SIZE = { [0] = 4, 2, 4 } + +-- number of multiples of s in [a, b] +local function samples(a: number, b: number, s: number): number + return b // s - (a - 1) // s +end + +type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey) + +local function newPlane(pw: number, ph: number): buffer + local px = buffer.create(pw * ph * 16) + for i = 0, pw * ph - 1 do + buffer.writef32(px, i * 16 + 12, 1) + end + return px +end +-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) +local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err? + local p = dp + for y = y0, y1 do + for i, c in part.channels do + if y % c.ys == 0 then + local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs) + local sz = SIZE[c.kind] + if p + nx * sz > buffer.len(data) then + return Err.new(Err.CORRUPT, "block too short") + end + local k = target[i] + if k ~= nil then + local row = y - oy + if c.xs == 1 and c.ys == 1 and k < 4 then + Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16) + else + local tmp = buffer.create(nx * 4) + Codec.samples(data, p, nx, c.kind, tmp, 0, 4) + local first = (x0 + c.xs - 1) // c.xs * c.xs + for s = 0, nx - 1 do + local v = buffer.readf32(tmp, s * 4) + local sx = first + s * c.xs + for yy = row, math.min(row + c.ys - 1, ph - 1) do + for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do + local o = (yy * pw + xx) * 16 + if k == 4 then + buffer.writef32(plane, o, v) + buffer.writef32(plane, o + 4, v) + buffer.writef32(plane, o + 8, v) + else + buffer.writef32(plane, o + k * 4, v) + end + end + end + end + end + end + p += nx * sz + end + end + end + return nil +end + +-- the raw bytes of a block (uncompressed size raw) +local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?) + if size == raw or comp == 0 then + if size < raw then + return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p) + end + return b, p, nil + end + local out, err + if comp == 1 then + out, err = Codec.rle(b, p, size, raw) + elseif comp == 2 or comp == 3 then + out, err = Codec.unzip(b, p, size, raw) + else + local chans: { Piz.Chan } = {} + for i, c in part.channels do + chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys } + end + out, err = Piz.decode(b, p, size, chans, y0, y1, raw) + end + if not out then + return nil, 0, Err.from(err, p) + end + return out, 0, nil +end + +local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number + local n = 0 + for y = y0, y1 do + for _, c in part.channels do + if y % c.ys == 0 then + n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind] + end + end + end + return n +end + +function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, perr = parse(r) + if not info then + return nil, perr + end + local b, base, limit = r.buf, r.base, r.limit + local want = opts and opts.part or 1 + local pt: Part? = nil + local partIndex = 0 + for i, p in info.parts do + if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then + pt, partIndex = p, i + end + end + if not pt then + return nil, Err.new(Err.ARG, "no part " .. tostring(want)) + end + local part = pt :: Part + if info.deep or (part.type and string.find(part.type, "deep")) then + return nil, Err.new(Err.UNSUPPORTED, "deep data") + end + local comp: number = part.compression + if comp > 4 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp))) + end + local box = part.box + local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4] + local w, h = xMax - xMin + 1, yMax - yMin + 1 + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel -> output component + local prefix = if opts and opts.layer then opts.layer .. "." else "" + local target: Target = {} + local hasRgb = false + for i, c in part.channels do + local n = c.name + if string.sub(n, 1, #prefix) == prefix then + local s = string.sub(n, #prefix + 1) + local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil + if k then + target[i] = k + hasRgb = hasRgb or k < 3 + end + end + end + if not hasRgb then + for i, c in part.channels do + if c.name == prefix .. "Y" then + target[i] = 4 + end + end + end + local multi = info.multipart + -- offsets: single-part tables with holes are rebuilt from the chunk sequence + local offsets = part.offsets + local bad = false + for _, o in offsets do + if o < info.dataStart or base + o + 8 > limit then + bad = true + break + end + end + if bad then + -- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part) + offsets = {} + local p = base + info.dataStart + local total = 0 + for _, q in info.parts do + total += q.chunks + end + for _ = 1, total do + local pi = 1 + local at = p + if multi then + if p + 4 > limit then + break + end + pi = readi32(b, p) + 1 + p += 4 + end + local q = info.parts[pi] + if not q then + break + end + local head = if q.tiled then 20 else 8 + if p + head > limit then + break + end + local size = readi32(b, p + head - 4) + if size < 0 then + break + end + if pi == partIndex then + table.insert(offsets, at - base) + end + p += head + size + end + end + + local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local tiles = part.tiles + local roundUp = tiles ~= nil and tiles[4] == 1 + local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 + + local lpb = LINES[comp] + for ci, off in offsets do + local p = base + off + if multi then + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk past the end", p) + end + if readi32(b, p) ~= partIndex - 1 then + return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p) + end + p += 4 + end + if part.tiled then + if p + 20 > limit then + return nil, Err.new(Err.TRUNCATED, "tile header past the end", p) + end + local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16) + p += 20 + local t = tiles :: { number } + local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1 + if level >= 0 then + local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp) + local x0, y0 = tx * t[1], ty * t[2] + if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then + return nil, Err.new(Err.CORRUPT, "tile outside the image", p) + end + if size < 0 or p + size > limit then + return nil, Err.new(Err.TRUNCATED, "tile data past the end", p) + end + local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0) + local plane = planes[level] + if not plane then + plane = newPlane(lw, lh) + planes[level] = plane + end + -- tile coordinates are relative to the level's data window origin + local ax, ay = xMin + x0, yMin + y0 + local raw = rawSize(part, ay, ay + bh - 1, ax, bw) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin) + if berr then + return nil, berr + end + end + else + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p) + end + local y, size = readi32(b, p), readi32(b, p + 4) + p += 8 + if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8) + end + if size < 0 or p + size > limit then + if ci > 1 then + break -- a cut file: keep the lines that decoded (meta.truncated) + end + return nil, Err.new(Err.TRUNCATED, "block data past the end", p) + end + local y1 = math.min(y + lpb - 1, yMax) + local raw = rawSize(part, y, y1, xMin, w) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin) + if berr then + return nil, berr + end + end + end + + local native = opts and opts.native + local function finish(px: buffer, pw: number, ph: number): Types.Image + if native then + local img = Types.Image.new(0, 0, "rgbaf32") + img.width, img.height, img.pixels = pw, ph, px + return img + end + local img = Types.Image.new(pw, ph, "rgba8") + local o = img.pixels + for i = 0, pw * ph - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v + buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5)) + end + end + return img + end + local img = finish(planes[0], w, h) + if wantMips then + local mips = {} + local l = 1 + while planes[l] do + mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp)) + l += 1 + end + if #mips > 0 then + img.meta.mipmaps = mips + end + end + local names, parts = {}, {} + for i, c in part.channels do + names[i] = c.name + end + for i, p in info.parts do + parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") } + end + img.meta.colorSpace = "linear" + img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h } + local dw = part.display + img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 } + local attrs = {} + for k, v in part.attrs do + if k ~= "_types" and (type(v) == "string" or type(v) == "number") then + attrs[k] = v + end + end + img.meta.attributes = attrs + local kinds = {} + for i, c in part.channels do + kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind] + end + img.meta.source = { + format = "exr", + compression = COMPRESSION[comp], + channels = names, + pixelTypes = kinds, + part = partIndex, + parts = parts, + tiled = part.tiled, + lineOrder = part.attrs.lineOrder, + bitDepth = if kinds[1] == "half" then 16 else 32, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer) + w:cstring(name) + w:cstring(typ) + w:u32le(buffer.len(data)) + w:bytes(data) +end + +function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad image size") + end + local compName = opts and opts.compression or "zip" + local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, zips or zip") + end + local ptype = opts and opts.pixelType or "half" + if ptype ~= "half" and ptype ~= "float" then + return nil, Err.new(Err.ARG, "pixelType must be half or float") + end + local level = opts and opts.level or 6 + -- the float values + local n = w * h + local fl = buffer.create(n * 16) + if img.format == "rgbaf32" then + buffer.copy(fl, 0, img.pixels, 0, n * 16) + else + for i = 0, n * 4 - 1 do + local v = buffer.readu8(img.pixels, i) / 255 + buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v) + end + end + local alpha = opts and opts.alpha + if alpha == nil then + alpha = false + for i = 0, n - 1 do + if buffer.readf32(fl, i * 16 + 12) ~= 1 then + alpha = true + break + end + end + end + local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } } + local kind = if ptype == "half" then 1 else 2 + local sz = if kind == 1 then 2 else 4 + local lpb = LINES[comp] + local nblocks = (h + lpb - 1) // lpb + -- header + local hw = Bytes.writer(512) + hw:string(MAGIC) + hw:u32le(2) + local cl = Bytes.writer() + for _, c in chans do + cl:cstring(c[1]) + cl:u32le(kind) + cl:u8(0) + cl:fill(0, 3) + cl:u32le(1) + cl:u32le(1) + end + cl:u8(0) + attr(hw, "channels", "chlist", cl:finish()) + attr(hw, "compression", "compression", buffer.fromstring(string.char(comp))) + local bw = Bytes.writer(16) + bw:u32le(0) + bw:u32le(0) + bw:u32le(w - 1) + bw:u32le(h - 1) + local boxb = bw:finish() + attr(hw, "dataWindow", "box2i", boxb) + attr(hw, "displayWindow", "box2i", boxb) + attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0")) + local fw = Bytes.writer(4) + fw:f32le(1) + attr(hw, "pixelAspectRatio", "float", fw:finish()) + attr(hw, "screenWindowCenter", "v2f", buffer.create(8)) + attr(hw, "screenWindowWidth", "float", fw:finish()) + hw:u8(0) + local tableAt = hw:tell() + hw:fill(0, nblocks * 8) + local from = Half.fromFloat + for bi = 0, nblocks - 1 do + local y0 = bi * lpb + local y1 = math.min(y0 + lpb - 1, h - 1) + local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz) + local o = 0 + for y = y0, y1 do + for _, c in chans do + local k = c[2] + for x = 0, w - 1 do + local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4) + if kind == 1 then + buffer.writeu16(raw, o, from(v)) + else + buffer.writef32(raw, o, v) + end + o += sz + end + end + end + local data = raw + if comp ~= 0 then + local z = Codec.zip(raw, level) + if buffer.len(z) < buffer.len(raw) then + data = z + end + end + local at = hw:tell() + hw:setU32le(tableAt + bi * 8, at) + hw:u32le(y0) + hw:u32le(buffer.len(data)) + hw:bytes(data) + end + return hw:finish(), nil +end + +return Exr +end +__FILES["image/exr/Codec"] = @native function() + + + +-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- +-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), +-- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +local Deflate = __include("codecs/compress/Deflate") +local Half = __include("codecs/image/Half") + +local Codec = {} + +local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 +local HALF = Half.TABLE + +-- undoes the predictor and the interleave of t (n bytes) -> a new buffer +@native local function reconstruct(t: buffer, n: number): buffer + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + prev = (prev + readu8(t, i) - 128) % 256 + writeu8(t, i, prev) + end + local out = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, half - 1 do + writeu8(out, i * 2, readu8(t, i)) + end + for i = 0, n - half - 1 do + writeu8(out, i * 2 + 1, readu8(t, half + i)) + end + return out +end + +-- rle(src, p, n, outSize) -> the raw block | nil, message +@native function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t = buffer.create(outSize) + local o, stop = 0, p + n + while p < stop do + local c = readi8(src, p) + p += 1 + if c < 0 then + local cnt = -c + if p + cnt > stop or o + cnt > outSize then + return nil, "bad RLE run" + end + buffer.copy(t, o, src, p, cnt) + p += cnt + o += cnt + else + if p >= stop or o + c + 1 > outSize then + return nil, "bad RLE run" + end + buffer.fill(t, o, readu8(src, p), c + 1) + p += 1 + o += c + 1 + end + end + if o ~= outSize then + return nil, "RLE data too short" + end + return reconstruct(t, outSize), nil +end + +-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) +@native function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t, err = Deflate.zlib(src, p, n, outSize) + if not t then + return nil, tostring(err) + end + if buffer.len(t) ~= outSize then + return nil, "zlib block has the wrong size" + end + return reconstruct(t, outSize), nil +end + +-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) +@native function Codec.zip(raw: buffer, level: number): buffer + local n = buffer.len(raw) + local t = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, n - 1 do + local v = readu8(raw, i) + if i % 2 == 0 then + writeu8(t, i // 2, v) + else + writeu8(t, half + i // 2, v) + end + end + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + local v = readu8(t, i) + writeu8(t, i, (v - prev + 384) % 256) + prev = v + end + return Deflate.zlibCompress(t, { level = level }) :: buffer +end + +-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into +-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them +@native function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number + if kind == 1 then + for i = 0, count - 1 do + writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)]) + end + return p + count * 2 + elseif kind == 2 then + for i = 0, count - 1 do + writef32(dst, d + i * step, readf32(src, p + i * 4)) + end + else + for i = 0, count - 1 do + writef32(dst, d + i * step, readu32(src, p + i * 4)) + end + end + return p + count * 4 +end + +return Codec +end +__FILES["image/exr/Piz"] = @native function() + + + +-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor +-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman +-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit +-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +local Piz = {} + +local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift + +local USHORT_RANGE, BITMAP_SIZE = 65536, 8192 +local HUF_ENCSIZE = 65537 +local DECBITS = 14 +local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 + +-- ------------------------------------------------------------------------------------------------ Huffman +-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) +@native local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? + local c, lc = 0, 0 + @native local function bits(n: number): number? + while lc < n do + if p >= limit then + return nil + end + c = c * 256 + readu8(src, p) + p += 1 + lc += 8 + end + lc -= n + local v = c // 2 ^ lc + c -= v * 2 ^ lc + return v + end + local i = im + while i <= iM do + local l = bits(6) + if not l then + return nil + end + if l == LONG_ZEROCODE_RUN then + local z = bits(8) + if not z then + return nil + end + z += SHORTEST_LONG_RUN + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + elseif l >= SHORT_ZEROCODE_RUN then + local z = l - SHORT_ZEROCODE_RUN + 2 + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + else + len[i + 1] = l + i += 1 + end + end + return p +end + +-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message +@native local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? + if n == 0 then + return if nRaw == 0 then nil else "empty Huffman data" + end + if n < 20 then + return "truncated Huffman header" + end + local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12) + if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then + return "bad Huffman symbol range" + end + local limit = p + n + local len = table.create(HUF_ENCSIZE, 0) + local q = unpackTable(src, p + 20, limit, im, iM, len) + if not q then + return "bad Huffman table" + end + if q + (nBits + 7) // 8 > limit then + return "truncated Huffman data" + end + -- canonical codes (OpenEXR's order: longest codes get the smallest values) + local count = table.create(59, 0) + for s = im, iM do + local l = len[s + 1] + if l > 58 then + return "bad Huffman code length" + end + count[l + 1] += 1 + end + local start = table.create(59, 0) + local c = 0 + for l = 58, 1, -1 do + local nc = (c + count[l + 1]) // 2 + start[l + 1] = c + c = nc + end + local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid + local long: { [number]: { [number]: number } } = {} + local maxLong = 0 + for s = im, iM do + local l = len[s + 1] + if l > 0 then + local code = start[l + 1] + start[l + 1] = code + 1 + if l <= DECBITS then + local base = code * 2 ^ (DECBITS - l) + local v = (s + 1) * 64 + l + for k = base, base + 2 ^ (DECBITS - l) - 1 do + if k < lshift(1, DECBITS) then + buffer.writeu32(fast, k * 4, v) + end + end + else + if l > 52 then + return "unsupported: Huffman code longer than 52 bits" + end + local t = long[l] + if not t then + t = {} + long[l] = t + end + t[code] = s + maxLong = math.max(maxLong, l) + end + end + end + -- decode MSB-first from a zero-padded copy + local nbytes = (nBits + 7) // 8 + local data = buffer.create(nbytes + 8) + buffer.copy(data, 0, src, q, nbytes) + local bp = 0 + local o = 0 + local rlc = iM + local mask = lshift(1, DECBITS) - 1 + while bp < nBits do + local byte = rshift(bp, 3) + local w = bit32.byteswap(readu32(data, byte)) + local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask) + local e = readu32(fast, peek * 4) + local sym: number, l: number = 0, 0 + if e ~= 0 then + sym = e // 64 - 1 + l = band(e, 63) + else + -- a long code: bit by bit from length 15 + sym = -1 + local code = 0 + for k = 0, maxLong - 1 do + local bitAt = bp + k + code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1) + if k + 1 > DECBITS then + local t = long[k + 1] + local found: number? = if t then t[code] else nil + if found then + sym = found + l = k + 1 + break + end + end + end + if sym < 0 then + return "invalid Huffman code" + end + end + bp += l + if bp > nBits then + return "Huffman code past the end of the data" + end + if sym == rlc then + if bp + 8 > nBits then + return "truncated run length" + end + local b2 = bit32.byteswap(readu32(data, rshift(bp, 3))) + local cs = band(rshift(b2, 24 - band(bp, 7)), 255) + bp += 8 + if o + cs > nRaw then + return "too much Huffman data" + end + if o == 0 then + return "run length at the start" + end + local s = readu16(out, (o - 1) * 2) + for _ = 1, cs do + writeu16(out, o * 2, s) + o += 1 + end + else + if o >= nRaw then + return "too much Huffman data" + end + writeu16(out, o * 2, sym) + o += 1 + end + end + if o ~= nRaw then + return "not enough Huffman data" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ wavelet +-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) +@native local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) + local w14 = mx < 16384 + local n = math.min(nx, ny) + local p = 1 + while p <= n do + p *= 2 + end + p //= 2 + local p2 = p + p //= 2 + @native local function dec(l: number, h: number): (number, number) + if w14 then + local ls = if l >= 32768 then l - 65536 else l + local hs = if h >= 32768 then h - 65536 else h + local ai = ls + hs % 2 + hs // 2 + return ai % 65536, (ai - hs) % 65536 + end + local bb = (l - rshift(h, 1)) % 65536 + return (h + bb - 32768) % 65536, bb + end + while p >= 1 do + local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2 + local py = base + local ey = base + oy * (ny - p2) + while py <= ey do + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local p10 = px + oy1 + local p11 = p10 + ox1 + local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2)) + local a, b = dec(i00, i01) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + local c, d = dec(i10, i11) + writeu16(t, p10 * 2, c) + writeu16(t, p11 * 2, d) + px += ox2 + end + if band(nx, p) ~= 0 then + local p10 = px + oy1 + local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p10 * 2, b) + end + py += oy2 + end + if band(ny, p) ~= 0 then + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + px += ox2 + end + end + p2 = p + p //= 2 + end +end + +-- ------------------------------------------------------------------------------------------------ decode +type Chan = { nx: number, ny: number, size: number, ys: number } + +-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. +-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and +-- ySampling. +@native function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) + local total = 0 + for _, c in chans do + total += c.nx * c.ny * c.size + end + if total * 2 ~= outSize then + return nil, "PIZ block size mismatch" + end + local out = buffer.create(outSize) + if total == 0 then + return out, nil + end + local limit = p + n + if p + 4 > limit then + return nil, "truncated PIZ header" + end + local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2) + p += 4 + if maxNZ >= BITMAP_SIZE then + return nil, "bad PIZ bitmap range" + end + local bitmap = buffer.create(BITMAP_SIZE) + if minNZ <= maxNZ then + local cnt = maxNZ - minNZ + 1 + if p + cnt > limit then + return nil, "truncated PIZ bitmap" + end + buffer.copy(bitmap, minNZ, src, p, cnt) + p += cnt + end + -- reverse LUT + local lut = buffer.create(USHORT_RANGE * 2) + local k = 0 + for i = 0, USHORT_RANGE - 1 do + if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then + writeu16(lut, k * 2, i) + k += 1 + end + end + local maxValue = k - 1 + if p + 4 > limit then + return nil, "truncated PIZ length" + end + local length = readu32(src, p) + p += 4 + if length > limit - p then + return nil, "truncated PIZ data" + end + local tmp = buffer.create(total * 2) + local herr = huffman(src, p, length, tmp, total) + if herr then + return nil, herr + end + local starts = table.create(#chans, 0) + local at = 0 + for i, c in chans do + starts[i] = at + for j = 0, c.size - 1 do + wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue) + end + at += c.nx * c.ny * c.size + end + for i = 0, total - 1 do + writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) + end + -- planes -> scanlines + local o = 0 + local cursor = table.clone(starts) + for y = minY, maxY do + for i, c in chans do + if y % c.ys == 0 then + local cnt = c.nx * c.size + buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2) + cursor[i] += cnt + o += cnt * 2 + end + end + end + return out, nil +end + +return Piz +end +__FILES["image/gif"] = function() + +-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image +-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames +-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / +-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames +-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize +-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with +-- alpha < 128 as the transparent index. +-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" +-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). +-- +-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every +-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the +-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as +-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lzw = __include("codecs/compress/Lzw") +local Quantize = __include("codecs/image/Quantize") +local Types = __include("Types") +local Decode = __include("image/gif/Decode") + +-- ------------------------------------------------------------------------------------------------ contract +local Gif = { + name = "gif", + category = "image", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) + maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28) + maxFrames: number?, -- stop after this many frames (default: all) +} +type EncodeOptions = { + maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed) + method: ("mediancut" | "octree")?, -- default "mediancut" + dither: boolean?, -- Floyd-Steinberg (default false) + loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops) + globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table, + -- each animation frame gets its own local table) +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 +local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } +local DISPOSE_CODE: { [string]: number } = { none = 1, background = 2, previous = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Gif.sniff(r: Bytes.Reader): number + local s = r:peek(6) + return if s == "GIF89a" or s == "GIF87a" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list +local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } }) + local t = buffer.create(1024) + local list: { { number } } = table.create(n) :: { { number } } + for i = 0, 255 do + buffer.writeu32(t, i * 4, 0xFF000000) + end + for i = 0, n - 1 do + local q = p + i * 3 + local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000) + list[i + 1] = { r, g, bl, 255 } + end + return t, list +end + +function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28 + local maxFrames = opts and opts.maxFrames or math.huge + local sig = r:string(6) + local cw, ch = r:u16le(), r:u16le() + local flags, bg, aspect = r:u8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + if sig ~= "GIF89a" and sig ~= "GIF87a" then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + if cw == 0 or ch == 0 then + return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6) + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels)) + end + local b = r.buf + local gct: buffer? = nil + local gpal: { { number } }? = nil + if bit32.band(flags, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(flags, 7) + 1) + if not r:need(n * 3) then + return nil, r.err + end + gct, gpal = colorTable(b, r.pos, n) + r.pos += n * 3 + end + local img = Types.Image.new(cw, ch, "rgba8") + local frames: { Types.Frame } = {} + local comments: { string } = {} + local loops: number? = nil + local total = 0 + -- the pending Graphic Control Extension + local delay, dispose, trans = 0, 0, -1 + local truncated = false + local interlacedAny = false + local localTables = 0 + local minCode = 8 + local limit = r.limit + -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) + local function subBlocks(): (buffer?, number) + local p = r.pos + local n = 0 + while true do + if p >= limit then + return nil, p + end + local len = readu8(b, p) + if len == 0 then + break + end + if p + 1 + len > limit then + -- keep what is there: a truncated last block + n += limit - p - 1 + p = limit + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < limit do + local l = math.min(readu8(b, q), limit - q - 1) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, -1 + end + n += len + p += 1 + len + end + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < p do + local l = readu8(b, q) + buffer.copy(out, o, b, q + 1, l) + o += l + q += 1 + l + end + return out, p + 1 + end + local function skipBlocks(): boolean + local p = r.pos + while p < limit do + local len = readu8(b, p) + if len == 0 then + r.pos = p + 1 + return true + end + p += 1 + len + end + r.pos = limit + return false + end + while true do + if r.pos >= limit then + truncated = true + break + end + local intro = r:u8() + if intro == 0x3B then + break + elseif intro == 0x21 then + local label = r:u8() + if r.err then + truncated = true + break + end + local p = r.pos + if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then + local f = readu8(b, p + 1) + dispose = bit32.band(bit32.rshift(f, 2), 7) + delay = readu8(b, p + 2) + readu8(b, p + 3) * 256 + trans = if bit32.band(f, 1) ~= 0 then readu8(b, p + 4) else -1 + elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then + local id = buffer.readstring(b, p + 1, 11) + if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then + local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256 + loops = if rep == 0 then 0 else rep + 1 -- the stored value repeats: plays = value + 1 + end + elseif label == 0xFE then + local data = subBlocks() + if data then + table.insert(comments, buffer.tostring(data)) + end + end + if not skipBlocks() then + truncated = true + break + end + elseif intro == 0x2C then + local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local f = r:u8() + if r.err then + truncated = true + break + end + if fw * fh > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos) + end + total += fw * fh + if total > maxTotal then + return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos) + end + local pal = gct + if bit32.band(f, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(f, 7) + 1) + if not r:need(n * 3) then + truncated = true + break + end + pal = colorTable(b, r.pos, n) + r.pos += n * 3 + localTables += 1 + end + local interlaced = bit32.band(f, 0x40) ~= 0 + interlacedAny = interlacedAny or interlaced + local mc = r:u8() + if r.err then + truncated = true + break + end + if mc < 1 or mc > 11 then + return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1) + end + minCode = mc + local data, nextPos = subBlocks() + if not data then + truncated = true + break + end + local n = fw * fh + local idx = buffer.create(n) + local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc) + if got < n or nextPos < 0 then + truncated = true -- the missing pixels stay index 0, as most decoders show them + end + local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown) + local t = buffer.create(1024) + if pal then + buffer.copy(t, 0, pal) + else + -- no colour table at all: a grey ramp (what the spec leaves to the decoder) + for i = 0, 255 do + buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000) + end + end + if trans >= 0 then + buffer.writeu32(t, trans * 4, 0) + end + local fimg = Types.Image.new(fw, fh, "rgba8") + Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels) + if #frames == 0 then + Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh) + end + table.insert(frames, { + image = fimg, + delay = delay / 100, + x = fx, + y = fy, + dispose = DISPOSE[dispose] or "none", + blend = if trans >= 0 then "over" else "source", + } :: Types.Frame) + delay, dispose, trans = 0, 0, -1 + if nextPos < 0 then + break + end + r.pos = nextPos + if #frames >= maxFrames then + break + end + else + -- junk between blocks: stop here, keeping what was read + if #frames == 0 then + return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) + end + truncated = true + break + end + end + if #frames == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", r.pos) + end + if #frames > 1 then + img.frames = frames + img.loops = loops or 1 + else + img.loops = loops or 0 + end + img.meta.palette = gpal + img.meta.background = bg + if #comments > 0 then + img.meta.text = { comment = table.concat(comments, "\n") } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "gif", + version = string.sub(sig, 4), + bitDepth = minCode, + colorType = "palette", + frames = #frames, + interlaced = interlacedAny, + localPalettes = localTables, + aspect = aspect, + loopExtension = loops ~= nil, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validImage(i: any): boolean + return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4 +end + +local function hasTransparency(px: buffer, n: number): boolean + for i = 0, n - 1 do + if readu8(px, i * 4 + 3) < 128 then + return true + end + end + return false +end + +-- palette list -> padded table bytes (power of two entries, >= 2) and its size code +local function writeTable(w: Bytes.Writer, pal: { { number } }): number + local bits = 1 + while bit32.lshift(1, bits) < #pal do + bits += 1 + end + for i = 1, bit32.lshift(1, bits) do + local c = pal[i] + if c then + w:u8(c[1]) + w:u8(c[2]) + w:u8(c[3]) + else + w:fill(0, 3) + end + end + return bits +end + +local function tableBits(n: number): number + local bits = 1 + while bit32.lshift(1, bits) < n do + bits += 1 + end + return bits +end + +function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels") + end + local maxColors = opts and opts.maxColors or 256 + if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then + return nil, Err.new(Err.ARG, "maxColors must be 2..256") + end + maxColors = math.floor(maxColors) + local method = opts and opts.method or "mediancut" + if method ~= "mediancut" and method ~= "octree" then + return nil, Err.new(Err.ARG, "method must be mediancut or octree") + end + local dither = opts and opts.dither or false + -- the frames to write: { image, x, y, delay, dispose } + local list: { Types.Frame } = {} + if type(img.frames) == "table" and #(img.frames :: any) > 0 then + for i, f in img.frames :: { Types.Frame } do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position") + end + table.insert(list, f) + end + else + list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" } + end + local animated = #list > 1 + local loops = opts and opts.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then + return nil, Err.new(Err.ARG, "loops must be 0..65536") + end + -- palettes + local shared = (opts and opts.globalPalette) or not animated + local qopts: Quantize.PaletteOptions = { method = method, dither = dither } + local globalPal: { { number } }? = nil + local globalTrans = false + if shared then + -- every frame's pixels together + local npx = 0 + for _, f in list do + npx += f.image.width * f.image.height + end + local all = buffer.create(npx * 4) + local o = 0 + for _, f in list do + local n = f.image.width * f.image.height * 4 + buffer.copy(all, o, f.image.pixels, 0, n) + o += n + end + globalTrans = hasTransparency(all, npx) + local pal = Quantize.palette(all, npx, 1, if globalTrans then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if globalTrans then + table.insert(pal, { 0, 0, 0, 0 }) + end + globalPal = pal + end + local w = Bytes.writer(img.width * img.height + 1024) + w:string("GIF89a") + w:u16le(img.width) + w:u16le(img.height) + if globalPal then + w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1)) + w:u8(0) + w:u8(0) + writeTable(w, globalPal) + else + w:u8(0x70) + w:u8(0) + w:u8(0) + end + if animated and loops ~= 1 then + w:u8(0x21) + w:u8(0xFF) + w:u8(11) + w:string("NETSCAPE2.0") + w:u8(3) + w:u8(1) + w:u16le(if loops == 0 then 0 else loops - 1) + w:u8(0) + end + local text = img.meta and img.meta.text + local comment = text and (text.comment or text.Comment) + if type(comment) == "string" and #comment > 0 then + w:u8(0x21) + w:u8(0xFE) + for i = 1, #comment, 255 do + local part = string.sub(comment, i, i + 254) + w:u8(#part) + w:string(part) + end + w:u8(0) + end + for _, f in list do + local fi = f.image + local fw, fh = fi.width, fi.height + local n = fw * fh + local pal: { { number } } + local tidx: number? = nil + if globalPal then + pal = globalPal + if globalTrans then + tidx = #pal - 1 + end + else + local tr = hasTransparency(fi.pixels, n) + pal = Quantize.palette(fi.pixels, fw, fh, if tr then maxColors - 1 else maxColors, qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if tr then + table.insert(pal, { 0, 0, 0, 0 }) + tidx = #pal - 1 + end + end + local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx }) + -- the Graphic Control Extension: always for animations, else only for transparency + if animated or tidx then + local d = DISPOSE_CODE[f.dispose or "none"] or 1 + w:u8(0x21) + w:u8(0xF9) + w:u8(4) + w:u8(d * 4 + (if tidx then 1 else 0)) + w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535)) + w:u8(tidx or 0) + w:u8(0) + end + w:u8(0x2C) + w:u16le(f.x or 0) + w:u16le(f.y or 0) + w:u16le(fw) + w:u16le(fh) + local bits + if globalPal then + w:u8(0) + bits = tableBits(#globalPal) + else + bits = tableBits(#pal) + w:u8(0x80 + bits - 1) + writeTable(w, pal) + end + local mc = math.max(2, bits) + w:u8(mc) + local codes = Lzw.encode(idx, 0, n, "gif", mc) + local cl = buffer.len(codes) + local p = 0 + while p < cl do + local l = math.min(255, cl - p) + w:u8(l) + w:bytes(codes, p, l) + p += l + end + w:u8(0) + end + w:u8(0x3B) + return w:finish(), nil +end + +return Gif +end +__FILES["image/gif/Decode"] = @native function() + + + +-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to +-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every +-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Decode = {} + +-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from +-- 2, every 2nd from 1) +@native local function interlacedRow(fh: number): { number } + local map = table.create(fh, 0) + local r = 0 + for _, pass in { { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } } do + local y = pass[1] + while y < fh do + map[y + 1] = r + r += 1 + y += pass[2] + end + end + return map +end + +-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the +-- transparent one already alpha 0) +@native function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer) + local rows = if interlaced then interlacedRow(fh) else nil + for y = 0, fh - 1 do + local src = (if rows then rows[y + 1] else y) * fw + local dst = y * fw * 4 + for x = 0, fw - 1 do + writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4)) + end + end +end + +-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) +@native function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + for y = y0, y1 - 1 do + local s = ((y - fy) * fw - fx) * 4 + local d = y * cw * 4 + for x = x0, x1 - 1 do + local v = readu32(frame, s + x * 4) + if v >= 0x01000000 then + writeu32(canvas, d + x * 4, v) + end + end + end +end + +-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) +@native function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + if x1 <= x0 then + return + end + for y = y0, y1 - 1 do + buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4) + end +end + +return Decode +end +__FILES["image/hdr"] = function() + +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. +-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of +-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution +-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. +-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: +-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a +-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). +-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/hdr/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Hdr = { + name = "hdr", + category = "image", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + rle: boolean?, -- new-style RLE scanlines (default true) + exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GAMMA = 1 / 2.2 + +-- ------------------------------------------------------------------------------------------------ sniff +function Hdr.sniff(r: Bytes.Reader): number + local s = r:peek(10) + if s == "#?RADIANCE" then + return 1 + end + if string.sub(s, 1, 6) == "#?RGBE" then + return 1 + end + if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, limit = r.buf, r.limit + local p = r.base + -- header lines up to the first empty one + local function line(): string? + local s = p + while p < limit and buffer.readu8(b, p) ~= 10 do + p += 1 + end + if p >= limit then + return nil + end + local l = buffer.readstring(b, s, p - s) + p += 1 + return l + end + local first = line() + if not first or string.sub(first, 1, 2) ~= "#?" then + return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base) + end + local exposure = 1 + local format = nil + local text: { [string]: string } = {} + while true do + local l = line() + if l == nil then + return nil, Err.new(Err.TRUNCATED, "header ends early", p) + end + l = string.gsub(l, "\r$", "") + if l == "" then + break + end + local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$") + if k == "FORMAT" then + format = v + elseif k == "EXPOSURE" then + local e = tonumber(v) + if e and e > 0 then + exposure *= e + end + elseif k then + text[k] = v :: string + end + end + if format and format ~= "32-bit_rle_rgbe" then + return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format) + end + local res = line() + if not res then + return nil, Err.new(Err.TRUNCATED, "no resolution line", p) + end + local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$") + if not s1 or a1 == a2 or #(n1 :: string) > 9 or #(n2 :: string) > 9 then + return nil, Err.new(Err.CORRUPT, "bad resolution line", p) + end + local outer, inner = tonumber(n1) :: number, tonumber(n2) :: number + local w, h = if a1 == "Y" then inner else outer, if a1 == "Y" then outer else inner + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "zero size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgbaf32") + local px = img.pixels + local row = buffer.create(inner * 4) + local truncated = false + for i = 0, outer - 1 do + local np, err = Codec.readLine(b, p, limit, inner, row) + if not np then + if err == "truncated" then + truncated = true + break + end + return nil, Err.new(Err.CORRUPT, tostring(err), p) + end + p = np + -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first + local base, step + if a1 == "Y" then + local y = if s1 == "-" then i else h - 1 - i + if s2 == "+" then + base, step = y * w * 16, 16 + else + base, step = (y * w + w - 1) * 16, -16 + end + else + local x = if s1 == "+" then i else w - 1 - i + if s2 == "-" then + base, step = x * 16, w * 16 + else + base, step = ((h - 1) * w + x) * 16, -w * 16 + end + end + Codec.toFloat(row, inner, px, base, step) + end + if not (opts and opts.native) then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + for c = 0, 2 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5)) + end + buffer.writeu8(o.pixels, i * 4 + 3, 255) + end + o.meta = img.meta + img = o + end + img.meta.exposure = exposure + img.meta.colorSpace = "linear" + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1 :: string, s2 :: string, a2 :: string) } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgbaf32" then 16 else 4 + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o: any = opts or {} + local px = img.pixels + if bpp == 4 then + -- rgba8 through the inverse of the decoder's display curve + local lut = table.create(256, 0) + for v = 0, 255 do + lut[v + 1] = (v / 255) ^ 2.2 + end + px = buffer.create(w * h * 16) + for i = 0, w * h - 1 do + for c = 0, 2 do + buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1]) + end + buffer.writef32(px, i * 16 + 12, 1) + end + end + local exposure = o.exposure or (img.meta and img.meta.exposure) + local head = "#?RADIANCE\n# written by rosetta\nFORMAT=32-bit_rle_rgbe\n" + if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then + head ..= string.format("EXPOSURE=%.9g\n", exposure) + end + head ..= string.format("\n-Y %d +X %d\n", h, w) + local rle = o.rle ~= false and w >= 8 and w <= 32767 + local out = buffer.create(#head + h * (w * 5 + 8)) + buffer.writestring(out, 0, head) + local op = #head + local row = buffer.create(w * 4) + for y = 0, h - 1 do + Codec.fromFloat(px, y, w, row) + if rle then + op = Codec.writeLine(row, w, out, op) + else + buffer.copy(out, op, row, 0, w * 4) + for x = 0, w - 1 do + -- 1, 1, 1 would read as an old-style run marker + if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then + buffer.writeu8(out, op + x * 4 + 2, 0) + end + end + op += w * 4 + end + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Hdr +end +__FILES["image/hdr/Codec"] = @native function() + + + +-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes +-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE +-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then +-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and +-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 +local frexp = math.frexp + +local Codec = {} + +-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +@native function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?) + if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then + if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then + return nil, "scanline width mismatch" + end + p += 4 + for c = 0, 3 do + local x = 0 + while x < w do + if p >= limit then + return nil, "truncated" + end + local n = readu8(b, p) + p += 1 + if n > 128 then + n -= 128 + if x + n > w or p >= limit then + return nil, if p >= limit then "truncated" else "bad run" + end + local v = readu8(b, p) + p += 1 + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, v) + end + else + if n == 0 or x + n > w then + return nil, "bad count" + end + if p + n > limit then + return nil, "truncated" + end + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, readu8(b, p)) + p += 1 + end + end + x += n + end + end + return p, nil + end + -- flat pixels, with old-style runs + local x = 0 + local shift = 0 + while x < w do + if p + 4 > limit then + return nil, "truncated" + end + local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p += 4 + if r == 1 and g == 1 and bl == 1 then + if x == 0 then + return nil, "run at the start of a scanline" + end + local n = e * 2 ^ shift + if x + n > w then + return nil, "bad run" + end + local q = (x - 1) * 4 + local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3) + for i = x, x + n - 1 do + writeu8(row, i * 4, pr) + writeu8(row, i * 4 + 1, pg) + writeu8(row, i * 4 + 2, pb) + writeu8(row, i * 4 + 3, pe) + end + x += n + shift += 8 + if shift > 24 then + return nil, "bad run" + end + else + writeu8(row, x * 4, r) + writeu8(row, x * 4 + 1, g) + writeu8(row, x * 4 + 2, bl) + writeu8(row, x * 4 + 3, e) + x += 1 + shift = 0 + end + end + return p, nil +end + +-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step +@native function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number) + for i = 0, n - 1 do + local q = i * 4 + local e = readu8(row, q + 3) + local o = base + i * step + if e == 0 then + writef32(out, o, 0) + writef32(out, o + 4, 0) + writef32(out, o + 8, 0) + else + local f = 2 ^ (e - 136) + writef32(out, o, readu8(row, q) * f) + writef32(out, o + 4, readu8(row, q + 1) * f) + writef32(out, o + 8, readu8(row, q + 2) * f) + end + writef32(out, o + 12, 1) + end +end + +-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) +@native function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer) + for x = 0, w - 1 do + local q = (y * w + x) * 16 + local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8) + if r ~= r or r < 0 then + r = 0 + end + if g ~= g or g < 0 then + g = 0 + end + if b ~= b or b < 0 then + b = 0 + end + local v = math.max(r, g, b) + local o = x * 4 + if v < 1e-32 or v == math.huge then + if v == math.huge then + -- clamp infinities to the largest RGBE value + writeu8(row, o, if r == math.huge then 255 else 0) + writeu8(row, o + 1, if g == math.huge then 255 else 0) + writeu8(row, o + 2, if b == math.huge then 255 else 0) + writeu8(row, o + 3, 255) + else + writeu8(row, o, 0) + writeu8(row, o + 1, 0) + writeu8(row, o + 2, 0) + writeu8(row, o + 3, 0) + end + else + local m, e = frexp(v) + if e > 127 then + writeu8(row, o, 255) + writeu8(row, o + 1, 255) + writeu8(row, o + 2, 255) + writeu8(row, o + 3, 255) + else + local s = m * 256 / v + writeu8(row, o, math.min(255, math.floor(r * s))) + writeu8(row, o + 1, math.min(255, math.floor(g * s))) + writeu8(row, o + 2, math.min(255, math.floor(b * s))) + writeu8(row, o + 3, e + 128) + end + end + end +end + +-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 +@native function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number + writeu8(out, o, 2) + writeu8(out, o + 1, 2) + writeu8(out, o + 2, w // 256) + writeu8(out, o + 3, w % 256) + o += 4 + for c = 0, 3 do + local cur = 0 + while cur < w do + -- find the next run of at least 4 + local begRun = cur + local runCount = 0 + local oldRun = 0 + while runCount < 4 and begRun < w do + begRun += runCount + oldRun = runCount + runCount = 1 + if begRun < w then + local v = readu8(row, begRun * 4 + c) + while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do + runCount += 1 + end + end + end + -- a short run just before the long one + if oldRun > 1 and oldRun == begRun - cur then + writeu8(out, o, 128 + oldRun) + writeu8(out, o + 1, readu8(row, cur * 4 + c)) + o += 2 + cur = begRun + end + -- raw bytes up to the run + while cur < begRun do + local n = math.min(begRun - cur, 128) + writeu8(out, o, n) + o += 1 + for i = cur, cur + n - 1 do + writeu8(out, o, readu8(row, i * 4 + c)) + o += 1 + end + cur += n + end + if runCount >= 4 then + writeu8(out, o, 128 + runCount) + writeu8(out, o + 1, readu8(row, begRun * 4 + c)) + o += 2 + cur += runCount + end + end + end + return o +end + +return Codec +end +__FILES["image/icns"] = function() + +-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: +-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha +-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any +-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), +-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists +-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns +-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage +-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / +-- 48 / 128 with masks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") + +-- ------------------------------------------------------------------------------------------------ contract +local Icns = { + name = "icns", + category = "image", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) + maxPixels: number?, -- refuse entries larger than this (default 2^22) +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) + legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } } +local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true } +local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 } +local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } } +local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" } +local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } } +local LAYOUT: Chunks.Layout = { + bigEndian = true, + resize = function(_id: string, declared: number): number? + return math.max(0, declared - 8) + end, +} + +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Icns.sniff(r: Bytes.Reader): number + return Sniff.magic(r, "icns") +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) +local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean + for _, ch in channels do + local i = 0 + while i < count do + if p >= stop then + return false + end + local c = readu8(b, p) + p += 1 + if c >= 128 then + local n = c - 125 + if p >= stop then + return false + end + local v = readu8(b, p) + p += 1 + for _ = 1, math.min(n, count - i) do + buffer.writeu8(out, i * 4 + ch, v) + i += 1 + end + else + local n = c + 1 + if p + n > stop then + return false + end + for k = 0, math.min(n, count - i) - 1 do + buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k)) + end + i += math.min(n, count - i) + p += n + end + end + end + return true +end + +local function isPng(b: buffer, p: number, n: number): boolean + return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n" +end +local function isJp2(b: buffer, p: number, n: number): boolean + return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81") +end + +function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then + return nil, Err.new(Err.CORRUPT, "not an icns file", o) + end + local total = bit32.byteswap(buffer.readu32(b, o + 4)) + local stop = math.min(limit, o + math.max(total, 8)) + local list = Chunks.walk(b, o + 8, stop, LAYOUT) + local decodeImage = opts and opts.decodeImage + local maxPixels = opts and opts.maxPixels or 2 ^ 22 + local masks: { [string]: Chunks.Chunk } = {} + for _, c in list do + if MASKS[c.id] then + masks[c.id] = c + end + end + local frames: { Types.Frame } = {} + local skipped: { string } = {} + local function add(im: Types.Image, typ: string, extra: { [string]: any }?) + local src: { [string]: any } = { format = "icns", type = typ } + if extra then + for k, v in extra do + src[k] = v + end + end + im.meta.source = src :: any + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame) + end + for _, c in list do + local id, p, n = c.id, c.offset, c.avail + if c.truncated then + table.insert(skipped, id .. " (truncated)") + elseif RGB[id] then + local size = RGB[id][1] + local im = Types.Image.new(size, size, "rgba8") + local px = im.pixels + local q = if id == "it32" then p + 4 else p + local count = size * size + local ok + if n == count * 3 then + for i = 0, count - 1 do + for k = 0, 2 do + buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i)) + end + end + ok = true + else + ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count) + end + local m = masks[RGB[id][2]] + for i = 0, count - 1 do + buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255) + end + if ok then + add(im, id, { bitDepth = 24, mask = m ~= nil }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then + local size = ARGB[id] + local im = Types.Image.new(size, size, "rgba8") + if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then + add(im, id, { bitDepth = 32 }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif MONO[id] then + local w, h = MONO[id][1], MONO[id][2] + local bytes = w * h // 8 + if n >= bytes * 2 then + local im = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000) + end + add(im, id, { bitDepth = 1 }) + end + elseif isPng(b, p, n) then + if decodeImage then + local sub = buffer.create(n) + buffer.copy(sub, 0, b, p, n) + local okc, im, ierr = pcall(decodeImage, sub) + if okc and im then + if im.width * im.height <= maxPixels then + add(im :: Types.Image, id, { png = true }) + else + table.insert(skipped, id .. " (over maxPixels)") + end + else + table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")") + end + else + table.insert(skipped, id .. " (PNG: no decodeImage hook)") + end + elseif isJp2(b, p, n) then + table.insert(skipped, id .. " (JPEG 2000)") + elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then + table.insert(skipped, id) + end + end + if #frames == 0 then + if #skipped > 0 then + return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")") + end + return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8) + end + local main = frames[1].image + for _, f in frames do + if f.image.width * f.image.height > main.width * main.height then + main = f.image + end + end + local img = Types.Image.new(0, 0, "rgba8") + img.width, img.height, img.pixels = main.width, main.height, main.pixels + if #frames > 1 then + img.frames = frames + end + if #skipped > 0 then + img.meta.skipped = skipped + end + img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the icns RLE of one channel (count bytes, step 4 from ch) into w +local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number) + local i = 0 + while i < count do + local v = readu8(px, i * 4 + ch) + local run = 1 + while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do + run += 1 + end + if run >= 3 then + w:u8(run + 125) + w:u8(v) + i += run + else + local lit = 0 + while i + lit < count and lit < 128 do + local a = readu8(px, (i + lit) * 4 + ch) + if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + w:u8(lit - 1) + for k = 0, lit - 1 do + w:u8(readu8(px, (i + k) * 4 + ch)) + end + i += lit + end + end +end + +function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local images: { Types.Image } = {} + local seen: { [number]: boolean } = {} + local function take(im: Types.Image): Err.Err? + if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then + return Err.new(Err.ARG, "icons are square rgba8 images") + end + if not seen[im.width] then + seen[im.width] = true + table.insert(images, im) + end + return nil + end + local e = take(img) + if e then + return nil, e + end + if type(img.frames) == "table" then + for _, f in img.frames do + local fe = take(f.image) + if fe then + return nil, fe + end + end + end + table.sort(images, function(a: Types.Image, c: Types.Image): boolean + return a.width < c.width + end) + local encodeImage = opts and opts.encodeImage + local legacy = (opts and opts.legacy) or encodeImage == nil + local body = Bytes.writer() + local function chunk(id: string, data: buffer) + body:string(id) + body:u32be(buffer.len(data) + 8) + body:bytes(data) + end + for _, im in images do + local s = im.width + if legacy and LEGACY[s] then + local types = LEGACY[s] + local w = Bytes.writer() + if s == 128 then + w:u32be(0) + end + for ch = 0, 2 do + rle(w, im.pixels, ch, s * s) + end + chunk(types[1], w:finish()) + local m = buffer.create(s * s) + for i = 0, s * s - 1 do + buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3)) + end + chunk(types[2], m) + elseif encodeImage and PNG_TYPES[s] then + local ok, png, perr = pcall(encodeImage, im, "png") + if not ok or not png then + return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png)) + end + chunk(PNG_TYPES[s], png :: buffer) + else + return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)")) + end + end + local data = body:finish() + local out = Bytes.writer(buffer.len(data) + 8) + out:string("icns") + out:u32be(buffer.len(data) + 8) + out:bytes(data) + return out:finish(), nil +end + +return Icns +end +__FILES["image/ico"] = function() + +-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every +-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or +-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are +-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); +-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png +-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as +-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it +-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. +-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS +-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Dib = __include("image/ico/Dib") + +-- ------------------------------------------------------------------------------------------------ contract +local Ico = { + name = "ico", + category = "image", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) + maxPixels: number?, -- refuse larger entries (default 2^26) +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) + png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists) + cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot) +} + +-- ------------------------------------------------------------------------------------------------ constants +local PNG_SIG = "\137PNG\r\n\26\n" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ico.sniff(r: Bytes.Reader): number + if r:remaining() < 22 then + return 0 + end + local b, o = r.buf, r.pos + local typ = buffer.readu16(b, o + 2) + local count = buffer.readu16(b, o + 4) + if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then + return 0 + end + -- the first entry: reserved byte 0, a size and offset inside the file + local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18) + if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function le16(b: buffer, p: number): number + return buffer.readu16(b, p) +end +local function le32(b: buffer, p: number): number + return buffer.readu32(b, p) +end + +function Ico.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local decodeImage = opts and opts.decodeImage + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 6 then + return nil, Err.new(Err.TRUNCATED, "short header", base) + end + local typ, count = le16(b, base + 2), le16(b, base + 4) + if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then + return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base) + end + if count == 0 then + return nil, Err.new(Err.CORRUPT, "no images", base) + end + if base + 6 + count * 16 > limit then + return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base) + end + local frames: { Types.Frame } = {} + local best: Types.Image? = nil + local bestScore = -1 + local skipped, lastErr = 0, nil :: Err.Err? + for i = 0, count - 1 do + local d = base + 6 + i * 16 + local dw, dh = readu8(b, d), readu8(b, d + 1) + dw = if dw == 0 then 256 else dw + dh = if dh == 0 then 256 else dh + local f1, f2 = le16(b, d + 4), le16(b, d + 6) + local size, off = le32(b, d + 8), le32(b, d + 12) + local p, e = base + off, base + off + size + local img: Types.Image? = nil + local depth = 0 + local isPng = false + if off < 6 or p >= limit then + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d) + else + e = math.min(e, limit) + if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then + isPng = true + depth = 32 + if decodeImage then + local sub = buffer.create(e - p) + buffer.copy(sub, 0, b, p, e - p) + local ok, pimg, perr = pcall(decodeImage, sub) + if ok and pimg and pimg.format == "rgba8" then + img = pimg + else + lastErr = if ok and perr then perr else Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG") + end + else + lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)") + end + elseif e - p >= 40 then + local hs = le32(b, p) + local bw = buffer.readi32(b, p + 4) + local bh = buffer.readi32(b, p + 8) + local bpp = le16(b, p + 14) + local clrUsed = le32(b, p + 32) + local w = if bw > 0 then bw else dw + local h = if bh ~= 0 then math.abs(bh) // 2 else dh + if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then + lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p) + elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p) + elseif w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + else + depth = bpp + local q = p + hs + local palN = 0 + local pal = buffer.create(4) + if bpp <= 8 then + palN = if clrUsed > 0 and clrUsed < 2 ^ bpp then clrUsed else 2 ^ bpp + if q + palN * 4 > e then + palN = 0 + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q) + else + pal = buffer.create(palN * 4) + for k = 0, palN - 1 do + local c = q + k * 4 + buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000) + end + q += palN * 4 + end + end + if bpp > 8 or palN > 0 then + if bpp == 16 and le32(b, p + 16) == 3 then + q += 12 -- BI_BITFIELDS masks (assumed 5-5-5) + end + local out = Types.Image.new(w, h, "rgba8") + local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels) + if ok then + img = out + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q) + end + end + end + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p) + end + end + if img then + local im = img :: Types.Image + im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) } + if typ == 2 then + im.meta.hotspot = { x = f1, y = f2 } + end + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame) + local score = im.width * im.height * 64 + depth + if score > bestScore then + best, bestScore = im, score + end + else + skipped += 1 + end + end + if not best then + return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry") + end + local main = best :: Types.Image + local img = Types.Image.new(main.width, main.height, "rgba8") + buffer.copy(img.pixels, 0, main.pixels) + if #frames > 1 then + img.frames = frames + end + img.meta.source = { format = "ico", type = if typ == 2 then "cur" else "ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png } + img.meta.hotspot = main.meta.hotspot + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ico.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: any = opts or {} + local list: { Types.Image } = {} + if type(img.frames) == "table" and #img.frames > 0 then + for _, f in img.frames do + table.insert(list, f.image) + end + else + list[1] = img + end + local cursor = o.cursor + if cursor == nil then + cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil + end + local blobs: { buffer } = {} + for i, im in list do + if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image") + end + local w, h = im.width, im.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side") + end + local png = nil + if o.encodeImage and (o.png or w == 256 or h == 256) then + local ok, res, err = pcall(o.encodeImage, im, "png") + if not ok or not res then + return nil, if ok and err then err else Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed") + end + png = res + elseif o.png then + return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)") + end + if png then + blobs[i] = png + else + local maskStride = ((w + 31) // 32) * 4 + local n = 40 + w * h * 4 + maskStride * h + local d = buffer.create(n) + buffer.writeu32(d, 0, 40) + buffer.writei32(d, 4, w) + buffer.writei32(d, 8, h * 2) + buffer.writeu16(d, 12, 1) + buffer.writeu16(d, 14, 32) + buffer.writeu32(d, 20, w * h * 4 + maskStride * h) + Dib.encode(im.pixels, w, h, d, 40) + blobs[i] = d + end + end + local total = 6 + #list * 16 + for _, bl in blobs do + total += buffer.len(bl) + end + local out = buffer.create(total) + buffer.writeu16(out, 2, if cursor then 2 else 1) + buffer.writeu16(out, 4, #list) + local off = 6 + #list * 16 + for i, im in list do + local d = 6 + (i - 1) * 16 + buffer.writeu8(out, d, im.width % 256) + buffer.writeu8(out, d + 1, im.height % 256) + if cursor then + local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 } + buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535)) + buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535)) + else + buffer.writeu16(out, d + 4, 1) + buffer.writeu16(out, d + 6, 32) + end + buffer.writeu32(out, d + 8, buffer.len(blobs[i])) + buffer.writeu32(out, d + 12, off) + buffer.copy(out, off, blobs[i]) + off += buffer.len(blobs[i]) + end + return out, nil +end + +return Ico +end +__FILES["image/ico/Dib"] = @native function() + + + +-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from +-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit +-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha +-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are +-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +local Pixels = __include("codecs/image/Pixels") + +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Dib = {} + +-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +@native function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?) + local stride = ((w * bpp + 31) // 32) * 4 + local maskStride = ((w + 31) // 32) * 4 + if p + stride * h > e then + return false, "colour bitmap runs past the entry" + end + local hasMask = p + stride * h + maskStride * h <= e + local anyAlpha = false + if bpp == 32 then + anyAlpha = Pixels.bgra32(b, p, stride, out, w, h, false) ~= 0 + elseif bpp == 24 then + Pixels.bgr24(b, p, stride, out, w, h, false) + elseif bpp == 16 then + Pixels.rgb555(b, p, stride, out, w, h, false) + else + -- palette indexes past palN read as opaque black + local full = buffer.create(1024) + for i = 0, 255 do + writeu32(full, i * 4, if i < palN then readu32(pal, i * 4) else 0xFF000000) + end + Pixels.indexed(b, p, stride, bpp, out, w, h, false, full) + end + if bpp == 32 and anyAlpha then + return true, nil + end + if hasMask then + local mp = p + stride * h + for y = 0, h - 1 do + local row = mp + (h - 1 - y) * maskStride + for x = 0, w - 1 do + local o = (y * w + x) * 4 + local px = readu32(out, o) % 16777216 + if (readu8(b, row + x // 8) // 2 ^ (7 - x % 8)) % 2 == 1 then + writeu32(out, o, px) -- transparent + else + writeu32(out, o, px + 0xFF000000) + end + end + end + elseif bpp == 32 then + -- no alpha and no mask: opaque + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000) + end + end + return true, nil +end + +-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). +-- out needs room for w * h * 4 + maskStride * h bytes. +@native function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 4 + buffer.writeu8(out, o, readu8(px, q + 2)) + buffer.writeu8(out, o + 1, readu8(px, q + 1)) + buffer.writeu8(out, o + 2, readu8(px, q)) + buffer.writeu8(out, o + 3, readu8(px, q + 3)) + o += 4 + end + end + local maskStride = ((w + 31) // 32) * 4 + for y = h - 1, 0, -1 do + local acc, nb, written = 0, 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu8(px, (y * w + x) * 4 + 3) == 0 then 1 else 0) + nb += 1 + if nb == 8 then + buffer.writeu8(out, o + written, acc) + written += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb)) + written += 1 + end + buffer.fill(out, o + written, 0, maskStride - written) + o += maskStride + end + return o +end + +return Dib +end +__FILES["image/ilbm"] = function() + +-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks +-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a +-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), +-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or +-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH +-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else +-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer +-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local PackBits = __include("codecs/compress/PackBits") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Ilbm = { + name = "ilbm", + category = "image", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + compress: boolean?, -- ByteRun1 (default true) +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ilbm.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local t = r:peek(4, 8) + return if t == "ILBM" or t == "PBM " then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o) + end + local form = buffer.readstring(b, o + 8, 4) + if form ~= "ILBM" and form ~= "PBM " then + return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8) + end + local chunky = form == "PBM " + local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF) + local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY") + if not bmhd or bmhd.avail < 20 then + return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12) + end + if not body then + return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12) + end + local q = bmhd.offset + local w, h = be16(b, q), be16(b, q + 2) + local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10) + local trans = be16(b, q + 12) + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "bad size", q) + end + if comp > 1 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10) + end + if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then + return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local camg = 0 + local c = Chunks.find(list, "CAMG") + if c and c.avail >= 4 then + camg = bit32.byteswap(buffer.readu32(b, c.offset)) + end + local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) + local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham + -- palette + local pal = buffer.create(1024) + local ncol = 0 + if cmap then + ncol = math.min(256, cmap.avail // 3) + local low = true + for i = 0, ncol * 3 - 1 do + low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0 + end + local adjust = low and opts and opts.adjustColors + for i = 0, ncol - 1 do + local function ch(k: number): number + local v = readu8(b, cmap.offset + i * 3 + k) + return if adjust then v + bit32.rshift(v, 4) else v + end + buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000) + end + end + if ncol == 0 and planes <= 8 then + local n = bit32.lshift(1, planes) + for i = 0, n - 1 do + local g = (i * 255) // math.max(1, n - 1) + buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000) + end + ncol = n + end + if ehb then + for i = 0, 31 do + local v = buffer.readu32(pal, i * 4) + local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255) + buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) + end + end + -- the body, decompressed + local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2 + local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h + local raw = buffer.create(total) + local truncated + if comp == 1 then + local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total) + truncated = written < total + else + local n = math.min(total, body.avail) + buffer.copy(raw, 0, b, body.offset, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if chunky then + Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal) + if masking == 2 then + for i = 0, w * h - 1 do + local y, x = i // w, i % w + if readu8(raw, y * rowBytes + x) == trans then + buffer.writeu32(px, i * 4, 0) + end + end + end + else + local stride = rowBytes * (planes + (if masking == 1 then 1 else 0)) + local deep = planes >= 24 + local bits = planes - 2 + for y = 0, h - 1 do + local row = y * stride + local pr: number, pg: number, pb: number = 0, 0, 0 + if ham then + local v = buffer.readu32(pal, 0) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + end + for x = 0, w - 1 do + local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7) + local idx = 0 + for k = 0, planes - 1 do + idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k + end + local out: number + if deep then + local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255 + out = bit32.band(idx, 0xFFFFFF) + a * 16777216 + elseif ham then + local ctl = bit32.rshift(idx, bits) + local val = bit32.band(idx, bit32.lshift(1, bits) - 1) + local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4) + if ctl == 0 then + local v = buffer.readu32(pal, val * 4) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + elseif ctl == 1 then + pb = v8 + elseif ctl == 2 then + pr = v8 + else + pg = v8 + end + out = pr + pg * 256 + pb * 65536 + 0xFF000000 + else + out = buffer.readu32(pal, bit32.band(idx, 255) * 4) + if masking == 2 and idx == trans then + out = 0 + end + end + if masking == 1 then + local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1) + if m == 0 then + out = 0 + end + end + buffer.writeu32(px, (y * w + x) * 4, out) + end + end + end + if ncol > 0 and planes <= 8 and not ham then + local plist: { { number } } = {} + for i = 0, (if ehb then 64 else ncol) - 1 do + local v = buffer.readu32(pal, i * 4) + plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = plist + end + local text: { [string]: string } = {} + for _, ch in list do + if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then + local s = buffer.readstring(b, ch.offset, ch.avail) + local key = string.gsub(ch.id, "[^%w]", "") + text[string.lower(key)] = (string.gsub(s, "%z+$", "")) + end + end + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ilbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 + local planes = if usePal then 1 elseif alpha then 32 else 24 + if usePal then + while bit32.lshift(1, planes) < #cols do + planes += 1 + end + end + local compress = not (opts and opts.compress == false) + local index: { [number]: number } = {} + for i, cv in cols do + index[cv] = i - 1 + end + local rowBytes = ((w + 15) // 16) * 2 + local body = Bytes.writer(rowBytes * planes * h) + local row = buffer.create(rowBytes) + for y = 0, h - 1 do + for k = 0, planes - 1 do + buffer.fill(row, 0, 0, rowBytes) + for x = 0, w - 1 do + local v = buffer.readu32(px, (y * w + x) * 4) + local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v + if bit32.band(bit32.rshift(idx, k), 1) == 1 then + local at = bit32.rshift(x, 3) + buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7)))) + end + end + if compress then + body:bytes(PackBits.encode(row, 0, rowBytes)) + else + body:bytes(row) + end + end + end + local bodyData = body:finish() + local out = Bytes.writer(buffer.len(bodyData) + 900) + out:string("FORM") + out:u32be(0) + out:string("ILBM") + out:string("BMHD") + out:u32be(20) + out:u16be(w) + out:u16be(h) + out:u16be(0) + out:u16be(0) + out:u8(planes) + out:u8(0) + out:u8(if compress then 1 else 0) + out:u8(0) + out:u16be(0) + out:u8(1) + out:u8(1) + out:u16be(w) + out:u16be(h) + if usePal then + local n = bit32.lshift(1, planes) + out:string("CMAP") + out:u32be(n * 3) + for i = 1, n do + local cv = cols[i] or 0 + out:u8(bit32.band(cv, 255)) + out:u8(bit32.band(bit32.rshift(cv, 8), 255)) + out:u8(bit32.rshift(cv, 16)) + end + if (n * 3) % 2 == 1 then + out:u8(0) + end + end + out:string("BODY") + out:u32be(buffer.len(bodyData)) + out:bytes(bodyData) + if buffer.len(bodyData) % 2 == 1 then + out:u8(0) + end + local res = out:finish() + buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8)) + return res, nil +end + +return Ilbm +end +__FILES["image/jpeg"] = function() + +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG +-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical +-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the +-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi +-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images +-- (coded 4:2:0 from the planes as they are). +-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit +-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt +-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's +-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt +-- scans decode as far as they go (meta.truncated = true). +-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or +-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta; +-- byte-identical to cjpeg for the same settings. +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit +-- or CMYK encoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("codecs/image/Jpeg") + +-- ------------------------------------------------------------------------------------------------ contract +local Jpeg = { + name = "jpeg", + category = "image", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only) + orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only) + native: boolean?, -- grey files decode to gray8 (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables + subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420") + progressive: boolean?, -- default false + optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises) + gray: boolean?, -- a one-component file (default: true for gray8 images) + restart: number?, -- restart interval in MCUs (default 0 = none) + jfif: boolean?, -- write the JFIF APP0 header (default true) + meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true) +} + +type Info = Codec.Info + +-- ------------------------------------------------------------------------------------------------ sniff +function Jpeg.sniff(r: Bytes.Reader): number + local s = r:peek(3) + return if s == "\255\216\255" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- info(r) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?) + return Codec.info(r.buf, r.base, r.limit - r.base) +end + +function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o = opts or {} :: DecodeOptions + -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + return Codec.decode(r.buf, r.base, r.limit - r.base, { + scale = o.scale, + orient = o.orient, + native = o.native, + maxPixels = o.maxPixels, + fields = false, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the APP1 / APP2 / COM segments and the JFIF density from img.meta +local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?) + local segments = {} + if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then + local d = buffer.create(buffer.len(meta.exif) + 6) + buffer.writestring(d, 0, "Exif\0\0") + buffer.copy(d, 6, meta.exif) + table.insert(segments, { marker = 0xE1, data = d }) + end + if type(meta.icc) == "buffer" then + local icc = meta.icc :: buffer + local n = buffer.len(icc) + local chunk = 65519 + local count = math.max(1, math.ceil(n / chunk)) + if count <= 255 then + for i = 1, count do + local a = (i - 1) * chunk + local l = math.min(chunk, n - a) + local d = buffer.create(l + 14) + buffer.writestring(d, 0, "ICC_PROFILE\0") + buffer.writeu8(d, 12, i) + buffer.writeu8(d, 13, count) + buffer.copy(d, 14, icc, a, l) + table.insert(segments, { marker = 0xE2, data = d }) + end + end + end + local text = meta.text + if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then + table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) }) + end + local density = nil + if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then + density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) } + end + return segments, density +end + +function Jpeg.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o: any = opts or {} + local segments, density = {}, nil + if o.meta ~= false then + segments, density = metaSegments(img.meta or {}) + elseif type(img.meta) == "table" then + local _ + _, density = metaSegments({ dpi = img.meta.dpi }) + end + return Codec.encode(img, { + quality = o.quality, + subsampling = o.subsampling, + progressive = o.progressive, + optimize = o.optimize, + gray = o.gray, + restart = o.restart, + jfif = o.jfif, + density = density, + segments = segments, + }) +end + +return Jpeg +end +__FILES["image/ktx"] = function() + +-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL +-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the +-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every +-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip +-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are +-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is +-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. +-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 +-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, +-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and +-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Ktx = { + name = "ktx", + category = "image", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8) + mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) + surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) + maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) +} +type EncodeOptions = { + pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) + srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") + mips: boolean?, -- a full mip chain (box filter; default false) + cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") + zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none) + keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ID1 = "\171KTX 11\187\r\n\26\n" +local ID2 = "\171KTX 20\187\r\n\26\n" + +-- VkFormat -> texture format name +local VK: { [number]: string } = { + [2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1", + [9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8", + [16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8", + [23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8", + [30] = "bgr8", [36] = "bgr8", + [37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8", + [44] = "bgra8", [50] = "bgra8", + [58] = "bgr10a2", [64] = "rgb10a2", + [70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f", + [77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f", + [84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f", + [91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f", + [98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f", + [104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f", + [122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f", + [131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3", + [139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7", + [147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba", + [153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s", +} +local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true } +local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black +-- OpenGL compressed internal formats +local GL_COMPRESSED: { [number]: string } = { + [0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3", + [0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3", + [0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s", + [0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h", + [0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1", + [0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s", +} +local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true } +local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true } +-- glFormat -> channel order; glType -> bit size, Texel suffix +local GL_ORDER: { [number]: string } = { + [0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra", + [0x1909] = "l", [0x190A] = "la", [0x1906] = "a", + [0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats +} +local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true } +local GL_PACKED: { [number]: string } = { + [0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5", +} +local GL_TYPES: { [number]: { any } } = { + [0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" }, + [0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" }, +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } + +local readu32, readstring = buffer.readu32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Ktx.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1)) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Info = { + version: number, -- 1 or 2 + width: number, + height: number, + depth: number, -- 1 for 2D + layers: number, + faces: number, + levels: number, + format: string?, -- the texture format name (nil when unsupported: see unsupported) + unsupported: string?, + srgb: boolean, + opaque: boolean, -- BC1 RGB + vkFormat: number?, + glInternalFormat: number?, + supercompression: number?, + keyValue: { [string]: string }, + bigEndian: boolean?, + typeSize: number, + dataOffset: number, -- KTX1: the first imageSize field (relative to the file) + levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2 +} + +local function u64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4 +local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string } + local kv: { [string]: string } = {} + while p + 4 <= stop do + local n = readu32(b, p) + if be then + n = bit32.byteswap(n) + end + p += 4 + if n > stop - p then + break + end + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + if z then + local v = string.sub(s, z + 1) + if string.sub(v, -1) == "\0" then + v = string.sub(v, 1, -2) + end + kv[string.sub(s, 1, z - 1)] = v + end + p += n + (3 - (n + 3) % 4) + end + return kv +end + +local function info1(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 64 then + return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o) + end + local e = readu32(b, o + 12) + local be = e == 0x01020304 + if not be and e ~= 0x04030201 then + return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12) + end + local function f(i: number): number + local v = readu32(b, o + 16 + i * 4) + return if be then bit32.byteswap(v) else v + end + local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3) + local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16) + end + if 64 + kvBytes > n then + return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64) + end + local info: Info = { + version = 1, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, arr), + faces = faces, + levels = math.max(1, levels), + srgb = GL_SRGB[internal] == true, + opaque = GL_OPAQUE[internal] == true, + glInternalFormat = internal, + keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be), + bigEndian = be, + typeSize = typeSize, + dataOffset = 64 + kvBytes, + } + if glType == 0 then + info.format = GL_COMPRESSED[internal] + if not info.format then + info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal) + end + else + local name = GL_PACKED[glType] + if not name then + local order = GL_ORDER[glFormat] + local int = GL_INTEGER[glFormat] == true + -- glType -> component bits, Texel suffix (normalized / integer) + local t = GL_TYPES[glType] + local size: number? = t and t[1] + local suffix: string = if t then (if int then t[3] else t[2]) else "" + if order and size then + name = order .. tostring(size) .. suffix + end + end + if name and Texel.FORMATS[name] then + info.format = name + else + info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType) + end + end + return info, nil +end + +local function info2(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 80 then + return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o) + end + local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16) + local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28) + local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20) + end + local nl = math.max(1, levels) + if 80 + nl * 24 > n then + return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80) + end + local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60) + local info: Info = { + version = 2, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, layers), + faces = faces, + levels = nl, + srgb = VK_SRGB[vk] == true, + opaque = VK_OPAQUE[vk] == true, + vkFormat = vk, + supercompression = scheme, + keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {}, + typeSize = typeSize, + dataOffset = 0, + levelIndex = {}, + } + for i = 0, nl - 1 do + local q = o + 80 + i * 24 + table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) }) + end + -- the colour model of the DFD tells Basis Universal apart + local model = -1 + if dfdLen >= 16 and dfdOff + dfdLen <= n then + model = buffer.readu8(b, o + dfdOff + 12) + if buffer.readu8(b, o + dfdOff + 14) == 2 then + info.srgb = true + end + end + if scheme == 1 or model == 163 then + info.unsupported = "Basis Universal ETC1S / BasisLZ" + elseif model == 166 then + info.unsupported = "Basis Universal UASTC" + elseif scheme > 3 then + info.unsupported = "supercompression scheme " .. scheme + elseif vk == 0 then + info.unsupported = "VK_FORMAT_UNDEFINED" + else + info.format = VK[vk] + if not info.format then + info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "") + end + end + return info, nil +end + +-- info(r) -> Info | nil, Err (the headers only) +function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) + local id = r:peek(12) + if id == ID2 then + return info2(r) + elseif id == ID1 then + return info1(r) + end + return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) +end + +-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image +local function swapped(b: buffer, p: number, n: number, size: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, p, n) + for i = 0, n - size, size do + if size == 2 then + buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16)) + else + buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i))) + end + end + return out +end + +-- flips the rows of a decoded surface (KTXorientation T=u) +local function flip(img: Types.Image) + local row = img.width * (Types.BPP[img.format] or 4) + local px = img.pixels + local tmp = buffer.create(row) + for y = 0, img.height // 2 - 1 do + local a, z = y * row, (img.height - 1 - y) * row + buffer.copy(tmp, 0, px, a, row) + buffer.copy(px, a, px, z, row) + buffer.copy(px, z, tmp, 0, row) + end +end + +function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Ktx.info(r) + if not info then + return nil, ierr + end + local fmt = info.format + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format") + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base, limit = r.buf, r.base, r.limit + local bw, bh, bbytes = Texture.block(fmt) + local blockFmt = bw == 4 + local orient = info.keyValue.KTXorientation or "" + local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u") + local list: { Texture.Surface } = {} + local pixels = 0 + local count = info.layers * info.faces + local p = base + info.dataOffset + local w, h, d = info.width, info.height, info.depth + for level = 0, info.levels - 1 do + local want = level == 0 or wantMips + -- the level's data: buf, offset, the image stride and row pitch + local lb, lp = b, 0 + local rowPitch: number? = nil + local imgSize = Texture.size(fmt, w, h) :: number + local stride = imgSize + if info.version == 1 then + if p + 4 > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "missing level 0", p) + end + break + end + local declared = readu32(b, p) + if info.bigEndian then + declared = bit32.byteswap(declared) + end + p += 4 + if not blockFmt then + local tight = (bbytes :: number) * w + rowPitch = tight + (3 - (tight + 3) % 4) + imgSize = (rowPitch :: number) * h + end + stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding + local total = stride * count * d + if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then + return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4) + end + if p + total > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p) + end + break + end + lp = p + p += total + p += 3 - (total + 3) % 4 + if info.bigEndian and info.typeSize > 1 and want then + lb, lp = swapped(b, lp, total, info.typeSize), 0 + end + else + local li = (info.levelIndex :: any)[level + 1] + local off, len = base + li.offset, li.length + if off + len > limit or li.offset < 80 then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off) + end + break + end + local expect = imgSize * count * d + if want then + local scheme = info.supercompression + if scheme == 2 or scheme == 3 then + if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24) + end + local out, zerr + if scheme == 2 then + out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed }) + else + out, zerr = Deflate.zlib(b, off, len, li.uncompressed) + end + if not out then + return nil, Err.wrap(zerr) + end + lb, lp = out, 0 + else + lb, lp = b, off + end + if lp + expect > buffer.len(lb) then + return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off) + end + end + end + if want then + for layer = 0, count - 1 do + for slice = 0, d - 1 do + if level == 0 and not wantAll and (layer > 0 or slice > 0) then + continue + end + if level > 0 and (layer > 0 or slice > 0) then + continue + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local at = lp + (layer * d + slice) * stride + local px, pf + if rowPitch then + px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch) + else + px, pf = Texture.decode(fmt, lb, at, w, h, native) + end + if not px then + return nil, Err.from(pf, at) + end + local im = Texture.image(px, pf, w, h) + if info.opaque then + for i = 0, w * h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + end + if up then + flip(im) + end + table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im }) + end + end + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d" + local img = Texture.assemble(list, layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no image data") + end + if info.faces == 6 then + img.meta.faces = table.clone(FACES) + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.keyValue = info.keyValue + img.meta.source = { + format = "ktx", + version = info.version, + pixelFormat = fmt, + vkFormat = info.vkFormat, + glInternalFormat = info.glInternalFormat, + supercompression = info.supercompression, + mips = info.levels, + layers = info.layers, + depth = info.depth, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- format -> VkFormat, bytes per texel, component bytes, kind +local OUT: { [string]: { number } } = { + rgba8 = { 37, 4, 1 }, + rgba16 = { 91, 8, 2 }, + rgba16f = { 97, 8, 2 }, + rgba32f = { 109, 16, 4 }, +} + +-- the DFD: one basic descriptor block with four samples (R G B A) +local function dfd(f: string, srgb: boolean): buffer + local spec = OUT[f] + local texel, comp = spec[2], spec[3] + local float = f == "rgba16f" or f == "rgba32f" + local w = Bytes.writer(92) + local blockSize = 24 + 16 * 4 + w:u32le(4 + blockSize) + w:u32le(0) -- vendor 0, descriptor type 0 + w:u32le(2 + blockSize * 65536) -- version 2, block size + w:u8(1) -- colour model RGBSDA + w:u8(1) -- primaries BT.709 + w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear + w:u8(0) -- straight alpha + w:u32le(0) -- texel block 1 x 1 x 1 x 1 + w:u32le(texel) -- bytesPlane0 + w:u32le(0) + for c = 0, 3 do + local channel = if c == 3 then 15 else c + local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0) + w:u16le(c * comp * 8) + w:u8(comp * 8 - 1) + w:u8(channel + qual) + w:u32le(0) -- sample position + if float then + w:u32le(0xBF800000) + w:u32le(0x3F800000) + else + w:u32le(0) + w:u32le(if comp == 1 then 255 else 65535) + end + end + return w:finish() +end + +function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf) + local spec = OUT[f] + if not spec then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb")) + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and (#images % 6 ~= 0 or img.width ~= img.height) then + return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer") + end + local faces = if cube then 6 else 1 + local layers = #images // faces + local levels = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + levels += 1 + end + end + local zl = opts and opts.zlib + if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then + return nil, Err.new(Err.ARG, "zlib level must be 1..9") + end + -- level data: the images of every layer / face per level + local levelData: { buffer } = {} + local raw: { number } = {} + local cur = table.clone(images) + for lv = 1, levels do + local w = Bytes.writer() + for i, im in cur do + local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels + w:bytes(data, 0, im.width * im.height * spec[2]) + if lv < levels then + cur[i] = Texture.halve(im) + end + end + local lb = w:finish() + raw[lv] = buffer.len(lb) + if zl then + lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer + end + levelData[lv] = lb + end + -- key / value data + local kvw = Bytes.writer() + local pairs_: { { string } } = { { "KTXwriter", "rosetta" } } + if opts and opts.keyValue then + for k, v in opts.keyValue do + if k ~= "KTXwriter" then + table.insert(pairs_, { k, v }) + end + end + end + table.sort(pairs_, function(a: { string }, c: { string }): boolean + return a[1] < c[1] + end) + for _, kv in pairs_ do + local n = #kv[1] + 1 + #kv[2] + 1 + kvw:u32le(n) + kvw:string(kv[1]) + kvw:u8(0) + kvw:string(kv[2]) + kvw:u8(0) + kvw:fill(0, 3 - (n + 3) % 4) + end + local kvd = kvw:finish() + local d = dfd(f, srgb == true) + local dfdOff = 80 + levels * 24 + local kvOff = dfdOff + buffer.len(d) + local dataStart = kvOff + buffer.len(kvd) + local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4) + -- smallest level first + local offsets: { number } = {} + local p = dataStart + for lv = levels, 1, -1 do + p += (align - p % align) % align + offsets[lv] = p + p += buffer.len(levelData[lv]) + end + local out = Bytes.writer(p) + out:string(ID2) + out:u32le(if f == "rgba8" and srgb then 43 else spec[1]) + out:u32le(spec[3]) + out:u32le(img.width) + out:u32le(img.height) + out:u32le(0) + out:u32le(if layers > 1 then layers else 0) + out:u32le(faces) + out:u32le(levels) + out:u32le(if zl then 3 else 0) + out:u32le(dfdOff) + out:u32le(buffer.len(d)) + out:u32le(kvOff) + out:u32le(buffer.len(kvd)) + out:u64le(0) + out:u64le(0) + for lv = 1, levels do + out:u64le(offsets[lv]) + out:u64le(buffer.len(levelData[lv])) + out:u64le(raw[lv]) + end + out:bytes(d) + out:bytes(kvd) + for lv = levels, 1, -1 do + out:fill(0, offsets[lv] - out:tell()) + out:bytes(levelData[lv]) + end + return out:finish(), nil +end + +return Ktx +end +__FILES["image/pcx"] = function() + +-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit +-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the +-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross +-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as +-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcx = { + name = "pcx", + category = "image", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcx.sniff(r: Bytes.Reader): number + if r:size() < 128 then + return 0 + end + local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3) + if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then + return 0 + end + return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 128 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if readu8(b, o) ~= 10 then + return nil, Err.new(Err.CORRUPT, "not a PCX file", o) + end + local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) + local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10) + local planes, bpl = readu8(b, o + 65), readu16(b, o + 66) + local w, h = x1 - x0 + 1, y1 - y0 + 1 + if x1 < x0 or y1 < y0 then + return nil, Err.new(Err.CORRUPT, "bad window", o + 4) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local kind + if bpp == 8 and planes == 1 then + kind = "pal8" + elseif bpp == 8 and (planes == 3 or planes == 4) then + kind = "rgb" + elseif bpp == 1 and planes >= 1 and planes <= 4 then + kind = "planar" + elseif (bpp == 2 or bpp == 4) and planes == 1 then + kind = "packed" + else + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3) + end + if bpl * 8 < w * bpp then + return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66) + end + -- the scan lines (planes after each other per line), RLE across lines + local total = bpl * planes * h + local raw = buffer.create(total) + local p, q = o + 128, 0 + local truncated = false + if enc == 1 then + while q < total do + if p >= limit then + truncated = true + break + end + local c = readu8(b, p) + p += 1 + if c >= 0xC0 then + if p >= limit then + truncated = true + break + end + local n = math.min(c - 0xC0, total - q) + buffer.fill(raw, q, readu8(b, p), n) + p += 1 + q += n + else + buffer.writeu8(raw, q, c) + q += 1 + end + end + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + p += n + truncated = n < total + end + -- palettes + local pal = buffer.create(1024) + local function setPal(i: number, rr: number, gg: number, bb: number) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + if kind == "pal8" then + local at = limit - 769 + if at >= p and readu8(b, at) == 12 then + for i = 0, 255 do + setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3)) + end + else + for i = 0, 255 do + setPal(i, i, i, i) + end + end + elseif kind == "planar" and planes == 1 then + setPal(0, 0, 0, 0) + setPal(1, 255, 255, 255) + else + for i = 0, 15 do + setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3)) + end + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if kind == "pal8" or kind == "packed" then + Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal) + elseif kind == "planar" then + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local idx = 0 + for pl = 0, planes - 1 do + local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3)) + idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl) + end + buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4)) + end + end + else + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local d = (y * w + x) * 4 + buffer.writeu8(px, d, readu8(raw, row + x)) + buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x)) + buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x)) + buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255) + end + end + end + if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then + local list: { { number } } = {} + for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + local hd, vd = readu16(b, o + 12), readu16(b, o + 14) + if hd > 0 and vd > 0 then + img.meta.dpi = { x = hd, y = vd } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- RLE of one plane row into w +local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number) + local i = 0 + while i < n do + local v = readu8(src, p + i) + local run = 1 + while i + run < n and run < 63 and readu8(src, p + i + run) == v do + run += 1 + end + if run > 1 or v >= 0xC0 then + out:u8(0xC0 + run) + end + out:u8(v) + i += run + end +end + +function Pcx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false) + local planes = if usePal then 1 elseif alpha then 4 else 3 + local bpl = w + w % 2 + local out = Bytes.writer(128 + w * h * planes + 800) + out:u8(10) + out:u8(5) + out:u8(1) + out:u8(8) + out:u16le(0) + out:u16le(0) + out:u16le(w - 1) + out:u16le(h - 1) + local dpi = img.meta and img.meta.dpi + out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72) + out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72) + out:fill(0, 48) + out:u8(0) + out:u8(planes) + out:u16le(bpl) + out:u16le(1) + out:fill(0, 58) + local row = buffer.create(bpl) + local index: { [number]: number } = {} + for i, c in cols do + index[c] = i - 1 + end + for y = 0, h - 1 do + for pl = 0, planes - 1 do + for x = 0, w - 1 do + local s = (y * w + x) * 4 + local v + if usePal then + v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0 + else + v = readu8(px, s + pl) + end + buffer.writeu8(row, x, v) + end + rleRow(out, row, 0, bpl) + end + end + if usePal then + out:u8(12) + for i = 0, 255 do + local c = cols[i + 1] or 0 + out:u8(bit32.band(c, 255)) + out:u8(bit32.band(bit32.rshift(c, 8), 255)) + out:u8(bit32.rshift(c, 16)) + end + end + return out:finish(), nil +end + +return Pcx +end +__FILES["image/png"] = function() + +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. +-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), +-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha +-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). +-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / +-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not +-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode +-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. +-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are +-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Decode = __include("image/png/Decode") +local Encode = __include("image/png/Encode") +local Apng = __include("image/png/Apng") + +-- ------------------------------------------------------------------------------------------------ contract +local Png = { + name = "png", + category = "image", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 } }, +} + +type DecodeOptions = { + checkCrc: boolean?, -- verify every chunk's CRC-32 (default false) + maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer) +} +type EncodeOptions = { + level: number?, -- deflate level 0..9 (default 6) + colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one + apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when + -- img.frames is a non-empty list +} + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = "\137PNG\r\n\26\n" +local VALID = { + [0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true }, + [2] = { [8] = true, [16] = true }, + [3] = { [1] = true, [2] = true, [4] = true, [8] = true }, + [4] = { [8] = true, [16] = true }, + [6] = { [8] = true, [16] = true }, +} +local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" } + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Png.sniff(r: Bytes.Reader): number + return if r:peek(8) == SIGNATURE then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number } + +-- the IHDR at r's start: Header | nil, Err +local function header(r: Bytes.Reader): (Header?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", o) + end + if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then + return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8) + end + local h = { + width = be32(b, o + 16), + height = be32(b, o + 20), + bitDepth = readu8(b, o + 24), + colorType = readu8(b, o + 25), + interlace = readu8(b, o + 28), + } + if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad image size", o + 16) + end + local depths = VALID[h.colorType] + if not depths then + return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25) + end + if not depths[h.bitDepth] then + return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24) + end + if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then + return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26) + end + return h, nil +end + +-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) +function Png.info(r: Bytes.Reader): (Header?, Err.Err?) + return header(r) +end + +type FrameControl = { + width: number, + height: number, + x: number, + y: number, + num: number, + den: number, + dispose: number, + blend: number, + chunks: { { number } }, -- fdAT payloads: offset, length + len: number, +} +local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" } + +-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split +-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) +local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err? + -- the inflated size: every (pass) row has a filter byte + local channels = Decode.CHANNELS[ct] + local expected = 0 + if interlace == 0 then + expected = ht * (Decode.rowBytes(w, channels, depth) + 1) + else + for _, pass in Decode.PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if ht > y0 then (ht - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + expected += ph * (Decode.rowBytes(pw, channels, depth) + 1) + end + end + end + local z: buffer + if #chunks == 1 then + z = b + else + z = buffer.create(total) + local w0 = 0 + for _, c in chunks do + buffer.copy(z, w0, b, c[1], c[2]) + w0 += c[2] + end + end + local zo = if #chunks == 1 then chunks[1][1] else 0 + local raw, zerr = Deflate.zlib(z, zo, total, expected) + if not raw then + -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows + local loose = Deflate.zlib(z, zo, total) + if not loose or buffer.len(loose) < expected then + return zerr or Err.new(Err.CORRUPT, "bad image data") + end + raw = loose + end + local ok, derr = Decode.run(raw :: buffer, w, ht, depth, ct, interlace, pal, tr, out) + if not ok then + return Err.new(Err.CORRUPT, tostring(derr)) + end + return nil +end + +function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local checkCrc = opts and opts.checkCrc or false + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h, herr = header(r) + if not h then + return nil, herr + end + local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b, n = r.buf, r.limit + -- chunks + local pal = buffer.create(1024) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black + end + local palCount = 0 + local tr = -1 + local idat: { { number } } = {} + local idatLen = 0 + local text: { [string]: string } = {} + local iccCompressed: buffer? = nil + -- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter + local plays: number? = nil + local fctls: { FrameControl } = {} + local seq = 0 + local idatInAnim = false + local animPixels = 0 + local p = r.base + 8 + local first = true + for _, c in Chunks.walk(b, p, n, Chunks.PNG) do + local len, typ, d = c.size, c.id, c.offset + p = c.start + if c.truncated then + if p + 12 > n then + break -- not even a whole chunk header + CRC left (a cut tail) + end + return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p) + end + if checkCrc then + local want = be32(b, d + len) + if Crc32.raw(b, p + 4, len + 4) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len) + end + end + if first and typ ~= "IHDR" then + return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p) + end + first = false + if typ == "PLTE" then + if len % 3 ~= 0 or len > 768 or len == 0 then + return nil, Err.new(Err.CORRUPT, "bad PLTE length", p) + end + palCount = len // 3 + for i = 0, palCount - 1 do + local q = d + i * 3 + buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000) + end + elseif typ == "tRNS" then + if ct == 3 then + for i = 0, math.min(len, 256) - 1 do + buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i)) + end + elseif ct == 0 and len >= 2 then + tr = readu8(b, d) * 256 + readu8(b, d + 1) + elseif ct == 2 and len >= 6 then + local function u16(q: number): number + return readu8(b, d + q) * 256 + readu8(b, d + q + 1) + end + tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4) + end + elseif typ == "IDAT" then + table.insert(idat, { d, len }) + idatLen += len + if #fctls == 1 and #idat == 1 then + idatInAnim = true + end + elseif typ == "tEXt" then + local s = buffer.readstring(b, d, len) + local z = string.find(s, "\0", 1, true) + if z then + text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1) + end + elseif typ == "iCCP" then + local cb = buffer.create(len) + buffer.copy(cb, 0, b, d, len) + iccCompressed = cb + elseif typ == "acTL" then + if len >= 8 and plays == nil and #idat == 0 then + plays = be32(b, d + 4) + end + elseif typ == "fcTL" and plays ~= nil then + if len < 26 then + return nil, Err.new(Err.CORRUPT, "short fcTL", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f: FrameControl = { + width = be32(b, d + 4), + height = be32(b, d + 8), + x = be32(b, d + 12), + y = be32(b, d + 16), + num = readu8(b, d + 20) * 256 + readu8(b, d + 21), + den = readu8(b, d + 22) * 256 + readu8(b, d + 23), + dispose = readu8(b, d + 24), + blend = readu8(b, d + 25), + chunks = {}, + len = 0, + } + if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then + return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p) + end + if f.dispose > 2 or f.blend > 1 then + return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p) + end + if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then + return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p) + end + animPixels += f.width * f.height + if animPixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels)) + end + table.insert(fctls, f) + elseif typ == "fdAT" and plays ~= nil then + if len < 4 then + return nil, Err.new(Err.CORRUPT, "short fdAT", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p) + end + seq += 1 + local f = fctls[#fctls] + if not f or (#fctls == 1 and idatInAnim) then + return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p) + end + table.insert(f.chunks, { d + 4, len - 4 }) + f.len += len - 4 + elseif typ == "IEND" then + break -- a missing IEND is tolerated (truncated tail after the data) + elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then + return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p) + end + end + if #idat == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", p) + end + if ct == 3 and palCount == 0 then + return nil, Err.new(Err.CORRUPT, "palette image without PLTE") + end + local img = Types.Image.new(w, ht, "rgba8") + local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels) + if ierr then + return nil, ierr + end + if plays ~= nil and #fctls > 0 then + local last = fctls[#fctls] + if #fctls > 1 and #last.chunks == 0 then + fctls[#fctls] = nil -- a truncated file: the last frame never got its data + end + local frames: { Types.Frame } = {} + for i, f in fctls do + local fimg: Types.Image + if i == 1 and idatInAnim then + fimg = Types.Image.new(w, ht, "rgba8") + buffer.copy(fimg.pixels, 0, img.pixels) + else + if #f.chunks == 0 then + return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data") + end + fimg = Types.Image.new(f.width, f.height, "rgba8") + local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels) + if ferr then + ferr.message = "frame " .. i .. ": " .. ferr.message + return nil, ferr + end + end + frames[i] = { + image = fimg, + delay = f.num / (if f.den == 0 then 100 else f.den), + x = f.x, + y = f.y, + dispose = DISPOSE[f.dispose] :: any, + blend = if f.blend == 1 then "over" :: "over" else "source" :: "source", + } + end + img.frames = frames + img.loops = plays + img.meta.apngDefaultHidden = not idatInAnim + end + if ct == 3 then + local palette: { { number } } = {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if next(text) then + img.meta.text = text + end + img.meta.iccCompressed = iccCompressed + img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } +local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 } +local BLEND_CODES: { [string]: number } = { source = 0, over = 1 } + +-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds +local function delayFraction(delay: number): (number, number) + for den = 1, 1000 do + local num = math.floor(delay * den + 0.5) + if num > 65535 then + break + end + if math.abs(num / den - delay) < 1e-9 then + return num, den + end + end + if delay * 1000 <= 65535 then + return math.floor(delay * 1000 + 0.5), 1000 + elseif delay * 100 <= 65535 then + return math.floor(delay * 100 + 0.5), 100 + end + return math.min(65535, math.floor(delay + 0.5)), 1 +end + +local function validImage(im: any): boolean + return type(im) == "table" + and im.format == "rgba8" + and type(im.pixels) == "buffer" + and type(im.width) == "number" + and type(im.height) == "number" + and im.width >= 1 + and im.height >= 1 + and im.width % 1 == 0 + and im.height % 1 == 0 + and buffer.len(im.pixels) >= im.width * im.height * 4 +end + +-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list +local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?) + local frames = img.frames + local mode = if opts then opts.apng else nil + if mode == false then + return nil, nil + end + if frames ~= nil and type(frames) ~= "table" then + return nil, Err.new(Err.ARG, "frames must be a list") + end + if frames == nil or #frames == 0 then + if mode then + return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: any }, nil + end + return nil, nil + end + for i, f in frames do + local label = "png encode: frame " .. i + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, label .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then + return nil, Err.new(Err.ARG, label .. ": rectangle outside the image") + end + if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then + return nil, Err.new(Err.ARG, label .. ": bad delay") + end + if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then + return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose)) + end + if f.blend ~= nil and BLEND_CODES[f.blend] == nil then + return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend)) + end + end + return frames, nil +end + +function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + local level = opts and opts.level or 6 + if type(level) ~= "number" or level < 0 or level > 9 then + return nil, Err.new(Err.ARG, "level must be 0..9") + end + local frames, ferr = animationFrames(img, opts) + if ferr then + return nil, ferr + end + local loops = img.loops or 0 + if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then + return nil, Err.new(Err.ARG, "loops must be an integer 0..2^32-1") + end + local want = opts and opts.colorType or "auto" + local ctName: string = want + if want == "auto" then + -- the smallest colour type that holds the image and every frame + local alpha, color = false, false + local function scan(im: Types.Image) + local c = Encode.pickColorType(im.pixels, im.width, im.height) + alpha = alpha or c == "rgba" or c == "graya" + color = color or c == "rgba" or c == "rgb" + end + scan(img) + if frames then + for _, f in frames do + scan(f.image) + end + end + ctName = if color then (if alpha then "rgba" else "rgb") else (if alpha then "graya" else "gray") + end + local ct = CT_CODES[ctName] + if ct == nil then + return nil, Err.new(Err.ARG, "unknown colorType " .. tostring(want)) + end + local function zdata(im: Types.Image): buffer + return Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) :: buffer + end + + local out = Bytes.writer(w * h + 128) + local function chunk(typ: string, data: buffer?, prefix: number?) + local len = (if data then buffer.len(data) else 0) + (if prefix then 4 else 0) + out:u32be(len) + local start = out:tell() + out:string(typ) + if prefix then + out:u32be(prefix) + end + if data then + out:bytes(data) + end + out:u32be(Crc32.raw(out.buf, start, len + 4)) + end + out:string(SIGNATURE) + local ihdr = Bytes.writer(13) + ihdr:u32be(w) + ihdr:u32be(h) + ihdr:u8(8) + ihdr:u8(ct) + ihdr:u8(0) + ihdr:u8(0) + ihdr:u8(0) + chunk("IHDR", ihdr:finish()) + if frames then + local actl = Bytes.writer(8) + actl:u32be(#frames) + actl:u32be(loops) + chunk("acTL", actl:finish()) + end + if img.meta and img.meta.text then + for k, v in img.meta.text do + local t = Bytes.writer() + t:string(k) + t:u8(0) + t:string(v) + chunk("tEXt", t:finish()) + end + end + if not frames then + chunk("IDAT", zdata(img)) + chunk("IEND", nil) + return out:finish(), nil + end + -- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is + -- written first, outside the animation + local f1 = frames[1] + local f1i = f1.image + local inAnim = f1i == img + or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4)) + local seq = 0 + if not inAnim then + chunk("IDAT", zdata(img)) + end + for i, f in frames do + local fi = f.image + local num, den = delayFraction(f.delay or 0) + local fc = Bytes.writer(26) + fc:u32be(seq) + fc:u32be(fi.width) + fc:u32be(fi.height) + fc:u32be(f.x or 0) + fc:u32be(f.y or 0) + fc:u16be(num) + fc:u16be(den) + fc:u8(DISPOSE_CODES[f.dispose or "none"]) + fc:u8(BLEND_CODES[f.blend or "source"]) + chunk("fcTL", fc:finish()) + seq += 1 + if i == 1 and inAnim then + chunk("IDAT", zdata(img)) + else + chunk("fdAT", zdata(fi), seq) + seq += 1 + end + end + chunk("IEND", nil) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a +-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. +function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?) + if not validImage(img) then + return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") + end + local frames, ferr = animationFrames(img, { apng = true }) + if not frames then + return nil, ferr + end + local w, h = img.width, img.height + local list = {} + for i, f in frames do + list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" } + end + local out = {} + for i, b in Apng.composite(w, h, list) do + local im = Types.Image.new(w, h, "rgba8") + im.pixels = b + out[i] = im + end + return out, nil +end + +return Png +end +__FILES["image/png/Apng"] = @native function() + + + +-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / +-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the +-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Apng = {} + +@native local function div255(x: number): number + return (x + 128) * 257 // 65536 +end + +-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas +@native local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean) + for y = 0, fh - 1 do + local so = y * fw * 4 + local co = ((fy + y) * cw + fx) * 4 + if not over then + bcopy(canvas, co, src, so, fw * 4) + else + for x = 0, fw - 1 do + local s, c = so + x * 4, co + x * 4 + local fa = readu8(src, s + 3) + if fa == 255 then + writeu32(canvas, c, readu32(src, s)) + elseif fa ~= 0 then + local ba = readu8(canvas, c + 3) + local oa = fa + div255((255 - fa) * ba) + if ba == 255 then + for k = 0, 2 do + writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k))) + end + else + local den = 255 * oa + for k = 0, 2 do + writeu8(canvas, c + k, (255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) // den) + end + end + writeu8(canvas, c + 3, oa) + end + end + end + end +end + +-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) +@native function Apng.composite(w: number, h: number, frames: { any }): { buffer } + local canvas = bcreate(w * h * 4) + local saved = bcreate(w * h * 4) + local out: { buffer } = {} + for i, f in frames do + local fi = f.image + local fw, fh = fi.width, fi.height + local dispose, over = f.dispose, f.blend == "over" + if i == 1 then + over = false -- the canvas starts transparent black: source and over differ only in hidden colour + if dispose == "previous" then + dispose = "background" + end + end + if dispose == "previous" then + bcopy(saved, 0, canvas, 0) + end + blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over) + local snap = bcreate(w * h * 4) + bcopy(snap, 0, canvas, 0) + out[i] = snap + if dispose == "background" then + for y = 0, fh - 1 do + bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4) + end + elseif dispose == "previous" then + bcopy(canvas, 0, saved, 0) + end + end + return out +end + +return Apng +end +__FILES["image/png/Decode"] = @native function() + + + +-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the +-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. +-- Absorbed from png-luau src/Png/Decode.luau (same author). +-- +-- The caller (init) has validated the header and checked that the data holds at least the expected number of +-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcopy = buffer.copy + +local Decode = {} + +-- Adam7: x0, y0, dx, dy per pass +local PASSES = { + { 0, 0, 8, 8 }, + { 4, 0, 8, 8 }, + { 0, 4, 4, 8 }, + { 2, 0, 4, 4 }, + { 0, 2, 2, 4 }, + { 1, 0, 2, 2 }, + { 0, 1, 1, 2 }, +} +Decode.PASSES = PASSES + +local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } +Decode.CHANNELS = CHANNELS + +-- bytes per row (without the filter byte) for a pass width +@native function Decode.rowBytes(pw: number, channels: number, depth: number): number + return (pw * channels * depth + 7) // 8 +end + +-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per +-- complete pixel (at least 1). Returns true, or false + the bad filter type. +@native local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number) + local stride = rb + 1 + for r = 0, ph - 1 do + local f = readu8(raw, p) + local cur = p + 1 + if f == 0 then + -- none + elseif f == 1 then + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + elseif f == 2 then + if r > 0 then + local i = cur + local e4 = cur + rb - 4 + while i <= e4 do + -- four bytes at once: add without carries between the byte lanes + local x, y = readu32(raw, i), readu32(raw, i - stride) + local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) + writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) + i += 4 + end + while i < cur + rb do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + i += 1 + end + end + elseif f == 3 then + if r > 0 then + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1)) + end + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1)) + end + else + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1)) + end + end + elseif f == 4 then + if r > 0 then + -- the first pixel: a = c = 0, so Paeth picks b + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + end + for i = cur + bpp, cur + rb - 1 do + local a = readu8(raw, i - bpp) + local b = readu8(raw, i - stride) + local c = readu8(raw, i - stride - bpp) + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + local v + if pa <= pb and pa <= pc then + v = a + elseif pb <= pc then + v = b + else + v = c + end + writeu8(raw, i, readu8(raw, i) + v) + end + else + -- no previous row: Paeth is sub + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + end + else + return false, f + end + p += stride + end + return true, 0 +end + +-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. +-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), +-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. +@native local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number) + if ct == 6 then + if depth == 8 then + if ostep == 4 then + bcopy(out, oo, raw, ro, pw * 4) + else + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4)) + end + end + else + for x = 0, pw - 1 do + local s = ro + x * 8 + local o = oo + x * ostep + writeu8(out, o, readu8(raw, s)) + writeu8(out, o + 1, readu8(raw, s + 2)) + writeu8(out, o + 2, readu8(raw, s + 4)) + writeu8(out, o + 3, readu8(raw, s + 6)) + end + end + elseif ct == 2 then + if depth == 8 then + for x = 0, pw - 1 do + local s = ro + x * 3 + local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216) + end + else + for x = 0, pw - 1 do + local s = ro + x * 6 + local r = readu8(raw, s) * 256 + readu8(raw, s + 1) + local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3) + local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216) + end + end + elseif ct == 3 then + if depth == 8 then + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4)) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + writeu32(out, oo + x * ostep, readu32(pal, idx * 4)) + end + end + elseif ct == 0 then + if depth == 8 then + for x = 0, pw - 1 do + local v = readu8(raw, ro + x) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + elseif depth == 16 then + for x = 0, pw - 1 do + local hi = readu8(raw, ro + x * 2) + local v = hi * 256 + readu8(raw, ro + x * 2 + 1) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216) + end + else + local per = 8 // depth + local mask = lshift(1, depth) - 1 + local scale = 255 // mask + for x = 0, pw - 1 do + local byte = readu8(raw, ro + x // per) + local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + local a = if v == tr then 0 else 255 + writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216) + end + end + else -- ct == 4: grey + alpha + if depth == 8 then + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + else + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + end + end +end + +-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). +-- Returns true, or false + message. +@native function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?) + local channels = CHANNELS[ct] + local bpp = math.max(1, (channels * depth) // 8) + local p = 0 + if interlace == 0 then + local rb = Decode.rowBytes(w, channels, depth) + local ok, f = unfilter(raw, 0, h, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for y = 0, h - 1 do + convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) + end + return true, nil + end + for _, pass in PASSES do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = if w > x0 then (w - x0 + dx - 1) // dx else 0 + local ph = if h > y0 then (h - y0 + dy - 1) // dy else 0 + if pw > 0 and ph > 0 then + local rb = Decode.rowBytes(pw, channels, depth) + local ok, f = unfilter(raw, p, ph, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for r = 0, ph - 1 do + local y = y0 + r * dy + convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr) + end + p += ph * (rb + 1) + end + end + return true, nil +end + +return Decode +end +__FILES["image/png/Encode"] = @native function() + + + +-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and +-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute +-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy = buffer.create, buffer.copy + +local Encode = {} + +local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } + +-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" +@native function Encode.pickColorType(px: buffer, w: number, h: number): string + local opaque, gray = true, true + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3) + if a ~= 255 then + opaque = false + end + if r ~= g or g ~= b then + gray = false + end + if not opaque and not gray then + return "rgba" + end + end + if gray then + return if opaque then "gray" else "graya" + end + return "rgb" +end + +-- convert rgba8 to the colour type's packed rows (no filter bytes) +@native local function pack(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + if ch == 4 then + return px + end + local out = bcreate(w * h * ch) + local n = w * h + if ct == 2 then + for i = 0, n - 1 do + bcopy(out, i * 3, px, i * 4, 3) + end + elseif ct == 0 then + for i = 0, n - 1 do + writeu8(out, i, readu8(px, i * 4)) + end + else -- graya + for i = 0, n - 1 do + writeu8(out, i * 2, readu8(px, i * 4)) + writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3)) + end + end + return out +end + +@native local function paeth(a: number, b: number, c: number): number + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + if pa <= pb and pa <= pc then + return a + elseif pb <= pc then + return b + end + return c +end + +-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); +-- the arithmetic is inlined: this runs for every byte +@native local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number) + local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local b, c = 0, 0 + if not first then + b = readu8(src, p + i) + if i >= bpp then + c = readu8(src, p + i - bpp) + end + end + local d = if x < 128 then x else 256 - x + c0 += d + d = (x - a) % 256 + c1 += if d < 128 then d else 256 - d + d = (x - b) % 256 + c2 += if d < 128 then d else 256 - d + d = (x - (a + b) // 2) % 256 + c3 += if d < 128 then d else 256 - d + local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c) + local pr = if pa <= pb and pa <= pc then a elseif pb <= pc then b else c + d = (x - pr) % 256 + c4 += if d < 128 then d else 256 - d + end + return c0, c1, c2, c3, c4 +end + +-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) +@native local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number) + writeu8(out, o, f) + o += 1 + if f == 0 or (f == 2 and first) then + bcopy(out, o, src, s, rb) + return + end + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = if i >= bpp then readu8(src, s + i - bpp) else 0 + local pred + if f == 1 then + pred = a + elseif f == 2 then + pred = readu8(src, p + i) + elseif f == 3 then + pred = (a + (if first then 0 else readu8(src, p + i))) // 2 + elseif first then + pred = a + else + local c = if i >= bpp then readu8(src, p + i - bpp) else 0 + pred = paeth(a, readu8(src, p + i), c) + end + writeu8(out, o + i, x - pred) + end +end + +-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of +-- |signed residuals| (the libpng heuristic) +@native function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer + local ch = CHANNELS[ct] + local src = pack(px, w, h, ct) + local rb = w * ch + local out = bcreate(h * (rb + 1)) + for y = 0, h - 1 do + local s = y * rb + local first = y == 0 + local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first) + local best, bc = 0, c0 + if c1 < bc then + best, bc = 1, c1 + end + if c2 < bc then + best, bc = 2, c2 + end + if c3 < bc then + best, bc = 3, c3 + end + if c4 < bc then + best = 4 + end + apply(src, s, rb, ch, first, best, out, y * (rb + 1)) + end + return out +end + +return Encode +end +__FILES["image/pnm"] = function() + +-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), +-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any +-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). +-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout +-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is +-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel +-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. +-- Not supported: multi-image streams (the first image is read), PAM depths above 4. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/pnm/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Pnm = { + name = "pnm", + category = "image", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- keep the source layout (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour + -- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default + ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false) + maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it + threshold: number?, -- pbm: grey below this (0..255) is black (default 128) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FMT_CODE: { [string]: number } = { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } +local BPP: { [string]: number } = { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pnm.sniff(r: Bytes.Reader): number + if r:remaining() < 3 then + return 0 + end + local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2) + if a ~= 80 then -- 'P' + return 0 + end + local ws = c == 32 or (c >= 9 and c <= 13) + if b >= 49 and b <= 55 and ws then -- P1..P7 + return 0.9 + end + if (b == 70 or b == 102) and ws then -- PF / Pf + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function isSpace(c: number): boolean + return c == 32 or (c >= 9 and c <= 13) +end + +-- the next header token from p: token, position after it (nil at the end) +local function token(b: buffer, p: number, limit: number): (string?, number) + while p < limit do + local c = readu8(b, p) + if c == 35 then + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif isSpace(c) then + p += 1 + else + break + end + end + local s = p + while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do + p += 1 + end + if p == s then + return nil, p + end + return buffer.readstring(b, s, p - s), p +end + +local function int(s: string?): number? + if s == nil or not string.match(s, "^%d+$") or #s > 9 then + return nil + end + return tonumber(s) +end + +function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local native = opts and opts.native or false + local b, limit = r.buf, r.limit + if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local kind = string.char(readu8(b, r.base + 1)) + local p = r.base + 2 + local w: number?, h: number?, maxval: number?, ch: number, mode: number + local bits = false -- PBM: 1 = black + local bw = false -- PAM BLACKANDWHITE: 1 = white + local tupl: string? = nil + local scale: number? = nil + if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then + local t1, t2, t3 + t1, p = token(b, p, limit) + t2, p = token(b, p, limit) + w, h = int(t1), int(t2) + if kind == "1" or kind == "4" then + maxval = 1 + elseif kind == "F" or kind == "f" then + t3, p = token(b, p, limit) + scale = if t3 then tonumber(t3) else nil + if scale == nil or scale == 0 then + return nil, Err.new(Err.CORRUPT, "bad PFM scale", p) + end + maxval = 1 + else + t3, p = token(b, p, limit) + maxval = int(t3) + end + if w == nil or h == nil or maxval == nil then + return nil, if p >= limit then Err.new(Err.TRUNCATED, "header ends early", p) else Err.new(Err.CORRUPT, "bad header", p) + end + if kind ~= "1" and kind ~= "2" and kind ~= "3" then + p += 1 -- exactly one whitespace byte before binary data + end + ch = if kind == "3" or kind == "6" or kind == "F" then 3 else 1 + bits = kind == "1" or kind == "4" + mode = if kind == "1" then 4 elseif kind == "2" or kind == "3" then 3 elseif kind == "4" then 0 elseif (maxval :: number) > 255 then 2 else 1 + elseif kind == "7" then + local depth: number? + while true do + local key + key, p = token(b, p, limit) + if key == nil then + return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p) + end + if key == "ENDHDR" then + break + end + local v + v, p = token(b, p, limit) + if key == "WIDTH" then + w = int(v) + elseif key == "HEIGHT" then + h = int(v) + elseif key == "DEPTH" then + depth = int(v) + elseif key == "MAXVAL" then + maxval = int(v) + elseif key == "TUPLTYPE" then + tupl = v + -- the rest of the line belongs to the value + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + end + end + -- ENDHDR ends with a newline + while p < limit and readu8(b, p) ~= 10 do + p += 1 + end + p += 1 + if w == nil or h == nil or depth == nil or maxval == nil then + return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p) + end + if (depth :: number) < 1 or (depth :: number) > 4 then + return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth :: number)) + end + ch = depth :: number + bw = tupl ~= nil and string.sub(tupl :: string, 1, 13) == "BLACKANDWHITE" + mode = if (maxval :: number) > 255 then 2 else 1 + else + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil + if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local n = w * h + local img: Types.Image + local colorType = if ch == 1 then "gray" elseif ch == 2 then "graya" elseif ch == 3 then "rgb" else "rgba" + if scale then + local f = Types.Image.new(w, h, "rgbaf32") + local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale :: number) < 0, f.pixels) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + img = f + if not native then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, n * 4 - 1 do + local v = buffer.readf32(f.pixels, i * 4) + buffer.writeu8(o.pixels, i, if v ~= v then 0 else math.floor(math.clamp(v, 0, 1) * 255 + 0.5)) + end + img = o + end + img.meta.source = { format = "pnm", type = if ch == 3 then "pfm" else "pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale :: number), byteOrder = if (scale :: number) < 0 then "little" else "big" } + return img, nil + end + local samples = buffer.create(n * ch * 2) + local ok, e + if mode == 0 then + ok, e = Codec.readBits(b, p, limit, w, h, samples) + else + ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples) + end + if not ok then + return nil, Err.new(if e == "truncated" then Err.TRUNCATED else Err.CORRUPT, tostring(e)) + end + local fmt: Types.PixelFormat = "rgba8" + if native then + local wide = maxval > 255 + if bits or bw or ch == 1 then + fmt = if wide then "gray16" else "gray8" + elseif ch == 2 then + fmt = if wide then "rgba16" else "graya8" + elseif ch == 3 then + fmt = if wide then "rgba16" else "rgb8" + else + fmt = if wide then "rgba16" else "rgba8" + end + end + img = Types.Image.new(w, h, fmt :: Types.PixelFormat) + Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels) + local typ = if kind == "7" then "pam" elseif bits then "pbm" elseif ch == 1 then "pgm" else "ppm" + img.meta.source = { + format = "pnm", + type = typ, + ascii = mode == 3 or mode == 4, + bitDepth = if bits or bw then 1 elseif maxval > 255 then 16 else 8, + maxval = maxval, + colorType = if bits or bw then "bilevel" else colorType, + tupltype = tupl, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true } + +function Pnm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local fc = FMT_CODE[img.format] + if fc == nil then + return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w: number, h: number = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o: any = opts or {} + local n = w * h + local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8" + local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32" + if hasAlpha and img.format ~= "graya8" then + -- an alpha channel that is fully opaque does not count + local opaque = true + for i = 0, n - 1 do + local a + if img.format == "rgba8" then + a = buffer.readu8(img.pixels, i * 4 + 3) == 255 + elseif img.format == "rgba16" then + a = buffer.readu16(img.pixels, i * 8 + 6) == 65535 + else + a = buffer.readf32(img.pixels, i * 16 + 12) == 1 + end + if not a then + opaque = false + break + end + end + hasAlpha = not opaque + end + local sub = if type(o.format) == "string" then string.lower(o.format) else nil + if not (sub and SUBTYPES[sub]) then + if img.format == "rgbaf32" and not hasAlpha then + sub = "pfm" + elseif hasAlpha then + sub = "pam" + elseif isGray then + sub = "pgm" + else + sub = "ppm" + end + end + local ascii = o.ascii == true + local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" + local maxval: number = o.maxval or (if wideSrc then 65535 else 255) + if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxval must be 1..65535") + end + local out: buffer + local op = 0 + local function header(s: string, extra: number) + out = buffer.create(#s + extra) + buffer.writestring(out, 0, s) + op = #s + end + if sub == "pfm" then + local ch = if isGray then 1 else 3 + local src = img + if img.format ~= "rgbaf32" then + local s = Codec.extract(img.pixels, fc, n, 4, true) + src = Types.Image.new(w, h, "rgbaf32") + for i = 0, n * 4 - 1 do + buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535) + end + end + header(string.format("%s\n%d %d\n-1.0\n", if ch == 3 then "PF" else "Pf", w, h), n * ch * 4) + op = Codec.writeFloats(src.pixels, w, h, ch, out, op) + return out, nil + end + local ch = if sub == "pbm" or sub == "pgm" then 1 elseif sub == "ppm" then 3 elseif isGray then (if hasAlpha then 2 else 1) else (if hasAlpha then 4 else 3) + if sub == "pbm" then + local thr = o.threshold or 128 + local s = Codec.extract(img.pixels, fc, n, 1, false) + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("P1\n%d %d\n", w, h) + for y = 0, h - 1 do + local row = table.create(w) + for x = 0, w - 1 do + row[x + 1] = if buffer.readu16(s, (y * w + x) * 2) < thr then "1" else "0" + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("P4\n%d %d\n", w, h), ((w + 7) // 8) * h) + op = Codec.writeBits(s, w, h, thr, out, op) + return out, nil + end + local wide = maxval > 255 + local s = Codec.extract(img.pixels, fc, n, ch, wide) + if maxval ~= 255 and maxval ~= 65535 then + local top = if wide then 65535 else 255 + for i = 0, n * ch - 1 do + buffer.writeu16(s, i * 2, (buffer.readu16(s, i * 2) * maxval + top // 2) // top) + end + end + local magic + if sub == "pam" then + local tt = if ch == 1 then "GRAYSCALE" elseif ch == 2 then "GRAYSCALE_ALPHA" elseif ch == 3 then "RGB" else "RGB_ALPHA" + header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil + end + magic = if sub == "pgm" then (if ascii then "P2" else "P5") else (if ascii then "P3" else "P6") + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval) + local rowLen = w * ch + for y = 0, h - 1 do + local row = table.create(rowLen) + for i = 0, rowLen - 1 do + row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2)) + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (if wide then 2 else 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil +end + +return Pnm +end +__FILES["image/pnm/Codec"] = @native function() + + + +-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, +-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM +-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. +-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 +local byteswap = bit32.byteswap + +local Codec = {} + +-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). +-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) +@native function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?) + if mode == 1 then + if p + count > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i)) + end + return true, nil + elseif mode == 2 then + if p + count * 2 > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1)) + end + return true, nil + end + local i = 0 + while i < count do + -- skip whitespace and comments + while p < limit do + local c = readu8(b, p) + if c == 35 then -- '#' + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p += 1 + end + elseif c == 32 or (c >= 9 and c <= 13) then + p += 1 + else + break + end + end + if p >= limit then + return false, "truncated" + end + local c = readu8(b, p) + if c < 48 or c > 57 then + return false, "bad ASCII sample" + end + if mode == 4 then + writeu16(out, i * 2, c - 48) + p += 1 + else + local v = 0 + while p < limit do + local d = readu8(b, p) + if d < 48 or d > 57 then + break + end + v = math.min(v * 10 + d - 48, 65535) + p += 1 + end + writeu16(out, i * 2, v) + end + i += 1 + end + return true, nil +end + +-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values +@native function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?) + local rowBytes = (w + 7) // 8 + if p + rowBytes * h > limit then + return false, "truncated" + end + for y = 0, h - 1 do + local r = p + y * rowBytes + for x = 0, w - 1 do + local byte = readu8(b, r + x // 8) + writeu16(out, (y * w + x) * 2, (byte // 2 ^ (7 - x % 8)) % 2) + end + end + return true, nil +end + +-- format codes for pack / extract +Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 + +-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for +-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +@native function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer) + local wide = fmt == 4 or fmt == 5 + local top = if wide then 65535 else 255 + local half = maxval // 2 + @native local function get(i: number): number + local v = math.min(readu16(s, i * 2), maxval) + if invert then + v = maxval - v + end + if maxval == top then + return v + end + return (v * top + half) // maxval + end + for i = 0, n - 1 do + local q = i * ch + local r, g, b, a + if ch == 1 then + r = get(q) + g, b, a = r, r, top + elseif ch == 2 then + r = get(q) + g, b, a = r, r, get(q + 1) + elseif ch == 3 then + r, g, b, a = get(q), get(q + 1), get(q + 2), top + else + r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3) + end + if fmt == 0 then + writeu32(dst, i * 4, r + g * 256 + b * 65536 + (a :: number) * 16777216) + elseif fmt == 1 then + writeu8(dst, i * 3, r) + writeu8(dst, i * 3 + 1, g) + writeu8(dst, i * 3 + 2, b) + elseif fmt == 2 then + writeu8(dst, i, r) + elseif fmt == 3 then + writeu8(dst, i * 2, r) + writeu8(dst, i * 2 + 1, a :: number) + elseif fmt == 4 then + writeu16(dst, i * 8, r) + writeu16(dst, i * 8 + 2, g) + writeu16(dst, i * 8 + 4, b) + writeu16(dst, i * 8 + 6, a :: number) + elseif fmt == 5 then + writeu16(dst, i * 2, r) + end + end +end + +-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst +@native function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?) + if p + w * h * ch * 4 > limit then + return false, "truncated" + end + local tmp = buffer.create(4) + for y = 0, h - 1 do + local row = p + (h - 1 - y) * w * ch * 4 + for x = 0, w - 1 do + local o = (y * w + x) * 16 + for c = 0, ch - 1 do + local v + if le then + v = readf32(b, row + (x * ch + c) * 4) + else + writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4))) + v = readf32(tmp, 0) + end + writef32(dst, o + c * 4, v) + end + if ch == 1 then + local v = readf32(dst, o) + writef32(dst, o + 4, v) + writef32(dst, o + 8, v) + end + writef32(dst, o + 12, 1) + end + end + return true, nil +end + +@native local function f(v: number): number + if v ~= v then + return 0 + end + return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) +end + +-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for +-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +@native function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer + local out = buffer.create(n * ch * 2) + local srcWide = fmt == 4 or fmt == 5 + local isGray = fmt == 2 or fmt == 3 or fmt == 5 + for i = 0, n - 1 do + local r, g, b, a + if fmt == 0 then + r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3) + elseif fmt == 1 then + r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255 + elseif fmt == 2 then + r = readu8(px, i) + g, b, a = r, r, 255 + elseif fmt == 3 then + r, a = readu8(px, i * 2), readu8(px, i * 2 + 1) + g, b = r, r + elseif fmt == 4 then + r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6) + elseif fmt == 5 then + r = readu16(px, i * 2) + g, b, a = r, r, 65535 + else + r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12)) + end + local w16 = srcWide or fmt == 6 + local gray = r + if ch <= 2 and not isGray then + gray = (r * 299 + g * 587 + b * 114) // 1000 + end + local vals = if ch == 1 then 1 elseif ch == 2 then 2 else ch + for c = 0, vals - 1 do + local v + if ch <= 2 then + v = if c == 0 then gray else a :: number + else + v = if c == 0 then r elseif c == 1 then g elseif c == 2 then b else a :: number + end + if wide and not w16 then + v *= 257 + elseif w16 and not wide then + v = (v * 255 + 32767) // 65535 + end + writeu16(out, (i * ch + c) * 2, v) + end + end + return out +end + +-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) +@native function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number + if wide then + for i = 0, count - 1 do + local v = readu16(s, i * 2) + writeu8(out, o, v // 256) + writeu8(out, o + 1, v % 256) + o += 2 + end + else + for i = 0, count - 1 do + writeu8(out, o, readu16(s, i * 2)) + o += 1 + end + end + return o +end + +-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) +@native function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number + for y = 0, h - 1 do + local acc, nb = 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (if readu16(s, (y * w + x) * 2) < threshold then 1 else 0) + nb += 1 + if nb == 8 then + writeu8(out, o, acc) + o += 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + writeu8(out, o, acc * 2 ^ (8 - nb)) + o += 1 + end + end + return o +end + +-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM +-- rows, bottom-to-top +@native function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number + for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 16 + for c = 0, ch - 1 do + writef32(out, o, readf32(px, q + c * 4)) + o += 4 + end + end + end + return o +end + +return Codec +end +__FILES["image/qoi"] = function() + +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. +-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); +-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. +-- Not supported: nothing in the spec is left out. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/qoi/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", + category = "image", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4) + linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear") +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Qoi.sniff(r: Bytes.Reader): number + return if r:peek(4) == "qoif" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local magic = r:string(4) + local w, h = r:u32be(), r:u32be() + local channels, cs = r:u8(), r:u8() + if r.err then + return nil, r.err + end + if magic ~= "qoif" then + return nil, Err.new(Err.CORRUPT, "bad magic", r.base) + end + if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then + return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4) + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgba8") + local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + if opts and opts.native and channels == 3 then + local rgb = Types.Image.new(w, h, "rgb8") + local src, dst = img.pixels, rgb.pixels + for i = 0, w * h - 1 do + buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4)) + buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2)) + end + img = rgb + end + img.meta.source = { format = "qoi", bitDepth = 8, colorType = if channels == 4 then "rgba" else "rgb", channels = channels, colorSpace = if cs == 1 then "linear" else "srgb" } + if cs == 1 then + img.meta.colorSpace = "linear" + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image") + end + local w, h = img.width, img.height + local bpp = if img.format == "rgba8" then 4 else 3 + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local channels = opts and opts.channels + if channels == nil then + channels = 3 + if bpp == 4 then + local px = img.pixels + for i = 0, w * h - 1 do + if buffer.readu8(px, i * 4 + 3) ~= 255 then + channels = 4 + break + end + end + end + elseif channels ~= 3 and channels ~= 4 then + return nil, Err.new(Err.ARG, "channels must be 3 or 4") + end + local linear = opts and opts.linear + if linear == nil then + local src = img.meta and img.meta.source + linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false + end + local n = w * h + local out = buffer.create(14 + n * (bpp + 1) + 8) + buffer.writestring(out, 0, "qoif") + buffer.writeu32(out, 4, bit32.byteswap(w)) + buffer.writeu32(out, 8, bit32.byteswap(h)) + buffer.writeu8(out, 12, channels :: number) + buffer.writeu8(out, 13, if linear then 1 else 0) + local o = Codec.encode(img.pixels, n, bpp, out, 14) + buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") + o += 8 + local res = buffer.create(o) + buffer.copy(res, 0, out, 0, o) + return res, nil +end + +return Qoi +end +__FILES["image/qoi/Codec"] = @native function() + + + +-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). +-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read +-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +local index = buffer.create(256) + +-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) +@native function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?) + buffer.fill(index, 0, 0, 256) + local r, g, bl, a = 0, 0, 0, 255 + local o = 0 + local stop = n * 4 + while o < stop do + if p >= limit then + return false, "truncated" + end + local op = readu8(b, p) + p += 1 + if op == 0xFE then + if p + 3 > limit then + return false, "truncated" + end + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) + p += 3 + elseif op == 0xFF then + if p + 4 > limit then + return false, "truncated" + end + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) + a = readu8(b, p + 3) + p += 4 + else + local tag = op // 64 + if tag == 0 then + local q = op * 4 + r = readu8(index, q) + g = readu8(index, q + 1) + bl = readu8(index, q + 2) + a = readu8(index, q + 3) + elseif tag == 1 then + r = (r + (op // 16) % 4 - 2) % 256 + g = (g + (op // 4) % 4 - 2) % 256 + bl = (bl + op % 4 - 2) % 256 + elseif tag == 2 then + if p >= limit then + return false, "truncated" + end + local d2 = readu8(b, p) + p += 1 + local dg = op % 64 - 32 + g = (g + dg) % 256 + r = (r + dg + d2 // 16 - 8) % 256 + bl = (bl + dg + d2 % 16 - 8) % 256 + else + local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA) + local v = r + g * 256 + bl * 65536 + a * 16777216 + local e = math.min(o + run * 4, stop - 4) + while o < e do + writeu32(out, o, v) + o += 4 + end + end + end + writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216) + o += 4 + local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4 + writeu8(index, h, r) + writeu8(index, h + 1, g) + writeu8(index, h + 2, bl) + writeu8(index, h + 3, a) + end + return true, nil +end + +-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes +@native function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number + buffer.fill(index, 0, 0, 256) + local pr, pg, pb, pa = 0, 0, 0, 255 + local run = 0 + local hasA = bpp == 4 + for i = 0, n - 1 do + local q = i * bpp + local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2) + local a = if hasA then readu8(px, q + 3) else 255 + if r == pr and g == pg and b == pb and a == pa then + run += 1 + if run == 62 or i == n - 1 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + else + if run > 0 then + writeu8(out, o, 0xC0 + run - 1) + o += 1 + run = 0 + end + local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + local hq = h * 4 + if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then + writeu8(out, o, h) + o += 1 + else + writeu8(index, hq, r) + writeu8(index, hq + 1, g) + writeu8(index, hq + 2, b) + writeu8(index, hq + 3, a) + if a == pa then + local dr = (r - pr + 128) % 256 - 128 + local dg = (g - pg + 128) % 256 - 128 + local db = (b - pb + 128) % 256 - 128 + local dgr, dgb = dr - dg, db - dg + if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then + writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2) + o += 1 + elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then + writeu8(out, o, 0x80 + dg + 32) + writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8) + o += 2 + else + writeu8(out, o, 0xFE) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + o += 4 + end + else + writeu8(out, o, 0xFF) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + writeu8(out, o + 4, a) + o += 5 + end + end + pr, pg, pb, pa = r, g, b, a + end + end + return o +end + +return Codec +end +__FILES["image/sgi"] = function() + +-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" +-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) +-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 +-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is +-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / +-- colour-map files (colormap field 1..3: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Sgi = { + name = "sgi", + category = "image", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- rgba16 for 2-byte files (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + rle: boolean?, -- RLE storage (default true) + name: string?, -- the image name (up to 79 bytes; default meta.text.name) +} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sgi.sniff(r: Bytes.Reader): number + if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then + return 0 + end + local st, bpc = r:peekU8(2), r:peekU8(3) + return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 512 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if be16(b, o) ~= 474 then + return nil, Err.new(Err.CORRUPT, "not an SGI image", o) + end + local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4) + local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10) + if dim == 1 then + h, z = 1, 1 + elseif dim == 2 then + z = 1 + end + if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then + return nil, Err.new(Err.CORRUPT, "bad header", o + 2) + end + if z > 4 then + return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10) + end + local cmap = be32(b, o + 104) + if cmap ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel planes as 16-bit samples (8-bit values scaled * 257) + local plane = buffer.create(w * h * z * 2) + local truncated = false + local function put(c: number, row: number, x: number, v: number) + buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v) + end + if rle == 0 then + local need = w * h * z * bpc + local p = o + 512 + local avail = math.min(need, limit - p) + truncated = avail < need + for i = 0, avail // bpc - 1 do + local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2) + buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v) + end + else + local n = h * z + if o + 512 + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512) + end + for c = 0, z - 1 do + for row = 0, h - 1 do + local i = c * h + row + local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4) + local p = o + start + local stop = math.min(limit, p + len) + local x = 0 + while x < w and p + bpc <= stop do + local cnt = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + local count = bit32.band(cnt, 0x7F) + if count == 0 then + break + end + if bit32.band(cnt, 0x80) ~= 0 then + for _ = 1, count do + if x >= w or p + bpc > stop then + break + end + put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p)) + p += bpc + x += 1 + end + else + if p + bpc > stop then + break + end + local v = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + for _ = 1, count do + if x >= w then + break + end + put(c, row, x, v) + x += 1 + end + end + end + if x < w then + truncated = true + end + end + end + end + local wide = opts and opts.native and bpc == 2 + local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8") + local px = img.pixels + for y = 0, h - 1 do + local row = h - 1 - y + for x = 0, w - 1 do + local function s(c: number): number + return buffer.readu16(plane, ((c * h + row) * w + x) * 2) + end + local rr: number = s(0) + local gg: number = if z >= 3 then s(1) else rr + local bb: number = if z >= 3 then s(2) else rr + local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535 + local d = (y * w + x) + if wide then + buffer.writeu16(px, d * 8, rr) + buffer.writeu16(px, d * 8 + 2, gg) + buffer.writeu16(px, d * 8 + 4, bb) + buffer.writeu16(px, d * 8 + 6, aa) + else + buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216) + end + end + end + local name = buffer.readstring(b, o + 24, 80) + local zpos = string.find(name, "\0", 1, true) + name = if zpos then string.sub(name, 1, zpos - 1) else name + if name ~= "" then + img.meta.text = { name = name } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local wide = img.format == "rgba16" + local bpc = if wide then 2 else 1 + local px = img.pixels + local function sample(x: number, y: number, c: number): number + local i = (y * w + x) * 4 + c + return if wide then buffer.readu16(px, i * 2) else readu8(px, i) + end + local z = 3 + for i = 0, w * h - 1 do + if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then + z = 4 + break + end + end + local rle = not (opts and opts.rle == false) + local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8) + out:u16be(474) + out:u8(if rle then 1 else 0) + out:u8(bpc) + out:u16be(3) + out:u16be(w) + out:u16be(h) + out:u16be(z) + out:u32be(0) + out:u32be(if wide then 65535 else 255) + out:u32be(0) + local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or "" + name = string.sub(name, 1, 79) + out:string(name) + out:fill(0, 80 - #name) + out:u32be(0) + out:fill(0, 404) + local function put(v: number) + if wide then + out:u16be(v) + else + out:u8(v) + end + end + if not rle then + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + for x = 0, w - 1 do + put(sample(x, y, c)) + end + end + end + return out:finish(), nil + end + local tables = out:tell() + out:fill(0, h * z * 8) + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + local start = out:tell() + local x = 0 + while x < w do + -- a run of equal samples (>= 3) or literals up to the next run + local v = sample(x, y, c) + local run = 1 + while x + run < w and run < 127 and sample(x + run, y, c) == v do + run += 1 + end + if run >= 3 then + put(run) + put(v) + x += run + else + local lit = 0 + while x + lit < w and lit < 127 do + local a = sample(x + lit, y, c) + if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + put(0x80 + lit) + for k = 0, lit - 1 do + put(sample(x + k, y, c)) + end + x += lit + end + end + put(0) + local i = c * h + row + out:setU32be(tables + i * 4, start) + out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start) + end + end + return out:finish(), nil +end + +return Sgi +end +__FILES["image/sunras"] = function() + +-- image/sunras: Sun Raster (rasterfile(5), SunOS ; new code). Decode: 1-bit (0 = white without a colour +-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, +-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in +-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the +-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), +-- raw colour maps (RMT_RAW is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Sunras = { + name = "sunras", + category = "image", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD +} + +local MAGIC = "\89\166\106\149" +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sunras.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 32 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a Sun raster", o) + end + local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, "bad size", o + 4) + end + if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12) + end + if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then + return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local p = o + 32 + if p + maplen > limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local pal = buffer.create(1024) + local ncol = 0 + if maptype == 1 and maplen > 0 then + ncol = math.min(256, maplen // 3) + for i = 0, ncol - 1 do + buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000) + end + elseif depth == 1 then + buffer.writeu32(pal, 0, 0xFFFFFFFF) + buffer.writeu32(pal, 4, 0xFF000000) + else + for i = 0, 255 do + buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000) + end + end + p += maplen + local stride = ((w * depth + 15) // 16) * 2 + local total = stride * h + local raw = buffer.create(total + 4) + local truncated = false + if typ == 2 then + local q = 0 + while q < total and p < limit do + local c = readu8(b, p) + p += 1 + if c ~= 0x80 then + buffer.writeu8(raw, q, c) + q += 1 + else + if p >= limit then + break + end + local n = readu8(b, p) + p += 1 + if n == 0 then + buffer.writeu8(raw, q, 0x80) + q += 1 + else + if p >= limit then + break + end + local cnt = math.min(n + 1, total - q) + buffer.fill(raw, q, readu8(b, p), cnt) + p += 1 + q += cnt + end + end + end + truncated = q < total + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if depth <= 8 then + Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal) + else + local rgb = typ == 3 + local bytes = depth // 8 + local alpha = false + if bytes == 4 then + for y = 0, h - 1 do + for x = 0, w - 1 do + if readu8(raw, y * stride + x * 4) ~= 0 then + alpha = true + end + end + end + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local s = y * stride + x * bytes + local a = 255 + if bytes == 4 then + a = if alpha then readu8(raw, s) else 255 + s += 1 + end + local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0 + buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216) + end + end + end + if ncol > 0 then + local list: { { number } } = {} + for i = 0, ncol - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local px = img.pixels + local alpha = false + for i = 0, w * h - 1 do + if readu8(px, i * 4 + 3) < 255 then + alpha = true + break + end + end + local depth = if alpha then 32 else 24 + local bytes = depth // 8 + local stride = ((w * depth + 15) // 16) * 2 + local raw = buffer.create(stride * h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local s, d = (y * w + x) * 4, y * stride + x * bytes + if alpha then + buffer.writeu8(raw, d, readu8(px, s + 3)) + d += 1 + end + buffer.writeu8(raw, d, readu8(px, s + 2)) + buffer.writeu8(raw, d + 1, readu8(px, s + 1)) + buffer.writeu8(raw, d + 2, readu8(px, s)) + end + end + local rle = not (opts and opts.rle == false) + local body = raw + if rle then + local wr = Bytes.writer(stride * h) + local i, n = 0, stride * h + while i < n do + local v = readu8(raw, i) + local run = 1 + while i + run < n and run < 256 and readu8(raw, i + run) == v do + run += 1 + end + if run >= 3 or v == 0x80 then + if run == 1 then + wr:u8(0x80) + wr:u8(0) + else + wr:u8(0x80) + wr:u8(run - 1) + wr:u8(v) + end + else + for _ = 1, run do + wr:u8(v) + end + end + i += run + end + body = wr:finish() + end + local out = Bytes.writer(32 + buffer.len(body)) + out:string(MAGIC) + out:u32be(w) + out:u32be(h) + out:u32be(depth) + out:u32be(buffer.len(body)) + out:u32be(if rle then 2 else 1) + out:u32be(0) + out:u32be(0) + out:bytes(body) + return out:finish(), nil +end + +return Sunras +end +__FILES["image/tga"] = function() + +-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) +-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / +-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, +-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: +-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data +-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. +-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left +-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage +-- stamp, ...), which are ignored. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/tga/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Tga = { + name = "tga", + category = "image", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + rle: boolean?, -- run-length encode (default false) + origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands) + alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255) + id: string?, -- the image ID field (up to 255 bytes; default meta.text.id) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true } +local FOOTER = "TRUEVISION-XFILE.\0" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { + idLen: number, + cmapType: number, + imageType: number, + cmapFirst: number, + cmapLen: number, + cmapBits: number, + width: number, + height: number, + depth: number, + desc: number, +} + +local function header(r: Bytes.Reader): Header? + if r.limit - r.base < 18 then + return nil + end + local b, o = r.buf, r.base + local function u16(q: number): number + return readu8(b, o + q) + readu8(b, o + q + 1) * 256 + end + local h: Header = { + idLen = readu8(b, o), + cmapType = readu8(b, o + 1), + imageType = readu8(b, o + 2), + cmapFirst = u16(3), + cmapLen = u16(5), + cmapBits = readu8(b, o + 7), + width = u16(12), + height = u16(14), + depth = readu8(b, o + 16), + desc = readu8(b, o + 17), + } + return h +end + +-- plausible(h) -> nil | why not +local function implausible(h: Header): string? + local t = h.imageType + if not TYPES[t] then + return "image type " .. t + end + if h.cmapType > 1 then + return "colour map type " .. h.cmapType + end + local mapped = t == 1 or t == 9 + if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then + return "colour-mapped image without a colour map" + end + if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then + return "colour map entry size " .. h.cmapBits + end + if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then + return "pixel depth " .. h.depth + end + if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then + return "grey pixel depth " .. h.depth + end + if h.width == 0 or h.height == 0 then + return "zero size" + end + if h.desc >= 64 then + return "interleaving / reserved descriptor bits" + end + return nil +end + +function Tga.sniff(r: Bytes.Reader): number + local h = header(r) + if not h or implausible(h) then + return 0 + end + local n = r.limit - r.base + if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h = header(r) + if not h then + return nil, Err.new(Err.TRUNCATED, "short header", r.base) + end + local why = implausible(h) + if why then + return nil, Err.new(if h.imageType == 0 then Err.UNSUPPORTED else Err.CORRUPT, why, r.base) + end + local w, ht = h.width, h.height + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b = r.buf + local p = r.base + 18 + local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil + p += h.idLen + -- colour map + local pal = buffer.create(4) + local palN = 0 + if h.cmapType == 1 and h.cmapLen > 0 then + local eb = (h.cmapBits + 7) // 8 + if p + h.cmapLen * eb > r.limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local first = h.cmapFirst + palN = first + h.cmapLen + pal = buffer.create(palN * 4) + buffer.fill(pal, 0, 0, palN * 4) + local kind = if h.cmapBits == 24 then 3 elseif h.cmapBits == 32 then 4 else 2 + for i = 0, h.cmapLen - 1 do + buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0)) + end + for i = 0, first - 1 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + p += h.cmapLen * eb + end + local t = h.imageType + local alphaBits = h.desc % 16 + local kind + if t == 1 or t == 9 then + kind = if h.depth == 8 then 5 else 6 + elseif t == 3 or t == 11 then + kind = if h.depth == 8 then 0 else 1 + else + kind = if h.depth == 24 then 3 elseif h.depth == 32 then 4 else 2 + end + local bpp = (h.depth + 7) // 8 + local bottomUp = (h.desc // 32) % 2 == 0 + local rtl = (h.desc // 16) % 2 == 1 + local img = Types.Image.new(w, ht, "rgba8") + local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels) + local native = opts and opts.native + if native and kind == 0 then + local g = Types.Image.new(w, ht, "gray8") + for i = 0, w * ht - 1 do + buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4)) + end + img = g + elseif native and kind == 3 then + local c = Types.Image.new(w, ht, "rgb8") + for i = 0, w * ht - 1 do + buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4)) + buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2)) + end + img = c + end + if palN > 0 then + local palette = {} + for i = 0, palN - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if id then + img.meta.text = { id = id } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "tga", + bitDepth = h.depth, + colorType = if kind >= 5 then "palette" elseif kind <= 1 then (if kind == 1 then "graya" else "gray") else (if kind == 3 then "rgb" else "rgba"), + rle = t >= 9, + origin = (if bottomUp then "bottom" else "top") .. "-" .. (if rtl then "right" else "left"), + alphaBits = alphaBits, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tga.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local srcBpp = if img.format == "rgba8" then 4 elseif img.format == "rgb8" then 3 elseif img.format == "gray8" then 1 else nil + if not srcBpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + local o: any = opts or {} + local origin = o.origin or "bottom-left" + if origin ~= "bottom-left" and origin ~= "top-left" then + return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"") + end + local outBpp = srcBpp + if srcBpp == 4 then + local alpha = o.alpha + if alpha == nil then + alpha = false + for i = 0, w * h - 1 do + if readu8(img.pixels, i * 4 + 3) ~= 255 then + alpha = true + break + end + end + end + outBpp = if alpha then 4 else 3 + end + local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or "" + if type(id) ~= "string" then + id = "" + end + id = string.sub(id, 1, 255) + local rle = o.rle == true + local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26) + buffer.writeu8(out, 0, #id) + buffer.writeu8(out, 2, (if outBpp == 1 then 3 else 2) + (if rle then 8 else 0)) + buffer.writeu16(out, 12, w) + buffer.writeu16(out, 14, h) + buffer.writeu8(out, 16, outBpp * 8) + buffer.writeu8(out, 17, (if outBpp == 4 then 8 else 0) + (if origin == "top-left" then 32 else 0)) + buffer.writestring(out, 18, id) + local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id) + -- TGA 2.0 footer: no extension / developer areas + buffer.writeu32(out, op, 0) + buffer.writeu32(out, op + 4, 0) + buffer.writestring(out, op + 8, FOOTER) + op += 26 + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Tga +end +__FILES["image/tga/Codec"] = @native function() + + + +-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 +-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented +-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, +-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +@native local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number + if kind == 0 then + return readu8(b, p) * 0x10101 + 0xFF000000 + elseif kind == 1 then + return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000 + elseif kind == 2 then + local v = readu16(b, p) + local r, g, bl = (v // 1024) % 32, (v // 32) % 32, v % 32 + local a = if alpha1 and v < 32768 then 0 else 255 + return (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick + elseif kind == 3 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000 + elseif kind == 4 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216 + end + local i = if kind == 5 then readu8(b, p) else readu16(b, p) + if i >= palN then + return 0xFF000000 + end + return readu32(pal, i * 4) +end +Codec.pixel = pixel + +-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? +@native function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean) + local n = w * h + local i = 0 + @native local function put(v: number) + local row, col = i // w, i % w + if bottomUp then + row = h - 1 - row + end + if rtl then + col = w - 1 - col + end + writeu32(out, (row * w + col) * 4, v) + i += 1 + end + if not rle then + local avail = math.min(n, (limit - p) // bpp) + for _ = 1, avail do + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + return i, avail < n + end + while i < n do + if p >= limit then + return i, true + end + local hd = readu8(b, p) + p += 1 + local count = hd % 128 + 1 + if hd >= 128 then + if p + bpp > limit then + return i, true + end + local v = pixel(b, p, kind, alpha1, pal, palN) + p += bpp + for _ = 1, math.min(count, n - i) do + put(v) + end + else + for _ = 1, math.min(count, n - i) do + if p + bpp > limit then + return i, true + end + put(pixel(b, p, kind, alpha1, pal, palN)) + p += bpp + end + end + end + return i, false +end + +-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); +-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. +-- out needs room for w * h * (outBpp + 1) bytes. +@native function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number + @native local function get(q: number): number + if srcBpp == 1 then + return readu8(px, q) + elseif srcBpp == 3 then + return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000 + end + return readu32(px, q) + end + @native local function emit(v: number) + if outBpp == 1 then + writeu8(out, o, v % 256) + else + writeu8(out, o, (v // 65536) % 256) + writeu8(out, o + 1, (v // 256) % 256) + writeu8(out, o + 2, v % 256) + if outBpp == 4 then + writeu8(out, o + 3, v // 16777216) + end + end + o += outBpp + end + for y = 0, h - 1 do + local row = if topDown then y else h - 1 - y + local base = row * w * srcBpp + if not rle then + for x = 0, w - 1 do + emit(get(base + x * srcBpp)) + end + else + local x = 0 + while x < w do + local v = get(base + x * srcBpp) + local run = 1 + while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do + run += 1 + end + if run >= 2 then + writeu8(out, o, 127 + run) + o += 1 + emit(v) + x += run + else + -- a raw packet up to the next run of 2 or more + local s = x + local cnt = 0 + while x < w and cnt < 128 do + local c = get(base + x * srcBpp) + if x + 1 < w and get(base + (x + 1) * srcBpp) == c then + break + end + cnt += 1 + x += 1 + end + writeu8(out, o, cnt - 1) + o += 1 + for k = s, s + cnt - 1 do + emit(get(base + k * srcBpp)) + end + end + end + end + end + return o +end + +return Codec +end +__FILES["image/tiff"] = function() + +-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. +-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / +-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's +-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), +-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, +-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as +-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard +-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). +-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / +-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. +-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Lzw = __include("codecs/compress/Lzw") +local Pixels = __include("image/tiff/Pixels") +local PackBits = __include("codecs/compress/PackBits") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiff = { + name = "tiff", + category = "image", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8 + maxPixels: number?, -- per page (default 2^26) + maxPages: number?, -- pages decoded into img.frames (default 1024) + page: number?, -- decode only this page (1-based) + decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages +} +type EncodeOptions = { + compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate" + predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true) + level: number?, -- deflate level 0..9 (default 6) + rowsPerStrip: number?, -- default: about 64 KB per strip +} + +-- ------------------------------------------------------------------------------------------------ constants +local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 } +local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" } +local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" } +local TWO32 = 4294967296 + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Tiff.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Entry = { tag: number, typ: number, count: number, at: number } +type Ctx = { b: buffer, base: number, limit: number, le: boolean, big: boolean } + +local function u16(c: Ctx, at: number): number + if at < c.base or at + 2 > c.limit then + return 0 + end + return if c.le then readu16(c.b, at) else readu8(c.b, at) * 256 + readu8(c.b, at + 1) +end +local function u32(c: Ctx, at: number): number + if at < c.base or at + 4 > c.limit then + return 0 + end + local v = readu32(c.b, at) + return if c.le then v else bit32.byteswap(v) +end +local function u64(c: Ctx, at: number): number + local lo, hi = u32(c, at), u32(c, at + 4) + if not c.le then + lo, hi = hi, lo + end + return hi * TWO32 + lo +end +local function off(c: Ctx, at: number): number + return if c.big then u64(c, at) else u32(c, at) +end + +-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many +local function values(c: Ctx, e: Entry?, max: number?): { number }? + if not e then + return nil + end + local size = TYPE_SIZE[e.typ] + if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then + return nil + end + local out = table.create(e.count, 0) + local b = c.b + for i = 0, e.count - 1 do + local p = e.at + i * size + local t = e.typ + local v + if t == 1 or t == 2 or t == 7 then + v = readu8(b, p) + elseif t == 6 then + v = buffer.readi8(b, p) + elseif t == 3 then + v = u16(c, p) + elseif t == 8 then + v = u16(c, p) + if v >= 32768 then + v -= 65536 + end + elseif t == 4 or t == 13 then + v = u32(c, p) + elseif t == 9 then + v = u32(c, p) + if v >= 2147483648 then + v -= TWO32 + end + elseif t == 5 or t == 10 then + local n, d = u32(c, p), u32(c, p + 4) + if t == 10 then + if n >= 2147483648 then + n -= TWO32 + end + if d >= 2147483648 then + d -= TWO32 + end + end + v = if d ~= 0 then n / d else 0 + elseif t == 11 then + v = Pixels.f32(u32(c, p)) + elseif t == 12 then + local lo, hi = u32(c, p), u32(c, p + 4) + if not c.le then + lo, hi = hi, lo + end + v = Pixels.f64(lo, hi) + else + v = u64(c, p) + end + out[i + 1] = v + end + return out +end + +local function one(c: Ctx, e: Entry?, default: number): number + local v = values(c, e, 64) + return if v and v[1] then v[1] else default +end + +-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err +local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?) + local esize = if c.big then 20 else 12 + local hsize = if c.big then 8 else 2 + if p < c.base or p + hsize > c.limit then + return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p) + end + local n = if c.big then u64(c, p) else u16(c, p) + if n == 0 or p + hsize + n * esize > c.limit then + return nil, 0, Err.new(if n == 0 then Err.CORRUPT else Err.TRUNCATED, "bad IFD entry count " .. n, p) + end + local entries: { [number]: Entry } = {} + for i = 0, n - 1 do + local q = p + hsize + i * esize + local tag, typ = u16(c, q), u16(c, q + 2) + local count = if c.big then u64(c, q + 4) else u32(c, q + 4) + local vat = q + (if c.big then 12 else 8) + local size = TYPE_SIZE[typ] + if size then + local at = vat + if count * size > (if c.big then 8 else 4) then + at = c.base + off(c, vat) + end + entries[tag] = { tag = tag, typ = typ, count = count, at = at } + end + end + local nq = p + hsize + n * esize + local nextOff = 0 + if nq + (if c.big then 8 else 4) <= c.limit then + nextOff = off(c, nq) + end + return entries, if nextOff > 0 then c.base + nextOff else 0, nil +end + +local function bytesOf(c: Ctx, e: Entry?, max: number): buffer? + if not e or e.at < c.base then + return nil + end + local size = TYPE_SIZE[e.typ] or 1 + local n = e.count * size + if n > max or e.at + n > c.limit then + return nil + end + local x = buffer.create(n) + buffer.copy(x, 0, c.b, e.at, n) + return x +end + +-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err +local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?) + if p < c.base or len < 0 or p + len > c.limit then + -- a chunk past the end: keep what exists (truncated files) + len = math.max(0, math.min(len, c.limit - p)) + if p < c.base or p >= c.limit then + return 0, nil + end + end + local src, sp = c.b, p + if rev then + src = buffer.create(len) + buffer.copy(src, 0, c.b, p, len) + Pixels.reverseBits(src, 0, len) + sp = 0 + end + if comp == 1 then + local n = math.min(len, size) + buffer.copy(out, o, src, sp, n) + return n, nil + elseif comp == 5 then + local n = Lzw.decode(src, sp, len, out, o, size, "tiff") + return n, nil + elseif comp == 8 or comp == 32946 then + local raw = Deflate.zlib(src, sp, len, size) + if not raw then + raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len) + end + if not raw then + return nil, Err.new(Err.CORRUPT, "bad deflate data", p) + end + local n = math.min(buffer.len(raw :: buffer), size) + buffer.copy(out, o, raw :: buffer, 0, n) + return n, nil + elseif comp == 32773 then + return (PackBits.decode(src, sp, sp + len, out, o, size)), nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) +end + +type Page = { image: Types.Image, info: { [string]: any } } + +local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local w, h = one(c, t[256], 0), one(c, t[257], 0) + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local spp = one(c, t[277], 1) + local bpsList = values(c, t[258], 64) or { 1 } + local bps = bpsList[1] or 1 + for i = 2, math.min(#bpsList, spp) do + if bpsList[i] ~= bps then + return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample") + end + end + local comp = one(c, t[259], 1) + local photo = one(c, t[262], if spp >= 3 then 2 else 1) + local planar = one(c, t[284], 1) + local predictor = one(c, t[317], 1) + local sfmt = one(c, t[339], 1) + local fill = one(c, t[266], 1) + if spp < 1 or spp > 16 or bps < 1 or bps > 64 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps)) + end + if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats") + end + if sfmt ~= 3 and bps > 32 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers") + end + if not COMPRESSION[comp] then + local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" } + return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")") + end + if not PHOTOMETRIC[photo] then + return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo) + end + local cc = if photo == 2 or photo == 6 then 3 elseif photo == 5 then 4 else 1 + if spp < cc then + return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo)) + end + if photo == 5 and one(c, t[332], 1) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK") + end + local extra = values(c, t[338], 16) or {} + local alpha, assoc = -1, false + if spp > cc then + local kind = extra[1] or 0 + alpha = cc + assoc = kind == 1 + end + local chunky = planar ~= 2 or spp == 1 + local tiled = t[322] ~= nil + local cw = if tiled then one(c, t[322], 0) else w + local ch = if tiled then one(c, t[323], 0) else math.min(one(c, t[278], h), h) + if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then + return nil, Err.new(Err.CORRUPT, "bad tile / strip size") + end + if ch > h and not tiled then + ch = h + end + local pspp = if chunky then spp else 1 -- samples per pixel in one plane + local nplanes = if chunky then 1 else spp + local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane + local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") + end + local across = if tiled then math.ceil(w / cw) else 1 + local down = math.ceil(h / ch) + local perPlane = across * down + local offs = values(c, if tiled then t[324] else t[273], 2 ^ 24) + local lens = values(c, if tiled then t[325] else t[279], 2 ^ 24) + if not offs or #offs < perPlane * nplanes then + return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") + end + local planes: { buffer } = table.create(nplanes) :: { buffer } + for i = 1, nplanes do + planes[i] = buffer.create(rb * h + 8) + end + local tmp = buffer.create(crb * ch + 8) + local ftmp = buffer.create(math.max(rb, crb) + 8) + local le = c.le + local bytesPer = bps // 8 + local hook = opts and opts.decodeImage + local jpegTables = if comp == 7 then bytesOf(c, t[347], 1 * 2 ^ 20) else nil + local jpegPixels: buffer? = nil + if comp == 7 then + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)") + end + jpegPixels = buffer.create(w * h * 4) + end + for pl = 0, nplanes - 1 do + for ty = 0, down - 1 do + for tx = 0, across - 1 do + local idx = pl * perPlane + ty * across + tx + local p = c.base + offs[idx + 1] + local len = if lens and lens[idx + 1] then lens[idx + 1] else c.limit - p + local rows = if tiled then ch else math.min(ch, h - ty * ch) + local size = rows * crb + if comp == 7 then + -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI + if p < c.base or p + len > c.limit or len < 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p) + end + local tl = if jpegTables and buffer.len(jpegTables) >= 4 then buffer.len(jpegTables) - 2 else 0 + local s = buffer.create(tl + len - (if tl > 0 then 2 else 0)) + if tl > 0 then + buffer.copy(s, 0, jpegTables :: buffer, 0, tl) + buffer.copy(s, tl, c.b, p + 2, len - 2) + else + buffer.copy(s, 0, c.b, p, len) + end + local ok, img, herr = pcall(hook :: any, s) + if not ok or type(img) ~= "table" or img.format ~= "rgba8" then + return nil, if ok and herr then herr else Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring(if ok then herr else img)) + end + local x0, y0 = tx * cw, ty * ch + local cwid = math.min(cw, w - x0, img.width) + for yy = 0, math.min(rows, h - y0, img.height) - 1 do + buffer.copy(jpegPixels :: buffer, ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4) + end + continue + end + buffer.fill(tmp, 0, 0, size) + local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2) + if derr then + return nil, derr + end + if predictor == 2 then + Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le) + elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then + Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) + end + -- into the plane + local plane = planes[pl + 1] + local x0b = math.floor(tx * cw * pspp * bps / 8) + local cols = math.min(cw, w - tx * cw) + local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b) + for yy = 0, rows - 1 do + local y = ty * ch + yy + if y >= h then + break + end + buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb) + end + end + end + end + local floatOut = sfmt == 3 + if predictor == 3 and floatOut then + le = true -- fpAcc leaves the samples little endian + end + local colorType = PHOTOMETRIC[photo] + -- the output layout + local kind = "rgba8" + if opts and opts.native and comp ~= 7 then + if photo == 3 or photo == 5 then + kind = "rgba8" + elseif floatOut then + kind = "rgbaf32" + elseif cc == 1 then + if alpha >= 0 then + kind = if bps <= 8 then "graya8" else "rgba16" + else + kind = if bps <= 8 then "gray8" else "gray16" + end + else + if alpha >= 0 then + kind = if bps <= 8 then "rgba8" else "rgba16" + else + kind = if bps <= 8 then "rgb8" else "rgba16" + end + end + end + local img = Types.Image.new(w, h, kind :: any) + if comp == 7 then + img.pixels = jpegPixels :: buffer + else + if photo == 6 then + return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr") + end + local cmap = nil + if photo == 3 then + local n = 3 * 2 ^ math.min(bps, 16) + local cv = values(c, t[320], n) + if not cv or #cv < n then + return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap") + end + cmap = buffer.create(n * 2) + for i = 1, n do + buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535)) + end + end + Pixels.convert({ + planes = planes, + rb = rb, + chunky = chunky, + w = w, + h = h, + spp = spp, + bps = bps, + sfmt = sfmt, + le = le, + photo = photo, + alpha = alpha, + assoc = assoc, + cmap = cmap, + kind = kind, + out = img.pixels, + }) + end + local xr, yr = one(c, t[282], 0), one(c, t[283], 0) + if xr > 0 and yr > 0 then + local unit = one(c, t[296], 2) + local k = if unit == 3 then 2.54 else 1 + if unit ~= 1 then + img.meta.dpi = { x = xr * k, y = yr * k } + end + end + img.meta.icc = bytesOf(c, t[34675], 2 ^ 26) + local function ascii(tag: number): string? + local v = bytesOf(c, t[tag], 65536) + if not v then + return nil + end + local s = buffer.tostring(v) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local text = {} + for tag, key in { [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" } do + local s = ascii(tag) + if s and s ~= "" then + text[key] = s + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { + format = "tiff", + bitDepth = bps, + colorType = colorType, + photometric = photo, + samples = spp, + sampleFormat = if sfmt == 3 then "float" elseif sfmt == 2 then "int" else "uint", + compression = COMPRESSION[comp], + predictor = predictor, + planar = planar, + tiled = tiled, + alpha = if alpha >= 0 then (if assoc then "associated" else "unassociated") else nil, + bigtiff = c.big, + byteOrder = if c.le then "II" else "MM", + } + return img, nil +end + +-- pages(r) -> the IFD tables of every page (and the context) | nil, Err +local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 then + return nil, nil, Err.new(Err.TRUNCATED, "short header") + end + local bo = buffer.readstring(b, base, 2) + if bo ~= "II" and bo ~= "MM" then + return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark") + end + local c: Ctx = { b = b, base = base, limit = limit, le = bo == "II", big = false } + local magic = u16(c, base + 2) + local first + if magic == 42 then + first = u32(c, base + 4) + elseif magic == 43 then + if limit - base < 16 or u16(c, base + 4) ~= 8 then + return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header") + end + c.big = true + first = u64(c, base + 8) + else + return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic) + end + local list = {} + local seen = {} + local p = base + first + while p > 0 and #list < maxPages do + if seen[p] then + break -- an IFD loop + end + seen[p] = true + local t, nextP, err = readIfd(c, p) + if not t then + if #list == 0 then + return nil, nil, err + end + break + end + table.insert(list, t) + p = nextP + end + return list, c, nil +end + +-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err +function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?) + local list, c, err = pages(r, 1024) + if not list or not c then + return nil, err + end + local t = list[1] + return { + pages = #list, + width = one(c, t[256], 0), + height = one(c, t[257], 0), + bitDepth = one(c, t[258], 1), + samples = one(c, t[277], 1), + compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)), + photometric = PHOTOMETRIC[one(c, t[262], 1)], + bigtiff = c.big, + }, + nil +end + +function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local maxPages = opts and opts.maxPages or 1024 + local list, c, err = pages(r, if opts and opts.page then math.max(1, opts.page) else maxPages) + if not list or not c then + return nil, err + end + if opts and opts.page then + local t = list[opts.page] + if not t then + return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page)) + end + local img, perr = decodePage(c, t, opts) + if img then + (img.meta.source :: { [string]: any }).pages = #list + end + return img, perr + end + local first: Types.Image? = nil + local frames = {} + for i, t in list do + -- reduced-resolution subfiles (thumbnails) after page 1 are skipped + local sub = one(c, t[254], 0) + if i > 1 and bit32.band(sub, 1) ~= 0 then + continue + end + local img, perr = decodePage(c, t, opts) + if not img then + if i == 1 then + return nil, perr + end + continue + end + if not first then + first = img + end + table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) + end + local img = first :: Types.Image + (img.meta.source :: { [string]: any }).pages = #frames + if #frames > 1 then + img.frames = frames :: any + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- layout per pixel format: samples, bits, sample format, photometric, extra samples +local LAYOUT = { + gray8 = { 1, 8, 1, 1 }, + graya8 = { 2, 8, 1, 1 }, + gray16 = { 1, 16, 1, 1 }, + rgb8 = { 3, 8, 1, 2 }, + rgba8 = { 4, 8, 1, 2 }, + rgba16 = { 4, 16, 1, 2 }, + rgbaf32 = { 4, 32, 3, 2 }, +} +local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 } + +type Tag = { tag: number, typ: number, vals: { number }?, data: buffer? } + +local function encodePage(img: Types.Image, o: EncodeOptions, comp: number): ({ Tag }?, { buffer }?, Err.Err?) + local L = LAYOUT[img.format] + if not L then + return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h = img.width, img.height + local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4] + local rb = w * spp * bps // 8 + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then + return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local rps = o.rowsPerStrip or math.max(1, 65536 // rb) + if type(rps) ~= "number" or rps < 1 then + return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1") + end + rps = math.min(math.floor(rps), h) + local predictor = 1 + if (comp == 8 or comp == 5) and o.predictor ~= false then + predictor = if sfmt == 3 then 3 else 2 + end + local strips = {} + local tmp = buffer.create(rb + 8) + for y0 = 0, h - 1, rps do + local rows = math.min(rps, h - y0) + local raw = buffer.create(rows * rb) + buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb) + if predictor == 2 then + Pixels.predict2(raw, 0, rows, rb, spp, bps) + elseif predictor == 3 then + Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp) + end + local out + if comp == 1 then + out = raw + elseif comp == 8 then + out = Deflate.zlibCompress(raw, { level = o.level or 6 }) :: buffer + elseif comp == 5 then + out = Lzw.encode(raw, 0, rows * rb, "tiff") + else + local parts, total = {}, 0 + for r = 0, rows - 1 do + local p = PackBits.encode(raw, r * rb, rb) + table.insert(parts, p) + total += buffer.len(p) + end + out = buffer.create(total) + local q = 0 + for _, p in parts do + buffer.copy(out, q, p) + q += buffer.len(p) + end + end + table.insert(strips, out) + end + local bpsv = table.create(spp, bps) + local tags: { Tag } = { + { tag = 254, typ = 4, vals = { 0 } }, + { tag = 256, typ = 4, vals = { w } }, + { tag = 257, typ = 4, vals = { h } }, + { tag = 258, typ = 3, vals = bpsv }, + { tag = 259, typ = 3, vals = { comp } }, + { tag = 262, typ = 3, vals = { photo } }, + { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched + { tag = 277, typ = 3, vals = { spp } }, + { tag = 278, typ = 4, vals = { rps } }, + { tag = 279, typ = 4, vals = table.create(#strips, 0) }, + { tag = 284, typ = 3, vals = { 1 } }, + } + for i, s in strips do + (tags[10].vals :: { number })[i] = buffer.len(s) + end + local dpi = img.meta and img.meta.dpi + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } }) + table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } }) + table.insert(tags, { tag = 296, typ = 3, vals = { 2 } }) + end + if predictor > 1 then + table.insert(tags, { tag = 317, typ = 3, vals = { predictor } }) + end + if spp == 2 or spp == 4 then + table.insert(tags, { tag = 338, typ = 3, vals = { 2 } }) + end + if sfmt ~= 1 then + table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) }) + end + local icc = img.meta and img.meta.icc + if type(icc) == "buffer" then + table.insert(tags, { tag = 34675, typ = 7, data = icc }) + end + local text = img.meta and img.meta.text + if type(text) == "table" then + for key, tag in { description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 } :: { [string]: number } do + if type(text[key]) == "string" then + table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) + end + end + end + table.sort(tags, function(a: Tag, b: Tag): boolean + return a.tag < b.tag + end) + return tags, strips, nil +end + +function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o: EncodeOptions = opts or {} + local comp = COMP_CODES[o.compression or "deflate"] + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits") + end + local list = { img } + if type(img.frames) == "table" and #img.frames > 1 then + list = {} + for _, f in img.frames :: any do + if type(f) ~= "table" or type(f.image) ~= "table" then + return nil, Err.new(Err.ARG, "bad frame") + end + table.insert(list, f.image) + end + end + local w = Bytes.writer(1024) + w:string("II") + w:u16le(42) + w:u32le(0) -- first IFD, patched + local prevNext = 4 + for _, page in list do + local tags, strips, err = encodePage(page, o, comp) + if not tags or not strips then + return nil, err + end + -- strip data first + local soffs = {} + for i, s in strips do + if w:tell() % 2 == 1 then + w:u8(0) + end + soffs[i] = w:tell() + w:bytes(s) + end + for _, tg in tags do + if tg.tag == 273 then + tg.vals = soffs + end + end + -- out-of-line values + local valOff: { [number]: number } = {} + for i, tg in tags do + local size = TYPE_SIZE[tg.typ] + local n = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) * size + if n > 4 then + if w:tell() % 2 == 1 then + w:u8(0) + end + valOff[i] = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + elseif tg.typ == 4 then + w:u32le(v) + elseif tg.typ == 5 then + w:u32le(math.floor(v * 10000 + 0.5)) + w:u32le(10000) + end + end + end + end + end + if w:tell() % 2 == 1 then + w:u8(0) + end + local ifd = w:tell() + w:setU32le(prevNext, ifd) + w:u16le(#tags) + for i, tg in tags do + local count = if tg.data then buffer.len(tg.data :: buffer) else #(tg.vals :: { number }) + w:u16le(tg.tag) + w:u16le(tg.typ) + w:u32le(count) + if valOff[i] then + w:u32le(valOff[i]) + else + local start = w:tell() + if tg.data then + w:bytes(tg.data :: buffer) + else + for _, v in tg.vals :: { number } do + if tg.typ == 3 then + w:u16le(v) + else + w:u32le(v) + end + end + end + w:fill(0, 4 - (w:tell() - start)) + end + end + prevNext = w:tell() + w:u32le(0) + end + return w:finish(), nil +end + +return Tiff +end +__FILES["image/tiff/Pixels"] = @native function() + + + +-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and +-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's +-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. +-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +local Bytes = __include("core/Bytes") +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 +local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Pixels = {} + +local scratch = buffer.create(8) + +-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an +-- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +@native local function f32(bits: number): number + if band(bits, 0x7F800000) == 0x7F800000 then + if band(bits, 0x7FFFFF) ~= 0 then + return 0 / 0 + end + return if bits >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, bits) + return readf32(scratch, 0) +end +@native local function f64(lo: number, hi: number): number + if band(hi, 0x7FF00000) == 0x7FF00000 then + if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then + return 0 / 0 + end + return if hi >= 0x80000000 then -math.huge else math.huge + end + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end +Pixels.f32 = f32 +Pixels.f64 = f64 + +-- ------------------------------------------------------------------------------------------------ fill order +local REV = buffer.create(256) +for i = 0, 255 do + local r = 0 + for k = 0, 7 do + if band(i, lshift(1, k)) ~= 0 then + r = bor(r, lshift(1, 7 - k)) + end + end + writeu8(REV, i, r) +end +@native function Pixels.reverseBits(b: buffer, off: number, len: number) + for i = off, off + len - 1 do + writeu8(b, i, readu8(REV, readu8(b, i))) + end +end + +-- ------------------------------------------------------------------------------------------------ predictors +-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) +@native function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + elseif bps == 16 then + local n = rb // 2 + for k = stride, n - 1 do + local i = base + k * 2 + local j = i - stride * 2 + if le then + writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF)) + else + local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1) + writeu8(b, i, band(rshift(v, 8), 255)) + writeu8(b, i + 1, band(v, 255)) + end + end + elseif bps == 32 then + local n = rb // 4 + for k = stride, n - 1 do + local i = base + k * 4 + local j = i - stride * 4 + if le then + writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296) + else + writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296)) + end + end + end + end +end + +-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) +@native function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + elseif bps == 16 then + for k = rb // 2 - 1, stride, -1 do + local i = base + k * 2 + writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF)) + end + end + end +end + +-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little +-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +@native function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + buffer.copy(tmp, 0, b, base, rb) + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c)) + end + end + end +end + +-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) +@native function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer) + local wc = rb // bytes + for r = 0, rows - 1 do + local base = off + r * rb + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k)) + end + end + buffer.copy(b, base, tmp, 0, rb) + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ samples +local half = Bytes.half + +type Params = { + planes: { buffer }, + rb: number, -- bytes per row in each plane + chunky: boolean, + w: number, + h: number, + spp: number, + bps: number, + sfmt: number, -- 1 uint, 2 int, 3 float + le: boolean, + photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK + alpha: number, -- sample index of the alpha channel, -1 = none + assoc: boolean, -- premultiplied alpha (undone) + cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block) + kind: string, -- the output pixel format + out: buffer, +} + +-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them +@native local function fast(P: Params): boolean + if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then + return false + end + local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out + local o = 0 + if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then + local four = kind == "rgba8" + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + writeu8(out, o, readu8(b, p)) + writeu8(out, o + 1, readu8(b, p + 1)) + writeu8(out, o + 2, readu8(b, p + 2)) + if four then + writeu8(out, o + 3, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 4 + else + o += 3 + end + p += spp + end + end + return true + elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then + local inv = if P.photo == 0 then 255 else 0 + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + local v = math.abs(inv - readu8(b, p)) + if kind == "gray8" then + writeu8(out, o, v) + o += 1 + elseif kind == "graya8" then + writeu8(out, o, v) + writeu8(out, o + 1, if alpha >= 0 then readu8(b, p + alpha) else 255) + o += 2 + else + writeu32(out, o, v * 0x10101 + (if alpha >= 0 then readu8(b, p + alpha) else 255) * 0x1000000) + o += 4 + end + p += spp + end + end + return true + end + return false +end + +-- convert(P): every pixel into P.out in P.kind's layout +@native function Pixels.convert(P: Params) + if fast(P) then + return + end + local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le + local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out + local maxv = 2 ^ math.min(bps, 32) - 1 + local float = sfmt == 3 + local signed = sfmt == 2 + local cmapN = 2 ^ math.min(bps, 16) + -- raw sample s of pixel x in the row starting at byte ro of its plane + @native local function raw(s: number, x: number, row: number): number + local b, i + if chunky then + b, i = planes[1], x * spp + s + else + b, i = planes[s + 1], x + end + local ro = row * rb + if bps == 8 then + local v = readu8(b, ro + i) + return if signed then (v + 128) % 256 else v + elseif bps == 16 then + local p = ro + i * 2 + local v = if le then readu16(b, p) else readu8(b, p) * 256 + readu8(b, p + 1) + if float then + return half(v) + end + return if signed then (v + 32768) % 65536 else v + elseif bps == 32 then + local p = ro + i * 4 + if float then + return f32(if le then readu32(b, p) else byteswap(readu32(b, p))) + end + local v = if le then readu32(b, p) else byteswap(readu32(b, p)) + return if signed then (v + 2147483648) % 4294967296 else v + elseif bps == 64 then + local p = ro + i * 8 + if le then + return f64(readu32(b, p), readu32(b, p + 4)) + end + return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p))) + else + -- any other depth (1..31): MSB-first bit fields + local bit = i * bps + local v = 0 + local need = bps + local p = ro + rshift(bit, 3) + local sh = band(bit, 7) + local cur = band(readu8(b, p), rshift(255, sh)) + local avail = 8 - sh + while need > 0 do + if need >= avail then + v = v * 2 ^ avail + cur + need -= avail + p += 1 + cur = if need > 0 then readu8(b, p) else 0 + avail = 8 + else + v = v * 2 ^ need + rshift(cur, avail - need) + need = 0 + end + end + return v + end + end + -- normalised 0..1 (floats as stored) + @native local function norm(s: number, x: number, row: number): number + local v = raw(s, x, row) + if float then + return v + end + return v / maxv + end + local o = 0 + local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8" + local is16 = kind == "rgba16" or kind == "gray16" + local nch = if kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" then 4 elseif kind == "rgb8" then 3 elseif kind == "graya8" then 2 else 1 + for y = 0, h - 1 do + for x = 0, w - 1 do + local r, g, bl, a + if photo == 3 then + local idx = raw(0, x, y) + if cmap and idx < cmapN then + r = readu16(cmap, idx * 2) / 65535 + g = readu16(cmap, (cmapN + idx) * 2) / 65535 + bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535 + else + r, g, bl = 0, 0, 0 + end + elseif photo == 2 then + r = norm(0, x, y) + g = norm(1, x, y) + bl = norm(2, x, y) + elseif photo == 5 then + local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y) + r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k) + else + local v = norm(0, x, y) + if photo == 0 then + v = 1 - v + end + r, g, bl = v, v, v + end + if alpha >= 0 then + a = norm(alpha, x, y) + if assoc then + if a > 0 then + r = math.min(r / a, 1) + g = math.min(g / a, 1) + bl = math.min(bl / a, 1) + else + r, g, bl = 0, 0, 0 + end + end + else + a = 1 + end + if is8 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + local R = floor(math.clamp(r, 0, 1) * 255 + 0.5) + if nch == 1 then + writeu8(out, o, R) + elseif nch == 2 then + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + else + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5)) + writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5)) + if nch == 4 then + writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + end + end + o += nch + elseif is16 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5)) + if nch == 4 then + writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5)) + end + o += nch * 2 + else + writef32(out, o, r) + writef32(out, o + 4, g) + writef32(out, o + 8, bl) + writef32(out, o + 12, a) + o += 16 + end + end + end +end + +return Pixels +end +__FILES["image/tim"] = function() + +-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation +-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. +-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit +-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 +-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when +-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. +-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image +-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque +-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Tim = { + name = "tim", + category = "image", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + clut: number?, -- the CLUT row to use for indexed images (0-based, default 0) + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + bpp: number?, -- 4, 8, 16 (default) or 24 + x: number?, -- VRAM position of the image (default 0, 0) + y: number?, + clutX: number?, -- VRAM position of the CLUT (default 0, 480) + clutY: number?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32 +local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Tim.sniff(r: Bytes.Reader): number + if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then + return 0 + end + local flags = r:peekU8(4) + if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colour(c: number): number + if c == 0 then + return 0 + end + local r, g, b = c % 32, (c // 32) % 32, (c // 1024) % 32 + r, g, b = r * 8 + r // 4, g * 8 + g // 4, b * 8 + b // 4 + return 0xFF000000 + b * 65536 + g * 256 + r +end + +function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local magic, flags = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if magic ~= 0x10 then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local pmode = flags % 8 + local bpp = BPP[pmode] + if not bpp then + return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4) + end + local stp = false + local pal: buffer? = nil + local clutInfo: any = nil + if bit32.band(flags, 8) ~= 0 then + local start = r:tell() + local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + if bnum < 12 or cw * ch * 2 > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad CLUT block", start) + end + if not r:need(cw * ch * 2) then + return nil, r.err + end + local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0)) + pal = buffer.create(256 * 4) + local p = r.pos + row * cw * 2 + for i = 0, math.min(cw, 256) - 1 do + local c = readu16(r.buf, p + i * 2) + if c >= 0x8000 then + stp = true + end + writeu32(pal :: buffer, i * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row } + r:seek(start + bnum) + if r.err then + return nil, r.err + end + elseif bpp <= 8 then + return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4) + end + local start = r:tell() + local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + local w = if bpp == 4 then iw * 4 elseif bpp == 8 then iw * 2 elseif bpp == 16 then iw else (iw * 2) // 3 + local stride = iw * 2 + if w * ih > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + if bnum < 12 or stride * ih > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad image block", start) + end + if not r:need(stride * ih) then + return nil, r.err + end + local img = Types.Image.new(w, ih) + local px, src, at = img.pixels, r.buf, r.pos + for y = 0, ih - 1 do + local row = at + y * stride + local d = y * w * 4 + if bpp == 4 then + for x = 0, w - 1 do + local v = readu8(src, row + x // 2) + local i = if x % 2 == 0 then v % 16 else v // 16 + writeu32(px, d + x * 4, readu32(pal :: buffer, i * 4)) + end + elseif bpp == 8 then + for x = 0, w - 1 do + writeu32(px, d + x * 4, readu32(pal :: buffer, readu8(src, row + x) * 4)) + end + elseif bpp == 16 then + for x = 0, w - 1 do + local c = readu16(src, row + x * 2) + if c >= 0x8000 then + stp = true + end + writeu32(px, d + x * 4, if c == 0x8000 then 0xFF000000 else colour(c % 0x8000)) + end + else + for x = 0, w - 1 do + local o = row + x * 3 + writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o)) + end + end + end + img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- rgba8 pixel -> PSX colour +local function psx(v: number): number + local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216 + if a < 128 then + return 0 + end + local c = (b // 8) * 1024 + (g // 8) * 32 + r // 8 + return if c == 0 then 0x8000 else c +end + +function Tim.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + local bpp = opts and opts.bpp or 16 + local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } :: { [number]: number })[bpp] + if not per then + return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24") + end + local iw = if bpp == 24 then (w * 3 + 1) // 2 else math.ceil(w / per) + if iw > 0xFFFF or h > 0xFFFF then + return nil, Err.new(Err.ARG, "image too wide for TIM") + end + local px = img.pixels + local out = Bytes.writer(64 + iw * 2 * h) + out:u32le(0x10) + local colours: { number } = {} + local index: { [number]: number } = {} + if bpp <= 8 then + for i = 0, w * h - 1 do + local c = psx(readu32(px, i * 4)) + if not index[c] then + table.insert(colours, c) + index[c] = #colours - 1 + if #colours > (if bpp == 4 then 16 else 256) then + return nil, Err.new(Err.ARG, "more than " .. (if bpp == 4 then 16 else 256) .. " colours for a " .. bpp .. "-bit TIM") + end + end + end + local n = if bpp == 4 then 16 else 256 + out:u32le(8 + (if bpp == 4 then 0 else 1)) + out:u32le(12 + n * 2) + out:u16le(opts and opts.clutX or 0) + out:u16le(opts and opts.clutY or 480) + out:u16le(n) + out:u16le(1) + for i = 1, n do + out:u16le(colours[i] or 0) + end + else + out:u32le(if bpp == 16 then 2 else 3) + end + out:u32le(12 + iw * 2 * h) + out:u16le(opts and opts.x or 0) + out:u16le(opts and opts.y or 0) + out:u16le(iw) + out:u16le(h) + local at = out:reserve(iw * 2 * h) + local b = out.buf + buffer.fill(b, at, 0, iw * 2 * h) + for y = 0, h - 1 do + local row = at + y * iw * 2 + for x = 0, w - 1 do + local v = readu32(px, (y * w + x) * 4) + if bpp == 4 then + local i = index[psx(v)] + local o = row + x // 2 + buffer.writeu8(b, o, buffer.readu8(b, o) + (if x % 2 == 0 then i else i * 16)) + elseif bpp == 8 then + buffer.writeu8(b, row + x, index[psx(v)]) + elseif bpp == 16 then + writeu16(b, row + x * 2, psx(v)) + else + buffer.writeu8(b, row + x * 3, v % 256) + buffer.writeu8(b, row + x * 3 + 1, (v // 256) % 256) + buffer.writeu8(b, row + x * 3 + 2, (v // 65536) % 256) + end + end + end + out.pos = at + iw * 2 * h + return out:finish(), nil +end + +return Tim +end +__FILES["image/vtf"] = function() + +-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer +-- Community "VTF (Valve Texture Format)" page; no code taken. +-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail +-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image +-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to +-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure +-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, +-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through +-- codecs/image/Texel), DXT1 (+ one-bit alpha), +-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, +-- texel, reflectivity, bumpScale }. +-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtf = { + name = "vtf", + category = "image", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + mip: number?, -- mip level (0 = full size, default) + face: number?, -- cube map face (0-based, default 0) + slice: number?, -- volume slice (0-based, default 0) + frames: boolean?, -- decode every frame into img.frames (default true) + delay: number?, -- frame delay in seconds (default 0.1) + maxPixels: number?, -- default 2^26 +} + +-- ------------------------------------------------------------------------------------------------ constants +local M = Texel.masked +-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind +local FORMATS: { [number]: any } = { + [0] = "rgba8", -- RGBA8888 + [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 + [2] = "rgb8", -- RGB888 + [3] = "bgr8", -- BGR888 + [4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it) + [5] = "l8", -- I8 + [6] = "la8", -- IA88 + [8] = "a8", -- A8 + [9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN + [10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN + [11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory) + [12] = "bgra8", -- BGRA8888 + [13] = "bc1", -- DXT1 + [14] = "bc2", -- DXT3 + [15] = "bc3", -- DXT5 + [16] = "bgrx8", -- BGRX8888 + [17] = "b5g6r5", -- BGR565: blue in the low bits + [18] = "b5g5r5x1", -- BGRX5551 + [19] = "b4g4r4a4", -- BGRA4444 + [20] = "bc1a", -- DXT1_ONEBITALPHA + [21] = "b5g5r5a1", -- BGRA5551 + [22] = "rg8", -- UV88 + [23] = "rgba8", -- UVWQ8888 + [24] = "rgba16f", -- RGBA16161616F + [25] = "rgba16", -- RGBA16161616 + [26] = "rgba8", -- UVLX8888 + [27] = "r32f", -- R32F + [28] = "rgb32f", -- RGB323232F + [29] = "rgba32f", -- RGBA32323232F + [34] = "bc5", -- ATI2N (Alien Swarm and later) + [35] = "bc4", -- ATI1N (Alien Swarm and later) + [37] = "bc5", -- ATI2N (Source 2013) + [38] = "bc4", -- ATI1N (Source 2013) +} +local BCN: { [string]: boolean } = { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true } +local NAMES: { [number]: string } = { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN", + "BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", + "DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F", + "RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" } +local ENVMAP = 0x4000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtf.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VTF\0" and r:peekU8(4) == 7 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- bytes of one w x h image in format f +local function imageSize(f: any, w: number, h: number): number + if type(f) == "string" and BCN[f] then + return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0 + end + return Texel.size(if type(f) == "table" and f.texel then f.texel else f, w, h) or 0 +end + +function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local size = r.limit - r.base + local b, base = r.buf, r.base + if size < 64 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VTF\0" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8) + if major ~= 7 or minor > 5 then + return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4) + end + local headerSize = buffer.readu32(b, base + 12) + local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18) + local flags = buffer.readu32(b, base + 20) + local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26) + local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) } + local bump = buffer.readf32(b, base + 48) + local fmtId = buffer.readi32(b, base + 52) + local mips = buffer.readu8(b, base + 56) + local lowFmt = buffer.readi32(b, base + 57) + local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62) + local depth = if minor >= 2 and size >= 65 then math.max(1, buffer.readu16(b, base + 63)) else 1 + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "zero size", 16) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local f: any = FORMATS[fmtId] + if not f then + return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52) + end + frames = math.max(1, frames) + mips = math.max(1, mips) + local faces = 1 + if bit32.band(flags, ENVMAP) ~= 0 then + faces = if minor < 5 and firstFrame ~= 0xFFFF then 7 else 6 + end + -- where the high-resolution data starts + local dataAt: number? = nil + if minor >= 3 then + if size < 80 then + return nil, Err.new(Err.TRUNCATED, "resource directory", 68) + end + local nres = buffer.readu32(b, base + 68) + if nres > 32 or 80 + nres * 8 > size then + return nil, Err.new(Err.CORRUPT, "bad resource count", 68) + end + for i = 0, nres - 1 do + local o = base + 80 + i * 8 + if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then + dataAt = buffer.readu32(b, o + 4) + end + end + if not dataAt then + return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80) + end + else + local lf = FORMATS[lowFmt] + local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0 + dataAt = headerSize + lowSize + end + -- the chain: mips smallest first; per mip: frames, faces, slices + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) + local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) + local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) + local off = dataAt :: number + for m = mips - 1, mip + 1, -1 do + local mw, mh, md = math.max(1, w // 2 ^ m), math.max(1, h // 2 ^ m), math.max(1, depth // 2 ^ m) + off += imageSize(f, mw, mh) * md * faces * frames + end + local mw, mh, md = math.max(1, w // 2 ^ mip), math.max(1, h // 2 ^ mip), math.max(1, depth // 2 ^ mip) + local one = imageSize(f, mw, mh) + local function image(frame: number): (Types.Image?, Err.Err?) + local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one + if at + one > size or at < 0 then + return nil, Err.new(Err.TRUNCATED, "image data past the end", at) + end + local img = Types.Image.new(mw, mh) + if type(f) == "string" and BCN[f] then + local kind = if f == "bc1a" then "bc1" else f + local px, e = Bcn.decode(kind, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if f == "bc1" then + -- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black + for i = 0, mw * mh - 1 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + end + else + local blue = type(f) == "table" and f.bluescreen == true + local px, e = Texel.decode(if blue then f.texel else f, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if blue then + -- pure blue is the transparent key + for i = 0, mw * mh - 1 do + if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then + buffer.writeu32(img.pixels, i * 4, 0) + end + end + end + end + return img, nil + end + local img, err = image(0) + if not img then + return nil, err + end + if frames > 1 and not (opts and opts.frames == false) then + local delay = opts and opts.delay or 0.1 + local list: { Types.Frame } = { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any } + for fr = 1, frames - 1 do + local fi, ferr = image(fr) + if not fi then + return nil, ferr + end + table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } :: any) + end + img.frames = list + img.loops = 0 + end + img.meta.source = { + format = "vtf", + version = major .. "." .. minor, + flags = flags, + frames = frames, + faces = faces, + depth = depth, + mips = mips, + texel = NAMES[fmtId], + reflectivity = refl, + bumpScale = bump, + } + return img, nil +end + +return Vtf +end +__FILES["image/webp"] = function() + +-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 +-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the +-- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. +-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw +-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the +-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or +-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif +-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and +-- metadata). +-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does), +-- alpha dithering / premultiplied output. +-- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s +-- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). +-- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vp8 = __include("codecs/image/Vp8") +local Vp8L = __include("codecs/image/Vp8L") +local Riff = __include("containers/Riff") +local Alpha = __include("image/webp/Alpha") +local Anim = __include("image/webp/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local Webp = { + name = "webp", + category = "image", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26) + native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8) + upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" = + -- dwebp -nofancy) + coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none", + -- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle) + frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas) +} + +type EncodeOptions = { + lossless: boolean?, -- must be true or nil (lossy encoding is not supported) + effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower) + exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed) + loops: number?, -- animations: play count (default img.loops; 0 = forever) + background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_MAX_PIXELS = 2 ^ 26 +local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20 + +local readu8 = buffer.readu8 + +local function u24(buf: buffer, p: number): number + return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536 +end + +local function corrupt(msg: string, offset: number?): (nil, Err.Err) + return nil, Err.new(Err.CORRUPT, msg, offset) +end + +-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT) +local function fromMessage(msg: any, offset: number?): Err.Err + if Err.is(msg) then + return msg + end + local m = tostring(msg) + for _, k in { { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } } do + if string.sub(m, 1, #k[1]) == k[1] then + return Err.new(k[2], string.sub(m, #k[1] + 1), offset) + end + end + return Err.new(Err.CORRUPT, m, offset) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Webp.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Chunk = { id: string, off: number, size: number } -- off: absolute offset of the payload + +local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?) + local out: { Chunk } = {} + for _, c in list do + if c.truncated then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset) + end + table.insert(out, { id = c.id, off = c.offset, size = c.size }) + end + return out, nil +end + +-- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size +-- must fit the data (TRUNCATED) and bytes after it are ignored. +local function readChunks(r: Bytes.Reader): ({ Chunk }?, any) + local buf, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "RIFF header", base) + end + if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then + return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base) + end + local size = buffer.readu32(buf, base + 4) + if size < 12 then + return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4) + end + if 8 + size > limit - base then + return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4) + end + local f, err = Riff.read(Bytes.reader(buf, base, 8 + size)) + if not f then + return nil, err + end + local list, cerr = convert(f.chunks) + if not list then + return nil, cerr + end + return list, f +end + +-- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) +local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) + local n = c.size - 12 + return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) +end + +type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } } + +-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk +local function findImage(chunks: { Chunk }, from: number): (Chunk?, Chunk?) + local alph: Chunk? = nil + for i = from, #chunks do + local c = chunks[i] + if c.id == "ALPH" and not alph then + alph = c + elseif c.id == "VP8 " or c.id == "VP8L" then + return c, alph + elseif c.id == "ANMF" then + break + end + end + return nil, nil +end + +local function decodeBitstream(buf: buffer, c: Chunk, alph: Chunk?, opts: DecodeOptions, allowNative: boolean): (Bitstream?, Err.Err?) + local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS + if c.id == "VP8L" then + local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels) + if not rgba then + return nil, w + end + return { rgba = rgba, w = w, h = h :: number, hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil + end + local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels }) + if not y then + return nil, u + end + local fw, fh = w :: number, h :: number + local source: { [string]: any } = { codec = "vp8", lossless = false } + if allowNative and opts.native and not alph then + local img = Types.Image.new(fw, fh, "yuv420p") + local ny, nc = fw * fh, buffer.len(v :: buffer) + buffer.copy(img.pixels, 0, y, 0, ny) + buffer.copy(img.pixels, ny, u, 0, nc) + buffer.copy(img.pixels, ny + nc, v :: buffer, 0, nc) + return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil + end + local rgba = Vp8.yuvToRgba(y, u, v :: buffer, fw, fh, opts.upsampling ~= "nearest") + if alph then + local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh) + if not a then + return nil, fromMessage(info, alph.off) + end + Vp8.setAlpha(rgba, a, fw * fh) + source.alpha = info + end + return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil +end + +local function collectMeta(buf: buffer, chunks: { Chunk }, meta: Types.ImageMeta) + for _, c in chunks do + local key = if c.id == "ICCP" then "icc" elseif c.id == "EXIF" then "exif" elseif c.id == "XMP " then "xmp" else nil + if key and meta[key] == nil then + local b = buffer.create(c.size) + buffer.copy(b, 0, buf, c.off, c.size) + meta[key] = b + end + end +end + +function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS + local buf = r.buf + local chunks, file = readChunks(r) + if not chunks then + return nil, file + end + local first = chunks[1] + if not first then + return corrupt("no chunks", r.base + 12) + end + if first.id == "VP8 " or first.id == "VP8L" then + local bs, err = decodeBitstream(buf, first, nil, o, true) + if not bs then + return nil, err + end + local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = false + img.meta.source = bs.source + return img, nil + end + if first.id ~= "VP8X" then + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8) + end + if first.size < 10 then + return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off) + end + local flags = readu8(buf, first.off) + local cw = u24(buf, first.off + 4) + 1 + local ch = u24(buf, first.off + 7) + 1 + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels)) + end + local meta: Types.ImageMeta = {} + collectMeta(buf, chunks, meta) + + if bit32.band(flags, FLAG_ANIM) == 0 then + local c, alph = findImage(chunks, 2) + if not c then + return corrupt("no VP8 / VP8L image chunk") + end + local bs, err = decodeBitstream(buf, c, if c.id == "VP8 " then alph else nil, o, true) + if not bs then + return nil, err + end + if bs.w ~= cw or bs.h ~= ch then + return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off) + end + local img = bs.yuv or Types.Image.new(cw, ch, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + for k, v in meta do + img.meta[k] = v + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = true + bs.source.flags = flags + img.meta.source = bs.source + return img, nil + end + + -- animation: ANIM then ANMF frames + local bg, loops = 0, 0 + local haveAnim = false + local frames: { Anim.Frame } = {} + local sources: { any } = {} + local delays: { number } = {} + local wantAll = o.frames ~= false + for i = 2, #chunks do + local c = chunks[i] + if c.id == "ANIM" then + if c.size < 6 then + return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off) + end + bg = buffer.readu32(buf, c.off) + loops = buffer.readu16(buf, c.off + 4) + haveAnim = true + elseif c.id == "ANMF" then + if not haveAnim then + return corrupt("ANMF before ANIM", c.off) + end + if c.size < 16 then + return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off) + end + local fx = u24(buf, c.off) * 2 + local fy = u24(buf, c.off + 3) * 2 + local fw = u24(buf, c.off + 6) + 1 + local fh = u24(buf, c.off + 9) + 1 + local dur = u24(buf, c.off + 12) + local fl = readu8(buf, c.off + 15) + if fx + fw > cw or fy + fh > ch then + return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off) + end + local sub, serr = subChunks(file, c) + if not sub then + return nil, serr + end + local img, alph = findImage(sub, 1) + if not img then + return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off) + end + local bs, err = decodeBitstream(buf, img, if img.id == "VP8 " then alph else nil, o, false) + if not bs then + return nil, err + end + if bs.w ~= fw or bs.h ~= fh then + return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off) + end + table.insert(frames, { + rgba = bs.rgba :: buffer, + x = fx, + y = fy, + w = fw, + h = fh, + blend = bit32.band(fl, 2) == 0, + disposeBg = bit32.band(fl, 1) == 1, + hasAlpha = bs.hasAlpha, + }) + bs.source.hasAlpha = bs.hasAlpha + table.insert(sources, bs.source) + table.insert(delays, dur) + if not wantAll then + break + end + end + end + if #frames == 0 then + return corrupt("animation without frames") + end + local canvases = Anim.coalesce(cw, ch, frames) + local img = Types.Image.new(cw, ch, "rgba8") + img.pixels = canvases[1] + img.loops = loops + for k, v in meta do + img.meta[k] = v + end + img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) } + img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless } + if wantAll then + local list: { Types.Frame } = {} + for i, f in frames do + local fi: Types.Image + if o.coalesce then + fi = Types.Image.new(cw, ch, "rgba8") + fi.pixels = canvases[i] + else + fi = Types.Image.new(f.w, f.h, "rgba8") + fi.pixels = f.rgba + end + fi.meta.source = sources[i] + fi.meta.duration = delays[i] + list[i] = { + image = fi, + delay = delays[i] / 1000, + x = if o.coalesce then 0 else f.x, + y = if o.coalesce then 0 else f.y, + dispose = if not o.coalesce and f.disposeBg then "background" else "none", + blend = if not o.coalesce and f.blend then "over" else "source", + } + end + img.frames = list + end + return img, nil +end + +-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err +function Webp.info(r: Bytes.Reader): (any, Err.Err?) + local chunks, cerr = readChunks(r) + if not chunks then + return nil, cerr + end + local first = chunks[1] + if not first then + return corrupt("no chunks") + end + local buf = r.buf + if first.id == "VP8X" and first.size >= 10 then + local flags = readu8(buf, first.off) + local n = 0 + for _, c in chunks do + if c.id == "ANMF" then + n += 1 + end + end + return { + width = u24(buf, first.off + 4) + 1, + height = u24(buf, first.off + 7) + 1, + animated = bit32.band(flags, FLAG_ANIM) ~= 0, + alpha = bit32.band(flags, FLAG_ALPHA) ~= 0, + frames = if n > 0 then n else 1, + }, nil + elseif first.id == "VP8L" then + local i, err = Vp8L.info(buf, first.off, first.size) + if not i then + return nil, err + end + return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil + elseif first.id == "VP8 " then + local h, err = Vp8.info(buf, first.off, first.size) + if not h then + return nil, err + end + return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil + end + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X") +end + +-- ------------------------------------------------------------------------------------------------ encode +local function hasAlpha(px: buffer, n: number): boolean + for i = 0, n - 1 do + if readu8(px, i * 4 + 3) ~= 255 then + return true + end + end + return false +end + +local function validImage(img: any): boolean + return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4 +end + +local function vp8x(flags: number, w: number, h: number): buffer + local b = Bytes.writer(10) + b:u8(flags) + b:u24le(0) + b:u24le(w - 1) + b:u24le(h - 1) + return b:finish() +end + +local function metaChunk(meta: any, key: string): buffer? + local v = meta and meta[key] + if type(v) == "buffer" and buffer.len(v) > 0 then + return v + elseif type(v) == "string" and #v > 0 then + return buffer.fromstring(v) + end + return nil +end + +function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + if o.lossless == false then + return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)") + end + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)") + end + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "effort must be 0..9") + end + local vopts: Vp8L.EncodeOptions = { effort = effort, exact = o.exact } + local w, h = img.width, img.height + local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp") + local frames = img.frames + local body = Riff.writer("WEBP", { rf64 = false }) + + if not frames or #frames == 0 then + local bits, err = Vp8L.encode(img.pixels, w, h, vopts) + if not bits then + return nil, err + end + if icc or exif or xmp then + local flags = (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0) + if hasAlpha(img.pixels, w * h) then + flags += FLAG_ALPHA + end + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + body:chunk("VP8L", bits) + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + else + body:chunk("VP8L", bits) + end + return body:finish() + end + + -- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every + -- frame flattened to a full canvas + local list: { Anim.Frame } = {} + local direct = true + for i, f in frames do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local fx, fy = f.x or 0, f.y or 0 + local fw, fh = f.image.width, f.image.height + if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then + return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas") + end + local dispose = f.dispose or "none" + if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose)) + end + if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then + direct = false + end + table.insert(list, { + rgba = f.image.pixels, + x = fx, + y = fy, + w = fw, + h = fh, + blend = f.blend == "over", + disposeBg = dispose == "background", + disposePrev = dispose == "previous", + hasAlpha = true, + }) + end + if not direct then + local canvases = Anim.composite(w, h, list) + for i, c in canvases do + list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true } + end + end + local anyAlpha = false + for _, f in list do + if hasAlpha(f.rgba, f.w * f.h) then + anyAlpha = true + break + end + end + local flags = FLAG_ANIM + (if anyAlpha then FLAG_ALPHA else 0) + (if icc then FLAG_ICC else 0) + (if exif then FLAG_EXIF else 0) + (if xmp then FLAG_XMP else 0) + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + local loops = o.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65535 then + return nil, Err.new(Err.ARG, "loops must be 0..65535") + end + local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 } + if type(bgc) ~= "table" then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a }") + end + for k = 1, 4 do + local v = bgc[k] + if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers") + end + end + local anim = buffer.create(6) + -- the background colour is stored as B, G, R, A + buffer.writeu8(anim, 0, bgc[3] or 0) + buffer.writeu8(anim, 1, bgc[2] or 0) + buffer.writeu8(anim, 2, bgc[1] or 0) + buffer.writeu8(anim, 3, bgc[4] or 0) + buffer.writeu16(anim, 4, loops) + body:chunk("ANIM", anim) + for i, f in list do + local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts) + if not bits then + return nil, err + end + local delay = frames[i].delay + local ms = if type(delay) == "number" and delay == delay then math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) else 100 + local hdr = Bytes.writer(16 + buffer.len(bits) + 9) + hdr:u24le(f.x // 2) + hdr:u24le(f.y // 2) + hdr:u24le(f.w - 1) + hdr:u24le(f.h - 1) + hdr:u24le(ms) + hdr:u8((if f.blend then 0 else 2) + (if f.disposeBg then 1 else 0)) + local nb = buffer.len(bits) + hdr:string("VP8L") + hdr:u32le(nb) + hdr:bytes(bits) + if nb % 2 == 1 then + hdr:u8(0) + end + body:chunk("ANMF", hdr.buf, 0, hdr:tell()) + end + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + return body:finish() +end + +-- ------------------------------------------------------------------------------------------------ extras +-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way +-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) +function Webp.coalesce(img: Types.Image): { buffer }? + if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil + end + local list: { Anim.Frame } = {} + for _, f in img.frames :: { Types.Frame } do + if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then + return nil + end + table.insert(list, { + rgba = f.image.pixels, + x = f.x, + y = f.y, + w = f.image.width, + h = f.image.height, + blend = f.blend == "over", + disposeBg = f.dispose == "background", + hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false), + }) + end + return Anim.coalesce(img.width, img.height, list) +end + +return Webp +end +__FILES["image/webp/Alpha"] = @native function() + + +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), +-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / +-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. +local Vp8L = __include("codecs/image/Vp8L") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Alpha = {} + +@native local function unfilter(a: buffer, w: number, h: number, filter: number) + if filter == 0 then + return + end + for y = 0, h - 1 do + local row = y * w + local prev = row - w + if y == 0 or filter == 1 then + -- horizontal (also the first row of the other filters): the left pixel, the first one from above + local pred = if y == 0 then 0 else readu8(a, prev) + for i = row, row + w - 1 do + pred = (pred + readu8(a, i)) % 256 + writeu8(a, i, pred) + end + elseif filter == 2 then + for i = 0, w - 1 do + writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256) + end + else + local top = readu8(a, prev) + local topLeft, left = top, top + for i = 0, w - 1 do + top = readu8(a, prev + i) + local g = left + top - topLeft + g = if g < 0 then 0 elseif g > 255 then 255 else g + left = (readu8(a, row + i) + g) % 256 + topLeft = top + writeu8(a, row + i, left) + end + end + end +end + +-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message +@native function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any) + if len <= 1 then + return nil, "truncated: ALPH chunk" + end + local hb = readu8(buf, off) + local method = hb % 4 + local filter = (hb // 4) % 4 + local pre = (hb // 16) % 4 + if method > 1 or pre > 1 or hb >= 64 then + return nil, "bad ALPH header" + end + local a: buffer + if method == 0 then + if len - 1 < w * h then + return nil, "truncated: raw alpha" + end + a = buffer.create(w * h) + buffer.copy(a, 0, buf, off + 1, w * h) + else + local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h) + if not d then + local e = err :: any + return nil, if e.code == "TRUNCATED" then "truncated: alpha " .. e.message else "alpha: " .. e.message + end + a = d + end + unfilter(a, w, h, filter) + return a, { method = method, filter = filter, preprocessing = pre } +end + +return Alpha +end +__FILES["image/webp/Anim"] = @native function() + + +-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour +-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha +-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the +-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws. +local band, rshift = bit32.band, bit32.rshift +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Anim = {} + +type Frame = { + rgba: buffer, -- w * h rgba8 + x: number, + y: number, + w: number, + h: number, + blend: boolean, -- alpha-blend over the canvas (false: overwrite) + disposeBg: boolean, -- after display, clear the rectangle to transparent + disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only) + hasAlpha: boolean, +} + +-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult) +@native local function blendPixel(src: number, dst: number): number + local sa = rshift(src, 24) + if sa == 0 then + return dst + end + local da = rshift(dst, 24) + local dfa = rshift(da * (256 - sa), 8) + local ba = sa + dfa + local scale = 16777216 // ba + local r = ((band(src, 255) * sa + band(dst, 255) * dfa) * scale) // 16777216 + local g = ((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) // 16777216 + local b = ((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) // 16777216 + return r + g * 256 + b * 65536 + ba * 16777216 +end +Anim.blendPixel = blendPixel + +-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets) +@native local function blendRow(cur: buffer, prev: buffer, o: number, n: number) + for i = o, o + n - 1 do + local s = readu32(cur, i * 4) + if s < 0xff000000 then + writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4))) + end + end +end + +-- draw(canvas, cw, f): copy the frame rectangle into the canvas +@native local function draw(canvas: buffer, cw: number, f: Frame) + for j = 0, f.h - 1 do + bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) + end +end + +@native local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: number, h: number) + for j = 0, h - 1 do + bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4) + end +end + +-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them +@native function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer } + local size = cw * ch * 4 + local out: { buffer } = {} + local disposed = bcreate(size) + local prev: Frame? = nil + local prevKey = false + for n, f in frames do + local full = f.w == cw and f.h == ch + local key + if n == 1 then + key = true + elseif (not f.hasAlpha or not f.blend) and full then + key = true + else + local p = prev :: Frame + key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey) + end + local cur = bcreate(size) + if not key then + bcopy(cur, 0, disposed, 0, size) + end + draw(cur, cw, f) + if n > 1 and f.blend and not key then + local p = prev :: Frame + if not p.disposeBg then + for j = 0, f.h - 1 do + blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w) + end + else + -- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp + local pmx, pmy = p.x + p.w, p.y + p.h + local smx = f.x + f.w + for j = 0, f.h - 1 do + local cy = f.y + j + if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then + blendRow(cur, disposed, cy * cw + f.x, f.w) + else + if f.x < p.x then + blendRow(cur, disposed, cy * cw + f.x, p.x - f.x) + end + if smx > pmx then + blendRow(cur, disposed, cy * cw + pmx, smx - pmx) + end + end + end + end + end + table.insert(out, cur) + prev = f + prevKey = key + bcopy(disposed, 0, cur, 0, size) + if f.disposeBg then + clearRect(disposed, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or +-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle; +-- previous: restore) +@native function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer } + local size = cw * ch * 4 + local canvas = bcreate(size) + local out: { buffer } = {} + for _, f in frames do + local saved: buffer? = nil + if f.disposePrev then + saved = bcreate(size) + bcopy(saved :: buffer, 0, canvas, 0, size) + end + if f.blend then + for j = 0, f.h - 1 do + local co = (f.y + j) * cw + f.x + for i = 0, f.w - 1 do + local s = readu32(f.rgba, (j * f.w + i) * 4) + local d = readu32(canvas, (co + i) * 4) + writeu32(canvas, (co + i) * 4, if s >= 0xff000000 or d < 0x01000000 then s else blendPixel(s, d)) + end + end + else + draw(canvas, cw, f) + end + local shown = bcreate(size) + bcopy(shown, 0, canvas, 0, size) + table.insert(out, shown) + if saved then + canvas = saved + elseif f.disposeBg then + clearRect(canvas, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +return Anim +end +__FILES["image/xbm"] = function() + +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height +-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, +-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below +-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Xbm = { + name = "xbm", + category = "image", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + transparent: boolean?, -- clear bits transparent (default false: white) + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _) + threshold: number?, -- luminance below this is black (default 128) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xbm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 256, true) + if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 26 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local s = buffer.readstring(r.buf, r.base, n) + local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)")) + local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)")) + if not w or not h or w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "missing width / height defines") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local brace = string.find(s, "{", 1, true) + if not brace then + return nil, Err.new(Err.CORRUPT, "missing bits array") + end + local decl = string.sub(s, 1, brace) + local short = string.find(decl, "short", 1, true) ~= nil + local unit = if short then 16 else 8 + local per = (w + unit - 1) // unit + local want = per * h + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF + local got = 0 + local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ") + for tok in string.gmatch(body, "[%w]+") do + if got >= want then + break + end + local v + if string.match(tok, "^0[xX]%x+$") then + v = tonumber(string.sub(tok, 3), 16) + elseif string.match(tok, "^0%d+$") then + v = tonumber(tok, 8) + elseif string.match(tok, "^%d+$") then + v = tonumber(tok) + end + if v then + local y, cx = got // per, (got % per) * unit + for k = 0, unit - 1 do + local x = cx + k + if x < w then + buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear) + end + end + got += 1 + end + end + if got < want then + for i = got * unit, want * unit - 1 do + local y, x = i // (per * unit), i % (per * unit) + if x < w then + buffer.writeu32(px, (y * w + x) * 4, clear) + end + end + img.meta.truncated = true + end + local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)")) + local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)")) + if hx and hy then + img.meta.hotspot = { x = hx, y = hy } + end + local name = string.match(s, "#define%s+([%w_]-)_?width%s") + img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local th = opts and opts.threshold or 128 + local px = img.pixels + local parts = { + string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h), + } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y)) + end + table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name)) + local per = (w + 7) // 8 + local bytes = {} + for y = 0, h - 1 do + for bx = 0, per - 1 do + local v = 0 + for k = 0, 7 do + local x = bx * 8 + k + if x < w then + local o = (y * w + x) * 4 + local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2) + if lum < th and buffer.readu8(px, o + 3) >= 128 then + v += bit32.lshift(1, k) + end + end + end + table.insert(bytes, string.format("0x%02x", v)) + end + end + for i = 1, #bytes, 12 do + table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n")) + end + return buffer.fromstring(table.concat(parts)), nil +end + +return Xbm +end +__FILES["image/xpm"] = function() + +-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: +-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / +-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour +-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in +-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, +-- the fewest chars per pixel; opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Names = __include("image/xpm/Names") + +-- ------------------------------------------------------------------------------------------------ contract +local Xpm = { + name = "xpm", + category = "image", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +type EncodeOptions = { + name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _) +} + +-- the characters of pixel codes (printable ASCII without '"' and '\') +local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|" + +-- ------------------------------------------------------------------------------------------------ sniff +function Xpm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 64, true) + if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colour value -> rgba8 u32, or nil for an unknown name +local function colour(v: string): number? + local l = string.lower(v) + if l == "none" or l == "transparent" then + return 0 + end + if string.sub(v, 1, 1) == "#" then + local hex = string.sub(v, 2) + local n = #hex + if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then + return nil + end + local k = n // 3 + local mx = 16 ^ k - 1 + local c = 0 + for i = 0, 2 do + local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number + c += math.floor(x * 255 / mx + 0.5) * 256 ^ i + end + return c + 0xFF000000 + end + local rgb = Names.lookup(l) + return if rgb then rgb + 0xFF000000 else nil +end + +-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) +local function strings(s: string): { string } + local out = {} + if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then + local first = true + for line in string.gmatch(s, "[^\n]+") do + if first then + first = false + else + table.insert(out, (string.gsub(line, "\r$", ""))) + end + end + return out + end + local i, n = 1, #s + while i <= n do + local c = string.sub(s, i, i) + if c == "/" and string.sub(s, i + 1, i + 1) == "*" then + local e = string.find(s, "*/", i + 2, true) + i = if e then e + 2 else n + 1 + elseif c == '"' then + local parts = {} + local j = i + 1 + while j <= n do + local d = string.sub(s, j, j) + if d == "\\" then + table.insert(parts, string.sub(s, j + 1, j + 1)) + j += 2 + elseif d == '"' then + break + else + local e = string.find(s, '["\\]', j) + local stop = (e or n + 1) - 1 + table.insert(parts, string.sub(s, j, stop)) + j = stop + 1 + end + end + table.insert(out, table.concat(parts)) + i = j + 1 + else + i += 1 + end + end + return out +end + +local KEYS = { c = true, m = true, g4 = true, g = true, s = true } + +function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 27 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local list = strings(buffer.readstring(r.buf, r.base, n)) + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XPM strings") + end + local vals: { number } = {} + for tok in string.gmatch(list[1], "%S+") do + table.insert(vals, tonumber(tok) or -1) + end + local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1 + if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad values line") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels or nc > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + if #list < 1 + nc then + return nil, Err.new(Err.TRUNCATED, "colour table runs past the end") + end + local map: { [string]: number } = {} + local unknown: { string } = {} + local palette: { { number } } = {} + for i = 1, nc do + local line = list[1 + i] + local code = string.sub(line, 1, cpp) + local rest = string.sub(line, cpp + 1) + local found: { [string]: string } = {} + local key: string? = nil + local acc = {} + for tok in string.gmatch(rest, "%S+") do + if KEYS[tok] and (key == nil or #acc > 0) then + if key then + found[key] = table.concat(acc, " ") + end + key, acc = tok, {} + else + table.insert(acc, tok) + end + end + if key then + found[key] = table.concat(acc, " ") + end + local v = found.c or found.g or found.g4 or found.m + local c = if v then colour(v) else nil + if v and not c then + c = colour((string.gsub(v, " ", ""))) + end + local cv: number = c or 0xFF000000 + if not c then + table.insert(unknown, v or "") + end + c = cv + map[code] = cv + palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) } + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local truncated = false + for y = 0, h - 1 do + local row = list[2 + nc + y] + if not row then + truncated = true + break + end + for x = 0, w - 1 do + local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)] + buffer.writeu32(px, (y * w + x) * 4, c or 0) + end + end + if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then + img.meta.hotspot = { x = vals[5], y = vals[6] } + end + if #unknown > 0 then + img.meta.unknownColours = unknown + end + if truncated then + img.meta.truncated = true + end + img.meta.palette = palette + img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local px = img.pixels + local index: { [number]: number } = {} + local order: { number } = {} + local keys = table.create(w * h, 0) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF) + if not index[k] then + table.insert(order, k) + index[k] = #order + end + keys[i + 1] = index[k] + end + local nchars = #CODE_CHARS + local cpp = 1 + while nchars ^ cpp < #order do + cpp += 1 + end + local codes: { string } = {} + for i = 1, #order do + local v, s = i - 1, "" + for _ = 1, cpp do + local d = v % nchars + s ..= string.sub(CODE_CHARS, d + 1, d + 1) + v //= nchars + end + codes[i] = s + end + local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y)) + else + table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp)) + end + for i, k in order do + local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16)) + table.insert(parts, string.format('"%s c %s",\n', codes[i], col)) + end + for y = 0, h - 1 do + local row = table.create(w, "") + for x = 0, w - 1 do + row[x + 1] = codes[keys[y * w + x + 1]] + end + table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n")) + end + table.insert(parts, "};\n") + return buffer.fromstring(table.concat(parts)), nil +end + +return Xpm +end +__FILES["image/xpm/Names"] = function() + +-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's +-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. +-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +local Names = {} + +local HEX: { [string]: number } = { + aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF, + beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF, + blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00, + chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C, + cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9, + darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F, + darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F, + darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1, + darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF, + gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE, + green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4, + indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA, + lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080, + lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90, + lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA, + lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0, + lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060, + mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB, + mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC, + mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5, + navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23, + orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98, + paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F, + pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000, + rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460, + seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB, + slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F, + steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0, + violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, +} + +-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) +function Names.lookup(name: string): number? + local v = HEX[name] + if v then + return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536 + end + local n = string.match(name, "^gr[ae]y(%d+)$") + if n then + local k = tonumber(n) :: number + if k <= 100 then + local g = math.floor(k * 255 / 100 + 0.49) + return g * 0x10101 + end + end + return nil +end + +return Names +end +__FILES["layered/aseprite"] = function() + +-- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, +-- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every +-- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, +-- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to +-- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old +-- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and +-- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, +-- delay }. +-- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk +-- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, +-- palette, tags. +-- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour +-- profiles (sRGB assumed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") + +-- ------------------------------------------------------------------------------------------------ contract +local Aseprite = { + name = "aseprite", + category = "layered", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, +} + +type DecodeOptions = { + maxPixels: number?, -- refuse sprites / cels larger than this (default 2^26) + maxFrames: number?, -- default 65535 +} +type EncodeOptions = { + depth: number?, -- 32 (RGBA), 16 (grayscale) or 8 (indexed, with layered.meta.palette); default meta.colorDepth if + -- the pixels fit it, else 32 + level: number?, -- zlib level for the cels (default 6) +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" } +local BLEND_IDS: { [string]: number } = {} +for k, v in BLENDS do + BLEND_IDS[v] = k +end +BLEND_IDS.add = 16 +BLEND_IDS.passThrough = 0 +local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" } +local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Aseprite.sniff(r: Bytes.Reader): number + if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then + local d = r:peekU8(12) + if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then + return 1 + end + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + return r:string(r:u16le()) +end + +-- cel pixels (depth bytes per pixel) -> rgba8 +local function toRGBA(src: buffer, so: number, n: number, depth: number, palette: buffer, transparent: number, background: boolean): buffer + local out = buffer.create(n * 4) + if depth == 32 then + buffer.copy(out, 0, src, so, n * 4) + elseif depth == 16 then + for i = 0, n - 1 do + local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1) + buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216) + end + else + for i = 0, n - 1 do + local k = buffer.readu8(src, so + i) + local c = buffer.readu32(palette, k * 4) + if k == transparent and not background then + c = 0 + end + buffer.writeu32(out, i * 4, c) + end + end + return out +end + +type LayerInfo = { name: string, flags: number, type: number, level: number, blend: number, opacity: number, userData: any? } + +function Aseprite.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxFrames = opts and opts.maxFrames or 65535 + if r:size() < 128 then + return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos) + end + r:skip(4) + if r:u16le() ~= 0xA5E0 then + return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2) + end + local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local hflags = r:u32le() + r:skip(2 + 8) + local transparent = r:u8() + r:skip(3) + local ncolors = r:u16le() + local pw, ph = r:u8(), r:u8() + local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le() + r:seek(128) + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth) + end + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "bad size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h)) + end + if nframes > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames") + end + local bpp = depth // 8 + local palette = buffer.create(1024) + local palList: { { number } } = {} + local palNames: { [number]: string } = {} + local infos: { LayerInfo } = {} + local tags: { any } = {} + local frames: { { cels: { [number]: any }, delay: number } } = {} + local skipped = 0 + local lastUser: any = nil -- the object the next user data chunk belongs to + local tagUser = 0 -- tags waiting for their user data chunks + for fi = 1, nframes do + local fstart = r.pos + local fbytes = r:u32le() + local fmagic = r:u16le() + local oldChunks = r:u16le() + local duration = r:u16le() + r:skip(2) + local newChunks = r:u32le() + if r.err then + return nil, r.err + end + if fmagic ~= 0xF1FA then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4) + end + if fbytes < 16 or fstart + fbytes > r.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart) + end + local nchunks = if newChunks ~= 0 then newChunks else oldChunks + local frame = { cels = {}, delay = duration / 1000 } + frames[fi] = frame + local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos) + for _ = 1, nchunks do + if fr:remaining() < 6 then + break + end + local cstart = fr.pos + local csize = fr:u32le() + local ctype = fr:u16le() + if csize < 6 or cstart + csize > fr.limit then + return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart) + end + local c = Bytes.reader(fr.buf, cstart + 6, csize - 6) + fr.pos = cstart + csize + if ctype == 0x2004 then + local info: LayerInfo = { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 } + c:skip(4) + info.blend = c:u16le() + info.opacity = c:u8() + c:skip(3) + info.name = str(c) + if c.err then + return nil, c.err + end + if info.type == 2 then + skipped += 1 + end + table.insert(infos, info) + lastUser = info + elseif ctype == 0x2005 then + local li = c:u16le() + local x, y = c:i16le(), c:i16le() + local op = c:u8() + local ctyp = c:u16le() + local z = c:i16le() + c:skip(5) + if c.err then + return nil, c.err + end + local cel: any = { x = x, y = y, opacity = op, z = z } + if ctyp == 0 or ctyp == 2 then + local cw, ch = c:u16le(), c:u16le() + if c.err then + return nil, c.err + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "cel over the pixel limit") + end + local n = cw * ch + local raw: buffer, ro: number + if ctyp == 0 then + if not c:need(n * bpp) then + return nil, c.err + end + raw, ro = c.buf, c.pos + else + local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp) + if not z2 then + -- some writers leave padding after the stream: inflate without the exact size + local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos) + if not loose or buffer.len(loose) < n * bpp then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos) + end + z2 = loose + end + raw, ro = z2 :: buffer, 0 + end + cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro + elseif ctyp == 1 then + cel.link = c:u16le() + 1 + else + cel.skip = true -- tilemap cel + end + frame.cels[li + 1] = cel + lastUser = cel + elseif ctype == 0x2018 then + local n = c:u16le() + c:skip(8) + tagUser = 0 + for _ = 1, n do + local from, to = c:u16le(), c:u16le() + local dir = c:u8() + local rep = c:u16le() + c:skip(6) + local cr, cg, cb = c:u8(), c:u8(), c:u8() + c:skip(1) + local name = str(c) + if c.err then + return nil, c.err + end + table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } }) + tagUser += 1 + end + lastUser = nil + elseif ctype == 0x2019 then + local size = c:u32le() + local first, last = c:u32le(), c:u32le() + c:skip(8) + if first > last or last > 255 or size > 256 then + return nil, Err.new(Err.CORRUPT, "bad palette range", cstart) + end + for k = first, last do + local f = c:u16le() + local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8() + if bit32.band(f, 1) ~= 0 then + palNames[k + 1] = str(c) + end + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216) + palList[k + 1] = { cr, cg, cb, ca } + end + for k = #palList + 1, size do + palList[k] = { 0, 0, 0, 255 } + end + if c.err then + return nil, c.err + end + elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then + -- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB + local packets = c:u16le() + local k = 0 + for _ = 1, packets do + k += c:u8() + local n = c:u8() + if n == 0 then + n = 256 + end + for _ = 1, n do + local cr, cg, cb = c:u8(), c:u8(), c:u8() + if ctype == 0x0011 then + cr, cg, cb = cr * 255 // 63, cg * 255 // 63, cb * 255 // 63 + end + if k < 256 then + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000) + end + k += 1 + end + end + if c.err then + return nil, c.err + end + for i = 0, math.min(k, 256) - 1 do + local v = buffer.readu32(palette, i * 4) + palList[i + 1] = { v % 256, v // 256 % 256, v // 65536 % 256, 255 } + end + palList = table.move(palList, 1, math.min(k, 256), 1, {}) + elseif ctype == 0x2020 then + local f = c:u32le() + local ud: any = {} + if bit32.band(f, 1) ~= 0 then + ud.text = str(c) + end + if bit32.band(f, 2) ~= 0 then + ud.color = { c:u8(), c:u8(), c:u8(), c:u8() } + end + if not c.err then + if tagUser > 0 then + -- after a tags chunk, user data chunks follow for each tag in order + local t = tags[#tags - tagUser + 1] + if t then + t.userData = ud + end + tagUser -= 1 + elseif lastUser then + lastUser.userData = ud + end + end + end + -- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped + end + r.pos = fstart + fbytes + end + local _ = ncolors + -- the layer tree of one frame + local function build(fi: number): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = { root } -- stack[level + 1] = the children list at that level + for li, info in infos do + local level = math.min(info.level, #stack - 1) + local list = stack[level + 1] + local l: any = { + name = info.name, + x = 0, + y = 0, + opacity = if bit32.band(hflags, 1) ~= 0 or info.type ~= 0 then info.opacity / 255 else 1, + blend = BLENDS[info.blend] or "normal", + visible = bit32.band(info.flags, 1) ~= 0, + flags = info.flags, + } + if info.userData then + l.userData = info.userData + end + if info.type == 1 then + l.image = Types.Image.new(0, 0) + l.children = {} + -- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then + -- into a buffer of its own): pass-through vs isolated + if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then + l.blend = "passThrough" + l.opacity = 1 + end + table.insert(list, l) + -- deeper layers go into this group + for k = #stack, level + 2, -1 do + stack[k] = nil + end + stack[level + 2] = l.children + else + for k = #stack, level + 2, -1 do + stack[k] = nil + end + l.image = Types.Image.new(0, 0) + if info.type == 2 then + l.tilemap = true + end + local cel = frames[fi].cels[li] + local guard = 0 + while cel and cel.link and guard < 8 do -- follow links (one hop in valid files) + l.link = cel.link + local target = frames[cel.link] + cel = if target then target.cels[li] else nil + guard += 1 + end + if cel and cel.image then + l.image = cel.image + l.x, l.y = cel.x, cel.y + if cel.opacity < 255 then + l.fillOpacity = cel.opacity / 255 + end + if cel.z ~= 0 then + l.zIndex = cel.z + end + if cel.userData then + l.celUserData = cel.userData + end + end + table.insert(list, l) + end + end + return root + end + -- cel images (shared by linked cels) + for _, f in frames do + for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + if cel.raw then + local info = infos[li] + local img = Types.Image.new(cel.w, cel.h) + img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0) + cel.image = img + cel.raw = nil + end + end + end + local layered = Types.Layered.new(w, h) + local list = {} + for fi = 1, nframes do + list[fi] = { layers = build(fi), delay = frames[fi].delay } + end + if nframes > 0 then + layered.layers = list[1].layers + end + layered.frames = list + if #palList > 0 then + layered.meta.palette = palList + if next(palNames) then + layered.meta.paletteNames = palNames + end + end + layered.meta.tags = tags + layered.meta.colorDepth = depth + layered.meta.transparentIndex = transparent + layered.meta.pixelRatio = { if pw == 0 then 1 else pw, if ph == 0 then 1 else ph } + layered.meta.grid = { gx, gy, gw, gh } + if skipped > 0 then + layered.meta.skipped = skipped + end + layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = if depth == 32 then "rgba" elseif depth == 16 then "graya" else "indexed" } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Node = { layer: any, level: number } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +-- the nodes of a tree in file order (a group, then its children one level deeper) +local function nodes(layers: { any }, level: number, out: { Node }): boolean + for _, l in layers do + if type(l) ~= "table" or level > 64 then + return false + end + table.insert(out, { layer = l, level = level }) + if type(l.children) == "table" then + if not nodes(l.children, level + 1, out) then + return false + end + end + end + return true +end + +local function writeStr(w: Bytes.Writer, s: string) + local n = math.min(#s, 65535) + w:u16le(n) + w:string(string.sub(s, 1, n)) +end + +function Aseprite.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 65535 or H > 65535 then + return nil, Err.new(Err.ARG, "bad sprite size") + end + local meta: any = if type(layered.meta) == "table" then layered.meta else {} + local level = opts and opts.level or 6 + -- frames: the layered frames, or one frame of the layers + local frameList: { any } = if type(layered.frames) == "table" and #layered.frames > 0 then layered.frames else { { layers = layered.layers, delay = 0.1 } } + local struct: { Node } = {} + if not nodes(frameList[1].layers, 0, struct) then + return nil, Err.new(Err.ARG, "bad layer tree") + end + if #struct > 65535 or #frameList > 65535 then + return nil, Err.new(Err.ARG, "too many layers / frames") + end + local perFrame: { { Node } } = {} + for fi, f in frameList do + if type(f) ~= "table" or type(f.layers) ~= "table" then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers") + end + local ns: { Node } = {} + if not nodes(f.layers, 0, ns) or #ns ~= #struct then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + for k, n in ns do + if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image") + end + end + perFrame[fi] = ns + end + -- the colour depth: requested, or the source's when every pixel fits + local depth = opts and opts.depth or meta.colorDepth or 32 + local explicit = opts ~= nil and opts.depth ~= nil + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8") + end + local palette: { { number } } = if type(meta.palette) == "table" then meta.palette else {} + local transparent = if type(meta.transparentIndex) == "number" then meta.transparentIndex else 0 + local index: { [number]: number } = {} + for k = #palette, 1, -1 do + local c = palette[k] + if type(c) == "table" then + index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1 + end + end + if depth ~= 32 then + local fits = depth ~= 8 or #palette > 0 + for _, ns in perFrame do + for _, n in ns do + local img = n.layer.image + if fits and type(n.layer.children) ~= "table" then + local px = img.pixels + for i = 0, img.width * img.height - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + local r, g, b = v % 256, v // 256 % 256, v // 65536 % 256 + if r ~= g or g ~= b then + fits = false + break + end + elseif v // 16777216 ~= 0 and index[v] == nil then + fits = false + break + end + end + end + end + end + if not fits then + if explicit then + return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (if depth == 8 then " with meta.palette" else "")) + end + depth = 32 + end + end + local bpp = depth // 8 + local function pixels(n: any): buffer + local img = n.layer.image + local count = img.width * img.height + if depth == 32 then + return img.pixels + end + local out = buffer.create(count * bpp) + local px = img.pixels + for i = 0, count - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + buffer.writeu8(out, i * 2, v % 256) + buffer.writeu8(out, i * 2 + 1, v // 16777216) + else + local k = if v // 16777216 == 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 then transparent else index[v] or transparent + buffer.writeu8(out, i, k) + end + end + return out + end + + local out = Bytes.writer(65536) + -- header (file size patched at the end) + out:u32le(0) + out:u16le(0xA5E0) + out:u16le(#frameList) + out:u16le(W) + out:u16le(H) + out:u16le(depth) + out:u32le(3) -- layer opacity and group opacity / blend valid + out:u16le(100) + out:u32le(0) + out:u32le(0) + out:u8(if depth == 8 then transparent else 0) + out:fill(0, 3) + out:u16le(if #palette > 0 and #palette < 256 then #palette else 0) + local ratio = if type(meta.pixelRatio) == "table" then meta.pixelRatio else { 1, 1 } + out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255)) + out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255)) + local grid = if type(meta.grid) == "table" then meta.grid else { 0, 0, 16, 16 } + out:i16le(tonumber(grid[1]) or 0) + out:i16le(tonumber(grid[2]) or 0) + out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535)) + out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535)) + out:fill(0, 84) + + local function chunk(fw: Bytes.Writer, ctype: number, body: Bytes.Writer) + local b = body:finish() + fw:u32le(buffer.len(b) + 6) + fw:u16le(ctype) + fw:bytes(b) + end + local function userData(fw: Bytes.Writer, ud: any): number + if type(ud) ~= "table" then + return 0 + end + local c = Bytes.writer(64) + local f = (if type(ud.text) == "string" then 1 else 0) + (if type(ud.color) == "table" then 2 else 0) + c:u32le(f) + if type(ud.text) == "string" then + writeStr(c, ud.text) + end + if type(ud.color) == "table" then + for k = 1, 4 do + c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255)) + end + end + chunk(fw, 0x2020, c) + return 1 + end + -- where each (layer, frame) cel's image was first written: linked cels + local firstAt: { [number]: { [any]: { frame: number, x: number, y: number, fill: number } } } = {} + for fi, f in frameList do + local fw = Bytes.writer(4096) + local count = 0 + if fi == 1 then + -- colour profile: sRGB + local cp = Bytes.writer(16) + cp:u16le(1) + cp:u16le(0) + cp:u32le(0) + cp:fill(0, 8) + chunk(fw, 0x2007, cp) + count += 1 + if #palette > 0 then + local p = Bytes.writer(#palette * 6 + 20) + local n = math.min(#palette, 256) + p:u32le(n) + p:u32le(0) + p:u32le(n - 1) + p:fill(0, 8) + local names = if type(meta.paletteNames) == "table" then meta.paletteNames else {} + for k = 1, n do + local c = palette[k] + local nm = names[k] + p:u16le(if type(nm) == "string" then 1 else 0) + p:u8(c[1] or 0) + p:u8(c[2] or 0) + p:u8(c[3] or 0) + p:u8(c[4] or 255) + if type(nm) == "string" then + writeStr(p, nm) + end + end + chunk(fw, 0x2019, p) + count += 1 + end + for _, n in struct do + local l = n.layer + local c = Bytes.writer(64) + local isGroup = type(l.children) == "table" + local flags = tonumber(l.flags) or 3 + flags = bit32.band(flags, bit32.bnot(1)) + (if l.visible == false then 0 else 1) + c:u16le(flags) + c:u16le(if isGroup then 1 else 0) + c:u16le(n.level) + c:u16le(0) + c:u16le(0) + c:u16le(BLEND_IDS[l.blend] or 0) + c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + c:fill(0, 3) + writeStr(c, tostring(l.name or "Layer")) + chunk(fw, 0x2004, c) + count += 1 + count += userData(fw, l.userData) + end + local tags = if type(meta.tags) == "table" then meta.tags else {} + if #tags > 0 then + local c = Bytes.writer(64) + c:u16le(#tags) + c:fill(0, 8) + for _, t in tags do + c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535)) + c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535)) + c:u8(DIRECTION_IDS[t.direction] or 0) + c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535)) + c:fill(0, 6) + local col = if type(t.color) == "table" then t.color else { 0, 0, 0 } + c:u8(col[1] or 0) + c:u8(col[2] or 0) + c:u8(col[3] or 0) + c:u8(0) + writeStr(c, tostring(t.name or "Tag")) + end + chunk(fw, 0x2018, c) + count += 1 + for _, t in tags do + if type(t.userData) == "table" then + count += userData(fw, t.userData) + else + local e = Bytes.writer(4) + e:u32le(0) + chunk(fw, 0x2020, e) + count += 1 + end + end + end + end + for li, n in perFrame[fi] do + local l = n.layer + if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then + continue + end + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255) + local c = Bytes.writer(256) + c:u16le(li - 1) + c:i16le(x) + c:i16le(y) + c:u8(fill) + local seen = firstAt[li] and firstAt[li][l.image] + if seen and seen.x == x and seen.y == y and seen.fill == fill then + c:u16le(1) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(seen.frame - 1) + else + c:u16le(2) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(l.image.width) + c:u16le(l.image.height) + local z = Deflate.zlibCompress(pixels(n), { level = level }) + if not z then + return nil, Err.new(Err.ARG, "cel compression failed") + end + c:bytes(z) + firstAt[li] = firstAt[li] or {} + firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill } + end + chunk(fw, 0x2005, c) + count += 1 + count += userData(fw, l.celUserData) + end + local body = fw:finish() + out:u32le(buffer.len(body) + 16) + out:u16le(0xF1FA) + out:u16le(math.min(count, 0xFFFF)) + out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535)) + out:u16le(0) + out:u32le(count) + out:bytes(body) + end + out:setU32le(0, out:tell()) + return out:finish(), nil +end + +return Aseprite +end +__FILES["layered/ora"] = function() + +-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with +-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. +-- Decode: the stack tree (nested = groups: isolation="auto" is passThrough; name / src / x / y / +-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), +-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: +-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) +-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to +-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the / / +-- elements (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Xml = __include("codecs/text/Xml") +local Blend = __include("codecs/image/Blend") + +-- ------------------------------------------------------------------------------------------------ contract +local Ora = { + name = "ora", + category = "layered", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one) + composite: boolean?, -- decode mergedimage.png into meta.composite (default true) + maxLayers: number?, -- default 10000 +} +type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one) + composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend) + thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MIME = "image/openraster" +local OPS: { [string]: string } = { + ["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay", + ["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn", + ["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference", + ["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color", + ["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge", +} +local BACK: { [string]: string } = {} +for k, v in OPS do + BACK[v] = k +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ora.sniff(r: Bytes.Reader): number + -- a zip whose first (stored) entry is "mimetype" holding image/openraster + if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(v: any, default: number): number + local n = tonumber(v) + return if n and n == n then n else default +end + +function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local mt = zip:readString("mimetype") + if mt and string.gsub(mt, "%s+$", "") ~= MIME then + return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME) + end + local stackText, serr = zip:readString("stack.xml") + if not stackText then + return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml") + end + local doc, xerr = Xml.decode(stackText) + if not doc then + return nil, xerr + end + local root = doc.root + if not root or root.name ~= "image" then + return nil, Err.new(Err.CORRUPT, "stack.xml has no root") + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook") + end + local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0) + if W < 1 or H < 1 or W > 65536 or H > 65536 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxLayers = opts and opts.maxLayers or 10000 + local count = 0 + local function png(path: string): (Types.Image?, Err.Err?) + local data, derr = zip:read(path) + if not data then + return nil, derr or Err.new(Err.CORRUPT, "missing " .. path) + end + local ok, img, ierr = pcall(decodeImage, data) + if not ok or not img then + return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img)) + end + return img, nil + end + -- a 's children, top first in the file -> bottom to top + local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?) + local out: { Types.Layer } = {} + for _, ch in node.children do + if type(ch) ~= "table" then + continue + end + local a = ch.attrs or {} + local visible = a.visibility ~= "hidden" + local op = a["composite-op"] or "svg:src-over" + local blend = OPS[op] or op + local x, y = ox + num(a.x, 0), oy + num(a.y, 0) + count += 1 + if count > maxLayers then + return nil, Err.new(Err.LIMIT, "too many layers") + end + if ch.name == "layer" then + local src = a.src + if type(src) ~= "string" then + continue + end + if string.lower(string.sub(src, -4)) ~= ".png" then + return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src) + end + local img, perr = png(src) + if not img then + return nil, perr + end + local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y) + layer.opacity = math.clamp(num(a.opacity, 1), 0, 1) + layer.visible = visible + layer.blend = blend + table.insert(out, 1, layer) + elseif ch.name == "stack" then + local kids, kerr = stack(ch, x, y) + if not kids then + return nil, kerr + end + local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer }) + g.opacity = math.clamp(num(a.opacity, 1), 0, 1) + g.visible = visible + g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough" + table.insert(out, 1, g) + end + end + return out, nil + end + local top = Xml.child(root, "stack") + if not top then + return nil, Err.new(Err.CORRUPT, "stack.xml has no ") + end + local layers, lerr = stack(top, 0, 0) + if not layers then + return nil, lerr + end + local doc2 = Types.Layered.new(W, H) + doc2.layers = layers :: { Types.Layer } + if not (opts and opts.composite == false) and zip:find("mergedimage.png") then + doc2.meta.composite = png("mergedimage.png") + end + local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres) + if xr and yr then + doc2.meta.dpi = { x = xr, y = yr } + end + doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count } + return doc2, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- nearest-neighbour downscale to fit max x max +local function thumbnail(img: Types.Image, max: number): Types.Image + local w, h = img.width, img.height + local s = math.min(1, max / math.max(w, h)) + local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s)) + local t = Types.Image.new(tw, th, "rgba8") + for y = 0, th - 1 do + local sy = math.min(h - 1, math.floor(y / s)) + for x = 0, tw - 1 do + local sx = math.min(w - 1, math.floor(x / s)) + buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4)) + end + end + return t +end + +function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then + return nil, Err.new(Err.ARG, "needs a Layered document") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook") + end + local W, H = doc.width, doc.height + local zw = Zip.writer() + zw:add("mimetype", MIME, { method = "store" }) + local files: { { any } } = {} + local n = 0 + local function png(img: Types.Image, label: string): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images") + end + local ok, data, err = pcall(encodeImage, img, "png") + if not ok or not data then + return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data)) + end + return data, nil + end + -- layers bottom to top -> xml children top first + local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?) + local kids = {} + for i = #layers, 1, -1 do + local l = layers[i] + local attrs: { [string]: string } = { + name = l.name or "", + opacity = string.format("%.6g", l.opacity or 1), + visibility = if l.visible == false then "hidden" else "visible", + } + if l.children then + attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate" + if l.blend ~= "passThrough" then + attrs["composite-op"] = BACK[l.blend] or l.blend + end + local sub, serr = stack(l.children) + if not sub then + return nil, serr + end + table.insert(kids, Xml.element("stack", attrs, sub)) + else + n += 1 + local path = string.format("data/layer%03d.png", n) + local data, perr = png(l.image, "layer " .. tostring(l.name)) + if not data then + return nil, perr + end + table.insert(files, { path, data }) + attrs.src = path + attrs.x = tostring(math.floor(l.x or 0)) + attrs.y = tostring(math.floor(l.y or 0)) + attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over" + table.insert(kids, Xml.element("layer", attrs)) + end + end + return kids, nil + end + local kids, kerr = stack(doc.layers) + if not kids then + return nil, kerr + end + local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) } + local dpi = doc.meta and doc.meta.dpi + if dpi then + rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y) + end + local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 }) + zw:add("stack.xml", xml :: string) + for _, f in files do + zw:add(f[1], f[2], { method = "store" }) + end + local merged = opts and opts.composite + if not merged then + local m = Types.Image.new(W, H, "rgba8") + Blend.flatten(doc.layers, m.pixels, W, H, false) + merged = m + end + local mdata, merr = png(merged :: Types.Image, "mergedimage") + if not mdata then + return nil, merr + end + zw:add("mergedimage.png", mdata, { method = "store" }) + if not (opts and opts.thumbnail == false) then + local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail") + if not tdata then + return nil, terr + end + zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" }) + end + return zw:finish() +end + +return Ora +end +__FILES["layered/psd"] = function() + +-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of +-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers +-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, +-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / +-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image +-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. +-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend +-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, +-- clipping, opacity / fill, hidden flags and Unicode names. +-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer +-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Blend = __include("codecs/image/Blend") +local Channels = __include("layered/psd/Channels") + +-- ------------------------------------------------------------------------------------------------ contract +local Psd = { + name = "psd", + category = "layered", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 } }, +} + +type DecodeOptions = { + layers: boolean?, -- read the layers (default true; false reads only the merged image) + maxPixels: number?, -- refuse documents / layers larger than this (default 2^26) + maxLayers: number?, -- default 10000 +} +type EncodeOptions = { + composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend) +} + +-- ------------------------------------------------------------------------------------------------ constants +local BLEND_KEYS: { [string]: string } = { + norm = "normal", + diss = "dissolve", + dark = "darken", + ["mul "] = "multiply", + idiv = "colorBurn", + lbrn = "linearBurn", + dkCl = "darkerColor", + lite = "lighten", + scrn = "screen", + ["div "] = "colorDodge", + lddg = "linearDodge", + lgCl = "lighterColor", + over = "overlay", + sLit = "softLight", + hLit = "hardLight", + vLit = "vividLight", + lLit = "linearLight", + pLit = "pinLight", + hMix = "hardMix", + diff = "difference", + smud = "exclusion", + fsub = "subtract", + fdiv = "divide", + ["hue "] = "hue", + ["sat "] = "saturation", + colr = "color", + ["lum "] = "luminosity", + pass = "passThrough", +} +local BLEND_NAMES: { [string]: string } = {} +for k, v in BLEND_KEYS do + BLEND_NAMES[v] = k +end +BLEND_NAMES.add = "lddg" + +-- colour channels per mode (the rest are alpha / spot channels) +local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 } +local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" } +-- additional layer info keys with 8-byte lengths in PSB +local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Psd.sniff(r: Bytes.Reader): number + local h = r:peek(6) + if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { psb: boolean, depth: number, mode: number, maxPixels: number, maxLayers: number } + +local function len(r: Bytes.Reader, psb: boolean): number + return if psb then r:u64be() else r:u32be() +end + +local function utf16be(s: string): string + return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) +end + +-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err +local function layerRecords(r: Bytes.Reader, c: Ctx): ({ any }?, boolean, Err.Err?) + local count = r:i16be() + local absAlpha = count < 0 + count = math.abs(count) + if r.err then + return nil, absAlpha, r.err + end + if count > c.maxLayers then + return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers") + end + local recs = {} + for li = 1, count do + local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be() + local nch = r:u16be() + if r.err then + return nil, absAlpha, r.err + end + if nch > 56 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos) + end + local chans = {} + for k = 1, nch do + chans[k] = { id = r:i16be(), size = len(r, c.psb) } + end + if r:string(4) ~= "8BIM" and not r.err then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4) + end + local key = r:string(4) + local opacity, clipping, flags = r:u8(), r:u8(), r:u8() + r:skip(1) + local extraLen = r:u32be() + if r.err then + return nil, absAlpha, r.err + end + local ex = r:slice(extraLen) + local rec: { [string]: any } = { + top = top, + left = left, + bottom = bottom, + right = right, + chans = chans, + blend = BLEND_KEYS[key] or "normal", + blendKey = key, + opacity = opacity / 255, + clip = clipping ~= 0, + hidden = bit32.band(flags, 2) ~= 0, + flags = flags, + } + -- mask data + local ml = ex:u32be() + if ml > 0 then + local mr = ex:slice(ml) + if ml >= 18 then + rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() } + end + end + -- blending ranges + ex:skip(ex:u32be()) + -- name: Pascal string padded to 4 + local nl = ex:u8() + rec.name = ex:string(nl) + ex:skip((4 - (nl + 1) % 4) % 4) + -- additional layer info + while ex:remaining() >= 12 do + local sig = ex:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = ex:string(4) + local l = if c.psb and LONG_KEYS[k] then ex:u64be() else ex:u32be() + if ex.err then + break + end + local d = ex:slice(l) + if k == "luni" then + local n = d:u32be() + local s = d:string(math.min(n * 2, d:remaining())) + rec.name = utf16be(s) + elseif k == "lsct" or k == "lsdk" then + rec.section = d:u32be() + if d:remaining() >= 8 and d:string(4) == "8BIM" then + rec.sectionBlend = d:string(4) + end + elseif k == "iOpa" then + rec.fill = d:u8() / 255 + elseif k == "lyid" then + rec.id = d:u32be() + end + end + if r.err then + return nil, absAlpha, r.err + end + recs[li] = rec + end + -- channel image data + local b = r.buf + for li, rec in recs do + local w, h = rec.right - rec.left, rec.bottom - rec.top + if w < 0 or h < 0 or w > 300000 or h > 300000 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos) + end + if w * h > c.maxPixels then + return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h)) + end + local planes: { [any]: buffer } = {} + for _, ch in rec.chans do + local p = r.pos + if ch.size < 0 or p + ch.size > r.limit then + return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p) + end + r.pos = p + ch.size + local cw, chh = w, h + if ch.id == -2 or ch.id == -3 then + local m = rec.mask + if not m then + continue + end + cw, chh = m.right - m.left, m.bottom - m.top + if cw < 0 or chh < 0 or cw * chh > c.maxPixels then + continue + end + end + if ch.size < 2 then + continue -- an empty channel + end + local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) + if not plane then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p) + end + if c.depth == 32 then + Channels.swap32(plane) + end + if ch.id == -1 then + planes.alpha = plane + elseif ch.id == -2 then + rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth) + elseif ch.id >= 0 and ch.id < 56 then + planes[ch.id + 1] = plane + end + end + local img = Types.Image.new(w, h) + if w > 0 and h > 0 then + img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil) + end + rec.image = img + end + return recs, absAlpha, nil +end + +-- records (bottom to top) -> a layer tree +local function tree(recs: { any }): { Types.Layer } + local root: { Types.Layer } = {} + local stack: { { Types.Layer } } = {} + local cur = root + local function layerOf(rec: any): Types.Layer + local l: any = { + name = rec.name, + image = rec.image, + x = rec.left, + y = rec.top, + opacity = rec.opacity, + blend = rec.blend, + visible = not rec.hidden, + } + if rec.clip then + l.clip = true + end + if rec.fill and rec.fill < 1 then + l.fillOpacity = rec.fill + end + if rec.id then + l.id = rec.id + end + if rec.mask and rec.maskPlane then + local m = rec.mask + local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8") + mi.pixels = rec.maskPlane + l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 } + end + return l + end + for _, rec in recs do + local s = rec.section + if s == 3 then + table.insert(stack, cur) + cur = {} + elseif s == 1 or s == 2 then + local g = layerOf(rec) + g.image = Types.Image.new(0, 0) + g.children = cur + if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then + g.blend = BLEND_KEYS[rec.sectionBlend] + end + ;(g :: any).collapsed = s == 2 + cur = table.remove(stack) or root + table.insert(cur, g) + else + table.insert(cur, layerOf(rec)) + end + end + -- unbalanced dividers: splice the open groups' layers back in + while #stack > 0 do + local parent = table.remove(stack) :: { Types.Layer } + for _, l in cur do + table.insert(parent, l) + end + cur = parent + end + return cur +end + +function Psd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local o: DecodeOptions = opts or {} + local c: Ctx = { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 } + if Psd.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos) + end + r:skip(4) + local version = r:u16be() + r:skip(6) + local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be() + if r.err then + return nil, r.err + end + c.psb, c.depth, c.mode = version == 2, depth, mode + if nch < 1 or nch > 56 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch) + end + local maxSide = if c.psb then 300000 else 30000 + if w < 1 or h < 1 or w > maxSide or h > maxSide then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h)) + end + if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then + return nil, Err.new(Err.CORRUPT, "bad depth " .. depth) + end + if COLOR_CHANNELS[mode] == nil then + return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode) + end + if (mode == 0) ~= (depth == 1) then + return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode") + end + if w * h > c.maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels)) + end + local layered = Types.Layered.new(w, h) + -- colour mode data + local cm = r:slice(r:u32be()) + local palette: buffer? = nil + if mode == 2 and cm:size() >= 768 then + palette = cm:bytes(768) + local pal = {} + for i = 0, 255 do + pal[i + 1] = { buffer.readu8(palette :: buffer, i), buffer.readu8(palette :: buffer, 256 + i), buffer.readu8(palette :: buffer, 512 + i), 255 } + end + layered.meta.palette = pal + end + -- image resources + local rr = r:slice(r:u32be()) + if r.err then + return nil, r.err + end + local resources = {} + while rr:remaining() >= 12 and rr:string(4) == "8BIM" do + local id = rr:u16be() + local nl = rr:u8() + local name = rr:string(nl) + rr:skip((nl + 1) % 2) + local size = rr:u32be() + if rr.err or size > rr:remaining() then + break + end + local data = rr:bytes(size) + rr:skip(size % 2) + table.insert(resources, { id = id, name = name, data = data }) + if id == 0x040F then + layered.meta.icc = data + end + end + layered.meta.resources = resources + -- layer and mask information + local lm = r:slice(len(r, c.psb)) + if r.err then + return nil, r.err + end + local recs: { any }? = nil + local absAlpha = false + if o.layers ~= false and lm:size() > 0 then + local liLen = len(lm, c.psb) + local li = lm:slice(liLen) + if lm.err then + return nil, lm.err + end + if liLen > 0 then + local list, aa, lerr = layerRecords(li, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + -- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32) + lm:skip(lm:u32be()) + while not lm.err and lm:remaining() >= 12 do + local sig = lm:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = lm:string(4) + local l = if c.psb and LONG_KEYS[k] then lm:u64be() else lm:u32be() + if lm.err then + break + end + local d = lm:slice(l) + if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then + local list, aa, lerr = layerRecords(d, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + lm:align(4) + end + end + if recs then + layered.layers = tree(recs) + end + -- the merged image + local comp = r:u16be() + if r.err then + return nil, r.err + end + local cc = COLOR_CHANNELS[mode] + if mode == 7 then + cc = math.min(nch, 3) + end + local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7 + local nread = math.min(nch, cc + (if useAlpha then 1 else 0)) + local rb = Channels.rowBytes(w, depth) + local planes: { [any]: buffer } = {} + local b = r.buf + if comp == 0 then + for k = 1, nread do + local p = r.pos + (k - 1) * rb * h + if p + rb * h > r.limit then + return nil, Err.new(Err.TRUNCATED, "merged image past the end", p) + end + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, b, p, rb * h) + planes[k] = plane + end + elseif comp == 1 then + local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb) + if not counts then + return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos) + end + local p: number = q + for k = 1, nread do + local plane = buffer.create(rb * h) + local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0) + if not np then + return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p) + end + p = np + planes[k] = plane + end + elseif comp == 2 or comp == 3 then + -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) + if not all then + return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) + end + for k = 1, nread do + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h) + planes[k] = plane + end + else + return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp) + end + if useAlpha then + planes.alpha = planes[cc + 1] + planes[cc + 1] = nil :: any + end + if depth == 32 then + for _, p in planes do + Channels.swap32(p) + end + end + local composite = Types.Image.new(w, h) + composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette) + if planes.alpha then + Channels.unmatte(composite.pixels, w * h) + end + composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] } + layered.meta.composite = composite + layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb } + return layered, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +type Rec = { layer: any, section: number?, name: string } + +local function isImage(v: any): boolean + return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function pascal(name: string): string + local s = string.gsub(name, "[\128-\255]", "?") + s = string.sub(s, 1, 255) + local pad = (4 - (#s + 1) % 4) % 4 + return string.char(#s) .. s .. string.rep("\0", pad) +end + +local function block(w: Bytes.Writer, key: string, data: string) + w:string("8BIM") + w:string(key) + local pad = (4 - #data % 4) % 4 -- additional info is padded to 4 + w:u32be(#data + pad) + w:string(data) + w:fill(0, pad) +end + +local function u32s(v: number): string + return string.char(v // 16777216 % 256, v // 65536 % 256, v // 256 % 256, v % 256) +end + +local function luni(name: string): string + local out = {} + local n = 0 + for _, cp in utf8.codes(name) do + if cp >= 0x10000 then + local v = cp - 0x10000 + local hi, lo = 0xD800 + v // 1024, 0xDC00 + v % 1024 + table.insert(out, string.char(hi // 256, hi % 256, lo // 256, lo % 256)) + n += 2 + else + table.insert(out, string.char(cp // 256, cp % 256)) + n += 1 + end + end + return u32s(n) .. table.concat(out) +end + +function Psd.encode(layered: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 300000 or H > 300000 then + return nil, Err.new(Err.ARG, "bad document size") + end + local psb = W > 30000 or H > 30000 + -- the records, bottom to top + local recs: { Rec } = {} + local bad: string? = nil + local function walk(list: { any }, depth: number) + for _, l in list do + if type(l) ~= "table" then + bad = "a layer is not a table" + return + end + if type(l.children) == "table" then + if depth > 64 then + bad = "groups nested too deep" + return + end + table.insert(recs, { layer = l, section = 3, name = "" }) + walk(l.children, depth + 1) + table.insert(recs, { layer = l, section = if l.collapsed then 2 else 1, name = tostring(l.name or "Group") }) + else + if not isImage(l.image) then + bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image" + return + end + table.insert(recs, { layer = l, name = tostring(l.name or "Layer") }) + end + end + end + walk(layered.layers, 0) + if bad then + return nil, Err.new(Err.ARG, bad :: string) + end + if #recs > 32767 then + return nil, Err.new(Err.ARG, "too many layers") + end + local function lenW(w: Bytes.Writer, v: number) + if psb then + w:u64be(v) + else + w:u32be(v) + end + end + -- layer records and channel data + local info = Bytes.writer(4096) + local data = Bytes.writer(65536) + info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency + for _, rec in recs do + local l = rec.layer + local img = if rec.section then nil else l.image + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local w, h = if img then img.width else 0, if img then img.height else 0 + if rec.section then + x, y = 0, 0 + end + info:i32be(y) + info:i32be(x) + info:i32be(y + h) + info:i32be(x + w) + local chans: { { id: number, data: buffer } } = {} + if img and w > 0 and h > 0 then + local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h) + chans = { + { id = -1, data = Channels.rleChannel(pa, w, h, psb) }, + { id = 0, data = Channels.rleChannel(pr, w, h, psb) }, + { id = 1, data = Channels.rleChannel(pg, w, h, psb) }, + { id = 2, data = Channels.rleChannel(pb, w, h, psb) }, + } + else + chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } } + end + -- the mask + local m = if rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" then l.mask else nil + local mw, mh = 0, 0 + if m then + local mi = m.image + mw, mh = mi.width, mi.height + local plane = mi.pixels + if mi.format == "rgba8" then + plane = (Channels.planes8(mi.pixels, mw, mh)) + elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then + return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8") + end + if buffer.len(plane) < mw * mh then + return nil, Err.new(Err.ARG, "bad mask image") + end + table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) }) + end + info:u16be(#chans) + for _, ch in chans do + info:i16be(ch.id) + lenW(info, buffer.len(ch.data) + 2) + data:u16be(if buffer.len(ch.data) > 0 then 1 else 0) + data:bytes(ch.data) + end + info:string("8BIM") + local blend = if type(l.blend) == "string" then l.blend else "normal" + local key = BLEND_NAMES[blend] or "norm" + if rec.section and rec.section ~= 3 then + key = if blend == "passThrough" then "pass" else key + end + info:string(key) + info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + info:u8(if l.clip and rec.section == nil then 1 else 0) + local flags = 8 -- bit 3: bit 4 is meaningful + if l.visible == false and rec.section ~= 3 then + flags += 2 + end + if rec.section then + flags += 16 -- pixel data irrelevant to the appearance + end + info:u8(flags) + info:u8(0) + local ex = Bytes.writer(256) + if m then + ex:u32be(20) + local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0) + ex:i32be(my) + ex:i32be(mx) + ex:i32be(my + mh) + ex:i32be(mx + mw) + ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255)) + ex:u8(if m.disabled then 2 else 0) + ex:u16be(0) + else + ex:u32be(0) + end + ex:u32be(0) -- blending ranges + ex:string(pascal(rec.name)) + block(ex, "luni", luni(rec.name)) + if rec.section then + block(ex, "lsct", u32s(rec.section) .. (if rec.section ~= 3 then "8BIM" .. key else "")) + end + local fill = tonumber(l.fillOpacity) + if fill and fill < 1 and rec.section == nil then + block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0") + end + local exb = ex:finish() + info:u32be(buffer.len(exb)) + info:bytes(exb) + end + info:bytes(data:finish()) + if info:tell() % 2 == 1 then + info:u8(0) + end + local infoB = info:finish() + -- the merged image + local comp: Types.Image? = opts and opts.composite + if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then + return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image") + end + local merged: buffer + if comp then + merged = comp.pixels + else + merged = buffer.create(W * H * 4) + Blend.flatten(layered.layers, merged, W, H, false) + end + local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024) + out:string("8BPS") + out:u16be(if psb then 2 else 1) + out:fill(0, 6) + out:u16be(4) + out:u32be(H) + out:u32be(W) + out:u16be(8) + out:u16be(3) + out:u32be(0) -- colour mode data + out:u32be(0) -- image resources + local lmLen = (if psb then 8 else 4) + buffer.len(infoB) + 4 + lenW(out, lmLen) + lenW(out, buffer.len(infoB)) + out:bytes(infoB) + out:u32be(0) -- global layer mask info + -- merged: RLE, all row counts first + out:u16be(1) + local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H) + local cs = if psb then 4 else 2 + local parts = {} + for k, plane in { pr, pg, pb, pa } do + local ch = Channels.rleChannel(plane, W, H, psb) + parts[k] = ch + out:bytes(ch, 0, H * cs) + end + for k = 1, 4 do + out:bytes(parts[k], H * cs) + end + return out:finish(), nil +end + +return Psd +end +__FILES["layered/psd/Channels"] = @native function() + + +-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a +-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the +-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". +-- Never throws: every read is range-checked first; failures return nil, "message". +local Deflate = __include("codecs/compress/Deflate") +local PackBits = __include("codecs/compress/PackBits") + +local Channels = {} + +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill +local floor, min, max = math.floor, math.min, math.max +local byteswap = bit32.byteswap + +-- rowBytes(w, depth) -> bytes per row of one channel +@native function Channels.rowBytes(w: number, depth: number): number + if depth == 1 then + return (w + 7) // 8 + end + return w * (depth // 8) +end + +-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil +@native function Channels.rleCounts(src: buffer, p: number, limit: number, rows: number, psb: boolean): ({ number }?, number) + local size = if psb then 4 else 2 + if rows < 0 or p + rows * size > limit then + return nil, p + end + local counts: { number } = table.create(rows) :: { number } + for i = 1, rows do + if psb then + counts[i] = byteswap(readu32(src, p)) + else + counts[i] = readu8(src, p) * 256 + readu8(src, p + 1) + end + p += size + end + return counts, p +end + +-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message +@native function Channels.rle(src: buffer, p: number, limit: number, counts: { number }, first: number, rows: number, rowBytes: number, dst: buffer, d: number): (number?, string?) + for i = 0, rows - 1 do + local c = counts[first + i] or 0 + if p + c > limit then + return nil, "RLE row past the end" + end + local _, _, clean = PackBits.decode(src, p, p + c, dst, d + i * rowBytes, rowBytes) + if not clean then + -- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too) + return nil, "bad RLE row" + end + p += c + end + return p, nil +end + +-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place +@native local function unpredict(plane: buffer, w: number, h: number, depth: number) + if depth == 8 then + for y = 0, h - 1 do + local o = y * w + local acc = readu8(plane, o) + for x = 1, w - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + end + elseif depth == 16 then + for y = 0, h - 1 do + local o = y * w * 2 + local acc = readu8(plane, o) * 256 + readu8(plane, o + 1) + for x = 1, w - 1 do + local q = o + x * 2 + acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536 + writeu8(plane, q, acc // 256) + writeu8(plane, q + 1, acc % 256) + end + end + elseif depth == 32 then + -- byte deltas over the row, then the row is 4 byte planes (all high bytes first) + local rb = w * 4 + local tmp = bcreate(rb) + for y = 0, h - 1 do + local o = y * rb + local acc = readu8(plane, o) + for x = 1, rb - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + for x = 0, w - 1 do + writeu8(tmp, x * 4, readu8(plane, o + x)) + writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x)) + writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x)) + writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x)) + end + bcopy(plane, o, tmp, 0, rb) + end + end +end + +-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the +-- 2-byte compression code and the data of one layer channel. +@native function Channels.channel(src: buffer, p: number, limit: number, w: number, h: number, depth: number, psb: boolean): (buffer?, string?) + local rb = Channels.rowBytes(w, depth) + local plane = bcreate(rb * h) + if w == 0 or h == 0 then + return plane, nil + end + if p + 2 > limit then + return nil, "channel data past the end" + end + local comp = readu8(src, p) * 256 + readu8(src, p + 1) + p += 2 + if comp == 0 then + if p + rb * h > limit then + return nil, "raw channel data past the end" + end + bcopy(plane, 0, src, p, rb * h) + elseif comp == 1 then + local counts, q = Channels.rleCounts(src, p, limit, h, psb) + if not counts then + return nil, "RLE row counts past the end" + end + local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0) + if not ok then + return nil, err + end + elseif comp == 2 or comp == 3 then + local out, err = Deflate.zlib(src, p, limit - p, rb * h) + if not out then + return nil, "ZIP channel: " .. tostring(err) + end + plane = out + if comp == 3 then + unpredict(plane, w, h, depth) + end + else + return nil, "unknown channel compression " .. comp + end + return plane, nil +end + +-- sample8(plane, i, depth) -> sample i as 0..255 +@native local function sample8(plane: buffer, i: number, depth: number): number + if depth == 8 then + return readu8(plane, i) + elseif depth == 16 then + return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) + elseif depth == 32 then + local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + if f ~= f then + return 0 + end + return floor(max(0, min(1, f)) * 255 + 0.5) + end + -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + return if readu8(plane, i // 8) // 2 ^ (7 - i % 8) % 2 == 1 then 0 else 255 +end + +-- swap32(plane): big-endian f32 samples to native order, in place +@native function Channels.swap32(plane: buffer) + for i = 0, blen(plane) // 4 - 1 do + writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) + end +end + +-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +@native local function srgb(c: number): number + c = if c <= 0.0031308 then 12.92 * c else 1.055 * c ^ (1 / 2.4) - 0.055 + return floor(max(0, min(1, c)) * 255 + 0.5) +end +@native local function lab(l8: number, a8: number, b8: number): (number, number, number) + local L = l8 * 100 / 255 + local a, b = a8 - 128, b8 - 128 + local fy = (L + 16) / 116 + local fx = fy + a / 500 + local fz = fy - b / 200 + @native local function f(t: number): number + return if t > 6 / 29 then t * t * t else 3 * (6 / 29) ^ 2 * (t - 4 / 29) + end + local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz) + local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z + local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z + local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z + return srgb(r), srgb(g), srgb(bl) +end + +-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } +-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +@native function Channels.toRGBA(planes: { [any]: buffer }, w: number, h: number, depth: number, mode: number, palette: buffer?): buffer + local n = w * h + local out = bcreate(n * 4) + local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4] + local alpha = planes.alpha + local bitmapW = (w + 7) // 8 + if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then + -- the common case, without a call per sample + local g8 = if mode == 3 and c2 and blen(c2) >= n then c2 else c1 + local b8 = if mode == 3 and c3 and blen(c3) >= n then c3 else c1 + local a8 = if alpha and blen(alpha) >= n then alpha else nil + for i = 0, n - 1 do + local a = if a8 then readu8(a8, i) else 255 + writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216) + end + return out + end + for i = 0, n - 1 do + local r, g, b = 0, 0, 0 + if mode == 3 then + r = if c1 then sample8(c1, i, depth) else 0 + g = if c2 then sample8(c2, i, depth) else r + b = if c3 then sample8(c3, i, depth) else r + elseif mode == 4 then + local cc = if c1 then sample8(c1, i, depth) else 255 + local mm = if c2 then sample8(c2, i, depth) else 255 + local yy = if c3 then sample8(c3, i, depth) else 255 + local kk = if c4 then sample8(c4, i, depth) else 255 + r = floor(cc * kk / 255 + 0.5) + g = floor(mm * kk / 255 + 0.5) + b = floor(yy * kk / 255 + 0.5) + elseif mode == 2 then + local k = if c1 then readu8(c1, i) else 0 + if palette and blen(palette) >= 768 then + r = readu8(palette, k) + g = readu8(palette, 256 + k) + b = readu8(palette, 512 + k) + else + r, g, b = k, k, k + end + elseif mode == 0 then + local y, x = i // w, i % w + local bit = if c1 then readu8(c1, y * bitmapW + x // 8) // 2 ^ (7 - x % 8) % 2 else 0 + r = if bit == 1 then 0 else 255 + g, b = r, r + elseif mode == 9 then + local L = if c1 then sample8(c1, i, depth) else 0 + local A = if c2 then sample8(c2, i, depth) else 128 + local B = if c3 then sample8(c3, i, depth) else 128 + r, g, b = lab(L, A, B) + else -- grey, duotone, multichannel: the first channel as grey + r = if c1 then sample8(c1, i, depth) else 0 + g, b = r, r + end + local a = if alpha then sample8(alpha, i, depth) else 255 + writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return out +end + +-- gray8(plane, w, h, depth) -> 1 byte per pixel +@native function Channels.gray8(plane: buffer, w: number, h: number, depth: number): buffer + local n = w * h + local out = bcreate(n) + for i = 0, n - 1 do + writeu8(out, i, sample8(plane, i, depth)) + end + return out +end + +-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it +@native function Channels.unmatte(rgba: buffer, n: number) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(rgba, o + 3) + if a == 0 then + writeu32(rgba, o, 0) + elseif a < 255 then + local f = a / 255 + for k = 0, 2 do + local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f + writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6)) + end + end + end +end + +-- matte(rgba, n) -> a copy matted with white (the writer's merged image) +@native function Channels.matte(rgba: buffer, n: number): buffer + local out = bcreate(n * 4) + bcopy(out, 0, rgba, 0, n * 4) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(out, o + 3) + if a < 255 then + local f = a / 255 + for k = 0, 2 do + writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5)) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ writer helpers +-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) +@native function Channels.packRow(src: buffer, o: number, n: number, out: buffer, d: number): number + local start = d + local i = 0 + while i < n do + -- a run of at least 3 equal bytes? + local v = readu8(src, o + i) + local run = 1 + while i + run < n and run < 128 and readu8(src, o + i + run) == v do + run += 1 + end + if run >= 3 then + writeu8(out, d, 257 - run) + writeu8(out, d + 1, v) + d += 2 + i += run + else + -- literals up to the next run of 3 + local j = i + while j < n and j - i < 128 do + if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then + break + end + j += 1 + end + local c = j - i + writeu8(out, d, c - 1) + bcopy(out, d + 1, src, o + i, c) + d += c + 1 + i = j + end + end + return d - start +end + +-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) +@native function Channels.planes8(rgba: buffer, w: number, h: number): (buffer, buffer, buffer, buffer) + local n = w * h + local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) + if blen(rgba) < n * 4 then + return r, g, b, a + end + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + writeu8(r, i, v % 256) + writeu8(g, i, v // 256 % 256) + writeu8(b, i, v // 65536 % 256) + writeu8(a, i, v // 16777216) + end + return r, g, b, a +end + +-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code +@native function Channels.rleChannel(plane: buffer, w: number, h: number, psb: boolean): buffer + local cs = if psb then 4 else 2 + local out = bcreate(h * cs + h * (w + w // 128 + 2)) + local d = h * cs + for y = 0, h - 1 do + local n = Channels.packRow(plane, y * w, w, out, d) + if psb then + writeu32(out, y * 4, byteswap(n)) + else + writeu16(out, y * 2, byteswap(n) // 65536) + end + d += n + end + local res = bcreate(d) + bcopy(res, 0, out, 0, d) + return res +end + +return Channels +end +__FILES["model/3ds"] = function() + +-- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the +-- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference +-- for transforms and conventions; no code ported) and lib3ds (layouts only). +-- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, +-- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and +-- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials +-- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, +-- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as +-- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / +-- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the +-- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), +-- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, +-- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / +-- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from +-- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects +-- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not +-- applied), the keyframer frame range. +-- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first +-- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural +-- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on +-- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") +local Write = __include("model/3ds/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeDs = { + name = "3ds", + category = "model", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) + maxVertices: number?, -- refuse more vertices in total (default 2^24) +} +type EncodeOptions = { + flipV: boolean?, -- default true (the inverse of decode) + fps: number?, -- seconds -> keyframer frames (default 30) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeDs.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then + return 0 + end + local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8) + local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216 + local child = c1 + c2 * 256 + if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then + return 0 + end + return if size == r.limit - r.pos then 0.95 else 0.7 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) + if not raw then + return nil, Err.from(msg, at) + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene = pcall(Build.scene, raw, opts :: any) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeDs.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts :: any) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return ThreeDs +end +__FILES["model/3ds/Build"] = function() + +-- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world +-- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * +-- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix +-- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key +-- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's +-- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position +-- are averaged; group 0 is flat). Times are frame / fps. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Read = __include("model/3ds/Read") + +local Build = {} + +local S = Types.Scene +local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32 +local band = bit32.band +local sqrt, abs = math.sqrt, math.abs + +type Options = { normals: boolean?, flipV: boolean?, fps: number? } + +-- ------------------------------------------------------------------------------------------------ math +-- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 +local function meshMatrix(m: { number }?): { number } + if not m then + return Mat4.identity() + end + return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 } +end +Build.meshMatrix = meshMatrix + +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) +end +Build.det3 = det3 + +-- q(a) * q(b) +local function qmul(a: { number }, b: { number }): { number } + local ax, ay, az, aw = a[1], a[2], a[3], a[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end +Build.qmul = qmul + +-- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +local function keyQuat(angle: number, x: number, y: number, z: number): { number } + if x == 0 and y == 0 and z == 0 then + return { 0, 0, 0, 1 } + end + return Mat4.axisAngle(x, y, z, -math.deg(angle)) +end + +local function normalize(x: number, y: number, z: number): (number, number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0, 0 + end + return x / l, y / l, z / l, l +end + +-- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +function Build.lookAt(p: { number }, t: { number }, roll: number): { number } + local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) + if l == 0 then + fx, fy, fz = 0, 1, 0 + end + local ux, uy, uz = 0, 0, 1 + if abs(fz) > 0.999999 then + ux, uy, uz = 0, 1, 0 + end + -- right = forward x up, up = right x forward + local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) + ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx + local a = math.rad(roll) + local c, s = math.cos(a), math.sin(a) + local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz + local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz + return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +-- ------------------------------------------------------------------------------------------------ accessors +local function floats(values: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #values // comps) + for i = 1, (#values // comps) * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" } + +local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number } + local byName: { [string]: number } = {} + local texByFile: { [string]: number } = {} + local function texture(m: Read.Map): Types.TextureRef? + local file = m.file + if not file or file == "" then + return nil + end + local ti = texByFile[file] + if not ti then + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + local tiling = m.tiling or 0 + local wrap: any = if band(tiling, 0x10) ~= 0 then "clamp" elseif band(tiling, 0x2) ~= 0 then "mirror" else "repeat" + local tex: Types.Texture = { name = file, uri = file, mime = MIME[ext] :: string?, sampler = { wrapS = wrap, wrapT = wrap } } + table.insert(scene.textures, tex) + ti = #scene.textures + texByFile[file] = ti + end + local ref: Types.TextureRef = { texture = ti } + local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0 + if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then + ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) } + end + return ref + end + for i, m in raw.materials do + local mat = S.material(m.name) + local d = m.diffuse or { 0.5, 0.5, 0.5 } + local transparency = math.clamp(m.transparency or 0, 0, 1) + mat.baseColor = { d[1], d[2], d[3], 1 - transparency } + mat.metallic = 0 + mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1) + local si = m.selfIllum or 0 + if si > 0 then + mat.emissive = { d[1] * si, d[2] * si, d[3] * si } + end + mat.alphaMode = if transparency > 0 then "blend" else "opaque" + mat.doubleSided = m.twoSided + local maps: { [string]: any } = {} + for kind, mp in m.maps do + local ref = texture(mp) + maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture } + if kind == "diffuse" then + mat.baseColorTexture = ref + elseif kind == "selfIllum" and ref then + mat.emissiveTexture = ref + if si <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + mat.extras = { + ["3ds"] = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess, + shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum, + shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps, + }, + } + table.insert(scene.materials, mat) + local key = string.lower(m.name) + if byName[key] == nil then + byName[key] = i + end + end + return byName +end + +-- ------------------------------------------------------------------------------------------------ meshes +-- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved +-- by xf (world -> the node's local space) +local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh + local nv, nf = m.nv, m.nf + local pos, faces = m.positions, m.faces + -- local positions + local lp = table.create(nv * 3, 0) + for v = 0, nv - 1 do + local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) + lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z + end + -- faces with valid corners, their materials + local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) + local valid = table.create(nf, false) + for f = 0, nf - 1 do + local a, b, c = readu16(faces :: buffer, f * 8), readu16(faces :: buffer, f * 8 + 2), readu16(faces :: buffer, f * 8 + 4) + fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c + valid[f + 1] = a < nv and b < nv and c < nv + end + local fmat = table.create(nf, 0) + for _, fm in m.faceMats do + local mi = matByName[string.lower(fm.name)] or 0 + for _, f in fm.faces do + if f < nf then + fmat[f + 1] = mi + end + end + end + local smooth = m.smoothing + local doNormals = opts.normals ~= false + -- face normals (area weighted) and the faces around each distinct position + local fn = table.create(nf * 3, 0) + local around: { [number]: { number } } = {} + local group = table.create(nv, 0) + if doNormals then + local keyToGroup: { [string]: number } = {} + for v = 0, nv - 1 do + local k = buffer.readstring(pos, v * 12, 12) + local g = keyToGroup[k] + if not g then + g = v + keyToGroup[k] = g + end + group[v + 1] = g + end + for f = 1, nf do + if valid[f] then + local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3 + local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3] + local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3] + fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { fa[f], fb[f], fc[f] } do + local g = group[v + 1] + local list = around[g] + if not list then + list = {} + around[g] = list + end + if list[#list] ~= f then + table.insert(list, f) + end + end + end + end + end + local function sgOf(f: number): number + return if smooth then readu32(smooth, (f - 1) * 4) else 1 + end + local function cornerNormal(f: number, v: number, sg: number): (number, number, number) + local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] + if sg ~= 0 then + local sx, sy, sz = 0, 0, 0 + for _, g in around[group[v + 1]] do + if band(sgOf(g), sg) ~= 0 then + sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3] + end + end + local nx, ny, nz, l = normalize(sx, sy, sz) + if l > 0 then + return nx, ny, nz + end + end + local nx, ny, nz = normalize(x, y, z) + return nx, ny, nz + end + -- primitives in the order their material first appears + local order: { number } = {} + local byMat: { [number]: { number } } = {} + for f = 1, nf do + if valid[f] then + local mi = fmat[f] + if not byMat[mi] then + byMat[mi] = {} + table.insert(order, mi) + end + table.insert(byMat[mi], f) + end + end + local uvs, nuv = m.uvs, m.nuv + local flipV = opts.flipV ~= false + local out: Types.Mesh = { name = name, primitives = {} } + for _, mi in order do + local list = byMat[mi] + local remap: { [number]: number } = {} + local P: { number }, N: { number }, U: { number } = {}, {}, {} + local idx = table.create(#list * 3, 0) + local sgs = table.create(#list, 0) + local count = 0 + for i, f in list do + local sg = sgOf(f) + sgs[i] = sg + for k, v in { fa[f], fb[f], fc[f] } do + local key = if not doNormals then v elseif sg ~= 0 then v * 4294967296 + sg else -(f * 65536 + v + 1) + local o: number = remap[key] or -1 + if o < 0 then + o = count + count += 1 + remap[key] = o + P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] + if doNormals then + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg) + end + if uvs then + local u: number, w: number = 0, 0 + if v < nuv then + u = readf32(uvs, v * 8) + w = readf32(uvs, v * 8 + 4) + end + U[o * 2 + 1] = u + U[o * 2 + 2] = if flipV then 1 - w else w + end + end + idx[(i - 1) * 3 + k] = o + end + end + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3) }, + indices = ind, + mode = "triangles", + material = if mi > 0 then mi else nil, + extras = { ["3ds"] = { smoothing = sgs } }, + } + if doNormals then + prim.attributes.NORMAL = floats(N, 3) + end + if uvs then + prim.attributes.TEXCOORD_0 = floats(U, 2) + end + table.insert(out.primitives, prim) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ tracks +-- the value of a track at a frame (linear between keys, clamped at the ends) +local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } + if not t or #t.frames == 0 then + return default + end + local fr, vals, n = t.frames, t.values, t.size + local function at(k: number): { number } + local r = table.create(n, 0) + for c = 1, n do + r[c] = vals[(k - 1) * n + c] + end + return r + end + if frame <= fr[1] then + return at(1) + end + for k = 1, #fr - 1 do + local f0, f1 = fr[k], fr[k + 1] + if frame <= f1 then + local u = if f1 > f0 then (frame - f0) / (f1 - f0) else 1 + local a, b = at(k), at(k + 1) + for c = 1, n do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return at(#fr) +end + +local function first(t: Read.Track?, default: { number }): { number } + return evalTrack(t, -math.huge, default) +end + +local function scaleKey(v: { number }): { number } + return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } +end + +-- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys +local function rotations(t: Read.Track): ({ number }, { { number } }) + local frames, quats = {}, {} + local acc: { number }? = nil + for k = 1, #t.frames do + local o = (k - 1) * 4 + local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4] + if acc == nil then + acc = keyQuat(angle, x, y, z) + else + local prev = acc :: { number } + local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64) + local f0 = frames[#frames] + for s = 1, steps - 1 do + table.insert(frames, f0 + (t.frames[k] - f0) * s / steps) + table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z))) + end + acc = qmul(prev, keyQuat(angle, x, y, z)) + end + local q = acc :: { number } + local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if n > 0 then + q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n } + end + acc = q + table.insert(frames, t.frames[k]) + table.insert(quats, q) + end + return frames, quats +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene + local o: Options = opts or {} + local fps = o.fps or 30 + local scene = S.new() + local matByName = materials(raw, scene) + -- objects by name + local objByName: { [string]: Read.Object } = {} + for _, obj in raw.objects do + if objByName[obj.name] == nil then + objByName[obj.name] = obj + end + local low = string.lower(obj.name) + if objByName[low] == nil then + objByName[low] = obj + end + end + local function findObj(name: string): Read.Object? + return objByName[name] or objByName[string.lower(name)] + end + local meshCache: { [any]: number } = {} + local function meshOf(obj: Read.Object, pivot: { number }?, placed: boolean): number? + local m = obj.mesh + if not m or m.nf == 0 or not m.faces then + return nil + end + local pv = pivot or { 0, 0, 0 } + local key = obj.name .. (if placed then string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) else "|free") + if meshCache[key] then + return meshCache[key] + end + local M = meshMatrix(m.matrix) + local inv = Mat4.inverse(M) or Mat4.identity() + local xf = inv + if placed then + if det3(M) < 0 then + xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf) + end + xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf) + end + local me = mesh(obj.name, m, xf, matByName, o) + if #me.primitives == 0 then + return nil + end + table.insert(scene.meshes, me) + meshCache[key] = #scene.meshes + return #scene.meshes + end + local camIndex: { [Read.Object]: number } = {} + local function cameraOf(obj: Read.Object): number + if camIndex[obj] then + return camIndex[obj] + end + local c = obj.camera :: Read.Camera + local hfov = if c.lens > 1e-3 then 2400 / c.lens else 45 + hfov = math.clamp(hfov, 0.01, 179) + local aspect = 4 / 3 + local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect) + local near = if c.near and c.near > 0 then c.near else 0.1 + local far = if c.far and c.far > near then c.far else nil + local cam: Types.Camera = { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + table.insert(scene.cameras, cam) + camIndex[obj] = #scene.cameras + return #scene.cameras + end + local lightIndex: { [Read.Object]: number } = {} + local function lightOf(obj: Read.Object): number + if lightIndex[obj] then + return lightIndex[obj] + end + local l = obj.light :: Read.Light + local L: Types.Light = { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier } + if l.spot then + L.type = "spot" + local hot = math.clamp(l.spot.hotspot, 0, 179.9) + local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9) + L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2 + end + if l.attenuate and l.outer and l.outer > 0 then + L.range = l.outer + end + table.insert(scene.lights, L) + lightIndex[obj] = #scene.lights + return #scene.lights + end + + local kf = raw.keyframer + local kfNodes = if kf then kf.nodes else {} + -- targets of cameras / spotlights by name + local targets: { [string]: Read.Node } = {} + for _, n in kfNodes do + if n.kind == "target" or n.kind == "lightTarget" then + targets[n.name] = targets[n.name] or n + end + end + local placedObj: { [Read.Object]: boolean } = {} + local sceneOf: { [number]: number } = {} -- kf id -> scene node + local channels: { Types.Channel } = {} + local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) + for i = 1, #times do + times[i] /= fps + end + local ch: Types.Channel = { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" } + table.insert(channels, ch) + end + local function addNode(n: Types.Node, parent: number?): number + table.insert(scene.nodes, n) + local i = #scene.nodes + if parent then + table.insert(scene.nodes[parent].children, i) + else + table.insert(scene.roots, i) + end + return i + end + + for k, kn in kfNodes do + local kind = kn.kind + if kind == "target" or kind == "lightTarget" or kind == "ambient" then + continue + end + local id = kn.id or (k - 1) + local parent = if kn.parent >= 0 then sceneOf[kn.parent] else nil + local obj = findObj(kn.name) + local tr = kn.tracks + local name = if kn.instance and kn.instance ~= "" then kn.instance else kn.name + local node: Types.Node = { name = name, children = {} } + local x3ds: { [string]: any } = { kind = kind, object = kn.name, id = id, pivot = kn.pivot } + node.extras = { ["3ds"] = x3ds } + local animated = false + if kind == "object" then + if obj and obj.mesh then + node.mesh = meshOf(obj, kn.pivot, true) + placedObj[obj] = true + x3ds.hidden = obj.hidden or nil + end + node.translation = first(tr.pos, { 0, 0, 0 }) + node.rotation = if tr.rot and #tr.rot.frames > 0 then (select(2, rotations(tr.rot)) :: any)[1] else { 0, 0, 0, 1 } + node.scale = scaleKey(first(tr.scl, { 1, 1, 1 })) + local ni = addNode(node, parent) + sceneOf[id] = ni + if tr.pos and #tr.pos.frames > 1 then + channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3) + end + if tr.rot and #tr.rot.frames > 1 then + local frames, quats = rotations(tr.rot) + local vals = {} + for _, q in quats do + table.move(q, 1, 4, #vals + 1, vals) + end + channel(ni, "rotation", frames, vals, 4) + end + if tr.scl and #tr.scl.frames > 1 then + local vals = {} + for i = 1, #tr.scl.frames do + local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] }) + table.move(v, 1, 3, #vals + 1, vals) + end + channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) + end + else + -- cameras and lights: position, target, roll + local isCam = kind == "camera" + local cam = if obj and isCam then obj.camera else nil + local lit = if obj and not isCam then obj.light else nil + local tgt = targets[kn.name] + local basePos = if cam then cam.pos elseif lit then lit.pos else { 0, 0, 0 } + local baseTgt = if cam then cam.target elseif lit and lit.spot then lit.spot.target else nil + local aims = isCam or kind == "spot" or baseTgt ~= nil + local function pose(frame: number): ({ number }, { number }?) + local p = evalTrack(tr.pos, frame, basePos) + if not aims then + return p, nil + end + local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] }) + local roll = evalTrack(tr.roll, frame, { if cam then cam.roll else 0 })[1] + return p, Build.lookAt(p, t, roll) + end + local p0, r0 = pose(-math.huge) + node.translation, node.rotation = p0, r0 + if cam then + node.camera = cameraOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.lens, x3ds.roll = cam.lens, cam.roll + elseif lit then + node.light = lightOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.off = lit.off or nil + end + local ni = addNode(node, parent) + sceneOf[id] = ni + -- every key time of the position, roll and target tracks + local set: { [number]: boolean } = {} + local times: { number } = {} + for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do + if t and #t.frames > 1 then + animated = true + end + for _, f in (if t then t.frames else {}) :: { number } do + if not set[f] then + set[f] = true + table.insert(times, f) + end + end + end + if animated then + table.sort(times) + local tv, rv = {}, {} + for _, f in times do + local p, r = pose(f) + table.move(p, 1, 3, #tv + 1, tv) + if r then + table.move(r, 1, 4, #rv + 1, rv) + end + end + channel(ni, "translation", table.clone(times), tv, 3) + if aims then + channel(ni, "rotation", times, rv, 4) + end + end + end + end + -- objects the keyframer does not place (or files without one): at their own matrix / position + for _, obj in raw.objects do + if placedObj[obj] then + continue + end + local node: Types.Node = { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } } + if obj.mesh then + local mi = meshOf(obj, nil, false) + if not mi then + continue + end + node.mesh = mi + if obj.mesh.matrix then + node.matrix = meshMatrix(obj.mesh.matrix) + end + elseif obj.camera then + local c = obj.camera + node.camera = cameraOf(obj) + node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll) + elseif obj.light then + local l = obj.light + node.light = lightOf(obj) + node.translation = l.pos + if l.spot then + node.rotation = Build.lookAt(l.pos, l.spot.target, 0) + end + else + continue + end + addNode(node, nil) + end + if #channels > 0 then + table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels }) + end + scene.meta.up = "z" + scene.meta.source = { + format = "3ds", + version = raw.version, + meshVersion = raw.meshVersion, + masterScale = raw.masterScale, + ambient = raw.ambient, + keyframer = kf ~= nil, + frames = if kf and kf.first then { kf.first, kf.last } else nil, + fps = fps, + } + return scene +end + +return Build +end +__FILES["model/3ds/Read"] = function() + +-- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read +-- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their +-- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes +-- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). +-- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is +-- clipped to the parent. Never throws on bad data: returns nil, message, offset. +local Read = {} + +local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ chunk ids +local C = { + MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100, + RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031, + AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130, + UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620, + ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700, + CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010, + MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, + MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084, + MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351, + MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C, + KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011, + NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022, + TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028, +} +Read.C = C + +-- material map chunks -> their name in Raw materials +Read.MAPS = { + [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", + [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", +} +-- keyframer node chunks -> kind +local NODE_KINDS = { + [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", + [0xB006] = "lightTarget", [0xB007] = "spot", +} +-- track chunks -> (field, values per key) +local TRACKS: { [number]: { any } } = { + [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, + [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Map = { file: string?, strength: number?, tiling: number?, uscale: number?, vscale: number?, uoffset: number?, voffset: number?, angle: number? } +type Material = { + name: string, + ambient: { number }?, diffuse: { number }?, specular: { number }?, + shininess: number?, shinStrength: number?, transparency: number?, selfIllum: number?, -- fractions 0..1 + twoSided: boolean, wire: boolean, shading: number?, + maps: { [string]: Map }, +} +type Mesh = { + nv: number, positions: buffer, -- nv * 3 f32 (world space) + nuv: number, uvs: buffer?, -- nuv * 2 f32 + nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) + faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers + smoothing: buffer?, -- nf u32 + matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) +} +type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } +type Light = { + pos: { number }, color: { number }, multiplier: number, off: boolean, attenuate: boolean, + inner: number?, outer: number?, spot: { target: { number }, hotspot: number, falloff: number }?, +} +type Object = { name: string, hidden: boolean, mesh: Mesh?, camera: Camera?, light: Light? } +type Track = { frames: { number }, values: { number }, size: number, flags: number } +type Node = { + kind: string, id: number?, name: string, parent: number, flags: number, instance: string?, pivot: { number }?, + tracks: { [string]: Track }, +} +type Raw = { + version: number?, meshVersion: number?, masterScale: number?, ambient: { number }?, + materials: { Material }, objects: { Object }, + keyframer: { name: string?, length: number?, first: number?, last: number?, nodes: { Node } }?, + vertices: number, +} + +-- ------------------------------------------------------------------------------------------------ helpers +type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } + +-- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error +local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) + local b = ctx.b + while p + 6 <= stop do + local id, size = readu16(b, p), readu32(b, p + 2) + if size < 6 then + return nil, nil -- padding or garbage after the last chunk + end + local e = p + size + if e > ctx.limit then + return string.format("chunk 0x%04x runs past the end of the data", id), p + end + local err, at = fn(id, p + 6, math.min(e, stop)) + if err then + return err, at + end + p = e + end + return nil, nil +end + +-- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil +local function cstring(b: buffer, p: number, stop: number): (string?, number) + for q = p, stop - 1 do + if readu8(b, q) == 0 then + return buffer.readstring(b, p, q - p), q + 1 + end + end + return nil, stop +end + +local function vec3(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } +end + +-- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +local function color(ctx: Ctx, p: number, stop: number): { number }? + local b = ctx.b + local main: { number }?, lin: { number }? = nil, nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then + local c = vec3(b, q) + if id == C.RGBF then + main = main or c + else + lin = lin or c + end + elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then + local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 } + if id == C.RGBB then + main = main or c + else + lin = lin or c + end + end + return nil, nil + end) + return main or lin +end + +-- a percentage chunk list -> a fraction 0..1 +local function percent(ctx: Ctx, p: number, stop: number): number? + local b = ctx.b + local v: number? = nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if v == nil and id == C.PERCENTW and e - q >= 2 then + v = readu16(b, q) / 100 + elseif v == nil and id == C.PERCENTF and e - q >= 4 then + v = readf32(b, q) / 100 + end + return nil, nil + end) + return v +end + +-- ------------------------------------------------------------------------------------------------ materials +local function map(ctx: Ctx, p: number, stop: number): Map + local b = ctx.b + local m: Map = {} + m.strength = percent(ctx, p, stop) + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.MAP_FILE then + m.file = cstring(b, q, e) + elseif id == C.MAP_TILING and n >= 2 then + m.tiling = readu16(b, q) + elseif n >= 4 then + local v = readf32(b, q) + if id == C.MAP_USCALE then + m.uscale = v + elseif id == C.MAP_VSCALE then + m.vscale = v + elseif id == C.MAP_UOFFSET then + m.uoffset = v + elseif id == C.MAP_VOFFSET then + m.voffset = v + elseif id == C.MAP_ANGLE then + m.angle = v + end + end + return nil, nil + end) + return m +end + +local function material(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local m: Material = { name = "", twoSided = false, wire = false, maps = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MAT_NAME then + m.name = cstring(b, q, e) or "" + elseif id == C.MAT_AMBIENT then + m.ambient = color(ctx, q, e) + elseif id == C.MAT_DIFFUSE then + m.diffuse = color(ctx, q, e) + elseif id == C.MAT_SPECULAR then + m.specular = color(ctx, q, e) + elseif id == C.MAT_SHININESS then + m.shininess = percent(ctx, q, e) + elseif id == C.MAT_SHIN_STRENGTH then + m.shinStrength = percent(ctx, q, e) + elseif id == C.MAT_TRANSPARENCY then + m.transparency = percent(ctx, q, e) + elseif id == C.MAT_SELF_ILPCT then + m.selfIllum = percent(ctx, q, e) + elseif id == C.MAT_TWO_SIDE then + m.twoSided = true + elseif id == C.MAT_WIRE then + m.wire = true + elseif id == C.MAT_SHADING and e - q >= 2 then + m.shading = readu16(b, q) + elseif Read.MAPS[id] then + m.maps[Read.MAPS[id]] = map(ctx, q, e) + end + return nil, nil + end) + table.insert(ctx.raw.materials, m) +end + +-- ------------------------------------------------------------------------------------------------ objects +local function faceList(ctx: Ctx, mesh: Mesh, p: number, stop: number): (string?, number?) + local b = ctx.b + if stop - p < 2 then + return "truncated face list", p + end + local nf = readu16(b, p) + if p + 2 + nf * 8 > stop then + return "face list runs past its chunk", p + end + local faces = buffer.create(nf * 8) + buffer.copy(faces, 0, b, p + 2, nf * 8) + mesh.nf, mesh.faces = nf, faces + return each(ctx, p + 2 + nf * 8, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.FACE_MAT then + local name, r = cstring(b, q, e) + if not name or r + 2 > e then + return "bad face material list", q + end + local n = readu16(b, r) + if r + 2 + n * 2 > e then + return "face material list runs past its chunk", q + end + local list: { number } = {} + for i = 0, n - 1 do + list[i + 1] = readu16(b, r + 2 + i * 2) + end + table.insert(mesh.faceMats, { name = name, faces = list }) + elseif id == C.SMOOTH then + local n = math.min(nf, (e - q) // 4) + local s = buffer.create(nf * 4) + buffer.copy(s, 0, b, q, n * 4) + mesh.smoothing = s + end + return nil, nil + end) +end + +local function trimesh(ctx: Ctx, p: number, stop: number): (Mesh?, string?, number?) + local b = ctx.b + local mesh: Mesh = { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} } + local err, at = each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERTICES or id == C.UVS then + if e - q < 2 then + return "truncated vertex list", q + end + local n = readu16(b, q) + local size = if id == C.VERTICES then 12 else 8 + if q + 2 + n * size > e then + return "vertex list runs past its chunk", q + end + local data = buffer.create(n * size) + buffer.copy(data, 0, b, q + 2, n * size) + if id == C.VERTICES then + ctx.raw.vertices += n + if ctx.raw.vertices > ctx.maxVertices then + return "limit: more than " .. ctx.maxVertices .. " vertices", q + end + mesh.nv, mesh.positions = n, data + else + mesh.nuv, mesh.uvs = n, data + end + elseif id == C.FACES then + return faceList(ctx, mesh, q, e) + elseif id == C.MATRIX and e - q >= 48 then + local m: { number } = {} + for i = 0, 11 do + m[i + 1] = readf32(b, q + i * 4) + end + mesh.matrix = m + end + return nil, nil + end) + if err then + return nil, err, at + end + return mesh, nil, nil +end + +local function camera(ctx: Ctx, p: number, stop: number): Camera? + local b = ctx.b + if stop - p < 32 then + return nil + end + local cam: Camera = { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) } + each(ctx, p + 32, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.CAM_RANGES and e - q >= 8 then + cam.near, cam.far = readf32(b, q), readf32(b, q + 4) + end + return nil, nil + end) + return cam +end + +local function light(ctx: Ctx, p: number, stop: number): Light? + local b = ctx.b + if stop - p < 12 then + return nil + end + local l: Light = { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false } + l.color = color(ctx, p + 12, stop) or l.color + each(ctx, p + 12, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.SPOT and n >= 20 then + l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) } + elseif id == C.LIGHT_OFF then + l.off = true + elseif id == C.ATTENUATE then + l.attenuate = true + elseif id == C.MULTIPLIER and n >= 4 then + l.multiplier = readf32(b, q) + elseif id == C.INNER_RANGE and n >= 4 then + l.inner = readf32(b, q) + elseif id == C.OUTER_RANGE and n >= 4 then + l.outer = readf32(b, q) + end + return nil, nil + end) + return l +end + +local function object(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + local name, q = cstring(b, p, stop) + if not name then + return "object without a name", p + end + local obj: Object = { name = name, hidden = false } + local err, at = each(ctx, q, stop, function(id: number, r: number, e: number): (string?, number?) + if id == C.TRIMESH then + local mesh, merr, mat = trimesh(ctx, r, e) + if not mesh then + return merr, mat + end + obj.mesh = mesh + elseif id == C.CAMERA then + obj.camera = camera(ctx, r, e) + elseif id == C.LIGHT then + obj.light = light(ctx, r, e) + elseif id == C.OBJ_HIDDEN then + obj.hidden = true + end + return nil, nil + end) + if err then + return err, at + end + table.insert(ctx.raw.objects, obj) + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ keyframer +-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of +-- tension / continuity / bias / ease to / ease from), then the values +local function track(b: buffer, p: number, stop: number, size: number): Track? + if stop - p < 14 then + return nil + end + local flags, n = readu16(b, p), readu32(b, p + 10) + local t: Track = { frames = {}, values = {}, size = size, flags = flags } + p += 14 + for _ = 1, n do + if p + 6 > stop then + break + end + local frame, spline = readu32(b, p), readu16(b, p + 4) + p += 6 + for bit = 0, 4 do + if band(spline, bit32.lshift(1, bit)) ~= 0 then + p += 4 + end + end + if p + size * 4 > stop then + break + end + table.insert(t.frames, frame) + for k = 0, size - 1 do + table.insert(t.values, readf32(b, p + k * 4)) + end + p += size * 4 + end + return t +end + +local function node(ctx: Ctx, kind: string, p: number, stop: number, list: { Node }) + local b = ctx.b + local n: Node = { kind = kind, name = "", parent = -1, flags = 0, tracks = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.NODE_ID and e - q >= 2 then + n.id = readu16(b, q) + elseif id == C.NODE_HDR then + local name, r = cstring(b, q, e) + n.name = name or "" + if r + 6 <= e then + n.flags = readu16(b, r) + n.parent = readi16(b, r + 4) + end + elseif id == C.NODE_INSTANCE then + n.instance = cstring(b, q, e) + elseif id == C.NODE_PIVOT and e - q >= 12 then + n.pivot = vec3(b, q) + elseif TRACKS[id] then + local spec = TRACKS[id] + n.tracks[spec[1]] = track(b, q, e, spec[2]) + end + return nil, nil + end) + table.insert(list, n) +end + +local function keyframer(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local kf = { nodes = {} :: { Node }, name = nil :: string?, length = nil :: number?, first = nil :: number?, last = nil :: number? } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.KF_HDR and e - q >= 2 then + local name, r = cstring(b, q + 2, e) + kf.name = name + if r + 4 <= e then + kf.length = readu32(b, r) + end + elseif id == C.KF_FRAMES and e - q >= 8 then + kf.first, kf.last = readu32(b, q), readu32(b, q + 4) + elseif NODE_KINDS[id] then + node(ctx, NODE_KINDS[id], q, e, kf.nodes) + end + return nil, nil + end) + ctx.raw.keyframer = kf +end + +-- ------------------------------------------------------------------------------------------------ parse +local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + return each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MATERIAL then + material(ctx, q, e) + elseif id == C.OBJECT then + return object(ctx, q, e) + elseif id == C.MESH_VERSION and e - q >= 4 then + ctx.raw.meshVersion = readu32(b, q) + elseif id == C.MASTER_SCALE and e - q >= 4 then + ctx.raw.masterScale = readf32(b, q) + elseif id == C.AMBIENT_LIGHT then + ctx.raw.ambient = color(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) -- some writers nest it here + end + return nil, nil + end) +end + +-- parse(b, base, limit, opts) -> Raw | nil, message, offset +function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) + if limit - base < 6 or readu16(b, base) ~= C.MAIN then + return nil, "not a 3DS file (no 0x4D4D main chunk)", base + end + local raw: Raw = { materials = {}, objects = {}, vertices = 0 } + local ctx: Ctx = { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw } + local size = readu32(b, base + 2) + if size < 6 then + return nil, "bad main chunk size", base + end + -- a main chunk declared longer than the data: truncated + if base + size > limit then + return nil, "truncated: the main chunk runs past the end of the data", base + end + local err, at = each(ctx, base + 6, base + size, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERSION and e - q >= 4 then + raw.version = readu32(b, q) + elseif id == C.EDITOR then + return editor(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) + end + return nil, nil + end) + if err then + return nil, err, at + end + return raw, nil, nil +end + +return Read +end +__FILES["model/3ds/Write"] = function() + +-- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world +-- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's +-- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 +-- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with +-- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and +-- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in +-- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key +-- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. +-- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Sampler = __include("codecs/model/Sampler") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") + +local Write = {} + +local C = Read.C +local S = Types.Scene +local writeu32 = buffer.writeu32 +local sqrt, abs = math.sqrt, math.abs + +type Options = { flipV: boolean?, fps: number?, name: string?, files: { [string]: any }?, smoothing: boolean? } + +-- ------------------------------------------------------------------------------------------------ chunks +type W = Bytes.Writer +local function open(w: W, id: number): number + local at = w.pos + w:u16le(id) + w:u32le(0) + return at +end +local function close(w: W, at: number) + writeu32(w.buf, at + 2, w.pos - at) +end +local function leaf(w: W, id: number, fn: () -> ()) + local at = open(w, id) + fn() + close(w, at) +end +local function name(s: string?, fallback: string): string + local n = string.gsub(s or "", "%z", "") + if n == "" then + n = fallback + end + return string.sub(n, 1, 63) +end + +local function colorChunk(w: W, id: number, c: { number }) + leaf(w, id, function() + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(c[k] or 0) + end + end) + leaf(w, C.RGBB, function() + for k = 1, 3 do + w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255)) + end + end) + end) +end +local function percentChunk(w: W, id: number, v: number) + leaf(w, id, function() + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100)) + end) + leaf(w, C.PERCENTF, function() + w:f32le(v * 100) + end) + end) +end + +-- ------------------------------------------------------------------------------------------------ math +local function world(scene: Types.Scene): ({ [number]: { number } }, { [number]: number }, { number }) + local W: { [number]: { number } } = {} + local parent: { [number]: number } = {} + local order: { number } = {} + local function visit(i: number, p: number?, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or W[i] or depth > 256 then + return + end + W[i] = S.mul(pm, S.nodeMatrix(n)) + parent[i] = p or 0 + table.insert(order, i) + for _, c in n.children or {} do + visit(c, i, W[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, nil, S.IDENTITY, 0) + end + return W, parent, order +end + +local function col(m: { number }, c: number): (number, number, number) + return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3] +end +local function unit(x: number, y: number, z: number): (number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0 + end + return x / l, y / l, z / l +end + +-- a quaternion -> the 3DS (clockwise angle, axis) +local function axisAngle(q: { number }): (number, number, number, number) + local x, y, z, w = q[1], q[2], q[3], q[4] + local n = sqrt(x * x + y * y + z * z + w * w) + if n < 1e-30 then + return 0, 0, 0, 0 + end + x, y, z, w = x / n, y / n, z / n, w / n + local s = sqrt(x * x + y * y + z * z) + if s < 1e-12 then + return 0, 0, 0, 0 + end + local angle = 2 * math.atan2(s, w) + return -angle, x / s, y / s, z / s +end + +local function conj(q: { number }): { number } + return { -q[1], -q[2], -q[3], q[4] } +end + +-- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) +local function sample(ch: Types.Channel, t: number): { number } + local f = Sampler.channel(ch) + if not f then + return if ch.path == "rotation" then { 0, 0, 0, 1 } else { 0, 0, 0 } + end + return f(t) +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" } + +local function textureFiles(scene: Types.Scene, opts: Options): { [number]: string } + local files = opts.files + local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture" + local out: { [number]: string } = {} + for i, tex in scene.textures do + local file = tex.uri + if not file or file == "" or string.sub(file, 1, 5) == "data:" then + file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + if tex.data and type(files) == "table" then + files[file] = tex.data + end + end + out[i] = file + end + return out +end + +local MAP_IDS: { [string]: number } = {} +for id, kind in Read.MAPS do + MAP_IDS[kind] = id +end +local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" } + +local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [number]: string }) + local x = (m.extras and m.extras["3ds"] or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + local diffuse = { bc[1], bc[2], bc[3] } + local shininess = math.clamp(1 - (m.roughness or 1), 0, 1) + local transparency = math.clamp(1 - (bc[4] or 1), 0, 1) + local e = m.emissive or { 0, 0, 0 } + local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1) + local at = open(w, C.MATERIAL) + leaf(w, C.MAT_NAME, function() + w:cstring(mname) + end) + colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse) + colorChunk(w, C.MAT_DIFFUSE, diffuse) + colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 }) + percentChunk(w, C.MAT_SHININESS, shininess) + percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5) + percentChunk(w, C.MAT_TRANSPARENCY, transparency) + percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum) + leaf(w, C.MAT_SHADING, function() + w:u16le(x.shading or 3) + end) + if m.doubleSided then + leaf(w, C.MAT_TWO_SIDE, function() end) + end + if x.wire then + leaf(w, C.MAT_WIRE, function() end) + end + -- maps: the PBR texture refs first, then the other kinds model/3ds read + local maps: { [string]: any } = {} + local function fromRef(ref: Types.TextureRef?, saved: any): any + if not ref or not files[ref.texture] then + return nil + end + local s = saved or {} + local tf = ref.transform + return { + file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling, + uscale = if tf and tf.scale then tf.scale[1] else s.uscale, vscale = if tf and tf.scale then tf.scale[2] else s.vscale, + uoffset = if tf and tf.offset then tf.offset[1] else s.uoffset, voffset = if tf and tf.offset then tf.offset[2] else s.voffset, + angle = if tf and tf.rotation then math.deg(tf.rotation) else s.angle, + } + end + local saved = (x.maps or {}) :: { [string]: any } + maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) + maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum) + for kind, s in saved do + if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then + maps[kind] = fromRef(if s.texture then { texture = s.texture } else nil, s) + end + end + for _, kind in MAP_ORDER do + local mp = maps[kind] + if mp then + local mat = open(w, MAP_IDS[kind]) + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100)) + end) + leaf(w, C.MAP_FILE, function() + w:cstring(name(mp.file, "texture")) + end) + if mp.tiling then + leaf(w, C.MAP_TILING, function() + w:u16le(mp.tiling) + end) + end + for _, f in { { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } } do + local v = f[2] + if type(v) == "number" then + leaf(w, f[1], function() + w:f32le(v) + end) + end + end + close(w, mat) + end + end + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } + +-- the mesh as 3DS parts (local space), or nil, message +local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean + return n == "TEXCOORD_0" or n == "NORMAL" + end, { triangulate = true }) + if not merged then + return nil, err + end + local P = merged.attrs.POSITION.values + local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values + local T = merged.attrs.TEXCOORD_0 + local tv, tc = if T then T.values else nil, if T then T.components else 0 + local flipV = opts.flipV ~= false + local corners = merged.corners + -- per face: material, smoothing group + local nf = #corners // 3 + local fmat, fsg = table.create(nf, 0), table.create(nf, 1) + for _, part in merged.parts do + local prim: any = part.prim + local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing + local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles" + for f = part.firstFace + 1, part.firstFace + part.faceCount do + fmat[f] = if type(prim.material) == "number" then prim.material else 0 + if savedOk then + fsg[f] = saved[f - part.firstFace] + elseif N then + -- flat when every corner normal is the face normal + local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] + local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } + local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } + local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]) + local flat = true + for _, v in { a, b, c } do + local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3]) + if vx * nx + vy * ny + vz * nz < 0.9998 then + flat = false + end + end + fsg[f] = if flat then 0 else 1 + end + end + end + local out: { Part } = {} + local cur: Part? = nil + local remap: { [number]: number } = {} + local count = 0 + for f = 1, nf do + local fresh = 0 + for k = 1, 3 do + if not remap[corners[f * 3 - 3 + k]] then + fresh += 1 + end + end + if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then + cur = { name = if #out == 0 then base else string.sub(base, 1, 56) .. "." .. #out, positions = {}, uvs = if tv then {} else nil, faces = {}, smooth = {}, mats = {} } + table.insert(out, cur :: Part) + remap, count = {}, 0 + end + local p = cur :: Part + for k = 1, 3 do + local v = corners[f * 3 - 3 + k] + local o = remap[v] + if not o then + o = count + count += 1 + remap[v] = o + table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions) + if tv and p.uvs then + local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0 + table.insert(p.uvs, u) + table.insert(p.uvs, if flipV then 1 - vv else vv) + end + end + table.insert(p.faces, o) + end + table.insert(p.smooth, fsg[f]) + local mi = fmat[f] + if mi > 0 then + p.mats[mi] = p.mats[mi] or {} + table.insert(p.mats[mi], #p.smooth - 1) + end + end + return out, nil +end + +local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: string }) + local at = open(w, C.OBJECT) + w:cstring(part.name) + local tm = open(w, C.TRIMESH) + local nv = #part.positions // 3 + leaf(w, C.VERTICES, function() + w:u16le(nv) + local p = part.positions + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3]) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + if part.uvs then + local uvs = part.uvs + leaf(w, C.UVS, function() + w:u16le(nv) + for i = 1, nv * 2 do + w:f32le(uvs[i] or 0) + end + end) + end + leaf(w, C.MATRIX, function() + for _, c in { 0, 1, 2, 3 } do + local x, y, z = col(M, c) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + local fl = open(w, C.FACES) + local nf = #part.smooth + w:u16le(nf) + for f = 0, nf - 1 do + w:u16le(part.faces[f * 3 + 1]) + w:u16le(part.faces[f * 3 + 2]) + w:u16le(part.faces[f * 3 + 3]) + w:u16le(7) -- edges AB, BC, CA visible + end + local mats: { number } = {} + for mi in part.mats do + table.insert(mats, mi) + end + table.sort(mats) + for _, mi in mats do + local list = part.mats[mi] + leaf(w, C.FACE_MAT, function() + w:cstring(matNames[mi]) + w:u16le(#list) + for _, f in list do + w:u16le(f) + end + end) + end + leaf(w, C.SMOOTH, function() + for _, s in part.smooth do + w:u32le(s) + end + end) + close(w, fl) + close(w, tm) + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ cameras / lights +-- the eye, target and roll of a node's world matrix (looking down -Z, Y up) +local function aim(m: { number }, dist: number): ({ number }, { number }, number) + local p = { m[13], m[14], m[15] } + local fx, fy, fz = unit(-m[9], -m[10], -m[11]) + if fx == 0 and fy == 0 and fz == 0 then + fx, fy, fz = 0, 0, -1 + end + local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } + -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis + local q0 = Build.lookAt(p, t, 0) + local m0 = Mat4.fromQuat(q0) + local ux, uy, uz = unit(m[5], m[6], m[7]) + local cu = ux * m0[5] + uy * m0[6] + uz * m0[7] + local cr = ux * m0[1] + uy * m0[2] + uz * m0[3] + return p, t, math.deg(math.atan2(-cr, cu)) +end + +local function writeCamera(w: W, cname: string, cam: Types.Camera, m: { number }, dist: number) + local p, t, roll = aim(m, dist) + local aspect = cam.aspect or 4 / 3 + local yfov = if cam.type == "perspective" and cam.yfov then cam.yfov else math.rad(45) + local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect)) + local at = open(w, C.OBJECT) + w:cstring(cname) + local c = open(w, C.CAMERA) + for _, v in { p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) } do + w:f32le(v) + end + leaf(w, C.CAM_RANGES, function() + w:f32le(cam.znear or 0) + w:f32le(cam.zfar or 1000) + end) + close(w, c) + close(w, at) +end + +local function writeLight(w: W, lname: string, l: Types.Light, m: { number }, dist: number) + local p, t = aim(m, dist) + local at = open(w, C.OBJECT) + w:cstring(lname) + local c = open(w, C.LIGHT) + for k = 13, 15 do + w:f32le(m[k]) + end + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(l.color and l.color[k] or 1) + end + end) + if l.type ~= "point" then + local inner = if l.type == "spot" then (l.innerCone or 0) else math.rad(45) + local outer = if l.type == "spot" then (l.outerCone or math.pi / 4) else math.rad(45) + leaf(w, C.SPOT, function() + for k = 1, 3 do + w:f32le(t[k]) + end + w:f32le(math.deg(inner * 2)) + w:f32le(math.deg(math.max(outer, inner) * 2)) + end) + end + if l.range and l.range > 0 then + leaf(w, C.ATTENUATE, function() end) + leaf(w, C.OUTER_RANGE, function() + w:f32le(l.range :: number) + end) + end + leaf(w, C.MULTIPLIER, function() + w:f32le(l.intensity or 1) + end) + close(w, c) + close(w, at) + return p +end + +-- ------------------------------------------------------------------------------------------------ keyframer +local function writeTrack(w: W, id: number, frames: { number }, values: { number }, size: number) + leaf(w, id, function() + w:u16le(0) + w:u32le(0) + w:u32le(0) + w:u32le(#frames) + for k, f in frames do + w:u32le(f) + w:u16le(0) + for c = 1, size do + w:f32le(values[(k - 1) * size + c]) + end + end + end) +end + +type KfNode = { + chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + frames: { [string]: { number } }, values: { [string]: { number } }, +} + +-- frames (rounded, strictly increasing) and the indices of the channel keys they keep +local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) + local IN = S.reader(ch.input) :: any + local frames, keep = {}, {} + for k = 0, ch.input.count - 1 do + local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5)) + if #frames == 0 or f > frames[#frames] then + table.insert(frames, f) + table.insert(keep, k) + end + end + return frames, keep +end + +local function channelValues(ch: Types.Channel, keep: { number }, comps: number): { { number } } + local OUT = S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + local out = {} + for _, k in keep do + local e = if cubic then k * 3 + 1 else k + local v = table.create(comps, 0) + for c = 1, comps do + v[c] = OUT(e, c - 1) + end + table.insert(out, v) + end + return out +end + +local function rotTrack(quats: { { number } }): { number } + local vals = {} + local prev: { number }? = nil + for _, q in quats do + local d = q + if prev then + d = Build.qmul(conj(prev), q) + if d[4] < 0 then + d = { -d[1], -d[2], -d[3], -d[4] } + end + end + local a, x, y, z = axisAngle(d) + table.insert(vals, a) + table.insert(vals, x) + table.insert(vals, y) + table.insert(vals, z) + prev = q + end + return vals +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local fps = o.fps or 30 + local W, parentOf, order = world(scene) + local w = Bytes.writer(65536) + local main = open(w, C.MAIN) + leaf(w, C.VERSION, function() + w:u32le(3) + end) + local ed = open(w, C.EDITOR) + leaf(w, C.MESH_VERSION, function() + w:u32le(3) + end) + -- materials (unique names) + local files = textureFiles(scene, o) + local matNames: { [number]: string } = {} + local used: { [string]: boolean } = {} + local function unique(base: string): string + local n, k = base, 1 + while used[string.lower(n)] do + k += 1 + n = string.sub(base, 1, 56) .. "_" .. k + end + used[string.lower(n)] = true + return n + end + for i, m in scene.materials do + matNames[i] = unique(name(m.name, "Material" .. i)) + writeMaterial(w, m, matNames[i], files) + end + leaf(w, C.MASTER_SCALE, function() + w:f32le(1) + end) + -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) + used = {} + local firstNode: { [number]: number } = {} + for _, i in order do + local mi = scene.nodes[i].mesh + if mi and scene.meshes[mi] and not firstNode[mi] then + firstNode[mi] = i + end + end + local meshParts: { [number]: { Part } } = {} + local meshM: { [number]: { number } } = {} + for mi, mesh in scene.meshes do + local ni = firstNode[mi] + if ni == nil and #scene.nodes > 0 then + continue + end + local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o) + if not list then + return nil, err + end + local M = if ni then W[ni] else S.IDENTITY + if not Mat4.inverse(M) then + M = S.IDENTITY + end + meshParts[mi], meshM[mi] = list, M + for _, part in list do + used[string.lower(part.name)] = true + writeMesh(w, part, M, matNames) + end + end + -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors + local KW: { [number]: { number } } = {} + for _, i in order do + local n = scene.nodes[i] + local m = W[i] + if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then + m = S.mul(m, Mat4.scaling(-1, 1, 1)) + end + KW[i] = m + end + local kfs: { KfNode } = {} + local kfOf: { [number]: number } = {} + local anim = scene.animations[1] + local byNode: { [number]: { [string]: Types.Channel } } = {} + if anim then + for _, ch in anim.channels do + if ch.path ~= "weights" then + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + end + local lastFrame = 0 + local function single(v: { number }): { number } + return table.clone(v) + end + for _, i in order do + local n = scene.nodes[i] + local p = parentOf[i] + local pk = if p ~= 0 then kfOf[p] else nil + local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) + local dist = 100 + local function placeCamLight(kind: number, objName: string, tgtChunk: number?) + local pos, tgt, roll = aim(W[i], dist) + local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } + table.insert(kfs, kn) + local idx = #kfs + -- animated root cameras / lights: position, target and roll at the key times + local chs: any = if p == 0 then byNode[i] else nil + local targetFrames, targetVals = { 0 }, tgt + if chs and (chs.translation or chs.rotation) then + local fr: { [number]: boolean } = {} + local frames: { number } = {} + local list: { Types.Channel } = {} + table.insert(list, chs.translation) + table.insert(list, chs.rotation) + for _, ch in list do + for _, f in (frameKeys(ch, fps)) do + if not fr[f] then + fr[f] = true + table.insert(frames, f) + end + end + end + table.sort(frames) + local pv, tv, rv = {}, {}, {} + for _, f in frames do + local t = f / fps + local ct, cr = chs.translation, chs.rotation + local tr = if ct then sample(ct, t) else { W[i][13], W[i][14], W[i][15] } + local rq = if cr then sample(cr, t) else (n.rotation or { 0, 0, 0, 1 }) + local sc = n.scale or { 1, 1, 1 } + local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist) + table.move(ps, 1, 3, #pv + 1, pv) + table.move(ts, 1, 3, #tv + 1, tv) + table.insert(rv, rs) + lastFrame = math.max(lastFrame, f) + end + kn.frames.pos, kn.values.pos = frames, pv + kn.frames.roll, kn.values.roll = frames, rv + targetFrames, targetVals = frames, tv + end + if tgtChunk then + table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } }) + end + if kind ~= 0xB003 then + kn.frames.roll, kn.values.roll = nil :: any, nil :: any + end + return idx + end + local function camLight(onlyThis: boolean): number? + if not camOrLight then + return nil + end + local idx: number? = nil + if n.camera and scene.cameras[n.camera] then + local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera)) + writeCamera(w, cname, scene.cameras[n.camera], W[i], dist) + idx = placeCamLight(0xB003, cname, 0xB004) + end + if n.light and scene.lights[n.light] then + local l = scene.lights[n.light] + local lname = unique(name(l.name or n.name, "Light" .. n.light)) + writeLight(w, lname, l, W[i], dist) + local k = placeCamLight(if l.type == "point" then 0xB005 else 0xB007, lname, if l.type == "point" then nil else 0xB006) + idx = idx or k + end + if onlyThis and idx then + kfOf[i] = idx + -- the node's frame in the keyframer: the camera / light pose + local kn = kfs[idx] + local pos = kn.values.pos + local m: { number } = W[i] + if kn.chunk == 0xB005 then + KW[i] = Mat4.translation(pos[1], pos[2], pos[3]) + else + local _, tgt, roll = aim(m, dist) + KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, if kn.chunk == 0xB003 then roll else 0), nil) + end + end + return idx + end + if n.mesh == nil and camOrLight then + camLight(true) + continue + end + -- an object node (or a dummy) with the node's transform relative to its keyframer parent + local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY + local inv = Mat4.inverse(pkw) or Mat4.identity() + local L = S.mul(inv, KW[i]) + local t, r, s = Mat4.decompose(L) + local plist = if n.mesh then meshParts[n.mesh] else nil + local objName = if plist then plist[1].name else "$$$DUMMY" + local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil + local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } + -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) + local chs = byNode[i] + if chs then + local own = S.nodeMatrix(n) + local same = true + for k = 1, 16 do + if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then + same = false + end + end + if same then + for path, field in { translation = "pos", rotation = "rot", scale = "scl" } :: { [string]: string } do + local ch = chs[path] + if ch then + local frames, keep = frameKeys(ch, fps) + local vals = channelValues(ch, keep, if path == "rotation" then 4 else 3) + lastFrame = math.max(lastFrame, frames[#frames] or 0) + kn.frames[field] = frames + if path == "rotation" then + kn.values[field] = rotTrack(vals) + else + local flat = {} + for _, v in vals do + table.move(v, 1, 3, #flat + 1, flat) + end + kn.values[field] = flat + end + end + end + end + end + table.insert(kfs, kn) + kfOf[i] = #kfs + for k = 2, if plist then #plist else 0 do + local extra = table.clone(kn) + extra.name, extra.instance = (plist :: { Part })[k].name, nil + table.insert(kfs, extra) + end + camLight(false) + end + close(w, ed) + -- the keyframer + local kf = open(w, C.KEYFRAMER) + leaf(w, C.KF_HDR, function() + w:u16le(5) + w:cstring("MAXSCENE") + w:u32le(math.max(lastFrame, 100)) + end) + leaf(w, C.KF_FRAMES, function() + w:u32le(0) + w:u32le(math.max(lastFrame, 100)) + end) + for id, kn in kfs do + local nc = open(w, kn.chunk) + leaf(w, C.NODE_ID, function() + w:u16le(id - 1) + end) + leaf(w, C.NODE_HDR, function() + w:cstring(kn.name) + w:u16le(0x4000) + w:u16le(0) + w:u16le(if kn.parent >= 0 then kn.parent else 0xFFFF) + end) + if kn.instance then + leaf(w, C.NODE_INSTANCE, function() + w:cstring(kn.instance :: string) + end) + end + if kn.chunk == 0xB002 then + leaf(w, C.NODE_PIVOT, function() + w:f32le(0) + w:f32le(0) + w:f32le(0) + end) + end + for _, tr in { { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } } do + local field = tr[1] :: string + local frames = kn.frames[field] + if frames then + writeTrack(w, tr[2] :: number, frames, kn.values[field], tr[3] :: number) + end + end + close(w, nc) + end + close(w, kf) + close(w, main) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/3mf"] = function() + +-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, +-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts +-- (codecs/text/Xml). +-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from +-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices +-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata +-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours +-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to +-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it +-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first +-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices +-- are split where a vertex's corners carry different colours / texture coordinates. +-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a +-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, +-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). +-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are +-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Read = __include("model/3mf/Read") +local Write = __include("model/3mf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeMf = { + name = "3mf", + category = "model", + extensions = { "3mf" }, + mime = { "model/3mf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25) + maxNodes: number?, -- refuse more object instances (default 2^20) +} +type EncodeOptions = { + unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else + -- millimeter); positions are scaled through the build transforms when meta.unit differs + level: number?, -- deflate level for the XML parts (default 6; 0 stores them) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeMf.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "PK\3\4" then + return 0 + end + -- the central directory sits at the end: look for the model part's name there, then at the start + local n = r:size() + local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) + if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then + return 0.95 + end + local head = r:peek(256) + if string.find(head, "3D/", 1, true) then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local ok, scene, err = pcall(Read.scene, zip, opts or {}) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")") + end + return scene, err +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then + return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit)) + end + local ok, out, err = pcall(Write.build, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")") + end + return out, err +end + +return ThreeMf +end +__FILES["model/3mf/Read"] = function() + +-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first +-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), +-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension +-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, +-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. +-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and +-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Read = {} + +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +Read.UNITS = UNITS +local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" } +local MAX_DEPTH = 64 + +local localName = Xml.localName + +-- an attribute by local name (namespaced attributes such as p:path) +local function attr(node: any, name: string): string? + local a = node.attrs + local v = a[name] + if v ~= nil then + return v + end + for k, x in next, a do + if type(k) == "string" and localName(k) == name then + return x + end + end + return nil +end + +local function int(s: string?): number? + local n = if s then tonumber(s) else nil + if n and n == math.floor(n) and n >= 0 then + return n + end + return nil +end + +-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +local function hexColor(s: string?): { number }? + if type(s) ~= "string" then + return nil + end + local h = string.match(s, "^%s*#(%x+)%s*$") + if not h or (#h ~= 6 and #h ~= 8) then + return nil + end + local function c(i: number): number + return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255 + end + return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 } +end +Read.hexColor = hexColor + +function Read.toLinear(c: number): number + if c <= 0.04045 then + return c / 12.92 + end + return ((c + 0.055) / 1.055) ^ 2.4 +end +local toLinear = Read.toLinear + +-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +local function transform(s: string?): ({ number }?, boolean) + if not s then + return nil, true + end + local v = {} + for w in string.gmatch(s, "%S+") do + local n = tonumber(w) + if not n or n ~= n or n == math.huge or n == -math.huge then + return nil, false + end + table.insert(v, n) + end + if #v ~= 12 then + return nil, false + end + local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 } + for i = 1, 16 do + if m[i] ~= Types.Scene.IDENTITY[i] then + return m, true + end + end + return nil, true +end + +local function normPath(p: string): string + p = string.gsub(p, "\\", "/") + p = string.gsub(p, "^/+", "") + return p +end + +-- one model part parsed into its resources and build +type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? } + +local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?) + local doc, err = Xml.decode(text, { parents = false }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or localName(root.name) ~= "model" then + return nil, Err.new(Err.CORRUPT, path .. ": the root element is not ") + end + local maxV = opts.maxVertices or 2 ^ 25 + local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") } + local resources: any = nil + local build: any = nil + for _, ch in Xml.children(root) do + local ln = localName(ch.name) + if ln == "metadata" then + local n = attr(ch, "name") + if n then + model.metadata[n] = Xml.text(ch) + end + elseif ln == "resources" then + resources = ch + elseif ln == "build" then + build = ch + end + end + local total = 0 + if resources then + for _, r in Xml.children(resources) do + local ln = localName(r.name) + local id = int(attr(r, "id")) + if id == nil then + continue + end + if ln == "object" then + local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") } + local mesh = Xml.child(r, "mesh") + local comps = Xml.child(r, "components") + if mesh then + local verts = Xml.child(mesh, "vertices") + local tris = Xml.child(mesh, "triangles") + local vl = if verts then Xml.children(verts, "vertex") else {} + local tl = if tris then Xml.children(tris, "triangle") else {} + total += #vl + #tl * 3 + if total > maxV then + return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners") + end + local nv = #vl + local pos = table.create(nv * 3, 0) + for i, v in vl do + local a = v.attrs + local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z) + if not x or not y or not z then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i) + end + pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z + end + local nt = #tl + local tv = table.create(nt * 3, 0) + local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none) + for i, tri in tl do + local a = tri.attrs + local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3) + if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index") + end + tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3 + local b = i * 4 - 4 + local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3) + tp[b + 1] = pid or -1 + tp[b + 2] = p1 or -1 + tp[b + 3] = p2 or p1 or -1 + tp[b + 4] = p3 or p1 or -1 + end + o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt + end + if comps then + o.components = {} + for _, c in Xml.children(comps, "component") do + local oid = int(attr(c, "objectid")) + local m, ok = transform(attr(c, "transform")) + if oid and ok then + table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") }) + end + end + end + model.res[id] = o + elseif ln == "basematerials" then + local items = {} + for _, b in Xml.children(r, "base") do + table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") }) + end + model.res[id] = { kind = "base", id = id, items = items } + elseif ln == "colorgroup" then + local items = {} + for _, c in Xml.children(r, "color") do + table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 }) + end + model.res[id] = { kind = "color", id = id, items = items } + elseif ln == "texture2d" then + model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") } + elseif ln == "texture2dgroup" then + local uvs = {} + for _, c in Xml.children(r, "tex2coord") do + table.insert(uvs, tonumber(attr(c, "u")) or 0) + table.insert(uvs, tonumber(attr(c, "v")) or 0) + end + model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 } + elseif ln == "compositematerials" then + local mats = {} + for w in string.gmatch(attr(r, "matindices") or "", "%S+") do + table.insert(mats, tonumber(w) or 0) + end + local items = {} + for _, c in Xml.children(r, "composite") do + local vals = {} + for w in string.gmatch(attr(c, "values") or "", "%S+") do + table.insert(vals, tonumber(w) or 0) + end + table.insert(items, vals) + end + model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items } + elseif ln == "multiproperties" then + local pids = {} + for w in string.gmatch(attr(r, "pids") or "", "%S+") do + table.insert(pids, tonumber(w) or -1) + end + local items = {} + for _, c in Xml.children(r, "multi") do + local ix = {} + for w in string.gmatch(attr(c, "pindices") or "", "%S+") do + table.insert(ix, tonumber(w) or 0) + end + table.insert(items, ix) + end + model.res[id] = { kind = "multi", id = id, pids = pids, items = items } + end + end + end + if build then + for _, it in Xml.children(build, "item") do + local oid = int(attr(it, "objectid")) + local m, ok = transform(attr(it, "transform")) + if oid and ok then + table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") }) + end + end + end + return model, nil +end + +-- the root model part's path +local function rootPath(zip: any): string? + local rels = zip:readString("_rels/.rels") + if rels then + local doc = Xml.decode(rels, { parents = false }) + if doc then + for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do + local t, target = attr(rel, "Type"), attr(rel, "Target") + if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then + return normPath(target) + end + end + end + end + for _, e in zip:list() do + if not e.isDir and string.find(string.lower(e.name), "%.model$") then + return e.name + end + end + return nil +end + +function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) + local rootP = rootPath(zip) + if not rootP then + return nil, Err.new(Err.CORRUPT, "no 3D model part in the package") + end + local models: { [string]: Model } = {} + local function getModel(path: string): (Model?, Err.Err?) + local p = normPath(path) + local m = models[p] + if m then + return m, nil + end + local text, err = zip:readString(p) + if not text then + return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p) + end + if string.sub(text, 1, 5) == "%3McF" then + return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped") + end + local mm, perr = parseModel(text, p, opts) + if not mm then + return nil, perr + end + models[p] = mm + return mm, nil + end + local root, rerr = getModel(rootP) + if not root then + return nil, rerr + end + + local scene = Types.Scene.new() + local unitName = root.unit or "millimeter" + scene.meta.up = "z" + scene.meta.unit = UNITS[unitName] or 1e-3 + scene.meta.metadata = root.metadata + scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } + + -- textures and materials (shared across model parts by part path + resource id) + local texCache: { [string]: number } = {} + local function texture(model: Model, id: number): number? + local key = model.path .. "#" .. id + if texCache[key] then + return texCache[key] + end + local r = model.res[id] + if not r or r.kind ~= "texture" or type(r.path) ~= "string" then + return nil + end + local data = zip:read(normPath(r.path)) + local tex: Types.Texture = { + name = r.path, + data = data, + mime = r.contenttype, + uri = r.path, + sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil }, + extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } }, + } + table.insert(scene.textures, tex) + texCache[key] = #scene.textures + return #scene.textures + end + local matCache: { [string]: number } = {} + local function addMaterial(key: string, make: () -> Types.Material): number + local i = matCache[key] + if i then + return i + end + table.insert(scene.materials, make()) + matCache[key] = #scene.materials + return #scene.materials + end + local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material + local m = Types.Scene.material(name) + m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] } + m.metallic = 0 + m.roughness = 1 + if c[4] < 1 then + m.alphaMode = "blend" + end + m.extras = { ["3mf"] = extras } + return m + end + + -- property of one corner -> (group key, material index?, kind, resource, index) + local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number) + local r = model.res[pid] + if not r or p < 0 then + return "none", nil, "none", nil, 0 + end + local k = r.kind + if k == "base" then + local item = r.items[p + 1] + if not item then + return "none", nil, "none", nil, 0 + end + local key = "b" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex }) + end), "base", r, p + elseif k == "color" then + return "c" .. model.path .. "#" .. pid, nil, "color", r, p + elseif k == "texgroup" then + local ti = r.texid and texture(model, r.texid) + local mat: number? = nil + if ti then + local mk = "t" .. model.path .. "#" .. (r.texid :: number) + mat = addMaterial(mk, function() + local m = Types.Scene.material("texture " .. tostring(r.texid)) + m.metallic = 0 + m.roughness = 1 + m.baseColorTexture = { texture = ti :: number } + m.extras = { ["3mf"] = { texture = r.texid } } + return m + end) + end + return "t" .. model.path .. "#" .. pid, mat, "tex", r, p + elseif k == "composite" then + local item = r.items[p + 1] + local base = r.matid and model.res[r.matid] + if not item or not base or base.kind ~= "base" then + return "none", nil, "none", nil, 0 + end + local key = "x" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + local c, sum = { 0, 0, 0, 0 }, 0 + for j, w in item do + local b = base.items[(r.matindices[j] or 0) + 1] + if b then + for q = 1, 4 do + c[q] += b.color[q] * w + end + sum += w + end + end + if sum > 0 then + for q = 1, 4 do + c[q] /= sum + end + else + c = { 1, 1, 1, 1 } + end + return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p }) + end), "base", r, p + elseif k == "multi" and (depth or 0) < 1 then + local item = r.items[p + 1] + local first = r.pids[1] + if item and first then + return resolve(model, first, item[1] or 0, 1) + end + end + return "none", nil, "none", nil, 0 + end + + -- one Scene mesh per (part, object) with a mesh + local meshCache: { [string]: number } = {} + local function buildMesh(model: Model, o: any): number? + local key = model.path .. "#" .. o.id + local cached = meshCache[key] + if cached ~= nil then + return if cached > 0 then cached else nil + end + local groups: { [string]: any } = {} + local order: { any } = {} + local pos, tv, tp = o.positions, o.tv, o.tp + for t = 0, o.nt - 1 do + local pid = tp[t * 4 + 1] + local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] } + if pid < 0 then + pid = o.pid or -1 + if ps[1] < 0 then + local d = o.pindex or (if pid >= 0 then 0 else -1) + ps = { d, d, d } + end + end + local gkey, mat, kind, res, _ = resolve(model, pid, ps[1]) + local g = groups[gkey] + if not g then + g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 } + groups[gkey] = g + table.insert(order, g) + end + for c = 1, 3 do + local v = tv[t * 3 + c] + local vk = v + local pc = 0 + if kind == "color" or kind == "tex" then + pc = ps[c] + local cnt = if kind == "color" then #res.items else res.count + if pc < 0 or pc >= cnt then + pc = ps[1] + end + if pc < 0 or pc >= cnt then + pc = 0 + end + vk = v * (cnt + 1) + pc + end + local ni = g.vmap[vk] + if not ni then + ni = g.n + g.n += 1 + g.vmap[vk] = ni + table.insert(g.pos, pos[v * 3 + 1]) + table.insert(g.pos, pos[v * 3 + 2]) + table.insert(g.pos, pos[v * 3 + 3]) + if kind == "color" then + local col = res.items[pc + 1] or { 1, 1, 1, 1 } + table.insert(g.attr, toLinear(col[1])) + table.insert(g.attr, toLinear(col[2])) + table.insert(g.attr, toLinear(col[3])) + table.insert(g.attr, col[4]) + elseif kind == "tex" then + table.insert(g.attr, res.uvs[pc * 2 + 1] or 0) + table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0)) + end + end + table.insert(g.idx, ni) + end + end + local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } } + for _, g in order do + local n = g.n + local pa = Types.Scene.accessor(nil, "f32", 3, n) + for i, x in g.pos do + buffer.writef32(pa.data, (i - 1) * 4, x) + end + local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx) + for i, x in g.idx do + buffer.writeu32(ia.data, (i - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material } + if g.kind == "color" then + local ca = Types.Scene.accessor(nil, "f32", 4, n) + for i, x in g.attr do + buffer.writef32(ca.data, (i - 1) * 4, x) + end + prim.attributes.COLOR_0 = ca + prim.extras = { ["3mf"] = { colorgroup = g.res.id } } + elseif g.kind == "tex" then + local ua = Types.Scene.accessor(nil, "f32", 2, n) + for i, x in g.attr do + buffer.writef32(ua.data, (i - 1) * 4, x) + end + prim.attributes.TEXCOORD_0 = ua + prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } } + end + table.insert(mesh.primitives, prim) + end + if #mesh.primitives == 0 then + meshCache[key] = 0 + return nil + end + table.insert(scene.meshes, mesh) + meshCache[key] = #scene.meshes + return #scene.meshes + end + + -- nodes: one per object instance (build items and components) + local nodeCount = 0 + local maxNodes = opts.maxNodes or 2 ^ 20 + local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?) + function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?) + if depth > MAX_DEPTH then + return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)") + end + nodeCount += 1 + if nodeCount > maxNodes then + return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances") + end + local o = model.res[oid] + if not o or o.kind ~= "object" then + return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path) + end + local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } } + table.insert(scene.nodes, node) + local index = #scene.nodes + if o.positions then + node.mesh = buildMesh(model, o) + end + if o.components then + for _, c in o.components do + local m: Model? = model + if c.path then + local mm, err = getModel(c.path) + if not mm then + return nil, err + end + m = mm + end + local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path }) + if not child then + return nil, err + end + table.insert(node.children, child) + end + end + return index, nil + end + for _, it in root.items do + local m: Model? = root + if it.path then + local mm, err = getModel(it.path) + if not mm then + return nil, err + end + m = mm + end + local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true }) + if not idx then + return nil, err + end + table.insert(scene.roots, idx) + end + return scene, nil +end + +function Read.open(r: any): (any, Err.Err?) + return Zip.open(r) +end + +return Read +end +__FILES["model/3mf/Write"] = function() + +-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, +-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the +-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), +-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has +-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). +-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Write = {} + +local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture" +local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" } +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" } + +local fmt = string.format +local esc = Xml.escapeAttr + +local function num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 1e15 then + return fmt("%d", x) + end + return fmt("%.9g", x) +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + if c <= 0.0031308 then + return c * 12.92 + end + return 1.055 * c ^ (1 / 2.4) - 0.055 +end + +local function hex(r: number, g: number, b: number, a: number): string + local function q(x: number): number + return math.clamp(math.floor(x * 255 + 0.5), 0, 255) + end + return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) +end + +-- the triangle corner list of a primitive (0-based vertex indices) or nil +local function triangles(prim: any): { number }? + local pos = prim.attributes and prim.attributes.POSITION + if type(pos) ~= "table" then + return nil + end + local n = pos.count + local ix: { number } = {} + if prim.indices then + local get = Types.Scene.reader(prim.indices) + if not get then + return nil + end + for i = 0, prim.indices.count - 1 do + ix[i + 1] = get(i, 0) + end + else + for i = 1, n do + ix[i] = i - 1 + end + end + for _, v in ix do + if v ~= v or v < 0 or v >= n then + return nil + end + end + local mode = prim.mode or "triangles" + local out: { number } = {} + local function tri(a: number, b: number, c: number) + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + if mode == "triangles" then + for i = 1, #ix - 2, 3 do + tri(ix[i], ix[i + 1], ix[i + 2]) + end + elseif mode == "triangle_strip" then + for i = 1, #ix - 2 do + if i % 2 == 1 then + tri(ix[i], ix[i + 1], ix[i + 2]) + else + tri(ix[i + 1], ix[i], ix[i + 2]) + end + end + elseif mode == "triangle_fan" then + for i = 2, #ix - 1 do + tri(ix[1], ix[i], ix[i + 1]) + end + elseif mode == "polygons" and prim.faces then + local get = Types.Scene.reader(prim.faces) + if not get then + return nil + end + local at = 1 + for f = 0, prim.faces.count - 1 do + local k = get(f, 0) + if at + k - 1 > #ix then + break + end + for j = 1, k - 2 do + tri(ix[at], ix[at + j], ix[at + j + 1]) + end + at += k + end + else + return nil + end + return out +end + +function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) + local o = opts or {} + local nextId = 0 + local function id(): number + nextId += 1 + return nextId + end + local res: { string } = {} -- resource XML chunks, in definition order + local files: { { name: string, data: buffer, mime: string } } = {} + + -- unit + local unitName: string, scale: number = "millimeter", 1 + local mu: any = scene.meta and scene.meta.unit + if type(o.unit) == "string" and UNITS[o.unit] then + unitName = o.unit + if type(mu) == "number" and mu > 0 then + scale = mu / UNITS[o.unit] + end + elseif type(mu) == "number" and mu > 0 then + local found = false + for _, u in UNIT_ORDER do + if math.abs(UNITS[u] - mu) <= 1e-9 * mu then + unitName, found = u, true + break + end + end + if not found then + scale = mu / 1e-3 + end + end + + -- base materials: one group with every Scene material + local baseId: number? = nil + local nmat = #scene.materials + local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local needDefault = false + if nmat > 0 then + baseId = id() + end + + -- textures used as base colour textures + local texRes: { [number]: number } = {} + local function textureId(ti: number): number? + if texRes[ti] ~= nil then + return if texRes[ti] > 0 then texRes[ti] else nil + end + local tex = scene.textures[ti] + local ext = tex and TEX_EXT[tex.mime or ""] + if not tex or type(tex.data) ~= "buffer" or not ext then + texRes[ti] = 0 + return nil + end + local rid = id() + local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string) + table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string }) + local s = tex.sampler + local function tile(w: string?): string + return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap" + end + local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto" + table.insert(res, fmt('\t\t\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter)) + texRes[ti] = rid + return rid + end + + -- objects + local objectOf: { [number]: number } = {} + local objChunks: { string } = {} + for mi, mesh in scene.meshes do + local verts: { string } = {} + local tris: { string } = {} + local base = 0 + local objPid: number?, objP: number? = nil, nil + local anyNone = false + local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + for _, prim in mesh.primitives do + local corners = triangles(prim) + if not corners or #corners == 0 then + continue + end + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + if not getP then + continue + end + local n = pos.count + for v = 0, n - 1 do + table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0))) + end + -- properties: texture group, colour group, base material, none + local pid, kind = -1, "none" + local mat = prim.material and scene.materials[prim.material] + local uv = prim.attributes.TEXCOORD_0 + local col = prim.attributes.COLOR_0 + local tref = mat and mat.baseColorTexture + local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil + if tid and uv then + local get = Types.Scene.reader(uv) + if get then + pid, kind = id(), "tex" + local parts = { fmt('\t\t\n', pid, tid) } + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t\n', num(get(v, 0)), num(1 - get(v, 1)))) + end + table.insert(parts, "\t\t\n") + table.insert(res, table.concat(parts)) + end + end + if kind == "none" and col then + local get = Types.Scene.reader(col) + if get then + pid, kind = id(), "color" + local parts = { fmt('\t\t\n', pid) } + local four = col.components >= 4 + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1))) + end + table.insert(parts, "\t\t\n") + table.insert(res, table.concat(parts)) + end + end + local pindex = -1 + if kind == "none" and baseId and prim.material and scene.materials[prim.material] then + pid, kind, pindex = baseId :: number, "base", prim.material - 1 + end + for i = 1, #corners, 3 do + local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base + if kind == "tex" or kind == "color" then + table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] }) + elseif kind == "base" then + table.insert(triList, { a, b, c, pid, pindex, pindex, pindex }) + else + table.insert(triList, { a, b, c, -1, -1, -1, -1 }) + anyNone = true + end + if objPid == nil and kind ~= "none" then + objPid, objP = pid, if kind == "base" then pindex else corners[i] + end + end + base += n + end + if #triList == 0 then + continue + end + if objPid and anyNone then + needDefault = true + if not baseId then + baseId = id() + end + end + for _, t in triList do + if t[4] < 0 and objPid then + t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase + end + if t[4] < 0 then + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3])) + elseif t[5] == t[6] and t[6] == t[7] then + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5])) + else + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7])) + end + end + local oid = id() + objectOf[mi] = oid + local head = fmt('\t\t\n\t\t\t\n\t\t\t\t\n", table.concat(verts), "\t\t\t\t\n\t\t\t\t\n", table.concat(tris), "\t\t\t\t\n\t\t\t\n\t\t\n" })) + table.insert(res, objChunks[#objChunks]) + end + + -- the base material group goes first (its id was taken first) + if baseId then + local parts = { fmt('\t\t\n', baseId) } + for _, m in scene.materials do + local c = m.baseColor or { 1, 1, 1, 1 } + table.insert(parts, fmt('\t\t\t\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1))) + end + if needDefault then + table.insert(parts, '\t\t\t\n') + end + table.insert(parts, "\t\t\n") + table.insert(res, 1, table.concat(parts)) + end + + -- build items: every node with a mesh, at its world matrix + local items: { string } = {} + local seen: { [number]: boolean } = {} + for _, pl in Types.Scene.flatten(scene) do + if seen[pl.node] then + continue + end + seen[pl.node] = true + local oid = objectOf[pl.mesh] + if not oid then + continue + end + local m = pl.matrix + local s = scale + local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s } + local ident = s == 1 + for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do + if tr[i] ~= v then + ident = false + end + end + if ident then + table.insert(items, fmt('\t\t\n', oid)) + else + local ns = table.create(12, "") + for i = 1, 12 do + ns[i] = num(tr[i]) + end + table.insert(items, fmt('\t\t\n', oid, table.concat(ns, " "))) + end + end + + -- metadata + local meta: { string } = {} + local md = scene.meta and scene.meta.metadata + if type(md) == "table" then + local keys: { string } = {} + for k: any, v: any in md do + if type(k) == "string" and (type(v) == "string" or type(v) == "number") then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + table.insert(meta, fmt('\t%s\n', esc(k), Xml.escape(tostring(md[k])))) + end + end + + local model = table.concat({ + '\n', + '\n', + table.concat(meta), + "\t\n", + table.concat(res), + "\t\n\t\n", + table.concat(items), + "\t\n\n", + }) + + local types = { '\n\n', + '\t\n', + '\t\n' } + local exts: { [string]: boolean } = {} + for _, f in files do + local e = string.match(f.name, "%.(%w+)$") :: string + if not exts[e] then + exts[e] = true + table.insert(types, fmt('\t\n', e, f.mime)) + end + end + table.insert(types, "\n") + local rels = '\n\n' + .. fmt('\t\n', REL_MODEL) + .. "\n" + + local w = Zip.writer() + local level = o.level or 6 + local method = if level == 0 then "store" else "deflate" + local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method }) + if ok then + ok, err = w:add("_rels/.rels", rels, { level = level, method = method }) + end + if ok then + ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method }) + end + if ok and #files > 0 then + local mr = { '\n\n' } + for i, f in files do + table.insert(mr, fmt('\t\n', esc(f.name), i, REL_TEXTURE)) + end + table.insert(mr, "\n") + ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method }) + for _, f in files do + if ok then + ok, err = w:add(f.name, f.data, { method = "store" }) + end + end + end + if not ok then + return nil, err or Err.new(Err.ARG, "zip writer failed") + end + return w:finish() +end + +return Write +end +__FILES["model/b3d"] = function() + +-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description +-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. +-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, +-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> +-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is +-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree +-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / +-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the +-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights +-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the +-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, +-- default 60) -> one animation of LINEAR channels at frame / fps seconds. +-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding +-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their +-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. +-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the +-- extras; texture coordinate sets of 3 / 4 components keep their first two. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/b3d/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local B3d = { + name = "b3d", + category = "model", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the files by name + maxVertices: number?, -- default 2^24 + maxDepth: number?, -- node nesting (default 256) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function B3d.sniff(r: Bytes.Reader): number + if r:peek(4) == "BB3D" then + return if r:peek(4, 8) ~= "" then 1 else 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r:peek(4) ~= "BB3D" then + return nil, Err.new(Err.CORRUPT, "no BB3D chunk") + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +return B3d +end +__FILES["model/b3d/Read"] = function() + +-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are +-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes +-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, + maxDepth: number?, +} + +local LAYOUT: Chunks.Layout = { maxChunks = 1000000 } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } } +type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number } +type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } } +type Bone = { node: number, target: MeshRec?, list: { number } } +type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } + +-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated +-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +local function vec(r: Bytes.Reader): { number } + local x, y, z = r:f32le(), r:f32le(), r:f32le() + return { x, y, -z } +end +local function quat(r: Bytes.Reader): { number } + local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le() + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 or l ~= l then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, -z / l, w / l } +end + +local function fetcher(opts: Options?): (string) -> buffer? + local files = opts and opts.files + local resolve = opts and opts.resolve + return function(uri: string): buffer? + local v: any = if type(files) == "table" then files[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- scene(r, opts) -> Scene | nil, message, kind +function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) + local buf = src.buf + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxDepth = opts and opts.maxDepth or 256 + local fetch = fetcher(opts) + local top = Chunks.walk(buf, src.base, src.limit, LAYOUT) + local head = top[1] + if not head or head.id ~= "BB3D" then + return nil, "not a BB3D file", nil + end + if head.truncated then + return nil, "truncated", "truncated" + end + local hr = Bytes.reader(buf, head.offset, head.size) + local version = hr:i32le() + if hr.err then + return nil, "truncated", "truncated" + end + + local scene = Types.Scene.new() + local texs: { TexInfo } = {} + local brushes: { Brush } = {} + local materialOf: { [number]: number } = {} -- brush index (0-based) -> material + local meshes: { MeshRec } = {} + local bones: { Bone } = {} + local nodeKeys: { [number]: Keys } = {} + local anim: { frames: number, fps: number, flags: number }? = nil + local lastMesh: MeshRec? = nil + local totalVertices = 0 + local failure: string?, failKind: string? = nil, nil + + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + local function body(c: Chunks.Chunk): Bytes.Reader + if c.truncated then + fail("truncated " .. c.id .. " chunk", "truncated") + end + return Bytes.reader(buf, c.offset, c.avail) + end + + local function readTexs(r: Bytes.Reader) + while r.pos < r.limit and not r.err do + local file = r:cstring() + local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 } + if r.err then + return fail("truncated TEXS entry", "truncated") + end + local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] } + local data = fetch(file) + if not data then + local base = string.match(file, "([^/\\]+)$") + if base and base ~= file then + data = fetch(base) + end + end + tex.data = data + if bit32.band(t.flags, 48) ~= 0 then + tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" } + end + tex.extras = { b3d = { flags = t.flags, blend = t.blend } } + table.insert(scene.textures, tex) + t.index = #scene.textures + table.insert(texs, t) + end + end + + local function readBrus(r: Bytes.Reader) + local n = r:i32le() + if r.err or n < 0 or n > 8 then + return fail("bad BRUS texture count") + end + while r.pos < r.limit and not r.err do + local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} } + for i = 1, n do + b.textures[i] = r:i32le() + end + if r.err then + return fail("truncated BRUS entry", "truncated") + end + table.insert(brushes, b) + end + end + + -- the material of brush id (0-based) | nil for -1 / out of range + local function material(id: number): number? + if id < 0 or id >= #brushes then + return nil + end + local have = materialOf[id] + if have then + return have + end + local b = brushes[id + 1] + local m = Types.Scene.material(b.name ~= "" and b.name or nil) + local c = b.color + local function clamp01(v: number): number + return if v ~= v then 1 else math.clamp(v, 0, 1) + end + m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) } + m.metallic = 0 + m.roughness = 1 - 0.8 * clamp01(b.shininess) + m.doubleSided = bit32.band(b.fx, 16) ~= 0 + if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then + m.alphaMode = "blend" + end + if bit32.band(b.fx, 1) ~= 0 then + m.extensions = { KHR_materials_unlit = {} } + end + local extraTex: { number } = {} + for i, tid in b.textures do + local t = texs[tid + 1] + if tid >= 0 and t then + if not m.baseColorTexture then + local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil } + local o, s, rot = t.offset, t.scale, t.rotation + if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot } + end + m.baseColorTexture = ref + if bit32.band(t.flags, 4) ~= 0 then + m.alphaMode = "mask" + elseif bit32.band(t.flags, 2) ~= 0 then + m.alphaMode = "blend" + end + else + extraTex[i] = t.index + end + end + end + m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } } + table.insert(scene.materials, m) + materialOf[id] = #scene.materials + return #scene.materials + end + + local function readMesh(r: Bytes.Reader, nodeIndex: number): number? + local master = r:i32le() + if r.err then + fail("truncated MESH", "truncated") + return nil + end + local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT) + local attrs: { [string]: Types.Accessor }? = nil + local count = 0 + local mesh: Types.Mesh = { primitives = {} } + local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} } + for _, c in list do + local cr = body(c) + if c.id == "VRTS" and not attrs then + local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le() + if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then + fail("bad VRTS header") + return nil + end + local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0 + local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4 + local n = (cr.limit - cr.pos) // stride + totalVertices += n + if totalVertices > maxVertices then + fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit") + return nil + end + local pos = buffer.create(n * 12) + local nrm = if hasN then buffer.create(n * 12) else nil + local col = if hasC then buffer.create(n * 16) else nil + local uvs: { buffer } = {} + for s = 1, sets do + uvs[s] = buffer.create(n * 8) + end + local readf32, writef32 = buffer.readf32, buffer.writef32 + local p = cr.pos + for i = 0, n - 1 do + writef32(pos, i * 12, readf32(buf, p)) + writef32(pos, i * 12 + 4, readf32(buf, p + 4)) + writef32(pos, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + if nrm then + writef32(nrm, i * 12, readf32(buf, p)) + writef32(nrm, i * 12 + 4, readf32(buf, p + 4)) + writef32(nrm, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + end + if col then + for k = 0, 3 do + writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4)) + end + p += 16 + end + for s = 1, sets do + if size >= 1 then + writef32(uvs[s], i * 8, readf32(buf, p)) + end + if size >= 2 then + writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4)) + end + p += size * 4 + end + end + local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) } + if nrm then + a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n) + end + if col then + a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n) + end + if size > 0 then + for s = 1, sets do + a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n) + end + end + attrs, count = a, n + mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } } + elseif c.id == "TRIS" then + local brush = cr:i32le() + if cr.err then + fail("truncated TRIS", "truncated") + return nil + end + if not attrs then + fail("TRIS before VRTS") + return nil + end + local nt = (cr.limit - cr.pos) // 12 + local idx = buffer.create(nt * 12) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + local p = cr.pos + for i = 0, nt - 1 do + local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8) + if a >= count or b >= count or cc >= count then + fail(string.format("triangle %d: vertex index out of range", i)) + return nil + end + -- mirrored z: reverse the winding to keep the faces front-facing + writeu32(idx, i * 12, a) + writeu32(idx, i * 12 + 4, cc) + writeu32(idx, i * 12 + 8, b) + p += 12 + end + local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" } + prim.material = material(if brush == -1 then master else brush) + table.insert(mesh.primitives, prim) + end + end + if not attrs then + return nil -- a mesh without vertices: the node stays a pivot + end + if #mesh.primitives == 0 then + table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) + end + table.insert(scene.meshes, mesh) + rec.mesh, rec.count = #scene.meshes, count + table.insert(meshes, rec) + lastMesh = rec + return #scene.meshes + end + + local function readBone(r: Bytes.Reader, nodeIndex: number) + local b: Bone = { node = nodeIndex, target = lastMesh, list = {} } + table.insert(bones, b) + local list = b.list + while r.pos + 8 <= r.limit do + local v, w = r:i32le(), r:f32le() + table.insert(list, v) + table.insert(list, w) + end + end + + local function readKeys(r: Bytes.Reader, nodeIndex: number) + local flags = r:i32le() + local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0) + local k = nodeKeys[nodeIndex] + if not k then + k = { t = {}, s = {}, r = {} } + nodeKeys[nodeIndex] = k + end + while not r.err and r.pos + per <= r.limit do + local frame = r:i32le() + if bit32.band(flags, 1) ~= 0 then + k.t[frame] = vec(r) + end + if bit32.band(flags, 2) ~= 0 then + local x, y, z = r:f32le(), r:f32le(), r:f32le() + k.s[frame] = { x, y, z } + end + if bit32.band(flags, 4) ~= 0 then + k.r[frame] = quat(r) + end + end + end + + local function readNode(c: Chunks.Chunk, depth: number): number? + if depth > maxDepth then + fail("limit: nodes nested deeper than " .. maxDepth, "limit") + return nil + end + local r = body(c) + local name = r:cstring() + local t = vec(r) + local sx, sy, sz = r:f32le(), r:f32le(), r:f32le() + local q = quat(r) + if r.err then + fail("truncated NODE", "truncated") + return nil + end + local node: Types.Node = { name = name, children = {} } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then + node.rotation = q + end + if sx ~= 1 or sy ~= 1 or sz ~= 1 then + node.scale = { sx, sy, sz } + end + table.insert(scene.nodes, node) + local index = #scene.nodes + for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do + if failure then + break + end + local id = sub.id + if id == "NODE" then + local child = readNode(sub, depth + 1) + if child then + table.insert(node.children, child) + end + elseif id == "MESH" and not node.mesh then + node.mesh = readMesh(body(sub), index) + elseif id == "BONE" then + readBone(body(sub), index) + elseif id == "KEYS" then + readKeys(body(sub), index) + elseif id == "ANIM" then + local ar = body(sub) + local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le() + if not ar.err and not anim then + anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 } + end + end + end + return index + end + + for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do + if failure then + break + end + if c.id == "TEXS" then + readTexs(body(c)) + elseif c.id == "BRUS" then + readBrus(body(c)) + elseif c.id == "NODE" then + local n = readNode(c, 1) + if n then + table.insert(scene.roots, n) + end + end + end + if failure then + return nil, failure, failKind + end + if #scene.nodes == 0 then + return nil, "no NODE chunk", nil + end + + -- ------------------------------------------------------------------------------------------ skins + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, ch in n.children do + parent[ch] = i + end + end + local worldCache: { [number]: { number } } = {} + local function world(i: number): { number } + local w = worldCache[i] + if not w then + local n = scene.nodes[i] + local l = Mat4.compose(n.translation, n.rotation, n.scale) + w = if parent[i] then Mat4.mul(world(parent[i]), l) else l + worldCache[i] = w + end + return w + end + local bonesOf: { [MeshRec]: { Bone } } = {} + for _, b in bones do + local m = b.target + if m then + local l = bonesOf[m] or {} + bonesOf[m] = l + table.insert(l, b) + end + end + for _, rec in meshes do + local list = bonesOf[rec] + if list then + local nv = rec.count + local inf: { { number } } = {} + local joints: { number } = {} + for j, b in list do + joints[j] = b.node + local l = b.list + for k = 1, #l, 2 do + local v, w = l[k], l[k + 1] + if v >= 0 and v < nv and w > 0 and w == w then + local e = inf[v + 1] + if not e then + e = {} + inf[v + 1] = e + end + table.insert(e, j - 1) + table.insert(e, w) + end + end + end + local self: number? = nil -- the mesh node as a joint, for vertices no bone moves + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for v = 0, nv - 1 do + local e = inf[v + 1] + if not e then + if not self then + table.insert(joints, rec.node) + self = #joints - 1 + end + buffer.writeu16(jb, v * 8, self :: number) + buffer.writef32(wb, v * 16, 1) + else + -- the 4 strongest, normalised + local order = {} + for k = 1, #e, 2 do + table.insert(order, k) + end + table.sort(order, function(a: number, b: number): boolean + return e[a + 1] > e[b + 1] + end) + local sum = 0 + for k = 1, math.min(4, #order) do + sum += e[order[k] + 1] + end + for k = 1, math.min(4, #order) do + buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]]) + buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum) + end + end + end + local meshWorld = world(rec.node) + local ibm = buffer.create(#joints * 64) + for j, ni in joints do + local inv = Mat4.inverse(world(ni)) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local ia = Types.Scene.accessor(ibm, "f32", 16, #joints) + ia.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia }) + scene.nodes[rec.node].skin = #scene.skins + local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv) + for _, prim in scene.meshes[rec.mesh].primitives do + prim.attributes.JOINTS_0 = J + prim.attributes.WEIGHTS_0 = W + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + local fps = if anim then anim.fps else 60 + local channels: { Types.Channel } = {} + for ni = 1, #scene.nodes do + local k = nodeKeys[ni] + if k then + for _, path in { "translation", "rotation", "scale" } do + local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s + local frames = {} + for f in map do + table.insert(frames, f) + end + if #frames > 0 then + table.sort(frames) + local nc = if path == "rotation" then 4 else 3 + local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4) + for i, f in frames do + buffer.writef32(input, (i - 1) * 4, f / fps) + local v = map[f] + for c = 1, nc do + buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c]) + end + end + table.insert(channels, { + node = ni, + path = path :: any, + input = Types.Scene.accessor(input, "f32", 1, #frames), + output = Types.Scene.accessor(output, "f32", nc, #frames), + interpolation = "LINEAR" :: "LINEAR", + }) + end + end + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "b3d", channels = channels }) + end + + scene.meta.up = "y" + scene.meta.source = { + format = "b3d", + version = version, + brushes = #brushes, + frames = if anim then anim.frames else nil, + fps = if anim then anim.fps else nil, + handedness = "left", -- converted: z mirrored, winding reversed + } + return scene, nil, nil +end + +return Read +end +__FILES["model/bsp"] = function() + +-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) +-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a +-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III +-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as +-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not +-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. +-- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up. +-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Brush = __include("model/bsp/Brush") +local Quake3 = __include("model/bsp/Quake3") + +-- ------------------------------------------------------------------------------------------------ contract +local Bsp = { + name = "bsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- Quake 1: the 768-byte palette + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + patchLevel: number?, -- Quake III patch subdivisions (default 4) + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" } +local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves", + "leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" } +local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes", + "brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Bsp.sniff(r: Bytes.Reader): number + if r:remaining() < 64 then + return 0 + end + local m = r:peek(4) + local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0)) + if m == "IBSP" then + return if v == 38 or v == 46 or v == 47 then 1 else 0.3 + end + if v == 29 or v == 30 then + -- no magic: check that the lump directory fits the file + local size = r:remaining() + for i = 0, 14 do + local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) + if o < 0 or n < 0 or o + n > size then + return 0 + end + end + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the entities text -> { { key = value } } +local function entities(text: string): { { [string]: string } } + local out: { { [string]: string } } = {} + for block in string.gmatch(text, "%b{}") do + local e: { [string]: string } = {} + for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do + e[k] = v + end + table.insert(out, e) + end + return out +end + +function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local b, base = r.buf, r.base + local m = r:peek(4) + local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0)) + local names: { string }, dir: number, variant: string + if m == "IBSP" and version == 38 then + names, dir, variant = Q2_LUMPS, 8, "q2" + elseif m == "IBSP" and (version == 46 or version == 47) then + names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m ~= "IBSP" and (version == 29 or version == 30) then + names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1" + elseif m == "VBSP" then + return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0) + else + return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0) + end + if dir + #names * 8 > size then + return nil, Err.new(Err.TRUNCATED, "lump directory", dir) + end + local lumps: { [string]: { at: number, size: number } } = {} + for i, name in names do + local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4) + if o < 0 or n < 0 or o + n > size then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8) + end + lumps[name] = { at = o, size = n } + end + local scene: Types.Scene?, msg: string? + if variant == "q3" then + scene, msg = Quake3.decode(b, base, lumps, opts :: any) + else + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Brush.decode(b, base, lumps, variant, { + palette = pal, + wal = function(name: string): buffer? + return Input.sibling(opts, "textures/" .. name .. ".wal") + end, + maxPixels = opts and opts.maxPixels, + maxVertices = opts and opts.maxVertices, + }) + end + if not scene then + return nil, Err.from(msg) + end + local e = lumps.entities + local text = buffer.readstring(b, base + e.at, e.size) + text = string.match(text, "^[^%z]*") :: string + scene.meta.entities = entities(text) + scene.meta.source = { + format = "bsp", + variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + version = version, + entities = text, + palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, + } + return scene, nil +end + +return Bsp +end +__FILES["model/bsp/Brush"] = function() + +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex +-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture +-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the +-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / +-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the +-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from +-- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). +-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. +-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local Brush = {} + +local Scene = Types.Scene +local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Lump = { at: number, size: number } +type Options = { + palette: buffer?, + wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size) + maxPixels: number?, + maxVertices: number?, +} + +type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean } +type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } } + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- miptex lump (Quake / Half-Life) -> textures +local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?) + local out: { Tex } = {} + if l.size < 4 then + return out, nil + end + local at = base + l.at + local n = readi32(b, at) + if n < 0 or n > 65536 or 4 + n * 4 > l.size then + return nil, "bad miptex lump" + end + local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + for i = 0, n - 1 do + local o = readi32(b, at + 4 + i * 4) + if o < 0 or o + 40 > l.size then + out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } + else + local m = at + o + local name = cstr(b, m, 16) + local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) + local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } + if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then + local px = m + off0 + local need = w * h + local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 + if o + off0 + need <= l.size then + local p = gpal + if hl then + p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil + end + local img = Types.Image.new(w, h) + if p then + Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) + else + for k = 0, need - 1 do + writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) + end + end + img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + t.image = img + end + end + out[i + 1] = t + end + end + return out, nil +end + +-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message +-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, +-- models, miptex (q1 / hl) +function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) + local q2 = variant == "q2" + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models + local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20 + local tiSize = if q2 then 76 else 40 + local nTI, nP = TI.size // tiSize, P.size // 20 + local mSize = if q2 then 48 else 64 + local nM = M.size // mSize + if nF > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many faces" + end + -- textures + local texs: { Tex } = {} + local texOf: { number } = {} -- texinfo -> texture index (1-based) + if q2 then + local byName: { [string]: number } = {} + for i = 0, nTI - 1 do + local name = cstr(b, base + TI.at + i * 76 + 40, 32) + local ti = byName[name] + if not ti then + local w, h, texels = 1, 1, true + local wal = opts and opts.wal and opts.wal(name) + if wal and buffer.len(wal) >= 40 then + w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false + end + table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels }) + ti = #texs + byName[name] = ti + end + texOf[i + 1] = ti + end + else + local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels) + if not list then + return nil, err + end + texs = list + for i = 0, nTI - 1 do + local mt = readi32(b, base + TI.at + i * 40 + 32) + texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0 + end + end + -- faces of each model + local scene = Scene.new() + scene.meta.up = "z" + local faceModel: { number } = {} + local models: { { first: number, count: number, origin: { number } } } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * mSize + local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) } + local fo = if q2 then 40 else 56 + local first, count = readi32(b, o + fo), readi32(b, o + fo + 4) + table.insert(models, { first = first, count = count, origin = origin }) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + if #models == 0 then + table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } }) + for f = 1, nF do + faceModel[f] = 1 + end + end + local batches: { [number]: { [number]: Batch } } = {} + local orders: { [number]: { number } } = {} + local skipped = 0 + for f = 0, nF - 1 do + local fo = base + Fc.at + f * 20 + local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local model = faceModel[f + 1] + if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + skipped += 1 + continue + end + -- the polygon + local poly: { number } = {} + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(b, base + SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2) + if v >= nV then + ok = false + break + end + local vo = base + V.at + v * 12 + table.insert(poly, readf32(b, vo)) + table.insert(poly, readf32(b, vo + 4)) + table.insert(poly, readf32(b, vo + 8)) + end + if not ok then + skipped += 1 + continue + end + local po = base + P.at + plane * 20 + local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + local n = #poly // 3 + local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local j = (k + 1) % n + local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3] + ax += (y1 - y2) * (z1 + z2) + ay += (z1 - z2) * (x1 + x2) + az += (x1 - x2) * (y1 + y2) + end + local order: { number } = {} + if ax * nx + ay * ny + az * nz >= 0 then + for k = 0, n - 1 do + order[k + 1] = k + end + else + order[1] = 0 + for k = 1, n - 1 do + order[k + 1] = n - k + end + end + local tio = base + TI.at + texinfo * tiSize + local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) + local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local ti = texOf[texinfo + 1] or 0 + local tex = texs[ti] + local w, h = if tex then tex.width else 1, if tex then tex.height else 1 + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[ti] + if not bt then + bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bm[ti] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, ti) + end + local batch: Batch = bt + for k = 2, n - 1 do + for _, c in { order[1], order[k], order[k + 1] } do + local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3] + local pp, nn, uu = batch.pos, batch.nrm, batch.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz + uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w + uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + end + end + end + -- textures, materials + for i, t in texs do + local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } + table.insert(scene.textures, tex) + local mat = Scene.material(t.name) + mat.metallic = 0 + local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } + mat.extras = extras + mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any + table.insert(scene.materials, mat) + end + -- meshes and nodes + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + for m, mdl in models do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, ti in list do + local bt = batches[m][ti] + local nv = #bt.pos // 3 + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, bt.pos[k]) + writef32(nb, (k - 1) * 4, bt.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, bt.uv[k]) + end + for k = 0, nv - 1 do + writeu32(ib, k * 4, k) + end + table.insert(mesh.primitives, { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = if ti > 0 then ti else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.skippedFaces = skipped + return scene, nil +end + +return Brush +end +__FILES["model/bsp/Quake3"] = function() + +-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a +-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches +-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap +-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 +-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as +-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. +-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +local Types = __include("Types") + +local Quake3 = {} + +local Scene = Types.Scene +local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8 +local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8 + +type Lump = { at: number, size: number } +type Options = { patchLevel: number?, maxVertices: number? } + +type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- decode(b, base, lumps, opts) -> Scene | nil, message +function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?) + local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps + local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152 + local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) + local maxV = opts and opts.maxVertices or 2 ^ 24 + -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + local extra: { number } = {} + local function vertex(i: number): { number } + local o = base + VX.at + i * 44 + local v = table.create(14, 0) + for k = 0, 9 do + v[k + 1] = readf32(b, o + k * 4) + end + for k = 0, 3 do + v[11 + k] = readu8(b, o + 40 + k) + end + return v + end + local function addExtra(v: { number }): number + for k = 1, 14 do + table.insert(extra, v[k]) + end + return -(#extra // 14) + end + local faceModel: { number } = {} + for m = 0, nM - 1 do + local o = base + M.at + m * 40 + local first, count = readi32(b, o + 24), readi32(b, o + 28) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + local batches: { [number]: { [string]: Batch } } = {} + local orders: { [number]: { string } } = {} + local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 } + local total = 0 + for f = 0, nF - 1 do + local o = base + F.at + f * 104 + local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28) + local model = faceModel[f + 1] or 1 + local tris: { number } = {} + if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then + for k = 0, nmv - 3, 3 do + local ok = true + local tri = {} + for c = 0, 2 do + local idx = readi32(b, base + MV.at + (mv + k + c) * 4) + if idx < 0 or idx >= n then + ok = false + end + tri[c + 1] = first + idx + end + if ok then + table.insert(tris, tri[3]) + table.insert(tris, tri[2]) + table.insert(tris, tri[1]) + end + end + counts[if kind == 1 then "polygons" else "meshes"] += 1 + elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then + local w, h = readi32(b, o + 96), readi32(b, o + 100) + if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + counts.patches += 1 + local L = level + for py = 0, (h - 1) // 2 - 1 do + for px = 0, (w - 1) // 2 - 1 do + -- the 3x3 control points of this sub-patch + local ctrl: { { number } } = {} + for j = 0, 2 do + for i = 0, 2 do + ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) + end + end + local grid: { number } = {} + for gy = 0, L do + local tv = gy / L + for gx = 0, L do + local tu = gx / L + local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } + local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } + local v = table.create(14, 0) + for j = 0, 2 do + for i = 0, 2 do + local wgt = bu[i + 1] * bv[j + 1] + local cp = ctrl[j * 3 + i + 1] + for k = 1, 14 do + v[k] += cp[k] * wgt + end + end + end + local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) + if l > 0 then + v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l + end + grid[gy * (L + 1) + gx + 1] = addExtra(v) + end + end + for gy = 0, L - 1 do + for gx = 0, L - 1 do + local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] + local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] + -- counter-clockwise for Quake's clockwise-front control grids + for _, v in { a, d, c2, c2, d, e } do + table.insert(tris, v) + end + end + end + end + end + else + counts.skipped += 1 + end + elseif kind == 4 then + counts.billboards += 1 + else + counts.skipped += 1 + end + total += #tris + if total > maxV then + return nil, "limit: too many vertices" + end + if #tris > 0 then + local key = shader .. ":" .. lm + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[key] + if not bt then + bt = { shader = shader, lightmap = lm, verts = {} } + bm[key] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, key) + end + for _, v in tris do + table.insert(bt.verts, v) + end + end + end + local scene = Scene.new() + scene.meta.up = "z" + -- shaders, lightmaps + for i = 0, nT - 1 do + local name = cstr(b, base + T.at + i * 72, 64) + table.insert(scene.textures, { name = name, uri = name }) + end + local lmTex: { [number]: number } = {} + for i = 0, nLM - 1 do + local img = Types.Image.new(128, 128) + local o = base + LM.at + i * 49152 + for k = 0, 128 * 128 - 1 do + writeu8(img.pixels, k * 4, readu8(b, o + k * 3)) + writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1)) + writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2)) + writeu8(img.pixels, k * 4 + 3, 255) + end + img.meta.source = { format = "bsp", lightmap = i } + table.insert(scene.textures, { name = "lightmap " .. i, image = img }) + lmTex[i] = #scene.textures + end + local matOf: { [string]: number } = {} + local root: Types.Node = { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelCount = math.max(nM, 1) + for m = 1, modelCount do + local list = orders[m] + if list then + local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} } + for _, key in list do + local bt = batches[m][key] + local nv = #bt.verts + local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4) + for k, id in bt.verts do + local v: { number } + if id >= 0 then + v = vertex(id) + else + local e = (-id - 1) * 14 + v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number } + end + local o = (k - 1) + writef32(pb, o * 12, v[1]) + writef32(pb, o * 12 + 4, v[2]) + writef32(pb, o * 12 + 8, v[3]) + writef32(ub, o * 8, v[4]) + writef32(ub, o * 8 + 4, v[5]) + writef32(lb, o * 8, v[6]) + writef32(lb, o * 8 + 4, v[7]) + writef32(nb, o * 12, v[8]) + writef32(nb, o * 12 + 4, v[9]) + writef32(nb, o * 12 + 8, v[10]) + for c = 0, 3 do + writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255)) + end + writeu32(ib, o * 4, o) + end + local mi = matOf[key] + if not mi then + local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader" + local mat = Scene.material(name) + mat.metallic = 0 + if bt.shader >= 0 and bt.shader < nT then + mat.baseColorTexture = { texture = bt.shader + 1 } + end + local lt = lmTex[bt.lightmap] + mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } } + table.insert(scene.materials, mat) + mi = #scene.materials + matOf[key] = mi + end + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, nv), + NORMAL = Scene.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv), + TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv), + COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv), + }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" :: any, + material = mi, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.faces = counts + return scene, nil +end + +return Quake3 +end +__FILES["model/dae"] = function() + +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its +-- manifest.xml and the images). New code. +-- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input +-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), +-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / +-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> +-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), +-- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix / +-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances +-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under +-- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph +-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; +-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as +-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE +-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, +-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" +-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left +-- origin (opts.flipV = false keeps Collada's). +-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. +-- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves +-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than +-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") +local Read = __include("model/dae/Read") +local Write = __include("model/dae/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Dae = { + name = "dae", + category = "model", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths + files: { [string]: any }?, -- or: the files by uri / base name + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention) + maxVertices: number?, -- refuse more output vertices / array values (default 2^25) +} +type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Dae.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + if string.sub(head, 1, 4) == "PK\3\4" then + local nlen = string.byte(head, 27) or 0 + local name = string.lower(string.sub(head, 31, 30 + nlen)) + if string.find(name, "%.dae$") or name == "manifest.xml" then + return 0.95 + end + return 0 + end + -- UTF-16 files: drop the zero bytes + if string.find(string.sub(head, 1, 4), "\0", 1, true) then + head = string.gsub(head, "%z", "") + end + if string.find(head, ", else the first .dae entry +local function zae(r: Bytes.Reader): (any, string?, Err.Err?) + local zip, err = Zip.open(r) + if not zip then + return nil, nil, err + end + local main: string? = nil + local manifest = zip:readString("manifest.xml") + if manifest then + local d = Xml.decode(manifest) + local rootEl = d and d.root and Xml.child(d.root :: Xml.Node, "dae_root") + if rootEl then + main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") + main = main and string.gsub(main, "^%./", "") + end + end + if not main or not zip:find(main) then + main = nil + for _, e in zip:list() do + if string.find(string.lower(e.name), "%.dae$") then + main = e.name + break + end + end + end + if not main then + return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae") + end + local text, rerr = zip:readString(main) + if not text then + return nil, nil, rerr + end + return zip, text, nil +end + +function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text: string + local zip: any = nil + if r:peek(4) == "PK\3\4" then + local z, t, err = zae(r) + if not z then + return nil, err + end + zip, text = z, t :: string + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local scene, err = Read.scene(doc, fetcher(opts, zip), opts) + if not scene then + return nil, err + end + if zip and scene.meta.source then + scene.meta.source.zae = true + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "zae" then + -- a zip: manifest.xml, the .dae and its images + local files = {} + local o = table.clone(opts) + o.files = files + o.name = "model.dae" + local text = Write.build(scene, o) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + local w = Zip.writer() + w:add("manifest.xml", '\n./model.dae\n') + w:add("model.dae", text) + local names = {} + for name in files do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + w:add(name, files[name], { method = "store" }) + end + return w:finish() + end + local text = Write.build(scene, opts) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + return buffer.fromstring(text), nil +end + +return Dae +end +__FILES["model/dae/Math"] = function() + +-- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices, +-- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +local Mat4 = __include("codecs/model/Mat4") + +local DaeMath = {} + +local sqrt, rad = math.sqrt, math.rad + +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function norm(a: { number }): { number } + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + if l < 1e-20 then + return { 0, 0, 0 } + end + return { a[1] / l, a[2] / l, a[3] / l } +end + +-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +function DaeMath.lookat(v: { number }): { number } + local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 + local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) + local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z)) + local y = cross(z, x) + return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } +end + +-- skew(angle, rotation axis, translation axis) (RenderMan's skew) +function DaeMath.skew(v: { number }): { number } + local a = rad(v[1] or 0) + local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) + local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) + local s = math.tan(a) + local m = Mat4.identity() + -- M = I + s * t * r^T (column-major: m[col*4 + row]) + for row = 0, 2 do + for col = 0, 2 do + m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] + end + end + return m +end + +return DaeMath +end +__FILES["model/dae/Read"] = function() + +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / +-- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile +-- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, +-- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / +-- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin +-- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as +-- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform +-- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS +-- channels; one animation per animation clip, else one for the file). +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local M = __include("model/dae/Math") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Fetch = (uri: string) -> buffer? + +local Scene = Types.Scene +local find, sub, gmatch, match, lower, upper = string.find, string.sub, string.gmatch, string.match, string.lower, string.upper +local children, child, text = Xml.children, Xml.child, Xml.text + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" } +local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" } +local PARAM_SIZE: { [string]: number } = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } +local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 } + +-- ------------------------------------------------------------------------------------------------ helpers +local function numbers(s: string, limit: number): ({ number }?, string?) + local out = {} + local n = 0 + for w in gmatch(s, "[^%s]+") do + n += 1 + if n > limit then + return nil, "array over the limit" + end + local v = tonumber(w) + if v == nil and find(w, ",", 1, true) and not find(w, ".", 1, true) then + v = tonumber((string.gsub(w, ",", "."))) -- decimal commas (some 3ds Max exporters) + end + if v == nil then + local lw = lower(w) + v = if lw == "nan" or lw == "-nan" or lw == "1.#qnan" or lw == "-1.#ind" then 0 elseif lw == "inf" or lw == "1.#inf" then math.huge elseif lw == "-inf" or lw == "-1.#inf" then -math.huge elseif lw == "true" then 1 elseif lw == "false" then 0 else 0 + end + out[n] = v :: number + end + return out, nil +end +local function words(s: string): { string } + local out = {} + for w in gmatch(s, "[^%s]+") do + table.insert(out, w) + end + return out +end +local function attr(node: any, name: string): string? + local v = node and node.attrs and node.attrs[name] + return if type(v) == "string" then v else nil +end +local function urlId(url: string?): string? + if not url then + return nil + end + return match(url, "^#(.*)$") or url +end +local function lname(node: any): string + return Xml.localName(node.name) +end +local function numText(node: any, default: number): number + if not node then + return default + end + return tonumber(match(text(node), "[^%s]+") or "") or default +end +local function color(node: any): { number }? + local c = node and child(node, "color") + if not c then + return nil + end + local v = numbers(text(c), 16) or {} + return { v[1] or 0, v[2] or 0, v[3] or 0, v[4] or 1 } +end + +type Ctx = { + doc: any, + ids: { [string]: any }, + fetch: Fetch, + scene: Types.Scene, + limit: number, + vertices: number, + flipV: boolean, + triangulate: boolean, + sources: { [any]: any }, + materials: { [string]: number }, + textures: { [string]: number }, + images: { [string]: any }, + meshes: { [string]: number }, + skins: { [string]: number }, + posIndex: { [any]: { number } }, + nodeOf: { [string]: { number } }, -- collada node id -> scene nodes + info: { [number]: any }, -- scene node -> { el, xf, sid, cid } + pendingSkins: { any }, + skipped: { [string]: number }, + err: string?, + depth: number, +} + +local function skip(C: Ctx, what: string) + C.skipped[what] = (C.skipped[what] or 0) + 1 +end + +-- ------------------------------------------------------------------------------------------------ sources +-- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) +local function readSource(C: Ctx, el: any): any + local cached = C.sources[el] + if cached ~= nil then + return cached or nil + end + C.sources[el] = false + local arrEl: any = nil + local strings = false + for _, ch in children(el) do + local n = lname(ch) + if n == "float_array" or n == "int_array" or n == "bool_array" then + arrEl = ch + elseif n == "Name_array" or n == "IDREF_array" or n == "SIDREF_array" or n == "token_array" then + arrEl, strings = ch, true + end + end + local values: { any } = {} + if arrEl then + if strings then + values = words(text(arrEl)) + else + local v, e = numbers(text(arrEl), C.limit) + if not v then + C.err = e + return nil + end + values = v + end + end + local tc = child(el, "technique_common") + local acc = tc and child(tc, "accessor") + local out: any + if not acc then + out = { data = values, comps = 1, count = #values } + else + local count = tonumber(attr(acc, "count") or "") or 0 + local stride = tonumber(attr(acc, "stride") or "") or 1 + local offset = tonumber(attr(acc, "offset") or "") or 0 + local picks = {} + local pos = 0 + local anyNamed = false + for _, p in children(acc, "param") do + if attr(p, "name") then + anyNamed = true + end + end + for _, p in children(acc, "param") do + local w = PARAM_SIZE[attr(p, "type") or ""] or 1 + if attr(p, "name") or not anyNamed then + for k = 0, w - 1 do + table.insert(picks, pos + k) + end + end + pos += w + end + if #picks == 0 then + for k = 0, stride - 1 do + table.insert(picks, k) + end + end + if stride < 1 or count < 0 or count * stride > C.limit * 16 then + C.err = "bad accessor" + return nil + end + count = math.min(count, math.max(0, (#values - offset) // math.max(stride, 1))) + local comps = #picks + local data = table.create(count * comps) + local n = 0 + for i = 0, count - 1 do + local base = offset + i * stride + 1 + for _, k in picks do + n += 1 + data[n] = values[base + k] or 0 + end + end + out = { data = data, comps = comps, count = count } + end + C.sources[el] = out + return out +end + +local function sourceById(C: Ctx, url: string?): any + local id = urlId(url) + local el = id and C.ids[id] + if not el or lname(el) ~= "source" then + return nil + end + return readSource(C, el) +end + +-- ------------------------------------------------------------------------------------------------ images, materials +local function fetchImage(C: Ctx, ref: string): (buffer?, string) + local uri = ref + uri = string.gsub(uri, "^file:///(%a:)", "%1") + uri = string.gsub(uri, "^file://", "") + local data = C.fetch(uri) + if not data then + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + data = C.fetch(decoded) + if not data then + local base = match(decoded, "([^/\\]+)$") + if base and base ~= decoded then + data = C.fetch(base) + end + end + end + return data, uri +end + +local function image(C: Ctx, id: string): any + local cached = C.images[id] + if cached ~= nil then + return cached or nil + end + C.images[id] = false + local el = C.ids[id] + if not el or lname(el) ~= "image" then + return nil + end + local img: any = { name = attr(el, "name") or id } + local init = child(el, "init_from") + local hex: any = child(el, "data") + if init then + local ref = child(init, "ref") + local s = match(text(ref or init), "^%s*(.-)%s*$") or "" + if s ~= "" then + if sub(s, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(s) + if d then + img.data, img.mime = d, mime + end + else + local d, uri = fetchImage(C, s) + img.data, img.uri = d, uri + local ext = match(uri, "%.([%w]+)$") + img.mime = ext and MIME[lower(ext)] + end + end + hex = hex or child(init, "hex") + end + if hex and not img.data then + local h = string.gsub(text(hex), "%s+", "") + if #h % 2 == 0 and not find(h, "[^%x]") then + local b = buffer.create(#h // 2) + for i = 0, #h // 2 - 1 do + buffer.writeu8(b, i, tonumber(sub(h, i * 2 + 1, i * 2 + 2), 16) :: number) + end + img.data = b + local fmt = attr(hex, "format") or attr(el, "format") + img.mime = fmt and MIME[lower(fmt)] + end + end + if img.data and not img.mime then + local b = img.data + if buffer.len(b) >= 4 then + local m4 = buffer.readstring(b, 0, 4) + img.mime = if m4 == "\137PNG" then "image/png" elseif sub(m4, 1, 3) == "\255\216\255" then "image/jpeg" else nil + end + end + C.images[id] = img + return img +end + +-- the effect's newparams by sid (this level and the profile's) +local function newparams(effect: any, profile: any, technique: any): { [string]: any } + local out = {} + for _, scope in { effect, profile, technique } do + if scope then + for _, np in children(scope, "newparam") do + local sid = attr(np, "sid") + if sid then + out[sid] = np + end + end + end + end + return out +end + +-- texture(effect params, sampler sid) -> scene texture index +local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? + local np = params[samplerSid] + local imageId: string? = nil + local sampler: any = nil + if np then + local s2d = child(np, "sampler2D") or child(np, "samplerCUBE") or child(np, "sampler3D") + if s2d then + sampler = s2d + local inst = child(s2d, "instance_image") + if inst then + imageId = urlId(attr(inst, "url")) + else + local src = child(s2d, "source") + local surfNp = src and params[match(text(src), "^%s*(.-)%s*$") or ""] + local surf = surfNp and child(surfNp, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + local surf = child(np, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + -- many exporters reference the image id directly + imageId = samplerSid + end + if not imageId then + return nil + end + local key = imageId .. "|" .. samplerSid + local cached = C.textures[key] + if cached then + return cached + end + local img = image(C, imageId) + if not img then + return nil + end + local tex: Types.Texture = { name = img.name, data = img.data, mime = img.mime, uri = img.uri } + if sampler then + local ws, wt = child(sampler, "wrap_s"), child(sampler, "wrap_t") + local mag = child(sampler, "magfilter") + local smp: Types.Sampler = {} + if ws then + smp.wrapS = WRAP[upper(match(text(ws), "[%w_]+") or "")] :: any + end + if wt then + smp.wrapT = WRAP[upper(match(text(wt), "[%w_]+") or "")] :: any + end + if mag then + local f = upper(match(text(mag), "[%w_]+") or "") + smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil + end + if next(smp :: any) then + tex.sampler = smp + end + end + table.insert(C.scene.textures, tex) + local idx = #C.scene.textures + C.textures[key] = idx + return idx +end + +-- one colour-or-texture parameter of a common technique +local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) + if not el then + return nil, nil + end + local c = color(el) + local f = child(el, "float") + local tx = child(el, "texture") + local ref: any = nil + if tx then + local ti = texture(C, params, attr(tx, "texture") or "") + if ti then + ref = { texture = ti } + local set = uvsets[attr(tx, "texcoord") or ""] + if set and set > 0 then + ref.texCoord = set + end + end + end + if c then + return c, ref + elseif f then + return numText(f, 0), ref + end + local pr = child(el, "param") + if pr then + local np = params[attr(pr, "ref") or ""] + local v = np and (child(np, "float4") or child(np, "float3") or child(np, "float")) + if v then + local nums = numbers(text(v), 16) or {} + if #nums == 1 then + return nums[1], ref + end + return { nums[1] or 0, nums[2] or 0, nums[3] or 0, nums[4] or 1 }, ref + end + end + return nil, ref +end + +local function material(C: Ctx, id: string, uvsets: { [string]: number }): number? + local cached = C.materials[id] + if cached then + return cached + end + local el = C.ids[id] + if not el or lname(el) ~= "material" then + return nil + end + local mat = Scene.material(attr(el, "name") or id) + mat.metallic = 0 + local inst = child(el, "instance_effect") + local effect = inst and C.ids[urlId(attr(inst, "url")) or ""] + local phong: { [string]: any } = {} + if effect and lname(effect) == "effect" then + local profile = child(effect, "profile_COMMON") + local tech = profile and child(profile, "technique") + local shader: any = nil + if tech then + for _, ch in children(tech) do + local n = lname(ch) + if n == "phong" or n == "blinn" or n == "lambert" or n == "constant" then + shader = ch + phong.model = n + break + end + end + end + local params = newparams(effect, profile, tech) + if shader then + local diffuse, dtex = param(C, params, child(shader, "diffuse"), uvsets) + local emission, etex = param(C, params, child(shader, "emission"), uvsets) + local ambient, atex = param(C, params, child(shader, "ambient"), uvsets) + local specular, stex = param(C, params, child(shader, "specular"), uvsets) + local shininess = param(C, params, child(shader, "shininess"), uvsets) + local reflective = param(C, params, child(shader, "reflective"), uvsets) + local reflectivity = param(C, params, child(shader, "reflectivity"), uvsets) + local transparentEl = child(shader, "transparent") + local transparent, ttex = param(C, params, transparentEl, uvsets) + local transparency = param(C, params, child(shader, "transparency"), uvsets) + local ior = param(C, params, child(shader, "index_of_refraction"), uvsets) + phong.diffuse, phong.diffuseTexture = diffuse, dtex + phong.emission, phong.emissionTexture = emission, etex + phong.ambient, phong.ambientTexture = ambient, atex + phong.specular, phong.specularTexture = specular, stex + phong.shininess, phong.reflective, phong.reflectivity = shininess, reflective, reflectivity + phong.transparent, phong.transparentTexture, phong.transparency = transparent, ttex, transparency + phong.indexOfRefraction = ior + if type(diffuse) == "table" then + mat.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 } -- its alpha is not opacity (exporters write 0) + end + if phong.model == "constant" and type(emission) == "table" then + mat.baseColor = { emission[1], emission[2], emission[3], 1 } + mat.extensions = { KHR_materials_unlit = {} } + end + if dtex then + mat.baseColorTexture = dtex + if type(diffuse) ~= "table" then + mat.baseColor = { 1, 1, 1, 1 } + end + end + if type(emission) == "table" and phong.model ~= "constant" then + mat.emissive = { emission[1], emission[2], emission[3] } + end + if etex then + mat.emissiveTexture = etex + mat.emissive = { 1, 1, 1 } + end + if type(shininess) == "number" then + mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + end + -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then + local mode = attr(transparentEl, "opaque") or "A_ONE" + local tv = if type(transparency) == "number" then transparency else 1 + local tc: any = if type(transparent) == "table" then transparent else { 1, 1, 1, 1 } + local a: number + if mode == "RGB_ZERO" then + a = 1 - tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + elseif mode == "A_ZERO" then + a = 1 - tv * tc[4] + elseif mode == "RGB_ONE" then + a = tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + else + a = tv * tc[4] + end + a = math.clamp(a, 0, 1) + if a < 0.999 and a > 0.001 then + mat.baseColor[4] = a + mat.alphaMode = "blend" + end + phong.opacity = a + end + if ttex then + mat.alphaMode = "blend" + end + end + -- FCOLLADA / MAX3D / OpenCOLLADA extras: bump maps and double sidedness + for _, scope in { tech, profile, effect } do + if scope then + for _, ex in children(scope, "extra") do + for _, tq in children(ex, "technique") do + local bump = child(tq, "bump") + if bump and not mat.normalTexture then + local _, btex = param(C, params, bump, uvsets) + if btex then + mat.normalTexture = btex + end + end + local ds = child(tq, "double_sided") + if ds and numText(ds, 0) ~= 0 then + mat.doubleSided = true + end + end + end + end + end + end + mat.extras = { phong = phong } + table.insert(C.scene.materials, mat) + local idx = #C.scene.materials + C.materials[id] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Input = { semantic: string, source: any, offset: number, set: number } + +-- the inputs of a primitive element (VERTEX expanded into the inputs) +local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) + local out: { Input } = {} + local stride = 0 + for _, inp in children(prim, "input") do + local sem = upper(attr(inp, "semantic") or "") + local offset = tonumber(attr(inp, "offset") or "") or 0 + local set = tonumber(attr(inp, "set") or "") or 0 + if offset + 1 > stride then + stride = offset + 1 + end + if sem == "VERTEX" then + local vel = C.ids[urlId(attr(inp, "source")) or ""] or verticesEl + if vel and lname(vel) == "vertices" then + for _, vin in children(vel, "input") do + local vs = upper(attr(vin, "semantic") or "") + local src = sourceById(C, attr(vin, "source")) + if src then + table.insert(out, { semantic = vs, source = src, offset = offset, set = tonumber(attr(vin, "set") or "") or set }) + end + end + end + else + local src = sourceById(C, attr(inp, "source")) + if src then + table.insert(out, { semantic = sem, source = src, offset = offset, set = set }) + end + end + end + return out, math.max(stride, 1) +end + +-- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode +local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) + local p: { number } = {} + local faces: { number } = {} + local starts: { number } = {} + local function addP(el: any): (number, number) + local v, e = numbers(text(el), C.limit) + if not v then + C.err = e + return 0, 0 + end + local base = #p + table.move(v, 1, #v, base + 1, p) + return base // stride, #v // stride + end + if kind == "triangles" or kind == "lines" then + local per = if kind == "triangles" then 3 else 2 + local pe = child(prim, "p") + if pe then + local _, n = addP(pe) + local count = math.min(tonumber(attr(prim, "count") or "") or n // per, n // per) + for f = 0, count - 1 do + table.insert(faces, per) + for k = 0, per - 1 do + table.insert(starts, f * per + k) + end + end + end + return p, faces, starts, kind + elseif kind == "polylist" then + local pe = child(prim, "p") + local vc = child(prim, "vcount") + if pe and vc then + local _, n = addP(pe) + local counts = numbers(text(vc), C.limit) or {} + local at = 0 + for _, c in counts do + c = math.floor(c) + if c < 0 or at + c > n then + break + end + table.insert(faces, c) + for k = 0, c - 1 do + table.insert(starts, at + k) + end + at += c + end + end + return p, faces, starts, "polygons" + elseif kind == "polygons" then + local list = children(prim, "p") + for _, ph in children(prim, "ph") do + local outer = child(ph, "p") + if outer then + table.insert(list, outer) + end + skip(C, "polygon holes") + end + for _, pe in list do + local first, n = addP(pe) + if n > 0 then + table.insert(faces, n) + for k = 0, n - 1 do + table.insert(starts, first + k) + end + end + end + return p, faces, starts, "polygons" + elseif kind == "linestrips" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 2 do + table.insert(faces, 2) + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + end + end + return p, faces, starts, "lines" + elseif kind == "tristrips" or kind == "trifans" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 3 do + table.insert(faces, 3) + if kind == "trifans" then + table.insert(starts, first) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + elseif k % 2 == 0 then + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + else + table.insert(starts, first + k + 1) + table.insert(starts, first + k) + table.insert(starts, first + k + 2) + end + end + end + return p, faces, starts, "triangles" + end + return nil, nil, nil, kind +end + +local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true } + +type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } + +-- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) +local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? + local ins, stride = inputs(C, prim, verticesEl) + local p, faces, starts, mode = corners(C, prim, kind, stride) + if C.err or not p or not faces or not starts then + return nil + end + local posIn: Input? = nil + for _, i in ins do + if i.semantic == "POSITION" then + posIn = i + break + end + end + if not posIn then + skip(C, "primitives without positions") + return nil + end + -- attribute names + local named: { { input: Input, name: string, comps: number } } = {} + local texSets: { number } = {} + local texInputs: { Input } = {} + local colorN, normalSeen = 0, false + for _, i in ins do + if i.semantic == "TEXCOORD" then + table.insert(texInputs, i) + end + end + table.sort(texInputs, function(a: Input, b: Input): boolean + if a.set ~= b.set then + return a.set < b.set + end + return a.offset < b.offset + end) + for k, i in texInputs do + texSets[k] = i.set + table.insert(named, { input = i, name = "TEXCOORD_" .. (k - 1), comps = 2 }) + end + for _, i in ins do + local s = i.semantic + local comps = math.min(i.source.comps, 4) + if s == "POSITION" then + if i == posIn then + table.insert(named, { input = i, name = "POSITION", comps = 3 }) + end + elseif s == "NORMAL" then + table.insert(named, { input = i, name = if normalSeen then "_NORMAL" .. i.set else "NORMAL", comps = 3 }) + normalSeen = true + elseif s == "COLOR" then + table.insert(named, { input = i, name = "COLOR_" .. colorN, comps = if comps >= 4 then 4 else 3 }) + colorN += 1 + elseif s ~= "TEXCOORD" then + table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) + end + end + -- de-index + local np = #p + local keyOf: { [any]: number } = {} + local tuples: { number } = {} -- the first p index of each output vertex's tuple + local corner = table.create(#starts) :: { number } + local count = 0 + for ci, s in starts do + local base = s * stride + if base + stride > np then + C.err = "index list too short" + return nil + end + local key: any + if stride == 1 then + key = p[base + 1] + else + key = table.concat(p, ",", base + 1, base + stride) + end + local v = keyOf[key] + if not v then + v = count + count += 1 + keyOf[key] = v + tuples[count] = base + end + corner[ci] = v + end + C.vertices += count + if C.vertices > C.limit then + C.err = "over the vertex limit" + return nil + end + local attributes: { [string]: Types.Accessor } = {} + local posIndex = table.create(count, 0) + for _, a in named do + local src = a.input.source + local comps, scomps = a.comps, src.comps + local data, n = src.data, src.count + local buf = buffer.create(count * comps * 4) + local off = a.input.offset + 1 + local isTex = sub(a.name, 1, 9) == "TEXCOORD_" + local isPos = a.name == "POSITION" + for v = 0, count - 1 do + local idx = p[tuples[v + 1] + off] + if idx == nil or idx < 0 or idx >= n or idx ~= idx // 1 then + C.err = "index out of range" + return nil + end + if isPos then + posIndex[v + 1] = idx + end + local at = idx * scomps + for k = 1, comps do + local x = if k <= scomps then data[at + k] else (if k == 4 then 1 else 0) + if type(x) ~= "number" then + x = 0 + end + if isTex and k == 2 and C.flipV then + x = 1 - x + end + buffer.writef32(buf, (v * comps + k - 1) * 4, x) + end + end + attributes[a.name] = Scene.accessor(buf, "f32", comps, count) + end + local nc = #corner + local out: Types.Primitive = { attributes = attributes, mode = "triangles" } + if mode == "polygons" then + local allTri = true + for _, f in faces do + if f ~= 3 then + allTri = false + break + end + end + if allTri then + mode = "triangles" + elseif C.triangulate then + -- fan triangulation + local tri: { number } = {} + local at = 0 + for _, f in faces do + for k = 1, f - 2 do + table.insert(tri, corner[at + 1]) + table.insert(tri, corner[at + k + 1]) + table.insert(tri, corner[at + k + 2]) + end + at += f + end + corner, nc, mode = tri, #tri, "triangles" + else + local fb = buffer.create(#faces * 4) + for i, f in faces do + buffer.writeu32(fb, (i - 1) * 4, f) + end + out.faces = Scene.accessor(fb, "u32", 1, #faces) + end + end + out.mode = mode :: any + local ib = buffer.create(nc * 4) + for i = 1, nc do + buffer.writeu32(ib, (i - 1) * 4, corner[i]) + end + out.indices = Scene.accessor(ib, "u32", 1, nc) + return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } +end + +-- geometry(el) -> the built primitives (cached per geometry element) +local function geometry(C: Ctx, el: any): { Built }? + local cached = C.posIndex[el] + if cached then + return cached :: any + end + local mesh = child(el, "mesh") or child(el, "convex_mesh") + if not mesh then + if child(el, "spline") or child(el, "brep") then + skip(C, "spline / brep geometry") + end + return nil + end + local verticesEl = child(mesh, "vertices") + local out: { Built } = {} + for _, ch in children(mesh) do + local n = lname(ch) + if PRIMS[n] then + local b = buildPrim(C, ch, verticesEl, n) + if C.err then + return nil + end + if b then + table.insert(out, b) + end + end + end + C.posIndex[el] = out :: any + return out +end + +-- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set +local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) + local syms: { [string]: string } = {} + local sets: { [string]: { [string]: number } } = {} + local bm = node and child(node, "bind_material") + local tc = bm and child(bm, "technique_common") + if tc then + for _, im in children(tc, "instance_material") do + local sym, target = attr(im, "symbol"), urlId(attr(im, "target")) + if sym and target then + syms[sym] = target + local s = {} + for _, bvi in children(im, "bind_vertex_input") do + local sem = attr(bvi, "semantic") + if sem then + s[sem] = tonumber(attr(bvi, "input_set") or "") or 0 + end + end + sets[sym] = s + end + end + end + return syms, sets +end + +local function copyAccessor(a: Types.Accessor): Types.Accessor + local b = buffer.create(buffer.len(a.data)) + buffer.copy(b, 0, a.data) + return Scene.accessor(b, a.type, a.components, a.count) +end + +-- mesh(geometry element, instance element, skin?) -> scene mesh index +local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) + local syms, sets = bindings(inst) + local parts = { key } + for s, t in syms do + table.insert(parts, s .. "=" .. t) + end + table.sort(parts) + local k = table.concat(parts, ";") + local built = geometry(C, geomEl) + if not built or #built == 0 then + return nil, nil + end + local cached = C.meshes[k] + if cached then + return cached, built + end + local mesh: Types.Mesh = { name = attr(geomEl, "name") or attr(geomEl, "id"), primitives = {} } + for _, b in built do + local prim = b.prim + if bindShape then + -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) + local attrs = table.clone(prim.attributes) + local pos = copyAccessor(attrs.POSITION) + for v = 0, pos.count - 1 do + local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) + x, y, z = Mat4.point(bindShape, x, y, z) + buffer.writef32(pos.data, v * 12, x) + buffer.writef32(pos.data, v * 12 + 4, y) + buffer.writef32(pos.data, v * 12 + 8, z) + end + attrs.POSITION = pos + if attrs.NORMAL then + local nm = Mat4.normalMatrix(bindShape) + local nrm = copyAccessor(attrs.NORMAL) + for v = 0, nrm.count - 1 do + local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8) + x, y, z = nm[1] * x + nm[5] * y + nm[9] * z, nm[2] * x + nm[6] * y + nm[10] * z, nm[3] * x + nm[7] * y + nm[11] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + buffer.writef32(nrm.data, v * 12, x) + buffer.writef32(nrm.data, v * 12 + 4, y) + buffer.writef32(nrm.data, v * 12 + 8, z) + end + attrs.NORMAL = nrm + end + prim = table.clone(prim) + prim.attributes = attrs + else + prim = table.clone(prim) + end + local sym = b.symbol + local target = sym and (syms[sym] or (if C.ids[sym] and lname(C.ids[sym]) == "material" then sym else nil)) + if not target then + -- no (or an unbound) symbol and a single binding: that one (MakeHuman leaves out the symbol) + local only, n = nil, 0 + for s2 in syms do + only, n = s2, n + 1 + end + if n == 1 then + sym = only + target = syms[only :: string] + end + end + if target then + -- texcoord semantic -> TEXCOORD_n index among this primitive's sets + local uv: { [string]: number } = {} + for sem, set in (sym and sets[sym]) or {} do + uv[sem] = (table.find(b.texSets, set) or 1) - 1 + end + prim.material = material(C, target, uv) + end + table.insert(mesh.primitives, prim) + end + table.insert(C.scene.meshes, mesh) + local idx = #C.scene.meshes + C.meshes[k] = idx + return idx, built +end + +-- morph controller -> mesh with targets (deltas) +local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? + local base = C.ids[urlId(attr(morph, "source")) or ""] + if not base or lname(base) ~= "geometry" then + return nil + end + local idx, built = meshFor(C, base, inst, "morph:" .. (attr(ctrl, "id") or ""), nil) + if not idx or not built then + return nil + end + local mesh = C.scene.meshes[idx] + if mesh.weights then + return idx + end + local relative = upper(attr(morph, "method") or "NORMALIZED") == "RELATIVE" + local targetsEl = child(morph, "targets") + local targetIds: { string } = {} + local weights: { number } = {} + if targetsEl then + for _, inp in children(targetsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if src and sem == "MORPH_TARGET" then + for _, v in src.data do + table.insert(targetIds, tostring(v)) + end + elseif src and sem == "MORPH_WEIGHT" then + for _, v in src.data do + table.insert(weights, if type(v) == "number" then v else 0) + end + end + end + end + local tbuilt: { { Built } } = {} + for _, tid in targetIds do + local g = C.ids[tid] + local tb = g and lname(g) == "geometry" and geometry(C, g) + if not tb or #tb ~= #built then + skip(C, "morph targets with another topology") + return idx + end + table.insert(tbuilt, tb) + end + for pi, prim in mesh.primitives do + local targets = {} + for ti, tb in tbuilt do + local tp = tb[pi].prim + local t: { [string]: Types.Accessor } = {} + for _, name in { "POSITION", "NORMAL" } do + local a, b = prim.attributes[name], tp.attributes[name] + if a and b and a.count == b.count then + local d = buffer.create(a.count * 12) + for i = 0, a.count * 3 - 1 do + local bv = buffer.readf32(b.data, i * 4) + buffer.writef32(d, i * 4, if relative then bv else bv - buffer.readf32(a.data, i * 4)) + end + t[name] = Scene.accessor(d, "f32", 3, a.count) + end + end + targets[ti] = t + end + prim.targets = targets + end + mesh.weights = weights + return idx +end + +-- ------------------------------------------------------------------------------------------------ cameras, lights +local function camera(C: Ctx, el: any): number? + local optics = child(el, "optics") + local tc = optics and child(optics, "technique_common") + if not tc then + return nil + end + local cam: Types.Camera + local persp, ortho = child(tc, "perspective"), child(tc, "orthographic") + if persp then + local xfov, yfov = child(persp, "xfov"), child(persp, "yfov") + local aspect = child(persp, "aspect_ratio") + local ar = if aspect then numText(aspect, 1) else nil + local yf: number + if yfov then + yf = math.rad(numText(yfov, 45)) + elseif xfov and ar then + yf = 2 * math.atan(math.tan(math.rad(numText(xfov, 45)) / 2) / ar) + else + yf = math.rad(numText(xfov, 45)) + end + if xfov and yfov and not ar then + local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2) + ar = if ty > 0 then tx / ty else nil + end + cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective" :: "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } :: Types.Camera + elseif ortho then + local xm, ym = child(ortho, "xmag"), child(ortho, "ymag") + local ar = numText(child(ortho, "aspect_ratio"), 1) + local x = if xm then numText(xm, 1) else numText(ym, 1) * ar + local y = if ym then numText(ym, 1) else numText(xm, 1) / ar + cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic" :: "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } :: Types.Camera + else + return nil + end + table.insert(C.scene.cameras, cam) + return #C.scene.cameras +end + +-- light(el) -> light index, or nil and the ambient colour +local function light(C: Ctx, el: any): (number?, { number }?) + local tc = child(el, "technique_common") + if not tc then + return nil, nil + end + local amb = child(tc, "ambient") + if amb then + return nil, color(amb) or { 1, 1, 1, 1 } + end + local kinds: { [string]: string } = { directional = "directional", point = "point", spot = "spot" } + for k, t in kinds do + local l = child(tc, k) + if l then + local c = color(l) or { 1, 1, 1 } + local lt: Types.Light = { name = attr(el, "name") or attr(el, "id"), type = t :: any, color = { c[1], c[2], c[3] }, intensity = 1 } + if t == "spot" then + local fa = numText(child(l, "falloff_angle"), 180) + lt.outerCone = math.clamp(math.rad(fa) / 2, 0, math.pi / 2) + lt.innerCone = 0 + end + table.insert(C.scene.lights, lt) + local idx = #C.scene.lights + if t ~= "directional" then + lt.extras = { + dae = { + constantAttenuation = numText(child(l, "constant_attenuation"), 1), + linearAttenuation = numText(child(l, "linear_attenuation"), 0), + quadraticAttenuation = numText(child(l, "quadratic_attenuation"), 0), + falloffExponent = if t == "spot" then numText(child(l, "falloff_exponent"), 0) else nil, + }, + } :: any + end + return idx, nil + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ nodes +local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } + +-- the matrix of one transform element's values +local function xfMatrix(kind: string, v: { number }): { number } + if kind == "matrix" then + return Mat4.fromRows(v) + elseif kind == "translate" then + return Mat4.translation(v[1] or 0, v[2] or 0, v[3] or 0) + elseif kind == "rotate" then + return Mat4.fromQuat(Mat4.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) + elseif kind == "scale" then + return Mat4.scaling(v[1] or 1, v[2] or 1, v[3] or 1) + elseif kind == "lookat" then + return M.lookat(v) + elseif kind == "skew" then + return M.skew(v) + end + return Mat4.identity() +end + +local function compose(xf: { any }): { number } + local m = Mat4.identity() + for _, x in xf do + m = Mat4.mul(m, xfMatrix(x.kind, x.values)) + end + return m +end + +local function setTransform(node: Types.Node, m: { number }) + local t, r, s = Mat4.decomposeStrict(m) + node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil + if t and r and s then + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if math.abs(r[4]) < 1 - 1e-9 then + node.rotation = r + end + if math.abs(s[1] - 1) > 1e-7 or math.abs(s[2] - 1) > 1e-7 or math.abs(s[3] - 1) > 1e-7 then + node.scale = s + end + else + for i = 1, 16 do + if math.abs(m[i] - Mat4.identity()[i]) > 0 then + node.matrix = m + break + end + end + end +end + +local visitNode: (C: Ctx, el: any) -> number? + +local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + table.insert(parent.children, idx) + return idx +end + +-- the instances of a node: the first of each kind on the node itself, the rest on child nodes +local function instances(C: Ctx, el: any, node: Types.Node, idx: number) + local function slot(kind: string, name: string?): (Types.Node, number) + local n: any = node + if n[kind] == nil then + return node, idx + end + local extra: Types.Node = { name = name, children = {} } + return extra, addChild(C, node, extra) + end + for _, ch in children(el) do + local n = lname(ch) + if n == "instance_geometry" then + local g = C.ids[urlId(attr(ch, "url")) or ""] + if g and lname(g) == "geometry" then + local mi = meshFor(C, g, ch, "geom:" .. (attr(g, "id") or ""), nil) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(g, "name")) + target.mesh = mi + end + end + elseif n == "instance_controller" then + local ctrl = C.ids[urlId(attr(ch, "url")) or ""] + local skinEl = ctrl and child(ctrl, "skin") + local morph = ctrl and child(ctrl, "morph") + if skinEl then + -- the skin's source may be a morph controller + local src = C.ids[urlId(attr(skinEl, "source")) or ""] + local morphEl = src and lname(src) == "controller" and child(src, "morph") + if morphEl then + src = C.ids[urlId(attr(morphEl, "source")) or ""] + skip(C, "skins over morph controllers (morph dropped)") + end + if src and lname(src) == "geometry" then + local bsm = child(skinEl, "bind_shape_matrix") + local bind = if bsm then Mat4.fromRows(numbers(text(bsm), 16) or {}) else nil + local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind) + if C.err then + return + end + if mi and built then + local target, ti = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + local roots = {} + for _, sk in children(ch, "skeleton") do + table.insert(roots, urlId(match(text(sk), "^%s*(.-)%s*$"))) + end + table.insert(C.pendingSkins, { node = ti, ctrl = ctrl, skin = skinEl, mesh = mi, built = built, roots = roots, bind = bind }) + end + end + elseif morph then + local mi = morphMesh(C, ctrl, morph, ch) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + target.weights = C.scene.meshes[mi].weights + end + end + elseif n == "instance_camera" then + local cel = C.ids[urlId(attr(ch, "url")) or ""] + local ci = cel and lname(cel) == "camera" and camera(C, cel) + if ci then + local target = slot("camera", C.scene.cameras[ci].name) + target.camera = ci + end + elseif n == "instance_light" then + local lel = C.ids[urlId(attr(ch, "url")) or ""] + if lel and lname(lel) == "light" then + local li, ambient = light(C, lel) + if li then + local target = slot("light", C.scene.lights[li].name) + target.light = li + elseif ambient then + local ex: any = node.extras or {} + ex.dae = ex.dae or {} + ex.dae.ambientLight = ambient + node.extras = ex + end + end + elseif n == "instance_node" then + local target = C.ids[urlId(attr(ch, "url")) or ""] + if target and lname(target) == "node" then + local ci = visitNode(C, target) + if ci then + table.insert(node.children, ci) + end + end + end + end +end + +visitNode = function(C: Ctx, el: any): number? + if C.depth > 256 or #C.scene.nodes > C.limit then + C.err = "node tree too deep or too large (instance_node cycle?)" + return nil + end + C.depth += 1 + local xf = {} + for _, ch in children(el) do + local n = lname(ch) + local want = XFORMS[n] + if want then + local v = numbers(text(ch), 64) or {} + table.insert(xf, { kind = n, sid = attr(ch, "sid"), values = v }) + end + end + local node: Types.Node = { name = attr(el, "name") or attr(el, "id"), children = {} } + setTransform(node, compose(xf)) + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + local id = attr(el, "id") + C.info[idx] = { xf = xf, sid = attr(el, "sid"), id = id, joint = upper(attr(el, "type") or "") == "JOINT" } + if id then + C.nodeOf[id] = C.nodeOf[id] or {} + table.insert(C.nodeOf[id], idx) + end + if upper(attr(el, "type") or "") == "JOINT" then + node.extras = { dae = { joint = true, sid = attr(el, "sid") } } :: any + end + instances(C, el, node, idx) + for _, ch in children(el, "node") do + if C.err then + break + end + local ci = visitNode(C, ch) + if ci then + table.insert(node.children, ci) + end + end + C.depth -= 1 + return idx +end + +-- ------------------------------------------------------------------------------------------------ skins +-- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? + local nodes = C.scene.nodes + local function search(i: number, depth: number): number? + if depth > 300 then + return nil + end + local inf = C.info[i] + if inf and (inf.sid == name or (byId and inf.id == name)) then + return i + end + for _, c in nodes[i].children do + local r = search(c, depth + 1) + if r then + return r + end + end + return nil + end + for _, r in roots do + local f = search(r, 0) + if f then + return f + end + end + for i in nodes do + local inf = C.info[i] + if inf and (inf.sid == name or inf.id == name) then + return i + end + end + for i, n in nodes do + if n.name == name then + return i + end + end + return nil +end + +local function resolveSkins(C: Ctx) + local cache: { [string]: number } = {} + for _, ps in C.pendingSkins do + local skinEl = ps.skin + local jointsEl = child(skinEl, "joints") + local names: { string } = {} + local byId = false + local ibm: any = nil + if jointsEl then + for _, inp in children(jointsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local srcEl = C.ids[urlId(attr(inp, "source")) or ""] + local src = srcEl and lname(srcEl) == "source" and readSource(C, srcEl) + if src and sem == "JOINT" then + for _, v in src.data do + table.insert(names, tostring(v)) + end + byId = child(srcEl, "IDREF_array") ~= nil + elseif src and sem == "INV_BIND_MATRIX" then + ibm = src + end + end + end + local roots: { number } = {} + for _, r in ps.roots do + for _, ni in C.nodeOf[r] or {} do + table.insert(roots, ni) + end + end + local jointNodes: { number } = {} + local ok = #names > 0 + for i, nm in names do + local j = findJoint(C, nm, roots, byId) + if not j then + ok = false + break + end + jointNodes[i] = j + end + if not ok then + skip(C, "skins with unresolved joints") + continue + end + local key = (attr(ps.ctrl, "id") or "") .. "|" .. table.concat(jointNodes, ",") + local si = cache[key] + if not si then + local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } + if ps.bind then + local sk: any = skin + sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + end + if ibm and ibm.comps == 16 and ibm.count >= #names then + local b = buffer.create(#names * 64) + for i = 0, #names - 1 do + local cm = Mat4.fromRows(ibm.data, i * 16 + 1) + for k = 1, 16 do + buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) + end + end + local acc = Scene.accessor(b, "f32", 16, #names) + acc.matrix = true + skin.inverseBindMatrices = acc + end + if roots[1] then + skin.skeleton = roots[1] + end + table.insert(C.scene.skins, skin) + si = #C.scene.skins + cache[key] = si + end + C.scene.nodes[ps.node].skin = si + -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) + local mesh = C.scene.meshes[ps.mesh] + if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then + continue + end + local vw = child(skinEl, "vertex_weights") + if not vw then + continue + end + local jOff, wOff, wSrc = 0, 1, nil + local stride = 1 + for _, inp in children(vw, "input") do + local sem = upper(attr(inp, "semantic") or "") + local off = tonumber(attr(inp, "offset") or "") or 0 + stride = math.max(stride, off + 1) + if sem == "JOINT" then + jOff = off + elseif sem == "WEIGHT" then + wOff = off + wSrc = sourceById(C, attr(inp, "source")) + end + end + local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} + local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} + local wdata = wSrc and wSrc.data or {} + local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local at = 0 + for pi, c in vcount do + local list = {} + for _ = 1, math.floor(c) do + local j, w = v[at + jOff + 1], v[at + wOff + 1] + at += stride + local wv = if w then wdata[w + 1] else nil + if j and j >= 0 and j < #names and type(wv) == "number" and wv > 0 then + table.insert(list, { j, wv }) + end + end + table.sort(list, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local total = 0 + for k = 1, math.min(4, #list) do + total += list[k][2] + end + local e = {} + for k = 1, math.min(4, #list) do + e[k * 2 - 1], e[k * 2] = list[k][1], list[k][2] / total + end + per[pi] = e + end + for pi, prim in mesh.primitives do + local posIndex = ps.built[pi] and ps.built[pi].posIndex + local n = prim.attributes.POSITION.count + if posIndex and #posIndex == n then + local jt = if #names < 256 then "u8" else "u16" + local js = if jt == "u8" then 1 else 2 + local jb = buffer.create(n * 4 * js) + local wb = buffer.create(n * 16) + for vi = 0, n - 1 do + local e = per[posIndex[vi + 1] + 1] + for k = 0, 3 do + local j, w = 0, 0 + if e and e[k * 2 + 1] then + j, w = e[k * 2 + 1], e[k * 2 + 2] + end + if js == 1 then + buffer.writeu8(jb, vi * 4 + k, j) + else + buffer.writeu16(jb, (vi * 4 + k) * 2, j) + end + buffer.writef32(wb, (vi * 4 + k) * 4, w) + end + end + prim.attributes.JOINTS_0 = Scene.accessor(jb, jt, 4, n) + prim.attributes.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +type Curve = { input: { number }, output: { number }, stride: number, interp: { string }, member: number?, xf: any } + +local function sample(c: Curve, t: number): { number } + local inp, out, st = c.input, c.output, c.stride + local n = #inp + local function at(i: number): { number } + local r = table.create(st) :: { number } + for k = 1, st do + r[k] = out[(i - 1) * st + k] or 0 + end + return r + end + if n == 0 then + return {} + end + if t <= inp[1] then + return at(1) + end + if t >= inp[n] then + return at(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if inp[mid] <= t then + lo = mid + else + hi = mid + end + end + local a, b = at(lo), at(hi) + if c.interp[lo] == "STEP" then + return a + end + local span = inp[hi] - inp[lo] + local f = if span > 0 then (t - inp[lo]) / span else 0 + for k = 1, st do + a[k] += (b[k] - a[k]) * f + end + return a +end + +-- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +local function target(C: Ctx, s: string): ({ number }?, any, number?) + -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + local id, sids = match(s, "^([^/]*)/(.*)$") + if not id then + return nil, nil, nil + end + local spath, rest = match(sids :: string, "^([^%.%(]*)(.*)$") + if not spath then + return nil, nil, nil + end + local parts = string.split(id .. "/" .. spath, "/") + local nodes = C.nodeOf[parts[1]] + if not nodes or #parts < 2 then + return nil, nil, nil + end + local sid = parts[#parts] + local info = C.info[nodes[1]] + local xf: any = nil + for _, x in info.xf do + if x.sid == sid then + xf = x + break + end + end + if not xf then + return nil, nil, nil + end + local member: number? = nil + if rest and rest ~= "" then + local m1 = match(rest, "^%.(.+)$") + if m1 then + member = MEMBER[upper(m1)] + if not member then + return nil, nil, nil + end + else + local i, j = match(rest, "^%((%d+)%)%((%d+)%)$") + if i then + member = tonumber(i) :: number * 4 + tonumber(j) :: number + 1 + else + local k = match(rest, "^%((%d+)%)$") + if not k then + return nil, nil, nil + end + member = tonumber(k) :: number + 1 + end + end + end + return nodes, xf, member +end + +-- the channels of one (recursively) -> curves grouped by node +local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) + if depth > 64 then + return + end + for _, ch in children(anim, "channel") do + local smp = C.ids[urlId(attr(ch, "source")) or ""] + local nodes, xf, member = target(C, attr(ch, "target") or "") + if smp and lname(smp) == "sampler" and nodes and xf then + local input, output, interp: any = nil, nil, nil + for _, inp in children(smp, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if sem == "INPUT" then + input = src + elseif sem == "OUTPUT" then + output = src + elseif sem == "INTERPOLATION" then + interp = src + end + end + if input and output and input.count > 0 then + local stride = if member then 1 else #xf.values + local ins = {} + for i = 1, input.count do + local x = input.data[(i - 1) * input.comps + 1] + ins[i] = if type(x) == "number" then x else 0 + end + local outs = output.data + if #outs >= input.count * stride then + local ip = {} + if interp then + for i = 1, input.count do + ip[i] = upper(tostring(interp.data[i] or "LINEAR")) + end + end + local curve: Curve = { input = ins, output = outs, stride = stride, interp = ip, member = member, xf = xf } + for _, ni in nodes do + if not byNode[ni] then + byNode[ni] = {} + table.insert(order, ni) + end + table.insert(byNode[ni], curve) + end + end + end + elseif not (nodes and xf) then + skip(C, "animation channels on other targets") + end + end + for _, sub2 in children(anim, "animation") do + collect(C, sub2, byNode, order, depth + 1) + end +end + +local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, order: { number }): Types.Animation? + local channels: { Types.Channel } = {} + for _, ni in order do + local curves = byNode[ni] + local info = C.info[ni] + -- the union of the key times, plus subdivisions of rotations over 90 degrees + local set: { [number]: boolean } = {} + local times: { number } = {} + local function add(t: number) + if not set[t] then + set[t] = true + table.insert(times, t) + end + end + for _, c in curves do + for i, t in c.input do + add(t) + if i > 1 and c.xf.kind == "rotate" and (c.member == 4 or c.member == nil) then + local k = if c.member then 1 else 4 + local a, b = c.output[(i - 2) * c.stride + k] or 0, c.output[(i - 1) * c.stride + k] or 0 + local steps = math.min(math.ceil(math.abs(b - a) / 90), 64) + for s = 1, steps - 1 do + add(c.input[i - 1] + (t - c.input[i - 1]) * s / steps) + end + end + end + if #times > C.limit then + return nil + end + end + table.sort(times) + local n = #times + local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) + local prev: { number }? = nil + for i, t in times do + -- this time's values of each animated element + local xf = {} + for k, x in info.xf do + xf[k] = { kind = x.kind, values = table.clone(x.values) } + end + for _, c in curves do + local v = sample(c, t) + local k = table.find(info.xf, c.xf) + if k then + local vals = xf[k].values + if c.member then + vals[c.member] = v[1] or 0 + else + for j = 1, #v do + vals[j] = v[j] + end + end + end + end + local tr, ro, sc = Mat4.decomposeStrict(compose(xf)) + tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 } + if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then + ro = { -ro[1], -ro[2], -ro[3], -ro[4] } + end + prev = ro + for k = 1, 3 do + buffer.writef32(tb, ((i - 1) * 3 + k - 1) * 4, tr[k]) + buffer.writef32(sb, ((i - 1) * 3 + k - 1) * 4, sc[k]) + end + for k = 1, 4 do + buffer.writef32(rb, ((i - 1) * 4 + k - 1) * 4, ro[k]) + end + end + local ib = buffer.create(n * 4) + for i, t in times do + buffer.writef32(ib, (i - 1) * 4, t) + end + local input = Scene.accessor(ib, "f32", 1, n) + table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) + table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel) + table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel) + -- the node is now TRS-driven + local node = C.scene.nodes[ni] + if node.matrix then + setTransform(node, node.matrix) + end + end + if #channels == 0 then + return nil + end + return { name = name, channels = channels } +end + +local function animations(C: Ctx, root: any) + local libs = children(root, "library_animations") + if #libs == 0 then + return + end + local clipsLib = child(root, "library_animation_clips") + local clips = clipsLib and children(clipsLib, "animation_clip") or {} + if #clips > 0 then + for _, clip in clips do + local byNode, order = {}, {} + for _, ia in children(clip, "instance_animation") do + local a = C.ids[urlId(attr(ia, "url")) or ""] + if a and lname(a) == "animation" then + collect(C, a, byNode, order, 0) + end + end + local anim = bake(C, attr(clip, "name") or attr(clip, "id"), byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end + end + return + end + local byNode, order = {}, {} + local name: string? = nil + local count = 0 + for _, lib in libs do + for _, a in children(lib, "animation") do + collect(C, a, byNode, order, 0) + count += 1 + name = name or attr(a, "name") or attr(a, "id") + end + end + local anim = bake(C, if count == 1 then name else nil, byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local root = doc and doc.root + if not root or lname(root) ~= "COLLADA" then + return nil, Err.new(Err.CORRUPT, "no root element") + end + local scene = Scene.new() + local C: Ctx = { + doc = doc, + ids = {}, + fetch = fetch, + scene = scene, + limit = opts and opts.maxVertices or 2 ^ 25, + vertices = 0, + flipV = not (opts and opts.flipV == false), + triangulate = not (opts and opts.triangulate == false), + sources = {}, + materials = {}, + textures = {}, + images = {}, + meshes = {}, + skins = {}, + posIndex = {}, + nodeOf = {}, + info = {}, + pendingSkins = {}, + skipped = {}, + err = nil, + depth = 0, + } + for _, el in Xml.descendants(root) do + local id = el.attrs.id + -- duplicate ids: the first one, unless it is empty (some exporters write before the real one) + if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then + C.ids[id] = el + end + end + -- asset: up axis, unit + local asset = child(root, "asset") + local up = asset and child(asset, "up_axis") + local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" + scene.meta.up = if upAxis == "Z_UP" then "z" :: "z" elseif upAxis == "X_UP" then "x" :: any else "y" :: "y" + local unit = asset and child(asset, "unit") + local meter = unit and attr(unit, "meter") + scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 + -- the instanced visual scene (else the first one) + local vsId: string? = nil + local sceneEl = child(root, "scene") + local ivs = sceneEl and child(sceneEl, "instance_visual_scene") + if ivs then + vsId = urlId(attr(ivs, "url")) + end + local vs = vsId and C.ids[vsId] + if not vs or lname(vs) ~= "visual_scene" then + local lib = child(root, "library_visual_scenes") + vs = lib and child(lib, "visual_scene") + end + if vs then + for _, n in children(vs, "node") do + local idx = visitNode(C, n) + if C.err then + break + end + if idx then + table.insert(scene.roots, idx) + end + end + end + if C.err then + return nil, Err.new(if find(C.err :: string, "limit", 1, true) then Err.LIMIT else Err.CORRUPT, C.err :: string) + end + resolveSkins(C) + animations(C, root) + if C.err then + return nil, Err.new(Err.CORRUPT, C.err :: string) + end + local contributor = asset and child(asset, "contributor") + local tool = contributor and child(contributor, "authoring_tool") + scene.meta.source = { + format = "dae", + version = attr(root, "version"), + upAxis = upAxis, + authoringTool = if tool then text(tool) else nil, + skipped = if next(C.skipped) then C.skipped else nil, + } + return scene, nil +end + +return Read +end +__FILES["model/dae/Write"] = function() + +-- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips +-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n +-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its +-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras; +-- lights. Not written: skins, morph targets, animations. +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + +local Scene = Types.Scene +local format, concat = string.format, table.concat +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" } + +local function f(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e15 then + return format("%d", v) + end + return format("%.9g", v) +end +local function list(v: { number }): string + local out = table.create(#v) + for i, x in v do + out[i] = f(x) + end + return concat(out, " ") +end +local function esc(s: string): string + return Xml.escapeAttr(s) +end +local function nameAttr(s: string?): string + return if s then ' name="' .. esc(s) .. '"' else "" +end + +-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind +local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?) + local n = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil, nil, nil + end + for i = 0, prim.indices.count - 1 do + idx[i + 1] = get(i, 0) + end + else + for i = 0, n - 1 do + idx[i + 1] = i + end + end + for _, i in idx do + if i < 0 or i >= n then + return nil, nil, nil + end + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + local m = #idx - #idx % 3 + return table.move(idx, 1, m, 1, {}), "triangles", nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local out = {} + for k = 1, #idx - 2 do + if mode == "triangle_fan" then + table.insert(out, idx[1]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + elseif k % 2 == 1 then + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + else + table.insert(out, idx[k + 1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 2]) + end + end + return out, "triangles", nil + elseif mode == "lines" then + local m = #idx - #idx % 2 + return table.move(idx, 1, m, 1, {}), "lines", nil + elseif mode == "line_strip" or mode == "line_loop" then + local out = {} + for k = 1, #idx - 1 do + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + if mode == "line_loop" and #idx > 2 then + table.insert(out, idx[#idx]) + table.insert(out, idx[1]) + end + return out, "lines", nil + elseif mode == "polygons" and prim.faces then + local get = Scene.reader(prim.faces) + if not get then + return nil, nil, nil + end + local sizes = {} + local total = 0 + for i = 0, prim.faces.count - 1 do + sizes[i + 1] = get(i, 0) + total += sizes[i + 1] + end + if total ~= #idx then + return nil, nil, nil + end + return idx, "polylist", sizes + end + return nil, nil, nil +end + +local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean) + local get = Scene.reader(acc) + if not get then + return + end + local vals = table.create(acc.count * comps) + local n = 0 + for i = 0, acc.count - 1 do + for c = 0, comps - 1 do + n += 1 + local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0) + if flipV and c == 1 then + v = 1 - v + end + vals[n] = f(v) + end + end + table.insert(out, format('%s', id, id, n, concat(vals, " "))) + local ps = {} + for c = 1, comps do + ps[c] = format('', params[c] or "V") + end + table.insert(out, format('%s\n', id, acc.count, comps, concat(ps))) +end + +local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string + if tex then + return format('<%s>', tag, tex, uv or 0, tag) + end + local v = c or { 0, 0, 0, 1 } + return format("<%s>%s %s %s %s", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag) +end + +function Write.build(scene: Types.Scene, opts: any?): string? + local files = opts and type(opts.files) == "table" and opts.files or nil + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local flipV = not (opts and opts.flipV == false) + local out: { string } = {} + local function w(s: string) + table.insert(out, s) + end + w('\n\n') + local meta: { [string]: any } = scene.meta or {} + local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" + w(format('rosetta1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up)) + -- images + local imageId: { [number]: string } = {} + if #scene.textures > 0 then + w("\n") + for i, tex in scene.textures do + local uri: string? = nil + if tex.data then + if files then + uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + files[uri :: string] = tex.data + else + uri = Base64.dataUri(tex.data, tex.mime or "image/png") + end + elseif tex.uri then + uri = tex.uri + end + if uri then + local id = "image" .. i + imageId[i] = id + w(format('%s\n', id, nameAttr(tex.name), Xml.escape(uri :: string))) + end + end + w("\n") + end + -- effects + materials + if #scene.materials > 0 then + w("\n") + for i, mat in scene.materials do + local ph: any = mat.extras and mat.extras.phong or {} + local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys + local function texParam(ref: Types.TextureRef?): (string?, number?) + if not ref or not imageId[ref.texture] then + return nil, nil + end + local sid = "tex" .. ref.texture + if not params[sid] then + params[sid] = true + table.insert(params, format('%s%s-surface', sid, imageId[ref.texture], sid, sid)) + end + return sid, ref.texCoord + end + local dtex, duv = texParam(mat.baseColorTexture) + local etex, euv = texParam(mat.emissiveTexture) + local ntex, nuv = texParam(mat.normalTexture) + local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil + local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong" + local body = {} + local bc = mat.baseColor + if unlit then + table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil)) + else + table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv)) + table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil)) + table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv)) + if model == "phong" then + table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil)) + local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0) + table.insert(body, format("%s", f(sh))) + end + end + if (bc[4] or 1) < 1 then + table.insert(body, '1 1 1 1') + table.insert(body, format("%s", f(bc[4]))) + end + local extra = "" + if ntex or mat.doubleSided then + extra = "" .. (if ntex then format('', ntex, nuv or 0) else "") .. (if mat.doubleSided then "1" else "") .. "" + end + w(format('%s<%s>%s%s\n', i, concat(params), model, concat(body), model, extra)) + end + w("\n\n") + for i, mat in scene.materials do + w(format('\n', i, nameAttr(mat.name), i)) + end + w("\n") + end + -- geometries: one per primitive + local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} + w("\n") + for mi, mesh in scene.meshes do + geoms[mi] = {} + for pi, prim in mesh.primitives do + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + continue + end + local idx, kind, sizes = corners(prim) + if not idx or not kind or #idx == 0 then + continue + end + local id = format("mesh%d-%d", mi, pi) + w(format('\n', id, nameAttr(mesh.name))) + source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false) + local ins = { format('', id) } + if prim.attributes.NORMAL then + source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false) + table.insert(ins, format('', id)) + end + local sets = 0 + for k = 0, 7 do + local a = prim.attributes["TEXCOORD_" .. k] + if not a then + break + end + source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV) + table.insert(ins, format('', id, k, k)) + sets += 1 + end + for k = 0, 7 do + local a = prim.attributes["COLOR_" .. k] + if not a then + break + end + local c = if a.components >= 4 then 4 else 3 + source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false) + table.insert(ins, format('', id, k, k)) + end + w(format('\n', id, id)) + local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else "" + local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number }) + w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins))) + if sizes then + w("" .. list(sizes) .. "") + end + w("

" .. list(idx) .. "

\n
\n") + table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets }) + end + end + w("
\n") + -- cameras / lights + if #scene.cameras > 0 then + w("\n") + for i, cam in scene.cameras do + local body: string + if cam.type == "orthographic" then + body = format("%s%s%s%s", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000)) + else + body = format("%s%s%s%s", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("%s", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000)) + end + w(format('%s\n', i, nameAttr(cam.name), body)) + end + w("\n") + end + if #scene.lights > 0 then + w("\n") + for i, l in scene.lights do + local c = l.color or { 1, 1, 1 } + local k = l.intensity or 1 + local col = format("%s %s %s", f(c[1] * k), f(c[2] * k), f(c[3] * k)) + local body = if l.type == "spot" then format("%s100%s0", col, f(math.deg(l.outerCone or math.pi / 4) * 2)) + elseif l.type == "point" then format("%s100", col) + else format("%s", col) + w(format('%s\n', i, nameAttr(l.name), body)) + end + w("\n") + end + -- the node tree + w('\n') + local seen: { [number]: boolean } = {} + local function node(i: number, depth: number) + local n = scene.nodes[i] + if not n or seen[i] or depth > 512 then + return + end + seen[i] = true + w(format('%s', i, nameAttr(n.name), list(Mat4.toRows(Scene.nodeMatrix(n))))) + if n.mesh and geoms[n.mesh] then + for _, g in geoms[n.mesh] do + if g.material then + local binds = {} + for k = 0, g.sets - 1 do + table.insert(binds, format('', k, k)) + end + w(format('%s', g.id, g.material, g.material, concat(binds))) + else + w(format('', g.id)) + end + end + end + if n.camera and scene.cameras[n.camera] then + w(format('', n.camera)) + end + if n.light and scene.lights[n.light] then + w(format('', n.light)) + end + w("\n") + for _, c in n.children or {} do + node(c, depth + 1) + end + w("\n") + end + local roots = scene.roots + if not roots or #roots == 0 then + local isChild = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + isChild[c] = true + end + end + roots = {} + for i in scene.nodes do + if not isChild[i] then + table.insert(roots, i) + end + end + end + for _, r in roots do + node(r, 0) + end + w('\n\n
\n') + return concat(out) +end + +return Write +end +__FILES["model/fbx"] = function() + +-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays +-- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and +-- assimp's FBX importer, and the FBX SDK's documentation of the transform model. +-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl +-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms +-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, +-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference +-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR +-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins +-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets +-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and +-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for +-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). +-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives +-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), +-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + +-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler +-- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). +-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered +-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/fbx/Binary") +local Ascii = __include("model/fbx/Ascii") +local Read = __include("model/fbx/Read") +local Write = __include("model/fbx/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Fbx = { + name = "fbx", + category = "model", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention) + sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only) + resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the files by name + maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30) + maxVertices: number?, -- refuse more polygon corners (default 2^25) +} +type EncodeOptions = { + ascii: boolean?, -- write ASCII FBX (default binary) + version: number?, -- 7400 (default) or 7500 (64-bit records) + flipV: boolean?, -- default true (the inverse of decode) + embedTextures: boolean?, -- embed texture.data as Video content (default true) + compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger) + name: string?, -- the destination's file name (names textures without a uri) + creator: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = Binary.MAGIC + +-- ------------------------------------------------------------------------------------------------ sniff +function Fbx.sniff(r: Bytes.Reader): number + if r:peek(21) == MAGIC then + return 1 + end + local head = r:peek(2048) + if string.find(head, "FBXHeaderExtension:", 1, true) then + return 0.95 + end + if string.find(head, "^; FBX %d") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +local toErr = Err.from + +-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. +-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. +function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?) + if r:peek(21) == MAGIC then + local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) + if not root then + return nil, toErr(version, off) + end + return root, version, true + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local root, version, off = Ascii.parse(text, opts) + if not root then + return nil, toErr(version, off and r.base + off) + end + if type(version) ~= "number" then + return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion") + end + if version < 7000 then + return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)") + end + return root, version, false +end + +function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local root, version, binary = Fbx.tree(r, opts) + if not root then + return nil, version + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) + end + if not scene then + return nil, err + end + (scene.meta.source :: { [string]: any }).binary = binary + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Fbx.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local version = opts and opts.version or 7400 + if version ~= 7400 and version ~= 7500 then + return nil, Err.new(Err.ARG, "version must be 7400 or 7500") + end + local ok, root, err = pcall(Write.tree, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root)) + end + if not root then + return nil, err + end + if opts and opts.ascii then + return buffer.fromstring(Ascii.write(root, version)), nil + end + return Binary.write(root, version, not (opts and opts.compress == false)), nil +end + +return Fbx +end +__FILES["model/fbx/Ascii"] = function() + +-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' +-- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary +-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +local Base64 = __include("core/Base64") + +local Ascii = {} + +type Node = { name: string, props: { any }, children: { Node } } + +local sbyte, sfind, ssub = string.byte, string.find, string.sub +local MAX_DEPTH = 128 + +local function isNameStart(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end + +-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset +function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local n = #text + local i = 1 + local total = 0 + + local function skip() + while i <= n do + local c = sbyte(text, i) + if c == 59 then -- ; comment + local e = sfind(text, "\n", i, true) + i = if e then e + 1 else n + 1 + elseif c == 32 or c == 9 or c == 10 or c == 13 then + i += 1 + else + return + end + end + end + + -- at i: a name followed by ':'? -> name, the index after ':' + local function nameAt(): (string?, number) + local c = sbyte(text, i) + if not c or not isNameStart(c) then + return nil, i + end + local s, e = sfind(text, "^[%w_|%-]+", i) + if not s then + return nil, i + end + local j = (e :: number) + 1 + while j <= n do + local d = sbyte(text, j) + if d == 32 or d == 9 then + j += 1 + else + break + end + end + if sbyte(text, j) == 58 then + return ssub(text, i, e :: number), j + 1 + end + return nil, i + end + + -- the values of one node (after the ':'), up to a new name, '{' or '}' + local function values(): ({ any }?, string?) + local props: { any } = {} + while true do + skip() + if i > n then + return props, nil + end + local c = sbyte(text, i) + if c == 44 then -- , + i += 1 + elseif c == 123 or c == 125 then + return props, nil + elseif c == 34 then -- " + local e = sfind(text, "\"", i + 1, true) + if not e then + return nil, "unterminated string" + end + local s = ssub(text, i + 1, e - 1) + if sfind(s, "&", 1, true) then + s = string.gsub(s, """, "\"") + end + table.insert(props, s) + i = e + 1 + elseif c == 42 then -- *N + local s, e = sfind(text, "^%*%d+", i) + if not s then + return nil, "bad array length" + end + table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) }) + i = (e :: number) + 1 + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + local s, e = sfind(text, "^[-+%deE.]+", i) + local tok = ssub(text, i, e :: number) + local v = tonumber(tok) + if v == nil then + -- "1.#INF", "-1.#IND", "nan": special floats + local s2, e2 = sfind(text, "^[-+%w.#]+", i) + tok = ssub(text, i, e2 :: number) + local low = string.lower(tok) + if sfind(low, "inf", 1, true) then + v = if sbyte(tok, 1) == 45 then -math.huge else math.huge + else + v = 0 / 0 + end + e = e2 + local _ = s2 + elseif #tok > 15 and not sfind(tok, "[.eE]") then + v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any + end + local _ = s + table.insert(props, v) + i = (e :: number) + 1 + else + local nm = nameAt() + if nm then + return props, nil + end + local s, e = sfind(text, "^[%w_]+", i) + if not s then + return nil, string.format("unexpected character %q", ssub(text, i, i)) + end + table.insert(props, ssub(text, i, e :: number)) + i = (e :: number) + 1 + end + end + end + + local function nodes(depth: number, into: { Node }): string? + while true do + skip() + if i > n then + return if depth > 0 then "unterminated {" else nil + end + if sbyte(text, i) == 125 then + if depth == 0 then + return "unbalanced }" + end + i += 1 + return nil + end + local name, j = nameAt() + if not name then + return string.format("expected a node name at %q", ssub(text, i, i + 10)) + end + i = j + local props, err = values() + if not props then + return err + end + local node: Node = { name = name, props = props, children = {} } + skip() + if sbyte(text, i) == 123 then + if depth >= MAX_DEPTH then + return "nodes nested too deep" + end + i += 1 + local e = nodes(depth + 1, node.children) + if e then + return e + end + end + -- "*N { a: v, v, ... }" -> an Array + local p1 = props[1] + if #props == 1 and type(p1) == "table" and p1.star then + local a = node.children[1] + local count = if a and a.name == "a" then #a.props else 0 + total += count * 8 + if total > maxBytes then + return "limit:arrays over " .. maxBytes .. " bytes" + end + local data = buffer.create(count * 8) + for k = 1, count do + local v = (a :: Node).props[k] + buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0)) + end + node.props = { { array = true, type = "d", count = count, data = data } } + node.children = {} + end + table.insert(into, node) + end + end + + local root: Node = { name = "", props = {}, children = {} } + local err = nodes(0, root.children) + if err then + return nil, err, i - 1 + end + local version = nil + for _, c in root.children do + if c.name == "FBXHeaderExtension" then + for _, d in c.children do + if d.name == "FBXVersion" then + version = d.props[1] + end + end + end + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +local function fmt(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + if v ~= v then + return "0" + end + return string.format("%.17g", v) +end + +-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) +function Ascii.write(root: any, version: number?): string + local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } + local function node(nd: any, indent: string) + local parts = {} + local arr = nil + for _, v in nd.props do + local tv = type(v) + if tv == "number" then + table.insert(parts, fmt(v)) + elseif tv == "boolean" then + table.insert(parts, if v then "T" else "F") + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then + table.insert(parts, string.sub(v, 2)) + else + local nm, cls = string.match(v, "^(.-)%z\1(.*)$") + local sv = if nm then (cls :: string) .. "::" .. nm else v + table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"") + end + elseif tv == "table" and v.array then + arr = v + elseif tv == "buffer" then + -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + local b64 = Base64.encode(v) + local chunks = {} + for k = 1, #b64, 2048 do + table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"") + end + table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"") + end + end + if arr then + local vals = table.create(arr.count) :: { string } + for k = 0, arr.count - 1 do + vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8)) + end + table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent)) + return + end + table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", ")) + local ch = nd.children + if ch and #ch > 0 then + table.insert(out, " {\n") + for _, c in ch do + node(c, indent .. "\t") + end + table.insert(out, indent .. "}\n") + else + table.insert(out, "\n") + end + end + for _, c in root.children do + node(c, "") + end + return table.concat(out) +end + +return Ascii +end +__FILES["model/fbx/Binary"] = @native function() + + +-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit +-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's +-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array +-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become +-- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset). +local Deflate = __include("codecs/compress/Deflate") + +local Binary = {} + +type Node = { name: string, props: { any }, children: { Node } } +type Array = { array: true, type: string, count: number, data: buffer } + +local MAGIC = "Kaydara FBX Binary \0" +Binary.MAGIC = MAGIC +local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126" +local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11" +local MAX_DEPTH = 128 + +local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 +local writef64 = buffer.writef64 + +-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +@native local function i64(b: buffer, p: number, asString: boolean): any + local lo, hi = readu32(b, p), readu32(b, p + 4) + if hi >= 0x80000000 then + local v = (hi - 4294967296) * 4294967296 + lo + if v >= -9007199254740991 or not asString then + return v + end + else + if hi < 0x200000 or not asString then + return hi * 4294967296 + lo + end + end + return string.format("L%08x%08x", hi, lo) +end +Binary.i64 = i64 + +local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } + +-- the elements of a raw array (n elements of type t at p) as f64s +@native local function toF64(t: string, src: buffer, p: number, n: number): buffer + local out = buffer.create(n * 8) + if t == "d" then + buffer.copy(out, 0, src, p, n * 8) + elseif t == "f" then + for k = 0, n - 1 do + writef64(out, k * 8, readf32(src, p + k * 4)) + end + elseif t == "i" then + for k = 0, n - 1 do + writef64(out, k * 8, readi32(src, p + k * 4)) + end + elseif t == "l" then + for k = 0, n - 1 do + local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4) + writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo) + end + else + for k = 0, n - 1 do + writef64(out, k * 8, readu8(src, p + k)) + end + end + return out +end + +-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset +@native function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then + return nil, "not a binary FBX", base + end + local version = readu32(b, base + 23) + if version < 7000 or version >= 10000 then + return nil, "unsupported:FBX version " .. version, base + 23 + end + local wide = version >= 7500 + local head = if wide then 25 else 13 + local total = 0 + + @native local function props(p: number, n: number, stop: number): ({ any }?, any) + local out = table.create(math.min(n, 64)) + for k = 1, n do + if p >= stop then + return nil, "property list runs past its record" + end + local c = readu8(b, p) + p += 1 + local v: any + if c == 89 then -- Y + if p + 2 > stop then return nil, "truncated property" end + v = readi16(b, p) + p += 2 + elseif c == 67 then -- C + if p + 1 > stop then return nil, "truncated property" end + v = readu8(b, p) ~= 0 + p += 1 + elseif c == 73 then -- I + if p + 4 > stop then return nil, "truncated property" end + v = readi32(b, p) + p += 4 + elseif c == 70 then -- F + if p + 4 > stop then return nil, "truncated property" end + v = readf32(b, p) + p += 4 + elseif c == 68 then -- D + if p + 8 > stop then return nil, "truncated property" end + v = readf64(b, p) + p += 8 + elseif c == 76 then -- L + if p + 8 > stop then return nil, "truncated property" end + v = i64(b, p, true) + p += 8 + elseif c == 83 or c == 82 then -- S, R + if p + 4 > stop then return nil, "truncated property" end + local len = readu32(b, p) + p += 4 + if len > stop - p then return nil, "string runs past its record" end + if c == 83 then + v = buffer.readstring(b, p, len) + else + local raw = buffer.create(len) + buffer.copy(raw, 0, b, p, len) + v = raw + end + p += len + elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c + if p + 12 > stop then return nil, "truncated array header" end + local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8) + p += 12 + local t = string.char(c) + local es = ELEM[t] + if clen > stop - p then return nil, "array runs past its record" end + total += count * 8 + if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end + local data: buffer + if enc == 0 then + if clen < count * es then return nil, "raw array shorter than its count" end + data = toF64(t, b, p, count) + elseif enc == 1 then + local raw, err = Deflate.zlib(b, p, clen, count * es) + if not raw then + return nil, "array: " .. tostring(if type(err) == "table" then err.message else err) + end + data = toF64(t, raw, 0, count) + else + return nil, "unknown array encoding " .. enc + end + p += clen + v = { array = true, type = t, count = count, data = data } + else + return nil, string.format("unknown property type 0x%02x", c) + end + out[k] = v + end + return out, p + end + + -- one node record at p: node | false (the null record), next offset | nil, message, offset + @native local function node(p: number, stop: number, depth: number): (any, any, number?) + if p + head > stop then + return nil, "truncated node record", p + end + local endOff, nprops, plen, nlen + if wide then + endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296 + nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296 + plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296 + nlen = readu8(b, p + 24) + else + endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), (readu8(b, p + 12)) + end + if endOff == 0 then + return false, p + head + end + local e = base + endOff + if e > stop or e < p + head + nlen + plen then + return nil, "node end offset out of range", p + end + if nprops > plen then + return nil, "more properties than bytes", p + end + local q = p + head + local name = buffer.readstring(b, q, nlen) + q += nlen + local pl, nq = props(q, nprops, q + plen) + if not pl then + return nil, nq, q + end + q += plen + local children: { Node } = {} + if q < e then + if depth >= MAX_DEPTH then + return nil, "nodes nested too deep", p + end + while q < e do + local child, nx, off = node(q, e, depth + 1) + if child == nil then + return nil, nx, off + end + q = nx + if child == false then + break + end + table.insert(children, child) + end + end + return { name = name, props = pl, children = children }, e + end + + local root: Node = { name = "", props = {}, children = {} } + local p = base + 27 + while p < limit do + local n, nx, off = node(p, limit, 0) + if n == nil then + if #root.children > 0 and p + head > limit then + break -- a file cut right after its last node: keep what was read + end + return nil, nx, off + end + if n == false then + break + end + table.insert(root.children, n) + p = nx + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit +-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint +-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their +-- type (compressed with zlib when longer than 32 elements, unless compress = false). +type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +@native local function sizeHint(n: WNode): number + local s = 32 + #n.name + for _, v in n.props do + if type(v) == "string" then + s += 5 + #v + elseif type(v) == "buffer" then + s += 5 + buffer.len(v) + elseif type(v) == "table" then + s += 13 + (v.count or 0) * 8 + else + s += 9 + end + end + for _, c in n.children or {} do + s += sizeHint(c) + end + return s +end + +@native function Binary.write(root: WNode, version: number?, compress: boolean?): buffer + local zip = compress ~= false + local ver = version or 7400 + local wide = ver >= 7500 + local head = if wide then 25 else 13 + local cap = sizeHint(root) + 256 + local out = buffer.create(cap) + local pos = 0 + @native local function ensure(n: number) + if pos + n > cap then + while pos + n > cap do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, out, 0, pos) + out = nb + end + end + @native local function u8(v: number) + ensure(1) + buffer.writeu8(out, pos, v) + pos += 1 + end + @native local function u32(v: number) + ensure(4) + buffer.writeu32(out, pos, v) + pos += 4 + end + @native local function i64w(v: number) + ensure(8) + local hi = math.floor(v / 4294967296) + local lo = v - hi * 4294967296 + buffer.writeu32(out, pos, lo) + buffer.writeu32(out, pos + 4, hi % 4294967296) + pos += 8 + end + @native local function str(s: string) + ensure(#s) + buffer.writestring(out, pos, s) + pos += #s + end + @native local function bytes(src: buffer) + local n = buffer.len(src) + ensure(n) + buffer.copy(out, pos, src, 0, n) + pos += n + end + @native local function array(a: any) + local t, n, d = a.type, a.count, a.data + local es = ELEM[t] or 8 + local raw = buffer.create(n * es) + if a.raw then + buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es)) + else + for k = 0, n - 1 do + local v = readf64(d, k * 8) + if t == "d" then + writef64(raw, k * 8, v) + elseif t == "f" then + buffer.writef32(raw, k * 4, v) + elseif t == "i" then + buffer.writei32(raw, k * 4, v) + elseif t == "b" then + buffer.writeu8(raw, k, if v ~= 0 then 1 else 0) + else + local hi = math.floor(v / 4294967296) + buffer.writeu32(raw, k * 8, v - hi * 4294967296) + buffer.writeu32(raw, k * 8 + 4, hi % 4294967296) + end + end + end + u8(string.byte(t)) + u32(n) + if zip and n > 32 then + local z = Deflate.zlibCompress(raw, { level = 6 }) + if z then + u32(1) + u32(buffer.len(z)) + bytes(z) + return + end + end + u32(0) + u32(n * es) + bytes(raw) + end + @native local function setOff(at: number, v: number) + if wide then + buffer.writeu32(out, at, v % 4294967296) + buffer.writeu32(out, at + 4, math.floor(v / 4294967296)) + else + buffer.writeu32(out, at, v) + end + end + @native local function nullRecord() + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + end + @native local function node(n: WNode) + local start = pos + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + buffer.writeu8(out, start + head - 1, #n.name) + str(n.name) + local pstart = pos + local hints = n.types or "" + for k, v in n.props do + local h = string.sub(hints, k, k) + local tv = type(v) + if tv == "number" then + if h == "I" then + u8(73) + ensure(4) + buffer.writei32(out, pos, v) + pos += 4 + elseif h == "L" then + u8(76) + i64w(v) + elseif h == "F" then + u8(70) + ensure(4) + buffer.writef32(out, pos, v) + pos += 4 + elseif h == "Y" then + u8(89) + ensure(2) + buffer.writei16(out, pos, v) + pos += 2 + else + u8(68) + ensure(8) + writef64(out, pos, v) + pos += 8 + end + elseif tv == "boolean" then + u8(67) + u8(if v then 1 else 0) + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then + u8(76) + local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0 + u32(lo) + u32(hi) + else + u8(83) + u32(#v) + str(v) + end + elseif tv == "buffer" then + u8(82) + u32(buffer.len(v)) + bytes(v) + elseif tv == "table" and v.array then + array(v) + else + u8(83) + u32(0) + end + end + local plen = pos - pstart + local children = n.children + if children and #children > 0 then + for _, c in children do + node(c) + end + nullRecord() + elseif #n.props == 0 then + nullRecord() + end + setOff(start, pos) + if wide then + setOff(start + 8, #n.props) + setOff(start + 16, plen) + else + buffer.writeu32(out, start + 4, #n.props) + buffer.writeu32(out, start + 8, plen) + end + end + str(MAGIC) + u8(0x1A) + u8(0) + u32(ver) + for _, c in root.children or {} do + node(c) + end + nullRecord() + str(FOOT_ID) + str("\0\0\0\0") + local pad = ((pos + 15) // 16) * 16 - pos + if pad == 0 then + pad = 16 + end + str(string.rep("\0", pad)) + u32(ver) + str(string.rep("\0", 120)) + str(FOOT_MAGIC) + local res = buffer.create(pos) + buffer.copy(res, 0, out, 0, pos) + return res +end + +return Binary +end +__FILES["model/fbx/Read"] = function() + +-- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> +-- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric +-- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in +-- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one +-- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the +-- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file +-- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind +-- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's +-- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or +-- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node +-- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Xform = __include("model/fbx/Xform") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +type Node = { name: string, props: { any }, children: { Node } } +type Array = { array: true, type: string, count: number, data: buffer } +type Obj = { id: any, node: Node, name: string, class: string, sub: string, props: { [string]: { any } } } +type Conn = { id: any, prop: string? } +type Fetch = (uri: string) -> buffer? + +local TICKS = 46186158000 -- FBX time units per second +Read.TICKS = TICKS + +-- ------------------------------------------------------------------------------------------------ tree helpers +local function child(n: Node?, name: string): Node? + if not n then + return nil + end + for _, c in n.children do + if c.name == name then + return c + end + end + return nil +end +Read.child = child + +local function value(n: Node?, name: string): any + local c = child(n, name) + return c and c.props[1] +end + +local function isArray(v: any): boolean + return type(v) == "table" and v.array == true +end + +-- the array under n. (or inline numbers: old ASCII files) +local function array(n: Node?, name: string): Array? + local c = child(n, name) + if not c then + return nil + end + local p = c.props[1] + if isArray(p) then + return p + end + local count = 0 + for _, v in c.props do + if type(v) == "number" then + count += 1 + end + end + if count == 0 then + return nil + end + local data = buffer.create(count * 8) + local k = 0 + for _, v in c.props do + if type(v) == "number" then + buffer.writef64(data, k * 8, v) + k += 1 + end + end + return { array = true, type = "d", count = count, data = data } +end + +local function at(a: Array, i: number): number + if i < 0 or i >= a.count then + return 0 + end + return buffer.readf64(a.data, i * 8) +end + +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +local function objectName(s: any): string + if type(s) ~= "string" then + return "" + end + local nm = string.match(s, "^(.-)%z\1") + if nm then + return nm + end + local _, rest = string.match(s, "^(%w+)::(.*)$") + if rest then + return rest + end + return s +end +Read.objectName = objectName + +-- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } + local out = into or {} + local p70 = child(n, "Properties70") + if p70 then + for _, p in p70.children do + local nm = p.props[1] + if p.name == "P" and type(nm) == "string" then + local v = { p.props[2] } + for k = 5, #p.props do + v[k - 3] = p.props[k] + end + out[nm] = v + end + end + end + return out +end +Read.properties = properties + +local function pnum(props: { [string]: { any } }, name: string, default: number): number + local p = props[name] + local v = p and p[2] + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return default +end +local function pvec(props: { [string]: { any } }, name: string, default: { number }): { number } + local p = props[name] + if p and type(p[2]) == "number" and type(p[3]) == "number" and type(p[4]) == "number" then + return { p[2], p[3], p[4] } + end + return table.clone(default) +end +local function pstr(props: { [string]: { any } }, name: string): string? + local p = props[name] + local v = p and p[2] + return if type(v) == "string" then v else nil +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local sampleRate = opts and type(opts.sampleRate) == "number" and opts.sampleRate > 0 and opts.sampleRate or nil + local maxVertices = opts and opts.maxVertices or 2 ^ 25 + local scene = Types.Scene.new() + + -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + local templates: { [string]: { [string]: { any } } } = {} + local defs = child(root, "Definitions") + if defs then + for _, ot in defs.children do + if ot.name == "ObjectType" and type(ot.props[1]) == "string" then + local pt = child(ot, "PropertyTemplate") + if pt then + templates[ot.props[1]] = properties(pt) + end + end + end + end + + -- objects + local objects: { [any]: Obj } = {} + local order: { Obj } = {} + local objs = child(root, "Objects") + if not objs then + return nil, Err.new(Err.CORRUPT, "no Objects section") + end + for _, n in objs.children do + local id = n.props[1] + if (type(id) == "number" or type(id) == "string") and objects[id] == nil then + local base = templates[n.name] + local props = properties(n, if base then table.clone(base) else nil) + local o: Obj = { id = id, node = n, name = objectName(n.props[2]), class = n.name, sub = if type(n.props[3]) == "string" then n.props[3] else "", props = props } + objects[id] = o + table.insert(order, o) + end + end + + -- connections: children (sources) of each parent, parents of each child, in file order + local kids: { [any]: { Conn } } = {} + local parents: { [any]: { Conn } } = {} + local conns = child(root, "Connections") + if conns then + for _, c in conns.children do + if c.name == "C" or c.name == "Connect" then + local src, dst = c.props[2], c.props[3] + local prop = if type(c.props[4]) == "string" then c.props[4] else nil + if src ~= nil and dst ~= nil and type(src) ~= "table" and type(dst) ~= "table" then + kids[dst] = kids[dst] or {} + table.insert(kids[dst], { id = src, prop = prop }) + parents[src] = parents[src] or {} + table.insert(parents[src], { id = dst, prop = prop }) + end + end + end + end + local function sources(id: any, class: string?, sub: string?): { Obj } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) and (sub == nil or o.sub == sub) then + table.insert(out, o) + end + end + return out + end + local function sourcesProp(id: any): { { obj: Obj, prop: string? } } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + local function targets(id: any, class: string?): { { obj: Obj, prop: string? } } + local out = {} + for _, c in parents[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + + -- global settings + local gs = properties(child(root, "GlobalSettings")) + local upAxis = pnum(gs, "UpAxis", 1) + local unitScale = pnum(gs, "UnitScaleFactor", 1) + scene.meta.up = if upAxis == 2 then "z" else "y" + scene.meta.unit = unitScale / 100 + local frameRates = { [1] = 120, [2] = 100, [3] = 60, [4] = 50, [5] = 48, [6] = 30, [7] = 30, [8] = 29.97, [9] = 29.97, [10] = 25, [11] = 24, [13] = 96, [14] = 72, [15] = 59.94, [17] = 119.88 } + local timeMode = pnum(gs, "TimeMode", 0) + local fps = if timeMode == 14 then pnum(gs, "CustomFrameRate", 24) else frameRates[timeMode] or 24 + + -- ------------------------------------------------------------------------------------------ textures + local textureIndex: { [any]: number } = {} + local function mimeOf(data: buffer?, name: string?): string? + if data and buffer.len(data) >= 4 then + local h = buffer.readstring(data, 0, 4) + if h == "\137PNG" then + return "image/png" + elseif string.sub(h, 1, 3) == "\255\216\255" then + return "image/jpeg" + elseif string.sub(h, 1, 2) == "BM" then + return "image/bmp" + elseif h == "DDS " then + return "image/vnd-ms.dds" + elseif h == "RIFF" then + return "image/webp" + end + end + local ext = name and string.lower(string.match(name, "%.(%w+)$") or "") or "" + local M = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", webp = "image/webp", gif = "image/gif", psd = "image/vnd.adobe.photoshop" } + return M[ext] + end + local function content(v: Node?): buffer? + if not v then + return nil + end + local c = child(v, "Content") + if not c then + return nil + end + for _, p in c.props do + if type(p) == "buffer" and buffer.len(p) > 0 then + return p + end + end + -- ASCII: base64 strings (possibly split into several) + local parts = {} + for _, p in c.props do + if type(p) == "string" then + table.insert(parts, p) + end + end + local s = table.concat(parts) + if #s > 0 then + local d = Base64.decode(s) + if d and buffer.len(d) > 0 then + return d + end + end + return nil + end + local function texture(o: Obj): number + local have = textureIndex[o.id] + if have then + return have + end + local n = o.node + local rel = value(n, "RelativeFilename") + local file = value(n, "FileName") or value(n, "Filename") + local data: buffer? = nil + local video: Obj? = sources(o.id, "Video")[1] + if video then + data = content(video.node) + rel = rel or value(video.node, "RelativeFilename") + file = file or value(video.node, "Filename") or value(video.node, "FileName") + end + local uri: string? = nil + if type(rel) == "string" and rel ~= "" then + uri = (string.gsub(rel, "\\", "/")) + elseif type(file) == "string" and file ~= "" then + uri = (string.gsub(file, "\\", "/")) + end + if not data and uri then + data = fetch(uri :: string) + if not data then + local base = string.match(uri :: string, "([^/]+)$") + if base and base ~= uri then + data = fetch(base) + end + end + end + local tex: Types.Texture = { name = o.name, data = data, uri = if data and video and content(video.node) then nil else uri, mime = mimeOf(data, uri) } + local wrapU, wrapV = pnum(o.props, "WrapModeU", 0), pnum(o.props, "WrapModeV", 0) + if wrapU ~= 0 or wrapV ~= 0 then + tex.sampler = { wrapS = if wrapU == 1 then "clamp" else "repeat", wrapT = if wrapV == 1 then "clamp" else "repeat" } + end + tex.extras = { fbx = { uri = uri, uvSet = pstr(o.props, "UVSet") } } + table.insert(scene.textures, tex) + textureIndex[o.id] = #scene.textures + return #scene.textures + end + local function texRef(o: Obj): Types.TextureRef? + local tobj = o + if o.class == "LayeredTexture" then + local t = sources(o.id, "Texture")[1] + if not t then + return nil + end + tobj = t + end + local ref: Types.TextureRef = { texture = texture(tobj) } + local tr, sc = pvec(tobj.props, "Translation", { 0, 0, 0 }), pvec(tobj.props, "Scaling", { 1, 1, 1 }) + local rot = pvec(tobj.props, "Rotation", { 0, 0, 0 }) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot[3] ~= 0 then + ref.transform = { offset = { tr[1], tr[2] }, scale = { sc[1], sc[2] }, rotation = rot[3] * math.pi / 180 } + end + return ref + end + + -- ------------------------------------------------------------------------------------------ materials + local materialIndex: { [any]: number } = {} + local function material(o: Obj): number + local have = materialIndex[o.id] + if have then + return have + end + local p = o.props + local m = Types.Scene.material(o.name) + local shading = value(o.node, "ShadingModel") + local diffuse = pvec(p, "DiffuseColor", pvec(p, "Diffuse", { 0.8, 0.8, 0.8 })) + local dfac = pnum(p, "DiffuseFactor", 1) + local emissive = pvec(p, "EmissiveColor", pvec(p, "Emissive", { 0, 0, 0 })) + local efac = pnum(p, "EmissiveFactor", 1) + local shininess = pnum(p, "ShininessExponent", pnum(p, "Shininess", 20)) + local opacity: number + if p.Opacity then + opacity = pnum(p, "Opacity", 1) + else + local tc = pvec(p, "TransparentColor", { 1, 1, 1 }) + opacity = 1 - pnum(p, "TransparencyFactor", 0) * (tc[1] + tc[2] + tc[3]) / 3 + end + opacity = math.clamp(opacity, 0, 1) + m.baseColor = { diffuse[1] * dfac, diffuse[2] * dfac, diffuse[3] * dfac, opacity } + m.emissive = { emissive[1] * efac, emissive[2] * efac, emissive[3] * efac } + m.metallic = 0 + m.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + if opacity < 1 then + m.alphaMode = "blend" + end + -- 3ds Max Physical / PBR materials + local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] + if pbr then + local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" + local bc = pbr + if type(bc[2]) == "number" then + m.baseColor = { bc[2], bc[3] or 1, bc[4] or 1, if type(bc[5]) == "number" then bc[5] else 1 } + end + m.metallic = pnum(p, prefix .. "metalness", 0) + m.roughness = pnum(p, prefix .. "roughness", 1) + if pnum(p, prefix .. "useGlossiness", 0) == 1 or pnum(p, prefix .. "roughness_inv", 0) == 1 then + m.roughness = 1 - pnum(p, prefix .. "glossiness", 1 - m.roughness) + end + local ec = p[prefix .. "emit_color"] or p[prefix .. "emission_color"] + if ec and type(ec[2]) == "number" then + local k = pnum(p, prefix .. "emission", 1) + m.emissive = { ec[2] * k, (ec[3] or 0) * k, (ec[4] or 0) * k } + end + end + local extras: { [string]: any } = { + shadingModel = if type(shading) == "string" then string.lower(shading) else pstr(p, "ShadingModel"), + diffuse = diffuse, + diffuseFactor = dfac, + ambient = pvec(p, "AmbientColor", pvec(p, "Ambient", { 0, 0, 0 })), + ambientFactor = pnum(p, "AmbientFactor", 1), + specular = pvec(p, "SpecularColor", pvec(p, "Specular", { 0.2, 0.2, 0.2 })), + specularFactor = pnum(p, "SpecularFactor", 1), + shininess = shininess, + emissive = emissive, + emissiveFactor = efac, + opacity = opacity, + reflection = pvec(p, "ReflectionColor", { 0, 0, 0 }), + reflectionFactor = pnum(p, "ReflectionFactor", 0), + bumpFactor = pnum(p, "BumpFactor", 1), + textures = {}, + } + for _, s in sourcesProp(o.id) do + local cls = s.obj.class + if (cls == "Texture" or cls == "LayeredTexture") and s.prop then + local ref = texRef(s.obj) + if ref then + local prop = s.prop :: string + local lp = string.lower(prop) + extras.textures[prop] = ref.texture + if lp == "diffusecolor" or string.find(lp, "base_?color_map") or lp == "maya|basecolor" or lp == "maya|texturebasecolor" then + m.baseColorTexture = m.baseColorTexture or ref + elseif lp == "normalmap" or lp == "bump" or string.find(lp, "norm_map") or string.find(lp, "bump_map") or lp == "maya|normalcamera" then + m.normalTexture = m.normalTexture or ref + elseif lp == "emissivecolor" or string.find(lp, "emit_color_map") or string.find(lp, "emission_map") then + m.emissiveTexture = m.emissiveTexture or ref + if m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 1, 1, 1 } + end + elseif string.find(lp, "ao_map") then + m.occlusionTexture = m.occlusionTexture or ref + end + end + end + end + if not next(extras.textures) then + extras.textures = nil + end + m.extras = { fbx = extras } + table.insert(scene.materials, m) + materialIndex[o.id] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ nodes + local models: { Obj } = {} + local nodeOf: { [any]: number } = {} + for _, o in order do + if o.class == "Model" then + table.insert(models, o) + local nd: Types.Node = { name = o.name, children = {} } + table.insert(scene.nodes, nd) + nodeOf[o.id] = #scene.nodes + end + end + if #models > maxVertices then + return nil, Err.new(Err.LIMIT, "too many models") + end + local function xprops(o: Obj, over: { [string]: { number } }?): Xform.Props + local p = o.props + local function g(name: string, key: string, default: { number }): { number } + if over and over[key] then + return over[key] + end + return pvec(p, name, default) + end + return { + T = g("Lcl Translation", "T", { 0, 0, 0 }), + R = g("Lcl Rotation", "R", { 0, 0, 0 }), + S = g("Lcl Scaling", "S", { 1, 1, 1 }), + Rpre = pvec(p, "PreRotation", { 0, 0, 0 }), + Rpost = pvec(p, "PostRotation", { 0, 0, 0 }), + Roff = pvec(p, "RotationOffset", { 0, 0, 0 }), + Rp = pvec(p, "RotationPivot", { 0, 0, 0 }), + Soff = pvec(p, "ScalingOffset", { 0, 0, 0 }), + Sp = pvec(p, "ScalingPivot", { 0, 0, 0 }), + order = pnum(p, "RotationOrder", 0), + } + end + local localM: { [number]: Mat4.M4 } = {} + for _, o in models do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + local m = Xform.localMatrix(xprops(o)) + localM[ni] = m + local t, r, s = Mat4.decompose(m) + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + nd.translation = t + end + if r[1] ~= 0 or r[2] ~= 0 or r[3] ~= 0 or r[4] ~= 1 then + nd.rotation = r + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + nd.scale = s + end + nd.extras = { fbx = { type = o.sub, id = o.id } } + -- parent + local parentModel: Obj? = nil + for _, t2 in targets(o.id, "Model") do + parentModel = t2.obj + break + end + local pi = parentModel and nodeOf[parentModel.id] + if pi and pi ~= ni then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + do + local placed: { [number]: boolean } = {} + local function visit(i: number) + placed[i] = true + local nd = scene.nodes[i] + local keepKids = {} + for _, c in nd.children do + if not placed[c] then + table.insert(keepKids, c) + visit(c) + end + end + nd.children = keepKids + end + for _, r in scene.roots do + visit(r) + end + for i in scene.nodes do + if not placed[i] then + -- part of a parent cycle: make it a root + table.insert(scene.roots, i) + visit(i) + end + end + end + -- world matrices (rest pose) + local worldM: { [number]: Mat4.M4 } = {} + local function world(i: number, parent: Mat4.M4) + worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) + for _, c in scene.nodes[i].children do + if not worldM[c] then + world(c, worldM[i]) + end + end + end + for _, r in scene.roots do + world(r, Mat4.identity()) + end + + -- ------------------------------------------------------------------------------------------ meshes + local corners = 0 + -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels + local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) + local skin = sources(geo.id, "Deformer", "Skin")[1] + if not skin then + return nil, nil + end + local perCp: { { { number } } } = {} + local joints: { number } = {} + local ibms: { Mat4.M4 } = {} + for _, cl in sources(skin.id, "Deformer", "Cluster") do + local bone = sources(cl.id, "Model")[1] + local bi = bone and nodeOf[bone.id] + if bi then + local ji = #joints + 1 + joints[ji] = bi + local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") + local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") + local tm = Mat4.identity() + if T and T.count >= 16 then + for k = 1, 16 do + tm[k] = at(T, k - 1) + end + end + local tl: Mat4.M4? = nil + if TL and TL.count >= 16 then + tl = {} + for k = 1, 16 do + (tl :: any)[k] = at(TL, k - 1) + end + else + tl = worldM[bi] + end + local inv = Mat4.inverse(tl :: Mat4.M4) or Mat4.identity() + ibms[ji] = Mat4.mul(inv, tm) + if idx and w then + for k = 0, math.min(idx.count, w.count) - 1 do + local cp = at(idx, k) + local wt = at(w, k) + if cp >= 0 and cp == math.floor(cp) and cp < maxVertices and wt > 0 then + local l = perCp[cp + 1] + if not l then + l = {} + perCp[cp + 1] = l + end + table.insert(l, { ji - 1, wt }) + end + end + end + end + end + if #joints == 0 then + return nil, nil + end + local ibm = buffer.create(#joints * 64) + for j, m in ibms do + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local acc = Types.Scene.accessor(ibm, "f32", 16, #joints) + acc.matrix = true + return perCp, { name = skin.name, joints = joints, inverseBindMatrices = acc } + end + type Shape = { name: string, channel: Obj, weight: number, idx: Array?, dv: Array?, dn: Array? } + local function shapesOf(geo: Obj): { Shape } + local out = {} + for _, bs in sources(geo.id, "Deformer", "BlendShape") do + for _, ch in sources(bs.id, "Deformer", "BlendShapeChannel") do + local shapes = sources(ch.id, "Geometry") + local sh = shapes[#shapes] -- in-betweens: the full (last) shape + if sh then + table.insert(out, { + name = ch.name ~= "" and ch.name or sh.name, + channel = ch, + weight = pnum(ch.props, "DeformPercent", 0) / 100, + idx = array(sh.node, "Indexes"), + dv = array(sh.node, "Vertices"), + dn = array(sh.node, "Normals"), + }) + end + end + end + return out + end + + local meshCache: { [string]: number } = {} + local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves) + local nodeSkin: { [number]: number } = {} + local skinCache: { [any]: number } = {} + + local function buildMesh(geo: Obj, mats: { number }, G: Mat4.M4?): (number?, Err.Err?) + local g = geo.node + local verts = array(g, "Vertices") + local pvi = array(g, "PolygonVertexIndex") + if not verts or not pvi then + return nil, nil + end + local ncp = verts.count // 3 + local nc = pvi.count + corners += nc + if corners > maxVertices or ncp > maxVertices then + return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") + end + -- polygons: corner -> control point, polygon of each corner, polygon starts + local cp = table.create(nc, 0) + local polyOf = table.create(nc, 0) + local starts: { number } = { 0 } + local np = 0 + for c = 0, nc - 1 do + local v = at(pvi, c) + local last = v < 0 + if last then + v = -v - 1 + end + if v >= ncp or v ~= math.floor(v) then + v = 0 + end + cp[c + 1] = v + polyOf[c + 1] = np + if last then + np += 1 + starts[np + 1] = c + 1 + end + end + if starts[np + 1] ~= nc then + -- the last polygon has no end marker + np += 1 + starts[np + 1] = nc + end + -- layer elements + type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } + local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } + local out: { Elem } = {} + for _, c in g.children do + if c.name == kind then + local data = array(c, dataName) + local mapping = value(c, "MappingInformationType") + local ref = value(c, "ReferenceInformationType") + local index = if ref == "IndexToDirect" or ref == "Index" then array(c, indexName) or array(c, dataName .. "Index") else nil + if kind == "LayerElementMaterial" then + index = data + end + if data and type(mapping) == "string" then + table.insert(out, { data = data, index = index, mapping = mapping, comps = comps, name = value(c, "Name"), order = if type(c.props[1]) == "number" then c.props[1] else #out }) + end + end + end + table.sort(out, function(a: Elem, b: Elem): boolean + return a.order < b.order + end) + return out + end + -- the data element of a corner (c 0-based), or -1 + local function lookup(e: Elem, c: number): number + local m = e.mapping + local i + if m == "ByPolygonVertex" then + i = c + elseif m == "ByVertice" or m == "ByVertex" then + i = cp[c + 1] + elseif m == "ByPolygon" then + i = polyOf[c + 1] + elseif m == "AllSame" then + i = 0 + else + return -1 + end + if e.index and e.data ~= e.index then + if i >= (e.index :: Array).count then + return -1 + end + i = at(e.index :: Array, i) + end + if i < 0 or (i + 1) * e.comps > e.data.count then + return -1 + end + return i + end + local normals = elems("LayerElementNormal", "Normals", "NormalsIndex", 3) + local uvs = elems("LayerElementUV", "UV", "UVIndex", 2) + local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) + local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) + local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] + -- the normals index name varies ("NormalsIndex" / "NormalIndex") + for _, e in normals do + if not e.index then + local c = nil + for _, x in g.children do + if x.name == "LayerElementNormal" then + c = x + break + end + end + local r = c and value(c, "ReferenceInformationType") + if r == "IndexToDirect" then + e.index = array(c, "NormalIndex") + end + end + end + -- polygons by material slot + local groups: { [number]: { number } } = {} + local slots: { number } = {} + for p = 0, np - 1 do + local slot = 0 + if matEl then + local c0 = starts[p + 1] + local i = if matEl.mapping == "AllSame" then 0 else p + if matEl.mapping == "ByPolygonVertex" then + i = c0 + end + slot = at(matEl.data, i) + if slot < 0 or slot ~= math.floor(slot) then + slot = 0 + end + end + local grp = groups[slot] + if not grp then + grp = {} + groups[slot] = grp + table.insert(slots, slot) + end + table.insert(grp, p) + end + table.sort(slots) + local perCp, skin = skinOf(geo) + local shapes = shapesOf(geo) + local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) + if G then + local inv = Mat4.inverse(G) + if inv then + N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } + end + end + local mesh: Types.Mesh = { name = geo.name, primitives = {} } + local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Mat4.M4?, w: number) + if M then + x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w + end + buffer.writef32(dst, o, x) + buffer.writef32(dst, o + 4, y) + buffer.writef32(dst, o + 8, z) + end + local skipped = 0 + for _, slot in slots do + local polys = groups[slot] + local nv = 0 + local ntri = 0 + for _, p in polys do + local k = starts[p + 2] - starts[p + 1] + if k >= 3 or not triangulate then + nv += k + ntri += math.max(k - 2, 0) + else + skipped += 1 + end + end + if nv > 0 then + local pos = buffer.create(nv * 12) + local nrm = if normals[1] then buffer.create(nv * 12) else nil + local tan = if tangents[1] then buffer.create(nv * 16) else nil + local uvb: { buffer } = {} + for k = 1, #uvs do + uvb[k] = buffer.create(nv * 8) + end + local colb: { buffer } = {} + for k = 1, #colors do + colb[k] = buffer.create(nv * 16) + end + local joints = if perCp then buffer.create(nv * 8) else nil + local weights = if perCp then buffer.create(nv * 16) else nil + local tgt: { { [string]: Types.Accessor } } = {} + local shapeData: { { pos: buffer, nrm: buffer?, map: { [number]: number } } } = {} + for si, sh in shapes do + local map: { [number]: number } = {} + if sh.idx then + for k = 0, sh.idx.count - 1 do + map[at(sh.idx, k)] = k + end + end + shapeData[si] = { pos = buffer.create(nv * 12), nrm = if sh.dn and nrm then buffer.create(nv * 12) else nil, map = map } + end + local faces = if not triangulate then buffer.create(#polys * 4) else nil + local idx = buffer.create((if triangulate then ntri * 3 else nv) * 4) + local v = 0 + local ti = 0 + local fi = 0 + for _, p in polys do + local c0, c1 = starts[p + 1], starts[p + 2] + local k = c1 - c0 + if k >= 3 or not triangulate then + local first = v + for c = c0, c1 - 1 do + local i = cp[c + 1] + v3(pos, v * 12, at(verts, i * 3), at(verts, i * 3 + 1), at(verts, i * 3 + 2), G, 1) + if nrm then + local d = lookup(normals[1], c) + local e = normals[1].data + if d >= 0 then + v3(nrm, v * 12, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), N3, 0) + end + end + if tan then + local d = lookup(tangents[1], c) + local e = tangents[1].data + if d >= 0 then + v3(tan, v * 16, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), G, 0) + buffer.writef32(tan, v * 16 + 12, 1) + end + end + for u, e in uvs do + local d = lookup(e, c) + if d >= 0 then + local uu, vv = at(e.data, d * 2), at(e.data, d * 2 + 1) + buffer.writef32(uvb[u], v * 8, uu) + buffer.writef32(uvb[u], v * 8 + 4, if flipV then 1 - vv else vv) + end + end + for u, e in colors do + local d = lookup(e, c) + local b = colb[u] + if d >= 0 then + for q = 0, 3 do + buffer.writef32(b, v * 16 + q * 4, at(e.data, d * 4 + q)) + end + else + buffer.writef32(b, v * 16 + 12, 1) + end + end + if perCp and joints and weights then + local l = perCp[i + 1] + if l then + if #l > 4 then + table.sort(l, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + end + local sum = 0 + for q = 1, math.min(#l, 4) do + sum += l[q][2] + end + for q = 1, math.min(#l, 4) do + buffer.writeu16(joints, v * 8 + (q - 1) * 2, l[q][1]) + buffer.writef32(weights, v * 16 + (q - 1) * 4, if sum > 0 then l[q][2] / sum else 0) + end + end + end + for si, sd in shapeData do + local sh = shapes[si] + local k2 = sd.map[i] + if k2 and sh.dv then + v3(sd.pos, v * 12, at(sh.dv, k2 * 3), at(sh.dv, k2 * 3 + 1), at(sh.dv, k2 * 3 + 2), G, 0) + if sd.nrm and sh.dn then + v3(sd.nrm, v * 12, at(sh.dn, k2 * 3), at(sh.dn, k2 * 3 + 1), at(sh.dn, k2 * 3 + 2), N3, 0) + end + end + end + if not triangulate then + buffer.writeu32(idx, v * 4, v) + end + v += 1 + end + if triangulate then + for q = 1, k - 2 do + buffer.writeu32(idx, ti * 4, first) + buffer.writeu32(idx, ti * 4 + 4, first + q) + buffer.writeu32(idx, ti * 4 + 8, first + q + 1) + ti += 3 + end + elseif faces then + buffer.writeu32(faces, fi * 4, k) + fi += 1 + end + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if tan then + attrs.TANGENT = Types.Scene.accessor(tan, "f32", 4, nv) + end + for u, b in uvb do + attrs["TEXCOORD_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 2, nv) + end + for u, b in colb do + attrs["COLOR_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 4, nv) + end + if joints and weights then + attrs.JOINTS_0 = Types.Scene.accessor(joints, "u16", 4, nv) + attrs.WEIGHTS_0 = Types.Scene.accessor(weights, "f32", 4, nv) + end + for si, sd in shapeData do + local t: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(sd.pos, "f32", 3, nv) } + if sd.nrm then + t.NORMAL = Types.Scene.accessor(sd.nrm, "f32", 3, nv) + end + tgt[si] = t + end + local prim: Types.Primitive = { + attributes = attrs, + indices = Types.Scene.accessor(idx, "u32", 1, if triangulate then ntri * 3 else nv), + mode = if triangulate then "triangles" else "polygons", + faces = if faces then Types.Scene.accessor(faces, "u32", 1, #polys) else nil, + material = mats[slot + 1], + targets = if #tgt > 0 then tgt else nil, + } + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + local names = {} + for k, uv in uvs do + names[k] = uv.name + end + mesh.extras = { fbx = { id = geo.id, uvSets = names, skippedPolygons = if skipped > 0 then skipped else nil } } + if #shapes > 0 then + local w, tn, chans = {}, {}, {} + for si, sh in shapes do + w[si] = sh.weight + tn[si] = sh.name + chans[si] = sh.channel + end + mesh.weights = w + ;(mesh.extras :: any).targetNames = tn + table.insert(scene.meshes, mesh) + shapeChannels[#scene.meshes] = chans + else + table.insert(scene.meshes, mesh) + end + local mi = #scene.meshes + if skin then + skinCache[geo.id] = skinCache[geo.id] or (function(): number + table.insert(scene.skins, skin) + return #scene.skins + end)() + end + return mi, nil + end + + local orient = math.sqrt(0.5) + for _, o in models do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + -- materials of the model, in connection order + local mats: { number } = {} + for _, m in sources(o.id, "Material") do + table.insert(mats, material(m)) + end + -- geometric transform (not inherited: baked into the mesh) + local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) + local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) + local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) + local G: Mat4.M4? = nil + if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then + G = Mat4.mul(Mat4.translation(gt[1], gt[2], gt[3]), Mat4.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Mat4.scaling(gsc[1], gsc[2], gsc[3]))) + end + for _, geo in sources(o.id, "Geometry") do + if geo.sub == "Mesh" or geo.sub == "" then + local key = tostring(geo.id) .. "|" .. table.concat(mats, ",") .. "|" .. (if G then table.concat(G :: any, ",") else "") + local mi = meshCache[key] + if mi == nil then + local m, err = buildMesh(geo, mats, G) + if err then + return nil, err + end + if m then + meshCache[key] = m + mi = m + end + end + if mi then + if nd.mesh == nil then + nd.mesh = mi + if skinCache[geo.id] then + nd.skin = skinCache[geo.id] + end + nd.weights = scene.meshes[mi].weights and table.clone(scene.meshes[mi].weights :: { number }) + else + -- a second geometry on the same model: a child node + table.insert(scene.nodes, { name = o.name, children = {}, mesh = mi, skin = skinCache[geo.id] }) + table.insert(nd.children, #scene.nodes) + end + nodeSkin[ni] = skinCache[geo.id] + end + end + end + -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + for _, a in sources(o.id, "NodeAttribute") do + local p = a.props + if a.sub == "Camera" then + local ortho = pnum(p, "CameraProjectionType", 0) == 1 + local aw, ah = pnum(p, "AspectWidth", 0), pnum(p, "AspectHeight", 0) + local fw, fh = pnum(p, "FilmWidth", 0.816), pnum(p, "FilmHeight", 0.612) + local aspect = if aw > 0 and ah > 0 then aw / ah elseif fh > 0 then fw / fh else 4 / 3 + local cam: Types.Camera + local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) + if ortho then + local zoom = pnum(p, "OrthoZoom", 1) + cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } :: Types.Camera + else + local focal = pnum(p, "FocalLength", 0) + local hfov + if focal > 0 and fw > 0 then + hfov = 2 * math.atan(fw * 25.4 / (2 * focal)) + else + hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 + end + local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) + cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } :: Types.Camera + end + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) + table.insert(nd.children, #scene.nodes) + elseif a.sub == "Light" then + local lt = pnum(p, "LightType", 0) + local col = pvec(p, "Color", { 1, 1, 1 }) + local light: Types.Light = { + name = a.name ~= "" and a.name or o.name, + type = if lt == 1 then "directional" elseif lt == 2 then "spot" else "point", + color = col, + intensity = pnum(p, "Intensity", 100) / 100, + } + if lt == 2 then + local outer = pnum(p, "OuterAngle", pnum(p, "Cone angle", 45)) + local inner = pnum(p, "InnerAngle", pnum(p, "HotSpot", 0)) + light.outerCone = math.clamp(outer / 2, 0, 90) * math.pi / 180 + light.innerCone = math.clamp(math.min(inner, outer) / 2, 0, 90) * math.pi / 180 + end + if pnum(p, "EnableFarAttenuation", 0) == 1 then + light.range = pnum(p, "FarAttenuationEnd", 0) + end + table.insert(scene.lights, light) + table.insert(scene.nodes, { name = o.name .. "_light", children = {}, light = #scene.lights, rotation = { -orient, 0, 0, orient }, extras = { fbx = { orientation = "light", lightType = lt } } }) + table.insert(nd.children, #scene.nodes) + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + type Curve = { times: { number }, values: { number }, flags: { number }, slopes: { { number } }? } + local curveCache: { [any]: Curve } = {} + local function curve(o: Obj): Curve? + local have = curveCache[o.id] + if have then + return have + end + local kt, kv = array(o.node, "KeyTime"), array(o.node, "KeyValueFloat") + if not kt or not kv then + return nil + end + local n = math.min(kt.count, kv.count) + if n == 0 then + return nil + end + local times, values = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = at(kt, k) / TICKS + values[k + 1] = at(kv, k) + end + -- per-key attribute flags (expanded through KeyAttrRefCount) + local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") + local flags = table.create(n, 4) + local slopes: { { number } } = {} + if fl and rc then + local key = 1 + for a = 0, math.min(fl.count, rc.count) - 1 do + local f = at(fl, a) + local cnt = at(rc, a) + for _ = 1, math.min(cnt, n - key + 1) do + flags[key] = f + if df and df.count >= (a + 1) * 4 then + slopes[key] = { at(df, a * 4), at(df, a * 4 + 1) } + end + key += 1 + end + end + end + local c: Curve = { times = times, values = values, flags = flags, slopes = slopes } + curveCache[o.id] = c + return c + end + local function eval(c: Curve, t: number): number + local ts, vs = c.times, c.values + local n = #ts + if t <= ts[1] then + return vs[1] + elseif t >= ts[n] then + return vs[n] + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if ts[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = ts[hi] - ts[lo] + if dt <= 0 then + return vs[hi] + end + local u = (t - ts[lo]) / dt + local f = bit32.band(c.flags[lo] or 4, 0x0E) + if f == 2 then + return vs[lo] + elseif f == 8 and c.slopes and c.slopes[lo] then + local s = (c.slopes :: { { number } })[lo] + local m0, m1 = s[1] * dt, s[2] * dt + local u2, u3 = u * u, u * u * u + return (2 * u3 - 3 * u2 + 1) * vs[lo] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * vs[hi] + (u3 - u2) * m1 + end + return vs[lo] + (vs[hi] - vs[lo]) * u + end + local function allConstant(cs: { Curve }): boolean + for _, c in cs do + for k = 1, #c.times - 1 do + if bit32.band(c.flags[k] or 4, 0x0E) ~= 2 then + return false + end + end + end + return true + end + local function sampleTimes(cs: { Curve }): { number } + local set: { [number]: boolean } = {} + local out: { number } = {} + local tmin, tmax = math.huge, -math.huge + for _, c in cs do + for _, t in c.times do + tmin, tmax = math.min(tmin, t), math.max(tmax, t) + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + if sampleRate and tmax > tmin then + local steps = math.min(math.ceil((tmax - tmin) * sampleRate), 100000) + for k = 0, steps do + local t = tmin + (tmax - tmin) * k / steps + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + table.sort(out) + return out + end + local function f32acc(vals: { number }, comps: number): Types.Accessor + local n = #vals // comps + local b = buffer.create(#vals * 4) + for k, v in vals do + buffer.writef32(b, (k - 1) * 4, v) + end + return Types.Scene.accessor(b, "f32", comps, n) + end + local PROPS = { ["Lcl Translation"] = "T", ["Lcl Rotation"] = "R", ["Lcl Scaling"] = "S" } + for _, stack in order do + if stack.class == "AnimationStack" then + local anim: Types.Animation = { name = stack.name, channels = {} } + -- model id -> { T/R/S -> { axis -> curve } , defaults } + type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } + local tracks: { [any]: Track } = {} + local trackOrder: { any } = {} + local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve + local layers = sources(stack.id, "AnimationLayer") + for _, layer in layers do + for _, cn in sources(layer.id, "AnimationCurveNode") do + for _, tgt in targets(cn.id) do + local key = tgt.prop and PROPS[tgt.prop] + if key and tgt.obj.class == "Model" and nodeOf[tgt.obj.id] then + local tr = tracks[tgt.obj.id] + if not tr then + tr = { curves = {}, defaults = {} } + tracks[tgt.obj.id] = tr + table.insert(trackOrder, tgt.obj.id) + end + if not tr.curves[key] then + local axes: { [number]: Curve } = {} + for _, s in sourcesProp(cn.id) do + if s.obj.class == "AnimationCurve" and s.prop then + local ax = if string.find(s.prop, "X$") then 1 elseif string.find(s.prop, "Y$") then 2 elseif string.find(s.prop, "Z$") then 3 else nil + local c = ax and curve(s.obj) + if ax and c then + axes[ax] = c + end + end + end + if next(axes) then + tr.curves[key] = axes + tr.defaults[key] = { pnum(cn.props, "d|X", 0), pnum(cn.props, "d|Y", 0), pnum(cn.props, "d|Z", 0) } + end + end + elseif tgt.prop == "DeformPercent" and tgt.obj.class == "Deformer" then + for _, s in sources(cn.id, "AnimationCurve") do + local c = curve(s) + if c and not morph[tgt.obj.id] then + morph[tgt.obj.id] = c + end + end + end + end + end + end + for _, id in trackOrder do + local tr = tracks[id] + local o = objects[id] + local ni = nodeOf[id] + local cs: { Curve } = {} + for _, axes in tr.curves do + for _, c in pairs(axes) do + table.insert(cs, c) + end + end + local times = sampleTimes(cs) + if #times > 0 then + local base = xprops(o) + local T, R, S = {}, {}, {} + local prevQ: { number }? = nil + for _, t in times do + local over: { [string]: { number } } = {} + for key, axes in tr.curves do + local stat = (base :: any)[key] + local v = table.clone(stat) + for ax = 1, 3 do + local c = axes[ax] + if c then + v[ax] = eval(c, t) + end + end + over[key] = v + end + local tt, rr, ss = Mat4.decompose(Xform.localMatrix(xprops(o, over))) + if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then + rr = { -rr[1], -rr[2], -rr[3], -rr[4] } + end + prevQ = rr + table.move(tt, 1, 3, #T + 1, T) + table.move(rr, 1, 4, #R + 1, R) + table.move(ss, 1, 3, #S + 1, S) + end + local input = f32acc(times, 1) + local interp: any = if allConstant(cs) then "STEP" else "LINEAR" + local nd = scene.nodes[ni] + local function varies(vals: { number }, comps: number, rest: { number }): boolean + for k = 0, #vals // comps - 1 do + for q = 1, comps do + if math.abs(vals[k * comps + q] - rest[q]) > 1e-6 then + return true + end + end + end + return false + end + if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then + table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp } :: Types.Channel) + end + if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then + table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp } :: Types.Channel) + end + if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then + table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp } :: Types.Channel) + end + end + end + -- morph target weights: every node whose mesh has an animated blend shape channel + if next(morph) then + for ni, nd in scene.nodes do + local chans = nd.mesh and shapeChannels[nd.mesh] + if chans then + local cs: { Curve } = {} + for _, ch in chans do + if morph[ch.id] then + table.insert(cs, morph[ch.id]) + end + end + if #cs > 0 then + local times = sampleTimes(cs) + local out = {} + for _, t in times do + for _, ch in chans do + local c = morph[ch.id] + table.insert(out, (if c then eval(c, t) else pnum(ch.props, "DeformPercent", 0)) / 100) + end + end + local acc = f32acc(out, 1) + table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" } :: Types.Channel) + end + end + end + end + if #anim.channels > 0 then + table.insert(scene.animations, anim) + end + end + end + + -- ------------------------------------------------------------------------------------------ meta + local header = child(root, "FBXHeaderExtension") + local creator = value(root, "Creator") or value(header, "Creator") + scene.meta.source = { + format = "fbx", + version = version, + creator = if type(creator) == "string" then creator else nil, + upAxis = upAxis, + upAxisSign = pnum(gs, "UpAxisSign", 1), + frontAxis = pnum(gs, "FrontAxis", 2), + frontAxisSign = pnum(gs, "FrontAxisSign", 1), + coordAxis = pnum(gs, "CoordAxis", 0), + coordAxisSign = pnum(gs, "CoordAxisSign", 1), + unitScaleFactor = unitScale, + originalUnitScaleFactor = pnum(gs, "OriginalUnitScaleFactor", unitScale), + frameRate = fps, + } + local _ = nodeSkin + return scene, nil +end + +return Read +end +__FILES["model/fbx/Write"] = function() + +-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types +-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). +-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one +-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals +-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; +-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> +-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +local Err = __include("core/Err") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + +type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +local TICKS = 46186158000 +local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } } + +local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode + return { name = name, types = types, props = props, children = children } +end +local function arr(t: string, list: { number }): any + local n = #list + local d = buffer.create(n * 8) + for k = 1, n do + buffer.writef64(d, (k - 1) * 8, list[k]) + end + return { array = true, type = t, count = n, data = d } +end +-- P: name, type, label, flags, values (vt: one type character per value) +local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode + return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } +end +local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode + return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3]) +end +local function Pcolor(name: string, v: { number }): WNode + return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0) +end +local function Pnum(name: string, v: number): WNode + return P(name, "Number", "", "A", "D", v) +end +local function Pint(name: string, v: number): WNode + return P(name, "int", "Integer", "", "I", v) +end +local function Penum(name: string, v: number): WNode + return P(name, "enum", "", "", "I", v) +end +local function Pdouble(name: string, v: number): WNode + return P(name, "double", "Number", "", "D", v) +end +local function Ptime(name: string, v: number): WNode + return P(name, "KTime", "Time", "", "L", v) +end +local function cls(name: string?, class: string): string + return (name or "") .. "\0\1" .. class +end + +local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)? + if not acc then + return nil + end + return Types.Scene.reader(acc) +end + +-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) +local function faces(prim: Types.Primitive): { { number } }? + local pos = prim.attributes.POSITION + if not pos then + return nil + end + local n = pos.count + local idx = accessorReader(prim.indices) + local count = if prim.indices then prim.indices.count else n + local function I(k: number): number + return if idx then idx(k, 0) else k + end + local out: { { number } } = {} + local mode = prim.mode or "triangles" + if mode == "triangles" then + for k = 0, count // 3 - 1 do + table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) }) + end + elseif mode == "polygons" and prim.faces then + local f = accessorReader(prim.faces) + local p = 0 + if f then + for k = 0, prim.faces.count - 1 do + local sz = f(k, 0) + if p + sz > count then + break + end + local poly = table.create(sz) :: { number } + for q = 0, sz - 1 do + poly[q + 1] = I(p + q) + end + p += sz + table.insert(out, poly) + end + end + elseif mode == "triangle_strip" then + for k = 0, count - 3 do + local a, b, c = I(k), I(k + 1), I(k + 2) + if k % 2 == 1 then + a, b = b, a + end + table.insert(out, { a, b, c }) + end + elseif mode == "triangle_fan" then + for k = 1, count - 2 do + table.insert(out, { I(0), I(k), I(k + 1) }) + end + else + return nil -- points / lines: not written + end + for _, f in out do + for q, v in f do + if v < 0 or v >= n then + f[q] = 0 + end + end + end + return out +end + +function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) + local flipV = not (opts and opts.flipV == false) + local embed = not (opts and opts.embedTextures == false) + local nextId = 1000000 + local function id(): number + nextId += 1 + return nextId + end + local objects: { WNode } = {} + local conns: { WNode } = {} + local counts: { [string]: number } = {} + local function add(class: string, node: WNode) + table.insert(objects, node) + counts[class] = (counts[class] or 0) + 1 + end + local function OO(child: number, parent: number) + table.insert(conns, N("C", "SLL", { "OO", child, parent })) + end + local function OP(child: number, parent: number, prop: string) + table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop })) + end + local nodes = scene.nodes or {} + + -- ------------------------------------------------------------------------------------------ textures + local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } + local texIds: { [number]: number } = {} + local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + for ti, tex in scene.textures or {} do + local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) + local tname = tex.name or ("Texture" .. ti) + local vid, tid = id(), id() + local vchildren = { + N("Type", "S", { "Clip" }), + N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }), + N("UseMipMap", "I", { 0 }), + N("Filename", "S", { file }), + N("RelativeFilename", "S", { file }), + } + if embed and tex.data then + table.insert(vchildren, N("Content", "R", { tex.data })) + end + add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren)) + local tp = { P("UseMaterial", "bool", "", "", "I", 1) } + local smp = tex.sampler + if smp and smp.wrapS == "clamp" then + table.insert(tp, Penum("WrapModeU", 1)) + end + if smp and smp.wrapT == "clamp" then + table.insert(tp, Penum("WrapModeV", 1)) + end + add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, { + N("Type", "S", { "TextureVideoClip" }), + N("Version", "I", { 202 }), + N("TextureName", "S", { cls(tname, "Texture") }), + N("Properties70", "", {}, tp), + N("Media", "S", { cls(tname, "Video") }), + N("FileName", "S", { file }), + N("RelativeFilename", "S", { file }), + N("ModelUVTranslation", "DD", { 0, 0 }), + N("ModelUVScaling", "DD", { 1, 1 }), + N("Texture_Alpha_Source", "S", { "None" }), + N("Cropping", "IIII", { 0, 0, 0, 0 }), + })) + OO(vid, tid) + texIds[ti] = tid + end + + -- ------------------------------------------------------------------------------------------ materials + local matIds: { [number]: number } = {} + for mi, m in scene.materials or {} do + local x = m.extras and (m.extras :: any).fbx or {} + local bc = m.baseColor or { 1, 1, 1, 1 } + local alpha = bc[4] or 1 + local rough = math.clamp(m.roughness or 1, 0.02, 1) + local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2 + local em = m.emissive or { 0, 0, 0 } + local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 } + local pid = id() + local props = { + Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }), + Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1), + Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }), + Pnum("DiffuseFactor", 1), + Pcolor("EmissiveColor", em), + Pnum("EmissiveFactor", 1), + Pcolor("SpecularColor", spec), + Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1), + Pnum("Shininess", shin), + Pnum("ShininessExponent", shin), + Pcolor("TransparentColor", { 1, 1, 1 }), + Pnum("TransparencyFactor", 1 - alpha), + Pnum("Opacity", alpha), + Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }), + Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0), + } + add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, { + N("Version", "I", { 102 }), + N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }), + N("MultiLayer", "I", { 0 }), + N("Properties70", "", {}, props), + })) + matIds[mi] = pid + local function link(ref: Types.TextureRef?, prop: string) + local t = ref and texIds[ref.texture] + if t then + OP(t, pid, prop) + end + end + link(m.baseColorTexture, "DiffuseColor") + link(m.normalTexture, "NormalMap") + link(m.emissiveTexture, "EmissiveColor") + -- the other textures the FBX material had (specular, metalness, ... maps), under their property names + local linked = { + [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, + [m.normalTexture and m.normalTexture.texture or -1] = true, + [m.emissiveTexture and m.emissiveTexture.texture or -1] = true, + } + if type(x.textures) == "table" then + local props = {} + for prop in x.textures do + table.insert(props, prop) + end + table.sort(props) + for _, prop in props do + local ti = x.textures[prop] + if type(ti) == "number" and not linked[ti] and texIds[ti] then + linked[ti] = true + OP(texIds[ti], pid, prop) + end + end + end + end + + -- ------------------------------------------------------------------------------------------ models + local modelIds: { [number]: number } = {} + local skip: { [number]: boolean } = {} + local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) + local parentOf: { [number]: number } = {} + for i, nd in nodes do + for _, c in nd.children or {} do + if parentOf[c] == nil and c ~= i then + parentOf[c] = i + end + end + end + local jointSet: { [number]: boolean } = {} + for _, s in scene.skins or {} do + for _, j in s.joints do + jointSet[j] = true + end + end + for i, nd in nodes do + local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation + local p = parentOf[i] + if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then + skip[i] = true + attrHost[i] = p + end + end + -- world matrices (rest pose) for clusters and the bind pose + local worldM: { [number]: Mat4.M4 } = {} + local visiting: { [number]: boolean } = {} + local function world(i: number): Mat4.M4 + if worldM[i] then + return worldM[i] + end + if visiting[i] then + return Mat4.identity() + end + visiting[i] = true + local nd = nodes[i] + local l = if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then nd.matrix else Mat4.compose(nd.translation, nd.rotation, nd.scale) + local p = parentOf[i] + local w = if p then Mat4.mul(world(p), l) else l + worldM[i] = w + return w + end + local function trs(nd: Types.Node): ({ number }, { number }, { number }) + if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then + return Mat4.decompose(nd.matrix) + end + return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } + end + local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number + local mid = id() + add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, { + N("Version", "I", { 232 }), + N("Properties70", "", {}, { + Penum("RotationOrder", 0), + Penum("InheritType", 1), + Pint("DefaultAttributeIndex", 0), + Pvec("Lcl Translation", "Lcl Translation", "", t), + Pvec("Lcl Rotation", "Lcl Rotation", "", r), + Pvec("Lcl Scaling", "Lcl Scaling", "", s), + }), + N("Shading", "C", { true }), + N("Culling", "S", { "CullingOff" }), + })) + return mid + end + local function attribute(nd: Types.Node, mid: number, nodeName: string) + if nd.camera and scene.cameras[nd.camera] then + local c = scene.cameras[nd.camera] + local aid = id() + local aspect = c.aspect or 4 / 3 + local fh = 0.612 + local fw = fh * aspect + local props + if c.type == "orthographic" then + props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) } + else + local yfov = c.yfov or 0.8 + local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect) + local focal = fw * 25.4 / (2 * math.tan(hfov / 2)) + props = { + Penum("CameraProjectionType", 0), + Penum("ApertureMode", 1), + P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi), + P("FocalLength", "Number", "", "A", "D", focal), + Pdouble("FilmWidth", fw), + Pdouble("FilmHeight", fh), + Penum("AspectRatioMode", 0), + Pdouble("AspectWidth", aspect * 100), + Pdouble("AspectHeight", 100), + Pdouble("NearPlane", c.znear or 0.1), + Pdouble("FarPlane", c.zfar or 1000), + } + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Camera" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + elseif nd.light and scene.lights[nd.light] then + local l = scene.lights[nd.light] + local aid = id() + local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0 + local props = { + Penum("LightType", lt), + Pcolor("Color", l.color or { 1, 1, 1 }), + Pnum("Intensity", (l.intensity or 1) * 100), + P("CastLight", "bool", "", "", "I", 1), + } + if lt == 2 then + table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi)) + table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi)) + end + if l.range then + table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1)) + table.insert(props, Pnum("FarAttenuationEnd", l.range)) + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Light" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + end + end + for i, nd in nodes do + if not skip[i] then + local t, r, s = trs(nd) + local euler = Mat4.eulerXYZ(r) + local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type + local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" + -- an orientation child folded into this node gives it its attribute + local folded: number? = nil + for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) + if host == i then + folded = c + end + end + if not nd.mesh and folded then + sub = if nodes[folded].camera then "Camera" else "Light" + end + local mid = model(nd.name or ("Node" .. i), sub, t, euler, s) + modelIds[i] = mid + if sub == "LimbNode" then + local aid = id() + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) })) + OO(aid, mid) + end + if folded then + attribute(nodes[folded], mid, nd.name or "") + end + if nd.camera or nd.light then + -- a glTF-oriented camera / light: an FBX-oriented child model carries it + local kind = if nd.camera then "camera" else "light" + local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 }) + OO(cmid, mid) + attribute(nd, cmid, nd.name or "") + end + end + end + for i in nodes do + local mid = modelIds[i] + if mid then + local p = parentOf[i] + local pm = p and modelIds[p] + OO(mid, pm or 0) + end + end + + -- ------------------------------------------------------------------------------------------ geometry + local geoIds: { [number]: number } = {} + local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot + local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} + local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) + local geoCount: { [number]: number } = {} + local function geometry(mi: number): number? + if geoIds[mi] then + return geoIds[mi] + end + local mesh = scene.meshes[mi] + if not mesh then + return nil + end + local V, PVI, NRM, MATS = {}, {}, {}, {} + local UV: { [number]: { number } } = {} + local UVI: { [number]: { number } } = {} + local COL: { [number]: { number } } = {} + local COLI: { [number]: { number } } = {} + local slots: { number } = {} + local slotOf: { [number]: number } = {} + local hasN = false + local nuv, ncol = 0, 0 + for _, prim in mesh.primitives do + for k = 0, 7 do + if prim.attributes["TEXCOORD_" .. k] then + nuv = math.max(nuv, k + 1) + end + if prim.attributes["COLOR_" .. k] then + ncol = math.max(ncol, k + 1) + end + end + if prim.attributes.NORMAL then + hasN = true + end + end + for k = 1, nuv do + UV[k], UVI[k] = {}, {} + end + for k = 1, ncol do + COL[k], COLI[k] = {}, {} + end + local layout = {} + local offset = 0 + for _, prim in mesh.primitives do + local fs = faces(prim) + local pos = prim.attributes.POSITION + local R = accessorReader(pos) + if fs and R and pos then + table.insert(layout, { prim = prim, offset = offset }) + local n = pos.count + for v = 0, n - 1 do + table.insert(V, R(v, 0)) + table.insert(V, R(v, 1)) + table.insert(V, R(v, 2)) + end + local NR = accessorReader(prim.attributes.NORMAL) + if hasN then + for v = 0, n - 1 do + if NR then + table.insert(NRM, NR(v, 0)) + table.insert(NRM, NR(v, 1)) + table.insert(NRM, NR(v, 2)) + else + table.insert(NRM, 0) + table.insert(NRM, 0) + table.insert(NRM, 1) + end + end + end + local uvBase: { number } = {} + for k = 1, nuv do + uvBase[k] = #UV[k] // 2 + local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)]) + for v = 0, n - 1 do + local u, w = 0, 0 + if T then + u, w = T(v, 0), (T(v, 1)) + end + table.insert(UV[k], u) + table.insert(UV[k], if flipV then 1 - w else w) + end + end + local colBase: { number } = {} + for k = 1, ncol do + colBase[k] = #COL[k] // 4 + local acc = prim.attributes["COLOR_" .. (k - 1)] + local C = accessorReader(acc) + local comps = acc and acc.components or 4 + for v = 0, n - 1 do + table.insert(COL[k], if C then C(v, 0) else 1) + table.insert(COL[k], if C then C(v, 1) else 1) + table.insert(COL[k], if C then C(v, 2) else 1) + table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1) + end + end + local mat = prim.material or 0 + local slot = slotOf[mat] + if slot == nil then + table.insert(slots, mat) + slot = #slots - 1 + slotOf[mat] = slot + end + for _, f in fs do + for q, v in f do + local cp = v + offset + table.insert(PVI, if q == #f then -cp - 1 else cp) + for k = 1, nuv do + table.insert(UVI[k], uvBase[k] + v) + end + for k = 1, ncol do + table.insert(COLI[k], colBase[k] + v) + end + end + table.insert(MATS, slot) + end + offset += n + end + end + if #PVI == 0 then + return nil + end + local gid = id() + local ch: { WNode } = { + N("Properties70", "", {}, {}), + N("GeometryVersion", "I", { 124 }), + N("Vertices", "", { arr("d", V) }), + N("PolygonVertexIndex", "", { arr("i", PVI) }), + } + local layer0: { WNode } = { N("Version", "I", { 100 }) } + if hasN then + table.insert(ch, N("LayerElementNormal", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { "ByVertice" }), + N("ReferenceInformationType", "S", { "Direct" }), + N("Normals", "", { arr("d", NRM) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) })) + end + local extraLayers: { WNode } = {} + local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {} + for k = 1, nuv do + table.insert(ch, N("LayerElementUV", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("UV", "", { arr("d", UV[k]) }), + N("UVIndex", "", { arr("i", UVI[k]) }), + })) + local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) }) + if k == 1 then + table.insert(layer0, le) + else + table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le })) + end + end + for k = 1, ncol do + table.insert(ch, N("LayerElementColor", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Colors", "", { arr("d", COL[k]) }), + N("ColorIndex", "", { arr("i", COLI[k]) }), + })) + if k == 1 then + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) })) + end + end + local anyMat = false + for _, m in slots do + if m ~= 0 and matIds[m] then + anyMat = true + end + end + if anyMat then + local allSame = #slots == 1 + table.insert(ch, N("LayerElementMaterial", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) })) + end + table.insert(ch, N("Layer", "I", { 0 }, layer0)) + for _, l in extraLayers do + table.insert(ch, l) + end + add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch)) + geoIds[mi] = gid + geoSlots[mi] = if anyMat then slots else {} + geoVerts[mi] = layout + geoCount[mi] = offset + -- morph targets + local prims = mesh.primitives + local ntargets = 0 + for _, l in layout do + ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0) + end + if ntargets > 0 then + local bsid = id() + add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) })) + OO(bsid, gid) + local names = mesh.extras and (mesh.extras :: any).targetNames or {} + for t = 1, ntargets do + local IDX, DV, DN = {}, {}, {} + local anyN = false + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + if tg and tg.NORMAL then + anyN = true + end + end + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + local TP: ((i: number, c: number) -> number)? = tg and accessorReader(tg.POSITION) + local TN: ((i: number, c: number) -> number)? = tg and accessorReader(tg.NORMAL) + if TP then + for v = 0, l.prim.attributes.POSITION.count - 1 do + local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) + local nx, ny, nz = 0, 0, 0 + if TN then + nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2) + end + if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then + table.insert(IDX, l.offset + v) + table.insert(DV, x) + table.insert(DV, y) + table.insert(DV, z) + if anyN then + table.insert(DN, nx) + table.insert(DN, ny) + table.insert(DN, nz) + end + end + end + end + end + local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t) + local chid, shid = id(), id() + local w = mesh.weights and mesh.weights[t] or 0 + add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, { + N("Version", "I", { 100 }), + N("DeformPercent", "D", { w * 100 }), + N("FullWeights", "", { arr("d", { 100 }) }), + N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }), + })) + local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) } + if anyN then + table.insert(shch, N("Normals", "", { arr("d", DN) })) + end + add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch)) + OO(chid, bsid) + OO(shid, chid) + local gc: any = geoChannels + gc[mi] = gc[mi] or {} + gc[mi][t] = chid + end + end + local _ = prims + return gid + end + + local poseNodes: { WNode } = {} + local posed: { [number]: boolean } = {} + local function pose(mid: number, m: Mat4.M4) + if posed[mid] then + return + end + posed[mid] = true + table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) })) + end + local skinned: { [string]: boolean } = {} + for i, nd in nodes do + local mid = modelIds[i] + if nd.mesh and mid then + local gid = geometry(nd.mesh) + if gid then + OO(gid, mid) + for _, m in geoSlots[nd.mesh] do + local pm = matIds[m] + if pm then + OO(pm, mid) + end + end + -- skin: one Skin per (geometry, skin) + local skin = nd.skin and scene.skins[nd.skin] + local key = tostring(gid) .. ":" .. tostring(nd.skin) + if skin and not skinned[key] then + skinned[key] = true + local sid = id() + add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) })) + OO(sid, gid) + local meshWorld = world(i) + pose(mid, meshWorld) + local ibm = accessorReader(skin.inverseBindMatrices) + -- per joint: control points and weights + local perJoint: { { idx: { number }, w: { number } } } = {} + for j in skin.joints do + perJoint[j] = { idx = {}, w = {} } + end + for _, l in geoVerts[nd.mesh] do + local J = accessorReader(l.prim.attributes.JOINTS_0) + local W = accessorReader(l.prim.attributes.WEIGHTS_0) + if J and W then + for v = 0, l.prim.attributes.POSITION.count - 1 do + for q = 0, 3 do + local j, w = J(v, q), W(v, q) + local pj = perJoint[j + 1] + if w > 0 and pj then + table.insert(pj.idx, l.offset + v) + table.insert(pj.w, w) + end + end + end + end + end + for j, ji in skin.joints do + local jm = modelIds[ji] + if jm then + local IB = Mat4.identity() + if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then + for k = 1, 16 do + IB[k] = ibm(j - 1, k - 1) + end + end + local inv = Mat4.inverse(IB) or Mat4.identity() + local link = Mat4.mul(meshWorld, inv) + local cid = id() + add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { + N("Version", "I", { 100 }), + N("UserData", "SS", { "", "" }), + N("Indexes", "", { arr("i", perJoint[j].idx) }), + N("Weights", "", { arr("d", perJoint[j].w) }), + N("Transform", "", { arr("d", meshWorld) }), + N("TransformLink", "", { arr("d", link) }), + })) + OO(cid, sid) + OO(jm, cid) + pose(jm, link) + end + end + end + end + end + end + if #poseNodes > 0 then + local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) } + for _, pn in poseNodes do + table.insert(pch, pn) + end + add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch)) + end + + -- ------------------------------------------------------------------------------------------ animations + local tmin, tmax = math.huge, -math.huge + local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean) + local cnid = id() + local p = {} + for k, lab in labels do + table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0)) + end + add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) })) + OO(cnid, layer) + OP(cnid, target, prop) + local ticks = table.create(#times, 0) + for k, t in times do + ticks[k] = math.floor(t * TICKS + 0.5) + end + for k, lab in labels do + local cid = id() + local df = buffer.create(32) + buffer.writeu32(df, 8, 218434821) + local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) } + buffer.writef64(dfa.data, 16, buffer.readf32(df, 8)) + add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, { + N("Default", "D", { comps[k][1] or 0 }), + N("KeyVer", "I", { 4009 }), + N("KeyTime", "", { arr("l", ticks) }), + N("KeyValueFloat", "", { arr("f", comps[k]) }), + N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }), + N("KeyAttrDataFloat", "", { dfa }), + N("KeyAttrRefCount", "", { arr("i", { #times }) }), + })) + OP(cid, cnid, "d|" .. lab) + end + end + local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } + for ai, anim in scene.animations or {} do + local stid, lid = id(), id() + local astart: number, astop: number = math.huge, -math.huge + local layerNodes = {} + for _, ch in anim.channels do + local mid = modelIds[ch.node] + local IN = accessorReader(ch.input) + local OUT = accessorReader(ch.output) + local spec = PATH[ch.path] + if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then + local n = ch.input.count + local times = table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = IN(k, 0) + astart, astop = math.min(astart, times[k + 1]), (math.max(astop, times[k + 1])) + end + local cubic = ch.interpolation == "CUBICSPLINE" + local step = ch.interpolation == "STEP" + if spec then + local comps = spec[3] + local function val(k: number, c: number): number + local e = if cubic then k * 3 + 1 else k + if e >= ch.output.count then + return 0 + end + return OUT(e, c) + end + local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0) + local prev: { number }? = nil + for k = 0, n - 1 do + local v + if comps == 4 then + local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) } + local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if ql > 0 then + q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } + else + q = { 0, 0, 0, 1 } + end + v = Mat4.eulerXYZ(q) + if prev then + for a = 1, 3 do + while v[a] - prev[a] > 180 do + v[a] -= 360 + end + while v[a] - prev[a] < -180 do + v[a] += 360 + end + end + end + prev = v + else + v = { val(k, 0), val(k, 1), val(k, 2) } + end + X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3] + end + table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) + else + -- weights: one DeformPercent curve per blend shape channel of the node's mesh + local nd = nodes[ch.node] + local gc: any = geoChannels + local chans = nd.mesh and gc[nd.mesh] + if chans then + local nt = #chans + for t = 1, nt do + local vals = table.create(n, 0) + for k = 0, n - 1 do + local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1) + vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0 + end + table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step }) + end + end + end + end + end + if astart > astop then + astart, astop = 0, 0 + end + tmin, tmax = math.min(tmin, astart), math.max(tmax, astop) + add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, { + N("Properties70", "", {}, { + Ptime("LocalStart", math.floor(astart * TICKS + 0.5)), + Ptime("LocalStop", math.floor(astop * TICKS + 0.5)), + Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)), + Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)), + }), + })) + add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) })) + OO(lid, stid) + for _, ln in layerNodes do + curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8]) + end + end + if tmin > tmax then + tmin, tmax = 0, 0 + end + + -- ------------------------------------------------------------------------------------------ document + local meta: { [string]: any } = scene.meta or {} + local src: { [string]: any } = type(meta.source) == "table" and meta.source or {} + local up = if meta.up == "z" then 2 else 1 + local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 + if up == 2 then + front, frontSign = 1, -1 + end + if src.format == "fbx" and src.upAxis == up then + upSign = src.upAxisSign or upSign + front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign + coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign + end + local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1 + local creator = opts and opts.creator or "rosetta" + local defs: { WNode } = { N("Version", "I", { 100 }) } + local total = 1 + local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" } + for _, c in CLASSES do + total += counts[c] or 0 + end + table.insert(defs, N("Count", "I", { total })) + table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) })) + for _, c in CLASSES do + if counts[c] then + table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) })) + end + end + local docId = id() + local root: WNode = { name = "", props = {}, children = { + N("FBXHeaderExtension", "", {}, { + N("FBXHeaderVersion", "I", { 1003 }), + N("FBXVersion", "I", { opts and opts.version or 7400 }), + N("CreationTimeStamp", "", {}, { + N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }), + N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }), + }), + N("Creator", "S", { creator }), + }), + N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }), + N("CreationTime", "S", { "1970-01-01 10:00:00:000" }), + N("Creator", "S", { creator }), + N("GlobalSettings", "", {}, { + N("Version", "I", { 1000 }), + N("Properties70", "", {}, { + Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign), + Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign), + Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale), + P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0), + P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"), + Penum("TimeMode", 6), + Penum("TimeProtocol", 2), + Penum("SnapOnFrameMode", 0), + Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)), + Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)), + Pdouble("CustomFrameRate", -1), + }), + }), + N("Documents", "", {}, { + N("Count", "I", { 1 }), + N("Document", "LSS", { docId, "Scene", "Scene" }, { + N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }), + N("RootNode", "L", { 0 }), + }), + }), + N("References", "", {}, {}), + N("Definitions", "", {}, defs), + N("Objects", "", {}, objects), + N("Connections", "", {}, conns), + N("Takes", "", {}, { N("Current", "S", { "" }) }), + } } + local _ = Err + return root, nil +end + +return Write +end +__FILES["model/fbx/Xform"] = function() + +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model +-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The +-- matrix / quaternion arithmetic is codecs/model/Mat4. +local Mat4 = __include("codecs/model/Mat4") + +local Xform = {} + +-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ) +local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } +function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 + return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") +end + +-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers +type Props = { + T: { number }, R: { number }, S: { number }, + Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number }, + order: number, +} +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +function Xform.localMatrix(p: Props): Mat4.M4 + local m = Mat4.translation(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) + if not isZero(p.Rpre) then + m = Mat4.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + end + m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + if not isZero(p.Rpost) then + -- the inverse of a rotation is its transpose + m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) + end + m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) + m = Mat4.mul(m, Mat4.scaling(p.S[1], p.S[2], p.S[3])) + if not isZero(p.Sp) then + m = Mat4.mul(m, Mat4.translation(-p.Sp[1], -p.Sp[2], -p.Sp[3])) + end + return m +end + +return Xform +end +__FILES["model/gltf"] = function() + +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and +-- binary (.glb). New code. +-- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every +-- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR +-- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, +-- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, +-- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, +-- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, +-- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a +-- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. +-- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). +-- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes .bin and the +-- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). +-- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the +-- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back +-- uncompressed (the extension is dropped). +-- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels +-- (skipped and counted in the animation's extras). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Read = __include("model/gltf/Read") +local Write = __include("model/gltf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Gltf = { + name = "gltf", + category = "model", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths + files: { [string]: any }?, -- or: the files by uri + maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30) +} +type EncodeOptions = { + binary: boolean?, -- write GLB (default: when opts.format is "glb") + format: string?, -- "glb" -> binary (set by the api from the destination's extension) + external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs) + files: { [string]: any }?, -- receives .bin and images with external = true + name: string?, -- the destination's file name (names the external files) + embedImages: boolean?, -- default true (false with external = true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local GLB_MAGIC = 0x46546C67 -- "glTF" +local CHUNK_JSON = 0x4E4F534A +local CHUNK_BIN = 0x004E4942 + +-- ------------------------------------------------------------------------------------------------ sniff +function Gltf.sniff(r: Bytes.Reader): number + if r:peek(4) == "glTF" then + return 1 + end + local head = r:peek(1024) + local s = Sniff.dropBom(head) + if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then + return 0.9 + end + if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[decoded] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +-- the JSON text and BIN chunk of a GLB +local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?) + local magic, version, length = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, nil, r.err + end + if magic ~= GLB_MAGIC then + return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic") + end + if version ~= 2 then + return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version) + end + if length > r:size() then + return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8) + end + local json: string? = nil + local bin: buffer? = nil + while r:tell() + 8 <= length do + local clen, ctype = r:u32le(), r:u32le() + if clen > length - r:tell() then + return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8) + end + if ctype == CHUNK_JSON and json == nil then + json = r:string(clen) + elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then + bin = r:bytes(clen) + else + r:skip(clen) + end + if r.err then + return nil, nil, r.err + end + end + if not json then + return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk") + end + return json, bin, nil +end + +function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local binary = r:peek(4) == "glTF" + local text: string?, bin: buffer? + if binary then + local t, b, err = glb(r) + if not t then + return nil, err + end + text, bin = t, b + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, jerr = Json.decode(text :: string) + if doc == nil then + return nil, jerr + end + local scene, err = Read.scene(doc, bin, fetcher(opts), opts) + if not scene then + return nil, err + end + scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } + +function Gltf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local binary = opts and (opts.binary or opts.format == "glb") or false + local external = opts and opts.external == true and type(opts.files) == "table" and not binary + local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external + local out, err = Write.build(scene, { binary = binary, embedImages = embedImages }) + if not out then + return nil, err + end + local doc = out.doc + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local files = opts and opts.files + -- images: data: URIs, or files + if doc.images then + local n = 0 + for _, im in doc.images do + if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then + for _, o in out.images do + if o.name == im.uri then + if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then + im.uri = Base64.dataUri(o.data, o.mime or "image/png") + else + n += 1 + local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png") + files[fname] = o.data + im.uri = fname + end + break + end + end + elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then + for _, o in out.images do + if o.name == im.uri then + files[im.uri] = o.data + end + end + end + end + end + local binLen = buffer.len(out.bin) + if binLen > 0 then + local b = Types.object() + b.byteLength = binLen + if not binary then + if external then + local fname = base .. ".bin" + b.uri = fname + local ff: any = files + ff[fname] = out.bin + else + b.uri = Base64.dataUri(out.bin, "application/octet-stream") + end + end + doc.buffers = { b } + end + local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 }) + if not text then + return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr)) + end + if not binary then + return buffer.fromstring(text :: string), nil + end + local jpad = (4 - #(text :: string) % 4) % 4 + local bpad = (4 - binLen % 4) % 4 + local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad) + w:u32le(GLB_MAGIC) + w:u32le(2) + local lenAt = w:tell() + w:u32le(0) + w:u32le(#(text :: string) + jpad) + w:u32le(CHUNK_JSON) + w:string(text :: string) + w:string(string.rep(" ", jpad)) + if binLen > 0 then + w:u32le(binLen + bpad) + w:u32le(CHUNK_BIN) + w:bytes(out.bin) + w:fill(0, bpad) + end + w:setU32le(lenAt, w:tell()) + return w:finish(), nil +end + +return Gltf +end +__FILES["model/gltf/Pack"] = @native function() + + +-- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene +-- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range +-- first (offsets, strides and counts against the buffer lengths); nothing here throws. +local Pack = {} + +local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 + +-- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is +-- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = +-- cols * colBytes bytes each) +@native function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, 0, src, off, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, i * elem, src, off + i * stride, elem) + end + return + end + for i = 0, count - 1 do + local s = off + i * stride + local d = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes) + end + end +end + +-- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) +@native function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, at, src, 0, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, at + i * stride, src, i * elem, elem) + end + return + end + for i = 0, count - 1 do + local d = at + i * stride + local s = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes) + end + end +end + +-- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element +-- idx[k] of dst becomes value k (values packed, elem bytes each) +@native function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean + for k = 0, n - 1 do + local i + if idxSize == 1 then + i = readu8(idx, idxOff + k) + elseif idxSize == 2 then + i = readu16(idx, idxOff + k * 2) + else + i = readu32(idx, idxOff + k * 4) + end + if i >= count then + return false + end + bcopy(dst, i * elem, values, valOff + k * elem, elem) + end + return true +end + +return Pack +end +__FILES["model/gltf/Read"] = function() + +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type +-- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, +-- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the +-- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the +-- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, +-- scenes. glTF extras and unhandled extensions are kept in .extras.gltf = { extras, extensions }. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Pack = __include("model/gltf/Pack") +local Draco = __include("codecs/model/Draco") + +local Read = {} + +local COMPONENT: { [number]: { string } } = { + [5120] = { "i8", "snorm8" }, + [5121] = { "u8", "unorm8" }, + [5122] = { "i16", "snorm16" }, + [5123] = { "u16", "unorm16" }, + [5125] = { "u32", "" }, + [5126] = { "f32", "" }, +} +local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 } +local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } +local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } +local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } +local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } +local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } +-- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +local KNOWN = { + KHR_lights_punctual = true, + KHR_mesh_quantization = true, + KHR_texture_transform = true, + KHR_materials_emissive_strength = true, + KHR_materials_unlit = true, + KHR_materials_clearcoat = true, + KHR_materials_transmission = true, + KHR_materials_volume = true, + KHR_materials_ior = true, + KHR_materials_specular = true, + KHR_materials_sheen = true, + KHR_materials_iridescence = true, + KHR_materials_anisotropy = true, + KHR_materials_dispersion = true, + KHR_materials_diffuse_transmission = true, + KHR_materials_variants = true, + KHR_materials_pbrSpecularGlossiness = true, + KHR_texture_basisu = true, -- the image stays encoded (image/ktx2) + EXT_texture_webp = true, + EXT_texture_avif = true, + KHR_node_visibility = true, + KHR_xmp_json_ld = true, + KHR_draco_mesh_compression = true, +} +Read.KNOWN = KNOWN + +type Fetch = (uri: string) -> buffer? +type View = { buf: buffer, offset: number, length: number, stride: number? } +type Img = { data: buffer?, mime: string?, uri: string?, name: string? } + +local function num(v: any, default: number): number + return if type(v) == "number" then v else default +end +local function int(v: any): number? + return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil +end +local function arr(v: any): { any } + return if type(v) == "table" then v else {} +end +local function str(v: any): string? + return if type(v) == "string" then v else nil +end +local function numbers(v: any, n: number): { number }? + if type(v) ~= "table" or #v ~= n then + return nil + end + for i = 1, n do + if type(v[i]) ~= "number" then + return nil + end + end + return table.move(v, 1, n, 1, {} :: { number }) +end + +-- extras.gltf: the JSON extras and the extensions not turned into Scene fields +local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }? + local extras = obj.extras + local ext: { [string]: any }? = nil + if type(obj.extensions) == "table" then + for k, v in obj.extensions do + if not (handled and handled[k]) then + ext = ext or {} + local e: any = ext + e[k] = v + end + end + end + if extras == nil and ext == nil then + return nil + end + return { gltf = { extras = extras, extensions = ext } } +end + +-- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value +-- by value: normalized integers <-> floats, ints widened or narrowed) +local DRACO_HANDLED = { KHR_draco_mesh_compression = true } +local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } +local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } +local DRACO_WRITE: { [string]: (buffer, number, number) -> () } = { i8 = buffer.writei8, u8 = buffer.writeu8, i16 = buffer.writei16, u16 = buffer.writeu16, i32 = buffer.writei32, u32 = buffer.writeu32, f32 = buffer.writef32 } +local NORM_MAX: { [string]: number } = { u8 = 255, i8 = 127, u16 = 65535, i16 = 32767, u32 = 4294967295, i32 = 2147483647 } +local function dracoAccessor(da: Draco.Attribute, acc: Types.Accessor, n: number): Types.Accessor? + if da.components ~= acc.components or not DRACO_SIZE[da.type] then + return nil + end + local out = Types.Scene.accessor(nil, acc.type, acc.components, n) + out.name = acc.name + if DRACO_SAME[acc.type] == da.type then + out.data = da.data + return out + end + local reader = Types.Scene.reader({ data = da.data, type = da.type :: any, components = da.components, count = n }) + local size = Types.COMPONENT_SIZE[acc.type] + local norm = string.match(acc.type, "^[us]norm") ~= nil + local base: string = DRACO_SAME[acc.type] or acc.type + local wr = DRACO_WRITE[base] + local dmax = NORM_MAX[base] or 1 + if not reader or not wr or not size then + return nil + end + local get = reader :: (number, number) -> number + local w = wr :: (buffer, number, number) -> () + local stride = size * acc.components + local function put(v: number, c: number, x: number) + if base ~= "f32" then + if norm then + x = math.clamp(x, if base == "u8" or base == "u16" then 0 else -1, 1) * dmax + end + x = math.floor(x + 0.5) + end + w(out.data, v * stride + c * size, x) + end + local srcMax = if da.normalized then NORM_MAX[da.type] else nil + for v = 0, n - 1 do + for c = 0, da.components - 1 do + local x = get(v, c) + if srcMax then + x = math.max(x / srcMax, -1) + end + put(v, c, x) + end + end + return out +end + +function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if type(doc) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the JSON is not an object") + end + local asset = doc.asset + if type(asset) ~= "table" or type(asset.version) ~= "string" then + return nil, Err.new(Err.CORRUPT, "no asset.version") + end + if string.sub(asset.version, 1, 1) ~= "2" then + return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)") + end + for _, e in arr(doc.extensionsRequired) do + if type(e) == "string" and not KNOWN[e] then + return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e) + end + end + local scene = Types.Scene.new() + -- buffers + local buffers: { buffer } = {} + local total = 0 + for i, b in arr(doc.buffers) do + if type(b) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1)) + end + local len = int(b.byteLength) + if not len then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength") + end + total += len + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes") + end + local data: buffer? = nil + local uri = str(b.uri) + if uri == nil then + if i == 1 and bin then + data = bin + else + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk") + end + elseif string.sub(uri, 1, 5) == "data:" then + local d, derr = Base64.decodeDataUri(uri) + if not d then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr)) + end + data = d + else + data = fetch(uri) + if not data then + return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)") + end + end + if buffer.len(data :: buffer) < len then + return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength") + end + buffers[i] = data :: buffer + end + -- buffer views -> { buf, offset, length, stride } + local views: { View } = {} + for i, v in arr(doc.bufferViews) do + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1)) + end + local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength) + local b = bi and buffers[bi + 1] + if not b or not off or not len or off + len > buffer.len(b) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range") + end + local stride = v.byteStride + if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride") + end + views[i] = { buf = b, offset = off, length = len, stride = stride } + end + -- accessors + local accessors: { Types.Accessor } = {} + for i, a in arr(doc.accessors) do + local label = "accessor " .. (i - 1) + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad " .. label) + end + local ct, count, typ = a.componentType, int(a.count), a.type + local names = COMPONENT[ct] + local comps = TYPE_COMPONENTS[typ] + if not names or not count or not comps then + return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type") + end + local normalized = a.normalized == true + local tname = if normalized then names[2] else names[1] + if tname == "" then + return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1]) + end + local size = SIZE[ct] + local cols = TYPE_COLUMNS[typ] or 1 + local rows = comps // cols + local colBytes = rows * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + if count * elem > maxBytes then + return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes") + end + local data = buffer.create(count * elem) + local vi = a.bufferView + if vi ~= nil then + local view = int(vi) and views[vi + 1] + if not view then + return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView") + end + local off = int(a.byteOffset or 0) + if not off then + return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset") + end + local stride = view.stride or padded + if stride < padded and count > 1 then + return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element") + end + if count > 0 and off + (count - 1) * stride + padded > view.length then + return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView") + end + if count > 0 then + Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride) + end + end + local sp = a.sparse + if type(sp) == "table" then + local n = int(sp.count) + local si, sv = sp.indices, sp.values + if not n or type(si) ~= "table" or type(sv) ~= "table" then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse") + end + local isz = SIZE[si.componentType] + local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1] + local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0) + local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125 + if not okType or not isz or not iv or not vv or not io or not vo then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values") + end + if io + n * isz > iv.length or vo + n * elem > vv.length then + return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") + end + -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + local vals, valOff = vv.buf, vv.offset + vo + if cols > 1 and colBytes ~= colStride then + vals = buffer.create(n * elem) + Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride) + valOff = 0 + end + if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then + return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range") + end + end + local acc = Types.Scene.accessor(data, tname, comps, count) + if cols > 1 then + acc.matrix = true + end + acc.name = str(a.name) + accessors[i] = acc + end + local function accessor(v: any): Types.Accessor? + local k = int(v) + return if k then accessors[k + 1] else nil + end + -- images (kept encoded), samplers, textures + local images: { Img } = {} + for i, im in arr(doc.images) do + if type(im) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1)) + end + local img: Img = { mime = str(im.mimeType), name = str(im.name) } + if im.bufferView ~= nil then + local view = int(im.bufferView) and views[im.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView") + end + local d = buffer.create(view.length) + buffer.copy(d, 0, view.buf, view.offset, view.length) + img.data = d + elseif type(im.uri) == "string" then + if string.sub(im.uri, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(im.uri) + if d then + img.data = d + img.mime = img.mime or mime + end + else + img.uri = im.uri + img.data = fetch(im.uri) + if not img.mime then + local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "") + img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil + end + end + end + images[i] = img + end + local samplers: { Types.Sampler } = {} + for i, s in arr(doc.samplers) do + if type(s) == "table" then + samplers[i] = { + wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any, + wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any, + filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil, + minFilter = MIN_FILTER[s.minFilter], + } + else + samplers[i] = {} + end + end + local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" } + for i, t in arr(doc.textures) do + if type(t) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1)) + end + local src = t.source + local handled = {} + if type(t.extensions) == "table" then + for _, e in TEX_SOURCE_EXT do + local x = t.extensions[e] + if type(x) == "table" and int(x.source) then + src = x.source + handled[e] = true + break + end + end + end + local img = int(src) and images[src + 1] + local tex: Types.Texture = { name = str(t.name) } + if img then + tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri + tex.name = tex.name or img.name + end + local si = int(t.sampler) + if si and samplers[si + 1] then + tex.sampler = table.clone(samplers[si + 1]) + end + tex.extras = keep(t, handled) + if next(handled) then + -- the fallback image (t.source) and the extension name, for writing the texture back the same way + tex.extras = tex.extras or { gltf = {} } + local g = (tex.extras :: any).gltf + g.sourceExtension = next(handled) + local fb = int(t.source) and images[t.source + 1] + if fb then + g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri } + end + end + table.insert(scene.textures, tex) + end + -- materials + local function texRef(info: any): Types.TextureRef? + if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then + return nil + end + local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil } + local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform + if type(tt) == "table" then + r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) } + end + return r + end + -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + local function convertExt(v: any): any + if type(v) ~= "table" then + return v + end + local out = if Types.isObject(v) or next(v) == nil then Types.object() else {} + for k, x in v do + if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then + out[k] = texRef(x) + else + out[k] = convertExt(x) + end + end + return out + end + for i, m in arr(doc.materials) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1)) + end + local mat = Types.Scene.material(str(m.name)) + local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {} + mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 } + mat.baseColorTexture = texRef(pbr.baseColorTexture) + mat.metallic = num(pbr.metallicFactor, 1) + mat.roughness = num(pbr.roughnessFactor, 1) + mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture) + mat.normalTexture = texRef(m.normalTexture) + mat.occlusionTexture = texRef(m.occlusionTexture) + mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 } + mat.emissiveTexture = texRef(m.emissiveTexture) + mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque" + mat.alphaCutoff = num(m.alphaCutoff, 0.5) + mat.doubleSided = m.doubleSided == true + if type(m.extensions) == "table" then + local ext = {} + for k, v in m.extensions do + ext[k] = convertExt(v) + end + mat.extensions = ext + end + local kept = keep(m, mat.extensions and (mat.extensions :: any) or {}) + local pk = keep(pbr, nil) + if pk then + kept = kept or { gltf = {} } + local kk: any = kept + kk.gltf.pbr = pk.gltf + end + mat.extras = kept + table.insert(scene.materials, mat) + end + -- meshes + for i, m in arr(doc.meshes) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) + end + local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) } + for k, p in arr(m.primitives) do + if type(p) ~= "table" or type(p.attributes) ~= "table" then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1)) + end + local pext = if type(p.extensions) == "table" then p.extensions else nil + if pext and pext.EXT_meshopt_compression then + return nil, Err.new(Err.UNSUPPORTED, "meshopt compressed primitives (EXT_meshopt_compression)") + end + -- KHR_draco_mesh_compression: the attributes it lists and the indices come from the Draco data + local dext = pext and pext.KHR_draco_mesh_compression + local draco: Draco.Geometry? = nil + local dmap: { [string]: number } = {} + if dext ~= nil then + local view = type(dext) == "table" and int(dext.bufferView) and views[dext.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: draco: bad bufferView", i - 1, k - 1)) + end + local g, derr = Draco.decode(view.buf, view.offset, view.length, { maxPoints = maxBytes // 4, maxFaces = maxBytes // 12 }) + if not g then + local e = derr :: Err.Err + return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - 1, e.message)) + end + draco = g + for name, id in (if type(dext.attributes) == "table" then dext.attributes else {}) do + if type(name) == "string" and int(id) then + dmap[name] = id + end + end + end + local attrs: { [string]: Types.Accessor } = {} + local count = -1 + for name, ai in p.attributes do + local a = accessor(ai) + if a and draco and dmap[name] then + local da = Draco.attribute(draco, dmap[name]) + a = if da then dracoAccessor(da, a, draco.numPoints) else nil + end + if not a then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) + end + if count >= 0 and a.count ~= count then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1)) + end + count = a.count + attrs[name] = a + end + local mode = MODES[if p.mode == nil then 4 else p.mode] + if not mode then + return nil, Err.new(Err.CORRUPT, "bad primitive mode") + end + local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil } + if draco then + if draco.kind == "mesh" then + prim.indices = Types.Scene.accessor(draco.indices, "u32", 1, draco.numFaces * 3) + prim.mode = "triangles" + else + prim.mode = "points" + end + elseif p.indices ~= nil then + local ind = accessor(p.indices) + if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then + return nil, Err.new(Err.CORRUPT, "bad indices accessor") + end + -- indices must reference existing vertices + local get = Types.Scene.reader(ind :: Types.Accessor) :: any + for q = 0, ind.count - 1 do + if get(q, 0) >= count then + return nil, Err.new(Err.CORRUPT, "index out of range") + end + end + prim.indices = ind :: Types.Accessor + end + if type(p.targets) == "table" then + local targets = {} + for ti, t in p.targets do + local tt = {} + for name, ai in (if type(t) == "table" then t else {}) do + local a = accessor(ai) + if not a or a.count ~= count then + return nil, Err.new(Err.CORRUPT, "bad morph target accessor") + end + tt[name] = a + end + targets[ti] = tt + end + prim.targets = targets + end + prim.extras = keep(p, DRACO_HANDLED) + table.insert(mesh.primitives, prim) + end + table.insert(scene.meshes, mesh) + end + -- cameras, lights + for _, c in arr(doc.cameras) do + if type(c) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad camera") + end + if c.type == "orthographic" and type(c.orthographic) == "table" then + local o = c.orthographic + table.insert(scene.cameras, { name = str(c.name), type = "orthographic" :: "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) } :: Types.Camera) + else + local p = if type(c.perspective) == "table" then c.perspective else {} + table.insert(scene.cameras, { name = str(c.name), type = "perspective" :: "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil } :: Types.Camera) + end + end + local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual + for _, l in arr(lp and lp.lights) do + if type(l) == "table" then + local spot = if type(l.spot) == "table" then l.spot else {} + table.insert(scene.lights, { + name = str(l.name), + type = if l.type == "spot" or l.type == "point" then l.type else "directional", + color = numbers(l.color, 3) or { 1, 1, 1 }, + intensity = num(l.intensity, 1), + range = if type(l.range) == "number" then l.range else nil, + innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil, + outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil, + }) + end + end + -- nodes + local nodes = arr(doc.nodes) + for i, n in nodes do + if type(n) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1)) + end + local node: Types.Node = { name = str(n.name), children = {} } + for _, c in arr(n.children) do + if not int(c) or c >= #nodes then + return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child") + end + table.insert(node.children, c + 1) + end + if int(n.mesh) and n.mesh < #scene.meshes then + node.mesh = n.mesh + 1 + end + if int(n.camera) and n.camera < #scene.cameras then + node.camera = n.camera + 1 + end + if int(n.skin) and n.skin < #arr(doc.skins) then + node.skin = n.skin + 1 + end + node.matrix = numbers(n.matrix, 16) + node.translation = numbers(n.translation, 3) + node.rotation = numbers(n.rotation, 4) + node.scale = numbers(n.scale, 3) + node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil + local handled = {} + local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual + if type(le) == "table" and int(le.light) and le.light < #scene.lights then + node.light = le.light + 1 + handled.KHR_lights_punctual = true + end + node.extras = keep(n, handled) + scene.nodes[i] = node + end + -- a node may have one parent only, and no cycles + local parent: { [number]: number } = {} + for i, node in scene.nodes do + for _, c in node.children do + if parent[c] or c == i then + return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child") + end + parent[c] = i + end + end + for i in scene.nodes do + local seen, p = 0, parent[i] + while p do + seen += 1 + if seen > #scene.nodes then + return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle") + end + p = parent[p] + end + end + -- skins + for _, s in arr(doc.skins) do + if type(s) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad skin") + end + local joints = {} + for _, j in arr(s.joints) do + if not int(j) or j >= #scene.nodes then + return nil, Err.new(Err.CORRUPT, "skin: bad joint") + end + table.insert(joints, j + 1) + end + table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil }) + end + -- animations + for _, a in arr(doc.animations) do + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad animation") + end + local anim: Types.Animation = { name = str(a.name), channels = {} } + local samplersA = arr(a.samplers) + local skipped = {} + for _, c in arr(a.channels) do + local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1] + local target = type(c) == "table" and c.target + if not s or type(target) ~= "table" then + return nil, Err.new(Err.CORRUPT, "animation: bad channel") + end + local input, output = accessor(s.input), accessor(s.output) + if not input or not output then + return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors") + end + local path = target.path + if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then + table.insert(anim.channels, { + node = target.node + 1, + path = path, + input = input, + output = output, + interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR", + }) + else + table.insert(skipped, c) -- KHR_animation_pointer and friends + end + end + if #skipped > 0 then + local aa: any = anim + aa.extras = { gltf = { skippedChannels = #skipped } } + end + table.insert(scene.animations, anim) + end + -- scenes + local scenes = arr(doc.scenes) + local list = {} + for _, s in scenes do + local roots = {} + for _, n in arr(type(s) == "table" and s.nodes) do + if int(n) and n < #scene.nodes and not parent[n + 1] then + table.insert(roots, n + 1) + end + end + table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil }) + end + local which = int(doc.scene) or 0 + if list[which + 1] then + scene.roots = list[which + 1].nodes + elseif #list == 0 then + for i in scene.nodes do + if not parent[i] then + table.insert(scene.roots, i) + end + end + end + -- root extensions other than the lights, asset info + local rootExt = nil + if type(doc.extensions) == "table" then + for k, v in doc.extensions do + if k ~= "KHR_lights_punctual" then + rootExt = rootExt or {} + rootExt[k] = v + end + end + end + scene.meta.up = "y" + scene.meta.unit = 1 + scene.meta.gltf = { + asset = asset, + scenes = list, + scene = if doc.scene ~= nil then which + 1 else nil, + extensionsUsed = doc.extensionsUsed, + extensionsRequired = doc.extensionsRequired, + extensions = rootExt, + extras = doc.extras, + } + return scene, nil +end + +return Read +end +__FILES["model/gltf/Write"] = function() + +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex +-- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), +-- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), +-- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, +-- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their +-- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first +-- for concave faces). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pack = __include("model/gltf/Pack") + +local Write = {} + +local object = Types.object +local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 } +local SIZE = Types.COMPONENT_SIZE +local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true } +local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 } +local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 } +local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 } +-- attribute types the core spec allows (others need KHR_mesh_quantization) +local CORE = { + POSITION = { f32 = true }, + NORMAL = { f32 = true }, + TANGENT = { f32 = true }, + TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true }, + COLOR = { f32 = true, unorm8 = true, unorm16 = true }, + JOINTS = { u8 = true, u16 = true }, + WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true }, +} + +type Options = { embedImages: boolean?, binary: boolean? } +type Out = { doc: any, bin: buffer, images: { { data: buffer, mime: string?, name: string } } } + +local function convert(acc: Types.Accessor, to: string): Types.Accessor + local get = Types.Scene.reader(acc) :: (number, number) -> number + local out = Types.Scene.accessor(nil, to, acc.components, acc.count) + local w = if to == "f32" then buffer.writef32 else buffer.writeu32 + local size = SIZE[to] + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + local v = get(i, c) + if to == "u32" then + v = math.clamp(math.floor(v), 0, 4294967295) + end + w(out.data, (i * acc.components + c) * size, v) + end + end + out.matrix = acc.matrix + out.name = acc.name + return out +end + +local function checkAcc(acc: any, label: string): Err.Err? + if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then + return Err.new(Err.ARG, label .. ": not an accessor") + end + if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then + return Err.new(Err.ARG, label .. ": data is smaller than count x components") + end + return nil +end + +function Write.build(scene: Types.Scene, opts: Options?): (Out?, Err.Err?) + local binary = opts and opts.binary or false + local embedImages = not (opts and opts.embedImages == false) + local doc: { [string]: any } = object() + local used: { [string]: boolean } = {} + local required: { [string]: boolean } = {} + local bin = Bytes.writer(65536) + local views: { any } = {} + local accessors: { any } = {} + local accIndex: { [any]: number } = {} + local failure: Err.Err? = nil + + local function view(data: buffer, length: number, target: number?, stride: number?): number + local pad = (4 - bin:tell() % 4) % 4 + bin:fill(0, pad) + local v = object() + v.buffer = 0 + v.byteOffset = bin:tell() + v.byteLength = length + v.target = target + v.byteStride = stride + bin:bytes(data, 0, length) + table.insert(views, v) + return #views - 1 + end + + -- accessor(acc, usage, attribute?) -> the glTF index (0-based) + local function accessor(acc: Types.Accessor, usage: string, attribute: string?): number + local known = accIndex[acc] + if known then + return known + end + local err = checkAcc(acc, attribute or usage) + if err then + failure = failure or err + return 0 + end + local a = acc + if usage == "index" then + if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then + a = convert(a, "u32") + end + elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then + a = convert(a, "f32") + end + if attribute then + local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute + local core = CORE[kind] + if core and not core[a.type] then + used.KHR_mesh_quantization = true + required.KHR_mesh_quantization = true + end + end + local size = SIZE[a.type] + local comps = a.components + local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16) + local cols = if isMat then math.sqrt(comps) else 1 + local colBytes = (comps // cols) * size + local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes + local elem = comps * size + local padded = cols * colStride + local stride = padded + local byteStride: number? = nil + if usage == "vertex" and padded % 4 ~= 0 then + stride = (padded + 3) // 4 * 4 + byteStride = stride + end + local data = a.data + local length = a.count * stride + if stride ~= elem then + data = buffer.create(length) + Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride) + end + local g = object() + g.bufferView = view(data, length, if usage == "vertex" then 34962 elseif usage == "index" then 34963 else nil, byteStride) + g.componentType = CT[a.type] + g.normalized = if NORMALIZED[a.type] then true else nil + g.count = a.count + g.type = if isMat then ({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] else ({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps] + g.name = acc.name + if not g.type then + failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type") + return 0 + end + if attribute == "POSITION" or usage == "input" then + -- min / max of the raw component values + local raw = Types.Scene.accessor(a.data, if a.type == "unorm8" then "u8" elseif a.type == "unorm16" then "u16" elseif a.type == "snorm8" then "i8" elseif a.type == "snorm16" then "i16" else a.type, comps, a.count) + local get = Types.Scene.reader(raw) :: (number, number) -> number + local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) + for i = 0, a.count - 1 do + for c = 1, comps do + local v = get(i, c - 1) + if v < lo[c] then + lo[c] = v + end + if v > hi[c] then + hi[c] = v + end + end + end + if a.count > 0 then + g.min, g.max = lo, hi + end + end + table.insert(accessors, g) + local index = #accessors - 1 + accIndex[acc] = index + return index + end + + -- extras.gltf -> extras / extensions fields of a glTF object + local function restore(g: any, extras: any) + local saved = type(extras) == "table" and extras.gltf + if type(saved) ~= "table" then + return + end + if saved.extras ~= nil then + g.extras = saved.extras + end + if type(saved.extensions) == "table" then + g.extensions = g.extensions or object() + for k, v in saved.extensions do + if g.extensions[k] == nil then + g.extensions[k] = v + used[k] = true + end + end + end + end + + -- images, samplers, textures + local images: { any } = {} + local imageOut: { { data: buffer, mime: string?, name: string } } = {} + local imageIndex: { [any]: number } = {} + local function image(data: buffer?, mime: string?, uri: string?, name: string?): number? + local key: any = data or uri + if key == nil then + return nil + end + if imageIndex[key] then + return imageIndex[key] + end + local im = object() + im.name = name + if data then + if binary then + im.bufferView = view(data, buffer.len(data), nil, nil) + im.mimeType = mime or "image/png" + elseif embedImages then + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + else + im.uri = uri or ("\0file" .. (#images + 1)) + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + end + else + im.uri = uri + im.mimeType = mime + end + table.insert(images, im) + imageIndex[key] = #images - 1 + return #images - 1 + end + local samplers: { any } = {} + local samplerIndex: { [string]: number } = {} + local function sampler(s: Types.Sampler?): number? + if type(s) ~= "table" then + return nil + end + local g = object() + g.wrapS = if s.wrapS then WRAP[s.wrapS] else nil + g.wrapT = if s.wrapT then WRAP[s.wrapT] else nil + g.magFilter = if s.filter == "nearest" then 9728 elseif s.filter == "linear" then 9729 else nil + g.minFilter = if s.minFilter then MIN_FILTER[s.minFilter] else nil + local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter)) + if samplerIndex[key] == nil then + table.insert(samplers, g) + samplerIndex[key] = #samplers - 1 + end + return samplerIndex[key] + end + local textures: { any } = {} + for i, t in scene.textures or {} do + if type(t) ~= "table" then + return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table") + end + local g = object() + g.name = t.name + g.sampler = sampler(t.sampler) + local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil + local srcExt = saved and saved.sourceExtension + local img = image(t.data, t.mime, t.uri, t.name) + if srcExt and img then + g.extensions = object() + local e = object() + e.source = img + g.extensions[srcExt] = e + used[srcExt] = true + local fb = saved.fallback + if type(fb) == "table" then + g.source = image(fb.data, fb.mime, fb.uri, nil) + end + if g.source == nil then + required[srcExt] = true + end + else + g.source = img + end + restore(g, t.extras) + table.insert(textures, g) + end + local function texInfo(r: any, kind: string?): any + if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then + return nil + end + local g = object() + g.index = r.texture - 1 + if r.texCoord and r.texCoord ~= 0 then + g.texCoord = r.texCoord + end + if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then + g.scale = r.scale + end + if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then + g.strength = r.strength + end + if type(r.transform) == "table" then + local tt = object() + tt.offset = r.transform.offset + tt.scale = r.transform.scale + tt.rotation = r.transform.rotation + tt.texCoord = r.transform.texCoord + g.extensions = object() + g.extensions.KHR_texture_transform = tt + used.KHR_texture_transform = true + end + return g + end + local function extValue(v: any, key: string?): any + if type(v) ~= "table" then + return v + end + if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then + return texInfo(v, if key == "normalTexture" or key == "clearcoatNormalTexture" then "normal" else nil) + end + local out = if Types.isObject(v) or next(v) == nil then object() else {} + for k, x in v do + out[k] = extValue(x, if type(k) == "string" then k else nil) + end + return out + end + -- materials + local materials: { any } = {} + for i, m in scene.materials or {} do + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "material " .. i .. ": not a table") + end + local g = object() + g.name = m.name + local pbr = object() + local bc = m.baseColor or { 1, 1, 1, 1 } + if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then + pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 } + end + pbr.baseColorTexture = texInfo(m.baseColorTexture) + if m.metallic ~= nil and m.metallic ~= 1 then + pbr.metallicFactor = m.metallic + end + if m.roughness ~= nil and m.roughness ~= 1 then + pbr.roughnessFactor = m.roughness + end + pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture) + local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil + if saved and saved.pbr then + restore(pbr, { gltf = saved.pbr }) + end + g.pbrMetallicRoughness = pbr + g.normalTexture = texInfo(m.normalTexture, "normal") + g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion") + g.emissiveTexture = texInfo(m.emissiveTexture) + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then + g.emissiveFactor = { em[1], em[2], em[3] } + end + if m.alphaMode == "mask" then + g.alphaMode = "MASK" + if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then + g.alphaCutoff = m.alphaCutoff + end + elseif m.alphaMode == "blend" then + g.alphaMode = "BLEND" + end + if m.doubleSided then + g.doubleSided = true + end + if type(m.extensions) == "table" then + g.extensions = object() + for k, v in m.extensions do + g.extensions[k] = extValue(v, nil) + used[k] = true + end + end + restore(g, m.extras) + table.insert(materials, g) + end + -- meshes + local meshes: { any } = {} + for i, mesh in scene.meshes or {} do + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives") + end + local g = object() + g.name = mesh.name + g.primitives = {} + for k, p in mesh.primitives do + if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then + return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k)) + end + local gp = object() + gp.attributes = object() + local names: { string } = {} + for name in p.attributes do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + gp.attributes[name] = accessor(p.attributes[name], "vertex", name) + end + local mode = p.mode or "triangles" + local indices = p.indices + if mode == "polygons" then + -- fan-triangulate + local faces = p.faces + local getf = faces and Types.Scene.reader(faces) + local n = if indices then indices.count else p.attributes.POSITION.count + local geti = if indices then Types.Scene.reader(indices) else nil + if not faces or not getf or (indices and not geti) then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local list = {} + local at = 0 + for f = 0, faces.count - 1 do + local c = getf(f, 0) + if at + c > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + for a = 1, c - 2 do + for _, j in { at, at + a, at + a + 1 } do + table.insert(list, if geti then geti(j, 0) else j) + end + end + at += c + end + local ib = buffer.create(#list * 4) + for q, v in list do + buffer.writeu32(ib, (q - 1) * 4, v) + end + indices = Types.Scene.accessor(ib, "u32", 1, #list) + mode = "triangles" + end + if MODES[mode] == nil then + return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode)) + end + if indices then + gp.indices = accessor(indices, "index", nil) + end + if mode ~= "triangles" then + gp.mode = MODES[mode] + end + if type(p.material) == "number" and materials[p.material] then + gp.material = p.material - 1 + end + if type(p.targets) == "table" and #p.targets > 0 then + gp.targets = {} + for _, t in p.targets do + local gt = object() + local tn = {} + for name in t do + table.insert(tn, name) + end + table.sort(tn) + for _, name in tn do + gt[name] = accessor(t[name], "vertex", nil) + end + table.insert(gp.targets, gt) + end + end + restore(gp, p.extras) + table.insert(g.primitives, gp) + end + g.weights = mesh.weights + restore(g, mesh.extras) + table.insert(meshes, g) + end + -- cameras, lights + local cameras: { any } = {} + for _, c in scene.cameras or {} do + local g = object() + g.name = c.name + g.type = c.type + local p = object() + if c.type == "orthographic" then + p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100 + g.orthographic = p + else + g.type = "perspective" + p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar + g.perspective = p + end + table.insert(cameras, g) + end + local lights: { any } = {} + for _, l in scene.lights or {} do + local g = object() + g.name = l.name + g.type = l.type + if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then + g.color = { l.color[1], l.color[2], l.color[3] } + end + if l.intensity ~= nil and l.intensity ~= 1 then + g.intensity = l.intensity + end + if l.type ~= "directional" then + g.range = l.range + end + if l.type == "spot" then + local s = object() + s.innerConeAngle = if l.innerCone and l.innerCone ~= 0 then l.innerCone else nil + s.outerConeAngle = if l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 then l.outerCone else nil + g.spot = s + end + table.insert(lights, g) + end + -- nodes + local nodes: { any } = {} + local nodeCount = #(scene.nodes or {}) + for i, n in scene.nodes or {} do + if type(n) ~= "table" then + return nil, Err.new(Err.ARG, "node " .. i .. ": not a table") + end + local g = object() + g.name = n.name + if n.children and #n.children > 0 then + g.children = {} + for _, c in n.children do + if type(c) ~= "number" or c < 1 or c > nodeCount then + return nil, Err.new(Err.ARG, "node " .. i .. ": bad child") + end + table.insert(g.children, c - 1) + end + end + if n.mesh and meshes[n.mesh] then + g.mesh = n.mesh - 1 + end + if n.camera and cameras[n.camera] then + g.camera = n.camera - 1 + end + if n.skin and scene.skins[n.skin] then + g.skin = n.skin - 1 + end + if n.matrix then + local ident = true + for k = 1, 16 do + if n.matrix[k] ~= Types.Scene.IDENTITY[k] then + ident = false + end + end + if not ident then + g.matrix = n.matrix + end + else + g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale + end + g.weights = n.weights + if n.light and lights[n.light] then + g.extensions = object() + local le = object() + le.light = n.light - 1 + g.extensions.KHR_lights_punctual = le + used.KHR_lights_punctual = true + end + restore(g, n.extras) + table.insert(nodes, g) + end + -- skins + local skins: { any } = {} + for _, s in scene.skins or {} do + local g = object() + g.name = s.name + g.joints = {} + for _, j in s.joints or {} do + table.insert(g.joints, j - 1) + end + if s.inverseBindMatrices then + local ibm = s.inverseBindMatrices + if ibm.matrix == nil and ibm.components == 16 then + ibm.matrix = true + end + g.inverseBindMatrices = accessor(ibm, "other", nil) + end + if s.skeleton then + g.skeleton = s.skeleton - 1 + end + table.insert(skins, g) + end + -- animations + local animations: { any } = {} + for _, a in scene.animations or {} do + local g = object() + g.name = a.name + g.channels, g.samplers = {}, {} + local samplerOf: { [string]: number } = {} + for _, c in a.channels or {} do + local input = accessor(c.input, "input", nil) + local output = accessor(c.output, "other", nil) + local key = input .. "/" .. output .. "/" .. tostring(c.interpolation) + if samplerOf[key] == nil then + local s = object() + s.input, s.output = input, output + if c.interpolation and c.interpolation ~= "LINEAR" then + s.interpolation = c.interpolation + end + table.insert(g.samplers, s) + samplerOf[key] = #g.samplers - 1 + end + local ch = object() + ch.sampler = samplerOf[key] + ch.target = object() + ch.target.node = c.node - 1 + ch.target.path = c.path + table.insert(g.channels, ch) + end + table.insert(animations, g) + end + if failure then + return nil, failure + end + -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + local meta: { [string]: any } = if type(scene.meta) == "table" then scene.meta else {} + local mg = type(meta.gltf) == "table" and meta.gltf or {} + local scenes = {} + if type(mg.scenes) == "table" and #mg.scenes > 0 then + for _, s in mg.scenes do + local g = object() + g.name = s.name + g.nodes = {} + for _, n in s.nodes or {} do + if nodes[n] then + table.insert(g.nodes, n - 1) + end + end + restore(g, s.extras) + table.insert(scenes, g) + end + -- the current roots replace the default scene's list + local which = mg.scene or 1 + if scenes[which] then + scenes[which].nodes = {} + for _, r in scene.roots or {} do + table.insert(scenes[which].nodes, r - 1) + end + end + doc.scene = (mg.scene or 1) - 1 + else + local g = object() + g.nodes = {} + for _, r in scene.roots or {} do + table.insert(g.nodes, r - 1) + end + table.insert(scenes, g) + doc.scene = 0 + end + local asset = object() + asset.version = "2.0" + asset.generator = "rosetta" + if type(mg.asset) == "table" then + asset.copyright = mg.asset.copyright + asset.minVersion = mg.asset.minVersion + asset.extras = mg.asset.extras + end + doc.asset = asset + -- root extensions kept from the source (variants, ...), the lights + if type(mg.extensions) == "table" then + doc.extensions = object() + for k, v in mg.extensions do + doc.extensions[k] = v + used[k] = true + end + end + if #lights > 0 then + doc.extensions = doc.extensions or object() + local lp = object() + lp.lights = lights + doc.extensions.KHR_lights_punctual = lp + used.KHR_lights_punctual = true + end + doc.extras = mg.extras + local function list(t: { [string]: boolean }): { string }? + local out = {} + for k in t do + table.insert(out, k) + end + table.sort(out) + return if #out > 0 then out else nil + end + -- the source's required extensions that are still used stay required + for _, e in (if type(mg.extensionsRequired) == "table" then mg.extensionsRequired else {}) do + if used[e] then + required[e] = true + end + end + doc.extensionsUsed = list(used) + doc.extensionsRequired = list(required) + doc.scenes = scenes + doc.nodes = if #nodes > 0 then nodes else nil + doc.meshes = if #meshes > 0 then meshes else nil + doc.materials = if #materials > 0 then materials else nil + doc.textures = if #textures > 0 then textures else nil + doc.images = if #images > 0 then images else nil + doc.samplers = if #samplers > 0 then samplers else nil + doc.cameras = if #cameras > 0 then cameras else nil + doc.skins = if #skins > 0 then skins else nil + doc.animations = if #animations > 0 then animations else nil + doc.accessors = if #accessors > 0 then accessors else nil + doc.bufferViews = if #views > 0 then views else nil + return { doc = doc, bin = bin:finish(), images = imageOut }, nil +end + +return Write +end +__FILES["model/iqm"] = function() + +-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / +-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). +-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as +-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as +-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints +-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels +-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in +-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's +-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). +-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and +-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/iqm/Read") +local Write = __include("model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- refuse more vertices or triangles (default 2^25) +} +type EncodeOptions = { + framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) + comment: string?, -- stored in the comment block +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r: Bytes.Reader): number + return if r:peek(16) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message) + end + return out, nil +end + +return Iqm +end +__FILES["model/iqm/Read"] = function() + +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and +-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). +-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h: number): number + local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } + local out = table.create(n) :: { number } + local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v: number + if format == 0 then + v = readi8(b, p) + v = if normalized then math.max(v / 127, -1) else v + elseif format == 1 then + v = readu8(b, p) + v = if normalized then v / 255 else v + elseif format == 2 then + v = readi16(b, p) + v = if normalized then math.max(v / 32767, -1) else v + elseif format == 3 then + v = readu16(b, p) + v = if normalized then v / 65535 else v + elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals: { number }, comps: number): Types.Accessor + local d = buffer.create(#vals * 4) + for i, v in vals do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, #vals // comps) +end + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +-- scene(b, base, limit, opts) -> Scene | nil, message +function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) + local size = limit - base + local H: { [string]: number } = {} + for i, name in Read.HEADER do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs: number, count: number, each: number, what: string): string? + if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" + local function str(ofs: number): string + if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + -- vertex arrays (the whole model's vertices; meshes are ranges of them) + local nv = H.num_vertexes + type Array = { kind: string, name: string, format: number, comps: number, offset: number } + local arrays: { Array } = {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) + table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + -- joints -> nodes + a skin + local jointNodes: { number } = {} + local skin: number? = nil + if H.num_joints > 0 then + local joints: { Rig.Joint } = {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = table.create(10) :: { number } + for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM names its texture there) + local matOf: { [string]: number } = {} + local function material(name: string): number? + if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + -- meshes + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes: { [string]: Types.Accessor } = {} + for _, a in arrays do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (if big then 2 else 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 + x = math.clamp(math.floor(x), 0, if big then 65535 else 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 + writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name + local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps + if want ~= a.comps then + local fixed = table.create(cv * want, 0) :: { number } + for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 + end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses: { { mask: number, offset: { number }, scale: { number } } } = {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = table.create(10) :: { number }, table.create(10) :: { number } + for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels += 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes: number = H.num_framechannels * 2 + local framesAt: number = base + H.ofs_frames + local function frame(f: number): { { number } } + local out = table.create(np) :: { { number } } + local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = table.create(10) :: { number } + for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k: number = ps.scale[c + 1] + x += readu16(b, q) * k + q += 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims: { any } = {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = if rate > 0 and rate == rate then rate else 30 + local times = table.create(count) :: { number } + local tracks: { [number]: Rig.Track } = {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in tracks do + local v = fr[j] + local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } + table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = if ql > 0 then ql else 1 + table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read +end +__FILES["model/iqm/Write"] = function() + +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines +-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights +-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins +-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse +-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world +-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are +-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), +-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. +-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). +-- Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Mat4 = __include("codecs/model/Mat4") +local Sampler = __include("codecs/model/Sampler") +local Read = __include("model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene +type M4 = { number } + +-- ------------------------------------------------------------------------------------------------ scene walk +-- world matrices (rest pose, or with a pose's overrides) and the parent of every node +local function parents(scene: Types.Scene): { [number]: number } + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4 + if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 } + local world: { [number]: M4 } = {} + local function get(i: number, depth: number): M4 + local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in scene.nodes do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points +local function triangles(prim: Types.Primitive): { number }? + local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = if fget then fget(f, 0) else 0 + for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at += n + end + else + return nil + end + for _, v in out do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }? + if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = table.create(nv * comps) :: { number } + for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1] + end + end + return out +end + +-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } + local pairs_: { { number } } = {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, pr in pairs_ do + sum += pr[2] + end + local q: { number } = {} + local left = 255 + for k, pr in pairs_ do + q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0 + left -= q[k] + end + if #pairs_ > 0 then + q[1] += left + end + local list: { number } = {} + for k, pr in pairs_ do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +-- appends a flat influence list to the blend index / weight arrays (4 slots) +local function push4(bi: { number }, bw: { number }, list: { number }) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end + +-- ------------------------------------------------------------------------------------------------ writer +type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number } + +function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) + local parent = parents(scene) + local rest = worlds(scene, parent, nil) + -- the skeleton: every skin joint, parents first + local isJoint: { [number]: boolean } = {} + local ibmOf: { [number]: M4 } = {} + for _, skin in scene.skins do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in skin.joints do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = table.create(16) :: M4 + for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + local jointList: { number } = {} + local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local function add(n: number, depth: number) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard += 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in scene.skins do + for _, n in skin.joints do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n: number): number + local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard += 1 + end + return -1 + end + local bindWorld: { [number]: M4 } = {} + for _, n in jointList do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number }) + local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1]]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + -- the meshes + local nodeOfMesh: { [number]: number } = {} + local placed: { { node: number, mesh: number } } = {} + local seen: { [number]: boolean } = {} + local function visit(i: number, depth: number) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in node.children or {} do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in scene.nodes do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in roots do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in scene.meshes do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris: { number } = {} + local meshes: { MeshOut } = {} + -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds + local skinOf: { { number } } = {} + local nvTotal = 0 + for _, pl in placed do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY + local nrmM = Mat4.normalMatrix(world) + for pi, prim in mesh.primitives do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number } + local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = if pl.node > 0 then pl.node else nil + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard += 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + local list: { number } + if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- triangles back to IQM's clockwise order + local tfirst = #tris // 3 + for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else "" + end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name ..= "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 }) + nvTotal += nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + -- animation frames + local frames: { { { number } } } = {} -- frames[f][joint] = 10 values + local anims: { { name: string, first: number, count: number, rate: number } } = {} + local frameWorld: { { [number]: M4 } } = {} + if hasJoints then + for ai, anim in scene.animations do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second + local dt = if #keys > 1 then keys[2] - keys[1] else 0 + local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = if uniform then 1 / dt else 30 + end + local fps: number = math.clamp(rate :: number, 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ: { [number]: { number } } = {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = table.create(#jointList) :: { { number } } + for j, n in jointList do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + -- quantization per pose channel + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in frames do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels += 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + -- text + local text = { "\0" } + local textLen = 1 + local textAt: { [string]: number } = { [""] = 0 } + local function str(s: string): number + local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen += #s + 1 + textAt[s] = at + return at + end + for _, m in meshes do + str(m.name) + str(m.material) + end + for _, n in jointList do + str(scene.nodes[n].name or "") + end + for _, a in anims do + str(a.name) + end + local comment = opts and opts.comment + -- layout + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H: { [string]: number } = {} + local function at(): number + return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text += 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in meshes do + for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do + w:u32le(v) + end + end + -- vertex arrays: headers, then data + type Arr = { typ: number, format: number, comps: number, data: { number } } + local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt: { number } = {} + for i, a in arrs do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in a.data do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in a.data do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in a.data do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in a.data do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), #tris // 3 + for _, v in tris do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in jointList do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le(if p < 0 then p + 2 ^ 32 else p) + for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in jointList do + local jp = jointParent(n) + w:u32le(if jp < 0 then jp + 2 ^ 32 else jp) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in anims do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in frames do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + -- bounds of the skinned vertices per frame + H.ofs_bounds = at() + local skinM = table.create(#jointList) :: { M4 } + for f, world in frameWorld do + for j, n in jointList do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in Read.HEADER do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in arrs do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write +end +__FILES["model/ldraw"] = function() + +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and +-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked +-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. +-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + +-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines +-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at +-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried +-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing +-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). +-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without +-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main +-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = +-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one +-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines +-- = false drops them); no normals, no indices (each triangle has its own three vertices). +-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise +-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or +-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. +-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge +-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig +-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered +-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> +-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). +-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node +-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = +-- false leaves it out (meta.up = nil, meta.source.up = "-y"). +-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. +-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta +-- commands (ignored); BFC in model files' references (models place parts as certified). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/ldraw/Read") +local Colors = __include("model/ldraw/Colors") + +-- ------------------------------------------------------------------------------------------------ contract +local Ldraw = { + name = "ldraw", + category = "model", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths) + files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...) + ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours + color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour") + upright: boolean?, -- add the root node turning -Y up into Y up (default true) + flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false) + lines: boolean?, -- type 2 edge lines as "lines" primitives (default true) + optionalLines: boolean?, -- type 5 optional lines too (default false) + maxDepth: number?, -- sub-file nesting (default 64) + maxTriangles: number?, -- default 2^24 + maxNodes: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ldraw.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 2048, true) + if string.find(head, "^0%s+FILE%s") then + return 0.9 + end + if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then + return 0.8 + end + if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, text, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, +-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added +function Ldraw.colors(ldconfig: string?): { [number]: any } + local t = Colors.builtin() + if ldconfig then + Colors.parse(ldconfig, t) + end + return t +end + +return Ldraw +end +__FILES["model/ldraw/Colors"] = function() + +-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from +-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see +-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. +local Colors = {} + +type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? } +type Table = { [number]: Colour } + +local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } + +-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +function Colors.entry(rest: string): (number?, Colour?) + local words: { string } = {} + for w in string.gmatch(rest, "%S+") do + table.insert(words, w) + end + local name = words[1] + local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil + local i = 2 + while i <= #words do + local k, v = words[i], words[i + 1] + if k == "CODE" and v then + code = tonumber(v) + i += 1 + elseif k == "VALUE" and v and rgb == nil then + rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16) + i += 1 + elseif k == "EDGE" and v then + local hex = string.match(v, "^#(%x%x%x%x%x%x)$") + edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v) + i += 1 + elseif k == "ALPHA" and v then + alpha = math.clamp(tonumber(v) or 255, 0, 255) + i += 1 + elseif k == "LUMINANCE" and v then + lum = math.clamp(tonumber(v) or 0, 0, 255) + i += 1 + elseif FINISHES[k] then + finish = k + elseif k == "MATERIAL" and v then + finish = v + break + end + i += 1 + end + if not name or not code or not rgb or code % 1 ~= 0 then + return nil, nil + end + return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } +end + +-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added +function Colors.parse(text: string, into: Table?): Table + local t: Table = into or {} + for line in string.gmatch(text, "[^\n]+") do + local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$") + if rest then + local code, c = Colors.entry(rest) + if code and c then + t[code] = c + end + end + end + return t +end + +local BUILTIN = [[ +Black CODE 0 VALUE #1B2A34 EDGE #808080 +Blue CODE 1 VALUE #1E5AA8 EDGE #333333 +Green CODE 2 VALUE #00852B EDGE #333333 +Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333 +Red CODE 4 VALUE #B40000 EDGE #333333 +Dark_Pink CODE 5 VALUE #D3359D EDGE #333333 +Brown CODE 6 VALUE #543324 EDGE #1E1E1E +Light_Grey CODE 7 VALUE #8A928D EDGE #333333 +Dark_Grey CODE 8 VALUE #545955 EDGE #333333 +Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333 +Bright_Green CODE 10 VALUE #58AB41 EDGE #333333 +Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333 +Salmon CODE 12 VALUE #F06D61 EDGE #333333 +Pink CODE 13 VALUE #F6A9BB EDGE #333333 +Yellow CODE 14 VALUE #FAC80A EDGE #333333 +White CODE 15 VALUE #F4F4F4 EDGE #333333 +Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333 +Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333 +Tan CODE 19 VALUE #D7BA8C EDGE #333333 +Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333 +Purple CODE 22 VALUE #671F81 EDGE #333333 +Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333 +Orange CODE 25 VALUE #D67923 EDGE #333333 +Magenta CODE 26 VALUE #901F76 EDGE #333333 +Lime CODE 27 VALUE #A5CA18 EDGE #333333 +Dark_Tan CODE 28 VALUE #897D62 EDGE #333333 +Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333 +Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333 +Lavender CODE 31 VALUE #CDA4DE EDGE #333333 +Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333 +Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333 +Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080 +Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333 +Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333 +Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333 +Medium_Green CODE 74 VALUE #7FC475 EDGE #333333 +Light_Pink CODE 77 VALUE #FECCCF EDGE #333333 +Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333 +Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333 +Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333 +Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333 +Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333 +Nougat CODE 92 VALUE #BB805A EDGE #333333 +Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333 +Violet CODE 110 VALUE #26469A EDGE #333333 +Medium_Violet CODE 112 VALUE #4861AC EDGE #333333 +Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333 +Aqua CODE 118 VALUE #9CD6CC EDGE #333333 +Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333 +Light_Orange CODE 125 VALUE #F9A777 EDGE #333333 +Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333 +Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333 +Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333 +Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333 +Rust CODE 216 VALUE #872B17 EDGE #333333 +Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333 +Lilac CODE 219 VALUE #564E9D EDGE #333333 +Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333 +Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333 +Dark_Blue CODE 272 VALUE #19325A EDGE #333333 +Dark_Green CODE 288 VALUE #00451A EDGE #808080 +Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333 +Dark_Brown CODE 308 VALUE #352100 EDGE #808080 +Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333 +Dark_Red CODE 320 VALUE #720012 EDGE #333333 +Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333 +Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333 +Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333 +Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333 +Olive_Green CODE 330 VALUE #77774E EDGE #333333 +Sand_Red CODE 335 VALUE #88605E EDGE #333333 +Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333 +Coral CODE 353 VALUE #FF6D77 EDGE #333333 +Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333 +Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333 +Medium_Brown CODE 370 VALUE #755945 EDGE #333333 +Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333 +Sand_Purple CODE 373 VALUE #75657D EDGE #333333 +Sand_Green CODE 378 VALUE #708E7C EDGE #333333 +Sand_Blue CODE 379 VALUE #70819A EDGE #333333 +Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333 +Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333 +Umber_Brown CODE 423 VALUE #543F33 EDGE #333333 +Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333 +Medium_Orange CODE 462 VALUE #F58624 EDGE #333333 +Dark_Orange CODE 484 VALUE #91501C EDGE #333333 +Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333 +Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333 +Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333 +Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333 +Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333 +Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128 +Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128 +Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128 +Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128 +Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128 +Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128 +Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128 +Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128 +Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128 +Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128 +Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 +Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128 +Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128 +Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128 +Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 +Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128 +Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128 +Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 +Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210 +Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128 +Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128 +Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128 +Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128 +Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128 +Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128 +Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128 +Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128 +Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME +Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME +Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME +Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME +Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME +Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME +Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME +Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT +Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT +Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT +Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT +Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT +Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT +Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT +Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT +Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT +Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT +Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT +Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT +Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT +Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT +Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT +Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT +Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT +Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT +Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT +Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL +Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL +Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL +Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL +Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL +Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL +Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL +Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL +Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240 +Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15 +Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15 +Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15 +Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER +Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER +Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE +Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE +Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER +Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER +Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER +Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER +Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER +Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER +Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER +Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER +Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER +Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER +Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER +Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER +Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER +Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER +Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER +Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER +Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER +Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER +Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER +Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER +Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER +Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER +Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER +Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER +Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER +Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER +Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER +Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER +Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER +Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER +Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER +Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER +Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER +Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER +Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER +Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER +Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC +Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC +Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC +Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC +Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC +Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC +Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC +Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC +Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC +Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC +Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC +Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333 +Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333 +Magnet CODE 493 VALUE #656761 EDGE #333333 METAL +Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL +Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL +Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 +]] + +local cache: Table? = nil +-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) +function Colors.builtin(): Table + if not cache then + local t: Table = {} + for line in string.gmatch(BUILTIN, "[^\n]+") do + local code, c = Colors.entry(line) + if code and c then + t[code] = c + end + end + cache = t + end + local copy: Table = {} + for k, v in cache :: Table do + copy[k] = v + end + return copy +end + +return Colors +end +__FILES["model/ldraw/Read"] = function() + +-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command +-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into +-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Types = __include("Types") +local Colors = __include("model/ldraw/Colors") + +local Read = {} + +type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + ldconfig: string?, + color: number?, + upright: boolean?, + flatten: boolean?, + lines: boolean?, + optionalLines: boolean?, + maxDepth: number?, + maxTriangles: number?, + maxNodes: number?, +} + +-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } +type File = { + name: string, + key: string, + cmds: { Cmd }, + certified: boolean, + org: string?, + refs: number, + library: boolean, + main: boolean, + title: string?, + author: string?, + model: boolean?, +} +type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? } + +local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" } +local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true } +local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 } +local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 } + +local function norm(name: string): string + return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/"))) +end + +local function srgbToLinear(v: number): number + return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 +end + +-- parse(text, name) -> File (colour definitions go into colours as they are met) +local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File + local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } + local cmds = f.cmds + local invert, step, first = false, 1, true + for line in string.gmatch(text, "[^\n]+") do + local t = string.match(line, "^%s*(%d)%s") + if t then + stats.lines += 1 + end + if t == "0" then + local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$") + if w1 == "BFC" and rest then + local u = string.upper(rest) + local cmd: Cmd? = nil + for word in string.gmatch(u, "%S+") do + if word == "CERTIFY" then + f.certified = true + elseif word == "NOCERTIFY" then + f.certified = false + elseif word == "INVERTNEXT" then + invert = true + elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then + local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 } + cmd = c + if word == "CW" or word == "CCW" then + c.cw = word == "CW" + else + c.clip = word == "CLIP" + end + end + end + if cmd then + table.insert(cmds, cmd) + end + elseif w1 == "!COLOUR" then + Colors.parse(line, colours) + elseif w1 == "!LDRAW_ORG" and rest then + f.org = string.match(rest, "^(%S+)") + elseif w1 == "STEP" then + step += 1 + elseif w1 == "Author:" then + f.author = rest + elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then + -- (headers) + elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then + f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) + end + first = false + elseif t then + first = false + local k = tonumber(t) :: number + local inv = invert + invert = false + if k == 1 then + local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$") + local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) } + local code = tonumber(c) + local complete = true + for j = 1, 12 do + if v[j] == nil then + complete = false + end + end + if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then + table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step }) + f.refs += 1 + else + stats.bad += 1 + end + elseif k >= 2 and k <= 5 then + local need = if k == 2 then 6 elseif k == 3 then 9 else 12 + local v: { number } = {} + local code: number? = nil + local n = 0 + for w in string.gmatch(line, "%S+") do + n += 1 + if n == 2 then + code = tonumber(w) + elseif n > 2 and n <= need + 2 then + local num = tonumber(w) + if not num then + break + end + v[n - 2] = num + end + end + if code and code >= 0 and code % 1 == 0 and #v == need then + table.insert(cmds, { k = k, c = code, v = v }) + else + stats.bad += 1 + end + elseif k ~= 0 then + stats.bad += 1 + end + end + end + return f +end + +-- scene(text, opts) -> Scene | nil, message, kind +function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) + local o: Options = opts or {} + local colours = Colors.builtin() + if type(o.ldconfig) == "string" then + Colors.parse(o.ldconfig, colours) + end + local maxDepth = o.maxDepth or 64 + local maxTriangles = o.maxTriangles or 2 ^ 24 + local maxNodes = o.maxNodes or 2 ^ 20 + local withLines = o.lines ~= false + local withOptional = o.optionalLines == true + local stats = { bad = 0, lines = 0 } + + -- ------------------------------------------------------------------------------------------ MPD sections + text = string.gsub(text, "\r", "") + local sections: { [string]: string } = {} + local mainName: string? = nil + local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil + local mainText = text + if mpd then + local cur: string? = nil + local buf: { string } = {} + local function close() + if cur and sections[cur] == nil then + sections[cur] = table.concat(buf, "\n") + end + cur, buf = nil, {} + end + for line in string.gmatch(text, "[^\n]+") do + local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$") + if fname then + close() + cur = norm(fname) + if not mainName then + mainName = fname + end + elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then + close() + elseif cur then + table.insert(buf, line) + end + end + close() + mainText = sections[norm(mainName or "")] or "" + end + + -- ------------------------------------------------------------------------------------------ files + local cache: { [string]: File | false } = {} + local missing: { [string]: boolean } = {} + local fetchFiles = o.files + local resolve = o.resolve + local function fetch(uri: string): string? + local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil + end + local function lookup(name: string): File? + local key = norm(name) + local have = cache[key] + if have ~= nil then + return have or nil + end + local sec = sections[key] + if sec then + local f = parse(sec, name, colours, stats) + cache[key] = f + return f + end + local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/") + for _, prefix in PREFIXES do + for _, cand in { prefix .. slash, prefix .. key } do + local data = fetch(cand) + if data then + local f = parse((string.gsub(data, "\r", "")), name, colours, stats) + f.library = LIBRARY[prefix] == true + cache[key] = f + return f + end + end + end + missing[key] = true + cache[key] = false + return nil + end + local function isModel(f: File): boolean + local m = f.model + if m == nil then + local org = string.lower(f.org or "") + local orgPart = org ~= "" and not string.find(org, "model", 1, true) + if f.main then + m = not orgPart and f.refs > 0 + else + local ext = string.match(f.key, "%.(%w+)$") + m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd") + end + f.model = m + end + return m :: boolean + end + + -- ------------------------------------------------------------------------------------------ colours, materials + local scene = Types.Scene.new() + local function edgeOf(c: number): number + local e = colours[c] + if e then + return e.edge + end + return if c >= 0x2000000 then 0x2000000 else 0x2333333 + end + local function resolveColour(code: number, cur: number): number + if code == 16 then + return cur + elseif code == 24 then + return edgeOf(cur) + end + return code + end + local materialOf: { [string]: number } = {} + local function material(col: number, ds: boolean): number + local key = col .. (if ds then "d" else "") + local have = materialOf[key] + if have then + return have + end + local entry = colours[col] + local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil + if entry then + rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish + elseif col >= 0x2000000 and col < 0x4000000 then + rgb = col % 0x1000000 + alpha = if col >= 0x3000000 then 128 else 255 + name = string.format("#%06X", rgb) + elseif col >= 0x4000000 and col < 0x8000000 then + -- dithered: two 12-bit colours, shown as their mean + local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000 + local function ch(v: number, s: number): number + return ((v // s) % 16) * 17 + end + rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2 + alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255 + name = string.format("Dither_%X", col) + end + local m = Types.Scene.material(name) + m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 } + if alpha < 255 then + m.alphaMode = "blend" + end + m.doubleSided = ds + m.metallic = 0 + m.roughness = 0.35 + if finish == "CHROME" or finish == "METAL" then + m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4 + elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then + m.metallic, m.roughness = 0.6, 0.45 + elseif finish == "RUBBER" then + m.roughness = 0.9 + end + m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } } + table.insert(scene.materials, m) + materialOf[key] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ baking + local failure: string?, failKind: string? = nil, nil + local triangles = 0 + local cycles = 0 + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + + -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-files nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local model = isModel(f) + local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m) + local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9) + local cw, clip = false, true + local function group(mode: string, col: number, ds: boolean): Group + local key = mode .. col .. (if ds then "d" else "") + local g = groups[key] + if not g then + g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil } + groups[key] = g + table.insert(order, g) + end + return g + end + local function put(list: { number }, x: number, y: number, z: number) + local n = #list + list[n + 1] = m1 * x + m2 * y + m3 * z + m4 + list[n + 2] = m5 * x + m6 * y + m7 * z + m8 + list[n + 3] = m9 * x + m10 * y + m11 * z + m12 + end + for _, cmd in f.cmds do + if failure then + break + end + local k = cmd.k + local v = cmd.v + if k == 0 then + if cmd.cw ~= nil then + cw = cmd.cw :: boolean + end + if cmd.clip ~= nil then + clip = cmd.clip :: boolean + end + elseif k == 1 then + if not direct then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v) + local child = { + m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4, + m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8, + m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12, + } + local childCert = if model then true else certified and f.certified and clip + bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false) + end + end + elseif k == 3 or k == 4 then + local col = resolveColour(cmd.c, colour) + local one = certified and f.certified and clip + local g = group("triangles", col, not one) + local rev = cw ~= inv ~= (det < 0) + local p = g.pos + local nt = if k == 3 then 1 else 2 + triangles += nt + if triangles > maxTriangles then + return fail(string.format("limit: more than %d triangles", maxTriangles), "limit") + end + local function tri(a: number, b: number, c: number) + if rev then + a, c = c, a + end + put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3]) + put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3]) + put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3]) + end + tri(0, 1, 2) + if k == 4 then + tri(0, 2, 3) + end + elseif k == 2 and withLines then + local g = group("lines", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + elseif k == 5 and withOptional then + local g = group("optional", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + local ctrl = g.ctrl :: { number } + for _ = 1, 2 do + put(ctrl, v[7], v[8], v[9]) + put(ctrl, v[10], v[11], v[12]) + end + end + end + stack[f] = nil + end + + local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor + local b = buffer.create(count * 12) + for i = 0, count - 1 do + local s = from + i * step + buffer.writef32(b, i * 12, list[s]) + buffer.writef32(b, i * 12 + 4, list[s + 1]) + buffer.writef32(b, i * 12 + 8, list[s + 2]) + end + return Types.Scene.accessor(b, "f32", 3, count) + end + + -- the mesh of a file baked at the identity (nil when it has no geometry) + local meshOf: { [string]: number | false } = {} + local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? + local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") + local have = meshOf[key] + if have ~= nil then + return have or nil + end + local groups: { [string]: Group } = {} + local order: { Group } = {} + bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct) + local mesh: Types.Mesh = { name = f.name, primitives = {} } + for _, g in order do + local count = #g.pos // 3 + if count > 0 then + local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" } + prim.material = material(g.colour, g.ds) + if g.mode == "optional" then + local ctrl = g.ctrl :: { number } + prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count) + prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count) + prim.extras = { ldraw = { optional = true } } + end + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + meshOf[key] = false + return nil + end + table.insert(scene.meshes, mesh) + meshOf[key] = #scene.meshes + return #scene.meshes + end + + -- ------------------------------------------------------------------------------------------ the node tree + local mainFile = parse(mainText, mainName or "main", colours, stats) + mainFile.main = true + if stats.lines == 0 then + return nil, "no LDraw lines", nil + end + if mainName then + cache[norm(mainName)] = mainFile + end + local mainColour = o.color or 16 + local function newNode(node: Types.Node): number + table.insert(scene.nodes, node) + if #scene.nodes > maxNodes then + fail(string.format("limit: more than %d nodes", maxNodes), "limit") + end + return #scene.nodes + end + local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean }) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-models nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local direct = meshFor(f, colour, inv, true) + if direct then + table.insert(out, newNode({ name = f.name, children = {}, mesh = direct })) + end + for _, cmd in f.cmds do + if failure then + break + end + if cmd.k == 1 then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local v = cmd.v + local c = resolveColour(cmd.c, colour) + local subInv = inv ~= (cmd.inv == true) + local node: Types.Node = { + name = cmd.name, + children = {}, + matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 }, + extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } }, + } + local index = newNode(node) + if isModel(sub) then + expand(sub, c, subInv, node.children, depth + 1, stack) + else + node.mesh = meshFor(sub, c, subInv, false) + end + table.insert(out, index) + end + end + end + stack[f] = nil + end + local top: { number } = {} + if o.flatten or not isModel(mainFile) then + local mesh = meshFor(mainFile, mainColour, false, false) + table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh })) + else + expand(mainFile, mainColour, false, top, 0, {}) + end + if failure then + return nil, failure, failKind + end + if o.upright == false then + scene.roots = top + else + table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) }) + scene.roots = { #scene.nodes } + scene.meta.up = "y" + end + scene.meta.unit = 0.0004 + local missingList: { string } = {} + for k in missing do + table.insert(missingList, k) + end + table.sort(missingList) + local nfiles = 0 + for _, f in cache do + if f then + nfiles += 1 + end + end + scene.meta.source = { + format = "ldraw", + mpd = mpd, + name = mainName, + title = mainFile.title, + author = mainFile.author, + files = nfiles, + missing = missingList, + cycles = cycles, + badLines = stats.bad, + up = if o.upright == false then "-y" else nil, + } + return scene, nil, nil +end + +return Read +end +__FILES["model/lwo"] = function() + +-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from +-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. +-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / +-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and +-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: +-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the +-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has +-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces +-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> +-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, +-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: +-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding +-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. +-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / +-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") +local Build = __include("model/lwo/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Lwo = { + name = "lwo", + category = "model", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more points / polygon corners (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ constants +local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lwo.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local v = r:peek(4, 8) + return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 12 then + return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base) + end + if r:peek(4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base) + end + local v = r:peek(4, 8) + if v == "LWO3" then + return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8) + end + if not VERSIONS[v] then + return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8) + end + local maxCorners = opts and opts.maxVertices or 2 ^ 25 + local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model)) + end + if not model then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, model, opts) + if not ok2 then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + return scene, nil +end + +return Lwo +end +__FILES["model/lwo/Build"] = function() + +-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z +-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's +-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its +-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), +-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, +-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. +-- Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } + +-- ------------------------------------------------------------------------------------------------ materials +local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number + local hit = cache[path] + if hit then + return hit + end + local norm = string.gsub(path, "\\", "/") + local base = string.match(norm, "([^/:]+)$") or norm + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } }) + cache[path] = #scene.textures + return #scene.textures +end + +local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material + local mat = Scene.material(surf.name) + local v = surf.values + local c = surf.color + local tran = math.clamp(v.TRAN or 0, 0, 1) + mat.baseColor = { c[1], c[2], c[3], 1 - tran } + if tran > 0 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + local gloss = v.GLOS + mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1 + local lumi = v.LUMI or 0 + if lumi > 0 then + mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi } + end + mat.doubleSided = surf.side == 3 + local maps = {} + local blocks = table.clone(surf.blocks) + table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean + return a.ordinal < b.ordinal + end) + for _, blk in blocks do + local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil + local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap } + if path and (blk.kind == "IMAP" or blk.kind == "TEX") then + local ti = textureIndex(scene, cache, path) + entry.texture = ti + if blk.enabled then + local ref: Types.TextureRef = { texture = ti } + if blk.uvmap and uvSets[blk.uvmap] then + ref.texCoord = uvSets[blk.uvmap] + end + if blk.channel == "COLR" and not mat.baseColorTexture then + mat.baseColorTexture = ref + elseif blk.channel == "LUMI" and not mat.emissiveTexture then + mat.emissiveTexture = ref + if lumi <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + end + table.insert(maps, entry) + end + local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source } + for k, x in v do + extras[string.lower(k)] = x + end + if surf.vcol then + extras.vcol = surf.vcol.name + end + mat.extras = { lwo = extras } + return mat +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group } + local groups: { Group } = {} + local byKey: { [string]: Group } = {} + for i, poly in layer.polys do + local kind = poly.kind + local n = #poly.corners + if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then + local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch" + local mi = surfaceOf(poly.surf) + local key = mi .. class + local g = byKey[key] + if not g then + g = { material = mi, class = class, polys = {} } + byKey[key] = g + table.insert(groups, g) + end + table.insert(g.polys, i - 1) + end + end + local rank: { [string]: number } = { poly = 1, patch = 2, line = 3, point = 4 } + table.sort(groups, function(a: Group, b: Group): boolean + if a.material ~= b.material then + return a.material < b.material + end + return rank[a.class] < rank[b.class] + end) + return groups +end + +-- the corners of a face in output order (winding reversed for the handedness change, first corner kept) +local function ordered(corners: { number }): { number } + local n = #corners + local out = table.create(n) :: { number } + out[1] = corners[1] + for k = 2, n do + out[k] = corners[n - k + 2] + end + return out +end + +type Attr = { map: Parse.Map, name: string, comps: number } + +local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive + local pts, pivot = layer.pts, layer.pivot + local vertOf: { [number]: number } = {} + local srcPoint: { number } = {} -- vertex (1-based) -> point + local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local indices: { number } = {} + local faces: { number } = {} + local madMaps: { Parse.Map } = {} + for _, a in attrs do + if next(a.map.mad) then + table.insert(madMaps, a.map) + end + end + for _, m in morphs do + if next(m.mad) then + table.insert(madMaps, m) + end + end + local function vertex(f: number, p: number): number + local own = false + for _, m in madMaps do + local row = m.mad[f] + if row and row[p] then + own = true + break + end + end + if not own then + local v = vertOf[p] + if v then + return v + end + end + table.insert(srcPoint, p) + table.insert(srcPoly, if own then f else -1) + local v = #srcPoint - 1 + if not own then + vertOf[p] = v + end + return v + end + for _, f in g.polys do + local corners = ordered(layer.polys[f + 1].corners) + local n = #corners + local vs = table.create(n) :: { number } + for k = 1, n do + vs[k] = vertex(f, corners[k]) + end + if g.class == "poly" or g.class == "patch" then + if triangulate then + for k = 2, n - 1 do + table.insert(indices, vs[1]) + table.insert(indices, vs[k]) + table.insert(indices, vs[k + 1]) + end + else + table.insert(faces, n) + table.move(vs, 1, n, #indices + 1, indices) + end + else + table.move(vs, 1, n, #indices + 1, indices) + end + end + local nv = #srcPoint + local pos = buffer.create(nv * 12) + for v = 1, nv do + local p = srcPoint[v] * 3 + local o = (v - 1) * 12 + writef32(pos, o, pts[p + 1] - pivot[1]) + writef32(pos, o + 4, pts[p + 2] - pivot[2]) + writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) + end + local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } + -- the value of map m for vertex v (1-based), or nil + local function value(m: Parse.Map, v: number): ({ number }?, number?) + local f = srcPoly[v] + if f >= 0 then + local row = m.mad[f] + local hit = row and row[srcPoint[v]] + if hit then + return hit, nil + end + end + local p = srcPoint[v] + if m.has[p] then + return nil, p * m.dims + end + return nil, nil + end + local names: { [string]: string } = {} + for _, a in attrs do + local m, comps = a.map, a.comps + local data = buffer.create(nv * comps * 4) + for v = 1, nv do + local o = (v - 1) * comps * 4 + local direct, at = value(m, v) + local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {} + if m.kind == "uv" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, 1 - (x[2] or 0)) + elseif m.kind == "color" then + writef32(data, o, x[1] or 1) + writef32(data, o + 4, x[2] or 1) + writef32(data, o + 8, x[3] or 1) + writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1) + elseif m.kind == "normal" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, x[2] or 0) + writef32(data, o + 8, -(x[3] or 0)) + else + writef32(data, o, x[1] or 0) + end + end + attributes[a.name] = Scene.accessor(data, "f32", comps, nv) + names[a.name] = m.name + end + local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + local targetNames: { string } = {} + for _, m in morphs do + local d = buffer.create(nv * 12) + for v = 1, nv do + local direct, at = value(m, v) + local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil + if x then + local p = srcPoint[v] * 3 + local dx, dy, dz = x[1], x[2], x[3] + if m.kind == "spot" then + dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3] + end + writef32(d, (v - 1) * 12, dx) + writef32(d, (v - 1) * 12 + 4, dy) + writef32(d, (v - 1) * 12 + 8, -dz) + end + end + local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) } + table.insert(targets, tgt) + table.insert(targetNames, m.name) + end + prim.targets = targets + names._targets = table.concat(targetNames, "\n") + end + local ib = buffer.create(#indices * 4) + for k, x in indices do + writeu32(ib, (k - 1) * 4, x) + end + prim.indices = Scene.accessor(ib, "u32", 1, #indices) + if g.class == "line" then + prim.mode = "lines" + elseif g.class == "point" then + prim.mode = "points" + elseif not triangulate then + prim.mode = "polygons" + local fb = buffer.create(#faces * 4) + for k, x in faces do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #faces) + end + prim.material = g.material + local extras: { [string]: any } = { maps = names } + if g.class == "patch" then + extras.subdivision = true + end + prim.extras = { lwo = extras } + return prim +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } + -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + local uvSets: { [string]: number } = {} + local nuv = 0 + for _, layer in m.layers do + for _, map in layer.maps do + if map.kind == "uv" and uvSets[map.name] == nil then + uvSets[map.name] = nuv + nuv += 1 + end + end + end + -- materials: one per surface, then one per tag without a surface, then a default one + local texCache: { [string]: number } = {} + local bySurfName: { [string]: number } = {} + for i, surf in m.surfaces do + scene.materials[i] = material(scene, m, surf, uvSets, texCache) + if bySurfName[surf.name] == nil then + bySurfName[surf.name] = i + end + local low = string.lower(surf.name) + if bySurfName[low] == nil then + bySurfName[low] = i + end + end + local tagMat: { [number]: number } = {} + local default: number? = nil + local function surfaceOf(tag: number?): number + if tag ~= nil then + local hit = tagMat[tag] + if hit then + return hit + end + local name = m.tags[tag + 1] + if name then + local mi = bySurfName[name] or bySurfName[string.lower(name)] + if not mi then + table.insert(scene.materials, Scene.material(name)) + mi = #scene.materials + bySurfName[name] = mi + end + tagMat[tag] = mi + return mi + end + end + if not default then + local mat = Scene.material("Default") + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + mat.metallic = 0 + table.insert(scene.materials, mat) + default = #scene.materials + end + return default :: number + end + -- nodes and meshes + local nodeOf: { [number]: number } = {} + local layerOfNode: { Parse.Layer } = {} + for _, layer in m.layers do + local hasGeometry = #layer.polys > 0 + if not (layer.implicit and not hasGeometry) then + local node: Types.Node = { name = layer.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + layerOfNode[ni] = layer + if nodeOf[layer.index] == nil then + nodeOf[layer.index] = ni + end + node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } } + local groups = groupLayer(layer, surfaceOf) + if #groups > 0 then + local attrs: { Attr } = {} + local morphs: { Parse.Map } = {} + local hasUv = {} + local maxUv = -1 + for _, map in layer.maps do + if map.kind == "uv" then + hasUv[uvSets[map.name]] = map + maxUv = math.max(maxUv, uvSets[map.name]) + elseif map.kind == "morph" or map.kind == "spot" then + table.insert(morphs, map) + end + end + local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} } + for k = 0, maxUv do + table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 }) + end + local nw, nc, hasNormal = 0, 0, false + for _, map in layer.maps do + if map.kind == "normal" and not hasNormal then + hasNormal = true + table.insert(attrs, { map = map, name = "NORMAL", comps = 3 }) + elseif map.kind == "weight" then + table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 }) + nw += 1 + end + end + local prims = {} + for _, g in groups do + local mat = scene.materials[g.material] + local ex: any = mat and mat.extras + local vcol = ex and ex.lwo and ex.lwo.vcol + local pa = table.clone(attrs) + nc = 0 + for _, map in layer.maps do + if map.kind == "color" then + if map.name == vcol then + table.insert(pa, { map = map, name = "COLOR_0", comps = 4 }) + else + table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 }) + nc += 1 + end + end + end + table.insert(prims, primitive(layer, g, pa, morphs, triangulate)) + end + local mesh: Types.Mesh = { name = layer.name, primitives = prims } + if #morphs > 0 then + mesh.weights = table.create(#morphs, 0) + local tn = {} + for _, mp in morphs do + table.insert(tn, mp.name) + end + mesh.extras = { targetNames = tn } + end + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + end + end + -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + local parentOf: { [number]: number } = {} + for ni, layer in layerOfNode do + local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil + if pi and pi ~= ni then + local up, steps = pi, 0 + while up and up ~= ni and steps <= #scene.nodes do + up = parentOf[up] + steps += 1 + end + if up ~= ni then + parentOf[ni] = pi + end + end + end + for ni = 1, #scene.nodes do + local layer = layerOfNode[ni] + local pi = parentOf[ni] + local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 } + local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + scene.nodes[ni].translation = t + end + if pi then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + return scene, nil +end + +return Build +end +__FILES["model/lwo/Parse"] = function() + +-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build +-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave +-- 5.x), checked against what assimp's LWO importer reads (no code taken). +-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are +-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS +-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo +-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural +-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). +-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, +-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. +-- Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local Parse = {} + +type Map = { + kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" + name: string, + dims: number, + vals: { number }, -- per point: vals[point * dims + c + 1] + has: { [number]: boolean }, + mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values +} +type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +type Layer = { + index: number, + name: string?, + parent: number?, + pivot: { number }, + pts: { number }, -- x, y, z flat + polys: { Poly }, + maps: { Map }, + implicit: boolean?, -- the layer before any LAYR +} +type Block = { + kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB) + ordinal: string, + channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP + enabled: boolean, + opacity: number, + projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV + axis: number?, + clip: number?, + file: string?, -- LWOB: the TIMG path + uvmap: string?, + wrap: { number }?, + negative: boolean?, +} +type Surface = { + name: string, + values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + color: { number }, + side: number, + vcol: { name: string, kind: string, intensity: number }?, + blocks: { Block }, + source: string?, +} +type Model = { + version: string, -- "LWO2" | "LWOB" | "LXOB" + tags: { string }, + layers: { Layer }, + surfaces: { Surface }, + clips: { [number]: string }, -- clip index -> path + skipped: { [string]: number }, + corners: number, +} + +local MAP_KINDS: { [string]: string } = { + TXUV = "uv", + RGB = "color", + RGBA = "color", + WGHT = "weight", + MNVW = "weight", + NORM = "normal", + MORF = "morph", + SPOT = "spot", +} + +-- ------------------------------------------------------------------------------------------------ primitives +-- S0: a NUL-terminated string padded to an even length +local function s0(r: Bytes.Reader): string + local start = r.pos + local s = r:cstring() + if (r.pos - start) % 2 == 1 and r.pos < r.limit then + r.pos += 1 + end + return s +end + +-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +local function vx(r: Bytes.Reader): number + if r:peekU8() == 0xFF then + return r:u32be() - 0xFF000000 + end + return r:u16be() +end + +local function id4(r: Bytes.Reader): string + local s = r:string(4) + return (string.gsub(s, " +$", "")) +end + +-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) + while p + 6 <= e do + local id = buffer.readstring(buf, p, 4) + local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5) + local body = p + 6 + local avail = math.min(n, e - body) + f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail)) + p = body + n + (n % 2) + end +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function newLayer(index: number): Layer + return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} } +end + +local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? + local n = r:remaining() // 12 + if #layer.pts // 3 + n > limit then + return "limit: more than " .. limit .. " points" + end + local pts = layer.pts + local k = #pts + for _ = 1, n * 3 do + k += 1 + pts[k] = r:f32be() + end + return nil +end + +-- POLS (LWO2): returns nil or an error +local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 2 do + local n = bit32.band(r:u16be(), 0x3FF) + local corners = table.create(n) :: { number } + for i = 1, n do + local p = vx(r) + ptBase + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + if r.err then + return "truncated polygon list" + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + table.insert(polys, { kind = kind, surf = nil, corners = corners }) + end + return nil +end + +-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count) +local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 4 do + local n = r:u16be() + local corners = table.create(n) :: { number } + for i = 1, n do + local p = r:u16be() + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + local surf = r:i16be() + if r.err then + return "truncated polygon list" + end + if surf < 0 then + surf = -surf + r:u16be() -- the detail polygon count: they follow as ordinary records + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + if n > 0 then + table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners }) + end + end + return nil +end + +local function findMap(layer: Layer, kind: string, name: string, dims: number): Map + for _, m in layer.maps do + if m.kind == kind and m.name == name then + return m + end + end + local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} } + table.insert(layer.maps, m) + return m +end + +local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number }) + local typ = id4(r) + local dims = r:u16be() + local name = s0(r) + local kind = MAP_KINDS[typ] + if r.err or not kind then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3 + if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local m = findMap(layer, kind, name, want) + local npts = #layer.pts // 3 + local npolys = #layer.polys + local vals, has, mad = m.vals, m.has, m.mad + while r:remaining() >= 2 do + local p = vx(r) + ptBase + local f = if perPoly then vx(r) + polyBase else -1 + local v = table.create(want, 1) :: { number } + for c = 1, dims do + local x = r:f32be() + if c <= want then + v[c] = x + end + end + if r.err then + break + end + if p < npts then + if perPoly then + if f < npolys then + local row = mad[f] + if not row then + row = {} + mad[f] = row + end + row[p] = v + end + else + has[p] = true + for c = 1, want do + vals[p * want + c] = v[c] + end + end + end + end +end + +local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number) + local typ = id4(r) + if typ ~= "SURF" and typ ~= "MATR" then + return + end + local polys = layer.polys + while r:remaining() >= 4 do + local f = vx(r) + polyBase + local tag = r:u16be() + if r.err then + break + end + local poly = polys[f + 1] + if poly then + poly.surf = tag + end + end +end + +-- ------------------------------------------------------------------------------------------------ surfaces +local function newSurface(name: string): Surface + return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil } +end + +local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } + +local function readBlock(r: Bytes.Reader, surf: Surface) + -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + if r:remaining() < 6 then + return + end + local kind = id4(r) + local hn = r:u16be() + local hend = math.min(r.pos + hn, r.limit) + local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 } + local hr = Bytes.reader(r.buf, r.pos, hend - r.pos) + blk.ordinal = s0(hr) + subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader) + if id == "CHAN" then + blk.channel = id4(sr) + elseif id == "ENAB" then + blk.enabled = sr:u16be() ~= 0 + elseif id == "OPAC" then + sr:u16be() + blk.opacity = sr:f32be() + elseif id == "NEGA" then + blk.negative = sr:u16be() ~= 0 + elseif id == "AXIS" then + blk.axis = sr:u16be() + end + end) + subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader) + if id == "PROJ" then + blk.projection = sr:u16be() + elseif id == "AXIS" then + blk.axis = sr:u16be() + elseif id == "IMAG" then + blk.clip = vx(sr) + elseif id == "VMAP" then + blk.uvmap = s0(sr) + elseif id == "WRAP" then + blk.wrap = { sr:u16be(), sr:u16be() } + end + end) + table.insert(surf.blocks, blk) +end + +local function readSurface(r: Bytes.Reader, surfaces: { Surface }) + local name = s0(r) + local source = s0(r) + local surf = newSurface(name) + if source ~= "" then + for _, s in surfaces do + if s.name == source then + surf.values = table.clone(s.values) + surf.color = table.clone(s.color) + surf.side = s.side + surf.vcol = s.vcol + surf.blocks = table.clone(s.blocks) + break + end + end + surf.source = source + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:f32be(), sr:f32be(), sr:f32be() } + if not sr.err then + surf.color = c + end + elseif SURF_VALUES[id] then + local v = sr:f32be() + if not sr.err then + surf.values[id] = v + end + elseif id == "SIDE" then + surf.side = sr:u16be() + elseif id == "VCOL" then + local intensity = sr:f32be() + vx(sr) + local kind = id4(sr) + local vname = s0(sr) + if not sr.err then + surf.vcol = { name = vname, kind = kind, intensity = intensity } + end + elseif id == "BLOK" then + readBlock(sr, surf) + end + end) + table.insert(surfaces, surf) +end + +-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks +local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" } +local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" } +local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" } +local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 } + +local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface }) + local surf = newSurface(s0(r)) + local tex: Block? = nil + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 } + if not sr.err then + surf.color = c + end + elseif B_VALUES[id] then + local v = sr:u16be() + if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then + surf.values[B_VALUES[id]] = v / 256 + end + elseif B_FLOATS[id] then + local v = sr:f32be() + if not sr.err then + surf.values[B_FLOATS[id]] = v + surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one + end + elseif id == "GLOS" then + local v = sr:u16be() + if not sr.err then + -- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness + surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1) + end + elseif id == "SMAN" then + surf.values.SMAN = sr:f32be() + elseif id == "FLAG" then + local fl = sr:u16be() + if bit32.band(fl, 0x100) ~= 0 then + surf.side = 3 + end + elseif B_TEX[id] then + local desc = sr:cstring() + local proj: number? = nil + for word, v in B_PROJ do + if string.find(desc, word, 1, true) then + proj = v + end + end + local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj } + table.insert(surf.blocks, blk) + tex = blk + elseif id == "TIMG" and tex then + local path = sr:cstring() + if path ~= "" and path ~= "(none)" then + tex.file = path + end + elseif id == "TFLG" and tex then + local fl = sr:u16be() + tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2 + tex.negative = bit32.band(fl, 16) ~= 0 + elseif id == "TVAL" and tex then + tex.opacity = sr:u16be() / 256 + end + end) + for k in surf.values do + if string.sub(k, -1) == "!" then + surf.values[k] = nil + end + end + table.insert(surfaces, surf) +end + +local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number }) + local index = r:u32be() + if r.err then + return + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "STIL" then + clips[index] = s0(sr) + elseif id == "ISEQ" then + local digits = sr:u8() + sr:u8() + local offset = sr:i16be() + sr:u16be() + local start = sr:i16be() + sr:u16be() + local prefix = s0(sr) + local suffix = s0(sr) + if not sr.err then + clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix + end + elseif id == "XREF" then + refs[index] = sr:u32be() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ the file +-- parse(buf, from, limit, opts) -> Model | nil, message +function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) + local version = buffer.readstring(buf, from + 8, 4) + local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) + local e = math.min(limit, from + 8 + declared) + local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 } + local layer = newLayer(0) + layer.implicit = true + table.insert(model.layers, layer) + local ptBase, polyBase = 0, 0 + local budget = { maxCorners } + local refs: { [number]: number } = {} + local lwob = version == "LWOB" + local list = Chunks.walk(buf, from + 12, e, Chunks.IFF) + for _, c in list do + local id = c.id + local r = Bytes.reader(buf, c.offset, c.avail) + local err: string? = nil + if id == "TAGS" or id == "SRFS" then + while r:remaining() > 0 do + table.insert(model.tags, s0(r)) + end + elseif id == "LAYR" and not lwob then + local index = r:u16be() + r:u16be() -- flags (hidden) + local px, py, pz = r:f32be(), r:f32be(), r:f32be() + local name = s0(r) + local parent: number? = if r:remaining() >= 2 then r:u16be() else nil + if r.err then + return nil, "truncated LAYR chunk" + end + if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then + table.remove(model.layers, #model.layers) + end + layer = newLayer(index) + layer.name = name + layer.parent = if parent == 0xFFFF then nil else parent + layer.pivot = { px, py, pz } + table.insert(model.layers, layer) + ptBase, polyBase = 0, 0 + elseif id == "PNTS" then + ptBase = #layer.pts // 3 + err = readPoints(r, layer, maxCorners) + elseif id == "POLS" then + polyBase = #layer.polys + if lwob then + err = readPolysB(r, layer, budget) + else + local kind = id4(r) + if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then + err = readPolys(r, layer, kind, ptBase, budget) + else + -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + local before = #layer.polys + err = readPolys(r, layer, kind, ptBase, budget) + model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before + end + end + elseif id == "VMAP" or id == "VMAD" then + readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped) + elseif id == "PTAG" then + readPtag(r, layer, polyBase) + elseif id == "SURF" then + if lwob then + readSurfaceB(r, model.surfaces) + else + readSurface(r, model.surfaces) + end + elseif id == "CLIP" then + readClip(r, model.clips, refs) + end + if err then + return nil, err + end + end + for index, target in refs do + if model.clips[index] == nil and model.clips[target] then + model.clips[index] = model.clips[target] + end + end + model.corners = maxCorners - budget[1] + return model, nil +end + +return Parse +end +__FILES["model/mca"] = function() + +-- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft +-- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads +-- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over +-- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, +-- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). +-- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks +-- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with +-- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its +-- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, +-- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header +-- and one chunk's NBT without building voxels. +-- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the +-- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Chunk = __include("model/mca/Chunk") +local Lz4Block = __include("model/mca/Lz4Block") + +-- ------------------------------------------------------------------------------------------------ contract +local Mca = { + name = "mca", + category = "model", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) + area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) + maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) + maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) + keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) + region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files + name: string?, -- the file name (the api fills it in) + resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc +} +type Entry = { + x: number, -- local chunk coordinates 0 .. 31 + z: number, + sector: number, -- 4 KiB sector of the chunk + sectors: number, + timestamp: number, -- seconds since 1970 +} + +-- ------------------------------------------------------------------------------------------------ constants +local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mca.sniff(r: Bytes.Reader): number + local n = r.limit - r.base + if n < 8192 then + return 0 + end + local sectors = (n + 4095) // 4096 + local used, b = 0, r.buf + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) + if e ~= 0 then + local off, cnt = e // 256, e % 256 + if off < 2 or cnt == 0 or off + cnt > sectors then + return 0 + end + used += 1 + if used == 1 then + local p = r.base + off * 4096 + if p + 5 > r.limit then + return 0 + end + local c = buffer.readu8(b, p + 4) % 128 + if COMPRESSION[c] == nil then + return 0 + end + end + end + end + return if used > 0 then 0.8 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) +function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local n = r.limit - r.base + if n < 8192 then + return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) + end + local out: { Entry } = {} + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) + if e ~= 0 then + table.insert(out, { + x = i % 32, + z = i // 32, + sector = e // 256, + sectors = e % 256, + timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), + }) + end + end + return out, nil +end + +local function regionCoords(o: DecodeOptions): (number?, number?) + if o.region then + return o.region[1], o.region[2] + end + if o.name then + local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") + if x then + return tonumber(x), tonumber(z) + end + end + return nil, nil +end + +-- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err +local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) + local p = r.base + e.sector * 4096 + if p + 5 > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) + end + local len = bit32.byteswap(buffer.readu32(r.buf, p)) + local ctype = buffer.readu8(r.buf, p + 4) + local data: buffer, start: number, size: number = r.buf, p + 5, len - 1 + if ctype >= 128 then + -- stored in c...mcc next to the region (whole file = the compressed payload) + local rx, rz = regionCoords(o) + if not o.resolve or rx == nil then + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) + end + local name = string.format("c.%d.%d.mcc", (rx :: number) * 32 + e.x, (rz :: number) * 32 + e.z) + local ext = o.resolve(name) + if type(ext) ~= "buffer" then + return nil, Err.new(Err.IO, "cannot read " .. name) + end + data, start, size = ext, 0, buffer.len(ext) + ctype -= 128 + elseif len < 1 or p + 4 + len > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) + end + local comp = COMPRESSION[ctype] + local maxBytes = o.maxBytes or 2 ^ 26 + local out, err + if comp == "gzip" then + out, err = Deflate.gunzip(data, start, size) + elseif comp == "zlib" then + out, err = Deflate.zlib(data, start, size) + elseif comp == "none" then + out = buffer.create(size :: number) + buffer.copy(out, 0, data, start, size) + elseif comp == "lz4" then + local msg + out, msg = Lz4Block.decode(data, start, size :: number, maxBytes) + if not out then + err = Err.from(msg, start - r.base) + end + else + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) + end + if not out then + return nil, err + end + if buffer.len(out) > maxBytes then + return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) + end + return out, comp +end + +-- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) +function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) + local o: DecodeOptions = opts or {} + if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then + return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") + end + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + for _, e in entries do + if e.x == x and e.z == z then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, info + end + return v, comp + end + end + return nil, nil +end + +function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + local want: { [number]: boolean }? = nil + if o.chunks then + local w: { [number]: boolean } = {} + for _, c in o.chunks do + w[(c[1] or 0) + 32 * (c[2] or 0)] = true + end + want = w + end + local area = o.area + if area and #area ~= 6 then + return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") + end + local keep = o.keepNbt ~= false + local chunks: { Chunk.Blocks } = {} + local infos = {} + for _, e in entries do + if not want or want[e.x + 32 * e.z] then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) + end + local blocks, berr = Chunk.blocks(v) + if not blocks then + return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) + end + local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) + if inArea then + table.insert(chunks, blocks) + table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = if keep then v else nil }) + end + end + end + -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, c in chunks do + lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) + lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) + for _, s in c.sections do + local solid = false + for _, st in s.states do + if not Mc.isAir(st) then + solid = true + break + end + end + if solid then + lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) + end + end + end + if area then + for k = 1, 3 do + lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) + if area[k] > area[k + 3] then + return nil, Err.new(Err.ARG, "area minimum past its maximum") + end + end + if lo[2] == math.huge then + lo[2], hi[2] = area[2], area[5] + end + end + if lo[2] == math.huge then + lo[2], hi[2] = 0, -1 -- no blocks at all + end + if #chunks == 0 then + lo, hi = { 0, 0, 0 }, { -1, -1, -1 } + end + local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) + local n = sx * sy * sz + if n > (o.maxCells or 2 ^ 25) then + return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) + end + -- one palette for the grid (air first), each section copied in through a remap table + local states = { "minecraft:air" } + local index: { [string]: number } = { ["minecraft:air"] = 0 } + local grid = buffer.create(n * 2) + local bes, ents = {}, {} + for _, c in chunks do + local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] + for _, s in c.sections do + local cy = s.y * 16 - lo[2] + if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then + local lut = table.create(#s.states) :: { number } + for i, st in s.states do + local g = index[st] + if g == nil then + table.insert(states, st) + g = #states - 1 + index[st] = g + end + lut[i] = g + end + if #states > 65536 then + return nil, Err.new(Err.LIMIT, "more than 65536 block states") + end + local cells = s.cells + local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) + local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) + local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) + for y = y0, y1 do + for z = z0, z1 do + local src = ((y * 16 + z) * 16 + x0) * 2 + local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 + for _ = x0, x1 do + buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) + src += 2 + dst += 2 + end + end + end + end + end + for _, rec in c.blockEntities do + local be = Mc.blockEntity(rec, "flat") + if be then + local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] + if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then + be.pos = { px, py, pz } + table.insert(bes, be) + end + end + end + for _, ent in c.entities do + table.insert(ents, ent) + end + end + local v = Mc.voxels(sx, sy, sz, states, grid) + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = bes + b.entities = ents + local scene = Types.Scene.new() + scene.voxels = { v } + scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } + scene.roots = { 1 } + scene.meta.up = "y" + scene.meta.unit = 1 + local rx, rz = regionCoords(o) + scene.meta.source = { format = "mca", region = if rx then { rx, rz } else nil, chunks = infos } + return scene, nil +end + +return Mca +end +__FILES["model/mca/Chunk"] = function() + +-- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three +-- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least +-- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = +-- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through +-- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Chunk = {} + +local Packed = Mc.Packed + +type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order +type Blocks = { + x: number, -- chunk coordinates (xPos / zPos) + z: number, + dataVersion: number?, + sections: { Section }, + blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z) + entities: { any }, -- entities stored in the chunk (before 1.17) +} + +local function int(v: any): number? + local n = Nbt.number(v) + return if n and n == n and n % 1 == 0 then n else nil +end + +local function list(v: any): { any } + return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} +end + +-- a palette section (1.13+): states from the palette compounds, cells from the packed array +local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) + local states = table.create(#palette) :: { string } + for i, c in palette do + local s = Mc.stateFromNbt(c) + if not s then + return nil, "section " .. y .. ": bad palette entry " .. i + end + states[i] = s + end + if #states == 0 then + return nil, nil + end + local cells = buffer.create(8192) + if #states > 1 or data ~= nil then + if not (Nbt.isTag(data) and data.type == "longArray") then + return nil, "section " .. y .. ": no block state data" + end + local bits = Packed.bitsFor(#states, minBits) + local ok, e = Packed.unpack(data.value, bits, 4096, spanning, cells, #states) + if not ok then + return nil, "section " .. y .. ": " .. tostring(e) + end + end + return { y = y, states = states, cells = cells }, nil +end + +-- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk +function Chunk.blocks(root: any): (Blocks?, string?) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, "chunk NBT is not a compound" + end + local dv = int(root.DataVersion) + local level = if Types.isObject(root.Level) then root.Level else root + local x, z = int(level.xPos), int(level.zPos) + if not x or not z then + return nil, "chunk without xPos / zPos" + end + local out: Blocks = { x = x, z = z, dataVersion = dv, sections = {}, blockEntities = {}, entities = list(level.Entities) } + if root.sections ~= nil then + -- 1.18+ + for _, s in list(root.sections) do + local y = int(s.Y) + local bs = s.block_states + if y and type(bs) == "table" and not Nbt.isTag(bs) then + local sec, e = paletted(y, list(bs.palette), bs.data, 4, false) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + end + end + out.blockEntities = list(root.block_entities) + return out, nil + end + for _, s in list(level.Sections) do + local y = int(s.Y) + if y then + if s.Palette ~= nil then + local sec, e = paletted(y, list(s.Palette), s.BlockStates, 4, (dv or 0) < 2529) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + elseif type(s.Blocks) == "buffer" then + local blocks = s.Blocks :: buffer + if buffer.len(blocks) < 4096 then + return nil, "section " .. y .. ": short Blocks array" + end + local data = if type(s.Data) == "buffer" and buffer.len(s.Data) >= 2048 then s.Data else nil + local add = if type(s.Add) == "buffer" and buffer.len(s.Add) >= 2048 then s.Add else nil + local slots: { [number]: number } = {} + local states: { string } = {} + local cells = buffer.create(8192) + for i = 0, 4095 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, false) * 256 + end + local d = if data then Packed.nibble(data, 0, i, false) else 0 + local key = id * 16 + d + local slot = slots[key] + if not slot then + table.insert(states, Mc.legacyState(id, d)) + slot = #states - 1 + slots[key] = slot + end + buffer.writeu16(cells, i * 2, slot :: number) + end + table.insert(out.sections, { y = y, states = states, cells = cells }) + end + end + end + out.blockEntities = list(level.TileEntities) + return out, nil +end + +return Chunk +end +__FILES["model/mca/Lz4Block"] = function() + +-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 +-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | +-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the +-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +local Lz4 = __include("codecs/compress/Lz4") + +local Lz4Block = {} + +local MAGIC = "LZ4Block" + +-- decode(buf, offset, length, maxBytes) -> buffer | nil, message +function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) + local p, e = offset, offset + length + local parts, total = {}, 0 + while true do + if p + 21 > e then + if #parts > 0 and p >= e then + break -- some writers stop without the empty end block + end + return nil, "truncated LZ4 block header" + end + if buffer.readstring(b, p, 8) ~= MAGIC then + return nil, "bad LZ4Block magic" + end + local token = buffer.readu8(b, p + 8) + local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13) + p += 21 + local method = token // 16 * 16 + if clen < 0 or dlen < 0 or p + clen > e then + return nil, "truncated LZ4 block" + end + if dlen == 0 and clen == 0 then + break + end + total += dlen + if total > maxBytes then + return nil, "limit: chunk inflates past maxBytes" + end + if method == 0x10 then + if clen ~= dlen then + return nil, "raw LZ4 block length mismatch" + end + local out = buffer.create(dlen) + buffer.copy(out, 0, b, p, clen) + table.insert(parts, out) + elseif method == 0x20 then + local out, err = Lz4.decompress(b, p, clen, dlen) + if not out then + return nil, "LZ4: " .. tostring(err and err.message) + end + table.insert(parts, out) + else + return nil, "unsupported: LZ4Block method " .. method + end + p += clen + end + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +return Lz4Block +end +__FILES["model/md2"] = function() + +-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the +-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. +-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, +-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), +-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored +-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not +-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one +-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture +-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. +-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. +-- Not supported: the GL command list (the triangles carry the same geometry), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md2 = { + name = "md2", + category = "model", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + frame: number?, -- the frame used as the base POSITION (1-based, default 1) + morph: boolean?, -- every frame as a morph target + the animations (default true) + fps: number?, -- animation frame rate (default 10) + maxVertices: number?, -- frames x vertices (default 2^24) +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Md2.sniff(r: Bytes.Reader): number + if r:remaining() < 68 then + return 0 + end + return if Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- group frame names by their name without trailing digits, in file order +local function groups(names: { string }, fps: number): { Rig.Range } + local out: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)_?%d*$") or n + if stem == "" then + stem = n + end + local last = out[#out] + if last and last.name == stem and last.last == i - 1 then + last.last = i + else + table.insert(out, { name = stem, first = i, last = i, fps = fps }) + end + end + return out +end + +function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if not r:match("IDP2") then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local h: { number } = {} + for i = 1, 16 do + h[i] = r:i32le() + end + if r.err then + return nil, r.err + end + local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14) + if version ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4) + end + if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then + return nil, Err.new(Err.CORRUPT, "bad counts", 8) + end + if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then + return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44) + end + if frameSize < 40 + nXyz * 4 then + return nil, Err.new(Err.CORRUPT, "frame size too small", 16) + end + local b, base = r.buf, r.base + -- skins + local skins: { string } = {} + for i = 0, nSkins - 1 do + local s = buffer.readstring(b, base + oSkins + i * 64, 64) + table.insert(skins, (string.match(s, "^[^%z]*")) :: string) + end + -- weld (xyz, st) pairs + local key: { [number]: number } = {} + local vx: { number }, vst: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + oTris + t * 12 + local corner: { number } = {} + for c = 0, 2 do + local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2) + if xi >= nXyz or (nSt > 0 and si >= nSt) then + return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12) + end + local k = xi * 65536 + si + local v = key[k] + if not v then + table.insert(vx, xi) + table.insert(vst, si) + v = #vx - 1 + key[k] = v + end + corner[c + 1] = v + end + table.insert(indices, corner[3]) + table.insert(indices, corner[2]) + table.insert(indices, corner[1]) + end + local nv = #vx + local uv = buffer.create(nv * 8) + for i = 1, nv do + if nSt > 0 then + local o = base + oSt + vst[i] * 4 + writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1)) + writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) + end + end + -- frames + local frames: { buffer } = {} + local normals: { buffer } = {} + local names: { string } = {} + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + for f = 1, nFrames do + if morph or f == want then + local o = base + oFrames + (f - 1) * frameSize + local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) + local pos = buffer.create(nv * 12) + for i = 1, nv do + local p = o + 40 + vx[i] * 4 + writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx) + writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty) + writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz) + end + frames[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16) + names[f] = (string.match(nm, "^[^%z]*")) :: string + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + if #skins > 0 then + for _, s in skins do + table.insert(scene.textures, { name = s, uri = s }) + end + local mat = Scene.material(skins[1]) + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + table.insert(scene.materials, mat) + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + local fr: { buffer } = {} + for f = 1, nFrames do + fr[f] = frames[f] + end + Rig.morph(prim, fr, normals) + local w = table.create(nFrames, 0) + scene.meshes[1].weights = w + Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR") + end + scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false } + return scene, nil +end + +return Md2 +end +__FILES["model/md3"] = function() + +-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format +-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" +-- notes (PhaethonH); no code taken. +-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame +-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left +-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all +-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes +-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). +-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md3 = { + name = "md3", + category = "model", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1) + morph: boolean?, -- every frame as a morph target + the animation (default true) + fps: number?, -- animation frame rate (default 15) + maxVertices: number?, -- frames x vertices over all surfaces (default 2^24) +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32 +local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal) + +-- ------------------------------------------------------------------------------------------------ sniff +function Md3.sniff(r: Bytes.Reader): number + if r:remaining() < 108 then + return 0 + end + return if Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 108 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if not r:match("IDP3") then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 15 then + return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4) + end + local b, base = r.buf, r.base + local name = cstr(b, base + 8, 64) + r:skip(68) + local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le() + local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then + return nil, Err.new(Err.CORRUPT, "bad counts", 76) + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then + return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88) + end + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + local maxV = opts and opts.maxVertices or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + local mesh: Types.Mesh = { name = if name ~= "" then name else nil, primitives = {} } + scene.meshes[1] = mesh + scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 } + scene.roots[1] = 1 + local total = 0 + local so = oSurf + for s = 1, nSurf do + if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so) + end + local p = base + so + local sname = cstr(b, p + 4, 64) + local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84) + local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104) + if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72) + end + total += nVerts * nFrames + if total > maxV then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then + return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so) + end + local ib = buffer.create(nTris * 12) + local idx = table.create(nTris * 3, 0) :: { number } + for t = 0, nTris - 1 do + for c = 0, 2 do + local v = readi32(b, p + oTri + t * 12 + c * 4) + if v < 0 or v >= nVerts then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12) + end + idx[t * 3 + 3 - c] = v + end + end + for i, v in idx do + writeu32(ib, (i - 1) * 4, v) + end + local uv = buffer.create(nVerts * 8) + buffer.copy(uv, 0, b, p + oSt, nVerts * 8) + local frames: { buffer }, normals: { buffer } = {}, {} + for f = 1, nFrames do + if morph or f == want then + local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12) + local q = p + oXyz + (f - 1) * nVerts * 8 + for v = 0, nVerts - 1 do + local o = q + v * 8 + writef32(pos, v * 12, readi16(b, o) / 64) + writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64) + writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64) + local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K + writef32(nrm, v * 12, math.cos(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 8, math.cos(lng)) + end + frames[f], normals[f] = pos, nrm + end + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nVerts), + NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts), + }, + indices = Scene.accessor(ib, "u32", 1, nTris * 3), + mode = "triangles", + extras = { md3 = { surface = sname } }, + } + if morph then + Rig.morph(prim, frames, normals) + end + local shaders: { string } = {} + for k = 0, nShaders - 1 do + table.insert(shaders, cstr(b, p + oSh + k * 68, 64)) + end + local mat = Scene.material(sname) + mat.metallic = 0 + if shaders[1] and shaders[1] ~= "" then + table.insert(scene.textures, { name = shaders[1], uri = shaders[1] }) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { md3 = { shaders = shaders } } + table.insert(scene.materials, mat) + prim.material = #scene.materials + table.insert(mesh.primitives, prim) + so += oEnd + end + -- frames and tags + local frameNames: { string } = {} + for f = 0, nFrames - 1 do + frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) + end + local tagNodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + local tagNames: { string } = {} + for k = 0, nTags - 1 do + local tr: Rig.Track = { translation = {}, rotation = {} } + local first: any = nil + for f = 0, nFrames - 1 do + local o = base + oTags + (f * nTags + k) * 112 + local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) } + local a: { number } = {} + for i = 0, 8 do + a[i + 1] = readf32(b, o + 76 + i * 4) + end + local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 } + local q = Mat4.quat(m) + for c = 1, 3 do + table.insert(tr.translation :: { number }, t[c]) + end + for c = 1, 4 do + table.insert(tr.rotation :: { number }, q[c]) + end + if f == want - 1 then + first = { name = cstr(b, o, 64), t = t, q = q } + end + end + table.insert(tagNames, first.name) + table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } }) + table.insert(scene.nodes[1].children, #scene.nodes) + tagNodes[k + 1] = #scene.nodes + tracks[k + 1] = tr + end + if morph and nFrames > 1 then + scene.meshes[1].weights = table.create(nFrames, 0) + local fps = opts and opts.fps or 15 + Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR") + if nTags > 0 then + local times: { number } = {} + for f = 1, nFrames do + times[f] = (f - 1) / fps + end + local ai = Rig.animation(scene, "tags", tagNodes, times, tracks) + local tagAnim = table.remove(scene.animations, ai) :: Types.Animation + for _, ch in tagAnim.channels do + table.insert(scene.animations[1].channels, ch) + end + end + end + scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames } + return scene, nil +end + +return Md3 +end +__FILES["model/md5"] = function() + +-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim +-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from +-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by +-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless +-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom +-- units, z up. Not supported: writing, .md5camera. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/md5/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local Md5 = { + name = "md5", + category = "model", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + anims: { string }?, -- .md5anim files to load with a .md5mesh + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED) + name: string?, -- the file name (names a standalone animation) + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Md5.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + return if string.match(head, "^MD5Version%s+%d+") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function stem(name: string): string + local base = string.match(name, "([^/\\]+)$") or name + return (string.gsub(base, "%.[^.]*$", "")) +end + +function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + if string.find(text, "numAnimatedComponents", 1, true) then + local a, msg = Read.anim(text) + if not a then + return nil, Err.from(msg) + end + return Read.animScene(a, if opts and type(opts.name) == "string" then stem(opts.name) else "animation"), nil + end + local scene, byName = Read.mesh(text, opts :: any) + if not scene then + return nil, Err.from(byName) + end + if opts and type(opts.anims) == "table" then + for _, name in opts.anims do + local got = if type(name) == "string" then Input.sibling(opts, name) else nil + local src = if got then buffer.tostring(got) else nil + if not src then + if not opts.skipMissing then + return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)") + end + else + local a, msg = Read.anim(Sniff.dropBom(src)) + if not a then + return nil, Err.from("animation " .. name .. ": " .. tostring(msg)) + end + Read.addAnim(scene, byName, a, stem(name)) + end + end + end + return scene, nil +end + +return Md5 +end +__FILES["model/md5/Read"] = function() + +-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: +-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive +-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed +-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: +-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at +-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding +-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ tokens +type Lexer = { text: string, pos: number, err: string? } + +local function token(L: Lexer): string? + local s = L.text + while true do + local a = string.find(s, "%S", L.pos) + if not a then + L.pos = #s + 1 + return nil + end + if string.sub(s, a, a + 1) == "//" then + local nl = string.find(s, "\n", a, true) + L.pos = if nl then nl + 1 else #s + 1 + else + L.pos = a + break + end + end + local c = string.sub(s, L.pos, L.pos) + if c == '"' then + local e = string.find(s, '"', L.pos + 1, true) + if not e then + L.err = "unterminated string" + L.pos = #s + 1 + return nil + end + local v = string.sub(s, L.pos + 1, e - 1) + L.pos = e + 1 + return '"' .. v + end + if c == "(" or c == ")" or c == "{" or c == "}" then + L.pos += 1 + return c + end + local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1) + local v = string.sub(s, L.pos, e - 1) + L.pos = e + return v +end + +local function num(L: Lexer): number + local t = token(L) + local v = t and tonumber(t) + if not v then + L.err = L.err or ("expected a number, got " .. tostring(t)) + return 0 + end + return v +end + +local function str(L: Lexer): string + local t = token(L) + if not t or string.sub(t, 1, 1) ~= '"' then + L.err = L.err or ("expected a string, got " .. tostring(t)) + return "" + end + return string.sub(t, 2) +end + +local function expect(L: Lexer, want: string) + local t = token(L) + if t ~= want then + L.err = L.err or ("expected " .. want .. ", got " .. tostring(t)) + end +end + +local function vec(L: Lexer, n: number): { number } + expect(L, "(") + local v = table.create(n, 0) + for i = 1, n do + v[i] = num(L) + end + expect(L, ")") + return v +end + +-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +local function quat(x: number, y: number, z: number): { number } + local t = 1 - x * x - y * y - z * z + return { x, y, z, if t < 0 then 0 else -math.sqrt(t) } +end + +local function rotate(q: { number }, vx: number, vy: number, vz: number): (number, number, number) + local qx, qy, qz, qw = q[1], q[2], q[3], q[4] + -- v + 2 w (q x v) + 2 q x (q x v) + local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx) + return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx) +end + +-- ------------------------------------------------------------------------------------------------ md5mesh +type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } } + +-- mesh(text, opts) -> Scene, joint node indices by name | nil, message +function Read.mesh(text: string, opts: Options?): (Types.Scene?, any) + local L: Lexer = { text = text, pos = 1, err = nil } + local joints: { MeshJoint } = {} + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = "md5", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local version: number? = nil + local mesh: Types.Mesh = { primitives = {} } + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + local skinIndex = 0 + local nodes: { number } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numJoints" or t == "numMeshes" then + num(L) + elseif t == "joints" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad joint line" + end + local parent = num(L) + local p, q = vec(L, 3), vec(L, 3) + table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) }) + end + local list: { Rig.Joint } = {} + for i, j in joints do + list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q } + end + local n, si = Rig.skeleton(scene, list, "world", 1) + nodes, skinIndex = n, si + elseif t == "mesh" then + expect(L, "{") + local shader = "" + local verts: { { number } } = {} -- s, t, startWeight, countWeight + local tris: { number } = {} + local weights: { { number } } = {} -- joint, bias, x, y, z + while not L.err do + local k = token(L) + if k == "}" then + break + elseif k == "shader" then + shader = str(L) + elseif k == "numverts" or k == "numtris" or k == "numweights" then + local n = num(L) + total += if k == "numverts" then n else 0 + if total > maxV then + return nil, "limit: too many vertices" + end + elseif k == "vert" then + local i = num(L) + local st = vec(L, 2) + verts[i + 1] = { st[1], st[2], num(L), num(L) } + elseif k == "tri" then + num(L) + local a, b, c = num(L), num(L), num(L) + table.insert(tris, c) + table.insert(tris, b) + table.insert(tris, a) + elseif k == "weight" then + local i = num(L) + local j, bias = num(L), num(L) + local p = vec(L, 3) + weights[i + 1] = { j, bias, p[1], p[2], p[3] } + else + return nil, "unknown mesh keyword " .. tostring(k) + end + end + local nv = #verts + local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi = 1, nv do + local v = verts[vi] + if not v then + return nil, "missing vert " .. (vi - 1) + end + local x, y, z = 0, 0, 0 + local l: { number } = {} + for w = v[3] + 1, v[3] + v[4] do + local wt = weights[w] + local j = wt and joints[wt[1] + 1] + if not wt or not j then + return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1) + end + local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5]) + x += (j.pos[1] + rx) * wt[2] + y += (j.pos[2] + ry) * wt[2] + z += (j.pos[3] + rz) * wt[2] + table.insert(l, wt[1]) + table.insert(l, wt[2]) + end + writef32(pos, (vi - 1) * 12, x) + writef32(pos, (vi - 1) * 12 + 4, y) + writef32(pos, (vi - 1) * 12 + 8, z) + writef32(uv, (vi - 1) * 8, v[1]) + writef32(uv, (vi - 1) * 8 + 4, v[2]) + lists[vi] = l + end + for _, ix in tris do + if ix < 0 or ix >= nv then + return nil, "triangle index out of range" + end + end + local ib = buffer.create(#tris * 4) + for i, ix in tris do + writeu32(ib, (i - 1) * 4, ix) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #joints > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(shader) + mat.metallic = 0 + table.insert(scene.textures, { name = shader, uri = shader }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" :: any, material = #scene.materials }) + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #joints > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + local byName: { [string]: number } = {} + for i, j in joints do + byName[j.name] = nodes[i] + end + scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives } + return scene, byName +end + +-- ------------------------------------------------------------------------------------------------ md5anim +type Anim = { + frameRate: number, + frames: number, + joints: { { name: string, parent: number } }, + base: { { number } }, -- per joint: px py pz qx qy qz + tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame +} + +-- anim(text) -> Anim | nil, message +function Read.anim(text: string): (Anim?, string?) + local L: Lexer = { text = text, pos = 1, err = nil } + local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } + local hier: { { number } } = {} -- flags, startIndex + local version: number? = nil + local nComp = 0 + local frames: { { number } } = {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numFrames" then + a.frames = num(L) + elseif t == "numJoints" then + num(L) + elseif t == "frameRate" then + a.frameRate = num(L) + elseif t == "numAnimatedComponents" then + nComp = num(L) + if nComp < 0 or nComp > 2 ^ 20 then + return nil, "bad numAnimatedComponents" + end + elseif t == "hierarchy" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad hierarchy line" + end + local parent, flags, start = num(L), num(L), num(L) + table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 }) + table.insert(hier, { flags, start }) + end + elseif t == "bounds" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" or s == nil then + break + end + end + elseif t == "baseframe" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if s ~= "(" then + return nil, "bad baseframe line" + end + L.pos -= 1 + local p, q = vec(L, 3), vec(L, 3) + table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] }) + end + elseif t == "frame" then + local fi = num(L) + expect(L, "{") + local vals = table.create(nComp, 0) + for k = 1, nComp do + vals[k] = num(L) + end + expect(L, "}") + if fi < 0 or fi > 2 ^ 20 then + return nil, "bad frame index" + end + frames[fi + 1] = vals + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version" + end + if #a.base ~= #a.joints then + return nil, "baseframe and hierarchy disagree" + end + for f = 1, a.frames do + if not frames[f] then + return nil, "missing frame " .. (f - 1) + end + end + for j, h in hier do + local tr: { number }, rot: { number } = {}, {} + local flags, start = h[1], h[2] + for f = 1, a.frames do + local v = table.clone(a.base[j]) + local k = start + 1 + for bit = 0, 5 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + v[bit + 1] = frames[f][k] or v[bit + 1] + k += 1 + end + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = quat(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + a.tracks[j] = { translation = tr, rotation = rot } + end + return a, nil +end + +-- addAnim(scene, nodes by joint name, anim, name) -> channels added +function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number + local nodes: { number } = {} + local tracks: { [number]: Rig.Track } = {} + for j, jt in a.joints do + local nd = byName[jt.name] + if nd then + table.insert(nodes, nd) + tracks[#nodes] = a.tracks[j] + end + end + local times: { number } = {} + local rate = if a.frameRate > 0 then a.frameRate else 24 + for f = 1, a.frames do + times[f] = (f - 1) / rate + end + local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR") + return #scene.animations[ai].channels +end + +-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation +function Read.animScene(a: Anim, name: string): Types.Scene + local scene = Scene.new() + scene.meta.up = "z" + table.insert(scene.nodes, { name = "md5", children = {} }) + scene.roots[1] = 1 + local list: { Rig.Joint } = {} + for j, jt in a.joints do + local b = a.base[j] + list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) } + end + local nodes = Rig.skeleton(scene, list, "local", 1) + local byName: { [string]: number } = {} + for j, jt in a.joints do + byName[jt.name] = nodes[j] + end + Read.addAnim(scene, byName, a, name) + scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate } + return scene +end + +return Read +end +__FILES["model/mdl"] = function() + +-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: +-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the +-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), +-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = +-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx +-- files) is UNSUPPORTED. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Quake = __include("model/mdl/Quake") +local HalfLife = __include("model/mdl/HalfLife") + +-- ------------------------------------------------------------------------------------------------ contract +local Mdl = { + name = "mdl", + category = "model", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey) + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + frame: number?, -- Quake: the frame used as the base POSITION (default 1) + morph: boolean?, -- Quake: frames as morph targets + animations (default true) + fps: number?, -- Quake: animation frame rate (default 10) + bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1) + textures: (buffer | string)?, -- Half-Life: the "t.mdl" texture file of a model without textures + maxPixels: number?, -- default 2^24 + maxVertices: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mdl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + local v = r:peekU8(4) + if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4) + local scene: Types.Scene?, msg: string? + if magic == "IDPO" then + if version ~= 6 then + return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4) + end + local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Quake.decode(r.buf, r.base, size, pal, opts :: any) + elseif magic == "IDST" then + if version ~= 10 then + return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4) + end + local o: any = opts and table.clone(opts :: any) or {} + o.textures = if opts and opts.textures then Bytes.toBuffer(opts.textures) else nil + scene, msg = HalfLife.decode(r.buf, r.base, size, o) + else + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +return Mdl +end +__FILES["model/mdl/HalfLife"] = function() + +-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h +-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. +-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> +-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans +-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = +-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> +-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). +-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone +-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "t.mdl" (pass it +-- as opts.textures = that file's bytes). +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local HalfLife = {} + +local Scene = Types.Scene +local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32 +local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16 + +type Bone = { name: string, parent: number, value: { number }, scale: { number } } +type Options = { bodies: { number }?, textures: buffer?, maxPixels: number?, maxVertices: number? } + +local function str(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message +local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string) + local n, at = readi32(b, base + 180), readi32(b, base + 184) + if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then + return nil, "bad texture table" + end + local out: { Types.Image } = {} + local names: { string } = {} + for i = 0, n - 1 do + local o = base + at + i * 80 + local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76) + if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then + return nil, "bad texture " .. i + end + local img = Types.Image.new(w, h) + local pal = Pixels.palette(b, base + data + w * h, 256) + Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal) + local flags = readi32(b, o + 64) + img.meta.source = { format = "mdl", flags = flags } + out[i + 1] = img + names[i + 1] = str(b, o, 64) + end + return out, names +end + +-- one animation value: bone default + stored value * scale (frame f, 0-based) +local function animValue(b: buffer, at: number, limit: number, f: number): number? + local p = at + local k = f + for _ = 1, 65536 do + if p + 2 > limit then + return nil + end + local valid, total = readu8(b, p), readu8(b, p + 1) + if total == 0 then + return nil + end + if total > k then + local idx = if valid > k then k + 1 else valid + if p + idx * 2 + 2 > limit then + return nil + end + return readi16(b, p + idx * 2) + end + k -= total + p += (valid + 1) * 2 + end + return nil +end + +-- decode(b, base, size, opts) -> Scene | nil, message +function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) + if size < 244 then + return nil, "truncated header" + end + local limit = base + size + local function hdr(o: number): number + return readi32(b, base + o) + end + local nBones, oBones = hdr(140), hdr(144) + local nSeq, oSeq = hdr(164), hdr(168) + local nTex = hdr(180) + local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200) + local nParts, oParts = hdr(204), hdr(208) + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then + return nil, "bad bone table" + end + if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then + return nil, "bad sequence table" + end + if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then + return nil, "bad body part table" + end + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + -- bones + local bones: { Bone } = {} + local joints: { Rig.Joint } = {} + for i = 0, nBones - 1 do + local o = base + oBones + i * 112 + local value, scale = {}, {} + for k = 0, 5 do + value[k + 1] = readf32(b, o + 64 + k * 4) + scale[k + 1] = readf32(b, o + 88 + k * 4) + end + local parent = readi32(b, o + 32) + bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale } + joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) } + end + local root: Types.Node = { name = str(b, base + 8, 64), children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) + -- textures and skins + local texSrc, texBase, texSize = b, base, size + if nTex == 0 and opts and opts.textures then + texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) + if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then + return nil, "opts.textures is not a studio texture file" + end + nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200) + end + local images, texNames = textures(texSrc, texBase, texSize, maxPixels) + if not images then + return nil, texNames :: string + end + local names = texNames :: { string } + for i, img in images do + table.insert(scene.textures, { name = names[i], image = img, uri = names[i] }) + local mat = Scene.material(names[i]) + mat.metallic = 0 + mat.baseColorTexture = { texture = i } + table.insert(scene.materials, mat) + end + local skinMap: { number } = {} + if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then + for r = 0, nSkinRef - 1 do + skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 + end + end + -- body parts + local totalVerts = 0 + for part = 0, nParts - 1 do + local po = base + oParts + part * 76 + local pname = str(b, po, 64) + local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72) + local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1 + if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then + local mo = base + oModels + (pick - 1) * 112 + local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76) + local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88) + local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100) + if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then + return nil, "body part " .. pname .. ": bad model tables" + end + local mesh: Types.Mesh = { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } } + for m = 0, nMesh - 1 do + local me = base + oMesh + m * 20 + local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8) + local tex = skinMap[skinref + 1] or (skinref + 1) + local img = images[tex] + local tw, th = if img then img.width else 1, if img then img.height else 1 + -- triangle commands + local weld: { [string]: number } = {} + local corners: { { number } } = {} + local indices: { number } = {} + local p = base + oTri + if oTri < 0 or oTri >= size then + return nil, "bad triangle command offset" + end + while true do + if p + 2 > limit then + return nil, "truncated triangle commands" + end + local n = readi16(b, p) + p += 2 + if n == 0 then + break + end + local fan = n < 0 + n = math.abs(n) + if p + n * 8 > limit then + return nil, "truncated triangle commands" + end + local ids: { number } = {} + for k = 0, n - 1 do + local o = p + k * 8 + local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6) + if vi >= nVerts or ni >= nNorms then + return nil, "triangle command vertex out of range" + end + local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t + local id = weld[key] + if not id then + table.insert(corners, { vi, ni, s, t }) + id = #corners - 1 + weld[key] = id + end + ids[k + 1] = id + end + p += n * 8 + for k = 3, n do + local a, c2, c3 + if fan then + a, c2, c3 = ids[1], ids[k - 1], ids[k] + elseif k % 2 == 1 then + a, c2, c3 = ids[k - 2], ids[k - 1], ids[k] + else + a, c2, c3 = ids[k - 1], ids[k - 2], ids[k] + end + -- studio models wind clockwise: reverse + table.insert(indices, c3) + table.insert(indices, c2) + table.insert(indices, a) + end + end + local nv = #corners + totalVerts += nv + if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for i, c in corners do + local o = (i - 1) * 12 + local bone = readu8(b, base + oVertInfo + c[1]) + local nbone = readu8(b, base + oNormInfo + c[2]) + local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12 + local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8) + local m4 = world[bone + 1] + if m4 then + x, y, z = Mat4.point(m4, x, y, z) + end + writef32(pos, o, x) + writef32(pos, o + 4, y) + writef32(pos, o + 8, z) + local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8) + local n4 = world[nbone + 1] + if n4 then + nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz + end + writef32(nrm, o, nx) + writef32(nrm, o + 4, ny) + writef32(nrm, o + 8, nz) + writef32(uv, (i - 1) * 8, c[3] / tw) + writef32(uv, (i - 1) * 8 + 4, c[4] / th) + writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1))) + writef32(wb, (i - 1) * 16, 1) + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if nBones > 0 then + attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv) + end + table.insert(mesh.primitives, { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles" :: any, + material = if img then tex else nil, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = if nBones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + end + -- sequences + local seqs: { any } = {} + for s = 0, nSeq - 1 do + local so = base + oSeq + s * 176 + local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56) + local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156) + table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group }) + if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then + local rate = if fps > 0 then fps else 30 + local times: { number } = {} + for f = 0, nFrames - 1 do + times[f + 1] = f / rate + end + local tracks: { [number]: Rig.Track } = {} + for j = 1, nBones do + local bn = bones[j] + local ao = base + oAnim + (j - 1) * 12 + local tr, rot = {}, {} + for f = 0, nFrames - 1 do + local v: { number } = {} + for k = 0, 5 do + local off = readu16(b, ao + k * 2) + local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil + v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for k = 1, 4 do + table.insert(rot, q[k]) + end + end + tracks[j] = { translation = tr, rotation = rot } + end + Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR") + end + end + scene.meta.source = { + format = "mdl", + variant = "halflife", + name = root.name, + bones = nBones, + sequences = seqs, + textures = #images, + skinFamilies = nFamilies, + hitboxes = hdr(156), + attachments = hdr(212), + } + return scene, nil +end + +return HalfLife +end +__FILES["model/mdl/Quake"] = function() + +-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et +-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. +-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; +-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per +-- side); simple and grouped frames become morph targets with one animation per frame-name group. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local Quake = {} + +local Scene = Types.Scene +local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32 + +type Options = { frame: number?, morph: boolean?, fps: number?, maxVertices: number?, maxPixels: number? } + +local function name16(b: buffer, at: number): string + return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string +end + +-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) +function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?) + if size < 84 then + return nil, "truncated header" + end + local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) } + local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) } + local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56) + local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68) + if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then + return nil, "bad counts" + end + if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: skin too big" + end + if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local p = 84 + local function need(n: number): boolean + return n >= 0 and p + n <= size + end + -- skins + local pal = if palette then Pixels.palette(palette, 0, 256) else nil + local skins: { Types.Image } = {} + local px = sw * sh + for _ = 1, nSkins do + if not need(4) then + return nil, "truncated skins" + end + local group = readi32(b, base + p) + p += 4 + local count = 1 + if group ~= 0 then + if not need(4) then + return nil, "truncated skin group" + end + count = readi32(b, base + p) + p += 4 + if count <= 0 or count > 256 or not need(count * 4) then + return nil, "bad skin group" + end + p += count * 4 + end + if not need(count * px) then + return nil, "truncated skin pixels" + end + local img = Types.Image.new(sw, sh) + if pal then + Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal) + else + for i = 0, px - 1 do + local v = readu8(b, base + p + i) + writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101) + end + end + img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count } + table.insert(skins, img) + p += count * px + end + -- texture coordinates and triangles + if not need(nVerts * 12 + nTris * 16) then + return nil, "truncated vertices / triangles" + end + local stAt = p + p += nVerts * 12 + local weld: { [number]: number } = {} + local src: { number }, uvs: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + p + t * 16 + local front = readi32(b, o) ~= 0 + local c: { number } = {} + for k = 1, 3 do + local v = readi32(b, o + k * 4) + if v < 0 or v >= nVerts then + return nil, "triangle vertex out of range" + end + local so = base + stAt + v * 12 + local seam = readi32(b, so) ~= 0 and not front + local key = v * 2 + (if seam then 1 else 0) + local id = weld[key] + if not id then + table.insert(src, v) + local s = readi32(b, so + 4) + (if seam then sw / 2 else 0) + table.insert(uvs, (s + 0.5) / math.max(sw, 1)) + table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1)) + id = #src - 1 + weld[key] = id + end + c[k] = id + end + -- Quake's front faces are clockwise + table.insert(indices, c[3]) + table.insert(indices, c[2]) + table.insert(indices, c[1]) + end + p += nTris * 16 + -- frames: simple (type 0) or groups of simple frames + local frameAt: { number } = {} + local names: { string } = {} + local fsize = 24 + nVerts * 4 + for _ = 1, nFrames do + if not need(4) then + return nil, "truncated frames" + end + local kind = readi32(b, base + p) + p += 4 + if kind == 0 then + if not need(fsize) then + return nil, "truncated frame" + end + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + else + if not need(12) then + return nil, "truncated frame group" + end + local count = readi32(b, base + p) + if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then + return nil, "bad frame group" + end + p += 12 + count * 4 + for _ = 1, count do + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p += fsize + end + end + end + local nv = #src + local total = #frameAt + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total) + local positions: { buffer }, normals: { buffer } = {}, {} + for f, at in frameAt do + if morph or f == want then + local pos = buffer.create(nv * 12) + local vo = base + at + 16 + for i, v in src do + for k = 0, 2 do + writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1]) + end + end + positions[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local uvb = buffer.create(nv * 8) + for i, v in uvs do + writef32(uvb, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(positions[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + for i, img in skins do + table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" :: any } }) + end + if #skins > 0 then + local mat = Scene.material("skin") + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + scene.materials[1] = mat + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + Rig.morph(prim, positions, normals) + scene.meshes[1].weights = table.create(total, 0) + local ranges: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)%d*$") or n + local last = ranges[#ranges] + if last and last.name == stem then + last.last = i + else + table.insert(ranges, { name = if stem ~= "" then stem else n, first = i, last = i, fps = opts and opts.fps or 10 }) + end + end + Rig.morphAnimation(scene, 1, total, ranges, "LINEAR") + end + scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil } + return scene, nil +end + +return Quake +end +__FILES["model/ms3d"] = function() + +-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of +-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested +-- against (no code ported). +-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and +-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in +-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; +-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use +-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse +-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes +-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, +-- the model comment / fps / frames / joint size in meta.source. meta.up = "y". +-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), +-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 +-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/ms3d/Read") +local Write = __include("model/ms3d/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ms3d = { + name = "ms3d", + category = "model", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- refuse more triangle corners (default 2^20) +} +type EncodeOptions = { + fps: number?, -- the animation's frames per second (default: the source's, else 24) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ms3d.sniff(r: Bytes.Reader): number + local h = r:peek(14) + if string.sub(h, 1, 10) ~= Read.MAGIC then + return 0 + end + local v = string.byte(h, 11) + return if v == 3 or v == 4 then 1 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, at) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ms3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return Ms3d +end +__FILES["model/ms3d/Read"] = function() + +-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h +-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a +-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess +-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and +-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds +-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), +-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), +-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). +-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices +-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + +-- key positions). Never throws on bad data: returns nil, message, offset. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +local S = Types.Scene +local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring +local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32 + +Read.MAGIC = "MS3D000000" + +type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ helpers +local function fixed(b: buffer, p: number, n: number): string + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function floats(values: { number }, comps: number): Types.Accessor + local n = #values // comps + local a = S.accessor(nil, "f32", comps, n) + for i = 1, n * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +local function color(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) } +end + +-- the texture file name as a relative uri (MilkShape writes ".\name.jpg") +local function uri(s: string): string + local u = string.gsub(s, "\\", "/") + u = string.gsub(u, "^%./", "") + return u +end + +-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion +local function euler(x: number, y: number, z: number): { number } + return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) +end + +-- ------------------------------------------------------------------------------------------------ parse +type Vertex = { pos: { number }, bones: { number }, weights: { number } } +type Joint = { + name: string, parent: string, flags: number, rot: { number }, pos: { number }, + rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, +} + +-- scene(b, base, limit, opts) -> Scene | nil, message, offset +function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) + local p = base + local function need(n: number): boolean + return p + n <= limit + end + if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then + return nil, "not a MilkShape 3D file", base + end + local version = readi32(b, p + 10) + if version ~= 3 and version ~= 4 then + return nil, "unsupported: version " .. version, p + 10 + end + p += 14 + local maxV = opts and opts.maxVertices or 2 ^ 20 + -- vertices + if not need(2) then + return nil, "truncated vertex count", p + end + local nv = readu16(b, p) + p += 2 + if not need(nv * 15) then + return nil, "truncated vertices", p + end + local verts: { Vertex } = {} + for i = 1, nv do + local q = p + (i - 1) * 15 + verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } + end + p += nv * 15 + -- triangles + if not need(2) then + return nil, "truncated triangle count", p + end + local nt = readu16(b, p) + p += 2 + if not need(nt * 70) then + return nil, "truncated triangles", p + end + if nt * 3 > maxV then + return nil, "limit: more than " .. maxV .. " triangle corners", p + end + local triAt = p + p += nt * 70 + -- groups + if not need(2) then + return nil, "truncated group count", p + end + local ng = readu16(b, p) + p += 2 + local groups = {} + for _ = 1, ng do + if not need(35) then + return nil, "truncated group", p + end + local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? } + local n = readu16(b, p + 33) + p += 35 + if not need(n * 2 + 1) then + return nil, "truncated group triangles", p + end + for k = 0, n - 1 do + local ti = readu16(b, p + k * 2) + if ti >= nt then + return nil, "group triangle " .. ti .. " out of range", p + k * 2 + end + table.insert(g.tris, ti) + end + p += n * 2 + g.material = readi8(b, p) + p += 1 + table.insert(groups, g) + end + -- materials + if not need(2) then + return nil, "truncated material count", p + end + local nm = readu16(b, p) + p += 2 + if not need(nm * 361) then + return nil, "truncated materials", p + end + local mats = {} + for i = 0, nm - 1 do + local q = p + i * 361 + table.insert(mats, { + name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64), + emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100), + mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?, + }) + end + p += nm * 361 + -- animation header and joints (version 3 files may end here) + local fps, current, frames = 24, 0, 0 + local joints: { Joint } = {} + if need(12) then + fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8) + p += 12 + if not need(2) then + return nil, "truncated joint count", p + end + local nj = readu16(b, p) + p += 2 + for _ = 1, nj do + if not need(93) then + return nil, "truncated joint", p + end + local j: Joint = { + flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32), + rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) }, + pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) }, + rotKeys = {}, posKeys = {}, + } + local nr, np = readu16(b, p + 89), readu16(b, p + 91) + p += 93 + if not need((nr + np) * 16) then + return nil, "truncated joint keys", p + end + for k = 0, nr + np - 1 do + local q = p + k * 16 + local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) } + table.insert(if k < nr then j.rotKeys else j.posKeys, key) + end + p += (nr + np) * 16 + table.insert(joints, j) + end + end + -- sub-versioned blocks + local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } + local function comments(list: { any }): string? + if not need(4) then + return "truncated comments" + end + local n = readi32(b, p) + p += 4 + for _ = 1, math.max(n, 0) do + if not need(8) then + return "truncated comment" + end + local index, len = readi32(b, p), readi32(b, p + 4) + p += 8 + if len < 0 or not need(len) then + return "comment runs past the end" + end + if list[index + 1] then + list[index + 1].comment = readstring(b, p, len) + end + p += len + end + return nil + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.commentVersion = sub + if sub == 1 then + for _, list in { groups, mats, joints } :: { { any } } do + local e = comments(list) + if e then + return nil, e, p + end + end + if not need(4) then + return nil, "truncated model comment", p + end + local has = readi32(b, p) + p += 4 + if has ~= 0 then + if not need(4) then + return nil, "truncated model comment", p + end + local len = readi32(b, p) + p += 4 + if len < 0 or not need(len) then + return nil, "model comment runs past the end", p + end + source.comment = readstring(b, p, len) + p += len + end + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.vertexVersion = sub + local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0 + if size > 0 and need(nv * size) then + for i = 1, nv do + local q = p + (i - 1) * size + local v = verts[i] + local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5) + if w0 + w1 + w2 > 0 then + local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100 + v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) } + v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) } + end + end + p += nv * size + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + if (sub == 1 or sub == 2) and need(#joints * 12) then + for _, j in joints do + j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } + p += 12 + end + end + end + if need(16) and readi32(b, p) >= 1 then + source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12) + end + return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil +end + +-- ------------------------------------------------------------------------------------------------ build +function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene + local scene = S.new() + scene.meta.up = "y" + scene.meta.source = source :: any + -- materials, textures + for _, m in mats do + local mat = S.material(m.name) + local d = m.diffuse + mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) } + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1) + mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] } + mat.alphaMode = if m.transparency < 1 then "blend" else "opaque" + if m.texture ~= "" then + local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) } + table.insert(scene.textures, tex) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { + ms3d = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess, + transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment, + }, + } + table.insert(scene.materials, mat) + end + -- joints: nodes, rest pose, skin + local nj = #joints + local jointNode: { [number]: number } = {} + local byName: { [string]: number } = {} + local abs: { { number } } = {} + for i, j in joints do + local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) } + node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } } + table.insert(scene.nodes, node) + jointNode[i] = #scene.nodes + if byName[j.name] == nil then + byName[j.name] = i + end + end + for i, j in joints do + local pi = byName[j.parent] + -- parents must come first (MilkShape writes them in that order); others become roots + local local_ = S.nodeMatrix(scene.nodes[jointNode[i]]) + if pi and pi < i then + table.insert(scene.nodes[jointNode[pi]].children, jointNode[i]) + abs[i] = S.mul(abs[pi], local_) + else + table.insert(scene.roots, jointNode[i]) + abs[i] = local_ + end + end + local skinned = false + for _, v in verts do + for k = 1, 4 do + if v.bones[k] >= nj then + v.bones[k] = -1 + end + end + skinned = skinned or (nj > 0 and v.bones[1] >= 0) + end + if nj > 0 then + local ibm = S.accessor(nil, "f32", 16, nj) + ibm.matrix = true + for i = 1, nj do + local inv = Mat4.inverse(abs[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local list = table.create(nj, 0) + for i = 1, nj do + list[i] = jointNode[i] + end + scene.skins[1] = { joints = list, inverseBindMatrices = ibm } + end + -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner + local nv = #verts + for gi, g in groups do + local remap: { [string]: number } = {} + local P, N, U, J, W = {}, {}, {}, {}, {} + local idx: { number } = {} + local sgs: { number } = {} + local count = 0 + for _, ti in g.tris do + local q = triAt + ti * 70 + -- a triangle with an out-of-range vertex is dropped + if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then + continue + end + table.insert(sgs, readu8(b, q + 68)) + for k = 0, 2 do + local vi = readu16(b, q + 2 + k * 2) + local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4) + local o = remap[key] + if o == nil then + o = count + count += 1 + remap[key] = o + local v = verts[vi + 1] + table.move(v.pos, 1, 3, o * 3 + 1, P) + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) + U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) + -- influences: the valid bones, weights normalized + local sum = 0 + for c = 1, 4 do + if v.bones[c] >= 0 then + sum += v.weights[c] + end + end + for c = 1, 4 do + local ok = v.bones[c] >= 0 and sum > 0 + J[o * 4 + c] = if ok then v.bones[c] else 0 + W[o * 4 + c] = if ok then v.weights[c] / sum else 0 + end + end + table.insert(idx, o :: number) + end + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) }, + mode = "triangles", + material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil, + extras = { ms3d = { smoothing = sgs } }, + } + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + prim.indices = ind + local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } } + if skinned then + local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count) + for i = 1, count * 4 do + if nj > 255 then + writeu16(ja.data, (i - 1) * 2, J[i]) + else + writeu8(ja.data, i - 1, J[i]) + end + end + prim.attributes.JOINTS_0 = ja + prim.attributes.WEIGHTS_0 = floats(W, 4) + node.skin = 1 + end + local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } } + scene.meshes[gi] = mesh + node.mesh = gi + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- the animation: rest * key rotations, rest + key positions + local channels: { Types.Channel } = {} + for i, j in joints do + if #j.rotKeys > 0 then + local times, vals = {}, {} + local rest = scene.nodes[jointNode[i]].rotation :: { number } + for _, k in j.rotKeys do + table.insert(times, k[1]) + local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4])))) + table.move(q, 1, 4, #vals + 1, vals) + end + local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" } + table.insert(channels, ch) + end + if #j.posKeys > 0 then + local times, vals = {}, {} + for _, k in j.posKeys do + table.insert(times, k[1]) + table.insert(vals, j.pos[1] + k[2]) + table.insert(vals, j.pos[2] + k[3]) + table.insert(vals, j.pos[3] + k[4]) + end + local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" } + table.insert(channels, ch) + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "ms3d", channels = channels }) + end + return scene +end + +return Read +end +__FILES["model/ms3d/Write"] = function() + +-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, +-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first +-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); +-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each +-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's +-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: +-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and +-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), +-- joint colours and model extras are written in their sub-versioned blocks. +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + +local S = Types.Scene +local sqrt = math.sqrt + +type Options = { fps: number?, name: string?, files: { [string]: any }? } + +local function fixedString(w: Bytes.Writer, s: string, n: number) + local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1) + w:string(v) + for _ = #v + 1, n do + w:u8(0) + end +end + +local function msg(s: any): string + return if type(s) == "string" then s else "" +end + +-- ------------------------------------------------------------------------------------------------ tree +type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } } +local function tree(scene: Types.Scene): Tree + local t: Tree = { world = {}, parent = {}, order = {} } + local function visit(i: number, p: number, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or t.world[i] or depth > 256 then + return + end + t.world[i] = S.mul(pm, S.nodeMatrix(n)) + t.parent[i] = p + table.insert(t.order, i) + for _, c in n.children or {} do + visit(c, i, t.world[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, 0, S.IDENTITY, 0) + end + return t +end + +-- ------------------------------------------------------------------------------------------------ joints +type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } + +-- the rigid part (rotation and translation) of a matrix +local function rigid(m: { number }): { number } + local t, r = Mat4.decompose(m) + return Mat4.compose(t, r, nil) +end + +-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; +-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices +local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) + local skin = scene.skins[1] + local anim = scene.animations[1] + local out: { Joint } = {} + local bySkin: { [number]: number } = {} + local byNode: { [number]: number } = {} + local skinIndex: { [number]: number } = {} + local isJoint: { [number]: boolean } = {} + for k, ni in (if skin then skin.joints else {}) :: { number } do + skinIndex[ni] = k - 1 + isJoint[ni] = true + end + local chans: { [number]: { Types.Channel } } = {} + for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do + if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then + isJoint[ch.node] = true + chans[ch.node] = chans[ch.node] or {} + table.insert(chans[ch.node], ch) + end + end + -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix + local B = S.IDENTITY + local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil + if skin and IBM and tr.world[skin.joints[1]] then + local m = table.create(16, 0) + for c = 1, 16 do + m[c] = (IBM :: any)(0, c - 1) + end + B = S.mul(tr.world[skin.joints[1]], m) + end + local names: { [string]: boolean } = {} + for _, ni in tr.order do + if not isJoint[ni] or #out >= 127 then + continue + end + local p = tr.parent[ni] + while p ~= 0 and byNode[p] == nil do + p = tr.parent[p] + end + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the + -- joint and its joint parent (C) carry over to the keys + local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() + local gp = tr.parent[ni] + local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) + local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni]))) + local e = Mat4.eulerXYZ(r) + local base = string.sub(msg(scene.nodes[ni].name), 1, 27) + local name = if base ~= "" then base else "joint" .. #out + local n = 1 + while names[name] do + n += 1 + name = base .. "_" .. n + end + names[name] = true + local j: Joint = { + node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t, + rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {}, + } + table.insert(out, j) + byNode[ni] = #out - 1 + if skinIndex[ni] then + bySkin[skinIndex[ni]] = #out - 1 + end + -- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest + local _, rc = Mat4.decompose(C) + local inv = Mat4.transpose3(Mat4.fromQuat(r)) + for _, ch in chans[ni] or {} do + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + for k = 0, ch.input.count - 1 do + local v = if cubic then k * 3 + 1 else k + local time = IN(k, 0) + if ch.path == "rotation" then + local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) } + local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 } + local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q))))) + table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) }) + else + local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2)) + table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] }) + end + end + end + end + return out, bySkin, byNode, B +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } } +type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } +type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } + +-- every placed primitive as a group: vertices, triangles; or nil, message +local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) + local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} + for _, pl in S.flatten(scene) do + local prim: any = pl.primitive + local node = scene.nodes[pl.node] + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean + return false + end, { triangulate = true }) + if not merged then + return verts, tris, groups, err + end + local corners = merged.corners + if #corners == 0 then + continue + end + local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil + -- a rigid mesh follows its nearest joint + local rigid = -1 + if not skinned then + local p = pl.node + while p and p ~= 0 do + if byNode[p] then + rigid = byNode[p] + break + end + p = tr.parent[p] + end + end + local M = if skinned then B else pl.matrix + local NM = Mat4.normalMatrix(M) + local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0 + local A = prim.attributes + local POS = S.reader(A.POSITION) :: any + local zero = function(_: number, _: number): number + return 0 + end + type Get = (number, number) -> number + local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil + local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero + local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero + local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero + local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero + local base = #verts + local nv = A.POSITION.count + if base + nv > 65535 then + return verts, tris, groups, "more than 65535 vertices" + end + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2)) + local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 } + if skinned then + local inf = {} + for c = 0, 3 do + local w = WE(v, c) + local j = bySkin[JO(v, c)] + if w > 0 and j then + table.insert(inf, { j, w }) + end + end + table.sort(inf, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, e in inf do + sum += e[2] + end + for c = 1, 4 do + local e = inf[c] + bones[c] = if e then e[1] else -1 + weights[c] = if e and sum > 0 then e[2] / sum else 0 + end + end + table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights }) + end + local gi = #groups + if gi >= 255 then + return verts, tris, groups, "more than 255 groups" + end + local name = msg(node.name) + if name == "" then + name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name) + end + local x = node.extras and node.extras.ms3d + local g: Group = { + name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0, + material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1, + comment = x and x.comment, + } + local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing + if type(saved) ~= "table" or #saved ~= #corners // 3 then + saved = nil + end + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if mirror then + b, c = c, b + end + local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } + -- the face normal for primitives without normals + local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] + local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z + local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z + local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + local nx, ny, nz = fx, fy, fz + if hasN then + local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2) + nx = NM[1] * ox + NM[5] * oy + NM[9] * oz + ny = NM[2] * ox + NM[6] * oy + NM[10] * oz + nz = NM[3] * ox + NM[7] * oy + NM[11] * oz + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n) + table.insert(t.uv, UV(v, 0)) + table.insert(t.uv, UV(v, 1)) + end + table.insert(tris, t) + table.insert(g.tris, #tris - 1) + end + if #tris > 65535 then + return verts, tris, groups, "more than 65535 triangles" + end + table.insert(groups, g) + end + return verts, tris, groups, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local tr = tree(scene) + local js, bySkin, byNode, B = joints(scene, tr) + local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B) + if gerr then + return nil, gerr + end + if #scene.materials > 127 then + return nil, "more than 127 materials" + end + local src: any = scene.meta.source + local fromMs3d = src ~= nil and src.format == "ms3d" + local w = Bytes.writer(65536) + w:string("MS3D000000") + w:u32le(4) + w:u16le(#verts) + for _, v in verts do + w:u8(0) + w:f32le(v.x) + w:f32le(v.y) + w:f32le(v.z) + w:i8(v.bones[1] % 256) + w:u8(1) + end + w:u16le(#tris) + for _, t in tris do + w:u16le(0) + for k = 1, 3 do + w:u16le(t.v[k]) + end + for k = 1, 9 do + w:f32le(t.n[k]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2 - 1]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2]) + end + w:u8(math.clamp(t.sg, 0, 255)) + w:u8(t.group) + end + w:u16le(#groups) + for _, g in groups do + w:u8(g.flags % 256) + fixedString(w, g.name, 32) + w:u16le(#g.tris) + for _, ti in g.tris do + w:u16le(ti) + end + w:i8(g.material % 256) + end + -- materials + w:u16le(#scene.materials) + local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" + for i, m in scene.materials do + local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32) + local e = m.emissive or { 0, 0, 0 } + for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do + for k = 1, 4 do + w:f32le(c[k] or 1) + end + end + local r = math.max(m.roughness or 1, 0.1) + w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128)) + w:f32le(bc[4] or 1) + w:i8((tonumber(x.mode) or 0) % 256) + local file = "" + local ref: any = m.baseColorTexture + local tex: any = ref and scene.textures[ref.texture] + if tex then + file = tex.uri or "" + if file == "" or string.sub(file, 1, 5) == "data:" then + file = base .. "_" .. ref.texture .. ".png" + if o.files and tex.data then + o.files[file] = tex.data + end + end + end + fixedString(w, file, 128) + fixedString(w, msg(x.alphamap), 128) + end + -- the animation header and joints + local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) + local last = 0 + for _, j in js do + for _, k in j.rotKeys do + last = math.max(last, k[1]) + end + for _, k in j.posKeys do + last = math.max(last, k[1]) + end + end + w:f32le(fps) + w:f32le(0) + w:u32le(math.max(1, math.ceil(last * fps))) + w:u16le(#js) + for _, j in js do + local x = scene.nodes[j.node].extras + local jx = x and x.ms3d + w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0) + fixedString(w, j.name, 32) + fixedString(w, j.parent, 32) + for k = 1, 3 do + w:f32le(j.rot[k]) + end + for k = 1, 3 do + w:f32le(j.pos[k]) + end + w:u16le(#j.rotKeys) + w:u16le(#j.posKeys) + for _, list in { j.rotKeys, j.posKeys } do + for _, k in list do + for c = 1, 4 do + w:f32le(k[c]) + end + end + end + end + -- comments + w:u32le(1) + local function comments(list: { any }, get: (any) -> string?) + local found = {} + for i, item in list do + local c = get(item) + if type(c) == "string" and c ~= "" then + table.insert(found, { i - 1, c }) + end + end + w:u32le(#found) + for _, f in found do + w:u32le(f[1]) + w:u32le(#f[2]) + w:string(f[2]) + end + end + comments(groups, function(g: any): string? + return g.comment + end) + comments(scene.materials, function(m: any): string? + return m.extras and m.extras.ms3d and m.extras.ms3d.comment + end) + comments(js, function(j: any): string? + local x: any = scene.nodes[j.node].extras + return x and x.ms3d and x.ms3d.comment + end) + local mc = if fromMs3d then msg(src.comment) else "" + w:u32le(if mc ~= "" then 1 else 0) + if mc ~= "" then + w:u32le(#mc) + w:string(mc) + end + -- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32 + w:u32le(2) + for _, v in verts do + local p = table.create(3, 0) + local left = 100 + for c = 1, 3 do + p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left) + left -= p[c] + end + if v.bones[2] < 0 and v.bones[1] >= 0 then + p = { 100, 0, 0 } + end + for c = 2, 4 do + w:i8(v.bones[c] % 256) + end + for c = 1, 3 do + w:u8(p[c]) + end + w:u32le(0) + end + -- joint colours, model extras + w:u32le(1) + for _, j in js do + local x: any = scene.nodes[j.node].extras + local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 } + for k = 1, 3 do + w:f32le(c[k] or 1) + end + end + w:u32le(1) + w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1) + w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0) + w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/obj"] = function() + +-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp +-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form +-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR +-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line +-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", +-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false +-- keeps OBJ's). +-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. +-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. +-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups +-- (s: kept per node in extras.obj.smoothing, not used to compute normals). +-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to +-- opts.files[.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mtl = __include("model/obj/Mtl") + +-- ------------------------------------------------------------------------------------------------ contract +local Obj = { + name = "obj", + category = "model", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + mtl: (string | buffer)?, -- the material library text, when not found through resolve / files + resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the other files by name + maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25) +} +type EncodeOptions = { + name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl") + mtlName: string?, -- the .mtl file name (overrides name) + files: { [string]: any }?, -- receives the .mtl and embedded textures + flipV: boolean?, -- default true (the inverse of decode) + normals: boolean?, -- write vn (default true when the primitives have NORMAL) + texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0) + colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Obj.sniff(r: Bytes.Reader): number + local head = r:peek(512) + if string.find(head, "\0", 1, true) then + return 0 + end + if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then + return 0.6 + end + if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts: DecodeOptions?, uri: string): string? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "buffer" then + return buffer.tostring(v) + elseif type(v) == "string" then + return v + end + return nil +end + +type Prim = { + material: string?, + mode: string, + cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none) + ct: { number }, + cn: { number }, + faces: { number }, -- corners per face (polygons / lines) + hasT: boolean, + hasN: boolean, +} +type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? } + +function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local maxV = opts and opts.maxVertices or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local P, C, UV, N = {}, {}, {}, {} + local np, nt, nn = 0, 0, 0 + local hasColor = false + local sections: { Section } = {} + local byName: { [string]: Section } = {} + local cur: Section? = nil + local object: string? = nil + local group: string? = nil + local material: string? = nil + local smoothing: string? = nil + local mtllibs: { string } = {} + local skipped = 0 + local corners = 0 + local hasObjects = false + local lineNo = 0 + local pos = 1 + local len = #text + local function section(): Section + if cur then + return cur + end + local key = (object or "") .. "\0" .. (group or "") + local s = byName[key] + if not s then + s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing } + byName[key] = s + table.insert(sections, s) + end + cur = s + return s + end + local function prim(mode: string): Prim + local s = section() + local key = mode .. "\0" .. (material or "") + local p = s.byKey[key] + if not p then + p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false } + s.byKey[key] = p + table.insert(s.prims, p) + end + return p + end + -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil + local function corner(tok: string): (number?, number, number) + local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") + local vi = tonumber(a) + if not vi then + return nil, -1, -1 + end + vi = if vi < 0 then np + vi else vi - 1 + local ti, ni = -1, -1 + local t = tonumber(b) + if t then + ti = if t < 0 then nt + t else t - 1 + if ti < 0 or ti >= nt then + return nil, -1, -1 + end + end + local n = tonumber(c) + if n then + ni = if n < 0 then nn + n else n - 1 + if ni < 0 or ni >= nn then + return nil, -1, -1 + end + end + if vi < 0 or vi >= np then + return nil, -1, -1 + end + return vi, ti, ni + end + local fs: { string } = {} + while pos <= len do + local e = string.find(text, "\n", pos, true) or (len + 1) + local line = string.sub(text, pos, e - 1) + pos = e + 1 + lineNo += 1 + -- continuation lines + while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do + line = string.gsub(line, "\\\r?$", " ") + local e2 = string.find(text, "\n", pos, true) or (len + 1) + line ..= string.sub(text, pos, e2 - 1) + pos = e2 + 1 + lineNo += 1 + end + local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$") + if key == nil or string.sub(key, 1, 1) == "#" then + continue + end + local rest: string = rest :: string -- both captures match together + local hash = string.find(rest, "#", 1, true) + if hash then + rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") + end + if key == "v" then + local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo) + end + if np >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices") + end + P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz + local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c) + if cr and cg and cb then + hasColor = true + C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb + end + np += 1 + elseif key == "vt" then + local u, v = string.match(rest, "^(%S+)%s*(%S*)") + local fu = tonumber(u) + if not fu then + return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo) + end + if nt >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates") + end + local fv = tonumber(v) or 0 + UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv + nt += 1 + elseif key == "vn" then + local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo) + end + if nn >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals") + end + N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz + nn += 1 + elseif key == "f" or key == "l" or key == "p" then + table.clear(fs) + for tok in string.gmatch(rest, "%S+") do + table.insert(fs, tok) + end + local k = #fs + local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points" + if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then + return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo) + end + corners += k + if corners > maxV * 4 then + return nil, Err.new(Err.LIMIT, "too many face corners") + end + local p = prim(mode) + local base = #p.cv + for i, tok in fs do + local vi, ti, ni = corner(tok) + if not vi then + return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo) + end + p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni + if ti >= 0 then + p.hasT = true + end + if ni >= 0 then + p.hasN = true + end + end + if mode == "triangles" and k > 3 then + -- fan: rewrite the k corners as (k - 2) triangles + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 2, k - 1 do + for _, j in { 1, a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "lines" then + -- a polyline -> segments + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 1, k - 1 do + for _, j in { a, a + 1 } do + o += 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "polygons" then + table.insert(p.faces, k) + end + elseif key == "o" then + object = rest + group = nil + hasObjects = true + cur = nil + elseif key == "g" then + group = if rest == "" then nil else rest + cur = nil + elseif key == "usemtl" then + material = rest + elseif key == "mtllib" then + table.insert(mtllibs, rest) + elseif key == "s" then + smoothing = rest + if cur then + cur.smoothing = cur.smoothing or rest + end + else + skipped += 1 + end + end + -- materials + local scene = Types.Scene.new() + local matIndex: { [string]: number } = {} + local texIndex: { [string]: number } = {} + local function texture(map: Mtl.Map): number + local file = string.gsub(map.file, "\\", "/") + local i = texIndex[file] + if i then + return i + end + local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) } + local data = fetch(opts, file) + if data then + tex.data = buffer.fromstring(data) + end + if map.options.clamp and map.options.clamp[1] == "on" then + tex.sampler = { wrapS = "clamp", wrapT = "clamp" } + end + table.insert(scene.textures, tex) + i = #scene.textures + texIndex[file] = i + return i + end + local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil + local missing: { string } = {} + local libs: { string } = {} + if mtlText then + table.insert(libs, mtlText :: string) + end + for _, lib in mtllibs do + local t = fetch(opts, lib) + if t then + table.insert(libs, t) + elseif not mtlText then + table.insert(missing, lib) + end + end + for _, lt in libs do + for _, e in Mtl.parse(lt) do + if not matIndex[e.name] then + table.insert(scene.materials, Mtl.toMaterial(e, texture)) + matIndex[e.name] = #scene.materials + end + end + end + -- materials named by usemtl but not defined anywhere: a default one with the name + for _, s in sections do + for _, p in s.prims do + if p.material and not matIndex[p.material] then + table.insert(scene.materials, Types.Scene.material(p.material)) + scene.materials[#scene.materials].metallic = 0 + matIndex[p.material] = #scene.materials + end + end + end + -- vertices: one per distinct (v, vt, vn) in each primitive + local f32 = buffer.writef32 + local KT, KN = nt + 1, nn + 1 + local numericKeys = np * KT * KN < 2 ^ 52 + local function build(p: Prim): Types.Primitive + local n = #p.cv + local map: { [any]: number } = {} + local verts: { number } = {} + local idx = buffer.create(n * 4) + local count = 0 + for i = 1, n do + local v, t, nr = p.cv[i], p.ct[i], p.cn[i] + local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr) + local k = map[key] + if k == nil then + k = count + map[key] = k + count += 1 + verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr + end + buffer.writeu32(idx, (i - 1) * 4, k) + end + local pb = buffer.create(count * 12) + local tb = if p.hasT then buffer.create(count * 8) else nil + local nb = if p.hasN then buffer.create(count * 12) else nil + local cb = if hasColor then buffer.create(count * 12) else nil + for k = 0, count - 1 do + local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3] + f32(pb, k * 12, P[v * 3 + 1]) + f32(pb, k * 12 + 4, P[v * 3 + 2]) + f32(pb, k * 12 + 8, P[v * 3 + 3]) + if tb and t >= 0 then + f32(tb, k * 8, UV[t * 2 + 1]) + f32(tb, k * 8 + 4, UV[t * 2 + 2]) + end + if nb and nr >= 0 then + f32(nb, k * 12, N[nr * 3 + 1]) + f32(nb, k * 12 + 4, N[nr * 3 + 2]) + f32(nb, k * 12 + 8, N[nr * 3 + 3]) + end + if cb then + f32(cb, k * 12, C[v * 3 + 1] or 1) + f32(cb, k * 12 + 4, C[v * 3 + 2] or 1) + f32(cb, k * 12 + 8, C[v * 3 + 3] or 1) + end + end + local A = Types.Scene.accessor + local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) } + if tb then + attrs.TEXCOORD_0 = A(tb, "f32", 2, count) + end + if nb then + attrs.NORMAL = A(nb, "f32", 3, count) + end + if cb then + attrs.COLOR_0 = A(cb, "f32", 3, count) + end + local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil } + if p.mode == "points" then + out.indices = if count == n then nil else out.indices + end + if p.mode == "polygons" then + local fb = buffer.create(#p.faces * 4) + for i, k in p.faces do + buffer.writeu32(fb, (i - 1) * 4, k) + end + out.faces = A(fb, "u32", 1, #p.faces) + end + return out + end + -- nodes: objects at the root, their groups as children; without objects every group is a root + local objectNode: { [string]: number } = {} + for _, s in sections do + if #s.prims > 0 then + local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} } + for _, p in s.prims do + table.insert(mesh.primitives, build(p)) + end + table.insert(scene.meshes, mesh) + local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes } + if s.smoothing then + node.extras = { obj = { smoothing = s.smoothing } } + end + if hasObjects and s.object and s.group then + local oi = objectNode[s.object] + if not oi then + table.insert(scene.nodes, { name = s.object, children = {} }) + oi = #scene.nodes + objectNode[s.object] = oi + table.insert(scene.roots, oi) + end + table.insert(scene.nodes, node) + table.insert(scene.nodes[oi].children, #scene.nodes) + else + if hasObjects and s.object and not s.group and objectNode[s.object] == nil then + table.insert(scene.nodes, node) + objectNode[s.object] = #scene.nodes + table.insert(scene.roots, #scene.nodes) + elseif hasObjects and s.object and objectNode[s.object] then + -- the object's own faces after its groups: a child too + table.insert(scene.nodes, node) + table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes) + else + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + end + end + end + scene.meta.up = "y" + scene.meta.source = { + format = "obj", + positions = np, + texcoords = nt, + normals = nn, + vertexColors = hasColor, + mtllib = if #mtllibs > 0 then mtllibs else nil, + missingMtl = if #missing > 0 then missing else nil, + skipped = skipped, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest decimal that reads back as the same f32 +local probe = buffer.create(4) +local function f32str(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e7 then + return string.format("%d", v) + end + buffer.writef32(probe, 0, v) + local want = buffer.readf32(probe, 0) + for _, f in { "%.6g", "%.7g", "%.8g" } do + local s = string.format(f, v) + buffer.writef32(probe, 0, tonumber(s) :: number) + if buffer.readf32(probe, 0) == want then + return s + end + end + return string.format("%.9g", v) +end + +local function nameOk(s: string): string + local t = string.gsub(s, "[\r\n]", " ") + return t +end + +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } + +function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local flipV = not (opts and opts.flipV == false) + local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local mtlName = opts and opts.mtlName or (base .. ".mtl") + local files = opts and opts.files + local placed = Types.Scene.flatten(scene) + local out = { "# written by rosetta" } + local mats = scene.materials or {} + -- material names (unique), texture file names + local names: { string } = {} + local used: { [string]: boolean } = {} + for i, m in mats do + local n = string.gsub(m.name or ("material_" .. i), "%s", "_") + while used[n] do + n ..= "_" .. i + end + used[n] = true + names[i] = n + end + local texFiles: { [number]: string } = {} + local function textureFile(i: number): string? + if texFiles[i] then + return texFiles[i] + end + local tex = scene.textures and scene.textures[i] + if not tex then + return nil + end + local file = tex.uri + if (file == nil or string.find(file, "^data:")) and tex.data then + file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + if file and tex.data and type(files) == "table" then + files[file] = tex.data + end + texFiles[i] = file + return file + end + if #mats > 0 then + table.insert(out, "mtllib " .. mtlName) + if type(files) == "table" then + files[mtlName] = Mtl.write(mats, names, textureFile) + end + end + local nv, nt, nn = 0, 0, 0 + local lastNode = -1 + for _, pl in placed do + local prim = pl.primitive + local attrs = prim.attributes + local pos = attrs and attrs.POSITION + if not pos then + continue + end + local P = Types.Scene.reader(pos) + if not P then + return nil, Err.new(Err.ARG, "bad POSITION accessor") + end + if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then + return nil, Err.new(Err.ARG, "POSITION data is smaller than its count") + end + local m = pl.matrix + local ident = m == Types.Scene.IDENTITY + local node = scene.nodes[pl.node] + if pl.node ~= lastNode then + lastNode = pl.node + table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) + end + local n = pos.count + local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0 :: Types.Accessor) else nil + local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0 :: Types.Accessor) else nil + local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL :: Types.Accessor) else nil + for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do + if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then + return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") + end + end + -- the normal matrix (inverse transpose) for baked normals + local nm: { number }? = nil + if Nr and not ident then + local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + local k = if det ~= 0 then 1 / det else 1 + nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k } + end + for v = 0, n - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if not ident then + x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + end + if Cc then + table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2)))) + else + table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if T then + for v = 0, n - 1 do + local tv = T(v, 1) + table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv))) + end + end + if Nr then + for v = 0, n - 1 do + local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2) + if nm then + x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + end + table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if prim.material and names[prim.material] then + table.insert(out, "usemtl " .. names[prim.material]) + end + local function ref(i: number): string + local s = tostring(nv + i + 1) + if T and Nr then + return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1) + elseif T then + return string.format("%s/%d", s, nt + i + 1) + elseif Nr then + return string.format("%s//%d", s, nn + i + 1) + end + return s + end + -- the corner list + local ind = prim.indices + local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil + local count = if ind then ind.count else n + if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then + return nil, Err.new(Err.ARG, "indices data is smaller than its count") + end + local function at(i: number): number + return if I then I(i, 0) else i + end + for i = 0, count - 1 do + if at(i) >= n then + return nil, Err.new(Err.ARG, "index out of range") + end + end + local mirror = not ident and (m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])) < 0 + local function face(list: { number }) + local parts = table.create(#list + 1) + parts[1] = "f" + if mirror then + for k = #list, 1, -1 do + table.insert(parts, ref(list[k])) + end + else + for k = 1, #list do + table.insert(parts, ref(list[k])) + end + end + table.insert(out, table.concat(parts, " ")) + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + for t = 0, count // 3 - 1 do + face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) }) + end + elseif mode == "polygons" then + local F = if prim.faces then Types.Scene.reader(prim.faces) else nil + if not F or not prim.faces then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local o = 0 + for f = 0, prim.faces.count - 1 do + local k = F(f, 0) + if o + k > count then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + local list = table.create(k) :: { number } + for j = 0, k - 1 do + list[j + 1] = at(o + j) + end + if k >= 3 then + face(list) + end + o += k + end + elseif mode == "triangle_strip" or mode == "triangle_fan" then + for t = 0, count - 3 do + local a, b, c = at(t), at(t + 1), at(t + 2) + if mode == "triangle_fan" then + a = at(0) + elseif t % 2 == 1 then + a, b = b, a + end + face({ a, b, c }) + end + elseif mode == "lines" then + for s = 0, count // 2 - 1 do + table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1))) + end + elseif mode == "line_strip" or mode == "line_loop" then + local parts = { "l" } + for i = 0, count - 1 do + table.insert(parts, ref(at(i))) + end + if mode == "line_loop" and count > 0 then + table.insert(parts, ref(at(0))) + end + table.insert(out, table.concat(parts, " ")) + elseif mode == "points" then + for i = 0, count - 1 do + table.insert(out, "p " .. ref(at(i))) + end + end + nv += n + if T then + nt += n + end + if Nr then + nn += n + end + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) +function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.materials) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local files: { [string]: string } = {} + local o: any = table.clone(opts or {}) + o.files = files + o.mtlName = "x.mtl" + local _, err = Obj.encode(scene, o) + if err then + return nil, err + end + local text = files["x.mtl"] + return buffer.fromstring(text or ""), nil +end + +return Obj +end +__FILES["model/obj/Mtl"] = function() + +-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, +-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping +-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the +-- reverse (from extras.obj when present, else from the PBR fields). +local Types = __include("Types") + +local Mtl = {} + +type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values +type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } } + +-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers +local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 } +local MAPS = { + map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true, + map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true, + map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true, +} +Mtl.MAPS = MAPS + +local function parseMap(args: { string }): Map + local opts: { [string]: { string } } = {} + local i = 1 + while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do + local key = string.sub(args[i], 2) + local vals = {} + i += 1 + local n = OPT_ARGS[key] + if n then + for _ = 1, n do + if i <= #args then + table.insert(vals, args[i]) + i += 1 + end + end + else + -- -o / -s / -t: up to three numbers + while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do + table.insert(vals, args[i]) + i += 1 + end + end + opts[key] = vals + end + -- the file name is the rest (it may contain spaces) + local file = table.concat(args, " ", i) + return { file = file, options = opts } +end + +-- parse(text) -> { Entry } in file order +function Mtl.parse(text: string): { Entry } + local out: { Entry } = {} + local cur: Entry? = nil + for line in string.gmatch(text, "[^\r\n]+") do + local l = string.gsub(line, "#.*$", "") + local words = {} + for w in string.gmatch(l, "%S+") do + table.insert(words, w) + end + local key = words[1] + if key == "newmtl" then + cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} } + table.insert(out, cur :: Entry) + elseif key and cur then + local e = cur :: Entry + local args = table.move(words, 2, #words, 1, {}) + if MAPS[key] then + e.maps[key] = parseMap(args) + table.insert(e.order, key) + else + local nums = {} + for _, a in args do + local v = tonumber(a) + if v == nil then + nums = nil :: any + break + end + table.insert(nums, v) + end + if nums then + if e.values[key] == nil then + table.insert(e.order, key) + end + e.values[key] = nums + end + end + end + end + return out +end + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" } +function Mtl.mime(file: string): string? + local ext = string.match(file, "%.([%w]+)$") + return if ext then MIME[string.lower(ext)] else nil +end + +-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map +function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material + local m = Types.Scene.material(e.name) + local v = e.values + local kd = v.Kd + if kd and #kd >= 3 then + m.baseColor = { kd[1], kd[2], kd[3], 1 } + end + local d = if v.d then (v.d :: { number })[1] elseif v.Tr then 1 - (v.Tr :: { number })[1] else 1 + m.baseColor[4] = d + if d < 1 then + m.alphaMode = "blend" + end + local ke = v.Ke + if ke and #ke >= 3 then + m.emissive = { ke[1], ke[2], ke[3] } + end + m.metallic = if v.Pm then (v.Pm :: { number })[1] else 0 + if v.Pr then + m.roughness = v.Pr[1] + elseif v.Ns then + m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1) + end + local function ref(key: string): Types.TextureRef? + local map = e.maps[key] + if not map or map.file == "" then + return nil + end + local r: Types.TextureRef = { texture = texture(map) } + local o, s = map.options.o, map.options.s + if o or s then + r.transform = { + offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil, + scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil, + } + end + if map.options.bm then + r.scale = tonumber(map.options.bm[1]) + end + return r + end + m.baseColorTexture = ref("map_Kd") + m.emissiveTexture = ref("map_Ke") + m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump") + m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA") + if m.emissiveTexture and not ke then + m.emissive = { 1, 1, 1 } + end + -- everything else as it was, for the writer and for Phong renderers + local extra: { [string]: any } = {} + for k, vals in v do + extra[k] = vals + end + local maps: { [string]: any } = {} + for k, map in e.maps do + maps[k] = { file = map.file, options = map.options, texture = texture(map) } + end + m.extras = { obj = { values = extra, maps = maps, order = e.order } } + return m +end + +local function num(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end +Mtl.num = num + +-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. +function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string + local out = { "# written by rosetta" } + for i, m in materials do + table.insert(out, "") + table.insert(out, "newmtl " .. names[i]) + local saved = m.extras and m.extras.obj + local values: { [string]: { number } } = {} + local maps: { [string]: any } = {} + local order: { string } = {} + if type(saved) == "table" and type(saved.values) == "table" then + for k, vals in saved.values do + values[k] = vals + end + for k, mp in saved.maps or {} do + maps[k] = mp + end + order = table.clone(saved.order or {}) + end + -- the PBR fields win over the saved Phong values they map to + local bc = m.baseColor or { 1, 1, 1, 1 } + values.Kd = { bc[1], bc[2], bc[3] } + if (bc[4] or 1) < 1 or values.d then + values.d = { bc[4] or 1 } + values.Tr = nil + end + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then + values.Ke = { em[1], em[2], em[3] } + end + if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then + values.Pr = { m.roughness } + end + if m.metallic ~= 0 or values.Pm then + values.Pm = { m.metallic } + end + local function setMap(key: string, ref: Types.TextureRef?) + if ref then + local file = textureFile(ref.texture) + if file then + local prev = maps[key] + local options = if prev and prev.texture == ref.texture then prev.options else {} + options = table.clone(options or {}) + if ref.transform then + if ref.transform.offset then + options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) } + end + if ref.transform.scale then + options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) } + end + end + if ref.scale and key ~= "map_Kd" then + options.bm = { num(ref.scale) } + end + maps[key] = { file = file, options = options, texture = ref.texture } + end + end + end + setMap("map_Kd", m.baseColorTexture) + setMap("map_Ke", m.emissiveTexture) + if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then + setMap("norm", m.normalTexture) + end + setMap("map_ORM", m.metallicRoughnessTexture) + -- the saved order first, then the rest sorted + local keys = {} + local seen = {} + for _, k in order do + if (values[k] or maps[k]) and not seen[k] then + table.insert(keys, k) + seen[k] = true + end + end + local rest = {} + for k in values do + if not seen[k] then + table.insert(rest, k) + end + end + for k in maps do + if not seen[k] and not values[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + seen[k] = true + table.insert(keys, k) + end + for _, k in keys do + local mp = maps[k] + if mp and type(mp.file) == "string" then + local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file + local parts = { k } + local okeys = {} + for ok in mp.options or {} do + table.insert(okeys, ok) + end + table.sort(okeys) + for _, ok in okeys do + table.insert(parts, "-" .. ok) + for _, ov in mp.options[ok] do + table.insert(parts, tostring(ov)) + end + end + table.insert(parts, file) + table.insert(out, table.concat(parts, " ")) + elseif values[k] then + local parts = { k } + for _, x in values[k] do + table.insert(parts, num(x)) + end + table.insert(out, table.concat(parts, " ")) + end + end + end + table.insert(out, "") + return table.concat(out, "\n") +end + +return Mtl +end +__FILES["model/off"] = function() + +-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description +-- (geomview.org/docs/html/OFF.html). +-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the +-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; +-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 +-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). +-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; +-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are +-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or +-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single +-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". +-- meta.source = { format, keyword, vertices, faces, edges }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes +-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons +-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are +-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF +-- (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Off = { + name = "off", + category = "model", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +type EncodeOptions = { + colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true) + normals: boolean?, -- write NORMAL (NOFF) when present (default true) + texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true) + comment: string?, -- a "# ..." line after the header keyword +} + +-- ------------------------------------------------------------------------------------------------ constants +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Off.sniff(r: Bytes.Reader): number + local head = r:peek(512) + for _ = 1, 16 do -- leading comment lines + local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") + if not rest then + break + end + head = rest + end + local kw = string.match(head, "^%s*(%w+)") + if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 +type ColorSet = { values: { number }, float: boolean, max: number } + +local function colorType(c: ColorSet): string + return if not c.float and c.max > 1 then "unorm8" else "f32" +end + +-- the colour accessor for count entries of 4 values (nan = absent: opaque white) +local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?) + local t = colorType(c) + local buf = buffer.create(count * (if t == "unorm8" then 4 else 16)) + local vals = c.values + for i = 0, count * 4 - 1 do + local v = vals[i + 1] + if t == "unorm8" then + if v ~= v then + v = 255 + elseif v < 0 or v > 255 or v % 1 ~= 0 then + return nil, "colour value out of range" + end + writeu8(buf, i, v) + else + writef32(buf, i * 4, if v ~= v then 1 else v) + end + end + return Types.Scene.accessor(buf, t, 4, count), nil +end + +local function addColor(c: ColorSet, toks: { string }, from: number, n: number) + local vals = c.values + for k = 0, 3 do + if k < n then + local s = toks[from + k] + local v = tonumber(s) :: number + table.insert(vals, v) + if not c.float and string.find(s, "[%.eEnN]") then + c.float = true + end + if v > c.max then + c.max = v + end + else + table.insert(vals, 0 / 0) -- absent: full (opaque white) + end + end +end + +function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + -- the next non-empty line's tokens (comments stripped) + local at = 1 + local lineNo = 0 + local function line(): { string }? + while at <= #text do + local e = string.find(text, "\n", at, true) or (#text + 1) + local s = string.sub(text, at, e - 1) + at = e + 1 + lineNo += 1 + local hash = string.find(s, "#", 1, true) + if hash then + s = string.sub(s, 1, hash - 1) + end + local toks = {} + for w in string.gmatch(s, "%S+") do + table.insert(toks, w) + end + if #toks > 0 then + return toks + end + end + return nil + end + local head = line() + if not head then + return nil, Err.new(Err.TRUNCATED, "empty file") + end + local kw = head[1] + local rest = kw + local st, hasC, hasN = false, false, false + if string.sub(rest, 1, 2) == "ST" then + st, rest = true, (string.sub(rest, 3)) + end + if string.sub(rest, 1, 1) == "C" then + hasC, rest = true, (string.sub(rest, 2)) + end + if string.sub(rest, 1, 1) == "N" then + hasN, rest = true, (string.sub(rest, 2)) + end + if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then + return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") + elseif rest ~= "OFF" then + return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20)) + end + local counts: { string } + if head[2] == "BINARY" then + return nil, Err.new(Err.UNSUPPORTED, "binary OFF") + elseif #head >= 3 then + counts = { head[2], head[3], head[4] } + else + local c = line() + if not c then + return nil, Err.new(Err.TRUNCATED, "no counts line") + end + counts = c + end + local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0") + if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad counts line") + end + if nv > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices)) + end + if nf > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) + end + -- every vertex / face line takes at least 6 / 2 bytes + if nv * 6 + nf * 2 > #text - at + 2 then + return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") + end + local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0) + local pos = buffer.create(nv * 12) + local nrm = if hasN then buffer.create(nv * 12) else nil + local tex = if st then buffer.create(nv * 8) else nil + local vcol: ColorSet = { values = {}, float = false, max = 0 } + for i = 0, nv - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i)) + end + local n = #t + local nc = 0 + if hasC then + nc = n - fixed + if nc ~= 3 and nc ~= 4 then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed)) + end + elseif n < fixed then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed)) + end + for k = 1, fixed + nc do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i)) + end + end + writef32(pos, i * 12, tonumber(t[1]) :: number) + writef32(pos, i * 12 + 4, tonumber(t[2]) :: number) + writef32(pos, i * 12 + 8, tonumber(t[3]) :: number) + local k = 4 + if nrm then + writef32(nrm, i * 12, tonumber(t[4]) :: number) + writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number) + writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number) + k = 7 + end + if hasC then + addColor(vcol, t, k, nc) + k += nc + end + if tex then + writef32(tex, i * 8, tonumber(t[k]) :: number) + writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number) + end + end + local sizes = buffer.create(nf * 4) + local corners: { number } = {} + local fcol: ColorSet = { values = {}, float = false, max = 0 } + local anyFaceColor, colormap = false, false + for f = 0, nf - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f)) + end + local n = tonumber(t[1]) + if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f)) + end + writeu32(sizes, f * 4, n) + for k = 2, n + 1 do + local v = tonumber(t[k]) + if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f)) + end + table.insert(corners, v) + end + local nc = #t - n - 1 + if nc == 3 or nc == 4 then + for k = n + 2, #t do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f)) + end + end + addColor(fcol, t, n + 2, nc) + anyFaceColor = true + else + if nc == 1 then + colormap = true + end + addColor(fcol, t, 1, 0) + end + end + -- the primitive + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if hasC then + local acc, cerr = colorAccessor(vcol, nv) + if not acc then + return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr)) + end + attrs.COLOR_0 = acc + end + if tex then + attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv) + end + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local extras: { [string]: any } = {} + if anyFaceColor then + local acc, cerr = colorAccessor(fcol, nf) + if not acc then + return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr)) + end + extras.faceColors = acc + end + if nf > 0 then + local total = #corners + local cbuf = buffer.create(total * 4) + for i = 1, total do + writeu32(cbuf, (i - 1) * 4, corners[i]) + end + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + elseif triangulate then + local tris: { number } = {} + local fot: { number } = {} + local p = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + for k = 1, s - 2 do + table.insert(tris, corners[p + 1]) + table.insert(tris, corners[p + k + 1]) + table.insert(tris, corners[p + k + 2]) + table.insert(fot, f) + end + p += s + end + local ib = buffer.create(#tris * 4) + for i, v in tris do + writeu32(ib, (i - 1) * 4, v) + end + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris) + if anyFaceColor then + local fb = buffer.create(#fot * 4) + for i, v in fot do + writeu32(fb, (i - 1) * 4, v) + end + extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + if next(extras) then + prim.extras = extras + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function fnum(v: number): string? + writef32(scratch, 0, v) + v = buffer.readf32(scratch, 0) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) +end + +-- a colour attribute's 4 components of entry i (0-based) as text +local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string + local out = table.create(4) + for c = 1, 4 do + local v = if c <= comps then vals[i * comps + c] else nil + if a.raw and a.type == "unorm8" then + out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255)) + else + if v == nil then + v = 1 + elseif a.raw then + v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1) + end + out[c] = fnum(v :: number) or "0" + end + end + return table.concat(out, " ") +end + +function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false + local m, merr = Flatten.merge(scene, function(name: string): boolean + return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT) + end, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local A = m.attrs + local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0 + if T and T.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + local nv = m.count + local sizes = m.sizes or {} + local nf = #sizes + local out = table.create(nv + nf + 3) + table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF") + if o.comment then + table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " ")) + end + table.insert(out, string.format("%d %d 0", nv, nf)) + local pv = P.values + for i = 0, nv - 1 do + local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate") + end + local s = x .. " " .. y .. " " .. z + if N then + local nvv = N.values + s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0") + end + if C then + s ..= " " .. colorText(C, C.values, C.components, i) + end + if T then + local tv, tc = T.values, T.components + s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0") + end + table.insert(out, s) + end + -- face colours of a single primitive (per file face, or through faceOfTriangle) + local fc: Flatten.Attr? = nil + local fcMap: { number }? = nil + if wantC and #m.parts == 1 and nf > 0 then + local ex = m.parts[1].prim.extras + local acc = type(ex) == "table" and ex.faceColors + if acc then + local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16" + local vals = Flatten.numbers(acc, raw) + if vals then + local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals } + if acc.count == nf then + fc = a + elseif (ex :: { [string]: any }).faceOfTriangle then + local fot = Flatten.numbers(ex.faceOfTriangle, true) + if fot and #fot == nf then + fc, fcMap = a, fot + for _, f in fot do + if f < 0 or f >= acc.count then + fc = nil + break + end + end + end + end + end + end + end + local corners = m.corners + local p = 0 + for f = 1, nf do + local s = sizes[f] + local line = table.create(s + 2) + line[1] = string.format("%d", s) + for k = 1, s do + line[k + 1] = string.format("%d", corners[p + k]) + end + p += s + if fc then + local src = if fcMap then (fcMap :: { number })[f] else f - 1 + table.insert(line, colorText(fc, fc.values, fc.components, src)) + end + table.insert(out, table.concat(line, " ")) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Off +end +__FILES["model/ply"] = function() + +-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, +-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). +-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> +-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u +-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> +-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's +-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are +-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are +-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", +-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face +-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after +-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, +-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments +-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and +-- types. meta.source = { format, encoding, vertices, faces }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, +-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces +-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when +-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. +-- Not supported: list properties in the vertex element (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/ply/Binary") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- faces, and rows of any other element (default 2^25) +} +type EncodeOptions = { + format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" + comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) +} + +type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } +type Elem = { name: string, count: number, props: { Prop } } + +-- ------------------------------------------------------------------------------------------------ constants +local CODES: { [string]: number } = { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r: Bytes.Reader): number + local h = r:peek(4) + return if h == "ply\n" or h == "ply\r" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } + +local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + -- blank line + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert(if kw == "comment" then h.comments else h.objInfo, rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + if string.sub(ver :: string, 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. (ver :: string), lineAt) + end + h.encoding = enc + elseif kw == "element" then + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words: { string } = {} + for w in string.gmatch(line, "%S+") do + table.insert(words, w) + end + local p: Prop + if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3]], CODES[words[4]] + if not cc or not ic then + return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) + end + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } :: Prop + elseif #words == 3 and CODES[words[2]] then + p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } :: Prop + else + return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) + end + for _, q in el.props do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end + +-- the reading plan of one element: per property, where its values go +type Plan = { + code: { number }, + isList: { boolean }, + countCode: { number }, + dst: { buffer }, + dOff: { number }, + dStride: { number }, + dCode: { number }, + sizes: { buffer }, + bound: { number }, + totals: { number }, +} + +local function newPlan(e: Elem): Plan + local np = #e.props + local pl: Plan = { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = table.create(np) :: { buffer }, + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = table.create(np) :: { buffer }, + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in e.props do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +-- unset scalar destinations get their own native buffer +local function ownBuffers(e: Elem, pl: Plan) + for k, p in e.props do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +-- read one element's rows (binary) into the plan; returns the next offset or nil, Err +local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) + local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in e.props do + if pr.list then + hasList = true + rowSize += SIZE[pr.countCode :: number] + else + rowSize += SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in e.props do + srcOff[k] = o + o += SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in e.props do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +-- a token as a value of type code, or nil +local function value(tok: string?, code: number): number? + if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +-- read one element's rows (ascii) from the token stream +local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? + ownBuffers(e, pl) + local n = e.count + local listSizes: { [number]: { number } } = {} + local listItems: { [number]: { number } } = {} + for k, p in e.props do + if p.list then + listSizes[k] = table.create(n) :: { number } + listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in e.props do + if p.list then + local t = nextTok() + local c = value(t, p.countCode :: number) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in listSizes do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e: Elem, name: string): number? + for k, p in e.props do + if p.name == name then + return k + end + end + return nil +end + +-- vertex element -> attributes: sets the plan's destinations, returns the attribute table +local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) + local nv = e.count + local attrs: { [string]: Types.Accessor } = {} + local taken: { [number]: boolean } = {} + for _, p in e.props do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional + local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) + local ks: { [number]: number } = {} + local codes = {} + for i, nm in names do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in ks do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] + attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes: { number }): number? + for _, c in codes do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes: { number }): number? + return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + -- colours: one type class for all channels + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls: number? = codes[1] + for _, c in codes do + local a = if c == 8 then 7 else c + local b0 = if cls == 8 then 7 else cls + if a ~= b0 then + cls = nil + end + end + local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil + if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) + end + end + end + for _, pair in TEXCOORD_PAIRS do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in e.props do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle +local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) + local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt += s - 2 + end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t += 1 + end + p += s + end + return idx, nt, fot +end + +function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi: number?, fi: number?, idxK: number + for i, e in h.elems do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok: () -> string? = function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating + local need = 0 + for _, e in h.elems do + need += e.count * #e.props + end + if need > (#body + 1) // 2 then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = string.gmatch(body, "%S+") :: any + end + local plans: { Plan } = {} + local attrs: { [string]: Types.Accessor } = {} + local p = h.dataStart + if not ascii then + -- every row takes at least its scalar sizes and list counts: bound the counts before allocating + local need = 0 + for _, e in h.elems do + local row = 0 + for _, pr in e.props do + row += SIZE[if pr.list then pr.countCode :: number else pr.code] + end + need += e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in h.elems do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + -- the primitive + local prim: Types.Primitive = { attributes = attrs, mode = "points" } + local nf = 0 + local extras: { [string]: any } = {} + local faceProps: { any } = {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes: { [string]: Types.Accessor } = {} + local faceLists: { [string]: any } = {} + local anyExtra = false + for k, pr in e.props do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + -- raw elements, element order, property order + local elements: { any } = {} + local order: { string } = {} + for i, e in h.elems do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in e.props do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in h.elems[vi].props do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = if fi then faceProps else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) +type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } +type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +-- the spelling `want` from the source file when it means the same type as code, else the classic name +local function spell(want: string?, code: number): string + if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v: number, code: number): number + local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end + +-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer +type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } + +local function rowsAscii(out: { string }, n: number, cols: { Row }) + local fmt = string.format + local function num(code: number, v: number): string + if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at: { [number]: number } = {} + for i = 0, n - 1 do + local parts = {} + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) + local size = 0 + for _, c in cols do + if c.kind == "s" then + size += n * SIZE[(c.col :: Column).code] + else + local col = c.col :: ListColumn + size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] + end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at: { [number]: number } = {} + for i = 0, n - 1 do + for k, c in cols do + if c.kind == "s" then + local col = c.col :: Column + local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o += SIZE[code] + else + local col = c.col :: ListColumn + local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o += SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o += SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +-- numbers of a raw element column (buffer of a ply type) +local function bufNumbers(b: any, code: number, count: number): { number }? + if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then + return nil + end + local out = table.create(count) :: { number } + for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +-- the list count type for a maximum count +local function countCodeFor(maxCount: number): number + return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 +end + +function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} + local nv = m.count + -- source property spellings / order + local srcType: { [string]: string } = {} + local srcOrder: { [string]: number } = {} + if type(meta.vertexProperties) == "table" then + for i, vp in meta.vertexProperties do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols: { Column } = {} + local function add(name: string, code: number, a: Flatten.Attr, comp: number) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name: string): number + return if CODES[srcType[name] or ""] == 8 then 8 else 7 + end + local A = m.attrs + for i, nm in { "x", "y", "z" } do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in { "nx", "ny", "nz" } do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 + if C.raw and code == 7 then + -- another normalized type: as floats + local vals = table.create(#C.values) + local scale = if C.type == "snorm8" then 127 else 32767 + for i, v in C.values do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C :: Flatten.Attr + for i, nm in { "red", "green", "blue" } do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 + local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in TEXCOORD_PAIRS do + if srcOrder[pair[1]] and srcOrder[pair[2]] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in A do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in customs do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + -- the source order first (stable for the rest) + local rank: { [Column]: number } = {} + for i, c in cols do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a: Column, b: Column): boolean + return rank[a] < rank[b] + end) + -- faces + local faceRows: { Row }? = nil + local nf = 0 + if m.sizes then + local sizes = m.sizes :: { number } + nf = #sizes + local maxS, maxI = 0, 0 + for _, s in sizes do + maxS = math.max(maxS, s) + end + for _, c in m.corners do + maxI = math.max(maxI, c) + end + local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} + local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in fprops do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = if maxI < 2147483648 then 5 else 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows: { Row } = { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + -- per-face data of a single primitive + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot: { number }? = nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals: { number }, count: number): { number }? + if count == nf then + return vals + elseif fot and #fot == nf then + local out = table.create(nf) :: { number } + for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows: { [string]: Row } = {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + for name: string, acc: any in ex.faceAttributes do + local vals = Flatten.numbers(acc, true) + local code = CODE_OF_ACC[acc.type] + if vals and code and acc.components == 1 then + local pv = perFace(vals, acc.count) + if pv then + extraRows[name] = { kind = "s" :: "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + end + end + end + end + if type(ex) == "table" and type(ex.faceLists) == "table" then + for name: string, fl: any in ex.faceLists do + local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) + local items = type(fl) == "table" and Flatten.numbers(fl.items, true) + local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in sz do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + extraRows[name] = { kind = "l" :: "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + end + end + end + -- the source order, then the rest by name + local placed: { [string]: boolean } = { [idxName] = true } + local ordered: { Row } = {} + for _, fp in fprops do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in extraRows do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in rest do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end + -- raw elements + type Raw = { name: string, count: number, rows: { Row } } + local raws: { [string]: Raw } = {} + local rawOrder: { string } = {} + if type(meta.elements) == "table" then + for _, el in meta.elements do + if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then + continue + end + local rows: { Row } = {} + for _, pr: any in el.properties do + local code = CODES[pr.type or ""] + if not code then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in sz do + total += s + end + end + local items = sz and bufNumbers(pr.values, code, total) + if not (cc and sz and items) then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "l" :: "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + else + local vals = bufNumbers(pr.values, code, el.count) + if not vals then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "s" :: "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + end + end + raws[el.name] = { name = el.name, count = el.count, rows = rows } + table.insert(rawOrder, el.name) + end + end + end + -- element order: the source's, then vertex, face, the rest + local order: { string } = {} + local seen: { [string]: boolean } = {} + local function want(name: string) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in meta.order do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in rawOrder do + want(name) + end + -- header + local vrows: { Row } = {} + for _, c in cols do + table.insert(vrows, { kind = "s" :: "s", col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s: any): string + return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in o.comments or {} do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name: string): (number, { Row }) + if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in order do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in rows do + if rw.kind == "s" then + local c = rw.col :: Column + table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col :: ListColumn + table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body: { string } = {} + for _, name in order do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in order do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply +end +__FILES["model/ply/Binary"] = @native function() + + + +-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, +-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of +-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the +-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list +-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64 = buffer.readf32, buffer.readf64 +local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 +local writef32, writef64 = buffer.writef32, buffer.writef64 +local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift + +local Binary = {} + +Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } +local SIZE = Binary.SIZE +local scratch = buffer.create(8) + +@native local function swap16(v: number): number + return rshift(v, 8) + band(v, 255) * 256 +end + +-- rd(b, q, code, be) -> the value at q +@native local function rd(b: buffer, q: number, code: number, be: boolean): number + if not be then + if code == 7 then + return readf32(b, q) + elseif code == 2 then + return readu8(b, q) + elseif code == 5 then + return readi32(b, q) + elseif code == 6 then + return readu32(b, q) + elseif code == 8 then + return readf64(b, q) + elseif code == 1 then + return readi8(b, q) + elseif code == 3 then + return readi16(b, q) + end + return readu16(b, q) + end + if code <= 2 then + return if code == 1 then readi8(b, q) else readu8(b, q) + elseif code <= 4 then + local v = swap16(readu16(b, q)) + return if code == 3 and v >= 32768 then v - 65536 else v + elseif code <= 7 then + local v = byteswap(readu32(b, q)) + if code == 6 then + return v + elseif code == 5 then + return if v >= 2147483648 then v - 4294967296 else v + end + writeu32(scratch, 0, v) + return readf32(scratch, 0) + end + writeu32(scratch, 0, byteswap(readu32(b, q + 4))) + writeu32(scratch, 4, byteswap(readu32(b, q))) + return readf64(scratch, 0) +end +Binary.rd = rd + +-- wr(d, o, code, v): v as code, little endian +@native local function wr(d: buffer, o: number, code: number, v: number) + if code == 7 then + writef32(d, o, v) + elseif code == 6 then + writeu32(d, o, v) + elseif code == 5 then + writei32(d, o, v) + elseif code == 2 then + writeu8(d, o, v) + elseif code == 8 then + writef64(d, o, v) + elseif code == 1 then + writei8(d, o, v) + elseif code == 3 then + writei16(d, o, v) + else + writeu16(d, o, v) + end +end +Binary.wr = wr + +-- put(d, o, code, v, be): v as code in either byte order (the writer) +@native function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean) + if not be or code <= 2 then + wr(d, o, code, v) + return + end + wr(scratch, 0, code, v) + if code <= 4 then + writeu16(d, o, swap16(readu16(scratch, 0))) + elseif code <= 7 then + writeu32(d, o, byteswap(readu32(scratch, 0))) + else + writeu32(d, o, byteswap(readu32(scratch, 4))) + writeu32(d, o + 4, byteswap(readu32(scratch, 0))) + end +end + +-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p +@native function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }) + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] + if sc == dc and not be then + local sz = SIZE[sc] + if sz == 4 then + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + end + elseif sz == 1 then + for i = 0, n - 1 do + writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize)) + end + elseif sz == 2 then + for i = 0, n - 1 do + writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize)) + end + else + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4)) + end + end + else + for i = 0, n - 1 do + wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be)) + end + end + end +end + +-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, +-- or -1, message (truncated rows, a negative / fractional count) +@native function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any) + local totals = table.create(np, 0) + local q = p + for _ = 1, n do + for k = 1, np do + if isList[k] then + local cc = countCode[k] + local csz = SIZE[cc] + if q + csz > limit then + return -1, "list runs past the end" + end + local c = rd(b, q, cc, be) + if c < 0 or c ~= c // 1 then + return -1, "bad list count" + end + q += csz + c * SIZE[code[k]] + if q > limit then + return -1, "list runs past the end" + end + totals[k] += c + else + q += SIZE[code[k]] + if q > limit then + return -1, "row runs past the end" + end + end + end + end + return q, totals +end + +-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. +-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their +-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows +-- must have passed scan() with the same arguments. +@native function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?) + local at = table.create(np, 0) + local q = p + for i = 0, n - 1 do + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + if isList[k] then + local cc = countCode[k] + local c = rd(b, q, cc, be) + q += SIZE[cc] + writeu32(sizes[k], i * 4, c) + local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k] + if bd >= 0 then + for j = 0, c - 1 do + local v = rd(b, q, sc, be) + q += ssz + if v < 0 or v >= bd or v ~= v // 1 then + return false, "vertex index out of range" + end + wr(d, (ia + j) * dsz, dc, v) + end + else + for j = 0, c - 1 do + wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be)) + q += ssz + end + end + at[k] = ia + c + else + wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be)) + q += SIZE[sc] + end + end + end + return true, nil +end + +return Binary +end +__FILES["model/pmx"] = function() + +-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD +-- format, as documented by the MMD community). New code, no third-party code. +-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / +-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / +-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one +-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, +-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon +-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; +-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), +-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras +-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the +-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). +-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/pmx/Read") +local Pmd = __include("model/pmx/Pmd") +local Build = __include("model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) + resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) + morphs: boolean?, -- vertex morphs as morph targets (default true) + maxVertices: number?, -- default 2^24 + maxBytes: number?, -- morph target bytes (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Pmx.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local pmd = r:peek(3) == "Pmd" + local m: any, msg: string?, kind: string? + if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx +end +__FILES["model/pmx/Build"] = function() + +-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, +-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed +-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with +-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as +-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex +-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative +-- translation each) and one skin with translation-only inverse bind matrices. +local Types = __include("Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve +local function fetcher(opts: any): (string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +local function lh(v: { number }?): { number }? + return if v then { v[1], v[2], -v[3] } else nil +end + +-- the scene index of a file texture index (0-based, -1 = none) +local function texIndex(m: any, i: number?): number? + return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil +end + +local function material(m: any, mat: any): Types.Material + local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x: { [string]: any } = { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root +local function parents(bones: { any }): { number } + local nb = #bones + local par = table.create(nb, 0) + for i, b in bones do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps += 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered +local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive + local map: { [number]: number } = {} + local verts: { number } = {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, n // 3 - 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd: { Types.Accessor }? = nil + local deform: Types.Accessor? = nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = if c == 2 then -1 else 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in uvas do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + -- weights: invalid bones get weight 0, the rest is normalized + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum += w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0)) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + end + end + local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + for k, mo in morphs do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in mo.vertices do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m: any, opts: any): (any, ...any) + local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in m.textures do + local uri = string.gsub(path, "\\", "/") + local tex: Types.Texture = { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + scene.textures[i] = tex + end + for i, mat in m.materials do + scene.materials[i] = material(m, mat) + end + + -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in m.morphs do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28 + if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh: Types.Mesh = { name = m.name, primitives = {} } + local first = 0 + for i, mat in m.materials do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first += n + end + if first < m.indexCount then + -- faces no material covers + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + -- nodes: 1 = the model, 2 = the mesh, then one per bone + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world: { { number } } = {} + for i, b in bones do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints: { number } = {} + for i, b in bones do + local w, p = world[i], par[i] + local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] } + local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0 + writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build +end +__FILES["model/pmx/Pmd"] = function() + +-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as +-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community +-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, +-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to +-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in +-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in +-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +local Bytes = __include("core/Bytes") + +local Pmd = {} + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any) + if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, if single then 0 else 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, if single then -1 else b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, if single then 1 else w) + buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w) + buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1) + end + r.pos += nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos += ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each; texture names collected into the texture list + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex: { [string]: number } = {} + local function tex(name: string): number + if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in string.gmatch(file, "[^*]+") do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = if parent == 0xFFFF then -1 else parent + b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 } + b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10 + m.bones[i] = b + end + + -- IK chains + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base: { number } = {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups: { { [string]: any } } = {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t: { [string]: any }, en: string?) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw + if ascii(raw) then + t.nameSjis = nil + end + end + local en: any = {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in m.bones do + name(b, en.bones and en.bones[i]) + end + for i, mo in m.morphs do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in groups do + name(g, en.groups and en.groups[i]) + end + local toons: { string } = {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in m.materials do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd +end +__FILES["model/pmx/Read"] = function() + +-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that +-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. +-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices +-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, +-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, +-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). +-- Never throws: returns nil, message[, kind]. +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") + +local Read = {} + +type Model = { [string]: any } + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number + if size == 1 then + return if vertex then function() return r:u8() end else function() return r:i8() end + elseif size == 2 then + return if vertex then function() return r:u16le() end else function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 and at most remaining / minSize records +local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) + local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = if version > 2.05 then 2.1 else 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g: { number } = {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text(): string + local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos += n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef: buffer? = nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p += 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p += 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4) + if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + -- textures + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + -- materials + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat: { [string]: any } = { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + -- bones + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3) + if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link: { [string]: any } = { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + -- morphs + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas), they become morph targets + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off: { [string]: any } + if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read +end +__FILES["model/qb"] = function() + +-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the +-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA +-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 +-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. +-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as +-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view +-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and +-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). +-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; +-- options default to the source file's settings. +-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Qb = { + name = "qb", + category = "model", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) +} +type EncodeOptions = { + compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) + colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" + rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) + visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEFLAG, NEXTSLICEFLAG = 2, 6 +-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour +local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 + +-- ------------------------------------------------------------------------------------------------ sniff +function Qb.sniff(r: Bytes.Reader): number + if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then + return 0 + end + local b, p = r.buf, r.pos + local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) + if fmt > 1 or z > 1 or comp > 1 or mask > 1 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them +local function indexed(v: Types.Voxels, colors: buffer, n: number) + local count: { [number]: number } = {} + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + if c >= 0x1000000 then -- alpha > 0: filled + local rgb = c % 0x1000000 + local k = count[rgb] + if k == nil then + count[rgb] = 1 + else + count[rgb] = k + 1 + end + end + end + local order = {} + for rgb in count do + table.insert(order, rgb) + end + table.sort(order, function(a: number, b: number): boolean + if count[a] ~= count[b] then + return count[a] > count[b] + end + return a < b + end) + local slot: { [number]: number } = {} + for i = 1, math.min(255, #order) do + local rgb = order[i] + slot[rgb] = i + v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 } + end + for i = 256, #order do + local rgb = order[i] + local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536 + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot[rgb] = best + end + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0) + end +end + +function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxCells = o.maxCells or 2 ^ 27 + local ver = r:string(4) + local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= "\1\1\0\0" then + return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) + end + if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then + return nil, Err.new(Err.CORRUPT, "bad header flags", 4) + end + if count > r:remaining() // 25 then + return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) + end + local scene = Types.Scene.new() + local grids: { Types.Voxels } = {} + scene.voxels = grids + local total = 0 + local bgra = fmt == 1 + for m = 1, count do + local at = r:tell() + local nameLen = r:u8() + local name = r:string(nameLen) + local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() + local px, py, pz = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if sx * sy * sz + total > maxCells then + return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) + end + local n = sx * sy * sz + total += n + local colors = buffer.create(n * 4) + local b = r.buf + local function put(x: number, y: number, z: number, c: number) + if bgra then -- b, g, r, a -> r, g, b, a + c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216 + end + if c < 0x1000000 then + c = 0 -- alpha 0: empty + end + local zz = if zAxis == 0 then sz - 1 - z else z + buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) + end + if compressed == 0 then + if not r:need(n * 4) then + return nil, r.err + end + local p = r.pos + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + put(x, y, z, buffer.readu32(b, p)) + p += 4 + end + end + end + r.pos = p + else + local slice = sx * sy + for z = 0, sz - 1 do + local index = 0 + while true do + local d = r:u32le() + if r.err then + return nil, r.err + end + if d == NEXTSLICEFLAG then + break + elseif d == CODEFLAG then + local run, c = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if index + run > slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) + end + for _ = 1, run do + put(index % sx, index // sx, z, c) + index += 1 + end + else + if index >= slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) + end + put(index % sx, index // sx, z, d) + index += 1 + end + end + end + end + local v = Types.Voxels.new(sx, sy, sz) + v.name = name + v.colors = colors + indexed(v, colors, n) + table.insert(grids, v) + local tz = if zAxis == 0 then 0 - (pz + sz) else pz + table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.source = { + format = "qb", + colorFormat = if bgra then "bgra" else "rgba", + rightHanded = zAxis == 1, + compressed = compressed == 1, + visibilityMask = mask == 1, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function cellColor(v: Types.Voxels, i: number): number + if v.colors then + return buffer.readu32(v.colors, i * 4) + end + local idx = buffer.readu8(v.data, i) + if idx == 0 then + return 0 + end + local p = v.palette[idx] or { 0, 0, 0, 255 } + return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 +end + +function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {} + local function add(v: any, name: string?, pos: { number }): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local n = v.size[1] * v.size[2] * v.size[3] + if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then + return "voxel data shorter than its size" + end + local nm = name or v.name or ("matrix" .. (#grids + 1)) + if #nm > 255 then + return "matrix name longer than 255 bytes" + end + table.insert(grids, { v = v, name = nm, pos = pos }) + return nil + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then + local used: { [number]: boolean } = {} + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + used[node.voxels] = true + local e = add(value.voxels[node.voxels], node.name, p) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, Err.new(Err.ARG, e) + end + end + for i, v in value.voxels do + if not used[i] then + local e = add(v, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + end + end + else + return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") + end + local function pick(opt: any, key: string, default: any): any + if opt ~= nil then + return opt + elseif src and src[key] ~= nil then + return src[key] + end + return default + end + local compressed = pick(o.compressed, "compressed", true) + local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" + local right = pick(o.rightHanded, "rightHanded", true) + local mask = pick(o.visibilityMask, "visibilityMask", false) + local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks + local w = Bytes.writer(1024) + w:string("\1\1\0\0") + w:u32le(if bgra then 1 else 0) + w:u32le(if right then 1 else 0) + w:u32le(if compressed then 1 else 0) + w:u32le(if mask then 1 else 0) + w:u32le(#grids) + for _, g in grids do + local v = g.v + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + w:u8(#g.name) + w:string(g.name) + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) + w:u32le(px % 4294967296) + w:u32le(py % 4294967296) + w:u32le((if right then pz else -pz - sz) % 4294967296) + local function filled(x: number, y: number, z: number): boolean + if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then + return false + end + return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 + end + -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked + local function value(x: number, y: number, z: number): number + local zz = if right then z else sz - 1 - z + local c = cellColor(v, x + sx * (y + sy * zz)) + if c < 0x1000000 then + return 0 + end + local a = c // 16777216 + if mask and not keepMask then + a = 1 + if not filled(x - 1, y, zz) then a += LEFT end + if not filled(x + 1, y, zz) then a += RIGHT end + if not filled(x, y + 1, zz) then a += TOP end + if not filled(x, y - 1, zz) then a += BOTTOM end + if not filled(x, y, zz + 1) then a += FRONT end + if not filled(x, y, zz - 1) then a += BACK end + elseif not mask and src and src.visibilityMask then + a = 255 -- masks are not colours + end + local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256 + if bgra then + r, b = b, r + end + return r + gg * 256 + b * 65536 + a * 16777216 + end + for z = 0, sz - 1 do + if compressed then + local x, y = 0, 0 + local slice = sx * sy + local i = 0 + while i < slice do + x, y = i % sx, i // sx + local c = value(x, y, z) + local run = 1 + while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do + run += 1 + end + if run > 2 then + w:u32le(CODEFLAG) + w:u32le(run) + w:u32le(c) + else + for _ = 1, run do + w:u32le(c) + end + end + i += run + end + w:u32le(NEXTSLICEFLAG) + else + for y = 0, sy - 1 do + for x = 0, sx - 1 do + w:u32le(value(x, y, z)) + end + end + end + end + end + return w:finish(), nil +end + +return Qb +end +__FILES["model/rbxm"] = function() + +-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, " "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +function Rbxm.variant(r: Bytes.Reader): string? + local b, p, e = r.buf, r.base + 32, r.limit + if r:peek(14) ~= MAGIC then + return nil + end + while p + 16 <= e do + local name, clen, ulen = readstring(b, p, 4), readu32(b, p + 4), readu32(b, p + 8) + local size = if clen == 0 then ulen else clen + if p + 16 + size > e or name == "END\0" then + break + end + if name == "INST" then + local body: buffer?, o = b, p + 16 + if clen ~= 0 then + body = if Zstd.isFrame(b, p + 16) then Zstd.decompress(b, p + 16, clen, { maxBytes = ulen }) else Lz4.decompress(b, p + 16, clen, ulen) + o = 0 + end + if body and o + 8 <= buffer.len(body) then + local q = o + 8 + readu32(body, o + 4) + if q < buffer.len(body) and readu8(body, q) == 1 then + return "rbxl" + end + end + end + p += 16 + size + end + return "rbxm" +end + +-- ------------------------------------------------------------------------------------------------ decode +type Class = { id: number, name: string, refs: { number }, service: boolean } + +-- a length-prefixed string at p of b (limit e): string, next | nil +local function str(b: buffer, p: number, e: number): (string?, number) + if p + 4 > e then + return nil, p + end + local n = readu32(b, p) + if p + 4 + n > e then + return nil, p + end + return readstring(b, p + 4, n), p + 4 + n +end + +function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + local maxInstances = opts and opts.maxInstances or 2 ^ 22 + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "header", base) + end + if readstring(b, base, 14) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local version = buffer.readu16(b, base + 14) + if version ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14) + end + local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20) + if nClasses < 0 or nInstances < 0 then + return nil, Err.new(Err.CORRUPT, "negative counts", base + 16) + end + if nInstances > maxInstances then + return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20) + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} } + local classes: { [number]: Class } = {} + local byRef: { [number]: Rbx.Instance } = {} + local shared: { string } = {} + local parented: { [Rbx.Instance]: boolean } = {} + local order: { Rbx.Instance } = {} + local anyService = false + local comp: { [string]: boolean } = {} + local ctx: Binary.Ctx = { + ref = function(n: number): any + return byRef[n] + end, + shared = shared, + } + local p = base + 32 + local ended = false + while p < limit do + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header", p) + end + local name = readstring(b, p, 4) + local clen, ulen = readu32(b, p + 4), readu32(b, p + 8) + local at = p + p += 16 + if ulen > maxBytes then + return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at) + end + local body: buffer, bo: number, be: number + if clen == 0 then + if p + ulen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + body, bo, be = b, p, p + ulen + p += ulen + comp.none = true + else + if p + clen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + local out, err + if Zstd.isFrame(b, p) then + out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen }) + comp.zstd = true + else + out, err = Lz4.decompress(b, p, clen, ulen) + comp.lz4 = true + end + if not out then + return nil, err + end + if buffer.len(out) ~= ulen then + return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at) + end + body, bo, be = out, 0, ulen + p += clen + end + if name == "END\0" then + ended = true + break + elseif name == "META" then + if bo + 4 > be then + return nil, Err.new(Err.TRUNCATED, "META", at) + end + local q = bo + 4 + for _ = 1, readu32(body, bo) do + local k, q1 = str(body, q, be) + local v, q2 = str(body, q1, be) + if not k or not v then + return nil, Err.new(Err.TRUNCATED, "META entry", at) + end + tree.metadata[k] = v + q = q2 + end + elseif name == "SSTR" then + if bo + 8 > be then + return nil, Err.new(Err.TRUNCATED, "SSTR", at) + end + local q = bo + 8 + for i = 1, readu32(body, bo + 4) do + local s, q2 = str(body, q + 16, be) + if not s then + return nil, Err.new(Err.TRUNCATED, "shared string", at) + end + shared[i] = s + q = q2 + end + elseif name == "INST" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local cname, q = str(body, bo + 4, be) + if not cname or q + 5 > be then + return nil, Err.new(Err.TRUNCATED, "INST", at) + end + local fmt, count = readu8(body, q), readu32(body, q + 1) + if count > nInstances then + return nil, Err.new(Err.CORRUPT, "more instances than the header says", at) + end + local refs, q2 = Binary.readRefs(body, q + 5, be, count) + if not refs then + return nil, Err.new(Err.TRUNCATED, "INST referents", at) + end + if id < 0 or classes[id] then + return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at) + end + local service = fmt == 1 + if service and q2 + count > be then + return nil, Err.new(Err.TRUNCATED, "INST service markers", at) + end + classes[id] = { id = id, name = cname, refs = refs, service = service } + for i, ref in refs do + if byRef[ref] then + return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at) + end + local inst = Rbx.instance(cname) + inst.referent = tostring(ref) + if service and readu8(body, q2 + i - 1) ~= 0 then + inst.service = true + anyService = true + end + byRef[ref] = inst + table.insert(order, inst) + end + elseif name == "PROP" then + local id = if bo + 4 <= be then readi32(body, bo) else -1 + local pname, q = str(body, bo + 4, be) + if not pname or q + 1 > be then + return nil, Err.new(Err.TRUNCATED, "PROP", at) + end + local cls = classes[id] + if not cls then + return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at) + end + local t = readu8(body, q) + local n = #cls.refs + local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx) + if vals then + local tname = Rbx.TYPE_NAMES[t] + for i, ref in cls.refs do + local inst = byRef[ref] + if pname == "Name" and t == 0x01 then + inst.name = vals[i] + else + inst.properties[pname] = { type = tname, value = vals[i] } + end + end + elseif msg == "unknown" then + local data = buffer.create(be - q - 1) + buffer.copy(data, 0, body, q + 1, be - q - 1) + for i, ref in cls.refs do + byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } } + end + else + return nil, Err.from(msg, at) + end + elseif name == "PRNT" then + if bo + 5 > be then + return nil, Err.new(Err.TRUNCATED, "PRNT", at) + end + if readu8(body, bo) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at) + end + local count = readu32(body, bo + 1) + local kids, q = Binary.readRefs(body, bo + 5, be, count) + local parents = if kids then Binary.readRefs(body, q, be, count) else nil + if not kids or not parents then + return nil, Err.new(Err.TRUNCATED, "PRNT referents", at) + end + for i = 1, count do + local child, parent = byRef[kids[i]], parents[i] >= 0 and byRef[parents[i]] or nil + if not child or (parents[i] >= 0 and not parent) then + return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at) + end + if parented[child] then + return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) + end + parented[child] = true + -- refuse cycles: the parent may not be a descendant of the child + local up: Rbx.Instance? = parent + while up do + if up == child then + return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at) + end + up = up.parent + end + Rbx.add(parent or tree, child) + end + else + local data = buffer.create(be - bo) + buffer.copy(data, 0, body, bo, be - bo) + table.insert(tree.extra, { name = name, data = data }) + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) + end + -- instances PRNT does not mention are roots + for _, inst in order do + if not parented[inst] then + table.insert(tree.roots, inst) + end + end + tree.place = anyService + local list = {} + for k in comp do + table.insert(list, k) + end + table.sort(list) + local src: any = tree.meta.source + src.compression = list + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the binary type of a property over a class's instances: type id, type name | nil, message +local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?) + local id, tname = nil, nil + for _, inst in insts do + local v = inst.properties[pname] + if v then + if type(v) ~= "table" or type(v.type) ~= "string" then + return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table" + end + local t = if v.type == "Raw" then -1 elseif v.type == "XmlRaw" then -2 else Rbx.TYPE_IDS[v.type] + if not t then + return nil, "property " .. pname .. ": unknown type " .. v.type + end + if id == nil then + id, tname = t, v.type + elseif id ~= t then + return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type + end + end + end + return id, tname +end + +local function chunk(w: Bytes.Writer, name: string, body: buffer, compress: boolean) + w:string(name) + local n = buffer.len(body) + if compress then + local z = Lz4.compress(body) :: buffer + w:u32le(buffer.len(z)) + w:u32le(n) + w:u32le(0) + w:bytes(z) + else + w:u32le(0) + w:u32le(n) + w:u32le(0) + w:bytes(body) + end +end + +local function putStr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local o: any = opts or {} + local compress = o.compression ~= "none" + local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true + -- every instance depth first; referents in that order + local insts: { Rbx.Instance } = {} + local refOf: { [any]: number } = {} + local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {} + local function visit(inst: any, parent: Rbx.Instance?): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refOf[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refOf[inst] = #insts + table.insert(insts, inst) + parentOf[inst] = parent + for _, c in inst.children or {} do + local e = visit(c, inst) + if e then + return e + end + end + return nil + end + for _, root in tree.roots do + local e = visit(root, nil) + if e then + return nil, e + end + end + -- classes by name + local byClass: { [string]: { Rbx.Instance } } = {} + local names = {} + for _, inst in insts do + local list = byClass[inst.className] + if not list then + list = {} + byClass[inst.className] = list + table.insert(names, inst.className) + end + table.insert(list, inst) + end + table.sort(names) + -- shared strings, in order of first use + local sharedIdx: { [string]: number } = {} + local sharedList: { string } = {} + local ctx: Binary.Ctx = { + refOf = function(v: any): number + return refOf[v] or -1 + end, + sharedIndex = function(s: string): number + local i = sharedIdx[s] + if not i then + table.insert(sharedList, s) + i = #sharedList - 1 + sharedIdx[s] = i + end + return i + end, + } + local props: { buffer } = {} + local instChunks: { buffer } = {} + for classId, cname in names do + local list = byClass[cname] + local id = classId - 1 + -- INST + local w = Bytes.writer(64 + 5 * #list) + w:u32le(id) + putStr(w, cname) + local service = place and parentOf[list[1]] == nil + for _, inst in list do + if inst.service then + service = true + end + end + w:u8(if service then 1 else 0) + w:u32le(#list) + local refs = table.create(#list, 0) + for i, inst in list do + refs[i] = refOf[inst] + end + Binary.writeRefs(w, refs) + if service then + for _, inst in list do + w:u8(if inst.service or (place and parentOf[inst] == nil) then 1 else 0) + end + end + table.insert(instChunks, w:finish()) + -- PROP: Name, then every property any instance of the class has, sorted + local pnames: { string } = {} + local seen: { [string]: boolean } = {} + for _, inst in list do + for pn in inst.properties do + if not seen[pn] and pn ~= "Name" then + seen[pn] = true + table.insert(pnames, pn) + end + end + end + table.sort(pnames) + table.insert(pnames, 1, "Name") + for _, pn in pnames do + local t: number?, tname: string? + if pn == "Name" then + t, tname = 0x01, "String" + else + local e + t, e = columnType(list, pn) + if not t then + return nil, Err.new(Err.ARG, e or "bad property") + end + tname = e + end + local pw = Bytes.writer(64) + pw:u32le(id) + putStr(pw, pn) + local tid = t :: number + if tid == -1 then + -- Raw: the column read from a file, written back only when this class still has exactly its instances + local first = list[1].properties[pn] + local raw = first and first.value + local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" + if ok then + for i, inst in list do + local v = inst.properties[pn] + if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then + ok = false + break + end + end + end + if ok then + pw:u8(raw.typeId) + pw:bytes(raw.data) + table.insert(props, pw:finish()) + end + elseif tid ~= -2 then + pw:u8(tid) + local vals = table.create(#list) + for i, inst in list do + if pn == "Name" then + vals[i] = if type(inst.name) == "string" then inst.name else inst.className + else + local v = inst.properties[pn] + if v then + vals[i] = v.value + else + vals[i] = Rbx.default(tname :: string) + end + end + end + local e = Binary.encode(tid, vals, #list, pw, ctx) + if e then + return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e) + end + table.insert(props, pw:finish()) + end + end + end + -- PRNT + local pw = Bytes.writer(16 + 8 * #insts) + pw:u8(0) + pw:u32le(#insts) + local kids, parents = table.create(#insts, 0), table.create(#insts, 0) + for i, inst in insts do + kids[i] = i - 1 + local par = parentOf[inst] + parents[i] = if par then refOf[par] else -1 + end + Binary.writeRefs(pw, kids) + Binary.writeRefs(pw, parents) + + local out = Bytes.writer(1024) + out:string(MAGIC) + out:u16le(0) + out:u32le(#names) + out:u32le(#insts) + out:u32le(0) + out:u32le(0) + local metaKeys = {} + for k, v in tree.metadata or {} do + if type(k) == "string" and type(v) == "string" then + table.insert(metaKeys, k) + end + end + if #metaKeys > 0 then + table.sort(metaKeys) + local mw = Bytes.writer(64) + mw:u32le(#metaKeys) + for _, k in metaKeys do + putStr(mw, k) + putStr(mw, (tree.metadata :: any)[k]) + end + chunk(out, "META", mw:finish(), compress) + end + if #sharedList > 0 then + local sw = Bytes.writer(64) + sw:u32le(0) + sw:u32le(#sharedList) + for _, s in sharedList do + local h = Md5.new() + h:update(buffer.fromstring(s)) + sw:string(h:digest()) + putStr(sw, s) + end + chunk(out, "SSTR", sw:finish(), compress) + end + for _, c in instChunks do + chunk(out, "INST", c, compress) + end + for _, c in props do + chunk(out, "PROP", c, compress) + end + chunk(out, "PRNT", pw:finish(), compress) + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then + chunk(out, x.name, x.data, compress) + end + end + chunk(out, "END\0", buffer.fromstring(""), false) + return out:finish(), nil +end + +return Rbxm +end +__FILES["model/rbxmx"] = function() + +-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, ``), read + write, to and from +-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). +-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. +-- Decode: , with of every type codecs/model/Rbx lists (string, BinaryString +-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), +-- token, BrickColor (as rbx-dom: an ; read back as BrickColor for the BrickColor properties of a short +-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, +-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, +-- PhysicalProperties, Ref, SharedString (+ ), UniqueId, Font, SecurityCapabilities); unknown property +-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. +-- tree.place is true when a root is a Workspace (rbxlx). +-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, +-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control +-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Md5 = __include("core/Md5") +local Xml = __include("codecs/text/Xml") +local Rbx = __include("codecs/model/Rbx") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxmx = { + name = "rbxmx", + category = "model", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxDepth: number?, -- XML nesting limit (default 10000) +} +type EncodeOptions = { + indent: (number | string)?, -- default 2 spaces; 0 for none +} + +-- ------------------------------------------------------------------------------------------------ constants +local XmlNode = Xml.element +local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch + +-- tag name -> type name for the simple (text) types +local SCALAR_TAGS: { [string]: string } = { + string = "String", + ProtectedString = "ProtectedString", + bool = "Bool", + int = "Int32", + int64 = "Int64", + float = "Float32", + double = "Float64", + token = "Enum", + BrickColor = "BrickColor", + SecurityCapabilities = "SecurityCapabilities", + UniqueId = "UniqueId", +} +-- BrickColor properties: XML writes them as (rbx-dom reads them through its reflection database); these known ones +-- read back as BrickColor (the rest of an stays Int32) +local BRICKCOLOR: { [string]: boolean } = { + ["BrickColorValue.Value"] = true, + ["SpawnLocation.TeamColor"] = true, + ["Team.TeamColor"] = true, + ["FlagStand.TeamColor"] = true, + ["Skin.SkinColor"] = true, +} +-- the strings rbx-dom writes as BinaryString (the rest decides by content) +local BINARY_NAMES: { [string]: boolean } = { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxmx.sniff(r: Bytes.Reader): number + local head = r:peek(256) + head = string.gsub(head, "^\239\187\191", "") + head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "") + if match(head, "^%s*]") then + return if find(head, "version=", 1, true) then 1 else 0.8 + end + return 0 +end + +-- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +function Rbxmx.variant(r: Bytes.Reader): string? + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + return if find(text, ' type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs +-- come back as { pending = referent }) +local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local tag = node.name + local scalar = SCALAR_TAGS[tag] + if tag == "int" and BRICKCOLOR[key] then + scalar = "BrickColor" + end + if scalar then + local s = Xml.text(node) + if scalar == "String" or scalar == "ProtectedString" then + return scalar, s + elseif scalar == "Bool" then + return scalar, match(s, "^%s*true%s*$") ~= nil + elseif scalar == "UniqueId" then + return scalar, string.lower((string.gsub(s, "%s", ""))) + end + return scalar, num(s) + elseif tag == "BinaryString" then + local data = Base64.decode((string.gsub(Xml.text(node), "%s", ""))) + return "BinaryString", if data then buffer.tostring(data) else "" + elseif tag == "Content" or tag == "ContentId" then + local url = Xml.child(node, "url") + if url then + return "ContentId", Xml.text(url) + end + local uri = Xml.child(node, "uri") + if uri then + return "Content", Xml.text(uri) + end + local obj = Xml.child(node, "Object") or Xml.child(node, "Ref") + if obj then + return "Content", { pending = Xml.text(obj) } + end + if Xml.child(node, "null") then + return (if tag == "ContentId" then "ContentId" else "Content"), (if tag == "ContentId" then "" else nil) + end + return "ContentId", Xml.text(node) + elseif tag == "Vector2" or tag == "Vector2int16" then + return tag, comps(node, { "X", "Y" }) + elseif tag == "Vector3" or tag == "Vector3int16" then + return tag, comps(node, { "X", "Y", "Z" }) + elseif tag == "Color3" then + if Xml.child(node, "R") then + return tag, comps(node, { "R", "G", "B" }) + end + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256 / 255, (v // 256) % 256 / 255, v % 256 / 255 } + elseif tag == "Color3uint8" then + local v = num(Xml.text(node)) % 4294967296 + return tag, { (v // 65536) % 256, (v // 256) % 256, v % 256 } + elseif tag == "CoordinateFrame" or tag == "CFrame" then + return "CFrame", comps(node, CF_NAMES) + elseif tag == "OptionalCoordinateFrame" then + local cf = Xml.child(node, "CFrame") + return "OptionalCFrame", if cf then comps(cf, CF_NAMES) else nil + elseif tag == "UDim" then + return tag, comps(node, { "S", "O" }) + elseif tag == "UDim2" then + return tag, comps(node, { "XS", "XO", "YS", "YO" }) + elseif tag == "Rect2D" then + local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" }) + return "Rect", { a[1], a[2], b[1], b[2] } + elseif tag == "Ray" then + local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" }) + return tag, { a[1], a[2], a[3], b[1], b[2], b[3] } + elseif tag == "Faces" or tag == "Axes" then + local t = childText(node, string.lower(tag)) + return tag, num(t or Xml.text(node)) + elseif tag == "NumberRange" then + local v = numbers(Xml.text(node)) + return tag, { v[1] or 0, v[2] or 0 } + elseif tag == "NumberSequence" or tag == "ColorSequence" then + local k = if tag == "NumberSequence" then 3 else 5 + local v = numbers(Xml.text(node)) + local seq = {} + for i = 1, #v - k + 1, k do + table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0))) + end + return tag, seq + elseif tag == "PhysicalProperties" then + local custom = childText(node, "CustomPhysics") + if not custom or not match(custom, "^%s*true%s*$") then + return tag, nil + end + local v = comps(node, PHYS_NAMES) + local a = childText(node, "AcousticAbsorption") + v[6] = if a then num(a) else 1 + return tag, v + elseif tag == "Ref" then + local s = string.gsub(Xml.text(node), "%s", "") + return tag, if s == "" or s == "null" then nil else { pending = s } + elseif tag == "SharedString" then + local key = string.gsub(Xml.text(node), "%s", "") + return tag, shared[key] or "" + elseif tag == "Font" then + local fam = Xml.child(node, "Family") + local face = Xml.child(node, "CachedFaceId") + local f = { + family = if fam then childText(fam, "url") or Xml.text(fam) else "", + weight = num(childText(node, "Weight") or "400"), + style = if match(childText(node, "Style") or "", "Italic") then "Italic" else "Normal", + cachedFaceId = if face then childText(face, "url") or nil else nil, + } + if f.cachedFaceId == "" then + f.cachedFaceId = nil + end + return tag, f + end + return "XmlRaw", node +end + +-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary +-- decodes of the same data are equal. Which components are floats, by type (true = all) +local F32: { [string]: any } = { + Float32 = true, + Vector2 = true, + Vector3 = true, + Color3 = true, + CFrame = true, + OptionalCFrame = true, + Rect = true, + Ray = true, + NumberRange = true, + NumberSequence = true, + ColorSequence = true, + PhysicalProperties = true, + UDim = { true, false }, + UDim2 = { true, false, true, false }, +} +local f32buf = buffer.create(4) +local function f32(v: number): number + buffer.writef32(f32buf, 0, v) + return buffer.readf32(f32buf, 0) +end +local function round32(v: any, which: any): any + if type(v) == "number" then + return f32(v) + elseif type(v) == "table" then + for i, x in v do + if type(x) == "table" then + round32(x, true) + elseif type(x) == "number" and (which == true or which[i]) then + v[i] = f32(x) + end + end + end + return v +end +local function readValue(node: Xml.Node, shared: { [string]: string }, key: string): (string, any) + local t, v = readRaw(node, shared, key) + local which = F32[t] + if which then + v = round32(v, which) + end + return t, v +end + +function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } :: any) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or root.name ~= "roblox" then + return nil, Err.new(Err.CORRUPT, "the root element is not ") + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxmx", version = root.attrs.version } + -- shared strings first (properties name them by key) + local shared: { [string]: string } = {} + for _, ss in Xml.children(root, "SharedStrings") do + for _, s in Xml.children(ss, "SharedString") do + local key = s.attrs.md5 + local data = Base64.decode((string.gsub(Xml.text(s), "%s", ""))) + if key and data then + shared[key] = buffer.tostring(data) + end + end + end + local byRef: { [string]: Rbx.Instance } = {} + local pending: { { any } } = {} -- { value table, field, referent } + local function item(node: Xml.Node, parent: any): Err.Err? + local cls = node.attrs.class + if type(cls) ~= "string" then + return Err.new(Err.CORRUPT, "an without a class") + end + local inst = Rbx.instance(cls) + local ref = node.attrs.referent + if type(ref) == "string" then + inst.referent = ref + byRef[ref] = inst + end + Rbx.add(parent, inst) + for _, c in node.children do + if type(c) == "table" then + if c.name == "Properties" then + for _, pnode in c.children do + if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then + local pname = pnode.attrs.name + if type(pname) == "string" then + local t, v = readValue(pnode, shared, cls .. "." .. pname) + if pname == "Name" and (t == "String" or t == "ProtectedString") then + inst.name = v + else + local val = { type = t, value = v } + inst.properties[pname] = val + if type(v) == "table" and v.pending then + table.insert(pending, { val, v.pending }) + end + end + end + end + end + elseif c.name == "Item" then + local e = item(c, inst) + if e then + return e + end + end + end + end + return nil + end + for _, c in root.children do + if type(c) == "table" then + if c.name == "Item" then + local e = item(c, tree) + if e then + return nil, e + end + elseif c.name == "Meta" then + if type(c.attrs.name) == "string" then + tree.metadata[c.attrs.name] = Xml.text(c) + end + elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then + table.insert(tree.extra, c) + end + end + end + for _, p in pending do + p[1].value = byRef[p[2]] + end + for _, rt in tree.roots do + if rt.className == "Workspace" then + tree.place = true + end + end + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest text that reads back as the same float (single: f32 values; else f64) +local function fmt(v: any, single: boolean?): string + if type(v) ~= "number" then + v = 0 + end + if v ~= v then + return "NAN" + elseif v == math.huge then + return "INF" + elseif v == -math.huge then + return "-INF" + end + if single then + v = f32(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%.0f", v) + end + for d = if single then 6 else 15, if single then 9 else 17 do + local s = format("%." .. d .. "g", v) + local back = tonumber(s) or 0 + if (if single then f32(back) else back) == v then + return s + end + end + return format("%.17g", v) +end +local function int(v: any): string + return format("%.0f", math.floor(if type(v) == "number" and v == v and math.abs(v) ~= math.huge then v else 0)) +end + +local function textEl(tag: string, text: string): Xml.Node + return XmlNode(tag, nil, { text }) +end +local function compsEl(tag: string, attrs: { [string]: string }?, names: { string }, v: any, single: boolean?, ints: boolean?): Xml.Node + local kids = {} + for i, n in names do + local x = if type(v) == "table" then v[i] else 0 + table.insert(kids, textEl(n, if ints then int(x) else fmt(x, single))) + end + return XmlNode(tag, attrs, kids) +end + +local function hexDigits(i: number): string + return format("%032X", i) +end + +local function xmlSafe(s: string): boolean + if find(s, "[%z\1-\8\11\12\14-\31\127]") then + return false + end + return utf8.len(s) ~= nil +end + +-- a property -> its element, or nil to skip +local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node? + local t, x = v.type, v.value + local a = { name = name } + if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then + local s = if type(x) == "string" then x else "" + if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then + return XmlNode("BinaryString", a, { Base64.encode(s) }) + end + return XmlNode(if t == "ProtectedString" then "ProtectedString" else "string", a, { s }) + elseif t == "ContentId" then + local s = if type(x) == "string" then x else "" + return XmlNode("ContentId", a, { if s == "" then XmlNode("null") else textEl("url", s) }) + elseif t == "Content" then + if type(x) == "string" then + return XmlNode("Content", a, { textEl("uri", x) }) + elseif type(x) == "table" then + return XmlNode("Content", a, { textEl("Object", refOf(x)) }) + end + return XmlNode("Content", a, { XmlNode("null") }) + elseif t == "Bool" then + return XmlNode("bool", a, { if x then "true" else "false" }) + elseif t == "Int32" then + return XmlNode("int", a, { int(x) }) + elseif t == "Int64" then + return XmlNode("int64", a, { int(x) }) + elseif t == "Float32" then + return XmlNode("float", a, { fmt(x, true) }) + elseif t == "Float64" then + return XmlNode("double", a, { fmt(x) }) + elseif t == "Enum" then + return XmlNode("token", a, { int(x) }) + elseif t == "BrickColor" then + return XmlNode("int", a, { int(x) }) + elseif t == "SecurityCapabilities" then + return XmlNode("SecurityCapabilities", a, { int(x) }) + elseif t == "UniqueId" then + return XmlNode("UniqueId", a, { if type(x) == "string" then string.lower(x) else string.rep("0", 32) }) + elseif t == "Vector2" then + return compsEl(t, a, { "X", "Y" }, x, true) + elseif t == "Vector3" then + return compsEl(t, a, { "X", "Y", "Z" }, x, true) + elseif t == "Vector2int16" then + return compsEl(t, a, { "X", "Y" }, x, false, true) + elseif t == "Vector3int16" then + return compsEl(t, a, { "X", "Y", "Z" }, x, false, true) + elseif t == "Color3" then + return compsEl(t, a, { "R", "G", "B" }, x, true) + elseif t == "Color3uint8" then + local c = if type(x) == "table" then x else { 0, 0, 0 } + local function b(i: number): number + return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255) + end + return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) }) + elseif t == "CFrame" then + return compsEl("CoordinateFrame", a, CF_NAMES, x, true) + elseif t == "OptionalCFrame" then + return XmlNode("OptionalCoordinateFrame", a, if type(x) == "table" then { compsEl("CFrame", nil, CF_NAMES, x, true) } else {}) + elseif t == "UDim" then + local u = if type(x) == "table" then x else { 0, 0 } + return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) }) + elseif t == "UDim2" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) }) + elseif t == "Rect" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0 } + return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) }) + elseif t == "Ray" then + local u = if type(x) == "table" then x else { 0, 0, 0, 0, 0, 0 } + return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) }) + elseif t == "Faces" or t == "Axes" then + return XmlNode(t, a, { textEl(string.lower(t), int(x)) }) + elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then + local parts = {} + local list = if type(x) ~= "table" then {} elseif t == "NumberRange" then { x } else x + for _, key in list do + for _, c in key do + table.insert(parts, fmt(c, true) .. " ") + end + end + return XmlNode(t, a, { table.concat(parts) }) + elseif t == "PhysicalProperties" then + if type(x) ~= "table" then + return XmlNode(t, a, { textEl("CustomPhysics", "false") }) + end + local kids = { textEl("CustomPhysics", "true") } + for i, n in PHYS_NAMES do + table.insert(kids, textEl(n, fmt(x[i], true))) + end + table.insert(kids, textEl("AcousticAbsorption", fmt(if x[6] ~= nil then x[6] else 1, true))) + return XmlNode(t, a, kids) + elseif t == "Ref" then + return XmlNode("Ref", a, { if x ~= nil then refOf(x) else "null" }) + elseif t == "SharedString" then + return XmlNode("SharedString", a, { sharedKey(if type(x) == "string" then x else "") }) + elseif t == "Font" then + local f = if type(x) == "table" then x else Rbx.default("Font") + local kids = { + XmlNode("Family", nil, { textEl("url", if type(f.family) == "string" then f.family else "") }), + textEl("Weight", int(f.weight or 400)), + textEl("Style", if f.style == "Italic" then "Italic" else "Normal"), + } + if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then + table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) })) + end + return XmlNode("Font", a, kids) + elseif t == "XmlRaw" then + if type(x) == "table" and type(x.name) == "string" then + local copy = XmlNode(x.name, nil, x.children) + for k, val in x.attrs do + Xml.setAttr(copy, k, val) + end + Xml.setAttr(copy, "name", name) + return copy + end + end + return nil +end + +function Rbxmx.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local refs: { [any]: string } = {} + local count = 0 + local function assign(inst: any): Err.Err? + if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refs[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refs[inst] = "RBX" .. hexDigits(count) + count += 1 + for _, c in inst.children or {} do + local e = assign(c) + if e then + return e + end + end + return nil + end + for _, rt in tree.roots do + local e = assign(rt) + if e then + return nil, e + end + end + local function refOf(x: any): string + return refs[x] or "null" + end + local sharedKeys: { [string]: string } = {} + local sharedList: { string } = {} + local function sharedKey(s: string): string + local k = sharedKeys[s] + if not k then + local h = Md5.new() + h:update(buffer.fromstring(s)) + k = Base64.encode(h:digest()) + sharedKeys[s] = k + table.insert(sharedList, s) + end + return k + end + local function item(inst: Rbx.Instance): Xml.Node + local props = { textEl("string", inst.name or inst.className) } + props[1].attrs.name = "Name" + local names: { string } = {} + for k in inst.properties do + if k ~= "Name" then + table.insert(names, k) + end + end + table.sort(names) + for _, k in names do + local v = inst.properties[k] + if type(v) == "table" then + local el = writeValue(k, v, refOf, sharedKey) + if el then + table.insert(props, el) + end + end + end + local kids = { XmlNode("Properties", nil, props) } + for _, c in inst.children or {} do + table.insert(kids, item(c)) + end + local el = XmlNode("Item", nil, kids) + Xml.setAttr(el, "class", inst.className) + Xml.setAttr(el, "referent", refs[inst]) + return el + end + local root = XmlNode("roblox", nil, {}) + Xml.setAttr(root, "version", "4") + local metaKeys = {} + for k in tree.metadata or {} do + table.insert(metaKeys, k) + end + table.sort(metaKeys) + for _, k in metaKeys do + local m = textEl("Meta", tostring((tree.metadata :: any)[k])) + m.attrs.name = k + Xml.append(root, m) + end + for _, rt in tree.roots do + Xml.append(root, item(rt)) + end + for _, x in tree.extra or {} do + if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then + Xml.append(root, x) + end + end + if #sharedList > 0 then + local ss = XmlNode("SharedStrings", nil, {}) + for _, s in sharedList do + local el = XmlNode("SharedString", nil, { Base64.encode(s) }) + Xml.setAttr(el, "md5", sharedKeys[s]) + Xml.append(ss, el) + end + Xml.append(root, ss) + end + local indent = if opts and opts.indent ~= nil then opts.indent else 2 + local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return Rbxmx +end +__FILES["model/robloxmesh"] = function() + +-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh +-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. +-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, +-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown +-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes +-- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC +-- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed +-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in +-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' +-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes +-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw +-- (meta.source.facs). meta.up = "y"; units are studs. +-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every +-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes +-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to +-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). +-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing +-- 3.00 / 5.00+ / FACS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Draco = __include("codecs/model/Draco") +local Parse = __include("model/robloxmesh/Parse") +local Write = __include("model/robloxmesh/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local RobloxMesh = { + name = "robloxmesh", + category = "model", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxVertices: number?, -- default 2^24 + maxFaces: number?, -- default 2^25 +} +type EncodeOptions = { + version: ("2.00" | "4.00")?, -- default "2.00" +} + +-- ------------------------------------------------------------------------------------------------ constants +local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16 +local accessor = Types.Scene.accessor + +-- ------------------------------------------------------------------------------------------------ sniff +function RobloxMesh.sniff(r: Bytes.Reader): number + return if string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z) +local function boneMatrix(cf: { number }): { number } + return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } +end + +local function indices(r: Parse.Record, from: number, to: number): Types.Accessor + local n = math.max(0, to - from) + local d = buffer.create(n * 12) + buffer.copy(d, 0, r.faces, from * 12, n * 12) + return accessor(d, "u32", 1, n * 3) +end + +-- a Draco-compressed COREMESH body -> the record's vertex / face fields +local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?) + -- the stream follows a u32 byte count (accepted without it too) + if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then + len = buffer.readu32(b, off) + off += 4 + end + local g, err = Draco.decode(b, off, len) + if not g then + return nil, (err :: Err.Err).message + end + if g.kind ~= "mesh" then + return nil, "corrupt: Draco COREMESH holds a point cloud" + end + local n = g.numPoints + local by: { [string]: Draco.Attribute } = {} + for _, a in g.attributes do + local key = if a.name == "GENERIC" and a.components == 4 then "TANGENT" else a.name + if not by[key] then + by[key] = a + end + end + local pos = by.POSITION + if not pos or pos.components < 3 then + return nil, "corrupt: Draco COREMESH without positions" + end + -- an attribute's values as numbers (normalized integers as -1..1 / 0..1) + local function getter(a: Draco.Attribute): (number, number) -> number + local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type + local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) + if not rd then + return function(_i: number, _c: number): number + return 0 + end + end + return rd + end + local function floats(a: Draco.Attribute?, comps: number): buffer + local out = buffer.create(n * comps * 4) + if a then + local get = getter(a) + local m = math.min(comps, a.components) + for i = 0, n - 1 do + for c = 0, m - 1 do + writef32(out, (i * comps + c) * 4, get(i, c)) + end + end + end + return out + end + local tan: buffer? = nil + if by.TANGENT then + local get = getter(by.TANGENT) + local t = buffer.create(n * 4) + for i = 0, n - 1 do + for c = 0, 3 do + local v = if c < by.TANGENT.components then get(i, c) else 1 + buffer.writei8(t, i * 4 + c, math.clamp(math.floor(v * 127 + 0.5), -127, 127)) + end + end + tan = t + end + local col: buffer? = nil + if by.COLOR then + local a = by.COLOR + local c = buffer.create(n * 4) + if a.type == "u8" and a.components == 4 then + buffer.copy(c, 0, a.data, 0, n * 4) + else + local get = getter(a) + for i = 0, n - 1 do + for k = 0, 3 do + local v = if k < a.components then get(i, k) else 1 + if a.type ~= "f32" and not a.normalized then + v /= 255 + end + writeu8(c, i * 4 + k, math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + end + end + col = c + end + return { + numVerts = n, + pos = floats(pos, 3), + nrm = floats(by.NORMAL, 3), + uv = floats(by.TEX_COORD, 2), + tan = tan, + col = col, + numFaces = g.numFaces, + faces = g.indices :: buffer, + }, nil +end + +-- Parse is native: nothing may throw through it, so the callback never does +local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?) + local ok, c, err = pcall(dracoCore, b, off, len) + if not ok then + return nil, "corrupt: Draco COREMESH: " .. tostring(c) + end + return c, err +end + +function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local lim: Parse.Limits = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25, core = safeCore } + local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim) + if not r then + return nil, Err.from(msg, rd.base) + end + local nv, nf = r.numVerts, r.numFaces + local attrs: { [string]: Types.Accessor } = { + POSITION = accessor(r.pos, "f32", 3, nv), + NORMAL = accessor(r.nrm, "f32", 3, nv), + TEXCOORD_0 = accessor(r.uv, "f32", 2, nv), + } + local tan = r.tan + if tan then + local t = buffer.create(nv * 16) + for i = 0, nv - 1 do + local x, y, z, w = Parse.tangent(tan, i) + writef32(t, i * 16, x) + writef32(t, i * 16 + 4, y) + writef32(t, i * 16 + 8, z) + writef32(t, i * 16 + 12, w) + end + attrs.TANGENT = accessor(t, "f32", 4, nv) + end + if r.col then + attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) + end + -- LOD ranges (offsets clamped to the faces) + local offs = {} + for _, o in r.lods do + table.insert(offs, math.clamp(o, 0, nf)) + end + if #offs < 2 then + offs = { 0, nf } + end + local scene = Types.Scene.new() + local prim: Types.Primitive = { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" } + local lods = {} + for k = 2, #offs - 1 do + table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" }) + end + local mesh: Types.Mesh = { name = "Mesh", primitives = { prim } } + if #lods > 0 then + mesh.extras = { lods = lods } + end + scene.meshes[1] = mesh + scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + -- bones and skinning + local nb = #r.bones + if nb > 0 then + local world: { { number } } = table.create(nb) :: any + for i, bone in r.bones do + world[i] = boneMatrix(bone.cf) + end + local joints = table.create(nb, 0) + local ibm = buffer.create(nb * 64) + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + local m = world[i] + if parent then + local inv = Mat4.inverse(world[parent]) + if inv then + m = Mat4.mul(inv, m) + end + end + local node: Types.Node = { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } } + table.insert(scene.nodes, node) + joints[i] = #scene.nodes + local inv = Mat4.inverse(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k]) + end + end + for i, bone in r.bones do + local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil + if parent then + table.insert(scene.nodes[joints[parent]].children, joints[i]) + else + table.insert(scene.roots, joints[i]) + end + end + scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) } + scene.nodes[1].skin = 1 + local env = r.env + if env then + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4) + for i = 0, nv - 1 do + for k = 0, 3 do + writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k)) + end + end + for _, s in r.subsets do + local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1 + for v = s.vertsBegin, last do + for k = 0, 3 do + local li = readu8(env, v * 8 + k) + local g = s.bones[li + 1] + writeu16(jb, v * 8 + k * 2, if g and g < nb and readu8(wb, v * 4 + k) > 0 then g else 0) + end + end + end + attrs.JOINTS_0 = accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv) + end + end + local subsets = {} + for _, s in r.subsets do + table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones }) + end + scene.meta.up = "y" + scene.meta.source = { + format = "robloxmesh", + version = r.version, + lodType = r.lodType, + highQualityLods = r.highQualityLods, + lodOffsets = r.lods, + subsets = subsets, + facsFormat = r.facsFormat, + facs = r.facs, + chunks = r.chunks, + draco = if r.coreVersion == 2 then true else nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(attr: any, i: number, c: number, default: number): number + if not attr or c >= attr.components then + return default + end + return attr.values[i * attr.components + c + 1] +end + +-- area-weighted vertex normals +local function normals(pos: buffer, nv: number, corners: { number }): buffer + local acc = table.create(nv * 3, 0) + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + writef32(out, v * 12, x / l) + writef32(out, v * 12 + 4, y / l) + writef32(out, v * 12 + 8, z / l) + else + writef32(out, v * 12 + 4, 1) + end + end + return out +end + +-- world matrices of every node (parents through children lists) +local function worlds(scene: any): { [number]: { number } } + local out: { [number]: { number } } = {} + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parent[c] = i + end + end + local function world(i: number, depth: number): { number } + if out[i] then + return out[i] + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + if p and depth < 256 then + m = Mat4.mul(world(p, depth + 1), m) + end + out[i] = m + return m + end + for i in scene.nodes do + world(i, 0) + end + return out +end + +-- the bones of a skin: Parse.Bone list, or nil, message +local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?) + local joints = skin.joints + if type(joints) ~= "table" or #joints == 0 then + return nil, "a skin without joints" + end + if #joints > 65534 then + return nil, "too many joints" + end + local w = worlds(scene) + local index: { [number]: number } = {} + for i, j in joints do + index[j] = i - 1 + end + local parentOf: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + parentOf[c] = i + end + end + local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices) + local out = {} + for i, j in joints do + local node = scene.nodes[j] + if not node then + return nil, "a joint names a missing node" + end + local m = w[j] + if ibm and #ibm >= i * 16 then + local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0))) + if inv then + m = inv + end + end + local ex = if type(node.extras) == "table" then node.extras else {} + local p = parentOf[j] + out[i] = { + name = if type(node.name) == "string" then node.name else "Bone" .. i, + parent = if p then index[p] else nil, + lodParent = if type(ex.lodParent) == "number" then ex.lodParent else 0xFFFF, + culling = if type(ex.culling) == "number" then ex.culling else 0, + cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }, + } + end + return out, nil +end + +-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) +local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?) + local nv = #order + local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0 + local col = nil + if C then + local scale = if C.raw then 1 else 255 + local white = true + col = buffer.create(nv * 4) + for i, src in order do + for k = 0, 3 do + local v = math.clamp(math.floor(num(C, src, k, if C.raw then 255 else 1) * scale + 0.5), 0, 255) + writeu8(col, (i - 1) * 4 + k, v) + if v ~= 255 then + white = false + end + end + end + if white then + col = nil + end + end + for i, src in order do + local o = i - 1 + for k = 0, 2 do + writef32(pos, o * 12 + k * 4, num(P, src, k, 0)) + end + if N then + for k = 0, 2 do + writef32(nb, o * 12 + k * 4, num(N, src, k, 0)) + end + elseif nrm then + buffer.copy(nb, o * 12, nrm, src * 12, 12) + end + writef32(uv, o * 8, num(U, src, 0, 0)) + writef32(uv, o * 8 + 4, num(U, src, 1, 0)) + if T then + for k = 0, 3 do + local v = math.clamp(math.floor(num(T, src, k, if k == 3 then 1 else 0) * 127 + 0.5), -127, 127) + writeu8(tan, o * 4 + k, v % 256) + end + else + buffer.writeu32(tan, o * 4, 0x7F810000) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv +end + +function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or "2.00" + if version ~= "2.00" and version ~= "4.00" then + return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"") + end + if type(scene) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true } + local m, merr = Flatten.merge(scene, function(name: string): boolean + return keep[name] == true + end, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local corners = m.corners + if not m.sizes or #corners == 0 then + return nil, Err.new(Err.ARG, "no triangles to write") + end + local nv0 = m.count + if nv0 > 2 ^ 32 - 1 then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local r: Parse.Record = { + version = version, + numVerts = 0, + numFaces = #corners // 3, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + facsFormat = 0, + chunks = {}, + } + local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" then scene.meta.source else nil + if src and type(src.lodType) == "number" then + r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0 + end + -- normals when the scene has none + local nrm: buffer? = nil + if not m.attrs.NORMAL then + local pb = buffer.create(nv0 * 12) + for i = 0, nv0 - 1 do + for k = 0, 2 do + writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0)) + end + end + nrm = normals(pb, nv0, corners) + end + -- the skin (4.00): the first node with a mesh and a skin + local skin = nil + if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then + for _, n in scene.nodes or {} do + if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then + skin = scene.skins[n.skin] + break + end + end + end + local nf = #corners // 3 + if skin then + local bones, berr = skinBones(scene, skin) + if not bones then + return nil, Err.new(Err.ARG, berr or "bad skin") + end + r.bones = bones + local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 + local wscale = if W.raw then 1 / 255 else 1 + local nb = #bones + -- per vertex: up to 4 (joint, weight) pairs with weight > 0 + local influences: { { { number } } } = table.create(nv0) :: any + for v = 0, nv0 - 1 do + local list = {} + for k = 0, 3 do + local wt = num(W, v, k, 0) * wscale + local j = num(J, v, k, 0) + if wt > 0 and j >= 0 and j < nb then + table.insert(list, { j, wt }) + end + end + influences[v + 1] = list + end + -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + local faceIdx = buffer.create(nf * 12) + local order: { number } = {} + local s: any = nil + local function close() + if s then + table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones }) + end + end + local function open(f: number) + s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} } + end + open(0) + for f = 0, nf - 1 do + local need = {} + local extra = 0 + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + if s.local_[inf[1]] == nil and not need[inf[1]] then + need[inf[1]] = true + extra += 1 + end + end + end + if #s.bones + extra > 26 then + close() + open(f) + for c = 1, 3 do + for _, inf in influences[corners[f * 3 + c] + 1] do + need[inf[1]] = true + end + end + end + for j in need do + if s.local_[j] == nil then + table.insert(s.bones, j) + s.local_[j] = #s.bones - 1 + end + end + for c = 1, 3 do + local v = corners[f * 3 + c] + local nvx = s.remap[v] + if not nvx then + table.insert(order, v) + nvx = #order - 1 + s.remap[v] = nvx + end + buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx) + end + s.faceCount += 1 + end + close() + r.faces = faceIdx + fill(r, m, order, nrm) + -- envelopes: subset-local bone indices, weights summing to 255 + local env = buffer.create(#order * 8) + for _, sub in r.subsets do + local loc: { [number]: number } = {} + for i, j in sub.bones do + loc[j] = i - 1 + end + for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do + local list = influences[order[o + 1] + 1] + local total = 0 + for _, inf in list do + total += inf[2] + end + local bytes, sum, best = {}, 0, 1 + for k, inf in list do + local b = if total > 0 then math.floor(inf[2] / total * 255 + 0.5) else 0 + bytes[k] = b + sum += b + if inf[2] > list[best][2] then + best = k + end + end + if #list > 0 then + bytes[best] += 255 - sum + end + for k = 0, 3 do + local inf = list[k + 1] + writeu8(env, o * 8 + k, if inf then loc[inf[1]] or 0 else 0) + writeu8(env, o * 8 + 4 + k, if inf then math.clamp(bytes[k + 1], 0, 255) else 0) + end + end + end + r.env = env + r.lods = { 0, nf } + else + local order = table.create(nv0, 0) + for i = 1, nv0 do + order[i] = i - 1 + end + fill(r, m, order, nrm) + local faces = buffer.create(nf * 12) + for i, c in corners do + buffer.writeu32(faces, (i - 1) * 4, c) + end + r.faces = faces + r.lods = { 0, nf } + -- extra LODs of a single untransformed primitive + local part = m.parts[1] + local mesh = part and part.mesh + local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil + if version == "4.00" and type(lods) == "table" and #lods > 0 then + local list = {} + for _, lp in lods do + local idx = if type(lp) == "table" and lp.indices then Flatten.numbers(lp.indices) else nil + if idx and #idx % 3 == 0 then + table.insert(list, idx) + end + end + local total = nf + for _, idx in list do + total += #idx // 3 + end + local all = buffer.create(total * 12) + buffer.copy(all, 0, faces, 0, nf * 12) + local at = nf + for _, idx in list do + for i, c in idx do + if c >= nv0 then + return nil, Err.new(Err.ARG, "a LOD index is out of range") + end + buffer.writeu32(all, at * 12 + (i - 1) * 4, c) + end + at += #idx // 3 + table.insert(r.lods, at) + end + r.faces, r.numFaces = all, total + end + end + return Write.write(r, version), nil +end + +return RobloxMesh +end +__FILES["model/robloxmesh/Parse"] = @native function() + + + +-- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version: +-- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the +-- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core +-- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data. +local Parse = {} + +local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Bone = { name: string, parent: number?, lodParent: number, culling: number, cf: { number } } -- cf: r00..r22, x, y, z +type Subset = { facesBegin: number, facesLength: number, vertsBegin: number, vertsLength: number, bones: { number } } +type Record = { + version: string, + numVerts: number, + numFaces: number, + pos: buffer, -- f32 x3 + nrm: buffer, -- f32 x3 + uv: buffer, -- f32 x2 + tan: buffer?, -- i8 x4 (nil in version 1) + col: buffer?, -- u8 x4 (nil when the vertices have none) + faces: buffer, -- u32 x3 + lods: { number }, + lodType: number, + highQualityLods: number, + bones: { Bone }, + subsets: { Subset }, + env: buffer?, -- per vertex: 4 subset-local bone indices, 4 weights (u8) + facsFormat: number, + facs: buffer?, + chunks: { { name: string, version: number, data: buffer } }, -- 6.00+ chunks kept raw (HSRAVIS, unknown) + coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed +} + +-- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record +-- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco) +type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer } +type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? } + +@native local function record(version: string): Record + return { + version = version, + numVerts = 0, + numFaces = 0, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + tan = nil, + col = nil, + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + env = nil, + facsFormat = 0, + facs = nil, + chunks = {}, + coreVersion = nil, + } +end + +-- ------------------------------------------------------------------------------------------------ version 1 +@native local function ascii(text: string, version: string, lim: Limits): (Record?, string?) + local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)")) + if not nf then + return nil, "corrupt: no face count" + end + if nf * 3 > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + local r = record(version) + local nv = nf * 3 + r.numVerts, r.numFaces = nv, nf + r.pos, r.nrm, r.uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + r.faces = buffer.create(nf * 12) + local scale = if version == "1.00" then 0.5 else 1 + local i = 0 + local vals = table.create(9, 0) + local k = 0 + local start = string.find(text, "[", 1, true) or (#text + 1) + for a, b, c in string.gmatch(string.sub(text, start), "%[%s*([^,%]]+)%s*,%s*([^,%]]+)%s*,%s*([^,%]]+)%s*%]") do + local x, y, z = tonumber(a), tonumber(b), tonumber(c) + if not x or not y or not z then + return nil, "corrupt: bad number in a vector" + end + vals[k * 3 + 1], vals[k * 3 + 2], vals[k * 3 + 3] = x, y, z + k += 1 + if k == 3 then + if i >= nv then + break + end + writef32(r.pos, i * 12, vals[1] * scale) + writef32(r.pos, i * 12 + 4, vals[2] * scale) + writef32(r.pos, i * 12 + 8, vals[3] * scale) + writef32(r.nrm, i * 12, vals[4]) + writef32(r.nrm, i * 12 + 4, vals[5]) + writef32(r.nrm, i * 12 + 8, vals[6]) + writef32(r.uv, i * 8, vals[7]) + writef32(r.uv, i * 8 + 4, 1 - vals[8]) -- version 1 stores V upside down + i += 1 + k = 0 + end + end + if i < nv then + return nil, "truncated: " .. i .. " of " .. nv .. " vertices" + end + for f = 0, nv - 1 do + writeu32(r.faces, f * 4, f) + end + r.lods = { 0, nf } + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ binary parts +-- vertices of size vs (36 / 40) at p +@native local function vertices(b: buffer, p: number, n: number, vs: number, r: Record) + local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + local col = if vs >= 40 then buffer.create(n * 4) else nil + for i = 0, n - 1 do + local q = p + i * vs + buffer.copy(pos, i * 12, b, q, 12) + buffer.copy(nrm, i * 12, b, q + 12, 12) + buffer.copy(uv, i * 8, b, q + 24, 8) + buffer.copy(tan, i * 4, b, q + 32, 4) + if col then + buffer.copy(col, i * 4, b, q + 36, 4) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col = pos, nrm, uv, tan, col + r.numVerts = n +end + +@native local function faces(b: buffer, p: number, n: number, fs: number, r: Record): string? + local out = buffer.create(n * 12) + local nv = r.numVerts + for i = 0, n - 1 do + for k = 0, 2 do + local v = readu32(b, p + i * fs + k * 4) + if v >= nv then + return "corrupt: face " .. i .. " uses vertex " .. v .. " of " .. nv + end + writeu32(out, i * 12 + k * 4, v) + end + end + r.faces, r.numFaces = out, n + return nil +end + +@native local function bones(b: buffer, p: number, n: number, names: string, r: Record) + for i = 0, n - 1 do + local q = p + i * 60 + local ni = readu32(b, q) + local name = string.match(string.sub(names, ni + 1), "^[^%z]*") or "" + local parent = readu16(b, q + 4) + local cf = table.create(12, 0) + for k = 0, 11 do + cf[k + 1] = readf32(b, q + 12 + 4 * k) + end + r.bones[i + 1] = { name = name, parent = if parent == 0xFFFF then nil else parent, lodParent = readu16(b, q + 6), culling = readf32(b, q + 8), cf = cf } + end +end + +@native local function subsets(b: buffer, p: number, n: number, r: Record) + for i = 0, n - 1 do + local q = p + i * 72 + local count = math.min(readu32(b, q + 16), 26) + local list = table.create(count, 0) + for k = 0, count - 1 do + list[k + 1] = readu16(b, q + 20 + 2 * k) + end + r.subsets[i + 1] = { facesBegin = readu32(b, q), facesLength = readu32(b, q + 4), vertsBegin = readu32(b, q + 8), vertsLength = readu32(b, q + 12), bones = list } + end +end + +@native local function lods(b: buffer, p: number, n: number, r: Record) + local out = table.create(n, 0) + for i = 0, n - 1 do + out[i + 1] = readu32(b, p + 4 * i) + end + r.lods = out +end + +-- ------------------------------------------------------------------------------------------------ versions 2 .. 5 +@native local function classic(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local major = tonumber(string.sub(version, 1, 1)) or 0 + if p + 12 > e then + return nil, "truncated header" + end + local hs = readu16(b, p) + local nv: number, nf: number, vs: number, fs: number = 0, 0, 40, 12 + local nlod: number, nbones: number, namesSize: number, nsub: number = 0, 0, 0, 0 + if major == 2 or major == 3 then + vs = readu8(b, p + 2) + fs = readu8(b, p + 3) + if major == 2 then + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + else + if p + 16 > e then + return nil, "truncated header" + end + nlod = readu16(b, p + 6) + nv = readu32(b, p + 8) + nf = readu32(b, p + 12) + end + else + if p + 24 > e then + return nil, "truncated header" + end + r.lodType = readu16(b, p + 2) + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + nlod = readu16(b, p + 12) + nbones = readu16(b, p + 14) + namesSize = readu32(b, p + 16) + nsub = readu16(b, p + 20) + r.highQualityLods = readu8(b, p + 22) + if major >= 5 then + if p + 32 > e then + return nil, "truncated header" + end + r.facsFormat = readu32(b, p + 24) + end + end + if vs < 36 or fs < 12 then + return nil, "corrupt: vertex size " .. vs .. ", face size " .. fs + end + if nv > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces" + end + local q = p + hs + if q + nv * vs > e then + return nil, "truncated vertices" + end + vertices(b, q, nv, vs, r) + q += nv * vs + if nbones > 0 then + if q + nv * 8 > e then + return nil, "truncated skinning" + end + local env = buffer.create(nv * 8) + buffer.copy(env, 0, b, q, nv * 8) + r.env = env + q += nv * 8 + end + if q + nf * fs > e then + return nil, "truncated faces" + end + local ferr = faces(b, q, nf, fs, r) + if ferr then + return nil, ferr + end + q += nf * fs + if q + nlod * 4 > e then + return nil, "truncated LOD offsets" + end + lods(b, q, nlod, r) + q += nlod * 4 + if q + nbones * 60 + namesSize + nsub * 72 > e then + return nil, "truncated bones / subsets" + end + local names = readstring(b, q + nbones * 60, namesSize) + bones(b, q, nbones, names, r) + q += nbones * 60 + namesSize + subsets(b, q, nsub, r) + q += nsub * 72 + if major >= 5 then + local size = readu32(b, p + 28) + if size > 0 then + if q + size > e then + return nil, "truncated FACS data" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q, size) + r.facs = facs + end + end + if #r.lods == 0 then + r.lods = { 0, nf } + end + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ versions 6 / 7 +@native local function chunked(b: buffer, p: number, e: number, version: string, lim: Limits): (Record?, string?) + local r = record(version) + local core = false + while p < e do + if p + 16 > e then + return nil, "truncated chunk header" + end + local name = string.gsub(readstring(b, p, 8), "%z+$", "") + local cv, size = readu32(b, p + 8), readu32(b, p + 12) + local q = p + 16 + local ce = q + size + if ce > e then + return nil, "truncated chunk " .. name + end + if name == "COREMESH" then + if cv == 2 then + local decodeCore = lim.core + if not decodeCore then + return nil, "unsupported: Draco-compressed COREMESH" + end + local c, cerr = decodeCore(b, q, size) + if not c then + return nil, cerr or "corrupt: bad Draco COREMESH" + end + if c.numVerts > lim.maxVertices or c.numFaces > lim.maxFaces then + return nil, "limit: " .. c.numVerts .. " vertices, " .. c.numFaces .. " faces" + end + r.numVerts, r.pos, r.nrm, r.uv, r.tan, r.col = c.numVerts, c.pos, c.nrm, c.uv, c.tan, c.col + r.numFaces, r.faces = c.numFaces, c.faces + core = true + r.coreVersion = 2 + elseif cv ~= 1 then + return nil, "unsupported: COREMESH version " .. cv + else + if q + 4 > ce then + return nil, "truncated COREMESH" + end + local nv = readu32(b, q) + if nv > lim.maxVertices then + return nil, "limit: " .. nv .. " vertices" + end + if q + 4 + nv * 40 + 4 > ce then + return nil, "truncated COREMESH vertices" + end + vertices(b, q + 4, nv, 40, r) + local fq = q + 4 + nv * 40 + local nf = readu32(b, fq) + if nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + if fq + 4 + nf * 12 > ce then + return nil, "truncated COREMESH faces" + end + local ferr = faces(b, fq + 4, nf, 12, r) + if ferr then + return nil, ferr + end + core = true + end + elseif name == "LODS" and cv == 1 then + if q + 7 > ce then + return nil, "truncated LODS" + end + r.lodType = readu16(b, q) + r.highQualityLods = readu8(b, q + 2) + local n = readu32(b, q + 3) + if q + 7 + n * 4 > ce then + return nil, "truncated LODS" + end + lods(b, q + 7, n, r) + elseif name == "SKINNING" and cv == 1 then + if not core then + return nil, "corrupt: SKINNING before COREMESH" + end + if q + 4 > ce then + return nil, "truncated SKINNING" + end + local ns = readu32(b, q) + local s = q + 4 + if ns ~= r.numVerts or s + ns * 8 + 4 > ce then + return nil, "corrupt: SKINNING count" + end + local env = buffer.create(ns * 8) + buffer.copy(env, 0, b, s, ns * 8) + r.env = env + s += ns * 8 + local nb = readu32(b, s) + s += 4 + if s + nb * 60 + 4 > ce then + return nil, "truncated SKINNING bones" + end + local bq = s + s += nb * 60 + local namesSize = readu32(b, s) + s += 4 + if s + namesSize + 4 > ce then + return nil, "truncated SKINNING names" + end + bones(b, bq, nb, readstring(b, s, namesSize), r) + s += namesSize + local nsub = readu32(b, s) + s += 4 + if s + nsub * 72 > ce then + return nil, "truncated SKINNING subsets" + end + subsets(b, s, nsub, r) + if nb == 0 then + r.env = nil + end + elseif name == "FACS" and cv == 1 then + if q + 4 > ce then + return nil, "truncated FACS" + end + local size = readu32(b, q) + if q + 4 + size > ce then + return nil, "truncated FACS" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q + 4, size) + r.facs, r.facsFormat = facs, 1 + else + local data = buffer.create(size) + buffer.copy(data, 0, b, q, size) + table.insert(r.chunks, { name = name, version = cv, data = data }) + end + p = ce + end + if not core then + return nil, "corrupt: no COREMESH chunk" + end + if #r.lods == 0 then + r.lods = { 0, r.numFaces } + end + return r, nil +end + +-- parse(b, p, e, lim) -> Record | nil, message +@native function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?) + if e - p < 13 then + return nil, "truncated: no version line" + end + local line = readstring(b, p, 12) + local version = string.match(line, "^version (%d%.%d%d)$") + if not version or readu8(b, p + 12) ~= 10 and readu8(b, p + 12) ~= 13 then + return nil, "corrupt: bad version line" + end + local q = p + 13 + if readu8(b, p + 12) == 13 and q < e and readu8(b, q) == 10 then + q += 1 + end + local major = string.sub(version, 1, 1) + if major == "1" then + return ascii(readstring(b, p, e - p), version, lim) + elseif major == "2" or major == "3" or major == "4" or major == "5" then + return classic(b, q, e, version, lim) + elseif major == "6" or major == "7" then + return chunked(b, q, e, version, lim) + end + return nil, "unsupported: version " .. version +end + +-- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +@native local function snorm(v: number): number + local x = if v >= 128 then v - 256 else v + return math.clamp(x / 127, -1, 1) +end +@native function Parse.tangent(tan: buffer, i: number): (number, number, number, number) + return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) +end + +return Parse +end +__FILES["model/robloxmesh/Write"] = @native function() + + + +-- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: +-- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning +-- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +local Parse = __include("model/robloxmesh/Parse") +local Bytes = __include("core/Bytes") + +local Write = {} + +@native local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boolean) + local p = w:reserve(if colors then 40 else 36) + local b = w.buf + buffer.copy(b, p, r.pos, i * 12, 12) + buffer.copy(b, p + 12, r.nrm, i * 12, 12) + buffer.copy(b, p + 24, r.uv, i * 8, 8) + if r.tan then + buffer.copy(b, p + 32, r.tan, i * 4, 4) + else + buffer.writeu32(b, p + 32, 0x7F810000) -- (0, 0, -1, 1) + end + if colors then + if r.col then + buffer.copy(b, p + 36, r.col, i * 4, 4) + else + buffer.writeu32(b, p + 36, 0xFFFFFFFF) + end + end + w.pos = p + (if colors then 40 else 36) +end + +-- write(r, version) -> buffer ("2.00" | "4.00") +@native function Write.write(r: Parse.Record, version: string): buffer + local nv, nf = r.numVerts, r.numFaces + local w = Bytes.writer(64 + nv * 48 + nf * 12) + w:string("version " .. version .. "\n") + if version == "2.00" then + local colors = r.col ~= nil + w:u16le(12) + w:u8(if colors then 40 else 36) + w:u8(12) + w:u32le(nv) + w:u32le(nf) + for i = 0, nv - 1 do + vertex(w, r, i, colors) + end + w:bytes(r.faces, 0, nf * 12) + return w:finish() + end + -- 4.00 + local names = {} + local nameAt = {} + local size = 0 + for i, bone in r.bones do + nameAt[i] = size + table.insert(names, bone.name .. "\0") + size += #bone.name + 1 + end + local nb = #r.bones + w:u16le(24) + w:u16le(r.lodType) + w:u32le(nv) + w:u32le(nf) + w:u16le(#r.lods) + w:u16le(nb) + w:u32le(size) + w:u16le(#r.subsets) + w:u8(r.highQualityLods) + w:u8(0) + for i = 0, nv - 1 do + vertex(w, r, i, true) + end + if nb > 0 then + local env = r.env + if env then + w:bytes(env, 0, nv * 8) + else + w:fill(0, nv * 8) + end + end + w:bytes(r.faces, 0, nf * 12) + for _, o in r.lods do + w:u32le(o) + end + for i, bone in r.bones do + w:u32le(nameAt[i]) + w:u16le(if bone.parent then bone.parent else 0xFFFF) + w:u16le(bone.lodParent) + w:f32le(bone.culling) + for k = 1, 12 do + w:f32le(bone.cf[k] or 0) + end + end + w:string(table.concat(names)) + for _, s in r.subsets do + w:u32le(s.facesBegin) + w:u32le(s.facesLength) + w:u32le(s.vertsBegin) + w:u32le(s.vertsLength) + w:u32le(#s.bones) + for k = 1, 26 do + w:u16le(s.bones[k] or 0xFFFF) + end + end + return w:finish() +end + +return Write +end +__FILES["model/schematic"] = function() + +-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: +-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and +-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, +-- Sponge, Litematic. +-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic +-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as +-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = +-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the +-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). +-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) +-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, +-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the +-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. +-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with +-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") +local Mcedit = __include("model/schematic/Mcedit") +local Sponge = __include("model/schematic/Sponge") +local Litematic = __include("model/schematic/Litematic") + +-- ------------------------------------------------------------------------------------------------ contract +local Schematic = { + name = "schematic", + category = "model", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- refuse schematics with more cells in total (default 2^26) + maxBytes: number?, -- refuse NBT that inflates past this (default 2^28) +} +type EncodeOptions = { + variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" + version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's) + dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21) + name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name + title: string?, -- .litematic Metadata.Name + compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them + level: number?, -- deflate level + format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...) +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_DATA_VERSION = 3953 +local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } +local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed) + +local function hinted(head: string, hints: { string }): boolean + for _, h in hints do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return true + end + end + return false +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Schematic.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" or p.endian ~= "big" then + return 0 + end + if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then + return 1 + end + local head = buffer.tostring(p.head) + return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 +end + +-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) +function Schematic.variant(r: Bytes.Reader): string? + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p then + return nil + end + if p.firstName == "Schematic" then + return "schem" + end + local head = buffer.tostring(p.head) + if hinted(head, LITEMATIC_HINTS) then + return "litematic" + elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then + return "schem" + end + return if p.name == "Schematic" then "schematic" else nil +end + +-- ------------------------------------------------------------------------------------------------ decode +-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil +local function variantOf(root: any): (string?, any) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, nil + end + if Types.isObject(root.Regions) then + return "litematic", root + end + if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then + return "schem", root.Schematic + end + if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then + return "schem", root + end + if type(root.Blocks) == "buffer" then + return "schematic", root + end + return nil, nil +end + +function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base) + if root == nil then + return nil, info + end + local variant, s = variantOf(root) + if not variant then + return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)") + end + local maxCells = o.maxCells or 2 ^ 26 + local regions, extra + if variant == "litematic" then + regions, extra = Litematic.read(s, maxCells) + elseif variant == "schem" then + regions, extra = Sponge.read(s, maxCells) + else + regions, extra = Mcedit.read(s, maxCells) + end + if not regions then + local msg = tostring(extra) + return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil) + end + local scene = Types.Scene.new() + scene.voxels = {} + for i, reg in regions do + local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices) + v.name = reg.name + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = reg.blockEntities + b.entities = reg.entities + table.insert(scene.voxels :: { Types.Voxels }, v) + table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.unit = 1 + local src: { [string]: any } = { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression } + for k, v in extra do + src[k] = v + end + scene.meta.source = src :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function regionsOf(value: any): ({ Common.Region }?, string?) + local out: { Common.Region } = {} + local function add(v: Types.Voxels, pos: { number }, name: string?): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local states, indices = Mc.blocksOf(v) + if not states then + return indices + end + local b = v.blocks + table.insert(out, { + name = name or v.name, + size = { v.size[1], v.size[2], v.size[3] }, + position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) }, + states = states, + indices = indices, + blockEntities = if b and b.blockEntities then b.blockEntities else {}, + entities = if b and b.entities then b.entities else {}, + }) + return nil + end + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, { 0, 0, 0 }, nil) + return if e then nil else out, e + end + if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then + return nil, "expected a Scene with voxels or a Types.Voxels" + end + local placed = false + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + placed = true + local e = add(value.voxels[node.voxels], p, node.name) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, e + end + end + if not placed then + for _, v in value.voxels do + local e = add(v, { 0, 0, 0 }, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- merge(regions) -> one region covering them all (air where none is) +local function merge(regions: { Common.Region }): Common.Region + if #regions == 1 then + return regions[1] + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, r in regions do + for k = 1, 3 do + lo[k] = math.min(lo[k], r.position[k]) + hi[k] = math.max(hi[k], r.position[k] + r.size[k]) + end + end + local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] + local states = { "minecraft:air" } + local out = buffer.create(sx * sy * sz * 2) + local bes, ents = {}, {} + for _, r in regions do + local base = #states + for _, st in r.states do + table.insert(states, st) + end + local rx, ry, rz = r.size[1], r.size[2], r.size[3] + local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3] + for z = 0, rz - 1 do + for y = 0, ry - 1 do + local s = (rx * (y + ry * z)) * 2 + local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2 + for _ = 0, rx - 1 do + buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base) + s += 2 + d += 2 + end + end + end + for _, be in r.blockEntities do + table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data }) + end + for _, e in r.entities do + table.insert(ents, e) + end + end + local st, idx = Common.dedupe(states, out, sx * sy * sz) + return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents } +end + +function Schematic.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local regions, rerr = regionsOf(value) + if not regions then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" then value.meta.source else nil + local ext = if o.name then string.lower(string.match(o.name, "%.([%w]+)$") or "") else nil + local key = o.format and string.lower(o.format) + local variant = o.variant + or (if ext == "schem" or ext == "schematic" or ext == "litematic" then ext else nil) + or (if key == "schem" or key == "litematic" then key else nil) + or (src and src.variant) + or "schem" + if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local same = src ~= nil and src.variant == variant + local base = if same then (src :: any).nbt else nil + local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION + local root, rootName, e + if variant == "litematic" then + local version = o.version or (if same then (src :: any).version else nil) or 6 + local title = o.title or (if o.name then string.match(o.name, "([^/\\]-)%.[%w]+$") else nil) + root, e = Litematic.write(regions, version, dataVersion, base, title) + rootName = "" + elseif variant == "schem" then + local version = o.version or (if same then (src :: any).version else nil) or 3 + if version ~= 1 and version ~= 2 and version ~= 3 then + return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3") + end + local sameVersion = same and (src :: any).version == version + local inner = if sameVersion and base then (if version >= 3 then base.Schematic else base) else nil + local sch + sch, e = Sponge.write(merge(regions), version, dataVersion, inner) + if sch and version >= 3 then + root, rootName = Common.merge(if sameVersion then base else nil, { { "Schematic", sch } }), "" + else + root, rootName = sch, "Schematic" + end + else + root, e = Mcedit.write(merge(regions), base) + rootName = "Schematic" + end + if not root then + return nil, Err.new(Err.ARG, tostring(e)) + end + if same and (src :: any).rootName ~= nil then + rootName = (src :: any).rootName + end + return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level }) +end + +return Schematic +end +__FILES["model/schematic/Common"] = function() + +-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, +-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, +-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Common = {} + +-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +type Region = { + name: string?, + size: { number }, -- x, y, z cells + position: { number }, -- the minimum corner relative to the schematic origin + states: { string }, + indices: buffer, + blockEntities: { any }, + entities: { any }, +} + +-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil +Common.int = Mc.int + +-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells +function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) + local x, y, z = Common.int(a), Common.int(b), Common.int(c) + if not x or not y or not z then + return nil, "missing or non-integer size", nil + end + if x < 0 or y < 0 or z < 0 then + return nil, "negative size", nil + end + if x * y * z > max then + return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil + end + return x, y, z +end + +-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil +Common.ints = Mc.ints + +-- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) +Common.blockEntity = Mc.blockEntity +Common.flatBlockEntity = Mc.flatBlockEntity + +-- list(v) -> v when it is an NBT list (array), else an empty list +function Common.list(v: any): { any } + if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then + return v + end + return {} +end + +-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) +function Common.compound(fields: { { any } }): { [string]: any } + local o, keys = {}, {} + for _, kv in fields do + if kv[2] ~= nil then + o[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + end + return Types.object(o, keys) +end + +-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key +-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after +function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } + if type(base) ~= "table" or not Types.isObject(base) then + return Common.compound(fields) + end + local mine: { [string]: any } = {} + local present: { [string]: boolean } = {} + for _, kv in fields do + present[kv[1]] = true + mine[kv[1]] = kv[2] + end + local out = {} + for _, k in Types.keys(base) do + if present[k] then + if mine[k] ~= nil then + table.insert(out, { k, mine[k] }) + end + elseif not (drop and drop[k]) then + table.insert(out, { k, base[k] }) + end + end + local seen: { [string]: boolean } = {} + for _, kv in out do + seen[kv[1]] = true + end + for _, kv in fields do + if not seen[kv[1]] and kv[2] ~= nil then + table.insert(out, kv) + end + end + return Common.compound(out) +end + +-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) +function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) + local first: { [string]: number } = {} + local remap: { number } = {} + local out: { string } = {} + local dup = false + for i, s in states do + local at = first[s] + if at == nil then + table.insert(out, s) + at = #out - 1 + first[s] = at + else + dup = true + end + remap[i] = at + end + if not dup then + return states, indices + end + local res = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0) + end + return out, res +end + +return Common +end +__FILES["model/schematic/Litematic"] = function() + +-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, +-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, +-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state +-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative +-- to the region's minimum corner), Entities and pending ticks (kept as they are). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Litematic = {} + +local Packed = Mc.Packed + +local function xyz(c: any): { number }? + if type(c) ~= "table" then + return nil + end + local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z) + if not x or not y or not z then + return nil + end + return { x, y, z } +end + +local function vec(v: { number }): any + return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) +end + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) + if not Types.isObject(root.Regions) then + return nil, "no Regions" + end + local out: { Common.Region } = {} + local total = 0 + local raw: { [string]: any } = {} + for _, name in Types.keys(root.Regions) do + local reg = root.Regions[name] + if type(reg) ~= "table" then + return nil, "region " .. name .. " is not a compound" + end + local pos, size = xyz(reg.Position), xyz(reg.Size) + if not pos or not size then + return nil, "region " .. name .. ": no Position / Size" + end + local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3]) + local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total) + if not sx then + return nil, "region " .. name .. ": " .. tostring(sy) + end + total += ax * ay * az + local states: { string } = {} + for i, c in Common.list(reg.BlockStatePalette) do + local st = Mc.stateFromNbt(c) + if not st then + return nil, "region " .. name .. ": bad palette entry " .. i + end + states[i] = st + end + if #states == 0 then + states[1] = "minecraft:air" + end + local n = ax * ay * az + local yzx = buffer.create(n * 2) + local bs = reg.BlockStates + if n > 0 then + if not (Nbt.isTag(bs) and bs.type == "longArray") then + return nil, "region " .. name .. ": no BlockStates" + end + local bits = Packed.bitsFor(#states, 2) + local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states) + if not ok then + return nil, "region " .. name .. ": " .. tostring(e) + end + end + local bes = {} + for _, c in Common.list(reg.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + table.insert(out, { + name = name, + size = { ax, ay, az }, + position = { + pos[1] + (if size[1] < 0 then size[1] + 1 else 0), + pos[2] + (if size[2] < 0 then size[2] + 1 else 0), + pos[3] + (if size[3] < 0 then size[3] + 1 else 0), + }, + states = states, + indices = Packed.fromYzx(yzx, ax, ay, az), + blockEntities = bes, + entities = Common.list(reg.Entities), + }) + raw[name] = reg + end + return out, { + version = Common.int(root.Version), + subVersion = Common.int(root.SubVersion), + dataVersion = Common.int(root.MinecraftDataVersion), + metadata = root.Metadata, + regions = raw, + } +end + +-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root +-- (Metadata fields and each region's Position / Size signs and pending ticks are kept) +function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) + local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil + local regs, order = {}, {} + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local blocks, volume = 0, 0 + for i, r in regions do + local name = r.name or ("Region" .. (if i == 1 then "" else tostring(i))) + while regs[name] ~= nil do + name ..= "_" + end + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + if states[1] ~= "minecraft:air" then + -- Litematica keeps air at index 0 + local at = table.find(states, "minecraft:air") + local shifted = buffer.create(n * 2) + local nst = table.clone(states) + if at then + nst[1], nst[at] = states[at], states[1] + else + table.insert(nst, 1, "minecraft:air") + end + for c = 0, n - 1 do + local v = buffer.readu16(indices, c * 2) + local w = if at then (if v == 0 then at - 1 elseif v == at - 1 then 0 else v) else v + 1 + buffer.writeu16(shifted, c * 2, w) + end + states, indices = nst, shifted + end + local palette = Nbt.list("compound") + for k, st in states do + palette[k] = Mc.stateToNbt(st) + end + local airLike: { [number]: boolean } = {} + for k, st in states do + airLike[k - 1] = Mc.isAir(st) + end + for c = 0, n - 1 do + if not airLike[buffer.readu16(indices, c * 2)] then + blocks += 1 + end + end + volume += n + local bits = Packed.bitsFor(#states, 2) + local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true) + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local p = r.position + local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz } + local b = if baseRegions then baseRegions[name] else nil + local bsize = if type(b) == "table" then xyz(b.Size) else nil + if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then + -- keep the source's corner and signs + for k = 1, 3 do + if bsize[k] < 0 then + size[k] = bsize[k] + pos[k] = p[k] - bsize[k] - 1 + end + end + end + for k = 1, 3 do + lo[k] = math.min(lo[k], p[k]) + hi[k] = math.max(hi[k], p[k] + r.size[k]) + end + regs[name] = Common.merge(b, { + { "BlockStatePalette", palette }, + { "BlockStates", Nbt.longArray(longs) }, + { "Entities", if #r.entities > 0 then r.entities else Nbt.list("compound") }, + { "PendingBlockTicks", if type(b) == "table" then b.PendingBlockTicks else Nbt.list("compound") }, + { "PendingFluidTicks", if type(b) == "table" then b.PendingFluidTicks else Nbt.list("compound") }, + { "Position", vec(pos) }, + { "Size", vec(size) }, + { "TileEntities", tiles }, + }) + table.insert(order, name) + end + if #order == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local bm = if type(base) == "table" and type(base.Metadata) == "table" then base.Metadata else nil + local metadata = Common.merge(bm, { + { "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }, + { "Author", if bm and bm.Author then bm.Author else "" }, + { "Description", if bm and bm.Description then bm.Description else "" }, + { "Name", title or (if bm and bm.Name then bm.Name else "Unnamed") }, + { "RegionCount", #order }, + { "TimeCreated", if bm and bm.TimeCreated then bm.TimeCreated else Nbt.long(0) }, + { "TimeModified", if bm and bm.TimeModified then bm.TimeModified else Nbt.long(0) }, + { "TotalBlocks", blocks }, + { "TotalVolume", volume }, + }) + local regions_ = Types.object(regs, order) + return Common.merge(base, { + { "MinecraftDataVersion", dataVersion }, + { "Version", version }, + { "SubVersion", if type(base) == "table" and base.SubVersion ~= nil then base.SubVersion elseif version >= 6 then 1 else nil }, + { "Metadata", metadata }, + { "Regions", regions_ }, + }), nil +end + +return Litematic +end +__FILES["model/schematic/Mcedit"] = function() + +-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki +-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high +-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name +-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft +-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block +-- nearest in colour). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Mcedit = {} + +local Packed = Mc.Packed + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) + local blocks = root.Blocks + if type(blocks) ~= "buffer" then + return nil, "no Blocks byte array" + end + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells) + if not sx then + return nil, sy + end + local n = sx * sy :: number * (sz :: number) + if buffer.len(blocks) < n then + return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells" + end + local data = if type(root.Data) == "buffer" and buffer.len(root.Data) >= n then root.Data else nil + local add = if type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= (n + 1) // 2 then root.AddBlocks else nil + -- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name) + local names: { [number]: string } = {} + if Types.isObject(root.SchematicaMapping) then + for _, k in Types.keys(root.SchematicaMapping) do + local id = Common.int(root.SchematicaMapping[k]) + if id then + names[id] = k + end + end + end + if Types.isObject(root.BlockIDs) then + for _, k in Types.keys(root.BlockIDs) do + local id = tonumber(k) + if id and type(root.BlockIDs[k]) == "string" then + names[id] = root.BlockIDs[k] + end + end + end + local function state(id: number, d: number): string + local name = names[id] + if name then + local base = string.match(name, "^minecraft:(.*)$") or (if string.find(name, ":", 1, true) then nil else name) + if base then + local std = table.find(Mc.Legacy.NAMES, base) + if std then + return Mc.legacyState(std - 1, d) + end + end + return Mc.stateString(if string.find(name, ":", 1, true) then name else "minecraft:" .. name, if d ~= 0 then { { "data", tostring(d) } } else nil) + end + return Mc.legacyState(id, d) + end + local slots: { [number]: number } = {} + local states: { string } = {} + local yzx = buffer.create(n * 2) + for i = 0, n - 1 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, true) * 256 + end + local d = if data then buffer.readu8(data, i) % 16 else 0 + local key = id * 16 + d + local s = slots[key] + if not s then + table.insert(states, state(id, d)) + s = #states - 1 + slots[key] = s + end + buffer.writeu16(yzx, i * 2, s :: number) + end + local bes = {} + for _, c in Common.list(root.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + local regions: { Common.Region } = { + { + name = nil, + size = { sx, sy :: number, sz :: number }, + position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(root.Entities), + }, + } + return regions, { materials = root.Materials } +end + +-- the legacy blocks a colour can become (full blocks of distinct colours) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + local function add(id: number, d: number) + local c = Mc.color(Mc.legacyState(id, d)) + if c then + table.insert(out, { id, d, c }) + end + end + for d = 0, 15 do + add(35, d) -- wool + add(159, d) -- stained clay + add(251, d) -- concrete + end + for d = 0, 5 do + add(5, d) -- planks + end + for _, id in { 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 } do + add(id, 0) + end + CANDIDATES = out + return out +end + +local function nearest(state: string): (number, number) + local c = Mc.color(state) + if not c then + return 0, 0 + end + if c[4] < 200 then + return 20, 0 -- glass + end + local bid, bd, best = 1, 0, math.huge + for _, k in candidates() do + local kc = k[3] + local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2 + if dist < best then + bid, bd, best = k[1], k[2], dist + end + end + return bid, bd +end + +-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other +-- fields are kept +function Mcedit.write(r: Common.Region, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a .schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list + local map: { [string]: number } = {} + if type(base) == "table" then + if Types.isObject(base.SchematicaMapping) then + for _, k in Types.keys(base.SchematicaMapping) do + local id = Common.int(base.SchematicaMapping[k]) + if id then + map[k] = id + end + end + end + if Types.isObject(base.BlockIDs) then + for _, k in Types.keys(base.BlockIDs) do + local id = tonumber(k) + if id and type(base.BlockIDs[k]) == "string" then + map[base.BlockIDs[k]] = id + end + end + end + end + local ids, datas = table.create(#r.states) :: { number }, table.create(#r.states) :: { number } + local high = false + for i, s in r.states do + local id, d = Mc.legacyId(s) + if id ~= nil then + local lname = Mc.Legacy.NAMES[id + 1] + local mapped = lname and map["minecraft:" .. lname] + if mapped then + id = mapped + end + else + local name, props = Mc.parseState(s) + if map[name] then + id, d = map[name], 0 + for _, kv in props do + if kv[1] == "data" then + d = (tonumber(kv[2]) or 0) % 16 + end + end + else + id, d = nearest(s) + end + end + ids[i], datas[i] = id :: number, d :: number + if (id :: number) > 255 then + high = true + end + end + local yzx = Packed.toYzx(r.indices, sx, sy, sz) + local blocks, data = buffer.create(n), buffer.create(n) + local add = if high then buffer.create((n + 1) // 2) else nil + for i = 0, n - 1 do + local s = buffer.readu16(yzx, i * 2) + 1 + local id = ids[s] or 0 + buffer.writeu8(blocks, i, id % 256) + buffer.writeu8(data, i, datas[s] or 0) + if add then + Packed.setNibble(add, 0, i, id // 256, true) + end + end + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") + local fields: { { any } } = { + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Materials", "Alpha" }, + { "Blocks", blocks }, + { "Data", data }, + { "AddBlocks", add }, + { "Entities", ents }, + { "TileEntities", tiles }, + } + local p = r.position + if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then + table.insert(fields, { "WEOffsetX", p[1] }) + table.insert(fields, { "WEOffsetY", p[2] }) + table.insert(fields, { "WEOffsetZ", p[3] }) + end + local root = Common.merge(base, fields, { Add = true }) + return root, nil +end + +return Mcedit +end +__FILES["model/schematic/Sponge"] = function() + +-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the +-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the +-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / +-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Sponge = {} + +local Packed = Mc.Packed + +-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) +function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) + local version = Common.int(s.Version) or 1 + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells) + if not sx then + return nil, sy + end + local container = if version >= 3 then s.Blocks else s + if version >= 3 and type(container) ~= "table" then + return nil, "no Blocks container" + end + local palette = if version >= 3 then container.Palette else s.Palette + local data = if version >= 3 then container.Data else s.BlockData + if not Types.isObject(palette) then + return nil, "no block palette" + end + if type(data) ~= "buffer" then + return nil, "no block data" + end + local states: { string } = {} + local max = -1 + for _, k in Types.keys(palette) do + local i = Common.int(palette[k]) + if i == nil or i < 0 or i > 65535 then + return nil, "bad palette index for " .. k + end + states[i + 1] = k + if i > max then + max = i + end + end + for i = 1, max + 1 do + if states[i] == nil then + states[i] = "minecraft:air" + end + end + local n = sx * sy :: number * (sz :: number) + local yzx = buffer.create(n * 2) + local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1) + if not ok then + return nil, e + end + local bes = {} + local raw = if version >= 3 then container.BlockEntities elseif version == 2 then s.BlockEntities else s.TileEntities + for _, c in Common.list(raw) do + local be = Common.blockEntity(c, if version >= 3 then "data" else "pos") + if be then + table.insert(bes, be) + end + end + local off = Common.ints(s.Offset) or { 0, 0, 0 } + local regions: { Common.Region } = { + { + name = nil, + size = { sx, sy :: number, sz :: number }, + position = { off[1] or 0, off[2] or 0, off[3] or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(s.Entities), + }, + } + return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } +end + +-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, +-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept +function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a Sponge schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + local palette, keys = {}, {} + for i, st in states do + palette[st] = i - 1 + keys[i] = st + end + local pal = Types.object(palette, keys) + local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n) + local bes = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") -- optional, but readers expect it + local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) + local fields: { { any } } = { + { "Version", version }, + { "DataVersion", if version >= 2 then dataVersion else nil }, + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Offset", off }, + } + if version >= 3 then + local blocksBase = if type(base) == "table" then base.Blocks else nil + table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) }) + table.insert(fields, { "Entities", ents }) + else + table.insert(fields, { "PaletteMax", #states }) + table.insert(fields, { "Palette", pal }) + table.insert(fields, { "BlockData", data }) + table.insert(fields, { if version == 2 then "BlockEntities" else "TileEntities", bes }) + table.insert(fields, { "Entities", if version == 2 then ents else nil }) + end + -- the other version's block fields never carry over + local drop = if version >= 3 then { PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true } + else { Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 } + return Common.merge(base, fields, drop :: any), nil +end + +return Sponge +end +__FILES["model/smd"] = function() + +-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the +-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a +-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation +-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, +-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. +-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/smd/Read") +local Write = __include("model/smd/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Smd = { + name = "smd", + category = "model", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + fps: number?, -- skeleton frames per second (default 30) + name: string?, -- the root node / animation name (the api passes the file name) + maxVertices: number?, -- default 2^24 +} +type EncodeOptions = Write.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Smd.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 256, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(r:string(r:remaining())) + local o: any = opts and table.clone(opts :: any) or {} + if type(o.name) == "string" then + o.name = string.match(o.name, "([^/\\]+)$") or o.name + o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "") + end + local scene, msg = Read.read(text, o) + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local text, msg = Write.write(scene, opts) + if not text then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return buffer.fromstring(text), nil +end + +return Smd +end +__FILES["model/smd/Read"] = function() + +-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, +-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone +-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px +-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). +-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material +-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, +-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond +-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { fps: number?, name: string?, maxVertices: number? } + +type Bone = { id: number, name: string, parent: number } +local ZERO: { number } = { 0, 0, 0, 0, 0, 0 } + +-- read(text, opts) -> Scene | nil, message +function Read.read(text: string, opts: Options?): (Types.Scene?, string?) + local lines: { string } = {} + for line in string.gmatch(text, "[^\r\n]*") do + table.insert(lines, line) + end + local i = 1 + local n = #lines + local function nextLine(): string? + while i <= n do + local l = lines[i] + i += 1 + local s = string.match(l, "^%s*(.-)%s*$") :: string + s = string.gsub(s, "%s*//.*$", "") :: string + if s ~= "" then + return s + end + end + return nil + end + local bones: { Bone } = {} + local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based) + local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz } + local times: { number } = {} + type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } } + local batches: { Batch } = {} + local byMat: { [string]: Batch } = {} + local version: number? = nil + local vertexAnimations = 0 + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + while true do + local l = nextLine() + if not l then + break + end + local kw = string.lower(string.match(l, "^(%S+)") or "") + if kw == "version" then + version = tonumber(string.match(l, "^%S+%s+(%S+)")) + elseif kw == "nodes" then + while true do + local s = nextLine() + if not s then + return nil, "truncated: nodes without end" + end + if string.lower(s) == "end" then + break + end + local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)') + if not id then + id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)") + end + if not id then + return nil, "bad node line: " .. s + end + table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number }) + byId[tonumber(id) :: number] = #bones + end + elseif kw == "skeleton" then + local cur: { [number]: { number } }? = nil + while true do + local s = nextLine() + if not s then + return nil, "truncated: skeleton without end" + end + local low = string.lower(s) + if low == "end" then + break + end + local tm = string.match(low, "^time%s+(%-?[%d%.]+)") + if tm then + local prev = frames[#frames] + local f: { [number]: { number } } = {} + if prev then + for k, v in prev do + f[k] = v + end + end + table.insert(frames, f) + table.insert(times, tonumber(tm) :: number) + cur = f + else + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + table.insert(nums, tonumber(tok) or 0 / 0) + end + local bi = byId[nums[1]] + if not cur or #nums < 7 or not bi then + return nil, "bad skeleton line: " .. s + end + cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] } + end + end + elseif kw == "triangles" then + while true do + local mat = nextLine() + if not mat then + return nil, "truncated: triangles without end" + end + if string.lower(mat) == "end" then + break + end + local b = byMat[mat] + if not b then + b = { name = mat, keys = {}, verts = {}, indices = {} } + byMat[mat] = b + table.insert(batches, b) + end + for _ = 1, 3 do + local s = nextLine() + if not s then + return nil, "truncated triangle" + end + local nums: { number } = {} + for tok in string.gmatch(s, "%S+") do + local v = tonumber(tok) + if not v then + return nil, "bad vertex line: " .. s + end + table.insert(nums, v) + end + if #nums < 9 then + return nil, "short vertex line: " .. s + end + local id = b.keys[s] + if not id then + total += 1 + if total > maxV then + return nil, "limit: too many vertices" + end + table.insert(b.verts, nums) + id = #b.verts - 1 + b.keys[s] = id + end + table.insert(b.indices, id) + end + end + elseif kw == "vertexanimation" then + vertexAnimations += 1 + while true do + local s = nextLine() + if not s or string.lower(s) == "end" then + break + end + end + else + return nil, "unknown section " .. kw + end + end + if version ~= 1 then + return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version) + end + local scene = Scene.new() + scene.meta.up = "z" + local root: Types.Node = { name = opts and opts.name or "smd", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + -- skeleton (bind pose: the first frame) + local joints: { Rig.Joint } = {} + local bind: { [number]: { number } } = frames[1] or {} + for k, bn in bones do + local v: { number } = bind[k] or ZERO + local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0 + joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } + end + local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) + -- meshes + if #batches > 0 then + local mesh: Types.Mesh = { primitives = {} } + for _, b in batches do + local nv = #b.verts + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local lists: { { number } } = {} + for vi, v in b.verts do + local o = (vi - 1) * 12 + writef32(pos, o, v[2]) + writef32(pos, o + 4, v[3]) + writef32(pos, o + 8, v[4]) + writef32(nrm, o, v[5]) + writef32(nrm, o + 4, v[6]) + writef32(nrm, o + 8, v[7]) + writef32(uv, (vi - 1) * 8, v[8]) + writef32(uv, (vi - 1) * 8 + 4, 1 - v[9]) + local l: { number } = {} + local sum = 0 + local nl = if #v >= 10 then math.floor(v[10]) else 0 + for k = 0, nl - 1 do + local bi, w = byId[v[11 + k * 2]], v[12 + k * 2] + if bi and w then + table.insert(l, bi - 1) + table.insert(l, w) + sum += w + end + end + local parent = byId[v[1]] + if parent and sum < 0.999 then + table.insert(l, parent - 1) + table.insert(l, 1 - sum) + end + lists[vi] = l + end + local ib = buffer.create(#b.indices * 4) + for k, id in b.indices do + writeu32(ib, (k - 1) * 4, id) + end + local attrs: { [string]: Types.Accessor } = { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #bones > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(b.name) + mat.metallic = 0 + table.insert(scene.textures, { name = b.name, uri = b.name }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil }) + table.insert(root.children, #scene.nodes) + end + -- animation + if #frames > 1 or (#frames == 1 and #batches == 0) then + local fps = opts and opts.fps or 30 + local t: { number } = {} + for k, tm in times do + t[k] = (tm - times[1]) / fps + end + local tracks: { [number]: Rig.Track } = {} + for k = 1, #bones do + local tr: { number }, rot: { number } = {}, {} + for _, f in frames do + local v: { number } = f[k] or bind[k] or ZERO + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + tracks[k] = { translation = tr, rotation = rot } + end + Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR") + end + scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" } + return scene, nil +end + +return Read +end +__FILES["model/smd/Write"] = function() + +-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node +-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose +-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled +-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every +-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material +-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the +-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless +-- opts.triangles is true. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + +type Options = { animation: number?, links: boolean?, triangles: boolean? } + +local fmt = string.format + +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local s = fmt("%.6f", v) + if s == "-0.000000" then + return "0.000000" + end + return s +end + +-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x) +local function angles(q: { number }): (number, number, number) + local m = Mat4.fromQuat(q) + local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1] + local y = math.asin(math.clamp(-r31, -1, 1)) + local x, z + if math.abs(r31) < 0.9999999 then + x = math.atan2(r32, r33) + z = math.atan2(r21, r11) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return x, y, z +end + +local function lerp(a: { number }, b: { number }, t: number): { number } + local out: { number } = {} + for i = 1, #a do + out[i] = a[i] + (b[i] - a[i]) * t + end + return out +end + +-- the value of channel ch at time tm (nil when the channel has no keys) +local function sample(ch: Types.Channel, tm: number): { number }? + local input, output = ch.input, ch.output + local n = input.count + if n == 0 then + return nil + end + local comps = if ch.path == "rotation" then 4 else 3 + local function key(k: number): { number } + local out: { number } = {} + for c = 0, comps - 1 do + out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4) + end + return out + end + local times = input.data + if tm <= buffer.readf32(times, 0) then + return key(0) + end + for k = 1, n - 1 do + local t1 = buffer.readf32(times, k * 4) + if tm <= t1 then + local t0 = buffer.readf32(times, (k - 1) * 4) + local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0) + local a, b = key(k - 1), key(k) + if comps == 4 then + if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + local q = lerp(a, b, f) + local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a + end + return lerp(a, b, f) + end + end + return key(n - 1) +end + +-- write(scene, opts) -> text | nil, message +function Write.write(scene: Types.Scene, opts: Options?): (string?, string?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, "expected a Scene" + end + local out: { string } = { "version 1", "nodes" } + local skin = scene.skins and scene.skins[1] + local joints: { number } = if skin then skin.joints else {} + local jointOf: { [number]: number } = {} -- node index -> bone id (0-based) + for k, nd in joints do + jointOf[nd] = k - 1 + end + local parentOf: { [number]: number } = {} + for ni, nd in scene.nodes do + for _, c in nd.children do + parentOf[c] = ni + end + end + if #joints == 0 then + table.insert(out, '0 "root" -1') + else + for k, nd in joints do + local p = parentOf[nd] + while p and jointOf[p] == nil do + p = parentOf[p] + end + local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1)) + table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1)) + end + end + table.insert(out, "end") + table.insert(out, "skeleton") + local function pose(tr: { number }?, rot: { number }?): string + local t = tr or { 0, 0, 0 } + local x, y, z = angles(rot or { 0, 0, 0, 1 }) + return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ") + end + local animIndex = opts and opts.animation + local anim = animIndex and scene.animations[animIndex] + if animIndex and not anim then + return nil, "no animation " .. tostring(animIndex) + end + if anim then + local keyset: { [number]: boolean } = {} + for _, ch in anim.channels do + for k = 0, ch.input.count - 1 do + keyset[buffer.readf32(ch.input.data, k * 4)] = true + end + end + local keys: { number } = {} + for tm in keyset do + table.insert(keys, tm) + end + table.sort(keys) + local byNode: { [number]: { [string]: Types.Channel } } = {} + for _, ch in anim.channels do + local m = byNode[ch.node] or {} + byNode[ch.node] = m + m[ch.path] = ch + end + for f, tm in keys do + table.insert(out, "time " .. (f - 1)) + for k, nd in joints do + local node = scene.nodes[nd] + local chs: { [string]: Types.Channel } = byNode[nd] or {} + local tch, rch = chs.translation, chs.rotation + local tr = if tch then sample(tch, tm) else node.translation + local rot = if rch then sample(rch, tm) else node.rotation + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + else + table.insert(out, "time 0") + if #joints == 0 then + table.insert(out, "0 " .. pose(nil, nil)) + else + for k, nd in joints do + local node = scene.nodes[nd] + local tr, rot = node.translation, node.rotation + if node.matrix then + local t, r = Mat4.decompose(node.matrix) + tr, rot = t, r + end + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + end + table.insert(out, "end") + -- triangles + if not anim or (opts and opts.triangles) then + local m, err = Flatten.merge(scene, function(name: string): boolean + return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" + end, { triangulate = true }) + if not m then + return nil, err + end + local A = m.attrs + local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0 + local links = not (opts and opts.links == false) + local nbones = math.max(1, #joints) + if #m.corners > 0 then + table.insert(out, "triangles") + for _, part in m.parts do + local mat = part.prim.material and scene.materials[part.prim.material] + local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default" + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + table.insert(out, mname) + for c = 0, 2 do + local v = m.corners[f * 3 + c + 1] + local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3] + local nx, ny, nz = 0, 0, 1 + if N then + nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3] + end + local u, w = 0, 0 + if UV then + local k = UV.components + u, w = UV.values[v * k + 1], UV.values[v * k + 2] + end + local parent = 0 + local lk: { string } = {} + if J and W and #joints > 0 then + local jk, wk = J.components, W.components + local best, bestW = 0, -1 + local count = 0 + for c2 = 1, math.min(4, jk, wk) do + local jw = W.values[v * wk + c2] + local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1) + if jw and jw > 0 then + count += 1 + table.insert(lk, fmt("%d %s", jj, num(jw))) + if jw > bestW then + best, bestW = jj, jw + end + end + end + parent = best + if count > 0 then + table.insert(lk, 1, tostring(count)) + end + end + local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w)) + if links and #lk > 0 then + line ..= " " .. table.concat(lk, " ") + end + table.insert(out, line) + end + end + end + table.insert(out, "end") + end + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end +__FILES["model/stl"] = function() + +-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description +-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). +-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the +-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: +-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the +-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in +-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly +-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in +-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final +-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, +-- solids, facets }. +-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans +-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after +-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle +-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either +-- convention. Not supported: binary-only extensions other than the two colour conventions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Decode = __include("model/stl/Decode") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Stl = { + name = "stl", + category = "model", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxFaces: number?, -- refuse more facets (default 2^25) + colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the + -- header = magics, else any attribute with bit 15 set = viscam, else none) +} +type EncodeOptions = { + ascii: boolean?, -- default false (binary) + colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only) + defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly + -- that colour refer to it, the others carry their own (alpha 255) + name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh") + header: string?, -- the binary header text (at most 80 bytes; default "rosetta STL") + normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8, readu32 = buffer.readu8, buffer.readu32 +local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 + +local function lower5(s: string): boolean + return string.lower(s) == "solid" +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Stl.sniff(r: Bytes.Reader): number + local size = r:remaining() + if size >= 84 then + local c = r:peek(4, 80) + local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216 + if 84 + 50 * n == size then + return 0.9 + end + end + local head = r:peek(512) + local s = string.match(head, "^%s*(%a+)") + if s and lower5(s) then + local l = string.lower(head) + return if string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) then 0.9 else 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function soupPrim(n: number, pos: buffer, nrm: buffer): Types.Primitive + return { + attributes = { + POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3), + NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3), + }, + mode = "triangles", + } +end + +local function decodeBinary(r: Bytes.Reader, maxFaces: number, colors: string): (Types.Scene?, Err.Err?) + local b, base, size = r.buf, r.base, r.limit - r.base + local n = readu32(b, base + 80) + if n > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80) + end + if 84 + 50 * n > size then + return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80) + end + local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2) + local any = Decode.binary(b, base + 84, n, pos, nrm, attr) + local header = buffer.readstring(b, base, 80) + local cut = string.find(header, "\0", 1, true) -- the text before the first NUL + local text = if cut then string.sub(header, 1, cut - 1) else header + local mode = colors + local ci = string.find(header, "COLOR=", 1, true) + if mode == "auto" then + mode = if ci and ci + 9 <= 80 then "magics" elseif any >= 0x8000 then "viscam" else "none" + end + local prim = soupPrim(n, pos, nrm) + local source: { [string]: any } = { format = "stl", binary = true, header = text, facets = n } + if mode == "viscam" or mode == "magics" then + local dc = { 255, 255, 255, 255 } + if mode == "magics" and ci and ci + 9 <= 80 then + local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based) + dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) } + source.defaultColor = dc + local mi = string.find(header, "MATERIAL=", 1, true) + if mi and mi + 8 + 12 <= 80 then + local m = base + mi + 8 + local function rgba(k: number): { number } + return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) } + end + source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) } + end + end + local col = buffer.create(n * 12) + Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col) + prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3) + source.colors = mode + elseif any ~= 0 then + prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } } + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.up = "z" + scene.meta.source = source :: any + return scene, nil +end + +local function decodeAscii(r: Bytes.Reader, maxFaces: number): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local function tok(): string? + local s, e = string.find(text, "%S+", at) + if not s then + return nil + end + at = (e :: number) + 1 + return string.sub(text, s, e) + end + local function restOfLine(): string + local e = string.find(text, "\n", at, true) or (#text + 1) + local line = string.sub(text, at, e - 1) + at = e + 1 + return string.match(line, "^%s*(.-)%s*$") or "" + end + local function num(): number? + local t = tok() + return if t then tonumber(t) else nil + end + type Solid = { name: string, pos: { number }, nrm: { number } } + local solids: { Solid } = {} + local facets = 0 + while true do + local t = tok() + if t == nil then + break + end + if string.lower(t) ~= "solid" then + return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20)) + end + local cur: Solid = { name = restOfLine(), pos = {}, nrm = {} } + table.insert(solids, cur) + local pos, nrm = cur.pos, cur.nrm + while true do + local w = tok() + if w == nil then + break -- a missing endsolid at the end + end + local lw = string.lower(w) + if lw == "endsolid" then + restOfLine() + break + elseif lw ~= "facet" then + return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20)) + end + local nx, ny, nz = 0, 0, 0 + local k = tok() + if k and string.lower(k) == "normal" then + local a, bb, c = num(), num(), num() + if a == nil or bb == nil or c == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad facet normal") + end + nx, ny, nz = a, bb, c + k = tok() + end + local l2 = tok() + if k == nil or l2 == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then + return nil, Err.new(Err.CORRUPT, "expected outer loop") + end + local vs: { number } = {} + while true do + local v = tok() + if v == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + local lv = string.lower(v) + if lv == "endloop" then + break + elseif lv ~= "vertex" then + return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20)) + end + local x, y, z = num(), num(), num() + if x == nil or y == nil or z == nil then + return nil, Err.new(if at > #text then Err.TRUNCATED else Err.CORRUPT, "bad vertex") + end + table.insert(vs, x) + table.insert(vs, y) + table.insert(vs, z) + end + local e = tok() + if e == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + elseif string.lower(e) ~= "endfacet" then + return nil, Err.new(Err.CORRUPT, "expected endfacet") + end + local nvs = #vs // 3 + if nvs < 3 then + return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices") + end + for j = 2, nvs - 1 do + for _, vi in { 0, j - 1, j } do + table.insert(pos, vs[vi * 3 + 1]) + table.insert(pos, vs[vi * 3 + 2]) + table.insert(pos, vs[vi * 3 + 3]) + table.insert(nrm, nx) + table.insert(nrm, ny) + table.insert(nrm, nz) + end + facets += 1 + end + if facets > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces)) + end + end + end + if #solids == 0 then + return nil, Err.new(Err.TRUNCATED, "no solid") + end + local prims: { Types.Primitive } = {} + local names: { string } = {} + for i, s in solids do + local n = #s.pos // 9 + local pos, nrm = buffer.create(n * 36), buffer.create(n * 36) + for j = 1, n * 9 do + writef32(pos, (j - 1) * 4, s.pos[j]) + writef32(nrm, (j - 1) * 4, s.nrm[j]) + end + local prim = soupPrim(n, pos, nrm) + prim.extras = { solid = s.name } + prims[i] = prim + names[i] = s.name + end + local first = solids[1].name + local scene = Types.Scene.fromPrimitive(prims[1], if first ~= "" then first else nil) + for i = 2, #prims do + table.insert(scene.meshes[1].primitives, prims[i]) + end + scene.meta.up = "z" + scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets } + return scene, nil +end + +function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local colors = opts and opts.colors or "auto" + if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then + return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none") + end + local size = r.limit - r.base + if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then + return decodeBinary(r, maxFaces, colors) + end + local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)") + if s and lower5(s) then + return decodeAscii(r, maxFaces) + end + if size < 84 then + return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) + end + -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + return decodeBinary(r, maxFaces, colors) +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function f32(v: number): number + writef32(scratch, 0, v) + return buffer.readf32(scratch, 0) +end + +-- a COLOR_0 component as 0..255 +local function byte(a: Flatten.Attr, v: number): number + if a.raw then + if a.type == "unorm16" then + return (v * 255 + 32767) // 65535 + end + return math.clamp(v, 0, 255) + end + return math.floor(math.clamp(v, 0, 1) * 255 + 0.5) +end + +local function to5(c: number): number + return (c * 31 + 127) // 255 +end + +local function keep(name: string): boolean + return name == "NORMAL" or name == "COLOR_0" +end + +function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local colors = o.colors + if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then + return nil, Err.new(Err.ARG, "colors must be viscam or magics") + end + if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then + return nil, Err.new(Err.ARG, "normals must be compute or attribute") + end + if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then + return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local P = m.attrs.POSITION.values + local N = if o.normals == "attribute" and m.attrs.NORMAL then (m.attrs.NORMAL :: Flatten.Attr).values else nil + local C = m.attrs.COLOR_0 + local corners = m.corners + local nf = #corners // 3 + -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) + local function normal(f: number): (number, number, number) + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if N then + return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] + end + local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3] + local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az + local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 and l < math.huge then + return nx / l, ny / l, nz / l + end + return 0, 0, 0 + end + if o.ascii then + local out = table.create(nf * 7 + 2 * #m.parts) + local used: { [string]: boolean } = {} + local function fmt(v: number): string? + v = f32(v) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) + end + for _, part in m.parts do + local name = o.name + if name == nil then + local ex = part.prim.extras + name = if ex and type(ex.solid) == "string" then ex.solid elseif part.mesh and part.mesh.name then part.mesh.name elseif part.node and part.node.name then part.node.name else "mesh" + end + name = string.gsub(tostring(name), "[\r\n]", " ") + if used[name] then -- distinct names: some readers merge solids by name + local k = 2 + while used[name .. "_" .. k] do + k += 1 + end + name = name .. "_" .. k + end + used[name] = true + table.insert(out, "solid " .. name .. "\n") + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + local nx, ny, nz = normal(f) + table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0")) + for k = 1, 3 do + local v = corners[f * 3 + k] * 3 + local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate") + end + table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n") + end + table.insert(out, " endloop\n endfacet\n") + end + table.insert(out, "endsolid " .. name .. "\n") + end + if #m.parts == 0 then + table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + -- binary + local buf = buffer.create(84 + 50 * nf) + local header = o.header or "rosetta STL" + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + if type(dc) ~= "table" or #dc < 4 then + return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }") + end + header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.clamp(dc[1], 0, 255) // 1, math.clamp(dc[2], 0, 255) // 1, math.clamp(dc[3], 0, 255) // 1, math.clamp(dc[4], 0, 255) // 1) + end + local dcol: { number }? = nil + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + dcol = { dc[1] // 1, dc[2] // 1, dc[3] // 1, dc[4] // 1 } + end + buffer.writestring(buf, 0, header) + writeu32(buf, 80, nf) + -- the attribute words: colours, or the raw words of a single STL-decoded primitive + local rawAttr: { number }? = nil + if colors == nil and #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fa = ex and ex.faceAttributes + local acc = fa and fa.attribute + if acc and acc.count == nf then + rawAttr = Flatten.numbers(acc, true) + end + end + for f = 0, nf - 1 do + local q = 84 + f * 50 + local nx, ny, nz = normal(f) + writef32(buf, q, nx) + writef32(buf, q + 4, ny) + writef32(buf, q + 8, nz) + for k = 0, 2 do + local v = corners[f * 3 + k + 1] * 3 + writef32(buf, q + 12 + k * 12, P[v + 1]) + writef32(buf, q + 16 + k * 12, P[v + 2]) + writef32(buf, q + 20 + k * 12, P[v + 3]) + end + local w = 0 + if colors and C then + local a = corners[f * 3 + 1] * C.components + local cv = C.values + local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0)) + if colors == "viscam" then + w = 0x8000 + r5 * 1024 + g5 * 32 + b5 + elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and (if C.components >= 4 then byte(C, cv[a + 4]) else 255) == dcol[4] then + w = 0x8000 -- the object colour + else + w = r5 + g5 * 32 + b5 * 1024 + end + elseif colors == "magics" then + w = 0x8000 -- the object colour + elseif rawAttr then + w = math.clamp(rawAttr[f + 1] // 1, 0, 65535) + end + writeu16(buf, q + 48, w) + end + return buf, nil +end + +return Stl +end +__FILES["model/stl/Decode"] = @native function() + + + +-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 +-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that +-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + +local Decode = {} + +-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into +-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). +@native function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number + local any = 0 + for i = 0, n - 1 do + local q = p + i * 50 + local o = i * 36 + local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + writeu32(nrm, o, nx) + writeu32(nrm, o + 4, ny) + writeu32(nrm, o + 8, nz) + writeu32(nrm, o + 12, nx) + writeu32(nrm, o + 16, ny) + writeu32(nrm, o + 20, nz) + writeu32(nrm, o + 24, nx) + writeu32(nrm, o + 28, ny) + writeu32(nrm, o + 32, nz) + writeu32(pos, o, readu32(b, q + 12)) + writeu32(pos, o + 4, readu32(b, q + 16)) + writeu32(pos, o + 8, readu32(b, q + 20)) + writeu32(pos, o + 12, readu32(b, q + 24)) + writeu32(pos, o + 16, readu32(b, q + 28)) + writeu32(pos, o + 20, readu32(b, q + 32)) + writeu32(pos, o + 24, readu32(b, q + 36)) + writeu32(pos, o + 28, readu32(b, q + 40)) + writeu32(pos, o + 32, readu32(b, q + 44)) + local a = readu16(b, q + 48) + writeu16(attr, i * 2, a) + any = bor(any, a) + end + return any +end + +-- 5-bit -> 8-bit, rounded +@native local function x8(v: number): number + return (v * 255 + 15) // 31 +end + +-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, +-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +@native function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer) + for i = 0, n - 1 do + local w = readu16(attr, i * 2) + local r, g, bl, al = dr, dg, db, da + local own = if magics then w < 0x8000 else w >= 0x8000 + if own then + local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31)) + g, al = mid, 255 + if magics then + r, bl = lo, hi + else + r, bl = hi, lo + end + end + local o = i * 12 + for k = 0, 2 do + writeu8(out, o + k * 4, r) + writeu8(out, o + k * 4 + 1, g) + writeu8(out, o + k * 4 + 2, bl) + writeu8(out, o + k * 4 + 3, al) + end + end +end + +return Decode +end +__FILES["model/usda"] = function() + +-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text +-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own +-- reader / writer (pxr) and Blender's USD exporter. +-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / +-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, +-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one +-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every +-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, +-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / +-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> +-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / +-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). +-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. +-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs +-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel +-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Parse = __include("model/usda/Parse") +local Build = __include("model/usda/Build") +local Write = __include("model/usda/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Usda = { + name = "usda", + category = "model", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin) + resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths) + files: { [string]: any }?, -- or: the files by asset path + maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25) + maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30) +} +type EncodeOptions = { + files: { [string]: any }?, -- receives embedded texture bytes as _. + name: string?, -- the destination's file name (names the texture files) + format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension) + upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up) + metersPerUnit: number?, -- default scene.meta.unit or 1 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isUsdz(r: Bytes.Reader): boolean + if r:peek(4) ~= "PK\3\4" then + return false + end + -- the first entry is the root layer + local lo, hi = r:peekU8(26), r:peekU8(27) + if lo < 0 or hi < 0 then + return false + end + local nameLen = lo + hi * 256 + local name = string.lower(r:peek(30 + nameLen)) + name = string.sub(name, 31) + return string.find(name, "%.usd[ac]?$") ~= nil +end + +function Usda.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then + return 1 + end + if head == "PXR-USDC" then + return 0.9 -- recognised so the error says USDC is not supported + end + if isUsdz(r) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer? + return function(uri: string): buffer? + local candidates = { uri } + local slashed = string.gsub(uri, "\\", "/") + local stripped = string.gsub(slashed, "^%./", "") + if slashed ~= uri then + table.insert(candidates, slashed) + end + if stripped ~= slashed then + table.insert(candidates, stripped) + end + -- packaged assets: "model.usdz[textures/a.png]" + local inner = string.match(uri, "%[(.+)%]$") + if inner then + table.insert(candidates, inner) + end + for _, u in candidates do + if package then + local data = package:read(u) + if data then + return data + end + end + local v: any = nil + if opts and type((opts :: DecodeOptions).files) == "table" then + v = ((opts :: DecodeOptions).files :: { [string]: any })[u] + end + if v == nil and opts and type((opts :: DecodeOptions).resolve) == "function" then + local ok, res = pcall((opts :: DecodeOptions).resolve :: (uri: string) -> any, u) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + elseif type(v) == "buffer" then + return v + end + end + return nil + end +end + +function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local head = r:peek(8) + if head == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)") + end + local text: string + local package: any = nil + local usdz = false + if string.sub(head, 1, 4) == "PK\3\4" then + local archive, zerr = Zip.open(r) + if not archive then + return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package") + end + local entries = archive:list() + local root = nil + for _, e in entries do + if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then + root = e + break + end + end + if not root then + return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer") + end + local data, rerr = archive:read(root) + if not data then + return nil, rerr + end + if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer") + end + text = buffer.tostring(data) + package = archive + usdz = true + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + if not Parse.version(text) then + return nil, Err.new(Err.CORRUPT, "no #usda header") + end + local layer, msg, at = Parse.layer(text, opts and opts.maxBytes) + if not layer then + if msg == "array over the size limit" then + return nil, Err.new(Err.LIMIT, msg :: string, at) + end + local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT + if msg and string.find(msg, "^unterminated") then + code = Err.TRUNCATED + end + return nil, Err.new(code, msg or "parse error", if usdz then nil else at) + end + local scene, err = Build.scene(layer, { + triangulate = opts and opts.triangulate, + flipV = opts and opts.flipV, + maxVertices = opts and opts.maxVertices, + fetch = fetcher(opts, package), + }) + if not scene then + if err == "LIMIT" then + return nil, Err.new(Err.LIMIT, "a mesh over maxVertices") + end + return nil, Err.new(Err.CORRUPT, err or "bad scene") + end + local src: any = scene.meta.source + src.version = Parse.version(text) + src.usdz = usdz or nil + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "usdz" then + return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda") + end + local ok, text = pcall(Write.text, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text)) + end + return buffer.fromstring(text :: any), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover +function Usda.parse(text: string): (Parse.Layer?, Err.Err?) + local layer, msg, at = Parse.layer(text) + if not layer then + return nil, Err.new(Err.CORRUPT, msg or "parse error", at) + end + return layer, nil +end + +return Usda +end +__FILES["model/usda/Build"] = function() + +-- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux +-- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; +-- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh +-- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / +-- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. +-- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the +-- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local +-- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); +-- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / +-- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor +-- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every +-- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated +-- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. +-- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with +-- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> +-- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). +-- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in +-- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Parse = __include("model/usda/Parse") + +local Build = {} + +type Prim = Parse.Prim +type Prop = Parse.Prop + +local NONE = Parse.NONE +local DEG = math.pi / 180 + +local NOT_NODES = { Material = true, Shader = true, NodeGraph = true, GeomSubset = true, Skeleton = true, SkelAnimation = true, BlendShape = true } +local SKEL = { Skeleton = true, SkelAnimation = true, BlendShape = true } +local LIGHTS = { DistantLight = true, SphereLight = true, RectLight = true, DiskLight = true, CylinderLight = true, DomeLight = true } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", ktx2 = "image/ktx2", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", avif = "image/avif" } + +type Options = { + triangulate: boolean?, + flipV: boolean?, + fetch: ((uri: string) -> buffer?)?, + maxVertices: number?, +} + +-- ------------------------------------------------------------------------------------------------ helpers +local function isArr(v: any): boolean + return type(v) == "table" and v.t == "arr" +end +local function str(v: any): string? + if type(v) == "string" then + return v + elseif type(v) == "table" and (v.t == "id" or v.t == "asset" or v.t == "path") then + return v.v + end + return nil +end +-- a tuple / scalar -> numbers (nil when not numeric) +local function nums(v: any): { number }? + if type(v) == "number" then + return { v } + elseif type(v) == "boolean" then + return { if v then 1 else 0 } + elseif type(v) == "table" and v.t == "tuple" then + local out = {} + for k, x in v.v do + if type(x) == "number" then + out[k] = x + elseif type(x) == "table" and x.t == "tuple" then + for _, y in x.v do + if type(y) ~= "number" then + return nil + end + table.insert(out, y) + end + else + return nil + end + end + return out + elseif type(v) == "table" and v.t == "arr" then + return v.v + end + return nil +end +local function num(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return nil +end + +-- the value of a property: its default, else its earliest time sample +local function propValue(p: Prop?): any + if not p then + return nil + end + if p.samples and #p.samples.times > 0 then + local best, bi = math.huge, 0 + for k, t in p.samples.times do + if t < best then + best, bi = t, k + end + end + local v = p.samples.values[bi] + if v ~= NONE then + return v + end + end + if p.hasValue and p.value ~= NONE then + return p.value + end + return nil +end + +local function joinPath(parent: string, name: string): string + return if parent == "/" then "/" .. name else parent .. "/" .. name +end + +-- resolve a (possibly relative) Sdf path against the prim path that holds it +local function resolvePath(base: string, p: string): string + if string.sub(p, 1, 1) == "/" then + return p + end + local parts = string.split(base, "/") + local out: { string } = {} + for _, x in parts do + if x ~= "" then + table.insert(out, x) + end + end + for _, x in string.split(p, "/") do + if x == ".." then + table.remove(out) + elseif x ~= "." and x ~= "" then + table.insert(out, x) + end + end + return "/" .. table.concat(out, "/") +end +-- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" +local function splitProp(p: string): (string, string?) + local prim, prop = string.match(p, "^(.-)%.([^/]+)$") + if prim and prop then + return prim, prop + end + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ matrices +-- column-major 4x4 (glTF layout = USD's row-major row-vector text order) +local mul = Types.Scene.mul +local function quatM(x: number, y: number, z: number, w: number): { number } + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return Mat4.fromQuat({ x, y, z, w }) +end + +-- ------------------------------------------------------------------------------------------------ xform ops +type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } + +-- the op stack of a prim: ops in xformOpOrder, resetXformStack +local function xformOps(p: Prim): ({ Op }, boolean) + local order = p.props.xformOpOrder + local list = order and propValue(order) + local ops: { Op } = {} + local reset = false + if type(list) ~= "table" or list.t ~= "list" then + return ops, false + end + for _, item in list.v do + local name = str(item) + if name == "!resetXformStack!" then + reset = true + table.clear(ops) + elseif name then + local invert = false + if string.sub(name, 1, 8) == "!invert!" then + invert = true + name = string.sub(name, 9) + end + local prop = p.props[name] + local kind = string.match(name, "^xformOp:(%a+)") + if prop and kind then + local axes = string.match(kind, "^rotate([XYZ]+)$") + table.insert(ops, { kind = if axes then "rotate" else kind, axes = axes, prop = prop, invert = invert }) + end + end + end + return ops, reset +end + +local AXIS = { X = 1, Y = 2, Z = 3 } +-- the matrix of one op for a value +local function opMatrix(op: Op, v: any): { number }? + local n = nums(v) + if not n then + return nil + end + local m: { number }? + local k = op.kind + if k == "translate" then + m = Mat4.translation(n[1] or 0, n[2] or 0, n[3] or 0) + elseif k == "scale" then + local s1 = n[1] or 1 + m = Mat4.scaling(s1, n[2] or s1, n[3] or s1) + elseif k == "orient" then + -- USD quaternions are written (real, i, j, k) + m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) + elseif k == "transform" then + if #n ~= 16 then + return nil + end + m = table.clone(n) + elseif k == "rotate" and op.axes then + local axes = op.axes :: string + local r: { number } = Types.Scene.IDENTITY :: any + -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + for c = 1, #axes do + local a = AXIS[string.sub(axes, c, c)] + local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 + r = mul(Mat4.rotation(a, angle), r) + end + m = r + else + return nil + end + if op.invert and m then + m = Mat4.inverseFull(m) + end + return m +end + +local function lerpValue(a: any, b: any, f: number, quat: boolean): any + local na, nb = nums(a), nums(b) + if not na or not nb or #na ~= #nb then + return a + end + local out = table.create(#na) + if quat and #na == 4 then + -- (w, x, y, z): slerp through nlerp with the short path + local dot = 0 + for k = 1, 4 do + dot += na[k] * nb[k] + end + local sgn = if dot < 0 then -1 else 1 + for k = 1, 4 do + out[k] = na[k] + (nb[k] * sgn - na[k]) * f + end + return { t = "tuple", v = out } + end + for k = 1, #na do + out[k] = na[k] + (nb[k] - na[k]) * f + end + return { t = "tuple", v = out } +end + +-- an op's value at time code t (samples interpolated linearly, held outside their range) +local function opValueAt(op: Op, t: number?): any + local p = op.prop + local s = p.samples + if t ~= nil and s and #s.times > 0 then + local times, values = s.times, s.values + local lo, hi + for k = 1, #times do + local tk = times[k] + if values[k] ~= NONE then + if tk <= t and (lo == nil or tk > times[lo]) then + lo = k + end + if tk >= t and (hi == nil or tk < times[hi]) then + hi = k + end + end + end + if lo and hi then + if lo == hi or times[hi] == times[lo] then + return values[lo] + end + local f = (t - times[lo]) / (times[hi] - times[lo]) + return lerpValue(values[lo], values[hi], f, op.kind == "orient") + end + return values[lo or hi] + end + return propValue(p) +end + +local function localMatrix(ops: { Op }, t: number?): { number } + local m: { number } = Types.Scene.IDENTITY :: any + for _, op in ops do + local om = opMatrix(op, opValueAt(op, t)) + if om then + m = mul(m, om) + end + end + return m +end +Build.localMatrix = localMatrix + +-- ------------------------------------------------------------------------------------------------ build +function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + local flipV = opts.flipV ~= false + local triangulate = opts.triangulate ~= false + local maxVertices = opts.maxVertices or 2 ^ 25 + local fetch = opts.fetch + local unsupported: { [string]: boolean } = {} + local meta = layer.meta + + -- prim index (variants merged), paths + local byPath: { [string]: Prim } = {} + local parentOf: { [Prim]: string } = {} + local pathOf: { [Prim]: string } = {} + local function merge(p: Prim) + if not p.variantSets then + return + end + local nested: { any }? = nil + local sel = p.meta.variants + local chosen = if type(sel) == "table" and sel.t == "dict" then sel.v else {} + for setName, set in p.variantSets :: any do + local name = str(chosen[setName]) + local body = name and set[name] -- unselected sets contribute nothing + if body then + for _, pn in body.order do + if not p.props[pn] then + p.props[pn] = body.props[pn] + table.insert(p.order, pn) + end + end + for _, c in body.children do + table.insert(p.children, c) + end + for k, v in body.meta do + if p.meta[k] == nil then + p.meta[k] = v + end + end + if body.variantSets then + nested = nested or {} + table.insert(nested :: any, body.variantSets) + end + end + end + p.variantSets = nil + for _, vs in nested or {} do + p.variantSets = vs + merge(p) + end + end + local function index(p: Prim, parent: string, depth: number) + if depth > 200 then + return + end + merge(p) + local path = joinPath(parent, p.name) + pathOf[p] = path + parentOf[p] = parent + local existing = byPath[path] + if existing and existing ~= p then + -- over / def of the same path in one layer: merge into the first spec + for _, pn in p.order do + if not existing.props[pn] then + existing.props[pn] = p.props[pn] + table.insert(existing.order, pn) + end + end + existing.typeName = existing.typeName or p.typeName + if p.specifier == "def" then + existing.specifier = "def" + end + for _, c in p.children do + table.insert(existing.children, c) + end + table.clear(p.children) + p.specifier = "class" -- skipped below + else + byPath[path] = p + end + for _, key in { "references", "payload", "inherits", "specializes" } do + local v = p.meta[key] + if v ~= nil and v ~= NONE then + unsupported[key] = true + end + end + for _, c in p.children do + index(c, path, depth + 1) + end + end + for _, p in layer.prims do + index(p, "/", 1) + end + if meta.subLayers ~= nil then + unsupported.subLayers = true + end + + -- a property of a prim path ("/a/b.inputs:x") + local function propAt(path: string): (Prim?, Prop?) + local pp, pn = splitProp(path) + local prim = byPath[pp] + if not prim or not pn then + return prim, nil + end + return prim, prim.props[pn] + end + + -- --------------------------------------------------------------------------------------------- materials + local texCoordIndex: { [string]: number } = {} + local texCoordCount = 0 + local function texCoordFor(name: string): number + local k = texCoordIndex[name] + if k == nil then + k = texCoordCount + texCoordIndex[name] = k + texCoordCount += 1 + end + return k + end + -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + do + local names: { [string]: boolean } = {} + for _, p in byPath do + if p.typeName == "Mesh" then + for pn, pr in p.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") and pr.array then + names[nm] = true + end + end + end + end + local list = {} + for nm in names do + table.insert(list, nm) + end + table.sort(list, function(a: string, b: string): boolean + local pa = if a == "st" then 0 elseif string.sub(a, 1, 2) == "st" then 1 else 2 + local pb = if b == "st" then 0 elseif string.sub(b, 1, 2) == "st" then 1 else 2 + if pa ~= pb then + return pa < pb + end + return a < b + end) + for _, nm in list do + texCoordFor(nm) + end + end + + -- an input's resolved source: a value, or { shader = Prim, output = name } + type Source = { value: any?, shader: Prim?, output: string? } + local function input(prim: Prim, name: string, depth: number?): Source? + local d = depth or 0 + if d > 32 then + return nil + end + local p = prim.props["inputs:" .. name] + if not p then + return nil + end + if p.connect and #p.connect > 0 then + local target = resolvePath(pathOf[prim] or "/", p.connect[1]) + local tp, tn = splitProp(target) + local tprim = byPath[tp] + if tprim and tn then + local outName = string.match(tn, "^outputs:(.+)$") + local inName = string.match(tn, "^inputs:(.+)$") + if outName and tprim.typeName == "Shader" then + return { shader = tprim, output = outName } + elseif outName then + -- a NodeGraph output: follow its connection + local op = tprim.props[tn] + if op and op.connect and #op.connect > 0 then + local t2 = resolvePath(tp, op.connect[1]) + local sp, sn = splitProp(t2) + local sprim = byPath[sp] + if sprim and sn and string.match(sn, "^outputs:") then + return { shader = sprim, output = string.sub(sn, 9) } + end + end + elseif inName then + local r = input(tprim, inName, d + 1) + if r then + return r + end + end + end + end + local v = propValue(p) + if v ~= nil then + return { value = v } + end + return nil + end + local function shaderId(p: Prim): string? + return str(propValue(p.props["info:id"])) + end + + local textureIndex: { [string]: number } = {} + local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) + local function textureRef(shader: Prim): Types.TextureRef? + if shaderId(shader) ~= "UsdUVTexture" then + return nil + end + local f = input(shader, "file") + local file = f and str(f.value) + if not file or file == "" then + return nil + end + local ws = input(shader, "wrapS") + local wt = input(shader, "wrapT") + local wrapS = WRAP[ws and str(ws.value) or "repeat"] or "repeat" + local wrapT = WRAP[wt and str(wt.value) or "repeat"] or "repeat" + local key = file .. "|" .. wrapS .. "|" .. wrapT + local ti = textureIndex[key] + if not ti then + local tex: Types.Texture = { name = shader.name, uri = file, sampler = { wrapS = wrapS :: any, wrapT = wrapT :: any } } + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + tex.mime = MIME[ext] + local data = fetch and fetch(file) + if not data and string.sub(file, 1, 2) == "./" and fetch then + data = fetch(string.sub(file, 3)) + end + tex.data = data + local extras: { [string]: any } = { path = pathOf[shader] } + local cs = input(shader, "sourceColorSpace") + if cs and str(cs.value) then + extras.sourceColorSpace = str(cs.value) + end + tex.extras = { usd = extras } + table.insert(scene.textures, tex) + ti = #scene.textures + textureIndex[key] = ti + end + local ref: Types.TextureRef = { texture = ti :: number } + -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + local st = input(shader, "st") + local reader = st and st.shader + if reader and shaderId(reader) == "UsdTransform2d" then + local tr: { [string]: any } = {} + local rot = input(reader, "rotation") + local scl = input(reader, "scale") + local off = input(reader, "translation") + if rot and num(rot.value) and num(rot.value) ~= 0 then + tr.rotation = (num(rot.value) :: number) * DEG + end + if scl and nums(scl.value) then + tr.scale = nums(scl.value) + end + if off and nums(off.value) then + tr.offset = nums(off.value) + end + if next(tr) then + ref.transform = tr :: any + end + local inn = input(reader, "in") + reader = inn and inn.shader + end + if reader and string.find(shaderId(reader) or "", "^UsdPrimvarReader") then + local vn = input(reader, "varname") + local name = vn and str(vn.value) + if name then + local k = texCoordFor(name) + if k ~= 0 then + ref.texCoord = k + end + end + end + return ref + end + + local materialIndex: { [string]: number } = {} + local function material(path: string): number? + local mi = materialIndex[path] + if mi ~= nil then + return if mi > 0 then mi else nil + end + local mp = byPath[path] + if not mp or mp.typeName ~= "Material" then + materialIndex[path] = 0 + return nil + end + local mat = Types.Scene.material(mp.name) + mat.baseColor = { 0.18, 0.18, 0.18, 1 } + mat.metallic = 0 + mat.roughness = 0.5 + mat.extras = { usd = { path = path } } + -- the surface shader + local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] + local shader: Prim? = nil + if surf and surf.connect and #surf.connect > 0 then + local sp = splitProp(resolvePath(path, surf.connect[1])) + shader = byPath[sp] + end + if shader and shaderId(shader) == "UsdPreviewSurface" then + local sh = shader :: Prim + local function value(name: string): any + local s = input(sh, name) + return s and s.value + end + local function tex(name: string): (Types.TextureRef?, Prim?) + local s = input(sh, name) + if s and s.shader then + local ref = textureRef(s.shader) + return ref, if ref then s.shader else nil + end + return nil, nil + end + local dc = nums(value("diffuseColor")) + if dc and #dc >= 3 then + mat.baseColor = { dc[1], dc[2], dc[3], 1 } + end + local dt, dshader = tex("diffuseColor") + if dt then + mat.baseColorTexture = dt + mat.baseColor = { 1, 1, 1, 1 } + local sc = input(dshader :: Prim, "scale") + local s = sc and nums(sc.value) + if s and #s >= 3 then + mat.baseColor = { s[1], s[2], s[3], s[4] or 1 } + end + end + local op = num(value("opacity")) + local ot = tex("opacity") + if op then + mat.baseColor[4] = op + end + local thr = num(value("opacityThreshold")) + if thr and thr > 0 then + mat.alphaMode = "mask" + mat.alphaCutoff = thr + elseif (op and op < 1) or ot then + mat.alphaMode = "blend" + end + local m = num(value("metallic")) + if m then + mat.metallic = m + end + local r = num(value("roughness")) + if r then + mat.roughness = r + end + local mt = tex("metallic") + local rt = tex("roughness") + if rt or mt then + mat.metallicRoughnessTexture = rt or mt + if mt then + mat.metallic = 1 + end + if rt then + mat.roughness = 1 + end + end + local e = nums(value("emissiveColor")) + if e and #e >= 3 then + mat.emissive = { e[1], e[2], e[3] } + end + local et = tex("emissiveColor") + if et then + mat.emissiveTexture = et + mat.emissive = { 1, 1, 1 } + end + local nt = tex("normal") + if nt then + mat.normalTexture = nt + end + local oc = tex("occlusion") + if oc then + mat.occlusionTexture = oc + end + local ext: { [string]: any } = {} + local ior = num(value("ior")) + if ior and ior ~= 1.5 then + ext.KHR_materials_ior = { ior = ior } + end + local cc = num(value("clearcoat")) + if cc and cc > 0 then + ext.KHR_materials_clearcoat = { clearcoatFactor = cc, clearcoatRoughnessFactor = num(value("clearcoatRoughness")) or 0.01 } + end + if next(ext) then + mat.extensions = ext + end + local usd: any = (mat.extras :: any).usd + if num(value("useSpecularWorkflow")) == 1 then + usd.useSpecularWorkflow = true + usd.specularColor = nums(value("specularColor")) + end + elseif shader then + unsupported["shader " .. (shaderId(shader :: Prim) or "?")] = true + end + table.insert(scene.materials, mat) + materialIndex[path] = #scene.materials + return #scene.materials + end + + -- the bound material of a prim (material:binding, inherited from ancestors) + local function binding(prim: Prim, path: string): number? + local p: Prim? = prim + local pp = path + while p do + local rel = p.props["material:binding"] or p.props["material:binding:preview"] or p.props["material:binding:full"] + if rel and rel.value and #rel.value > 0 then + return material(resolvePath(pp, rel.value[1])) + end + if pp == "/" then + break + end + pp = parentOf[p :: Prim] or "/" + p = byPath[pp] + end + return nil + end + + local colorMaterials: { [string]: number } = {} + local function colorMaterial(c: { number }): number + local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) + local mi = colorMaterials[key] + if not mi then + local mat = Types.Scene.material("displayColor") + mat.baseColor = { c[1], c[2], c[3], c[4] or 1 } + mat.metallic = 0 + mat.roughness = 0.5 + if (c[4] or 1) < 1 then + mat.alphaMode = "blend" + end + mat.extras = { usd = { displayColor = true } } + table.insert(scene.materials, mat) + mi = #scene.materials + colorMaterials[key] = mi + end + return mi :: number + end + + -- --------------------------------------------------------------------------------------------- meshes + type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } + local function primvar(p: Prop?, defaultInterp: string): Primvar? + if not p then + return nil + end + local v = propValue(p) + if not isArr(v) then + return nil + end + local interp = defaultInterp + if p.meta and str(p.meta.interpolation) then + interp = str(p.meta.interpolation) :: string + end + return { data = v.v, w = v.w, interp = interp } + end + + local function buildMesh(prim: Prim, path: string): (Types.Mesh?, string?) + local pts = propValue(prim.props.points) + local cnt = propValue(prim.props.faceVertexCounts) + local idx = propValue(prim.props.faceVertexIndices) + if not isArr(pts) or pts.w ~= 3 then + return nil, nil + end + local points: { number } = pts.v + local npts = #points // 3 + local counts: { number } = if isArr(cnt) then cnt.v else {} + local indices: { number } = if isArr(idx) then idx.v else {} + local nfaces = #counts + local ncorners = 0 + for f = 1, nfaces do + local c = counts[f] + if c < 0 or c ~= c // 1 then + return nil, "bad faceVertexCounts at " .. path + end + ncorners += c + end + if ncorners ~= #indices then + return nil, "faceVertexCounts and faceVertexIndices disagree at " .. path + end + if ncorners > maxVertices or npts > maxVertices then + return nil, "LIMIT" + end + for k = 1, ncorners do + local v = indices[k] + if v < 0 or v >= npts or v ~= v // 1 then + return nil, "a face vertex index out of range at " .. path + end + end + local faceStart = table.create(nfaces + 1, 0) + do + local acc = 0 + for f = 1, nfaces do + faceStart[f] = acc + acc += counts[f] + end + faceStart[nfaces + 1] = acc + end + -- primvars, validated + local function sizeOk(pv: Primvar): boolean + local n = (if pv.idx then #pv.idx else #pv.data // pv.w) + local want = if pv.interp == "constant" then 1 + elseif pv.interp == "uniform" then nfaces + elseif pv.interp == "faceVarying" then ncorners + else npts + if n < want then + return false + end + if pv.idx then + local m = #pv.data // pv.w + for _, k in pv.idx :: { number } do + if k < 0 or k >= m or k ~= k // 1 then + return false + end + end + end + return #pv.data % pv.w == 0 + end + local function withIndices(pv: Primvar?, name: string): Primvar? + if not pv then + return nil + end + local ip = propValue(prim.props[name .. ":indices"]) + if isArr(ip) and ip.w == 1 then + pv.idx = ip.v + end + if not sizeOk(pv) then + unsupported["mismatched primvar " .. name] = true + return nil + end + return pv + end + local normals = withIndices(primvar(prim.props["primvars:normals"], "vertex"), "primvars:normals") + or withIndices(primvar(prim.props.normals, "vertex"), "normals") + if normals and normals.w ~= 3 then + normals = nil + end + local color = withIndices(primvar(prim.props["primvars:displayColor"], "constant"), "primvars:displayColor") + if color and color.w ~= 3 then + color = nil + end + local opacity = withIndices(primvar(prim.props["primvars:displayOpacity"], "constant"), "primvars:displayOpacity") + if opacity and opacity.w ~= 1 then + opacity = nil + end + local uvs: { [number]: Primvar } = {} + for pn, pr in prim.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and pr.array and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") then + local pv = withIndices(primvar(pr, "vertex"), pn) + if pv and pv.w == 2 then + uvs[texCoordFor(nm)] = pv + end + end + end + -- the value of a primvar for (point, face, corner) (0-based), component c + local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number + local e = if pv.interp == "constant" then 0 + elseif pv.interp == "uniform" then face + elseif pv.interp == "faceVarying" then corner + else point + if pv.idx then + e = (pv.idx :: { number })[e + 1] + end + return pv.data[e * pv.w + c + 1] or 0 + end + local perCorner = false + for _, pv in { normals, color, opacity } do + if pv and (pv.interp == "faceVarying" or pv.interp == "uniform") then + perCorner = true + end + end + for _, pv in uvs do + if pv.interp == "faceVarying" or pv.interp == "uniform" then + perCorner = true + end + end + local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" + -- holes + local hole: { [number]: boolean } = {} + local hv = propValue(prim.props.holeIndices) + if isArr(hv) then + for _, f in hv.v do + hole[f] = true + end + end + -- face sets: GeomSubsets ("face" elements), the rest + local meshMaterial = binding(prim, path) + local constantColor: { number }? = nil + if color and color.interp == "constant" then + constantColor = { get(color, 0, 0, 0, 0), get(color, 0, 0, 0, 1), get(color, 0, 0, 0, 2), if opacity and opacity.interp == "constant" then get(opacity, 0, 0, 0, 0) else 1 } + end + type Set = { faces: { number }, material: number?, name: string? } + local sets: { Set } = {} + local used: { [number]: boolean } = {} + for _, c in prim.children do + if c.typeName == "GeomSubset" and c.specifier ~= "class" then + local et = str(propValue(c.props.elementType)) or "face" + local fi = propValue(c.props.indices) + if et == "face" and isArr(fi) then + local faces = {} + for _, f in fi.v do + if f >= 0 and f < nfaces and f == f // 1 and not used[f] then + used[f] = true + table.insert(faces, f) + end + end + table.sort(faces) + local cpath = joinPath(path, c.name) + local rel = c.props["material:binding"] or c.props["material:binding:preview"] + local mi = if rel and rel.value and #rel.value > 0 then material(resolvePath(cpath, rel.value[1])) else meshMaterial + table.insert(sets, { faces = faces, material = mi, name = c.name }) + end + end + end + do + local rest = {} + for f = 0, nfaces - 1 do + if not used[f] then + table.insert(rest, f) + end + end + if #rest > 0 or #sets == 0 then + table.insert(sets, 1, { faces = rest, material = meshMaterial }) + end + end + local mesh: Types.Mesh = { name = prim.name, primitives = {} } + for _, set in sets do + -- vertices: one per point (vertex-rate data) or per corner + local keyToVert: { [number]: number } = {} + local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local nv = 0 + local out: { number } = {} + local faceSizes: { number } = {} + for _, f in set.faces do + local cnt0 = counts[f + 1] + if cnt0 >= 3 and not hole[f] then + local base = faceStart[f + 1] + local verts = table.create(cnt0) :: { number } + for k = 0, cnt0 - 1 do + local corner = base + k + local point = indices[corner + 1] + local key = if perCorner then corner else point + local v = keyToVert[key] + if not v then + v = nv + keyToVert[key] = v + nv += 1 + vp[nv], vf[nv], vc[nv] = point, f, corner + end + verts[k + 1] = v + end + if leftHanded then + local r = table.create(cnt0) :: { number } + for k = 1, cnt0 do + r[k] = verts[cnt0 - k + 1] + end + verts = r + end + if triangulate then + for k = 2, cnt0 - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[k]) + table.insert(out, verts[k + 1]) + end + else + for k = 1, cnt0 do + table.insert(out, verts[k]) + end + table.insert(faceSizes, cnt0) + end + end + end + if nv > 0 then + local attrs: { [string]: Types.Accessor } = {} + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + for v = 1, nv do + local p0 = vp[v] * 3 + buffer.writef32(pos.data, (v - 1) * 12, points[p0 + 1]) + buffer.writef32(pos.data, (v - 1) * 12 + 4, points[p0 + 2]) + buffer.writef32(pos.data, (v - 1) * 12 + 8, points[p0 + 3]) + end + attrs.POSITION = pos + local function fill(pv: Primvar, comps: number, flip: boolean): Types.Accessor + local a = Types.Scene.accessor(nil, "f32", comps, nv) + for v = 1, nv do + for c = 0, comps - 1 do + local x = get(pv, vp[v], vf[v], vc[v], c) + if flip and c == 1 then + x = 1 - x + end + buffer.writef32(a.data, ((v - 1) * comps + c) * 4, x) + end + end + return a + end + if normals then + local nrm = fill(normals, 3, false) + if leftHanded then + -- normals follow the authored (left-handed) winding: keep them as authored + end + attrs.NORMAL = nrm + end + for k, pv in uvs do + attrs["TEXCOORD_" .. k] = fill(pv, 2, flipV) + end + local mi = set.material + if color and not constantColor then + -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) + if opacity then + local a = Types.Scene.accessor(nil, "f32", 4, nv) + for v = 1, nv do + for c = 0, 2 do + buffer.writef32(a.data, ((v - 1) * 4 + c) * 4, get(color, vp[v], vf[v], vc[v], c)) + end + buffer.writef32(a.data, ((v - 1) * 4 + 3) * 4, get(opacity, vp[v], vf[v], vc[v], 0)) + end + attrs.COLOR_0 = a + else + attrs.COLOR_0 = fill(color, 3, false) + end + elseif constantColor and mi == nil then + mi = colorMaterial(constantColor) + end + local ind = Types.Scene.accessor(nil, "u32", 1, #out) + for k, v in out do + buffer.writeu32(ind.data, (k - 1) * 4, v) + end + local prm: Types.Primitive = { attributes = attrs, indices = ind, mode = if triangulate then "triangles" else "polygons", material = mi } + if not triangulate then + local fa = Types.Scene.accessor(nil, "u32", 1, #faceSizes) + for k, v in faceSizes do + buffer.writeu32(fa.data, (k - 1) * 4, v) + end + prm.faces = fa + end + if set.name then + prm.extras = { usd = { subset = set.name } } + end + local ds = propValue(prim.props.doubleSided) + if mi and (ds == 1 or ds == true) then + local m = mi and scene.materials[mi] + if m then + m.doubleSided = true + end + end + table.insert(mesh.primitives, prm) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + return mesh, nil + end + + -- --------------------------------------------------------------------------------------------- cameras / lights + local function camera(prim: Prim): Types.Camera + local function f(name: string, d: number): number + return num(propValue(prim.props[name])) or d + end + local focal = f("focalLength", 50) + local hap = f("horizontalAperture", 20.955) + local vap = f("verticalAperture", 15.2908) + local clip = nums(propValue(prim.props.clippingRange)) or { 1, 1000000 } + local proj = str(propValue(prim.props.projection)) or "perspective" + if proj == "orthographic" then + return { name = prim.name, type = "orthographic", xmag = hap / 20, ymag = vap / 20, znear = clip[1] or 1, zfar = clip[2] or 1000000 } + end + return { + name = prim.name, + type = "perspective", + yfov = 2 * math.atan(vap / (2 * focal)), + aspect = if vap > 0 then hap / vap else nil, + znear = clip[1] or 1, + zfar = clip[2], + } + end + local function light(prim: Prim): Types.Light + local function f(name: string, d: number): number + return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props[name])) or d + end + local col = nums(propValue(prim.props["inputs:color"])) or nums(propValue(prim.props.color)) or { 1, 1, 1 } + local intensity = f("intensity", 1) * 2 ^ f("exposure", 0) + local l: Types.Light = { name = prim.name, type = "point", color = { col[1] or 1, col[2] or 1, col[3] or 1 }, intensity = intensity } + local t = prim.typeName + local cone = num(propValue(prim.props["inputs:shaping:cone:angle"])) or num(propValue(prim.props["shaping:cone:angle"])) + if t == "DistantLight" then + l.type = "directional" + elseif t == "RectLight" or t == "DiskLight" then + l.type = "spot" + l.outerCone = math.pi / 2 + l.innerCone = 0 + end + if cone and cone < 90 then + local soft = num(propValue(prim.props["inputs:shaping:cone:softness"])) or 0 + l.type = "spot" + l.outerCone = cone * DEG + l.innerCone = math.max(0, cone * DEG * (1 - soft)) + end + return l + end + + -- --------------------------------------------------------------------------------------------- nodes + local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 + if tcps <= 0 then + tcps = 24 + end + local animation: Types.Animation = { name = "usd", channels = {} } + local failure: string? = nil + + local function isNode(p: Prim): boolean + -- class prims are abstract; an over with no def is not defined (UsdStage traversal skips both) + if p.specifier == "class" or p.specifier == "over" or NOT_NODES[p.typeName or ""] then + if SKEL[p.typeName or ""] then + unsupported["UsdSkel (skeletons, skinning, blend shapes)"] = true + end + return false + end + if p.typeName == "Scope" or p.typeName == nil then + -- scopes / untyped prims holding only materials are not nodes + local function hasContent(q: Prim, d: number): boolean + if d > 100 then + return false + end + for _, c in q.children do + if c.specifier ~= "class" and not NOT_NODES[c.typeName or ""] then + if c.typeName ~= nil and c.typeName ~= "Scope" then + return true + end + if hasContent(c, d + 1) then + return true + end + end + end + return false + end + if p.typeName == "Scope" or #p.children > 0 then + return hasContent(p, 0) + end + end + return true + end + + local function node(p: Prim, path: string, parent: number?, depth: number) + if depth > 200 or failure then + return + end + if not isNode(p) then + return + end + local n: Types.Node = { name = p.name, children = {}, extras = { usd = { path = path, type = p.typeName } } } + table.insert(scene.nodes, n) + local ni = #scene.nodes + local ops, reset = xformOps(p) + -- animated ops: the local matrix at the union of their time codes + local times: { number } = {} + do + local seen: { [number]: boolean } = {} + for _, op in ops do + local s = op.prop.samples + if s and #s.times > 1 then + for _, t in s.times do + if not seen[t] then + seen[t] = true + table.insert(times, t) + end + end + end + end + table.sort(times) + end + if #times > 1 then + local count = math.min(#times, 100000) + local tin = Types.Scene.accessor(nil, "f32", 1, count) + local tr = Types.Scene.accessor(nil, "f32", 3, count) + local ro = Types.Scene.accessor(nil, "f32", 4, count) + local sc = Types.Scene.accessor(nil, "f32", 3, count) + local prev: { number }? = nil + for k = 1, count do + local T, R, S = Mat4.decompose(localMatrix(ops, times[k])) + if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then + R = { -R[1], -R[2], -R[3], -R[4] } + end + prev = R + buffer.writef32(tin.data, (k - 1) * 4, times[k] / tcps) + for c = 0, 2 do + buffer.writef32(tr.data, ((k - 1) * 3 + c) * 4, T[c + 1]) + buffer.writef32(sc.data, ((k - 1) * 3 + c) * 4, S[c + 1]) + end + for c = 0, 3 do + buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) + end + end + table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } :: Types.Channel) + table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } :: Types.Channel) + table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } :: Types.Channel) + local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) + n.translation, n.rotation, n.scale = T, R, S + elseif #ops > 0 then + -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix + local simple = true + local stage = 0 + for _, op in ops do + local st = if op.kind == "translate" then 1 elseif op.kind == "rotate" or op.kind == "orient" then 2 elseif op.kind == "scale" then 3 else 9 + if op.invert or st == 9 or st <= stage or string.find(op.prop.name, "^xformOp:%a+:") then + simple = false + end + stage = st + end + local m = localMatrix(ops, nil) + if simple then + local T, R, S = Mat4.decompose(m) + local tx = ops[1].kind == "translate" + if tx then + n.translation = T + end + for _, op in ops do + if op.kind == "rotate" or op.kind == "orient" then + n.rotation = R + elseif op.kind == "scale" then + n.scale = S + end + end + -- a negative scale with a rotation is not TRS-representable through decompose: keep the matrix + local back = Types.Scene.nodeMatrix(n) + for k = 1, 16 do + if math.abs(back[k] - m[k]) > 1e-5 * math.max(1, math.abs(m[k])) then + simple = false + break + end + end + if not simple then + n.translation, n.rotation, n.scale = nil, nil, nil + end + end + if not simple then + local identity = true + for k = 1, 16 do + if m[k] ~= Types.Scene.IDENTITY[k] then + identity = false + end + end + if not identity then + n.matrix = m + end + end + end + if reset or parent == nil then + table.insert(scene.roots, ni) + if reset and parent then + (n.extras :: any).usd.resetXformStack = true + end + else + table.insert(scene.nodes[parent].children, ni) + end + local t = p.typeName + if t == "Mesh" then + local mesh, err = buildMesh(p, path) + if err == "LIMIT" then + failure = "LIMIT" + return + elseif err then + failure = err + return + end + if mesh then + table.insert(scene.meshes, mesh) + n.mesh = #scene.meshes + end + elseif t == "Camera" then + table.insert(scene.cameras, camera(p)) + n.camera = #scene.cameras + elseif t and LIGHTS[t] and t ~= "DomeLight" then + table.insert(scene.lights, light(p)) + n.light = #scene.lights + elseif t and t ~= "Xform" and t ~= "Scope" and t ~= "Mesh" and t ~= "DomeLight" and t ~= "SkelRoot" then + unsupported["prim type " .. t] = true + end + for _, c in p.children do + node(c, joinPath(path, c.name), ni, depth + 1) + end + end + + for _, p in layer.prims do + if p.specifier ~= "class" then + node(p, "/" .. p.name, nil, 1) + end + end + if failure then + return nil, failure + end + if #animation.channels > 0 then + table.insert(scene.animations, animation) + end + + -- stage metadata + local up = str(meta.upAxis) + scene.meta.up = if up == "Z" then "z" else "y" + local mpu = num(meta.metersPerUnit) + if mpu and mpu > 0 then + scene.meta.unit = mpu + end + local list = {} + for k in unsupported do + table.insert(list, k) + end + table.sort(list) + scene.meta.source = { + format = "usda", + defaultPrim = str(meta.defaultPrim), + timeCodesPerSecond = tcps, + startTimeCode = num(meta.startTimeCode), + endTimeCode = num(meta.endTimeCode), + doc = str(meta.doc), + unsupported = if #list > 0 then list else nil, + } + return scene, nil +end + +return Build +end +__FILES["model/usda/Parse"] = function() + +-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text +-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes +-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, +-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), +-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast +-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. +-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and +-- returns nil, message, offset - nothing escapes. +local Parse = {} + +-- values: numbers, booleans, strings, and these tagged tables +type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened) +type Value = any + +type Prop = { + name: string, + rel: boolean, -- a relationship + typeName: string?, -- "point3f", "token", ... (attributes) + array: boolean?, + uniform: boolean?, + custom: boolean?, + value: Value?, -- the default value (attributes) or the targets (relationships: { path strings }) + hasValue: boolean?, + samples: { times: { number }, values: { Value } }?, + connect: { string }?, -- connection target paths (attributes) + meta: { [string]: Value }?, +} +type Prim = { + specifier: string, -- "def" | "over" | "class" + typeName: string?, + name: string, + meta: { [string]: Value }, + props: { [string]: Prop }, + order: { string }, -- property names in file order + children: { Prim }, + variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children) +} +type Layer = { meta: { [string]: Value }, prims: { Prim } } + +local NONE = table.freeze({ t = "none" }) +Parse.NONE = NONE + +local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true } +local VARIABILITY = { uniform = true, varying = true, config = true } +local MAX_DEPTH = 200 + +local function fail(msg: string, at: number): never + error({ usda = msg, at = at }, 0) +end + +-- the parser over one text; positions are 1-based string indices +local function parser(s: string, maxBytes: number) + local n = #s + local depth = 0 + + -- whitespace and comments (newlines included) + local function ws(i: number): number + while true do + local _, e = sfind(s, "^[ \t\r\n]+", i) + if e then + i = e + 1 + end + local c = sbyte(s, i) + if c == 35 then -- # + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + local _, ce = sfind(s, "*/", i + 2, true) + if not ce then + fail("unterminated comment", i) + end + i = (ce :: number) + 1 + else + return i + end + end + end + + local function expect(i: number, ch: string): number + i = ws(i) + if ssub(s, i, i) ~= ch then + fail("expected '" .. ch .. "'", i) + end + return i + 1 + end + + local function ident(i: number): (string?, number) + local a, e = sfind(s, "^[%a_][%w_:]*", i) + if not a then + return nil, i + end + return ssub(s, a, e), (e :: number) + 1 + end + + local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" } + local function unescape(str: string): string + if not sfind(str, "\\", 1, true) then + return str + end + return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string + if x == "x" then + return "\\x" .. c -- left alone (rare) + end + return ESC[c] or c + end)) + end + + local function str(i: number): (string, number) + local q = ssub(s, i, i) + if ssub(s, i, i + 2) == q .. q .. q then + local e = sfind(s, q .. q .. q, i + 3, true) + if not e then + fail("unterminated string", i) + end + return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3 + end + local j = i + 1 + while true do + local a = sfind(s, "[\\\n" .. q .. "]", j) + if not a then + fail("unterminated string", i) + end + local c = sbyte(s, a :: number) + if c == 92 then + j = (a :: number) + 2 + elseif c == 10 then + fail("newline in string", a :: number) + else + return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1 + end + end + end + + local function number(i: number): (number?, number) + local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) + if not a then + a, e = sfind(s, "^[-+]?%d*%.?%d*", i) + end + if a and (e :: number) >= (a :: number) then + local v = tonumber(ssub(s, a, e)) + if v then + return v, (e :: number) + 1 + end + end + -- inf / -inf / nan + local w, e2 = sfind(s, "^[-+]?%a+", i) + if w then + local word = string.lower(ssub(s, w, e2)) + if word == "inf" or word == "+inf" then + return math.huge, (e2 :: number) + 1 + elseif word == "-inf" then + return -math.huge, (e2 :: number) + 1 + elseif word == "nan" or word == "-nan" or word == "+nan" then + return 0 / 0, (e2 :: number) + 1 + end + end + return nil, i + end + + -- skip a balanced (), [], {} block starting at i (strings and comments respected) + local function skipBalanced(i: number): number + local open = sbyte(s, i) + local level = 0 + while i <= n do + i = ws(i) + local c = sbyte(s, i) + if c == nil then + break + end + if c == 40 or c == 91 or c == 123 then + level += 1 + i += 1 + elseif c == 41 or c == 93 or c == 125 then + level -= 1 + i += 1 + if level == 0 then + return i + end + elseif c == 34 or c == 39 then + local _, j = str(i) + i = j + elseif c == 64 then + local e = sfind(s, "@", i + 1, true) + i = if e then e + 1 else n + 1 + elseif c == 60 then + local e = sfind(s, ">", i + 1, true) + i = if e then e + 1 else n + 1 + else + local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i) + i = if e then e + 1 else i + 1 + end + end + fail("unbalanced " .. string.char(open or 63), i) + end + + local value: (i: number) -> (Value, number) + local metadata: (i: number) -> ({ [string]: Value }, number) + + -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list + local function list(i: number): (Value, number) + local close = sfind(s, "]", i + 1, true) + if close then + local body = ssub(s, i + 1, close - 1) + if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then + local first = smatch(body, "^%s*%(([^%)]*)%)") + local w = 1 + if first then + w = 0 + for _ in gmatch(first, "[^%s,]+") do + w += 1 + end + elseif sfind(body, "[%(%)]") then + w = -1 -- nested tuples: the generic path + end + if w > 0 then + local out: { number } = {} + local k = 0 + local ok = true + for tok in gmatch(body, "[^%s,%(%)]+") do + local v = tonumber(tok) + if not v then + ok = false + break + end + k += 1 + out[k] = v + end + if ok and k % w == 0 then + if k * 8 > maxBytes then + fail("array over the size limit", i) + end + return { t = "arr", w = w, v = out } :: Arr, close + 1 + end + end + end + end + -- generic + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "]" then + i += 1 + break + elseif c == "" then + fail("unterminated list", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + local _ + _, i = metadata(i) + i = ws(i) + end + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= "]" then + fail("expected ',' or ']' in a list", i) + end + end + -- all numbers, or all equal-width numeric tuples -> arr + local w: number? = nil + local flat: { number } = {} + for _, it in items do + if type(it) == "number" then + if w and w ~= 1 then + return { t = "list", v = items }, i + end + w = 1 + table.insert(flat, it) + elseif type(it) == "table" and it.t == "tuple" then + local tw = #it.v + if (w and w ~= tw) or tw == 0 then + return { t = "list", v = items }, i + end + w = tw + for _, x in it.v do + if type(x) ~= "number" then + return { t = "list", v = items }, i + end + table.insert(flat, x) + end + else + return { t = "list", v = items }, i + end + end + if w == nil then + return { t = "list", v = items }, i + end + return { t = "arr", w = w, v = flat } :: Arr, i + end + + local function tuple(i: number): (Value, number) + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + i += 1 + break + elseif c == "" then + fail("unterminated tuple", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= ")" then + fail("expected ',' or ')' in a tuple", i) + end + end + return { t = "tuple", v = items }, i + end + + -- { type key = value ... } (metadata dictionaries) + local function dict(i: number): (Value, number) + local out: { [string]: Value } = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated dictionary", i) + elseif c == ";" or c == "," then + i += 1 + continue + end + local ty + ty, i = ident(i) + if not ty then + fail("expected a type in a dictionary", i) + end + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + i += 2 + end + i = ws(i) + local key: string? + c = ssub(s, i, i) + if c == '"' or c == "'" then + key, i = str(i) + else + key, i = ident(i) + end + if not key then + fail("expected a key in a dictionary", i) + end + i = expect(i, "=") + local v + v, i = value(i) + out[key :: string] = v + end + return { t = "dict", v = out }, i + end + + function value(i: number): (Value, number) + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + i = ws(i) + local c = ssub(s, i, i) + local v: Value + if c == "[" then + v, i = list(i) + elseif c == "(" then + v, i = tuple(i) + elseif c == "{" then + v, i = dict(i) + elseif c == '"' or c == "'" then + v, i = str(i) + elseif c == "@" then + local path + if ssub(s, i, i + 2) == "@@@" then + local e = sfind(s, "@@@", i + 3, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3 + else + local e = sfind(s, "@", i + 1, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1 + end + local a: { [string]: any } = { t = "asset", v = path } + local j = ws(i) + if ssub(s, j, j) == "<" then -- references = @file@ + local e = sfind(s, ">", j + 1, true) + if not e then + fail("unterminated path", j) + end + a.path = ssub(s, j + 1, (e :: number) - 1) + i = (e :: number) + 1 + end + v = a + elseif c == "<" then + local e = sfind(s, ">", i + 1, true) + if not e then + fail("unterminated path", i) + end + v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1 + else + local num, j = number(i) + if num ~= nil then + v, i = num, j + else + local id + id, j = ident(i) + if not id then + fail("expected a value", i) + end + i = j + if id == "None" then + v = NONE + elseif id == "true" then + v = true + elseif id == "false" then + v = false + else + v = { t = "id", v = id } + end + end + end + depth -= 1 + return v, i + end + + -- ( key = value ; "doc" ; prepend key = value ... ) + function metadata(i: number): ({ [string]: Value }, number) + local out: { [string]: Value } = {} + i = expect(i, "(") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + return out, i + 1 + elseif c == "" then + fail("unterminated metadata", i) + elseif c == ";" or c == "," then + i += 1 + continue + elseif c == '"' or c == "'" then + out.doc, i = str(i) + continue + end + local key + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + local op: string? = nil + if LISTOPS[key] then + op = key + i = ws(i) + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + end + i = ws(i) + if ssub(s, i, i) == "=" then + local v + v, i = value(i + 1) + if op == "delete" then + -- deletions only matter for composition + elseif op and op ~= "reorder" then + -- prepend / append / add: merge into one list + local prev = out[key :: string] + if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then + for _, x in v.v do + table.insert(prev.v, x) + end + else + out[key :: string] = v + end + else + out[key :: string] = v + end + end + end + end + + -- time samples: { time: value, ... } + local function samples(i: number): ({ times: { number }, values: { Value } }, number) + local times: { number }, values: { Value } = {}, {} + i = expect(i, "{") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated time samples", i) + elseif c == "," then + i += 1 + continue + end + local t + t, i = number(i) + if t == nil then + fail("expected a time code", i) + end + i = expect(i, ":") + local v + v, i = value(i) + table.insert(times, t :: number) -- fail() threw on nil + table.insert(values, v) + end + return { times = times, values = values }, i + end + + local function targets(v: Value): { string } + local out = {} + if type(v) == "table" then + if v.t == "path" then + table.insert(out, v.v) + elseif v.t == "list" then + for _, x in v.v do + if type(x) == "table" and x.t == "path" then + table.insert(out, x.v) + end + end + end + end + return out + end + + local primBody: (i: number, prim: Prim) -> number + + local function newPrim(specifier: string, typeName: string?, name: string): Prim + return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} } + end + + -- def Type "name" ( meta ) { body } + local function prim(i: number, specifier: string): (Prim, number) + i = ws(i) + local typeName: string? = nil + local c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + typeName, i = ident(i) + if not typeName then + fail("expected a prim type or name", i) + end + i = ws(i) + -- dotted schema names (rare) + while ssub(s, i, i) == "." do + local more + more, i = ident(i + 1) + typeName = (typeName :: string) .. "." .. (more or "") + end + i = ws(i) + end + c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + fail("expected a prim name", i) + end + local name + name, i = str(i) + local p = newPrim(specifier, typeName, name) + i = ws(i) + if ssub(s, i, i) == "(" then + p.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, p) + return p, i + end + + -- variantSet "name" = { "variant" ( meta ) { body } ... } + local function variantSet(i: number, p: Prim): number + i = ws(i) + local setName + setName, i = str(i) + i = expect(i, "=") + i = expect(i, "{") + local sets = p.variantSets or {} + p.variantSets = sets + local set = sets[setName] or {} + sets[setName] = set + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + return i + 1 + elseif c ~= '"' and c ~= "'" then + fail("expected a variant name", i) + end + local vname + vname, i = str(i) + local body = newPrim("def", nil, vname) + i = ws(i) + if ssub(s, i, i) == "(" then + body.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, body) + set[vname] = body + end + end + + -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + local function property(i: number, first: string, p: Prim): number + local word: string? = first + local op: string? = nil + if LISTOPS[word :: string] then + op = word + i = ws(i) + word, i = ident(i) + end + local custom, uniform = false, false + if word == "custom" then + custom = true + i = ws(i) + word, i = ident(i) + end + if word and VARIABILITY[word] then + uniform = word == "uniform" + i = ws(i) + word, i = ident(i) + end + if not word then + fail("expected a property", i) + end + local isRel = word == "rel" + local typeName: string? = nil + local array = false + if not isRel then + typeName = word + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + array = true + i += 2 + end + end + i = ws(i) + local name + name, i = ident(i) + if not name then + fail("expected a property name", i) + end + local suffix: string? = nil + if ssub(s, i, i) == "." then + suffix, i = ident(i + 1) + end + local prop = p.props[name :: string] + if not prop then + prop = { name = name :: string, rel = isRel } :: Prop + p.props[name :: string] = prop + table.insert(p.order, name :: string) + end + local pr = prop :: Prop + if typeName then + pr.typeName, pr.array = typeName, array + end + pr.uniform = pr.uniform or uniform or nil + pr.custom = pr.custom or custom or nil + i = ws(i) + if ssub(s, i, i) == "=" then + i = ws(i + 1) + if suffix == "timeSamples" then + pr.samples, i = samples(i) + elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then + i = skipBalanced(i) + else + local v + v, i = value(i) + if op == "delete" then + -- composition only + elseif suffix == "connect" then + pr.connect = targets(v) + elseif isRel then + pr.value = targets(v) + pr.hasValue = true + else + pr.value = v + pr.hasValue = true + end + end + end + i = ws(i) + if ssub(s, i, i) == "(" then + local m + m, i = metadata(i) + if pr.meta then + for k, v in m do + (pr.meta :: any)[k] = v + end + else + pr.meta = m + end + end + return i + end + + function primBody(i: number, p: Prim): number + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + depth -= 1 + return i + 1 + elseif c == "" then + fail("unterminated prim", i) + elseif c == ";" then + i += 1 + continue + end + local word, j = ident(i) + if not word then + fail("unexpected character in a prim", i) + end + if word == "def" or word == "over" or word == "class" then + local child + child, i = prim(j, word) + table.insert(p.children, child) + elseif word == "variantSet" then + i = variantSet(j, p) + elseif word == "reorder" then + local k = ws(j) + local w2, k2 = ident(k) + if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then + k2 = expect(k2, "=") + local _ + _, i = value(k2) + else + i = property(j, word, p) + end + else + i = property(j, word, p) + end + end + end + + -- the whole layer + local function layer(): Layer + local i = 1 + if ssub(s, 1, 3) == "\239\187\191" then + i = 4 + end + if ssub(s, i, i + 4) ~= "#usda" then + fail("not a USDA file (no #usda header)", i) + end + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + local out: Layer = { meta = {}, prims = {} } + i = ws(i) + if ssub(s, i, i) == "(" then + out.meta, i = metadata(i) + end + while true do + i = ws(i) + if i > n then + break + end + local word, j = ident(i) + if word == "def" or word == "over" or word == "class" then + local p + p, i = prim(j, word) + table.insert(out.prims, p) + elseif word == "reorder" then + j = ws(j) + local _ + _, j = ident(j) + j = expect(j, "=") + _, i = value(j) + elseif ssub(s, i, i) == ";" then + i += 1 + else + fail("expected def / over / class", i) + end + end + return out + end + + return layer +end + +-- layer(text, opts?) -> Layer | nil, message, offset (0-based) +function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) + local run = parser(text, maxBytes or 2 ^ 30) + local ok, res = pcall(run) + if ok then + return res, nil, nil + end + if type(res) == "table" and (res :: any).usda then + return nil, (res :: any).usda, math.max(((res :: any).at or 1) - 1, 0) + end + return nil, "parse error: " .. tostring(res), nil +end + +-- version(text) -> the "#usda " string +function Parse.version(text: string): string? + return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") +end + +return Parse +end +__FILES["model/usda/Write"] = function() + +-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. +-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, +-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture +-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a +-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, +-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are +-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) +-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), +-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the +-- embedded bytes written into opts.files as _.. Not written: skins, morph targets, weights animation, +-- lines / points primitives (counted in the returned notes). +local Types = __include("Types") + +local Write = {} + +local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } +local RAD = 180 / math.pi + +type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } + +-- ------------------------------------------------------------------------------------------------ text helpers +local function fmt(x: number): string + if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 1e15 then + return string.format("%d", x) + end + return string.format("%.9g", x) +end +local function tuple(t: { number }): string + local parts = table.create(#t) + for k, v in t do + parts[k] = fmt(v) + end + return "(" .. table.concat(parts, ", ") .. ")" +end +local function quote(s: string): string + return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"' +end +local function asset(s: string): string + if string.find(s, "@", 1, true) then + return "@@@" .. s .. "@@@" + end + return "@" .. s .. "@" +end +-- a valid, sibling-unique prim name +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local n = string.gsub(name or "", "[^%w_]", "_") + if n == "" then + n = fallback + end + if string.find(n, "^%d") then + n = "_" .. n + end + local base, k = n, 1 + while used[n] do + k += 1 + n = base .. "_" .. k + end + used[n] = true + return n + end +end + +-- an accessor's elements as numbers (normalized types to floats) +local function values(acc: Types.Accessor?): ({ number }?, number) + if not acc then + return nil, 0 + end + local get = Types.Scene.reader(acc) + if not get then + return nil, 0 + end + local n, c = acc.count, acc.components + local out = table.create(n * c) :: { number } + for i = 0, n - 1 do + for k = 0, c - 1 do + out[i * c + k + 1] = get(i, k) + end + end + return out, c +end + +-- array literal of tuples ("[(x, y, z), ...]") or scalars +local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string + local st = stride or width + local n = count or (#vals // st) + local parts = table.create(n) + local buf = table.create(width) + for i = 0, n - 1 do + for k = 1, width do + local v = vals[i * st + k] or 0 + if map then + v = map(i, k, v) + end + buf[k] = fmt(v) + end + parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")" + end + return "[" .. table.concat(parts, ", ") .. "]" +end + +-- ------------------------------------------------------------------------------------------------ primitives +type Merged = { + points: { number }, + counts: { number }, + indices: { number }, + normals: { number }?, + uvs: { [number]: { number } }, + colors: { number }?, -- rgba + hasAlpha: boolean, + subsets: { { faces: { number }, material: number? } }, +} + +-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points +local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) + local idx: { number } + if p.indices then + idx = (values(p.indices)) or {} :: { number } + else + idx = table.create(nverts) :: { number } + for i = 1, nverts do + idx[i] = i - 1 + end + end + local counts: { number }, out: { number } = {}, {} + local mode = p.mode + if mode == "triangles" or mode == nil then + for k = 1, #idx - 2, 3 do + table.insert(counts, 3) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "polygons" then + local fs = (values(p.faces)) or {} + local at = 1 + for _, n in fs do + if at + n - 1 > #idx then + break + end + table.insert(counts, n) + for k = at, at + n - 1 do + table.insert(out, idx[k]) + end + at += n + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b, c = idx[k], idx[k + 1], idx[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(counts, 3) + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(counts, 3) + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + else + return nil, nil + end + return counts, out +end + +-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable +local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? + local prims: { Types.Primitive } = {} + for _, p in mesh.primitives do + if p.attributes and p.attributes.POSITION and (p.attributes.POSITION :: Types.Accessor).components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then + table.insert(prims, p) + else + notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 + end + if p.targets and #p.targets > 0 then + notes["morph targets"] = (notes["morph targets"] or 0) + 1 + end + end + if #prims == 0 then + return nil + end + -- attributes every primitive has + local all = { NORMAL = true } + local uvSets: { number } = {} + for k = 0, 7 do + local every = true + for _, p in prims do + if not p.attributes["TEXCOORD_" .. k] then + every = false + end + end + if every then + table.insert(uvSets, k) + end + end + local anyColor = false + for _, p in prims do + if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then + all.NORMAL = false + end + if p.attributes.COLOR_0 then + anyColor = true + end + end + local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} } + for _, k in uvSets do + m.uvs[k] = {} + end + local face = 0 + for _, p in prims do + local base = #m.points // 3 + local pos = (values(p.attributes.POSITION)) or {} + local nv = p.attributes.POSITION.count + table.move(pos, 1, nv * 3, #m.points + 1, m.points) + if m.normals then + local nrm = (values(p.attributes.NORMAL)) or {} + table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals) + end + for _, k in uvSets do + local uv, c = values(p.attributes["TEXCOORD_" .. k]) + local dst = m.uvs[k] + for i = 0, nv - 1 do + table.insert(dst, (uv :: { number })[i * c + 1] or 0) + table.insert(dst, (uv :: { number })[i * c + 2] or 0) + end + end + if m.colors then + local col, c = values(p.attributes.COLOR_0) + local dst = m.colors :: { number } + for i = 0, nv - 1 do + if col then + table.insert(dst, col[i * c + 1] or 1) + table.insert(dst, col[i * c + 2] or 1) + table.insert(dst, col[i * c + 3] or 1) + local a = if c >= 4 then col[i * c + 4] or 1 else 1 + if a ~= 1 then + m.hasAlpha = true + end + table.insert(dst, a) + else + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + end + end + end + local counts, idx = faces(p, nv) + local sub = { faces = {}, material = p.material } + if counts and idx then + local ok = true + for _, v in idx do + if v < 0 or v >= nv then + ok = false + break + end + end + if ok then + for _, c in counts do + table.insert(m.counts, c) + table.insert(sub.faces, face) + face += 1 + end + for _, v in idx do + table.insert(m.indices, v + base) + end + else + notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1 + end + end + table.insert(m.subsets, sub) + end + return m +end + +-- ------------------------------------------------------------------------------------------------ write +function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number }) + local o: Options = opts or {} + local notes: { [string]: number } = {} + local out: { string } = {} + local function line(depth: number, s: string) + table.insert(out, string.rep(" ", depth) .. s) + end + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + if #(scene.skins or {}) > 0 then + notes.skins = #scene.skins + end + local wrap = #roots ~= 1 or (nodes[roots[1]] == nil) + local rootNames = namer() + local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") + + -- texture files + local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" + local texFile: { [number]: string } = {} + for i, tex in scene.textures or {} do + local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil + if tex.data and type(o.files) == "table" then + uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")) + if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + local files: any = o.files + if files[uri] == nil then + files[uri] = tex.data + end + elseif not uri then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1 + end + texFile[i] = uri :: string + end + + -- animation: per node, per path -> { times, values (components) } + type Track = { times: { number }, vals: { number }, comps: number } + local tracks: { [number]: { [string]: Track? } } = {} + local tcps = 24 + local tMin, tMax = math.huge, -math.huge + for _, anim in scene.animations or {} do + for _, ch in anim.channels or {} do + if ch.path == "weights" then + notes["weights animation"] = (notes["weights animation"] or 0) + 1 + elseif nodes[ch.node] and ch.input and ch.output then + local times = (values(ch.input)) or {} + local vals, comps = values(ch.output) + if vals and #times > 0 then + local stride = comps + local per = #vals // (comps * #times) + -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 + local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 + local tv = {} + for k = 0, #times - 1 do + for c = 1, stride do + table.insert(tv, vals[k * comps * mult + off + c] or 0) + end + end + tracks[ch.node] = tracks[ch.node] or {} + tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps } + for _, t in times do + tMin = math.min(tMin, t * tcps) + tMax = math.max(tMax, t * tcps) + end + end + end + end + end + + -- header + table.insert(out, "#usda 1.0") + table.insert(out, "(") + line(1, "defaultPrim = " .. quote(rootName)) + line(1, 'doc = "rosetta"') + if tMin <= tMax then + line(1, "endTimeCode = " .. fmt(tMax)) + end + line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1)) + if tMin <= tMax then + line(1, "startTimeCode = " .. fmt(tMin)) + line(1, "timeCodesPerSecond = " .. fmt(tcps)) + end + line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y"))) + table.insert(out, ")") + table.insert(out, "") + + local looksPath = "/" .. rootName .. "/Looks" + local matNames = namer() + local matPath: { [number]: string } = {} + for i, mat in scene.materials or {} do + matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) + end + + -- xform ops of a node (+ its animation) + local function xform(depth: number, ni: number, n: Types.Node) + local tr: { [string]: Track? }? = tracks[ni] + local order: { string } = {} + local function samples(track: Track, f: (vals: { number }, at: number) -> string): string + local parts = {} + for k, t in track.times do + table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps)) + end + return "{ " .. table.concat(parts, ", ") .. " }" + end + local function quat(v: { number }, at: number): string + -- USD writes (real, i, j, k) + return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local function vec3(v: { number }, at: number): string + return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local t, r, s = n.translation, n.rotation, n.scale + if n.matrix and #n.matrix == 16 then + if tr then + -- animated: start from the matrix's TRS + local m = n.matrix + local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) + local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) + local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2) + t, s = { m[13], m[14], m[15] }, { sx, sy, sz } + r = nil + notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1 + else + local m = n.matrix + line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] }))) + line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]') + return + end + end + if t or (tr and tr.translation) then + if t then + line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) + end + if tr and tr.translation then + line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation :: Track, vec3)) + end + table.insert(order, '"xformOp:translate"') + end + if r or (tr and tr.rotation) then + if r then + line(depth, "quatf xformOp:orient = " .. quat(r, 0)) + end + if tr and tr.rotation then + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation :: Track, quat)) + end + table.insert(order, '"xformOp:orient"') + end + if s or (tr and tr.scale) then + if s then + line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) + end + if tr and tr.scale then + line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale :: Track, vec3)) + end + table.insert(order, '"xformOp:scale"') + end + if #order > 0 then + line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]") + end + end + + local function meshBody(depth: number, m: Merged, path: string) + local doubleSided = false + for _, sub in m.subsets do + local mat = sub.material and scene.materials[sub.material] + if mat and mat.doubleSided then + doubleSided = true + end + end + if doubleSided then + line(depth, "uniform bool doubleSided = 1") + end + -- extent + local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, #m.points // 3 - 1 do + for c = 1, 3 do + local v = m.points[i * 3 + c] + if v < mn[c] then + mn[c] = v + end + if v > mx[c] then + mx[c] = v + end + end + end + if #m.points > 0 then + line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]") + end + line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1)) + line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1)) + local single = #m.subsets == 1 + if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then + line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">") + end + if m.normals then + line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, "point3f[] points = " .. arrayText(m.points, 3)) + if m.colors then + line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + if m.hasAlpha then + local alpha = {} + for i = 0, #m.colors // 4 - 1 do + alpha[i + 1] = m.colors[i * 4 + 4] + end + line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + end + local uvKeys = {} + for k in m.uvs do + table.insert(uvKeys, k) + end + table.sort(uvKeys) + for _, k in uvKeys do + local name = if k == 0 then "st" else "st" .. k + line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number + return if c == 2 then 1 - v else v + end) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, 'uniform token subdivisionScheme = "none"') + if not single then + local names = namer() + for k, sub in m.subsets do + if #sub.faces > 0 then + local mp = sub.material and matPath[sub.material :: number] + table.insert(out, "") + line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else "")) + line(depth, "{") + line(depth + 1, 'uniform token elementType = "face"') + line(depth + 1, 'uniform token familyName = "materialBind"') + line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1)) + if mp then + line(depth + 1, "rel material:binding = <" .. mp .. ">") + end + line(depth, "}") + end + end + end + end + + local function cameraBody(depth: number, c: Types.Camera) + if c.type == "orthographic" then + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20)) + line(depth, 'token projection = "orthographic"') + line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20)) + return + end + local vap = 24 + local yfov = c.yfov or 0.8 + local focal = vap / (2 * math.tan(yfov / 2)) + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float focalLength = " .. fmt(focal)) + line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1))) + line(depth, 'token projection = "perspective"') + line(depth, "float verticalAperture = " .. fmt(vap)) + end + + local LIGHT_TYPE: { [string]: string } = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } + local function lightBody(depth: number, l: Types.Light) + local c = l.color or { 1, 1, 1 } + line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) + line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1)) + if l.type ~= "directional" then + line(depth, "float inputs:radius = 0") + end + if l.type == "spot" then + local outer = l.outerCone or math.pi / 4 + line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD)) + line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0)) + end + if l.type ~= "directional" then + line(depth, "bool treatAsPoint = 1") + end + end + local function lightHead(l: Types.Light): string + return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else "" + end + + local visited: { [number]: boolean } = {} + local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean) + local n = nodes[ni] + if not n or visited[ni] then + return + end + visited[ni] = true + local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni) + local myPath = path .. "/" .. name + local mesh = n.mesh and scene.meshes[n.mesh] + local merged = mesh and merge(mesh, notes) + local cam = n.camera and scene.cameras[n.camera] + local lig = n.light and scene.lights[n.light] + local kind = "Xform" + local head = "" + local pad = string.rep(" ", depth) + if merged then + kind = "Mesh" + if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then + head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")" + end + elseif cam and not lig then + kind = "Camera" + elseif lig and not cam then + kind = LIGHT_TYPE[lig.type] or "SphereLight" + local h = lightHead(lig) + head = if h ~= "" then string.format(h, pad, pad) else "" + end + if n.skin then + notes.skins = (notes.skins or 0) + 0 + end + table.insert(out, "") + line(depth, "def " .. kind .. " " .. quote(name) .. head) + line(depth, "{") + xform(depth + 1, ni, n) + if kind == "Mesh" then + meshBody(depth + 1, merged :: Merged, myPath) + elseif kind == "Camera" then + cameraBody(depth + 1, cam :: Types.Camera) + elseif kind ~= "Xform" then + lightBody(depth + 1, lig :: Types.Light) + end + local childNames = namer() + -- a camera / light that did not take the node's prim + if cam and kind ~= "Camera" then + table.insert(out, "") + line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) + line(depth + 1, "{") + cameraBody(depth + 2, cam) + line(depth + 1, "}") + end + if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then + local l = lig :: Types.Light + local h = lightHead(l) + local pad2 = string.rep(" ", depth + 1) + table.insert(out, "") + line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else "")) + line(depth + 1, "{") + lightBody(depth + 2, l) + line(depth + 1, "}") + end + if isRoot and not wrap then + Write._looks(out, depth + 1, scene, matPath, texFile, line) + end + for _, c in n.children or {} do + writeNode(depth + 1, c, myPath, childNames, false) + end + line(depth, "}") + end + + if wrap then + line(0, "def Xform " .. quote(rootName)) + line(0, "{") + Write._looks(out, 1, scene, matPath, texFile, line) + local names = namer() + names("Looks", "Looks") + for _, r in roots do + writeNode(1, r, "/" .. rootName, names, false) + end + line(0, "}") + else + writeNode(0, roots[1], "", rootNames, true) + end + table.insert(out, "") + return table.concat(out, "\n"), notes +end + +-- the Looks scope: materials as UsdPreviewSurface networks +function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) + local mats = scene.materials or {} + if #mats == 0 then + return + end + table.insert(out, "") + line(depth, 'def Scope "Looks"') + line(depth, "{") + for i, mat in mats do + local path = matPath[i] + local mname = string.match(path, "([^/]+)$") :: string + table.insert(out, "") + line(depth + 1, "def Material " .. quote(mname)) + line(depth + 1, "{") + local d = depth + 2 + line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") + -- texture nodes (one per distinct ref) + type TexNode = { name: string, ref: Types.TextureRef, color: boolean } + local texNodes: { TexNode } = {} + local function texNode(ref: Types.TextureRef?, color: boolean): string? + if not ref or not texFile[ref.texture] then + return nil + end + for _, tn in texNodes do + if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then + return tn.name + end + end + local name = "Texture_" .. (#texNodes + 1) + table.insert(texNodes, { name = name, ref = ref, color = color }) + return name + end + local bc = mat.baseColor or { 1, 1, 1, 1 } + local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask" + local diffuseTex = texNode(mat.baseColorTexture, true) + local mrTex = texNode(mat.metallicRoughnessTexture, false) + local emTex = texNode(mat.emissiveTexture, true) + local nTex = texNode(mat.normalTexture, false) + local oTex = texNode(mat.occlusionTexture, false) + table.insert(out, "") + line(d, 'def Shader "PreviewSurface"') + line(d, "{") + local e = d + 1 + line(e, 'uniform token info:id = "UsdPreviewSurface"') + if diffuseTex then + line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>") + else + line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 })) + end + local em = mat.emissive or { 0, 0, 0 } + if emTex then + line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>") + elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then + line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 })) + end + local ext = mat.extensions or {} + if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then + line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor)) + line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0)) + end + if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then + line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior)) + end + if mrTex then + line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>") + else + line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0)) + end + if nTex then + line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>") + end + if oTex then + line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>") + end + if blend and diffuseTex then + line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>") + elseif blend then + line(e, "float inputs:opacity = " .. fmt(bc[4] or 1)) + end + if mat.alphaMode == "mask" then + line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5)) + end + if mrTex then + line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>") + else + line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1)) + end + line(e, "token outputs:surface") + line(d, "}") + -- primvar readers per texCoord set, transforms, textures + local readers: { [number]: boolean } = {} + for _, tn in texNodes do + local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 + if not readers[tc] then + readers[tc] = true + table.insert(out, "") + line(d, 'def Shader "PrimvarReader_' .. tc .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"') + line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc)) + line(d + 1, "float2 outputs:result") + line(d, "}") + end + end + for _, tn in texNodes do + local ref = tn.ref + local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0 + local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result" + if ref.transform then + local tr = ref.transform :: any + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '_Transform"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdTransform2d"') + line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">") + if tr.rotation then + line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD)) + end + if tr.scale then + line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 })) + end + if tr.offset then + line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 })) + end + line(d + 1, "float2 outputs:result") + line(d, "}") + stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" + end + local tex = scene.textures[ref.texture] + local sampler: Types.Sampler = tex and tex.sampler or {} + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdUVTexture"') + line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture])) + if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then + line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 })) + end + if tn.ref == mat.normalTexture then + line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)") + line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)") + end + line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"') + line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">") + line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"') + line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"') + line(d + 1, "float outputs:a") + line(d + 1, "float outputs:b") + line(d + 1, "float outputs:g") + line(d + 1, "float outputs:r") + line(d + 1, "float3 outputs:rgb") + line(d, "}") + end + line(depth + 1, "}") + end + line(depth, "}") +end + +return Write +end +__FILES["model/vox"] = function() + +-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) +-- and the files MagicaVoxel 0.99.x saves (version 150 and 200). +-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / +-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, +-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown +-- chunks are kept raw and written back. +-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per +-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as +-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is +-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. +-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must +-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. +-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Grid = __include("model/vox/Grid") + +-- ------------------------------------------------------------------------------------------------ contract +local Vox = { + name = "vox", + category = "model", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27) +} +type EncodeOptions = { + version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one) +} +type Dict = { [string]: string } +type GraphNode = { + kind: string, + id: number, + attrs: Dict, + child: number?, + layer: number?, + frames: { Dict }?, + children: { number }?, + models: { { model: number, attributes: Dict } }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps +local DEFAULT_PALETTE: { { number } } = {} +do + local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 } + for _, r in steps do + for _, g in steps do + for _, b in steps do + if #DEFAULT_PALETTE < 215 then + table.insert(DEFAULT_PALETTE, { r, g, b, 255 }) + end + end + end + end + local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + for ch = 1, 4 do + for _, v in ramp do + local c = { 0, 0, 0, 255 } + if ch == 4 then + c = { v, v, v, 255 } + else + c[ch] = v + end + table.insert(DEFAULT_PALETTE, c) + end + end +end +Vox.DEFAULT_PALETTE = DEFAULT_PALETTE + +local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs +local MAX_DEPTH = 256 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vox.sniff(r: Bytes.Reader): number + return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r: Bytes.Reader): string + local n = r:i32le() + if n < 0 or n > r:remaining() then + r:fail(Err.CORRUPT, "bad string length") + return "" + end + return r:string(n) +end + +local function dict(r: Bytes.Reader): Dict + local d: Dict = {} + local n = r:i32le() + if n < 0 or n * 8 > r:remaining() then + r:fail(Err.CORRUPT, "bad dictionary size") + return d + end + for _ = 1, n do + local k = str(r) + local v = str(r) + if r.err then + break + end + d[k] = v + end + return d +end + +local function ints(s: string?): { number } + local out = {} + if s then + for w in string.gmatch(s, "%S+") do + table.insert(out, tonumber(w) or 0) + end + end + return out +end + +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +local function rotation(b: number): { { number } }? + local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) + if i0 > 2 or i1 > 2 or i0 == i1 then + return nil + end + local i2 = 3 - i0 - i1 + local function sign(bit: number): number + return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1 + end + return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } +end + +-- the node transform of a frame dictionary (_r, _t) +local function applyFrame(node: Types.Node, f: Dict) + local t = ints(f._t) + local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + local rb = tonumber(f._r) + local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil + if not rows then + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end + return + end + -- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix + local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } } + for row = 1, 3 do + R[row][rows[row][1] + 1] = rows[row][2] + end + local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1]) + if det < 0 then + node.matrix = { + R[1][1], R[2][1], R[3][1], 0, + R[1][2], R[2][2], R[3][2], 0, + R[1][3], R[2][3], R[3][3], 0, + tx, ty, tz, 1, + } + return + end + local m00, m11, m22 = R[1][1], R[2][2], R[3][3] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(1 + m00 - m11 - m22) * 2 + w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s + elseif m11 > m22 then + local s = math.sqrt(1 + m11 - m00 - m22) * 2 + w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s + else + local s = math.sqrt(1 + m22 - m00 - m11) * 2 + w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s + end + node.rotation = { x, y, z, w } + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end +end + +-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +local function material(d: Dict): Types.VoxelMaterial + local m: Types.VoxelMaterial = { type = "diffuse" } + for k, v in d do + local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k + if key == "type" then + m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v + else + m[key] = tonumber(v) or v + end + end + return m +end + +type Parsed = { + version: number, + models: { Types.Voxels }, + palette: { { number } }?, + materials: { [number]: Types.VoxelMaterial }, + graph: { [number]: GraphNode }, + meta: { [string]: any }, + skipped: number, +} + +local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?) + local maxCells = opts and opts.maxCells or 2 ^ 27 + if r:string(4) ~= "VOX " then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + local version = r:u32le() + if r:string(4) ~= "MAIN" then + if r.err then + return nil, r.err + end + return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8) + end + local mainN, mainM = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if mainN < 0 or mainM < 0 or not r:skip(mainN) then + return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12) + end + local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 } + local meta = out.meta + local unknown: { any } = {} + local layers, robjs, cams = {}, {}, {} + local stop = r:tell() + mainM + if stop > r:size() then + return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16) + end + local pending: { number }? = nil + local cells = 0 + while r:tell() + 12 <= stop do + local at = r:tell() + local id = r:string(4) + local n, m = r:i32le(), r:i32le() + if n < 0 or m < 0 then + return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at) + elseif n > stop - r:tell() or m > stop - r:tell() - n then + return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at) + end + local c = r:slice(n) + if id == "SIZE" then + local sx, sy, sz = c:i32le(), c:i32le(), c:i32le() + if c.err or sx < 1 or sy < 1 or sz < 1 then + return nil, Err.new(Err.CORRUPT, "bad model size", at) + end + cells += sx * sy * sz + if cells > maxCells then + return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at) + end + pending = { sx, sy, sz } + elseif id == "XYZI" then + local size = pending + if not size then + return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at) + end + pending = nil + local count = c:i32le() + if c.err or count < 0 or count * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad voxel count", at) + end + local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE) + out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count) + table.insert(out.models, v) + elseif id == "RGBA" then + if n < 1024 then + return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) + end + local pal = table.create(255) :: { { number } } + for i = 1, 255 do + pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } + end + out.palette = pal + elseif id == "MATL" then + local mid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at) + end + out.materials[mid] = material(d) + elseif id == "nTRN" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() } + c:i32le() -- reserved + node.layer = c:i32le() + local nf = c:i32le() + if c.err or nf < 0 or nf * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at) + end + local frames = {} + for k = 1, nf do + frames[k] = dict(c) + end + node.frames = frames + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at) + end + out.graph[node.id] = node + elseif id == "nGRP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nc = c:i32le() + if c.err or nc < 0 or nc * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) + end + local children = table.create(nc) :: { number } + for k = 1, nc do + children[k] = c:i32le() + end + node.children = children + out.graph[node.id] = node + elseif id == "nSHP" then + local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) } + local nm = c:i32le() + if c.err or nm < 0 or nm * 8 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at) + end + local models = {} + for k = 1, nm do + models[k] = { model = c:i32le() + 1, attributes = dict(c) } + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nSHP models", at) + end + node.models = models + out.graph[node.id] = node + elseif id == "LAYR" then + local lid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at) + end + table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d }) + elseif id == "rOBJ" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at) + end + table.insert(robjs, d) + elseif id == "rCAM" then + local cid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at) + end + table.insert(cams, { id = cid, attributes = d }) + elseif id == "NOTE" then + local nn = c:i32le() + if c.err or nn < 0 or nn * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at) + end + local notes = table.create(nn) + for k = 1, nn do + notes[k] = str(c) + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad NOTE names", at) + end + meta.notes = notes + elseif id == "IMAP" then + local map = {} + for k = 1, math.min(n, 256) do + map[k] = c:u8() + end + meta.indexMap = map + elseif id == "META" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad META chunk", at) + end + meta.info = d + else + if id == "PACK" then + meta.pack = c:i32le() + end + table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? }) + end + if m > 0 then + local kids = r:bytes(math.min(m, r:remaining())) + if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then + unknown[#unknown].children = kids + end + end + if r.err then + return nil, r.err + end + end + if r:tell() < stop then + return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell()) + end + if #out.models == 0 then + return nil, Err.new(Err.CORRUPT, "no models") + end + if #layers > 0 then + meta.layers = layers + end + if #robjs > 0 then + meta.renderObjects = robjs + end + if #cams > 0 then + meta.cameras = cams + end + if #unknown > 0 then + meta.chunks = unknown + end + return out, nil +end + +-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) +local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number? + local t = graph[id] + if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then + return nil + end + visiting[id] = true + local node: Types.Node = { name = t.attrs._name, children = {} } + local index = #scene.nodes + 1 + scene.nodes[index] = node + local frames = t.frames or {} + if frames[1] then + applyFrame(node, frames[1]) + end + local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer } + if #frames > 1 or (frames[1] and frames[1]._f) then + vox.frames = frames + end + node.extras = { vox = vox } + local child = if t.child then graph[t.child] else nil + if child and child.kind == "nGRP" then + vox.group = child.attrs + for _, c in child.children or {} do + local ci = build(scene, graph, c, depth + 1, visiting, nmodels) + if ci then + table.insert(node.children, ci) + end + end + elseif child and child.kind == "nSHP" then + local models = child.models or {} + vox.shape = { attributes = child.attrs, models = models } + local first = models[1] + if first and first.model >= 1 and first.model <= nmodels then + node.voxels = first.model + end + end + visiting[id] = nil + return index +end + +-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err +function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + return p.models, nil +end + +function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local p, err = parse(r, opts) + if not p then + return nil, err + end + local scene = Types.Scene.new() + local pal = p.palette or DEFAULT_PALETTE + local mats = if next(p.materials) then p.materials else nil + for _, v in p.models do + v.palette = pal + v.materials = mats + end + scene.voxels = p.models + if p.graph[0] then + local root = build(scene, p.graph, 0, 0, {}, #p.models) + if root then + scene.roots = { root } + end + end + if #scene.nodes == 0 then + -- no scene graph (version 150 files): one node per model + for i = 1, #p.models do + scene.nodes[i] = { children = {}, voxels = i } + scene.roots[i] = i + end + end + scene.meta.up = "z" + scene.meta.vox = p.meta + scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function number(v: any): string + if type(v) ~= "number" then + return tostring(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return string.format("%d", v) + end + for _, f in { "%.6g", "%.9g", "%.17g" } do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end + +local function sortedKeys(d: { [string]: any }): { string } + local keys = {} + for k in d do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + return keys +end + +local function wstr(w: Bytes.Writer, s: string) + w:u32le(#s) + w:string(s) +end + +local function wdict(w: Bytes.Writer, d: { [string]: any }?) + if not d then + w:u32le(0) + return + end + local keys = sortedKeys(d) + w:u32le(#keys) + for _, k in keys do + wstr(w, k) + wstr(w, number(d[k])) + end +end + +-- a node's transform as a frame dictionary (_r, _t) | nil, message +local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?) + local f: Dict = {} + if base then + for k, v in base do + if k ~= "_r" and k ~= "_t" then + f[k] = v + end + end + end + local m = Types.Scene.nodeMatrix(node) + local cols, signs = {}, {} + for row = 0, 2 do + local best, bv, rest = 0, 0, 0 + for col = 0, 2 do + local v = m[col * 4 + row + 1] + if math.abs(v) > math.abs(bv) then + rest = math.max(rest, math.abs(bv)) + best, bv = col, v + else + rest = math.max(rest, math.abs(v)) + end + end + if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then + return nil, "node rotation is not a multiple of 90 degrees (or has a scale)" + end + table.insert(cols, best) + signs[row + 1] = if bv < 0 then 1 else 0 + end + local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64 + if rb ~= IDENTITY_R then + f._r = tostring(rb) + end + local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5) + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + f._t = string.format("%d %d %d", tx, ty, tz) + end + return f, nil +end + +type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? } + +function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local version = opts and opts.version or 200 + if type(version) ~= "number" or version < 0 then + return nil, Err.new(Err.ARG, "bad version") + end + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local scene: Types.Scene + if value.kind == "voxels" then + scene = Types.Scene.new() + scene.voxels = { value } + scene.nodes[1] = { children = {}, voxels = 1 } + scene.roots[1] = 1 + elseif value.kind == "scene" then + scene = value + else + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local models = scene.voxels + if type(models) ~= "table" or #models == 0 then + return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)") + end + for i, v in models do + local s = v.size + if type(s) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid") + end + for k = 1, 3 do + if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis") + end + end + if buffer.len(v.data) < s[1] * s[2] * s[3] then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") + end + end + local meta: any = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {} + local w = Bytes.writer(65536) + w:string("VOX ") + w:u32le(version) + w:string("MAIN") + w:u32le(0) + local mAt = w:tell() + w:u32le(0) + local function chunk(id: string, body: () -> ()) + w:string(id) + local at = w:tell() + w:u32le(0) + w:u32le(0) + body() + w:setU32le(at, w:tell() - at - 8) + end + if type(meta.info) == "table" then + chunk("META", function() + wdict(w, meta.info) + end) + end + -- models + for _, v in models do + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + chunk("SIZE", function() + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + end) + local count = Grid.count(v.data, sx * sy * sz) + chunk("XYZI", function() + w:u32le(count) + local at = w:reserve(count * 4) + Grid.write(w.buf, at, v.data, sx, sy, sz) + w.pos = at + count * 4 + end) + end + -- the scene graph + local records: { Record } = {} + local nextId = 0 + local function alloc(): number + local id = nextId + nextId += 1 + return id + end + local nodes = scene.nodes or {} + local visiting: { [number]: boolean } = {} + local failure: string? = nil + local function shape(model: number, vx: any?): number + local id = alloc() + local ms: { { model: number, attributes: Dict? } } = {} + local saved = vx and vx.shape + if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then + for _, sm in saved.models do + if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then + table.insert(ms, { model = sm.model - 1, attributes = sm.attributes }) + end + end + end + if #ms == 0 then + ms[1] = { model = model - 1, attributes = nil } + end + table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms }) + return id + end + local function visit(index: number, depth: number, layer: number?): number? + local node = nodes[index] + if not node or visiting[index] or depth > MAX_DEPTH then + failure = failure or "the node tree has a loop or is too deep" + return nil + end + visiting[index] = true + local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil + local id = alloc() + local attrs: { [string]: any } = {} + if vx and type(vx.attributes) == "table" then + for k, v in vx.attributes do + attrs[k] = v + end + end + attrs._name = node.name + local saved = vx and type(vx.frames) == "table" and vx.frames or nil + local f, ferr = frameOf(node, saved and saved[1]) + if not f then + failure = failure or ferr + f = {} + end + local frames = { f :: Dict } + if saved then + for k = 2, #saved do + frames[k] = saved[k] + end + end + local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames } + table.insert(records, rec) + local kids = node.children or {} + local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models + if hasVox and #kids == 0 then + rec.child = shape(node.voxels :: number, vx) + else + local gid = alloc() + local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} } + table.insert(records, grp) + rec.child = gid + if hasVox then + local tid = alloc() + local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } } + table.insert(records, t2) + table.insert(grp.children :: { number }, tid) + t2.child = shape(node.voxels :: number, vx) + end + for _, c in kids do + local cid = visit(c, depth + 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + visiting[index] = nil + return id + end + local roots = scene.roots or {} + local single = if #roots == 1 then nodes[roots[1]] else nil + if single and single.voxels == nil then + visit(roots[1], 0, -1) + elseif #roots > 0 then + local rid = alloc() + local gid = alloc() + local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } } + local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} } + table.insert(records, rec) + table.insert(records, grp) + for _, ri in roots do + local cid = visit(ri, 1, nil) + if cid then + table.insert(grp.children :: { number }, cid) + end + end + end + if failure then + return nil, Err.new(Err.ARG, failure) + end + for _, rec in records do + chunk(rec.kind, function() + w:u32le(rec.id) + wdict(w, rec.attrs) + if rec.kind == "nTRN" then + w:u32le(rec.child or 0) + w:u32le(0xFFFFFFFF) + w:u32le((rec.layer or 0) % 4294967296) + local frames = rec.frames or { {} } + w:u32le(#frames) + for _, f in frames do + wdict(w, f) + end + elseif rec.kind == "nGRP" then + local ch = rec.children or {} + w:u32le(#ch) + for _, c in ch do + w:u32le(c) + end + else + local ms = rec.models or {} + w:u32le(#ms) + for _, sm in ms do + w:u32le(sm.model) + wdict(w, sm.attributes) + end + end + end) + end + -- layers + if type(meta.layers) == "table" then + for _, l in meta.layers do + chunk("LAYR", function() + w:u32le(tonumber(l.id) or 0) + local d: { [string]: any } = {} + if type(l.attributes) == "table" then + for k, v in l.attributes do + d[k] = v + end + end + d._name = l.name + d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil + wdict(w, d) + w:u32le(0xFFFFFFFF) + end) + end + end + -- palette + local pal = models[1].palette or DEFAULT_PALETTE + chunk("RGBA", function() + for i = 1, 256 do + local c = pal[i] + if type(c) == "table" then + w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255)) + else + w:u32le(0) + end + end + end) + if type(meta.indexMap) == "table" then + chunk("IMAP", function() + for k = 1, 256 do + w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255)) + end + end) + end + -- materials + local mats = models[1].materials + if type(mats) == "table" then + local ids = {} + for id in mats do + if type(id) == "number" then + table.insert(ids, id) + end + end + table.sort(ids) + for _, id in ids do + local m = mats[id] + chunk("MATL", function() + w:u32le(id) + local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") } + for k, v in m do + if k ~= "type" and type(k) == "string" then + d["_" .. k] = v + end + end + wdict(w, d) + end) + end + end + if type(meta.renderObjects) == "table" then + for _, d in meta.renderObjects do + chunk("rOBJ", function() + wdict(w, d) + end) + end + end + if type(meta.cameras) == "table" then + for _, cam in meta.cameras do + chunk("rCAM", function() + w:u32le(tonumber(cam.id) or 0) + wdict(w, cam.attributes) + end) + end + end + if type(meta.notes) == "table" then + chunk("NOTE", function() + w:u32le(#meta.notes) + for _, s in meta.notes do + wstr(w, tostring(s)) + end + end) + end + if type(meta.chunks) == "table" then + for _, u in meta.chunks do + if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then + w:string(u.id) + w:u32le(buffer.len(u.content)) + w:u32le(if u.children then buffer.len(u.children) else 0) + w:bytes(u.content) + if u.children then + w:bytes(u.children) + end + end + end + end + w:setU32le(mAt, w:tell() - mAt - 4) + return w:finish(), nil +end + +return Vox +end +__FILES["model/vox/Grid"] = @native function() + + +-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI +-- records. Callers check every range first; nothing here throws. +local Grid = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the +-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. +-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. +@native function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number + local skipped = 0 + local sxy = sx * sy + for k = 0, n - 1 do + local p = off + k * 4 + local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) + if x < sx and y < sy and z < sz and i ~= 0 then + writeu8(dst, x + sx * y + sxy * z, i) + else + skipped += 1 + end + end + return skipped +end + +-- count(data, cells) -> the number of non-empty cells in data[0, cells) +@native function Grid.count(data: buffer, cells: number): number + local n = 0 + for k = 0, cells - 1 do + if readu8(data, k) ~= 0 then + n += 1 + end + end + return n +end + +-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). +-- The caller sizes dst with count() (sx, sy, sz <= 256). +@native function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number + local p = at + local k = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local i = readu8(data, k) + if i ~= 0 then + writeu8(dst, p, x) + writeu8(dst, p + 1, y) + writeu8(dst, p + 2, z) + writeu8(dst, p + 3, i) + p += 4 + end + k += 1 + end + end + end + return p +end + +return Grid +end +__FILES["model/vrml"] = function() + +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over +-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. +-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, +-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and +-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, +-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), +-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated +-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> +-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons +-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless +-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). +-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / +-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, +-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). +-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and +-- skins on write (the rest pose is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Wrl.sniff(r: Bytes.Reader): number + local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl +end +__FILES["model/x"] = function() + +-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", +-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format +-- specification and the standard templates, checked against assimp's X importer and test models. +-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per +-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal +-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global +-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, +-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), +-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four +-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, +-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. +-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. +-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in +-- meta.source.skippedFaces). +-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key +-- interpolation options (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Parse = __include("model/x/Parse") +local Build = __include("model/x/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local X = { + name = "x", + category = "model", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25) + maxValues: number?, -- refuse files with more numbers than this (default 2^27) + maxBytes: number?, -- refuse compressed files inflating to more (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" } + +-- ------------------------------------------------------------------------------------------------ sniff +function X.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "xof " then + return 0 + end + return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, +-- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may +-- refer back into the previous block's output). +local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) + end + local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p) + end + p += 4 + local spans: { { offset: number, length: number, size: number } } = {} + local o = 0 + while p + 6 <= limit and o < total do + local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2) + if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then + return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p) + end + if o + usize > total then + return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p) + end + table.insert(spans, { offset = p + 4, length = math.min(csize, limit - p - 4), size = usize }) + o += usize + p += 4 + csize + end + if o < total then + return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p) + end + local out, err = Deflate.mszip(b, spans) + if not out then + return nil, Err.new((err :: Err.Err).code, "MSZIP: " .. (err :: Err.Err).message, (err :: Err.Err).offset) + end + return out, nil +end + +function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 16 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", base) + end + if buffer.readstring(b, base, 4) ~= "xof " then + return nil, Err.new(Err.CORRUPT, "no xof header", base) + end + local enc = buffer.readstring(b, base + 8, 4) + local kind = ENCODINGS[enc] + if not kind then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8) + end + local bits = buffer.readstring(b, base + 12, 4) + local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0 + if floatSize == 0 then + return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12) + end + local data: buffer, from: number, to: number = b, base + 16, limit + if enc == "tzip" or enc == "bzip" then + local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30) + if not inflated then + return nil, err + end + data, from, to = inflated, 0, buffer.len(inflated) + end + local maxValues: number = opts and opts.maxValues or 2 ^ 27 + local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root)) + end + if not root then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, root, opts) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + local src = scene.meta.source :: { [string]: any } + src.version = buffer.readstring(b, base + 4, 4) + src.encoding = kind + src.compressed = enc == "tzip" or enc == "bzip" + src.floatSize = floatSize * 8 + return scene, nil +end + +return X +end +__FILES["model/x/Build"] = function() + +-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is +-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding +-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). +-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep +-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Parse = __include("model/x/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Node = Parse.Node + +-- a cursor over an object's flattened values +type Vals = { v: { any }, i: number } +local function num(c: Vals): number + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "number" then + error("expected a number in the data", 0) + end + return x +end +local function str(c: Vals): string + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "string" then + error("expected a string in the data", 0) + end + return x +end +-- a non-negative integer (an index) +local function index(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad index " .. n, 0) + end + return n +end + +-- a count of items that follow (each takes at least one value: a count past the data is refused before anything +-- is allocated for it) +local function count(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad count " .. n, 0) + end + if n > #c.v - c.i + 1 then + error("truncated: a count of " .. n .. " runs past the data", 0) + end + return n +end + +-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +local function mirror(m: { number }): { number } + local o = table.clone(m) + for _, k in { 3, 7, 9, 10, 12, 15 } do + o[k] = -o[k] + end + return o +end + +local function matrix(c: Vals): { number } + local m = table.create(16) :: { number } + for k = 1, 16 do + m[k] = num(c) + end + return mirror(m) +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material + local c: Vals = { v = node.vals, i = 1 } + local mat = Scene.material(node.name) + local r, g, b, a = num(c), num(c), num(c), num(c) + local power = num(c) + local sr, sg, sb = num(c), num(c), num(c) + local er, eg, eb = num(c), num(c), num(c) + mat.baseColor = { r, g, b, a } + if a < 1 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1) + mat.emissive = { er, eg, eb } + local textures = {} + for _, k in node.kids do + local lt = string.lower(k.type) + if lt == "texturefilename" or lt == "normalmapfilename" then + local path = k.vals[1] + if type(path) == "string" and path ~= "" then + path = string.gsub(path, "\\\\", "\\") + local uri = string.gsub(path, "\\", "/") + local ti = texCache[uri] + if not ti then + local base = string.match(uri, "([^/]+)$") or uri + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] }) + ti = #scene.textures + texCache[uri] = ti + end + table.insert(textures, uri) + if lt == "normalmapfilename" then + mat.normalTexture = mat.normalTexture or { texture = ti } + else + mat.baseColorTexture = mat.baseColorTexture or { texture = ti } + end + end + end + end + mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } } + return mat +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Bones = { { name: string, matrix: { number } } } +type Ctx = { + scene: Types.Scene, + globalMats: { [string]: number }, + texCache: { [string]: number }, + nodeByName: { [string]: number }, + pendingSkins: { { node: number, bones: Bones } }, + maxVertices: number, + skippedFaces: number, +} + +local function accessorF32(values: { number }, comps: number): Types.Accessor + local n = #values + local b = buffer.create(n * 4) + for i = 1, n do + writef32(b, (i - 1) * 4, values[i]) + end + return Scene.accessor(b, "f32", comps, n // comps) +end + +-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) +local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) + local scene = ctx.scene + local c: Vals = { v = m.vals, i = 1 } + local nv = count(c, ctx.maxVertices) + local pos = table.create(nv * 3) :: { number } + for k = 1, nv * 3 do + pos[k] = num(c) + end + local nf = count(c, ctx.maxVertices) + local faces = table.create(nf) :: { { number } } + local corners = 0 + for f = 1, nf do + local n = count(c, ctx.maxVertices) + corners += n + if corners > ctx.maxVertices then + error("limit: more than " .. ctx.maxVertices .. " face corners", 0) + end + local face = table.create(n) :: { number } + for k = 1, n do + local idx = index(c, 2 ^ 32) + if idx >= nv then + error("face index " .. idx .. " out of range", 0) + end + face[k] = idx + end + faces[f] = face + end + -- the optional data objects + local normals: { number }? = nil + local nfaces: { { number } }? = nil + local uvSets: { { number } } = {} + local colors: { { number } } = {} + local faceMat: { number } = {} + local mats: { number } = {} + local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {} + for _, k in m.kids do + local kc: Vals = { v = k.vals, i = 1 } + if k.type == "MeshNormals" then + local nn = count(kc, ctx.maxVertices) + local nr = table.create(nn * 3) :: { number } + for q = 1, nn * 3 do + nr[q] = num(kc) + end + local nnf = count(kc, ctx.maxVertices) + local nfs = table.create(nnf) :: { { number } } + for f = 1, nnf do + local n = count(kc, ctx.maxVertices) + local face = table.create(n) :: { number } + for q = 1, n do + face[q] = index(kc, 2 ^ 32) + end + nfs[f] = face + end + normals, nfaces = nr, nfs + elseif k.type == "MeshTextureCoords" then + local n = count(kc, ctx.maxVertices) + local uv = table.create(n * 2) :: { number } + for q = 1, n * 2 do + uv[q] = num(kc) + end + if n == nv then + table.insert(uvSets, uv) + end + elseif k.type == "MeshVertexColors" then + local n = count(kc, ctx.maxVertices) + local col = table.create(nv * 4, 1) :: { number } + for _ = 1, n do + local idx = index(kc, 2 ^ 32) + local r, g, b, a = num(kc), num(kc), num(kc), num(kc) + if idx < nv then + col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a + end + end + table.insert(colors, col) + elseif k.type == "MeshMaterialList" then + num(kc) -- material count (the objects below are authoritative) + local ni = count(kc, ctx.maxVertices) + for q = 1, ni do + faceMat[q] = index(kc, 2 ^ 20) + end + for _, mk in k.kids do + if mk.type == "@ref" then + table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0) + elseif mk.type == "Material" then + table.insert(scene.materials, material(scene, mk, ctx.texCache)) + table.insert(mats, #scene.materials) + end + end + elseif k.type == "SkinWeights" then + local name = str(kc) + local n = count(kc, ctx.maxVertices) + local verts = table.create(n) :: { number } + for q = 1, n do + verts[q] = index(kc, 2 ^ 32) + end + local weights = table.create(n) :: { number } + for q = 1, n do + weights[q] = num(kc) + end + table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) + end + end + -- material per face (a single index applies to every face) + local function matOf(f: number): number + local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] + return if mi then mi + 1 else 1 + end + -- unique vertices per (position, normal index) + local key: { [number]: number } = {} + local srcPos: { number } = {} + local srcNrm: { number } = {} + local groups: { [number]: { number } } = {} + local order: { number } = {} + local faceSizes: { [number]: { number } } = {} + local nNormals = if normals then #normals // 3 else 0 + for f, face in faces do + local n = #face + if n < 3 then + ctx.skippedFaces += 1 + else + local nface = nfaces and nfaces[f] + local vs = table.create(n) :: { number } + for k = 1, n do + local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept + local p = face[src] + local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 + local kk = p * (nNormals + 1) + q + 1 + local v = key[kk] + if not v then + table.insert(srcPos, p) + table.insert(srcNrm, q) + v = #srcPos - 1 + key[kk] = v + end + vs[k] = v + end + local mi = matOf(f) + local g = groups[mi] + if not g then + g = {} + groups[mi] = g + faceSizes[mi] = {} + table.insert(order, mi) + end + if triangulate then + for k = 2, n - 1 do + table.insert(g, vs[1]) + table.insert(g, vs[k]) + table.insert(g, vs[k + 1]) + end + else + table.move(vs, 1, n, #g + 1, g) + table.insert(faceSizes[mi], n) + end + end + end + if #order == 0 then + return nil, nil + end + table.sort(order) + -- shared vertex attributes (one vertex buffer for every primitive of the mesh) + local nout = #srcPos + local P = table.create(nout * 3) :: { number } + for v = 1, nout do + local p = srcPos[v] * 3 + P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3] + end + local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) } + if normals then + local N = table.create(nout * 3, 0) :: { number } + for v = 1, nout do + local q = srcNrm[v] + if q >= 0 then + N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3] + end + end + attributes.NORMAL = accessorF32(N, 3) + end + for s, uv in uvSets do + local U = table.create(nout * 2) :: { number } + for v = 1, nout do + local p = srcPos[v] * 2 + U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2] + end + attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2) + end + for s, col in colors do + local C = table.create(nout * 4) :: { number } + for v = 1, nout do + local p = srcPos[v] * 4 + C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4] + end + attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4) + end + if #bones > 0 then + local lists = table.create(nout) :: { { number } } + local byPos: { [number]: { number } } = {} + for j, bone in bones do + for q, vi in bone.verts do + local l = byPos[vi] + if not l then + l = {} + byPos[vi] = l + end + table.insert(l, j - 1) + table.insert(l, bone.weights[q] or 0) + end + end + for v = 1, nout do + lists[v] = byPos[srcPos[v]] or {} + end + attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists) + end + local skinBones: Bones? = nil + if #bones > 0 then + local list: Bones = {} + for _, bone in bones do + table.insert(list, { name = bone.name, matrix = bone.matrix }) + end + skinBones = list + end + local prims: { Types.Primitive } = {} + for _, mi in order do + local idx = groups[mi] + local ib = buffer.create(#idx * 4) + for k, x in idx do + writeu32(ib, (k - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" } + local mat = mats[mi] + prim.material = if mat and mat > 0 then mat else nil + if not triangulate then + prim.mode = "polygons" + local fs = faceSizes[mi] + local fb = buffer.create(#fs * 4) + for k, x in fs do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #fs) + end + table.insert(prims, prim) + end + table.insert(scene.meshes, { name = m.name, primitives = prims }) + return #scene.meshes, skinBones +end + +-- ------------------------------------------------------------------------------------------------ frames +local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number) + if depth > 200 then + error("frames nested too deep", 0) + end + local scene = ctx.scene + local node: Types.Node = { name = f.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + if f.name and ctx.nodeByName[f.name] == nil then + ctx.nodeByName[f.name] = ni + end + if parent then + table.insert(scene.nodes[parent].children, ni) + else + table.insert(scene.roots, ni) + end + local first = true + for _, k in f.kids do + if k.type == "FrameTransformMatrix" then + local m = matrix({ v = k.vals, i = 1 }) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + else + node.matrix = m + end + elseif k.type == "Mesh" then + -- the first mesh on the frame's node, more as child nodes + local mi, bones = mesh(ctx, k, triangulate) + if mi then + local holder = ni + if first then + node.mesh = mi + first = false + else + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + holder = #scene.nodes + table.insert(node.children, holder) + end + if bones then + table.insert(ctx.pendingSkins, { node = holder, bones = bones }) + end + end + elseif k.type == "Frame" then + frame(ctx, k, ni, triangulate, depth + 1) + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel + return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" } +end + +local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation? + local channels: { Types.Channel } = {} + for _, a in set.kids do + if a.type == "Animation" then + local target: string? = nil + for _, k in a.kids do + if k.type == "@ref" then + target = k.name + end + end + local node = target and ctx.nodeByName[target] + if node then + for _, k in a.kids do + if k.type == "AnimationKey" then + local c: Vals = { v = k.vals, i = 1 } + local kind = num(c) + local nk = count(c, ctx.maxVertices) + local times = table.create(nk) :: { number } + local T, R, S = {}, {}, {} + for q = 1, nk do + times[q] = num(c) / tps + local nvals = count(c, 16) + if kind == 0 and nvals == 4 then + local w, x, y, z = num(c), num(c), num(c), num(c) + -- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y + table.move({ x, y, -z, w }, 1, 4, #R + 1, R) + elseif (kind == 1 or kind == 2) and nvals == 3 then + local x, y, z = num(c), num(c), num(c) + if kind == 1 then + table.move({ x, y, z }, 1, 3, #S + 1, S) + else + table.move({ x, y, -z }, 1, 3, #T + 1, T) + end + elseif (kind == 3 or kind == 4) and nvals == 16 then + local t, r, s = Mat4.decompose(matrix(c)) + table.move(t, 1, 3, #T + 1, T) + table.move(r, 1, 4, #R + 1, R) + table.move(s, 1, 3, #S + 1, S) + else + error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0) + end + end + if #T == nk * 3 and nk > 0 then + table.insert(channels, channel(times, T, 3, node, "translation")) + end + if #R == nk * 4 and nk > 0 then + table.insert(channels, channel(times, R, 4, node, "rotation")) + end + if #S == nk * 3 and nk > 0 then + table.insert(channels, channel(times, S, 3, node, "scale")) + end + end + end + end + end + end + if #channels == 0 then + return nil + end + return { name = set.name, channels = channels } +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 } + local tps = 4800 + for _, k in root.kids do + if k.type == "Material" then + table.insert(scene.materials, material(scene, k, ctx.texCache)) + if k.name then + ctx.globalMats[k.name] = #scene.materials + end + elseif k.type == "AnimTicksPerSecond" then + local v = k.vals[1] + if type(v) == "number" and v > 0 then + tps = v + end + end + end + for _, k in root.kids do + if k.type == "Frame" then + frame(ctx, k, nil, triangulate, 0) + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + table.insert(scene.roots, #scene.nodes) + if bones then + table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones }) + end + end + end + -- skins: bone names -> frames + for _, ps in ctx.pendingSkins do + local joints: { number } = {} + local ibm = buffer.create(#ps.bones * 64) + for j, bone in ps.bones do + local ni = ctx.nodeByName[bone.name] + if not ni then + -- a bone without a frame: an extra root node keeps the joint numbering + table.insert(scene.nodes, { name = bone.name, children = {} }) + ni = #scene.nodes + table.insert(scene.roots, ni) + ctx.nodeByName[bone.name] = ni + end + joints[j] = ni + for k = 1, 16 do + writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, #ps.bones) + acc.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc }) + scene.nodes[ps.node].skin = #scene.skins + end + for _, k in root.kids do + if k.type == "AnimationSet" then + local anim = animationSet(ctx, k, tps) + if anim then + table.insert(scene.animations, anim) + end + end + end + scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces } + return scene, nil +end + +return Build +end +__FILES["model/x/Parse"] = function() + +-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the +-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and +-- binary tokens), checked against what assimp's XFileParser accepts (no code taken). +-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and +-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), +-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. +-- Text: ; and , separators, // and # comments, quoted strings, s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). +-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and +-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Parse = {} + +type Node = { type: string, name: string?, vals: { any }, kids: { Node } } + +local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring + +-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), +-- "punct", "eof"; err holds a message after a bad token +type Lexer = { next: () -> (string, any), err: string? } + +local KEYWORDS: { [number]: string } = { + [0x1F] = "template", + [0x28] = "WORD", + [0x29] = "DWORD", + [0x2A] = "FLOAT", + [0x2B] = "DOUBLE", + [0x2C] = "CHAR", + [0x2D] = "UCHAR", + [0x2E] = "SWORD", + [0x2F] = "SDWORD", + [0x30] = "void", + [0x31] = "string", + [0x32] = "unicode", + [0x33] = "cstring", + [0x34] = "array", +} + +-- ------------------------------------------------------------------------------------------------ text +local function textLexer(s: string): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = 1 + local n = #s + lex.next = function(): (string, any) + while true do + local _, e = string.find(s, "^[%s,;]+", p) + if e then + p = e + 1 + end + if p > n then + return "eof", nil + end + local c = string.byte(s, p) + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + local nl = string.find(s, "[\r\n]", p) + p = if nl then nl + 1 else n + 1 + else + break + end + end + local c = string.byte(s, p) + if c == 123 then + p += 1 + return "{", nil + elseif c == 125 then + p += 1 + return "}", nil + elseif c == 34 then + local q = string.find(s, '"', p + 1, true) + if not q then + lex.err = "unterminated string" + p = n + 1 + return "eof", nil + end + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "str", v + elseif c == 60 then + local q = string.find(s, ">", p + 1, true) or n + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "guid", v + end + local _, e = string.find(s, '^[^%s,;{}"]+', p) + local tok = string.sub(s, p, e :: number) + p = (e :: number) + 1 + if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + return "num", tonumber(tok) or 0 + end + return "id", tok + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ binary +local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = from + local function fail(msg: string): (string, any) + lex.err = msg + p = limit + return "eof", nil + end + lex.next = function(): (string, any) + if p + 2 > limit then + return "eof", nil + end + local tok = readu16(b, p) + p += 2 + if tok == 0x0A then + return "{", nil + elseif tok == 0x0B then + return "}", nil + elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token) + if p + 4 > limit then + return fail("truncated name") + end + local len = readu32(b, p) + p += 4 + if len > limit - p then + return fail("truncated name") + end + local v = readstring(b, p, len) + p += len + if tok == 2 then + p = math.min(p + 2, limit) + return "str", v + end + return "id", v + elseif tok == 3 then + if p + 4 > limit then + return fail("truncated integer") + end + local v = readu32(b, p) + p += 4 + return "num", v + elseif tok == 5 then + if p + 16 > limit then + return fail("truncated guid") + end + p += 16 + return "guid", "" + elseif tok == 6 or tok == 7 then + if p + 4 > limit then + return fail("truncated list") + end + local count = readu32(b, p) + p += 4 + local size = if tok == 6 then 4 else floatSize + if count > (limit - p) // size then + return fail("truncated list") + end + local out = table.create(count) :: { number } + if tok == 6 then + for i = 1, count do + out[i] = readu32(b, p) + p += 4 + end + elseif size == 8 then + for i = 1, count do + out[i] = readf64(b, p) + p += 8 + end + else + for i = 1, count do + out[i] = readf32(b, p) + p += 4 + end + end + return "list", out + elseif tok >= 0x0C and tok <= 0x14 then + return "punct", nil + elseif KEYWORDS[tok] then + return "id", KEYWORDS[tok] + end + return fail(string.format("unknown binary token 0x%x", tok)) + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ tree +local function tree(lex: Lexer, maxValues: number): (Node?, string?) + local queue: { { any } } = {} + local function take(): (string, any) + local q = table.remove(queue, 1) + if q then + return q[1], q[2] + end + return lex.next() + end + local function peek(k: number): string + while #queue < k do + local kind, v = lex.next() + table.insert(queue, { kind, v }) + if kind == "eof" then + break + end + end + local q = queue[k] + return if q then q[1] else "eof" + end + local budget = maxValues + -- skips a template / unknown block whose "{" was just read + local function skipBlock(): string? + local depth = 1 + while depth > 0 do + local kind = take() + if kind == "eof" then + return "unexpected end of file in a template" + elseif kind == "{" then + depth += 1 + elseif kind == "}" then + depth -= 1 + end + end + return nil + end + local body: (Node, number) -> string? + -- an object whose type token was read: [name] { ... } + local function object(parent: Node, typ: string, depth: number): string? + local name: string? = nil + local kind, v = take() + if kind ~= "{" then + name = if v ~= nil then tostring(v) else nil + kind = take() + if kind ~= "{" then + return "expected { after " .. typ + end + end + if typ == "template" then + return skipBlock() + end + local node: Node = { type = typ, name = name, vals = {}, kids = {} } + table.insert(parent.kids, node) + return body(node, depth + 1) + end + body = function(node: Node, depth: number): string? + if depth > 200 then + return "objects nested too deep" + end + local vals = node.vals + while true do + local kind, v = take() + if kind == "}" then + return nil + elseif kind == "eof" then + return if depth == 0 then nil else "unexpected end of file in " .. node.type + elseif kind == "num" or kind == "str" then + budget -= 1 + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + vals[#vals + 1] = v + elseif kind == "list" then + budget -= #v + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + table.move(v, 1, #v, #vals + 1, vals) + elseif kind == "{" then + -- a reference: { name [guid] } + local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} } + while true do + local k2, v2 = take() + if k2 == "}" then + break + elseif k2 == "eof" then + return "unexpected end of file in a reference" + elseif (k2 == "id" or k2 == "num") and ref.name == nil then + ref.name = tostring(v2) + end + end + table.insert(node.kids, ref) + elseif kind == "id" then + local k1 = peek(1) + if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then + local err = object(node, v, depth) + if err then + return err + end + end + -- a lone identifier (an enum value): ignored + end + -- guid / punct: ignored + if lex.err then + return lex.err + end + end + end + local root: Node = { type = "@root", name = nil, vals = {}, kids = {} } + local err = body(root, 0) + if err then + return nil, err + end + if lex.err then + return nil, lex.err + end + return root, nil +end + +-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message +function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) + local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) + return tree(lex, maxValues) +end + +return Parse +end +__FILES["model/x3d"] = function() + +-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, +-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). +-- New code. +-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, +-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, +-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / +-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; +-- head meta, components and UNIT length (-> meta.unit). +-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the +-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). +-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, +-- H-Anim skinning, scripts. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +type EncodeOptions = { + encoding: ("xml" | "x3dv")?, -- default "xml" + format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function X3d.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "]") or string.find(head, " 64 or restart >= 128 or npat > 128 then + return false + end + local bad = 0 + for i = 2, 109 do + local c = r:peekU8(i) + if c > 0 and c <= 31 then + bad += 1 + if bad > 40 then + return false + end + end + end + for i = 0, 127 do + local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i) + if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then + return false + end + end + return true +end + +function Six69.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Six69.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 497 then Err.TRUNCATED else Err.CORRUPT, "not a 669 module") + end + local extended = r:peek(2) == "JN" + r:skip(2) + local message = r:string(108) + local nsmp, npat, restart = r:u8(), r:u8(), r:u8() + local orders, tempos, breaks = {}, {}, {} + for i = 1, 128 do + orders[i] = r:u8() + end + for i = 1, 128 do + tempos[i] = r:u8() + end + for i = 1, 128 do + breaks[i] = r:u8() + end + if not r:need(nsmp * 25 + npat * 1536) then + return nil, r.err + end + local m = Tracker.newModule("669", 8, "s3m") + m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", "")) + m.meta.message = message + m.speed, m.tempo = 4, 78 + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5 + m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true + for i = 1, 8 do + m.channelPan[i] = if i % 2 == 0 then 0xD0 else 0x30 + end + local lengths: { number } = {} + for i = 1, nsmp do + local s = Tracker.newSample(r:fixed(13)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + if len >= 0x4000000 then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long") + end + s.c5speed = 8363 + if not (le > len and ls == 0) and le ~= 0 then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + lengths[i] = len + m.samples[i] = s + end + for i = 1, 128 do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + if orders[restart + 1] < npat then + m.restart = restart + end + -- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter) + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 8) + m.patterns[p + 1] = pat + local d = pat.data + local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat) + for row = 0, 63 do + for ch = 0, 7 do + local o = r.pos + (row * 8 + ch) * 3 + local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * 8 + ch) * 5 + local hasNote = ni < 0xFE + if hasNote then + buffer.writeu8(d, q, ni // 4 + 37) + buffer.writeu8(d, q + 1, (ni % 4) * 16 + iv // 16 + 1) + effect[ch + 1] = 0xFF + end + if ni <= 0xFE then + buffer.writeu8(d, q + 2, ((iv % 16) * 64 + 8) // 15 + 1) + end + if ep ~= 0xFF then + effect[ch + 1] = ep + end + local e = effect[ch + 1] + if e ~= 0xFF then + local cmd, param = e // 16, e % 16 + local name = EFFECTS[cmd + 1] + if cmd == 4 then + param = param * 17 -- vibrato: speed = depth + elseif cmd == 6 then + param = if param == 0 then 0x4F elseif param == 1 then 0xF4 else -1 + elseif cmd == 7 and not (hasNote and extended) then + name = nil + end + if name ~= "panslide" then + effect[ch + 1] = 0xFF + end + if name and param >= 0 then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + r:skip(1536) + if breaks[p + 1] < 63 then + Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next") + end + Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next") + end + -- sample data: unsigned 8-bit + local pos = r.pos + for i = 1, nsmp do + local s = m.samples[i] + local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += lengths[i] + end + m.meta.source = { format = "669", tracker = if extended then "UNIS 669" else "Composer 669" } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Six69.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Six69.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Six69 +end +__FILES["music/ahx"] = function() + +-- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: +-- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). +-- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel +-- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's +-- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Ahx = { + name = "ahx", + category = "music", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, stereo (0..4), loop, maxDuration + +-- ------------------------------------------------------------------------------------------------ sniff +function Ahx.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ahx.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "ahx" then + return nil, err or Err.new(Err.CORRUPT, "not an AHX module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) +function Ahx.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local song, err = Ahx.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Ahx +end +__FILES["music/far"] = function() + +-- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any +-- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads +-- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods +-- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, +-- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed +-- tempo OpenMPT uses (80 BPM in tracker terms). +-- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Far = { + name = "far", + category = "music", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT + +-- ------------------------------------------------------------------------------------------------ sniff +function Far.sniff(r: Bytes.Reader): number + if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +local function effect(e: number): (number, number, number) + local cmd, p = e // 16, e % 16 + if cmd == 1 then + return IT.portaup, 0xF0 + p, 0 + elseif cmd == 2 then + return IT.portadown, 0xF0 + p, 0 + elseif cmd == 3 then + return IT.toneporta, if p ~= 0 then 60 // p else 0, 0 + elseif cmd == 4 then + return IT.retrig, 6 // (1 + p) + 1, 0 + elseif cmd == 5 or cmd == 9 then + return IT.vibrato, p, 0 + elseif cmd == 6 then + return IT.vibrato, p * 8, 0 + elseif cmd == 7 then + return IT.volslide, p * 8, 0 + elseif cmd == 8 then + return IT.volslide, p, 0 + elseif cmd == 0xA then + return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume + elseif cmd == 0xB then + return IT.s3mex, 0x80 + p, 0 + elseif cmd == 0xF then + return IT.speed, p, 0 + end + return 0, 0, 0 +end + +function Far.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Far.sniff(r) == 0 then + return nil, Err.new(if r:size() < 98 then Err.TRUNCATED else Err.CORRUPT, "not a Farandole module") + end + r:skip(4) + local title = r:fixed(40) + r:skip(3) + local headerLength, version = r:u16le(), r:u8() + local onOff, pans = {}, {} + for i = 1, 16 do + onOff[i] = r:u8() + end + r:skip(9) + local speed = r:u8() + for i = 1, 16 do + pans[i] = r:u8() + end + r:skip(4) + local msgLen = r:u16le() + local message = r:string(msgLen) + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + local _npat, nord, restart = r:u8(), r:u8(), r:u8() + local sizes = {} + for i = 1, 256 do + sizes[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local m = Tracker.newModule("far", 16, "s3m") + m.title = title + m.meta.message = message + m.speed, m.tempo = if speed > 0 then speed else 4, 80 + m.mixVolume = 32 -- OpenMPT's pre-amp for FAR + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024 + m.flags.autoTonePorta = true + for i = 1, 16 do + m.channelMute[i] = onOff[i] == 0 + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + for i = 1, nord do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + m.restart = restart + -- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte + if not r:seek(headerLength) then + return nil, r.err + end + local last = -1 + for p = 0, 255 do + if sizes[p + 1] > 0 then + last = p + end + end + for p = 0, last do + local size = sizes[p + 1] + local rows = math.clamp((size - 2) // 64, 1, 1024) + local pat = Tracker.newPattern(if size > 0 then rows else 64, 16) + m.patterns[p + 1] = pat + if size > 0 then + local pr = r:slice(size) + if r.err then + return nil, r.err + end + local br = pr:u8() + pr:skip(1) + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, 15 do + local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * 16 + ch) * 5 + if note > 0 and note <= 72 then + buffer.writeu8(d, q, note + 36) + buffer.writeu8(d, q + 1, ins + 1) + end + if vol > 0 and vol <= 16 then + buffer.writeu8(d, q + 2, (vol - 1) * 64 // 15 + 1) + end + local fx, param, setVol = effect(e) + if setVol > 0 then + buffer.writeu8(d, q + 2, setVol) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + end + end + if br > 0 and br < rows - 2 then + Load.writeEffect(m, p, br + 1, IT["break"], 0, "next") + end + end + end + -- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data + local map = {} + for i = 1, 8 do + map[i] = r:u8() + end + r.err = nil + for i = 0, 63 do + if bit32.band(map[i // 8 + 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then + local h = r:slice(48) + if r.err then + break + end + local s = Tracker.newSample(h:fixed(32)) + local len = h:u32le() + h:skip(1) + local vol = h:u8() + local ls, le = h:u32le(), h:u32le() + local typ, loop = h:u8(), h:u8() + local bits = if typ % 2 == 1 then 16 else 8 + local frames = if bits == 16 then len // 2 else len + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.c5speed = 8363 * 2 + s.volume = math.min(vol * 4, 64) + local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + r:skip(math.min(len, r:remaining())) + if bit32.band(loop, 8) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + for k = #m.samples + 1, i do + m.samples[k] = Tracker.newSample() + end + m.samples[i + 1] = s + end + end + m.meta.source = { format = "far", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Far.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Far.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Far +end +__FILES["music/hmp"] = function() + +-- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) +-- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the +-- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE +-- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per +-- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker +-- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a +-- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP +-- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the +-- tracks apply on top. Renders through codecs/audio/MidiRender. +-- Not supported: writing; HMP branch tables (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Hmp = { + name = "hmp", + category = "music", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local HMI_MAGIC = "HMI-MIDISONG061595" + +function Hmp.sniff(r: Bytes.Reader): number + return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8, readu32 = buffer.readu8, buffer.readu32 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +-- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; +-- otherwise the MIDI encoding +local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number) + local v, shift = 0, 1 + for _ = 1, 5 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + if hmp then + v += (c % 128) * shift + shift *= 128 + if c >= 128 then + return v, p + end + else + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +type Ctx = { loops: number, budget: number } + +-- one track [p, e) -> events (note-offs merged in) | nil, message +local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?) + local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} + local tick, running = 0, 0 + while p < e do + local d, q = delta(b, p, e, hmp) + if not d then + break -- (a track cut inside its last delta: keep what was read) + end + tick += d + p = q + if p >= e then + return nil, "truncated event" + end + local st = readu8(b, p) + if st == 0xFE and not hmp then + -- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes + local n = 4 + if p + 1 < e and readu8(b, p + 1) == 0x10 then + n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1 + elseif p + 1 < e and readu8(b, p + 1) == 0x15 then + n = 8 + end + if p + n > e then + return nil, "truncated FE event" + end + p += n + elseif st == 0xFF then + local kind = if p + 1 < e then readu8(b, p + 1) else -1 + local n, r = delta(b, p + 2, e, false) + if kind < 0 or not n or r + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + end + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) }) + p = r + n + elseif st == 0xF0 or st == 0xF7 then + local n, r = delta(b, p + 1, e, false) + if not n or r + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) }) + p = r + n + running = 0 + else + if st >= 0x80 then + if st >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02X", st) + end + running = st + p += 1 + elseif running == 0 then + return nil, "running status without a status byte" + end + local hi, ch = running // 16, running % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local data = bytes(b, p, n) + p += n + if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then + ctx.loops += 1 + else + for i = 1, n do + data[i] %= 128 + end + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data }) + end + if hi == 9 and not hmp then + local dur, r = delta(b, p, e, false) + if not dur then + return nil, "truncated note duration" + end + p = r + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } }) + end + end + ctx.budget -= 1 + if ctx.budget < 0 then + return nil, "limit: too many events" + end + end + -- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them) + local out = Render.merge(list, offs) + table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} }) + return out, nil +end + +-- the chunk table -> { { start, stop } } track ranges | nil, message, kind +local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) + local new = buffer.readstring(b, base + 8, 6) == "013195" + local n = readu32(b, base + 0x30) + local p = base + (if new then 0x388 else 0x308) + if n == 0 or n > 256 then + return nil, string.format("bad track count %d", n), nil + end + local ranges = {} + for _ = 1, n do + if p + 12 > limit then + return nil, "truncated chunk header", "truncated" + end + local len = readu32(b, p + 4) + if len < 12 or p + len > limit then + return nil, "truncated chunk", "truncated" + end + table.insert(ranges, { p + 12, p + len }) + p += len + end + return ranges, nil, nil +end + +local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?) + local n = readu8(b, base + 228) + if n == 0 then + return nil, "no tracks", nil + end + if base + 370 + n * 4 > limit then + return nil, "truncated track table", "truncated" + end + local ranges, heads = {}, {} + for i = 0, n - 1 do + local at = base + readu32(b, base + 370 + i * 4) + if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then + return nil, string.format("bad track %d header", i), nil + end + local start = at + readu32(b, at + 0x57) + if start >= limit then + return nil, "truncated track", "truncated" + end + table.insert(ranges, { start, limit }) + table.insert(heads, at) + end + -- a track ends where the next track header starts (or at the end of the file) + for _, rg in ranges do + for _, h in heads do + if h >= rg[1] and h < rg[2] then + rg[2] = h + end + end + end + return ranges, nil, nil +end + +function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local hmi = r:peek(18) == HMI_MAGIC + if not hmi and r:peek(8) ~= "HMIMIDIP" then + return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file") + end + if limit - base < (if hmi then 371 else 0x40) then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38) + if rate == 0 or rate > 100000 then + return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate) + end + local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit) + if not ranges then + return nil, Err.from(msg :: string, nil, kind) + end + local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 } + local midi = Types.Midi.new(60) + for i, rg in ranges do + local evs, err = track(b, rg[1], rg[2], not hmi, ctx) + if not evs then + return nil, Err.from(err :: string, rg[1]) + end + if i == 1 then + local us = math.min(60000000 // rate, 0xFFFFFF) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } }) + end + midi.tracks[i] = { events = evs } + end + local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp" + Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops }) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Hmp.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Hmp +end +__FILES["music/hvl"] = function() + +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, +-- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- +-- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with +-- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer +-- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Hvl = { + name = "hvl", + category = "music", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type RenderOptions = Hively.RenderOptions -- sampleRate, subsong, loop, maxDuration (stereo: the file's) + +-- ------------------------------------------------------------------------------------------------ sniff +function Hvl.sniff(r: Bytes.Reader): number + local m = r:peek(4) + return if m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hvl.decode(r: Bytes.Reader, _opts: any?): (Types.Module?, Err.Err?) + local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "hvl" then + return nil, err or Err.new(Err.CORRUPT, "not an HVL module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) +function Hvl.open(r: Bytes.Reader, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + local song, err = Hvl.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song :: any).tune, opts) +end + +return Hvl +end +__FILES["music/it"] = function() + +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the +-- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or +-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, +-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo +-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. +-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's +-- extension chunks (plugins, extended instrument properties), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Itsex = __include("music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function It.sniff(r: Bytes.Reader): number + return if r:peek(4) == "IMPM" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r: Bytes.Reader, kind: string): any + local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = if kind == "vol" then math.clamp(y, 0, 64) else math.clamp(y, -32, 32) + end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r: Bytes.Reader, old: boolean): (any?, string?) + if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = if r:u8() ~= 0 then 1 else 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + -- channels: the highest one any pattern uses + local nch = 1 + local packed: { Bytes.Reader? } = {} + local rowsOf: { number } = {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + -- scan for the channel count + local scan = data:sub(0) + local seen: { [number]: number } = {} + while not scan:eof() do + local cv = scan:u8() + if cv == 0 then + continue + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end + end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = if speed > 0 then speed else 6 + m.tempo = if tempo >= 31 then tempo else 125 + m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p -= 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + -- instruments + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + -- samples + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = if c5 > 0 then c5 else 8363 + s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = if bit32.band(flg, 2) ~= 0 then 16 else 8 + local nchs = if bit32.band(flg, 4) ~= 0 then 2 else 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data: buffer? = nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p += used :: number + end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = bits // 8 + local avail = math.max(0, r:size() - ptr) // (bps * nchs) + len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), if bit32.band(flg, 64) ~= 0 then 2 else 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), if bit32.band(flg, 128) ~= 0 then 2 else 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do + local cv = pr:u8() + if cv == 0 then + row += 1 + continue + end + local ch = (cv - 1) % 64 + local mask = if cv >= 128 then pr:u8() else (lastMask[ch] or 0) + lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = if n < 120 then n + 1 elseif n == 255 then 255 elseif n == 254 then 254 elseif n == 246 then 253 else 0 + lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function It.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It +end +__FILES["music/it/Itsex"] = @native function() + + +-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). +-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of +-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. +-- +-- Never throws: every read is bounds-checked; corrupt streams return nil, message. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message +@native function Itsex.decompress(buf: buffer, off: number, limit: number, frames: number, bits: number, it215: boolean): (buffer?, number | string) + local out = buffer.create(frames * 4) + local blockLen = if bits == 16 then 0x4000 else 0x8000 + local topWidth = if bits == 16 then 17 else 9 + local fetchA = if bits == 16 then 4 else 3 + local lowerB = if bits == 16 then -8 else -4 + local upperB = if bits == 16 then 7 else 3 + local scale = if bits == 16 then 1 / 32768 else 1 / 128 + local wrap = if bits == 16 then 65536 else 256 + local half = wrap // 2 + local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p += 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + -- bit reader over [bstart, bend) + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + @native local function readBits(n: number): number + while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf += readu8(buf, bytePos) * 2 ^ bitCount + bytePos += 1 + bitCount += 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount -= n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do + if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw += 1 + width = if nw < width then nw else nw + 1 + continue + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(if bits == 16 then 0xFFFF else 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = if nw < width then nw else nw + 1 + continue + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 + continue + end + end + -- a delta, sign-extended from its width + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x -= shift + end + else + x = v % wrap + if x >= half then + x -= wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i += 1 + end + done += count + end + return out, p - off +end + +return Itsex +end +__FILES["music/med"] = function() + +-- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, +-- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song +-- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL +-- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks +-- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop +-- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave +-- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, +-- default pitch, volume). +-- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and +-- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Med = { + name = "med", + category = "music", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the +-- transpose used per octave of the keyboard, by the number of octaves stored (2..7) +local OCT_SAMPLE = { + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 2, 2, 1, 1, 0, 0, 0, 0 }, + { 3, 3, 2, 2, 1, 0, 0, 0 }, + { 4, 3, 2, 1, 1, 0, 0, 0 }, + { 5, 4, 3, 2, 1, 0, 0, 0 }, + { 6, 5, 4, 3, 2, 1, 0, 0 }, +} +local OCT_TRANSPOSE = { + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -60, -72 }, +} +local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 } +local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 52 or r:peek(3) ~= "MMD" then + return false + end + local v = r:peekU8(3) + if v < 0x30 or v > 0x33 then + return false + end + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52) +end + +function Med.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Ctx = { transpose: number, is8Ch: boolean, softMix: boolean, bpm: boolean, rowsPerBeat: number, volHex: boolean, vol7bit: boolean } + +-- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) +local function tempoToBpm(tempo: number, ctx: Ctx): number + if ctx.bpm and not ctx.is8Ch then + return if tempo < 7 then 111.5 else tempo * ctx.rowsPerBeat / 4 + end + if ctx.is8Ch and tempo > 0 then + return TEMPO_8CH[math.min(tempo, 10)] + elseif not ctx.softMix and tempo > 0 and tempo <= 10 then + return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo + elseif ctx.softMix and tempo < 8 then + return 157.86 + end + return tempo / 0.264 +end + +-- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +local function effect(cmd: number, p: number, ctx: Ctx): (number, number, boolean) + local lo = math.min(p, 15) + if cmd == 1 or cmd == 2 then + return if p > 0 then cmd else 0, p, false + elseif cmd == 4 then + return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's + elseif cmd == 5 then + return if p > 0 then 5 else 3, p, false + elseif cmd == 6 then + return if p > 0 then 6 else 4, p, false + elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then + return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset + elseif cmd == 9 then + return if p > 0 and p <= 0x20 then 0xF else 0, math.min(p, 0x1F), false + elseif cmd == 0xC then + if not ctx.volHex and p < 0x99 then + return 0xC, (p // 16) * 10 + p % 16, false + elseif ctx.volHex and not ctx.vol7bit then + return 0xC, math.min(p % 128, 64), false + elseif ctx.volHex then + return 0xC, (p % 128 + 1) // 2, false + end + return 0, 0, false + elseif cmd == 0xD then + return if p > 0 then 0xA else 0, p, false + elseif cmd == 0xF then + if p == 0 then + return 0xD, 0, false + elseif p <= 0xF0 then + local bpm = if p < 3 then 0x70 else math.floor(tempoToBpm(p, ctx) + 0.5) + if bpm > 255 then + local ext = Tracker.EXT.TEMPO_256 + math.min(bpm // 256, 3) - 1 -- tempos past 255 (EXT 0x47..0x49) + return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false + end + return 0xF, math.max(bpm, 0x20), false + elseif p == 0xF1 then + return 0xE, 0x93, false + elseif p == 0xF2 then + return 0xE, 0xD3, false + elseif p == 0xF3 then + return 0xE, 0x92, false + elseif p == 0xFF then + return 0, 0, true + end + return 0, 0, false + elseif cmd == 0x11 then + return 0xE, 0x10 + lo, false + elseif cmd == 0x12 then + return 0xE, 0x20 + lo, false + elseif cmd == 0x14 then + return 4, p, false -- ProTracker depth, faster + elseif cmd == 0x15 then + return 0xE, 0x50 + p % 16, false + elseif cmd == 0x16 then + return 0xE, 0x60 + lo, false + elseif cmd == 0x18 then + return 0xE, 0xC0 + lo, false + elseif cmd == 0x19 then + return 9, p, false + elseif cmd == 0x1A then + return 0xE, 0xA0 + lo, false + elseif cmd == 0x1B then + return 0xE, 0xB0 + lo, false + elseif cmd == 0x1D then + return 0xD, Load.bcd(p), false -- pattern break, the row in hex + elseif cmd == 0x1E then + return 0xE, 0xE0 + lo, false + elseif cmd == 0x1F then + if p >= 16 then + return 0xE, 0xD0 + p // 16, false + elseif p > 0 then + return 0xE, 0x90 + p, false + end + return 0, 0, false + elseif cmd == 0x2E then + if p <= 0x10 or p >= 0xF0 then + return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false + end + return 0, 0, false + elseif cmd < 0x10 and (cmd > 0 or p > 0) then + return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B) + end + return 0, 0, false +end + +-- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +local function wrapNote(note: number, vol7bit: boolean): number + local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) + if n > 132 and not vol7bit then + n -= 108 + elseif n > 120 then + n -= (n - 109) - (n - 109) % 12 + end + return if n >= 13 then n - 12 else 0 +end + +-- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding +local function readBlock(r: Bytes.Reader, off: number, version: number, ctx: Ctx, nch: number): (any?, boolean) + local br = r:sub(off) + local ntracks, nrows, info + if version < 1 then + ntracks, nrows, info = br:u8(), br:u8() + 1, 0 + else + ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be() + end + if br.err or nrows > 1024 then + return nil, false + end + local cmdExt: Bytes.Reader? = nil + if version >= 1 and info > 0 then + local ir = r:sub(info, 36) + ir:skip(16) + local ext = ir:u32be() + if not ir.err and ext > 0 then + local p = r:sub(ext, 4):u32be() + if p > 0 then + cmdExt = r:sub(p) + end + end + end + local lctx = table.clone(ctx) + lctx.vol7bit = cmdExt ~= nil + local pat = Tracker.newPattern(nrows, nch) + local d = pat.data + local high = false + local used = math.min(ntracks, nch) + for row = 0, nrows - 1 do + for ch = 0, ntracks - 1 do + local note, ins, cmd, param, cut = 0, 0, 0, 0, false + if version < 1 then + local ni, ic, p = br:u8(), br:u8(), br:u8() + if ni % 64 > 0 then + note = ni % 64 + lctx.transpose + end + ins = ic // 16 + bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1) + cmd, param = ic % 16, p + else + local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8() + if nv % 128 > 0 then + note = nv % 128 + lctx.transpose + elseif nv == 0x80 then + cut = true + end + ins, cmd, param = iv % 64, c, p + end + if br.err then + return pat, high + end + if ch < used then + local q = (row * nch + ch) * 5 + if note >= 61 + 24 - 12 then + high = true + end + local n = wrapNote(note, lctx.vol7bit) + if n > 0 then + buffer.writeu8(d, q, n) + elseif cut then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 1, ins) + if cmd ~= 0 or param ~= 0 then + local fx, fp, noteCut = effect(cmd, param, lctx) + if noteCut and n == 0 then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + end + return pat, high +end + +function Med.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 52 then Err.TRUNCATED else Err.CORRUPT, "not a MED module") + end + local version = r:peekU8(3) - 0x30 + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + h:skip(4) + local expOff = h:u32be() + -- the song: 63 sample headers, then the song header + local sh = r:sub(songOff, 63 * 8) + local song = r:sub(songOff + 63 * 8, 284) + local numBlocks, songLength = song:u16be(), song:u16be() + local seq = song:sub(4, 256) + song:skip(256) + local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8() + local trackVol = {} + for i = 1, 16 do + trackVol[i] = song:u8() + end + local masterVol, numSamples = song:u8(), song:u8() + if song.err or numSamples > 63 or numBlocks > 0x7FFF then + return nil, Err.new(Err.CORRUPT, "bad song header") + end + if numSamples > 0 and smpOff == 0 then + return nil, Err.new(Err.CORRUPT, "no sample table") + end + -- channels: the widest block (at least 4) + local nch = 4 + local blockPtr: { number } = {} + for b = 0, numBlocks - 1 do + local p = r:sub(blockOff + b * 4, 4):u32be() + blockPtr[b + 1] = p + if p > 0 and p < r:size() then + local w = if version < 1 then r:peekU8(p) else r:peekU8(p) * 256 + r:peekU8(p + 1) + nch = math.max(nch, w) + end + end + if nch > 64 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks") + end + local m = Tracker.newModule("med", nch, "xm") + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.envRowHold = "amiga", true + local stSlides = bit32.band(flags, 0x20) ~= 0 + m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides + local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0 + m.flags.amigaLimits = hardwareMix + -- the expansion data: instrument extras and names, the song name + local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 } + if expOff > 0 then + local e = r:sub(expOff, 80) + e:skip(4) + ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be() + ext.annoOff, ext.annoLen = e:u32be(), e:u32be() + ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be() + e:skip(16) + ext.nameOff, ext.nameLen = e:u32be(), e:u32be() + if e.err then + ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0 + end + end + if ext.nameOff > 0 and ext.nameLen > 0 then + m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) + end + -- instruments and samples + local needInstruments = false + local instruments, samples = {}, {} + local unsupported = {} + for ins = 1, numSamples do + local smpHead = sh:sub((ins - 1) * 8, 8) + local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2 + local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8() + local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 } + local xsize = 0 + if ext.instrExt > 0 and ins <= ext.instrExtN then + xsize = ext.instrExtSize + local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize) + x.hold, x.decay = xr:u8(), xr:u8() + xr:skip(1) + x.finetune = xr:i8() + x.pitch, x.flags = xr:u8(), xr:u8() + xr:skip(4) + x.loopStart, x.loopLen = xr:u32be(), xr:u32be() + x.volume = xr:u8() + end + local name = "" + if ext.infoOff > 0 and ins <= ext.infoN then + name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40)) + end + local instr = Tracker.newInstrument(name) + instruments[ins] = instr + local iptr = if smpOff > 0 then r:sub(smpOff + (ins - 1) * 4, 4):u32be() else 0 + local length, typ = 0, 0 + if iptr > 0 then + local ih = r:sub(iptr, 6) + length, typ = ih:u32be(), ih:i16be() + if ih.err then + length, typ = 0, 0 + end + end + local isSynth = typ < 0 + local masked = bit32.band(typ % 65536, 0x0F) + local count = if not isSynth then (SAMPLES_PER_TYPE[masked] or 1) else 1 + if isSynth then + table.insert(unsupported, "synth / hybrid instrument " .. ins) + needInstruments = needInstruments or typ == -1 or typ == -2 + end + if midiCh > 0 and midiCh <= 16 then + needInstruments = true + table.insert(unsupported, "MIDI instrument " .. ins) + end + local first = #samples + 1 + -- keymap: one sample per note, multi-octave samples spread over the octaves + for n = 1, 120 do + instr.sampleMap[n] = first + end + if count > 1 then + needInstruments = true + for n = 1, 120 do + local note = n + 11 + transpose -- OpenMPT's keyboard index + if note < 0 then + note = -note % 12 + end + local oct = math.clamp(note // 12 - 4, 0, 7) + instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1] + instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120) + end + transpose = 0 + elseif masked == 7 then + needInstruments = true -- two extra-low octaves + for n = 1, 120 do + instr.noteMap[n] = math.clamp(n - 24, 1, 120) + end + end + if midiCh == 0 then + -- notes past the mixer's range fold down (by octaves) + local top = 61 + (if hardwareMix then 24 else 36) + for n = 1, 120 do + local real = instr.noteMap[n] + 12 + transpose + if real >= top then + instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12)) + end + end + end + -- sample data + local list = {} + for i = 0, count - 1 do + local s = Tracker.newSample(name) + s.volume = math.min(volume, 64) + s.relativeNote = transpose + list[i + 1] = s + samples[first + i] = s + end + local hasLoop = loopLen > 2 + if not isSynth and iptr > 0 and length > 0 then + local bits = if bit32.band(typ, 0x10) ~= 0 then 16 else 8 + local stereo = bit32.band(typ, 0x20) ~= 0 + local nchs = if stereo then 2 else 1 + local bytes = length * nchs + local frames = length // (bits // 8) + if count > 1 then + frames //= (2 ^ count - 1) + end + local pos = r.base + iptr + 6 + local ls, le = loopStart, loopStart + loopLen + for i = 1, count do + local s = list[i] + local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) } + local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget) + if not ok then + return nil, err + end + pos += frames * nchs * bits // 8 + if hasLoop then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + frames, ls, le = frames * 2, ls * 2, le * 2 + end + end + -- the instrument extras + if xsize > 0 then + if x.hold > 0 and not isSynth then + local env = Tracker.newEnvelope() + env.enabled = true + local fall = x.hold + (if x.decay > 0 then 64 // x.decay else 0) + if x.hold == 1 then + env.ticks, env.values = { 0, fall }, { 64, 0 } + else + env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 } + end + instr.volEnv = env + instr.fadeout = if x.decay > 0 then math.min(x.decay * 512, 65535) else 32767 + needInstruments = true + end + if xsize > 4 and x.pitch ~= 0 then + instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120) + needInstruments = true + end + if xsize > 18 then + instr.globalVolume = (x.volume + 1) // 2 * 2 + end + local ls, le = x.loopStart, x.loopStart + x.loopLen + for _, s in list do + s.finetune = math.clamp(x.finetune * 16, -128, 127) + if not isSynth and xsize > 14 then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + ls, le = ls * 2, le * 2 + end + if xsize > 5 then + if not isSynth then + s.loopType = if bit32.band(x.flags, 1) == 0 then 0 elseif bit32.band(x.flags, 8) ~= 0 then 2 else 1 + end + if bit32.band(x.flags, 4) ~= 0 then + s.globalVolume = 0 + end + end + end + end + end + -- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands) + local jumps: { [number]: number } = {} + local preamp = 32 + if version < 2 then + if songLength > 256 then + return nil, Err.new(Err.CORRUPT, "bad song length") + end + for i = 1, songLength do + m.order[i] = seq:u8() + end + for i = 1, nch do + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + if i <= 16 then + m.channelVolume[i] = math.min(trackVol[i], 64) + end + end + else + local s2 = song:sub(4, 256) + local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be() + local numTracks, numPlaySeqs = s2:u16be(), s2:u16be() + local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be() + if numTracks < 1 or numTracks > 64 then + return nil, Err.new(Err.CORRUPT, "bad track count") + end + local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0 + if volAdjust > 0 then + preamp = (preamp * math.min(volAdjust, 800) + 50) // 100 + end + if freePan then + preamp //= 2 + end + if trackVolsOff > 0 then + for i = 1, nch do + m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64) + end + end + local pans = (freePan or version > 2) and trackPanOff > 0 + for i = 1, nch do + if pans then + m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8 + else + local k = (i - 1) % 4 + m.channelPan[i] = if k == 1 or k == 2 then 0xC0 else 0x40 + end + end + local sections = r:sub(sectionTable, songLength * 2) + for _ = 1, songLength do + local sec = sections:u16be() + if sections.err then + break + end + if sec <= numPlaySeqs then + local ps = r:sub(playSeqTable + sec * 4, 4):u32be() + local pr = r:sub(ps, 42) + pr:skip(32) + local cmdTable = pr:u32be() + pr:skip(4) + local len = pr:u16be() + if not pr.err then + if #m.order > 0 then + table.insert(m.order, 254) + end + local start = #m.order + local er = r:sub(ps + 42, len * 2) + for _ = 1, len do + local b = er:u16be() + if er.err then + break + end + if b < 0x8000 then + table.insert(m.order, math.min(b, 253)) + end + end + if cmdTable > 0 then + local cr = r:sub(cmdTable) + for _ = 1, 4096 do + local off, c, extra = cr:u16be(), cr:u8(), cr:u8() + local arg = if extra >= 2 then cr:sub(cr:tell(), 2):u16be() else 0 + cr:skip(extra) + local at = start + off + 1 + if cr.err or off == 0xFFFF or at > #m.order then + break + end + if c == 1 then + m.order[at] = 255 + elseif c == 2 then + jumps[at] = arg + m.order[at] = 254 + end + end + end + end + end + end + end + m.preamp = preamp + -- tempo, speed, volume, the pattern context + local ctx: Ctx = { + transpose = 36 + playTranspose - (if version > 2 then 24 else 0), + is8Ch = bit32.band(flags, 0x40) ~= 0, + softMix = bit32.band(flags2, 0x80) ~= 0, + bpm = bit32.band(flags2, 0x20) ~= 0, + rowsPerBeat = 1 + bit32.band(flags2, 0x1F), + volHex = bit32.band(flags, 0x10) ~= 0, + vol7bit = false, + } + m.tempo = tempoToBpm(defTempo, ctx) + m.speed = math.clamp(tempo2, 1, 32) + if masterVol > 0 then + m.globalVolume = math.min(masterVol, 64) * 2 + end + -- blocks + for b = 0, numBlocks - 1 do + local p = blockPtr[b + 1] + local pat, high = nil, false + if p and p > 0 then + pat, high = readBlock(r, p, version, ctx, nch) + end + m.patterns[b + 1] = pat or Tracker.newPattern(64, nch) + needInstruments = needInstruments or high + end + -- play-sequence jumps: a jump effect at the end of the block before the command + for at, to in jumps do + local prev = m.order[at - 1] + if prev and prev < 254 and m.patterns[prev + 1] then + -- the block may be played elsewhere: give this order entry its own copy + local src = m.patterns[prev + 1] + local cp = Tracker.newPattern(src.rows, nch) + buffer.copy(cp.data, 0, src.data) + table.insert(m.patterns, cp) + m.order[at - 1] = #m.patterns - 1 + Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev") + end + end + m.samples = samples + if needInstruments then + m.instrumentMode = true + m.instruments = instruments + end + if #unsupported > 0 then + m.meta.unsupported = unsupported + end + if ext.annoOff > 0 and ext.annoLen > 1 then + m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size())) + end + m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Med.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Med.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Med +end +__FILES["music/midi"] = function() + +-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the +-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / +-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: +-- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to +-- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running +-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and +-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. +-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Smf = __include("music/midi/Smf") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24) +type EncodeOptions = Smf.WriteOptions -- runningStatus (default true) +type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices + +-- ------------------------------------------------------------------------------------------------ sniff +function Midi.sniff(r: Bytes.Reader): number + if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and +-- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +local function karaoke(midi: Types.Midi) + local lyrics: { { time: number, tick: number, text: string } } = {} + local headers: { [string]: { string } } = {} + local map = Render.tempoMap(midi) + local kar, hasWords = false, false + for _, t in midi.tracks do + if t.name == "Words" then + kar, hasWords = true, true + end + for _, ev in t.events do + if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then + local c = ev.data[2] + if c == 75 or c == 84 then -- @K, @T + kar = true + end + end + end + end + for ti, t in midi.tracks do + local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map + local words = kar and (t.name == "Words" or not hasWords) + for _, ev in t.events do + if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then + local text = Smf.text(ev.data :: { number }) + if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then + local key = string.sub(text, 2, 2) + local list = headers[key] or {} + headers[key] = list + table.insert(list, string.sub(text, 3)) + else + table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text }) + end + end + end + end + if #lyrics == 0 and next(headers) == nil then + return + end + table.sort(lyrics, function(a: { time: number, tick: number, text: string }, b: { time: number, tick: number, text: string }): boolean + return a.time < b.time + end) + midi.meta.lyrics = lyrics + midi.meta.karaoke = headers + local tags: { [string]: string } = {} + if headers.T then + tags.title = headers.T[1] + tags.artist = headers.T[2] + end + if headers.L then + tags.language = headers.L[1] + end + if headers.I then + tags.comment = table.concat(headers.I, "\n") + end + midi.meta.tags = tags +end + +function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + Render.attach(midi, { format = "midi", smf = midi.format }) + karaoke(midi) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?) + return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) +function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) +function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?) + return Render.decoder(midi, opts) +end + +-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) +function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number + return Render.seconds(Render.tempoMap(midi, track), tick) +end + +-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +function Midi.length(midi: Types.Midi): number + return Render.length(midi) +end + +-- text(data) -> the bytes of a text meta event as a string +Midi.text = Smf.text + +return Midi +end +__FILES["music/midi/Smf"] = function() + +-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE +-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps +-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are +-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the +-- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track +-- has none. Written from the SMF 1.0 specification (no third-party code). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + +type ReadOptions = { + strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) + maxEvents: number?, -- default 2^24 +} +type WriteOptions = { + runningStatus: boolean?, -- default true +} + +local function bytesOf(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data: { number }): string + local parts = table.create(#data) + for i, c in data do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +-- one MTrk body [p, e): events | nil, message, truncated +local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = {} + local tick = 0 + local running = 0 + while p < e do + -- delta time + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + n += 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick += delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p += 1 + if status < 0xF0 then + running = status + end + end + budget[1] -= 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p += 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + m += 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p += len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = status // 16 + local count = if kind == 12 or kind == 13 then 1 else 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = if count == 2 then readu8(b, p + 1) else 0 + if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p += count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = if count == 2 then { d1, d2 } else { d1 }, + }) + end + end + return events, nil, false +end + +-- read(r, opts?) -> Midi | nil, Err +function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) + local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q += 8 + size + size % 2 + end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } + for _, ev in events do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data :: { number }) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(division // 256) + midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w: Bytes.Writer, v: number) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = v // 128 + end + for i, c in bytes do + w:u8(if i < #bytes then c + 128 else c) + end +end + +local function byteList(d: any, want: number?): { number }? + if type(d) ~= "table" then + return if want == 0 then {} else nil + end + for i, v in d do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +-- write(midi, opts?) -> buffer | nil, Err +function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) + if type(midi) ~= "table" or type(midi.tracks) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Midi value with tracks") + end + local running = not (opts and opts.runningStatus == false) + local format = midi.format or 1 + local division = midi.division or 480 + if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then + return nil, Err.new(Err.ARG, "format must be 0, 1 or 2") + end + if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then + return nil, Err.new(Err.ARG, "division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be(if division < 0 then division + 65536 else division) + for ti, track in midi.tracks do + local events = if type(track) == "table" then track.events else nil + if type(events) ~= "table" then + return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") + end + -- stable order by tick + local sorted = true + local last = 0 + for i, ev in events do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list: { any } = events + if not sorted then + list = table.clone(events) + local order: { [any]: number } = {} + for i, ev in list do + order[ev] = i + end + table.sort(list, function(a: any, c: any): boolean + if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end + -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own + if type(track.name) == "string" and track.name ~= "" then + local named = false + for _, ev in list do + if ev.type == "meta" and ev.meta == 0x03 then + named = true + break + end + end + if not named then + local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) } + list = table.clone(list) + table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes }) + end + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in list do + local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then + continue -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = if base == 0xC0 or base == 0xD0 then 1 else 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(if t == "sysex" then 0xF0 else 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "event data too long") + end + vlq(w, #d) + for _, c in d do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick + end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf +end +__FILES["music/mod"] = function() + +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse bigger sample data in total (default 64 MB of f32 samples) +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED: { [string]: number } = { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig: string): number? + local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = tonumber(d) :: number + return if n >= 1 then n else nil + end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = tonumber(dd) :: number + return if n >= 1 and n <= 32 then n else nil + end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = tonumber(t) :: number + return if n >= 1 then n else nil + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r: Bytes.Reader): number + if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = if size >= 1084 then r:peek(4, 1080) else "" + local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels :: number + local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths: { number } = {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = (if ft >= 8 then ft - 16 else ft) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order: { number } = {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = if restart < songLength then restart else 0 + m.meta.signature = if nsamples == 31 then sig else nil + m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (b0 // 16) * 16 + b2 // 16 + local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total += len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m: any, _opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf: { any } = {} + if m.format == "xm" then + for i, ins in m.instruments do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in m.samples do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in m.patterns do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas: { buffer } = {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(even // 2) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(s.loopStart // 2) + w:u16be(math.max(1, (s.loopEnd - s.loopStart) // 2)) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8(if m.restart < #order and m.restart > 0 then m.restart else 127) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = if npat > 64 then "M!K!" else "M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = if note >= 1 and note <= 120 then Tables.noteToPeriod(note) else 0 + if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((ins // 16) * 16 + period // 256) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod +end +__FILES["music/mtm"] = function() + +-- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared +-- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): +-- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk +-- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). +-- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Mtm = { + name = "mtm", + category = "music", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Mtm.sniff(r: Bytes.Reader): number + if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts +-- both on one row somewhere (then it was written for players that treat them as ProTracker does) +local function speedTempoQuirk(m: any) + local speed, tempo, together = false, false, false + for _, p in m.patterns do + for row = 0, p.rows - 1 do + local s, t = false, false + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + if param < 0x20 then + s = true + else + t = true + end + end + end + speed, tempo, together = speed or s, tempo or t, together or (s and t) + end + end + if not (speed and tempo) or together then + return + end + for pi, p in m.patterns do + for row = 0, p.rows - 1 do + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + Load.writeEffect(m, pi - 1, row, 0xF, if param < 0x20 then 125 else 6, nil, nil, true) + break + end + end + end + end +end + +function Mtm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:size() < 66 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(3) ~= "MTM" then + return nil, Err.new(Err.CORRUPT, "no MTM signature") + end + r:skip(3) + local version = r:u8() + local title = r:fixed(20) + local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8() + local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8() + local pans: { number } = {} + for i = 1, 32 do + pans[i] = r:u8() + end + if r.err then + return nil, r.err + end + if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + local m = Tracker.newModule("mtm", nch, "xm") + m.title = title + m.linear = false + m.instrumentMode = false + for i = 1, nch do + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + -- samples + local sizes: { number } = {} + for i = 1, numSamples do + local s = Tracker.newSample(r:fixed(22)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + local ft, vol, attr = r:i8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + s.volume = math.min(vol, 64) + s.finetune = math.clamp(ft * 16, -128, 127) + local bits = if attr % 2 == 1 then 16 else 8 + s.bits = bits + local frames = 0 + if len > 2 then + frames = len + le = math.min(math.max(le, 1) - 1, len) + if ls + 4 >= le then + ls, le = 0, 0 + end + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + if le > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + end + end + sizes[i] = if len > 2 then len else 0 + s.length = frames + m.samples[i] = s + end + -- the order list + for i = 1, 128 do + local o = r:u8() + if i <= lastOrder + 1 then + m.order[i] = o + end + end + if r.err then + return nil, r.err + end + -- tracks (64 rows of 3 bytes each) and the patterns made of them + local rows = if rowsPerTrack > 0 then rowsPerTrack else 64 + local tracks = r:tell() + if not r:skip(192 * numTracks) then + return nil, r.err + end + local buf = r.buf + for p = 0, lastPattern do + local pat = Tracker.newPattern(rows, nch) + m.patterns[p + 1] = pat + for ch = 0, 31 do + local track = r:u16le() + if r.err then + return nil, r.err + end + if track > 0 and track <= numTracks and ch < nch then + local base = r.base + tracks + 192 * (track - 1) + for row = 0, rows - 1 do + local o = base + row * 3 + local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * nch + ch) * 5 + if b0 >= 4 then + buffer.writeu8(pat.data, q, b0 // 4 + 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up) + end + buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + b1 // 16) + local cmd, param = b1 % 16, b2 + if cmd == 0xA then + param = if param >= 16 then param - param % 16 else param + elseif cmd == 8 then + cmd, param = 0, 0 -- no 8xx panning in MultiTracker + elseif cmd == 0xE then + local x = param // 16 + if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then + cmd, param = 0, 0 -- not in MultiTracker + end + end + buffer.writeu8(pat.data, q + 3, cmd) + buffer.writeu8(pat.data, q + 4, param) + end + end + end + end + speedTempoQuirk(m) + -- the song message (40-character lines), then the sample data (unsigned PCM) + m.meta.message = r:string(commentSize) + if r.err then + r.err = nil + end + local pos = r.pos + for i = 1, numSamples do + local s = m.samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + s.loopEnd = math.min(s.loopEnd, s.length) + end + end + m.meta.source = { format = "mtm", version = version, tracks = numTracks } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mtm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Mtm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mtm +end +__FILES["music/mus"] = function() + +-- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format +-- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter +-- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel +-- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at +-- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without +-- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per +-- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / +-- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. +-- Not supported: writing (save as .mid through the midi format's encoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Mus = { + name = "mus", + category = "music", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + rate: number?, -- ticks per second, default 140 (Doom); some players use 70 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ constants +-- MUS controller / system event number -> MIDI controller (0 is the program change) +local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mus.sniff(r: Bytes.Reader): number + return if r:peek(4) == "MUS\x1a" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +-- the score [p, e) -> events | nil, message +local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean) + local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } + local map: { [number]: number } = { [15] = 9 } + local volume: { [number]: number } = {} + local nextChannel = 0 + local tick = 0 + while p < e do + local ev = readu8(b, p) + p += 1 + local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15) + if kind == 6 then + return events, nil, false + end + local ch = map[mch] + if not ch then + ch = nextChannel + map[mch] = ch + nextChannel += if nextChannel == 8 then 2 else 1 + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } }) + end + local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1 + if kind == 7 then + return nil, "unknown event type 7", false + elseif p + need > e then + return events, nil, true + end + local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0 + p += need + if kind == 0 then + table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } }) + elseif kind == 1 then + if need == 2 then + volume[ch] = math.min(d2, 127) + end + table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } }) + elseif kind == 2 then + table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } }) + elseif kind == 3 or kind == 4 then + local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127) + if CONTROLLER[c] == nil then + return nil, string.format("unknown controller %d", c), false + end + if kind == 4 and c == 0 then + table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } }) + else + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } }) + end + end + if #events > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events", false + end + if ev >= 128 then + local delay = 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p += 1 + delay = delay * 128 + c % 128 + until c < 128 or delay > 2 ^ 28 + tick += delay + end + end + return events, nil, true +end + +function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + local rate = o.rate or 140 + if type(rate) ~= "number" or rate < 1 or rate > 100000 then + return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second") + end + if r:peek(4) ~= "MUS\x1a" then + return nil, Err.new(Err.CORRUPT, "not a MUS file") + end + r:skip(4) + local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:skip(2) + local instruments = {} + for i = 1, ninst do + instruments[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local size = r.limit - r.base + if start > size then + return nil, Err.new(Err.TRUNCATED, "score starts past the end") + end + local p = r.base + start + local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24) + if not events then + return nil, Err.from(msg :: string, p) + end + local last = events[#events].tick + table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) }) + table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local midi = Types.Midi.new(70) + midi.format = 0 + midi.tracks = { { events = events } } + Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate }) + midi.meta.truncated = truncated or p + len > r.limit + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Mus.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Mus +end +__FILES["music/okt"] = function() + +-- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can +-- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style +-- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with +-- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample +-- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: +-- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. +-- Not supported: the Amiga LED filter (F), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Okt = { + name = "okt", + category = "music", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +local LAYOUT = table.freeze({ bigEndian = true }) :: Chunks.Layout + +-- ------------------------------------------------------------------------------------------------ sniff +function Okt.sniff(r: Bytes.Reader): number + return if r:peek(8) == "OKTASONG" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a negative arpeggio offset as the equivalent positive one +local function invert(p: number): number + p %= 16 + if p == 0 then + return 0 + end + return if p <= 12 then 12 - p else 24 - p +end + +-- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off +local function effect(e: number, p: number, paired: boolean): (string?, number, number, boolean) + if e == 1 and p > 0 then + return "portaup", p, -1, false -- "portamento down (period)": the period goes down + elseif e == 2 and p > 0 then + return "portadown", p, -1, false + elseif e == 10 and p > 0 then + return "arpeggio", p % 16 + invert(p // 16) * 16, -1, false -- down, original, up + elseif e == 11 and p > 0 then + return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down + elseif e == 12 and p > 0 then + return "arpeggio", p, -1, false -- up, up, original + elseif e == 13 and p > 0 then + return "noteslidedown", 0x10 + math.min(p, 15), -1, false + elseif e == 30 and p > 0 then + return "noteslideup", 0x10 + math.min(p, 15), -1, false + elseif e == 21 and p > 0 then + return "noteslidedown", 0x50 + math.min(p, 15), -1, false + elseif e == 17 and p > 0 then + return "noteslideup", 0x50 + math.min(p, 15), -1, false + elseif e == 25 then + return "jump", p, -1, false + elseif e == 27 then + return nil, 0, -1, true + elseif e == 28 and p < 0x20 then + return "speed", p, -1, false + elseif e == 31 then + local x, y = p // 16, p % 16 + local slide = if paired then "chanvolslide" else "volslide" + if p <= 0x40 then + if paired then + return "chanvol", p, -1, false + end + return nil, 0, p, false + elseif x == 4 then + return slide, y, -1, false + elseif x == 5 then + return slide, y * 16, -1, false + elseif x == 6 then + return slide, 0xF0 + math.min(y, 0xE), -1, false + elseif x == 7 then + return slide, math.min(y, 0xE) * 16 + 0xF, -1, false + end + end + return nil, 0, -1, false +end + +function Okt.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:peek(8) ~= "OKTASONG" then + return nil, Err.new(if r:size() < 8 then Err.TRUNCATED else Err.CORRUPT, "no OKTASONG signature") + end + local buf = r.buf + local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT) + local cmod = Chunks.find(list, "CMOD") + if not cmod or cmod.avail < 8 then + return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)") + end + -- channels: each Amiga channel is one channel, or a mixed pair + local paired: { number } = {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel + local pans: { number } = {} + for ch = 0, 3 do + local pan = if ch == 1 or ch == 2 then 0xC0 else 0x40 + if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then + table.insert(paired, 1) + table.insert(pans, pan) + table.insert(paired, -1) + else + table.insert(paired, 0) + end + table.insert(pans, pan) + end + local nch = #paired + local m = Tracker.newModule("okt", nch, "it") + m.linear = false + m.instrumentMode = false + m.tempo = 125 + m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true + for i = 1, nch do + m.channelPan[i] = pans[i] + end + -- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2) + local types: { number } = {} + local samp = Chunks.find(list, "SAMP") + if samp then + for i = 1, math.min(samp.avail // 32, 36) do + local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32) + local s = Tracker.newSample(h:fixed(20)) + local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be() + s.c5speed = 8287 + s.volume = math.min(vol, 64) + s.length = len - len % 2 + if ll > 2 and ls + ll <= s.length then + s.susStart, s.susEnd, s.susType = ls, ls + ll, 1 + end + types[i] = typ + m.samples[i] = s + end + end + local spee = Chunks.find(list, "SPEE") + if spee and spee.avail >= 2 then + m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255) + end + local nord = 0 + local plen = Chunks.find(list, "PLEN") + if plen and plen.avail >= 2 then + nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1) + end + local patt = Chunks.find(list, "PATT") + for i = 1, math.min(nord, if patt then patt.avail else 0) do + m.order[i] = buffer.readu8(buf, (patt :: Chunks.Chunk).offset + i - 1) + end + -- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter) + local copies: { [number]: boolean } = {} -- type B samples with a loop also need an unlooped copy (paired channels) + local npat = 0 + for _, c in list do + if c.id == "PBOD" and npat < 256 then + local pr = Bytes.reader(buf, c.offset, c.avail) + local rows = if c.avail >= 2 then math.clamp(pr:u16be(), 1, 1024) else 64 + local pat = Tracker.newPattern(rows, nch) + npat += 1 + m.patterns[npat] = pat + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, nch - 1 do + local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * nch + ch) * 5 + local pair = paired[ch + 1] ~= 0 + if note > 0 and note <= 36 then + local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up) + if pair and n >= 49 + 22 then + n = 49 + 21 -- the mixer's highest note + end + local smp = ins + 1 + local s = m.samples[smp] + if s then + if pair and s.volume < 64 then + buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels + end + local t = types[smp] + if (t == 1 and pair) or (t == 0 and not pair) then + smp += 100 -- a sample of the wrong type stops the channel + elseif t == 2 and pair and s.susType > 0 then + copies[smp] = true + smp += 36 + end + end + buffer.writeu8(d, q, n) + buffer.writeu8(d, q + 1, smp) + end + local name, param, vol, off = effect(e, p, pair) + if off then + buffer.writeu8(d, q, 255) + buffer.writeu8(d, q + 1, 0) + end + if vol >= 0 then + buffer.writeu8(d, q + 2, vol + 1) + end + local fx, fp = Load.itEffect(name, param) + if fx ~= 0 then + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + if name == "chanvol" or name == "chanvolslide" then + -- a mixed pair shares its volume: the other channel gets it too (the second one wins) + local other = ch + paired[ch + 1] + local o2 = (row * nch + other) * 5 + local ofx = buffer.readu8(d, o2 + 3) + if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then + buffer.writeu8(d, o2 + 3, fx) + buffer.writeu8(d, o2 + 4, fp) + end + end + end + end + end + end + end + -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length + local k = 0 + local bodies: { Chunks.Chunk } = {} + for _, c in list do + if c.id == "SBOD" and c.avail > 0 then + table.insert(bodies, c) + end + end + local nsmp = #m.samples + for i = 1, nsmp do + local s = m.samples[i] + if s.length > 0 then + k += 1 + local c = bodies[k] + if not c then + s.length = 0 + continue + end + local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget) + if not ok then + return nil, err + end + end + end + for i = 1, nsmp do + local s = m.samples[i] + if copies[i] then + local cp = Tracker.newSample(s.name) + cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length + m.samples[i + 36] = cp + end + end + for i = 1, (if next(copies) then 72 else nsmp) do + if m.samples[i] == nil then + m.samples[i] = Tracker.newSample() + end + end + m.meta.source = { format = "okt", channels = nch } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Okt.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Okt.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Okt +end +__FILES["music/ptm"] = function() + +-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD +-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx +-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, +-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the +-- byte stream, as PolyTracker stores them), ping-pong loops. +-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ptm = { + name = "ptm", + category = "music", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- PolyTracker's effects past MOD's 0..F +local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then + return false + end + local h = r:sub(32, 10) + local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le() + return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128 +end + +function Ptm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values +local function delta16(buf: buffer, off: number, frames: number, limit: number): (buffer, number) + local n = math.max(0, math.min(frames, (limit - off) // 2)) + local raw = buffer.create(n * 2) + local acc = 0 + for i = 0, n * 2 - 1 do + acc = (acc + buffer.readu8(buf, off + i)) % 256 + buffer.writeu8(raw, i, acc) + end + return raw, n +end + +-- a PolyTracker effect -> name?, param +local function effect(cmd: number, param: number): (string?, number) + if cmd == 0x10 then + return "globalvol", math.min(param, 0x40) * 2 + elseif cmd > 0x10 then + return EXTRA[cmd - 0x10 + 1], param + elseif cmd == 8 then + return "s3mex", 0x80 + (math.max(param // 8, 1) - 1) % 16 -- 8xx pans in 16 steps + end + return Load.modCommand(cmd, param) +end + +-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) +local function readPattern(pr: Bytes.Reader, d: buffer, nch: number) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row += 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local name, param = effect(pr:u8(), pr:u8()) + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end +end + +function Ptm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 608 then Err.TRUNCATED else Err.CORRUPT, "not a PolyTracker module") + end + local title = r:fixed(28) + r:skip(1) + local vlo, vhi = r:u8(), r:u8() + r:skip(1) + local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:seek(64) + local m = Tracker.newModule("ptm", nch, "it") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx = true, true + m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels + for i = 1, 32 do + local p = r:u8() + if i <= nch then + m.channelPan[i] = (p % 16) * 16 + 4 + end + end + for i = 1, 256 do + local o = r:u8() + if i <= nord then + m.order[i] = o + end + end + local patOff: { number } = {} + for i = 1, 128 do + patOff[i] = r:u16le() * 16 + end + if r.err then + return nil, r.err + end + -- samples + local buf = r.buf + for i = 1, nsmp do + local h = r:slice(80) + if r.err then + return nil, r.err + end + local flags = h:u8() + h:skip(12) + local vol, c4 = h:u8(), h:u16le() + h:skip(2) + local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le() + h:skip(14) + local s = Tracker.newSample(h:fixed(28)) + m.samples[i] = s + s.volume = math.min(vol, 64) + s.c5speed = math.max(1, c4 * 2) + if flags % 4 == 1 and len > 0 then + local bits = if bit32.band(flags, 0x10) ~= 0 then 16 else 8 + if le > ls then + le -= 1 + end + local frames = len + if bits == 16 then + frames, ls, le = frames // 2, ls // 2, le // 2 + end + local at = r.base + off + if at < r.limit then + local ok, err + if bits == 16 then + local raw, n = delta16(buf, at, frames, r.limit) + ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget) + else + ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget) + end + if not ok then + return nil, err + end + end + if bit32.band(flags, 4) ~= 0 and le > ls then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + s.loopType = if bit32.band(flags, 8) ~= 0 then 2 else 1 + end + end + end + for p = 1, npat do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + if patOff[p] > 0 and patOff[p] < r:size() then + readPattern(r:sub(patOff[p]), pat.data, nch) + end + end + m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ptm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ptm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ptm +end +__FILES["music/s3m"] = function() + +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism +-- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning +-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 +-- speed reference, as IT shows S3M files). +-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function S3m.sniff(r: Bytes.Reader): number + if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset: { number } = {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = if speed > 0 and speed < 255 then speed else 6 + m.tempo = if tempo >= 33 then tempo else 125 + m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + -- orders, parapointers, panning + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans: { number } = {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = if c % 16 >= 8 then 0xCC else 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + -- samples + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = if c2spd > 0 then c2spd else 8363 + if typ == 1 and len > 0 and pack == 0 then + local bits = if bit32.band(sflags, 4) ~= 0 then 16 else 8 + local nchs = if bit32.band(sflags, 2) ~= 0 then 2 else 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + -- a short file: keep what is there + local avail = math.max(0, r:size() - off) // (nchs * bits // 8) + len = math.min(len, avail) + total += len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row += 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (nb // 16) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd = pr:u8() + info = pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function S3m.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m +end +__FILES["music/sf2"] = function() + +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the +-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), +-- presets / instruments / sample headers with global zones, generator merging into playable regions. +-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). +-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local SoundFont = __include("codecs/audio/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + maxRegions: number?, -- default 10^6 + maxSamples: number?, -- default 2^28 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Sf2.sniff(r: Bytes.Reader): number + return if SoundFont.sniff(r) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?) + return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 +end +__FILES["music/stm"] = function() + +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). +-- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module +-- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the +-- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump +-- happens at the end of the pattern or at the next Cxx). +-- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Stm = { + name = "stm", + category = "music", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local IT = Load.IT +-- .ABCDEFGHIJ (K..O do nothing) +local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r: Bytes.Reader): boolean + if r:size() < 48 then + return false + end + local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31) + local npat, gv = r:peekU8(33), r:peekU8(34) + if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then + return false + end + if npat > 64 or (gv > 64 and gv ~= 0x58) then + return false + end + for i = 20, 27 do + local c = r:peekU8(i) + if c < 0x20 or c >= 0x7F then + return false + end + end + return true +end + +function Stm.sniff(r: Bytes.Reader): number + return if validHeader(r) then 0.7 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a tempo byte of files before ST 2.21 is decimal +local function tempoByte(v: number, minor: number): number + return if minor < 21 then (v // 10) * 16 + v % 10 else v +end + +function Stm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not a Scream Tracker 2 module") + end + local title = r:fixed(20) + local tracker = r:fixed(8) + r:skip(3) + local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8() + r:skip(13) + local m = Tracker.newModule("stm", 4, "s3m") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.st2Tempo = true + initTempo = tempoByte(initTempo, minor) + if initTempo == 0 then + initTempo = 0x60 + end + m.speed, m.tempo = Tracker.st2Tempo(initTempo) + if minor > 10 then + m.globalVolume = math.min(gv, 64) * 2 + end + local offsets: { number } = {} + for i = 1, 31 do + local s = Tracker.newSample(r:fixed(12)) + local zero = r:u8() + r:skip(1) + local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local vol = r:u8() + r:skip(1) + local rate = r:u16le() + r:skip(6) + if r.err then + return nil, r.err + end + if zero ~= 0 and zero ~= 46 then + return nil, Err.new(Err.CORRUPT, "bad sample header " .. i) + end + s.c5speed = if rate > 0 then rate else 8363 + s.volume = math.min(vol, 64) + if len < 2 then + len = 0 + end + if ls < len and le > ls and le ~= 0xFFFF then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + len = math.max(le, len) -- ST2 lets a loop run into the next sample's data + end + s.length = len + offsets[i] = off * 16 + m.samples[i] = s + end + for i = 1, (if minor == 0 then 64 else 128) do + local o = r:u8() + if o == 99 or o == 255 then + o = 255 + elseif o > 63 then + return nil, Err.new(Err.CORRUPT, "bad order list") + end + m.order[i] = o + end + if r.err then + return nil, r.err + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + -- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 4) + m.patterns[p + 1] = pat + local d = pat.data + local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx + for row = 0, 63 do + for ch = 0, 3 do + local q = (row * 4 + ch) * 5 + local note = r:u8() + local insVol, volCmd, info = 0, 0, 0 + if note == 0xFB then + note = 0 -- a C-0 at volume 0 (OpenMPT reads it so) + elseif note == 0xFD then + buffer.writeu8(d, q, 254) + elseif note ~= 0xFC then + insVol, volCmd, info = r:u8(), r:u8(), r:u8() + end + if note ~= 0xFC and note ~= 0xFD then + if note == 0xFE then + buffer.writeu8(d, q, 254) + elseif note < 0x60 then + buffer.writeu8(d, q, (note // 16) * 12 + note % 16 + 37) + end + local ins = insVol // 8 + buffer.writeu8(d, q + 1, if ins > 31 then 0 else ins) + local vol = insVol % 8 + (volCmd // 16) * 8 + if vol <= 64 then + buffer.writeu8(d, q + 2, vol + 1) + end + local name, param = EFFECTS[volCmd % 16], info + if name == "volslide" then + param = if param % 16 > 0 then param % 16 else param - param % 16 + elseif name == "break" then + param = ((param - param % 16) * 10 + param % 16) % 256 + if breakPos >= 0 and param == 0 then + name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx + breakPos = -1 + end + breakRow = math.min(breakRow, row) + if name == "break" then + param = Load.bcd(param) + end + elseif name == "jump" then + breakPos, breakRow = param, 63 + name = nil + elseif name == "speed" then + param = tempoByte(param, minor) + if param == 0 then + name = nil + end + elseif name ~= "tremor" and param == 0 then + name = nil -- no effect memory in ST2 + end + if name then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + if r.err then + return nil, r.err + end + if breakPos >= 0 then + Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev") + end + end + -- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read) + local buf = r.buf + for i = 1, 31 do + local s = m.samples[i] + local len = s.length + s.length = 0 + if len > 0 and s.volume > 0 and offsets[i] > 48 then + local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + end + end + m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Stm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Stm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Stm +end +__FILES["music/ult"] = function() + +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored +-- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). +-- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects +-- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect +-- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone +-- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. +-- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the +-- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ult = { + name = "ult", + category = "music", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ constants +local EFFECTS: { [number]: string } = { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo", + [9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ult.sniff(r: Bytes.Reader): number + local v = r:peekU8(14) + if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +local function translate(e: number, param: number, version: number): (string?, number) + local name = EFFECTS[e] + if e == 0 then + if param == 0 or version < 3 then + name = nil + end + elseif e == 5 then + if (param % 16 == 0xC or param // 16 == 0xC) and version >= 3 then + return "keyoff", 0 + end + elseif e == 7 then + if version < 4 then + name = nil + end + elseif e == 0xA then + if param >= 16 then + param -= param % 16 + end + elseif e == 0xB then + param = (param % 16) * 0x11 + elseif e == 0xD then + param = 10 * (param // 16) + param % 16 + elseif e == 0xE then + local x, y = param // 16, param % 16 + if x == 1 then + return "portaup", 0xF0 + y + elseif x == 2 then + return "portadown", 0xF0 + y + elseif x == 8 and version >= 4 then + return "s3mex", 0x60 + y + elseif x == 9 then + return "retrig", y + elseif x == 0xA then + return "volslide", y * 16 + 0xF + elseif x == 0xB then + return "volslide", 0xF0 + y + elseif x == 0xC or x == 0xD then + return "s3mex", param + end + return nil, param + elseif e == 0xF then + if param > 0x2F then + name = "tempo" + end + end + return name, param +end + +-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +local function combine(a: string?, pa: number, b: string?, pb: number): (string?, number, string?, number) + if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then + return if b == "vibrato" then "vibratovol" else "toneportavol", pa, nil, 0 + elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then + return if a == "vibrato" then "vibratovol" else "toneportavol", pb, nil, 0 + end + return a, pa, b, pb +end + +-- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, +-- lost global effect (name?, param) +local function readEvent(r: Bytes.Reader, version: number): (number, number, number, number, number, number, string?, number) + local rep = 1 + local b = r:u8() + if b == 0xFC then + rep = r:u8() + b = r:u8() + end + local note = if b > 0 and b < 97 then b + 24 else 0 + local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8() + local c1, q1 = translate(cmd % 16, p1, version) + local c2, q2 = translate(cmd // 16, p2, version) + if c1 == "offset" and c2 == "offset" then + local off = (p2 * 256 + p1) // 64 + return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0 + elseif c1 == "offset" then + q1 = math.min(p1 * 4, 255) + elseif c2 == "offset" then + q2 = math.min(p2 * 4, 255) + elseif c1 ~= nil and c1 == c2 then + c2 = nil + end + if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces) + c1, q1, c2, q2 = c2, q2, c1, q1 + end + c2, q2, c1, q1 = combine(c2, q2, c1, q1) + if c1 == "keyoff" or c2 == "keyoff" then + -- key off (5xC): a note-off when the cell has no note + if note == 0 then + note = 255 + end + if c1 == "keyoff" then + c1 = nil + else + c2 = nil + end + end + local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2) + local fx, fp = Load.itEffect(name, param) + return rep, note, ins, vol, fx, fp, lost, lostParam +end + +function Ult.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Ult.sniff(r) == 0 then + return nil, Err.new(if r:size() < 48 then Err.TRUNCATED else Err.CORRUPT, "not an UltraTracker module") + end + r:skip(14) + local version = r:u8() - 0x30 + local title = (string.gsub(r:fixed(32), " +$", "")) + local lines = r:u8() + local message = r:string(lines * 32) + local nsmp = r:u8() + if r.err then + return nil, r.err + end + local samples, sizes = {}, {} + for i = 1, nsmp do + local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", ""))) + r:skip(12) + local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local vol, flags = r:u8(), r:u8() + local speed, finetune = 8363, 0 + if version >= 4 then + speed, finetune = r:u16le(), r:i16le() + else + finetune = r:i16le() + end + if r.err then + return nil, r.err + end + local bits = if bit32.band(flags, 4) ~= 0 then 16 else 8 + s.bits = bits + sizes[i] = 0 + if se > ss then + s.length = se - ss + sizes[i] = s.length * bits // 8 + s.volume = vol / 4 + s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768))) + if bit32.band(flags, 8) ~= 0 then + if bits == 16 then + ls, le = ls // 2, le // 2 + end + s.susStart, s.susEnd = ls, le + s.susType = if bit32.band(flags, 16) ~= 0 then 2 else 1 + end + end + samples[i] = s + end + local order = {} + for i = 1, 256 do + order[i] = r:u8() + end + local nch, npat = r:u8() + 1, r:u8() + 1 + if r.err then + return nil, r.err + end + if nch > 32 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " channels") + end + local m = Tracker.newModule("ult", nch, "it") + m.title = title + m.meta.message = message + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true + m.samples = samples + for i = 1, 256 do + m.order[i] = order[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + for i = 1, nch do + m.channelPan[i] = if version >= 3 then (r:u8() % 16) * 16 + 8 elseif i % 2 == 0 then 192 else 64 + end + for p = 1, npat do + m.patterns[p] = Tracker.newPattern(64, nch) + end + -- events, channel by channel, pattern by pattern + local speed0 = false + for ch = 0, nch - 1 do + for p = 0, npat - 1 do + if r:remaining() < 5 then + break + end + local d = m.patterns[p + 1].data + local row = 0 + while row < 64 do + local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version) + if r.err then + break + end + if lost and Load.isGlobal(lost, lostParam) then + local lf, lp = Load.itEffect(lost, lostParam) + Load.writeEffect(m, p, row, lf, lp, "next") + end + rep = math.min(rep, 64 - row) + if rep == 0 then + break + end + if fx == Load.IT.speed and param == 0 then + speed0 = true + end + for _ = 1, rep do + local q = (row * nch + ch) * 5 + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 2, vol) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + row += 1 + end + end + end + end + r.err = nil + if speed0 then + -- speed 0 resets the song speed and tempo (UltraTracker) + for p, pat in m.patterns do + for row = 0, 63 do + for ch = 0, nch - 1 do + local q = (row * nch + ch) * 5 + if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then + buffer.writeu8(pat.data, q + 4, 6) + Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next") + end + end + end + end + end + -- sample data: signed 8 / 16-bit + local pos = r.pos + for i = 1, nsmp do + local s = samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos += sizes[i] + end + end + m.meta.source = { format = "ult", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ult.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Ult.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ult +end +__FILES["music/umx"] = function() + +-- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package +-- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): +-- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each +-- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first +-- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and +-- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is +-- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. +-- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Umx = { + name = "umx", + category = "music", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, +} + +type DecodeOptions = { + decodeModule: ((buf: buffer, format: string?) -> (any, Err.Err?))?, -- loads the inner module (the api passes it) + index: number?, -- which music export to load (1-based, default 1) +} + +type Entry = { name: string, data: buffer, format: string? } + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\xC1\x83\x2A\x9E" + +-- ------------------------------------------------------------------------------------------------ sniff +type Header = { version: number, nameCount: number, nameOffset: number, exportCount: number, exportOffset: number, importCount: number, importOffset: number } + +local function header(r: Bytes.Reader): Header? + if r:size() < 36 or r:peek(4) ~= MAGIC then + return nil + end + local h = r:sub(4, 32) + local version = h:u16le() + h:skip(6) + local hd: Header = { + version = version, + nameCount = h:u32le(), + nameOffset = h:u32le(), + exportCount = h:u32le(), + exportOffset = h:u32le(), + importCount = h:u32le(), + importOffset = h:u32le(), + } + if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then + return nil + end + if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then + return nil + end + return hd +end + +-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set +local function index(r: Bytes.Reader): number + local b = r:u8() + local neg = b >= 0x80 + local v = b % 64 + if bit32.band(b, 0x40) ~= 0 then + local shift = 6 + repeat + b = r:u8() + v += (b % 128) * 2 ^ shift + shift += 7 + until b < 0x80 or shift >= 32 + end + return if neg then -v else v +end + +-- the name table (lower case) +local function names(r: Bytes.Reader, h: Header): { string } + local list = {} + local nr = r:sub(h.nameOffset) + for _ = 1, math.min(h.nameCount, 65536) do + if nr:remaining() < 5 then + break + end + if h.version >= 64 then + index(nr) + end + table.insert(list, string.lower(nr:cstring(1024))) + nr:skip(4) + end + return list +end + +function Umx.sniff(r: Bytes.Reader): number + local h = header(r) + if not h then + return 0 + end + return if table.find(names(r, h), "music") then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: +-- a guess from the inner module's signature: "it", "s3m", "xm", "mod") +function Umx.extract(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local h = header(r) + if not h then + return nil, Err.new(if r:size() < 36 then Err.TRUNCATED else Err.CORRUPT, "not an Unreal package") + end + local nm = names(r, h) + -- imports: the class names objects refer to + local classes = {} + local ir = r:sub(h.importOffset) + for _ = 1, math.min(h.importCount, 65536) do + if ir:remaining() < 4 then + break + end + index(ir) + index(ir) + if h.version >= 60 then + ir:skip(4) + else + index(ir) + end + local obj = index(ir) + if obj >= 0 and obj < #nm then + table.insert(classes, obj) + end + end + local out: { Entry } = {} + local er = r:sub(h.exportOffset) + for _ = 1, math.min(h.exportCount, 65536) do + if er:remaining() < 8 then + break + end + local cls = -index(er) - 1 -- ~index: the import the class is + index(er) + if h.version >= 60 then + er:skip(4) + end + local objName = index(er) + er:skip(4) + local size, offset = index(er), index(er) + if er.err then + break + end + if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then + local c = r:sub(offset, size) + if h.version < 40 then + c:skip(8) + end + if h.version < 60 then + c:skip(16) + end + index(c) -- the property list's "none" + if h.version >= 120 then + index(c) + c:skip(8) + elseif h.version >= 100 then + c:skip(4) + index(c) + c:skip(4) + elseif h.version >= 62 then + index(c) + c:skip(4) + else + index(c) + end + local len = index(c) + if not c.err and len > 0 and len <= c:remaining() then + local data = c:bytes(len) + local sig = Bytes.reader(data) + local fmt = if sig:peek(4) == "IMPM" then "it" elseif sig:peek(4, 44) == "SCRM" then "s3m" elseif sig:peek(17) == "Extended Module: " then "xm" elseif buffer.len(data) >= 1084 then "mod" else nil + table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt }) + end + end + end + return out, nil +end + +function Umx.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local list, err = Umx.extract(r) + if not list then + return nil, err + end + local i = opts and opts.index or 1 + local e = list[i] + if not e then + return nil, Err.new(Err.CORRUPT, "no music export" .. (if i > 1 then " " .. i else "")) + end + local hook = opts and opts.decodeModule + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)") + end + local m, merr = hook(e.data, nil) + if not m then + return nil, merr + end + if type(m) ~= "table" or m.kind ~= "music" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module") + end + local h = header(r) :: Header + m.meta = if type(m.meta) == "table" then m.meta else {} + m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Umx.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Umx.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Umx +end +__FILES["music/xm"] = function() + +-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and +-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit +-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga +-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files +-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). +-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's +-- stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse more sample data in total (f32 bytes, default 2^28) +} +type EncodeOptions = { + tracker: string?, -- the tracker name field (default: the source file's, else "rosetta") +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r: Bytes.Reader): number + return if r:peek(17) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r: Bytes.Reader): ({ number }, { number }) + local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs: { number }, ys: { number }, n: number, typ: number, sus: number, ls: number, le: number, pan: boolean): any + local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = if pan then math.clamp(ys[i], 0, 64) - 32 else math.clamp(ys[i], 0, 64) + end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + -- the raw fields, for a faithful re-save + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = if speed > 0 and speed < 256 then speed else 6 + m.tempo = if bpm >= 32 and bpm <= 999 then bpm else 125 + m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + -- patterns + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note = b + ins = pr:u8() + vol = pr:u8() + fx = pr:u8() + param = pr:u8() + end + if pr.err then + break -- a short pattern: the rest stays empty + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + -- instruments and their samples + local total = 0 + for i = 1, nins do + local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + -- a file cut inside the instruments: keep what was read + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) + continue + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = if bit32.band(h.typ, 16) ~= 0 then 16 else 8 + local bps = bits // 8 + s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = h.len // bps + if h.res == 0xAD and bits == 8 then + -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps + -- the samples whose nibbles are present + frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) + total += frames * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + s.data = buffer.create(frames * 4) + if frames > 0 then + Adpcm.modplug(r.buf, r.pos, frames, s.data, 0) + end + r:skip(math.min(16 + (h.len + 1) // 2, r:remaining())) + else + local avail = r:remaining() // bps + local got = math.min(frames, avail) + total += got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = if data then got else 0 + end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = h.ls // bps + s.loopEnd = (h.ls + h.ll) // bps + s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = if n <= 96 and k < ns then base + k + 1 else 0 + end + ins.keymap = keymap + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w: Bytes.Writer, s: string?, n: number) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } +local function instrumentsOf(m: any): ({ any }?, string?) + local out = {} + if m.format == "mod" then + for i, s in m.samples do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = if s.length > 0 then { s } else {}, keymap = km, ins = nil } + end + return out + end + for i, ins in m.instruments do + local list: { number } = {} + if type(ins.samples) == "table" then + for _, g in ins.samples do + table.insert(list, g) + end + end + local index: { [number]: number } = {} + for k, g in list do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in list do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w: Bytes.Writer, e: any, pan: boolean) + local n = if e then math.min(#e.ticks, 12) else 0 + for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (if pan then 32 else 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e: any): (number, number, number, number, number) + if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (if e.enabled then 1 else 0) + (if e.sustain then 2 else 0) + (if e.loop then 4 else 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type -- keep unknown bits + end + local function idx(v: number): number + return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +-- encode(module, opts) -> XM bytes ("xm" or "mod" modules) +function Xm.encode(m: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order: { number } = {} + for _, o in m.order do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "rosetta", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le(if m.restart < #order then m.restart else 0) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(if m.linear then 1 else 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in m.patterns do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (if note > 0 then 1 else 0) + (if ins > 0 then 2 else 0) + (if vol > 0 then 4 else 0) + (if fx > 0 then 8 else 0) + (if param > 0 then 16 else 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + -- instruments + for _, it in insts do + local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) + continue + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in smps do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = if s.bits == 16 then 16 else 8 + local bps = bits // 8 + datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (if bits == 16 then 16 else 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ += s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in datas do + w:bytes(dd) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Xm.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm +end +__FILES["music/xmi"] = function() + +-- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, +-- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description +-- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, +-- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's +-- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second +-- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the +-- first tempo event's value, unused). Renders through codecs/audio/MidiRender. +-- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Xmi = { + name = "xmi", + category = "music", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + track: number?, -- the song (1-based), default 1 + maxEvents: number?, -- default 2^24 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xmi.sniff(r: Bytes.Reader): number + local id, kind = r:peek(4), r:peek(4, 8) + if id == "FORM" and (kind == "XDIR" or kind == "XMID") then + return 1 + end + return if id == "CAT " and kind == "XMID" then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +-- a MIDI variable-length number at p -> value, next p (nil past e) +local function vlq(b: buffer, p: number, e: number): (number?, number) + local v = 0 + for _ = 1, 4 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p += 1 + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + return nil, p +end + +local function bytes(b: buffer, p: number, n: number): { number } + local t: { number } = table.create(n) :: { number } + for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +-- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message +local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?) + local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {} + local tick, tempo = 0, nil + while p < e do + local st = readu8(b, p) + p += 1 + if st < 0x80 then + tick += st + elseif st == 0xFF then + if p >= e then + return nil, "truncated meta event" + end + local kind = readu8(b, p) + local n, q = vlq(b, p + 1, e) + if not n or q + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + elseif kind == 0x51 and n >= 3 then + tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + else + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) }) + end + p = q + n + elseif st == 0xF0 or st == 0xF7 then + local n, q = vlq(b, p, e) + if not n or q + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) }) + p = q + n + elseif st < 0xF0 then + local hi, ch = st // 16, st % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local d = bytes(b, p, n) + p += n + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d }) + if hi == 9 then + local dur, q = vlq(b, p, e) + if not dur then + return nil, "truncated note duration" + end + p = q + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } }) + end + else + return nil, string.format("unexpected status byte 0x%02X", st) + end + if #list + #offs > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events" + end + end + -- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging) + for _, o in offs do + if o.tick > tick then + o.tick = tick + o.ev.tick = tick + end + end + return Render.merge(list, offs), tick, tempo +end + +-- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree +local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } } + local out = {} + local function form(c: Chunks.Chunk) + local song = {} + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + song[s.id] = song[s.id] or s + end + if song.EVNT then + table.insert(out, song) + end + end + for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do + local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else "" + if c.id == "FORM" and kind == "XMID" then + form(c) + elseif c.id == "CAT " and kind == "XMID" then + for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do + if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then + form(s) + end + end + end + end + return out +end + +function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) + local o: DecodeOptions = opts or {} + if Xmi.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an XMIDI file") + end + local list = songs(r.buf, r.base, r.limit) + local index = o.track or 1 + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk") + elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list)) + end + local song = list[index] + local ev = song.EVNT + local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24) + if not evs then + return nil, Err.from(endTick :: string, ev.offset) + end + local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) }) + table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local timbres = {} + local tb = song.TIMB + if tb and tb.avail >= 2 then + for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do + table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) }) + end + end + local rb = song.RBRN + local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0 + local midi = Types.Midi.new(60) + midi.format = 0 + midi.tracks = { { events = evs } } + Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches }) + midi.meta.truncated = ev.truncated + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?) + local midi, err = Xmi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Xmi +end +__FILES["ops/AudioOps"] = function() + +-- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an +-- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), +-- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. +-- +-- local AudioOps = require("@rosetta/ops/AudioOps") -- F.ops.audio in the api +-- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder +-- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) +-- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) +-- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) +-- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's +-- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) +-- local both = AudioOps.concat({ a, b }) +-- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape +-- +-- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders +-- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the +-- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot +-- exceed full scale; upmixes copy mono to FL / FR and stereo to FL / FR (other channels silent). Tags and meta are +-- copied from the (first) input. +local Err = __include("core/Err") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") + +local AudioOps = {} + +local readf32, writef32 = buffer.readf32, buffer.writef32 +local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt + +-- ------------------------------------------------------------------------------------------------ validation +local function isAudio(a: any): boolean + return type(a) == "table" + and a.kind == "audio" + and type(a.samples) == "buffer" + and type(a.frames) == "number" + and type(a.channels) == "number" + and a.channels >= 1 + and type(a.sampleRate) == "number" + and a.sampleRate > 0 + and buffer.len(a.samples) >= a.frames * a.channels * 4 +end + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +-- a new Audio with a's rate / tags / meta and the given layout +local function like(a: Types.Audio, channels: number, frames: number, rate: number?): Types.Audio + local out = Types.Audio.new(rate or a.sampleRate, channels, frames) + out.tags = table.clone(a.tags or {}) + out.meta = table.clone(a.meta or {}) + return out +end + +-- ------------------------------------------------------------------------------------------------ conversion +-- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT +-- past it; default 2^31) +function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, Err.Err?) + if isAudio(v) then + return v, nil + end + local src, err = Pcm.source(v) + if not src then + return nil, err + end + return Pcm.collect(src, opts and opts.maxFrames) +end +AudioOps.fromDecoder = AudioOps.toAudio + +-- ------------------------------------------------------------------------------------------------ levels +-- gain(a, factor) -> Audio with every sample times factor +function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("gain: expected an Audio") + end + if type(factor) ~= "number" or factor ~= factor then + return bad("gain: factor must be a number") + end + local n = a.frames * a.channels + local out = like(a, a.channels, a.frames) + local s, d = a.samples, out.samples + for i = 0, n - 1 do + writef32(d, i * 4, readf32(s, i * 4) * factor) + end + return out, nil +end + +-- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) +function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?) + if type(db) ~= "number" or db ~= db then + return bad("gainDb: dB must be a number") + end + return AudioOps.gain(a, 10 ^ (db / 20)) +end + +-- peak(a) -> the largest |sample|, { per channel } +function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "peak: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = abs(readf32(s, p + (c - 1) * 4)) + if v > per[c] then + per[c] = v + end + end + end + local m = 0 + for c = 1, ch do + m = max(m, per[c]) + end + return m, per +end + +-- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) +function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "rms: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = readf32(s, p + (c - 1) * 4) + per[c] += v * v + end + end + local total = 0 + local n = max(1, a.frames) + for c = 1, ch do + total += per[c] + per[c] = sqrt(per[c] / n) + end + return sqrt(total / (n * ch)), per +end + +-- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) +function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err.Err?) + local p, perr = AudioOps.peak(a) + if not p then + return nil, perr :: Err.Err + end + local t = target or 1 + if type(t) ~= "number" or t ~= t or t < 0 then + return bad("normalize: target must be a number >= 0") + end + return AudioOps.gain(a, if p > 0 then t / p else 1) +end + +-- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps +function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("fade: expected an Audio") + end + local fi = floor(max(0, (inSec or 0) * a.sampleRate) + 0.5) + local fo = floor(max(0, (outSec or 0) * a.sampleRate) + 0.5) + if fi ~= fi or fo ~= fo then + return bad("fade: bad duration") + end + local out = like(a, a.channels, a.frames) + buffer.copy(out.samples, 0, a.samples, 0, a.frames * a.channels * 4) + local ch, d, n = a.channels, out.samples, a.frames + for f = 0, min(fi, n) - 1 do + local g = f / fi + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + for k = 0, min(fo, n) - 1 do + local f = n - 1 - k + local g = k / fo + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ channels +-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) +local LAYOUT: { { string } } = { + { "C" }, + { "FL", "FR" }, + { "FL", "FR", "C" }, + { "FL", "FR", "BL", "BR" }, + { "FL", "FR", "C", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BC", "SL", "SR" }, + { "FL", "FR", "C", "LFE", "BL", "BR", "SL", "SR" }, +} +local H = sqrt(0.5) -- -3 dB +-- speaker -> its contribution to (left, right) in a stereo downmix +local TO_STEREO: { [string]: { number } } = { + FL = { 1, 0 }, FR = { 0, 1 }, C = { H, H }, LFE = { 0, 0 }, BL = { H, 0 }, BR = { 0, H }, SL = { H, 0 }, + SR = { 0, H }, BC = { 0.5, 0.5 }, +} + +-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +local function matrix(from: number, to: number): { { number } } + local m: { { number } } = table.create(to) :: any + for o = 1, to do + m[o] = table.create(from, 0) + end + if from == to then + for c = 1, to do + m[c][c] = 1 + end + return m + end + local inL, outL = LAYOUT[from], LAYOUT[to] + if to < from and inL and outL and to <= 2 then + -- down to stereo (then mono = the average of the two) + local l: { number }, r: { number } = table.create(from, 0), table.create(from, 0) + local sl, sr = 0, 0 + for i, sp in inL do + local w = TO_STEREO[sp] or { 0, 0 } + l[i], r[i] = w[1], w[2] + sl += w[1] + sr += w[2] + end + local norm = 1 / max(sl, sr, 1) + for i = 1, from do + if to == 2 then + m[1][i], m[2][i] = l[i] * norm, r[i] * norm + else + m[1][i] = (l[i] + r[i]) * norm * 0.5 + end + end + return m + end + if from == 1 then + -- mono up: FL and FR (or the only channel) + if outL then + local placed = false + for o, sp in outL do + if sp == "FL" or sp == "FR" then + m[o][1] = 1 + placed = true + end + end + if not placed then + m[1][1] = 1 + end + else + m[1][1] = 1 + end + return m + end + if inL and outL then + -- same-named speakers carry over; down: missing speakers fold into the stereo pair at their weights + local outIdx: { [string]: number } = {} + for o, sp in outL do + outIdx[sp] = o + end + for i, sp in inL do + local o = outIdx[sp] + if o then + m[o][i] = 1 + elseif to < from and outIdx.FL ~= nil and outIdx.FR ~= nil then + local w = TO_STEREO[sp] or { 0, 0 } + local fl, fr = outIdx.FL :: number, outIdx.FR :: number + m[fl][i] += w[1] + m[fr][i] += w[2] + end + end + if to < from then + for o = 1, to do + local s = 0 + for i = 1, from do + s += m[o][i] + end + if s > 1 then + for i = 1, from do + m[o][i] /= s + end + end + end + end + return m + end + -- unknown layouts: channel i -> i, extra outputs silent, extra inputs dropped + for c = 1, min(from, to) do + m[c][c] = 1 + end + return m +end +AudioOps.matrix = matrix + +-- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) +function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("remix: expected an Audio") + end + if type(channels) ~= "number" or channels < 1 or channels > 256 or channels % 1 ~= 0 then + return bad("remix: channels must be 1 .. 256") + end + local from = a.channels + local mm = m or matrix(from, channels) + if type(mm) ~= "table" or #mm ~= channels then + return bad("remix: the matrix needs one row per output channel") + end + for o = 1, channels do + if type(mm[o]) ~= "table" then + return bad("remix: matrix row " .. o .. " is not a table") + end + end + local out = like(a, channels, a.frames) + local s, d = a.samples, out.samples + local x = table.create(from, 0) + for f = 0, a.frames - 1 do + local p = f * from * 4 + for i = 1, from do + x[i] = readf32(s, p + (i - 1) * 4) + end + local q = f * channels * 4 + for o = 1, channels do + local row = mm[o] + local v = 0 + for i = 1, from do + local w = row[i] + if w and w ~= 0 then + v += w * x[i] + end + end + writef32(d, q + (o - 1) * 4, v) + end + end + return out, nil +end + +-- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) +function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("downmix: expected an Audio") + end + local n = channels or min(2, a.channels) + if n > a.channels then + return bad("downmix: more output channels than input") + end + return AudioOps.remix(a, n) +end + +-- upmix(a, channels) -> Audio with more channels +function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("upmix: expected an Audio") + end + if type(channels) ~= "number" or channels < a.channels then + return bad("upmix: fewer output channels than input") + end + return AudioOps.remix(a, channels) +end + +-- ------------------------------------------------------------------------------------------------ time +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") +function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("resample: expected an Audio") + end + local samples, frames = Resample.buffer(a.samples, a.frames, a.channels, a.sampleRate, rate, opts) + if not samples then + return bad("resample: " .. tostring(frames)) + end + local out = like(a, a.channels, 0, rate) + out.samples = samples + out.frames = frames :: number + return out, nil +end + +-- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) +function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("trim: expected an Audio") + end + if type(start) ~= "number" or start ~= start or (stop ~= nil and (type(stop) ~= "number" or stop ~= stop)) then + return bad("trim: start / stop must be numbers (seconds)") + end + local f0 = math.clamp(floor(start * a.sampleRate + 0.5), 0, a.frames) + local f1 = if stop then math.clamp(floor(stop * a.sampleRate + 0.5), f0, a.frames) else a.frames + local ch = a.channels + local out = like(a, ch, f1 - f0) + buffer.copy(out.samples, 0, a.samples, f0 * ch * 4, (f1 - f0) * ch * 4) + return out, nil +end + +-- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err +local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, Err.Err?) + if type(list) ~= "table" or #list == 0 then + return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") + end + local first = list[1] + if not isAudio(first) then + return nil, Err.new(Err.ARG, what .. ": item 1 is not an Audio") + end + local out = { first } + for i = 2, #list do + local a = list[i] + if not isAudio(a) then + return nil, Err.new(Err.ARG, what .. ": item " .. i .. " is not an Audio") + end + if a.sampleRate ~= first.sampleRate then + local r, err = AudioOps.resample(a, first.sampleRate) + if not r then + return nil, err + end + a = r + end + if a.channels ~= first.channels then + local r, err = AudioOps.remix(a, first.channels) + if not r then + return nil, err + end + a = r + end + out[i] = a + end + return out, nil +end + +-- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) +function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?) + local items, err = conform(list, "concat") + if not items then + return nil, err + end + local first = items[1] + local ch = first.channels + local total = 0 + for _, a in items do + total += a.frames + end + local out = like(first, ch, total) + local at = 0 + for _, a in items do + buffer.copy(out.samples, at * ch * 4, a.samples, 0, a.frames * ch * 4) + at += a.frames + end + return out, nil +end + +-- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at +-- the first one's rate and channel count +function AudioOps.mix(list: { Types.Audio }, weights: { number }?): (Types.Audio?, Err.Err?) + local items, err = conform(list, "mix") + if not items then + return nil, err + end + if weights ~= nil and type(weights) ~= "table" then + return bad("mix: weights must be a list of numbers") + end + local first = items[1] + local ch = first.channels + local frames = 0 + for _, a in items do + frames = max(frames, a.frames) + end + local out = like(first, ch, frames) + local d = out.samples + for i, a in items do + local w = if weights then weights[i] or 1 else 1 + if type(w) ~= "number" then + return bad("mix: weight " .. i .. " is not a number") + end + local s = a.samples + for k = 0, a.frames * ch - 1 do + writef32(d, k * 4, readf32(d, k * 4) + readf32(s, k * 4) * w) + end + end + return out, nil +end + +return AudioOps +end +__FILES["ops/ImageOps"] = function() + +-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion, +-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as +-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and +-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources. +-- +-- local Ops = require("@rosetta/ops/ImageOps") +-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws) +-- local grey = Ops.convert(img, "gray8") +-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over" +-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation +-- +-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as +-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's +-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and +-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with +-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8. +local Err = __include("core/Err") +local Types = __include("Types") +local K = __include("ops/ImageOps/Kernels") + +local ImageOps = {} + +local MAX_PIXELS = 2 ^ 26 + +type Image = Types.Image + +-- ------------------------------------------------------------------------------------------------ validation +local function arg(msg: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, msg) +end + +local function isInt(v: any): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31 +end + +local function bytesOf(fmt: string, w: number, h: number): number? + if fmt == "yuv420p" then + return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + end + local bpp = Types.BPP[fmt] + return if bpp then w * h * bpp else nil +end + +-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough) +local function check(img: any): (boolean?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return arg("expected an Image") + end + if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then + return arg("bad image size") + end + local need = bytesOf(img.format, img.width, img.height) + if not need then + return arg("unknown pixel format " .. tostring(img.format)) + end + if buffer.len(img.pixels) < need then + return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) + end + return true, nil +end +ImageOps.check = check + +local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?) + local max: number = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS + if w * h > max then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) + end + return true, nil +end + +-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames +local function like(img: Image, w: number, h: number, fmt: string?): Image + local out = Types.Image.new(w, h, (fmt or img.format) :: any) + for k, v in img.meta do + out.meta[k] = v + end + out.loops = img.loops + return out +end + +-- ------------------------------------------------------------------------------------------------ basics +-- new(w, h, format?) -> a zero-filled Image | nil, Err +function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?) + local fmt = format or "rgba8" + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("bad image size") + end + if not bytesOf(fmt, 1, 1) then + return arg("unknown pixel format " .. tostring(fmt)) + end + local ok, e = limit(w, h, nil) + if not ok then + return nil, e + end + return Types.Image.new(w, h, fmt :: any), nil +end + +-- copy(img) -> a deep copy of the pixels (frames are shared) +function ImageOps.copy(img: Image): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + local out = like(img, img.width, img.height) + buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels)) + out.frames = img.frames + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ convert +-- convert(img, format) -> a new Image in format (a copy when it is already) +function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not bytesOf(format, 1, 1) then + return arg("unknown pixel format " .. tostring(format)) + end + local w, h = img.width, img.height + if img.format == format then + return ImageOps.copy(img) + end + local src = img + if img.format == "yuv420p" then + local rgba = like(img, w, h, "rgba8") + K.yuvToRgba(img.pixels, w, h, rgba.pixels) + if format == "rgba8" then + return rgba, nil + end + src = rgba + end + local out = like(img, w, h, format) + if format == "yuv420p" then + local rgba = src + if src.format ~= "rgba8" then + rgba = like(img, w, h, "rgba8") + K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h) + end + K.rgbaToYuv(rgba.pixels, w, h, out.pixels) + return out, nil + end + K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) + return out, nil +end + +-- ops on yuv420p run on rgba8 and convert back +local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?) + if img.format ~= "yuv420p" then + return f(img) + end + local rgba = ImageOps.convert(img, "rgba8") :: Image + local res, e = f(rgba) + if not res then + return nil, e + end + return ImageOps.convert(res, "yuv420p") +end + +-- ------------------------------------------------------------------------------------------------ geometry +local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } + +-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) +function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then + return arg("crop: integer x, y, w, h") + end + local x0, y0 = math.max(0, x), math.max(0, y) + local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h) + if x1 <= x0 or y1 <= y0 then + return arg("crop: the rectangle is outside the image or empty") + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local bpp = Types.BPP[im.format] :: number + local out = like(im, x1 - x0, y1 - y0) + K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp) + return out, nil + end) +end + +-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom) +function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if axis ~= "h" and axis ~= "v" then + return arg("flip: axis must be \"h\" or \"v\"") + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local out = like(im, im.width, im.height) + K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h") + return out, nil + end) +end + +-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise) +function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(turns) then + return arg("rotate90: integer turns") + end + local t = turns % 4 + if t == 0 then + return ImageOps.copy(img) + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local swap = t ~= 2 + local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height) + K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t) + return out, nil + end) +end + +type ResizeFilter = "nearest" | "bilinear" | "lanczos" + +-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels) +function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("resize: bad target size") + end + local f = filter or "bilinear" + if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then + return arg("resize: filter must be nearest, bilinear or lanczos") + end + local lok, le = limit(w, h, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local fmt = im.format + local bpp = Types.BPP[fmt] :: number + local out = like(im, w, h) + if f == "nearest" then + K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h) + return out, nil + end + local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] + local src, sw, sh = im.pixels, im.width, im.height + local alpha = ALPHA_CH[fmt] + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, sw * sh, alpha, kind, false) + end + if w ~= sw then + local tmp = buffer.create(w * sh * bpp) + K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true) + src, sw = tmp, w + end + if h ~= sh then + K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false) + elseif src == im.pixels or (w == im.width and alpha) then + buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp) + return out, nil + else + out.pixels = src + end + if alpha then + K.premultiply(out.pixels, w * h, alpha, kind, true) + end + return out, nil + end) +end + +-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's +-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered +-- pixels are zero (transparent). opts.maxPixels. +function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then + return arg("rotate: degrees must be a finite number") + end + local expand = not (opts and opts.expand == false) + if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then + return ImageOps.rotate90(img, (degrees // 90) % 4) + end + local w, h = img.width, img.height + local ang = -math.rad(degrees) + local function r15(v: number): number + return math.floor(v * 1e15 + 0.5) / 1e15 + end + local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 } + local function tr(x: number, y: number): (number, number) + return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6] + end + local cx, cy = w / 2, h / 2 + m[3], m[6] = tr(-cx, -cy) + m[3] += cx + m[6] += cy + local nw, nh = w, h + if expand then + local xs, ys = {}, {} + for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do + local x, y = tr(p[1], p[2]) + table.insert(xs, x) + table.insert(ys, y) + end + nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4])) + nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4])) + m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2) + end + local lok, le = limit(nw, nh, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im: Image): (Image?, Err.Err?) + local out = like(im, nw, nh) + local kind = K.KIND[im.format] + local alpha = ALPHA_CH[im.format] + local src = im.pixels + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, w * h, alpha, kind, false) + end + K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m) + if alpha then + K.premultiply(out.pixels, nw * nh, alpha, kind, true) + end + return out, nil + end) +end + +-- ------------------------------------------------------------------------------------------------ compositing +local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true } + +type BlitOptions = { blend: ("over" | "source")?, opacity: number? } + +-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's +-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite +-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only). +function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?) + local ok, e = check(dst) + if not ok then + return nil, e + end + local ok2, e2 = check(src) + if not ok2 then + return nil, e2 + end + if not isInt(x) or not isInt(y) then + return arg("blit: integer x, y") + end + local blend = (opts and opts.blend) or "over" + if blend ~= "over" and blend ~= "source" then + return arg("blit: blend must be \"over\" or \"source\"") + end + local opacity = (opts and opts.opacity) or 1 + if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then + return arg("blit: opacity must be 0..1") + end + -- clip + local sx, sy = math.max(0, -x), math.max(0, -y) + local dx, dy = math.max(0, x), math.max(0, y) + local w = math.min(src.width - sx, dst.width - dx) + local h = math.min(src.height - sy, dst.height - dy) + if w <= 0 or h <= 0 then + return dst, nil + end + if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then + -- work on an rgba copy of the region, then write it back in dst's format + local region = ImageOps.crop(dst, dx, dy, w, h) :: Image + local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image + ImageOps.blit(work, src, x - dx, y - dy, opts) + if dst.format == "yuv420p" then + local full = ImageOps.convert(dst, "rgba8") :: Image + ImageOps.blit(full, work, dx, dy, { blend = "source" }) + local back = ImageOps.convert(full, "yuv420p") :: Image + buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels)) + else + local back = ImageOps.convert(work, dst.format) :: Image + K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number) + end + return dst, nil + end + local s = src + if src.format ~= dst.format then + s = ImageOps.convert(src, dst.format) :: Image + end + if blend == "source" then + K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number) + elseif dst.format == "rgba8" then + K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5)) + else + K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format]) + end + return dst, nil +end + +-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it +function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?) + local out, e = ImageOps.copy(dst) + if not out then + return nil, e + end + out.frames = nil + return ImageOps.blit(out, src, x or 0, y or 0, opts) +end + +local function premul(img: Image, un: boolean): (Image?, Err.Err?) + local out, e = ImageOps.copy(img) + if not out then + return nil, e + end + out.frames = nil + local ch = ALPHA_CH[img.format] + if ch then + K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) + end + return out, nil +end + +-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) +function ImageOps.premultiply(img: Image): (Image?, Err.Err?) + return premul(img, false) +end +function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?) + return premul(img, true) +end + +-- ------------------------------------------------------------------------------------------------ pixels +local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } + +-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; +-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. +function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("getPixel: coordinates out of range") + end + local b, f, i = img.pixels, img.format, y * img.width + x + local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32 + if f == "rgba8" then + return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3) + elseif f == "rgba16" then + return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6) + elseif f == "rgbaf32" then + return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12) + elseif f == "rgb8" then + return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255 + elseif f == "gray8" then + local v = ru8(b, i) + return v, v, v, 255 + elseif f == "gray16" then + local v = ru16(b, i * 2) + return v, v, v, 65535 + elseif f == "graya8" then + local v = ru8(b, i * 2) + return v, v, v, ru8(b, i * 2 + 1) + elseif f == "alpha8" then + return 255, 255, 255, ru8(b, i) + end + local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image + local rgba = ImageOps.convert(one, "rgba8") :: Image + local j = ((y % 2) * rgba.width + (x % 2)) * 4 + if j + 4 > buffer.len(rgba.pixels) then + j = 0 + end + return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 +end + +-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and +-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p. +function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("setPixel: coordinates out of range") + end + if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then + return arg("setPixel: numeric channels") + end + local f = img.format + if f == "yuv420p" then + return arg("setPixel: not supported on yuv420p (convert to rgba8 first)") + end + local max = MAXV[f] + local al = if a == nil then max else a + local function q(v: number): number + if max == 1 then + return v + end + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), 0, max) + end + local px, i = img.pixels, y * img.width + x + local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32 + local function grey(): number + if max == 1 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536 + end + if f == "rgba8" then + wu8(px, i * 4, q(r)) + wu8(px, i * 4 + 1, q(g)) + wu8(px, i * 4 + 2, q(b)) + wu8(px, i * 4 + 3, q(al)) + elseif f == "rgba16" then + wu16(px, i * 8, q(r)) + wu16(px, i * 8 + 2, q(g)) + wu16(px, i * 8 + 4, q(b)) + wu16(px, i * 8 + 6, q(al)) + elseif f == "rgbaf32" then + wf(px, i * 16, r) + wf(px, i * 16 + 4, g) + wf(px, i * 16 + 8, b) + wf(px, i * 16 + 12, al) + elseif f == "rgb8" then + wu8(px, i * 3, q(r)) + wu8(px, i * 3 + 1, q(g)) + wu8(px, i * 3 + 2, q(b)) + elseif f == "gray8" then + wu8(px, i, grey()) + elseif f == "gray16" then + wu16(px, i * 2, grey()) + elseif f == "graya8" then + wu8(px, i * 2, grey()) + wu8(px, i * 2 + 1, q(al)) + else + wu8(px, i, q(al)) + end + return true, nil +end + +-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) +function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + if img.format == "yuv420p" then + return arg("fill: not supported on yuv420p") + end + local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a) + if not sok then + return nil, se + end + local bpp = Types.BPP[img.format] :: number + local n = img.width * img.height * bpp + local filled = bpp + while filled < n do + local c = math.min(filled, n - filled) + buffer.copy(img.pixels, filled, img.pixels, 0, c) + filled += c + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ animation +-- frameCount(img) -> the number of frames (1 for a still image) +function ImageOps.frameCount(img: Image): number + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + return #img.frames + end + return 1 +end + +-- durations(img) -> { seconds } per frame ({ 0 } for a still image) +function ImageOps.durations(img: Image): { number } + local out = {} + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + for i, f in img.frames do + out[i] = if type(f.delay) == "number" then f.delay else 0 + end + return out + end + return { 0 } +end + +-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 / +-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's +-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores +-- the canvas from before the frame). A still image gives { img }. +function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?) + local ok, e = check(img) + if not ok then + return nil, e + end + local frames = img.frames + if type(frames) ~= "table" or #frames == 0 then + return { img }, nil + end + local fmt = if RGBA[img.format] then img.format else "rgba8" + local canvas = Types.Image.new(img.width, img.height, fmt :: any) + local bpp = Types.BPP[fmt] :: number + local out = {} + for i, f in frames do + if type(f) ~= "table" then + return arg("coalesce: frame " .. i .. " is not a Frame") + end + local fi = f.image + local fok, fe = check(fi) + if not fok then + return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message) + end + local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0 + local saved: buffer? = nil + if f.dispose == "previous" then + local sb = buffer.create(buffer.len(canvas.pixels)) + buffer.copy(sb, 0, canvas.pixels) + saved = sb + end + local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" }) + if not bok then + return nil, be + end + local snap = Types.Image.new(img.width, img.height, fmt :: any) + buffer.copy(snap.pixels, 0, canvas.pixels) + for k, v in img.meta do + snap.meta[k] = v + end + snap.meta.delay = f.delay + out[i] = snap + if f.dispose == "background" then + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height) + for y = y0, y1 - 1 do + if x1 > x0 then + buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp) + end + end + elseif saved then + canvas.pixels = saved + end + end + return out, nil +end + +-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, +-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds } +-- (default 0.1). All images need the same size and format. +function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?) + if type(images) ~= "table" or #images == 0 then + return arg("fromFrames: a non-empty list of Images") + end + local first = images[1] + local ok, e = check(first) + if not ok then + return nil, e + end + local frames = {} + for i, im in images do + local iok, ie = check(im) + if not iok then + return nil, ie + end + if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then + return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1") + end + local d = 0.1 + if type(delays) == "number" then + d = delays + elseif type(delays) == "table" and type(delays[i]) == "number" then + d = delays[i] + end + frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" } + end + local out = like(first, first.width, first.height) + buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) + out.frames = frames :: any + out.loops = 0 + return out, nil +end + +return ImageOps +end +__FILES["ops/ImageOps/Kernels"] = @native function() + + + +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller +-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by +-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers). +-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by +-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through +-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c. +local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 +local floor, clamp = math.floor, math.clamp + +local K = {} + +-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8 +K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } :: { [string]: number } +K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } :: { [string]: number } +K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } :: { [string]: number } + +@native local function rd(b: buffer, o: number, kind: number): number + if kind == 1 then + return readu8(b, o) + elseif kind == 2 then + return readu16(b, o) + end + return readf32(b, o) +end + +@native local function wr(b: buffer, o: number, kind: number, v: number) + if kind == 1 then + writeu8(b, o, clamp(floor(v + 0.5), 0, 255)) + elseif kind == 2 then + writeu16(b, o, clamp(floor(v + 0.5), 0, 65535)) + else + writef32(b, o, v) + end +end + +-- ------------------------------------------------------------------------------------------------ convert +-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 +local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } + +@native local function depthConv(v: number, from: number, to: number): number + if from == to then + return v + end + if from == 8 then + if to == 16 then + return v * 257 + end + return v / 255 + elseif from == 16 then + if to == 8 then + return (v * 255 + 32767) // 65535 + end + return v / 65535 + end + -- float + if v ~= v then + v = 0 + end + if to == 8 then + return clamp(floor(v * 255 + 0.5), 0, 255) + end + return clamp(floor(v * 65535 + 0.5), 0, 65535) +end + +-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth +@native local function luma(r: number, g: number, b: number, depth: number): number + if depth == 0 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536 +end + +@native function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number) + local sd, dd = DEPTH[sf] :: number, DEPTH[df] :: number + local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1 + local toGray = df == 5 or df == 6 or df == 7 + for i = 0, n - 1 do + local r: number, g: number, b: number, a: number + if sf == 1 then + local o = i * 4 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3) :: number + elseif sf == 2 then + local o = i * 8 + r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6) :: number + elseif sf == 3 then + local o = i * 16 + r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12) :: number + elseif sf == 4 then + local o = i * 3 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255 + elseif sf == 5 then + local v = readu8(src, i) + r, g, b, a = v, v, v, 255 + elseif sf == 6 then + local v = readu16(src, i * 2) + r, g, b, a = v, v, v, 65535 + elseif sf == 7 then + local v = readu8(src, i * 2) + r, g, b, a = v, v, v, readu8(src, i * 2 + 1) :: number + else + r, g, b, a = 255, 255, 255, readu8(src, i) + end + if toGray then + local isGray = sf == 5 or sf == 6 or sf == 7 + local l = if isGray then r else luma(r, g, b, sd) + l = depthConv(l, sd, dd) + if df == 5 then + writeu8(dst, i, l) + elseif df == 6 then + writeu16(dst, i * 2, l) + else + writeu8(dst, i * 2, l) + writeu8(dst, i * 2 + 1, depthConv(a, sd, dd)) + end + elseif df == 8 then + writeu8(dst, i, depthConv(a, sd, 8)) + else + r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd) :: number + if df == 1 then + local o = i * 4 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + writeu8(dst, o + 3, depthConv(a, sd, dd)) + elseif df == 2 then + local o = i * 8 + writeu16(dst, o, r) + writeu16(dst, o + 2, g) + writeu16(dst, o + 4, b) + writeu16(dst, o + 6, depthConv(a, sd, dd)) + elseif df == 3 then + local o = i * 16 + writef32(dst, o, r) + writef32(dst, o + 4, g) + writef32(dst, o + 8, b) + writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd)) + else -- rgb8 + local o = i * 3 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + end + end + end +end + +-- JPEG-style BT.601 full range +@native function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255)) + end + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local sr, sg, sb, n = 0, 0, 0, 0 + for dy = 0, 1 do + local y = cy * 2 + dy + if y < h then + for dx = 0, 1 do + local x = cx * 2 + dx + if x < w then + local o = (y * w + x) * 4 + sr += readu8(src, o) + sg += readu8(src, o + 1) + sb += readu8(src, o + 2) + n += 1 + end + end + end + end + sr, sg, sb = sr / n, sg / n, sb / n + local i = cy * cw + cx + writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255)) + writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255)) + end + end +end + +@native function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local uo, vo = w * h, w * h + cw * ch + for y = 0, h - 1 do + local crow = (y // 2) * cw + for x = 0, w - 1 do + local yy = readu8(src, y * w + x) + local ci = crow + x // 2 + local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128 + local o = (y * w + x) * 4 + writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255)) + writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255)) + writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255)) + writeu8(dst, o + 3, 255) + end + end + local _ = ch +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- flip(src, dst, w, h, bpp, horizontal) +@native function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean) + local stride = w * bpp + if not horizontal then + for y = 0, h - 1 do + buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride) + end + return + end + for y = 0, h - 1 do + local row = y * stride + for x = 0, w - 1 do + buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp) + end + end +end + +-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3 +@native function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local ox, oy, ow + if turns == 1 then + ox, oy, ow = y, w - 1 - x, h + elseif turns == 2 then + ox, oy, ow = w - 1 - x, h - 1 - y, w + else + ox, oy, ow = h - 1 - y, x, h + end + local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp + if bpp == 4 then + buffer.writeu32(dst, d, buffer.readu32(src, so)) + else + buffer.copy(dst, d, src, so, bpp) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ resample +@native local function bilinearF(x: number): number + if x < 0 then + x = -x + end + if x < 1 then + return 1 - x + end + return 0 +end + +@native local function sinc(x: number): number + if x == 0 then + return 1 + end + x *= math.pi + return math.sin(x) / x +end + +@native local function lanczosF(x: number): number + if x > -3 and x < 3 then + return sinc(x) * sinc(x / 3) + end + return 0 +end + +@native local function trunc(x: number): number + return if x < 0 then math.ceil(x) else floor(x) +end + +-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised) +type Coeffs = { start: { number }, count: { number }, weights: { { number } } } + +@native function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs + local support0 = if filter == "lanczos" then 3 else 1 + local f = if filter == "lanczos" then lanczosF else bilinearF + local scale = inSize / outSize + local filterscale = math.max(scale, 1) + local support = support0 * filterscale + local ss = 1 / filterscale + local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize) :: { { number } } + for xx = 0, outSize - 1 do + local center = (xx + 0.5) * scale + local xmin = math.max(0, trunc(center - support + 0.5)) + local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin + local w = table.create(math.max(xmax, 0), 0) + local ww = 0 + for x = 0, xmax - 1 do + local v = f((x + xmin - center + 0.5) * ss) + w[x + 1] = v + ww += v + end + if ww ~= 0 then + for x = 1, xmax do + w[x] /= ww + end + end + start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w + end + return { start = start, count = count, weights = weights } +end + +-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind. +@native function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean) + local start, count, weights = c.start, c.count, c.weights + local size = kind + local fixed = kind == 1 + -- 8-bit: Pillow's 22-bit fixed-point coefficients + local iw: { { number } } = weights + if fixed then + iw = table.create(outN) :: { { number } } + for i = 1, outN do + local src0 = weights[i] + local t = table.create(#src0, 0) + for k = 1, #src0 do + local v = src0[k] * 4194304 + t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5) + end + iw[i] = t + end + end + if horizontal then + for y = 0, h - 1 do + local row = y * w + for xx = 0, outN - 1 do + local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1] + local o = ((y * outN) + xx) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + else + for yy = 0, outN - 1 do + local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1] + for x = 0, w - 1 do + local o = (yy * w + x) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + end + local _ = h +end + +-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...) +@native function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number) + local sx, sy = w / ow, h / oh + for y = 0, oh - 1 do + local iy = math.min(floor((y + 0.5) * sy), h - 1) + for x = 0, ow - 1 do + local ix = math.min(floor((x + 0.5) * sx), w - 1) + buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp) + end + end +end + +-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src +-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow) +@native function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number }) + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + local size = kind + for y = 0, oh - 1 do + local py = y + 0.5 + for x = 0, ow - 1 do + local px = x + 0.5 + local xin = a * px + b * py + c - 0.5 + local yin = d * px + e * py + f - 0.5 + local o = (y * ow + x) * ch * size + local x0 = floor(xin) + local y0 = floor(yin) + if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then + continue -- dst starts zeroed + end + local dx, dy = xin - x0, yin - y0 + local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1) + local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1) + for cc = 0, ch - 1 do + local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind) + local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind) + local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind) + local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind) + local top = p00 + (p01 - p00) * dx + local bot = p10 + (p11 - p10) * dx + local v = top + (bot - top) * dy + if kind == 1 then + writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates + else + wr(dst, o + cc * size, kind, v) + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ compositing +-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place +@native function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number) + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * 4 + local doff = ((dy + y) * dw + dx + x) * 4 + local sa = readu8(src, so + 3) + if opacity < 255 then + sa = (sa * opacity + 127) // 255 + end + if sa == 0 then + continue + end + local da = readu8(dst, doff + 3) + local blend = da * (255 - sa) + local outa255 = sa * 255 + blend + local coef1 = (sa * 255 * 255 * 128) // outa255 + local coef2 = 255 * 128 - coef1 + for cc = 0, 2 do + local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128 + t = ((t // 256) + t) // 256 + writeu8(dst, doff + cc, t // 128) + end + local t = outa255 + 0x80 + writeu8(dst, doff + 3, ((t // 256) + t) // 256) + end + end +end + +-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1 +@native function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number) + local max = if kind == 2 then 65535 else 1 + local px = 4 * kind + for y = 0, h - 1 do + for x = 0, w - 1 do + local so = ((sy + y) * sw + sx + x) * px + local doff = ((dy + y) * dw + dx + x) * px + local sa = rd(src, so + 3 * kind, kind) / max * opacity + if sa <= 0 then + continue + end + local da = rd(dst, doff + 3 * kind, kind) / max + local oa = sa + da * (1 - sa) + for cc = 0, 2 do + local s = rd(src, so + cc * kind, kind) + local d = rd(dst, doff + cc * kind, kind) + wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0) + end + wr(dst, doff + 3 * kind, kind, oa * max) + end + end +end + +-- copyRect: rows of a rectangle (bpp bytes per pixel) +@native function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number) + for y = 0, h - 1 do + buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) + end +end + +-- premultiply / unpremultiply in place: ch channels, alpha last, kind +@native function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean) + local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1 + local px = ch * kind + for i = 0, n - 1 do + local o = i * px + local a = rd(b, o + (ch - 1) * kind, kind) + for cc = 0, ch - 2 do + local v = rd(b, o + cc * kind, kind) + local r + if un then + if a <= 0 then + r = 0 + elseif kind == 4 then + r = v / a + elseif kind == 1 then + r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba + else + r = math.min(max, (v * max + a // 2) // a) + end + else + if kind == 4 then + r = v * a + elseif kind == 1 then + local t = v * a + 128 -- Pillow's MULDIV255 + r = ((t // 256) + t) // 256 + else + r = (v * a + max // 2) // max + end + end + wr(b, o + cc * kind, kind, r) + end + end +end + +return K +end +__FILES["ops/LayerOps"] = function() + +-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an +-- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- grey layer masks; every frame as an animated Image; walking the leaves. +-- +-- local LayerOps = require("@rosetta/ops/LayerOps") +-- local img = LayerOps.flatten(layered) -- frame 1 / the layers +-- local img3 = LayerOps.flatten(layered, { frame = 3 }) +-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) +-- for layer, depth in LayerOps.leaves(layered.layers) do ... end +-- +-- Never throws: bad values return nil, Err.ARG. +local Err = __include("core/Err") +local Types = __include("Types") +local Blend = __include("codecs/image/Blend") + +local LayerOps = {} + +type FlattenOptions = { + frame: number?, -- 1-based animation frame (default: layered.layers, which is frame 1) + hidden: boolean?, -- include hidden layers (default false) + background: { number }?, -- r, g, b, a 0..255 under everything (default transparent) +} + +-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err +function LayerOps.flatten(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then + return nil, Err.new(Err.ARG, "flatten: needs a Layered value") + end + local o: FlattenOptions = opts or {} + local w, h = math.floor(layered.width), math.floor(layered.height) + if w < 0 or h < 0 or w * h > 2 ^ 28 then + return nil, Err.new(Err.ARG, "flatten: bad size") + end + local layers = layered.layers + if o.frame then + local f = if type(layered.frames) == "table" then layered.frames[o.frame] else nil + if f == nil and o.frame ~= 1 then + return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame)) + end + if f then + layers = f.layers + end + end + local img = Types.Image.new(w, h) + local bg = o.background + if type(bg) == "table" then + local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, w * h - 1 do + buffer.writeu32(img.pixels, i * 4, v) + end + end + Blend.flatten(layers, img.pixels, w, h, o.hidden == true) + return img, nil +end + +-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) +function LayerOps.flattenFrames(layered: Types.Layered, opts: FlattenOptions?): (Types.Image?, Err.Err?) + local first, err = LayerOps.flatten(layered, opts) + if not first then + return nil, err + end + local frames = if type(layered.frames) == "table" then layered.frames else {} + if #frames == 0 then + return first, nil + end + local list: { Types.Frame } = {} + for i, f in frames do + local o: FlattenOptions = table.clone(opts or {}) :: any + o.frame = i + local img = if i == 1 then first else LayerOps.flatten(layered, o) + if not img then + return nil, Err.new(Err.ARG, "flatten: frame " .. i) + end + list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" } + end + first.frames = list + return first, nil +end + +-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top +function LayerOps.leaves(layers: { Types.Layer }): () -> (Types.Layer?, number?) + local stack: { { any } } = { { layers, 0, 0 } } + return function(): (Types.Layer?, number?) + while #stack > 0 do + local top = stack[#stack] + top[2] += 1 + local l = top[1][top[2]] + if l == nil then + table.remove(stack) + elseif type(l.children) == "table" then + table.insert(stack, { l.children, 0, top[3] + 1 }) + else + return l, top[3] + end + end + return nil, nil + end +end + +return LayerOps +end +__FILES["ops/MeshOps"] = function() + +-- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear +-- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), +-- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an +-- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis +-- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). +-- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type +-- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). +-- +-- local MeshOps = require("@rosetta/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops) +-- local prim = MeshOps.merge(scene) -- one triangle primitive in world space +-- MeshOps.computeNormals(prim) +-- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +local Err = __include("core/Err") +local Types = __include("Types") +local Greedy = __include("ops/MeshOps/Greedy") + +local MeshOps = {} + +type Accessor = Types.Accessor +type Primitive = Types.Primitive +type Scene = Types.Scene + +local Scene = Types.Scene +local readf32, writef32 = buffer.readf32, buffer.writef32 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ accessors +-- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one +function MeshOps.f32(acc: Accessor): Accessor? + if acc.type == "f32" then + return acc + end + local get = Scene.reader(acc) + if not get then + return nil + end + local n, c = acc.count, acc.components + local out = buffer.create(n * c * 4) + for i = 0, n - 1 do + for k = 0, c - 1 do + writef32(out, (i * c + k) * 4, get(i, k)) + end + end + local a = Scene.accessor(out, "f32", c, n) + a.matrix = acc.matrix + return a +end + +-- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 +local function indexBuffer(prim: Primitive): (buffer, number) + local ind = prim.indices + if ind then + if ind.type == "u32" and ind.components == 1 then + return ind.data, ind.count + end + local get = Scene.reader(ind) + local out = buffer.create(ind.count * 4) + if get then + for i = 0, ind.count - 1 do + writeu32(out, i * 4, get(i, 0)) + end + end + return out, ind.count + end + local pos = prim.attributes.POSITION + local n = if pos then pos.count else 0 + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, i) + end + return out, n +end + +local function vertexCount(prim: Primitive): number + local pos = prim.attributes.POSITION + return if pos then pos.count else 0 +end + +local function checkPrim(prim: any): Err.Err? + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return Err.new(Err.ARG, "expected a Primitive") + end + local pos = prim.attributes.POSITION + if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then + return Err.new(Err.ARG, "primitive without a POSITION accessor") + end + local n = pos.count + for name, a in prim.attributes do + local size = Types.COMPONENT_SIZE[a.type] + if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") + end + if a.count ~= n then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") + end + end + if prim.indices then + local ind = prim.indices + local size = Types.COMPONENT_SIZE[ind.type] + if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then + return Err.new(Err.ARG, "bad indices accessor") + end + local get = Scene.reader(ind) + if get then + for i = 0, ind.count - 1 do + if get(i, 0) >= n then + return Err.new(Err.ARG, "index out of range") + end + end + end + end + return nil +end +MeshOps.check = checkPrim + +-- ------------------------------------------------------------------------------------------------ triangulate +-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck +local function earclip(poly: { number }, P: (number, number) -> number, out: { number }) + local k = #poly + if k < 3 then + return + end + if k == 3 then + table.insert(out, poly[1]) + table.insert(out, poly[2]) + table.insert(out, poly[3]) + return + end + -- Newell normal -> the projection plane (drop the dominant axis) + local nx, ny, nz = 0, 0, 0 + for a = 1, k do + local i, j = poly[a], poly[a % k + 1] + local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) + local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) + nx += (yi - yj) * (zi + zj) + ny += (zi - zj) * (xi + xj) + nz += (xi - xj) * (yi + yj) + end + local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) + local cu, cv, sign = 0, 1, nz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, nx + elseif ay >= az then + cu, cv, sign = 2, 0, ny + end + local function uv(i: number): (number, number) + return P(i, cu), P(i, cv) + end + local s = if sign < 0 then -1 else 1 + local ring = table.clone(poly) + local guard = 0 + while #ring > 3 and guard < k * k do + guard += 1 + local n = #ring + local clipped = false + for a = 1, n do + local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] + local ax2, ay2 = uv(ia) + local bx, by = uv(ib) + local cx, cy = uv(ic) + local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s + if cross > 0 then + local inside = false + for q = 1, n do + local iq = ring[q] + if iq ~= ia and iq ~= ib and iq ~= ic then + local qx, qy = uv(iq) + local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s + local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s + local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s + if d1 >= 0 and d2 >= 0 and d3 >= 0 then + inside = true + break + end + end + end + if not inside then + table.insert(out, ia) + table.insert(out, ib) + table.insert(out, ic) + table.remove(ring, a) + clipped = true + break + end + end + end + if not clipped then + break + end + end + -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan + for a = 2, #ring - 1 do + table.insert(out, ring[1]) + table.insert(out, ring[a]) + table.insert(out, ring[a + 1]) + end +end + +local function u32(list: { number }): Accessor + local n = #list + local b = buffer.create(n * 4) + for i = 1, n do + writeu32(b, (i - 1) * 4, list[i]) + end + return Scene.accessor(b, "u32", 1, n) +end + +-- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" +-- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). +-- Lines and points come back unchanged. +function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local mode = prim.mode or "triangles" + if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then + return prim, nil + end + local method = opts and opts.method or "earclip" + local ib, n = indexBuffer(prim) + local out: { number } = {} + if mode == "triangles" then + local m = n - n % 3 + for i = 0, m - 1 do + out[i + 1] = readu32(ib, i * 4) + end + elseif mode == "triangle_strip" then + for i = 0, n - 3 do + local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) + if i % 2 == 1 then + a, b = b, a + end + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + elseif mode == "triangle_fan" then + for i = 1, n - 2 do + table.insert(out, readu32(ib, 0)) + table.insert(out, readu32(ib, i * 4)) + table.insert(out, readu32(ib, i * 4 + 4)) + end + elseif mode == "polygons" then + local faces = prim.faces + if not faces then + return nil, Err.new(Err.ARG, "polygons primitive without faces") + end + local getf = Scene.reader(faces) + if not getf then + return nil, Err.new(Err.ARG, "bad faces accessor") + end + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local P = function(i: number, c: number): number + return readf32(pd, (i * 3 + c) * 4) + end + local at = 0 + for f = 0, faces.count - 1 do + local k = getf(f, 0) + if at + k > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + if k >= 3 then + if method == "fan" or k == 3 then + for a = 1, k - 2 do + table.insert(out, readu32(ib, at * 4)) + table.insert(out, readu32(ib, (at + a) * 4)) + table.insert(out, readu32(ib, (at + a + 1) * 4)) + end + else + local poly = table.create(k) :: { number } + for a = 0, k - 1 do + poly[a + 1] = readu32(ib, (at + a) * 4) + end + earclip(poly, P, out) + end + end + at += k + end + else + return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) + end + return { + attributes = prim.attributes, + indices = u32(out), + mode = "triangles", + material = prim.material, + targets = prim.targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +-- the inverse transpose of m's 3 x 3 part (column-major 9), for normals +local function normalMatrix(m: { number }): { number } + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + if det == 0 then + det = 1 + end + local k = 1 / det + -- cofactor matrix / det (= inverse transpose), column-major + return { + (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, + -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, + (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, + } +end + +-- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). +-- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + if type(m) ~= "table" or #m ~= 16 then + return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") + end + local nm = normalMatrix(m) + local function points(acc: Accessor?, w: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) + writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) + writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) + end + return a + end + local function dirs(acc: Accessor?, mat: { number }, normalize: boolean, flipW: boolean): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + local nx = mat[1] * x + mat[4] * y + mat[7] * z + local ny = mat[2] * x + mat[5] * y + mat[8] * z + local nz = mat[3] * x + mat[6] * y + mat[9] * z + if normalize then + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + writef32(d, o, nx) + writef32(d, o + 4, ny) + writef32(d, o + 8, nz) + if flipW and c >= 4 then + writef32(d, o + 12, -readf32(d, o + 12)) + end + end + return a + end + local mirror = det3(m) < 0 + local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } + local attrs = prim.attributes + attrs.POSITION = points(attrs.POSITION, 1) :: Accessor + attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) + attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) + if prim.targets then + for _, t in prim.targets do + t.POSITION = points(t.POSITION, 0) + t.NORMAL = dirs(t.NORMAL, nm, false, false) + t.TANGENT = dirs(t.TANGENT, m3, false, false) + end + end + if mirror and (prim.mode == "triangles" or prim.mode == nil) then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + buffer.copy(nb, 0, ib, 0, n * 4) + for t = 0, n // 3 - 1 do + local o = t * 12 + local b = readu32(nb, o + 4) + writeu32(nb, o + 4, readu32(nb, o + 8)) + writeu32(nb, o + 8, b) + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + elseif mirror and prim.mode == "polygons" and prim.faces then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + local getf = Scene.reader(prim.faces) + local at = 0 + if getf then + for f = 0, prim.faces.count - 1 do + local k = getf(f, 0) + for a = 0, k - 1 do + if at + a < n then + writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) + end + end + at += k + end + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + end + return prim, nil +end + +-- ------------------------------------------------------------------------------------------------ normals / tangents +-- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | +-- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle +-- modes are triangulated first (the returned primitive is then a new one). +function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?) + local p = prim + if (prim.mode or "triangles") ~= "triangles" then + local t, err = MeshOps.triangulate(prim) + if not t then + return nil, err + end + p = t + else + local err = checkPrim(prim) + if err then + return nil, err + end + end + if p.mode ~= "triangles" then + return p, nil -- lines / points: nothing to do + end + if opts and opts.flat then + p = MeshOps.unweld(p) + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local pd = pos.data + local nv = pos.count + local ib, n = indexBuffer(p) + local acc = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + -- the cross product is twice the area times the unit normal: area weighting for free + local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + else + x, y, z = 0, 0, 1 + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) + return p, nil +end + +-- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | +-- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_. +function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?) + local p = prim + if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then + local q, err = MeshOps.computeNormals(prim) + if not q then + return nil, err + end + p = q + end + local err = checkPrim(p) + if err then + return nil, err + end + local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] + if not uvAcc then + return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") + end + local pos = MeshOps.f32(p.attributes.POSITION) :: Accessor + local nrm = MeshOps.f32(p.attributes.NORMAL :: Accessor) :: Accessor + local uv = MeshOps.f32(uvAcc) :: Accessor + local pd, nd, ud = pos.data, nrm.data, uv.data + local nv = pos.count + local ib, n = indexBuffer(p) + local tan = table.create(nv * 3, 0) + local bit = table.create(nv * 3, 0) + for t = 0, n // 3 - 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) + local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs + local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs + local den = s1 * t2 - s2 * t1 + if den ~= 0 then + local r = 1 / den + local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r + local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r + for _, v in { a, b, c } do + tan[v * 3 + 1] += tx + tan[v * 3 + 2] += ty + tan[v * 3 + 3] += tz + bit[v * 3 + 1] += bx + bit[v * 3 + 2] += by + bit[v * 3 + 3] += bz + end + end + end + local out = buffer.create(nv * 16) + for v = 0, nv - 1 do + local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) + local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] + local dot = nx * tx + ny * ty + nz * tz + tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l > 1e-20 then + tx, ty, tz = tx / l, ty / l, tz / l + else + -- no UV gradient: any unit vector orthogonal to the normal + if math.abs(nx) < 0.9 then + tx, ty, tz = 0, nz, -ny + else + tx, ty, tz = -nz, 0, nx + end + local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) + if l2 > 0 then + tx, ty, tz = tx / l2, ty / l2, tz / l2 + end + end + -- handedness: (n x t) . b + local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx + local w = if cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 then -1 else 1 + writef32(out, v * 16, tx) + writef32(out, v * 16 + 4, ty) + writef32(out, v * 16 + 8, tz) + writef32(out, v * 16 + 12, w) + end + p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ weld / unweld +local function gather(acc: Accessor, ib: buffer, n: number): Accessor + local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components + local out = buffer.create(n * size) + for i = 0, n - 1 do + buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) + end + local a = Scene.accessor(out, acc.type, acc.components, n) + a.matrix = acc.matrix + return a +end + +-- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) +function MeshOps.unweld(prim: Primitive): Primitive + local ib, n = indexBuffer(prim) + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, ib, n) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, ib, n) + end + targets[k] = tt + end + end + return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } +end + +-- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. +-- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other +-- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). +-- Morph targets are kept per merged vertex (the first one's). +function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?) + local err = checkPrim(prim) + if err then + return nil, err + end + local eps = opts and opts.epsilon or 0 + local posOnly = opts and opts.positionsOnly or false + local names = {} + for name in prim.attributes do + if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then + table.insert(names, name) + end + end + table.sort(names) + local nv = vertexCount(prim) + local pos = MeshOps.f32(prim.attributes.POSITION) :: Accessor + local pd = pos.data + local inv = if eps > 0 then 1 / eps else 0 + local remap = buffer.create(nv * 4) + local keep: { number } = {} + local seen: { [string]: number } = {} + local parts = table.create(#names + 1) + for v = 0, nv - 1 do + local np = 0 + if eps > 0 then + np += 1 + parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) + end + for _, name in names do + local a = prim.attributes[name] + local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components + np += 1 + parts[np] = buffer.readstring(a.data, v * size, size) + end + local key = table.concat(parts, "\1", 1, np) + local k = seen[key] + if k == nil then + k = #keep + seen[key] = k + table.insert(keep, v) + end + writeu32(remap, v * 4, k) + end + local kb = buffer.create(#keep * 4) + for i, v in keep do + writeu32(kb, (i - 1) * 4, v) + end + local attrs = {} + for name, a in prim.attributes do + attrs[name] = gather(a, kb, #keep) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in prim.targets do + local tt = {} + for name, a in t do + tt[name] = gather(a, kb, #keep) + end + targets[k] = tt + end + end + local ib, n = indexBuffer(prim) + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) + end + return { + attributes = attrs, + indices = Scene.accessor(out, "u32", 1, n), + mode = prim.mode, + faces = prim.faces, + material = prim.material, + targets = targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ bounds +-- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and +-- voxel shape cell corners excluded) | nil, nil when there are no positions +function MeshOps.bounds(x: any): ({ number }?, { number }?) + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local function add(prim: Primitive, m: { number }?) + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + return + end + local get = Scene.reader(pos) + if not get then + return + end + for i = 0, pos.count - 1 do + local px, py, pz = get(i, 0), get(i, 1), get(i, 2) + if m and m ~= Scene.IDENTITY then + px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] + end + if px < lo[1] then + lo[1] = px + end + if py < lo[2] then + lo[2] = py + end + if pz < lo[3] then + lo[3] = pz + end + if px > hi[1] then + hi[1] = px + end + if py > hi[2] then + hi[2] = py + end + if pz > hi[3] then + hi[3] = pz + end + end + end + if type(x) ~= "table" then + return nil, nil + end + if x.kind == "scene" then + for _, pl in Scene.flatten(x) do + add(pl.primitive, pl.matrix) + end + else + add(x, nil) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) +local function defaultFor(name: string, k: number): number + if string.sub(name, 1, 6) == "COLOR_" then + return 1 + end + if string.sub(name, 1, 8) == "WEIGHTS_" then + return if k == 0 then 1 else 0 + end + return 0 +end + +-- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | +-- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input +-- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. +-- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets +-- are not applied (the rest pose). +function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?) + local placed: { Types.Placed } = {} + if type(input) ~= "table" then + return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") + end + if input.kind == "scene" then + placed = Scene.flatten(input) + else + for i, p in input do + placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } + end + end + -- triangulate + bake each + local groups: { [number]: { Primitive } } = {} + local order: { number } = {} + local allPoints = #placed > 0 + for _, pl in placed do + if pl.primitive.mode ~= "points" then + allPoints = false + end + end + for _, pl in placed do + local p = pl.primitive + local mode = p.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then + local t, err = if mode == "points" then p else MeshOps.triangulate(p, opts) + if not t then + return nil, err + end + -- a private copy of the attributes to bake + local copy: Primitive = { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } + for name, a in t.attributes do + copy.attributes[name] = MeshOps.f32(a) + end + if pl.matrix ~= Scene.IDENTITY then + local ok, terr = MeshOps.transform(copy, pl.matrix) + if not ok then + return nil, terr + end + end + local key = if opts and opts.byMaterial then (copy.material or 0) else 0 + if not groups[key] then + groups[key] = {} + table.insert(order, key) + end + table.insert(groups[key], copy) + end + end + table.sort(order) + local function concat(list: { Primitive }, material: number?): Primitive + local names: { [string]: number } = {} + local nv, ni = 0, 0 + local points = false + for _, p in list do + for name, a in p.attributes do + names[name] = math.max(names[name] or 0, a.components) + end + nv += vertexCount(p) + local _, n = indexBuffer(p) + ni += n + points = points or p.mode == "points" + end + local attrs: { [string]: Accessor } = {} + for name, comps in names do + local out = buffer.create(nv * comps * 4) + local base = 0 + for _, p in list do + local a = p.attributes[name] + local cnt = vertexCount(p) + for v = 0, cnt - 1 do + for k = 0, comps - 1 do + local value = if a and k < a.components then readf32(a.data, (v * a.components + k) * 4) else defaultFor(name, k) + writef32(out, ((base + v) * comps + k) * 4, value) + end + end + base += cnt + end + attrs[name] = Scene.accessor(out, "f32", comps, nv) + end + local idx = buffer.create(ni * 4) + local base, at = 0, 0 + for _, p in list do + local ib, n = indexBuffer(p) + for i = 0, n - 1 do + writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) + end + at += n + base += vertexCount(p) + end + return { + attributes = attrs, + indices = if points then nil else Scene.accessor(idx, "u32", 1, ni), + mode = if points then "points" else "triangles", + material = material, + } + end + if opts and opts.byMaterial then + local out = {} + for _, key in order do + table.insert(out, concat(groups[key], if key == 0 then nil else key)) + end + return out, nil + end + local all: { Primitive } = groups[0] or {} + local first = all[1] + return concat(all, first and first.material), nil +end + +-- ------------------------------------------------------------------------------------------------ units / up axis +local function scaleAccessor(acc: Accessor?, f: number): Accessor? + if not acc then + return nil + end + local a = MeshOps.f32(acc) :: Accessor + if a == acc then + a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + for i = 0, a.count * a.components - 1 do + writef32(a.data, i * 4, readf32(a.data, i * 4) * f) + end + return a +end + +-- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and +-- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by +-- factor (the same physical size in smaller units). +function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then + return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") + end + local done: { [any]: boolean } = {} + for _, mesh in scene.meshes do + for _, p in mesh.primitives do + if not done[p] then + done[p] = true + p.attributes.POSITION = scaleAccessor(p.attributes.POSITION, f) :: Accessor + for _, t in p.targets or {} do + t.POSITION = scaleAccessor(t.POSITION, f) + end + end + end + end + for _, n in scene.nodes do + if n.translation then + n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } + end + if n.matrix then + local m = table.clone(n.matrix) + m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f + n.matrix = m + end + end + for _, a in scene.animations do + for _, c in a.channels do + if c.path == "translation" and not done[c.output] then + done[c.output] = true + c.output = scaleAccessor(c.output, f) :: Accessor + end + end + end + for _, s in scene.skins do + local ibm = s.inverseBindMatrices + if ibm and not done[ibm] then + local a = MeshOps.f32(ibm) :: Accessor + if a == ibm then + a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) + buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) + end + for i = 0, a.count - 1 do + for k = 12, 14 do + writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) + end + end + a.matrix = true + s.inverseBindMatrices = a + done[a] = true + end + end + for _, c in scene.cameras do + if c.type == "perspective" then + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + else + c.znear *= math.abs(f) + if c.zfar then + c.zfar *= math.abs(f) + end + c.xmag = c.xmag and c.xmag * math.abs(f) + c.ymag = c.ymag and c.ymag * math.abs(f) + end + end + for _, l in scene.lights do + if l.range then + l.range *= math.abs(f) + end + end + scene.meta.unit = (scene.meta.unit or 1) / f + return scene, nil +end + +-- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) +function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?) + if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then + return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") + end + local from = scene.meta.unit or 1 + return MeshOps.scale(scene, from / metresPerUnit) +end + +-- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. +-- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). +function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then + return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") + end + local from = scene.meta.up or "y" + if from == up then + return scene, nil + end + local h = math.sqrt(0.5) + -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x + local q = if up == "y" then { -h, 0, 0, h } else { h, 0, 0, h } + table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) + scene.roots = { #scene.nodes } + scene.meta.up = up :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ voxels +local function linear(c: number): number + local s = c / 255 + return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4 +end + +-- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, +-- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. +-- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); +-- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or +-- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?) + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a Voxels grid") + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then + return nil, Err.new(Err.ARG, "bad voxel grid size") + end + local pivot = opts and opts.pivot or "center" + local scale = opts and opts.scale or 1 + local ox, oy, oz = 0, 0, 0 + if pivot == "center" then + ox, oy, oz = -(sx // 2), -(sy // 2), -(sz // 2) + end + local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) + local nv = g.vertices + local function trim(b: buffer, size: number): buffer + local out = buffer.create(size) + buffer.copy(out, 0, b, 0, size) + return out + end + local attrs: { [string]: Accessor } = { + POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), + NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), + } + local pal = v.palette or {} + local srgb = opts and opts.colors == "srgb" + local col = buffer.create(nv * (if srgb then 4 else 16)) + local lut: { { number } } = {} + for i = 1, 255 do + local c: { number } = pal[i] or { 255, 255, 255, 255 } + if srgb then + lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } + else + lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } + end + end + for k = 0, nv - 1 do + local c = lut[buffer.readu8(g.index, k)] or lut[1] + if srgb then + for j = 0, 3 do + buffer.writeu8(col, k * 4 + j, c[j + 1]) + end + else + for j = 0, 3 do + writef32(col, k * 16 + j * 4, c[j + 1]) + end + end + end + attrs.COLOR_0 = Scene.accessor(col, if srgb then "unorm8" else "f32", 4, nv) + if opts and opts.indexAttribute then + attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) + end + return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil +end + +-- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node +-- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as +-- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids). +function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local grids = scene.voxels or {} + local mat = 0 + local meshOf: { [number]: number } = {} + for i, v in grids do + local prim, err = MeshOps.voxelsToPrimitive(v, opts) + if not prim then + return nil, err + end + if mat == 0 then + local m = Scene.material("voxels") + m.metallic = 0 + table.insert(scene.materials, m) + mat = #scene.materials + end + prim.material = mat + table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) + meshOf[i] = #scene.meshes + end + for _, n in scene.nodes do + if n.voxels and meshOf[n.voxels] then + n.mesh = meshOf[n.voxels] + end + end + return scene, nil +end + +return MeshOps +end +__FILES["ops/MeshOps/Greedy"] = @native function() + + +-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each +-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged +-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are +-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the +-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz. +local Greedy = {} + +local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +type Out = { + positions: buffer, -- f32 x3 per vertex + normals: buffer, -- f32 x3 per vertex + index: buffer, -- u8 palette index per vertex + indices: buffer, -- u32, 6 per quad + vertices: number, + quads: number, +} + +-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale +@native function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out + local cap = 1024 + local pos = buffer.create(cap * 48) + local nrm = buffer.create(cap * 48) + local idx = buffer.create(cap * 4) + local tri = buffer.create(cap * 24) + local quads = 0 + local maxFace = math.max(sx * sy, sy * sz, sz * sx) + local mask = buffer.create(maxFace * 4) + local corner = { 0, 0, 0 } + for d = 0, 2 do + -- u, v: the two other axes, cyclic so that e_u x e_v = e_d + local u, v = (d + 1) % 3, (d + 2) % 3 + local nd = if d == 0 then sx elseif d == 1 then sy else sz + local nu = if u == 0 then sx elseif u == 1 then sy else sz + local nv = if v == 0 then sx elseif v == 1 then sy else sz + local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy + local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy + local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy + for slice = -1, nd - 1 do + -- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d) + local any = false + for j = 0, nv - 1 do + for i = 0, nu - 1 do + local base = i * stu + j * stv + local a = if slice >= 0 then readu8(data, base + slice * std) else 0 + local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0 + local m = 0 + if a ~= 0 and b == 0 then + m = a + elseif a == 0 and b ~= 0 then + m = -b + end + if m ~= 0 then + any = true + end + writei32(mask, (i + j * nu) * 4, m) + end + end + if any then + for j = 0, nv - 1 do + local i = 0 + while i < nu do + local m = readi32(mask, (i + j * nu) * 4) + if m == 0 then + i += 1 + else + local w = 1 + while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do + w += 1 + end + local h = 1 + local grow = true + while j + h < nv and grow do + for k = 0, w - 1 do + if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then + grow = false + break + end + end + if grow then + h += 1 + end + end + for jj = j, j + h - 1 do + for k = 0, w - 1 do + writei32(mask, (i + k + jj * nu) * 4, 0) + end + end + -- emit the rectangle + if quads == cap then + local ncap = cap * 2 + @native local function grow2(b: buffer, per: number): buffer + local nb = buffer.create(ncap * per) + buffer.copy(nb, 0, b, 0, cap * per) + return nb + end + pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24) :: buffer + cap = ncap + end + corner[d + 1] = slice + 1 + corner[u + 1] = i + corner[v + 1] = j + local cx, cy, cz = corner[1], corner[2], corner[3] + -- the u and v edge vectors + local ux = if u == 0 then w else 0 + local uy = if u == 1 then w else 0 + local uz = if u == 2 then w else 0 + local vx = if v == 0 then h else 0 + local vy = if v == 1 then h else 0 + local vz = if v == 2 then h else 0 + local nsign = if m > 0 then 1 else -1 + local nx = if d == 0 then nsign else 0 + local ny = if d == 1 then nsign else 0 + local nz = if d == 2 then nsign else 0 + local col = if m > 0 then m else -m + local vb = quads * 48 + local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale + writef32(pos, vb, px0) + writef32(pos, vb + 4, py0) + writef32(pos, vb + 8, pz0) + writef32(pos, vb + 12, px0 + ux * scale) + writef32(pos, vb + 16, py0 + uy * scale) + writef32(pos, vb + 20, pz0 + uz * scale) + writef32(pos, vb + 24, px0 + (ux + vx) * scale) + writef32(pos, vb + 28, py0 + (uy + vy) * scale) + writef32(pos, vb + 32, pz0 + (uz + vz) * scale) + writef32(pos, vb + 36, px0 + vx * scale) + writef32(pos, vb + 40, py0 + vy * scale) + writef32(pos, vb + 44, pz0 + vz * scale) + for k = 0, 3 do + writef32(nrm, vb + k * 12, nx) + writef32(nrm, vb + k * 12 + 4, ny) + writef32(nrm, vb + k * 12 + 8, nz) + writeu8(idx, quads * 4 + k, col) + end + local v0 = quads * 4 + local ib = quads * 24 + if m > 0 then + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 1) + writeu32(tri, ib + 8, v0 + 2) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 2) + writeu32(tri, ib + 20, v0 + 3) + else + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 2) + writeu32(tri, ib + 8, v0 + 1) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 3) + writeu32(tri, ib + 20, v0 + 2) + end + quads += 1 + i += w + end + end + end + end + end + end + return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads } +end + +return Greedy +end +__FILES["ops/MusicOps"] = function() + +-- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the +-- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, +-- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / +-- addInstrument / note in the api (also F.ops.music). +-- +-- local M = require("@rosetta/ops/MusicOps") +-- local song = M.new({ format = "mod", channels = 4, title = "demo" }) +-- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 +-- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list +-- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) +-- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod +-- +-- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample +-- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 +-- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering +-- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG. +local Err = __include("core/Err") +local Tracker = __include("codecs/audio/Tracker") + +local MusicOps = {} + +local FORMATS = { mod = true, xm = true, s3m = true, it = true } + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +local function isModule(m: any): boolean + -- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four) + return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table" +end + +local function int(v: any, lo: number, hi: number): boolean + return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi +end + +-- ------------------------------------------------------------------------------------------------ module +type NewOptions = { + format: string?, -- "mod" (default), "xm", "s3m", "it": the effect family (mod and xm can be saved) + channels: number?, -- 1..32 for mod, else 1..64 (default 4) + title: string?, + speed: number?, -- ticks per row (default 6) + tempo: number?, -- BPM (default 125) +} + +-- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format +function MusicOps.new(opts: NewOptions?): (any, Err.Err?) + local o: NewOptions = opts or {} + local format = o.format or "mod" + if not FORMATS[format] then + return bad("new: format must be mod, xm, s3m or it") + end + local channels = o.channels or 4 + if not int(channels, 1, if format == "mod" then 32 else 64) then + return bad("new: bad channel count") + end + local m = Tracker.newModule(format, channels) + m.title = if type(o.title) == "string" then o.title else "" + if o.speed ~= nil then + if not int(o.speed, 1, 255) then + return bad("new: speed must be 1..255") + end + m.speed = o.speed + end + if o.tempo ~= nil then + if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then + return bad("new: tempo must be 32..1000") + end + m.tempo = o.tempo + end + m.meta = { source = { format = format } } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ patterns +-- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). +-- The pattern is appended to the order list unless opts.order == false. +function MusicOps.addPattern(m: any, rows: number?, opts: { order: boolean? }?): (number?, Err.Err?) + if not isModule(m) then + return bad("addPattern: needs a tracker Module") + end + local n = rows or 64 + if not int(n, 1, 1024) then + return bad("addPattern: rows must be 1..1024") + end + table.insert(m.patterns, Tracker.newPattern(n, m.channels)) + local index = #m.patterns - 1 + if not (opts and opts.order == false) then + table.insert(m.order, index) + end + return index, nil +end + +local NAMES: { [string]: number } = { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } +local SPECIAL: { [string]: number } = { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } + +-- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, +-- "Db4" = 50, "off", "cut", "fade" +function MusicOps.note(v: any): (number?, Err.Err?) + if type(v) == "number" then + if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then + return v, nil + end + return bad("note: number must be 0..120 or 253..255") + end + if type(v) ~= "string" then + return bad("note: expected a number or a name") + end + local s = string.lower(v) + if SPECIAL[s] then + return SPECIAL[s], nil + end + local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$") + if not letter then + return bad("note: bad name " .. v) + end + local n = NAMES[letter :: string] + (if acc == "#" then 1 elseif acc == "b" then -1 else 0) + local num = 1 + (tonumber(oct) :: number) * 12 + n + if num < 1 or num > 120 then + return bad("note: out of range " .. v) + end + return num, nil +end + +type Cell = { + note: (number | string)?, -- 0 / nil = none + instrument: number?, -- 1-based sample (MOD / S3M) or instrument (XM / IT); 0 = none + volume: number?, -- the volume column as the format stores it (0 = none) + effect: number?, -- the format's effect number (MOD / XM 0..35; S3M / IT 1..26) + param: number?, -- 0..255 +} + +local function patternAt(m: any, pattern: any, row: any, channel: any): (any, Err.Err?) + if not isModule(m) then + return bad("needs a tracker Module") + end + local p: any = if int(pattern, 0, 1e6) then m.patterns[pattern + 1] else nil + if p == nil then + return bad("no pattern " .. tostring(pattern)) + end + if not int(row, 0, p.rows - 1) then + return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1)) + end + if not int(channel, 1, m.channels) then + return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels) + end + return p, nil +end + +-- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) +function MusicOps.setCell(m: any, pattern: number, row: number, channel: number, cell: Cell): (boolean?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + if type(cell) ~= "table" then + return bad("setCell: cell must be a table") + end + local note = 0 + if cell.note ~= nil then + local n, nerr = MusicOps.note(cell.note) + if not n then + return nil, nerr + end + note = n + end + for _, k in { "instrument", "volume", "effect", "param" } do + local v = (cell :: any)[k] + if v ~= nil and not int(v, 0, 255) then + return bad("setCell: " .. k .. " must be 0..255") + end + end + Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0) + return true, nil +end + +-- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err +function MusicOps.getCell(m: any, pattern: number, row: number, channel: number): (Cell?, Err.Err?) + local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) + return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil +end + +-- ------------------------------------------------------------------------------------------------ samples +type SampleSpec = { + name: string?, + audio: any?, -- an Audio (1 or 2 channels): the sample data and, unless rate is given, its rate + data: buffer?, -- or raw f32 frames (interleaved when channels = 2) ... + length: number?, -- ... with their frame count (default: the whole buffer) + channels: number?, -- 1 (default) or 2, for data + rate: number?, -- Hz the sample plays at on C-4 (MOD / XM) or C-5 (S3M / IT); default the Audio's, else 8363 + loop: string?, -- "none" (default), "forward", "pingpong" + loopStart: number?, -- frames (default 0) + loopEnd: number?, -- frames, exclusive (default the length) + volume: number?, -- 0..64 (default 64) + pan: number?, -- 0..256 (XM / IT; nil = the channel's) + bits: number?, -- 8 or 16: what writers store (default 8 for MOD, else 16) +} + +local LOOPS: { [string]: number } = { none = 0, forward = 1, pingpong = 2 } + +-- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for +-- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, +-- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). +function MusicOps.addSample(m: any, spec: SampleSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addSample: needs a tracker Module") + end + if type(spec) ~= "table" then + return bad("addSample: spec must be a table") + end + local data: buffer, length: number, channels: number + local rate = spec.rate + local a = spec.audio + if a ~= nil then + if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then + return bad("addSample: audio must be a mono or stereo Audio") + end + data, length, channels = a.samples, a.frames, a.channels + rate = rate or a.sampleRate + elseif type(spec.data) == "buffer" then + channels = spec.channels or 1 + if channels ~= 1 and channels ~= 2 then + return bad("addSample: channels must be 1 or 2") + end + local d: buffer = spec.data + length = spec.length or buffer.len(d) // (4 * channels) + if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then + return bad("addSample: data shorter than length") + end + data = d + else + return bad("addSample: needs audio or data") + end + rate = rate or 8363 + if type(rate) ~= "number" or rate < 1 or rate > 1e7 then + return bad("addSample: bad rate") + end + local s = Tracker.newSample(spec.name) + local copy = buffer.create(length * channels * 4) + buffer.copy(copy, 0, data, 0, length * channels * 4) + s.data, s.length, s.channels = copy, length, channels + s.bits = spec.bits or (if Tracker.family(m) == "mod" then 8 else 16) + if s.bits ~= 8 and s.bits ~= 16 then + return bad("addSample: bits must be 8 or 16") + end + s.c5speed = rate + local semis = 12 * math.log(rate / 8363) / math.log(2) + local rn = math.floor(semis + 0.5) + if rn < -96 or rn > 95 then + return bad("addSample: rate out of range") + end + s.relativeNote = rn + s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127) + local lt = LOOPS[spec.loop or "none"] + if lt == nil then + return bad("addSample: loop must be none, forward or pingpong") + end + if lt > 0 then + local ls, le = spec.loopStart or 0, spec.loopEnd or length + if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then + return bad("addSample: bad loop") + end + s.loopStart, s.loopEnd, s.loopType = ls, le, lt + end + if spec.volume ~= nil then + if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then + return bad("addSample: volume must be 0..64") + end + s.volume = spec.volume + end + if spec.pan ~= nil then + if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then + return bad("addSample: pan must be 0..256") + end + s.pan = spec.pan + end + table.insert(m.samples, s) + return #m.samples, nil +end + +-- ------------------------------------------------------------------------------------------------ instruments +type InstrumentSpec = { + name: string?, + sample: number?, -- the sample every note plays (1-based) + samples: { [number]: number }?, -- or a keymap: note number -> sample number (other notes: none) + fadeout: number?, -- volume fade per tick after key off, as the format stores it (XM 0..4095, IT 0..1024) + envelope: { points: { { number } }, sustain: number?, loopStart: number?, loopEnd: number? }?, -- volume + -- envelope: points { tick, 0..64 } with ticks increasing; sustain / loop points are 1-based point indexes +} + +-- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / +-- S3M cells name samples directly). +function MusicOps.addInstrument(m: any, spec: InstrumentSpec): (number?, Err.Err?) + if not isModule(m) then + return bad("addInstrument: needs a tracker Module") + end + if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then + return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") + end + if type(spec) ~= "table" then + return bad("addInstrument: spec must be a table") + end + local ins = Tracker.newInstrument(spec.name) + if spec.sample ~= nil then + if not int(spec.sample, 1, #m.samples) then + return bad("addInstrument: no sample " .. tostring(spec.sample)) + end + for n = 1, 120 do + ins.sampleMap[n] = spec.sample + end + elseif type(spec.samples) == "table" then + for note, smp in spec.samples do + if not int(note, 1, 120) or not int(smp, 0, #m.samples) then + return bad("addInstrument: bad keymap entry") + end + ins.sampleMap[note] = smp + end + end + if spec.fadeout ~= nil then + if not int(spec.fadeout, 0, 65535) then + return bad("addInstrument: bad fadeout") + end + ins.fadeout = spec.fadeout + end + local e = spec.envelope + if e ~= nil then + if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then + return bad("addInstrument: envelope needs points") + end + local env = Tracker.newEnvelope() + local last = -1 + for i, pt in e.points do + local tick: any, value: any = nil, nil + if type(pt) == "table" then + tick, value = pt[1], pt[2] + end + if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick :: number) <= last then + return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks") + end + last = tick :: number + env.ticks[i], env.values[i] = tick, value + end + env.enabled = true + local n = #e.points + if e.sustain ~= nil then + if not int(e.sustain, 1, n) then + return bad("addInstrument: bad sustain point") + end + env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain + end + if e.loopStart ~= nil or e.loopEnd ~= nil then + local ls, le = e.loopStart or 1, e.loopEnd or n + if not int(ls, 1, n) or not int(le, ls, n) then + return bad("addInstrument: bad envelope loop") + end + env.loop, env.loopStart, env.loopEnd = true, ls, le + end + ins.volEnv = env + end + table.insert(m.instruments, ins) + return #m.instruments, nil +end + +return MusicOps +end +__FILES["playlist/m3u"] = function() + +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no +-- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain +-- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / +-- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media +-- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, +-- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, +-- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. +-- +-- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) +-- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" +-- local out = M3u.encode(pl, { title = "My Mix" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local M3u = { + name = "m3u", + category = "playlist", + extensions = { "m3u", "m3u8" }, + mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} +type EncodeOptions = { + title: string?, -- #PLAYLIST: (default: the playlist's title) +} + +-- ------------------------------------------------------------------------------------------------ constants +local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } + +-- The extension of a URL's path (lower case), or nil +local function extension(url: string): string? + local p = Url.split(url).path + local ext = string.match(p, "%.([%w]+)$") + return if ext then string.lower(ext) else nil +end + +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s: string): { [string]: string } + local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq :: number) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:[ attr="v" ...], +local function extinf(rest: string): (number?, string?) + -- the first comma outside quoted attribute values + local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = if comma then string.sub(rest, 1, comma - 1) else rest + local title = if comma then Text.trim(string.sub(rest, comma + 1)) else nil + local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), if title and title ~= "" then title else nil +end + + +-- ------------------------------------------------------------------------------------------------ sniff +function M3u.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 512) + s = (string.match(s, "^%s*(.*)$") :: string) + if string.sub(s, 1, 7) == "#EXTM3U" then + return 0.95 + end + if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseM3u(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} } + local pendingDur, pendingTitle = nil, nil + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local upper = string.upper(string.sub(l, 1, 10)) + if string.sub(upper, 1, 8) == "#EXTINF:" then + pendingDur, pendingTitle = extinf(string.sub(l, 9)) + elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then + res.title = Text.trim(string.sub(l, 11)) + end + -- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + e.title = pendingTitle + e.duration = pendingDur + pendingDur, pendingTitle = nil, nil + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + return res +end + +local function parseHls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local hls: Hls = { master = false, endList = false, encrypted = false } + local res: Result = { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} } + local pendingDur, pendingTitle, pendingRange = nil, nil, nil + local pendingStream: { [string]: string }? = nil + local lastRangeEnd: number? = nil + local total = 0 + local formats = {} + local fmp4 = false + for n, line in ls do + local l = Text.trim(line) + if l == "" then + continue + end + if string.sub(l, 1, 1) == "#" then + local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$") + tag = if tag then string.upper(tag) else nil + if tag == "#EXT-X-STREAM-INF" then + hls.master = true + pendingStream = attributes(rest :: string) + elseif tag == "#EXT-X-MEDIA" then + hls.master = true + local a = attributes(rest :: string) + if a.URI then + local e: Entry = Url.locate(a.URI, base, baseScheme) + e.title = a.NAME + e.attributes = a + e.codecs = a.CODECS + table.insert(res.entries, e) + end + elseif tag == "#EXT-X-TARGETDURATION" then + hls.targetDuration = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-MEDIA-SEQUENCE" then + hls.mediaSequence = tonumber(Text.trim(rest :: string)) + elseif tag == "#EXT-X-ENDLIST" then + hls.endList = true + elseif tag == "#EXT-X-KEY" then + local a = attributes(rest :: string) + if a.METHOD and string.upper(a.METHOD) ~= "NONE" then + if not hls.encrypted then + table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD)) + end + hls.encrypted = true + end + elseif tag == "#EXT-X-MAP" then + fmp4 = true + elseif tag == "#EXTINF" then + pendingDur, pendingTitle = extinf(rest :: string) + elseif tag == "#EXT-X-BYTERANGE" then + local len, off = string.match(rest :: string, "^%s*(%d+)@?(%d*)") + if len then + local o = tonumber(off) or lastRangeEnd + pendingRange = { length = tonumber(len) :: number, offset = o } + lastRangeEnd = (o or 0) + (tonumber(len) :: number) + end + end + continue + end + local e: Entry = Url.locate(l, base, baseScheme) + if pendingStream then + e.attributes = pendingStream + e.bandwidth = tonumber(pendingStream.BANDWIDTH) + e.codecs = pendingStream.CODECS + e.title = pendingStream.NAME + pendingStream = nil + else + e.title = pendingTitle + e.duration = pendingDur + e.byteRange = pendingRange + if pendingDur then + total += pendingDur + end + local ext = extension(e.url) or "?" + formats[ext] = true + if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then + e.playable = false + e.reason = "segment format " .. (if fmp4 then "fmp4" else ext) + end + if e.playable and hls.encrypted then + e.playable = false + e.reason = "encrypted" + end + end + pendingDur, pendingTitle, pendingRange = nil, nil, nil + table.insert(res.entries, e) + if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end + end + if not hls.master then + hls.totalDuration = total + local list = {} + for ext in formats do + table.insert(list, ext) + end + table.sort(list) + hls.segmentFormat = if #list == 1 then list[1] elseif #list == 0 then nil else "mixed" + local bad = {} + for _, ext in list do + if UNSUPPORTED_SEGMENTS[ext] then + table.insert(bad, "." .. ext) + end + end + if fmp4 then + table.insert(bad, "fMP4 (EXT-X-MAP)") + end + if #bad > 0 then + table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ") + .. ": only mp3 segments can be played (concatenated)") + end + if not hls.endList then + table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments") + end + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function M3u.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local ls = Text.lines(t) + local res = if string.find(t, "#EXT%-X%-") then parseHls(ls, base, baseScheme, warnings) else parseM3u(ls, base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "m3u", hls = res.format == "hls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1. +-- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. +local function serialize(entries: { any }, opts: { title: string? }?): string + local out = { "#EXTM3U" } + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + if opts and opts.title then + table.insert(out, "#PLAYLIST:" .. clean(opts.title)) + end + for _, e in entries or {} do + if type(e) ~= "table" or type(e.url) ~= "string" then + continue + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + if e.title or d then + table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or "")))) + end + table.insert(out, clean(e.url)) + end + return table.concat(out, "\n") .. "\n" +end + +-- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of +-- entries ({ url, title?, duration? }) +function M3u.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local title = if opts and opts.title then opts.title else value.title + return buffer.fromstring(serialize(entries, { title = if type(title) == "string" then title else nil })), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +M3u.Url = Url + +return M3u +end +__FILES["playlist/pls"] = function() + +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case +-- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / +-- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. +-- +-- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) +-- local out = Pls.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local Pls = { + name = "pls", + category = "playlist", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Entry = { + url: string, + title: string?, + duration: number?, -- seconds; nil when unknown (-1 in the file) + playable: boolean, -- an http(s) URL the player can fetch + reason: string?, -- why not playable: "local path", "relative path without a base URL", "scheme ftp", ... + -- HLS + bandwidth: number?, -- master: BANDWIDTH + codecs: string?, -- master: CODECS + attributes: { [string]: string }?, -- master: the whole EXT-X-STREAM-INF / EXT-X-MEDIA attribute list + byteRange: { length: number, offset: number? }?, -- media: EXT-X-BYTERANGE +} + +type Hls = { + master: boolean, + targetDuration: number?, + mediaSequence: number?, + endList: boolean, -- media playlist: EXT-X-ENDLIST seen (false = live, the playlist grows) + encrypted: boolean, -- EXT-X-KEY with a METHOD other than NONE + totalDuration: number?, -- media: sum of the segment durations + segmentFormat: string?, -- media: the segments' common extension ("mp3", "ts", "aac", ...) or "mixed" +} + +type Result = { + kind: "playlist", + format: "m3u" | "pls" | "hls" | "xspf", + meta: { [string]: any }, + entries: { Entry }, + warnings: { string }, + title: string?, -- #PLAYLIST: / PLS has none + hls: Hls?, +} + +type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative entries + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local function duration(s: string?): number? + local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Pls.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 64) + local first = string.match(s, "^%s*([^\r\n]*)") + return if first and string.lower(Text.trim(first)) == "[playlist]" then 0.95 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parsePls(ls: { string }, base: string?, baseScheme: string?, warnings: { string }): Result + local res: Result = { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } + local files: { [number]: string }, titles: { [number]: string }, lengths: { [number]: string } = {}, {}, {} + local declared = nil + for _, line in ls do + local l = Text.trim(line) + if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then + continue + end + local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$") + if not key then + continue + end + local k = string.lower(Text.trim(key :: string)) + local name, idx = string.match(k, "^(%a+)(%d+)$") + local i = tonumber(idx) + if name == "file" and i then + files[i] = value + elseif name == "title" and i then + titles[i] = value + elseif name == "length" and i then + lengths[i] = value + elseif k == "numberofentries" then + declared = tonumber(value) + end + end + local order = {} + for i in files do + table.insert(order, i) + end + table.sort(order) + for _, i in order do + local e: Entry = Url.locate(files[i], base, baseScheme) + local t = titles[i] and Text.trim(titles[i]) + e.title = if t and t ~= "" then t else nil + e.duration = duration(lengths[i]) + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url)) + end + end + if declared and declared ~= #order then + table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order)) + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function Pls.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local res = parsePls(Text.lines(t), base, baseScheme, warnings) + local nLocal = 0 + for _, e in res.entries do + if e.reason == "local path" then + nLocal += 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + res.meta.source = { format = "pls" } + return res :: any, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a +-- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. +function Pls.encode(value: any, _opts: any?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local function clean(s: string): string + return (string.gsub(s, "[\r\n]+", " ")) + end + local out = { "[playlist]" } + local n = 0 + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + n += 1 + table.insert(out, string.format("File%d=%s", n, clean(e.url))) + if type(e.title) == "string" then + table.insert(out, string.format("Title%d=%s", n, clean(e.title))) + end + local d = tonumber(e.duration) + local secs = if d and d >= 0 and d == d and d ~= math.huge then math.floor(d + 0.5) else -1 + table.insert(out, string.format("Length%d=%d", n, secs)) + end + end + table.insert(out, "NumberOfEntries=" .. n) + table.insert(out, "Version=2") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Pls +end +__FILES["playlist/xspf"] = function() + +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau +-- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, +-- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, +-- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other +-- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. +-- +-- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) +-- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end +-- local out = Xspf.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local Xspf = { + name = "xspf", + category = "playlist", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + baseUrl: string?, -- the playlist's own URL (or Windows path), for relative locations + maxBytes: number?, -- refuse bigger files (default 64 MB) +} + +-- ------------------------------------------------------------------------------------------------ constants +local NS = "http://xspf.org/ns/0/" +local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" } +local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$") :: string) +end + +-- the text of the first child element with this local name, trimmed (nil when missing or empty) +local function field(node: any, name: string): string? + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + local s = trim(Xml.text(c)) + return if s ~= "" then s else nil + end + end + return nil +end + +local function elements(node: any, name: string): { any } + local out = {} + for _, c in node.children do + if type(c) == "table" and Xml.localName(c.name) == name then + table.insert(out, c) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Xspf.sniff(r: Bytes.Reader): number + local s = r:peek(1024) + local i = string.find(s, "<%w*:?playlist[%s>]") + if i and string.find(s, NS, 1, true) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd +-- tracks become warnings) +function Xspf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Playlist?, Err.Err?) + local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local doc, err = Xml.decode(r:string(n)) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or Xml.localName(root.name) ~= "playlist" then + return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>") + end + local warnings: { string } = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local function withXmlBase(node: any, b: string?, s: string?): (string?, string?) + local xb = node.attrs and node.attrs["xml:base"] + if type(xb) ~= "string" or xb == "" then + return b, s + end + local l = Url.locate(xb, b, s) + if Url.scheme(l.url) then + return l.url, Url.scheme(l.url) + end + return b, s + end + local pbase, pscheme = withXmlBase(root, base, baseScheme) + local pl: any = { + kind = "playlist", + format = "xspf", + entries = {}, + warnings = warnings, + title = field(root, "title"), + meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } }, + } + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + pl.meta[k] = field(root, k) + end + end + local nLocal = 0 + for _, list in elements(root, "trackList") do + for i, track in elements(list, "track") do + local tbase, tscheme = withXmlBase(track, pbase, pscheme) + local locs: { string } = {} + for _, l in elements(track, "location") do + local s = trim(Xml.text(l)) + if s ~= "" then + table.insert(locs, s) + end + end + if #locs == 0 then + table.insert(warnings, string.format("track %d: no location", i)) + else + local e: any = Url.locate(locs[1], tbase, tscheme) + for _, k in TRACK_FIELDS do + e[k] = field(track, k) + end + local d = tonumber(field(track, "duration")) + e.duration = if d and d >= 0 and d == d and d ~= math.huge then d / 1000 else nil + e.trackNum = tonumber(field(track, "trackNum")) + if #locs > 1 then + local all = {} + for _, l in locs do + table.insert(all, Url.locate(l, tbase, tscheme).url) + end + e.locations = all + end + if e.reason == "local path" then + nLocal += 1 + elseif e.reason then + table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url)) + end + table.insert(pl.entries, e) + end + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, if nLocal == 1 then "" else "s")) + end + return pl, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list +-- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. +function Xspf.encode(value: any, opts: { indent: number?, title: string? }?): (buffer?, Err.Err?) + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = if type(value.entries) == "table" then value.entries else value + local root = Xml.element("playlist", { version = "1", xmlns = NS }) + local function add(parent: any, name: string, v: any) + if type(v) == "string" and v ~= "" then + Xml.append(parent, Xml.element(name, nil, { v })) + elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) })) + end + end + local title = if opts and opts.title then opts.title else value.title + add(root, "title", title) + local meta = if type(value.meta) == "table" then value.meta else {} + for _, k in PLAYLIST_FIELDS do + if k ~= "title" then + add(root, k, meta[k]) + end + end + local list = Xml.append(root, Xml.element("trackList")) + for _, e in entries do + if type(e) == "table" and type(e.url) == "string" then + local tr = Xml.append(list, Xml.element("track")) + add(tr, "location", e.url) + if type(e.locations) == "table" then + for i = 2, #e.locations do + add(tr, "location", e.locations[i]) + end + end + for _, k in TRACK_FIELDS do + add(tr, k, e[k]) + end + local d = tonumber(e.duration) + if d and d >= 0 then + add(tr, "duration", d * 1000) + end + add(tr, "trackNum", tonumber(e.trackNum)) + end + end + local s = Xml.encode(Xml.document(root), { indent = if opts and opts.indent ~= nil then opts.indent else 2 }) + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "encode: the XML serializer failed") + end + return buffer.fromstring(s), nil +end + +return Xspf +end +__FILES["subtitle/ass"] = function() + +-- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of +-- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] +-- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the +-- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any +-- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. +-- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become +-- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. +-- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, +-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: +-- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Ass = { + name = "ass", + category = "subtitle", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +type EncodeOptions = { + crlf: boolean?, -- CRLF line ends (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" } +local STYLE_DEFAULT: { [string]: string } = { + Name = "Default", + Fontname = "Arial", + Fontsize = "16", + PrimaryColour = "&Hffffff", + SecondaryColour = "&Hffffff", + OutlineColour = "&H0", + TertiaryColour = "&H0", + BackColour = "&H0", + Bold = "0", + Italic = "0", + Underline = "0", + StrikeOut = "0", + ScaleX = "100", + ScaleY = "100", + Spacing = "0", + Angle = "0", + BorderStyle = "1", + Outline = "1", + Shadow = "0", + Alignment = "2", + MarginL = "10", + MarginR = "10", + MarginV = "10", + AlphaLevel = "0", + Encoding = "0", +} +local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } +-- event fields -> cue keys (the rest keep their field name) +local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } + +local function trim(s: string): string + return (string.match(s, "^%s*(.-)%s*$")) :: string +end + +local function fields(s: string): { string } + local out = {} + for _, f in string.split(s, ",") do + table.insert(out, trim(f)) + end + return out +end + +-- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil +local function time(s: string): number? + local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") + if not h then + return nil + end + local fr = if f ~= "" then (tonumber(f) :: number) / 10 ^ #(f :: string) else 0 + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + fr +end + +-- ASS text -> the shared markup +local TAGS = { i = "i", b = "b", u = "u", s = "s" } +function Ass.toMarkup(raw: string): string + local open: { [string]: boolean } = {} + local out = string.gsub(raw, "{([^}]*)}", function(block: string): string + local acc = {} + for tag, arg in string.gmatch(block, "\\(%a+)([^\\]*)") do + local t = TAGS[tag] + if t then + local on = arg == "" or (tonumber(arg) or 0) ~= 0 + if arg == "" then + on = not open[t] + end + if on and not open[t] then + table.insert(acc, "<" .. t .. ">") + open[t] = true + elseif not on and open[t] then + table.insert(acc, "</" .. t .. ">") + open[t] = false + end + elseif tag == "r" then + for _, k in { "s", "u", "b", "i" } do + if open[k] then + table.insert(acc, "</" .. k .. ">") + open[k] = false + end + end + end + end + return table.concat(acc) + end) + out = string.gsub(out, "\\[Nn]", "\n") + out = string.gsub(out, "\\h", "\194\160") + for _, k in { "s", "u", "b", "i" } do + if open[k] then + out ..= "</" .. k .. ">" + end + end + return out +end + +-- the shared markup -> ASS text +function Ass.fromMarkup(text: string): string + local s = string.gsub(text, "\r\n?", "\n") + s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close: string, tag: string): string + local t = TAGS[string.lower(tag)] + if not t then + return "" + end + return "{\\" .. t .. (if close == "/" then "0" else "1") .. "}" + end) + s = string.gsub(s, "\n", "\\N") + return s +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ass.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 64) + if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ass.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Ass.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local subs = Types.Subtitles.new() + local info: { [string]: string } = {} + local infoOrder: { string } = {} + local styleFormat: { string }? = nil + local styleOrder: { string } = {} + local eventFormat: { string } = EVENT_FORMAT + local comments = {} + local sections: { { name: string, lines: { string } } } = {} + local section = "" + local stylesName: string? = nil + for _, line in string.split(s, "\n") do + local name = string.match(line, "^%s*%[(.-)%]%s*$") + if name then + section = string.lower(name) + if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then + stylesName = name + section = "styles" + elseif section ~= "script info" and section ~= "events" then + table.insert(sections, { name = name, lines = {} :: { string } }) + end + continue + end + if section == "script info" then + if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then + table.insert(infoOrder, line) -- a comment line, kept in place + else + local k, v = string.match(line, "^([^:]+):%s?(.*)$") + if k then + k = trim(k) + if info[k] == nil then + table.insert(infoOrder, k) + end + info[k] = v :: string + end + end + elseif section == "styles" then + local k, v = string.match(line, "^%s*(%a+):%s*(.*)$") + if k == "Format" then + styleFormat = fields(v :: string) + elseif k == "Style" then + local fmt = styleFormat or STYLE_FORMAT + local vals = string.split(v :: string, ",") + local st: { [string]: string } = {} + for fi, f in fmt do + st[f] = trim(vals[fi] or "") + end + local sname = st.Name or "" + if subs.styles[sname] == nil then + table.insert(styleOrder, sname) + end + subs.styles[sname] = st + end + elseif section == "events" then + local k, v = string.match(line, "^%s*(%a+):%s?(.*)$") + if k == "Format" then + eventFormat = fields(v :: string) + elseif k == "Dialogue" or k == "Comment" then + local vals: { string } = {} + local rest = v :: string + for fi = 1, #eventFormat do + if fi == #eventFormat then + vals[fi] = rest + else + local c = string.find(rest, ",", 1, true) + if not c then + vals[fi] = rest + rest = "" + else + vals[fi] = string.sub(rest, 1, c - 1) + rest = string.sub(rest, c + 1) + end + end + end + local cue: { [string]: any } = { text = "", start = 0, stop = 0 } + local ok = true + for fi, f in eventFormat do + local val = vals[fi] or "" + if f == "Start" or f == "End" then + local t = time(val) + if not t then + ok = false + else + cue[if f == "Start" then "start" else "stop"] = t + end + elseif f == "Text" then + cue.raw = val + cue.text = Ass.toMarkup(val) + elseif f == "Style" then + cue.style = trim(val) + elseif f == "Layer" then + cue.layer = tonumber(trim(val)) or 0 + else + cue[EVENT_KEY[f] or f] = trim(val) + end + end + if ok then + if k == "Comment" then + cue.after = #subs.cues -- written back after that many dialogue lines + table.insert(comments, cue) + else + table.insert(subs.cues, cue :: any) + end + end + end + elseif section ~= "" then + table.insert(sections[#sections].lines, line) + end + end + subs.meta.scriptInfo = info + subs.meta.scriptInfoOrder = infoOrder + subs.meta.styleFormat = styleFormat + subs.meta.styleOrder = styleOrder + subs.meta.stylesSection = stylesName + subs.meta.eventFormat = eventFormat + if #comments > 0 then + subs.meta.comments = comments + end + if #sections > 0 then + -- drop trailing blank lines (the writer adds its own) + for _, sec in sections do + while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do + table.remove(sec.lines) + end + end + subs.meta.sections = sections + end + subs.meta.source = { format = "ass", scriptType = info.ScriptType } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local cs = math.floor(t * 100 + 0.5) + return string.format("%d:%02d:%02d.%02d", cs // 360000, cs // 6000 % 60, cs // 100 % 60, cs % 100) +end + +local function field(v: any): string + return (string.gsub(tostring(v), "[\r\n,]", " ")) +end + +function Ass.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = { "[Script Info]" } + local info: any = if type(meta.scriptInfo) == "table" then meta.scriptInfo else {} + local order = if type(meta.scriptInfoOrder) == "table" then meta.scriptInfoOrder else {} + local written: { [string]: boolean } = {} + if info.ScriptType == nil then + table.insert(out, "ScriptType: v4.00+") + end + for _, k in order do + if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then + table.insert(out, k) + elseif info[k] ~= nil and not written[k] then + table.insert(out, k .. ": " .. tostring(info[k])) + written[k] = true + end + end + local rest = {} + for k, v in info do + if not written[k] and type(k) == "string" then + table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " ")) + end + end + table.sort(rest) + table.move(rest, 1, #rest, #out + 1, out) + -- styles + local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" + local sfmt: { string } = if type(meta.styleFormat) == "table" then meta.styleFormat else STYLE_FORMAT + table.insert(out, "") + table.insert(out, "[" .. (if type(meta.stylesSection) == "string" then meta.stylesSection elseif ssa then "V4 Styles" else "V4+ Styles") .. "]") + table.insert(out, "Format: " .. table.concat(sfmt, ", ")) + local names: { string } = {} + local seen: { [string]: boolean } = {} + if type(meta.styleOrder) == "table" then + for _, nm in meta.styleOrder do + if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then + table.insert(names, nm) + seen[nm] = true + end + end + end + local extra = {} + if type(subs.styles) == "table" then + for nm, st in subs.styles do + if type(nm) == "string" and type(st) == "table" and not seen[nm] then + table.insert(extra, nm) + end + end + end + table.sort(extra) + table.move(extra, 1, #extra, #names + 1, names) + if #names == 0 then + names = { "Default" } + end + for _, nm in names do + local st = if type(subs.styles) == "table" and type(subs.styles[nm]) == "table" then subs.styles[nm] else {} + local vals = {} + for fi, f in sfmt do + local v = if f == "Name" then nm else st[f] + vals[fi] = field(if v ~= nil then v else (STYLE_DEFAULT[f] or "0")) + end + table.insert(out, "Style: " .. table.concat(vals, ",")) + end + -- events + local efmt: { string } = if type(meta.eventFormat) == "table" then meta.eventFormat else EVENT_FORMAT + if efmt[#efmt] ~= "Text" then + return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") + end + table.insert(out, "") + table.insert(out, "[Events]") + table.insert(out, "Format: " .. table.concat(efmt, ", ")) + local function event(kind: string, c: any, i: number): Err.Err? + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local vals = {} + for fi, f in efmt do + local v: any + if f == "Start" then + v = stamp(c.start) + elseif f == "End" then + v = stamp(c.stop) + elseif f == "Style" then + v = field(c.style or names[1]) + elseif f == "Text" then + if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then + v = string.gsub(c.raw, "[\r\n]", " ") + else + v = Ass.fromMarkup(c.text) + end + elseif f == "Layer" then + v = tostring(tonumber(c.layer) or 0) + elseif f == "Marked" then + v = field(c.marked or "Marked=0") + else + local key = EVENT_KEY[f] or f + local x = c[key] + v = field(if x ~= nil then x elseif string.sub(f, 1, 6) == "Margin" then "0" else "") + end + vals[fi] = v + end + table.insert(out, kind .. ": " .. table.concat(vals, ",")) + return nil + end + local comments = if type(meta.comments) == "table" then meta.comments else {} + local function commentsAfter(n: number?): Err.Err? + for i, c in comments do + if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then + local e = event("Comment", c, i) + if e then + return e + end + end + end + return nil + end + for i = 0, #subs.cues do + local e = (if i > 0 then event("Dialogue", subs.cues[i], i) else nil) or commentsAfter(i) + if e then + return nil, e + end + end + local e = commentsAfter(nil) + if e then + return nil, e + end + if type(meta.sections) == "table" then + for _, sec in meta.sections do + if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then + table.insert(out, "") + table.insert(out, "[" .. sec.name .. "]") + for _, l in sec.lines do + table.insert(out, tostring(l)) + end + end + end + end + table.insert(out, "") + local nl = if opts and opts.crlf then "\r\n" else "\n" + return buffer.fromstring(table.concat(out, nl)), nil +end + +return Ass +end +__FILES["subtitle/srt"] = function() + +-- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or +-- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing +-- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends +-- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / +-- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. +-- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. +-- Not supported: positioning beyond keeping the coordinates; the tags are not validated. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Srt = { + name = "srt", + category = "subtitle", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +type EncodeOptions = { + crlf: boolean?, -- CRLF line ends (default false: LF) +} + +-- ------------------------------------------------------------------------------------------------ constants +local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" + +-- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) +local function text(r: Bytes.Reader): string? + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + return s +end + +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line: string): (number?, number?, string?) + local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) + if not h1 then + return nil, nil, nil + end + local a = tonumber(h1) :: number * 3600 + tonumber(m1) :: number * 60 + tonumber(s1) :: number + frac(f1 :: string) + local b = tonumber(h2) :: number * 3600 + tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string) + return a, b, rest +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Srt.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 512) + head = string.gsub(head, "\r", "\n") + local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)") + if first and string.match(first, "^%d+%s*$") and second and timing(second) then + return 0.9 + end + if first and timing(first) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Srt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + local s = text(r) + if not s then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + local i = 1 + local function isStart(k: number): boolean -- a cue starts at line k (index + timing, or a timing) + local l = lines[k] + if l == nil then + return false + end + if timing(l) then + return true + end + return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil + end + while i <= n do + local line = lines[i] + local a, b, settings = timing(line) + if a then + local id: string? = nil + if i > 1 then + local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$") + id = prev + end + i += 1 + local body = {} + while i <= n do + local l = lines[i] + if string.match(l, "^%s*$") then + -- blank: the end of the cue unless more text follows before the next cue + local k = i + while k <= n and string.match(lines[k], "^%s*$") do + k += 1 + end + if k > n or isStart(k) then + break + end + for _ = i, k - 1 do + table.insert(body, "") + end + i = k + elseif timing(l) then + break -- a cue without the blank separator + else + table.insert(body, l) + i += 1 + end + end + -- an index line right before the next timing belongs to the next cue + if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then + table.remove(body) + end + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(body, "\n"), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + else + i += 1 + end + end + if #subs.cues == 0 and string.find(s, "%S") then + return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)") + end + subs.meta.source = { format = "srt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d,%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +function Srt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local nl = if opts and opts.crlf then "\r\n" else "\n" + local out = table.create(#subs.cues) + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue + local body = string.gsub(c.text, "\r\n?", "\n") + local settings = if type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") then " " .. c.settings else "" + out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl + end + return buffer.fromstring(table.concat(out, nl) .. nl), nil +end + +return Srt +end +__FILES["subtitle/vtt"] = function() + +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in +-- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments +-- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept +-- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). +-- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text +-- are dropped and `-->` escaped (WebVTT cue text cannot hold them). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtt = { + name = "vtt", + category = "subtitle", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +type EncodeOptions = {} + +-- ------------------------------------------------------------------------------------------------ constants +local function frac(digits: string): number + return (tonumber(digits) :: number) / 10 ^ #digits +end + +-- one timestamp at the start of s: seconds, the rest | nil +local function timestamp(s: string): (number?, string) + local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") + if h then + return tonumber(h) :: number * 3600 + tonumber(m) :: number * 60 + tonumber(sec) :: number + frac(f :: string), rest :: string + end + local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") + if m2 then + return tonumber(m2) :: number * 60 + tonumber(s2) :: number + frac(f2 :: string), rest2 :: string + end + return nil, s +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line: string): (number?, number?, string?) + local a, rest = timestamp((string.gsub(line, "^%s+", ""))) + if not a then + return nil, nil, nil + end + local after = string.match(rest, "^%s*%-%->%s*(.*)$") + if not after then + return nil, nil, nil + end + local b, rest2 = timestamp(after) + if not b then + return nil, nil, nil + end + local settings = string.match(rest2, "^%s*(.-)%s*$") or "" + return a, b, settings +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtt.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 10) + if string.sub(head, 1, 6) == "WEBVTT" then + local c = string.sub(head, 7, 7) + if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vtt.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Subtitles?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Vtt.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + -- the header block: WEBVTT[ text] + lines up to the first blank + local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" } + local i = 2 + while i <= n and lines[i] ~= "" do + table.insert(header, lines[i]) + i += 1 + end + if #header > 1 or header[1] ~= "" then + subs.meta.header = table.concat(header, "\n") + end + local notes, css, regions = {}, {}, {} + while i <= n do + if lines[i] == "" then + i += 1 + continue + end + -- a block: lines up to the next blank + local first = i + while i <= n and lines[i] ~= "" do + i += 1 + end + local block = table.move(lines, first, i - 1, 1, {}) + local head = block[1] + if string.match(head, "^NOTE[ \t]") or head == "NOTE" then + table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", ""))) + elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(css, table.concat(block, "\n", 2)) + elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(regions, table.concat(block, "\n", 2)) + else + local k, id = 1, nil + local a, b, settings = timing(block[1]) + if not a and block[2] then + id = block[1] + k = 2 + a, b, settings = timing(block[2]) + end + if a then + local cue: Types.Cue = { start = a, stop = b :: number, text = table.concat(block, "\n", k + 1), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + end + -- a block with no timing is skipped (the spec's parser ignores it) + end + end + if #notes > 0 then + subs.meta.notes = notes + end + if #css > 0 then + subs.meta.css = css + end + if #regions > 0 then + subs.meta.regions = regions + end + subs.meta.source = { format = "vtt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t: number): string + local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d.%03d", ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000) +end + +-- one block's text: no blank lines (they end a block), no `-->` +local function clean(s: string): string + s = string.gsub(s, "\r\n?", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "^\n+", "") + s = string.gsub(s, "%-%->", "-->") + return s +end + +function Vtt.encode(subs: Types.Subtitles, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta: any = if type(subs.meta) == "table" then subs.meta else {} + local out = {} + local header = if type(meta.header) == "string" and meta.header ~= "" then meta.header else nil + if header then + local h = string.gsub(clean(header), "%-%->", "") + table.insert(out, "WEBVTT " .. h .. "\n") + else + table.insert(out, "WEBVTT\n") + end + for _, key in { "regions", "css" } do + local list = meta[key] + if type(list) == "table" then + for _, b in list do + if type(b) == "string" then + table.insert(out, (if key == "css" then "STYLE\n" else "REGION\n") .. clean(b) .. "\n") + end + end + end + end + for i, c in subs.cues do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local id = if type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) then (string.gsub(c.id, "[\r\n]", " ")) .. "\n" else "" + local settings = if type(c.settings) == "string" and c.settings ~= "" then " " .. (string.gsub(c.settings, "[\r\n]", " ")) else "" + local body = clean(c.text) + table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (if body ~= "" then "\n" else "")) + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Vtt +end +__FILES["vector/svg"] = function() + +-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs +-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg +-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from +-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / +-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and +-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path +-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). +-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and +-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. +-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also +-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Parse = __include("vector/svg/Parse") +local Render = __include("vector/svg/Render") +local Write = __include("vector/svg/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Svg = { + name = "svg", + category = "vector", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 64 MB) +} +type EncodeOptions = {} +type RasterizeOptions = Render.Options + +-- ------------------------------------------------------------------------------------------------ sniff +function Svg.sniff(r: Bytes.Reader): number + local h = Sniff.text(r, 4096) + if not string.match(h, "^%s*<") then + return 0 + end + if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Svg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Vector?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, xerr + end + local v, msg = Parse.document(doc) + if not v then + return nil, Err.new(Err.CORRUPT, msg or "bad SVG") + end + v.meta.source = { format = "svg" } + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?) + local s, err = Write.vector(v) + if not s then + return nil, Err.new(Err.ARG, err or "bad Vector") + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox +-- maps onto w x h by its preserveAspectRatio. +function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?) + if type(v) ~= "table" or type(v.paths) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Vector value") + end + local W = math.ceil(w or v.width or 0) + local H = math.ceil(h or v.height or 0) + if W < 1 or H < 1 or W * H > 2 ^ 26 then + return nil, Err.new(Err.ARG, "bad raster size") + end + return Render.rasterize(v, W, H, opts), nil +end + +return Svg +end +__FILES["vector/svg/Parse"] = function() + +-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, +-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space +-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into +-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a +-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. +-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. +-- Never throws. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Style = __include("vector/svg/Style") +local PathData = __include("vector/svg/PathData") + +local Parse = {} + +type Node = Types.XmlNode +type M = { number } + +local IDENTITY = { 1, 0, 0, 1, 0, 0 } +local mul = Style.multiply + +-- properties that inherit, and their initial values +local INHERITED: { [string]: string } = { + fill = "black", + ["fill-opacity"] = "1", + ["fill-rule"] = "nonzero", + stroke = "none", + ["stroke-width"] = "1", + ["stroke-opacity"] = "1", + ["stroke-linecap"] = "butt", + ["stroke-linejoin"] = "miter", + ["stroke-miterlimit"] = "4", + ["stroke-dasharray"] = "none", + ["stroke-dashoffset"] = "0", + ["clip-rule"] = "nonzero", + visibility = "visible", + color = "black", + ["font-size"] = "16", +} +-- not inherited (reset per element) +local LOCAL: { [string]: boolean } = { + opacity = true, + ["clip-path"] = true, + display = true, + ["stop-color"] = true, + ["stop-opacity"] = true, + mask = true, + filter = true, +} + +local UNSUPPORTED: { [string]: boolean } = { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } +local CONTAINERS = { g = true, a = true, switch = true } +local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true } + +type Ctx = { + ids: { [string]: Node }, + rules: { Style.Rule }, + vector: Types.Vector, + groups: { any }, + clips: { any }, + unsupported: { [string]: number }, + vw: number, -- the current viewport (for percentages) + vh: number, + depth: number, + useDepth: number, +} + +local function local_(n: Node): string + return Xml.localName(n.name) +end +local function attr(n: Node, k: string): string? + local a = n.attrs :: any + return a[k] +end +local function href(n: Node): string? + local h = attr(n, "href") or attr(n, "xlink:href") + if h == nil then + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and Xml.localName(k) == "href" then + return v + end + end + end + return h +end +local function refId(s: string?): string? + if s == nil then + return nil + end + return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") +end + +-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +local function specified(n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k, v in pairs(n.attrs :: any) do + if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then + out[k] = v + end + end + if #ctx.rules > 0 then + local classes: { [string]: boolean } = {} + for c in string.gmatch(attr(n, "class") or "", "%S+") do + classes[c] = true + end + local hits: { Style.Rule } = {} + for _, r in ctx.rules do + if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then + table.insert(hits, r) + end + end + table.sort(hits, function(a: any, b: any): boolean + if a.selector.specificity ~= b.selector.specificity then + return a.selector.specificity < b.selector.specificity + end + return a.order < b.order + end) + for _, r in hits do + for k, v in pairs(r.decls) do + out[k] = v + end + end + end + local st = attr(n, "style") + if st then + for k, v in pairs(Style.declarations(st)) do + out[k] = v + end + end + return out +end + +-- computed(parent, n) -> the element's computed property strings +local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string } + local out: { [string]: string } = {} + for k in pairs(INHERITED) do + out[k] = parent[k] + end + for k, v in pairs(specified(n, ctx)) do + if v == "inherit" then + out[k] = parent[k] + elseif INHERITED[k] or LOCAL[k] then + out[k] = v + end + end + return out +end + +local function len(s: string?, ref: number, st: { [string]: string }, default: number?): number? + local fs = Style.length(st["font-size"], 16) or 16 + local v = Style.length(s, ref, fs) + if v == nil then + return default + end + return v +end + +-- ------------------------------------------------------------------------------------------------ paints +local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number } } + local list = {} + local parentStyle = computed(INHERITED, g, ctx) + for _, s in Xml.children(g) do + if local_(s) == "stop" then + local st = computed(parentStyle, s, ctx) + local off = attr(s, "offset") or "0" + local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "") + local offset = if o then o / 100 else (tonumber(off) or 0) + offset = math.clamp(offset, 0, 1) + if #list > 0 and offset < list[#list][1] then + offset = list[#list][1] + end + local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 } + if col == "none" then + col = { 0, 0, 0, 0 } + end + local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1) + table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) }) + end + end + if #list == 0 then + local h = refId(href(g)) + local other = if h then ctx.ids[h] else nil + if other and not seen[other] then + seen[other] = true + return stops(other, ctx, seen) + end + end + return list +end + +-- a gradient attribute, looked up through href templates +local function gattr(g: Node, k: string, ctx: Ctx): string? + local cur: Node? = g + local guard = 0 + while cur and guard < 16 do + local v = attr(cur, k) + if v ~= nil then + return v + end + local h = refId(href(cur)) + cur = if h then ctx.ids[h] else nil + guard += 1 + end + return nil +end + +local function gradient(g: Node, opacity: number, ctx: Ctx): any + local kind = local_(g) + local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox" + local obb = units ~= "userSpaceOnUse" + local list = stops(g, ctx, { [g] = true }) + if #list == 0 then + return "none" + end + if #list == 1 then + local s = list[1] + return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } } + end + local function coord(k: string, default: string, ref: number): number + local v = gattr(g, k, ctx) or default + local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$") + if pct then + local x = tonumber(pct) or 0 + return if obb then x / 100 else x / 100 * ref + end + return Style.length(v, ref) or 0 + end + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local p: any = { + type = if kind == "linearGradient" then "linear" else "radial", + units = if obb then "objectBoundingBox" else "userSpaceOnUse", + spread = gattr(g, "spreadMethod", ctx) or "pad", + stops = list, + opacity = opacity, + } + local t = gattr(g, "gradientTransform", ctx) + if t then + p.transform = Style.transform(t) + end + if p.type == "linear" then + p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh) + p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh) + else + p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh) + p.r = coord("r", "50%", diag) + p.fx = if gattr(g, "fx", ctx) then coord("fx", "50%", ctx.vw) else p.cx + p.fy = if gattr(g, "fy", ctx) then coord("fy", "50%", ctx.vh) else p.cy + p.fr = coord("fr", "0%", diag) + end + return p +end + +-- paint(value, opacity, st) -> Paint | nil (none) +local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any + if value == nil then + return nil + end + local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$") + if id then + local fallback = string.match(value, "%)%s*(.-)%s*$") + local g = ctx.ids[id] + if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then + local p = gradient(g, opacity, ctx) + return if p == "none" then nil else p + end + if g and local_(g) == "pattern" then + ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1 + end + if fallback and fallback ~= "" then + return paint(fallback, opacity, st, ctx) + end + return nil + end + local c = Style.color(value, Style.color(st.color or "black") :: any) + if c == nil or c == "none" then + return nil + end + return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } } +end + +-- ------------------------------------------------------------------------------------------------ shapes +local function shape(n: Node, st: { [string]: string }, ctx: Ctx): { PathData.Cmd }? + local kind = local_(n) + local vw, vh = ctx.vw, ctx.vh + local diag = math.sqrt((vw * vw + vh * vh) / 2) + if kind == "path" then + local d = attr(n, "d") + if d == nil then + return nil + end + local cmds = PathData.parse(d) + return cmds + elseif kind == "rect" then + local x, y = len(attr(n, "x"), vw, st, 0) :: number, len(attr(n, "y"), vh, st, 0) :: number + local w, h = len(attr(n, "width"), vw, st, 0) :: number, len(attr(n, "height"), vh, st, 0) :: number + if w <= 0 or h <= 0 then + return nil + end + local rx: number?, ry: number? = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + if rx and rx < 0 then + rx = nil + end + if ry and ry < 0 then + ry = nil + end + rx = rx or ry or 0 + ry = ry or rx + local rx: number, ry: number = math.min(rx :: number, w / 2), math.min(ry :: number, h / 2) + if rx <= 0 or ry <= 0 then + return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } :: { PathData.Cmd } + end + local out: { PathData.Cmd } = { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } } + PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out) + table.insert(out, { op = "L", x + w, y + h - ry }) + PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out) + table.insert(out, { op = "L", x + rx, y + h }) + PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out) + table.insert(out, { op = "L", x, y + ry }) + PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out) + table.insert(out, { op = "Z" } :: PathData.Cmd) + return out + elseif kind == "circle" or kind == "ellipse" then + local cx, cy = len(attr(n, "cx"), vw, st, 0) :: number, len(attr(n, "cy"), vh, st, 0) :: number + local rx, ry + if kind == "circle" then + rx = len(attr(n, "r"), diag, st, 0) :: number + ry = rx + else + rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + rx = rx or ry or 0 + ry = ry or rx + end + if (rx :: number) <= 0 or (ry :: number) <= 0 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", cx + rx, cy } } + PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out) + PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out) + PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out) + PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out) + table.insert(out, { op = "Z" } :: PathData.Cmd) + return out + elseif kind == "line" then + local x1, y1 = len(attr(n, "x1"), vw, st, 0) :: number, len(attr(n, "y1"), vh, st, 0) :: number + local x2, y2 = len(attr(n, "x2"), vw, st, 0) :: number, len(attr(n, "y2"), vh, st, 0) :: number + return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } :: { PathData.Cmd } + elseif kind == "polyline" or kind == "polygon" then + local v = Style.numbers(attr(n, "points")) + if #v < 4 then + return nil + end + local out: { PathData.Cmd } = { { op = "M", v[1], v[2] } } + for i = 3, #v - 1, 2 do + table.insert(out, { op = "L", v[i], v[i + 1] }) + end + if kind == "polygon" then + table.insert(out, { op = "Z" } :: PathData.Cmd) + end + return out + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ clip paths +local function transformOf(n: Node): M + local t = attr(n, "transform") + if t then + return Style.transform(t) or IDENTITY + end + return IDENTITY +end + +-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. +local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number? + local cp = ctx.ids[ref] + if cp == nil or local_(cp) ~= "clipPath" then + return nil + end + local base = mul(ctm, transformOf(cp)) + if attr(cp, "clipPathUnits") == "objectBoundingBox" then + if not bbox then + return nil + end + base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }) + end + local cpStyle = computed(st, cp, ctx) + local paths = {} + local function add(n: Node, parentStyle: { [string]: string }, m: M, depth: number) + if depth > 8 then + return + end + local s = computed(parentStyle, n, ctx) + if s.display == "none" or s.visibility == "hidden" then + return + end + local k = local_(n) + local tm = mul(m, transformOf(n)) + if SHAPES[k] then + local cmds = shape(n, s, ctx) + if cmds and #cmds > 0 then + table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" }) + end + elseif k == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target then + local x, y = len(attr(n, "x"), ctx.vw, s, 0) :: number, len(attr(n, "y"), ctx.vh, s, 0) :: number + add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) + end + end + end + for _, c in Xml.children(cp) do + add(c, cpStyle, base, 0) + end + table.insert(ctx.clips, { paths = paths }) + return #ctx.clips +end + +-- ------------------------------------------------------------------------------------------------ the walk +local walk: (n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) -> () + +local function bboxOf(cmds: { PathData.Cmd }): { number }? + local x0, y0, x1, y1 = PathData.bounds(cmds) + if not x0 then + return nil + end + return { x0 :: number, y0 :: number, x1 :: number, y1 :: number } +end + +local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if st.visibility == "hidden" or st.visibility == "collapse" then + return + end + local cmds = shape(n, st, ctx) + if not cmds or #cmds == 0 then + return + end + local tm = mul(ctm, transformOf(n)) + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx) + local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx) + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local sw = len(st["stroke-width"], diag, st, 1) :: number + if sw <= 0 then + stroke = nil + end + if fill == nil and stroke == nil then + return + end + if local_(n) == "line" then + fill = nil -- a line has no inside + end + local clipRef = refId(st["clip-path"]) + local clipId: number? = nil + if clipRef then + clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx) + if clipId == nil and ctx.ids[clipRef] then + return -- a broken clip reference (bad units): nothing shows + end + end + -- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice + local g = group + if opacity < 1 and fill and stroke then + table.insert(ctx.groups, { opacity = opacity, parent = group }) + g = #ctx.groups + opacity = 1 + end + local p: any = { + d = cmds, + fill = fill, + fillRule = if st["fill-rule"] == "evenodd" then "evenodd" else "nonzero", + stroke = stroke, + strokeWidth = sw, + transform = tm, + opacity = opacity, + group = g, + clip = clipId, + id = attr(n, "id"), + } + if stroke then + p.strokeLineJoin = st["stroke-linejoin"] + p.strokeLineCap = st["stroke-linecap"] + p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4 + local dash = st["stroke-dasharray"] + if dash and dash ~= "none" then + local list = {} + local ok = true + for part in string.gmatch(dash, "[^,%s]+") do + local v = len(part, diag, st) + if v == nil or v < 0 then + ok = false + end + table.insert(list, v or 0) + end + local sum = 0 + for _, v in list do + sum += v + end + if ok and sum > 0 then + if #list % 2 == 1 then + table.move(list, 1, #list, #list + 1, list) + end + p.strokeDashArray = list + p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0) + end + end + end + table.insert(ctx.vector.paths, p) +end + +-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) +function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M + if vb == nil or vb[3] <= 0 or vb[4] <= 0 then + return { 1, 0, 0, 1, x, y } + end + local sx, sy = w / vb[3], h / vb[4] + local align, mode = "xmidymid", "meet" + if par then + local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)") + if a == "defer" then + a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)") + end + align = a or align + if m and m ~= "" then + mode = m + end + end + if align == "none" then + return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy } + end + local s = if mode == "slice" then math.max(sx, sy) else math.min(sx, sy) + local tx, ty = x - vb[1] * s, y - vb[2] * s + local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$") + if ax == "mid" then + tx += (w - vb[3] * s) / 2 + elseif ax == "max" then + tx += w - vb[3] * s + end + if ay == "mid" then + ty += (h - vb[4] * s) / 2 + elseif ay == "max" then + ty += h - vb[4] * s + end + return { s, 0, 0, s, tx, ty } +end + +local function viewBox(n: Node): { number }? + local v = Style.numbers(attr(n, "viewBox")) + if #v == 4 and v[3] > 0 and v[4] > 0 then + return v + end + return nil +end + +local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?) + -- a layer for opacity / clip-path + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local clipRef = refId(st["clip-path"]) + local g = group + if opacity < 1 or clipRef then + local clipId: number? = nil + if clipRef then + local bbox: { number }? = nil + local cp = ctx.ids[clipRef] + if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then + -- the group's bounding box in its user space: walk once into a scratch vector + local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips + local scratch = Types.Vector.new(0, 0) + ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} + for _, c in children or Xml.children(n) do + walk(c, st, IDENTITY, nil, ctx) + end + ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, p in scratch.paths do + local b = bboxOf(p.d) + if b then + local m = p.transform or IDENTITY + for _, corner in { { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } } do + local px = m[1] * corner[1] + m[3] * corner[2] + m[5] + local py = m[2] * corner[1] + m[4] * corner[2] + m[6] + x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py) + end + end + end + if x0 <= x1 then + bbox = { x0, y0, x1, y1 } + end + end + clipId = clip(clipRef, ctm, bbox, st, ctx) + if clipId == nil and cp then + return + end + end + table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId }) + g = #ctx.groups + end + if local_(n) == "switch" then + -- the first child that renders (conditional attributes are not evaluated) + for _, c in children or Xml.children(n) do + if UNSUPPORTED[local_(c)] == nil then + walk(c, st, ctm, g, ctx) + return + end + end + return + end + for _, c in children or Xml.children(n) do + walk(c, st, ctm, g, ctx) + end +end + +-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number? + local ov = attr(n, "overflow") + if ov == "visible" or ov == "auto" then + return group + end + local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } }) + table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips }) + return #ctx.groups +end + +walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: number?, ctx: Ctx) + if ctx.depth > 200 then + return + end + local kind = local_(n) + if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then + return + end + local st = computed(parentStyle, n, ctx) + if st.display == "none" then + return + end + if UNSUPPORTED[kind] then + ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1 + return + end + ctx.depth += 1 + if CONTAINERS[kind] then + container(n, st, mul(ctm, transformOf(n)), group, ctx) + elseif SHAPES[kind] then + emitShape(n, st, ctm, group, ctx) + elseif kind == "use" then + local h = refId(href(n)) + local target = if h then ctx.ids[h] else nil + if target and ctx.useDepth < 16 then + ctx.useDepth += 1 + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y }) + local tk = local_(target) + if tk == "symbol" or tk == "svg" then + local w = len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h2 = len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(target) + local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + end + local tst = computed(st, target, ctx) + -- the use element's own opacity applies to the symbol's content too + local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + if uo < 1 then + tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1)) + end + if tst["clip-path"] == nil then + tst["clip-path"] = st["clip-path"] + end + -- the symbol's children as a group of the use element, clipped to its viewport + local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx) + container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target)) + ctx.vw, ctx.vh = saveW, saveH + else + -- the referenced element as if it were the use element's only child + container(n, st, m, group, ctx, { target }) + end + ctx.useDepth -= 1 + end + elseif kind == "svg" then + local x, y = len(attr(n, "x"), ctx.vw, st, 0) :: number, len(attr(n, "y"), ctx.vh, st, 0) :: number + local w = len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) :: number + local h = len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) :: number + local vb = viewBox(n) + local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + else + ctx.vw, ctx.vh = w, h + end + container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx) + ctx.vw, ctx.vh = saveW, saveH + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ entry +-- document(doc, opts) -> Vector | nil, message +function Parse.document(doc: any): (Types.Vector?, string?) + local root = doc.root + if root == nil or Xml.localName(root.name) ~= "svg" then + return nil, "the root element is not <svg>" + end + local ids: { [string]: Node } = {} + local rules: { Style.Rule } = {} + local count = 0 + local function index(n: Node) + count += 1 + if count > 1000000 then + return + end + local id = attr(n, "id") + if id and ids[id] == nil then + ids[id] = n + end + if local_(n) == "style" then + Style.css(Xml.text(n), rules) + end + for _, c in Xml.children(n) do + index(c) + end + end + index(root) + local vb = viewBox(root) + local w = Style.length(attr(root, "width") or "100%", if vb then vb[3] else 100) or 100 + local h = Style.length(attr(root, "height") or "100%", if vb then vb[4] else 100) or 100 + if w <= 0 or h <= 0 then + w, h = 100, 100 + end + local v = Types.Vector.new(w, h) + v.viewBox = vb or { 0, 0, w, h } + local ctx: Ctx = { + ids = ids, + rules = rules, + vector = v, + groups = {}, + clips = {}, + unsupported = {}, + vw = v.viewBox[3], + vh = v.viewBox[4], + depth = 0, + useDepth = 0, + } + local st = computed(INHERITED, root, ctx) + container(root, st, IDENTITY, nil, ctx) + v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio") + v.meta.groups = ctx.groups + v.meta.clips = ctx.clips + if next(ctx.unsupported) then + v.meta.unsupported = ctx.unsupported + end + return v, nil +end + +return Parse +end +__FILES["vector/svg/PathData"] = function() + +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands +-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the +-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a +-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the +-- commands so far are kept, as the spec's error handling says). +local PathData = {} + +type Cmd = { op: string, [number]: number } + +local byte, sub, find = string.byte, string.sub, string.find +local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi + +local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } + +-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out +local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd }) + if x1 == x2 and y1 == y2 then + return + end + rx, ry = abs(rx), abs(ry) + if rx == 0 or ry == 0 then + table.insert(out, { op = "L", x2, y2 }) + return + end + local phi = phiDeg % 360 * pi / 180 + local cp, sp = cos(phi), sin(phi) + local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) + if lambda > 1 then + local s = sqrt(lambda) + rx, ry = rx * s, ry * s + end + local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + local coef = if den == 0 then 0 else sqrt(math.max(0, num / den)) + if fa == fs then + coef = -coef + end + local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx + local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + local function angle(ux: number, uy: number, vx: number, vy: number): number + return atan2(ux * vy - uy * vx, ux * vx + uy * vy) + end + local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry + local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry + local t1 = angle(1, 0, ux, uy) + local dt = angle(ux, uy, vx, vy) + if not fs and dt > 0 then + dt -= 2 * pi + elseif fs and dt < 0 then + dt += 2 * pi + end + local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9)) + local step = dt / n + local k = 4 / 3 * math.tan(step / 4) + local px, py = x1, y1 + for i = 1, n do + local a0 = t1 + (i - 1) * step + local a1 = t1 + i * step + local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1) + -- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre + local e1x, e1y = c0 - k * s0, s0 + k * c0 + local e2x, e2y = c1 + k * s1, s1 - k * c1 + local ex, ey = c1, s1 + local function map(x: number, y: number): (number, number) + x, y = x * rx, y * ry + return cp * x - sp * y + cx, sp * x + cp * y + cy + end + local ax, ay = map(e1x, e1y) + local bx, by = map(e2x, e2y) + local qx, qy = map(ex, ey) + if i == n then + qx, qy = x2, y2 + end + table.insert(out, { op = "C", ax, ay, bx, by, qx, qy }) + px, py = qx, qy + end + local _ = px + py +end +PathData.arc = arc + +-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) +function PathData.parse(d: string): ({ Cmd }, boolean) + local out: { Cmd } = {} + local i, n = 1, #d + local cx, cy = 0, 0 -- current point + local sx, sy = 0, 0 -- subpath start + local lcx, lcy = 0, 0 -- last control point (for S / T) + local last = "" -- previous command letter (upper case) + local cmd: string? = nil + local rel = false + local nums: { number } = table.create(7) :: { number } + local function ws() + while i <= n do + local c = byte(d, i) + if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then + i += 1 + else + break + end + end + end + local function comma() + ws() + if i <= n and byte(d, i) == 44 then + i += 1 + ws() + end + end + local function digits(): boolean + local any = false + while i <= n do + local c = byte(d, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + return any + end + -- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5 + local function number(): number? + ws() + local s = i + local c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + local whole = digits() + local frac = false + if i <= n and byte(d, i) == 46 then + i += 1 + frac = digits() + end + if not whole and not frac then + i = s + return nil + end + c = byte(d, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = byte(d, i) + if c == 43 or c == 45 then + i += 1 + end + if not digits() then + i = save + end + end + return tonumber(sub(d, s, i - 1)) + end + local function flag(): number? + ws() + local c = byte(d, i) + if c == 48 or c == 49 then + i += 1 + return c - 48 + end + return nil + end + while true do + ws() + if i > n then + break + end + local c = sub(d, i, i) + local up = string.upper(c) + if ARGS[up] ~= nil and find(c, "%a") then + cmd = up + rel = c ~= up + i += 1 + if up == "Z" then + table.insert(out, { op = "Z" } :: Cmd) + cx, cy = sx, sy + last = "Z" + cmd = nil + continue + end + elseif cmd == nil then + return out, false + end + local c2 = cmd :: string + local na = ARGS[c2] + for k = 1, na do + local v = if c2 == "A" and (k == 4 or k == 5) then flag() else number() + if v == nil then + return out, false + end + nums[k] = v + if k < na then + comma() + end + end + comma() + local ox, oy = if rel then cx else 0, if rel then cy else 0 + if c2 == "M" then + cx, cy = nums[1] + ox, nums[2] + oy + sx, sy = cx, cy + table.insert(out, { op = "M", cx, cy }) + cmd = "L" -- further pairs are line-tos + elseif c2 == "L" then + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "H" then + cx = nums[1] + ox + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "V" then + cy = nums[1] + (if rel then cy else 0) + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "C" then + local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy + cx, cy = nums[5] + ox, nums[6] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "S" then + local x1, y1 = cx, cy + if last == "C" or last == "S" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + local x2, y2 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "Q" then + local x1, y1 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "T" then + local x1, y1 = cx, cy + if last == "Q" or last == "T" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "A" then + local x2, y2 = nums[6] + ox, nums[7] + oy + arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out) + cx, cy = x2, y2 + end + last = if c2 == "M" then "M" else c2 + end + return out, true +end + +-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box +-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves +function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?) + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "C" then + -- the curve's exact extrema + local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then bx else by + local p3 = if axis == 1 then ex else ey + local a = -p0 + 3 * p1 - 3 * p2 + p3 + local b = 2 * (p0 - 2 * p1 + p2) + local cc = p1 - p0 + local ts = {} + if abs(a) < 1e-12 then + if abs(b) > 1e-12 then + table.insert(ts, -cc / b) + end + else + local disc = b * b - 4 * a * cc + if disc >= 0 then + local s = sqrt(disc) + table.insert(ts, (-b + s) / (2 * a)) + table.insert(ts, (-b - s) / (2 * a)) + end + end + for _, t in ts do + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "Q" then + local ax, ay, ex, ey = c[1], c[2], c[3], c[4] + for axis = 1, 2 do + local p0 = if axis == 1 then px else py + local p1 = if axis == 1 then ax else ay + local p2 = if axis == 1 then ex else ey + local den = p0 - 2 * p1 + p2 + if abs(den) > 1e-12 then + local t = (p0 - p1) / den + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "M" or op == "L" then + px, py = c[1], c[2] + end + if op ~= "Z" then + x0, x1 = math.min(x0, px), math.max(x1, px) + y0, y1 = math.min(y0, py), math.max(y1, py) + end + end + if x0 > x1 then + return nil, nil, nil, nil + end + return x0, y0, x1, y1 +end + +-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) +local function num(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local r = math.floor(v * 10000 + 0.5) / 10000 + if r == math.floor(r) and abs(r) < 1e15 then + return string.format("%d", r) + end + local s = string.format("%.4f", r) + s = string.gsub(s, "0+$", "") + return s +end +PathData.num = num + +-- serialize(cmds) -> path data text +function PathData.serialize(cmds: { Cmd }): string + local out = {} + for _, c in cmds do + local k = ARGS[c.op] + if k ~= nil then + local parts = { c.op } + local cnt = if c.op == "C" then 6 elseif c.op == "Q" then 4 elseif c.op == "Z" then 0 else 2 + for j = 1, cnt do + table.insert(parts, num(tonumber(c[j]) or 0)) + end + table.insert(out, table.concat(parts, " ")) + end + end + return table.concat(out, " ") +end + +-- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) +local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } +function PathData.toRaster(cmds: { Cmd }): { any } + local out = table.create(#cmds) + for i, c in cmds do + local r: any = { op = RASTER[c.op] or "close" } + for j = 1, #c do + r[j] = c[j] + end + out[i] = r + end + return out +end + +return PathData +end +__FILES["vector/svg/Render"] = function() + +-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, +-- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and +-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, +-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox +-- maps onto the image by meta.preserveAspectRatio. Never throws. +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Blend = __include("codecs/image/Blend") +local PathData = __include("vector/svg/PathData") +local Parse = __include("vector/svg/Parse") + +local Render = {} + +type M = { number } + +local function mul(m: M, n: M): M + return Raster.multiply(m, n) +end + +-- ------------------------------------------------------------------------------------------------ gradients +local function stopColor(stops: { { number } }, t: number): (number, number, number, number) + local n = #stops + if t <= stops[1][1] then + local s = stops[1] + return s[2], s[3], s[4], s[5] + end + if t >= stops[n][1] then + local s = stops[n] + return s[2], s[3], s[4], s[5] + end + for i = 2, n do + local b = stops[i] + if t <= b[1] then + local a = stops[i - 1] + local span = b[1] - a[1] + local f = if span > 0 then (t - a[1]) / span else 1 + return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f + end + end + local s = stops[n] + return s[2], s[3], s[4], s[5] +end + +-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds +local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))? + local stops = p.stops + if type(stops) ~= "table" or #stops == 0 then + return nil + end + local g: M = { 1, 0, 0, 1, 0, 0 } + if p.units ~= "userSpaceOnUse" then + if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then + return nil -- a zero-size box: the gradient is not rendered + end + g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] } + end + if type(p.transform) == "table" then + g = mul(g, p.transform) + end + local inv = Raster.invert(mul(device, g)) + if not inv then + return nil + end + local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6] + local spread = p.spread + local opacity = tonumber(p.opacity) or 1 + local function wrap(t: number): number + if spread == "repeat" then + return t - math.floor(t) + elseif spread == "reflect" then + local r = t % 2 + return if r > 1 then 2 - r else r + end + return t + end + if p.type == "linear" then + local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0 + local dx, dy = x2 - x1, y2 - y1 + local dd = dx * dx + dy * dy + if dd == 0 then + local r, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return r, gg, bb, aa * opacity + end + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd) + local r, gg, bb, aa = stopColor(stops, t) + return r, gg, bb, aa * opacity + end + end + local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5 + local fx, fy = p.fx or cx, p.fy or cy + if r <= 0 then + local rr, gg, bb, aa = stopColor(stops, 1) + return function(): (number, number, number, number) + return rr, gg, bb, aa * opacity + end + end + -- SVG 1.1: a focal point outside the circle moves onto it + local fdx, fdy = fx - cx, fy - cy + local fd = math.sqrt(fdx * fdx + fdy * fdy) + if fd > r * 0.999 then + local k = r * 0.999 / fd + fx, fy = cx + fdx * k, cy + fdy * k + end + return function(x: number, y: number): (number, number, number, number) + local gx, gy = a * x + c * y + e, b * x + d * y + f + local dx, dy = gx - fx, gy - fy + local t + if dx == 0 and dy == 0 then + t = 0 + else + -- the ray from the focus through the point meets the circle at s: t = 1 / s + local ox, oy = fx - cx, fy - cy + local qa = dx * dx + dy * dy + local qb = 2 * (dx * ox + dy * oy) + local qc = ox * ox + oy * oy - r * r + local disc = qb * qb - 4 * qa * qc + local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa) + t = if s > 0 then 1 / s else 1 + end + local rr, gg, bb, aa = stopColor(stops, wrap(t)) + return rr, gg, bb, aa * opacity + end +end + +-- ------------------------------------------------------------------------------------------------ dashes +-- subpaths of a command list with their closed flag +local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } } + local out = {} + local cur: { any }? = nil + for _, c in cmds do + if c.op == "M" then + cur = { c } + table.insert(out, { cmds = cur, closed = false }) + elseif c.op == "Z" then + if cur then + out[#out].closed = true + -- a new subpath starts at the same point if more segments follow + local first = (cur :: { any })[1] + cur = { { op = "M", first[1], first[2] } } + table.insert(out, { cmds = cur, closed = false }) + end + elseif cur then + table.insert(cur, c) + end + end + return out +end + +-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) +local function polyline(cmds: { any }, tol: number): { number } + local pts: { number } = {} + local px, py = 0, 0 + for _, c in cmds do + local op = c.op + if op == "M" or op == "L" then + px, py = c[1], c[2] + table.insert(pts, px) + table.insert(pts, py) + elseif op == "Q" or op == "C" then + local len = 0 + local lx, ly = px, py + for k = 1, #c - 1, 2 do + len += math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2) + lx, ly = c[k], c[k + 1] + end + local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512) + for i = 1, steps do + local t = i / steps + local mt = 1 - t + local x, y + if op == "Q" then + x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3] + y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4] + else + x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5] + y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6] + end + table.insert(pts, x) + table.insert(pts, y) + end + px, py = c[#c - 1], c[#c] + end + end + return pts +end + +local function dashed(cmds: { any }, dashes: { number }, offset: number, tol: number): { any } + local out = {} + local total = 0 + for _, v in dashes do + total += v + end + if total <= 0 then + return cmds + end + for _, sp in subpaths(cmds) do + if #sp.cmds < 2 then + continue + end + local pts = polyline(sp.cmds, tol) + if #pts < 4 then + continue + end + if sp.closed then + table.insert(pts, pts[1]) + table.insert(pts, pts[2]) + end + -- dash state at the start (offset wraps through the pattern) + local idx, left = 1, 0 + local o = offset % total + if o < 0 then + o += total + end + while o > 0 do + if o >= dashes[idx] then + o -= dashes[idx] + idx = idx % #dashes + 1 + else + break + end + end + left = dashes[idx] - o + local on = idx % 2 == 1 + local cur: { any }? = nil + if on then + cur = { { op = "M", pts[1], pts[2] } } + end + for i = 1, #pts - 3, 2 do + local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3] + local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2) + local pos = 0 + local guard = 0 + while seg - pos > left and guard < 100000 do + guard += 1 + pos += left + local t = pos / seg + local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + if on then + table.insert(cur :: { any }, { op = "L", x, y }) + for _, c in cur :: { any } do + table.insert(out, c) + end + cur = nil + else + cur = { { op = "M", x, y } } + end + on = not on + idx = idx % #dashes + 1 + left = dashes[idx] + end + left -= seg - pos + if on and cur then + table.insert(cur, { op = "L", x1, y1 }) + end + end + if on and cur and #cur > 1 then + for _, c in cur do + table.insert(out, c) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ rendering +type Options = { + background: { number }?, -- r, g, b, a under the drawing (default transparent) + tolerance: number?, -- curve flattening in device pixels (default 0.1) +} + +-- the device transform scale (for stroke flattening tolerances) +local function scaleOf(m: M): number + return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) +end + +-- rasterize(v, w, h, opts?) -> rgba8 Image +function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image + local o: Options = opts or {} + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local bg = o.background + if type(bg) == "table" then + local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, n - 1 do + buffer.writeu32(px, i * 4, val) + end + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local tol = o.tolerance or 0.1 + local clipCache: { [number]: buffer } = {} + -- a clip's coverage over the whole image (1 byte per pixel) + local function clipMask(id: number): buffer? + if clipCache[id] then + return clipCache[id] + end + local c = clips[id] + if type(c) ~= "table" then + return nil + end + local mask = buffer.create(n) + for _, cp in (if type(c.paths) == "table" then c.paths else {}) do + local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol }) + if m then + for y = 0, m.height - 1 do + for x = 0, m.width - 1 do + local cv = buffer.readu8(m.coverage, y * m.width + x) + if cv > 0 then + local i = (m.y + y) * w + m.x + x + local old = buffer.readu8(mask, i) + buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5))) + end + end + end + end + end + clipCache[id] = mask + return mask + end + -- the layer stack: { group id, image } + local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + local function pop() + local top = table.remove(stack) :: any + local below = stack[#stack].img + local gr = groups[top.id] or {} + local mask: any = nil + if gr.clip then + local cm = clipMask(gr.clip) + mask = if cm then { pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } else { default = 0 } + end + Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask }) + end + local function draw(target: Types.Image, cmds: { any }, paint: any, device: M, rule: string?, opacity: number, bbox: { number }?) + local fill: any + if paint.type == "color" then + fill = paint.color + else + fill = gradientFn(paint, device, bbox) + if not fill then + return + end + end + Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol }) + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + -- groups: pop the layers this path is not in, push the ones it needs + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + pop() + end + for k = keep, #want do + table.insert(stack, { id = want[k], img = Types.Image.new(w, h) }) + end + local device = mul(view, p.transform or Raster.IDENTITY) + local target = stack[#stack].img + local clipMaskBuf: buffer? = nil + if p.clip then + clipMaskBuf = clipMask(p.clip) + if not clipMaskBuf then + continue + end + target = Types.Image.new(w, h) + end + local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1) + local rcmds = PathData.toRaster(p.d) + local bbox: { number }? = nil + if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then + local x0, y0, x1, y1 = PathData.bounds(p.d) + if x0 then + bbox = { x0 :: number, y0 :: number, x1 :: number, y1 :: number } + end + end + if type(p.fill) == "table" then + draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox) + end + if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then + local scale = math.max(scaleOf(device), 1e-6) + local src = p.d + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale) + end + local outline = Raster.stroke(PathData.toRaster(src), { + width = tonumber(p.strokeWidth) or 1, + join = p.strokeLineJoin, + cap = p.strokeLineCap, + miterLimit = p.strokeMiterLimit, + tolerance = tol / scale, + }) + draw(target, outline, p.stroke, device, "nonzero", opacity, bbox) + end + if clipMaskBuf then + Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } }) + end + end + while #stack > 1 do + pop() + end + return img +end + +return Render +end +__FILES["vector/svg/Style"] = function() + +-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / +-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), +-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated +-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). +-- Never throws. +local Raster = __include("codecs/image/Raster") +local Style = {} + +local NAMED: { [string]: number } = { + aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff, + beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff, + blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00, + chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c, + cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9, + darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f, + darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f, + darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1, + darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff, + gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080, + grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4, + indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa, + lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080, + lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90, + lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa, + lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de, + lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff, + maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3, + mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a, + mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa, + mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6, + olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6, + palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093, + papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd, + powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f, + royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57, + seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd, + slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4, + tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee, + wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32, +} + +local function clamp255(v: number): number + return math.clamp(math.floor(v + 0.5), 0, 255) +end + +local function hue(p: number, q: number, t: number): number + t %= 1 + if t < 1 / 6 then + return p + (q - p) * 6 * t + elseif t < 1 / 2 then + return q + elseif t < 2 / 3 then + return p + (q - p) * (2 / 3 - t) * 6 + end + return p +end + +-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value +function Style.color(s: string, current: { number }?): any + s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) + if s == "none" then + return "none" + elseif s == "transparent" then + return { 0, 0, 0, 0 } + elseif s == "currentcolor" then + return current or { 0, 0, 0, 255 } + end + local hex = string.match(s, "^#(%x+)$") + if hex then + local n = #hex + if n == 3 or n == 4 then + local v = {} + for k = 1, n do + v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17 + end + return { v[1], v[2], v[3], v[4] or 255 } + elseif n == 6 or n == 8 then + local v = {} + for k = 1, n // 2 do + v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number + end + return { v[1], v[2], v[3], v[4] or 255 } + end + return nil + end + local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$") + if fn then + local parts = {} + for p in string.gmatch(args :: string, "[^,%s/]+") do + table.insert(parts, p) + end + local function comp(p: string?, scale: number): number? + if p == nil then + return nil + end + local pct = string.match(p, "^([%d.eE+-]+)%%$") + if pct then + local v = tonumber(pct) + return if v then v / 100 * scale else nil + end + return tonumber(p) + end + local function alpha(p: string?): number + if p == nil then + return 255 + end + local v = comp(p, 1) + return clamp255((v or 1) * 255) + end + if fn == "rgb" or fn == "rgba" then + local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255) + if not (r and g and b) then + return nil + end + return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) } + elseif fn == "hsl" or fn == "hsla" then + local h = tonumber((string.gsub(parts[1] or "", "deg$", ""))) + local sat, l = comp(parts[2], 1), comp(parts[3], 1) + if not (h and sat and l) then + return nil + end + local hh = (h :: number) / 360 + local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1) + local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss + local p = 2 * ll - q + return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) } + end + return nil + end + local v = NAMED[s] + if v then + return { v // 65536, v // 256 % 256, v % 256, 255 } + end + return nil +end + +-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +local function scan(s: string, i: number): (number?, number) + local n = #s + local st = i + local c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local any = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + if i <= n and string.byte(s, i) == 46 then + i += 1 + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + any = true + else + break + end + end + end + if not any then + return nil, st + end + c = string.byte(s, i) + if c == 101 or c == 69 then + local save = i + i += 1 + c = string.byte(s, i) + if c == 43 or c == 45 then + i += 1 + end + local e = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i += 1 + e = true + else + break + end + end + if not e then + i = save + end + end + return tonumber(string.sub(s, st, i - 1)), i +end + +-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) +local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } +function Style.length(s: string?, ref: number?, fontSize: number?): number? + if s == nil then + return nil + end + local t = string.match(s, "^%s*(.-)%s*$") :: string + local x, j = scan(t, 1) + if x == nil then + return nil + end + local u = string.lower(string.sub(t, j)) + if u == "" then + return x + elseif u == "%" then + return x / 100 * (ref or 100) + elseif u == "em" then + return x * (fontSize or 16) + elseif u == "ex" then + return x * (fontSize or 16) / 2 + end + local k = UNITS[u] + return if k then x * k else nil +end + +-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else +function Style.numbers(s: string?): { number } + local out = {} + if s == nil then + return out + end + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then + i += 1 + else + local v, j = scan(s, i) + if v == nil then + break + end + table.insert(out, v) + i = j + end + end + return out +end + +-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error +local mul = Raster.multiply +Style.multiply = mul +function Style.transform(s: string): { number }? + local m = { 1, 0, 0, 1, 0, 0 } + local rest = s + while true do + rest = string.gsub(rest, "^[%s,]+", "") + if rest == "" then + break + end + local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$") + if not name then + return nil + end + rest = after :: string + local v = Style.numbers(string.sub(args :: string, 2, -2)) + local t: { number } + if name == "matrix" and #v == 6 then + t = v + elseif name == "translate" and (#v == 1 or #v == 2) then + t = { 1, 0, 0, 1, v[1], v[2] or 0 } + elseif name == "scale" and (#v == 1 or #v == 2) then + t = { v[1], 0, 0, v[2] or v[1], 0, 0 } + elseif name == "rotate" and (#v == 1 or #v == 3) then + local r = v[1] * math.pi / 180 + local c, sn = math.cos(r), math.sin(r) + t = { c, sn, -sn, c, 0, 0 } + if #v == 3 then + t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] }) + end + elseif name == "skewX" and #v == 1 then + t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 } + elseif name == "skewY" and #v == 1 then + t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 } + else + return nil + end + m = mul(m, t) + end + return m +end + +-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) +function Style.declarations(s: string): { [string]: string } + local out: { [string]: string } = {} + for decl in string.gmatch(s, "[^;]+") do + local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$") + if k and v then + v = string.gsub(v :: string, "%s*!important$", "") + out[string.lower(k :: string)] = v :: string + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ CSS +type Selector = { tag: string?, id: string?, classes: { string }, specificity: number } +type Rule = { selector: Selector, decls: { [string]: string }, order: number } + +local function selector(s: string): Selector? + s = string.gsub(s, "^%s*(.-)%s*$", "%1") + if s == "" or string.find(s, "[%s>+~%[:]") then + return nil -- combinators, attribute and pseudo selectors: not supported + end + local sel: Selector = { classes = {}, specificity = 0 } + local tag = string.match(s, "^([%a_][%w_-]*)") + if tag then + sel.tag = tag + sel.specificity += 1 + s = string.sub(s, #tag + 1) + elseif string.sub(s, 1, 1) == "*" then + s = string.sub(s, 2) + end + while s ~= "" do + local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$") + if not kind then + return nil + end + if kind == "." then + table.insert(sel.classes, name :: string) + sel.specificity += 100 + else + sel.id = name + sel.specificity += 10000 + end + s = rest :: string + end + return sel +end + +-- css(text, rules?) -> rules (appended to the list given) +function Style.css(text: string, rules: { Rule }?): { Rule } + local out: { Rule } = rules or {} + text = string.gsub(text, "/%*.-%*/", "") + text = string.gsub(text, "<!%-%-", "") + text = string.gsub(text, "%-%->", "") + -- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;) + local guard = 0 + while guard < 100 do + guard += 1 + local s, e = string.find(text, "@[%w-]+[^{;]*%b{}") + if not s then + break + end + text = string.sub(text, 1, s - 1) .. string.sub(text, (e :: number) + 1) + end + text = string.gsub(text, "@[%w-]+[^;{]*;", "") + for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do + local decls = Style.declarations(string.sub(body :: string, 2, -2)) + for one in string.gmatch(sels, "[^,]+") do + local sel = selector(one) + if sel then + table.insert(out, { selector = sel, decls = decls, order = #out + 1 }) + end + end + end + return out +end + +-- matches(sel, tag, id, classes) -> boolean +function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean + if sel.tag and sel.tag ~= tag then + return false + end + if sel.id and sel.id ~= id then + return false + end + for _, c in sel.classes do + if not classes[c] then + return false + end + end + return true +end + +return Style +end +__FILES["vector/svg/Write"] = function() + +-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients +-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> +-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local PathData = __include("vector/svg/PathData") + +local Write = {} + +local num = PathData.num + +local function el(name: string, attrs: { { any } }, children: { any }?): any + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2])) + end + end + return Xml.element(name, o :: any, children) +end + +local function hex(c: { number }): string + return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255)) +end + +local function matrix(m: any): string? + if type(m) ~= "table" or #m < 6 then + return nil + end + if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then + if m[5] == 0 and m[6] == 0 then + return nil + end + return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")" + end + local parts = {} + for k = 1, 6 do + parts[k] = num(tonumber(m[k]) or 0) + end + return "matrix(" .. table.concat(parts, " ") .. ")" +end + +-- write(v) -> SVG text | nil, message +function Write.vector(v: Types.Vector): (string?, string?) + if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then + return nil, "needs a Vector value" + end + local meta: any = if type(v.meta) == "table" then v.meta else {} + local groups: { any } = if type(meta.groups) == "table" then meta.groups else {} + local clips: { any } = if type(meta.clips) == "table" then meta.clips else {} + local defs = {} + local gradients = 0 + -- paints -> attribute values (gradients go to defs) + local function paintAttrs(p: any, which: string): { { any } } + if type(p) ~= "table" then + return { { which, "none" } } + end + if p.type == "color" and type(p.color) == "table" then + local a = p.color[4] or 255 + return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } } + end + if p.type ~= "linear" and p.type ~= "radial" then + return { { which, "none" } } + end + gradients += 1 + local id = "g" .. gradients + local kids = {} + for _, s in (if type(p.stops) == "table" then p.stops else {}) do + local a = s[5] or 255 + table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } })) + end + local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } } + if p.type == "linear" then + table.insert(attrs, { "x1", p.x1 or 0 }) + table.insert(attrs, { "y1", p.y1 or 0 }) + table.insert(attrs, { "x2", p.x2 or 1 }) + table.insert(attrs, { "y2", p.y2 or 0 }) + else + table.insert(attrs, { "cx", p.cx or 0.5 }) + table.insert(attrs, { "cy", p.cy or 0.5 }) + table.insert(attrs, { "r", p.r or 0.5 }) + table.insert(attrs, { "fx", p.fx }) + table.insert(attrs, { "fy", p.fy }) + if p.fr and p.fr ~= 0 then + table.insert(attrs, { "fr", p.fr }) + end + end + table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil }) + table.insert(attrs, { "gradientTransform", matrix(p.transform) }) + table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids)) + local op = tonumber(p.opacity) or 1 + return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } } + end + local clipIds: { [number]: string } = {} + local function clipRef(id: number?): string? + if id == nil or type(clips[id]) ~= "table" then + return nil + end + if clipIds[id] == nil then + local cid = "c" .. id + clipIds[id] = cid + local kids = {} + for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do + table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } })) + end + table.insert(defs, el("clipPath", { { "id", cid } }, kids)) + end + return "url(#" .. clipIds[id] .. ")" + end + local root = {} + -- the open <g> stack: { id, children } + local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } } + local function chain(g: number?): { number } + local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = if type(gr) == "table" then gr.parent else nil + guard += 1 + end + return out + end + for _, p in v.paths do + if type(p) ~= "table" or type(p.d) ~= "table" then + continue + end + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep += 1 + end + while #stack > keep do + table.remove(stack) + end + for k = keep, #want do + local gr = groups[want[k]] or {} + local kids = {} + local op = tonumber(gr.opacity) or 1 + table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids)) + table.insert(stack, { id = want[k], kids = kids }) + end + local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } } + for _, kv in paintAttrs(p.fill, "fill") do + table.insert(attrs, kv) + end + table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil }) + for _, kv in paintAttrs(p.stroke, "stroke") do + if kv[2] ~= "none" then + table.insert(attrs, kv) + end + end + if type(p.stroke) == "table" then + local sw = tonumber(p.strokeWidth) or 1 + table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil }) + table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil }) + table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil }) + local ml = tonumber(p.strokeMiterLimit) + table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil }) + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + local parts = {} + for k, d in p.strokeDashArray do + parts[k] = num(tonumber(d) or 0) + end + table.insert(attrs, { "stroke-dasharray", table.concat(parts :: { string }, " ") }) + local off = tonumber(p.strokeDashOffset) + table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil }) + end + end + local op = tonumber(p.opacity) or 1 + table.insert(attrs, { "opacity", if op < 1 then op else nil }) + local node = el("path", attrs) + local cr = clipRef(p.clip) + if cr then + node = el("g", { { "clip-path", cr } }, { node }) + end + table.insert(stack[#stack].kids, node) + end + local children = {} + if #defs > 0 then + table.insert(children, el("defs", {}, defs)) + end + for _, c in root do + table.insert(children, c) + end + local vb = v.viewBox + local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil + local svg = el("svg", { + { "xmlns", "http://www.w3.org/2000/svg" }, + { "width", v.width }, + { "height", v.height }, + { "viewBox", vbText }, + { "preserveAspectRatio", meta.preserveAspectRatio }, + }, children) + local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 }) + if not s then + return nil, tostring(err) + end + return s .. "\n", nil +end + +return Write +end +__FILES["vector/tiled"] = function() + +-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map +-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / +-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, +-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, +-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets +-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay +-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the +-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". +-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external +-- tilesets or images (callers resolve `source` / `imageSource` paths themselves). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Tmx = __include("vector/tiled/Tmx") +local Tmj = __include("vector/tiled/Tmj") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiled = { + name = "tiled", + category = "vector", + extensions = { "tmx", "tmj", "tsx", "tsj" }, + mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, + 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 }, +} + +type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 256 MB) +} +type EncodeOptions = { + format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx + encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64" + compression: string?, -- base64 data: nil | "zlib" | "gzip" + level: number?, -- deflate level for compressed data (default 6) + indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function head(r: Bytes.Reader): string + local h = Sniff.text(r, 1024) + return h +end + +function Tiled.sniff(r: Bytes.Reader): number + local h = head(r) + if string.match(h, "^%s*<") then + if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then + return 0.9 + end + return 0 + end + if string.match(h, "^%s*{") then + -- Tiled writes its keys sorted: "type" comes last, so look at the tail too + local n = r:remaining() + local tail = if n > 1024 then r:peek(1024, n - 1024) else "" + for _, part in { h, tail } do + if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then + return 0.8 + end + end + if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its +-- meta.tileset is true) | nil, Err +function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?) + local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local h = head(r) + local map: any, msg: string?, unsupported: boolean? + local flavour + if string.match(h, "^%s*<") then + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local root = (doc :: any).root + if root == nil then + return nil, Err.new(Err.CORRUPT, "no root element") + end + if root.name == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmx.tileset(root) } + map.meta.tileset = true + flavour = "tsx" + else + map, msg, unsupported = Tmx.read(root) + flavour = "tmx" + end + else + local v, jerr = Json.decode(text) + if v == nil then + return nil, jerr + end + if type(v) == "table" and v.type == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmj.tileset(v) } + map.meta.tileset = true + flavour = "tsj" + else + map, msg, unsupported = Tmj.read(v) + flavour = "tmj" + end + end + if not map then + return nil, Err.new(if unsupported then Err.UNSUPPORTED else Err.CORRUPT, msg or "bad map") + end + map.meta.source = { format = flavour } + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tiled.encode(map: Types.TileMap, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then + return nil, Err.new(Err.ARG, "needs a TileMap value") + end + local o: EncodeOptions = opts or {} + local meta: any = if type(map.meta) == "table" then map.meta else {} + local fmt = o.format or (if type(meta.source) == "table" then meta.source.format else nil) or "tmx" + fmt = string.lower(fmt) + if fmt == "tiled" then + fmt = if type(meta.source) == "table" and meta.source.format then meta.source.format else "tmx" + end + local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj" + if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then + return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml") + end + if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then + return nil, Err.new(Err.ARG, "compression must be zlib or gzip") + end + local wo: Tmx.WriteOptions = { encoding = o.encoding :: string?, compression = o.compression, level = o.level } + if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then + local doc: any, err: string? + if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" }) + else + doc, err = Tmx.write(map, wo) + end + if not doc then + return nil, Err.new(Err.ARG, err or "bad map") + end + local s, xerr = Xml.encode(doc, { indent = o.indent or 1 }) + if not s then + return nil, xerr + end + return buffer.fromstring(s .. "\n"), nil + elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then + local v: any, err: string? + if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + v = Tmj.tilesetValue(map.tilesets[1], false) + else + v, err = Tmj.write(map, wo) + end + if v == nil then + return nil, Err.new(Err.ARG, err or "bad map") + end + local indent = if o.indent == 0 then nil else (o.indent or 2) + local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s .. "\n"), nil + end + return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)") +end + +return Tiled +end +__FILES["vector/tiled/Data"] = function() + +-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) +-- to gids and back; property values and their types; number formatting. Never throws. +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") + +local Data = {} + +-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message +function Data.csv(text: string): ({ number }?, string?) + local out = {} + for tok in string.gmatch(text, "[^,%s]+") do + local v = tonumber(tok) + if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then + return nil, "bad gid " .. string.sub(tok, 1, 20) + end + table.insert(out, v) + end + return out, nil +end + +-- base64(text, compression) -> { gid } | nil, message, unsupported? +function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?) + local raw, err = Base64.decode(text) + if not raw then + return nil, err, nil + end + local bytes: buffer = raw + if compression == "zlib" then + local z, zerr = Deflate.zlib(bytes) + if not z then + return nil, "zlib: " .. tostring(zerr), nil + end + bytes = z + elseif compression == "gzip" then + local z, zerr = Deflate.gunzip(bytes) + if not z then + return nil, "gzip: " .. tostring(zerr), nil + end + bytes = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported", true + end + local n = buffer.len(bytes) // 4 + local out: { number } = table.create(n) :: { number } + for i = 0, n - 1 do + out[i + 1] = buffer.readu32(bytes, i * 4) + end + return out, nil, nil +end + +-- toBase64(gids, compression?, level?) -> text | nil, message +function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?) + local b = buffer.create(#gids * 4) + for i, g in gids do + buffer.writeu32(b, (i - 1) * 4, g % 4294967296) + end + if compression == "zlib" then + local z = Deflate.zlibCompress(b, { level = level or 6 }) + if not z then + return nil, "zlib failed" + end + b = z + elseif compression == "gzip" then + local z = Deflate.gzip(b, { level = level or 6 }) + if not z then + return nil, "gzip failed" + end + b = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported" + end + return Base64.encode(b), nil +end + +-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +function Data.num(v: number): string + if v % 1 == 0 and math.abs(v) < 2 ^ 53 then + return string.format("%.0f", v) + end + local s = string.format("%.15g", v) + if tonumber(s) ~= v then + s = string.format("%.17g", v) + end + return s +end + +-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +function Data.csvText(gids: { number }, width: number): string + local rows = {} + local row = {} + for i, g in gids do + table.insert(row, Data.num(g)) + if width > 0 and i % width == 0 then + table.insert(rows, table.concat(row, ",")) + row = {} + end + end + if #row > 0 then + table.insert(rows, table.concat(row, ",")) + end + return "\n" .. table.concat(rows, ",\n") .. "\n" +end + +-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +function Data.color(s: string?): string? + if type(s) ~= "string" then + return nil + end + local h = string.lower((string.gsub(s, "^#", ""))) + if #h == 8 and string.sub(h, 1, 2) == "ff" then + h = string.sub(h, 3) + end + return "#" .. h +end + +-- property values: TMX / TMJ type names -> a Luau value from text +function Data.value(typ: string, text: string): any + if typ == "int" or typ == "float" or typ == "object" then + return tonumber(text) or 0 + elseif typ == "bool" then + return text == "true" or text == "1" + elseif typ == "color" then + return Data.color(text) or "" + end + return text +end + +-- typeOf(v, declared?) -> the Tiled type to write for v +function Data.typeOf(v: any, declared: string?): string + if declared then + return declared + end + if type(v) == "boolean" then + return "bool" + elseif type(v) == "number" then + return if v % 1 == 0 then "int" else "float" + elseif type(v) == "table" then + return "class" + end + return "string" +end + +-- sortedKeys(t) -> its string keys, sorted +function Data.sortedKeys(t: { [any]: any }): { string } + local out = {} + for k in pairs(t) do + if type(k) == "string" then + table.insert(out, k) + end + end + table.sort(out) + return out +end + +return Data +end +__FILES["vector/tiled/Tmj"] = function() + +-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ +-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmj = {} + +local function n(v: any, default: number?): number? + if type(v) == "number" then + return v + end + return default +end +local function b(v: any, default: boolean): boolean + if type(v) == "boolean" then + return v + end + return default +end +local function s(v: any): string? + if type(v) == "string" then + return v + end + return nil +end +local function list(v: any): { any } + if type(v) == "table" then + return v + end + return {} +end + +-- ------------------------------------------------------------------------------------------------ read +local function properties(v: any): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + for _, p in list(v) do + if type(p) == "table" and type(p.name) == "string" then + local typ = s(p.type) or "string" + local val: any = p.value + if typ == "class" then + local inner, innerTypes = {}, nil + if type(val) == "table" then + -- a class value is an object of member -> value (types come from the project): keep them as they are + for k, x in pairs(val) do + if type(k) == "string" then + inner[k] = x + end + end + end + val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes } + elseif typ == "int" or typ == "float" or typ == "object" then + val = n(val, 0) + elseif typ == "bool" then + val = val == true + elseif typ == "color" then + val = Data.color(s(val)) or "" + elseif type(val) ~= "string" then + val = if val == nil then "" else tostring(val) + end + props[p.name] = val + if typ ~= "string" then + types = types or {} + ;(types :: any)[p.name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, v: any) + local props, types = properties(v.properties) + t.properties = props + if types then + t.propertyTypes = types + end +end + +local function gids(v: any, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if type(v) == "string" then + if encoding == "base64" or encoding == nil then + return Data.base64(v, compression) + end + return nil, "unknown encoding " .. tostring(encoding), true + end + local out = {} + for _, g in list(v) do + if type(g) ~= "number" or g < 0 or g >= 4294967296 then + return nil, "bad gid", nil + end + table.insert(out, g) + end + return out, nil, nil +end + +local function object(o: any): any + local obj: any = { + id = n(o.id), + name = s(o.name) or "", + class = s(o.class) or s(o.type) or "", + x = n(o.x, 0), + y = n(o.y, 0), + width = n(o.width, 0), + height = n(o.height, 0), + rotation = n(o.rotation, 0), + gid = n(o.gid), + visible = b(o.visible, true), + template = s(o.template), + shape = "rectangle", + } + withProps(obj, o) + if o.ellipse == true then + obj.shape = "ellipse" + elseif o.point == true then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + if type(o[kind]) == "table" then + obj.shape = kind + local pts = {} + for _, p in o[kind] do + if type(p) == "table" then + table.insert(pts, { n(p.x, 0), n(p.y, 0) }) + end + end + obj.points = pts + end + end + if type(o.text) == "table" then + local t = o.text + obj.shape = "text" + obj.text = { + text = s(t.text) or "", + fontFamily = s(t.fontfamily) or "sans-serif", + pixelSize = n(t.pixelsize, 16), + wrap = b(t.wrap, false), + color = Data.color(s(t.color)) or "#000000", + bold = b(t.bold, false), + italic = b(t.italic, false), + underline = b(t.underline, false), + strikeout = b(t.strikeout, false), + kerning = b(t.kerning, true), + halign = s(t.halign) or "left", + valign = s(t.valign) or "top", + } + end + return obj +end + +local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" } + +local layer: (v: any, depth: number) -> (any, string?, boolean?) + +local function common(v: any, typ: string): any + local l: any = { + type = typ, + id = n(v.id), + name = s(v.name) or "", + visible = b(v.visible, true), + opacity = n(v.opacity, 1), + x = n(v.x, 0), + y = n(v.y, 0), + offsetX = n(v.offsetx, 0), + offsetY = n(v.offsety, 0), + parallaxX = n(v.parallaxx, 1), + parallaxY = n(v.parallaxy, 1), + tintColor = Data.color(s(v.tintcolor)), + class = s(v.class) or "", + locked = b(v.locked, false), + } + withProps(l, v) + return l +end + +local function objectGroup(v: any): any + local l = common(v, "objects") + l.drawOrder = s(v.draworder) or "topdown" + l.color = Data.color(s(v.color)) + l.objects = {} + for _, o in list(v.objects) do + if type(o) == "table" then + table.insert(l.objects, object(o)) + end + end + return l +end + +layer = function(v: any, depth: number): (any, string?, boolean?) + if type(v) ~= "table" then + return nil, "a layer is not an object" + end + if depth > 100 then + return nil, "groups nested too deep" + end + local typ = TYPES[v.type] + if typ == "tiles" then + local l = common(v, "tiles") + l.width = n(v.width, 0) + l.height = n(v.height, 0) + l.encoding = s(v.encoding) + l.compression = s(v.compression) + if type(v.chunks) == "table" then + l.chunks = {} + for _, c in v.chunks do + if type(c) == "table" then + local g, err, uns = gids(c.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g }) + end + end + elseif v.data ~= nil then + local g, err, uns = gids(v.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + l.data = g + end + return l + elseif typ == "objects" then + return objectGroup(v) + elseif typ == "image" then + local l = common(v, "image") + l.imageSource = s(v.image) + l.imageWidth = n(v.imagewidth) + l.imageHeight = n(v.imageheight) + l.transparentColor = Data.color(s(v.transparentcolor)) + l.repeatX = b(v.repeatx, false) + l.repeatY = b(v.repeaty, false) + return l + elseif typ == "group" then + local l = common(v, "group") + l.layers = {} + for _, c in list(v.layers) do + local sub, err, uns = layer(c, depth + 1) + if not sub then + return nil, err, uns + end + table.insert(l.layers, sub) + end + return l + end + return nil, "unknown layer type " .. tostring(v.type) +end + +-- tileset(v) -> Tileset (a map's entry, or a .tsj root) +function Tmj.tileset(v: any): any + local ts: any = { + firstGid = n(v.firstgid, 1), + source = s(v.source), + name = s(v.name) or "", + tileWidth = n(v.tilewidth, 0), + tileHeight = n(v.tileheight, 0), + spacing = n(v.spacing, 0), + margin = n(v.margin, 0), + count = n(v.tilecount, 0), + columns = n(v.columns, 0), + objectAlignment = s(v.objectalignment), + class = s(v.class) or "", + imageSource = s(v.image), + imageWidth = n(v.imagewidth), + imageHeight = n(v.imageheight), + transparentColor = Data.color(s(v.transparentcolor)), + } + withProps(ts, v) + if type(v.tileoffset) == "table" then + ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) } + end + local tiles = {} + for _, t in list(v.tiles) do + if type(t) == "table" then + local tile: any = { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) } + withProps(tile, t) + tile.imageSource = s(t.image) + tile.imageWidth = n(t.imagewidth) + tile.imageHeight = n(t.imageheight) + if type(t.animation) == "table" then + tile.animation = {} + for _, f in t.animation do + if type(f) == "table" then + table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) }) + end + end + end + if type(t.objectgroup) == "table" then + tile.objectGroup = objectGroup(t.objectgroup) + end + table.insert(tiles, tile) + end + end + table.sort(tiles, function(x: any, y: any): boolean + return x.id < y.id + end) + ts.tiles = tiles + return ts +end + +-- read(value) -> TileMap | nil, message, unsupported? +function Tmj.read(v: any): (any, string?, boolean?) + if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then + return nil, "not a Tiled map (type is not \"map\")" + end + local map: any = Types.TileMap.new(n(v.width, 0) :: number, n(v.height, 0) :: number, n(v.tilewidth, 0) :: number, n(v.tileheight, 0) :: number) + map.version = if type(v.version) == "number" then Data.num(v.version) else s(v.version) + map.tiledVersion = s(v.tiledversion) + map.orientation = s(v.orientation) or "orthogonal" + map.renderOrder = s(v.renderorder) or "right-down" + map.infinite = b(v.infinite, false) + map.nextLayerId = n(v.nextlayerid) + map.nextObjectId = n(v.nextobjectid) + map.backgroundColor = Data.color(s(v.backgroundcolor)) + map.hexSideLength = n(v.hexsidelength) + map.staggerAxis = s(v.staggeraxis) + map.staggerIndex = s(v.staggerindex) + map.class = s(v.class) or "" + map.parallaxOriginX = n(v.parallaxoriginx, 0) + map.parallaxOriginY = n(v.parallaxoriginy, 0) + withProps(map, v) + for _, ts in list(v.tilesets) do + if type(ts) == "table" then + table.insert(map.tilesets, Tmj.tileset(ts)) + end + end + for _, l in list(v.layers) do + local x, err, uns = layer(l, 0) + if not x then + return nil, err, uns + end + table.insert(map.layers, x) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function obj(pairs_: { { any } }): any + local o = Types.object() + for _, kv in pairs_ do + if kv[2] ~= nil then + Types.set(o, kv[1], kv[2]) + end + end + return o +end +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propList(props: any, types: any): { any }? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local out = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local members = Types.object() + if type(v.properties) == "table" then + for _, mk in Data.sortedKeys(v.properties) do + Types.set(members, mk, v.properties[mk]) + end + end + table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } })) + else + table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } })) + end + end + return out +end + +local function writeObject(o: any): any + local t: any = nil + if o.shape == "text" and type(o.text) == "table" then + local x = o.text + t = obj({ + { "bold", nz(x.bold, false) }, + { "color", nz(x.color, "#000000") }, + { "fontfamily", nz(x.fontFamily, "sans-serif") }, + { "halign", nz(x.halign, "left") }, + { "italic", nz(x.italic, false) }, + { "kerning", nz(x.kerning, true) }, + { "pixelsize", nz(x.pixelSize, 16) }, + { "strikeout", nz(x.strikeout, false) }, + { "text", tostring(x.text or "") }, + { "underline", nz(x.underline, false) }, + { "valign", nz(x.valign, "top") }, + { "wrap", nz(x.wrap, false) }, + }) + end + local pts: any = nil + if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then + pts = {} + for _, p in o.points do + table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } })) + end + end + return obj({ + { "ellipse", if o.shape == "ellipse" then true else nil }, + { "gid", o.gid }, + { "height", o.height or 0 }, + { "id", o.id }, + { "name", o.name or "" }, + { "point", if o.shape == "point" then true else nil }, + { "polygon", if o.shape == "polygon" then pts else nil }, + { "polyline", if o.shape == "polyline" then pts else nil }, + { "properties", propList(o.properties, o.propertyTypes) }, + { "rotation", o.rotation or 0 }, + { "template", o.template }, + { "text", t }, + { "type", o.class or "" }, + { "visible", o.visible ~= false }, + { "width", o.width or 0 }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + }) +end + +type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local function writeObjectGroup(l: any): any + local objs = {} + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(objs, writeObject(o)) + end + return objs +end + +local writeLayer: (l: any, o: WriteOptions) -> (any, string?) + +writeLayer = function(l: any, o: WriteOptions): (any, string?) + local t = l.type + local fields: { { any } } = {} + local function add(k: string, v: any) + table.insert(fields, { k, v }) + end + if t == "tiles" then + local enc = o.encoding or l.encoding + if enc ~= "base64" then + enc = nil + end + local comp = if enc then (o.compression or (if o.encoding then nil else l.compression)) else nil + local function payload(g: { number }): (any, string?) + if enc == "base64" then + return Data.toBase64(g, comp, o.level) + end + return g, nil + end + if type(l.chunks) == "table" then + local chunks = {} + for _, c in l.chunks do + local d, err = payload(c.data or {}) + if d == nil then + return nil, err + end + table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } })) + end + add("chunks", chunks) + local sx, sy = math.huge, math.huge + for _, c in l.chunks do + sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0) + end + if #l.chunks > 0 then + add("startx", sx) + add("starty", sy) + end + elseif type(l.data) == "table" then + local d, err = payload(l.data) + if d == nil then + return nil, err + end + add("data", d) + end + add("compression", comp) + add("encoding", enc) + add("height", l.height or 0) + elseif t == "objects" then + add("color", l.color) + add("draworder", l.drawOrder or "topdown") + elseif t == "image" then + add("image", l.imageSource or "") + add("imageheight", l.imageHeight) + add("imagewidth", l.imageWidth) + elseif t == "group" then + local kids = {} + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local x, err = writeLayer(c, o) + if x == nil then + return nil, err + end + table.insert(kids, x) + end + add("layers", kids) + else + return nil, "unknown layer type " .. tostring(t) + end + add("class", str(l.class)) + add("id", l.id) + add("locked", nz(l.locked, false)) + add("name", l.name or "") + if t == "objects" then + add("objects", writeObjectGroup(l)) + end + add("offsetx", nz(l.offsetX, 0)) + add("offsety", nz(l.offsetY, 0)) + add("opacity", l.opacity or 1) + add("parallaxx", nz(l.parallaxX, 1)) + add("parallaxy", nz(l.parallaxY, 1)) + add("properties", propList(l.properties, l.propertyTypes)) + if t == "image" then + add("repeatx", nz(l.repeatX, false)) + add("repeaty", nz(l.repeatY, false)) + end + add("tintcolor", l.tintColor) + if t == "image" then + add("transparentcolor", l.transparentColor) + end + add("type", if t == "tiles" then "tilelayer" elseif t == "objects" then "objectgroup" elseif t == "image" then "imagelayer" else "group") + add("visible", l.visible ~= false) + if t == "tiles" then + add("width", l.width or 0) + end + add("x", l.x or 0) + add("y", l.y or 0) + return obj(fields), nil +end + +-- tilesetValue(ts, inMap) -> a JSON object +function Tmj.tilesetValue(ts: any, inMap: boolean): any + if inMap and type(ts.source) == "string" then + return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local tiles: any = nil + if type(ts.tiles) == "table" and #ts.tiles > 0 then + tiles = {} + for _, tile in ts.tiles do + local anim: any = nil + if type(tile.animation) == "table" then + anim = {} + for _, f in tile.animation do + table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } })) + end + end + local og: any = nil + if type(tile.objectGroup) == "table" then + og = writeLayer(tile.objectGroup, {}) + end + table.insert(tiles, obj({ + { "animation", anim }, + { "id", tile.id or 0 }, + { "image", tile.imageSource }, + { "imageheight", tile.imageHeight }, + { "imagewidth", tile.imageWidth }, + { "objectgroup", og }, + { "probability", tile.probability }, + { "properties", propList(tile.properties, tile.propertyTypes) }, + { "type", str(tile.class) }, + })) + end + end + return obj({ + { "class", str(ts.class) }, + { "columns", ts.columns or 0 }, + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "image", ts.imageSource }, + { "imageheight", ts.imageHeight }, + { "imagewidth", ts.imageWidth }, + { "margin", ts.margin or 0 }, + { "name", ts.name or "" }, + { "objectalignment", ts.objectAlignment }, + { "properties", propList(ts.properties, ts.propertyTypes) }, + { "spacing", ts.spacing or 0 }, + { "tilecount", ts.count or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "tileoffset", if type(ts.tileOffset) == "table" then obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) else nil }, + { "tiles", tiles }, + { "tilewidth", ts.tileWidth or 0 }, + { "transparentcolor", ts.transparentColor }, + { "type", if inMap then nil else "tileset" }, + }) +end + +-- write(map, opts) -> a JSON value | nil, message +function Tmj.write(map: any, o: WriteOptions): (any, string?) + local layers = {} + for _, l in map.layers do + local x, err = writeLayer(l, o) + if x == nil then + return nil, err + end + table.insert(layers, x) + end + local tilesets = {} + for _, ts in map.tilesets do + table.insert(tilesets, Tmj.tilesetValue(ts, true)) + end + return obj({ + { "backgroundcolor", map.backgroundColor }, + { "class", str(map.class) }, + { "compressionlevel", -1 }, + { "height", map.height }, + { "hexsidelength", map.hexSideLength }, + { "infinite", map.infinite == true }, + { "layers", layers }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + { "orientation", map.orientation or "orthogonal" }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "properties", propList(map.properties, map.propertyTypes) }, + { "renderorder", map.renderOrder or "right-down" }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "tiledversion", map.tiledVersion }, + { "tileheight", map.tileHeight }, + { "tilesets", tilesets }, + { "tilewidth", map.tileWidth }, + { "type", "map" }, + { "version", map.version or "1.10" }, + { "width", map.width }, + }), nil +end + +return Tmj +end +__FILES["vector/tiled/Tmx"] = function() + +-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. +-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmx = {} + +type Node = Types.XmlNode + +local function a(n: Node, k: string): string? + return (n.attrs :: any)[k] +end +local function num(n: Node, k: string, default: number?): number? + local v = a(n, k) + if v == nil then + return default + end + return tonumber(v) or default +end +local function flag(n: Node, k: string, default: boolean): boolean + local v = a(n, k) + if v == nil then + return default + end + return v == "1" or v == "true" +end + +-- ------------------------------------------------------------------------------------------------ read +-- <properties> -> values, types (types only for the non-string ones) +local function properties(n: Node?): ({ [string]: any }, { [string]: string }?) + local props: { [string]: any } = {} + local types: { [string]: string }? = nil + if n == nil then + return props, nil + end + for _, p in Xml.children(n, "property") do + local name = a(p, "name") + if name then + local typ = a(p, "type") or "string" + local v: any + if typ == "class" then + local inner, innerTypes = properties(Xml.child(p, "properties")) + v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes } + else + local text = a(p, "value") + if text == nil then + text = Xml.text(p) -- multi-line strings + end + v = Data.value(typ, text :: string) + end + props[name] = v + if typ ~= "string" then + types = types or {} + ;(types :: any)[name] = typ + end + end + end + return props, types +end + +local function withProps(t: any, n: Node) + local props, types = properties(Xml.child(n, "properties")) + t.properties = props + if types then + t.propertyTypes = types + end +end + +-- the gids of a <data> (or <chunk>) node +local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?) + if encoding == "csv" then + return Data.csv(Xml.text(d)) + elseif encoding == "base64" then + return Data.base64(Xml.text(d), compression) + elseif encoding == nil or encoding == "" then + local out = {} + for _, t in Xml.children(d, "tile") do + table.insert(out, num(t, "gid", 0) :: number) + end + return out, nil, nil + end + return nil, "unknown encoding " .. encoding, true +end + +local function object(o: Node): any + local obj: any = { + id = num(o, "id"), + name = a(o, "name") or "", + class = a(o, "class") or a(o, "type") or "", + x = num(o, "x", 0), + y = num(o, "y", 0), + width = num(o, "width", 0), + height = num(o, "height", 0), + rotation = num(o, "rotation", 0), + gid = num(o, "gid"), + visible = flag(o, "visible", true), + template = a(o, "template"), + shape = "rectangle", + } + withProps(obj, o) + if Xml.child(o, "ellipse") then + obj.shape = "ellipse" + elseif Xml.child(o, "point") then + obj.shape = "point" + end + for _, kind in { "polygon", "polyline" } do + local p = Xml.child(o, kind) + if p then + obj.shape = kind + local pts = {} + for x, y in string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)") do + table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 }) + end + obj.points = pts + end + end + local t = Xml.child(o, "text") + if t then + obj.shape = "text" + obj.text = { + text = Xml.text(t), + fontFamily = a(t, "fontfamily") or "sans-serif", + pixelSize = num(t, "pixelsize", 16), + wrap = flag(t, "wrap", false), + color = Data.color(a(t, "color")) or "#000000", + bold = flag(t, "bold", false), + italic = flag(t, "italic", false), + underline = flag(t, "underline", false), + strikeout = flag(t, "strikeout", false), + kerning = flag(t, "kerning", true), + halign = a(t, "halign") or "left", + valign = a(t, "valign") or "top", + } + end + return obj +end + +local layer: (n: Node) -> (any, string?, boolean?) + +local function common(n: Node, typ: string): any + local l: any = { + type = typ, + id = num(n, "id"), + name = a(n, "name") or "", + visible = flag(n, "visible", true), + opacity = num(n, "opacity", 1), + x = num(n, "x", 0), + y = num(n, "y", 0), + offsetX = num(n, "offsetx", 0), + offsetY = num(n, "offsety", 0), + parallaxX = num(n, "parallaxx", 1), + parallaxY = num(n, "parallaxy", 1), + tintColor = Data.color(a(n, "tintcolor")), + class = a(n, "class") or "", + locked = flag(n, "locked", false), + } + withProps(l, n) + return l +end + +local function objectGroup(n: Node): any + local l = common(n, "objects") + l.drawOrder = a(n, "draworder") or "topdown" + l.color = Data.color(a(n, "color")) + l.objects = {} + for _, o in Xml.children(n, "object") do + table.insert(l.objects, object(o)) + end + return l +end + +layer = function(n: Node): (any, string?, boolean?) + local name = n.name + if name == "layer" then + local l = common(n, "tiles") + l.width = num(n, "width", 0) + l.height = num(n, "height", 0) + local d = Xml.child(n, "data") + if d then + local enc, comp = a(d, "encoding"), a(d, "compression") + l.encoding, l.compression = enc, comp + local chunks = Xml.children(d, "chunk") + if #chunks > 0 then + l.chunks = {} + for _, c in chunks do + local g, err, uns = gids(c, enc, comp) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g }) + end + else + local g, err, uns = gids(d, enc, comp) + if not g then + return nil, err, uns + end + l.data = g + end + end + return l + elseif name == "objectgroup" then + return objectGroup(n) + elseif name == "imagelayer" then + local l = common(n, "image") + l.repeatX = flag(n, "repeatx", false) + l.repeatY = flag(n, "repeaty", false) + local img = Xml.child(n, "image") + if img then + l.imageSource = a(img, "source") + l.imageWidth = num(img, "width") + l.imageHeight = num(img, "height") + l.transparentColor = Data.color(a(img, "trans")) + end + return l + elseif name == "group" then + local l = common(n, "group") + l.layers = {} + for _, c in n.children do + if type(c) == "table" then + local sub, err, uns = layer(c) + if err then + return nil, err, uns + end + if sub then + table.insert(l.layers, sub) + end + end + end + return l + end + return nil +end + +-- a <tileset> element (in a map, or a .tsx root) -> Tileset +function Tmx.tileset(n: Node): any + local ts: any = { + firstGid = num(n, "firstgid", 1), + source = a(n, "source"), + name = a(n, "name") or "", + tileWidth = num(n, "tilewidth", 0), + tileHeight = num(n, "tileheight", 0), + spacing = num(n, "spacing", 0), + margin = num(n, "margin", 0), + count = num(n, "tilecount", 0), + columns = num(n, "columns", 0), + objectAlignment = a(n, "objectalignment"), + class = a(n, "class") or "", + } + withProps(ts, n) + local off = Xml.child(n, "tileoffset") + if off then + ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) } + end + local img = Xml.child(n, "image") + if img then + ts.imageSource = a(img, "source") + ts.imageWidth = num(img, "width") + ts.imageHeight = num(img, "height") + ts.transparentColor = Data.color(a(img, "trans")) + end + local tiles = {} + for _, t in Xml.children(n, "tile") do + local tile: any = { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") } + withProps(tile, t) + local ti = Xml.child(t, "image") + if ti then + tile.imageSource = a(ti, "source") + tile.imageWidth = num(ti, "width") + tile.imageHeight = num(ti, "height") + end + local anim = Xml.child(t, "animation") + if anim then + tile.animation = {} + for _, f in Xml.children(anim, "frame") do + table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) }) + end + end + local og = Xml.child(t, "objectgroup") + if og then + tile.objectGroup = objectGroup(og) + end + table.insert(tiles, tile) + end + ts.tiles = tiles + return ts +end + +-- read(root) -> TileMap | nil, message, unsupported? +function Tmx.read(root: Node): (any, string?, boolean?) + if root.name ~= "map" then + return nil, "the root element is <" .. root.name .. ">, not <map>" + end + local map: any = Types.TileMap.new(num(root, "width", 0) :: number, num(root, "height", 0) :: number, num(root, "tilewidth", 0) :: number, num(root, "tileheight", 0) :: number) + map.version = a(root, "version") + map.tiledVersion = a(root, "tiledversion") + map.orientation = a(root, "orientation") or "orthogonal" + map.renderOrder = a(root, "renderorder") or "right-down" + map.infinite = flag(root, "infinite", false) + map.nextLayerId = num(root, "nextlayerid") + map.nextObjectId = num(root, "nextobjectid") + map.backgroundColor = Data.color(a(root, "backgroundcolor")) + map.hexSideLength = num(root, "hexsidelength") + map.staggerAxis = a(root, "staggeraxis") + map.staggerIndex = a(root, "staggerindex") + map.class = a(root, "class") or "" + map.parallaxOriginX = num(root, "parallaxoriginx", 0) + map.parallaxOriginY = num(root, "parallaxoriginy", 0) + withProps(map, root) + for _, c in root.children do + if type(c) == "table" then + if c.name == "tileset" then + table.insert(map.tilesets, Tmx.tileset(c)) + else + local l, err, uns = layer(c) + if err then + return nil, err, uns + end + if l then + table.insert(map.layers, l) + end + end + end + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +type Attrs = { [string]: string } + +local function el(name: string, attrs: { { any } }, children: { any }?): Node + -- attrs in order; nil / default values dropped by the caller + local o = Types.object() + for _, kv in attrs do + if kv[2] ~= nil then + local v = kv[2] + Types.set(o, kv[1], if type(v) == "number" then Data.num(v) elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v)) + end + end + return Xml.element(name, o :: any, children) +end + +local function nz(v: any, default: any): any + if v == nil or v == default then + return nil + end + return v +end +local function str(v: any): string? + if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propsNode(props: any, types: any): Node? + if type(props) ~= "table" or next(props) == nil then + return nil + end + local list = {} + for _, k in Data.sortedKeys(props) do + local v = props[k] + local typ = Data.typeOf(v, if type(types) == "table" then types[k] else nil) + if typ == "class" and type(v) == "table" then + local inner = propsNode(v.properties, v.propertyTypes) + table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, if inner then { inner } else nil)) + else + local text = if type(v) == "boolean" then (if v then "true" else "false") elseif type(v) == "number" then Data.num(v) else tostring(v) + if string.find(text, "\n", 1, true) then + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil } }, { text })) + else + table.insert(list, el("property", { { "name", k }, { "type", if typ ~= "string" then typ else nil }, { "value", text } })) + end + end + end + return el("properties", {}, list) +end + +local function addProps(children: { any }, t: any) + local p = propsNode(t.properties, t.propertyTypes) + if p then + table.insert(children, p) + end +end + +local function writeObject(o: any): Node + local kids = {} + addProps(kids, o) + local shape = o.shape + if shape == "ellipse" then + table.insert(kids, el("ellipse", {})) + elseif shape == "point" then + table.insert(kids, el("point", {})) + elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then + local pts = {} + for _, p in o.points do + table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0)) + end + table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } })) + elseif shape == "text" and type(o.text) == "table" then + local t = o.text + table.insert(kids, el("text", { + { "fontfamily", nz(t.fontFamily, "sans-serif") }, + { "pixelsize", nz(t.pixelSize, 16) }, + { "wrap", nz(t.wrap, false) }, + { "color", nz(t.color, "#000000") }, + { "bold", nz(t.bold, false) }, + { "italic", nz(t.italic, false) }, + { "underline", nz(t.underline, false) }, + { "strikeout", nz(t.strikeout, false) }, + { "kerning", nz(t.kerning, true) }, + { "halign", nz(t.halign, "left") }, + { "valign", nz(t.valign, "top") }, + }, { tostring(t.text or "") })) + end + return el("object", { + { "id", o.id }, + { "name", str(o.name) }, + { "type", str(o.class) }, + { "gid", o.gid }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + { "width", nz(o.width, 0) }, + { "height", nz(o.height, 0) }, + { "rotation", nz(o.rotation, 0) }, + { "visible", nz(o.visible, true) }, + { "template", o.template }, + }, kids) +end + +local function commonAttrs(l: any, extra: { { any } }): { { any } } + local out: { { any } } = { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } } + table.move(extra, 1, #extra, #out + 1, out) + local tail = { + { "visible", nz(l.visible, true) }, + { "locked", nz(l.locked, false) }, + { "opacity", nz(l.opacity, 1) }, + { "tintcolor", l.tintColor }, + { "offsetx", nz(l.offsetX, 0) }, + { "offsety", nz(l.offsetY, 0) }, + { "parallaxx", nz(l.parallaxX, 1) }, + { "parallaxy", nz(l.parallaxY, 1) }, + } + table.move(tail, 1, #tail, #out + 1, out) + return out +end + +local function writeObjectGroup(l: any, tag: string?): Node + local kids = {} + addProps(kids, l) + for _, o in (if type(l.objects) == "table" then l.objects else {}) do + table.insert(kids, writeObject(o)) + end + return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids) +end + +type WriteOptions = { encoding: string?, compression: string?, level: number? } + +local writeLayer: (l: any, o: WriteOptions) -> (Node?, string?) + +writeLayer = function(l: any, o: WriteOptions): (Node?, string?) + local t = l.type + if t == "tiles" then + local kids = {} + addProps(kids, l) + local enc = o.encoding or l.encoding or "csv" + local comp = if o.encoding then o.compression else (o.compression or l.compression) + if enc ~= "base64" then + comp = nil + end + local function payload(g: { number }, width: number): (string?, string?) + if enc == "csv" then + return Data.csvText(g, width), nil + end + local s, err = Data.toBase64(g, comp, o.level) + if not s then + return nil, err + end + return "\n " .. s .. "\n ", nil + end + local dataKids = {} + if type(l.chunks) == "table" then + for _, c in l.chunks do + local kids: { any } = {} + if enc == "xml" then + for _, g in (c.data or {}) do + table.insert(kids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + else + local s, err = payload(c.data or {}, c.width or 0) + if not s then + return nil, err + end + kids = { s } + end + table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids)) + end + elseif type(l.data) == "table" and enc == "xml" then + for _, g in l.data do + table.insert(dataKids, el("tile", { { "gid", if g ~= 0 then g else nil } })) + end + elseif type(l.data) == "table" then + local s, err = payload(l.data, l.width or 0) + if not s then + return nil, err + end + dataKids = { s } + end + table.insert(kids, el("data", { { "encoding", if enc == "xml" then nil else enc }, { "compression", comp } }, dataKids)) + return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil + elseif t == "objects" then + return writeObjectGroup(l), nil + elseif t == "image" then + local kids = {} + addProps(kids, l) + if l.imageSource then + table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } })) + end + return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil + elseif t == "group" then + local kids = {} + addProps(kids, l) + for _, c in (if type(l.layers) == "table" then l.layers else {}) do + local n, err = writeLayer(c, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + return el("group", commonAttrs(l, {}), kids), nil + end + return nil, "unknown layer type " .. tostring(t) +end + +-- tilesetNode(ts, inMap) -> <tileset> +function Tmx.tilesetNode(ts: any, inMap: boolean): Node + if inMap and type(ts.source) == "string" then + return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local kids = {} + if type(ts.tileOffset) == "table" then + table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } })) + end + addProps(kids, ts) + if ts.imageSource then + table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } })) + end + for _, tile in (if type(ts.tiles) == "table" then ts.tiles else {}) do + local tk = {} + addProps(tk, tile) + if tile.imageSource then + table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } })) + end + if type(tile.objectGroup) == "table" then + table.insert(tk, writeObjectGroup(tile.objectGroup)) + end + if type(tile.animation) == "table" then + local frames = {} + for _, f in tile.animation do + table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } })) + end + table.insert(tk, el("animation", {}, frames)) + end + table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk)) + end + return el("tileset", { + { "firstgid", if inMap then ts.firstGid or 1 else nil }, + { "name", ts.name or "" }, + { "class", str(ts.class) }, + { "tilewidth", ts.tileWidth or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "spacing", nz(ts.spacing, 0) }, + { "margin", nz(ts.margin, 0) }, + { "tilecount", ts.count or 0 }, + { "columns", ts.columns or 0 }, + { "objectalignment", ts.objectAlignment }, + }, kids) +end + +-- write(map, opts) -> an XML document node | nil, message +function Tmx.write(map: any, o: WriteOptions): (Node?, string?) + local kids = {} + addProps(kids, map) + for _, ts in map.tilesets do + table.insert(kids, Tmx.tilesetNode(ts, true)) + end + for _, l in map.layers do + local n, err = writeLayer(l, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + local root = el("map", { + { "version", map.version or "1.10" }, + { "tiledversion", map.tiledVersion }, + { "class", str(map.class) }, + { "orientation", map.orientation or "orthogonal" }, + { "renderorder", map.renderOrder or "right-down" }, + { "width", map.width }, + { "height", map.height }, + { "tilewidth", map.tileWidth }, + { "tileheight", map.tileHeight }, + { "hexsidelength", map.hexSideLength }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "backgroundcolor", map.backgroundColor }, + { "infinite", map.infinite == true }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + }, kids) + return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil +end + +return Tmx +end +__FILES["video/avi"] = function() + +-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. +-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces +-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, +-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is +-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, +-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. +-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's +-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. +-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Avi = __include("containers/Avi") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local AviFormat = { + name = "avi", + category = "video", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) + track: number?, -- the video track (stream index + 1) to decode + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + openAudio: any?, -- set by the api +} +type EncodeOptions = { + quality: number?, -- MJPEG quality 1..100 (default 90) + reencode: boolean?, -- encode the frames even when the source is MJPEG + audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + video: boolean?, + maxFps: number?, -- the highest frame rate variable delays may need (default 100) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- WAVEFORMATEX wFormatTag -> codec id +local AUDIO_TAGS: { [number]: string } = { + [0x0001] = "pcm", + [0x0002] = "adpcm_ms", + [0x0003] = "pcm_f", + [0x0006] = "pcm_alaw", + [0x0007] = "pcm_mulaw", + [0x0011] = "adpcm_ima_wav", + [0x0050] = "mp2", + [0x0055] = "mp3", + [0x00FF] = "aac", + [0x1610] = "aac", + [0x706D] = "aac", + [0x2000] = "ac3", + [0x2001] = "dts", + [0xF1AC] = "flac", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function AviFormat.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "video", + codec = "", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 25, + frameRate = if s.scale > 0 then s.rate / s.scale else 0, + default = true, + name = s.name, + frames = s.length, + } + if buffer.len(f) >= 40 then + local w = buffer.readi32(f, 4) + local h = buffer.readi32(f, 8) + local bits = buffer.readu16(f, 14) + local comp = buffer.readstring(f, 16, 4) + t.width = math.abs(w) + t.height = math.abs(h) + t.codecTag = comp + t.bitsPerPixel = bits + if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then + t.codec = "rawvideo" + t.pixelFormat = if bits == 32 then "bgra" else "bgr24" + t.flip = h > 0 + t.stride = ((math.abs(w) * bits + 31) // 32) * 4 + if bits ~= 24 and bits ~= 32 then + t.codec = "rawvideo_" .. bits + end + else + t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", ""))) + if comp == "YV12" then + t.pixelFormat = "yv12" + elseif t.codec == "rawvideo" then + t.pixelFormat = "yuv420p" + end + end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end + local size = buffer.readu32(f, 0) + if size > 40 and buffer.len(f) > 40 then + local c = buffer.create(buffer.len(f) - 40) + buffer.copy(c, 0, f, 40) + t.config = c + end + else + t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler) + local fr = s.frame + t.width, t.height = fr[3] - fr[1], fr[4] - fr[2] + end + return t +end + +local function audioTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "audio", + codec = "unknown", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 1, + default = true, + name = s.name, + waveFormat = f, + } + if buffer.len(f) >= 16 then + local tag = buffer.readu16(f, 0) + t.channels = buffer.readu16(f, 2) + t.sampleRate = buffer.readu32(f, 4) + t.blockAlign = buffer.readu16(f, 12) + local bits = buffer.readu16(f, 14) + t.bitsPerSample = bits + if tag == 0xFFFE and buffer.len(f) >= 26 then + tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag + end + t.formatTag = tag + local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag) + if c == "pcm" then + c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le" + elseif c == "pcm_f" then + c = "pcm_f" .. bits .. "le" + end + t.codec = c + if buffer.len(f) >= 18 then + local cb = buffer.readu16(f, 16) + if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then + local cfg = buffer.create(cb) + buffer.copy(cfg, 0, f, 18, cb) + t.config = cfg + end + end + end + return t +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + local streams: { { any } } = {} + for i, s in file.streams do + local t: Types.Track? = nil + if s.type == "vids" then + t = videoTrack(s, i) + elseif s.type == "auds" then + t = audioTrack(s, i) + elseif s.type == "txts" then + t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 } + end + if t then + table.insert(tracks, t) + table.insert(streams, { s, t }) + end + end + local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } + local dmx = Demux.new("avi", tracks, r.buf, meta) + -- packets in file order across streams: merge by offset + local items: { { number } } = {} + for k, st in streams do + local s: Avi.Stream, t: any = st[1], st[2] + local tick = s.start + for _, c in s.chunks do + local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1 + if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then + dur = c.size / t.blockAlign + end + if c.size > 0 then + table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size }) + tick += dur + elseif t.kind == "video" then + tick += 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding) + end + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, it in items do + local t: any = streams[it[2]][2] + dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local streams, err = Source.streams(value, o, { + video = { copy = { mjpeg = true }, encode = "mjpeg" }, + audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true }, + }) + if not streams then + return nil, err + end + local wstreams: { Avi.WStream } = {} + local width, height, usPerFrame = 0, 0, 0 + local frameDur = 0 + for _, s in streams do + if s.kind == "video" then + -- a constant frame rate: the shortest frame duration (variable delays repeat frames) + local num, den, packets = Source.constantRate(s, o.maxFps) + s.packets = packets + frameDur = den / num + width, height = s.width or 0, s.height or 0 + usPerFrame = 1e6 * frameDur + local bih = Bytes.writer(40) + bih:u32le(40) + bih:u32le(width) + bih:u32le(height) + bih:u16le(1) + bih:u16le(24) + bih:string("MJPG") + bih:u32le(width * height * 3) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" }) + else + local ch = s.channels or 1 + local bits = if s.codec == "pcm_u8" then 8 else 16 + local align = ch * bits // 8 + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local wf = Bytes.writer(18) + wf:u16le(1) + wf:u16le(ch) + wf:u32le(rate) + wf:u32le(rate * align) + wf:u16le(align) + wf:u16le(bits) + wf:u16le(0) + table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) + end + end + -- chunks in time order (the video packets already repeated to the constant rate) + local chunks: { { any } } = {} + for _, item in Source.interleave(streams) do + table.insert(chunks, { item[1], item[2].data, true }) + end + local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height } :: Avi.WOptions, chunks) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = AviFormat.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return AviFormat +end +__FILES["video/fli"] = function() + +-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC +-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). +-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: +-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, +-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 +-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the +-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. +-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r: Bytes.Reader): number + local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer | nil, Err +function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = if magic == FLI then 70 else 1000 + local track: Types.Track = { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + -- the frame chunks + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, size) + end + p += size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Fli +end +__FILES["video/flv"] = function() + +-- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's +-- FourCC video tags). New in rosetta. +-- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... +-- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by +-- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 +-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks +-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets +-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), +-- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through +-- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. +-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / +-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at +-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data +-- rates, codec ids, file size). +-- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx +-- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H263 = __include("codecs/video/H263") +local H264 = __include("codecs/video/H264") +local Aac = __include("codecs/audio/Aac") +local Amf = __include("video/flv/Amf") +local Mux = __include("video/flv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Flv = { + name = "flv", + category = "video", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id (1 video, 2 audio) + audio: boolean?, -- false: do not open the audio track + maxPackets: number?, -- refuse files with more tags (default 2^24) + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + video: boolean?, -- false: no video + audio: boolean?, -- false: no audio; true: fail when the audio cannot be written (default: dropped) + reencodeAudio: boolean?, -- PCM s16 even when the audio could be copied +} + +-- ------------------------------------------------------------------------------------------------ constants +Flv.VIDEO_ID = 1 +Flv.AUDIO_ID = 2 + +-- SoundFormat -> codec id +local AUDIO_CODECS: { [number]: string } = { + [0] = "pcm", -- platform-endian (little-endian in practice) + [1] = "adpcm_swf", + [2] = "mp3", + [3] = "pcm", + [4] = "nellymoser", + [5] = "nellymoser", + [6] = "nellymoser", + [7] = "pcm_alaw", + [8] = "pcm_mulaw", + [10] = "aac", + [11] = "speex", + [14] = "mp3", + [15] = "device_specific", +} +local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 } +-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono +local FIXED_RATE: { [number]: number } = { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 } +local MONO: { [number]: boolean } = { [4] = true, [5] = true, [11] = true } + +-- CodecID -> codec id +local VIDEO_CODECS: { [number]: string } = { + [2] = "flv1", + [3] = "flashsv", + [4] = "vp6f", + [5] = "vp6a", + [6] = "flashsv2", + [7] = "h264", +} + +-- Enhanced FLV audio FourCCs +local AUDIO_FOURCC: { [string]: string } = { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Flv.sniff(r: Bytes.Reader): number + if r:remaining() >= 9 and r:peek(3) == "FLV" then + return if r:peekU8(3) == 1 then 1 else 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +local function u24(b: buffer, p: number): number + return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end + +local function s24(b: buffer, p: number): number + local v = u24(b, p) + return if v >= 0x800000 then v - 0x1000000 else v +end + +local function copy(b: buffer, p: number, n: number): buffer + local c = buffer.create(n) + buffer.copy(c, 0, b, p, n) + return c +end + +-- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil +local function frameSize(codec: string, b: buffer, p: number, n: number): (number?, number?) + if codec == "flv1" then + local h = H263.header(b, p, n, true) + if h then + return h.width, h.height + end + elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then + -- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB + -- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height + local adj = readu8(b, p - 1) + local q = p + (if codec == "vp6a" then 3 else 0) + if q + 6 > p + n or readu8(b, q) >= 128 then + return nil, nil + end + local b1 = readu8(b, q + 1) + local o = q + 2 + if readu8(b, q) % 2 == 1 or (b1 // 2) % 4 == 0 then + o += 2 + end + if o + 4 > p + n then + return nil, nil + end + local w = readu8(b, o + 3) * 16 - adj // 16 + local h = readu8(b, o + 2) * 16 - adj % 16 + if w > 0 and h > 0 then + return w, h + end + elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then + return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3) + end + return nil, nil +end + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Flv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local o: OpenOptions = opts or {} + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then + return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base) + end + local flags = readu8(b, base + 4) + local dataOffset = buffer.readu32(b, base + 5) + dataOffset = bit32.byteswap(dataOffset) + if dataOffset < 9 or base + dataOffset > limit then + return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5) + end + local meta: { [string]: any } = { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 } + local tracks: { Types.Track } = {} + local dmx = Demux.new("flv", tracks, b, meta) + local vt: any, at: any = nil, nil + local keyOff, keyLen = -1, 0 -- the first video keyframe + local maxPackets = o.maxPackets or 2 ^ 24 + local count = 0 + local p = base + dataOffset + 4 -- after PreviousTagSize0 + while p + 11 <= limit do + local tagType = bit32.band(readu8(b, p), 0x1F) + local filtered = bit32.band(readu8(b, p), 0x20) ~= 0 + local size = u24(b, p + 1) + local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000 + if ts >= 0x80000000 then + ts -= 0x100000000 + end + local d = p + 11 + if d + size > limit then + meta.truncated = true + break + end + count += 1 + if count > maxPackets then + return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags") + end + if tagType == 8 and size >= 1 then + local a = readu8(b, d) + local fmt = a // 16 + if not at then + at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true } + table.insert(tracks, at) + local bits = if (a // 2) % 2 == 1 then 16 else 8 + local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt) + if codec == "pcm" then + codec = if bits == 16 then "pcm_s16le" else "pcm_u8" + end + at.codec = codec + at.soundFormat = fmt + at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(a // 4) % 4] + at.channels = if MONO[fmt] then 1 else a % 2 + 1 + at.bitsPerSample = if codec == "pcm_alaw" or codec == "pcm_mulaw" then 8 else bits + end + if filtered then + at.unsupported = "encrypted audio tags" + elseif fmt == 10 and at.soundFormat == 10 then + if size >= 2 then + if readu8(b, d + 1) == 0 then + local c = copy(b, d + 2, size - 2) + at.config = c + local cfg = Aac.config(c) + if cfg then + at.sampleRate = cfg.extensionRate or cfg.sampleRate + at.channels = cfg.channels + end + elseif size > 2 then + dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2) + end + end + elseif fmt == 9 and at.soundFormat == 9 then + -- Enhanced FLV: packet type, FourCC + if size >= 5 then + local pt = a % 16 + local fcc = buffer.readstring(b, d + 1, 4) + at.codec = AUDIO_FOURCC[fcc] or fcc + at.codecTag = fcc + if pt == 0 then + at.config = copy(b, d + 5, size - 5) + elseif pt == 1 and size > 5 then + dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5) + end + end + elseif fmt == at.soundFormat and size > 1 then + dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1) + end + elseif tagType == 9 and size >= 1 then + local v = readu8(b, d) + local enhanced = v >= 128 + local frameType = if enhanced then (v // 16) % 8 else v // 16 + if frameType ~= 5 then -- not a video info / command frame + local codec: string?, codecTag: string? = nil, nil + local pt, cts, q, n = 0, 0, 0, 0 + if enhanced then + if size < 5 then + codec = nil + else + local fcc = buffer.readstring(b, d + 1, 4) + codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc + pt = v % 16 + q, n, cts = d + 5, size - 5, 0 + if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then + if n >= 3 then + cts = s24(b, q) + end + q, n = q + 3, n - 3 + elseif pt == 3 then + pt = 1 -- coded frames without a composition time + end + end + else + local id = v % 16 + codec = VIDEO_CODECS[id] or ("flv_video_" .. id) + codecTag = "flv video " .. id + pt, q, n, cts = 1, d + 1, size - 1, 0 + if codec == "h264" then + if size >= 5 then + pt = readu8(b, d + 1) + cts = s24(b, d + 2) + else + pt = 2 + end + q, n = d + 5, size - 5 + elseif codec == "vp6f" or codec == "vp6a" then + q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata) + end + end + if codec then + if not vt then + vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true } + table.insert(tracks, vt) + end + if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then + vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte + end + if filtered then + vt.unsupported = "encrypted video tags" + elseif codec == vt.codec then + if pt == 0 then + if n > 0 then + vt.config = copy(b, q, n) + end + elseif pt == 1 and n > 0 then + local key = frameType == 1 + dmx:add(vt.id, ts + cts, ts, nil, key, q, n) + if key and keyOff < 0 then + keyOff, keyLen = q, n + end + end + end + end + end + elseif tagType == 18 and size > 0 then + local name, value = Amf.script(Bytes.reader(b, d, size)) + if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then + meta.metadata = value + elseif name then + meta.scripts = meta.scripts or {} + table.insert(meta.scripts, { name = name, time = ts / 1000, value = value }) + end + end + p = d + size + 4 + end + -- the track facts onMetaData and the codec headers give + local md: { [string]: any } = meta.metadata or {} + if type(md.duration) == "number" and md.duration > 0 then + meta.duration = md.duration + end + if vt then + if vt.codec == "h264" and vt.config then + local ok, info = pcall(H264.info, vt.config) + if ok and info then + vt.width, vt.height = info.width, info.height + end + elseif keyOff >= 0 then + local w, h = frameSize(vt.codec, b, keyOff, keyLen) + vt.width, vt.height = w, h + end + if not vt.width and type(md.width) == "number" and type(md.height) == "number" then + vt.width, vt.height = math.floor(md.width), math.floor(md.height) + end + local fr = md.framerate or md.videoframerate + if type(fr) == "number" and fr > 0 and fr < 1000 then + vt.frameRate = fr + else + -- from the timestamps: the frames over the time they span + local n = dmx:count(vt.id) + local t0 = if n > 0 then dmx:info(vt.id, 1) else nil + local t1 = if n > 1 then dmx:info(vt.id, n) else nil + if t0 and t1 and t1 > t0 then + vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000 + end + end + end + if at and at.codec == "aac" and not at.config then + at.unsupported = "AAC without its AudioSpecificConfig" + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer +function Flv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { + video = { copy = Mux.VIDEO_COPY }, + audio = { copy = Mux.AUDIO_COPY, pcm = true }, + }) + if not streams then + return nil, err + end + -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true + for i = #streams, 1, -1 do + local s = streams[i] + local why = s.kind == "audio" and Mux.audioProblem(s) + if why then + if o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, why) + end + table.remove(streams, i) + end + end + if #streams == 0 then + return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold") + end + local ok, buf, merr = pcall(Mux.mux, streams) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Flv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Flv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Flv +end +__FILES["video/flv/Amf"] = function() + +-- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 +-- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference +-- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the +-- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. +-- +-- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } +-- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +local Bytes = __include("core/Bytes") + +local Amf = {} + +-- null / undefined inside arrays (dropped from objects) +Amf.NULL = table.freeze({}) + +local MAX_DEPTH = 32 + +local function str(r: Bytes.Reader, long: boolean): string + local n = if long then r:u32be() else r:u16be() + return r:string(n) +end + +local readValue: (r: Bytes.Reader, depth: number, refs: { any }) -> any + +-- object properties up to the end marker (00 00 09) or the end of the data +local function props(r: Bytes.Reader, depth: number, refs: { any }, into: { [string]: any }): boolean + while not r.err and r:remaining() >= 3 do + local key = str(r, false) + if key == "" and r:peekU8() == 9 then + r:skip(1) + return true + end + local v = readValue(r, depth + 1, refs) + if r.err or v == nil then + return false + end + if v ~= Amf.NULL then + into[key] = v + end + end + return false +end + +readValue = function(r: Bytes.Reader, depth: number, refs: { any }): any + if depth > MAX_DEPTH or r:remaining() < 1 then + return nil + end + local t = r:u8() + if t == 0 then + return r:f64be() + elseif t == 1 then + return r:u8() ~= 0 + elseif t == 2 then + return str(r, false) + elseif t == 12 then + return str(r, true) + elseif t == 3 or t == 8 then + if t == 8 then + r:u32be() -- the count (approximate in practice: the end marker ends it) + end + local o: { [string]: any } = {} + table.insert(refs, o) + props(r, depth, refs, o) + return o + elseif t == 10 then + local n = r:u32be() + local a: { any } = {} + table.insert(refs, a) + for i = 1, n do + if r.err or r:remaining() < 1 then + break + end + local v = readValue(r, depth + 1, refs) + if v == nil then + break + end + a[i] = v + end + return a + elseif t == 5 or t == 6 then + return Amf.NULL + elseif t == 7 then + local i = r:u16be() + return refs[i + 1] or Amf.NULL + elseif t == 11 then + local ms = r:f64be() + r:i16be() + return ms + end + return nil +end + +-- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) +function Amf.value(r: Bytes.Reader): any + local ok, v = pcall(readValue, r, 0, {}) + return if ok and not r.err then v else nil +end + +-- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil +function Amf.script(r: Bytes.Reader): (string?, any) + local name = Amf.value(r) + if type(name) ~= "string" then + return nil, nil + end + return name, Amf.value(r) +end + +-- ------------------------------------------------------------------------------------------------ write +local function writeString(w: Bytes.Writer, s: string) + if #s > 65535 then + w:u8(12) + w:u32be(#s) + else + w:u8(2) + w:u16be(#s) + end + w:string(s) +end + +-- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null +function Amf.writeValue(w: Bytes.Writer, v: any) + local t = type(v) + if t == "number" then + w:u8(0) + w:f64be(v) + elseif t == "boolean" then + w:u8(1) + w:u8(if v then 1 else 0) + elseif t == "string" then + writeString(w, v) + elseif t == "table" and v ~= Amf.NULL and #v > 0 then + w:u8(10) + w:u32be(#v) + for _, x in v do + Amf.writeValue(w, x) + end + else + w:u8(5) + end +end + +-- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as +-- { key, { pairs = { ... } } } becomes an object) +function Amf.writeEcma(w: Bytes.Writer, list: { { any } }, object: boolean?) + if object then + w:u8(3) + else + w:u8(8) + w:u32be(#list) + end + for _, kv in list do + local k: string = kv[1] + w:u16be(#k) + w:string(k) + local v = kv[2] + if type(v) == "table" and v.pairs then + Amf.writeEcma(w, v.pairs, true) + else + Amf.writeValue(w, v) + end + end + w:u16be(0) + w:u8(9) +end + +return Amf +end +__FILES["video/flv/Mux"] = function() + +-- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag +-- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 +-- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source +-- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), +-- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made +-- from the first ADTS header. Interpreted; never throws (returns nil, Err). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Amf = __include("video/flv/Amf") + +local Mux = {} + +-- the codecs FLV holds (copied from the source) +local VIDEO_COPY: { [string]: boolean } = { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true } +local AUDIO_COPY: { [string]: boolean } = { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true } +Mux.VIDEO_COPY = VIDEO_COPY +Mux.AUDIO_COPY = AUDIO_COPY + +local VIDEO_IDS: { [string]: number } = { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 } +local AUDIO_FORMATS: { [string]: number } = { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 } +local RATE_CODES: { [number]: number } = { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 } +local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + +local function isAdts(s: any): boolean + if s.track and s.track.adts then + return true + end + local p = s.packets[1] + return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 +end + +-- audioProblem(stream) -> why FLV cannot hold this audio stream | nil +function Mux.audioProblem(s: any): string? + local fmt = AUDIO_FORMATS[s.codec] + if not fmt then + return "FLV has no audio codec " .. tostring(s.codec) + end + if (s.channels or 1) > 2 then + return "FLV audio has at most 2 channels" + end + local rate = math.floor((s.sampleRate or 0) + 0.5) + if s.codec == "aac" then + if not s.config and not isAdts(s) then + return "AAC without its AudioSpecificConfig" + end + elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then + return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")" + elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then + return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")" + end + return nil +end + +local function audioFlags(s: any): number + local fmt = AUDIO_FORMATS[s.codec] + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local rc = RATE_CODES[rate] or 3 + local size = if s.codec == "pcm_u8" then 0 else 1 + local stereo = if (s.channels or 1) > 1 then 1 else 0 + if s.codec == "aac" then + rc, stereo = 3, 1 + elseif s.codec == "mp3" and rate == 8000 then + fmt = 14 + elseif s.codec == "speex" then + rc, stereo = 0, 0 + elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then + rc = 0 + elseif s.codec == "nellymoser" then + if rate == 16000 then + fmt = 4 + elseif rate == 8000 then + fmt = 5 + end + stereo = 0 + end + return fmt * 16 + rc * 4 + size * 2 + stereo +end + +-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header +local function fromAdts(s: any): ({ any }?, buffer?) + local out = {} + local cfg: buffer? = nil + local rate = s.sampleRate or 44100 + for _, p in s.packets do + local d: buffer = p.data + local n = buffer.len(d) + local o = 0 + local t = p.pts + while o + 7 <= n do + local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3) + if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then + return nil, nil + end + local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + buffer.readu8(d, o + 5) // 32 + local hl = if b1 % 2 == 1 then 7 else 9 + if len < hl or o + len > n then + return nil, nil + end + if not cfg then + local aot = b2 // 64 + 1 + local sfi = (b2 // 4) % 16 + local ch = (b2 % 2) * 4 + b3 // 64 + cfg = buffer.create(2) + buffer.writeu8(cfg, 0, aot * 8 + sfi // 2) + buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8) + rate = AAC_RATES[sfi + 1] or rate + end + local f = buffer.create(len - hl) + buffer.copy(f, 0, d, o + hl, len - hl) + table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f }) + t += 1024 / rate + o += len + end + end + return out, cfg +end + +local function f64At(b: buffer, at: number, v: number) + local t = buffer.create(8) + buffer.writef64(t, 0, v) + for i = 0, 7 do + buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i)) + end +end + +-- mux(streams) -> buffer | nil, Err +function Mux.mux(streams: { any }): (buffer?, Err.Err?) + local video, audio = nil :: any, nil :: any + for _, s in streams do + if s.kind == "video" and not video then + if not VIDEO_IDS[s.codec] then + return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec)) + end + if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then + return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV") + end + video = s + elseif s.kind == "audio" and not audio then + audio = s + end + end + if not video and not audio then + return nil, Err.new(Err.ARG, "no video or audio stream") + end + local aConfig: buffer? = audio and audio.config + local aPackets: { any } = audio and audio.packets or {} + if audio and audio.codec == "aac" and isAdts(audio) then + local pk, cfg = fromAdts(audio) + if not pk or not cfg then + return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio") + end + aPackets, aConfig = pk, cfg + end + local order: { { any } } = {} -- { kind, packet } + do + local vi, ai = 1, 1 + local vp: { any } = if video then video.packets else {} + while vi <= #vp or ai <= #aPackets do + local a, v = aPackets[ai], vp[vi] + if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then + table.insert(order, { "video", v }) + vi += 1 + else + table.insert(order, { "audio", a }) + ai += 1 + end + end + end + -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative + local shift = 0 + local duration = 0 + local vBytes, aBytes = 0, 0 + for _, e in order do + local p = e[2] + local t = p.dts or p.pts + if t < -shift then + shift = -t + end + duration = math.max(duration, p.pts + (p.duration or 0)) + if e[1] == "video" then + vBytes += buffer.len(p.data) + else + aBytes += buffer.len(p.data) + end + end + local function ms(t: number): number + return math.floor((t + shift) * 1000 + 0.5) + end + + local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20) + w:string("FLV") + w:u8(1) + w:u8((if audio then 4 else 0) + (if video then 1 else 0)) + w:u32be(9) + w:u32be(0) + local function tag(kind: number, ts: number, head: { number }, data: buffer?) + local n = #head + (if data then buffer.len(data) else 0) + w:u8(kind) + w:u24be(n) + local t = ts % 0x100000000 + w:u24be(t % 0x1000000) + w:u8(t // 0x1000000) + w:u24be(0) + for _, x in head do + w:u8(x) + end + if data then + w:bytes(data) + end + w:u32be(11 + n) + end + + -- onMetaData + local props: { { any } } = { { "duration", duration } } + if video then + table.insert(props, { "width", video.width or 0 }) + table.insert(props, { "height", video.height or 0 }) + table.insert(props, { "videodatarate", if duration > 0 then vBytes * 8 / duration / 1000 else 0 }) + table.insert(props, { "framerate", video.frameRate or 0 }) + table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] }) + end + if audio then + local flags = audioFlags(audio) + table.insert(props, { "audiodatarate", if duration > 0 then aBytes * 8 / duration / 1000 else 0 }) + table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) }) + table.insert(props, { "audiosamplesize", if audio.codec == "pcm_u8" then 8 else 16 }) + table.insert(props, { "stereo", (audio.channels or 1) > 1 }) + table.insert(props, { "audiocodecid", flags // 16 }) + end + table.insert(props, { "encoder", "rosetta" }) + table.insert(props, { "filesize", 0 }) + local mw = Bytes.writer(512) + Amf.writeValue(mw, "onMetaData") + Amf.writeEcma(mw, props) + local metaBody = mw:finish() + local metaAt = w:tell() + 11 + tag(18, 0, {}, metaBody) + local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker + + -- sequence headers + local vid = if video then VIDEO_IDS[video.codec] else 0 + if video and video.codec == "h264" then + tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) + end + local aflags = if audio then audioFlags(audio) else 0 + if audio and audio.codec == "aac" then + tag(8, 0, { aflags, 0 }, aConfig) + end + local vp6 = if video and (video.codec == "vp6f" or video.codec == "vp6a") then video.config else nil + local vp6Byte = if vp6 and buffer.len(vp6) > 0 then buffer.readu8(vp6, 0) else 0 + if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then + local wd, ht = video.width or 0, video.height or 0 + vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16 + end + local lastVideo = 0 + for _, e in order do + local p = e[2] + local dts = ms(p.dts or p.pts) + if e[1] == "video" then + local ft = (if p.keyframe then 1 else 2) * 16 + vid + if video.codec == "h264" then + local cts = ms(p.pts) - dts + if cts < 0 then + cts += 0x1000000 + end + tag(9, dts, { ft, 1, cts // 65536 % 256, cts // 256 % 256, cts % 256 }, p.data) + elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then + tag(9, dts, { ft, vp6Byte }, p.data) + else + tag(9, dts, { ft }, p.data) + end + lastVideo = math.max(lastVideo, dts) + elseif audio.codec == "aac" then + tag(8, dts, { aflags, 1 }, p.data) + else + tag(8, dts, { aflags }, p.data) + end + end + if video and video.codec == "h264" then + tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil) + end + local out = w:finish() + f64At(out, fileSizeAt, buffer.len(out)) + return out, nil +end + +return Mux +end +__FILES["video/h264"] = function() + +-- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg +-- `-f h264` output, the JVT conformance bitstreams). New in rosetta. +-- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a +-- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw +-- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). +-- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, +-- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is +-- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H264 = __include("codecs/video/H264") + +-- ------------------------------------------------------------------------------------------------ contract +local Format = { + name = "h264", + category = "video", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + maxPixels: number?, -- largest picture (default 2^22 luma samples) + frameRate: number?, -- frames per second when the stream has no VUI timing (default 25) + deblock: boolean?, -- false skips the deblocking filter (faster, not conformant) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0) +function Format.sniff(r: Bytes.Reader): number + local s = r:peek(5) + if not s or #s < 4 then + return 0 + end + local hdr + if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then + hdr = string.byte(s, 4) + elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then + hdr = string.byte(s, 5) + else + return 0 + end + if hdr >= 128 then + return 0 + end + local t = hdr % 32 + if t == 7 then + return 0.8 + elseif t == 9 or t == 6 or t == 8 then + return 0.5 + elseif t == 5 then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err +function Format.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local units = H264.accessUnits(buf, base, limit - base) + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base) + end + local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {} + if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then + -- still demuxable (remuxing works); decoding reports UNSUPPORTED + info.unsupported = true + end + local fps = info.frameRate or (opts and opts.frameRate) or 25 + if fps <= 0 or fps > 1000 then + fps = 25 + end + local track: Types.Track = { + id = 1, + kind = "video", + codec = "h264", + timescale = fps, + width = info.width, + height = info.height, + frameRate = fps, + profile = info.profile, + level = info.level, + ptsInOutputOrder = true, + default = true, + } + local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level }) + local k = 0 + for i = 1, #units, 3 do + dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1]) + k += 1 + end + track.frames = k + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) +function Format.encode(value: any, _opts: any?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) + if not streams then + return nil, err + end + local s = streams[1] + if not s or s.codec ~= "h264" then + return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream") + end + local parts = {} + for i, p in s.packets do + local data = p.data + if s.config then + local key = i == 1 or p.keyframe + local out, e = H264.toAnnexB(if key then s.config else nil, data) + if not out then + return nil, e + end + data = out + end + table.insert(parts, buffer.tostring(data)) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Format.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Format.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Format +end +__FILES["video/mkv"] = function() + +-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in +-- rosetta, on containers/Ebml. +-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, +-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video +-- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio +-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text +-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. +-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied +-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from +-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. +-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, +-- track.unsupported says why), chapters / attachments (skipped), writing subtitles. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") +local Mux = __include("video/mkv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Mkv = { + name = "mkv", + category = "video", + 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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track number to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPackets: number?, -- refuse files with more packets (default 2^24) + maxPixels: number?, + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + format: string?, -- "webm" writes WebM (DocType webm, WebM codecs only); else Matroska + webm: boolean?, -- the same as format = "webm" + quality: number?, -- MJPEG quality 1..100 when frames are encoded (default 90) + reencode: boolean?, -- encode the frames even when the video track could be copied (Matroska: MJPEG) + video: boolean?, -- false: no video stream + audio: boolean?, -- false: no audio; true: fail if the audio cannot be written (default: dropped) + title: string?, + clusterSeconds: number?, -- target cluster length (default 2) +} + +-- ------------------------------------------------------------------------------------------------ constants +local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true } +local WEBM_AUDIO = { opus = true, vorbis = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mkv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "\26\69\223\163" then + return 0 + end + local head = r:peek(math.min(64, r:remaining())) + if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then + return 1 + end + return 0.5 +end + +-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) +function Mkv.variant(r: Bytes.Reader): string? + local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) + if ok and docType == "webm" then + return "webm" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) +-- or a Demuxer +function Mkv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") + local want: Source.Want + if webm then + want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } + else + local copy: { [string]: boolean } = {} + for id, e in Video.codecs do + if e.matroska then + copy[id] = true + end + end + want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } + end + local so = table.clone(o) + so.quality = so.quality or 90 + local streams, err = Source.streams(value, so, want) + if not streams then + return nil, err + end + if not webm then + -- audio codecs Matroska cannot name: PCM instead + for i, s in streams do + if s.kind == "audio" and not Mux.codecId("audio", s.codec) then + local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) + if alt and alt[1] then + streams[i] = alt[1] + else + return nil, aerr + end + end + end + end + local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err +function Mkv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + return dmx, err +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Mkv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mkv.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil +function Mkv.subtitles(dmx: any, trackId: number?): Types.Subtitles? + local track = nil + for _, t in dmx.tracks do + if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then + track = t + break + end + end + if not track then + return nil + end + local subs = Types.Subtitles.new() + subs.meta.codec = track.codec + subs.meta.language = track.language + for k = 1, dmx:count(track.id) do + local p = dmx:get(track.id, k) + if p then + local start = p.pts / track.timescale + local stop = start + (p.duration or 0) / track.timescale + table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) } :: Types.Cue) + end + end + return subs +end + +return Mkv +end +__FILES["video/mkv/Mux"] = function() + +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), +-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of +-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative +-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come +-- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +local Err = __include("core/Err") +local Ebml = __include("containers/Ebml") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") + +local ID = Parse.ID +local Mux = {} + +local AUDIO_IDS: { [string]: string } = { + vorbis = "A_VORBIS", + opus = "A_OPUS", + flac = "A_FLAC", + mp3 = "A_MPEG/L3", + mp2 = "A_MPEG/L2", + mp1 = "A_MPEG/L1", + aac = "A_AAC", + ac3 = "A_AC3", + eac3 = "A_EAC3", + alac = "A_ALAC", + pcm_u8 = "A_PCM/INT/LIT", + pcm_s16le = "A_PCM/INT/LIT", + pcm_s24le = "A_PCM/INT/LIT", + pcm_s32le = "A_PCM/INT/LIT", + pcm_s16be = "A_PCM/INT/BIG", + pcm_s24be = "A_PCM/INT/BIG", + pcm_s32be = "A_PCM/INT/BIG", + pcm_f32le = "A_PCM/FLOAT/IEEE", + pcm_f64le = "A_PCM/FLOAT/IEEE", +} +Mux.AUDIO_IDS = AUDIO_IDS + +-- codecId(stream) -> the Matroska CodecID | nil +function Mux.codecId(kind: string, codec: string): string? + if kind == "video" then + local e = Video.entry(codec) + local m = e and e.matroska + return m and m[1] + end + return AUDIO_IDS[codec] +end + +local function pcmBits(codec: string): number? + local b = string.match(codec, "^pcm_[suf](%d+)") + if b then + return tonumber(b) + end + if codec == "pcm_u8" then + return 8 + end + return nil +end + +type Options = { + webm: boolean?, + title: string?, + app: string?, + clusterSeconds: number?, -- default 2 +} + +-- mux(streams, opts) -> buffer | nil, Err +function Mux.mux(streams: { any }, opts: Options): (buffer?, Err.Err?) + local webm = opts.webm == true + local app = opts.app or "rosetta" + local clusterSpan = opts.clusterSeconds or 2 + -- tracks + local ids: { string } = {} + local videoIndex = 0 + for i, s in streams do + local cid = Mux.codecId(s.kind, s.codec) + if not cid then + return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec) + end + ids[i] = cid + if s.kind == "video" and videoIndex == 0 then + videoIndex = i + end + end + local order = Source.interleave(streams) + local duration = 0 + for _, s in streams do + for _, p in s.packets do + local e = p.pts + (p.duration or 0) + if e > duration then + duration = e + end + end + end + + -- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known) + local body = Ebml.writer(65536) + local infoAt = body:tell() + local info = body:open(ID.Info) + body:uint(ID.TimecodeScale, 1000000) + body:string(ID.MuxingApp, app) + body:string(ID.WritingApp, app) + if opts.title then + body:string(ID.Title, opts.title) + end + body:float(ID.Duration, duration * 1000) + body:close(info) + + local tracksAt = body:tell() + local tracks = body:open(ID.Tracks) + for i, s in streams do + local te = body:open(ID.TrackEntry) + body:uint(ID.TrackNumber, i) + body:uint(ID.TrackUID, i) + body:uint(ID.TrackType, if s.kind == "video" then 1 else 2) + body:uint(ID.FlagLacing, 0) + body:string(ID.Language, "und") + body:string(ID.CodecID, ids[i]) + if s.config and buffer.len(s.config) > 0 then + body:binary(ID.CodecPrivate, s.config) + end + if s.kind == "video" then + if s.frameRate and s.frameRate > 0 then + body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5)) + end + local v = body:open(ID.Video) + body:uint(ID.PixelWidth, s.width or 0) + body:uint(ID.PixelHeight, s.height or 0) + body:close(v) + else + if s.codec == "opus" then + local pre = 0 + local c = s.config + if c and buffer.len(c) >= 12 then + pre = buffer.readu16(c, 10) + end + body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5)) + body:uint(ID.SeekPreRoll, 80000000) + end + local a = body:open(ID.Audio) + body:float(ID.SamplingFrequency, s.sampleRate or 48000) + body:uint(ID.Channels, s.channels or 1) + local bits = pcmBits(s.codec) or s.bitsPerSample + if bits and string.sub(s.codec, 1, 4) == "pcm_" then + body:uint(ID.BitDepth, bits) + end + body:close(a) + end + body:close(te) + end + body:close(tracks) + + -- clusters + local cues: { { number } } = {} -- { time ms, track, cluster offset in body } + local cl: number? = nil + local clTime = 0 + local clStart = 0 + for _, item in order do + local si: number, p = item[1], item[2] + local ms = math.floor(p.pts * 1000 + 0.5) + local isVideoKey = si == videoIndex and p.keyframe + local need = cl == nil + or ms - clTime > 30000 + or ms < clTime + or (isVideoKey and ms - clStart >= clusterSpan * 1000) + or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000) + if need then + if cl then + body:close(cl) + end + local at = body:tell() + cl = body:open(ID.Cluster) + clTime = ms + clStart = ms + body:uint(ID.Timecode, ms) + if videoIndex == 0 or isVideoKey then + table.insert(cues, { ms, if videoIndex > 0 then videoIndex else si, at }) + end + end + local data: buffer = p.data + local hdr = Ebml.vintString(si, 1) + local rel = ms - clTime + local size = #hdr + 3 + buffer.len(data) + body:header(ID.SimpleBlock, size) + body:raw(hdr) + body:raw(string.char(rel // 256, rel % 256, if p.keyframe or streams[si].kind ~= "video" then 0x80 else 0)) + body:rawBuffer(data) + end + if cl then + body:close(cl) + end + local cuesAt = body:tell() + if #cues > 0 then + local c = body:open(ID.Cues) + for _, q in cues do + local cp = body:open(ID.CuePoint) + body:uint(ID.CueTime, q[1]) + local tp = body:open(ID.CueTrackPositions) + body:uint(ID.CueTrack, q[2]) + body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length + body:close(tp) + body:close(cp) + end + body:close(c) + end + local bodyBuf = body:finish() + + -- the SeekHead: its own length shifts every position, so build it until its size is stable + local function seekHead(shift: number): buffer + local w = Ebml.writer(256) + local sh = w:open(ID.SeekHead) + local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } } + if #cues > 0 then + table.insert(entries, { ID.Cues, cuesAt }) + end + for _, e in entries do + local sk = w:open(0x4DBB) + local idv = e[1] + local bytes = {} + while idv > 0 do + table.insert(bytes, 1, idv % 256) + idv = idv // 256 + end + w:header(0x53AB, #bytes) + for _, b in bytes do + w:raw(string.char(b)) + end + w:uint(0x53AC, e[2] + shift) + w:close(sk) + end + w:close(sh) + return w:finish() + end + local shift = 0 + local head = seekHead(0) + for _ = 1, 4 do + local n = buffer.len(head) + if n == shift then + break + end + shift = n + head = seekHead(shift) + end + shift = buffer.len(head) + -- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element + -- (its uint widths may grow, but Cues are last, so nothing after them moves) + if #cues > 0 then + local w = Ebml.writer(4096) + local c = w:open(ID.Cues) + for _, q in cues do + local cp = w:open(ID.CuePoint) + w:uint(ID.CueTime, q[1]) + local tp = w:open(ID.CueTrackPositions) + w:uint(ID.CueTrack, q[2]) + w:uint(ID.CueClusterPosition, q[3] + shift) + w:close(tp) + w:close(cp) + end + w:close(c) + local cuesBuf = w:finish() + local nb = buffer.create(cuesAt + buffer.len(cuesBuf)) + buffer.copy(nb, 0, bodyBuf, 0, cuesAt) + buffer.copy(nb, cuesAt, cuesBuf) + bodyBuf = nb + end + + -- the file + local out = Ebml.writer(buffer.len(bodyBuf) + 256) + local eb = out:open(ID.EBML) + out:uint(0x4286, 1) + out:uint(0x42F7, 1) + out:uint(0x42F2, 4) + out:uint(0x42F3, 8) + out:string(ID.DocType, if webm then "webm" else "matroska") + out:uint(0x4287, 4) + out:uint(0x4285, 2) + out:close(eb) + local seg = out:open(ID.Segment) + out:rawBuffer(head) + out:rawBuffer(bodyBuf) + out:close(seg) + return out:finish(), nil +end + +return Mux +end +__FILES["video/mkv/Parse"] = function() + +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles +-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, +-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, +-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by +-- default). Interpreted (it only walks headers); never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Ebml = __include("containers/Ebml") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Avi = __include("containers/Avi") +local QtPalette = __include("containers/IsoBmff/QtPalette") +local Deflate = __include("codecs/compress/Deflate") + +local Parse = {} + +-- element IDs +local ID = { + EBML = 0x1A45DFA3, + DocType = 0x4282, + Segment = 0x18538067, + SeekHead = 0x114D9B74, + Info = 0x1549A966, + TimecodeScale = 0x2AD7B1, + Duration = 0x4489, + Title = 0x7BA9, + MuxingApp = 0x4D80, + WritingApp = 0x5741, + DateUTC = 0x4461, + Tracks = 0x1654AE6B, + TrackEntry = 0xAE, + TrackNumber = 0xD7, + TrackUID = 0x73C5, + TrackType = 0x83, + FlagEnabled = 0xB9, + FlagDefault = 0x88, + FlagForced = 0x55AA, + FlagLacing = 0x9C, + DefaultDuration = 0x23E383, + Name = 0x536E, + Language = 0x22B59C, + LanguageBCP47 = 0x22B59D, + CodecID = 0x86, + CodecPrivate = 0x63A2, + CodecDelay = 0x56AA, + SeekPreRoll = 0x56BB, + Video = 0xE0, + PixelWidth = 0xB0, + PixelHeight = 0xBA, + DisplayWidth = 0x54B0, + DisplayHeight = 0x54BA, + ColourSpace = 0x2EB524, + Audio = 0xE1, + SamplingFrequency = 0xB5, + OutputSamplingFrequency = 0x78B5, + Channels = 0x9F, + BitDepth = 0x6264, + ContentEncodings = 0x6D80, + ContentEncoding = 0x6240, + ContentEncodingType = 0x5033, + ContentEncodingScope = 0x5032, + ContentCompression = 0x5034, + ContentCompAlgo = 0x4254, + ContentCompSettings = 0x4255, + ContentEncryption = 0x5035, + Cluster = 0x1F43B675, + Timecode = 0xE7, + SimpleBlock = 0xA3, + BlockGroup = 0xA0, + Block = 0xA1, + BlockDuration = 0x9B, + ReferenceBlock = 0xFB, + DiscardPadding = 0x75A2, + Cues = 0x1C53BB6B, + CuePoint = 0xBB, + CueTime = 0xB3, + CueTrackPositions = 0xB7, + CueTrack = 0xF7, + CueClusterPosition = 0xF1, + CueRelativePosition = 0xF0, + Tags = 0x1254C367, + Tag = 0x7373, + SimpleTag = 0x67C8, + TagName = 0x45A3, + TagString = 0x4487, + Targets = 0x63C0, + Chapters = 0x1043A770, + Attachments = 0x1941A469, + Void = 0xEC, + Crc32 = 0xBF, +} +Parse.ID = ID + +-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts) +local TOP: { [number]: boolean } = { + [ID.SeekHead] = true, + [ID.Info] = true, + [ID.Tracks] = true, + [ID.Cluster] = true, + [ID.Cues] = true, + [ID.Tags] = true, + [ID.Chapters] = true, + [ID.Attachments] = true, + [ID.Segment] = true, + [ID.EBML] = true, +} + +-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/video/Video registry) +local AUDIO: { [string]: string } = { + A_VORBIS = "vorbis", + A_OPUS = "opus", + A_FLAC = "flac", + ["A_MPEG/L3"] = "mp3", + ["A_MPEG/L2"] = "mp2", + ["A_MPEG/L1"] = "mp1", + A_AAC = "aac", + ["A_AAC/MPEG4/LC"] = "aac", + ["A_AAC/MPEG4/LC/SBR"] = "aac", + ["A_AAC/MPEG2/LC"] = "aac", + A_AC3 = "ac3", + A_EAC3 = "eac3", + A_DTS = "dts", + A_ALAC = "alac", + A_TTA1 = "tta", + A_WAVPACK4 = "wavpack", + ["A_MS/ACM"] = "acm", +} +local SUBS: { [string]: string } = { + ["S_TEXT/UTF8"] = "text", + ["S_TEXT/ASCII"] = "text", + ["S_TEXT/WEBVTT"] = "webvtt", + ["S_TEXT/ASS"] = "ass", + ["S_TEXT/SSA"] = "ssa", + ["S_ASS"] = "ass", + ["S_SSA"] = "ssa", + ["S_VOBSUB"] = "dvdsub", + ["S_HDMV/PGS"] = "pgs", +} + +-- codecFor(CodecID, bitDepth) -> our codec id +local function codecFor(id: string, kind: string, bits: number?): string + if kind == "video" then + return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) + end + if id == "A_PCM/INT/LIT" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "le" + elseif id == "A_PCM/INT/BIG" then + return if bits == 8 then "pcm_u8" else "pcm_s" .. (bits or 16) .. "be" + elseif id == "A_PCM/FLOAT/IEEE" then + return "pcm_f" .. (bits or 32) .. "le" + end + return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", ""))) +end +Parse.codecFor = codecFor + +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t: any, codecId: string, priv: buffer) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, size // 16777216 % 256) + buffer.writeu8(desc, 1, size // 65536 % 256) + buffer.writeu8(desc, 2, size // 256 % 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + +type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } + +local function parseVideo(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.PixelWidth then + t.width = Ebml.uint(buf, o, n) + elseif id == ID.PixelHeight then + t.height = Ebml.uint(buf, o, n) + elseif id == ID.DisplayWidth then + t.displayWidth = Ebml.uint(buf, o, n) + elseif id == ID.DisplayHeight then + t.displayHeight = Ebml.uint(buf, o, n) + elseif id == ID.ColourSpace then + t.colourSpace = buffer.readstring(buf, o, math.min(n, 4)) + end + end +end + +local function parseAudio(buf: buffer, off: number, len: number, t: any) + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.SamplingFrequency then + t.sampleRate = Ebml.float(buf, o, n) + elseif id == ID.OutputSamplingFrequency then + t.outputSampleRate = Ebml.float(buf, o, n) + elseif id == ID.Channels then + t.channels = Ebml.uint(buf, o, n) + elseif id == ID.BitDepth then + t.bitsPerSample = Ebml.uint(buf, o, n) + end + end +end + +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption +-- are not +local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.ContentEncoding then + local etype = 0 + local scope = 1 + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.ContentEncodingScope then + scope = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentEncodingType then + etype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentCompression then + local algo, settings = 0, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.ContentCompAlgo then + algo = Ebml.uint(buf, o3, n3) + elseif id3 == ID.ContentCompSettings then + settings = Ebml.binary(buf, o3, n3) + end + end + if algo == 3 then + t.strip = settings + elseif algo == 0 then + t.zlib = scope -- 1: frames, 2: CodecPrivate + else + return "content compression algorithm " .. algo + end + elseif id2 == ID.ContentEncryption then + return "encrypted track" + end + end + if etype ~= 0 then + return "encrypted track" + end + end + end + return nil +end + +local function parseTracks(buf: buffer, off: number, len: number, scaleNs: number): ({ TrackInfo }, { [number]: string }) + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TrackEntry then + local t: any = { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" } + local ttype, codecId = 0, "" + local problem: string? = nil + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.TrackNumber then + t.id = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackUID then + t.uid = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackType then + ttype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.FlagDefault then + t.default = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagEnabled then + t.enabled = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagLacing then + t.lacing = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.DefaultDuration then + t.defaultDurationNs = Ebml.uint(buf, o2, n2) + elseif id2 == ID.Name then + t.name = Ebml.string(buf, o2, n2) + elseif id2 == ID.Language then + t.language = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecID then + codecId = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecPrivate then + t.config = Ebml.binary(buf, o2, n2) + elseif id2 == ID.CodecDelay then + t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.SeekPreRoll then + t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.Video then + parseVideo(buf, o2, n2, t) + elseif id2 == ID.Audio then + parseAudio(buf, o2, n2, t) + elseif id2 == ID.ContentEncodings then + problem = parseEncodings(buf, o2, n2, t) + end + end + if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then + local c = Deflate.zlib(t.config) + if c then + t.config = c + else + problem = "bad zlib-compressed CodecPrivate" + end + end + t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" + t.codecTag = codecId + t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + local cfg: buffer? = t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) + end + if t.kind == "audio" then + t.sampleRate = t.sampleRate or 8000 + t.channels = t.channels or 1 + end + if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then + t.frameRate = 1e9 / t.defaultDurationNs + end + if t.id > 0 then + table.insert(tracks, t) + if problem then + problems[t.id] = problem + end + end + end + end + return tracks, problems +end + +local function parseInfo(buf: buffer, off: number, len: number, meta: { [string]: any }): (number, number?) + local scale, duration = 1000000, nil + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.TimecodeScale then + scale = Ebml.uint(buf, o, n) + elseif id == ID.Duration then + duration = Ebml.float(buf, o, n) + elseif id == ID.Title then + meta.title = Ebml.string(buf, o, n) + elseif id == ID.MuxingApp then + meta.muxingApp = Ebml.string(buf, o, n) + elseif id == ID.WritingApp then + meta.writingApp = Ebml.string(buf, o, n) + end + end + if scale <= 0 then + scale = 1000000 + end + return scale, duration +end + +local function parseCues(buf: buffer, off: number, len: number, segData: number): { { time: number, track: number, position: number } } + local cues = {} + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.CuePoint then + local time = 0 + local positions = {} + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.CueTime then + time = Ebml.uint(buf, o2, n2) + elseif id2 == ID.CueTrackPositions then + local tr, pos = 0, 0 + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.CueTrack then + tr = Ebml.uint(buf, o3, n3) + elseif id3 == ID.CueClusterPosition then + pos = Ebml.uint(buf, o3, n3) + end + end + table.insert(positions, { tr, pos }) + end + end + for _, p in positions do + table.insert(cues, { time = time, track = p[1], position = segData + p[2] }) + end + end + end + return cues +end + +local function parseTags(buf: buffer, off: number, len: number, meta: { [string]: any }) + local tags = meta.tags or {} + meta.tags = tags + for id, o, n in Ebml.children(buf, off, off + len) do + if id == ID.Tag then + for id2, o2, n2 in Ebml.children(buf, o, o + n) do + if id2 == ID.SimpleTag then + local name, value = nil, nil + for id3, o3, n3 in Ebml.children(buf, o2, o2 + n2) do + if id3 == ID.TagName then + name = Ebml.string(buf, o3, n3) + elseif id3 == ID.TagString then + value = Ebml.string(buf, o3, n3) + end + end + if name and value and tags[string.lower(name)] == nil then + tags[string.lower(name)] = value + end + end + end + end + end +end + +type Ctx = { + buf: buffer, + dmx: any, + byNum: { [number]: TrackInfo }, + scaleNs: number, + err: string?, + maxPackets: number, +} + +-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing +local function block(ctx: Ctx, off: number, len: number, clusterTime: number, simple: boolean, keyHint: boolean?, durTicks: number?, discardNs: number?) + local buf = ctx.buf + local limit = off + len + local tn, tl = Ebml.vint(buf, off, limit) + if not tn or not tl or tn < 0 or off + tl + 3 > limit then + return + end + local p = off + tl + local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1) + if rel >= 32768 then + rel -= 65536 + end + local flags = buffer.readu8(buf, p + 2) + p += 3 + local t = ctx.byNum[tn] + if not t then + return + end + local key = if simple then bit32.band(flags, 0x80) ~= 0 else (keyHint ~= false) + if t.kind == "audio" or t.kind == "subtitle" then + key = true + end + local pts = clusterTime + rel + local lacing = bit32.band(bit32.rshift(flags, 1), 3) + local sizes: { number } = {} + if lacing == 0 then + sizes[1] = limit - p + else + if p >= limit then + return + end + local count = buffer.readu8(buf, p) + 1 + p += 1 + if lacing == 1 then -- Xiph + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= limit then + return + end + local b = buffer.readu8(buf, p) + p += 1 + s += b + if b ~= 255 then + break + end + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + elseif lacing == 3 then -- EBML + local s, l = Ebml.vint(buf, p, limit) + if not s or not l or s < 0 then + return + end + p += l + sizes[1] = s + local total = s + for k = 2, count - 1 do + local d, dl = Ebml.svint(buf, p, limit) + if not d or not dl then + return + end + p += dl + s += d + if s < 0 then + return + end + sizes[k] = s + total += s + end + sizes[count] = limit - p - total + else -- fixed + local each = (limit - p) // count + for k = 1, count do + sizes[k] = each + end + end + if sizes[count] < 0 then + return + end + end + -- frames after the first of a lace: the track's default duration + local stepTicks = 0 + if t.defaultDurationNs and t.defaultDurationNs > 0 then + stepTicks = t.defaultDurationNs / ctx.scaleNs + elseif durTicks and #sizes > 0 then + stepTicks = durTicks / #sizes + end + local dmx = ctx.dmx + for k, s in sizes do + if p + s > limit then + return + end + if dmx.n >= ctx.maxPackets then + ctx.err = "too many packets" + return + end + local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil) + local kf = key and (k == 1 or t.kind ~= "video") + local strip = t.strip + local z = (t :: any).zlib + if z and bit32.band(z, 1) ~= 0 then + local out = Deflate.zlib(buf, p, s) + if out then + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out) + end + elseif strip then + local nb = buffer.create(buffer.len(strip) + s) + buffer.copy(nb, 0, strip) + buffer.copy(nb, buffer.len(strip), buf, p, s) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb) + else + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s) + end + if discardNs and k == #sizes then + dmx:setExtra("discardPadding", discardNs / 1e9) + end + p += s + end +end + +-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended +local function cluster(ctx: Ctx, off: number, limit: number, unknown: boolean): number + local buf = ctx.buf + local pos = off + local time = 0 + while pos < limit and not ctx.err do + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + return limit + end + if unknown and TOP[id] then + return pos + end + if size < 0 then + size = limit - data -- an unknown-size child: to the end + end + if data + size > limit then + size = limit - data + end + if id == ID.Timecode then + time = Ebml.uint(buf, data, size) + elseif id == ID.SimpleBlock then + block(ctx, data, size, time, true) + elseif id == ID.BlockGroup then + local bo, bl = -1, 0 + local ref, dur, discard = false, nil, nil + for id2, o2, n2 in Ebml.children(buf, data, data + size) do + if id2 == ID.Block then + bo, bl = o2, n2 + elseif id2 == ID.ReferenceBlock then + ref = true + elseif id2 == ID.BlockDuration then + dur = Ebml.uint(buf, o2, n2) + elseif id2 == ID.DiscardPadding then + discard = Ebml.int(buf, o2, n2) + end + end + if bo >= 0 then + block(ctx, bo, bl, time, false, not ref, dur, discard) + end + end + pos = data + size + end + return pos +end + +type Options = { maxPackets: number? } + +-- parse(buf, base, limit, opts) -> a Demux | nil, Err +-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data +-- offset | nil, Err +function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?) + local id, size, data = Ebml.header(buf, base, limit) + if id ~= ID.EBML or not size or not data then + return nil, Err.new(Err.CORRUPT, "not an EBML file", base) + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base) + end + local docType = "matroska" + for cid, o, n in Ebml.children(buf, data, math.min(limit, data + size)) do + if cid == ID.DocType then + docType = Ebml.string(buf, o, n) + end + end + return docType, size, data +end + +function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?) + local docType, size, data = Parse.docType(buf, base, limit) + if not docType then + return nil, size + end + if docType ~= "matroska" and docType ~= "webm" then + return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) + end + local pos = data + size + -- the Segment (skip anything else at the top level) + local segData, segEnd = -1, limit + while pos < limit do + local sid, ssize, sdata = Ebml.header(buf, pos, limit) + if not sid or not ssize or not sdata then + break + end + if sid == ID.Segment then + segData = sdata + segEnd = if ssize < 0 or sdata + ssize > limit then limit else sdata + ssize + break + end + if ssize < 0 then + break + end + pos = sdata + ssize + end + if segData < 0 then + return nil, Err.new(Err.TRUNCATED, "no Segment") + end + local meta: { [string]: any } = { docType = docType } + local scaleNs, duration = 1000000, nil :: number? + local tracks: { TrackInfo } = {} + local problems: { [number]: string } = {} + local cuesAt: { number } = {} + local clusters: { { number } } = {} + -- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead) + pos = segData + while pos < segEnd do + local cid, csize, cdata = Ebml.header(buf, pos, segEnd) + if not cid or not csize or not cdata then + break + end + local unknown = csize < 0 + local cend = if unknown or cdata + csize > segEnd then segEnd else cdata + csize + if cid == ID.Info then + local d + scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta) + duration = d + elseif cid == ID.Tracks then + tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) + elseif cid == ID.Cluster then + if unknown then + -- find its end: walk children until a top-level ID + local p = cdata + while p < segEnd do + local xid, xsize, xdata = Ebml.header(buf, p, segEnd) + if not xid or not xsize or not xdata or TOP[xid] then + break + end + if xsize < 0 then + p = segEnd + break + end + p = math.min(segEnd, xdata + xsize) + end + cend = p + end + table.insert(clusters, { cdata, cend }) + elseif cid == ID.Cues then + table.insert(cuesAt, cdata) + table.insert(cuesAt, cend - cdata) + elseif cid == ID.Tags then + parseTags(buf, cdata, cend - cdata, meta) + end + if cend <= pos then + break + end + pos = cend + end + if #tracks == 0 then + return nil, Err.new(Err.CORRUPT, "no tracks") + end + -- track timescales follow the final TimecodeScale (Info may follow Tracks) + local byNum: { [number]: TrackInfo } = {} + for _, t in tracks do + t.timescale = 1e9 / scaleNs + byNum[t.id] = t + end + local dmx = Demux.new(if docType == "webm" then "webm" else "mkv", tracks :: any, buf, meta) + local ctx: Ctx = { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 } + for _, c in clusters do + cluster(ctx, c[1], c[2], false) + if ctx.err then + return nil, Err.new(Err.LIMIT, ctx.err) + end + end + if duration then + dmx.duration = duration * scaleNs / 1e9 + end + local cues = {} + for k = 1, #cuesAt, 2 do + for _, c in parseCues(buf, cuesAt[k], cuesAt[k + 1], segData) do + c.time = c.time * scaleNs / 1e9 + table.insert(cues, c) + end + end + meta.cues = cues + meta.timecodeScale = scaleNs + for tid, msg in problems do + local t = byNum[tid] + t.unsupported = msg + end + dmx:finish() + return dmx, nil +end + +return Parse +end +__FILES["video/mp4"] = function() + +-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on +-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. +-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first +-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as +-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG +-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through +-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / +-- 'lpcm' / 'ipcm'). +-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied +-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v +-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV +-- only; MP4 drops other audio unless opts.audio = true, which fails). +-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented +-- writing, timed text tracks, encrypted tracks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local IsoBmff = __include("containers/IsoBmff") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp4 = { + name = "mp4", + category = "video", + 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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- the video track id (default: the first video track) + audio: boolean?, + maxPixels: number?, + maxSamples: number?, + openAudio: any?, -- set by the api +} +type EncodeOptions = { + format: string?, -- "mov" writes QuickTime (brand 'qt '); else MP4 (brand 'isom') + quality: number?, -- MJPEG quality when frames are encoded (default 90) + reencode: boolean?, -- encode the frames to MJPEG even when the video could be copied + video: boolean?, + audio: boolean?, -- false: no audio; true: fail when the audio cannot be written +} + +-- ------------------------------------------------------------------------------------------------ constants +local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true } +local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true } +-- copied video codecs -> sample entry (MP4 / MOV) +local VIDEO_ENTRY: { [string]: string } = { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" } +local AUDIO_ENTRY: { [string]: string } = { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mp4.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil or IMAGE_BRANDS[brand] then + return 0 + end + if AUDIO_BRANDS[brand] then + return 0.2 + end + if brand == "M4V " then + return 0.9 + end + return if brand == "" then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian) +local function opusHead(d: buffer): buffer? + if buffer.len(d) < 11 then + return nil + end + local w = Bytes.writer(19 + buffer.len(d)) + w:string("OpusHead") + w:u8(1) + local ch = buffer.readu8(d, 1) + w:u8(ch) + w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3)) + w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7)) + w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9)) + local family = buffer.readu8(d, 10) + w:u8(family) + if family ~= 0 and buffer.len(d) >= 13 + ch then + w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping + end + return w:finish() +end + +local function pcmCodec(t: any): string + local p = t.pcm + local bits = if p then p.bits else (t.bitsPerSample or 16) + if p and p.float then + return "pcm_f" .. bits .. (if p.little then "le" else "be") + end + if bits == 8 then + return if t.entry == "raw " then "pcm_u8" else "pcm_s8" + end + return "pcm_s" .. bits .. (if p == nil or p.little then "le" else "be") +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie)) + end + if not movie then + return nil, err + end + local tracks: { Types.Track } = {} + local src = {} + for _, it in movie.tracks do + local t: any = { + id = it.id, + kind = it.kind, + codec = it.codec, + codecTag = it.entry, + timescale = it.timescale, + duration = it.duration, + language = it.language, + width = it.width, + height = it.height, + sampleRate = it.sampleRate, + channels = it.channels, + bitsPerSample = it.bitsPerSample, + config = it.config, + default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, + } + if it.kind == "video" then + if not Video.entry(t.codec) then + t.codec = Video.fromFourcc(it.entry) or t.codec + end + if it.sampleCount > 0 and it.duration > 0 then + t.frameRate = it.sampleCount / it.duration + end + elseif it.kind == "audio" then + if it.codec == "pcm" then + t.codec = pcmCodec(it) + elseif it.codec == "ulaw" then + t.codec = "pcm_mulaw" + elseif it.codec == "alaw" then + t.codec = "pcm_alaw" + elseif it.codec == "opus" and it.config then + t.config = opusHead(it.config) + end + if it.skip and it.skip > 0 then + t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg + end + if it.playDuration and it.playDuration > 0 and it.timescale > 0 then + t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played + end + end + table.insert(tracks, t) + table.insert(src, it) + end + local dmx = Demux.new(if movie.brand == "qt " then "mov" else "mp4", tracks, r.buf, { brand = movie.brand }) + -- samples in file order across tracks + local items: { { number } } = {} + for k, it in src do + -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio + -- keeps it as its codec delay), plus an initial empty edit (converted to media ticks) + local shift = 0 + if it.kind == "video" then + shift = -(it.skip or 0) + end + if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then + shift += it.delay / movie.timescale * it.timescale + end + for i = 1, it.sampleCount do + table.insert(items, { it.offsets[i], k, i, shift }) + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, e in items do + local it = src[e[2]] + local i = e[3] + local dts = it.dts[i] + local pts = dts + (if it.cts then it.cts[i] or 0 else 0) + e[4] + dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- OpusHead -> dOps payload +local function dOps(head: buffer?): buffer? + if not head or buffer.len(head) < 19 then + return nil + end + local w = Bytes.writer(16) + w:u8(0) + local ch = buffer.readu8(head, 9) + w:u8(ch) + w:u16be(buffer.readu16(head, 10)) + w:u32be(buffer.readu32(head, 12)) + w:u16be(buffer.readu16(head, 16)) + local family = buffer.readu8(head, 18) + w:u8(family) + if family ~= 0 and buffer.len(head) >= 21 + ch then + w:bytes(head, 19, 2 + ch) + end + return w:finish() +end + +-- encode(video, opts?) -> buffer | nil, Err +function Mp4.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.quality = o.quality or 90 + local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt") + local vcopy: { [string]: boolean } = { mjpeg = true } + for id in VIDEO_ENTRY do + vcopy[id] = true + end + local acopy: { [string]: boolean } = {} + for id in AUDIO_ENTRY do + acopy[id] = true + end + acopy.pcm_s16le = mov + local streams, err = Source.streams(value, o, { + video = { copy = vcopy, encode = "mjpeg" }, + audio = { copy = acopy, pcm = mov }, + }) + if not streams then + return nil, err + end + local mtracks = {} + for _, s in streams do + local scale = if s.kind == "audio" then math.floor((s.sampleRate or 48000) + 0.5) else 90000 + if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then + scale = s.track.timescale + end + local samples, durations, cts, sync = {}, {}, {}, {} + local anyCts = false + local firstDts = nil :: number? + for i, p in s.packets do + samples[i] = p.data + local dts = p.dts or p.pts + firstDts = firstDts or dts + local nextP = s.packets[i + 1] + local d = if nextP then (nextP.dts or nextP.pts) - dts else p.duration + durations[i] = math.max(0, math.floor(d * scale + 0.5)) + local c = math.floor((p.pts - dts) * scale + 0.5) + cts[i] = c + if c ~= 0 then + anyCts = true + end + if p.keyframe then + sync[i] = true + end + end + -- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay + local skip = 0 + if firstDts and firstDts < 0 then + skip = math.floor(-firstDts * scale + 0.5) + end + if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then + skip = math.floor(s.track.codecDelay * scale + 0.5) + end + -- video: the skipped decode delay is a composition shift, every frame still plays (ffmpeg drops the frames an + -- edit cuts); audio: the codec delay samples are not played + local playDuration = nil + if s.kind == "video" and skip > 0 then + playDuration = 0 + for _, d in durations do + playDuration += d + end + elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then + playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim + end + local t: any = { + kind = s.kind, + timescale = scale, + skip = if skip > 0 then skip else nil, + playDuration = playDuration, + samples = samples, + durations = durations, + cts = if anyCts then cts else nil, + sync = sync, + width = s.width, + height = s.height, + sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5), + channels = s.channels, + } + if s.kind == "video" then + if s.codec == "mjpeg" then + t.entry = if mov then "jpeg" else "mp4v" + if not mov then + t.objectType = 0x6C + t.configBox = "esds" + t.config = buffer.create(0) + end + else + t.entry = VIDEO_ENTRY[s.codec] + t.config = s.config + end + else + if s.codec == "pcm_s16le" then + t.entry = "sowt" + t.bitsPerSample = 16 + else + t.entry = AUDIO_ENTRY[s.codec] + t.config = if s.codec == "opus" then dOps(s.config) else s.config + if s.codec == "mp3" then + t.objectType = 0x6B + t.configBox = "esds" + t.config = buffer.create(0) + end + end + end + if not t.entry then + return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec) + end + table.insert(mtracks, t) + end + return IsoBmff.mux({ brand = if mov then "qt " else "isom", compatible = if mov then { "qt " } else { "isom", "iso2", "mp41" }, tracks = mtracks }) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Mp4.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Mp4.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Mp4 +end +__FILES["video/mpegps"] = function() + +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / +-- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both +-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get +-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). +-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its +-- sequence extension), audio through the api's opts.openAudio hook. +-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegPs = __include("containers/MpegPs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ps = { + name = "mpegps", + category = "video", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- the video stream id to decode (0xE0.. ; default: the first video stream) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ps.sniff(r: Bytes.Reader): number + if r:peek(4) == "\0\0\1\186" then + return 0.9 + end + if r:peek(4) == "\0\0\1\179" then + return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header) + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps +local function videoPackets(dmx: any, buf: buffer, s: MpegPs.Stream, t: any) + local total = 0 + for _, p in s.pes do + total += p.size + end + local es = buffer.create(total) + local starts: { number } = {} + local o = 0 + for i, p in s.pes do + starts[i] = o + buffer.copy(es, o, buf, p.offset, p.size) + o += p.size + end + local info = MpegEs.info(es, 0, total) + if info then + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + if info.mpeg2 then + t.codec = "mpeg2" + end + end + local pics = MpegEs.pictures(es, 0, total) + local fd = if t.frameRate and t.frameRate > 0 then 90000 / t.frameRate else 3600 + -- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it) + local k = 1 + local used: { [number]: boolean } = {} + local ptsOf: { [number]: number } = {} + for i, pic in pics do + while k < #s.pes and starts[k + 1] <= pic.offset do + k += 1 + end + -- a PES whose payload starts inside this picture's headers also labels it + local pes = s.pes[k] + if pes and pes.pts and not used[k] then + used[k] = true + ptsOf[i] = pes.pts + end + end + -- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0) + local anchorPts, anchorTr = nil :: number?, 0 + local lastPts = nil :: number? + local timed = next(ptsOf) ~= nil + local count = 0 + for i, pic in pics do + if pic.gop then + anchorPts = nil + if not timed then + anchorPts, anchorTr = count * fd, 0 + end + end + if not timed and anchorPts == nil then + anchorPts, anchorTr = count * fd, pic.temporal + end + count += 1 + local pts = ptsOf[i] + if pts then + anchorPts, anchorTr = pts, pic.temporal + elseif anchorPts then + pts = anchorPts + (pic.temporal - anchorTr) * fd + elseif lastPts then + pts = lastPts + fd + end + if pts then + lastPts = pts + local d = buffer.create(pic.size) + buffer.copy(d, 0, es, pic.offset, pic.size) + dmx:addData(t.id, pts, nil, fd, pic.type == 1, d) + end + end +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ps.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + if r:peek(4) == "\0\0\1\179" then + -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps + local t: any = { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 } + local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true }) + videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t) + dmx:finish() + return dmx, nil + end + local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + for _, id in file.order do + local s = file.streams[id] + table.insert(tracks, { + id = id, + kind = s.kind :: any, + codec = s.codec, + codecTag = string.format("0x%02x", id % 256), + timescale = 90000, + streamId = id, + } :: Types.Track) + end + local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors }) + for i, id in file.order do + local s = file.streams[id] + local t: any = tracks[i] + if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then + videoPackets(dmx, r.buf, s, t) + else + local last = nil :: number? + for _, p in s.pes do + local pts = p.pts or last + if pts and p.size > 0 then + last = pts + dmx:add(id, pts, p.dts, nil, true, p.offset, p.size) + end + end + if t.codec == "mp2" and #s.pes > 0 then + local p = s.pes[1] + local b = r.buf + for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do + if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then + local layer = (buffer.readu8(b, i2 + 1) // 2) % 4 + t.codec = if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + break + end + end + end + end + end + dmx:finish() -- (read() without a track gives the video packets first, then the audio ones) + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ps.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ps.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ps +end +__FILES["video/mpegts"] = function() + +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, +-- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS +-- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the +-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, +-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. +-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, +-- PES without PTS for video before the first one (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegTs = __include("containers/MpegTs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ts = { + name = "mpegts", + category = "video", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, + track: number?, -- the video PID to decode (default: the first video stream of the PMT) + audio: boolean?, + maxPixels: number?, + openAudio: any?, -- set by the api +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEC: { [string]: string } = { + mpeg1video = "mpeg1", + mpeg2video = "mpeg2", + mpegaudio = "mp2", + aac = "aac", + aac_latm = "aac_latm", + h264 = "h264", + hevc = "hevc", + mpeg4 = "mpeg4", + ac3 = "ac3", + eac3 = "eac3", +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart +-- (fewer in a short file) within the first 2 KB +local function packetSize(r: Bytes.Reader): (number, number) + local n = r:remaining() + for start = 0, math.min(n, 2048) - 1 do + if r:peekU8(start) == 0x47 then + for _, size in { 188, 192 } do + local hits, need = 0, math.min(3, (n - start - 1) // size + 1) + for k = 0, 2 do + local at = start + k * size + if at < n and r:peekU8(at) == 0x47 then + hits += 1 + end + end + if hits >= need and (need >= 2 or start == 0) then + if size == 192 and start >= 4 then + return 192, start - 4 + elseif size == 188 then + return 188, start + end + end + end + end + end + return 0, 0 +end + +function Ts.sniff(r: Bytes.Reader): number + local s, off = packetSize(r) + if s == 0 then + return 0 + end + if off > 0 then + return 0.6 + end + return if r:remaining() >= 3 * s then 0.9 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps) +local function strip192(b: buffer, base: number, limit: number): buffer + local n = (limit - base) // 192 + local out = buffer.create(n * 188) + for i = 0, n - 1 do + buffer.copy(out, i * 188, b, base + i * 192 + 4, 188) + end + return out +end + +local function mpegAudioCodec(u: any): string + local d: buffer = u.data + for i = 0, math.min(buffer.len(d), 4096) - 2 do + if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then + local layer = (buffer.readu8(d, i + 1) // 2) % 4 + return if layer == 1 then "mp3" elseif layer == 3 then "mp1" else "mp2" + end + end + return "mp2" +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ts.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local size, off = packetSize(r) + if size == 0 then + return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base) + end + local d = MpegTs.new() + if size == 192 then + local b = strip192(r.buf, r.base + off, r.limit) + d:push(b, 0, buffer.len(b)) + else + d:push(r.buf, r.base + off, r.limit - r.base - off) + end + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no PES units") + end + -- tracks: the PMT's streams, then PIDs found without one + local tracks: { Types.Track } = {} + local byPid: { [number]: any } = {} + local function track(pid: number, kind: string, codec: string, st: number, lang: string?): any + local t = byPid[pid] + if t then + return t + end + t = { + id = pid, + kind = if kind == "other" then "data" else kind, + codec = CODEC[codec] or codec, + codecTag = string.format("0x%02x", st), + timescale = 90000, + language = lang, + streamType = st, + } + byPid[pid] = t + table.insert(tracks, t :: Types.Track) + return t + end + for _, s in d.streams do + track(s.pid, s.kind, s.codec, s.streamType, s.language) + end + for _, u in units do + track(u.pid, u.kind, u.codec, u.streamType, nil) + end + -- codec details from the first unit + local seen: { [number]: boolean } = {} + for _, u in units do + local t = byPid[u.pid] + if not seen[u.pid] then + seen[u.pid] = true + if t.codec == "unknown" or t.kind == "data" then + -- a private / unknown stream type: go by the PES stream id and the payload + local sid = u.streamId or 0 + if sid >= 0xE0 and sid <= 0xEF then + t.kind = "video" + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + t.codec = if info then (if info.mpeg2 then "mpeg2" else "mpeg1") elseif MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) then "h264" else "unknown" + elseif sid >= 0xC0 and sid <= 0xDF then + t.kind, t.codec = "audio", "mp2" + end + end + if t.codec == "mpeg1" or t.codec == "mpeg2" then + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + if info then + t.codec = if info.mpeg2 then "mpeg2" else "mpeg1" + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + end + elseif t.codec == "mp2" then + t.codec = mpegAudioCodec(u) + elseif t.codec == "aac" then + t.adts = true + local b: buffer = u.data + if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + t.sampleRate = rates[(buffer.readu8(b, 2) // 4) % 16 + 1] + t.channels = (buffer.readu8(b, 2) % 2) * 4 + buffer.readu8(b, 3) // 64 + end + end + end + end + local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats }) + local lastPts: { [number]: number } = {} + for _, u in units do + local t = byPid[u.pid] + local pts = u.pts90 or u.dts90 + if pts == nil then + local prev = lastPts[u.pid] + if prev and t.frameRate and t.frameRate > 0 then + pts = prev + 90000 / t.frameRate + else + pts = prev + end + end + if pts ~= nil then + lastPts[u.pid] = pts + local key = true + local data: buffer = u.data + if t.kind == "video" then + if t.codec == "mpeg1" or t.codec == "mpeg2" then + key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1 + elseif t.codec == "h264" then + key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data)) + else + key = u.randomAccess + end + end + dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ts.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Ts.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ts +end +__FILES["video/ogv"] = function() + +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Demux = __include("containers/Demux") +local AudioWrap = __include("containers/AudioWrap") +local Theora = __include("codecs/video/Theora") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + verify: boolean?, -- false: skip the page CRC checks (default true) + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +type EncodeOptions = { + audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv +end +__FILES["video/smk"] = function() + +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Stream = __include("codecs/audio/Stream") +local Audio = __include("video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + audio: boolean?, -- false: do not open the audio track + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk +end +__FILES["video/smk/Audio"] = @native function() + + + +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = __include("codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +@native function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio +end +__FILES["video/y4m"] = function() + +-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. +-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder +-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono +-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. +-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 +-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), +-- alpha (C444alpha drops it). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Y4m = { + name = "y4m", + category = "video", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + maxPixels: number?, -- default 2^26 +} +type EncodeOptions = { + frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the + -- shortest frame, longer frames repeated) + maxFps: number?, -- the highest rate uneven frame times may need (default 100) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "YUV4MPEG2 " +-- C tag -> pixel format, bits +local COLOR: { [string]: { any } } = { + ["420jpeg"] = { "yuv420p", 8 }, + ["420paldv"] = { "yuv420p", 8 }, + ["420mpeg2"] = { "yuv420p", 8 }, + ["420"] = { "yuv420p", 8 }, + ["422"] = { "yuv422p", 8 }, + ["444"] = { "yuv444p", 8 }, + ["444alpha"] = { "yuva444p", 8 }, + mono = { "gray", 8 }, +} +for _, b in { 9, 10, 12, 14, 16 } do + COLOR["420p" .. b] = { "yuv420p", b } + COLOR["422p" .. b] = { "yuv422p", b } + COLOR["444p" .. b] = { "yuv444p", b } + COLOR["mono" .. b] = { "gray", b } +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Y4m.sniff(r: Bytes.Reader): number + return if r:peek(10) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function frameSize(pf: string, bits: number, w: number, h: number): number + local bps = if bits > 8 then 2 else 1 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + if pf == "yuv420p" then + return (w * h + 2 * cw * ch) * bps + elseif pf == "yuv422p" then + return (w * h + 2 * cw * h) * bps + elseif pf == "yuv444p" then + return w * h * 3 * bps + elseif pf == "yuva444p" then + return w * h * 4 * bps + end + return w * h * bps +end + +-- demux(r, opts?) -> the raw-video Demuxer | nil, Err +function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local nl = -1 + for i = base, math.min(limit, base + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + nl = i + break + end + end + if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base) + end + if nl < 0 then + return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base) + end + local header = buffer.readstring(buf, base + 10, nl - base - 10) + local w, h, fn, fd = 0, 0, 25, 1 + local ctag, itag, atag = "420jpeg", "p", "0:0" + local extra = {} + for tok in string.gmatch(header, "%S+") do + local k, v = string.sub(tok, 1, 1), string.sub(tok, 2) + if k == "W" then + w = tonumber(v) or 0 + elseif k == "H" then + h = tonumber(v) or 0 + elseif k == "F" then + local a, b = string.match(v, "^(%d+):(%d+)$") + if a and b and (tonumber(a) :: number) > 0 and (tonumber(b) :: number) > 0 then + fn, fd = tonumber(a) :: number, tonumber(b) :: number + end + elseif k == "C" then + ctag = v + elseif k == "I" then + itag = v + elseif k == "A" then + atag = v + elseif k == "X" then + table.insert(extra, v) + end + end + local color = COLOR[ctag] + if not color then + return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag) + end + if w <= 0 or h <= 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels") + end + local pf, bits = color[1], color[2] + local size = frameSize(pf, bits, w, h) + local track: Types.Track = { + id = 1, + kind = "video", + codec = "rawvideo", + codecTag = "C" .. ctag, + timescale = fn / fd, + width = w, + height = h, + frameRate = fn / fd, + pixelFormat = pf, + bitDepth = bits, + default = true, + } + local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag } + local dmx = Demux.new("y4m", { track }, buf, meta) + local pos = nl + 1 + local k = 0 + while pos + 5 <= limit do + if buffer.readstring(buf, pos, 5) ~= "FRAME" then + return nil, Err.new(Err.CORRUPT, "expected FRAME", pos) + end + local e = -1 + for i = pos + 5, math.min(limit, pos + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + e = i + break + end + end + if e < 0 then + break + end + local data = e + 1 + if data + size > limit then + break -- a truncated last frame is dropped + end + dmx:add(1, k, k, 1, true, data, size) + k += 1 + pos = data + size + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) + if not streams then + return nil, err + end + local s = streams[1] + local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps) + if opts and type(opts.frameRate) == "table" then + fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets + end + s.packets = packets + local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6)) + w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd)) + for _, p in s.packets do + w:string("FRAME\n") + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Y4m.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Y4m +end +local Rosetta = __include("") +Rosetta._internal = function(path) + return __include(path) +end +return Rosetta diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json new file mode 100644 index 0000000..b05f2e3 --- /dev/null +++ b/build/Rosetta.luau.linemap.json @@ -0,0 +1,539 @@ +[ +[27, "src/Rosetta/init.luau"], +[955, "src/Rosetta/Registry.luau"], +[3064, "src/Rosetta/Types.luau"], +[4221, "src/Rosetta/archive/7z/init.luau"], +[4614, "src/Rosetta/archive/7z/Header.luau"], +[5146, "src/Rosetta/archive/adf/init.luau"], +[5436, "src/Rosetta/archive/applesingle/init.luau"], +[5628, "src/Rosetta/archive/ar/init.luau"], +[6040, "src/Rosetta/archive/arj/init.luau"], +[6254, "src/Rosetta/archive/binhex/init.luau"], +[6510, "src/Rosetta/archive/br/init.luau"], +[6588, "src/Rosetta/archive/bz2/init.luau"], +[6654, "src/Rosetta/archive/cab/init.luau"], +[7083, "src/Rosetta/archive/cab/Sum.luau"], +[7127, "src/Rosetta/archive/cpio/init.luau"], +[7301, "src/Rosetta/archive/d64/init.luau"], +[7727, "src/Rosetta/archive/fat/init.luau"], +[7853, "src/Rosetta/archive/grp/init.luau"], +[7970, "src/Rosetta/archive/gzip/init.luau"], +[8159, "src/Rosetta/archive/iso/init.luau"], +[8236, "src/Rosetta/archive/lha/init.luau"], +[8672, "src/Rosetta/archive/lz4/init.luau"], +[9027, "src/Rosetta/archive/macbinary/init.luau"], +[9230, "src/Rosetta/archive/mpq/init.luau"], +[9651, "src/Rosetta/archive/mpq/Crypt.luau"], +[9718, "src/Rosetta/archive/pak/init.luau"], +[9855, "src/Rosetta/archive/rpm/init.luau"], +[10190, "src/Rosetta/archive/tar/init.luau"], +[10312, "src/Rosetta/archive/uu/init.luau"], +[10590, "src/Rosetta/archive/vpk/init.luau"], +[10909, "src/Rosetta/archive/wad/init.luau"], +[11385, "src/Rosetta/archive/wad/Map.luau"], +[11828, "src/Rosetta/archive/wad/Picture.luau"], +[11939, "src/Rosetta/archive/xz/init.luau"], +[12042, "src/Rosetta/archive/yenc/init.luau"], +[12321, "src/Rosetta/archive/z/init.luau"], +[12421, "src/Rosetta/archive/zip/init.luau"], +[12661, "src/Rosetta/archive/zoo/init.luau"], +[12860, "src/Rosetta/archive/zst/init.luau"], +[12925, "src/Rosetta/audio/aac/init.luau"], +[13136, "src/Rosetta/audio/ac3/init.luau"], +[13285, "src/Rosetta/audio/adpcm/init.luau"], +[13442, "src/Rosetta/audio/adx/init.luau"], +[13681, "src/Rosetta/audio/aiff/init.luau"], +[14083, "src/Rosetta/audio/ape/init.luau"], +[14219, "src/Rosetta/audio/au/init.luau"], +[14382, "src/Rosetta/audio/brstm/init.luau"], +[14682, "src/Rosetta/audio/caf/init.luau"], +[15352, "src/Rosetta/audio/flac/init.luau"], +[15515, "src/Rosetta/audio/flac/Meta.luau"], +[15740, "src/Rosetta/audio/flac/Stream.luau"], +[16125, "src/Rosetta/audio/m4a/init.luau"], +[16467, "src/Rosetta/audio/mp3/init.luau"], +[16747, "src/Rosetta/audio/mp3/Index.luau"], +[16943, "src/Rosetta/audio/mp3/Stream.luau"], +[17178, "src/Rosetta/audio/mp3/Tags.luau"], +[17497, "src/Rosetta/audio/mpc/init.luau"], +[17595, "src/Rosetta/audio/opus/init.luau"], +[17999, "src/Rosetta/audio/opus/Encode.luau"], +[18118, "src/Rosetta/audio/qoa/init.luau"], +[18305, "src/Rosetta/audio/tta/init.luau"], +[18430, "src/Rosetta/audio/vag/init.luau"], +[18663, "src/Rosetta/audio/voc/init.luau"], +[18943, "src/Rosetta/audio/vorbis/init.luau"], +[19415, "src/Rosetta/audio/vorbis/Encode.luau"], +[20244, "src/Rosetta/audio/wav/init.luau"], +[20889, "src/Rosetta/audio/wav/Codecs.luau"], +[21064, "src/Rosetta/audio/wavpack/init.luau"], +[21285, "src/Rosetta/cad/step/init.luau"], +[21697, "src/Rosetta/cad/step/Brep.luau"], +[21947, "src/Rosetta/cad/step/Parse.luau"], +[22522, "src/Rosetta/cad/step/Write.luau"], +[22776, "src/Rosetta/codecs/audio/Aac/init.luau"], +[23114, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[24019, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24355, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24529, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25447, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25551, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26371, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26701, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26954, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27383, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27812, "src/Rosetta/codecs/audio/Ape/init.luau"], +[28043, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28823, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28935, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28948, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29938, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30550, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30761, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[31012, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31984, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[32207, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[32412, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32625, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32986, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[33001, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[33066, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34705, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34999, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[35395, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[36062, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[36204, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[36430, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36791, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37692, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[38073, "src/Rosetta/codecs/audio/Opus/init.luau"], +[38090, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39956, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[41036, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[41096, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[41564, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41912, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[42149, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[44221, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[44595, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44891, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[45201, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[45500, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45879, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45950, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[46101, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[46626, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[47431, "src/Rosetta/codecs/audio/Stream.luau"], +[47614, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[48168, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[48461, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[48636, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[48770, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[50798, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[50926, "src/Rosetta/codecs/audio/Tta/init.luau"], +[51054, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[51315, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[51330, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[51726, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[52314, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[52745, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[52784, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[52848, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[53088, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[54573, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[54640, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[54743, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[55741, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[56609, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[56667, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[57197, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[57555, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[57989, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[58445, "src/Rosetta/codecs/compress/Explode.luau"], +[58651, "src/Rosetta/codecs/compress/Lz4.luau"], +[58944, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[59572, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[60141, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[60180, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[60674, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[60853, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[61144, "src/Rosetta/codecs/compress/Lzx.luau"], +[61595, "src/Rosetta/codecs/compress/PackBits.luau"], +[61692, "src/Rosetta/codecs/compress/Quantum.luau"], +[61945, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[62266, "src/Rosetta/codecs/compress/Xxh32.luau"], +[62340, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[62410, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[63392, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[63549, "src/Rosetta/codecs/entropy/Huffman.luau"], +[63857, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[63872, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[64089, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[64343, "src/Rosetta/codecs/font/Bitmap.luau"], +[64565, "src/Rosetta/codecs/font/Cff/init.luau"], +[65224, "src/Rosetta/codecs/font/GlyphNames.luau"], +[65380, "src/Rosetta/codecs/font/TrueType/init.luau"], +[65720, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[66125, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[66646, "src/Rosetta/codecs/image/Bcn/init.luau"], +[66769, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[67269, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[67713, "src/Rosetta/codecs/image/Blend.luau"], +[68114, "src/Rosetta/codecs/image/Dct/init.luau"], +[68512, "src/Rosetta/codecs/image/Etc.luau"], +[68829, "src/Rosetta/codecs/image/Half.luau"], +[68905, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[69297, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[69713, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[69963, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[70736, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[71637, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[72100, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[72179, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[72257, "src/Rosetta/codecs/image/Pixels.luau"], +[72542, "src/Rosetta/codecs/image/Quantize/init.luau"], +[73027, "src/Rosetta/codecs/image/Raster.luau"], +[73773, "src/Rosetta/codecs/image/Texel.luau"], +[74173, "src/Rosetta/codecs/image/Texture.luau"], +[74337, "src/Rosetta/codecs/image/Vp8/init.luau"], +[74497, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[76486, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[76762, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[77013, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[77138, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[77260, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[78135, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[79113, "src/Rosetta/codecs/image/Yuv.luau"], +[79403, "src/Rosetta/codecs/model/Draco/init.luau"], +[79758, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[80239, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[81445, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[81603, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[81968, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[82947, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[83429, "src/Rosetta/codecs/model/Mat4.luau"], +[83713, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[84258, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[84847, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[84930, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[85040, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[85262, "src/Rosetta/codecs/model/Polygon.luau"], +[85512, "src/Rosetta/codecs/model/Rbx/init.luau"], +[85795, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[86571, "src/Rosetta/codecs/model/Rig.luau"], +[86847, "src/Rosetta/codecs/model/Sampler.luau"], +[87022, "src/Rosetta/codecs/model/Vrml/init.luau"], +[87184, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[87776, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[87946, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[88718, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[89256, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[90008, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[90248, "src/Rosetta/codecs/text/Json/init.luau"], +[90544, "src/Rosetta/codecs/text/Json/Decode.luau"], +[90971, "src/Rosetta/codecs/text/Json/Encode.luau"], +[91280, "src/Rosetta/codecs/text/Nbt/init.luau"], +[91662, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[92362, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[93013, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[93271, "src/Rosetta/codecs/text/Text/init.luau"], +[93367, "src/Rosetta/codecs/text/Url/init.luau"], +[93585, "src/Rosetta/codecs/text/Xml/init.luau"], +[94027, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[94792, "src/Rosetta/codecs/video/Dsp.luau"], +[95537, "src/Rosetta/codecs/video/H263/init.luau"], +[95715, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[96611, "src/Rosetta/codecs/video/H263/Tables.luau"], +[96819, "src/Rosetta/codecs/video/H264/init.luau"], +[97236, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[97531, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[98676, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[99455, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[99721, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[100747, "src/Rosetta/codecs/video/H264/Inter.luau"], +[101015, "src/Rosetta/codecs/video/H264/Intra.luau"], +[101427, "src/Rosetta/codecs/video/H264/Mb.luau"], +[102360, "src/Rosetta/codecs/video/H264/Params.luau"], +[102815, "src/Rosetta/codecs/video/H264/Slice.luau"], +[103068, "src/Rosetta/codecs/video/H264/Tables.luau"], +[103112, "src/Rosetta/codecs/video/H264/Transform.luau"], +[103288, "src/Rosetta/codecs/video/Legacy/init.luau"], +[103504, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[103809, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[104183, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[104306, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[104423, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[104701, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[105108, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[105293, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[105306, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[105722, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[107286, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[107426, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[107572, "src/Rosetta/codecs/video/Theora/init.luau"], +[107863, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[109153, "src/Rosetta/codecs/video/Theora/Header.luau"], +[109525, "src/Rosetta/codecs/video/Video/init.luau"], +[110128, "src/Rosetta/codecs/video/Video/Source.luau"], +[110435, "src/Rosetta/containers/Archive.luau"], +[110728, "src/Rosetta/containers/AudioWrap.luau"], +[111249, "src/Rosetta/containers/Avi/init.luau"], +[111821, "src/Rosetta/containers/Chunks.luau"], +[111965, "src/Rosetta/containers/Cpio.luau"], +[112407, "src/Rosetta/containers/Demux.luau"], +[112705, "src/Rosetta/containers/Ebml/init.luau"], +[113042, "src/Rosetta/containers/Fat.luau"], +[113751, "src/Rosetta/containers/Iso9660.luau"], +[114278, "src/Rosetta/containers/IsoBmff/init.luau"], +[114468, "src/Rosetta/containers/IsoBmff/Box.luau"], +[114663, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[115527, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[116057, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[116578, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[116700, "src/Rosetta/containers/MacFile.luau"], +[116860, "src/Rosetta/containers/MpegEs.luau"], +[117035, "src/Rosetta/containers/MpegPs/init.luau"], +[117261, "src/Rosetta/containers/MpegTs/init.luau"], +[118078, "src/Rosetta/containers/Ogg/init.luau"], +[118536, "src/Rosetta/containers/Ogg/Mux.luau"], +[118746, "src/Rosetta/containers/Ogg/Page.luau"], +[118923, "src/Rosetta/containers/Riff/init.luau"], +[119268, "src/Rosetta/containers/Tar.luau"], +[119696, "src/Rosetta/containers/Zip/init.luau"], +[120356, "src/Rosetta/core/Adler32.luau"], +[120408, "src/Rosetta/core/Base64.luau"], +[120577, "src/Rosetta/core/Bits.luau"], +[120889, "src/Rosetta/core/Bytes.luau"], +[121458, "src/Rosetta/core/Crc16.luau"], +[121512, "src/Rosetta/core/Crc32.luau"], +[121635, "src/Rosetta/core/Err.luau"], +[121731, "src/Rosetta/core/Input.luau"], +[121815, "src/Rosetta/core/Md5.luau"], +[121981, "src/Rosetta/core/Sniff.luau"], +[122019, "src/Rosetta/data/cbor/init.luau"], +[122121, "src/Rosetta/data/cbor/Codec.luau"], +[122698, "src/Rosetta/data/csv/init.luau"], +[123015, "src/Rosetta/data/ini/init.luau"], +[123266, "src/Rosetta/data/json/init.luau"], +[123359, "src/Rosetta/data/msgpack/init.luau"], +[123451, "src/Rosetta/data/msgpack/Codec.luau"], +[123899, "src/Rosetta/data/nbt/init.luau"], +[123961, "src/Rosetta/data/plist/init.luau"], +[124269, "src/Rosetta/data/plist/Binary.luau"], +[124542, "src/Rosetta/data/snbt/init.luau"], +[124607, "src/Rosetta/data/toml/init.luau"], +[124679, "src/Rosetta/data/toml/Decode.luau"], +[125316, "src/Rosetta/data/toml/Encode.luau"], +[125532, "src/Rosetta/data/xml/init.luau"], +[125589, "src/Rosetta/data/yaml/init.luau"], +[125668, "src/Rosetta/data/yaml/Emit.luau"], +[125969, "src/Rosetta/data/yaml/Parse.luau"], +[127293, "src/Rosetta/font/bdf/init.luau"], +[127590, "src/Rosetta/font/bmfont/init.luau"], +[128032, "src/Rosetta/font/bmfont/Parse.luau"], +[128491, "src/Rosetta/font/eot/init.luau"], +[128726, "src/Rosetta/font/fon/init.luau"], +[129016, "src/Rosetta/font/hershey/init.luau"], +[129218, "src/Rosetta/font/pcf/init.luau"], +[129510, "src/Rosetta/font/psf/init.luau"], +[129840, "src/Rosetta/font/ttf/init.luau"], +[129894, "src/Rosetta/font/type1/init.luau"], +[130264, "src/Rosetta/font/type1/Charstring.luau"], +[130549, "src/Rosetta/font/woff/init.luau"], +[130683, "src/Rosetta/font/woff2/init.luau"], +[130742, "src/Rosetta/font/woff2/Rebuild.luau"], +[131292, "src/Rosetta/host/init.luau"], +[131344, "src/Rosetta/host/Love.luau"], +[131495, "src/Rosetta/host/LuaJIT.luau"], +[131545, "src/Rosetta/host/Luau.luau"], +[131568, "src/Rosetta/host/Roblox.luau"], +[131959, "src/Rosetta/image/ani/init.luau"], +[132144, "src/Rosetta/image/blp/init.luau"], +[132412, "src/Rosetta/image/bmp/init.luau"], +[132843, "src/Rosetta/image/dds/init.luau"], +[133342, "src/Rosetta/image/exr/init.luau"], +[134126, "src/Rosetta/image/exr/Codec.luau"], +[134245, "src/Rosetta/image/exr/Piz.luau"], +[134614, "src/Rosetta/image/gif/init.luau"], +[135150, "src/Rosetta/image/gif/Decode.luau"], +[135220, "src/Rosetta/image/hdr/init.luau"], +[135456, "src/Rosetta/image/hdr/Codec.luau"], +[135677, "src/Rosetta/image/icns/init.luau"], +[136016, "src/Rosetta/image/ico/init.luau"], +[136300, "src/Rosetta/image/ico/Dib.luau"], +[136401, "src/Rosetta/image/ilbm/init.luau"], +[136727, "src/Rosetta/image/jpeg/init.luau"], +[136878, "src/Rosetta/image/ktx/init.luau"], +[137552, "src/Rosetta/image/pcx/init.luau"], +[137820, "src/Rosetta/image/png/init.luau"], +[138418, "src/Rosetta/image/png/Apng.luau"], +[138502, "src/Rosetta/image/png/Decode.luau"], +[138757, "src/Rosetta/image/png/Encode.luau"], +[138921, "src/Rosetta/image/pnm/init.luau"], +[139307, "src/Rosetta/image/pnm/Codec.luau"], +[139598, "src/Rosetta/image/qoi/init.luau"], +[139722, "src/Rosetta/image/qoi/Codec.luau"], +[139876, "src/Rosetta/image/sgi/init.luau"], +[140164, "src/Rosetta/image/sunras/init.luau"], +[140413, "src/Rosetta/image/tga/init.luau"], +[140691, "src/Rosetta/image/tga/Codec.luau"], +[140850, "src/Rosetta/image/tiff/init.luau"], +[141694, "src/Rosetta/image/tiff/Pixels.luau"], +[142095, "src/Rosetta/image/tim/init.luau"], +[142344, "src/Rosetta/image/vtf/init.luau"], +[142591, "src/Rosetta/image/webp/init.luau"], +[143220, "src/Rosetta/image/webp/Alpha.luau"], +[143298, "src/Rosetta/image/webp/Anim.luau"], +[143462, "src/Rosetta/image/xbm/init.luau"], +[143626, "src/Rosetta/image/xpm/init.luau"], +[143900, "src/Rosetta/image/xpm/Names.luau"], +[143959, "src/Rosetta/layered/aseprite/init.luau"], +[144715, "src/Rosetta/layered/ora/init.luau"], +[145010, "src/Rosetta/layered/psd/init.luau"], +[145755, "src/Rosetta/layered/psd/Channels.luau"], +[146126, "src/Rosetta/model/3ds/init.luau"], +[146228, "src/Rosetta/model/3ds/Build.luau"], +[146893, "src/Rosetta/model/3ds/Read.luau"], +[147401, "src/Rosetta/model/3ds/Write.luau"], +[148230, "src/Rosetta/model/3mf/init.luau"], +[148327, "src/Rosetta/model/3mf/Read.luau"], +[148927, "src/Rosetta/model/3mf/Write.luau"], +[149346, "src/Rosetta/model/b3d/init.luau"], +[149416, "src/Rosetta/model/b3d/Read.luau"], +[149994, "src/Rosetta/model/bsp/init.luau"], +[150146, "src/Rosetta/model/bsp/Brush.luau"], +[150439, "src/Rosetta/model/bsp/Quake3.luau"], +[150702, "src/Rosetta/model/dae/init.luau"], +[150910, "src/Rosetta/model/dae/Math.luau"], +[150958, "src/Rosetta/model/dae/Read.luau"], +[152840, "src/Rosetta/model/dae/Write.luau"], +[153218, "src/Rosetta/model/fbx/init.luau"], +[153386, "src/Rosetta/model/fbx/Ascii.luau"], +[153662, "src/Rosetta/model/fbx/Binary.luau"], +[154125, "src/Rosetta/model/fbx/Read.luau"], +[155511, "src/Rosetta/model/fbx/Write.luau"], +[156509, "src/Rosetta/model/fbx/Xform.luau"], +[156553, "src/Rosetta/model/gltf/init.luau"], +[156807, "src/Rosetta/model/gltf/Pack.luau"], +[156883, "src/Rosetta/model/gltf/Read.luau"], +[157632, "src/Rosetta/model/gltf/Write.luau"], +[158330, "src/Rosetta/model/iqm/init.luau"], +[158414, "src/Rosetta/model/iqm/Read.luau"], +[158775, "src/Rosetta/model/iqm/Write.luau"], +[159483, "src/Rosetta/model/ldraw/init.luau"], +[159590, "src/Rosetta/model/ldraw/Colors.luau"], +[159911, "src/Rosetta/model/ldraw/Read.luau"], +[160493, "src/Rosetta/model/lwo/init.luau"], +[160581, "src/Rosetta/model/lwo/Build.luau"], +[161052, "src/Rosetta/model/lwo/Parse.luau"], +[161605, "src/Rosetta/model/mca/init.luau"], +[161962, "src/Rosetta/model/mca/Chunk.luau"], +[162099, "src/Rosetta/model/mca/Lz4Block.luau"], +[162171, "src/Rosetta/model/md2/init.luau"], +[162382, "src/Rosetta/model/md3/init.luau"], +[162618, "src/Rosetta/model/md5/init.luau"], +[162703, "src/Rosetta/model/md5/Read.luau"], +[163145, "src/Rosetta/model/mdl/init.luau"], +[163231, "src/Rosetta/model/mdl/HalfLife.luau"], +[163573, "src/Rosetta/model/mdl/Quake.luau"], +[163797, "src/Rosetta/model/ms3d/init.luau"], +[163881, "src/Rosetta/model/ms3d/Read.luau"], +[164347, "src/Rosetta/model/ms3d/Write.luau"], +[164835, "src/Rosetta/model/obj/init.luau"], +[165600, "src/Rosetta/model/obj/Mtl.luau"], +[165896, "src/Rosetta/model/off/init.luau"], +[166378, "src/Rosetta/model/ply/init.luau"], +[167528, "src/Rosetta/model/ply/Binary.luau"], +[167742, "src/Rosetta/model/pmx/init.luau"], +[167821, "src/Rosetta/model/pmx/Build.luau"], +[168130, "src/Rosetta/model/pmx/Pmd.luau"], +[168471, "src/Rosetta/model/pmx/Read.luau"], +[168884, "src/Rosetta/model/qb/init.luau"], +[169287, "src/Rosetta/model/rbxm/init.luau"], +[169894, "src/Rosetta/model/rbxmx/init.luau"], +[170563, "src/Rosetta/model/robloxmesh/init.luau"], +[171249, "src/Rosetta/model/robloxmesh/Parse.luau"], +[171711, "src/Rosetta/model/robloxmesh/Write.luau"], +[171822, "src/Rosetta/model/schematic/init.luau"], +[172158, "src/Rosetta/model/schematic/Common.luau"], +[172288, "src/Rosetta/model/schematic/Litematic.luau"], +[172505, "src/Rosetta/model/schematic/Mcedit.luau"], +[172756, "src/Rosetta/model/schematic/Sponge.luau"], +[172889, "src/Rosetta/model/smd/init.luau"], +[172960, "src/Rosetta/model/smd/Read.luau"], +[173237, "src/Rosetta/model/smd/Write.luau"], +[173489, "src/Rosetta/model/stl/init.luau"], +[173958, "src/Rosetta/model/stl/Decode.luau"], +[174037, "src/Rosetta/model/usda/init.luau"], +[174260, "src/Rosetta/model/usda/Build.luau"], +[175577, "src/Rosetta/model/usda/Parse.luau"], +[176399, "src/Rosetta/model/usda/Write.luau"], +[177241, "src/Rosetta/model/vox/init.luau"], +[178146, "src/Rosetta/model/vox/Grid.luau"], +[178209, "src/Rosetta/model/vrml/init.luau"], +[178288, "src/Rosetta/model/x/init.luau"], +[178432, "src/Rosetta/model/x/Build.luau"], +[179008, "src/Rosetta/model/x/Parse.luau"], +[179316, "src/Rosetta/model/x3d/init.luau"], +[179403, "src/Rosetta/music/669/init.luau"], +[179614, "src/Rosetta/music/ahx/init.luau"], +[179669, "src/Rosetta/music/far/init.luau"], +[179903, "src/Rosetta/music/hmp/init.luau"], +[180178, "src/Rosetta/music/hvl/init.luau"], +[180233, "src/Rosetta/music/it/init.luau"], +[180662, "src/Rosetta/music/it/Itsex.luau"], +[180784, "src/Rosetta/music/med/init.luau"], +[181447, "src/Rosetta/music/midi/init.luau"], +[181603, "src/Rosetta/music/midi/Smf.luau"], +[182023, "src/Rosetta/music/mod/init.luau"], +[182386, "src/Rosetta/music/mtm/init.luau"], +[182614, "src/Rosetta/music/mus/init.luau"], +[182779, "src/Rosetta/music/okt/init.luau"], +[183067, "src/Rosetta/music/ptm/init.luau"], +[183296, "src/Rosetta/music/s3m/init.luau"], +[183540, "src/Rosetta/music/sf2/init.luau"], +[183586, "src/Rosetta/music/stm/init.luau"], +[183821, "src/Rosetta/music/ult/init.luau"], +[184132, "src/Rosetta/music/umx/init.luau"], +[184356, "src/Rosetta/music/xm/init.luau"], +[184931, "src/Rosetta/music/xmi/init.luau"], +[185148, "src/Rosetta/ops/AudioOps.luau"], +[185632, "src/Rosetta/ops/ImageOps/init.luau"], +[186323, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[186845, "src/Rosetta/ops/LayerOps.luau"], +[186948, "src/Rosetta/ops/MeshOps/init.luau"], +[188037, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[188206, "src/Rosetta/ops/MusicOps.luau"], +[188577, "src/Rosetta/playlist/m3u/init.luau"], +[188946, "src/Rosetta/playlist/pls/init.luau"], +[189133, "src/Rosetta/playlist/xspf/init.luau"], +[189349, "src/Rosetta/subtitle/ass/init.luau"], +[189807, "src/Rosetta/subtitle/srt/init.luau"], +[189987, "src/Rosetta/subtitle/vtt/init.luau"], +[190197, "src/Rosetta/vector/svg/init.luau"], +[190293, "src/Rosetta/vector/svg/Parse.luau"], +[191053, "src/Rosetta/vector/svg/PathData.luau"], +[191432, "src/Rosetta/vector/svg/Render.luau"], +[191861, "src/Rosetta/vector/svg/Style.luau"], +[192244, "src/Rosetta/vector/svg/Write.luau"], +[192449, "src/Rosetta/vector/tiled/init.luau"], +[192638, "src/Rosetta/vector/tiled/Data.luau"], +[192796, "src/Rosetta/vector/tiled/Tmj.luau"], +[193432, "src/Rosetta/vector/tiled/Tmx.luau"], +[194052, "src/Rosetta/video/avi/init.luau"], +[194357, "src/Rosetta/video/fli/init.luau"], +[194516, "src/Rosetta/video/flv/init.luau"], +[194920, "src/Rosetta/video/flv/Amf.luau"], +[195088, "src/Rosetta/video/flv/Mux.luau"], +[195378, "src/Rosetta/video/h264/init.luau"], +[195525, "src/Rosetta/video/mkv/init.luau"], +[195696, "src/Rosetta/video/mkv/Mux.luau"], +[195983, "src/Rosetta/video/mkv/Parse.luau"], +[196715, "src/Rosetta/video/mp4/init.luau"], +[197058, "src/Rosetta/video/mpegps/init.luau"], +[197253, "src/Rosetta/video/mpegts/init.luau"], +[197501, "src/Rosetta/video/ogv/init.luau"], +[197910, "src/Rosetta/video/smk/init.luau"], +[198232, "src/Rosetta/video/smk/Audio.luau"], +[198357, "src/Rosetta/video/y4m/init.luau"] +] diff --git a/build/rosetta.lua b/build/rosetta.lua new file mode 100644 index 0000000..1cfa771 --- /dev/null +++ b/build/rosetta.lua @@ -0,0 +1,199233 @@ +-- rosetta (LuaJIT / LÖVE bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- require("rosetta") with build/?.lua on package.path, or dofile("build/rosetta.lua"): the API +-- (docs/API.md); Rosetta._internal("codecs/video/Mpeg1") -> an internal module. Error lines map back to +-- the sources through rosetta.lua.linemap.json (python3 -I tools/bundle.py --where). +local __compat = (function() +-- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain luajit and LÖVE). +-- tools/build.py copies this file to build/_modules/luajit/rosetta/_compat.lua (tools/bundle.py inlines it at the top +-- of build/rosetta.lua), and every built module starts with +-- local __compat = require("rosetta._compat") local buffer, bit32, utf8, typeof, type, __iter = ... +-- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string +-- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing. +-- +-- Semantics follow Luau (checked by tests/compat.luau under both runtimes): +-- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap +-- (fractional operands: see the bit32 section). +-- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws +-- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a +-- private metatable: typeof(b) and the injected type(b) return "buffer". +-- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to +-- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the +-- table has no keys past #t, anything else with next. +-- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b +-- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes. +local ffi = require("ffi") +local bit = require("bit") +local floor = math.floor +local rawtype, getmetatable, setmetatable, select, error, pairs, ipairs, next = type, getmetatable, setmetatable, select, error, pairs, ipairs, next + +local TWO32 = 4294967296 + +local M = {} + +-- ---------------------------------------------------------------------------------------------------- bit32 +-- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32. +-- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs +-- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step). +-- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never +-- passes fractions to bit32 (tests/compat.luau checks integers only). +do + local band, bor, bxor, bnot, lshift, rshift, arshift, bswap = + bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap + local B = {} + -- the 2- and 3-argument forms are the hot ones: no varargs on that path + function B.band(a, b, c, d, ...) + local r + if b == nil then + if a == nil then return TWO32 - 1 end + r = band(a, -1) + else + r = band(a, b) + if c ~= nil then + r = band(r, c) + if d ~= nil then + r = band(r, d) + for i = 1, select("#", ...) do r = band(r, (select(i, ...))) end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.bor(a, b, c, d, ...) + local r + if b == nil then + if a == nil then return 0 end + r = band(a, -1) + else + r = bor(a, b) + if c ~= nil then + r = bor(r, c) + if d ~= nil then + r = bor(r, d) + for i = 1, select("#", ...) do r = bor(r, (select(i, ...))) end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.bxor(a, b, c, d, e, f, g, h, ...) + local r + if b == nil then + if a == nil then return 0 end + r = band(a, -1) + else + r = bxor(a, b) + if c ~= nil then + r = bxor(r, c) + if d ~= nil then + r = bxor(r, d) + if e ~= nil then + r = bxor(r, e) + if f ~= nil then + r = bxor(r, f) + if g ~= nil then + r = bxor(r, g) + if h ~= nil then + r = bxor(r, h) + for i = 1, select("#", ...) do r = bxor(r, (select(i, ...))) end + end + end + end + end + end + end + end + if r < 0 then r = r + TWO32 end + return r + end + function B.btest(...) + return B.band(...) ~= 0 + end + function B.bnot(a) + local r = bnot(a) + if r < 0 then r = r + TWO32 end + return r + end + function B.lshift(a, n) + if n >= 32 or n <= -32 then return 0 end + local r + if n < 0 then r = rshift(a, -n) else r = lshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.rshift(a, n) + if n >= 32 or n <= -32 then return 0 end + local r + if n < 0 then r = lshift(a, -n) else r = rshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.arshift(a, n) + if n <= -32 then return 0 end + if n >= 32 then n = 31 end + local r + if n < 0 then r = lshift(a, -n) else r = arshift(a, n) end + if r < 0 then r = r + TWO32 end + return r + end + function B.lrotate(a, n) + n = n % 32 + local r = n == 0 and band(a, -1) or bor(lshift(a, n), rshift(a, 32 - n)) + if r < 0 then r = r + TWO32 end + return r + end + function B.rrotate(a, n) + return B.lrotate(a, -n) + end + function B.extract(a, field, width) + width = width or 1 + if field < 0 or width <= 0 or field + width > 32 then error("bit32.extract: trying to access non-existent bits", 2) end + local r = rshift(a, field) + if width < 32 then r = band(r, lshift(1, width) - 1) end + if r < 0 then r = r + TWO32 end + return r + end + function B.replace(a, v, field, width) + width = width or 1 + if field < 0 or width <= 0 or field + width > 32 then error("bit32.replace: trying to access non-existent bits", 2) end + local m = width == 32 and -1 or lshift(lshift(1, width) - 1, field) + local r = bor(band(a, bnot(m)), band(lshift(v, field), m)) + if r < 0 then r = r + TWO32 end + return r + end + function B.countlz(a) + a = band(a, -1) + if a == 0 then return 32 end + local n = 0 + if band(a, -65536) == 0 then n = n + 16; a = lshift(a, 16) end + if band(a, -16777216) == 0 then n = n + 8; a = lshift(a, 8) end + if band(a, -268435456) == 0 then n = n + 4; a = lshift(a, 4) end + if band(a, -1073741824) == 0 then n = n + 2; a = lshift(a, 2) end + if band(a, -2147483648) == 0 then n = n + 1 end + return n + end + function B.countrz(a) + a = band(a, -1) + if a == 0 then return 32 end + local n = 0 + while band(a, 1) == 0 do + a = rshift(a, 1) + n = n + 1 + end + return n + end + function B.byteswap(a) + local r = bswap(a) + if r < 0 then r = r + TWO32 end + return r + end + M.bit32 = B +end + +-- ---------------------------------------------------------------------------------------------------- buffer +do + ffi.cdef([[ + void *memmove(void *dst, const void *src, size_t n); + void *memset(void *s, int c, size_t n); + void *calloc(size_t n, size_t size); + void free(void *p); + ]]) + local C = ffi.C + local u8p = ffi.typeof("uint8_t*") + local i8p = ffi.typeof("int8_t*") + local u16p, i16p = ffi.typeof("uint16_t*"), ffi.typeof("int16_t*") + local u32p, i32p = ffi.typeof("uint32_t*"), ffi.typeof("int32_t*") + local f32p, f64p = ffi.typeof("float*"), ffi.typeof("double*") + local u8arr = ffi.typeof("uint8_t[?]") + local cast, fstring, fcopy = ffi.cast, ffi.string, ffi.copy + + local BUF = { __name = "buffer" } + BUF.__index = function() error("attempt to index a buffer value", 2) end + BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end + M.BUFFER_MT = BUF + + -- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the + -- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every + -- 512 MB of them. + local BIG = 262144 + local external = 0 + + local function oob() + error("buffer access out of bounds", 3) + end + + local Buf = {} + local function create(n) + if rawtype(n) ~= "number" or n < 0 then error("buffer.create: invalid size", 2) end + n = floor(n) + local mem, p + if n < BIG then + mem = u8arr(n > 0 and n or 1) + p = cast(u8p, mem) + else + external = external + n + if external > 536870912 then + external = 0 + collectgarbage() + end + local raw = C.calloc(n, 1) + if raw == nil then error("buffer.create: out of memory", 2) end + mem = ffi.gc(cast(u8p, raw), C.free) + p = mem + end + -- p, n and m are raw fields, so the throwing __index only runs for misuse (b.x on a buffer) + return setmetatable({ p = p, n = n, m = mem }, BUF) + end + Buf.create = create + function Buf.len(b) return b.n end + + -- reads / writes: o must satisfy 0 <= o and o + size <= n (Luau truncates a fractional offset) + function Buf.readu8(b, o) + if o < 0 or o >= b.n then oob() end + return b.p[o] + end + function Buf.readi8(b, o) + if o < 0 or o >= b.n then oob() end + return cast(i8p, b.p)[o] + end + function Buf.readu16(b, o) + if o < 0 or o + 2 > b.n then oob() end + return cast(u16p, b.p + o)[0] + end + function Buf.readi16(b, o) + if o < 0 or o + 2 > b.n then oob() end + return cast(i16p, b.p + o)[0] + end + function Buf.readu32(b, o) + if o < 0 or o + 4 > b.n then oob() end + return cast(u32p, b.p + o)[0] + end + function Buf.readi32(b, o) + if o < 0 or o + 4 > b.n then oob() end + return cast(i32p, b.p + o)[0] + end + -- NaNs are checked through their bits before the float is loaded: a NaN with an arbitrary payload, handed back by + -- the FFI, can alias LuaJIT's NaN-tagged object values (read as a table / userdata). Return the canonical NaN. + local NAN = 0 / 0 + function Buf.readf32(b, o) + if o < 0 or o + 4 > b.n then oob() end + local bits = cast(u32p, b.p + o)[0] + if bits % 0x80000000 > 0x7f800000 then return NAN end + return cast(f32p, b.p + o)[0] + end + function Buf.readf64(b, o) + if o < 0 or o + 8 > b.n then oob() end + local hi = cast(u32p, b.p + o + 4)[0] % 0x80000000 -- little-endian: sign / exponent / top mantissa bits + if hi >= 0x7ff00000 and (hi > 0x7ff00000 or cast(u32p, b.p + o)[0] ~= 0) then return NAN end + return cast(f64p, b.p + o)[0] + end + -- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for + -- 8/16-bit stores and through int64 for 32-bit ones, so values in +-2^51 wrap correctly + function Buf.writeu8(b, o, v) + if o < 0 or o >= b.n then oob() end + b.p[o] = v + end + function Buf.writei8(b, o, v) + if o < 0 or o >= b.n then oob() end + b.p[o] = v + end + function Buf.writeu16(b, o, v) + if o < 0 or o + 2 > b.n then oob() end + cast(u16p, b.p + o)[0] = v + end + Buf.writei16 = Buf.writeu16 + function Buf.writeu32(b, o, v) + if o < 0 or o + 4 > b.n then oob() end + cast(u32p, b.p + o)[0] = v % TWO32 + end + Buf.writei32 = Buf.writeu32 + function Buf.writef32(b, o, v) + if o < 0 or o + 4 > b.n then oob() end + cast(f32p, b.p + o)[0] = v + end + function Buf.writef64(b, o, v) + if o < 0 or o + 8 > b.n then oob() end + cast(f64p, b.p + o)[0] = v + end + + function Buf.readstring(b, o, count) + if o < 0 or count < 0 or o + count > b.n then oob() end + return fstring(b.p + o, count) + end + function Buf.writestring(b, o, s, count) + count = count or #s + if count < 0 or count > #s then error("buffer.writestring: string length overflow", 2) end + if o < 0 or o + count > b.n then oob() end + fcopy(b.p + o, s, count) + end + function Buf.copy(target, toff, source, soff, count) + soff = soff or 0 + if soff < 0 or soff > source.n then oob() end + count = count or (source.n - soff) + if count < 0 or soff + count > source.n or toff < 0 or toff + count > target.n then oob() end + if count > 0 then C.memmove(target.p + toff, source.p + soff, count) end + end + function Buf.fill(b, o, v, count) + if o < 0 or o > b.n then oob() end + count = count or (b.n - o) + if count < 0 or o + count > b.n then oob() end + if count > 0 then C.memset(b.p + o, v % 256, count) end + end + function Buf.tostring(b) return fstring(b.p, b.n) end + function Buf.fromstring(s) + local b = create(#s) + fcopy(b.p, s, #s) + return b + end + + -- readbits / writebits: bit i of the buffer is bit (i % 8) of byte i // 8 (little-endian bit order), up to 32 bits + function Buf.readbits(b, bitOffset, bitCount) + if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end + if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end + local v, scale = 0, 1 + local i = bitOffset + local e = bitOffset + bitCount + while i < e do + local byte = floor(i / 8) + local sh = i % 8 + local take = 8 - sh + if take > e - i then take = e - i end + local x = bit.band(bit.rshift(b.p[byte], sh), bit.lshift(1, take) - 1) + v = v + x * scale + scale = scale * 2 ^ take + i = i + take + end + return v + end + function Buf.writebits(b, bitOffset, bitCount, value) + if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end + if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end + value = value % TWO32 + local i = bitOffset + local e = bitOffset + bitCount + while i < e do + local byte = floor(i / 8) + local sh = i % 8 + local take = 8 - sh + if take > e - i then take = e - i end + local m = bit.lshift(bit.lshift(1, take) - 1, sh) + local x = bit.band(bit.lshift(value % 256, sh), m) + b.p[byte] = bit.bor(bit.band(b.p[byte], bit.bnot(m)), x) + value = floor(value / 2 ^ take) + i = i + take + end + end + + -- LuaJIT-only extensions + function Buf.toffi(b) return b.p end + function Buf.fromffi(ptr, n) + local b = create(n) + if n > 0 then fcopy(b.p, ptr, n) end + return b + end + M.buffer = Buf +end + +-- ---------------------------------------------------------------------------------------------------- typeof / type +do + local BUF = M.BUFFER_MT + function M.type(v) + local t = rawtype(v) + if t == "table" and getmetatable(v) == BUF then + return "buffer" + end + return t + end + M.typeof = M.type + M.isbuffer = function(v) return getmetatable(v) == BUF end +end + +-- ---------------------------------------------------------------------------------------------------- __iter +local function arrayIter(s, i) + local t, n = s[1], s[2] + i = i + 1 + local v = t[i] + while v == nil and i < n do + i = i + 1 + v = t[i] + end + if v ~= nil then return i, v end +end +function M.__iter(t, s, c) + if rawtype(t) == "function" then return t, s, c end + if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end + local mt = getmetatable(t) + if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end + local n = #t + -- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part; + -- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps + -- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau. + if n > 0 and t[0] == nil and next(t, n) == nil then + return arrayIter, { t, n }, 0 + end + return next, t, nil +end + +-- ---------------------------------------------------------------------------------------------------- table +do + local okn, tnew = pcall(require, "table.new") + local okc, tclear = pcall(require, "table.clear") + if not table.create then + function table.create(n, v) + local t = okn and tnew(n, 0) or {} + if v ~= nil then for i = 1, n do t[i] = v end end + return t + end + end + table.clear = table.clear or (okc and tclear) or function(t) for k in pairs(t) do t[k] = nil end end + table.unpack = table.unpack or unpack + table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + table.find = table.find or function(t, v, init) + for i = init or 1, #t do if t[i] == v then return i end end + return nil + end + table.move = table.move or function(a1, f, e, t, a2) + a2 = a2 or a1 + if e >= f then + if t > f or t > e or a1 ~= a2 then + for i = 0, e - f do a2[t + i] = a1[f + i] end + else + for i = e - f, 0, -1 do a2[t + i] = a1[f + i] end + end + end + return a2 + end + -- freeze is advisory on LuaJIT (no read-only tables): it only records the table for isfrozen + local frozen = setmetatable({}, { __mode = "k" }) + table.freeze = table.freeze or function(t) frozen[t] = true; return t end + table.isfrozen = table.isfrozen or function(t) return frozen[t] == true end + table.clone = table.clone or function(t) + local c = {} + for k, v in pairs(t) do c[k] = v end + return setmetatable(c, getmetatable(t)) + end + table.maxn = table.maxn or function(t) + local m = 0 + for k in pairs(t) do if rawtype(k) == "number" and k > m then m = k end end + return m + end +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 ~= 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 + return 0 + end + -- Luau rounds half away from zero + math.round = math.round or function(x) + if x >= 0 then return floor(x + 0.5) end + return -floor(-x + 0.5) + end + math.lerp = math.lerp or function(a, b, t) return t == 1 and b or a + (b - a) * t end + math.map = math.map or function(x, a, b, c, d) return c + (d - c) * (x - a) / (b - a) end + math.isnan = math.isnan or function(x) return x ~= x end + math.isinf = math.isinf or function(x) return x == math.huge or x == -math.huge end + math.isfinite = math.isfinite or function(x) return x == x and x ~= math.huge and x ~= -math.huge end + -- stub: deterministic but not Roblox's Perlin noise (nothing in the library depends on its values) + math.noise = math.noise or function(x, y, z) + local s = math.sin((x or 0) * 12.9898 + (y or 0) * 78.233 + (z or 0) * 37.719) * 43758.5453 + return (s - floor(s)) - 0.5 + end +end + +-- ---------------------------------------------------------------------------------------------------- string +string.split = string.split or function(s, sep) + sep = sep or "," + local out = {} + if sep == "" then + for i = 1, #s do out[i] = s:sub(i, i) end + return out + end + local i = 1 + while true do + local a, b = s:find(sep, i, true) + if not a then + out[#out + 1] = s:sub(i) + return out + end + out[#out + 1] = s:sub(i, a - 1) + i = b + 1 + end +end + +-- ---------------------------------------------------------------------------------------------------- utf8 +do + -- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it + local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" } + local char, byte = string.char, string.byte + local function enc(c) + if c < 0x80 then return char(c) + elseif c < 0x800 then return char(0xC0 + floor(c / 64), 0x80 + c % 64) + elseif c < 0x10000 then return char(0xE0 + floor(c / 4096), 0x80 + floor(c / 64) % 64, 0x80 + c % 64) + end + return char(0xF0 + floor(c / 262144), 0x80 + floor(c / 4096) % 64, 0x80 + floor(c / 64) % 64, 0x80 + c % 64) + end + function U.char(...) + local n = select("#", ...) + if n == 1 then return enc((...)) end + local out = {} + for i = 1, n do out[i] = enc((select(i, ...))) end + return table.concat(out) + end + -- decode at byte i: codepoint, length; nil on invalid UTF-8 + local function dec(s, i) + local c = byte(s, i) + if not c then return nil end + if c < 0x80 then return c, 1 end + local n, v + if c >= 0xF0 and c < 0xF8 then n, v = 4, c % 8 + elseif c >= 0xE0 then n, v = 3, c % 16 + elseif c >= 0xC2 then n, v = 2, c % 32 + else return nil end + if c >= 0xF8 then return nil end + for k = 1, n - 1 do + local cc = byte(s, i + k) + if not cc or cc < 0x80 or cc >= 0xC0 then return nil end + v = v * 64 + cc % 64 + end + if (n == 3 and v < 0x800) or (n == 4 and (v < 0x10000 or v > 0x10FFFF)) or (v >= 0xD800 and v <= 0xDFFF) then + return nil + end + return v, n + end + function U.codes(s) + local i = 1 + return function() + if i > #s then return nil end + local c, n = dec(s, i) + if not c then error("invalid UTF-8 code", 2) end + local p = i + i = i + n + return p, c + end + end + function U.codepoint(s, i, j) + i = i or 1 + if i < 0 then i = #s + i + 1 end + j = j or i + if j < 0 then j = #s + j + 1 end + local out, k = {}, 0 + while i <= j do + local c, n = dec(s, i) + if not c then error("invalid UTF-8 code", 2) end + k = k + 1 + out[k] = c + i = i + n + end + return unpack(out, 1, k) + end + -- len(s, i, j) -> count | nil, position of the first invalid byte + function U.len(s, i, j) + i = i or 1 + j = j or #s + if i < 0 then i = #s + i + 1 end + if j < 0 then j = #s + j + 1 end + local n = 0 + while i <= j do + local c, l = dec(s, i) + if not c then return nil, i end + n = n + 1 + i = i + l + end + return n + end + local function iscont(s, i) + local c = byte(s, i) + return c ~= nil and c >= 0x80 and c < 0xC0 + end + function U.offset(s, n, i) + i = i or (n >= 0 and 1 or #s + 1) + if i < 0 then i = #s + i + 1 end + if n == 0 then + while i > 1 and iscont(s, i) do i = i - 1 end + return i + end + if iscont(s, i) then error("initial position is a continuation byte", 2) end + if n > 0 then + n = n - 1 + while n > 0 and i <= #s do + i = i + 1 + while iscont(s, i) do i = i + 1 end + n = n - 1 + end + if n == 0 then return i end + return nil + end + while n < 0 and i > 1 do + i = i - 1 + while i > 1 and iscont(s, i) do i = i - 1 end + n = n + 1 + end + if n == 0 then return i end + return nil + end + function U.graphemes(s) + return U.codes(s) + end + M.utf8 = utf8 or U +end + +-- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself) +function M.install(env) + env = env or _G + env.buffer = env.buffer or M.buffer + env.bit32 = env.bit32 or M.bit32 + env.utf8 = env.utf8 or M.utf8 + env.typeof = env.typeof or M.typeof + return M +end + +return M +end)() +if package and package.loaded and package.loaded["rosetta._compat"] == nil then + package.loaded["rosetta._compat"] = __compat +end +local __FILES = {} +local __LOADED = {} +local function __include(path) + local r = __LOADED[path] + if r == nil then + local f = __FILES[path] + if f == nil then + error("rosetta: no module '" .. tostring(path) .. "'", 2) + end + __LOADED[path] = false -- while it runs (a cycle, or a module that threw) + r = f() + if r == nil then + r = true + end + __LOADED[path] = r + elseif r == false then + error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) + end + return r +end +__LOADED["_compat"] = __compat +__FILES[""] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- Rosetta: read, write and convert file formats in pure Luau, on Roblox and on LuaJIT / LÖVE (through tools/build.py). +-- Every format of a category maps onto one standard type (src/Rosetta/Types.luau): a PNG and a WebP both load as an +-- Image. Formats are found through the generated Registry: by content (each format's sniff), then by extension. +-- +-- local F = require(Rosetta) -- Roblox: the ModuleScript; LuaJIT: require("rosetta"); luau: "@rosetta" +-- local img, err = F.load(src, opts?) -- src: buffer | string | path (hosts with files); err: core/Err +-- local img = F.image.load(src) -- the same, restricted to one category (F.audio, F.model, ...) +-- local dec = F.audio.open(src) -- streaming decoders (audio / video) +-- local buf = F.save(img, nil, { format = "png" }) -- a buffer; without format: the source format +-- F.save(img, "out.png") -- a file (the format from the extension), on hosts with files +-- local s = F.saveString(img, { format = "png" }) +-- local buf = F.convert(src, "png", opts?) -- load + save +-- F.formats() -- the capability list (also docs/FORMATS.md) +-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / music / vector +-- +-- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Registry = __include("Registry") +local Video = __include("codecs/video/Video") +local AudioWrap = __include("containers/AudioWrap") +local Rbx = __include("codecs/model/Rbx") +local ImageOps = __include("ops/ImageOps") +local host = __include("host") + +local F = {} + +F.version = "0.1.0" +F.Err = Err +F.Types = Types +F.Bytes = Bytes +F.Rbx = Rbx -- the Roblox instance tree helpers (codecs/model/Rbx: tree, instance, add, set, get, find, descendants) +F.null = Types.null +F.host = host +F.plugins = {} +-- value.kind -> category + +local KIND_CATEGORY= { + image = "image", + audio = "audio", + video = "video", + scene = "model", + rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx) + cad = "cad", + font = "font", + archive = "archive", + vector = "vector", + tilemap = "vector", + layered = "layered", + subtitles = "subtitle", + music = "music", + midi = "music", + playlist = "playlist", +} + +-- ------------------------------------------------------------------------------------------------ registry access +local loaded= {} + +local function module(entry) +local m = loaded[entry.path] + if m then + return m + end + local ok, res = pcall(entry.load) + if not ok then + return nil, Err.new(Err.UNSUPPORTED, "format " .. entry.name .. " failed to load: " .. tostring(res)) + end + loaded[entry.path] = res + return res +end + +local function inCategory(entry, category) +return category == nil or entry.category == category +end + +-- find(nameOrExt, category?) -> the entry whose name, then whose extension, matches +local function find(key, category) +local k = string.lower(key) + for _, e in __iter(Registry) do + if e.name == k and inCategory(e, category) then + return e + end + end + for _, e in __iter(Registry) do + if inCategory(e, category) and table.find(e.extensions, k) then + return e + end + end + return nil +end + +-- detect(buf, name?, category?, format?) -> entry | nil, Err: opts.format, else the best sniff, else the extension +local function detect(buf, name, category, format) +if format then + local e = find(format, category) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. format .. ((category and((" in " .. category ))or("")))) + end + return e, nil + end + local ext = Input.extension(name) + local best= nil + local bestScore = 0 + for _, e in __iter(Registry) do + if inCategory(e, category) and (e.caps.decode or e.caps.open) then + local m = module(e) + if m and m.sniff then + local ok, score = pcall(m.sniff, Bytes.reader(buf)) + if ok and type(score) == "number" and score > 0 then + if ext and table.find(e.extensions, ext) then + score =score+ 0.01 -- ties go to the extension + end + if score > bestScore then + best, bestScore = e, score + end + end + end + end + end + if best then + return best, nil + end + if ext then + local e = find(ext, category) + if e then + return e, nil + end + end + return nil, Err.new(Err.UNKNOWN_FORMAT, "unrecognised data" .. ((name and((" (" .. name .. ")" ))or(""))) .. ((category and((" for " .. category ))or("")))) +end + +-- detectFor(buf, name, o) -> entry | nil, Err, rendered: detect with o.category / o.format; every music file that +-- renders (MOD, S3M, XM, IT, MIDI) is also audio, so an audio lookup that finds nothing falls back to them (rendered = +-- true: open the format, which renders it, instead of decoding it) +local function detectFor(buf, name, o) +local entry, err = detect(buf, name, o.category, o.format) + if not entry and o.category == "audio" then + local e = detect(buf, name, "music", o.format) + if e and e.caps.render then + return e, nil, true + end + end + return entry, err, false +end + +local function tag(value, formatName) + if type(value) == "table" then + local meta = value.meta + if type(meta) == "table" then + if meta.source == nil then + meta.source = { format = formatName } + elseif type(meta.source) == "table" and meta.source.format == nil then + meta.source.format = formatName + end + end + end +end + +-- full decode through a streaming decoder (audio formats with open but no decode) +local function drain(dec) +local channels = dec.channels + local parts, total = {}, 0 + while true do + local out, n = dec:read(65536) + if not out or n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total =total+ n + end + local a = Types.Audio.new(dec.sampleRate, channels, total) + local o = 0 + for _, p in __iter(parts) do + buffer.copy(a.samples, o, p) + o =o+ buffer.len(p) + end + a.tags = dec.tags or {} + return a +end + +-- siblings(path) -> resolve(uri): reads files relative to path's directory (no absolute paths, no "..", no URLs) +local function siblings(path) +local dir = string.match(path, "^(.*[/\\])") or "" + return function(uri) +if type(uri) ~= "string" or uri == "" or string.find(uri, "^%a[%w+.-]*:") or string.sub(uri, 1, 1) == "/" then + return nil + end + local u = string.gsub(uri, "%%(%x%x)", function(h) +return string.char((tonumber(h, 16) )) + end) + for part in __iter(string.gmatch(u, "[^/\\]+")) do + if part == ".." then + return nil + end + end + local b = host.readFile(dir .. u) + return b + end +end +-- ------------------------------------------------------------------------------------------------ API + + + +local load +-- bitmap fonts (font/bmfont) name their page images: attach a lazy loader, opts.loadPage(file, page) -> Image | buffer +-- | string, else the files next to the descriptor on hosts with a file system + +local function pageLoader(value, name, o) + if type(value) ~= "table" or value.kind ~= "font" or type(value.meta) ~= "table" or type(value.meta.pageFiles) ~= "table" then + return + end + local user= o.loadPage + if value.pages or (value.meta.pageLoader and type(user) ~= "function") then + return + end + local dir = (name and{string.match(name, "^(.*[/\\])") or "" }or{nil +})[1] if type(user) ~= "function" and not (dir and host.hasFiles) then + return + end + value.meta.pageLoader = function(file, page) +local src +if type(user) == "function" then + src = (user )(file, page) + else + src = (dir ) .. file + end + if type(src) == "table" then + return src -- already an Image + end + if src == nil then + return nil, Err.new(Err.IO, "no data for page " .. file) + end + return load(src, { category = "image", name = file, path = type(user) ~= "function" }) + end +end + +-- single-stream archives (gzip / zst / xz / bz2 / br: meta.stream) whose one entry sniffs as another archive (a +-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer +-- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's +-- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the +-- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font. +local function unwrap(value, formatName, o) +if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then + return value + end + if type(value) ~= "table" or value.kind ~= "archive" or type(value.meta) ~= "table" then + return value + end + local payload = value.meta.payload + if not value.meta.stream and type(payload) ~= "string" then + return value + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" or (#list ~= 1 and type(payload) ~= "string") or #list == 0 then + return value + end + local entryName = (type(payload) == "string" and{payload }or{list[1].name +})[1] local rok, inner = pcall(value.read, value, entryName) + if not rok or type(inner) ~= "buffer" then + return value + end + local category = "archive" + local e = detect(inner, nil, "archive", nil) + local innerExt = Input.extension(entryName) or "" + if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then + -- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font + e = detect(inner, entryName, "font", nil) + category = "font" + end + if not e then + return value + end + local io = table.clone(o) + io.category = category + io.name = entryName + io._depth = (o._depth or 0) + 1 + local v = load(inner, io) + if type(v) ~= "table" or type(v.meta) ~= "table" then + return value + end + if type(payload) == "string" then + v.meta.container = formatName + v.meta.outer = value + else + v.meta.compression = formatName + end + return v +end + +-- Embedded images (PNG inside ICO, JPEG inside TIFF, thumbnails, textures): a format never requires another format, +-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> +-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for +-- the embedded parts) when called directly. +-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. +-- +-- Tracker modules inside other files (music/umx): opts.decodeModule(buf, format?) -> Module | nil, Err, the bytes loaded +-- as music (sniffed, or as the given format). +-- +-- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets +-- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / +-- FLAC / AC-3 as they are), opened through F.open with that format. +local function openAudio(demuxer, track) +local buf, fmt, err = AudioWrap.wrap(demuxer, track) + if not buf then + return nil, err + end + local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) + -- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is + -- already the decoder's own (its first packet returns nothing) + -- MP4 edit lists add the play length (the encoder's end padding is cut, as ffmpeg does) + if dec and fmt ~= "opus" and fmt ~= "vorbis" then + local skip = (type(track.codecDelay) == "number" and track.codecDelay > 0 and{(math.floor(track.codecDelay * dec.sampleRate + 0.5) )}or{0 +})[1] local length = (type(track.playDuration) == "number" and track.playDuration > 0 and{(math.floor(track.playDuration * dec.sampleRate + 0.5) )}or{nil +})[1] if skip > 0 or length then + dec = AudioWrap.trim(dec, skip, length) + end + end + return dec, oerr +end + +local function withHooks(o) +if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil and o.decodeModule ~= nil then + return o + end + local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end + if c.openAudio == nil then + c.openAudio = openAudio + end + if c.decodeImage == nil then + c.decodeImage = function(b) +return F.load(b, { category = "image" }) + end + end + if c.encodeImage == nil then + c.encodeImage = function(img, format) +return F.save(img, nil, { format = format, category = "image" }) + end + end + if c.decodeModule == nil then + -- tracker modules inside other files (music/umx: the module of an Unreal package), as their own format + c.decodeModule = function(b, format) +return F.load(b, { category = "music", format = format }) + end + end + return c +end + +-- load(src, opts?) -> value | nil, Err +function F.load(src, opts) +local o= opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + if name and o.name == nil then + o = table.clone(o) + o.name = name -- formats may use the file name (single-stream archives name their entry after it) + end + local entry, derr, rendered = detectFor(buf, name, o) + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if o.resolve == nil and name and name == (type(src) == "string" and src or nil) and host.hasFiles then + -- files next to the one loaded (OBJ .mtl, glTF .bin / images): opts.resolve(uri) for the decoder + o = table.clone(o) + o.resolve = siblings(name) + end + local value, err + if m.decode and not rendered then + local ok, v, e = pcall(m.decode, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(v)), entry.name) + end + value, err = v, e + elseif m.open then + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec then + value = (type(dec) == "table" and dec.kind == "video" and{dec }or{(drain(dec) +)})[1] end + err = e + else + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no decoder"), entry.name) + end + if value == nil then + return nil, Err.wrap(err or Err.new(Err.CORRUPT, "decode failed"), entry.name) + end + tag(value, entry.name) + pageLoader(value, name, o) + return unwrap(value, entry.name, o) +end +load = F.load + +-- open(src, opts?) -> a streaming decoder (audio Decoder / VideoDecoder / Demuxer) | nil, Err +function F.open(src, opts) +local o= opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, derr = detectFor(buf, name, o) + if not entry and o.category == "video" and o.format == nil then + entry = detect(buf, name, "image", nil) -- animated images open as frames-backed videos + end + if not entry then + return nil, derr + end + local m, merr = module(entry) + if not m then + return nil, merr + end + if not m.open and entry.category == "image" and o.category == "video" then + local io = table.clone(o) + io.category = "image" + io.format = entry.name + local img, lerr = F.load(buf, io) + if not img then + return nil, lerr + end + return F.video.fromImage(img, o) + end + if not m.open then + return nil, Err.wrap(Err.new(Err.UNSUPPORTED, "no streaming decoder (use load)"), entry.name) + end + local ok, dec, e = pcall(m.open, Bytes.reader(buf), withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "decoder threw: " .. tostring(dec)), entry.name) + end + if dec == nil then + return nil, Err.wrap(e or Err.new(Err.CORRUPT, "open failed"), entry.name) + end + return dec +end + +local encodeTextures +-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil, +-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are +-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap +-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is. + +local function videoToImage(v, o) +if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then + return nil, Err.new(Err.ARG, "save: not a VideoDecoder") + end + local cap = o.maxFrames or 300 + local want = o.frames + local fps = o.fps + if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then + return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000") + end + local limit = math.floor((want and{(math.min(want, cap) )}or{cap})[1]) + local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1) + limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h)))) + local defaultDur = (type(v.frameRate) == "number" and v.frameRate > 0 and((1 / v.frameRate ))or(0.1 +)) local images, delays= {}, {} + local t0= nil + local taken = 0 -- output slots used (fps mode) + while #images < limit do + local ok, f, ferr = pcall(v.nextFrame, v) + if not ok then + return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f)) + end + if f == nil then + if ferr then + return nil, ferr + end + break + end + local dur = (type(f.duration) == "number" and f.duration > 0 and{f.duration }or{defaultDur +})[1] local delay = dur + if fps then + local start= t0 or f.pts + t0 = start + local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken + delay = slots / fps + taken =taken+ math.max(0, slots) + end + if delay > 0 then + local rok, img = pcall(v.toRGBA, v, f) + if not rok or type(img) ~= "table" then + return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8") + end + table.insert(images, img) + table.insert(delays, delay) + end + end + if #images == 0 then + return nil, Err.new(Err.ARG, "save: the video has no frames") + end + local img, ierr = ImageOps.fromFrames(images, delays) + if not img then + return nil, ierr + end + img.loops = (type(v.loops) == "number" and{v.loops }or{0 +})[1] img.meta.source = { format = v.format } + return img, nil +end + +-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker, or the Module's own render method +-- for other engines) or a Midi (music/midi render) | +-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ... +local TRACKER_FAMILY = { mod = true, s3m = true, xm = true, it = true } +local function renderMusic(value, o) +local ok, dec, err + if value.kind == "midi" then + local m, merr = F.format("midi") + if not m then + return nil, merr + end + ok, dec, err = pcall(m.render, value, o) + elseif TRACKER_FAMILY[value.engine or value.format] == nil and type(value.render) == "function" then + -- a Module with its own engine (AHX / HVL: codecs/audio/Hively): its render method (a failed render is an + -- empty Decoder carrying .err) + ok, dec = pcall(value.render, value, o) + if ok and type(dec) == "table" and dec.err then + return nil, dec.err + end + else + local Tracker= __include("codecs/audio/Tracker") + ok, dec, err = pcall(Tracker.render, value, o) + end + if not ok then + return nil, Err.new(Err.ARG, "render threw: " .. tostring(dec)) + end + if dec == nil then + return nil, err or Err.new(Err.ARG, "render failed") + end + return dec, nil +end + +-- the writable format for a value: opts.format, the destination's extension, or the source format +local function encoderFor(value, dest, o) +local category = o.category + if category == nil and type(value) == "table" and type(value.kind) == "string" then + category = KIND_CATEGORY[value.kind] + end + local key = o.format or Input.extension(dest) + if key == nil and type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" then + key = value.meta.source.format + end + if key == nil then + return nil, nil, Err.new(Err.ARG, "save: no format (pass opts.format or a destination with an extension)") + end + local entry = find(key, category) + if not entry and category == "image" and type(value) == "table" and value.kind == "image" then + entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi") + end + if not entry and category == "video" and type(value) == "table" and value.kind == "video" then + entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif") + end + if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav") + end + if not entry then + return nil, nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. key .. ((category and((" for " .. category ))or("")))) + end + local m, merr = module(entry) + if not m then + return nil, nil, merr + end + if not m.encode then + local alt = nil + for _, e in __iter(Registry) do + if e.category == entry.category and e.caps.encode then + alt = e.name + break + end + end + return nil, nil, Err.wrap(Err.new(Err.UNSUPPORTED, "read-only format" .. ((alt and(("; try " .. alt ))or("")))), entry.name) + end + return entry, m, nil, key +end + +-- scene textures with only a decoded image get PNG bytes before a model writer sees them (writers never encode images) +function encodeTextures(scene) +if type(scene.textures) ~= "table" then + return nil + end + for _, tex in __iter(scene.textures) do + if type(tex) == "table" and tex.data == nil and type(tex.image) == "table" and tex.uri == nil then + local png, err = F.save(tex.image, nil, { format = "png" }) + if not png then + return err + end + tex.data, tex.mime = png, "image/png" + end + end + return nil +end + +-- save(value, dest?, opts?) -> buffer (no dest) | true (written to dest) | nil, Err. Formats that write extra files +-- (caps.extraFiles: bmfont pages) return them without a dest as a third value { [file name] = bytes } (or fill the +-- caller's opts.files); with a dest they are written next to it. +function F.save(value, dest, opts) +local o= opts or {} + local entry, m, err, key = encoderFor(value, dest, o) + if not entry then + return nil, err + end + -- the encoder sees the format key it was picked by ("glb" vs "gltf"), the destination's name, and (writing a file) + -- an opts.files table for the extra files it writes (OBJ .mtl, glTF .bin) + o = table.clone(o) + o.format = o.format or key + if dest then + o.name = o.name or string.match(dest, "([^/\\]+)$") + if o.files == nil then + o.files = {} + end + elseif o.files == nil and entry.caps.extraFiles then + o.files = {} -- returned as the third value: F.save(ttf, nil, { format = "bmfont" }) -> fnt, nil, pages + end + if entry.category == "video" and type(value) == "table" and value.kind == "image" then + local v, verr = F.video.fromImage(value) + if not v then + return nil, verr + end + value = v + end + if entry.category == "image" and type(value) == "table" and value.kind == "video" then + local img, ierr = videoToImage(value, o) + if not img then + return nil, ierr + end + value = img + end + if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then + local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts + if not dec then + return nil, rerr + end + value = dec + end + if type(value) == "table" and value.kind == "scene" then + local terr = encodeTextures(value) + if terr then + return nil, terr + end + end + local ok, buf, e = pcall(m.encode, value, withHooks(o)) + if not ok then + return nil, Err.wrap(Err.new(Err.ARG, "encoder threw: " .. tostring(buf)), entry.name) + end + if buf == nil then + return nil, Err.wrap(e or Err.new(Err.ARG, "encode failed"), entry.name) + end + if dest then + local wok, werr = host.writeFile(dest, buf) + if not wok then + return nil, werr + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) then + local dir = string.match(dest, "^(.*[/\\])") or "" + for fname, data in __iter(o.files) do + local fok, ferr = host.writeFile(dir .. fname, (type(data) == "string" and{(buffer.fromstring(data) )}or{data})[1]) + if not fok then + return nil, ferr + end + end + end + return true + end + if type(o.files) == "table" and o.files ~= (opts and opts.files) and next(o.files) ~= nil then + return buf, nil, o.files + end + return buf +end + +-- saveString(value, opts?) -> string | nil, Err +function F.saveString(value, opts) +local buf, err = F.save(value, nil, opts) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- convert(src, format, opts?) -> buffer (or true with opts.out = a path) | nil, Err. opts go to both load and save. +function F.convert(src, format, opts) +local o= opts or {} + local value, err = F.load(src, o) + if value == nil then + return nil, err + end + local so = table.clone(o) + so.format = format + so.category = nil + return F.save(value, o.out, so) +end + +-- detect(src, opts?) -> format name | nil, Err +function F.detect(src, opts) +local o= opts or {} + local buf, ierr, name = Input.resolve(src, o, host) + if not buf then + return nil, ierr + end + local entry, err = detect(buf, name, o.category, o.format) + if not entry then + return nil, err + end + -- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm) + local m = module(entry) + if m and type(m.variant) == "function" then + local ok, v = pcall(m.variant, Bytes.reader(buf)) + if ok and type(v) == "string" then + return v, nil + end + end + return entry.name, nil +end + +-- formats(category?) -> { FormatInfo } (no format module is loaded) + + +function F.formats(category) +local out = {} + for _, e in __iter(Registry) do + if inCategory(e, category) then + table.insert(out, { name = e.name, category = e.category, extensions = e.extensions, mime = e.mime, caps = e.caps }) + end + end + return out +end + +-- format(name) -> the format module itself (its contract table: sniff / decode / encode / extras such as png.info) +function F.format(name) +local e = find(name) + if not e then + return nil, Err.new(Err.UNKNOWN_FORMAT, "no format named " .. name) + end + return module(e) +end + +-- ------------------------------------------------------------------------------------------------ category facades +-- F.image.load / save / open / formats, F.audio..., F.model... : the same calls restricted to one category +local function with(opts, category) +local o= (opts and{(table.clone(opts) )}or{{} +})[1] o.category = category + return o +end +for category in __iter(Types.CATEGORIES) do + local cat= category + F[cat] = { + load = function(src, opts) +return F.load(src, with(opts, cat)) + end, + open = function(src, opts) +return F.open(src, with(opts, cat)) + end, + save = function(value, dest, opts) +return F.save(value, dest, with(opts, cat)) + end, + formats = function() +return F.formats(cat) + end, + } +end +F.data.null = Types.null + +-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; +-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel +-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. +for _, fn in __iter({ "toBodies", "fromBodies", "tessellate" }) do + local name= fn + F.cad[name] = function(value, opts) +local o= (opts and{(table.clone(opts) )}or{{} +})[1] if o.plugins == nil then + o.plugins = F.plugins + end + local m, err = F.format("step") + if not m then + return nil, err + end + local ok, a, b = pcall(m[name], value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") + end + if a == nil and type(b) == "table" and b.code then + return nil, Err.wrap(b, "step") + end + return a, b + end +end +-- F.music.new / addPattern / setCell / getCell / addSample / addInstrument / note: building and editing tracker +-- Modules (ops/MusicOps, loaded on first use): F.music.new({ format = "mod", channels = 4 }) -> Module +for _, fn in __iter({ "new", "addPattern", "setCell", "getCell", "addSample", "addInstrument", "note" }) do + local name= fn + F.music[name] = function(...) +return (F.ops.music )[name](...) + end +end +-- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited +-- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). +F.video.fromImage = function(img, opts) +if type(img) ~= "table" or img.kind ~= "image" then + return nil, Err.new(Err.ARG, "fromImage: expected an Image") + end + local frames, delays = { img }, { 0.1 } + if type(img.frames) == "table" and #img.frames > 0 then + local list, cerr = ImageOps.coalesce(img) + if not list then + return nil, cerr + end + frames = list + delays = {} + for i, f in __iter(img.frames) do + delays[i] = (type(f.delay) == "number" and f.delay > 0 and{f.delay }or{0.1 +})[1] end + elseif img.format ~= "rgba8" and img.format ~= "yuv420p" then + local c, cerr = ImageOps.convert(img, "rgba8") + if not c then + return nil, cerr + end + frames = { c } + end + local src = type(img.meta) == "table" and img.meta.source + return Video.fromFrames(frames, delays, { format = type(src) == "table" and src.format or "image", loops = img.loops, meta = img.meta }) +end +-- F.video.fromFrames(images, delays?, opts?) -> a VideoDecoder over a list of same-size images (an image sequence: +-- F.save(F.video.fromFrames(list, 1 / 25), "out.avi")); delays in seconds (a number = every frame, default 0.1) +F.video.fromFrames = function(images, delays, opts) +return Video.fromFrames(images, delays, opts) +end +-- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) +F.video.codecs = Video + +-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or +-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images +-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose +-- image format is missing or broken keep image = nil and report an Err. +F.model.loadTextures = function(scene, opts) +local errs= {} + if type(scene) ~= "table" or type(scene.textures) ~= "table" then + return scene, errs + end + local resolve= opts and opts.resolve + for i, tex in __iter(scene.textures) do + if type(tex) == "table" and tex.image == nil then + local data = tex.data + if data == nil and tex.uri and resolve then + data = resolve(tex.uri) + end + if data ~= nil then + local img, err = F.load(data, { category = "image", name = tex.uri, data = true }) + if img then + tex.image = img + elseif err then + errs[i] = err + end + end + end + end + return scene, errs +end + +-- ------------------------------------------------------------------------------------------------ ops +-- F.ops: editing on the standard types, loaded on first use. +-- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... +-- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... +-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves +-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, +-- concat, fade, peak, rms +-- F.ops.music ops/MusicOps new, addPattern, setCell / getCell, addSample, addInstrument, note (also on F.music) +-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector +local OPS= { + image = function() + return ImageOps + end, + mesh = function() + return __include("ops/MeshOps") + end, + layers = function() + return __include("ops/LayerOps") + end, + audio = function() + return __include("ops/AudioOps") + end, + music = function() + return __include("ops/MusicOps") + end, + vector = function() + return { + rasterize = function(v, w, h, opts) +local svg, err = F.format("svg") + if not svg then + return nil, err + end + local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg") + end + if img == nil and rerr then + return nil, Err.wrap(rerr, "svg") + end + return img, rerr + end, + } + end, +} +F.ops = (setmetatable({}, { + __index = function(t, k) +local make = OPS[k] + if not make then + return nil + end + local m = make() + rawset(t, k, m) + return m + end, +}) ) + +return F +end +__FILES["Registry"] = function() +--!strict +-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit. +-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format +-- module on first use (a static require, as Roblox needs). Order: category, then name. + + + + + + + + + + + +local list= { + { + name = "ani", + category = "image", + path = "image/ani", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, + load = function() + return __include("image/ani") + end, + }, + { + name = "blp", + category = "image", + path = "image/blp", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, + load = function() + return __include("image/blp") + end, + }, + { + name = "bmp", + category = "image", + path = "image/bmp", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 __include("image/bmp") + end, + }, + { + name = "dds", + category = "image", + path = "image/dds", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, + load = function() + return __include("image/dds") + end, + }, + { + name = "exr", + category = "image", + path = "image/exr", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, + load = function() + return __include("image/exr") + end, + }, + { + name = "gif", + category = "image", + path = "image/gif", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 __include("image/gif") + end, + }, + { + name = "hdr", + category = "image", + path = "image/hdr", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, + load = function() + return __include("image/hdr") + end, + }, + { + name = "icns", + category = "image", + path = "image/icns", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, + load = function() + return __include("image/icns") + end, + }, + { + name = "ico", + category = "image", + path = "image/ico", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 __include("image/ico") + end, + }, + { + name = "ilbm", + category = "image", + path = "image/ilbm", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, + load = function() + return __include("image/ilbm") + end, + }, + { + name = "jpeg", + category = "image", + path = "image/jpeg", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 __include("image/jpeg") + end, + }, + { + name = "ktx", + category = "image", + path = "image/ktx", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, + load = function() + return __include("image/ktx") + end, + }, + { + name = "pcx", + category = "image", + path = "image/pcx", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, + load = function() + return __include("image/pcx") + end, + }, + { + name = "png", + category = "image", + path = "image/png", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 __include("image/png") + end, + }, + { + name = "pnm", + category = "image", + path = "image/pnm", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, + load = function() + return __include("image/pnm") + end, + }, + { + name = "qoi", + category = "image", + path = "image/qoi", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, + load = function() + return __include("image/qoi") + end, + }, + { + name = "sgi", + category = "image", + path = "image/sgi", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, + load = function() + return __include("image/sgi") + end, + }, + { + name = "sunras", + category = "image", + path = "image/sunras", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, + load = function() + return __include("image/sunras") + end, + }, + { + name = "tga", + category = "image", + path = "image/tga", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, + load = function() + return __include("image/tga") + end, + }, + { + name = "tiff", + category = "image", + path = "image/tiff", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 __include("image/tiff") + end, + }, + { + name = "tim", + category = "image", + path = "image/tim", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, + load = function() + return __include("image/tim") + end, + }, + { + name = "vtf", + category = "image", + path = "image/vtf", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, + load = function() + return __include("image/vtf") + end, + }, + { + name = "webp", + category = "image", + path = "image/webp", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 __include("image/webp") + end, + }, + { + name = "xbm", + category = "image", + path = "image/xbm", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, + load = function() + return __include("image/xbm") + end, + }, + { + name = "xpm", + category = "image", + path = "image/xpm", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, + load = function() + return __include("image/xpm") + end, + }, + { + name = "aac", + category = "audio", + path = "audio/aac", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-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 __include("audio/aac") + end, + }, + { + name = "ac3", + category = "audio", + path = "audio/ac3", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, + load = function() + return __include("audio/ac3") + end, + }, + { + name = "adpcm", + category = "audio", + path = "audio/adpcm", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, + load = function() + return __include("audio/adpcm") + end, + }, + { + name = "adx", + category = "audio", + path = "audio/adx", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, + load = function() + return __include("audio/adx") + end, + }, + { + name = "aiff", + category = "audio", + path = "audio/aiff", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, + load = function() + return __include("audio/aiff") + end, + }, + { + name = "ape", + category = "audio", + path = "audio/ape", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, + load = function() + return __include("audio/ape") + end, + }, + { + name = "au", + category = "audio", + path = "audio/au", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 __include("audio/au") + end, + }, + { + name = "brstm", + category = "audio", + path = "audio/brstm", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, + load = function() + return __include("audio/brstm") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 __include("audio/caf") + end, + }, + { + name = "flac", + category = "audio", + path = "audio/flac", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 __include("audio/flac") + end, + }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 __include("audio/m4a") + end, + }, + { + name = "mp3", + category = "audio", + path = "audio/mp3", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 __include("audio/mp3") + end, + }, + { + name = "mpc", + category = "audio", + path = "audio/mpc", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, + load = function() + return __include("audio/mpc") + end, + }, + { + name = "opus", + category = "audio", + path = "audio/opus", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 __include("audio/opus") + end, + }, + { + name = "qoa", + category = "audio", + path = "audio/qoa", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, + load = function() + return __include("audio/qoa") + end, + }, + { + name = "tta", + category = "audio", + path = "audio/tta", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, + load = function() + return __include("audio/tta") + end, + }, + { + name = "vag", + category = "audio", + path = "audio/vag", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, + load = function() + return __include("audio/vag") + end, + }, + { + name = "voc", + category = "audio", + path = "audio/voc", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, + load = function() + return __include("audio/voc") + end, + }, + { + name = "vorbis", + category = "audio", + path = "audio/vorbis", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + 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 __include("audio/vorbis") + end, + }, + { + name = "wav", + category = "audio", + path = "audio/wav", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, + load = function() + return __include("audio/wav") + end, + }, + { + name = "wavpack", + category = "audio", + path = "audio/wavpack", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, + load = function() + return __include("audio/wavpack") + end, + }, + { + name = "avi", + category = "video", + path = "video/avi", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, + load = function() + return __include("video/avi") + end, + }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return __include("video/fli") + end, + }, + { + name = "flv", + category = "video", + path = "video/flv", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, + load = function() + return __include("video/flv") + end, + }, + { + name = "h264", + category = "video", + path = "video/h264", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 __include("video/h264") + end, + }, + { + name = "mkv", + category = "video", + 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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, + load = function() + return __include("video/mkv") + end, + }, + { + name = "mp4", + category = "video", + 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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, + load = function() + return __include("video/mp4") + end, + }, + { + name = "mpegps", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, + load = function() + return __include("video/mpegps") + end, + }, + { + name = "mpegts", + category = "video", + 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/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, + load = function() + return __include("video/mpegts") + end, + }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return __include("video/ogv") + end, + }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return __include("video/smk") + end, + }, + { + name = "y4m", + category = "video", + path = "video/y4m", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 __include("video/y4m") + end, + }, + { + name = "3ds", + category = "model", + path = "model/3ds", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, + load = function() + return __include("model/3ds") + end, + }, + { + name = "3mf", + category = "model", + path = "model/3mf", + extensions = { "3mf" }, + mime = { "model/3mf" }, + 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 __include("model/3mf") + end, + }, + { + name = "b3d", + category = "model", + path = "model/b3d", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, + load = function() + return __include("model/b3d") + end, + }, + { + name = "bsp", + category = "model", + path = "model/bsp", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + load = function() + return __include("model/bsp") + end, + }, + { + name = "dae", + category = "model", + path = "model/dae", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 __include("model/dae") + end, + }, + { + name = "fbx", + category = "model", + path = "model/fbx", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 __include("model/fbx") + end, + }, + { + name = "gltf", + category = "model", + path = "model/gltf", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, + load = function() + return __include("model/gltf") + end, + }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return __include("model/iqm") + end, + }, + { + name = "ldraw", + category = "model", + path = "model/ldraw", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, + load = function() + return __include("model/ldraw") + end, + }, + { + name = "lwo", + category = "model", + path = "model/lwo", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, + load = function() + return __include("model/lwo") + end, + }, + { + name = "mca", + category = "model", + path = "model/mca", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, + load = function() + return __include("model/mca") + end, + }, + { + name = "md2", + category = "model", + path = "model/md2", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, + load = function() + return __include("model/md2") + end, + }, + { + name = "md3", + category = "model", + path = "model/md3", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, + load = function() + return __include("model/md3") + end, + }, + { + name = "md5", + category = "model", + path = "model/md5", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, + load = function() + return __include("model/md5") + end, + }, + { + name = "mdl", + category = "model", + path = "model/mdl", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, + load = function() + return __include("model/mdl") + end, + }, + { + name = "ms3d", + category = "model", + path = "model/ms3d", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, + load = function() + return __include("model/ms3d") + end, + }, + { + name = "obj", + category = "model", + path = "model/obj", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/obj") + end, + }, + { + name = "off", + category = "model", + path = "model/off", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + 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 __include("model/off") + end, + }, + { + name = "ply", + category = "model", + path = "model/ply", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + 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 __include("model/ply") + end, + }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return __include("model/pmx") + end, + }, + { + name = "qb", + category = "model", + path = "model/qb", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, + load = function() + return __include("model/qb") + end, + }, + { + name = "rbxm", + category = "model", + path = "model/rbxm", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, + load = function() + return __include("model/rbxm") + end, + }, + { + name = "rbxmx", + category = "model", + path = "model/rbxmx", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, + load = function() + return __include("model/rbxmx") + end, + }, + { + name = "robloxmesh", + category = "model", + path = "model/robloxmesh", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, + load = function() + return __include("model/robloxmesh") + end, + }, + { + name = "schematic", + category = "model", + path = "model/schematic", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, + load = function() + return __include("model/schematic") + end, + }, + { + name = "smd", + category = "model", + path = "model/smd", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, + load = function() + return __include("model/smd") + end, + }, + { + name = "stl", + category = "model", + path = "model/stl", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + 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 __include("model/stl") + end, + }, + { + name = "usda", + category = "model", + path = "model/usda", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 __include("model/usda") + end, + }, + { + name = "vox", + category = "model", + path = "model/vox", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, + load = function() + return __include("model/vox") + end, + }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return __include("model/vrml") + end, + }, + { + name = "x", + category = "model", + path = "model/x", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, + load = function() + return __include("model/x") + end, + }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return __include("model/x3d") + end, + }, + { + name = "step", + category = "cad", + path = "cad/step", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, + load = function() + return __include("cad/step") + end, + }, + { + name = "bdf", + category = "font", + path = "font/bdf", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, + load = function() + return __include("font/bdf") + end, + }, + { + name = "bmfont", + category = "font", + path = "font/bmfont", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, + load = function() + return __include("font/bmfont") + end, + }, + { + name = "eot", + category = "font", + path = "font/eot", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, + load = function() + return __include("font/eot") + end, + }, + { + name = "fon", + category = "font", + path = "font/fon", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, + load = function() + return __include("font/fon") + end, + }, + { + name = "hershey", + category = "font", + path = "font/hershey", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, + load = function() + return __include("font/hershey") + end, + }, + { + name = "pcf", + category = "font", + path = "font/pcf", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, + load = function() + return __include("font/pcf") + end, + }, + { + name = "psf", + category = "font", + path = "font/psf", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, + load = function() + return __include("font/psf") + end, + }, + { + name = "ttf", + category = "font", + path = "font/ttf", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, + load = function() + return __include("font/ttf") + end, + }, + { + name = "type1", + category = "font", + path = "font/type1", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, + load = function() + return __include("font/type1") + end, + }, + { + name = "woff", + category = "font", + path = "font/woff", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, + load = function() + return __include("font/woff") + end, + }, + { + name = "woff2", + category = "font", + path = "font/woff2", + extensions = { "woff2" }, + mime = { "font/woff2" }, + 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 __include("font/woff2") + end, + }, + { + name = "7z", + category = "archive", + path = "archive/7z", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + 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 __include("archive/7z") + end, + }, + { + name = "adf", + category = "archive", + path = "archive/adf", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, + load = function() + return __include("archive/adf") + end, + }, + { + name = "applesingle", + category = "archive", + path = "archive/applesingle", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, + load = function() + return __include("archive/applesingle") + end, + }, + { + name = "ar", + category = "archive", + path = "archive/ar", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, + load = function() + return __include("archive/ar") + end, + }, + { + name = "arj", + category = "archive", + path = "archive/arj", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, + load = function() + return __include("archive/arj") + end, + }, + { + name = "binhex", + category = "archive", + path = "archive/binhex", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, + load = function() + return __include("archive/binhex") + end, + }, + { + name = "br", + category = "archive", + path = "archive/br", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/br") + end, + }, + { + name = "bz2", + category = "archive", + path = "archive/bz2", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/bz2") + end, + }, + { + name = "cab", + category = "archive", + path = "archive/cab", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, + load = function() + return __include("archive/cab") + end, + }, + { + name = "cpio", + category = "archive", + path = "archive/cpio", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, + load = function() + return __include("archive/cpio") + end, + }, + { + name = "d64", + category = "archive", + path = "archive/d64", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, + load = function() + return __include("archive/d64") + end, + }, + { + name = "fat", + category = "archive", + path = "archive/fat", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, + load = function() + return __include("archive/fat") + end, + }, + { + name = "grp", + category = "archive", + path = "archive/grp", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, + load = function() + return __include("archive/grp") + end, + }, + { + name = "gzip", + category = "archive", + path = "archive/gzip", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, + load = function() + return __include("archive/gzip") + end, + }, + { + name = "iso", + category = "archive", + path = "archive/iso", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, + load = function() + return __include("archive/iso") + end, + }, + { + name = "lha", + category = "archive", + path = "archive/lha", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, + load = function() + return __include("archive/lha") + end, + }, + { + name = "lz4", + category = "archive", + path = "archive/lz4", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, + load = function() + return __include("archive/lz4") + end, + }, + { + name = "macbinary", + category = "archive", + path = "archive/macbinary", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, + load = function() + return __include("archive/macbinary") + end, + }, + { + name = "mpq", + category = "archive", + path = "archive/mpq", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, + load = function() + return __include("archive/mpq") + end, + }, + { + name = "pak", + category = "archive", + path = "archive/pak", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, + load = function() + return __include("archive/pak") + end, + }, + { + name = "rpm", + category = "archive", + path = "archive/rpm", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, + load = function() + return __include("archive/rpm") + end, + }, + { + name = "tar", + category = "archive", + path = "archive/tar", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, + load = function() + return __include("archive/tar") + end, + }, + { + name = "uu", + category = "archive", + path = "archive/uu", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, + load = function() + return __include("archive/uu") + end, + }, + { + name = "vpk", + category = "archive", + path = "archive/vpk", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, + load = function() + return __include("archive/vpk") + end, + }, + { + name = "wad", + category = "archive", + path = "archive/wad", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, + load = function() + return __include("archive/wad") + end, + }, + { + name = "xz", + category = "archive", + path = "archive/xz", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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 __include("archive/xz") + end, + }, + { + name = "yenc", + category = "archive", + path = "archive/yenc", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, + load = function() + return __include("archive/yenc") + end, + }, + { + name = "z", + category = "archive", + path = "archive/z", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, + load = function() + return __include("archive/z") + end, + }, + { + name = "zip", + category = "archive", + path = "archive/zip", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, + load = function() + return __include("archive/zip") + end, + }, + { + name = "zoo", + category = "archive", + path = "archive/zoo", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, + load = function() + return __include("archive/zoo") + end, + }, + { + name = "zst", + category = "archive", + path = "archive/zst", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return __include("archive/zst") + end, + }, + { + name = "cbor", + category = "data", + path = "data/cbor", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, + load = function() + return __include("data/cbor") + end, + }, + { + name = "csv", + category = "data", + path = "data/csv", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, + load = function() + return __include("data/csv") + end, + }, + { + name = "ini", + category = "data", + path = "data/ini", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, + load = function() + return __include("data/ini") + end, + }, + { + name = "json", + category = "data", + path = "data/json", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, + load = function() + return __include("data/json") + end, + }, + { + name = "msgpack", + category = "data", + path = "data/msgpack", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, + load = function() + return __include("data/msgpack") + end, + }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return __include("data/nbt") + end, + }, + { + name = "plist", + category = "data", + path = "data/plist", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + 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 __include("data/plist") + end, + }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return __include("data/snbt") + end, + }, + { + name = "toml", + category = "data", + path = "data/toml", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, + load = function() + return __include("data/toml") + end, + }, + { + name = "xml", + category = "data", + path = "data/xml", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, + load = function() + return __include("data/xml") + end, + }, + { + name = "yaml", + category = "data", + path = "data/yaml", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + 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 __include("data/yaml") + end, + }, + { + name = "svg", + category = "vector", + path = "vector/svg", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 __include("vector/svg") + end, + }, + { + name = "tiled", + category = "vector", + 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/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" }, + caps = { decode = true, encode = true, tilesets = true, infinite = true }, + load = function() + return __include("vector/tiled") + end, + }, + { + name = "aseprite", + category = "layered", + path = "layered/aseprite", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + 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 __include("layered/aseprite") + end, + }, + { + name = "ora", + category = "layered", + path = "layered/ora", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, + load = function() + return __include("layered/ora") + end, + }, + { + name = "psd", + category = "layered", + path = "layered/psd", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 __include("layered/psd") + end, + }, + { + name = "ass", + category = "subtitle", + path = "subtitle/ass", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/ass") + end, + }, + { + name = "srt", + category = "subtitle", + path = "subtitle/srt", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, + load = function() + return __include("subtitle/srt") + end, + }, + { + name = "vtt", + category = "subtitle", + path = "subtitle/vtt", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, + load = function() + return __include("subtitle/vtt") + end, + }, + { + name = "669", + category = "music", + path = "music/669", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, + load = function() + return __include("music/669") + end, + }, + { + name = "ahx", + category = "music", + path = "music/ahx", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, + load = function() + return __include("music/ahx") + end, + }, + { + name = "far", + category = "music", + path = "music/far", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, + load = function() + return __include("music/far") + end, + }, + { + name = "hmp", + category = "music", + path = "music/hmp", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, + load = function() + return __include("music/hmp") + end, + }, + { + name = "hvl", + category = "music", + path = "music/hvl", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, + load = function() + return __include("music/hvl") + end, + }, + { + name = "it", + category = "music", + path = "music/it", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, + load = function() + return __include("music/it") + end, + }, + { + name = "med", + category = "music", + path = "music/med", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/med") + end, + }, + { + name = "midi", + category = "music", + path = "music/midi", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, + load = function() + return __include("music/midi") + end, + }, + { + name = "mod", + category = "music", + path = "music/mod", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mod") + end, + }, + { + name = "mtm", + category = "music", + path = "music/mtm", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/mtm") + end, + }, + { + name = "mus", + category = "music", + path = "music/mus", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, + load = function() + return __include("music/mus") + end, + }, + { + name = "okt", + category = "music", + path = "music/okt", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, + load = function() + return __include("music/okt") + end, + }, + { + name = "ptm", + category = "music", + path = "music/ptm", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ptm") + end, + }, + { + name = "s3m", + category = "music", + path = "music/s3m", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/s3m") + end, + }, + { + name = "sf2", + category = "music", + path = "music/sf2", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, + load = function() + return __include("music/sf2") + end, + }, + { + name = "stm", + category = "music", + path = "music/stm", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, + load = function() + return __include("music/stm") + end, + }, + { + name = "ult", + category = "music", + path = "music/ult", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, + load = function() + return __include("music/ult") + end, + }, + { + name = "umx", + category = "music", + path = "music/umx", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, + load = function() + return __include("music/umx") + end, + }, + { + name = "xm", + category = "music", + path = "music/xm", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, + load = function() + return __include("music/xm") + end, + }, + { + name = "xmi", + category = "music", + path = "music/xmi", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, + load = function() + return __include("music/xmi") + end, + }, + { + name = "m3u", + category = "playlist", + 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/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, + load = function() + return __include("playlist/m3u") + end, + }, + { + name = "pls", + category = "playlist", + path = "playlist/pls", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/pls") + end, + }, + { + name = "xspf", + category = "playlist", + path = "playlist/xspf", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, + load = function() + return __include("playlist/xspf") + end, + }, +} + +return list +end +__FILES["Types"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors. +-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a +-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name. +-- +-- local T = require("rosetta.Types") +-- local img = T.Image.new(64, 32) -- rgba8, zero-filled +-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32 +-- +-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels. +local Err = __include("core/Err") + +local Types = {} +-- ------------------------------------------------------------------------------------------------ Image +-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the +-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each). + + + + +local BPP= { + rgba8 = 4, + rgba16 = 8, + rgbaf32 = 16, + rgb8 = 3, + gray8 = 1, + gray16 = 2, + graya8 = 2, + alpha8 = 1, +} +Types.BPP = (table.freeze(BPP) )-- one frame of an animation (GIF, APNG, WebP): the image is the frame's own rectangle, composited at x, y + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local Image = {} +-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8) +function Image.new(width, height, format) +local f= format or "rgba8" + local size + if f == "yuv420p" then + local cw, ch = math.floor((width + 1) / 2), math.floor((height + 1) / 2 +) size = width * height + 2 * cw * ch + else + size = width * height * (BPP[f] or 4) + end + return { + kind = "image", + width = width, + height = height, + format = f, + pixels = buffer.create(size), + frames = nil, + loops = 0, + meta = {}, + } +end +-- bpp(format) -> bytes per pixel (nil for planar formats) +function Image.bpp(format) +return BPP[format] +end +Types.Image = Image +-- ------------------------------------------------------------------------------------------------ Audio + + + + + + + + + + + + + + + + + +-- a fully decoded sound (F.load / F.audio.load)-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share) + + + + + + + + + + +local Audio = {} +function Audio.new(sampleRate, channels, frames) +return { + kind = "audio", + sampleRate = sampleRate, + channels = channels, + frames = frames, + samples = buffer.create(frames * channels * 4), + tags = {}, + meta = {}, + } +end +Types.Audio = Audio +-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI) + + + + + + + + + + + + + + + + + + + + + + + +local Midi = {} +function Midi.new(division) +return { kind = "midi", format = 1, division = division or 480, tracks = {}, meta = {} } +end +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/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 +-- / duration and every `duration` / `seek` argument are seconds. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +-- a voxel grid (MagicaVoxel): one byte per cell, 0 = empty, 1..255 = palette index-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped) +-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no +-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255, +-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the +-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load. +-- +-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference +-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the +-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture +-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write +-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil, +-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you. +-- +-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look +-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it +-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the +-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`.-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out + + + + + + +local Voxels = {} +-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) +function Voxels.new(sx, sy, sz, palette) +local pal = palette + if not pal then + local p = table.create(255) + for i = 1, 255 do + p[i] = { i, i, i, 255 } + end + pal = p + end + return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal , materials = nil } +end +-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check +function Voxels.get(v, x, y, z) +return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z)) +end +function Voxels.set(v, x, y, z, index) + buffer.writeu8(v.data, x + v.size[1] * (y + v.size[2] * z), index) +end +Types.Voxels = Voxels + + + + + + + + + + + + + + + + +local Scene = {} +function Scene.new() +return { + kind = "scene", + nodes = {}, + roots = {}, + meshes = {}, + materials = {}, + textures = {}, + cameras = {}, + lights = {}, + skins = {}, + animations = {}, + voxels = nil, + meta = {}, + } +end +-- the byte size of one component of an accessor type +local COMPONENT_SIZE= { + f32 = 4, + f64 = 8, + u8 = 1, + u16 = 2, + u32 = 4, + i8 = 1, + i16 = 2, + i32 = 4, + unorm8 = 1, + unorm16 = 2, + snorm8 = 1, + snorm16 = 2, +} +Types.COMPONENT_SIZE = (table.freeze(COMPONENT_SIZE) )-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer) + +function Scene.accessor(data, type, components, count) +local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4)) + return { data = d, type = type, components = components, count = count } +end +function Scene.material(name) +return { + name = name, + baseColor = { 1, 1, 1, 1 }, + metallic = 1, + roughness = 1, + emissive = { 0, 0, 0 }, + alphaMode = "opaque", + alphaCutoff = 0.5, + doubleSided = false, + } +end +-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF) +function Scene.fromPrimitive(prim, name) +local s = Scene.new() + s.meshes[1] = { name = name, primitives = { prim } } + s.nodes[1] = { name = name, children = {}, mesh = 1 } + s.roots[1] = 1 + return s +end +Types.Scene = Scene + +-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted +-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type. +function Scene.reader(acc) +local d, n, t = acc.data, acc.components, acc.type + local size = COMPONENT_SIZE[t] + if not size or type(d) ~= "buffer" then + return nil + end + local stride = n * size + local rb = buffer + if t == "f32" then + local f = rb.readf32 + return function(i, c) +return f(d, i * stride + c * 4) + end + elseif t == "f64" then + local f = rb.readf64 + return function(i, c) +return f(d, i * stride + c * 8) + end + elseif t == "u8" or t == "unorm8" then + local f, k = rb.readu8, t == "unorm8" and 1 / 255 or 1 + return function(i, c) +return f(d, i * stride + c) * k + end + elseif t == "u16" or t == "unorm16" then + local f, k = rb.readu16, t == "unorm16" and 1 / 65535 or 1 + return function(i, c) +return f(d, i * stride + c * 2) * k + end + elseif t == "u32" then + local f = rb.readu32 + return function(i, c) +return f(d, i * stride + c * 4) + end + elseif t == "i8" then + local f = rb.readi8 + return function(i, c) +return f(d, i * stride + c) + end + elseif t == "snorm8" then + local f = rb.readi8 + return function(i, c) +return math.max(f(d, i * stride + c) / 127, -1) + end + elseif t == "i16" then + local f = rb.readi16 + return function(i, c) +return f(d, i * stride + c * 2) + end + elseif t == "snorm16" then + local f = rb.readi16 + return function(i, c) +return math.max(f(d, i * stride + c * 2) / 32767, -1) + end + elseif t == "i32" then + local f = rb.readi32 + return function(i, c) +return f(d, i * stride + c * 4) + end + end + return nil +end + +-- the identity and products of column-major 4x4 matrices (flat arrays of 16) +local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }) +Scene.IDENTITY = IDENTITY +function Scene.mul(a, b) +local m = table.create(16, 0) + for col = 0, 3 do + for row = 0, 3 do + local s = 0 + for k = 0, 3 do + s =s+ a[k * 4 + row + 1] * b[col * 4 + k + 1] + end + m[col * 4 + row + 1] = s + end + end + return m +end +-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S) +function Scene.nodeMatrix(node) +if node.matrix and #node.matrix == 16 then + return node.matrix + end + local t, r, sc = node.translation, node.rotation, node.scale + if not t and not r and not sc then + return IDENTITY + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + end + local x, y, z, w = 0, 0, 0, 1 + if r then + x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1 + end + local sx, sy, sz = 1, 1, 1 + if sc then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + end + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + (1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0, + (2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0, + (2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0, + tx, ty, tz, 1, + } +end +-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots +-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent. + +function Scene.flatten(scene) +local out= {} + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in __iter(nodes) do + for _, c in __iter(n.children or {}) do + child[c] = true + end + end + roots = {} + for i in __iter(nodes) do + if not child[i] then + table.insert(roots, i) + end + end + end + local seen= {} + local function visit(i, parent) + local node = nodes[i] + if not node or seen[i] then + return + end + seen[i] = true + local m = Scene.nodeMatrix(node) + local world = (parent == IDENTITY and{m }or{(m == IDENTITY and{parent }or{(Scene.mul(parent, m) +)})[1]})[1] local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + for _, p in __iter(mesh.primitives) do + table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh }) + end + end + for _, c in __iter(node.children or {}) do + visit(c, world) + end + end + for _, r in __iter(roots) do + visit(r, IDENTITY) + end + return out +end +-- ------------------------------------------------------------------------------------------------ Cad +-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Rosetta.plugins.brep) +-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; +-- section = the DATA section index when a file has more than one (edition 3) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +-- ------------------------------------------------------------------------------------------------ Data +-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a +-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers. +-- ------------------------------------------------------------------------------------------------ Archive-- one bitmap glyph: a 1-bit (or grey) image in pixels with y down, placed relative to the pen on the baseline-- ------------------------------------------------------------------------------------------------ Font + + + + + + + + + + + +local nullMeta = { __tostring = function() + return "null" +end } +Types.null = table.freeze(setmetatable({}, nullMeta)) + +-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry +-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked +-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted). +-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" }) +-- Types.set(o, "c", 3) -- assigns and appends "c" to the order +-- for _, k in Types.keys(o) do ... end +local OBJECT = { __object = true } +local objectMeta= (setmetatable({}, { __mode = "k" }) )-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends) + +function Types.object(t, keys) +local o= t or {} + if getmetatable(o) == nil then + setmetatable(o, OBJECT) + end + objectMeta[o] = keys or {} + return o +end +-- isObject(v) -> true for tables made by Types.object +function Types.isObject(v) +return type(v) == "table" and objectMeta[v] ~= nil +end +-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns) +function Types.set(o, k, v) + local order = objectMeta[o] + if order and o[k] == nil and v ~= nil then + table.insert(order, k) + 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, b) +local ta, tb = type(a), type(b) + if ta ~= tb then + return ta < tb + end + if ta == "number" or ta == "string" then + return a < b + 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, emptyIsMap) +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 =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) +local order = objectMeta[t] + local out, seen = {}, {} + if order then + for _, k in __iter(order) do + if t[k] ~= nil and not seen[k] then + seen[k] = true + table.insert(out, k) + end + end + end + local rest = {} + for k in next, t do + if not seen[k] then + table.insert(rest, k) + end + end + if #rest > 0 then + table.sort(rest, keyLess) + table.move(rest, 1, #rest, #out + 1, out) + end + return out +end +-- Dates and times (TOML datetimes, plist <date>, CBOR tags 0 / 1, msgpack timestamps). Fields present depend on the +-- kind: "datetime" (with offset: an instant), "datetime-local", "date-local", "time-local". offset is in minutes +-- east of UTC (nil = local time). tostring gives RFC 3339 ("1979-05-27T07:32:00.5-07:00", "07:32:00", ...). + + + + + + + + + + + + +local DateMeta = {} +local function p2(n) +return string.format("%02d", n) +end +local function fmtDate(d) +local s= "" + 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 = s .. "T" + end + s =s.. p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0) + local ns = d.nanosecond or 0 + if ns > 0 then + local f = string.format("%09d", ns) + s =s.. "." .. (string.gsub(f, "0+$", "")) + end + if d.offset then + if d.offset == 0 then + s =s.. "Z" + else + local o = math.abs(d.offset) + s =s.. (d.offset < 0 and"-" or"+") .. p2(math.floor(o / 60)) .. ":" .. p2(o % 60) + end + end + end + return s +end +DateMeta.__tostring = fmtDate +DateMeta.__eq = function(a, b) +return fmtDate(a) == fmtDate(b) and a.kind == b.kind +end +local DateLib = {} +-- days since 1970-01-01 of a civil date (proleptic Gregorian; Howard Hinnant's algorithm) +local function daysFromCivil(y, m, d) +y = (m <= 2 and((y - 1 ))or(y +)) local era = math.floor(((y >= 0 and{y }or{(y - 399)})[1]) / 400 +) local yoe = y - era * 400 + local mp = (m + 9) % 12 + local doy = math.floor((153 * mp + 2) / 5 )+ d - 1 + local doe = yoe * 365 + math.floor(yoe / 4 )- math.floor(yoe / 100 )+ doy + return era * 146097 + doe - 719468 +end +local function civilFromDays(z) +z =z+ 719468 + local era = math.floor(((z >= 0 and{z }or{(z - 146096)})[1]) / 146097 +) local doe = z - era * 146097 + local yoe = math.floor((doe - math.floor(doe / 1460 )+ math.floor(doe / 36524 )- math.floor(doe / 146096)) / 365 +) local y = yoe + era * 400 + local doy = doe - (365 * yoe + math.floor(yoe / 4 )- math.floor(yoe / 100)) + local mp = math.floor((5 * doy + 2) / 153 +) local d = doy - math.floor((153 * mp + 2) / 5 )+ 1 + local m = (mp < 10 and((mp + 3 ))or((mp - 9 +))) return ((m <= 2 and((y + 1 ))or(y))), m, d +end +DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian) +DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01 +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) +local d= {} + for k, v in __iter(f) do + d[k] = v + end + if d.kind == nil then + d.kind = (d.year and d.hour and{(d.offset and"datetime" or"datetime-local") +}or{d.year and"date-local" +or"time-local" +})[1] end + return (setmetatable(d, DateMeta) ) +end +-- is(v) -> true for Dates +function DateLib.is(v) +return type(v) == "table" and getmetatable(v) == DateMeta +end +-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...) +function DateLib.valid(d) +if d.year then + local y, m, dd = d.year, d.month or 0, d.day or 0 + if y < 0 or y > 9999 or m < 1 or m > 12 or dd < 1 or dd > MDAYS[m] then + return false + end + if m == 2 and dd == 29 and not (y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)) then + return false + end + end + if d.hour then + if d.hour > 23 or (d.minute or 0) > 59 or (d.second or 0) > 60 then + return false + end + end + if d.offset and math.abs(d.offset) >= 24 * 60 then + return false + end + return true +end +-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27", +-- "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) +local d= {} + local rest= 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 +if rest == "" then + return (DateLib.valid(d) and{(DateLib.new(d) )}or{nil +})[1] end + local sep = string.sub(rest, 1, 1) + if sep ~= "T" and sep ~= "t" and sep ~= " " then + return nil + end + rest = string.sub(rest, 2) + end + local h, mi, r2 = string.match(rest, "^(%d%d):(%d%d)(.*)$") + if not h then + return nil + end + d.hour, d.minute = tonumber(h), tonumber(mi) + rest = r2 +local sec, r3 = string.match(rest, "^:(%d%d)(.*)$") + if not sec then + return nil + end + d.second = tonumber(sec) + rest = r3 +local frac, r4 = string.match(rest, "^%.(%d+)(.*)$") + if frac then + d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9)) + rest = r4 +else + d.nanosecond = 0 + end + if rest ~= "" then + if not d.year then + return nil + end + if rest == "Z" or rest == "z" then + d.offset = 0 + else + local sign, oh, om = string.match(rest, "^([%+%-])(%d%d):(%d%d)$") + if not sign then + return nil + end + local oh_n, om_n = (tonumber(oh) ), (tonumber(om) ) +if oh_n > 23 or om_n > 59 then + return nil + end + d.offset = (oh_n * 60 + om_n) * (sign == "-" and-1 or 1) + end + end + return (DateLib.valid(d) and{(DateLib.new(d) )}or{nil +})[1]end +-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC) +function DateLib.toUnix(d) +local days = (d.year and{(daysFromCivil(d.year, d.month or 1, d.day or 1) )}or{0 +})[1] local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60 + return s + (d.nanosecond or 0) / 1e9 +end +-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC) +function DateLib.fromUnix(t, offset) +local off = offset or 0 + local whole = math.floor(t) + local ns = math.floor((t - whole) * 1e9 + 0.5) + if ns >= 1e9 then + whole =whole+ 1 + ns =ns- 1e9 + end + local lt = whole + off * 60 + local days = math.floor(lt / 86400 +) local secs = lt - days * 86400 + local y, m, dd = civilFromDays(days) + return DateLib.new({ + kind = "datetime", + year = y, + month = m, + day = dd, + hour = math.floor(secs / 3600), + minute = (math.floor(secs / 60)) % 60, + second = secs % 60, + nanosecond = ns, + offset = off, + }) +end +Types.Date = table.freeze(DateLib) +-- XML: an element, or (name starting with "#") a "#document" / "#comment" / "#cdata" / "#pi" / "#doctype" node with +-- its content in text. attrs is a Types.object (attribute order kept). Text children are plain strings. + + + + + + + + + + + +-- ------------------------------------------------------------------------------------------------ Vector + + + + + + + + + + + + + + + + + + + + + + + + + + + +local Vector = {} +function Vector.new(width, height) +return { kind = "vector", width = width, height = height, viewBox = { 0, 0, width, height }, paths = {}, meta = {} } +end +Types.Vector = Vector +-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite) +-- 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`). + + + + + + + + + + + +local Layered = {} +function Layered.new(width, height) +return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} } +end +-- layer(name, image, x?, y?) -> a visible normal layer at full opacity +function Layered.layer(name, image, x, y) +return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true } +end +-- group(name, children) -> a pass-through group layer +function Layered.group(name, children) +return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children } +end +Types.Layered = Layered +-- ------------------------------------------------------------------------------------------------ TileMap (Tiled) +-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept). +-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller +-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite +-- maps, objects' shapes, per-tile data, ...: see vector/tiled). + + + + + + + + + + + + + + + + +local TileMap = {} +function TileMap.new(width, height, tileWidth, tileHeight) +return { kind = "tilemap", width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = "orthogonal", tilesets = {}, layers = {}, properties = {}, meta = {} } +end +Types.TileMap = TileMap +-- ------------------------------------------------------------------------------------------------ Subtitles + + + +local Subtitles = {} +function Subtitles.new() +return { kind = "subtitles", cues = {}, styles = {}, meta = {} } +end +Types.Subtitles = Subtitles +-- ------------------------------------------------------------------------------------------------ Playlist +-- the playlist-luau shape + + + + + + + + + + + + + + + + + + + + + + +-- the categories, in the order F.formats() lists them; kind = the `kind` of the values they decode to +-- ------------------------------------------------------------------------------------------------ the format contract +-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md) + + + + + + + + + + + + + + +Types.CATEGORIES = table.freeze({ + image = "image", + audio = "audio", + video = "video", + model = "scene", + cad = "cad", + font = "font", + archive = "archive", + data = "data", + vector = "vector", + layered = "layered", + subtitle = "subtitles", + music = "music", + playlist = "playlist", +} ) + +return Types +end +__FILES["archive/7z"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose +-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) +-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 / +-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM, +-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, +-- Windows / Unix attributes, folder and file CRC-32s (verified on read). +-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other +-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") +local Header = __include("archive/7z/Header") + +-- ------------------------------------------------------------------------------------------------ contract +local SevenZip = { + name = "7z", + category = "archive", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local MAGIC = "7z\188\175\39\28" + +-- method id -> xz filter id (BCJ / delta) +local FILTERS= { + ["\3\3\1\3"] = 0x04, -- x86 + ["\3\3\2\5"] = 0x05, -- PowerPC + ["\3\3\5\1"] = 0x07, -- ARM + ["\3\3\7\1"] = 0x08, -- ARM-Thumb + ["\3\3\8\5"] = 0x09, -- SPARC + ["\10"] = 0x0A, -- ARM64 + ["\3"] = 0x03, -- delta +} +local NAMES= { + ["\0"] = "copy", + ["\3\1\1"] = "lzma", + ["\33"] = "lzma2", + ["\4\1\8"] = "deflate", + ["\4\1\9"] = "deflate64", + ["\4\2\2"] = "bzip2", + ["\3\4\1"] = "ppmd", + ["\3\3\1\27"] = "bcj2", + ["\6\241\7\1"] = "aes", + ["\4\247\17\1"] = "zstd", + ["\4\247\17\2"] = "brotli", + ["\3\3\1\3"] = "bcj", + ["\3\3\2\5"] = "ppc", + ["\3\3\5\1"] = "arm", + ["\3\3\7\1"] = "armt", + ["\3\3\8\5"] = "sparc", + ["\10"] = "arm64", + ["\3"] = "delta", +} + +local function methodName(id) +local n = NAMES[id] + if n then + return n + end + local hex = {} + for i = 1, #id do + table.insert(hex, string.format("%02x", string.byte(id, i))) + end + return "method " .. table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function SevenZip.sniff(r) +return r:peek(6) == MAGIC and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream + + + +local function packStart(ctx, s, index) +local p = ctx.base + 32 + s.packPos + for i = 1, index do + p =p+ s.packSizes[i] + end + return p +end + +local function decodeFolder(ctx, s, f) -- coder -> first in / out stream index + +local inBase, outBase = {}, {} + local ni, no = 0, 0 + for i, c in __iter(f.coders) do + inBase[i], outBase[i] = ni, no + ni =ni+ c.numIn + no =no+ c.numOut + end + local depth = 0 + local function out(outIdx) +depth =depth+ 1 + if depth > 32 then + return nil, Err.new(Err.CORRUPT, "coder graph too deep") + end + local ci + for i, c in __iter(f.coders) do + if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then + ci = i + end + end + if not ci then + return nil, Err.new(Err.CORRUPT, "bad bind pair") + end + local c = f.coders[ci] + if c.numIn ~= 1 or c.numOut ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") + end + local size = f.unpackSizes[outIdx + 1] or 0 + if size > ctx.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) + end + -- the coder's input: another coder's output, or a packed stream + local inIdx = inBase[ci] + local src, so, sl +local bound = nil + for _, bp in __iter(f.bindPairs) do + if bp.inIndex == inIdx then + bound = bp.outIndex + end + end + if bound then + local b, e = out(bound) + if not b then + return nil, e + end + src = b + so = 0 + sl = buffer.len(b) + else + local k = table.find(f.packed, inIdx) + if not k then + return nil, Err.new(Err.CORRUPT, "unbound coder input") + end + local pi = f.firstPack + k - 1 + if pi >= #s.packSizes then + return nil, Err.new(Err.CORRUPT, "missing pack stream") + end + so = packStart(ctx, s, pi) + sl = s.packSizes[pi + 1] + if so + sl > ctx.limit or so < ctx.base then + return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) + end + src = ctx.buf + end + local id = c.id + local opts= { 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, nil + elseif id == "\3\1\1" then + if buffer.len(c.props) < 5 then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties") + end + local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) + return b, (b and{nil }or{e +})[1] elseif id == "\33" then + local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) + return b, (b and{nil }or{e +})[1] elseif id == "\4\1\8" then + local b, e = Deflate.inflate(src, so, sl, size) + return b, (b and{nil }or{e +})[1] elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames) + local b, e + if id == "\4\2\2" then + b, e = Bzip2.decompress(src, so, sl, opts) + else + b, e = Zstd.decompress(src, so, sl, opts) + end + if not b then + return nil, e + end + if buffer.len(b) ~= size then + return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size") + end + return b, nil + elseif FILTERS[id] then + if sl ~= size then + return nil, Err.new(Err.CORRUPT, "filter size mismatch") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) + if not ok then + return nil, e + end + return b, nil + end + return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") + end + local main = Header.mainOut(f) + if not main then + return nil, Err.new(Err.CORRUPT, "folder without a main output") + end + return out(main) +end + +local function folderMethod(f) +local names = {} + for _, c in __iter(f.coders) do + table.insert(names, methodName(c.id)) + end + return table.concat(names, "+") +end + +function SevenZip.decode(r, opts) +local o= opts or {} + local maxBytes = (type(o.maxBytes) == "number" and{o.maxBytes }or{(2 ^ 30 +)})[1] local checkCrc = o.checkCrc ~= false + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) + end + if buffer.readstring(b, base, 6) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) + end + if buffer.readu8(b, base + 6) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) + end + if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then + return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) + end + local hr = Bytes.reader(b, base + 12, 20) + local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() + local ctx= { buf = b, base = base, limit = limit, maxBytes = maxBytes } + local a = Archive.new("7z") + if nextSize == 0 then + return a, nil -- an empty archive + end + local ho = base + 32 + nextOff + if nextOff < 0 or ho + nextSize > limit then + return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) + end + if Crc32.raw(b, ho, nextSize) ~= nextCrc then + return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) + end + local hbuf, hoff, hlen = b, ho, nextSize + local parsed + for _ = 1, 4 do + local p, perr = Header.parse(hbuf, hoff, hlen) + if not p then + return nil, perr + end + if not p.encoded then + parsed = p + break + end + -- an encoded header: decode folder 1 of its streams, then parse again + local es = p.encoded + local f = es.folders[1] + if not f then + return nil, Err.new(Err.CORRUPT, "encoded header without a folder") + end + local hb, herr = decodeFolder(ctx, es, f) + if not hb then + return nil, herr + end + 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 = 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 = {} } + a.meta.folders = #s.folders + a.meta.solid = false + -- folder caches and the substream -> folder map + local cache= {} + local subFolder, subOffset= {}, {} + do + local si = 1 + for fi, f in __iter(s.folders) do + if f.numSub > 1 then + a.meta.solid = true + end + local off = 0 + for _ = 1, f.numSub do + subFolder[si], subOffset[si] = fi, off + off =off+ (s.subSizes[si] or 0 +) si =si+ 1 + end + if off > Header.unpackSize(f) then + return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") + end + end + end + local function folderData(fi) +local c = cache[fi] + if c then + return c, nil + end + local f = s.folders[fi] + local d, e = decodeFolder(ctx, s, f) + if not d then + return nil, e + end + if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") + end + cache[fi] = d + return d, nil + end + local si = 0 + for _, file in __iter(parsed.files) do +local __DARKLUA_CONTINUE_10=false repeat if file.anti then +__DARKLUA_CONTINUE_10=true break + end + local attr = file.attributes + local isDir = file.emptyStream and not file.emptyFile + if attr and bit32.band(attr, 0x10) ~= 0 then + isDir = true + end + local mode = (attr and bit32.band(attr, 0x8000) ~= 0 and{(bit32.rshift(attr, 16) )}or{nil +})[1] local e= { + name = file.name, + size = 0, + dir = isDir, + mtime = file.mtime, + attributes = attr, + mode = mode, + } + if not file.emptyStream then + si =si+ 1 + local idx = si + local fi = subFolder[idx] + if not fi then + return nil, Err.new(Err.CORRUPT, "more files than streams") + end + local size = s.subSizes[idx] + e.size = size + e.method = folderMethod(s.folders[fi]) + if s.folders[fi].numSub == 1 then + local pk = 0 + for k = 1, #s.folders[fi].packed do + pk =pk+ (s.packSizes[s.folders[fi].firstPack + k] or 0 +) end + e.compressedSize = pk + end + e.crc = s.subCrcs[idx] + e.load = function() +local d, derr = folderData(fi) + if not d then + return nil, derr + end + local off = subOffset[idx] + if off + size > buffer.len(d) then + return nil, Err.new(Err.CORRUPT, "substream past its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, d, off, size) + local want = s.subCrcs[idx] + 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, nil + end + end + Archive.put(a, e) +__DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end + return a, nil +end + +return SevenZip +end +__FILES["archive/7z/Header"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): +-- 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 = __include("codecs/text/Text") +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Header = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local K = { + End = 0x00, + Header = 0x01, + ArchiveProperties = 0x02, + AdditionalStreamsInfo = 0x03, + MainStreamsInfo = 0x04, + FilesInfo = 0x05, + PackInfo = 0x06, + UnPackInfo = 0x07, + SubStreamsInfo = 0x08, + Size = 0x09, + CRC = 0x0A, + Folder = 0x0B, + CodersUnPackSize = 0x0C, + NumUnPackStream = 0x0D, + EmptyStream = 0x0E, + EmptyFile = 0x0F, + Anti = 0x10, + Name = 0x11, + MTime = 0x14, + WinAttributes = 0x15, + EncodedHeader = 0x17, + Dummy = 0x19, +} +Header.K = K + +local Fail = {} + +local function bad(r, msg, code) +error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) +end + +local function check(r) + if r.err then + error(setmetatable({ err = r.err }, Fail), 0) + end +end + +local function byte(r) +local v = r:u8() + check(r) + return v +end + +-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes +local function number(r) +local first = byte(r) + local mask = 0x80 + local value = 0 + for i = 0, 7 do + if bit32.band(first, mask) == 0 then + local high = bit32.band(first, mask - 1) + return value + high * 2 ^ (8 * i) + end + value =value+ byte(r) * 2 ^ (8 * i) + mask = bit32.rshift(mask, 1) + end + return value +end + +-- a count bounded by the bytes left (every counted item takes at least `min` bytes) +local function count(r, min) +local n = number(r) + if n * (min or 1) > r:remaining() + 1 then + bad(r, "count " .. n .. " is larger than the header") + end + return n +end + +local function bits(r, n) +local out = table.create(n, false) + local cur, mask = 0, 0 + for i = 1, n do + if mask == 0 then + cur = byte(r) + mask = 0x80 + end + out[i] = bit32.band(cur, mask) ~= 0 + mask = bit32.rshift(mask, 1) + end + return out +end + +-- bits preceded by an "all defined" byte +local function defined(r, n) +if byte(r) ~= 0 then + return table.create(n, true) + end + return bits(r, n) +end + +local function digests(r, n) +local def = defined(r, n) + local out = {} + for i = 1, n do + if def[i] then + out[i] = r:u32le() + end + end + check(r) + return out +end + +local function packInfo(r, s) + s.packPos = number(r) + local n = count(r) + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.Size then + for i = 1, n do + s.packSizes[i] = number(r) + end + elseif t == K.CRC then + digests(r, n) + else + bad(r, "unexpected property " .. t .. " in pack info") + end + end + if #s.packSizes ~= n then + bad(r, "missing pack sizes") + end +end + +local function folder(r) +local ncoders = count(r) + if ncoders == 0 or ncoders > 64 then + bad(r, "bad coder count " .. ncoders) + end + local f= { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } + local totalIn, totalOut = 0, 0 + for _ = 1, ncoders do + local flags = byte(r) + if bit32.band(flags, 0x80) ~= 0 then + bad(r, "alternative coder methods", Err.UNSUPPORTED) + end + local idSize = bit32.band(flags, 0x0F) + local id = r:string(idSize) + check(r) + local nin, nout = 1, 1 + if bit32.band(flags, 0x10) ~= 0 then + nin = number(r) + nout = number(r) + if nin > 64 or nout > 64 then + bad(r, "bad coder stream count") + end + end + local props = buffer.create(0) + if bit32.band(flags, 0x20) ~= 0 then + local n = count(r) + props = r:bytes(n) + check(r) + end + table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) + totalIn =totalIn+ nin + totalOut =totalOut+ nout + end + if totalOut == 0 then + bad(r, "a folder without output") + end + for _ = 1, totalOut - 1 do + local i, o = number(r), number(r) + table.insert(f.bindPairs, { inIndex = i, outIndex = o }) + end + local npacked = totalIn - (totalOut - 1) + if npacked < 1 then + bad(r, "bad bind pairs") + end + if npacked == 1 then + for i = 0, totalIn - 1 do + local bound = false + for _, bp in __iter(f.bindPairs) do + if bp.inIndex == i then + bound = true + end + end + if not bound then + table.insert(f.packed, i) + break + end + end + if #f.packed ~= 1 then + bad(r, "no packed stream") + end + else + for _ = 1, npacked do + table.insert(f.packed, number(r)) + end + end + return f +end + +-- the folder's main out stream: the one no bind pair consumes +function Header.mainOut(f) +local total = 0 + for _, c in __iter(f.coders) do + total =total+ c.numOut + end + for o = 0, total - 1 do + local bound = false + for _, bp in __iter(f.bindPairs) do + if bp.outIndex == o then + bound = true + end + end + if not bound then + return o + end + end + return nil +end + +function Header.unpackSize(f) +local m = Header.mainOut(f) + return (m and{f.unpackSizes[m + 1] or 0 }or{0 +})[1]end + +local function unpackInfo(r, s) + if byte(r) ~= K.Folder then + bad(r, "expected the folder list") + end + local n = count(r) + if byte(r) ~= 0 then + bad(r, "external folders", Err.UNSUPPORTED) + end + for i = 1, n do + s.folders[i] = folder(r) + end + if byte(r) ~= K.CodersUnPackSize then + bad(r, "expected the coder unpack sizes") + end + for _, f in __iter(s.folders) do + local total = 0 + for _, c in __iter(f.coders) do + total =total+ c.numOut + end + for k = 1, total do + f.unpackSizes[k] = number(r) + end + end + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.CRC then + local d = digests(r, n) + for i = 1, n do + s.folders[i].crc = d[i] + end + else + bad(r, "unexpected property " .. t .. " in unpack info") + end + end +end + +local function subStreamsInfo(r, s) + local t = byte(r) + if t == K.NumUnPackStream then + for _, f in __iter(s.folders) do + f.numSub = count(r, 0) + end + t = byte(r) + end + local sizes = s.subSizes + if t == K.Size then + for _, f in __iter(s.folders) do + if f.numSub > 0 then + local sum = 0 + for _ = 1, f.numSub - 1 do + local v = number(r) + sum =sum+ v + table.insert(sizes, v) + end + local total = Header.unpackSize(f) + if sum > total then + bad(r, "substream sizes exceed the folder") + end + table.insert(sizes, total - sum) + end + end + t = byte(r) + else + for _, f in __iter(s.folders) do + if f.numSub > 1 then + bad(r, "missing substream sizes") + elseif f.numSub == 1 then + table.insert(sizes, Header.unpackSize(f)) + end + end + end + -- CRCs for the streams whose folder CRC does not already cover them + local unknown = 0 + for _, f in __iter(s.folders) do + if not (f.numSub == 1 and f.crc) then + unknown =unknown+ f.numSub + end + end + while t ~= K.End do + if t == K.CRC then + local d = digests(r, unknown) + local k, si = 1, 1 + for _, f in __iter(s.folders) do + if f.numSub == 1 and f.crc then + s.subCrcs[si] = f.crc + si =si+ 1 + else + for _ = 1, f.numSub do + s.subCrcs[si] = d[k] + k =k+ 1 + si =si+ 1 + end + end + end + else + bad(r, "unexpected property " .. t .. " in substreams info") + end + t = byte(r) + end +end + +local function streamsInfo(r) +local s= { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local sawSub = false + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.PackInfo then + packInfo(r, s) + elseif t == K.UnPackInfo then + unpackInfo(r, s) + elseif t == K.SubStreamsInfo then + subStreamsInfo(r, s) + sawSub = true + else + bad(r, "unexpected property " .. t .. " in streams info") + end + end + if not sawSub then + for i, f in __iter(s.folders) do + f.numSub = 1 + table.insert(s.subSizes, Header.unpackSize(f)) + if f.crc then + s.subCrcs[i] = f.crc + end + end + end + local p = 0 + for _, f in __iter(s.folders) do + f.firstPack = p + p =p+ #f.packed + end + if p > #s.packSizes then + bad(r, "folders use more pack streams than exist") + end + return s +end + +local function utf16(b, o, n) +return Text.utf16(b, o, n, false) +end + +local function filesInfo(r) +local n = count(r, 0) + if n > 1000000 then + bad(r, "too many files", Err.LIMIT) + end + local files= (table.create(n) ) +for i = 1, n do + files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } + end + local empties= {} + while true do + local t = byte(r) + if t == K.End then + break + end + local size = number(r) + if size > r:remaining() then + bad(r, "file property past the header") + end + local pr = r:slice(size) + check(r) + if t == K.EmptyStream then + local v = bits(pr, n) + empties = {} + for i = 1, n do + files[i].emptyStream = v[i] + if v[i] then + table.insert(empties, i) + end + end + elseif t == K.EmptyFile or t == K.Anti then + local v = bits(pr, #empties) + for k, i in __iter(empties) do + if t == K.EmptyFile then + files[i].emptyFile = v[k] + else + files[i].anti = v[k] + end + end + elseif t == K.Name then + if byte(pr) ~= 0 then + bad(pr, "external names", Err.UNSUPPORTED) + end + local b = pr.buf + local p = pr.pos + for i = 1, n do + local q = p + while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do + q =q+ 2 + end + if q + 1 >= pr.limit then + bad(pr, "unterminated name") + end + files[i].name = utf16(b, p, q - p) + p = q + 2 + end + elseif t == K.MTime or t == K.WinAttributes then + local def = defined(pr, n) + if byte(pr) ~= 0 then + bad(pr, "external file properties", Err.UNSUPPORTED) + end + for i = 1, n do + if def[i] then + if t == K.MTime then + local ft = pr:u64le() + files[i].mtime = math.floor(ft / 1e7 - 11644473600) + else + files[i].attributes = pr:u32le() + end + end + end + check(pr) + end + -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped + end + return files +end + +local function header(r) +local p= { streams = nil, files = {}, encoded = nil } + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.ArchiveProperties then + while true do + local pt = byte(r) + if pt == 0 then + break + end + r:skip(number(r)) + check(r) + end + elseif t == K.AdditionalStreamsInfo then + streamsInfo(r) + elseif t == K.MainStreamsInfo then + p.streams = streamsInfo(r) + elseif t == K.FilesInfo then + p.files = filesInfo(r) + else + bad(r, "unexpected property " .. t .. " in the header") + end + end + return p +end + +-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to +-- decode and parse again. +function Header.parse(b, o, n) +local r = Bytes.reader(b, o, n) + local ok, res = pcall(function() +local t = byte(r) + if t == K.Header then + return header(r) + elseif t == K.EncodedHeader then + return { streams = nil, files = {}, encoded = streamsInfo(r) } + end + return bad(r, "bad header type " .. t) + end) + if ok then + return res, nil + end + if type(res) == "table" and getmetatable(res ) == Fail then + return nil, (res ).err + end + error(res, 0) +end + +return Header +end +__FILES["archive/adf"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an +-- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international, +-- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through +-- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the +-- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked +-- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...), +-- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are +-- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description +-- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk +-- images (use the partition contents), dircache blocks (not needed to read). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Adf = { + name = "adf", + category = "archive", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + +local BS = 512 +local HT = 72 -- hash table slots in a 512-byte block +local T_HEADER, T_DATA, T_LIST = 2, 8, 16 +local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4 +local EPOCH = 252460800 -- 1978-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function Adf.sniff(r) +local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return 0 + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then + return 0 + end + return (n == 901120 or n == 1802240 )and 0.95 or 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function latin1(s) +if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + + + +local function u32(d, blk, off) +local o = d.base + blk * BS + off + return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3) +end + +local function i32(d, blk, off) +local v = u32(d, blk, off) + return (v >= 0x80000000 and((v - 0x100000000 ))or(v +))end + +local function bstr(d, blk, off, max) +local o = d.base + blk * BS + off + local n = math.min(buffer.readu8(d.b, o), max) + return latin1(buffer.readstring(d.b, o + 1, n)) +end + +local function checksumOk(d, blk) +local sum = 0 + for i = 0, BS - 4, 4 do + sum = (sum + u32(d, blk, i)) % 0x100000000 + end + return sum == 0 +end + +local function date(d, blk, off) +return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + math.floor(u32(d, blk, off + 8) / 50)) + EPOCH +end + +-- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables) +local function dataBlocks(d, hdr, maxBlocks) +local out = {} + local blk = hdr + local seen= {} + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or seen[blk] then + return nil, "bad extension block " .. blk + end + seen[blk] = true + if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then + return nil, "bad extension block " .. blk + end + local n = u32(d, blk, 8) + if n > HT then + return nil, "bad block count in " .. blk + end + for k = 0, n - 1 do + local db = u32(d, blk, 24 + (HT - 1 - k) * 4) + if db < 2 or db >= d.blocks then + return nil, "bad data block " .. db + end + table.insert(out, db) + if #out > maxBlocks then + return nil, "more data blocks than the disk has" + end + end + blk = u32(d, blk, BS - 8) + end + return out, nil +end + +local function readFile(d, hdr, ofs) +local size = u32(d, hdr, BS - 188) + if size > d.blocks * BS then + return nil, "file larger than the disk" + end + local list, err = dataBlocks(d, hdr, d.blocks) + if not list then + return nil, err + end + local out = buffer.create(size) + local o = 0 + for _, db in __iter(list) do + if o >= size then + break + end + if ofs then + if u32(d, db, 0) ~= T_DATA then + return nil, "data block " .. db .. " is not an OFS data block" + end + local n = math.min(u32(d, db, 12), 488, size - o) + buffer.copy(out, o, d.b, d.base + db * BS + 24, n) + o =o+ n + else + local n = math.min(BS, size - o) + buffer.copy(out, o, d.b, d.base + db * BS, n) + o =o+ n + end + end + if o < size then + return nil, "file data ends early" + end + return out, nil +end + +function Adf.decode(r, opts) +local o= opts or {} + local n = r:size() + if n < 4 * BS or n % BS ~= 0 then + return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks") + end + local h = r:peek(4) + if string.sub(h, 1, 3) ~= "DOS" then + return nil, Err.new(Err.CORRUPT, "no DOS boot block") + end + local flags = string.byte(h, 4) + if flags > 5 then + return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems") + end + local d= { b = r.buf, base = r.base, blocks = math.floor(n / BS )} + local ofs = bit32.band(flags, 1) == 0 + local root = math.floor((d.blocks - 1 + 2) / 2 +) if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then + return nil, Err.new(Err.CORRUPT, "no root block at " .. root) + end + if not checksumOk(d, root) then + return nil, Err.new(Err.CHECKSUM, "root block checksum") + end + local a = Archive.new("adf") + a.meta.volume = bstr(d, root, BS - 80, 30) + a.meta.fs = ofs and"ofs" or"ffs" + a.meta.intl = flags >= 2 + a.meta.dircache = flags >= 4 + a.meta.dosType = flags + a.meta.modified = date(d, root, BS - 92) + a.meta.created = date(d, root, BS - 28) + a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks } + local maxEntries = o.maxEntries or 65536 + local count = 0 + local pathOf= {} + local links= {} + local visited= { [root] = true } + + local function walk(dir, prefix) +for slot = 0, HT - 1 do + local blk = u32(d, dir, 24 + slot * 4) + while blk ~= 0 do + if blk < 2 or blk >= d.blocks or visited[blk] then + return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk) + end + visited[blk] = true + count =count+ 1 + if count > maxEntries then + return false, Err.new(Err.LIMIT, "more than maxEntries entries") + end + if u32(d, blk, 0) ~= T_HEADER then + return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block") + end + if not checksumOk(d, blk) then + return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum") + end + local name = prefix .. bstr(d, blk, BS - 80, 30) + local st = i32(d, blk, BS - 4) + local e= { + name = name, + size = 0, + dir = false, + mtime = date(d, blk, BS - 92), + protect = u32(d, blk, BS - 192), + comment = bstr(d, blk, BS - 184, 79), + method = "store", + } + if e.comment == "" then + e.comment = nil + end + if st == ST_USERDIR then + e.name = name .. "/" + e.dir = true + pathOf[blk] = e.name + Archive.put(a, e) + local ok, err = walk(blk, e.name) + if not ok then + return false, err + end + elseif st == ST_FILE then + e.size = u32(d, blk, BS - 188) + pathOf[blk] = name + local hb = blk + e.load = function() +local data, err = readFile(d, hb, ofs) + if not data then + return nil, Err.new(Err.CORRUPT, tostring(err)) + end + return data, nil + end + Archive.put(a, e) + elseif st == ST_SOFTLINK then + local lo = d.base + blk * BS + 24 + local s = buffer.readstring(d.b, lo, BS - 24 - 200) + e.link = latin1(string.match(s, "^[^%z]*") or "") + e.type = "symlink" + Archive.put(a, e) + elseif st == ST_LINKFILE or st == ST_LINKDIR then + e.type = "hardlink" + e.dir = st == ST_LINKDIR + if e.dir then + e.name = name .. "/" + end + Archive.put(a, e) + table.insert(links, { entry = e, target = u32(d, blk, BS - 44) }) + end + blk = u32(d, blk, BS - 16) + end + end + return true, nil + end + local ok, err = walk(root, "") + if not ok then + return nil, err + end + -- hard links: the linked path, and a file link reads its target's data + for _, l in __iter(links) do + local target = pathOf[l.target] + l.entry.hardlink = target + if target and not l.entry.dir then + local te = a._byName[target] + if te then + l.entry.size = te.size + l.entry.load = te.load + end + end + end + return a, nil +end + +return Adf +end +__FILES["archive/applesingle"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740): +-- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2: +-- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags). +-- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the +-- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name +-- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds +-- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with +-- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS / +-- MS-DOS / AFP info entries (kept in meta.entries as id + length). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local AppleSingle = { + name = "applesingle", + category = "archive", + extensions = { "as", "applesingle", "appledouble" }, + mime = { "application/applefile", "multipart/appledouble" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local SINGLE, DOUBLE = 0x00051600, 0x00051607 +local Y2K = 946684800 -- 2000-01-01 in unix seconds + +-- ------------------------------------------------------------------------------------------------ sniff +function AppleSingle.sniff(r) +local h = r:peek(8) + if #h < 8 then + return 0 + end + local magic = string.sub(h, 1, 4) + local ver = string.sub(h, 5, 8) + if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a, o) +return AppleSingle.encode(a, o) +end + +local function i32(v) +return (v >= 0x80000000 and((v - 0x100000000 ))or(v +))end + +function AppleSingle.decode(r, opts) +local o= opts or {} + local magic, ver = r:u32be(), r:u32be() + r:skip(16) + local count = r:u16be() + if r.err then + return nil, r.err + end + if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then + return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble") + end + local size = r:size() + local info= { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 } + local others = {} + local total = 0 + for _ = 1, count do + local id, off, len = r:u32be(), r:u32be(), r:u32be() + if r.err then + return nil, r.err + end + if off + len > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end") + end + total =total+ len + if total > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "entries larger than maxBytes") + end + local e = r:sub(off, len) + if id == 1 then + info.data = e:bytes(len) + elseif id == 2 then + info.rsrc = e:bytes(len) + elseif id == 3 then + info.name = MacFile.name(e:string(len)) + elseif id == 4 then + info.comment = MacFile.name(e:string(len)) + elseif id == 8 and len >= 8 then + local c, m = e:u32be(), e:u32be() + info.created = (c == 0x80000000 and{nil }or{(i32(c) + Y2K +)})[1] info.modified = (m == 0x80000000 and{nil }or{(i32(m) + Y2K +)})[1] elseif id == 7 and len >= 12 and ver == 0x10000 then + local c, m = e:u32be(), e:u32be() + info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m) + elseif id == 9 and len >= 10 then + info.type, info.creator = e:string(4), e:string(4) + info.flags = e:u16be() + else + table.insert(others, { id = id, length = len }) + end + end + if info.name == "" then + local n = (type(o.name) == "string" and{(string.match(o.name, "([^/\\]+)$") )}or{nil +})[1] info.name = (n and{(string.match(n, "^%._(.+)$") or n) }or{"data" +})[1] end + local a = Archive.new("applesingle", encoder) + MacFile.put(a, info, magic == DOUBLE) + a.meta.double = magic == DOUBLE + a.meta.entries = others + a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0 + a.meta.source = { format = "applesingle", variant = magic == DOUBLE and"appledouble" or"applesingle", version = math.floor(ver / 0x10000 )} + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function AppleSingle.encode(value, opts) +local o= opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + local function date(t) +if type(t) ~= "number" then + return 0x80000000 + end + return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000 + end + local dates = Bytes.writer(16) + dates:u32be(date(f.created or f.modified)) + dates:u32be(date(f.modified)) + dates:u32be(0x80000000) + dates:u32be(0x80000000) + local finder = Bytes.writer(32) + finder:string(f.type) + finder:string(f.creator) + finder:u16be(f.flags) + finder:string(string.rep("\0", 22)) + local entries= { { 3, buffer.fromstring(name) } } + if f.comment then + table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) }) + end + table.insert(entries, { 8, dates:finish() }) + table.insert(entries, { 9, finder:finish() }) + if not o.double then + table.insert(entries, { 1, f.data }) + end + if buffer.len(f.rsrc) > 0 or o.double then + table.insert(entries, { 2, f.rsrc }) + end + local w = Bytes.writer() + w:u32be((o.double and{DOUBLE }or{SINGLE})[1]) + w:u32be(0x20000) + w:string(string.rep("\0", 16)) + w:u16be(#entries) + local off = 26 + 12 * #entries + for _, e in __iter(entries) do + w:u32be(e[1]) + w:u32be(off) + w:u32be(buffer.len(e[2])) + off =off+ buffer.len(e[2]) + end + for _, e in __iter(entries) do + w:bytes(e[2]) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork +function AppleSingle.new() +local a = Archive.new("applesingle", encoder) + a.meta.source = { format = "applesingle" } + return a +end + +return AppleSingle +end +__FILES["archive/ar"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/" +-- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard +-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not +-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their +-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and +-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed +-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and +-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written +-- library needs ranlib), writing .deb control data (any entries write as a plain ar). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Ar = { + name = "ar", + category = "archive", + extensions = { "a", "ar", "deb", "lib" }, + mime = { "application/x-archive", "application/vnd.debian.binary-package" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local MAGIC = "!<arch>\n" +local HEADER = 60 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ar.sniff(r) +if r:peek(8) == MAGIC then + return r:peek(13, 68) == "debian-binary" and 1 or 0.9 + end + return r:peek(8) == "!<thin>\n" and 0.5 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b, at, n) +return function() +local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function decimal(s) +local d = string.match(s, "^%s*(%d+)%s*$") + return (d and{(tonumber(d) )}or{(string.find(s, "^%s*$") and 0 or nil) +})[1]end + +-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names +local function sysvSymbols(b, o, n, wide) +local out = {} + local w = wide and 8 or 4 + if n < w then + return out + end + local count = (wide and{(bit32.byteswap(buffer.readu32(b, o + 4)) )}or{(bit32.byteswap(buffer.readu32(b, o)) +)})[1] if count * w + w > n then + return out + end + local s = o + w + count * w + local e = o + n + for i = 0, count - 1 do + local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4))) + local q = s + while q < e and buffer.readu8(b, q) ~= 0 do + q =q+ 1 + end + table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off }) + s = q + 1 + if s > e then + break + end + end + return out +end + +-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings +local function bsdSymbols(b, o, n) +local out = {} + if n < 8 then + return out + end + local rb = buffer.readu32(b, o) + if rb % 8 ~= 0 or rb + 8 > n then + return out + end + local strs = o + 8 + rb + local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs) + for i = 0, math.floor(rb / 8 )- 1 do + local sx = buffer.readu32(b, o + 4 + i * 8) + if sx < strn then + local q = strs + sx + while q < strs + strn and buffer.readu8(b, q) ~= 0 do + q =q+ 1 + end + table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) }) + end + end + return out +end + +-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab) +local function controlFields(s) +local out= {} + local last= nil + for line in __iter(string.gmatch(s, "([^\n]*)\n?")) do + local c = string.sub(line, 1, 1) + if (c == " " or c == "\t") and last then + out[last]=out[last].. "\n" .. string.sub(line, 2) + else + local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$") + if k then + out[k], last = v , k + end + end + end + return out +end + +-- control.tar[.ext] -> the control file's fields, or nil +local function debControl(b, o, n, name, maxBytes) +local ext = string.match(name, "^control%.tar%.?(%w*)$") + local raw +local opts= { maxBytes = maxBytes } + if ext == "" then + raw = buffer.create(n) + buffer.copy(raw , 0, b, o, n) + elseif ext == "gz" then + raw = Deflate.gunzip(b, o, n) + elseif ext == "xz" then + raw = Lzma.xz(b, o, n, opts) + elseif ext == "lzma" then + raw = Lzma.alone(b, o, n, opts) + elseif ext == "zst" then + raw = Zstd.decompress(b, o, n, opts) + elseif ext == "bz2" then + raw = Bzip2.decompress(b, o, n, opts) + end + if not raw then + return nil + end + local list = Tar.read(raw) + for _, e in __iter(list or {}) do + if (e.name == "./control" or e.name == "control") and e.type == "0" then + return controlFields(buffer.readstring(raw, e.offset, e.size)) + end + end + return nil +end + +local function encode(archive, opts) +return Ar.encode(archive, opts) +end + +function Ar.decode(r, opts) +local o= opts or {} + local maxEntries = o.maxEntries or 1e6 + local b, base, e = r.buf, r.base, r.limit + if r:peek(8) == "!<thin>\n" then + return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base) + end + if r:peek(8) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local a = Archive.new("ar", encode) + local variant = "gnu" + local longNames= nil + local symbols= nil + local offsets= {} -- header offset (from the start) -> member name + local count = 0 + local p = base + 8 + while p < e do +local __DARKLUA_CONTINUE_7=false repeat local c = buffer.readu8(b, p) + if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then + break -- trailing padding (bsdtar fills its last 10240-byte block with zeros) + end + if p + HEADER > e then + return nil, Err.new(Err.TRUNCATED, "member header past the end", p) + end + if buffer.readstring(b, p + 58, 2) ~= "`\n" then + return nil, Err.new(Err.CORRUPT, "bad member header", p + 58) + end + local rawName = buffer.readstring(b, p, 16) + local mtime = decimal(buffer.readstring(b, p + 16, 12)) + local uid = decimal(buffer.readstring(b, p + 28, 6)) + local gid = decimal(buffer.readstring(b, p + 34, 6)) + local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$") + local size = decimal(buffer.readstring(b, p + 48, 10)) + if not (mtime and uid and gid and modeS and size) then + return nil, Err.new(Err.CORRUPT, "bad member header field", p) + end + local mode = modeS == "" and 0 or(tonumber(modeS, 8) ) +local data = p + HEADER + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "member data past the end", data) + end + local nextP = data + size + size % 2 + local name = string.gsub(rawName, " +$", "") + local dataSize = size + if string.sub(name, 1, 3) == "#1/" then + local n = tonumber(string.sub(name, 4)) + if not n or n > size then + return nil, Err.new(Err.CORRUPT, "bad BSD name length", p) + end + name = buffer.readstring(b, data, n) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + data =data+ n + dataSize =dataSize- n + variant = "bsd" + elseif name == "//" then + longNames = buffer.readstring(b, data, size) + p = nextP +__DARKLUA_CONTINUE_7=true break + elseif name == "/" or name == "/SYM64/" then + symbols = sysvSymbols(b, data, size, name == "/SYM64/") + p = nextP +__DARKLUA_CONTINUE_7=true break + elseif string.match(name, "^/%d+$") then + local off = (tonumber(string.sub(name, 2)) ) +if not longNames or off >= #longNames then + return nil, Err.new(Err.CORRUPT, "long name outside the name table", p) + end + local s = (string.match(longNames, "^([^\n]*)", off + 1) ) +name = string.gsub(s, "/$", "") + elseif string.sub(name, -1) == "/" then + name = string.sub(name, 1, -2) + end + if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then + symbols = bsdSymbols(b, data, dataSize) + variant = "bsd" + p = nextP +__DARKLUA_CONTINUE_7=true break + end + if name == "" then + return nil, Err.new(Err.CORRUPT, "empty member name", p) + end + offsets[p - base] = name + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + Archive.put(a, { + name = name, + size = dataSize, + dir = false, + mtime = mtime, + uid = uid, + gid = gid, + mode = bit32.band(mode, 0xFFF), + armode = modeS, + method = "store", + load = (dataSize > 0 and{(lazy(b, data, dataSize) )}or{nil})[1], + }) + p = nextP +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + if symbols then + local out = {} + for _, s in __iter(symbols) do + table.insert(out, { name = s.name, member = offsets[s.offset] }) + end + a.meta.symbols = out + end + a.meta.source = { format = "ar", variant = variant } + -- Debian packages + local list = a._entries + if list[1] and list[1].name == "debian-binary" then + a.meta.source.variant = "deb" + local v = a:read("debian-binary") + a.meta.debian = (v and{(string.match(buffer.tostring(v), "^%s*(.-)%s*$")) }or{nil +})[1] for _, ent in __iter(list) do + if string.match(ent.name, "^data%.tar") then + a.meta.payload = ent.name + elseif string.match(ent.name, "^control%.tar") then + local cb = a:read(ent.name) + if cb then + a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26) + end + end + end + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function pad(s, n) +return s .. string.rep(" ", n - #s) +end + +local function header(name, e, size) +local mtime = math.floor((type(e.mtime) == "number" and{e.mtime }or{0})[1]) + local uid = (type(e.uid) == "number" and{e.uid }or{0 +})[1] local gid = (type(e.gid) == "number" and{e.gid }or{0 +})[1] local mode= (type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") and{e.armode +}or{(string.format("%o", (type(e.mode) == "number" and{(bit32.band(e.mode, 0xFFF) )}or{0x1A4})[1]) +)})[1] local f= { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) } + local w = { 12, 6, 6, 8, 10 } + for i, s in __iter(f) do + if #s > w[i] or string.find(s, "[^%d]") then + return nil + end + end + return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n" +end + +function Ar.encode(archive, opts) +local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local o= opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local variant = o.variant or (src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") and"bsd" or"gnu") + if variant ~= "gnu" and variant ~= "bsd" then + return nil, Err.new(Err.ARG, "variant must be gnu or bsd") + end + local files = {} + for _, it in __iter(items) do + local e= it.entry + if not e.dir and (e.type == nil or e.type == "0") then + local data, err = it.read() + if not data then + return nil, err + end + table.insert(files, { e = e, data = data }) + end + end + local w = Bytes.writer(1024) + w:string(MAGIC) + -- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table + local table_= {} + local nameOf= {} + local tsize = 0 + for i, f in __iter(files) do + local name= f.e.name + if string.find(name, "\n") or name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar") + end + if variant == "gnu" then + if #name > 15 or string.find(name, "[/ ]") then + nameOf[i] = "/" .. tsize + table.insert(table_, name .. "/\n") + tsize =tsize+ (#name + 2 +) else + nameOf[i] = name .. "/" + end + end + end + if #table_ > 0 then + local t = table.concat(table_) + if #t % 2 == 1 then + t =t.. "\n" + end + w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t) + end + for i, f in __iter(files) do + local name= f.e.name + local size = buffer.len(f.data) + local prefix = "" + local field = nameOf[i] + if variant == "bsd" then + if #name > 16 or string.find(name, " ") then + field = "#1/" .. #name + prefix = name + else + field = name + end + end + local h = header(field, f.e, size + #prefix) + if not h then + return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header") + end + w:string(h) + w:string(prefix) + w:bytes(f.data) + if (size + #prefix) % 2 == 1 then + w:string("\n") + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" }) +function Ar.new() +local a = Archive.new("ar", encode) + a.meta.source = { format = "ar", variant = "gnu" } + return a +end + +return Ar +end +__FILES["archive/arj"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS, +-- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style +-- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type +-- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM). +-- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files, +-- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those +-- entries / calls). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Arj = { + name = "arj", + category = "archive", + extensions = { "arj" }, + mime = { "application/x-arj" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Arj.sniff(r) +local h = r:peek(4) + if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + return size > 0 and size <= 2600 and 0.9 or 0 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker + + + +local function block(r, p) +local h = r:sub(p, 4) + local id1, id2, size = h:u8(), h:u8(), h:u16le() + if h.err then + return nil, "truncated header" + end + if id1 ~= 0x60 or id2 ~= 0xEA then + return nil, "bad header id" + end + if size == 0 then + return nil, nil + end + if size > 2600 then + return nil, "header too large" + end + if p + 4 + size + 4 > r:size() then + return nil, "truncated header" + end + local crc = r:sub(p + 4 + size, 4):u32le() + if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then + return nil, "checksum: header CRC-32 mismatch" + end + local f = r:sub(p + 4, size) + local first = f:u8() + if first < 30 or first > size then + return nil, "bad first header size" + end + f:seek(first) + local name = f:cstring() + local comment = f:cstring() + -- extended headers + local q = p + 4 + size + 4 + local guard = 0 + while true do + local e = r:sub(q, 2) + local n = e:u16le() + if e.err then + return nil, "truncated extended header" + end + q =q+ 2 + if n == 0 then + break + end + q =q+ (n + 4 +) guard =guard+ 1 + if guard > 256 or q > r:size() then + return nil, "truncated extended header" + end + end + f:seek(0) + return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil +end + +function Arj.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local main, err = block(r, 0) + if not main then + return nil, Err.from(err or "no main header", r.base) + end + local a = Archive.new("arj") + local mf = main.fields + mf:skip(1) + local version, minVersion, host = mf:u8(), mf:u8(), mf:u8() + local flags = mf:u8() + mf:skip(3) + local created = mf:u32le() + a.meta.archive = main.name + a.meta.comment = (main.comment ~= "" and{main.comment }or{nil +})[1] a.meta.os = OS[host] + a.meta.created = Archive.fromDos(created) + a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags } + local p = main.next + local count = 0 + while true do + local h, herr = block(r, p) + if herr then + return nil, Err.from(herr, r.base + p) + end + if not h then + break + end + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local f = h.fields + f:skip(1) + f:skip(2) + local hostOs = f:u8() + local fl = f:u8() + local method = f:u8() + local ftype = f:u8() + f:skip(1) + local stamp = f:u32le() + local packed, size, crc = f:u32le(), f:u32le(), f:u32le() + f:skip(2) + local mode = f:u16le() + local dataAt = h.next + if dataAt + packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt) + end + local name = string.gsub(h.name, "\\", "/") + local isDir = ftype == 3 + if isDir and string.sub(name, -1) ~= "/" then + name =name.. "/" + end + local e= { + name = name, + size = isDir and 0 or size, + compressedSize = packed, + method = method == 0 and"store" or"arj" .. method, + mtime = Archive.fromDos(stamp), + dir = isDir, + mode = mode, + os = OS[hostOs], + comment = (h.comment ~= "" and{h.comment }or{nil})[1], + fileType = ftype, + } + if ftype ~= 4 then -- 4: a volume label, not a file + if not isDir and size > 0 then + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local buf, at = r.buf, r.base + dataAt + e.load = function() +if bit32.band(fl, 0x01) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries") + end + if bit32.band(fl, 0x0C) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes") + end + local out, derr +if method == 0 then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out , 0, buf, at, size) + elseif method >= 1 and method <= 3 then + out, derr = Lzh.decode(buf, at, packed, size, "lh6") + elseif method == 4 then + out, derr = Lzh.decode(buf, at, packed, size, "arj4") + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc32.of(out) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + end + p = dataAt + packed + end + return a, nil +end + +return Arj +end +__FILES["archive/binhex"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name, +-- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified: +-- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a +-- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file +-- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter +-- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with +-- archive/macbinary), several files in one .hqx (only the first is read). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local Binhex = { + name = "binhex", + category = "archive", + extensions = { "hqx", "hcx" }, + mime = { "application/mac-binhex40" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + +local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr" +local VALUE= {} +for i = 1, 64 do + VALUE[string.byte(ALPHABET, i)] = i - 1 +end +local BANNER = "(This file must be converted with BinHex" + +-- ------------------------------------------------------------------------------------------------ sniff +function Binhex.sniff(r) +local head = r:peek(2048) + local at = string.find(head, BANNER, 1, true) + if not at then + return 0 + end + return at == 1 and 1 or 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input) +local function unhex(text, maxBytes) +local banner = string.find(text, BANNER, 1, true) + if not banner then + return nil, "no BinHex banner" + end + local start = string.find(text, ":", banner, true) + if not start then + return nil, "truncated: no data start" + end + local raw = Bytes.writer(#text) + local acc, nbits = 0, 0 + local closed = false + for i = start + 1, #text do + local c = string.byte(text, i) + if c == 58 then -- ":" + closed = true + break + end + local v = VALUE[c] + if v then + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v) + nbits =nbits+ 6 + if nbits >= 8 then + nbits =nbits- 8 + raw:u8(bit32.band(bit32.rshift(acc, nbits), 255)) + end + elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then + return nil, string.format("bad character 0x%02x", c) + end + end + if not closed then + return nil, "truncated: no closing colon" + end + local src = raw:finish() + -- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90 + local out = Bytes.writer(buffer.len(src) * 2) + local n = buffer.len(src) + local prev = 0 + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + if c == 0x90 and i + 1 < n then + local count = buffer.readu8(src, i + 1) + i =i+ 2 + if count == 0 then + out:u8(0x90) + prev = 0x90 + else + if out:tell() + count > maxBytes then + return nil, "limit: data larger than maxBytes" + end + for _ = 2, count do + out:u8(prev) + end + end + else + out:u8(c) + prev = c + i =i+ 1 + end + end + return out:finish(), nil +end + +local function encoder(a, o) +return Binhex.encode(a, o) +end + +function Binhex.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes) + if not b then + return nil, Err.from(err) + end + local h = Bytes.reader(b) + local nameLen = h:u8() + local name = h:string(nameLen) + h:skip(1) -- version + local ftype, creator = h:string(4), h:string(4) + local flags = h:u16be() + local dlen, rlen = h:u32be(), h:u32be() + local hcrc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + if dlen + rlen > maxBytes then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + local forks = {} + for k, len in __iter({ dlen, rlen }) do + local at = h:tell() + local fork = h:bytes(len) + local crc = h:u16be() + if h.err then + return nil, h.err + end + if Crc16.ccitt(b, at, len) ~= crc then + return nil, Err.new(Err.CHECKSUM, (k == 1 and"data" or"resource") .. " fork CRC mismatch") + end + forks[k] = fork + end + local a = Archive.new("binhex", encoder) + MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "binhex" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Binhex.encode(value, opts) +local o= opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local w = Bytes.writer() + w:u8(#name) + w:string(name) + w:u8(0) + w:string(f.type) + w:string(f.creator) + w:u16be(f.flags) + w:u32be(buffer.len(f.data)) + w:u32be(buffer.len(f.rsrc)) + local hdr = w:finish() + local body = Bytes.writer() + for _, part in __iter({ hdr, f.data, f.rsrc }) do + body:bytes(part) + body:u16be(Crc16.ccitt(part, 0, buffer.len(part))) + end + local src = body:finish() + -- RLE90 + local rle = Bytes.writer(buffer.len(src) + 16) + local n = buffer.len(src) + local i = 0 + while i < n do + local c = buffer.readu8(src, i) + local run = 1 + while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do + run =run+ 1 + end + if c == 0x90 then + rle:u8(0x90) + rle:u8(0) + run = 1 + else + rle:u8(c) + if run >= 3 then + rle:u8(0x90) + rle:u8(run) + else + run = 1 + end + end + i =i+ run + end + local bytes = rle:finish() + -- 6-bit characters, 64 to a line (the first line includes the colon) + local chars = { ":" } + local col = 1 + local acc, nbits = 0, 0 + local function put(v) + table.insert(chars, string.sub(ALPHABET, v + 1, v + 1)) + col =col+ 1 + if col == 64 then + table.insert(chars, "\n") + col = 0 + end + end + for k = 0, buffer.len(bytes) - 1 do + acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k)) + nbits =nbits+ 8 + while nbits >= 6 do + nbits =nbits- 6 + put(bit32.band(bit32.rshift(acc, nbits), 63)) + end + end + if nbits > 0 then + put(bit32.band(bit32.lshift(acc, 6 - nbits), 63)) + end + table.insert(chars, ":\n") + return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork +function Binhex.new() +local a = Archive.new("binhex", encoder) + a.meta.source = { format = "binhex" } + return a +end + +return Binhex +end +__FILES["archive/br"] = function() +local __compat = __compat local buffer = __compat.buffer --!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/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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Br = { + name = "br", + category = "archive", + extensions = { "br" }, + mime = { "application/x-brotli" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff +local SNIFF_PREFIX = 65536 + +-- ------------------------------------------------------------------------------------------------ sniff +function Br.sniff(r) +local n = r:remaining() + if n == 0 then + return 0 + end + if n <= SNIFF_WHOLE then + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 }) + if out and consumed == r.limit then + return buffer.len(out) > 0 and 0.3 or 0.05 + end + return 0 + end + local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 }) + if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then + return 0.05 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Br.decode(r, opts) +local n = r:remaining() + local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes }) + if not out then + local e= consumed + e.message = string.gsub(e.message, "^brotli: ", "") + return nil, e + end + local a = Archive.new("br") + a.meta.stream = true + a.meta.compressedSize = consumed - r.pos + Archive.put(a, { + name = Archive.streamName(opts, Br.extensions), + size = buffer.len(out), + compressedSize = consumed - r.pos, + method = "brotli", + dir = false, + data = out, + }) + return a, nil +end + +return Br +end +__FILES["archive/bz2"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated +-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), +-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported: +-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Bzip2 = __include("codecs/compress/Bzip2") + +-- ------------------------------------------------------------------------------------------------ contract +local Bz2 = { + name = "bz2", + category = "archive", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + +function Bz2.sniff(r) +local h = r:peek(10) + if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then + return 0 + end + local lv = string.byte(h, 4) + if lv < 0x31 or lv > 0x39 then + return 0 + end + local magic = string.sub(h, 5, 10) + if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Bz2.decode(r, opts) +local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) + if not out then + return nil, consumed + end + local a = Archive.new("bz2") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(opts, Bz2.extensions), + size = buffer.len(out), + compressedSize = consumed - r.base, + method = "bzip2", + dir = false, + data = out, + }) + return a, nil +end + +return Bz2 +end +__FILES["archive/cab"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and +-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose +-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum +-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local +-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) +-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same +-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the +-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a +-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), +-- signed / self-extracting stubs before the header. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzx = __include("codecs/compress/Lzx") +local Quantum = __include("codecs/compress/Quantum") +local Archive = __include("containers/Archive") +local Sum = __include("archive/cab/Sum") + +-- ------------------------------------------------------------------------------------------------ contract +local Cab = { + name = "cab", + category = "archive", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 +local ATTR_UTF8 = 0x80 +local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } +local BLOCK = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function Cab.sniff(r) +if r:peek(8) == "MSCF\0\0\0\0" then + return 1 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next +-- cabinet (a block with cbUncomp 0) + + + + + + + + + +local function blocks(r, f, dataReserve, verify, maxBytes) +local list= {} + local p = f.dataAt + local total = 0 + for i = 1, f.blocks do + local h = r:sub(p, 8) + local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() + if h.err then + return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) + end + local at = p + 8 + dataReserve + if at + cbData > r:size() then + return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) + end + if cbUncomp == 0 then + return list, total, true + end + if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then + return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) + end + total =total+ cbUncomp + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") + end + table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) + p = at + cbData + end + return list, total, false +end + +-- the decompressed data of a folder's blocks +local function inflateFolder(buf, list, total, typ) +local method = bit32.band(typ, 15) + local out = buffer.create(total) + if method == 0 then + local o = 0 + for _, b in __iter(list) do + if b.len ~= b.size then + return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) + end + buffer.copy(out, o, buf, b.at, b.len) + o =o+ b.len + end + return out, nil + elseif method == 1 then + local spans= {} + for _, b in __iter(list) do + table.insert(spans, { offset = b.at, length = b.len, size = b.size }) + end + return Deflate.mszip(buf, spans) + elseif method == 3 then + local bits = bit32.band(bit32.rshift(typ, 8), 31) + local n = 0 + for _, b in __iter(list) do + n =n+ b.len + end + local src = buffer.create(n) + local o = 0 + for _, b in __iter(list) do + buffer.copy(src, o, buf, b.at, b.len) + o =o+ b.len + end + local res, err = Lzx.decode(src, 0, n, total, bits) + if not res then + return nil, Err.from(err) + end + return res, nil + elseif method == 2 then + local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31)) + if not res then + return nil, Err.from(err) + end + return res, nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) +end + +local function encode(archive, opts) +return Cab.encode(archive, opts) +end + +function Cab.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65535 + local verify = o.verify ~= false + if not r:match("MSCF") then + return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) + end + r:skip(4) + local cbCabinet = r:u32le() + r:skip(4) + local coffFiles = r:u32le() + r:skip(4) + local minor, major = r:u8(), r:u8() + local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() + local setId, iCabinet = r:u16le(), r:u16le() + local headerReserve, folderReserve, dataReserve = 0, 0, 0 + if bit32.band(flags, FLAG_RESERVE) ~= 0 then + headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() + end + local a = Archive.new("cab", encode) + local meta= a.meta + if headerReserve > 0 then + meta.reserve = r:bytes(headerReserve) + end + if bit32.band(flags, FLAG_PREV) ~= 0 then + meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) + end + if bit32.band(flags, FLAG_NEXT) ~= 0 then + meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) + end + if r.err then + return nil, r.err + end + if major ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) + end + meta.setId, meta.cabinet = setId, iCabinet + meta.source = { + format = "cab", + version = major .. "." .. minor, + size = cbCabinet, + flags = flags, + reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, + } + -- folders + local folders= {} + local methods = {} + for i = 1, cFolders do + local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() + r:skip(folderReserve) + if r.err then + return nil, r.err + end + folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } + local m = METHOD[bit32.band(typ, 15)] + methods[i] = { + method = m or ("type " .. bit32.band(typ, 15)), + window = ((m == "lzx" or m == "quantum" )and{(bit32.band(bit32.rshift(typ, 8), 31) )}or{nil})[1], + level = (m == "quantum" and{(bit32.band(bit32.rshift(typ, 4), 15) )}or{nil})[1], + blocks = nblocks, + } + end + meta.folders = methods + if cFiles == 0 or cFolders == 0 then + return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders") + end + if cFiles > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries files") + end + -- the folder cache: the last decompressed folder + local cachedIndex, cachedData, cachedRuns = 0, nil , false + local function folderData(f) +if cachedIndex == f.index then + return cachedData, nil, cachedRuns + end + local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) + if not list then + return nil, total, false + end + local data, err = inflateFolder(r.buf, list, total, f.type) + if not data then + return nil, err, false + end + cachedIndex, cachedData, cachedRuns = f.index, data, runs == true + return data, nil, runs + end + -- files + local fr = r:sub(coffFiles) + for _ = 1, cFiles do + local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() + local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() + local raw = fr:cstring(65536) + if fr.err then + return nil, fr.err + end + local name = string.gsub(raw, "\\", "/") + local spanned= nil + local folder +if iFolder == 0xFFFD or iFolder == 0xFFFF then + spanned = "a file continued from the previous cabinet" + folder = folders[1] + elseif iFolder == 0xFFFE then + spanned = "a file continued in the next cabinet" + folder = folders[#folders] + else + folder = folders[iFolder + 1] + if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then + spanned = "a folder continued from the previous cabinet" + end + end + if not folder then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) + end + local fo = folder +if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local e= { + name = name, + size = size, + method = METHOD[bit32.band(fo.type, 15)] or "unknown", + mtime = Archive.fromDos(date * 65536 + time), + dir = false, + attributes = bit32.band(attribs, 0xFF7F), + utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, + folder = fo.index, + offset = offset, + readonly = bit32.band(attribs, 0x01) ~= 0, + executable = bit32.band(attribs, 0x40) ~= 0, + } + if spanned then + e.spanned = true + end + if size > 0 or spanned then + e.load = function() +if spanned then + return nil, Err.new(Err.UNSUPPORTED, spanned ) + end + local data, err, runs = folderData(fo) + if not data then + return nil, err + end + if offset + size > buffer.len(data) then + if runs then + return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") + end + return nil, Err.new(Err.CORRUPT, "file past the end of its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, data, offset, size) + return out, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) +function Cab.encode(archive, opts) +local o= opts or {} + local compression = o.compression or "mszip" + if compression ~= "mszip" and compression ~= "none" then + return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") + end + local level = o.level or 6 + 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") + end + local files, ferr = Archive.files(archive) + if not files then + return nil, ferr + end + if #files == 0 then + return nil, Err.new(Err.ARG, "a cabinet needs at least one file") + end + if #files > 65535 then + return nil, Err.new(Err.ARG, "more than 65535 files") + end + local total = 0 + for _, f in __iter(files) do + total =total+ buffer.len(f.data) + end + if total > 0x7FFF8000 then + return nil, Err.new(Err.ARG, "more than 2 GB of data") + end + -- the folder data, in 32 KB blocks + local folder = buffer.create(total) + local p = 0 + for _, f in __iter(files) do + buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) + p =p+ buffer.len(f.data) + end + local data = Bytes.writer(math.floor(total / 2 )+ 64) + local nblocks = 0 + local s = 0 + while s < total do + local n = math.min(BLOCK, total - s) + local chunk = buffer.create(n) + buffer.copy(chunk, 0, folder, s, n) + local payload +if compression == "mszip" then + local z, zerr = Deflate.compress(chunk, { level = level }) + if not z then + return nil, zerr + end + payload = buffer.create(buffer.len(z) + 2) + buffer.writeu16(payload, 0, 0x4B43) + buffer.copy(payload, 2, z, 0, buffer.len(z)) + else + payload = chunk + end + local len = buffer.len(payload) + data:u32le(Sum.block(payload, 0, len, n)) + data:u16le(len) + data:u16le(n) + data:bytes(payload) + nblocks =nblocks+ 1 + s =s+ n + end + local blob = data:finish() + -- names and the file table + local table_ = Bytes.writer(64 + #files * 32) + local offset = 0 + for _, f in __iter(files) do + local e= f.entry + local name = string.gsub(f.name, "/", "\\") + local attribs = (type(e.attributes) == "number" and{(bit32.band(e.attributes, 0x7F) )}or{0x20 +})[1] if string.find(name, "[\128-\255]") then + attribs = bit32.bor(attribs, ATTR_UTF8) + end + local stamp = Archive.toDos(e.mtime) + table_:u32le(buffer.len(f.data)) + table_:u32le(offset) + table_:u16le(0) + table_:u16le(math.floor(stamp / 65536)) + table_:u16le(stamp % 65536) + table_:u16le(attribs) + table_:cstring(name) + offset =offset+ buffer.len(f.data) + end + local fileTable = table_:finish() + local nfolders = 1 + local coffFiles = 36 + 8 * nfolders + local dataAt = coffFiles + buffer.len(fileTable) + local size = dataAt + buffer.len(blob) + local w = Bytes.writer(size) + w:string("MSCF") + w:u32le(0) + w:u32le(size) + w:u32le(0) + w:u32le(coffFiles) + w:u32le(0) + w:u8(3) + w:u8(1) + w:u16le(nfolders) + w:u16le(#files) + w:u16le(0) + w:u16le(o.setId or 0) + w:u16le(0) + w:u32le(dataAt) + w:u16le(nblocks) + w:u16le(compression == "mszip" and 1 or 0) + w:bytes(fileTable) + w:bytes(blob) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) +function Cab.new() +local a = Archive.new("cab", encode) + a.meta.source = { format = "cab" } + return a +end + +return Cab +end +__FILES["archive/cab/Sum"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 +-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format +-- description ([MS-CAB] 2.4, CFDATA.csum). + +local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len +local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift + +local Sum = {} + +-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) +function Sum.of(buf, off, len, seed) +if off < 0 or len <= 0 or off + len > blen(buf) then + return seed + end + local s = seed + local p = off + local stop = off + len - len % 4 + while p < stop do + s = bxor(s, readu32(buf, p)) + p =p+ 4 + end + local rem = len % 4 + local tail = 0 + if rem == 3 then + tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) + elseif rem == 2 then + tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) + elseif rem == 1 then + tail = readu8(buf, p) + end + return bxor(s, tail) +end + +-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) +function Sum.block(buf, dataAt, cbData, cbUncomp) +return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) +end + +return Sum +end +__FILES["archive/cpio"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the +-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc +-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters), +-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor, +-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1") +-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local CpioFormat = { + name = "cpio", + category = "archive", + extensions = { "cpio" }, + mime = { "application/x-cpio" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function CpioFormat.sniff(r) +local m = r:peek(6) + if m == "070701" or m == "070702" or m == "070707" then + return 1 + end + local b2 = r:peek(2) + if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b, at, n) +return function() +local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive, opts) +return CpioFormat.encode(archive, opts) +end + +function CpioFormat.decode(r, opts) +local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("cpio", encode) + for _, e in __iter(list) do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = (data and{e.size }or{0})[1], + dir = e.dir, + mtime = e.mtime, + mode = bit32.band(e.mode, 0xFFF), + uid = e.uid, + gid = e.gid, + type = e.type, + link = e.link, + hardlink = e.hardlink, + nlink = e.nlink, + ino = e.ino, + devmajor = e.devmajor, + devminor = e.devminor, + rdevmajor = e.rdevmajor, + rdevminor = e.rdevminor, + method = "store", + load = (data and{(lazy(r.buf, e.offset, e.size) )}or{nil})[1], + }) + end + a.meta.source = { format = "cpio", variant = info.format } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(v) +return (type(v) == "number" and{v }or{nil +})[1]end + +function CpioFormat.encode(archive, opts) +local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local index= {} + for i, it in __iter(items) do + index[it.entry.name] = index[it.entry.name] or i + end + -- tar hard links ("1"): the same inode as their target, which counts the links + local links= {} + local target= {} + for i, it in __iter(items) do + local e= it.entry + if e.type == "1" and type(e.link) == "string" and index[e.link] then + local t = index[e.link] + target[i] = t + links[t] = (links[t] or 1) + 1 + end + end + local list= {} + for i, it in __iter(items) do + local e= it.entry + local typ = (type(e.type) == "string" and Cpio.TYPE_MODE[e.type] and{e.type }or{e.dir and"5" or"0" +})[1] local src = target[i] + local ino, nlink = num(e.ino), num(e.nlink) + if src then + typ, ino, nlink = "0", src, links[src] + elseif links[i] then + ino, nlink = i, links[i] + end + local data= nil + if typ == "0" then + local b, err = (items[src or i] ).read() + if not b then + return nil, err + end + data = b + end + local mode = num(e.mode) + table.insert(list, { + name = e.name, + data = data, + type = typ, + link = (type(e.link) == "string" and typ == "2" and{e.link }or{nil})[1], + mode = (mode and{(bit32.band(mode, 0xFFF) )}or{nil})[1], + uid = num(e.uid), + gid = num(e.gid), + nlink = nlink, + mtime = num(e.mtime), + ino = ino, + devmajor = num(e.devmajor), + devminor = num(e.devminor), + rdevmajor = num(e.rdevmajor), + rdevminor = num(e.rdevminor), + }) + end + -- opts.format may also be the api's format name ("cpio"): the variant default then + local o= opts or {} + local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source + local own = (src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") and{src.variant }or{"newc" +})[1] local variant = o.variant or (((o.format == "crc" or o.format == "odc" or o.format == "newc" )and{o.format }or{own})[1]) + return Cpio.write(list, { format = variant, block = o.block }) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write() +function CpioFormat.new() +local a = Archive.new("cpio", encode) + a.meta.source = { format = "cpio" } + return a +end + +return CpioFormat +end +__FILES["archive/d64"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info +-- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and +-- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are +-- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are +-- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII +-- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the +-- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any +-- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS +-- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers' +-- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local D64 = { + name = "d64", + category = "archive", + extensions = { "d64", "d71", "d81" }, + mime = { "application/x-d64" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" } +local TYPE_CODE= { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 } + + + +local function geometry(kind, tracks) +local offsets, spt = {}, {} + local o = 0 + for t = 1, tracks do + local n + if kind == "d81" then + n = 40 + else + local s = (kind == "d71" and t > 35 and((t - 35 ))or(t +)) n = s <= 17 and 21 or(s <= 24 and 19 or(s <= 30 and 18 or 17 +)) end + offsets[t], spt[t] = o, n + o =o+ n * 256 + end + return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = kind == "d81" and 40 or 18, total = o } +end + +-- image sizes -> geometry (sizes with the error-info block appended too) +local function detect(len) +for _, g in __iter({ { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } }) do + local geo = geometry(g[1] , g[2] ) + local sectors = math.floor(geo.total / 256 +) if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then + return geo + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function D64.sniff(r) +local geo = detect(r:size()) + if not geo then + return 0 + end + -- the BAM / header sector: dir track link and DOS version byte + local h = r:sub(geo.offsets[geo.dirTrack], 256) + local t, s, v = h:u8(), h:u8(), h:u8() + if geo.kind == "d81" then + return t == 40 and s == 3 and v == 0x44 and 0.9 or 0.3 + end + return t == 18 and s == 1 and (v == 0x41 or v == 0) and 0.9 or 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function petscii(raw) +local out = table.create(#raw) + for i = 1, #raw do + local c = string.byte(raw, i) + if c >= 0x41 and c <= 0x5A then + out[i] = string.char(c + 32) + elseif c >= 0xC1 and c <= 0xDA then + out[i] = string.char(c - 0x80) + elseif c >= 0x61 and c <= 0x7A then + out[i] = string.char(c - 32) + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + out[i] = string.char(c) + else + out[i] = utf8.char(0xE000 + c) + end + end + return table.concat(out) +end + +local function toPetscii(name) +local out = {} + if not utf8.len(name) then + return string.sub(name, 1, 16) + end + for _, c in __iter(utf8.codes(name)) do + local b + if c >= 0x61 and c <= 0x7A then + b = c - 32 + elseif c >= 0x41 and c <= 0x5A then + b = c + 0x80 + elseif c >= 0xE000 and c <= 0xE0FF then + b = c - 0xE000 + elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then + b = c + else + b = 0x3F + end + table.insert(out, string.char(b)) + end + return string.sub(table.concat(out), 1, 16) +end + +local function encoder(a, o) +return D64.encode(a, o) +end + +-- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops +local function chain(b, base, geo, t, s) +local w = Bytes.writer() + local seen= {} + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] then + return nil, string.format("chain leaves the disk at %d/%d", t, s) + end + local key = t * 256 + s + if seen[key] then + return nil, string.format("chain loops at %d/%d", t, s) + end + seen[key] = true + local o = base + geo.offsets[t] + s * 256 + local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if nt == 0 then + local last = math.max(ns, 1) + if last >= 2 then + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1))) + end + else + w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254))) + end + t, s = nt, ns + end + return w:finish(), nil +end + +function D64.decode(r, opts) +local o= opts or {} + local geo = detect(r:size()) + if not geo then + return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)") + end + local b, base = r.buf, r.base + local hdr = base + geo.offsets[geo.dirTrack] + local nameAt, idAt = geo.kind == "d81" and 0x04 or 0x90, geo.kind == "d81" and 0x16 or 0xA2 + local diskRaw = buffer.readstring(b, hdr + nameAt, 16) + local a = Archive.new("d64", encoder) + a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", ""))) + a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2)) + a.meta.variant = geo.kind + a.meta.tracks = geo.tracks + a.meta.errorInfo = r:size() ~= geo.total + a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks } + -- the directory chain + local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1) + local seen= {} + local count = 0 + local maxEntries = o.maxEntries or 4096 + while t ~= 0 do + if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then + return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s)) + end + seen[t * 256 + s] = true + local so = base + geo.offsets[t] + s * 256 + for k = 0, 7 do + local e = so + k * 32 + local ft = buffer.readu8(b, e + 2) + local kind = bit32.band(ft, 15) + if ft ~= 0 and kind ~= 0 then + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries") + end + local raw = buffer.readstring(b, e + 5, 16) + local name = petscii((string.gsub(raw, "\160+$", ""))) + local base_name, n = name, 2 + while a._byName[name] do + name = base_name .. ";" .. n + n =n+ 1 + end + local ty = TYPES[kind] or "?" + local entry= { + name = name, + rawName = raw, + type = ty, + closed = bit32.band(ft, 0x80) ~= 0, + locked = bit32.band(ft, 0x40) ~= 0, + blocks = buffer.readu16(b, e + 30), + dir = false, + method = "store", + } + if ty == "cbm" or ty == "dir" then + entry.size = 0 + else + local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4)) + if not data then + return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err)) + end + entry.size = buffer.len(data) + entry.data = data + if ty == "rel" then + entry.recordLength = buffer.readu8(b, e + 23) + end + end + Archive.put(a, entry) + end + end + t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- BAM layout per variant: where each track's free count + bitmap lives +local function bamEntry(geo, img, t) -- returns (offset of the free count, offset of the bitmap, bitmap bytes) + +local dir = geo.offsets[geo.dirTrack] + if geo.kind == "d81" then + local side = t <= 40 and 1 or 2 + local tt = (t <= 40 and{t }or{(t - 40 +)})[1] local o = dir + side * 256 + 0x10 + (tt - 1) * 6 + return o, o + 1, 5 + end + if t <= 35 then + local o = dir + 4 + (t - 1) * 4 + return o, o + 1, 3 + end + -- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0 + return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3 +end + +local function setFree(geo, img, t, s, free) + local co, bo = bamEntry(geo, img, t) + local byte = bo + bit32.rshift(s, 3) + local mask = bit32.lshift(1, bit32.band(s, 7)) + local cur = buffer.readu8(img, byte) + local isFree = bit32.band(cur, mask) ~= 0 + if free and not isFree then + buffer.writeu8(img, byte, bit32.bor(cur, mask)) + buffer.writeu8(img, co, buffer.readu8(img, co) + 1) + elseif not free and isFree then + buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask))) + buffer.writeu8(img, co, buffer.readu8(img, co) - 1) + end +end + +function D64.encode(value, opts) +local o= opts or {} + local variant = o.variant or ((type(value) == "table" and type(value.meta) == "table" and value.meta.variant and{value.meta.variant }or{"d64"})[1]) + if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then + return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81") + end + local files, err = Archive.files(value, "data") + if not files then + return nil, err + end + local geo = geometry(variant, variant == "d64" and 35 or(variant == "d71" and 70 or 80)) + local img = buffer.create(geo.total) + local dirT = geo.dirTrack + local dir = geo.offsets[dirT] + local diskName = toPetscii(o.disk or ((type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" and{value.meta.disk }or{"rosetta"})[1])) + local id = toPetscii(o.id or "fl") + local function pad16(s) +return s .. string.rep("\160", 16 - #s) + end + -- header / BAM + local firstDir + if variant == "d81" then + buffer.writestring(img, dir, "\40\3\68\0") + buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160") + for side = 1, 2 do + local bo = dir + side * 256 + buffer.writestring(img, bo, side == 1 and"\40\2\68\187" or"\0\255\68\187") + buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0") + end + firstDir = 3 + else + buffer.writestring(img, dir, "\18\1\65" .. (variant == "d71" and"\128" or"\0")) + buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160") + firstDir = 1 + end + for t = 1, geo.tracks do + for s = 0, geo.spt[t] - 1 do + setFree(geo, img, t, s, true) + end + end + -- system sectors: the header / BAM sectors and the first directory sector + local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true } + if variant == "d81" then + used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true + elseif variant == "d71" then + for s = 0, geo.spt[53] - 1 do + used[53 * 256 + s] = true + end + end + for k in __iter(used) do + setFree(geo, img, math.floor(k / 256), k % 256, false) + end + local maxDirSectors = geo.spt[dirT] - firstDir + if #files > maxDirSectors * 8 then + return nil, Err.new(Err.LIMIT, "too many files for one directory track") + end + -- allocation: tracks nearest the directory track first, interleave 10 + local order = {} + for d = 1, geo.tracks do + for _, t in __iter({ dirT - d, dirT + d }) do + if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then + table.insert(order, t) + end + end + end + local ti, lastS = 1, -10 + local function alloc() +while ti <= #order do + local t = order[ti] + local n = geo.spt[t] + for k = 0, n - 1 do + local s = (lastS + 10 + k) % n + if not used[t * 256 + s] then + used[t * 256 + s] = true + setFree(geo, img, t, s, false) + lastS = s + return t, s + end + end + ti =ti+ 1 + lastS = -10 + end + return nil, nil + end + local dirSector, slot = firstDir, 0 + local dirSectors = { firstDir } + for _, f in __iter(files) do + local data = f.data + local n = buffer.len(data) + local blocks = math.max(1, math.ceil(n / 254)) + local first_t, first_s = 0, 0 + local prev = -1 + for k = 0, blocks - 1 do + local t, s = alloc() + if not t or not s then + return nil, Err.new(Err.LIMIT, "disk full") + end + local so = geo.offsets[t] + s * 256 + if prev < 0 then + first_t, first_s = t, s + else + buffer.writeu8(img, prev, t) + buffer.writeu8(img, prev + 1, s) + end + local len = math.min(254, n - k * 254) + if len > 0 then + buffer.copy(img, so + 2, data, k * 254, len) + end + buffer.writeu8(img, so + 1, (k == blocks - 1 and((len + 1 ))or(0))) + prev = so + end + if slot == 8 then + -- next directory sector on the directory track (interleave 3) + local nextS = nil + for k = 0, geo.spt[dirT] - 1 do + local s = (dirSector + 3 + k) % geo.spt[dirT] + if not used[dirT * 256 + s] then + nextS = s + break + end + end + if not nextS then + return nil, Err.new(Err.LIMIT, "directory full") + end + used[dirT * 256 + nextS] = true + setFree(geo, img, dirT, nextS, false) + buffer.writeu8(img, dir + dirSector * 256, dirT) + buffer.writeu8(img, dir + dirSector * 256 + 1, nextS) + dirSector, slot = nextS, 0 + table.insert(dirSectors, nextS) + end + local e = dir + dirSector * 256 + slot * 32 + local ty= (type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] and{TYPE_CODE[f.entry.type] }or{2 +})[1] buffer.writeu8(img, e + 2, 0x80 + ty) + buffer.writeu8(img, e + 3, first_t) + buffer.writeu8(img, e + 4, first_s) + local raw = (type(f.entry.rawName) == "string" and #f.entry.rawName == 16 and{(string.gsub(f.entry.rawName, "\160+$", "")) }or{(toPetscii(f.name) +)})[1] buffer.writestring(img, e + 5, pad16(raw)) + buffer.writeu16(img, e + 30, blocks) + slot =slot+ 1 + end + buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF) + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" }) +function D64.new(variant) +local a = Archive.new("d64", encoder) + a.meta.variant = variant or "d64" + a.meta.source = { format = "d64" } + return a +end + +return D64 +end +__FILES["archive/fat"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the +-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 +-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the +-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy +-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a +-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Fat = __include("containers/Fat") + +-- ------------------------------------------------------------------------------------------------ contract +local FatFormat = { + name = "fat", + category = "archive", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + +function FatFormat.sniff(r) +if r:remaining() < 512 then + return 0 + end + local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + if not v then + return 0 + end + return v.partition and 0.6 or 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a, o) +return FatFormat.encode(a, o) +end + +function FatFormat.decode(r, opts) +local o= opts or {} + local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition }) + if not v then + return nil, Err.from(err) + end + local list, lerr = Fat.list(v, o.maxEntries) + if not list then + return nil, Err.from(lerr) + end + local a = Archive.new("fat", encoder) + for _, e in __iter(list) do + local entry = e + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + attr = e.attr, + shortName = e.shortName, + method = "store", + load = ((e.dir or e.size == 0 )and{nil }or{function() +local b, rerr = Fat.read(v , entry) + if not b then + return nil, Err.from(rerr) + end + return b, nil + end})[1], + }) + end + a.meta.fat = v.bits + a.meta.label = v.label + a.meta.oem = v.oem + a.meta.partition = v.partition + a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function FatFormat.encode(value, opts) +local o= opts or {} + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local files= {} + for _, it in __iter(items) do + local e= it.entry + local data= nil + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime }) + end + local img, err = Fat.write(files, { size = o.size, label = o.label }) + if not img then + return nil, (string.match(tostring(err), "^limit") and{(Err.from(err) )}or{(Err.new(Err.ARG, tostring(err)) +)})[1] end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) +function FatFormat.new() +local a = Archive.new("fat", encoder) + a.meta.source = { format = "fat" } + return a +end + +return FatFormat +end +__FILES["archive/grp"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count, +-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive +-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they +-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken. +-- Not supported: the "GRP 2" / RFF / SSI variants. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Grp = { + name = "grp", + category = "archive", + extensions = { "grp" }, + mime = { "application/x-build-grp" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + +local MAGIC = "KenSilverman" + +-- ------------------------------------------------------------------------------------------------ sniff +function Grp.sniff(r) +return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive, opts) +return Grp.encode(archive, opts) +end + +function Grp.decode(r, opts) +if not r:match(MAGIC) then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local count = r:u32le() + if r.err then + return nil, r.err + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + if count * 16 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 12) + end + local a = Archive.new("grp", encode) + local at = 16 + count * 16 + local size = r.limit - r.base + for i = 0, count - 1 do + local name = r:fixed(12) + local n = r:u32le() + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + at =at+ n + end + if r.err then + return nil, r.err + end + a.meta.source = { format = "grp", entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Grp.encode(archive, opts) +local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local files= {} + for _, it in __iter(items) do + if not it.entry.dir then + local name = it.entry.name + if opts and opts.upper then + name = string.upper(name) + end + if #name > 12 then + return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(MAGIC) + w:u32le(#files) + for _, f in __iter(files) do + w:string(f.name) + w:fill(0, 12 - #f.name) + w:u32le(buffer.len(f.data)) + end + for _, f in __iter(files) do + w:bytes(f.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty GRP Archive: a:add(name, data); a:write() +function Grp.new() +local a = Archive.new("grp", encode) + a.meta.source = { format = "grp" } + return a +end + +return Grp +end +__FILES["archive/gzip"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the +-- 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/compress/Deflate. Not supported: FHCRC verification. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local Gzip = { + name = "gzip", + category = "archive", + extensions = { "gz", "tgz", "gzip" }, + mime = { "application/gzip" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, stream = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + +function Gzip.sniff(r) +return r:peek(3) == "\31\139\8" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent) +local function header(b, o, e) +local h= {} + if o + 10 > e then + return h + end + local flg = buffer.readu8(b, o + 3) + h.mtime = buffer.readu32(b, o + 4) + h.os = buffer.readu8(b, o + 9) + local q = o + 10 + if bit32.band(flg, 4) ~= 0 and q + 2 <= e then + q =q+ (2 + buffer.readu16(b, q) +) end + for _, f in __iter({ { 8, "name" }, { 16, "comment" } }) do + if bit32.band(flg, f[1]) ~= 0 then + local s = q + while q < e and buffer.readu8(b, q) ~= 0 do + q =q+ 1 + end + if q < e then + h[f[2] ] = buffer.readstring(b, s, q - s) + end + q =q+ 1 + end + end + return h +end + +function Gzip.decode(r, opts) +local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base) + if not out then + return nil, err + end + local h = header(r.buf, r.base, r.limit) + local a = Archive.new("gzip", function(arc, o) +return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip", os = h.os } + a.meta.comment = h.comment + local name = h.name + if not name or name == "" or string.find(name, "[/\\]") then + name = Archive.streamName(opts, Gzip.extensions) + end + Archive.put(a, { + name = name, + size = buffer.len(out), + compressedSize = r.limit - r.base, + method = "deflate", + mtime = (h.mtime and h.mtime > 0 and{h.mtime }or{nil})[1], + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Gzip.encode(value, opts) +local o= opts or {} + local level = o.level == nil and 6 or 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") + end + local data +local name= o.name + local mtime= o.mtime or 0 + if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + else + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local files= {} + for _, it in __iter(items) do + if not it.entry.dir then + table.insert(files, it) + end + end + if #files == 1 and #items == 1 then + local b, err = files[1].read() + if not b then + return nil, err + end + data = b + name = name or files[1].entry.name + mtime = o.mtime or files[1].entry.mtime or 0 + else + -- several entries: a tar inside + local list = {} + for _, it in __iter(items) do + local e= it.entry + local b = nil + if not e.dir then + local rb, err = it.read() + if not rb then + return nil, err + end + b = rb + end + table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode }) + end + local t, terr = Tar.write(list) + if not t then + return nil, terr + end + data = t + end + end + if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then + mtime = 0 + end + local raw, cerr = Deflate.compress(data, { level = level }) + if not raw then + return nil, cerr + end + local w = Bytes.writer(buffer.len(raw) + 32 + ((name and((#name ))or(0)))) + w:string("\31\139\8") + w:u8(name and 8 or 0) + w:u32le(math.floor(mtime)) + w:u8(level >= 9 and 2 or(level <= 1 and 4 or 0)) + w:u8(255) + if name then + local z = string.find(name, "\0", 1, true) + w:cstring((z and{(string.sub(name, 1, z - 1) )}or{name})[1]) + end + w:bytes(raw) + w:u32le(Crc32.raw(data, 0, buffer.len(data))) + w:u32le(buffer.len(data) % 4294967296) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz) +function Gzip.new(data, name) +local a = Archive.new("gzip", function(arc, o) +return Gzip.encode(arc, o) + end) + a.meta.stream = true + a.meta.source = { format = "gzip" } + if data then + a:add(name or "data", data) + end + return a +end + +return Gzip +end +__FILES["archive/iso"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660: +-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories; +-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files. +-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts +-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El +-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one. +-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored +-- bytes), multi-session images (the first session). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Iso9660 = __include("containers/Iso9660") + +-- ------------------------------------------------------------------------------------------------ contract +local Iso = { + name = "iso", + category = "archive", + extensions = { "iso" }, + mime = { "application/x-iso9660-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" }, + caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + +function Iso.sniff(r) +return r:peek(5, 16 * 2048 + 1) == "CD001" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iso.decode(r, opts) +local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, info + end + local a = Archive.new("iso") + local b, limit = r.buf, r.limit + for _, e in __iter(list) do + local data = e.type == "0" and e.size > 0 + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + type = e.type, + mode = e.mode, + uid = e.uid, + gid = e.gid, + nlink = e.nlink, + link = e.link, + rdev = e.rdev, + hidden = e.hidden, + method = e.zisofs and"zisofs" or"store", + load = data +and function() +return Iso9660.extract(b, e, limit) + end +or nil, + }) + end + a.meta.boot = info.boot + info.boot = nil + a.meta.iso = info + a.meta.source = { format = "iso", tree = info.tree } + return a, nil +end + +return Iso +end +__FILES["archive/lha"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their +-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS +-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, +-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. +-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower +-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header +-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu +-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), +-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or +-- at the first header found in the first 64 KB). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lha = { + name = "lha", + category = "archive", + extensions = { "lzh", "lha", "lzs" }, + mime = { "application/x-lzh-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local METHODS= { + ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true, + ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true, + ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true, +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isHeader(s) +if #s < 22 then + return false + end + local m = string.sub(s, 3, 7) + local level = string.byte(s, 21) + return METHODS[m] == true and level <= 3 +end + +function Lha.sniff(r) +if isHeader(r:peek(22)) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) +local function path(s) +s = string.gsub(s, "[\\\255]", "/") + local parts = {} + for part in __iter(string.gmatch(s, "[^/]+")) do + if part ~= "." and part ~= ".." then + table.insert(parts, part) + end + end + return table.concat(parts, "/") .. (string.sub(s, -1) == "/" and #parts > 0 and"/" or"") +end + +-- the extended headers from offset p (size field width w), until a zero size; returns the end offset + + + + + + + + + + + + + + + + + + + + +local function extended(r, p, w, first, h, limit) +local size = first + local guard = 0 + while size ~= 0 do + guard =guard+ 1 + if guard > 4096 or size < w + 1 or p + size > limit then + return nil, "bad extended header" + end + local e = r:sub(p, size) + local kind = e:u8() + local body = size - 1 - w + if kind == 0x01 then + h.name = e:string(body) + elseif kind == 0x02 then + h.dir = e:string(body) + elseif kind == 0x3F or kind == 0x71 then + h.comment = e:string(body) + elseif kind == 0x40 and body >= 2 then + h.attr = e:u16le() + elseif kind == 0x50 and body >= 2 then + h.mode = e:u16le() + elseif kind == 0x51 and body >= 4 then + h.gid, h.uid = e:u16le(), e:u16le() + elseif kind == 0x52 then + h.gname = e:string(body) + elseif kind == 0x53 then + h.uname = e:string(body) + elseif kind == 0x54 and body >= 4 then + h.mtime = e:u32le() + elseif kind == 0x42 and body >= 16 then + h.packed, h.size = e:u64le(), e:u64le() + end + e:seek(size - w) + local nextSize = (w == 2 and{(e:u16le() )}or{(e:u32le() +)})[1] if e.err then + return nil, "truncated extended header" + end + p =p+ size + size = nextSize + end + return p, nil +end + +local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386", + [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", + [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } + +-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker +local function header(r, p) +local limit = r:size() + if p >= limit or r:sub(p, 1):u8() == 0 then + return nil, nil + end + if p + 22 > limit then + return nil, "truncated header" + end + local s = r:sub(p, 26) + local b0 = s:u8() + s:u8() + local method = s:string(5) + local packed, size, stamp = s:u32le(), s:u32le(), s:u32le() + s:u8() + local level = s:u8() + if not METHODS[method] then + return nil, "bad method " .. method + end + local h= { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 } + if level == 0 or level == 1 then + local hsize = b0 + 2 + if p + hsize > limit or hsize < 24 then + return nil, "truncated header" + end + local hr = r:sub(p + 21, hsize - 21) + local nlen = hr:u8() + h.name = hr:string(nlen) + h.crc = hr:u16le() + h.mtime = Archive.fromDos(stamp) + if level == 0 then + -- an optional Unix extension: 'U', mtime, mode, uid, gid + if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then + h.os = hr:u8() == 0x55 and"unix" or"os68k" + h.mtime = hr:u32le() + h.mode = hr:u16le() + h.uid, h.gid = hr:u16le(), hr:u16le() + end + h.dataAt = p + hsize + else + h.os = OS[hr:u8()] + local first = r:sub(p + hsize - 2, 2):u16le() + local e, err = extended(r, p + hsize, 2, first, h, limit) + if not e then + return nil, err + end + h.packed = packed - (e - (p + hsize)) + h.dataAt = e + end + if hr.err then + return nil, "truncated header" + end + elseif level == 2 then + local total = r:sub(p, 2):u16le() + local hr = r:sub(p + 21, 5) + h.crc = hr:u16le() + local osByte = hr:u8() + h.os = OS[osByte] + if osByte == 0x4B then + total =total+ 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates) + end + local first = hr:u16le() + h.mtime = stamp + local e, err = extended(r, p + 26, 2, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 26 or h.dataAt > limit then + return nil, "bad level 2 header size" + end + elseif level == 3 then + local hr = r:sub(p + 21, 11) + h.crc = hr:u16le() + h.os = OS[hr:u8()] + local total = hr:u32le() + local first = hr:u32le() + h.mtime = stamp + local e, err = extended(r, p + 32, 4, first, h, limit) + if not e or hr.err then + return nil, err or "truncated header" + end + h.dataAt = p + total + if total < 32 or h.dataAt > limit then + return nil, "bad level 3 header size" + end + else + return nil, "unsupported: header level " .. level + end + return h, nil +end + +local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" } + +local function encoder(a, o) +return Lha.encode(a, o) +end + +function Lha.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local p = 0 + -- a self-extracting stub: find the first header + if not isHeader(r:peek(22)) then + local head = r:peek(65536) + local at = nil + for k = 1, #head - 22 do + if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then + at = k - 1 + break + end + end + if not at then + return nil, Err.new(Err.CORRUPT, "no LHA header") + end + p = at + end + local a = Archive.new("lha", encoder) + local count = 0 + local levels = {} + while true do + local h, err = header(r, p) + if err then + return nil, Err.from(err, r.base + p) + end + if not h then + break + end + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + levels[h.level] = true + if h.packed < 0 or h.dataAt + h.packed > r:size() then + return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt) + end + -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do + local os = h.os + if os == nil or os == "msdos" or os == "atari" or os == "os2" then + if not string.find(h.name .. (h.dir or ""), "%l") then + h.name = string.lower(h.name) + h.dir = (h.dir and{(string.lower(h.dir) )}or{nil +})[1] end + end + -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers) + local name = path(h.name) + if h.dir and h.dir ~= "" then + local d = path(h.dir) + if string.sub(d, -1) ~= "/" then + d =d.. "/" + end + name = d .. name + end + local link= nil + local bar = string.find(name, "|", 1, true) + if bar then + name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1) + end + local isDir = h.method == "lhd" + if isDir and link == nil and string.sub(name, -1) ~= "/" then + name =name.. "/" + end + local e= { + name = name, + size = (isDir or link )and 0 or h.size, + compressedSize = h.packed, + method = h.method, + mtime = h.mtime, + dir = isDir and link == nil, + mode = h.mode, + uid = h.uid, + gid = h.gid, + uname = h.uname, + gname = h.gname, + attr = h.attr, + comment = h.comment, + os = h.os, + level = h.level, + crc = h.crc, + } + if link then + e.link = link + e.type = "symlink" + elseif not isDir and h.size > 0 then + if h.size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc + local buf, base = r.buf, r.base + e.load = function() +local out, derr +if method == "lh0" or method == "lz4" then + if packed < size then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(size) + buffer.copy(out , 0, buf, base + at, size) + elseif LZH_METHOD[method] then + out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method]) + else + return nil, Err.new(Err.UNSUPPORTED, "method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if crc and Crc16.arc(out, 0, size) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, e) + p = h.dataAt + h.packed + end + a.meta.source = { format = "lha", levels = levels } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lha.encode(value, opts) +local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out = Bytes.writer() + for _, it in __iter(items) do + local e= it.entry + local data = buffer.create(0) + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local full = string.gsub(e.name, "/+$", "") + local dirPart, base = string.match(full, "^(.*/)([^/]*)$") + if not dirPart then + dirPart, base = "", full + end + if e.dir then + dirPart, base = full .. "/", "" + end + local h = Bytes.writer() + h:u16le(0) -- total size, patched + h:string(e.dir and"-lhd-" or"-lh0-") + h:u32le(buffer.len(data)) + h:u32le(buffer.len(data)) + h:u32le((type(e.mtime) == "number" and e.mtime >= 0 and((math.floor(e.mtime) % 4294967296 ))or(0))) + h:u8(0x20) + h:u8(2) + h:u16le(Crc16.arc(data, 0, buffer.len(data))) + h:u8(0x55) -- 'U'nix + -- extended headers: [type][body][size of the next one]; the first size ends the base header + local exts= { { 0x00, "\0\0" }, { 0x01, base } } + if dirPart ~= "" then + table.insert(exts, { 0x02, (string.gsub(dirPart , "/", "\255")) }) + end + if type(e.mode) == "number" then + local m = bit32.band(e.mode, 0xFFF) + (e.dir and 0x4000 or 0x8000) + table.insert(exts, { 0x50, string.char(m % 256, math.floor(m / 256)) }) + end + h:u16le(#exts[1][2] + 3) + for i, x in __iter(exts) do + h:u8(x[1]) + h:string(x[2]) + h:u16le((exts[i + 1] and((#exts[i + 1][2] + 3 ))or(0))) + end + local hb = h:finish() + local total = buffer.len(hb) + if total > 65535 then + return nil, Err.new(Err.ARG, "header too long for " .. e.name) + end + buffer.writeu16(hb, 0, total) + -- the header CRC covers the whole header with its own field zero + local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27 + buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total)) + out:bytes(hb) + out:bytes(data) + end + out:u8(0) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) +function Lha.new() +local a = Archive.new("lha", encoder) + a.meta.source = { format = "lha" } + return a +end + +return Lha +end +__FILES["archive/lz4"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the +-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api +-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy +-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed +-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified +-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks +-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; +-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: +-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lz4 = __include("codecs/compress/Lz4") +local Xxh32 = __include("codecs/compress/Xxh32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lz4Format = { + name = "lz4", + category = "archive", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + +local MAGIC = 0x184D2204 +local LEGACY = 0x184C2102 +local LEGACY_BLOCK = 8 * 1048576 +local SIZES= { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lz4Format.sniff(r) +local m = r:peek(4) + if m == "\4\34\77\24" then + return 1 + elseif m == "\2\33\76\24" then + return 0.9 + elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then + -- a skippable frame (zstd shares the magic): an LZ4 frame after it + local h = r:peek(4, 4) + if #h == 4 then + local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216 + if r:peek(4, 8 + n) == "\4\34\77\24" then + return 1 + end + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function skippable(m) +return m >= 0x184D2A50 and m <= 0x184D2A5F +end + +-- room for k more bytes in the output (doubling, up to max) | false + + +local function room(out, k) +local need = out.n + k + if need > out.max then + return false + end + if need > buffer.len(out.buf) then + local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max)) + buffer.copy(nb, 0, out.buf, 0, out.n) + out.buf = nb + end + return true +end + +-- one LZ4 frame at p -> the input offset after it | nil, Err +local function frame(b, p, e, out, verify) +if p + 7 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) + end + local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5) + if bit32.rshift(flg, 6) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4) + end + if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then + return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4) + end + local independent = bit32.band(flg, 0x20) ~= 0 + local blockSum = bit32.band(flg, 0x10) ~= 0 + local hasSize = bit32.band(flg, 0x08) ~= 0 + local contentSum = bit32.band(flg, 0x04) ~= 0 + local hasDict = bit32.band(flg, 0x01) ~= 0 + local bmax = SIZES[bit32.rshift(bd, 4)] + if not bmax then + return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5) + end + local q = p + 6 + local size= nil + if hasSize then + if q + 8 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296 + q =q+ 8 + end + if hasDict then + return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q) + end + if q + 1 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255) + if hc ~= buffer.readu8(b, q) then + return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q) + end + q =q+ 1 + if size and out.n + size > out.max then + return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p) + end + local start = out.n + while true do + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "block header past the end", q) + end + local bs = buffer.readu32(b, q) + q =q+ 4 + if bs == 0 then + break + end + local raw = bit32.band(bs, 0x80000000) ~= 0 + local n = bit32.band(bs, 0x7FFFFFFF) + if n > bmax then + return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4) + end + if q + n + (blockSum and 4 or 0) > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then + return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n) + end + if not room(out, (raw and{n }or{bmax})[1]) and not room(out, (raw and{n }or{(math.min(bmax, out.max - out.n))})[1]) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + if raw then + buffer.copy(out.buf, out.n, b, q, n) + out.n =out.n+ n + else + local lim = math.min(out.n + bmax, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, (independent and{out.n }or{start})[1]) + if not dEnd then + if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + return nil, Err.from(msg, q) + end + out.n = dEnd + end + q =q+ (n + (blockSum and 4 or 0) +) end + if contentSum then + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q) + end + if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q) + end + q =q+ 4 + end + if size and out.n - start ~= size then + return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6) + end + return q, nil +end + +-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows +local function legacy(b, p, e, out) +local q = p + 4 + while q + 4 <= e do + local n = buffer.readu32(b, q) + if n == MAGIC or n == LEGACY or skippable(n) then + break + end + q =q+ 4 + if q + n > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim) + if not dEnd then + return nil, Err.from(msg, q) + end + out.n = dEnd + q =q+ n + end + return q, nil +end + +-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err +function Lz4Format.decompress(src, offset, length, opts) +local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + local verify = not (opts and opts.verify == false) + local out= { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes } + local p, e = o, o + n + local frames = 0 + while p + 4 <= e do + local m = buffer.readu32(b, p) + local q, err + if m == MAGIC then + q, err = frame(b, p, e, out, verify) + frames =frames+ 1 + elseif m == LEGACY then + q, err = legacy(b, p, e, out) + frames =frames+ 1 + elseif skippable(m) then + if p + 8 > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + q = p + 8 + buffer.readu32(b, p + 4) + if q > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + elseif frames > 0 then + break -- trailing data after the frames (as lz4 -d, which warns) + else + return nil, Err.new(Err.CORRUPT, "bad magic", p) + end + if not q then + return nil, err + end + p = q +end + if frames == 0 then + return nil, Err.new((n < 4 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no LZ4 frame", o) + end + local res = buffer.create(out.n) + buffer.copy(res, 0, out.buf, 0, out.n) + return res, nil +end + +local function encode(value, opts) +return Lz4Format.encode(value, opts) +end + +function Lz4Format.decode(r, opts) +local o= opts or {} + local n = r.limit - r.base + local out, err = Lz4Format.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("lz4", encode) + a.meta.stream = true + a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" } + local name = Archive.streamName(o, { "lz4" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and string.lower(ext) == "tlz4" then + name = stem .. ".tar" + end + Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- compress(data, opts?) -> one LZ4 frame | nil, Err +function Lz4Format.compress(data, opts) +local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) + if not b then + return nil, aerr + end + local op= opts or {} + local bsize = op.blockSize or 4194304 + local bd = nil + for k, v in __iter(SIZES) do + if v == bsize then + bd = k + end + end + if not bd then + return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304") + end + local blockSum = op.blockChecksum == true + local contentSum = op.contentChecksum ~= false + local withSize = op.contentSize == true + local w = Bytes.writer(n + math.floor(n / 200 )+ 64) + w:u32le(MAGIC) + local flg = 0x40 + 0x20 + (blockSum and 0x10 or 0) + (withSize and 0x08 or 0) + (contentSum and 0x04 or 0) + w:u8(flg) + w:u8(bd * 16) + if withSize then + w:u32le(n % 4294967296) + w:u32le(math.floor(n / 4294967296)) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255) + w:u8(hc) + local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1)))) + local p = o + while p < o + n do + local k = math.min(bsize, o + n - p) + local c = Lz4.encodeInto(b, p, k, scratch, 0) + local at = w.pos + if c < k then + w:u32le(c) + local q = w:reserve(c) + buffer.copy(w.buf, q, scratch, 0, c) + w.pos = q + c + else + w:u32le(k + 0x80000000) + local q = w:reserve(k) + buffer.copy(w.buf, q, b, p, k) + w.pos = q + k + end + if blockSum then + local len = w.pos - at - 4 + w:u32le(Xxh32.hash(w.buf, at + 4, len)) + end + p =p+ k + end + w:u32le(0) + if contentSum then + w:u32le(Xxh32.hash(b, o, n)) + end + return w:finish(), nil +end + +-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame +function Lz4Format.encode(value, opts) +local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return Lz4Format.compress(data, opts) +end + +return Lz4Format +end +__FILES["archive/macbinary"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags, +-- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III +-- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its +-- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry +-- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / +-- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the +-- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Archive = __include("containers/Archive") +local MacFile = __include("containers/MacFile") + +-- ------------------------------------------------------------------------------------------------ contract +local MacBinary = { + name = "macbinary", + category = "archive", + extensions = { "bin", "macbin" }, + mime = { "application/x-macbinary" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" }, + caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o + + + +local function version(b, o, len) +if len < 128 then + return nil + end + local u8 = function(i) +return buffer.readu8(b, o + i) + end + if u8(0) ~= 0 or u8(74) ~= 0 then + return nil + end + local nameLen = u8(1) + if nameLen < 1 or nameLen > 63 then + return nil + end + local function be32(i) +return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3) + end + local dlen, rlen = be32(83), be32(87) + if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then + return nil + end + local crc = u8(124) * 256 + u8(125) + if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then + return buffer.readstring(b, o + 102, 4) == "mBIN" and"III" or"II" + end + if buffer.readstring(b, o + 102, 4) == "mBIN" then + return nil -- III with a bad CRC + end + -- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file + if u8(82) ~= 0 then + return nil + end + for i = 99, 125 do + if u8(i) ~= 0 then + return nil + end + end + local need = 128 + math.ceil(dlen / 128) * 128 + rlen + return need <= len + 127 and"I" or nil +end + +function MacBinary.sniff(r) +local n = math.min(r:remaining(), 128) + if n < 128 then + return 0 + end + local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + return v == "III" and 0.95 or(v == "II" and 0.8 or(v == "I" and 0.3 or 0 +))end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a, o) +return MacBinary.encode(a, o) +end + +local function pad(n) +return math.ceil(n / 128) * 128 +end + +function MacBinary.decode(r, opts) +local o= opts or {} + local len = r.limit - r.base + local v = version(r.buf, r.base, len) + if not v then + if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch") + end + return nil, Err.new((len < 128 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a MacBinary header") + end + local h = r:sub(0, 128) + h:seek(1) + local name = h:string(h:u8()) + h:seek(65) + local ftype, creator = h:string(4), h:string(4) + local flagsHi = h:u8() + h:seek(83) + local dlen, rlen = h:u32be(), h:u32be() + local created, modified = h:u32be(), h:u32be() + local commentLen = h:u16be() + local flagsLo = h:u8() + h:seek(120) + local secondary = h:u16be() + if v == "I" then + commentLen, flagsLo, secondary = 0, 0, 0 + end + if dlen + rlen > (o.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "forks larger than maxBytes") + end + r:seek(128 + pad(secondary)) + local data = r:bytes(dlen) + r:seek(128 + pad(secondary) + pad(dlen)) + local rsrc = r:bytes(rlen) + local comment= nil + if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then + comment = MacFile.name(r:string(math.min(commentLen, r:remaining()))) + end + if r.err then + return nil, r.err + end + local a = Archive.new("macbinary", encoder) + MacFile.put(a, { + name = MacFile.name(name), + data = data, + rsrc = rsrc, + type = ftype, + creator = creator, + flags = flagsHi * 256 + flagsLo, + created = MacFile.fromMac(created), + modified = MacFile.fromMac(modified), + comment = comment, + }) + a.meta.stream = rlen == 0 + a.meta.source = { format = "macbinary", version = v } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function MacBinary.encode(value, opts) +local o= opts or {} + local files, err = MacFile.collect(value, o.name) + if not files then + return nil, err + end + local f = files[1] + if not f then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local name = MacFile.roman(f.name) + if #name < 1 or #name > 63 then + return nil, Err.new(Err.ARG, "the name must be 1..63 bytes") + end + local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc) + local comment = (f.comment and{(MacFile.roman(f.comment) )}or{"" +})[1] local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment) + buffer.writeu8(out, 1, #name) + buffer.writestring(out, 2, name) + buffer.writestring(out, 65, f.type) + buffer.writestring(out, 69, f.creator) + buffer.writeu8(out, 73, bit32.rshift(f.flags, 8)) + local function be32(at, v) + buffer.writeu32(out, at, bit32.byteswap(v)) + end + be32(83, dlen) + be32(87, rlen) + be32(91, MacFile.toMac(f.created or f.modified)) + be32(95, MacFile.toMac(f.modified)) + buffer.writeu8(out, 99, bit32.rshift(#comment, 8)) + buffer.writeu8(out, 100, bit32.band(#comment, 255)) + buffer.writeu8(out, 101, bit32.band(f.flags, 255)) + buffer.writestring(out, 102, "mBIN") + buffer.writeu8(out, 122, 130) + buffer.writeu8(out, 123, 129) + local crc = Crc16.ccitt(out, 0, 124) + buffer.writeu8(out, 124, bit32.rshift(crc, 8)) + buffer.writeu8(out, 125, bit32.band(crc, 255)) + buffer.copy(out, 128, f.data) + buffer.copy(out, 128 + pad(dlen), f.rsrc) + buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork +function MacBinary.new() +local a = Archive.new("macbinary", encoder) + a.meta.source = { format = "macbinary" } + return a +end + +return MacBinary +end +__FILES["archive/mpq"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the +-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset +-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block +-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block +-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded +-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 +-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks +-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive +-- Format", and StormLib's documentation); no code taken. +-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET +-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, +-- writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Deflate = __include("codecs/compress/Deflate") +local Bzip2 = __include("codecs/compress/Bzip2") +local Lzma = __include("codecs/compress/Lzma") +local Explode = __include("codecs/compress/Explode") +local Crypt = __include("archive/mpq/Crypt") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpq = { + name = "mpq", + category = "archive", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 +local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 +local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) +local TWO32 = 4294967296 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpq.sniff(r) +local m = r:peek(4) + if m == "MPQ\x1A" or m == "MPQ\x1B" then + return 1 + end + -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB + for at = 512, math.min(65536, r:remaining() - 32), 512 do + if r:peek(4, at) == "MPQ\x1A" then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros +local function unsparse(b, at, n, want) +local out = buffer.create(want) + local p, stop, o = at + 4, at + n, 0 + while p < stop and o < want do + local c = buffer.readu8(b, p) + p =p+ 1 + if c >= 0x80 then + local k = c - 0x7F + if p + k > stop then + return nil, "sparse run past the end" + end + k = math.min(k, want - o) + buffer.copy(out, o, b, p, k) + p =p+ k + o =o+ k + else + o = math.min(want, o + c + 3) + end + end + return out, nil +end + +-- one compressed sector (mask byte first) -> want bytes +local function decompress(b, at, n, want) +if n < 1 then + return nil, Err.new(Err.CORRUPT, "empty compressed sector") + end + local mask = buffer.readu8(b, at) + local cur, cat, cn= b, at + 1, n - 1 + if mask == 0x12 then + if cn < 14 or buffer.readu8(b, cat) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") + end + local props = buffer.readstring(b, cat + 1, 5) + local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) + if not out then + return nil, e + end + return out, nil + end + if band(mask, 0xC1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) + end + if band(mask, 0x10) ~= 0 then + local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x08) ~= 0 then + local out, e = Explode.decompress(cur, cat, cn, want) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x02) ~= 0 then + local out, e = Deflate.zlib(cur, cat, cn) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x20) ~= 0 then + local out, msg = unsparse(cur, cat, cn, want) + if not out then + return nil, Err.from(msg) + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x3A) ~= mask then + return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) + end + if cn ~= want then + return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) + end + if cur == b then + local len = cn +local copy = buffer.create(len) + buffer.copy(copy, 0, b, cat, len) + return copy, nil + end + return cur, nil +end + +-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) + + +local function readFile(b, limit, blk, at, name, sectorSize, maxBytes) +local flags = blk.flags + if band(flags, FLAG_PATCH) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "patch files") + end + if blk.size > maxBytes then + return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") + end + if at + blk.csize > limit then + return nil, Err.new(Err.TRUNCATED, "file data past the end") + end + local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 + local key = 0 + if encrypted then + if not name then + return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") + end + key = Crypt.hash(Crypt.baseName(name), 3) + if band(flags, FLAG_FIX_KEY) ~= 0 then + key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) + end + end + local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 + local imploded = band(flags, FLAG_IMPLODE) ~= 0 + local function sector(src, sat, sn, want, k) +local raw = buffer.create(sn) + buffer.copy(raw, 0, src, sat, sn) + if encrypted then + Crypt.decrypt(raw, 0, sn, k) + end + if compressed and sn < want then + if imploded then + return Explode.decompress(raw, 0, sn, want) + end + return decompress(raw, 0, sn, want) + end + if sn ~= want then + if sn > want then + local cut = buffer.create(want) + buffer.copy(cut, 0, raw, 0, want) + return cut, nil + end + return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) + end + return raw, nil + end + if band(flags, FLAG_SINGLE) ~= 0 then + local out, e = sector(b, at, blk.csize, blk.size, key) + if out and buffer.len(out) ~= blk.size then + return nil, Err.new(Err.CORRUPT, "file size mismatch") + end + return out, e + end + local out = buffer.create(blk.size) + local nsec = math.floor((blk.size + sectorSize - 1) / sectorSize +) if not compressed then + -- stored in sectors (each decrypted with key + its index) + for i = 0, nsec - 1 do + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + i * sectorSize, want, want, key + i) + if not s then + return nil, e + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil + end + local entries = nsec + 1 + (band(flags, FLAG_CRC) ~= 0 and 1 or 0) + if entries * 4 > blk.csize then + return nil, Err.new(Err.CORRUPT, "sector table larger than the file") + end + local tbl = buffer.create(entries * 4) + buffer.copy(tbl, 0, b, at, entries * 4) + if encrypted then + Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) + end + for i = 0, nsec - 1 do + local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) + if s1 < s0 or s1 > blk.csize then + return nil, Err.new(Err.CORRUPT, "bad sector offset table") + end + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + s0, s1 - s0, want, key + i) + if not s then + return nil, e + end + if buffer.len(s) ~= want then + return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil +end + +local function encode(_archive, _opts) +return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") +end + +-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil +local function findHeader(r) +local size = r.limit - r.base + local p = 0 + while p + 32 <= size do + local m = buffer.readstring(r.buf, r.base + p, 4) + if m == "MPQ\x1A" then + return p + elseif m == "MPQ\x1B" and p + 12 <= size then + local at = p + buffer.readu32(r.buf, r.base + p + 8) + if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then + return at + end + end + p =p+ 512 + end + return nil +end + +function Mpq.decode(r, opts) +local found = findHeader(r) + if not found then + return nil, Err.new((r:remaining() < 32 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no MPQ header", 0) + end + local h= found + local hr = r:sub(h) + hr:skip(4) + local headerSize, archiveSize = hr:u32le(), hr:u32le() + local version, shift = hr:u16le(), hr:u16le() + local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() + local hiBlockPos, hashHi, blockHi = 0, 0, 0 + if version >= 1 and headerSize >= 44 then + hiBlockPos = hr:u64le() + hashHi, blockHi = hr:u16le(), hr:u16le() + end + if hr.err then + return nil, hr.err + end + if shift > 20 then + return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) + end + local sectorSize = 512 * 2 ^ shift + if hashCount == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") + end + local maxEntries= opts and opts.maxEntries or 1e6 + if hashCount > maxEntries * 4 or blockCount > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local size = r.limit - r.base + local hashAt = h + hashPos + hashHi * TWO32 + local blockAt = h + blockPos + blockHi * TWO32 + if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then + return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) + end + local hashes = buffer.create(hashCount * 16) + buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) + Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) + local blocksBuf = buffer.create(blockCount * 16) + buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) + Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) + local hiAt = (hiBlockPos > 0 and((h + hiBlockPos ))or((-1 +))) if hiAt >= 0 and hiAt + blockCount * 2 > size then + hiAt = -1 + end + local blocks= {} + for i = 0, blockCount - 1 do + local hi = (hiAt >= 0 and{(buffer.readu16(r.buf, r.base + hiAt + i * 2) )}or{0 +})[1] blocks[i + 1] = { + offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, + csize = buffer.readu32(blocksBuf, i * 16 + 4), + size = buffer.readu32(blocksBuf, i * 16 + 8), + flags = buffer.readu32(blocksBuf, i * 16 + 12), + } + end + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local mask = hashCount - 1 + local pow2 = band(hashCount, mask) == 0 + -- lookup(name) -> block index (1-based) | nil + local function lookup(name) +local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) + local start = (pow2 and{(band(h0, mask) )}or{(h0 % hashCount +)})[1] for k = 0, hashCount - 1 do + local o = ((start + k) % hashCount) * 16 + local bi = buffer.readu32(hashes, o + 12) + if bi == 0xFFFFFFFF then + return nil + end + if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then + return bi + 1 + end + end + return nil + end + local function usable(bi) +local f = blocks[bi].flags + return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 + end + local function blockData(bi, name) +local blk = blocks[bi] + return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) + end + -- names: (listfile) and opts.names + local names= {} + for _, internal in __iter({ "(attributes)", "(signature)", "(user data)" }) do + table.insert(names, internal) + end + local lf = lookup("(listfile)") + if lf and usable(lf) then + table.insert(names, "(listfile)") + local data = blockData(lf, "(listfile)") + if data then + for line in __iter(string.gmatch(buffer.tostring(data), "[^\r\n;]+")) do + local nm = string.match(line, "^%s*(.-)%s*$") + if nm and nm ~= "" then + table.insert(names, nm) + end + end + end + end + if opts and type(opts.names) == "table" then + for _, nm in __iter(opts.names) do + if type(nm) == "string" then + table.insert(names, nm) + end + end + end + local a = Archive.new("mpq", encode) + local named= {} + local function add(bi, name) + local blk = blocks[bi] + local entryName = name or string.format("File%08d.xxx", bi - 1) + Archive.put(a, { + name = entryName, + size = blk.size, + compressedSize = blk.csize, + dir = false, + method = band(blk.flags, FLAG_IMPLODE) ~= 0 and"implode" or(band(blk.flags, FLAG_COMPRESS) ~= 0 and"compress" or"store"), + encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, + flags = blk.flags, + block = bi - 1, + load = function() +return blockData(bi, name) + end, + }) + end + for _, nm in __iter(names) do + local bi = lookup(nm) + if bi and usable(bi) and not named[bi] then + named[bi] = nm + add(bi, nm) + end + end + for bi = 1, blockCount do + if not named[bi] and usable(bi) and blocks[bi].size > 0 then + add(bi, nil) + end + end + a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) +Mpq.hash = Crypt.hash + +return Mpq +end +__FILES["archive/mpq/Crypt"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file +-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois +-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every +-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot + +local Crypt = {} + +local TWO32 = 4294967296 +local TABLE = buffer.create(0x500 * 4) +do + local seed = 0x00100001 + for i1 = 0, 255 do + local i2 = i1 + for _ = 0, 4 do + seed = (seed * 125 + 3) % 0x2AAAAB + local t1 = band(seed, 0xFFFF) * 65536 + seed = (seed * 125 + 3) % 0x2AAAAB + local t2 = band(seed, 0xFFFF) + writeu32(TABLE, i2 * 4, t1 + t2) + i2 =i2+ 0x100 + end + end +end + +-- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +function Crypt.hash(name, kind) +local s1, s2 = 0x7FED7FED, 0xEEEEEEEE + local base = kind * 0x100 + for i = 1, #name do + local c = string.byte(name, i) + if c >= 97 and c <= 122 then + c =c- 32 + elseif c == 47 then + c = 92 + end + s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) + s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 + end + return s1 +end + +-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +function Crypt.decrypt(buf, at, n, key) + local s2 = 0xEEEEEEEE + local k = key % TWO32 + for i = 0, math.floor(n / 4 )- 1 do + local o = at + i * 4 + s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 + local ch = bxor(readu32(buf, o), (k + s2) % TWO32) + k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) + s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 + writeu32(buf, o, ch) + end +end + +-- base name of an archived path (the file key uses it) +function Crypt.baseName(name) +return string.match(name, "([^\\/]*)$") or name +end + +return Crypt +end +__FILES["archive/pak"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the +-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored +-- bytes) and written from any Archive value. Written from the format description in the Quake source release +-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. +-- Not supported: Daikatana's compressed PAK entries. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Pak = { + name = "pak", + category = "archive", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + +local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Pak.sniff(r) +if r:remaining() < 12 then + return 0 + end + return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive, opts) +return Pak.encode(archive, opts) +end + +function Pak.decode(r, opts) +local magic = r:string(4) + local dirOfs, dirLen = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + local variant = magic == "PACK" and"quake" or(magic == "SPAK" and"sin" or nil +) if not variant then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local nameLen = VARIANTS[variant].nameLen + local entrySize = nameLen + 8 + local size = r.limit - r.base + if dirOfs + dirLen > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) + end + if dirLen % entrySize ~= 0 then + return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) + end + local count = math.floor(dirLen / entrySize +) if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + local a = Archive.new("pak", encode) + local d = r:sub(dirOfs, dirLen) + for i = 0, count - 1 do + local name = d:fixed(nameLen) + local at, n = d:u32le(), d:u32le() + if d.err then + return nil, d.err + end + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + end + a.meta.source = { format = "pak", variant = variant, entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pak.encode(archive, opts) +local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local variant = opts and opts.variant or ((type(src) == "table" and src.format == "pak" and{src.variant }or{nil})[1]) or "quake" + local v = VARIANTS[variant] + if not v then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local files= {} + for _, it in __iter(items) do + if not it.entry.dir then + local name = string.gsub(it.entry.name, "\\", "/") + if #name >= v.nameLen then + return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(v.magic) + w:u32le(0) + w:u32le(0) + local offsets= {} + for i, f in __iter(files) do + offsets[i] = w:tell() + w:bytes(f.data) + end + local dirOfs = w:tell() + for i, f in __iter(files) do + w:string(f.name) + w:fill(0, v.nameLen - #f.name) + w:u32le(offsets[i]) + w:u32le(buffer.len(f.data)) + end + w:setU32le(4, dirOfs) + w:setU32le(8, w:tell() - dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() +function Pak.new(variant) +local a = Archive.new("pak", encode) + a.meta.source = { format = "pak", variant = variant or "quake" } + return a +end + +return Pak +end +__FILES["archive/rpm"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature +-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in +-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with +-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload +-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed +-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not +-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package +-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio" +-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local Lzma = __include("codecs/compress/Lzma") +local Zstd = __include("codecs/compress/Zstd") +local Bzip2 = __include("codecs/compress/Bzip2") +local Archive = __include("containers/Archive") +local Cpio = __include("containers/Cpio") + +-- ------------------------------------------------------------------------------------------------ contract +local Rpm = { + name = "rpm", + category = "archive", + extensions = { "rpm" }, + mime = { "application/x-rpm" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" }, + caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local LEAD_MAGIC = "\237\171\238\219" +local HEADER_MAGIC = "\142\173\232\1" +local RPMFILE_GHOST = 64 + +-- the tags meta.rpm names +local NAMES= { + [1000] = "name", + [1001] = "version", + [1002] = "release", + [1003] = "epoch", + [1004] = "summary", + [1005] = "description", + [1006] = "buildtime", + [1007] = "buildhost", + [1009] = "size", + [1010] = "distribution", + [1011] = "vendor", + [1014] = "license", + [1015] = "packager", + [1016] = "group", + [1020] = "url", + [1021] = "os", + [1022] = "arch", + [1044] = "sourcerpm", + [1047] = "provides", + [1049] = "requires", + [1124] = "payloadFormat", + [1125] = "payloadCompressor", + [1126] = "payloadFlags", + [5009] = "longsize", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Rpm.sniff(r) +return r:peek(4) == LEAD_MAGIC and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a header structure at p -> { [tag] = value }, end offset | nil, Err +local function header(b, p, e) +if p + 16 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local n = bit32.byteswap(buffer.readu32(b, p + 8)) + local hsize = bit32.byteswap(buffer.readu32(b, p + 12)) + local index = p + 16 + local store = index + n * 16 + if n > 0x10000 or hsize > 0x10000000 then + return nil, Err.new(Err.LIMIT, "header too large", p) + end + if store + hsize > e then + return nil, Err.new(Err.TRUNCATED, "header data past the end", p) + end + local tags= {} + local se = store + hsize + for i = 0, n - 1 do + local q = index + i * 16 + local tag = bit32.byteswap(buffer.readu32(b, q)) + local typ = bit32.byteswap(buffer.readu32(b, q + 4)) + local off = bit32.byteswap(buffer.readu32(b, q + 8)) + local count = bit32.byteswap(buffer.readu32(b, q + 12)) + local d = store + off + if off > hsize then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local width = (typ == 2 or typ == 1 )and 1 or(typ == 3 and 2 or(typ == 4 and 4 or(typ == 5 and 8 or 0 +))) if width > 0 then + if d + count * width > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + local v = table.create(count) + for k = 0, count - 1 do + local x = d + k * width + v[k + 1] = (width == 1 and{(buffer.readu8(b, x) +)}or{(width == 2 and{(bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1)) +)}or{(width == 4 and{(bit32.byteswap(buffer.readu32(b, x)) +)}or{(bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4)) +)})[1]})[1]})[1] end + tags[tag] = v + elseif typ == 7 then + if d + count > se then + return nil, Err.new(Err.CORRUPT, "tag data outside the header", q) + end + tags[tag] = buffer.readstring(b, d, count) + elseif typ == 6 or typ == 8 or typ == 9 then + local v = {} + local s = d + local want = typ == 6 and 1 or count + if want > hsize then + return nil, Err.new(Err.CORRUPT, "bad string count", q) + end + for _ = 1, want do + local z = s + while z < se and buffer.readu8(b, z) ~= 0 do + z =z+ 1 + end + if z >= se then + return nil, Err.new(Err.CORRUPT, "unterminated string", s) + end + table.insert(v, buffer.readstring(b, s, z - s)) + s = z + 1 + end + tags[tag] = (typ == 6 and{v[1] }or{v +})[1] end + end + return tags, se +end + +-- the file list of the header: { name, size, mode, mtime, link, user, group, flags } +local function files(tags) +local names= {} + local bn, dn, di = tags[1117], tags[1118], tags[1116] + if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then + for i, base in __iter(bn) do + local d = dn[(di[i] or 0) + 1] + names[i] = ((type(d) == "string" and{d }or{""})[1]) .. base + end + elseif type(tags[1027]) == "table" then + names = tags[1027] + end + local sizes = tags[5008] or tags[1028] or {} + local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {} + local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {} + local out = {} + for i, n in __iter(names) do + table.insert(out, { + name = n, + size = sizes[i] or 0, + mode = modes[i] or 0, + mtime = mtimes[i] or 0, + link = (links[i] and links[i] ~= "" and{links[i] }or{nil})[1], + user = users[i], + group = groups[i], + flags = flags[i] or 0, + }) + end + return out +end + +local function strip(name) +return (string.gsub(name, "^%.?/+", "")) +end + +-- the payload: decompressed, then its cpio entries by stripped name +local function payload(b, p, e, compressor, o) +local n = e - p + local opts= { maxBytes = o.maxBytes or 2 ^ 30 } + local raw, err +local m = (n >= 6 and{(buffer.readstring(b, p, 6) )}or{"" +})[1] if string.sub(m, 1, 2) == "\31\139" then + raw, err = Deflate.gunzip(b, p, n) + elseif m == "\253" .. "7zXZ\0" then + raw, err = Lzma.xz(b, p, n, opts) + elseif string.sub(m, 1, 3) == "BZh" then + raw, err = Bzip2.decompress(b, p, n, opts) + elseif string.sub(m, 1, 4) == "\40\181\47\253" then + raw, err = Zstd.decompress(b, p, n, opts) + elseif compressor == "lzma" then + raw, err = Lzma.alone(b, p, n, opts) + elseif string.sub(m, 1, 5) == "07070" then + raw = buffer.create(n) + buffer.copy(raw , 0, b, p, n) + else + return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p) + end + if not raw then + return nil, err + end + if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then + return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)") + end + local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries }) + if not list then + return nil, cerr + end + local by = {} + for _, ent in __iter(list) do + by[strip(ent.name)] = ent + end + return { buf = raw, by = by }, nil +end + +function Rpm.decode(r, opts) +local o= opts or {} + local b, base, e = r.buf, r.base, r.limit + if e - base < 96 then + return nil, Err.new(Err.TRUNCATED, "lead past the end", base) + end + if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad lead magic", base) + end + local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5) + local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7)) + local leadName = buffer.readstring(b, base + 10, 66) + leadName = (string.match(leadName, "^[^%z]*") ) +if major < 3 then + return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4) + end + local sig, sigEnd = header(b, base + 96, e) + if not sig then + return nil, sigEnd + end + local hp = base + math.floor((sigEnd - base + 7) / 8 )* 8 + local tags, hEnd = header(b, hp, e) + if not tags then + return nil, hEnd + end + local a = Archive.new("rpm") + local info= { tags = tags, signature = sig, type = kind == 1 and"source" or"binary", lead = { major = major, minor = minor, name = leadName } } + for tag, key in __iter(NAMES) do + local v = tags[tag] + if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value + v = v[1] + end + info[key] = v + end + a.meta.rpm = info + a.meta.source = { format = "rpm", compressor = info.payloadCompressor } + if info.payloadFormat and info.payloadFormat ~= "cpio" then + return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd) + end + local cache= nil + local cacheErr= nil + local function entry(name) +if not cache and not cacheErr then + cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o) + end + if not cache then + return nil, cacheErr + end + local ent = cache.by[name] + if not ent then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload") + end + return ent, nil + end + local list = files(tags) + if #list > (o.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many files") + end + for _, f in __iter(list) do +local __DARKLUA_CONTINUE_9=false repeat if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then +__DARKLUA_CONTINUE_9=true break + end + local name = strip(f.name) + local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0" + local data = typ == "0" and f.size > 0 + Archive.put(a, { + name = name, + size = (data and{f.size }or{0})[1], + dir = typ == "5", + mtime = f.mtime, + mode = bit32.band(f.mode, 0xFFF), + type = typ, + link = (typ == "2" and{f.link }or{nil})[1], + uname = f.user, + gname = f.group, + method = (info.payloadCompressor and{info.payloadCompressor }or{"store"})[1], + load = data +and function() +local ent, err = entry(name) + if not ent then + return nil, err + end + local out = buffer.create(ent.size) + buffer.copy(out, 0, cache.buf, ent.offset, ent.size) + return out, nil + end +or nil, + }) +__DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err +function Rpm.cpio(r, opts) +local a, err = Rpm.decode(r, opts) + if not a then + return nil, err + end + local p = r.base + 96 + local _, sigEnd = header(r.buf, p, r.limit) + local hp = r.base + math.floor((sigEnd - r.base + 7) / 8 )* 8 + local _, hEnd = header(r.buf, hp, r.limit) + local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {}) + if not pl then + return nil, perr + end + return pl.buf, nil +end + +return Rpm +end +__FILES["archive/tar"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value +-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() + +-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which +-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format). +-- Not supported: sparse files, multi-volume archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Archive = __include("containers/Archive") +local Tar = __include("containers/Tar") + +-- ------------------------------------------------------------------------------------------------ contract +local TarFormat = { + name = "tar", + category = "archive", + extensions = { "tar" }, + mime = { "application/x-tar" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" }, + caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + +function TarFormat.sniff(r) +if r:remaining() < 512 then + return 0 + end + if not Tar.valid(r.buf, r.pos) then + return 0 + end + return r:peek(5, 257) == "ustar" and 0.95 or 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function lazy(b, at, n) +return function() +local out = buffer.create(n) + buffer.copy(out, 0, b, at, n) + return out, nil + end +end + +local function encode(archive, opts) +return TarFormat.encode(archive, opts) +end + +function TarFormat.decode(r, opts) +local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts) + if not list then + return nil, err + end + local a = Archive.new("tar", encode) + for _, e in __iter(list) do + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + mode = e.mode, + uid = e.uid, + gid = e.gid, + uname = e.uname, + gname = e.gname, + type = e.type, + link = e.link, + method = "store", + load = ((e.dir or e.size == 0 )and{nil }or{(lazy(r.buf, e.offset, e.size))})[1], + }) + end + a.meta.source = { format = "tar" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function TarFormat.encode(archive, opts) +local items = Archive.entries(archive) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local list= {} + for _, it in __iter(items) do + local e= it.entry + local data= nil + if not e.dir and e.type ~= "1" and e.type ~= "2" then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(list, { + name = e.name, + data = data, + dir = e.dir, + type = (type(e.type) == "string" and #e.type == 1 and{e.type }or{nil})[1], + link = (type(e.link) == "string" and{e.link }or{nil})[1], + mode = (type(e.mode) == "number" and{e.mode }or{nil})[1], + uid = (type(e.uid) == "number" and{e.uid }or{nil})[1], + gid = (type(e.gid) == "number" and{e.gid }or{nil})[1], + uname = (type(e.uname) == "string" and{e.uname }or{nil})[1], + gname = (type(e.gname) == "string" and{e.gname }or{nil})[1], + mtime = (type(e.mtime) == "number" and{e.mtime }or{nil})[1], + }) + end + return Tar.write(list, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write() +function TarFormat.new() +local a = Archive.new("tar", encode) + a.meta.source = { format = "tar" } + return a +end + +return TarFormat +end +__FILES["archive/uu"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin <mode> <name>" block of a +-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode); +-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each +-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and +-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils +-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings +-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Uu = { + name = "uu", + category = "archive", + extensions = { "uu", "uue", "xxe", "b64" }, + mime = { "text/x-uuencode" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +local XX_VALUE= {} +for i = 1, 64 do + XX_VALUE[string.byte(XX, i)] = i - 1 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Uu.sniff(r) +local head = r:peek(4096) + if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then + return 0.9 + end + if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the value of character c in a variant, or nil +local function value(c, xx) +if xx then + return XX_VALUE[c] + end + if c >= 32 and c <= 96 then + return bit32.band(c - 32, 63) + end + return nil +end + +-- does a data line fit the variant: every character valid and the length matching the count character +local function fits(line, xx) +local n = value(string.byte(line, 1) or 0, xx) + if not n then + return false + end + local need = math.ceil(n / 3) * 4 + if #line - 1 < need or #line - 1 > need + 2 then + return false + end + for i = 2, need + 1 do + if not value(string.byte(line, i), xx) then + return false + end + end + return true +end + +-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line) +local function decodeLines(lines, xx, maxBytes) +local total = 0 + for _, l in __iter(lines) do + total =total+ (value(string.byte(l, 1) or 0, xx) or 0 +) end + if total > maxBytes then + return nil, "limit: data larger than maxBytes" + end + local out = buffer.create(total) + local o = 0 + for li, l in __iter(lines) do + local n = value(string.byte(l, 1) or 0, xx) or 0 + local p = 2 + local left = n + while left > 0 do + local a = value(string.byte(l, p) or 0, xx) + local b = value(string.byte(l, p + 1) or 0, xx) + local c = value(string.byte(l, p + 2) or 0, xx) or 0 + local d = value(string.byte(l, p + 3) or 0, xx) or 0 + if not a or not b then + return nil, "bad character in line " .. li + end + local v = a * 262144 + b * 4096 + c * 64 + d + for k = 2, 0, -1 do + if left > 0 then + buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255)) + o =o+ 1 + left =left- 1 + end + end + p =p+ 4 + end + end + return out, nil +end + + + +local function parse(text, maxBytes) +local lines = string.split(text, "\n") + local blocks= {} + local i = 1 + while i <= #lines do + local line = string.gsub(lines[i], "\r$", "") + local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$") + if not b64 then + mode, name = string.match(line, "^begin ([0-7]+) (.+)$") + end + if mode and name then + local body= {} + local closed = false + i =i+ 1 + while i <= #lines do + local l = string.gsub(lines[i], "\r$", "") + if (b64 and l == "====") or (not b64 and l == "end") then + closed = true + break + end + table.insert(body, l) + i =i+ 1 + end + if not closed then + return nil, "truncated: block " .. name .. " has no end line" + end + local data, variant + if b64 then + local d, err = Base64.decode(table.concat(body)) + if not d then + return nil, "block " .. name .. ": " .. tostring(err) + end + data, variant = d, "base64" + else + -- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines + local data_lines= {} + for _, l in __iter(body) do + if l ~= "" then + table.insert(data_lines, l) + end + end + local uuOk, xxOk = true, true + for _, l in __iter(data_lines) do + uuOk = uuOk and fits(l, false) + xxOk = xxOk and fits(l, true) + end + local xx = xxOk and not uuOk + if not uuOk and not xxOk then + return nil, "block " .. name .. ": lines are neither uuencode nor xxencode" + end + local d, err = decodeLines(data_lines, xx, maxBytes) + if not d then + return nil, err + end + data, variant = d, xx and"xx" or"uu" + end + table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data }) + end + i =i+ 1 + end + if #blocks == 0 then + return nil, "no begin line" + end + return blocks, nil +end + +local function encoder(a, o) +return Uu.encode(a, o) +end + +function Uu.decode(r, opts) +local o= opts or {} + local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30) + if not blocks then + return nil, Err.from(err) + end + local a = Archive.new("uu", encoder) + for _, b in __iter(blocks) do + Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data }) + end + a.meta.stream = #a:list() == 1 + a.meta.source = { format = "uu", variant = blocks[1].variant } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function encodeLines(data, xx, out) + local n = buffer.len(data) + local function ch(v) +if xx then + return string.sub(XX, v + 1, v + 1) + end + return v == 0 and"`" or string.char(v + 32) + end + local p = 0 + while p < n do + local len = math.min(45, n - p) + local parts = { ch(len) } + for q = p, p + len - 1, 3 do + local b0 = buffer.readu8(data, q) + local b1 = (q + 1 < p + len and{(buffer.readu8(data, q + 1) )}or{0 +})[1] local b2 = (q + 2 < p + len and{(buffer.readu8(data, q + 2) )}or{0 +})[1] local v = b0 * 65536 + b1 * 256 + b2 + table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63))) + end + table.insert(out, table.concat(parts)) + p =p+ len + end + table.insert(out, ch(0)) +end + +function Uu.encode(value, opts) +local o= opts or {} + local variant = o.variant or "uu" + if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then + return nil, Err.new(Err.ARG, "variant must be uu, xx or base64") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local out= {} + for _, f in __iter(files) do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local mode = (type(f.entry.mode) == "number" and{f.entry.mode }or{(o.mode or 0x1A4) +})[1] local m = string.format("%o", bit32.band(mode, 0xFFF)) + if variant == "base64" then + table.insert(out, "begin-base64 " .. m .. " " .. f.name) + local s = Base64.encode(f.data) + for p = 1, #s, 60 do + table.insert(out, string.sub(s, p, p + 59)) + end + table.insert(out, "====") + else + table.insert(out, "begin " .. m .. " " .. f.name) + encodeLines(f.data, variant == "xx", out) + table.insert(out, "end") + end + end + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant }) +function Uu.new() +local a = Archive.new("uu", encoder) + a.meta.source = { format = "uu" } + return a +end + +return Uu +end +__FILES["archive/vpk"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the +-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes +-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the +-- numbered part files "<name>_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes +-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's +-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), +-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the +-- Valve Developer Community VPK file format page; no code taken. +-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Crc32 = __include("core/Crc32") +local Md5 = __include("core/Md5") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Vpk = { + name = "vpk", + category = "archive", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local SIGNATURE = 0x55AA1234 +local EMBEDDED = 0x7FFF + +-- ------------------------------------------------------------------------------------------------ sniff +function Vpk.sniff(r) +if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then + return 0 + end + local v = r:peekU8(4) + return (v == 1 or v == 2 )and 1 or 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive, opts) +return Vpk.encode(archive, opts) +end + +-- the part file `index` as a buffer (cached per archive) +local function partLoader(opts) +local cache= {} + local prefix = "pak01" + if opts and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") or opts.name + prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base + end + return function(index) +local hit = cache[index] + if hit then + return hit, nil + end + local name = string.format("%s_%03d.vpk", prefix, index) + local b = Input.sibling(opts, name) + if not b then + return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") + end + cache[index] = b + return b, nil + end +end + +local function loader(r, e, dataBase, part, verify) +return function() +local src, at +if e.archiveIndex == EMBEDDED then + src, at = r.buf, r.base + dataBase + e.archiveOffset + if dataBase + e.archiveOffset + e.length > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") + end + else + local b, err = part(e.archiveIndex) + if not b then + return nil, err + end + src, at = b, e.archiveOffset + if at + e.length > buffer.len(b) then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) + end + end + local out = buffer.create(e.preloadLength + e.length) + buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) + buffer.copy(out, e.preloadLength, src, at, e.length) + if verify and Crc32.of(out) ~= e.crc32 then + return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") + end + return out, nil + end +end + +function Vpk.decode(r, opts) +local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if sig ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", 0) + end + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) + end + local v2= nil + if version == 2 then + v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } + if r.err then + return nil, r.err + end + end + local headerLen = r:tell() - r.base + if headerLen + treeSize > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) + end + local t = r:sub(headerLen, treeSize) + local a = Archive.new("vpk", encode) + local part = partLoader(opts) + local verify = not (opts and opts.verify == false) + local maxEntries = opts and opts.maxEntries or 1e6 + local count = 0 + local parts= {} + local dataBase = headerLen + treeSize + while true do + local ext = t:cstring() + if t.err then + return nil, t.err + end + if ext == "" then + break + end + while true do + local path = t:cstring() + if t.err then + return nil, t.err + end + if path == "" then + break + end + while true do + local name = t:cstring() + if t.err then + return nil, t.err + end + if name == "" then + break + end + local e= { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } + local term = t:u16le() + e.preloadAt = t.pos + t:skip(e.preloadLength) + if t.err then + return nil, t.err + end + if term ~= 0xFFFF then + return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) + end + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local full = (path == " " and"" or path .. "/") .. name .. (ext == " " and"" or"." .. ext) + e.name = full + if e.archiveIndex ~= EMBEDDED then + parts[e.archiveIndex] = true + end + Archive.put(a, { + name = full, + size = e.preloadLength + e.length, + dir = false, + method = "store", + crc32 = e.crc32, + archiveIndex = (e.archiveIndex == EMBEDDED and{nil }or{e.archiveIndex})[1], + preload = e.preloadLength, + load = loader(r, e, dataBase, part, verify), + }) + end + end + end + local partList= {} + for k in __iter(parts) do + table.insert(partList, k) + end + table.sort(partList) + a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } + if v2 then + local md5At = dataBase + v2.fileDataSize + if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then + local m = r:sub(md5At + v2.archiveMd5Size, 48) + v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) + end + a.meta.source.v2 = v2 + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vpk.encode(archive, opts) +local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local version = opts and opts.version or ((type(src) == "table" and src.format == "vpk" and{src.version }or{nil})[1]) or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + -- group by extension, then path, keeping first-seen order + local exts= {} + local byExt= {} + for _, it in __iter(items) do + if not it.entry.dir then + local full = string.gsub(it.entry.name, "\\", "/") + local dir, file = string.match(full, "^(.*)/([^/]*)$") + if not dir then + dir, file = " ", full + end + local stem, ext = string.match(file , "^(.*)%.([^.]*)$") + if not stem or stem == "" then + stem, ext = file, " " + end + if stem == "" or dir == "" or string.find(full, "\0", 1, true) then + return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) + end + local g = byExt[ext ] + if not g then + g = { paths = {}, byPath = {} } + byExt[ext ] = g + table.insert(exts, ext ) + end + local l = g.byPath[dir ] + if not l then + l = {} + g.byPath[dir ] = l + table.insert(g.paths, dir ) + end + table.insert(l, { name = stem , data = it.data }) + end + end + local tree = Bytes.writer() + local data = Bytes.writer() + for _, ext in __iter(exts) do + tree:cstring(ext) + local g = byExt[ext] + for _, path in __iter(g.paths) do + tree:cstring(path) + for _, f in __iter(g.byPath[path]) do + tree:cstring(f.name) + tree:u32le(Crc32.of(f.data)) + tree:u16le(0) + tree:u16le(EMBEDDED) + tree:u32le(data:tell()) + tree:u32le(buffer.len(f.data)) + tree:u16le(0xFFFF) + data:bytes(f.data) + end + tree:u8(0) + end + tree:u8(0) + end + tree:u8(0) + local tb, db = tree:finish(), data:finish() + local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) + w:u32le(SIGNATURE) + w:u32le(version) + w:u32le(buffer.len(tb)) + if version == 2 then + w:u32le(buffer.len(db)) + w:u32le(0) + w:u32le(48) + w:u32le(0) + end + w:bytes(tb) + w:bytes(db) + if version == 2 then + local treeMd5 = Md5.new() + treeMd5:update(tb) + local tmd = treeMd5:digest() + local chunkMd5 = Md5.new():digest() + local file = Md5.new() + local sofar = w:finish() + file:update(sofar) + file:update(buffer.fromstring(tmd .. chunkMd5)) + local out = Bytes.writer(buffer.len(sofar) + 48) + out:bytes(sofar) + out:string(tmd) + out:string(chunkMd5) + out:string(file:digest()) + return out:finish(), nil + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() +function Vpk.new(version) +local a = Archive.new("vpk", encode) + a.meta.source = { format = "vpk", version = version or 2 } + return a +end + +return Vpk +end +__FILES["archive/wad"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the +-- standard Archive and written from any Archive value, plus the lumps as game data: +-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map +-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer +-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image +-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0) +-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES) +-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts) +-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene +-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map) +-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps +-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again +-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom +-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken. +-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant, +-- big-endian (Jaguar) WADs, compressed Jaguar lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Archive = __include("containers/Archive") +local Pixels = __include("codecs/image/Pixels") +local Picture = __include("archive/wad/Picture") +local Map = __include("archive/wad/Map") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad = { + name = "wad", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-doom" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" }, + caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + +local MAP_LUMPS= { + THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true, + SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true, + MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true, +} +-- namespace markers: first letter(s) before _START / _END +local NAMESPACES= { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches", + P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps", + TX = "textures", HI = "hires", A = "acs", V = "voices" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad.sniff(r) +if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + if m ~= "IWAD" and m ~= "PWAD" then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive, opts) +return Wad.encode(archive, opts) +end + +local function nameAt(b, at) +local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper((z and{(string.sub(s, 1, z - 1) )}or{s})[1]) +end + +function Wad.decode(r, opts) +local kind = r:string(4) + local count, dirOfs = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local size = r.limit - r.base + if count < 0 or dirOfs < 0 then + return nil, Err.new(Err.CORRUPT, "negative directory field", 4) + end + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many lumps: " .. count) + end + if dirOfs + count * 16 > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 8) + end + local a = Archive.new("wad", encode) + local lumps= {} + local seen= {} + local b = r.buf + local ns= nil + local map= nil + local udmf = false + for i = 0, count - 1 do + local o = r.base + dirOfs + i * 16 + local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4) + local name = nameAt(b, o + 8) + if n < 0 or at < 0 or (n > 0 and at + n > size) then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16) + end + -- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map + local nextName = (i + 1 < count and{(nameAt(b, o + 24) )}or{"" +})[1] local inMap= nil + if map then + if udmf then + inMap = map + if name == "ENDMAP" then + map = nil + end + elseif MAP_LUMPS[name] then + inMap = map + else + map = nil + end + end + local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP") + if isMapMarker then + map, udmf = name, nextName == "TEXTMAP" + end + -- namespaces + local marker= false + local pre = string.match(name, "^(%w+)_START$") + local post = string.match(name, "^(%w+)_END$") + if pre and NAMESPACES[pre] then + ns = NAMESPACES[pre] + marker = true + elseif post and NAMESPACES[post] then + ns = (#post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) and{ns }or{nil +})[1] marker = true + end + local entry = (inMap and((inMap .. "/" .. name ))or(name +)) local k = seen[entry] + if k then + k =k+ 1 + seen[entry] = k + entry = entry .. "~" .. k + else + seen[entry] = 1 + end + local lump= { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = (marker and{nil }or{ns})[1], map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil } + table.insert(lumps, lump) + Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) }) + end + a.meta.source = { format = "wad", type = kind, lumps = count } + a.meta.wad = { lumps = lumps, buf = b, base = r.base } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wad.encode(archive, opts) +local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local kind = opts and opts.type or ((type(src) == "table" and src.format == "wad" and{src.type }or{nil})[1]) or "PWAD" + if kind ~= "IWAD" and kind ~= "PWAD" then + return nil, Err.new(Err.ARG, "type must be IWAD or PWAD") + end + local list= {} + for _, it in __iter(items) do + if not it.entry.dir then + local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name + base = string.upper((string.gsub(base, "~%d+$", ""))) + if #base > 8 or #base == 0 then + return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name) + end + table.insert(list, { name = base, data = it.data }) + end + end + local w = Bytes.writer() + w:string(kind) + w:u32le(#list) + w:u32le(0) + local offs= {} + for i, l in __iter(list) do + offs[i] = w:tell() + w:bytes(l.data) + end + local dirOfs = w:tell() + for i, l in __iter(list) do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:string(l.name) + w:fill(0, 8 - #l.name) + end + w:setU32le(8, dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a) +return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil +end + +-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given +local function find(w, name, ns) +local up = string.upper(name) + local best= nil + for _, l in __iter(w.lumps) do + if l.name == up and not l.map then + if ns == nil or l.namespace == ns then + best = l + elseif not best then + best = l + end + end + end + if best and ns and best.namespace ~= ns then + for _, l in __iter(w.lumps) do + if l.name == up and l.namespace == ns then + best = l + end + end + end + return best +end + +-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write() +function Wad.new(kind) +local a = Archive.new("wad", encode) + a.meta.source = { format = "wad", type = kind or "PWAD" } + return a +end + +-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD) +function Wad.lumps(a) +local w = info(a) + return w and w.lumps +end + +-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err +function Wad.palette(a, index) +local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local l = find(w, "PLAYPAL") + local i = index or 0 + if not l or l.size < (i + 1) * 768 then + return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i) + end + return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil +end + +-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic) +-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding. +function Wad.image(a, name, opts) +local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local kind = opts and opts.kind + local l = find(w, name, kind == "flat" and"flats" or nil) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local pal, perr = Wad.palette(a, opts and opts.palette) + if not pal then + return nil, perr + end + local at = w.base + l.offset + local pw, ph, left, top = Picture.header(w.buf, at, l.size) + local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw)) + if asFlat then + local fw, fh = Picture.flatSize(l.size) + if not fw then + return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat") + end + local img = Types.Image.new(fw, fh) + Picture.flat(w.buf, at, fw, fh, pal, img.pixels) + img.meta.source = { format = "wad", kind = "flat", lump = l.name } + return img, nil + end + if not pw then + return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture") + end + local img = Types.Image.new(pw, ph) + local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph) + if not ok then + return nil, Err.from(msg, l.offset) + end + img.meta.offset = { left, top } + img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top } + return img, nil +end + +-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } } +local function textureDefs(w) +if w.textures then + return w.textures + end + local defs= {} + w.textures = defs + local pn = find(w, "PNAMES") + local names= {} + if pn and pn.size >= 4 then + local at = w.base + pn.offset + local n = math.min(buffer.readi32(w.buf, at), math.floor((pn.size - 4) / 8)) + for i = 0, n - 1 do + names[i + 1] = nameAt(w.buf, at + 4 + i * 8) + end + end + for _, tl in __iter({ "TEXTURE1", "TEXTURE2" }) do + local l = find(w, tl) + if l and l.size >= 4 then + local r = Bytes.reader(w.buf, w.base + l.offset, l.size) + local n = r:i32le() + if n > 0 and n * 4 <= l.size - 4 then + for i = 0, n - 1 do + r:seek(4 + i * 4) + local o = r:i32le() + if o > 0 and o + 22 <= l.size then + r:seek(o) + local tname = string.upper(r:fixed(8)) + r:skip(4) + local tw, th = r:i16le(), r:i16le() + r:skip(4) + local pc = r:i16le() + local patches = {} + for _ = 1, math.max(0, pc) do + local px, py, pi = r:i16le(), r:i16le(), r:i16le() + r:skip(4) + if names[pi + 1] then + table.insert(patches, { x = px, y = py, patch = names[pi + 1] }) + end + end + if not r.err and tw > 0 and th > 0 and defs[tname] == nil then + defs[tname] = { width = tw, height = th, patches = patches } + end + r.err = nil + end + end + end + end + end + return defs +end + +-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette) +function Wad.texture(a, name, opts) +local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local def = textureDefs(w)[string.upper(name)] + if not def then + return nil, Err.new(Err.ARG, "no texture named " .. tostring(name)) + end + if def.width * def.height > 4096 * 4096 then + return nil, Err.new(Err.LIMIT, "texture too big") + end + local img = Types.Image.new(def.width, def.height) + for _, p in __iter(def.patches) do + local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" }) + if pimg then + Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y) + end + end + img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches } + return img, nil +end + +-- maps(a) -> { map names } in file order +function Wad.maps(a) +local w = info(a) + local out= {} + if w then + local seen= {} + for _, l in __iter(w.lumps) do + if l.map and not seen[l.map] then + seen[l.map] = true + table.insert(out, l.map) + end + end + end + return out +end + +-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references) +function Wad.mapData(a, name) +local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD archive") + end + local up = string.upper(name) + local lumps= {} + for _, l in __iter(w.lumps) do + if l.map == up and lumps[l.name] == nil then + lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size } + end + end + if not next(lumps) then + return nil, Err.new(Err.ARG, "no map named " .. tostring(name)) + end + if lumps.TEXTMAP then + return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps") + end + local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil) + if not m then + return nil, Err.from(msg) + end + return m, nil +end + +-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and +-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes +-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData +function Wad.map(a, name, opts) +local m, err = Wad.mapData(a, name) + if not m then + return nil, err + end + local w = info(a) + local defs = textureDefs(w) + local images = not (opts and opts.textures == false) + local cache= {} + local pal = opts and opts.palette + local function image(kind, tname) +local key = kind .. ":" .. tname + local c = cache[key] + if c == nil then + local img = (kind == "flat" and{(Wad.image(a, tname, { kind = "flat", palette = pal }) )}or{(Wad.texture(a, tname, { palette = pal }) +)})[1] c = img or false + cache[key] = c + end + return (c and{c }or{nil +})[1] end + local tex= { + size = function(kind, tname) +if kind == "texture" then + local d = defs[tname] + if d then + return d.width, d.height + end + return nil, nil + end + local l = find(w, tname, "flats") + if l then + local fw, fh = Picture.flatSize(l.size) + return fw, fh + end + return nil, nil + end, + image = (images and{image }or{nil})[1], + } + local scene = Map.scene(m, tex, string.upper(name)) + scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = math.floor(#m.vertices / 2 )} + return scene, nil +end + +return Wad +end +__FILES["archive/wad/Map"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS, +-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a +-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with +-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the +-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one +-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z +-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not +-- supported. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") + +local Map = {} + +local Scene = Types.Scene +local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 +-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows +-- ------------------------------------------------------------------------------------------------ parse + + + + + + + + + + + + + + + + + + + +local function name8(b, at) +local s = buffer.readstring(b, at, 8) + local z = string.find(s, "\0", 1, true) + return string.upper((z and{(string.sub(s, 1, z - 1) )}or{s})[1]) +end + +local function side(v) +return (v == 0xFFFF and{nil }or{(v + 1 +)})[1]end + +-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump) +function Map.parse(lumps, hexen) +for _, k in __iter({ "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" }) do + if not lumps[k] then + return nil, "map has no " .. k + end + end + local m= { format = hexen and"hexen" or"doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} } + local v = lumps.VERTEXES + for i = 0, math.floor(v.size / 4 )- 1 do + table.insert(m.vertices, readi16(v.buf, v.at + i * 4)) + table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2)) + end + local s = lumps.SECTORS + for i = 0, math.floor(s.size / 26 )- 1 do + local o = s.at + i * 26 + table.insert(m.sectors, { + floor = readi16(s.buf, o), + ceiling = readi16(s.buf, o + 2), + floorFlat = name8(s.buf, o + 4), + ceilingFlat = name8(s.buf, o + 12), + light = readi16(s.buf, o + 20), + special = readu16(s.buf, o + 22), + tag = readu16(s.buf, o + 24), + }) + end + local sd = lumps.SIDEDEFS + for i = 0, math.floor(sd.size / 30 )- 1 do + local o = sd.at + i * 30 + table.insert(m.sidedefs, { + xoff = readi16(sd.buf, o), + yoff = readi16(sd.buf, o + 2), + upper = name8(sd.buf, o + 4), + lower = name8(sd.buf, o + 12), + middle = name8(sd.buf, o + 20), + sector = readu16(sd.buf, o + 28) + 1, + }) + end + local l = lumps.LINEDEFS + local ls = hexen and 16 or 14 + for i = 0, math.floor(l.size / ls )- 1 do + local o = l.at + i * ls + local b = l.buf + if hexen then + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu8(b, o + 6), + args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) }, + front = side(readu16(b, o + 12)), + back = side(readu16(b, o + 14)), + }) + else + table.insert(m.linedefs, { + v1 = readu16(b, o) + 1, + v2 = readu16(b, o + 2) + 1, + flags = readu16(b, o + 4), + special = readu16(b, o + 6), + tag = readu16(b, o + 8), + front = side(readu16(b, o + 10)), + back = side(readu16(b, o + 12)), + }) + end + end + local t = lumps.THINGS + if t then + local ts = hexen and 20 or 10 + for i = 0, math.floor(t.size / ts )- 1 do + local o = t.at + i * ts + local b = t.buf + if hexen then + table.insert(m.things, { + tid = readi16(b, o), + x = readi16(b, o + 2), + y = readi16(b, o + 4), + z = readi16(b, o + 6), + angle = readi16(b, o + 8), + type = readu16(b, o + 10), + flags = readu16(b, o + 12), + special = readu8(b, o + 14), + args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) }, + }) + else + table.insert(m.things, { + x = readi16(b, o), + y = readi16(b, o + 2), + angle = readi16(b, o + 4), + type = readu16(b, o + 6), + flags = readu16(b, o + 8), + }) + end + end + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ sector outlines +-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1; +-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks; +-- chains that do not close are dropped +local function loops(m) +local edges= {} + local nv = math.floor(#m.vertices / 2 +) local function add(sec, a, b) + local e = edges[sec] or {} + edges[sec] = e + table.insert(e, { a, b }) + end + for _, ld in __iter(m.linedefs) do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local fs = ld.front and m.sidedefs[ld.front] + local bs = ld.back and m.sidedefs[ld.back] + local f = fs and fs.sector + local b = bs and bs.sector + if f ~= b then + if f and m.sectors[f] then + add(f, ld.v1, ld.v2) + end + if b and m.sectors[b] then + add(b, ld.v2, ld.v1) + end + end + end + end + local V = m.vertices + local out= {} + for sec, list in __iter(edges) do + local from= {} + for i, e in __iter(list) do + local l = from[e[1] ] or {} + from[e[1] ] = l + table.insert(l, i) + end + local used= {} + local res= {} + for start = 1, #list do + if not used[start] then + used[start] = true + local loop = { list[start][1] } + local cur = start + local closed = false + for _ = 1, #list do + local e = list[cur] + local at = e[2] + if at == loop[1] then + closed = true + break + end + table.insert(loop, at) + local cands = from[at] + local best, bestT = nil , math.huge + if cands then + local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2] + for _, c in __iter(cands) do + if not used[c] then + local n2 = list[c][2] + local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2] + local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy) + if t < bestT then + best, bestT = c, t + end + end + end + end + if not best then + break + end + used[best] = true + cur = best + end + if closed and #loop >= 3 then + table.insert(res, loop) + end + end + end + out[sec] = res + end + return out +end + +local function insideLoop(V, loop, x, y) +local c = false + local n = #loop + local j = n + for i = 1, n do + local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2] + local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2] + if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then + c = not c + end + j = i + end + return c +end +-- ------------------------------------------------------------------------------------------------ scene + + + +local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4 + +-- scene(m, tex, name) -> Scene +function Map.scene(m, tex, name) +local batches= {} + local order= {} + local function batch(kind, tname) +local key = kind .. ":" .. tname + local b = batches[key] + if not b then + b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} } + batches[key] = b + table.insert(order, key) + end + return b + end + local function vert(b, x, y, z, nx, ny, nz, u, v) + local p, n, t = b.pos, b.nrm, b.uv + p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z + n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz + t[#t + 1], t[#t + 2] = u, v + end + local V = m.vertices + local nv = math.floor(#V / 2 +) -- floors and ceilings + local secLoops = loops(m) + for sec, ls in __iter(secLoops) do + local s = m.sectors[sec] + local flat= {} + for li, loop in __iter(ls) do + local f= {} + for _, vi in __iter(loop) do + table.insert(f, V[vi * 2 - 1]) + table.insert(f, V[vi * 2]) + end + flat[li] = f + end + local tris = Polygon.triangulate(flat) + for pass = 1, 2 do + local tname = (pass == 1 and{s.floorFlat }or{s.ceilingFlat +})[1] local fw, fh = tex.size("flat", tname) + local w, h = fw or 64, fh or 64 + local z = (pass == 1 and{s.floor }or{s.ceiling +})[1] local b = batch("flat", tname) + local nz = pass == 1 and 1 or-1 + for k = 1, #tris, 6 do + for c = 0, 2 do + local cc = (pass == 1 and{c }or{(2 - c +)})[1] local loop = ls[tris[k + cc * 2] ] + local vi = loop[tris[k + cc * 2 + 1] ] + local x, y = V[vi * 2 - 1], V[vi * 2] + vert(b, x, y, z, 0, 0, nz, x / w, -y / h) + end + end + end + end + -- walls + local function quad(tname, x1, y1, x2, y2, zb, zt, xoff, len, texTop, yoff) + if tname == "-" or tname == "" or zt <= zb then + return + end + local tw, th = tex.size("texture", tname) + local w, h = tw or 64, th or 128 + local b = batch("texture", tname) + local dx, dy = x2 - x1, y2 - y1 + local l = math.sqrt(dx * dx + dy * dy) + local nx, ny = dy / l, -dx / l + local u0, u1 = xoff / w, (xoff + len) / w + local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zb, nx, ny, 0, u1, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zb, nx, ny, 0, u0, vb) + vert(b, x2, y2, zt, nx, ny, 0, u1, vt) + vert(b, x1, y1, zt, nx, ny, 0, u0, vt) + end + for _, ld in __iter(m.linedefs) do + if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then + local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2] + local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2) + for sideN = 1, 2 do + local sdi = (sideN == 1 and{ld.front }or{ld.back +})[1] local odi = (sideN == 1 and{ld.back }or{ld.front +})[1] local sd = sdi and m.sidedefs[sdi] + local me = sd and m.sectors[sd.sector] + if sd and me then + local x1, y1, x2, y2 = ax, ay, bx, by + if sideN == 2 then + x1, y1, x2, y2 = bx, by, ax, ay + end + local od = odi and m.sidedefs[odi] + local other = od and m.sectors[od.sector] + if not other then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local top = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and((me.floor + th ))or(me.ceiling +)) quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff) + else + if other.floor > me.floor then + local top = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and{me.ceiling }or{other.floor +})[1] quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff) + end + local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY" + if other.ceiling < me.ceiling and not sky then + local th = select(2, tex.size("texture", sd.upper)) or 128 + local top = (bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 and{me.ceiling }or{(other.ceiling + th +)})[1] quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff) + end + if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then + local th = select(2, tex.size("texture", sd.middle)) or 128 + local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling) + local top = (bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 and((lo + th ))or(hi +)) quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff) + end + end + end + end + end + end + -- the scene + local scene = Scene.new() + scene.meta.up = "z" + local mesh= { name = name, primitives = {} } + local texIndex= {} + for _, key in __iter(order) do + local b = batches[key] + local n = math.floor(#b.pos / 3 +) if n > 0 then + local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + for i = 1, n * 3 do + writef32(pb, (i - 1) * 4, b.pos[i]) + writef32(nb, (i - 1) * 4, b.nrm[i]) + end + for i = 1, n * 2 do + writef32(ub, (i - 1) * 4, b.uv[i]) + end + for i = 0, n - 1 do + writeu32(ib, i * 4, i) + end + local ti = texIndex[key] + if not ti then + table.insert(scene.textures, { name = b.name, uri = b.name, image = (tex.image and{(tex.image(b.kind, b.name) )}or{nil})[1], extras = { wad = { kind = b.kind } } }) + ti = #scene.textures + texIndex[key] = ti + end + local mat = Scene.material(b.name) + mat.metallic = 0 + mat.baseColorTexture = { texture = ti } + mat.extras = { wad = { kind = b.kind } } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, n), + NORMAL = Scene.accessor(nb, "f32", 3, n), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n), + }, + indices = Scene.accessor(ib, "u32", 1, n), + mode = "triangles" , + material = #scene.materials, + extras = { wad = { kind = b.kind, texture = b.name } }, + }) + end + end + table.insert(scene.meshes, mesh) + scene.nodes[1] = { name = name, children = {}, mesh = 1 } + scene.roots[1] = 1 + -- things, on the floor of the sector under them + for i, th in __iter(m.things) do + local z = th.z or 0 + for sec, ls in __iter(secLoops) do + local inside = false + for _, loop in __iter(ls) do + if insideLoop(V, loop, th.x, th.y) then + inside = not inside + end + end + if inside then + z =z+ m.sectors[sec].floor + break + end + end + local a = math.rad(th.angle) / 2 + table.insert(scene.nodes, { + name = "thing " .. i, + children = {}, + translation = { th.x, th.y, z }, + rotation = { 0, 0, math.sin(a), math.cos(a) }, + extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } }, + }) + table.insert(scene.nodes[1].children, #scene.nodes) + end + return scene +end + +return Map +end +__FILES["archive/wad/Picture"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column +-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of +-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative) +-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip). +-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's +-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end. +local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32 + +local Picture = {} + +-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it) +function Picture.header(b, at, n) +if n < 8 then + return nil, 0, 0, 0 + end + local w, h = readu16(b, at), readu16(b, at + 2) + if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then + return nil, 0, 0, 0 + end + for x = 0, w - 1 do + local o = readu32(b, at + 8 + x * 4) + if o < 8 + w * 4 or o >= n then + return nil, 0, 0, 0 + end + end + return w, h, readi16(b, at + 4), readi16(b, at + 6) +end + +-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed) +function Picture.decode(b, at, n, pal, out, w, h) +local stop = at + n + for x = 0, w - 1 do + local p = at + readu32(b, at + 8 + x * 4) + local top = -1 + while true do + if p >= stop then + return false, "column " .. x .. " runs past the end" + end + local delta = readu8(b, p) + if delta == 255 then + break + end + if p + 3 > stop then + return false, "post header past the end" + end + local len = readu8(b, p + 1) + top = (delta <= top and((top + delta ))or(delta +)) if p + 4 + len > stop then + return false, "post past the end" + end + local src = p + 3 + for k = 0, len - 1 do + local y = top + k + if y < h then + writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4)) + end + end + p =p+ (4 + len +) end + end + return true, nil +end + +-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits) +function Picture.flatSize(n) +if n == 4096 then + return 64, 64 + elseif n == 4160 then + return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding + elseif n == 8192 then + return 64, 128 + elseif n == 12800 then + return 64, 200 -- Heretic / Hexen scrolling flats + end + local s = math.floor(math.sqrt(n) + 0.5) + if s * s == n and s > 0 then + return s, s + end + if n > 0 and n % 64 == 0 then + return 64, math.floor(n / 64 +) end + return nil, 0 +end + +-- flat(b, at, w, h, pal, out): raw indexes, row by row +function Picture.flat(b, at, w, h, pal, out) + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4)) + end +end + +-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy), +-- clipped (composite wall textures from patches) +function Picture.blit(src, sw, sh, dst, dw, dh, ox, oy) + local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1 + for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do + local so, d = y * sw, (y + oy) * dw + ox + for x = x0, x1 do + local v = readu32(src, (so + x) * 4) + if v ~= 0 then + writeu32(dst, (d + x) * 4, v) + end + end + end +end + +return Picture +end +__FILES["archive/xz"] = function() +local __compat = __compat local buffer = __compat.buffer --!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/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: +-- the api unwraps an inner archive (a .tar.xz loads as the tar). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Lzma = __include("codecs/compress/Lzma") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Xz = { + name = "xz", + category = "archive", + extensions = { "xz", "txz", "lzma" }, + mime = { "application/x-xz", "application/x-lzma" }, + 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" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local XZ_MAGIC = "\253" .. "7zXZ\0" + +-- ------------------------------------------------------------------------------------------------ sniff +-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1), +-- a size of -1 or under 2^40, and a 0 range coder byte +local function aloneScore(r) +local h = r:peek(14) + if #h < 14 then + return 0 + end + local d = string.byte(h, 1) + if d >= 225 or string.byte(h, 14) ~= 0 then + return 0 + end + local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216 + local okDict = false + for n = 12, 31 do + if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then + okDict = true + break + end + end + if not okDict then + return 0 + end + local s = string.sub(h, 6, 13) + if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then + return 0 + end + return d == 0x5D and 0.4 or 0.2 +end + +function Xz.sniff(r) +if r:peek(6) == XZ_MAGIC then + return 1 + end + return aloneScore(r) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xz.decode(r, opts) +local o= opts or {} + local n = r.limit - r.base + local out, res + local method + if r:peek(6) == XZ_MAGIC then + out, res = Lzma.xz(r.buf, r.base, n, o) + method = "lzma2" + else + out, res = Lzma.alone(r.buf, r.base, n, o) + method = "lzma" + end + if not out then + return nil, res + end + local a = Archive.new("xz") + a.meta.stream = true + a.meta.container = method == "lzma" and"lzma" or"xz" + Archive.put(a, { + name = Archive.streamName(o, Xz.extensions), + size = buffer.len(out), + compressedSize = n, + method = method, + dir = false, + data = out, + }) + return a, nil +end + +return Xz +end +__FILES["archive/yenc"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive: +-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart +-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified +-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a +-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one +-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space +-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Yenc = { + name = "yenc", + category = "archive", + extensions = { "yenc", "ync" }, + mime = { "application/x-yenc" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" }, + caps = { decode = true, encode = true, multipart = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function Yenc.sniff(r) +local head = r:peek(4096) + if string.match(head, "^=ybegin ") then + return 0.95 + end + return string.find(head, "\n=ybegin [^\n]*name=") and 0.6 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- key=value fields of a keyword line; name= runs to the end of the line +local function fields(line) +local f= {} + local s, name = string.match(line, "^(.-)name=(.*)$") + if s then + f.name = string.gsub(name , "%s+$", "") + line = s + end + for k, v in __iter(string.gmatch(line, "(%w+)=(%S+)")) do + f[k] = v + end + return f +end + +-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out) +local function decodeData(src, i, j, out, o) +local lim = buffer.len(out) + local esc = false + for p = i, j - 1 do +local __DARKLUA_CONTINUE_2=false repeat local c = buffer.readu8(src, p) + if c == 13 or c == 10 then +__DARKLUA_CONTINUE_2=true break + end + if c == 61 and not esc then + esc = true +__DARKLUA_CONTINUE_2=true break + end + if esc then + c =c- 64 + esc = false + end + if o < lim then + buffer.writeu8(out, o, (c - 42) % 256) + end + o =o+ 1 +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + return o +end + +-- count the decoded bytes of the data lines [i, j) +local function countData(src, i, j) +local n, esc = 0, false + for p = i, j - 1 do + local c = buffer.readu8(src, p) + if c ~= 13 and c ~= 10 then + if c == 61 and not esc then + esc = true + else + esc = false + n =n+ 1 + end + end + end + return n +end + + + + +local function hex(s) +return (s and string.match(s, "^%x+$") and #s <= 8 and{(tonumber(s, 16) )}or{nil +})[1]end + +local function parse(b, base, limit) +local files= {} + local byName= {} + local p = base + local cur= nil + local part= nil + while p < limit do + local nl = p + while nl < limit and buffer.readu8(b, nl) ~= 10 do + nl =nl+ 1 + end + local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y" + if isKey then + local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "") + local kw = string.match(line, "^=y(%a+)") + local f = fields(line) + if kw == "begin" then + local name = f.name + local size = tonumber(f.size or "") + if not name or name == "" or not size or size < 0 then + return nil, "=ybegin without name or size" + end + local file= byName[name] + if not file then + local nf= { name = name , size = size, parts = {}, total = tonumber(f.total or "") } + byName[name] = nf + table.insert(files, nf) + file = nf + end + cur = file + part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") } + elseif kw == "part" and part then + local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "") + if not first or not last or first < 1 or last < first - 1 then + return nil, "bad =ypart range" + end + part.first, part.last = first - 1, last + part.from, part.to = nl + 1, nl + 1 + elseif kw == "end" and part and cur then + part.pcrc = hex(f.pcrc32) + if f.crc32 then + cur.crc = hex(f.crc32) + end + local size = tonumber(f.size or "") + if size and size ~= part.last - part.first then + return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")" + end + table.insert(cur.parts, part) + part = nil + end + elseif part then + part.to = nl + 1 + end + p = nl + 1 + end + if part then + return nil, "truncated: no =yend" + end + if #files == 0 then + return nil, "no =ybegin line" + end + return files, nil +end + +local function encoder(a, o) +return Yenc.encode(a, o) +end + +function Yenc.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local b = r.buf + local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b))) + if not files then + return nil, Err.from(perr) + end + local a = Archive.new("yenc", encoder) + local incomplete = {} + for _, f in __iter(files) do + if f.size > maxBytes then + return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes") + end + local out = buffer.create(f.size) + local covered = 0 + for _, pt in __iter(f.parts) do + local n = countData(b, pt.from, pt.to) + if n ~= pt.last - pt.first or pt.last > f.size then + return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first)) + end + local tmp = buffer.create(n) + decodeData(b, pt.from, pt.to, tmp, 0) + if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch") + end + buffer.copy(out, pt.first, tmp, 0, n) + covered =covered+ n + end + local whole = covered == f.size + if whole and f.crc and Crc32.of(out) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch") + end + if not whole then + table.insert(incomplete, f.name) + end + Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole }) + end + a.meta.stream = #files == 1 + a.meta.incomplete = (#incomplete > 0 and{incomplete }or{nil +})[1] a.meta.source = { format = "yenc" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Yenc.encode(value, opts) +local o= opts or {} + local lineLen = o.line or 128 + if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then + return nil, Err.new(Err.ARG, "line must be 2..997") + end + local files, err = Archive.files(value, o.name) + if not files then + return nil, err + end + if #files == 0 then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local w = Bytes.writer() + for _, f in __iter(files) do + if string.find(f.name, "[\r\n]") then + return nil, Err.new(Err.ARG, "file names may not contain line breaks") + end + local data = f.data + local n = buffer.len(data) + w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name)) + local col = 0 + for i = 0, n - 1 do + local c = (buffer.readu8(data, i) + 42) % 256 + local critical = c == 0 or c == 10 or c == 13 or c == 61 + if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then + critical = true + elseif not critical and c == 46 and col == 0 then + critical = true + end + if critical then + w:u8(61) + w:u8((c + 64) % 256) + col =col+ 2 + else + w:u8(c) + col =col+ 1 + end + if col >= lineLen and i < n - 1 then + w:string("\r\n") + col = 0 + end + end + if n > 0 then + w:string("\r\n") + end + w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data))) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line }) +function Yenc.new() +local a = Archive.new("yenc", encoder) + a.meta.source = { format = "yenc" } + return a +end + +return Yenc +end +__FILES["archive/z"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one +-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a +-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed, +-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is +-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local UnixCompress = __include("codecs/compress/UnixCompress") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Z = { + name = "z", + category = "archive", + extensions = { "z", "taz", "tz" }, + mime = { "application/x-compress" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function Z.sniff(r) +if r:peek(2) ~= "\31\157" then + return 0 + end + local f = r:peekU8(2) + return f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 and 1 or 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the entry name: the file name without .Z; .taz / .tz name a tar +local function entryName(opts) +local name = Archive.streamName(opts, { "z" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then + return stem .. ".tar" + end + return name +end + +local function encode(value, opts) +return Z.encode(value, opts) +end + +function Z.decode(r, opts) +local o= opts or {} + local n = r.limit - r.base + local out, err = UnixCompress.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 } + Archive.put(a, { + name = entryName(o), + size = buffer.len(out), + compressedSize = n, + method = "lzw", + dir = false, + data = out, + }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Z.encode(value, opts) +local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits }) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(data?, name?) -> a .Z Archive holding one entry +function Z.new(data, name) +local a = Archive.new("z", encode) + a.meta.stream = true + a.meta.source = { format = "z" } + if data then + a:add(name or "data", data) + end + return a +end + +return Z +end +__FILES["archive/zip"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip. +-- 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/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. +-- +-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf) +-- for _, e in a:list() do print(e.name, e.size, e.method) end +-- local data = a:read("dir/file.txt") +-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() } +-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" }) +-- local b = Zip.create() -- an empty archive + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Container = __include("containers/Zip") + +-- ------------------------------------------------------------------------------------------------ contract +local Zip = { + name = "zip", + category = "archive", + extensions = { "zip", "wsz" }, + mime = { "application/zip", "application/x-zip-compressed" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" } + +local Archive = {} +Archive.__index = Archive + +local function new(zip, verify) +local a = setmetatable({ + kind = "archive", + format = "zip", + meta = { source = { format = "zip" }, comment = (zip and{zip.comment }or{nil})[1], zip64 = (zip and{zip.zip64 }or{nil })[1]}, + _zip = zip, + _verify = verify, + _order = {} , + _items = {} , + }, Archive) + if zip then + for _, e in __iter(zip:list()) do + if a._items[e.name] == nil then + table.insert(a._order, e.name) + end + a._items[e.name] = { raw = e } + end + end + return a +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Zip.sniff(r) +local s = r:peek(4) + -- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff + if s == "PK\3\4" or s == "PK\5\6" then + return 0.6 + end + if string.sub(s, 1, 2) == "MZ" then + return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip" + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Archive | nil, Err +function Zip.decode(r, opts) +local zip, err = Container.open(r) + if not zip then + return nil, err + end + return new(zip, not (opts and opts.verify == false)), nil +end + +-- create() -> an empty Archive +function Zip.create() +return new(nil, true) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written +-- here), or a plain table { [name] = buffer | string }. +function Zip.encode(value, opts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table") + end + if getmetatable(value) == Archive then + return value:write(opts) + end + local a = new(nil, true) + if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then + for _, e in __iter(value:list()) do + if e.dir then + a:add(e.name, nil, { mtime = e.mtime }) + else + local data, err = value:read(e.name) + if not data then + return nil, err + end + a:add(e.name, data, { mtime = e.mtime }) + end + end + else + local names = {} + for k, v in __iter(value) do + if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then + return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data") + end + table.insert(names, k) + end + table.sort(names) + for _, k in __iter(names) do + a:add(k, value[k]) + end + end + return a:write(opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the Archive methods (Types.Archive) + +-- list() -> { ArchiveEntry } in archive order (+ crc32, comment) +function Archive.list(self) +local out = {} + for _, name in __iter(self._order) do + local it = self._items[name] + if it.raw then + local e = it.raw + table.insert(out, { + name = e.name, + size = e.size, + compressedSize = e.compressedSize, + method = METHODS[e.method] or ("method " .. e.method), + mtime = e.mtime, + dir = e.isDir, + crc32 = e.crc32, + comment = e.comment, + }) + else + table.insert(out, { + name = name, + size = buffer.len(it.data), + compressedSize = nil, + method = it.opts.method or "deflate", + mtime = it.opts.mtime, + dir = string.sub(name, -1) == "/", + }) + end + end + return out +end + +-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup +function Archive.read(self, name) +if type(name) ~= "string" then + return nil, Err.new(Err.ARG, "read: name must be a string") + end + local it = self._items[name] + if it and not it.raw then + local copy = buffer.create(buffer.len(it.data)) + buffer.copy(copy, 0, it.data) + return copy, nil + end + if it then + return self._zip:read(it.raw, self._verify) + end + if self._zip then + local e = self._zip:find(name) + if e and self._items[e.name] and self._items[e.name].raw == e then + return self._zip:read(e, self._verify) + end + end + return nil, Err.new(Err.ARG, "no entry " .. name) +end + +-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/") +function Archive.add(self, name, data, opts) + local b= (type(data) == "string" and{(buffer.fromstring(data) )}or{(type(data) == "buffer" and{data }or{(buffer.create(0) +)})[1]})[1] if self._items[name] == nil then + table.insert(self._order, name) + end + self._items[name] = { data = b, opts = opts or {} } +end + +-- remove(name) -> true when there was such an entry +function Archive.remove(self, name) +if self._items[name] == nil then + return false + end + self._items[name] = nil + local i = table.find(self._order, name) + if i then + table.remove(self._order, i) + end + return true +end + +-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are +function Archive.write(self, opts) +local w = Container.writer() + for _, name in __iter(self._order) do + local it = self._items[name] + local ok, err + if it.raw then + ok, err = w:addRaw(it.raw, self._zip) + else + ok, err = w:add(name, it.data, it.opts) + end + if not ok then + return nil, err + end + end + local o= opts or {} + if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then + o = table.clone(o) + o.comment = self.meta.comment + end + return w:finish(o) +end + +Zip.Container = Container + +return Zip +end +__FILES["archive/zoo"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of +-- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers), +-- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit +-- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read +-- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not +-- supported: writing, file generations beyond keeping the newest (older versions of a name get ";<version>"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc16 = __include("core/Crc16") +local Lzw = __include("codecs/compress/Lzw") +local Lzh = __include("codecs/compress/Lzh") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zoo = { + name = "zoo", + category = "archive", + extensions = { "zoo" }, + mime = { "application/x-zoo" }, + deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local TAG = 0xFDC4A7DC + +-- ------------------------------------------------------------------------------------------------ sniff +function Zoo.sniff(r) +local h = r:peek(24) + if #h < 24 then + return 0 + end + local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216 + if tag ~= TAG then + return 0 + end + return string.sub(h, 1, 4) == "ZOO " and 1 or 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zoo.decode(r, opts) +local o= opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65536 + local h = r:sub(0, 34) + local text = h:string(20) + local tag, start = h:u32le(), h:u32le() + h:skip(4) + local major, minor = h:u8(), h:u8() + if h.err then + return nil, h.err + end + if tag ~= TAG then + return nil, Err.new(Err.CORRUPT, "no zoo tag") + end + local a = Archive.new("zoo") + a.meta.text = string.match(text, "^[^%z\26]*") + a.meta.source = { format = "zoo", version = major .. "." .. minor } + local p = start + local count = 0 + local seen= {} + local size = r:size() + while true do + if seen[p] or p < 34 or p + 51 > size then + return nil, Err.new((p + 51 > size and{Err.TRUNCATED }or{Err.CORRUPT})[1], "bad directory entry offset " .. p) + end + seen[p] = true + local e = r:sub(p, size - p) + local etag = e:u32le() + local etype, method = e:u8(), e:u8() + local nextP, dataAt = e:u32le(), e:u32le() + local date, time = e:u16le(), e:u16le() + local crc = e:u16le() + local orig, packed = e:u32le(), e:u32le() + e:skip(2) + local deleted = e:u8() + e:skip(1) + local commentAt, commentLen = e:u32le(), e:u16le() + local fname = e:fixed(13) + if e.err then + return nil, e.err + end + if etag ~= TAG then + return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p) + end + if nextP == 0 then + break + end + count =count+ 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries entries") + end + local name, dir = fname, "" + local entry= {} + if etype == 2 then + local varLen = e:u16le() + e:skip(3) -- tz, dir_crc + if varLen > 0 then + local v = e:slice(varLen) + local nlen, dlen = v:u8(), v:u8() + local lname = v:string(nlen) + dir = v:string(dlen) + if nlen > 0 then + name = string.match(lname, "^[^%z]*") or lname + end + if v:remaining() >= 2 then + entry.system = v:u16le() + end + if v:remaining() >= 3 then + local f0, f1, f2 = v:u8(), v:u8(), v:u8() + local attr = f0 + f1 * 256 + f2 * 65536 + if bit32.band(attr, 0x400000) ~= 0 then + entry.mode = bit32.band(attr, 0xFFFF) + end + end + if v:remaining() >= 4 then + local vflag, ver = v:u16le(), v:u16le() + if bit32.band(vflag, 0x40) ~= 0 then + entry.version = ver + end + end + end + if e.err then + return nil, e.err + end + end + dir = string.match(dir, "^[^%z]*") or dir + dir = string.gsub(dir, "\\", "/") + local full = (dir ~= "" and{((string.gsub(dir, "/+$", "")) .. "/" .. name )}or{name +})[1] full = string.gsub(full, "^/+", "") + if deleted == 0 then + local key = full + if a._byName[key] then + key = full .. ";" .. tostring(entry.version or count) + end + entry.name = key + entry.size = orig + entry.compressedSize = packed + entry.method = method == 0 and"store" or(method == 1 and"lzw" or(method == 2 and"lzh" or"method" .. method +)) entry.mtime = Archive.fromDos(date * 65536 + time) + entry.dir = false + if commentLen > 0 and commentAt + commentLen <= size then + entry.comment = r:sub(commentAt, commentLen):string(commentLen) + end + if dataAt + packed > size then + return nil, Err.new(Err.TRUNCATED, full .. ": data past the end") + end + if orig > maxBytes then + return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes") + end + if orig > 0 then + local buf, at = r.buf, r.base + dataAt + entry.load = function() +local out, derr +if method == 0 then + if packed < orig then + return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") + end + out = buffer.create(orig) + buffer.copy(out , 0, buf, at, orig) + elseif method == 1 then + local ob = buffer.create(orig) + local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo") + if n ~= orig then + return nil, Err.from(lerr or "corrupt: LZW data ends early") + end + out = ob + elseif method == 2 then + out, derr = Lzh.decode(buf, at, packed, orig, "lh5") + else + return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method) + end + if not out then + return nil, Err.from(derr) + end + if Crc16.arc(out, 0, orig) ~= crc then + return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") + end + return out, nil + end + end + Archive.put(a, entry) + end + p = nextP + end + return a, nil +end + +return Zoo +end +__FILES["archive/zst"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Zstd = __include("codecs/compress/Zstd") +local Archive = __include("containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zst = { + name = "zst", + category = "archive", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function Zst.sniff(r) +local m = r:peek(4) + if m == Zstd.MAGIC then + return 1 + end + -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame + if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zst.decode(r, opts) +local o= opts or {} + local len = r.limit - r.base + local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) + if not out then + return nil, err + end + local a = Archive.new("zst") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(o, Zst.extensions), + size = buffer.len(out), + compressedSize = len, + method = "zstd", + dir = false, + data = out, + }) + return a, nil +end + +return Zst +end +__FILES["audio/aac"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!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/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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") + +-- ------------------------------------------------------------------------------------------------ contract +local AacFormat = { + name = "aac", + category = "audio", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local readu8 = buffer.readu8 + +-- the size of an ID3v2 tag at p (0 if none) +local function id3Size(b, p, limit) +if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local s = 0 + for i = 6, 9 do + s = s * 128 + bit32.band(readu8(b, p + i), 127) + end + local footer = bit32.band(readu8(b, p + 5), 0x10) ~= 0 and 10 or 0 + return 10 + s + footer +end + +-- a few ID3v2.3 / 2.4 text frames -> tags +local ID3_TAGS= { + TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", + COMM = "comment", TCOM = "composer", TPE2 = "albumartist", +} +local function id3Tags(b, p, size) +local tags= {} + local ver = readu8(b, p + 3) + if ver < 3 then + return tags + end + local q, stop = p + 10, p + size + while q + 10 <= stop do + local id = buffer.readstring(b, q, 4) + if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then + break + end + local n = 0 + for i = 4, 7 do + n = (ver == 4 and{(n * 128 + bit32.band(readu8(b, q + i), 127) )}or{(n * 256 + readu8(b, q + i) +)})[1] end + if n < 1 or q + 10 + n > stop then + break + end + local key = ID3_TAGS[id] + local enc = readu8(b, q + 10) + if key and (enc == 0 or enc == 3) then + local s = buffer.readstring(b, q + 11, n - 1) + if id == "COMM" and #s > 3 then + s = string.sub(s, 4) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, z + 1) + end + end + s = (string.gsub(s, "%z+$", "")) + tags[key] = s + end + q =q+ (10 + n +) end + return tags +end + +-- ------------------------------------------------------------------------------------------------ sniff +function AacFormat.sniff(r) +local b, p, limit = r.buf, r.pos, r.limit + p =p+ id3Size(b, p, limit) + local h = Aac.adts(b, p, limit) + if not h then + return 0 + end + -- a second header right after the first makes it certain + local h2 = Aac.adts(b, p + h.frameSize, limit) + if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then + return 0.9 + end + return p + h.frameSize >= limit and 0.7 or 0.4 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the frame index: offsets of every ADTS frame (resyncing over garbage) +local function index(r, maxFrames) +local b, limit = r.buf, r.limit + local p = r.base + id3Size(b, r.base, limit) + local offs, sizes = {}, {} + local first= nil + while p + 7 <= limit do +local __DARKLUA_CONTINUE_4=false repeat local h = Aac.adts(b, p, limit) + if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then + h = nil -- a false sync inside the data + end + if not h then + p =p+ 1 +__DARKLUA_CONTINUE_4=true break + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + if not first then + first = h + end + if h.blocks ~= 1 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) + end + table.insert(offs, p + h.headerSize) + table.insert(sizes, h.frameSize - h.headerSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p =p+ h.frameSize +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end + return offs, sizes, first, nil +end + +function AacFormat.open(r, opts) +local o= opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first then + return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) + end + local h = first +if h.objectType ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") + end + if h.channelConfig == 0 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") + end + local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] +local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) + if not dec then + return nil, derr + end + local d = dec +local sr = d.sampleRate + local nframes = #offs + local total = nframes * 1024 + local bytes = 0 + for _, s in __iter(sizes) do + bytes =bytes+ s + end + local id3 = id3Size(r.buf, r.base, r.limit) + local tags = (id3 > 0 and{(id3Tags(r.buf, r.base, id3) )}or{{} +})[1] local buf = r.buf + local out= { + sampleRate = sr, + channels = channels, + frames = total, + duration = total / sr, + bitrate = (total > 0 and{(math.floor(bytes * 8 * sr / total) )}or{0})[1], + tags = tags, + codec = "aac", + } + -- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking + return Stream.packets(out, { + count = nframes, + start = function(i) +return (i - 1) * 1024 + end, + decode = function(i) +return d:decode(buf, offs[i], sizes[i]) + end, + pcm = function() +return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function AacFormat.decode(r, opts) +local dec, err = AacFormat.open(r, opts) + if not dec then + return nil, err + end + local d= dec + return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate }) +end + +return AacFormat +end +__FILES["audio/ac3"] = function() +--!strict +-- audio/ac3: raw AC-3 (Dolby Digital, ATSC A/52) elementary streams, the .ac3 files of DVD / broadcast rips, through +-- codecs/audio/Ac3 (written from the A/52 specification). Supports: every channel layout (1+1, 1/0 .. 3/2, LFE) +-- output in WAVE order without downmixing, 32 / 44.1 / 48 kHz, every bit rate, coupling, rematrixing, block +-- switching, delta bit allocation, the CRC check, resync over garbage, a truncated last frame (dropped), streaming and +-- exact seeking (one frame of pre-roll for the overlap). Dynamic range control is off by default (`drc` = 0 .. 1). +-- Not supported: writing, E-AC-3 / Dolby Digital Plus (UNSUPPORTED), bsid 9 / 10 reduced-rate streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Ac3 = __include("codecs/audio/Ac3") + +-- ------------------------------------------------------------------------------------------------ contract +local Ac3Format = { + name = "ac3", + category = "audio", + extensions = { "ac3", "a52" }, + mime = { "audio/ac3", "audio/x-ac3" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Ac3" }, + caps = { decode = true, encode = false, codecs = { "ac3" }, channels = 6, streaming = true, lossy = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff +-- (E-AC-3 streams sniff too, so loading one says UNSUPPORTED instead of an unknown format) + + + + + + + +function Ac3Format.sniff(r) +local b, p, limit = r.buf, r.pos, r.limit + local h = Ac3.header(b, p, limit) + if not h then + return 0 + end + local h2 = Ac3.header(b, p + h.frameSize, limit) + if h2 and h2.sampleRate == h.sampleRate then + return 0.9 + end + return p + h.frameSize >= limit and 0.6 or 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the syncframe index (resyncing over garbage: a header counts when the next one follows it, or the data ends) +local function index(r, maxFrames) +local b, limit = r.buf, r.limit + local p = r.base + local offs, sizes = {}, {} + local first= nil + while p + 8 <= limit do +local __DARKLUA_CONTINUE_1=false repeat local h = Ac3.header(b, p, limit) + if h and first and (h.sampleRate ~= first.sampleRate or h.bsid > 10) then + h = nil + end + if h and not first and p + h.frameSize + 8 <= limit then + local h2 = Ac3.header(b, p + h.frameSize, limit) + if not h2 then + h = nil -- a false sync word + end + end + if not h then + p =p+ 1 +__DARKLUA_CONTINUE_1=true break + end + if not first then + first = h + if h.bsid > 10 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "E-AC-3 (Dolby Digital Plus)", p) + elseif h.bsid > 8 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "reduced sample rate AC-3 (bsid " .. h.bsid .. ")", p) + end + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, h.frameSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p =p+ h.frameSize +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + return offs, sizes, first, nil +end + +function Ac3Format.open(r, opts) +local o= opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first or #offs == 0 then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", r.base) + end + local h = first +local d = Ac3.decoder({ drc = o.drc, crc = o.crc }) + local buf = r.buf + local n = #offs + local out = { + sampleRate = h.sampleRate, + channels = h.channels, + frames = n * 1536, + duration = n * 1536 / h.sampleRate, + bitrate = h.bitrate, + tags = {}, + codec = "ac3", + acmod = h.acmod, + lfe = h.lfeon, + } + return Stream.packets(out, { + count = n, + start = function(i) +return (i - 1) * 1536 + end, + decode = function(i) +local frames, err = d:decode(buf, offs[i], sizes[i]) + if frames and d.channels ~= h.channels then + return nil, Err.new(Err.UNSUPPORTED, "channel layout change inside the stream", offs[i]) + end + return frames, err + end, + pcm = function() +return d.pcm + end, + reset = function() + d:reset() + end, + preroll = 1, + }) +end + +function Ac3Format.decode(r, opts) +local dec, err = Ac3Format.open(r, opts) + if not dec then + return nil, err + end + local d= dec + return Pcm.drain(d, { format = "ac3", codec = "ac3", acmod = d.acmod, lfe = d.lfe, bitrate = d.bitrate }) +end + +return Ac3Format +end +__FILES["audio/adpcm"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- audio/adpcm: headerless ADPCM streams (.adpcm / .ima / .vox-style dumps), over codecs/audio/Adpcm. New in +-- rosetta. A raw stream has no header, so nothing identifies it: sniff is always 0, F.detect only finds it by +-- extension, and the layout comes from the options (codec, sampleRate, channels, blockAlign). vgmstream plays such +-- files only through a .txth description and ffmpeg not at all (its adpcm_* codecs need a container), so the codecs +-- here are the layouts those containers use: +-- "ima" IMA nibbles from predictor 0 / step index 0, channels interleaved by nibble, the high nibble first +-- (DVI order, as KVAG / adpcm_ima_ssi); lowFirst = true for the other order +-- "ima_wav" Microsoft IMA blocks (the WAV / AVI data chunk), blockAlign bytes each (default 1024) +-- "ms" Microsoft ADPCM blocks with the 7 standard coefficient pairs (default blockAlign 1024) +-- "ima_qt" Apple ima4 packets (34 bytes per channel, 64 frames), as in AIFF-C / CAF / QuickTime +-- "psx" Sony PS-ADPCM frames (16 bytes, 28 samples), channels interleaved every `interleave` bytes (default 16) +-- Encode: "ima", "ima_wav" and "ms" (from an Audio or a Decoder). Not supported: raw DSP / ADX (their coefficients +-- live in a header: see audio/brstm and audio/adx). +-- +-- local a = Adpcm.decode(Bytes.reader(buf), { codec = "ms", sampleRate = 22050, channels = 2, blockAlign = 512 }) +-- local raw = Adpcm.encode(a, { codec = "ima" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Raw = { + name = "adpcm", + category = "audio", + extensions = { "adpcm", "ima" }, + mime = { "audio/x-adpcm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, headerless = true, codecs = { "ima", "ima_wav", "ms", "ima_qt", "psx" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + +local CODECS = { ima = true, ima_wav = true, ms = true, ima_qt = true, psx = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Raw.sniff(_r) +return 0 -- no header: found by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Raw.decode(r, opts) +local dec, err = Raw.open(r, opts) + if not dec then + return nil, err + end + local limit = opts and opts.maxFrames or 2 ^ 28 + if dec.frames > limit or dec.frames * dec.channels > 2 ^ 28 then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", dec.frames)) + end + return Pcm.drain(dec, { format = "adpcm", codec = (dec ).codec }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Raw.encode(value, opts) +local o= opts or {} + local codec = o.codec or "ima" + if codec ~= "ima" and codec ~= "ima_wav" and codec ~= "ms" then + return nil, Err.new(Err.ARG, "encode: codec must be ima, ima_wav or ms") + end + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local ch, n, x = a.channels, a.frames, a.samples + if codec == "ima" then + local out = buffer.create(math.floor((n * ch + 1) / 2)) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.imaEncode(x, c, ch, n, st, c * 8, out, 0, c, ch, not o.lowFirst) + end + return out, nil + end + local ba = o.blockAlign or 256 * ch + local spb = Decoder.blockFrames(codec, ba, ch) + if type(ba) ~= "number" or ba ~= math.floor(ba) or ba > 65535 or not spb or spb < 2 then + return nil, Err.new(Err.ARG, "bad blockAlign " .. tostring(ba)) + end + if codec == "ima_wav" and (ba % (4 * ch) ~= 0) then + return nil, Err.new(Err.ARG, "ima_wav: blockAlign must be a multiple of 4 * channels") + end + local blocks = math.floor((n + spb - 1) / spb +) local out = buffer.create(blocks * ba) + local st = buffer.create(8 * ch) + for b = 0, blocks - 1 do + local f0 = b * spb + if codec == "ms" then + Adpcm.msEncode(x, f0, n - f0, ch, spb, out, b * ba) + else + Adpcm.imaWavEncode(x, f0, n - f0, ch, spb, st, out, b * ba) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Raw.open(r, opts) +if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local o= opts or {} + local codec = o.codec or "ima" + local rate, ch = o.sampleRate or 22050, o.channels or 1 + if not CODECS[codec] then + return nil, Err.new(Err.ARG, "unknown codec " .. tostring(codec)) + end + if type(rate) ~= "number" or rate <= 0 or rate ~= rate or type(ch) ~= "number" or ch < 1 or ch > 255 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + local size = r.limit - r.base + local dec= { sampleRate = rate, channels = ch, tags = {}, codec = codec, frames = 0, duration = 0 } + local d, err + if codec == "ima" then + d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base, size = size, hi = not o.lowFirst }) + elseif codec == "psx" then + local il = o.interleave or 16 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = r.base, size = size, interleave = ch == 1 and 16 or il }) + else + local ba = o.blockAlign or 1024 + if type(ba) ~= "number" or ba < 1 or ba ~= math.floor(ba) then + return nil, Err.new(Err.ARG, "bad blockAlign") + end + d, err = Decoder.blocks(dec, { kind = codec , buf = r.buf, offset = r.base, size = size, blockAlign = ba }) + end + if not d then + return nil, err + end + d.bitrate = (d.duration > 0 and{(math.floor(size * 8 / d.duration) )}or{0 +})[1] return d, nil +end + +return Raw +end +__FILES["audio/adx"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- audio/adx: CRI ADX (.adx), the game-audio ADPCM of Sega / CRI Middleware, over codecs/audio/Adpcm. New in +-- rosetta; the header layout and the decoder details follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), +-- whose output it matches bit for bit (the scale + 1 of CRI's decoders, the version 3 rounding; ffmpeg's ADX decoder +-- differs slightly on both). Supports: encoding type 3 (the standard predictor from the header's high-pass cutoff), +-- versions 3, 4 and 5, 1-8 channels, the initial history of version 4, loop points (dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive). Encode (Audio or Decoder): version 4, 1-8 channels, +-- loop points from opts.loop. Not supported: encrypted ADX (versions 0x0408 / 0x0409, keys needed), the fixed (2) and +-- exponential (4) encoding types, AHX. +-- +-- local dec = Adx.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, version, cutoff) +-- local file = Adx.encode(audio, { loop = { start = 44100, stop = 441000 } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Adx = { + name = "adx", + category = "audio", + extensions = { "adx" }, + mime = { "audio/x-adx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 8 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local FRAME = 18 + +-- ------------------------------------------------------------------------------------------------ sniff +function Adx.sniff(r) +if r:peekU8(0) ~= 0x80 or r:peekU8(1) ~= 0 then + return 0 + end + local off = r:peekU8(2) * 256 + r:peekU8(3) + return r:peek(6, off - 2) == "(c)CRI" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Adx.decode(r, opts) +local dec, err = Adx.open(r) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "adx", version = d.version, cutoff = d.cutoff, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Adx.encode(value, opts) +local o= opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "ADX holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local loop = o.loop + if loop == nil then + local v = value +local m = type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.loop + loop = (type(m) == "table" and{m }or{((type(v.loop) == "table" and{v.loop }or{nil})[1]) +})[1] end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + if loop and (type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop <= loop.start or loop.stop > n) then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + local cutoff = o.cutoff or 500 + if type(cutoff) ~= "number" or cutoff < 1 or cutoff >= rate / 2 or cutoff > 65535 then + return nil, Err.new(Err.ARG, "bad cutoff") + end + cutoff = math.floor(cutoff) + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local hist = (ch > 1 and((4 * ch ))or(8 +)) local start = 0x18 + hist + (loop and 0x18 or 0) + 6 + start = math.floor((start + 3) / 4 )* 4 + local nframes = math.floor((n + 31) / 32 +) local w = Bytes.writer(start + (nframes + 1) * FRAME * ch) + w:u16be(0x8000) + w:u16be(start - 4) + w:u8(3) + w:u8(FRAME) + w:u8(4) + w:u8(ch) + w:u32be(rate) + w:u32be(n) + w:u16be(cutoff) + w:u16be(0x0400) + w:u32be(0) + w:fill(0, hist) + if loop then + local bytesAt = function(f) +return start + (math.floor(f / 32)) * FRAME * ch + end + w:u16be(0) + w:u16be(1) + w:u32be(1) + w:u32be(loop.start) + w:u32be(bytesAt(loop.start)) + w:u32be(loop.stop) + w:u32be(bytesAt(loop.stop + 31)) + end + w:fill(0, start - 6 - w.pos) + w:string("(c)CRI") + local at = w:reserve(nframes * FRAME * ch) + local st = buffer.create(8 * ch) + for c = 0, ch - 1 do + Adpcm.adxEncode(a.samples, c, ch, n, c1, c2, st, c * 8, w.buf, at + c * FRAME, FRAME * ch) + end + w.pos = at + nframes * FRAME * ch + -- the end marker: scale 0x8001, then the padding size + w:u16be(0x8001) + w:u16be(FRAME - 4) + w:fill(0, FRAME - 4) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Adx.open(r, _opts) +if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if Adx.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an ADX file") + end + local h = r:sub(0) + local copyright = (h:seek(2) and h:u16be()) or 0 + local start = copyright + 4 + local enc, fsize, bits, ch = h:u8(), h:u8(), h:u8(), h:u8() + local rate, frames, cutoff, version = h:u32be(), h:u32be(), h:u16be(), h:u16be() + if h.err then + return nil, h.err + end + if version == 0x0408 or version == 0x0409 then + return nil, Err.new(Err.UNSUPPORTED, "encrypted ADX (keys needed)") + end + if enc ~= 3 then + return nil, Err.new(Err.UNSUPPORTED, "encoding type " .. enc .. ((enc == 0x10 or enc == 0x11 )and" (AHX)" or"")) + end + if fsize ~= FRAME or bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, string.format("frame size %d, %d bits", fsize, bits)) + end + if ch < 1 or ch > 8 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + if version ~= 0x0300 and version ~= 0x0400 and version ~= 0x0500 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%04X", version)) + end + local size = r.limit - r.base - start + if size < 0 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + -- loop points and the initial history (vgmstream's reading of the extra header fields) + local hist= nil + local loopsAt= nil + if version == 0x0300 then + if start - 6 >= 0x14 + 0x18 then + loopsAt = 0x14 + end + elseif version == 0x0400 then + local hsize = (ch > 1 and((4 * ch ))or(8 +)) hist = {} + for c = 0, ch - 1 do + local hh = r:sub(0x18 + c * 4, 4) + local h1, h2 = hh:i16be(), hh:i16be() + hist[c * 2 + 1], hist[c * 2 + 2] = hh.err and 0 or h1, hh.err and 0 or h2 + end + local ainf = 0 + local ai = r:sub(0x18 + hsize + 4, 8) + if ai:string(4) == "AINF" then + ainf = ai:u32be() + end + if start - ainf - 6 >= 0x18 + hsize + 0x18 then + loopsAt = 0x18 + hsize + end + end + local loopTable= nil + if loopsAt then + local l = r:sub(loopsAt + 4, 0x14) + local flag, ls, _, le = l:u32be(), l:u32be(), l:u32be(), l:u32be() + if not l.err and flag ~= 0 and le > ls then + loopTable = { start = ls, stop = le } + end + end + local c1, c2 = Adpcm.adxCoefs(cutoff, rate) + local dec= { sampleRate = rate, channels = ch, tags = {}, version = version, cutoff = cutoff, loop = loopTable } + local d, err = Decoder.interleaved(dec, { + kind = "adx", + buf = r.buf, + offset = r.base + start, + size = size, + interleave = FRAME, + frames = frames, + c1 = c1, + c2 = c2, + v3 = version == 0x0300, + hist = hist, + }) + if not d then + return nil, err + end + d.bitrate = math.floor(rate * FRAME * ch * 8 / 32 +) return d, nil +end + +return Adx +end +__FILES["audio/aiff"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- audio/aiff: AIFF and AIFF-C (Apple Audio Interchange File Format 1.3, AIFF-C draft 1991). New code from the specs. +-- Supports: decode / open of AIFF PCM (1..32 bits, big endian) and AIFF-C NONE / twos / sowt (little endian) / raw +-- (unsigned 8-bit) / in24 / in32 / fl32 / fl64 / ulaw / alaw; NAME / AUTH / (c) / ANNO chunks as tags; truncated +-- SSND data (the frames present are decoded, meta.source.truncated). Encode (Audio or Decoder, streamed) to AIFF 8 / +-- 16 / 24 / 32-bit, or AIFF-C sowt / fl32 / fl64 / ulaw / alaw. AIFF-C ima4 (Apple IMA ADPCM, codecs/audio/Adpcm; +-- COMM counts packets of 64 frames) decodes too. Not supported: the other compressed AIFF-C codecs (MAC3 / MAC6, +-- Qclp, ...: Err.UNSUPPORTED), MARK / INST loops (ignored), the ID3 chunk. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Aiff = { + name = "aiff", + category = "audio", + extensions = { "aiff", "aif", "aifc", "afc" }, + mime = { "audio/aiff", "audio/x-aiff" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder", "containers/Chunks" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local TEXT_TAGS = { NAME = "title", AUTH = "artist", ["(c) "] = "copyright", ANNO = "comment" } +local TEXT_ORDER = { { "NAME", "title" }, { "AUTH", "artist" }, { "(c) ", "copyright" }, { "ANNO", "comment" } } +local AIFC_VERSION = 0xA2805140 + +-- ext80(b, o) -> the 80-bit IEEE extended float at b[o] (big endian) +local function ext80(b, o) +local se = buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) + local hi = bit32.byteswap(buffer.readu32(b, o + 2)) + local lo = bit32.byteswap(buffer.readu32(b, o + 6)) + local e = bit32.band(se, 0x7FFF) + if e == 0 and hi == 0 and lo == 0 then + return 0 + end + if e == 0x7FFF then + return math.huge + end + local v = (hi * 4294967296 + lo) * 2 ^ (e - 16383 - 63) + return (se >= 0x8000 and{(-v )}or{v +})[1]end + +-- the 10 bytes of x (> 0) as an 80-bit extended float +local function writeExt80(w, x) + if x <= 0 or x ~= x then + w:fill(0, 10) + return + end + local e = 0 + while x >= 2 ^ (e + 1) do + e =e+ 1 + end + while x < 2 ^ e do + e =e- 1 + end + local m = x * 2 ^ (63 - e) -- in [2^63, 2^64) + local hi = math.floor(m / 4294967296) + local lo = m - hi * 4294967296 + w:u16be(e + 16383) + w:u32be(hi) + w:u32be(math.floor(lo)) +end + +-- the sample format of a COMM chunk: Pcm format name | nil, message +local function sampleFormat(comp, bits) +if comp == "NONE" or comp == "twos" or comp == "" then + if bits >= 1 and bits <= 8 then + return "s8", nil + elseif bits <= 16 then + return "s16be", nil + elseif bits <= 24 then + return "s24be", nil + elseif bits <= 32 then + return "s32be", nil + end + return nil, "bad sample size " .. bits + elseif comp == "sowt" then + if bits >= 1 and bits <= 8 then + return "s8", nil + elseif bits <= 16 then + return "s16le", nil + elseif bits <= 24 then + return "s24le", nil + elseif bits <= 32 then + return "s32le", nil + end + return nil, "bad sample size " .. bits + elseif comp == "raw " then + return "u8", nil + elseif comp == "in24" then + return "s24be", nil + elseif comp == "in32" then + return "s32be", nil + elseif comp == "42ni" then + return "s32le", nil + elseif comp == "fl32" or comp == "FL32" then + return "f32be", nil + elseif comp == "fl64" or comp == "FL64" then + return "f64be", nil + elseif comp == "ulaw" or comp == "ULAW" then + return "ulaw", nil + elseif comp == "alaw" or comp == "ALAW" then + return "alaw", nil + elseif comp == "ima4" then + return "ima4", nil -- not a Pcm format: Adpcm/Decoder.blocks + end + return nil, "compression " .. string.format("%q", comp) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Aiff.sniff(r) +if r:remaining() < 12 or r:peek(4) ~= "FORM" then + return 0 + end + local form = buffer.readstring(r.buf, r.pos + 8, 4) + return (form == "AIFF" or form == "AIFC" )and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- parse(r) -> Info | nil, Err (walks the chunks; does not decode samples) + + + + + + + + + + + + + + + +local function parse(r) +local b = r.buf + local base, limit = r.base, r.limit + if limit - base < 12 or buffer.readstring(b, base, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not a FORM file", base) + end + local form = buffer.readstring(b, base + 8, 4) + if form ~= "AIFF" and form ~= "AIFC" then + return nil, Err.new(Err.CORRUPT, "FORM type " .. string.format("%q", form) .. " is not AIFF / AIFC", base + 8) + end + local aifc = form == "AIFC" + local formEnd = math.min(limit, base + 8 + bit32.byteswap(buffer.readu32(b, base + 4))) + local info= nil + local comm = false + local ssnd= nil + local ssndLen = 0 + local tags= {} + -- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body) + for _, c in __iter(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) + end + local ch = buffer.readu8(b, d) * 256 + buffer.readu8(b, d + 1) + local frames = bit32.byteswap(buffer.readu32(b, d + 2)) + local bits = buffer.readu8(b, d + 6) * 256 + buffer.readu8(b, d + 7) + local rate = ext80(b, d + 8) + local comp = (aifc and{(buffer.readstring(b, d + 18, 4) )}or{"NONE" +})[1] if ch < 1 then + return nil, Err.new(Err.CORRUPT, "no channels", d) + end + if not (rate > 0 and rate < 2 ^ 31) then + return nil, Err.new(Err.CORRUPT, "bad sample rate", d + 8) + end + local fmt, why = sampleFormat(comp, bits) + if not fmt then + return nil, Err.new(((comp == "NONE" or comp == "twos" or comp == "sowt" )and{Err.CORRUPT }or{Err.UNSUPPORTED})[1], why , d + 18) + end + info = { + channels = ch, + frames = frames, + sampleRate = rate, + bits = bits, + format = fmt, + compression = comp, + aifc = aifc, + dataOffset = 0, + dataSize = 0, + truncated = false, + tags = tags, + } + comm = true + elseif id == "SSND" then + if avail < 8 then + return nil, Err.new(Err.TRUNCATED, "SSND chunk too short", p) + end + local off = bit32.byteswap(buffer.readu32(b, d)) + ssnd = d + 8 + off + ssndLen = math.max(0, avail - 8 - off) + if len >= 8 + off then + ssndLen = math.min(ssndLen, len - 8 - off) + end + elseif TEXT_TAGS[id] then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + local key = TEXT_TAGS[id] + tags[key] = (tags[key] and((tags[key] .. "\n" .. s ))or(s +)) end + if len > formEnd - d then + break + end + end + if not comm or not info then + return nil, Err.new(Err.CORRUPT, "no COMM chunk", base) + end + local fi = info +if fi.frames > 0 and not ssnd then + return nil, Err.new(Err.TRUNCATED, "no SSND chunk", base) + end + local present + if fi.format == "ima4" then + fi.frames =fi.frames* 64 -- COMM counts packets + present = (ssnd and((math.floor(ssndLen / (34 * fi.channels) )* 64 ))or(0 +)) else + present = (ssnd and{(math.floor(ssndLen / (fi.channels * Pcm.Convert.SIZE[fi.format]) ))}or{0 +})[1] end + if present < fi.frames then + fi.frames = present + fi.truncated = true + end + fi.dataOffset = ssnd or base + fi.dataSize = ssndLen + return fi, nil +end + +-- info(r) -> { channels, frames, sampleRate, bits, format, compression, aifc, tags } | nil, Err +function Aiff.info(r) +return parse(r) +end + +function Aiff.decode(r, opts) +local dec, err = Aiff.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +local FORMATS = { + s8 = { "s8", 8, "NONE" }, + s16 = { "s16be", 16, "NONE" }, + s24 = { "s24be", 24, "NONE" }, + s32 = { "s32be", 32, "NONE" }, + f32 = { "f32be", 32, "fl32" }, + f64 = { "f64be", 64, "fl64" }, + ulaw = { "ulaw", 16, "ulaw" }, + alaw = { "alaw", 16, "alaw" }, +} +local LE = { s16be = "s16le" } +local COMP_NAMES = { NONE = "not compressed", sowt = "", fl32 = "32-bit floating point", fl64 = "64-bit floating point", ulaw = "\181Law 2:1", alaw = "ALaw 2:1" } + +function Aiff.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local spec = FORMATS[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + local fmt, bits, comp = spec[1], spec[2], spec[3] + if o.littleEndian then + if not LE[fmt] then + return nil, Err.new(Err.ARG, "littleEndian needs 16-bit samples") + end + fmt, comp = LE[fmt], "sowt" + end + if src.channels > 65535 then + return nil, Err.new(Err.ARG, "too many channels") + end + local aifc = o.aifc or comp ~= "NONE" + local w = Bytes.writer(65536) + w:string("FORM") + w:u32be(0) -- patched + w:string(aifc and"AIFC" or"AIFF") + if aifc then + w:string("FVER") + w:u32be(4) + w:u32be(AIFC_VERSION) + end + -- text chunks from the tags + for _, pair in __iter(TEXT_ORDER) do + local id, key = pair[1], pair[2] + local s = src.tags[key] + if type(s) == "string" and #s > 0 then + w:string(id) + w:u32be(#s) + w:string(s) + if #s % 2 == 1 then + w:u8(0) + end + end + end + local commAt = w:tell() + w:string("COMM") + if aifc then + local name = COMP_NAMES[comp] or "" + local plen = 1 + #name + plen =plen+ plen % 2 + w:u32be(22 + plen) + else + w:u32be(18) + end + w:u16be(src.channels) + w:u32be(0) -- frames, patched + w:u16be(bits) + writeExt80(w, src.sampleRate) + if aifc then + w:string(comp) + local name = COMP_NAMES[comp] or "" + w:u8(#name) + w:string(name) + if (1 + #name) % 2 == 1 then + w:u8(0) + end + end + local ssndAt = w:tell() + w:string("SSND") + w:u32be(0) -- patched + w:u32be(0) -- offset + w:u32be(0) -- block size + local frames, perr = Pcm.encode(src, fmt, w) + if not frames then + return nil, perr + end + local dataLen = w:tell() - ssndAt - 16 + if dataLen % 2 == 1 then + w:u8(0) + end + w:setU32be(ssndAt + 4, dataLen + 8) + w:setU32be(commAt + 10, frames) + w:setU32be(4, w:tell() - 8) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Aiff.open(r, opts) +local info, err = parse(r) + if not info then + return nil, err + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if info.frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", info.frames, maxFrames)) + end + local dec, derr + if info.format == "ima4" then + local base = { sampleRate = info.sampleRate, channels = info.channels, tags = info.tags } + dec, derr = Adpcm.blocks(base, { kind = "ima_qt", buf = r.buf, offset = info.dataOffset, size = info.dataSize, frames = info.frames }) + if dec then + (dec ).bitrate = math.floor(info.sampleRate * 34 * 8 * info.channels / 64) + end + else + dec, derr = Pcm.rawDecoder(r.buf, info.dataOffset, info.frames, info.channels, info.sampleRate, info.format, info.tags) + end + if not dec then + return nil, derr + end + local d = dec +d.source = { + format = "aiff", + aifc = info.aifc, + compression = info.compression, + bitDepth = info.bits, + sampleFormat = info.format, + truncated = info.truncated or nil, + } + return dec, nil +end + +return Aiff +end +__FILES["audio/ape"] = function() +local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict +-- audio/ape: Monkey's Audio (.ape) files around codecs/audio/Ape: the header in front (after an optional ID3v2 tag), +-- the frames (each independent: sample-accurate seeking through the seek table), APEv2 tags at the end +-- (codecs/audio/ApeTag). Written from the Monkey's Audio SDK 13.28 (BSD 3-clause, licenses/monkeys-audio-LICENSE.txt). +-- Supports file versions 3.95 and later, every compression level, 8 - 32-bit integer and 32-bit float, 1 - 32 +-- channels (as the source WAV ordered them). Not supported: files before 3.95, encoding. +-- +-- local dec = Ape.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, level, version, float, md5 +-- local i32, n = dec:readInt(4096) -- integer files: the samples as `mac -d` writes them +-- local audio = Ape.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local ApeCodec = __include("codecs/audio/Ape") + +-- ------------------------------------------------------------------------------------------------ contract +local Ape = { + name = "ape", + category = "audio", + extensions = { "ape" }, + mime = { "audio/ape", "audio/x-ape", "audio/x-monkeys-audio" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Ape" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, float = true, depths = { 8, 16, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local LEVELS = { [1000] = "fast", [2000] = "normal", [3000] = "high", [4000] = "extra high", [5000] = "insane" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ape.sniff(r) +local head = r:peek(4) + if head == "MAC " or head == "MACF" then -- MACF: float samples + return 1 + end + if string.sub(head, 1, 3) == "ID3" then + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + local id = r:peek(4, 10 + sz + (footer and 10 or 0)) + return (id == "MAC " or id == "MACF" )and 1 or 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Ape.decode(r, opts) +local dec, err = Ape.open(r, opts) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Ape.open(r, opts) +if type(r) == "buffer" then + r = Bytes.reader(r ) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = (tagInfo and{tagInfo.start }or{limit +})[1] local info, err = ApeCodec.info(buf, base, stop) + if not info then + return nil, err + end + if info.channels * info.blocksPerFrame > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "frames of " .. info.blocksPerFrame .. " blocks") + end + local codec, cerr = ApeCodec.decoder(info) + if not codec then + return nil, cerr + end + local frames = info.totalBlocks + local bpf = info.blocksPerFrame + local dec= { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + level = LEVELS[info.level] or tostring(info.level), + version = info.version, + md5 = info.md5, + source = { format = "ape", bitDepth = info.bitsPerSample, float = info.float, level = info.level, version = info.version, programVersion = info.programVersion, tags = tagInfo and tagInfo.items }, + } + local count = info.totalFrames + return Stream.packets(dec, { + count = count, + start = function(i) +return (i > count and{frames }or{((i - 1) * bpf +)})[1] end, + decode = function(i) +return codec:frame(buf, i) + end, + pcm = function() +return codec.pcm + end, + reset = function() end, + stop = frames, + scale = info.float and 1 or 1 / 2 ^ (info.bitsPerSample - 1), + ints = not info.float, + }) +end + +return Ape +end +__FILES["audio/au"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- audio/au: Sun / NeXT audio (.au / .snd), big endian. New code from the Sun audio file format description. +-- Supports: decode / open of encodings 1 (G.711 mu-law), 2 (8-bit), 3 (16-bit), 4 (24-bit), 5 (32-bit linear), +-- 6 (32-bit float), 7 (64-bit float), 27 (G.711 A-law); an unknown data size (0xFFFFFFFF: to the end of the file); +-- the annotation as tags.comment. Encode (Audio or Decoder, streamed) to any of those encodings (default 16-bit). +-- Not supported: G.721 / G.722 / G.723 ADPCM and the other NeXT encodings (Err.UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Au = { + name = "au", + category = "audio", + extensions = { "au", "snd" }, + mime = { "audio/basic", "audio/x-au" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local ENCODINGS= { + [1] = "ulaw", + [2] = "s8", + [3] = "s16be", + [4] = "s24be", + [5] = "s32be", + [6] = "f32be", + [7] = "f64be", + [27] = "alaw", +} +local WRITE = { + ulaw = { 1, "ulaw" }, + s8 = { 2, "s8" }, + s16 = { 3, "s16be" }, + s24 = { 4, "s24be" }, + s32 = { 5, "s32be" }, + f32 = { 6, "f32be" }, + f64 = { 7, "f64be" }, + alaw = { 27, "alaw" }, +} +local BITS = { ulaw = 8, alaw = 8, s8 = 8, s16be = 16, s24be = 24, s32be = 32, f32be = 32, f64be = 64 } + +local function be32(b, o) +return bit32.byteswap(buffer.readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Au.sniff(r) +return r:peek(4) == ".snd" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Au.decode(r, opts) +local dec, err = Au.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Au.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + -- annotation: the comment tag, NUL-terminated, padded to a multiple of 8 (at least 4 bytes, as Sun requires) + local note = (type(src.tags.comment) == "string" and{src.tags.comment }or{"" +})[1] local alen = #note + 1 + alen = math.max(8, alen + (8 - alen % 8) % 8) + local w = Bytes.writer(65536) + w:string(".snd") + w:u32be(24 + alen) + w:u32be(0xFFFFFFFF) -- patched + w:u32be(spec[1]) + w:u32be(src.sampleRate) + w:u32be(src.channels) + w:string(note) + w:fill(0, alen - #note) + local frames, perr = Pcm.encode(src, spec[2], w) + if not frames then + return nil, perr + end + w:setU32be(8, w:tell() - 24 - alen) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Au.open(r, opts) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < 24 or buffer.readstring(b, base, 4) ~= ".snd" then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local off, size, enc, rate, ch = be32(b, base + 4), be32(b, base + 8), be32(b, base + 12), be32(b, base + 16), be32(b, base + 20) + local fmt = ENCODINGS[enc] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. enc, base + 12) + end + if ch < 1 or ch > 65535 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch, base + 20) + end + if rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate", base + 16) + end + if off < 24 or off > limit - base then + return nil, Err.new(Err.CORRUPT, "bad data offset", base + 4) + end + local tags= {} + if off > 24 then + local s = buffer.readstring(b, base + 24, off - 24) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + if #s > 0 then + tags.comment = s + end + end + local avail = limit - base - off + local truncated = false + if size == 0xFFFFFFFF then + size = avail + elseif size > avail then + size = avail + truncated = true + end + local frameBytes = ch * Pcm.Convert.SIZE[fmt] + local frames = math.floor(size / frameBytes +) local maxFrames = opts and opts.maxFrames or 2 ^ 28 + if frames > maxFrames then + return nil, Err.new(Err.LIMIT, string.format("%d frames is over the %d frame limit", frames, maxFrames)) + end + local dec, derr = Pcm.rawDecoder(b, base + off, frames, ch, rate, fmt, tags) + if not dec then + return nil, derr + end + local d = dec +d.source = { format = "au", encoding = enc, sampleFormat = fmt, bitDepth = BITS[fmt], truncated = truncated or nil } + return dec, nil +end + +return Au +end +__FILES["audio/brstm"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- audio/brstm: Nintendo's streamed audio: BRSTM (Wii, "RSTM", big-endian), BCSTM (3DS, "CSTM", little-endian) and +-- BFSTM (Wii U big-endian / Switch little-endian, "FSTM"), over codecs/audio/Adpcm. New in rosetta; the layouts +-- follow vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: DSP +-- ADPCM (with the header's initial history; seeks into blocks not yet played use the ADPC / SEEK history table), PCM16 +-- and PCM8, 1-255 channels in block-interleaved layout, the loop start (dec.loop and meta.source.loop = { start, stop } +-- in frames, stop exclusive). Read only. Not supported: BCSTM IMA ADPCM, BRSTM version 0.1 (beta), BFSTM regions +-- (the whole stream plays), the track table (channels are not grouped). +-- +-- local dec = Brstm.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, container, codec) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Brstm = { + name = "brstm", + category = "audio", + extensions = { "brstm", "bcstm", "bfstm" }, + mime = { "audio/x-brstm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = false, streaming = true, lossy = true, loops = true, containers = { "RSTM", "CSTM", "FSTM" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local CODECS = { [0] = "pcm8", [1] = "pcm16", [2] = "dsp", [3] = "ima" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Brstm.sniff(r) +local m = r:peek(4) + if m ~= "RSTM" and m ~= "CSTM" and m ~= "FSTM" then + return 0 + end + local bom = r:peek(2, 4) + return (bom == "\254\255" or bom == "\255\254" )and 1 or 0 +end + +-- variant(r) -> "brstm" / "bcstm" / "bfstm": the flavour, for F.detect +function Brstm.variant(r) +local m = r:peek(4) + return m == "RSTM" and"brstm" or(m == "CSTM" and"bcstm" or(m == "FSTM" and"bfstm" or nil +))end + +-- ------------------------------------------------------------------------------------------------ decode +function Brstm.decode(r, opts) +local dec, err = Brstm.open(r) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "brstm", container = d.container, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- a reader of the whole file in its byte order: u8 / u16 / u32 / i16 / i32 at absolute offsets (relative to the file +-- start); a read out of range records the error in .err and returns 0 +local function view(r, be) + local v = { err = nil } + local size = r.limit - r.base + local function at(o, n) +if o < 0 or o + n > size then + v.err = "an offset points past the end" + return nil + end + return r:sub(o, n) + end + function v.u8(o) +local s = at(o, 1) + return (s and{(s:u8() )}or{0 +})[1] end + function v.u16(o) +local s = at(o, 2) + return (s and{((be and{(s:u16be() )}or{(s:u16le())})[1]) }or{0 +})[1] end + function v.i16(o) +local s = at(o, 2) + return (s and{((be and{(s:i16be() )}or{(s:i16le())})[1]) }or{0 +})[1] end + function v.u32(o) +local s = at(o, 4) + return (s and{((be and{(s:u32be() )}or{(s:u32le())})[1]) }or{0 +})[1] end + function v.i32(o) +local s = at(o, 4) + return (s and{((be and{(s:i32be() )}or{(s:i32le())})[1]) }or{0 +})[1] end + return v +end + + + + + + + + + + + + + + + + +local function parseRstm(v) +if v.u16(0x06) ~= 0x0100 then + return nil, string.format("unsupported: BRSTM version %d.%d", v.u8(0x06), v.u8(0x07)) + end + local head = v.u32(0x10) + local adpc = v.u32(0x18) + if v.u32(head) ~= 0x48454144 then -- "HEAD", read big-endian + return nil, "no HEAD chunk" + end + local base = head + 8 + local info = base + v.u32(base + 4) + local chans = base + v.u32(base + 20) + local ch = v.u8(info + 2) + local L= { + codec = v.u8(info), + loop = v.u8(info + 1) ~= 0, + ch = ch, + rate = v.u16(info + 4), + loopStart = v.u32(info + 8), + frames = v.u32(info + 12), + data = v.u32(info + 16), + blockSize = v.u32(info + 24), + lastPadded = v.u32(info + 40), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = base + v.u32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = base + v.u32(ci + 4) + end + if adpc > 0 and v.u32(adpc) == 0x41445043 then -- "ADPC" + L.hist = adpc + 8 + L.histEntries = math.floor((v.u32(adpc + 4) - 8) / math.max(1, 4 * ch) +) end + return L, nil +end + +local function parseFstm(v) +local info, seek, data= 0, 0, 0 + local seekSize= 0 + for i = 0, math.min(v.u16(0x10), 16) - 1 do + local id, off = v.u16(0x14 + i * 12), v.u32(0x14 + i * 12 + 4) + if id == 0x4000 then + info = off + elseif id == 0x4001 then + seek = off + seekSize = (v.u32(0x14 + i * 12 + 8) ) +elseif id == 0x4002 then + data = off + end + end + if info == 0 or data == 0 then + return nil, "no INFO or DATA block" + end + local stream = info + 8 + v.i32(info + 0x0C) + local chans = info + 8 + v.i32(info + 0x1C) + local ch = v.u8(stream + 2) + local dataRef = stream + 0x30 + local L= { + codec = v.u8(stream), + loop = v.u8(stream + 1) ~= 0, + ch = ch, + rate = v.u32(stream + 4), + loopStart = v.u32(stream + 8), + frames = v.u32(stream + 12), + blockSize = v.u32(stream + 20), + lastPadded = v.u32(stream + 36), + data = (v.u16(dataRef) == 0x1F00 and((data + 8 + v.i32(dataRef + 4) ))or((data + 0x20))), + adp = {}, + hist = nil, + histEntries = 0, + } + for c = 0, ch - 1 do + local ci = chans + v.i32(chans + 4 + c * 8 + 4) + L.adp[c + 1] = ci + v.i32(ci + 4) + end + if seek > 0 and seekSize > 8 then + L.hist = seek + 8 + L.histEntries = math.floor((seekSize - 8) / math.max(1, 4 * ch) +) end + return L, nil +end + +function Brstm.open(r, _opts) +if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + if r.limit - r.base < 0x40 then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + if Brstm.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a BRSTM / BCSTM / BFSTM file") + end + local magic = r:peek(4) + local be = r:peek(2, 4) == "\254\255" + local v = view(r, be) + local parsed, msg +if magic == "RSTM" then + if not be then + return nil, Err.new(Err.CORRUPT, "a little-endian BRSTM") + end + parsed, msg = parseRstm(v) + else + parsed, msg = parseFstm(v) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + elseif not parsed then + return nil, Err.from(msg) + end + local L = parsed +local codec = CODECS[L.codec] + if not codec then + return nil, Err.new(Err.CORRUPT, "codec " .. L.codec) + elseif codec == "ima" then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM streams") + end + local ch = L.ch + if ch < 1 or L.rate < 1 then + return nil, Err.new(Err.CORRUPT, "bad channel count or sample rate") + end + local size = r.limit - r.base - L.data + if L.data < 0 or size < 0 then + return nil, Err.new(Err.TRUNCATED, "the data starts past the end") + end + local kind = codec == "dsp" and"dsp" or(codec == "pcm8" and"s8" or(be and"s16be" or"s16le" +)) local coefs= nil + local hist= nil + if codec == "dsp" then + coefs = buffer.create(64 * ch) + hist = {} + for c = 0, ch - 1 do + local adp = L.adp[c + 1] + for k = 0, 15 do + buffer.writei32(coefs , c * 64 + k * 4, v.i16(adp + k * 2)) + end + hist[c * 2 + 1], hist[c * 2 + 2] = v.i16(adp + 36), v.i16(adp + 38) + end + if v.err then + return nil, Err.new(Err.TRUNCATED, v.err) + end + end + local histAt, entries = L.hist, L.histEntries + local loop = L.loop and L.loopStart < L.frames and{ start = L.loopStart, stop = L.frames } or nil + local dec= { sampleRate = L.rate, channels = ch, tags = {}, container = magic, codec = codec, loop = loop } + local block = L.blockSize + if block < 1 or (kind == "dsp" and block % 8 ~= 0) or (kind ~= "s8" and block % 2 ~= 0) then + return nil, Err.new(Err.CORRUPT, "bad block size " .. block) + end + local d, err = Decoder.interleaved(dec, { + kind = kind , + buf = r.buf, + offset = r.base + L.data, + size = size, + interleave = block, + lastInterleave = (L.lastPadded > 0 and L.lastPadded <= block and{L.lastPadded }or{block})[1], + frames = L.frames, + coefs = coefs, + hist = hist, + restore = codec == "dsp" and histAt +and function(row, st) +if row >= entries then + return false + end + for c = 0, ch - 1 do + local p = (histAt ) + (row * ch + c) * 4 + buffer.writei32(st, c * 8, v.i16(p)) + buffer.writei32(st, c * 8 + 4, v.i16(p + 2)) + end + return v.err == nil + end +or nil, + }) + if d then + d.bitrate = (d.duration > 0 and{(math.floor(size * 8 / d.duration) )}or{0 +})[1] end + return d, err +end + +return Brstm +end +__FILES["audio/caf"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!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/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. IMA4 (Apple IMA ADPCM, codecs/audio/Adpcm) decodes too, with exact seeking. Not supported: +-- other compressed formats (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") +local Adpcm = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Adpcm/Decoder", "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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local INFO_TAGS= { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO= {} +for k, v in __iter(INFO_TAGS) do + TAG_INFO[v] = k +end + +-- mu-law / A-law -> linear 16-bit +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = (bit32.band(u, 128) ~= 0 and((132 - t ))or((t - 132 +))) local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = (bit32.band(a, 128) ~= 0 and{m }or{(-m +)})[1]end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r) +local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo + + + + + + + + + + + + + + + +local function esdsConfig(b) +local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len() +local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n + end + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r) +local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +local function parse(r, o) +if Caf.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) + end + local p= { desc = nil , dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + -- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file + for _, ch in __iter(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 = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = (d.bytesPerPacket == 0 and{(vlq(c) )}or{d.bytesPerPacket +})[1] if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v + end + end + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end +-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err + + + + + + + + + + + + + +local function source(r, p) +local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = (fmt == "lpcm" and{d.bits }or{8 +})[1] local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (math.floor(bits / 8)) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = math.floor(bits / 8 +) if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = math.floor((p.dataEnd - p.dataStart) / bpf +) local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src= { + channels = ch, + rate = d.rate, + packetCount = math.floor((total + per - 1) / per), + packetFrames = function(i) +return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = fmt == "lpcm" and"pcm" or fmt, + bits = bits, + decode = function(i) +local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = (little and{(buffer.readf32(b, q) )}or{(Bytes.reader(b, q, 4):f32be() +)})[1] else + v = (little and{(buffer.readf64(b, q) )}or{(Bytes.reader(b, q, 8):f64be() +)})[1] end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = (little and{(buffer.readi16(b, q) )}or{(readi8(b, q) * 256 + readu8(b, q + 1) +)})[1] v =v* scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v =v* scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v =v* scale + end + pcm[k] = v + k =k+ 1 + q =q+ bps + end + end + return n, nil + end, + } + return src, nil + end + -- packetised codecs + local sizes = p.packets + if not sizes or (#sizes == 0 and d.bytesPerPacket > 0) then -- constant packets: pakt may list none + if d.bytesPerPacket > 0 then + local n = math.floor((p.dataEnd - p.dataStart) / d.bytesPerPacket +) sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#(sizes ), 0) + local o = p.dataStart + for i, s in __iter(sizes) do + offsets[i] = o + o =o+ s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil +sizes = table.move(sizes , 1, i - 1, 1, {}) + break + end + end + local count = #(sizes ) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i) +return (pf and{pf[i] }or{fpp +})[1] end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie ) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i) +local n, e = dec:decode(b, offsets[i], (sizes )[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = (cookie and{(esdsConfig(cookie ) )}or{nil +})[1] if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc ) + if not dec then + return nil, err + end + local ad = dec +return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i) +return ad:decode(b, offsets[i], (sizes )[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r, opts) +local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local pp = p +if pp.desc.format == "ima4" then + -- Apple IMA ADPCM: 34-byte packets per channel, 64 frames; the predictor carries across packets + local ch = pp.desc.channels + local packets = math.floor((pp.dataEnd - pp.dataStart) / (34 * ch) +) local frames = packets * 64 + if pp.validFrames and pp.validFrames >= 0 then + frames = math.min(frames, pp.validFrames) + end + local dec= { sampleRate = pp.desc.rate, channels = ch, tags = pp.tags, codec = "ima4", bitsPerSample = 16 } + local d, derr = Adpcm.blocks(dec, { kind = "ima_qt", buf = r.buf, offset = pp.dataStart, size = pp.dataEnd - pp.dataStart, frames = frames }) + if d then + d.bitrate = math.floor(pp.desc.rate * 34 * 8 * ch / 64) + end + return d, derr + end + local s, serr = source(r, pp) + if not s then + return nil, serr + end + local src = s +local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total =total+ src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local dec= { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = (frames > 0 and{(math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) )}or{0})[1], + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + } + return Stream.packets(dec, { + count = src.packetCount, + start = function(i) +return starts[i] + end, + decode = src.decode, + pcm = function() +return src.pcm + end, + reset = src.reset, + skip = skip, + stop = stopAt, + preroll = src.codec == "aac" and 1 or 0, + }) +end + +function Caf.decode(r, opts) +local dec, err = Caf.open(r, opts) + if not dec then + return nil, err + end + local d= dec + return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w, typ, size) + w:string(typ) + w:i64be(size) +end + +-- encode(audio | decoder, opts?) -> buffer | nil, Err +function Caf.encode(value, opts) +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") + end + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + -- the source frames + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf= nil + local function nextBlock(n) +if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done =done+ k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done =done+ got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes= {} + local enc= nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e ):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(depth == 32 and 1 or 0) -- float / big-endian integer + w:u32be(math.floor(ch * depth / 8)) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in __iter(tags) do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in __iter(keys) do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in __iter(sizes) do + -- BER variable-length integer + local bytes = { s % 128 } + local v = math.floor(s / 128 +) while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v =math.floor(v/ 128 +) end + for _, x in __iter(bytes) do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf +end +__FILES["audio/flac"] = function() +local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict +-- audio/flac: FLAC (RFC 9639), native and in Ogg (the Ogg FLAC mapping). Absorbed from flac-luau 7083d0d (same author, +-- no third-party code); the Ogg demuxer is now a direct require of containers/Ogg instead of an injected module. +-- Supports: every subframe type (constant, verbatim, fixed, LPC up to order 32, wasted bits), Rice / Rice2 residuals +-- 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 (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 +-- local i32, n = dec:readInt(4096) -- bit-exact integer samples +-- local audio = Flac.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Stream = __include("audio/flac/Stream") +local Encode = __include("codecs/audio/Flac/Encode") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Flac = { + name = "flac", + category = "audio", + extensions = { "flac", "oga" }, + mime = { "audio/flac", "audio/x-flac" }, + 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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + +function Flac.sniff(r) +local head = r:peek(4) + if head == "fLaC" then + return 1 + end + if head == "OggS" then + -- the first page's packet: 0x7F "FLAC" (the Ogg FLAC mapping) + local nseg = r:peekU8(26) + if nseg > 0 and r:peek(5, 27 + nseg) == "\127FLAC" then + return 1 + end + return 0 + end + if string.sub(head, 1, 3) == "ID3" then + -- an ID3v2 tag, then fLaC (mp3 files start with ID3 too) + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return r:peek(4, 10 + sz + (footer and 10 or 0)) == "fLaC" and 1 or 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Flac.decode(r, opts) +local dec, err = Flac.open(r, opts) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + 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 +-- encode(audioOrDecoder, opts?) -> FLAC file buffer | nil, Err +function Flac.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local level = o.level or 5 + if type(level) ~= "number" or level ~= math.floor(level) or level < 0 or level > 8 then + return nil, Err.new(Err.ARG, "level must be 0..8") + end + local bits = o.bits + if bits == nil then + local v = value +local sb = (type(v.meta) == "table" and type(v.meta.source) == "table" and v.meta.source.bitDepth) or v.bitsPerSample + bits = (type(sb) == "number" and sb >= 4 and sb <= 24 and{sb }or{16 +})[1] end + if type(bits) ~= "number" or bits ~= math.floor(bits) or bits < 4 or bits > 24 then + return nil, Err.new(Err.ARG, "bits must be 4..24") + end + local bs = o.blockSize + if bs ~= nil and (type(bs) ~= "number" or bs ~= math.floor(bs) or bs < 16 or bs > 65535) then + return nil, Err.new(Err.ARG, "blockSize must be 16..65535") + end + if src.channels > 8 then + return nil, Err.new(Err.ARG, "FLAC holds at most 8 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 20 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer below 2^20") + end + local out, msg = Encode.encode(src , { + level = level, + bits = bits , + blockSize = bs, + seekInterval = math.max(0, o.seekInterval or 10), + padding = math.clamp(math.floor(o.padding or 0), 0, 0xFFFFFF), + vendor = "rosetta", + }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Flac.open(r, opts) +if type(r) == "buffer" then + r = Bytes.reader(r ) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local dec, msg, code = Stream.open(r.buf, r.base, r.limit - r.base, opts) + if not dec then + return nil, Err.new(code or Err.CORRUPT, tostring(msg)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Flac.Stream = Stream +Flac.Ogg = Ogg + +return Flac +end +__FILES["audio/flac/Meta"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +--!native +--!optimize 2 +-- 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 = __include("codecs/audio/VorbisComment") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Meta = {} + +local function be16(b, p) +return readu8(b, p) * 256 + readu8(b, p + 1) +end +local function be24(b, p) +return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end +local function be32(b, p) +return be16(b, p) * 65536 + be16(b, p + 2) +end + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function streamInfo(b, p) +local b12, b13 = readu8(b, p + 12), readu8(b, p + 13) + local hex = table.create(16) + for i = 0, 15 do + hex[i + 1] = string.format("%02x", readu8(b, p + 18 + i)) + end + return { + minBlockSize = be16(b, p), + maxBlockSize = be16(b, p + 2), + minFrameSize = be24(b, p + 4), + maxFrameSize = be24(b, p + 7), + sampleRate = readu8(b, p + 10) * 4096 + readu8(b, p + 11) * 16 + bit32.rshift(b12, 4), + channels = bit32.band(bit32.rshift(b12, 1), 7) + 1, + bitsPerSample = bit32.band(b12, 1) * 16 + bit32.rshift(b13, 4) + 1, + totalSamples = bit32.band(b13, 15) * 4294967296 + be32(b, p + 14), + md5 = table.concat(hex), + } +end + +local function vorbisComment(b, p, e, info) +if p + 4 > e then + return false + end + local vl = readu32(b, p) + p =p+ 4 + if p + vl > e then + return false + end + info.vendor = buffer.readstring(b, p, vl) + p =p+ vl + if p + 4 > e then + return false + end + local n = readu32(b, p) + p =p+ 4 + for _ = 1, n do + if p + 4 > e then + return false + end + local l = readu32(b, p) + p =p+ 4 + if p + l > e then + return false + end + local s = buffer.readstring(b, p, l) + p =p+ l + local eq = string.find(s, "=", 1, true) + if eq then + 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] = (old and((old .. "; " .. value ))or(value +)) end + end + return true +end + +local function picture(b, p, e) +if p + 8 > e then + return nil + end + local typ = be32(b, p) + local ml = be32(b, p + 4) + p =p+ 8 + if p + ml + 4 > e then + return nil + end + local mime = buffer.readstring(b, p, ml) + p =p+ ml + local dl = be32(b, p) + p =p+ 4 + if p + dl + 20 > e then + return nil + end + local desc = buffer.readstring(b, p, dl) + p =p+ dl + local pic = { + type = typ, + mime = mime, + description = desc, + width = be32(b, p), + height = be32(b, p + 4), + depth = be32(b, p + 8), + colors = be32(b, p + 12), + offset = p + 20, + size = be32(b, p + 16), + } + if pic.offset + pic.size > e then + return nil + end + return pic +end + +-- Parse the metadata blocks that follow "fLaC" at pos (data ends at len) +function Meta.parse(b, pos, len) +if pos + 4 > len or buffer.readstring(b, pos, 4) ~= "fLaC" then + return nil, "Flac: no fLaC marker" + end + local info= { + streamInfo = nil , + seekTable = {}, + vendor = "", + tags = {}, + comments = {}, + pictures = {}, + firstFrame = 0, + } + local p = pos + 4 + while true do + if p + 4 > len then + return nil, "Flac: truncated metadata" + end + local h = readu8(b, p) + local last = h >= 128 + local typ = bit32.band(h, 127) + local size = be24(b, p + 1) + p =p+ 4 + local e = p + size + if e > len then + return nil, "Flac: truncated metadata block" + end + if typ == 0 then + if size < 34 then + return nil, "Flac: bad STREAMINFO" + end + info.streamInfo = streamInfo(b, p) + elseif typ == 3 then + for q = p, e - 18, 18 do + local hi = be32(b, q) + if hi ~= 0xFFFFFFFF then -- placeholder points are all ones + table.insert(info.seekTable, { + sample = hi * 4294967296 + be32(b, q + 4), + offset = be32(b, q + 8) * 4294967296 + be32(b, q + 12), + samples = be16(b, q + 16), + }) + end + end + elseif typ == 4 then + vorbisComment(b, p, e, info) -- a broken comment block leaves what was read + elseif typ == 6 then + local pic = picture(b, p, e) + if pic then + table.insert(info.pictures, pic) + end + elseif typ == 127 then + return nil, "Flac: invalid metadata block type" + end + p = e + if last then + break + end + end + if not info.streamInfo then + return nil, "Flac: no STREAMINFO" + end + local si = info.streamInfo + if si.sampleRate == 0 then + return nil, "Flac: bad STREAMINFO values" + end + info.firstFrame = p + return info, nil +end + +return Meta +end +__FILES["audio/flac/Stream"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- audio/flac/Stream: the streaming FLAC decoder (native FLAC with an optional ID3v2 tag in front, and Ogg FLAC through +-- containers/Ogg): stream setup, read / readInt with resync past corrupt frames, sample-accurate seeking (seek table, +-- byte bisection by sync search, then a frame walk), length from the last frame when STREAMINFO has none. Absorbed +-- from flac-luau 7083d0d (same author, no third-party code; the Ogg demuxer is now a direct require instead of an +-- injected module). Nothing throws: open returns nil, message, code. +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Frame = __include("codecs/audio/Flac/Frame") +local Meta = __include("audio/flac/Meta") + +local Stream = {} + +local writef32, writei32 = buffer.writef32, buffer.writei32 + +local PAD = Frame.PAD + + + + + + + + + + + + + + + + + + + + + + +local Dec = {} +Dec.__index = Dec + +-- the sample number of a frame +local function sampleOf(self, h) +return (h.variable and{h.number }or{(h.number * self._nominal +)})[1]end + +-- a header that also matches the stream (guards the sync search against false syncs) +local function plausible(self, h) +if h.channels ~= self.channels or h.bps ~= self.bitsPerSample or h.blockSize > 65536 then + return false + end + if self.frames > 0 and sampleOf(self, h) >= self.frames then + return false + end + return true +end + +local function findFrame(self, pos, limit) +local b, len, si = self._b, self._len, self._si + while true do + local h = Frame.find(b, pos, limit, len, si) + if not h then + return nil + end + if plausible(self, h) then + return h + end + pos = h.offset + 1 + end +end + +local function ensure(self, n) + if n > self._cap then + for c = 1, self.channels do + self._chans[c] = table.create(n, 0) + end + self._cap = n + end +end + +-- Decode the frame at or after pos (resyncing past corrupt data). Sets the current frame; false at the end. +local function decodeAt(self, pos) +local b, len = self._b, self._len + while true do + local h = Frame.header(b, pos, len, self._si) + if not h or not plausible(self, h) then + h = findFrame(self, pos, len) + if not h then + self._pos = len + return false + end + end + ensure(self, h.blockSize) + local nextPos = Frame.decode(b, len, h, self._chans, self._cf, self._crc) + if nextPos then + local s = sampleOf(self, h) + local n = h.blockSize + if self.frames > 0 and s + n > self.frames then + n = math.max(0, self.frames - s) + end + self._pos = nextPos + self._fs = s + self._fn = n + self._cur = 0 + return true + end + pos = h.offset + 1 + end +end + +local function pull(self, maxFrames, asInt, dst) +local ch = self.channels + local want = math.floor(tonumber(maxFrames) or 0) + if not (want >= 0) then + want = 0 -- negative or NaN + end + want = math.min(want, math.floor(2 ^ 26 / ch)) -- keeps the output buffer under 256 MB + local reuse = dst ~= nil and type(dst) == "buffer" and buffer.len(dst) >= want * ch * 4 + local out = (reuse and{dst }or{(buffer.create(want * ch * 4) +)})[1] local got = 0 + local scale = 1 / 2 ^ (self.bitsPerSample - 1) + local stride = ch * 4 + while got < want do + if self._cur >= self._fn then + if self._pos >= self._len or not decodeAt(self, self._pos) then + self._fs =self._fs+ self._cur + self._cur, self._fn = 0, 0 + break + end + end + local take = math.min(want - got, self._fn - self._cur) + local from = self._cur + 1 + local to = self._cur + take + for c = 1, ch do + local s = self._chans[c] + local o = (got * ch + c - 1) * 4 + if asInt then + for i = from, to do + writei32(out, o, s[i]) + o =o+ stride + end + else + for i = from, to do + writef32(out, o, s[i] * scale) + o =o+ stride + end + end + end + self._cur =self._cur+ take + got =got+ take + end + if got < want and not reuse then + local short = buffer.create(got * ch * 4) + buffer.copy(short, 0, out, 0, got * ch * 4) + out = short + end + return out, got +end + +-- Up to maxFrames sample frames as interleaved f32 (sample / 2^(bps-1)); 0 frames = end of stream. out (if given) is +-- reused when big enough. +function Dec.read(self, maxFrames, out) +return pull(self, maxFrames, false, out) +end + +-- The same as interleaved i32 integer samples (bit-exact, right-aligned) +function Dec.readInt(self, maxFrames, out) +return pull(self, maxFrames, true, out) +end + +-- seconds, sample frame of the next frame read() returns +function Dec.position(self) +local s = self._fs + self._cur + return s / self.sampleRate, s +end + +-- Seek so the next read starts exactly at sample frame t. Uses the seek table to bracket t, bisects byte offsets +-- by sync search, then walks frame headers forward. Returns false if the stream has no frame there. +function Dec.seekSample(self, t) +t = math.floor(tonumber(t) or 0) + if not (t >= 0) then + t = 0 -- negative or NaN + end + if self.frames > 0 and t >= self.frames then + self._pos, self._fs, self._fn, self._cur = self._len, self.frames, 0, 0 + return true + end + if self._fn > 0 and t >= self._fs and t < self._fs + self._fn then + self._cur = t - self._fs + return true + end + local first, len = self._first, self._len + local lo, hi = first, len + for _, sp in __iter(self.seekTable) do + local o = first + sp.offset + if o < len then + if sp.sample <= t then + lo = math.max(lo, o) + else + hi = math.min(hi, o) + break + end + end + end + local window = math.max(16384, 2 * self._si.maxFrameSize) + while hi - lo > window do + local mid = math.floor((lo + hi) / 2 +) local h = findFrame(self, mid, hi) + if h and sampleOf(self, h) <= t then + lo = h.offset + else + hi = mid + end + end + local pos = lo + while true do + local h = findFrame(self, pos, len) + if not h then + self._pos, self._fs, self._fn, self._cur = len, math.max(t, self.frames), 0, 0 + return false + end + local s = sampleOf(self, h) + if s + h.blockSize > t then + if decodeAt(self, h.offset) then + if self._fs <= t and t < self._fs + self._fn then + self._cur = t - self._fs + return true + elseif self._fs > t then + return false -- a hole in the stream: we are at the next frame + end + pos = self._pos + else + return false + end + else + pos = h.offset + h.size + end + end +end + +function Dec.seek(self, seconds) +return self:seekSample(math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5)) +end + +-- Find the total length from the last frame (when STREAMINFO does not give it) +local function scanLength(self) +local len = self._len + local step = math.max(65536, 2 * self._si.maxFrameSize) + local from = len + while from > self._first do + local start = math.max(self._first, from - step) + local best= nil + local pos = start + while true do + local h = findFrame(self, pos, from) + if not h then + break + end + best = h + pos = h.offset + 1 + end + if best then + local s = sampleOf(self, best) + -- the last frame may be shorter than its header claims only via STREAMINFO, which is unknown here + return s + best.blockSize + end + from = start + end + return 0 +end + +local function skipId3(b, base, len) +local p = 0 + while p + 10 <= len and buffer.readstring(b, base + p, 3) == "ID3" do + local sz = 0 + for i = 6, 9 do + sz = sz * 128 + bit32.band(buffer.readu8(b, base + p + i), 127) + end + local footer = bit32.band(buffer.readu8(b, base + p + 5), 0x10) ~= 0 + p =p+ (10 + sz + (footer and 10 or 0) +) end + return p +end + +-- opts.crc16 = false skips the per-frame CRC-16 check +function Stream.open(buf, base, srcLen, opts) +local b, len, container + if srcLen >= 4 and buffer.readstring(buf, base, 4) == "OggS" then + local demux, err = Ogg.open(Bytes.reader(buf, base, srcLen)) + if not demux then + return nil, (err ).message, "CORRUPT" + end + local serial = demux:find("flac") + if not serial then + return nil, "no FLAC stream in the Ogg file", "CORRUPT" + end + -- rebuild a native stream: "fLaC" + metadata (from the header packets) + frames (one per packet) + local packets, total = {}, 0 + for p in __iter(demux:packets(serial)) do + local off, size = p.offset, p.size + if #packets == 0 then + if size < 13 then + return nil, "bad Ogg FLAC header", "CORRUPT" + end + off =off+ 9 + size =size- 9 + end + table.insert(packets, { p.data, off, size }) + total =total+ size + end + b = buffer.create(total + PAD) + local o = 0 + for _, p in __iter(packets) do + buffer.copy(b, o, p[1], p[2], p[3]) + o =o+ p[3] + end + len = total + container = "ogg" + else + local start = skipId3(buf, base, srcLen) + if start + 4 > srcLen or buffer.readstring(buf, base + start, 4) ~= "fLaC" then + return nil, "not a FLAC file", "CORRUPT" + end + len = srcLen - start + b = buffer.create(len + PAD) + buffer.copy(b, 0, buf, base + start, len) + container = "flac" + end + local info, err = Meta.parse(b, 0, len) + if not info then + return nil, err, "CORRUPT" + end + local si = info.streamInfo + local self = setmetatable({ + sampleRate = si.sampleRate, + channels = si.channels, + bitsPerSample = si.bitsPerSample, + frames = si.totalSamples, + duration = 0, + bitrate = 0, + tags = info.tags, + comments = info.comments, + vendor = info.vendor, + md5 = si.md5, + seekTable = info.seekTable, + pictures = info.pictures, + container = container, + _b = b, + _len = len, + _si = si, + _first = info.firstFrame, + _pos = info.firstFrame, + _chans = {}, + _cap = 0, + _cf = table.create(32, 0), + _crc = not (opts and opts.crc16 == false), + _fs = 0, + _fn = 0, + _cur = 0, + _nominal = math.max(si.maxBlockSize, 1), + }, Dec) + ensure(self, math.max(si.maxBlockSize, 16)) + local h = findFrame(self, info.firstFrame, len) + if h then + if not h.variable then + self._nominal = h.blockSize + end + end + if self.frames == 0 then + self.frames = scanLength(self) + end + self.duration = self.frames / self.sampleRate + if self.duration > 0 then + self.bitrate = (len - info.firstFrame) * 8 / self.duration + end + return self , nil +end + +Stream.Dec = Dec + +return Stream +end +__FILES["audio/m4a"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading +-- 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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local IsoBmff = __include("containers/IsoBmff") +local Aac = __include("codecs/audio/Aac") +local Alac = __include("codecs/audio/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + 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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + +local AUDIO_BRANDS= { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r) +local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end +-- ------------------------------------------------------------------------------------------------ decode +-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats + + + + + + + + + + +local function packetDecoder(t) +if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config ) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd= { + channels = cfg.channels, + sampleRate = (cfg.sampleRate > 0 and{cfg.sampleRate }or{(t.sampleRate or 44100)})[1], + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf, off, len) +local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config ) + if not dec then + return nil, err + end + local d = dec +local pd= { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf, off, len) +return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +-- open(r, opts?) -> Types.Decoder | nil, Err +function M4a.open(r, opts) +local o= opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track= nil + local other= nil + for _, t in __iter(movie.tracks) do +local __DARKLUA_CONTINUE_2=false repeat if t.kind == "audio" then + if o.track and t.id ~= o.track then +__DARKLUA_CONTINUE_2=true break + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track +local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd +local channels, sr = p.channels, p.sampleRate + -- media ticks -> sample frames + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = (gapless and{(math.floor(t.skip * tickScale + 0.5) )}or{0 +})[1] local total = 0 + for i = 1, t.sampleCount do + total =total+ t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + 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 + if gapless and not t.edits and smpb then + local f= {} + for w in __iter(string.gmatch(smpb, "%x+")) do + table.insert(f, (tonumber(w, 16) )) + end + if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then + skip = f[2] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + local dec= { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + } + local bytes = 0 + for i = 1, t.sampleCount do + bytes =bytes+ t.sizes[i] + end + dec.bitrate = (frames > 0 and{(math.floor(bytes * 8 * sr / frames) )}or{(t.bitrate or 0) +})[1] -- 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) +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) +return p.decode(buf, t.offsets[i], t.sizes[i]) + end, + pcm = function() +return p.pcm + end, + reset = p.reset, + skip = skip, + stop = total, + preroll = t.codec == "aac" and 1 or 0, + cumulative = true, + }) +end + +-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) +function M4a.decode(r, opts) +local dec, err = M4a.open(r, opts) + if not dec then + return nil, err + end + local d= dec + 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, derr +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A +function M4a.encode(value, opts) +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") + end + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc +local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets= {} + local durations= {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + -- frames from an Audio buffer or a streaming Decoder + local src, srcFrames = nil , 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk= nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done =done+ n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = (sr < 65536 and{sr }or{0 +})[1] local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = (timescale > 0 and{timescale }or{48000})[1], + samples = packets, + durations = (timescale > 0 and{durations }or{((function() + local d = {} + for i, v in __iter(durations) do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)())})[1], + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a +end +__FILES["audio/mp3"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- audio/mp3: MPEG audio (ISO/IEC 11172-3, 13818-3; MPEG-2.5), layers I, II and III. Absorbed from mp3-luau c755bbf +-- (same author; a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt). Supports: decode of MPEG-1 / 2 / 2.5 +-- 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, 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; 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()) +-- local audio = Mp3.decode(Bytes.reader(buf)) -- a Types.Audio (the whole file) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Header = __include("codecs/audio/Mpa/Header") +local Index = __include("audio/mp3/Index") +local Tags = __include("audio/mp3/Tags") +local Stream = __include("audio/mp3/Stream") +local Encode3 = __include("codecs/audio/Mpa/Encode3") +local Encode2 = __include("codecs/audio/Mpa/Encode2") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp3 = { + name = "mp3", + category = "audio", + extensions = { "mp3", "mp2", "mp1", "mpga" }, + mime = { "audio/mpeg", "audio/mp3", "audio/mpa" }, + 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 +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + +local MAX_FRAMES = 2 ^ 31 + +-- ------------------------------------------------------------------------------------------------ sniff +-- an ID3v2 tag and / or a valid frame header at the start, more when the next frame chains on +function Mp3.sniff(r) +local b, p, lim = r.buf, r.pos, r.limit + local id3 = false + for _ = 1, 4 do -- (ffmpeg writes a tag even when the input had one: tags can follow each other) + local n = (p + 3 <= lim and buffer.readstring(b, p, 3) == "ID3" and{(Tags.id3v2Size(b, p, lim) )}or{0 +})[1] if n <= 0 then + break + end + id3 = true + p =p+ n + end + if p + 4 > lim or not Header.valid(b, p) then + return id3 and 0.5 or 0 + end + local fb = Header.frameBytes(b, p, 0) + if fb > 0 then + fb =fb+ Header.padding(b, p) + if p + fb + 4 <= lim and Header.compare(b, p, p + fb) then + return 0.9 + end + if p + fb == lim then + return 0.6 + end + end + return id3 and 0.7 or 0.25 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts) -> Types.Audio (the whole stream, through open) +function Mp3.decode(r, opts) +local dec, err = Mp3.open(r, opts) + if not dec then + return nil, err + end + 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 + return a, derr +end + +-- ------------------------------------------------------------------------------------------------ encode +local ID3_FRAMES = { + { "title", "TIT2" }, + { "artist", "TPE1" }, + { "album", "TALB" }, + { "albumartist", "TPE2" }, + { "year", "TDRC" }, + { "date", "TDRC" }, + { "track", "TRCK" }, + { "genre", "TCON" }, + { "composer", "TCOM" }, +} + +-- an ID3v2.4 tag (UTF-8 text frames + a COMM frame) | nil when there is nothing to write +local function id3Tag(tags) +local w = Bytes.writer(256) + local seen= {} + local function syncsafe(v) + w:u8((math.floor(v / 2097152)) % 128) + w:u8((math.floor(v / 16384)) % 128) + w:u8((math.floor(v / 128)) % 128) + w:u8(v % 128) + end + for _, f in __iter(ID3_FRAMES) do + local v = tags[f[1] ] + if type(v) == "string" and #v > 0 and not seen[f[2] ] then + seen[f[2] ] = true + w:string(f[2]) + syncsafe(#v + 1) + w:u16be(0) + w:u8(3) -- UTF-8 + w:string(v) + end + end + if type(tags.comment) == "string" and #tags.comment > 0 then + local v = tags.comment + w:string("COMM") + syncsafe(#v + 5) + w:u16be(0) + w:u8(3) + w:string("eng") + w:u8(0) -- empty description + w:string(v) + end + local body = w:finish() + if buffer.len(body) == 0 then + return nil + end + local out = Bytes.writer(buffer.len(body) + 10) + out:string("ID3") + out:u8(4) + out:u8(0) + out:u8(0) + local n = buffer.len(body) + out:u8((math.floor(n / 2097152)) % 128) + out:u8((math.floor(n / 16384)) % 128) + out:u8((math.floor(n / 128)) % 128) + out:u8(n % 128) + out:bytes(body) + return out:finish() +end + +-- encode(audioOrDecoder, opts?) -> an MP3 (layer III) or MP2 (layer II) file | nil, Err +function Mp3.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local layer = o.layer or 3 + if layer ~= 2 and layer ~= 3 then + return nil, Err.new(Err.ARG, "layer must be 2 or 3") + end + local Enc = (layer == 3 and{Encode3 }or{Encode2 +})[1] -- 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 __iter(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 (src.channels == 1 and"mono" or(layer == 3 and"joint" or"stereo")) + if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then + return nil, Err.new(Err.ARG, "mode must be stereo, joint or mono") + end + if src.channels > 2 then + return nil, Err.new(Err.ARG, "MPEG audio holds 1 or 2 channels") + end + if layer == 2 and mode == "joint" then + mode = "stereo" + end + -- bitrate: bit/s, or kbit/s below 1000; the encoder works in kbit/s + local bitrate = o.bitrate or ((mpeg1 and{(layer == 3 and 128 or 192) }or{(layer == 3 and 64 or 96)})[1]) + if type(bitrate) == "number" and bitrate >= 1000 then + bitrate =bitrate/ 1000 + end + if not table.find(Enc.BITRATES[mpeg1 and 1 or 2], bitrate) then + return nil, Err.new(Err.ARG, string.format("%s bit/s is not a layer %d bit rate at %d Hz", tostring((type(o.bitrate) == "number" and o.bitrate < 1000 and((o.bitrate * 1000 ))or(o.bitrate))), layer, rate)) + end + if layer == 2 and mpeg1 then + -- the standard's allowed bit rate / mode combinations + if mode == "mono" and bitrate > 192 then + return nil, Err.new(Err.ARG, "layer II mono is at most 192 kbps") + elseif mode ~= "mono" and (bitrate == 32 or bitrate == 48 or bitrate == 56 or bitrate == 80) then + return nil, Err.new(Err.ARG, "layer II stereo needs 64 kbps or more (and not 80)") + end + end + local prefix = (o.id3 == false and{nil }or{(id3Tag(src.tags) +)})[1] local out, msg = Enc.encode(src , { bitrate = bitrate, mode = mode, prefix = prefix }) + if not out then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment) +local function stringTags(t) +local out= {} + for k, v in __iter(t) do + if type(k) == "string" and type(v) == "string" and k ~= "id3v2" then + out[k] = v + end + end + return out +end + +-- open(r, opts) -> the streaming Decoder (Types.Decoder) | nil, Err +function Mp3.open(r, opts) +local b = r.buf + if r.base ~= 0 or r.limit ~= buffer.len(b) then + b = buffer.create(r.limit - r.base) -- the core indexes from offset 0 + buffer.copy(b, 0, r.buf, r.base, r.limit - r.base) + end + local okTags, tags, start, stop = pcall(Tags.parse, b) + if not okTags then + tags, start, stop = { raw = {} }, 0, buffer.len(b) + end + local idx = Index.build(b, start, stop) + if not idx then + return nil, Err.new(Err.CORRUPT, "no MPEG audio frames found") + end + local dec = Stream.new(b, idx, stringTags(tags), { + raw = tags.raw, + id3v2 = tags.id3v2, + id3v1 = tags.id3v1 == true, + ape = tags.ape == true, + }) + if dec.frames > (opts and opts.maxFrames or MAX_FRAMES) then + return nil, Err.new(Err.LIMIT, string.format("%d sample frames is over the limit", dec.frames)) + end + return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Mp3.Tags = Tags -- Tags.parse(buf) -> (tags, audio start, audio end) + +return Mp3 +end +__FILES["audio/mp3/Index"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- audio/mp3/Index: the frame index of a stream, built once on open. It follows minimp3_ex's mp3dec_load_buf frame by frame +-- (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 = __include("codecs/audio/Mpa/Header") +local Core = __include("codecs/audio/Mpa/Core") + +local band, rshift = bit32.band, bit32.rshift +local ru8 = buffer.readu8 +local min, max = math.min, math.max + +local compare, frameBytes, padding, findFrame = + Header.compare, Header.frameBytes, Header.padding, Header.findFrame + +local Index = {} + +Index.FLAG_RESET = 1 -- decoder state is zeroed before this frame (minimp3 re-synced here) +Index.FLAG_OUTPUT = 2 -- this frame gives samples in a continuous decode + + + + + + + + + + + + + + + + + + + + + + + + +local function grow(b, n) +local nb = buffer.create(n) + buffer.copy(nb, 0, b, 0, math.min(buffer.len(b), n)) + return nb +end + +function Index.build(b, start, stop) +local cap = 1024 + local OFF, SIZE, FLAGS, OUT, MAIN = buffer.create(cap * 4), buffer.create(cap * 2), buffer.create(cap), buffer.create(cap * 4), buffer.create(cap * 2) + local n = 0 + local pos = start + local prev = -1 -- offset of the last decoded header (dec->header), -1 = none + local ffb = 0 -- free format bytes + local reserv = 0 + local outTotal = 0 + local bytes = 0 + local first = true + local skipped = 0 + local outCh = 0 -- the most channels of a frame that gives output + local hz, nch, layer, spf, version = 0, 0, 0, 0, 0 + local vbr, tagFrames, delay, pad = 0, 0, 0, 0 + + while true do +local __DARKLUA_CONTINUE_1=false repeat local remaining = stop - pos + if remaining <= 0 then + break + end + local fs = 0 + local reset = false + if remaining > 4 and prev >= 0 and compare(b, prev, pos) then + fs = frameBytes(b, pos, ffb) + padding(b, pos) + if fs ~= remaining and (fs + 4 > remaining or not compare(b, pos, pos + fs)) then + fs = 0 + end + end + if fs == 0 then + reset = true + reserv = 0 + local i + i, fs, ffb = findFrame(b, pos, remaining, 0) + if fs == 0 or i + fs > remaining then + break + end + pos =pos+ i + end + if fs < 4 or fs > Core.MAX_FRAME then + -- cannot happen with a well-formed header, but never index an impossible frame + prev = -1 + pos =pos+ max(fs, 1) +__DARKLUA_CONTINUE_1=true break + end + local h1, h2, h3 = ru8(b, pos + 1), ru8(b, pos + 2), ru8(b, pos + 3) + local fLayer = 4 - band(rshift(h1, 1), 3) + local fHz = Header.sampleRate(h1, h2) + local fCh = band(h3, 0xC0) == 0xC0 and 1 or 2 + + if first then + first = false + hz, nch, layer, spf = fHz, fCh, fLayer, (Header.frameSamples(h1) ) +version = band(h1, 8) ~= 0 and 1 or(band(h1, 0x10) ~= 0 and 2 or 2.5 +) if fLayer == 3 then + local ret, frames, d, p = Core.vbrTag(b, pos, fs) + if ret ~= 0 then + vbr, tagFrames, delay, pad = ret, frames, d, p + if ret < 0 then + delay, pad = 0, 0 + end + -- the tag frame is not audio; the next frame is found again from scratch + prev = -1 + pos =pos+ fs +__DARKLUA_CONTINUE_1=true break + end + end + elseif fHz ~= hz or fLayer ~= layer then + skipped =skipped+ 1 + prev = pos + pos =pos+ fs +__DARKLUA_CONTINUE_1=true break + end + + local output = true + local mainBytes = 0 + local nextPrev = pos + if fLayer == 3 then + local mdb, p23, mb = Core.probeL3(b, pos, fs) + if mdb < 0 then + output = false + nextPrev = -1 -- mp3dec_init: the next frame re-syncs + else + mainBytes = mb + local have = min(reserv, mdb) + output = reserv >= mdb + local remains = have + mb - ((output and{(math.floor((p23 + 7) / 8 ))}or{0})[1]) + reserv = max(0, min(remains, 511)) + end + else + output = Core.probeL12(b, pos, fs) + if not output then + nextPrev = -1 + end + end + + if output and fCh > outCh then + outCh = fCh -- mono / stereo switches: the stream is stereo, mono frames are duplicated + end + if n == cap then + cap =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) ) +end + buffer.writeu32(OFF, n * 4, pos) + buffer.writeu16(SIZE, n * 2, fs) + buffer.writeu8(FLAGS, n, ((reset and{Index.FLAG_RESET }or{0})[1]) + ((output and{Index.FLAG_OUTPUT }or{0})[1])) + buffer.writeu32(OUT, n * 4, outTotal) + buffer.writeu16(MAIN, n * 2, min(mainBytes, 65535)) + n =n+ 1 + bytes =bytes+ fs + if output then + outTotal =outTotal+ spf + end + prev = nextPrev + pos =pos+ fs +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + + if first then + return nil + end + return { + n = n, + off = OFF, + size = SIZE, + flags = FLAGS, + out = OUT, + main = MAIN, + outTotal = outTotal, + bytes = bytes, + sampleRate = hz, + channels = (outCh > 0 and{outCh }or{nch})[1], + layer = layer, + version = version, + spf = spf, + vbrTag = vbr, + tagFrames = tagFrames, + delay = delay, + padding = pad, + skipped = skipped, + } +end + +return Index +end +__FILES["audio/mp3/Stream"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!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 = __include("codecs/audio/Mpa/Core") +local Index = __include("audio/mp3/Index") + +local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT +local ru8, ru16, ru32 = buffer.readu8, buffer.readu16, buffer.readu32 +local band = bit32.band +local min, max, floor = math.min, math.max, math.floor + +local Stream = {} + +local Decoder = {} +Decoder.__index = Decoder + +-- new(b, idx, tags, id3) -> Decoder over the whole buffer b, with its frame index (Index.build) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function Stream.new(b, idx, tags, id3) +local spf, hz, nch = idx.spf, idx.sampleRate, idx.channels + -- gapless: minimp3_ex cuts delay samples off the start and caps the length at the Xing / LAME count + local delay = 0 + local total = idx.outTotal + if idx.vbrTag > 0 then + delay = idx.delay + local detected = spf * idx.tagFrames + if detected >= delay then + detected =detected- delay + end + if idx.padding > 0 and detected >= idx.padding then + detected =detected- idx.padding + end + total = max(0, total - delay) + total = min(total, detected) + end + delay = min(delay, idx.outTotal) + local self = setmetatable({ + sampleRate = hz, + channels = nch, + frames = total, + duration = total / hz, + bitrate = (idx.n > 0 and{(floor(idx.bytes * 8 * hz / (idx.n * spf) + 0.5) )}or{0})[1], -- bit/s + tags = tags, + id3 = id3, + layer = idx.layer, + version = idx.version, + vbr = idx.vbrTag ~= 0, + delay = delay, + padding = (idx.vbrTag > 0 and{(max(0, idx.padding) )}or{0})[1], + mpegFrames = idx.n, + _buf = b, + _idx = idx, + _st = Core.newState(), + _pcm = buffer.create(1152 * 2 * 4), + _cur = 0, + _pcmPos = 0, + _pcmEnd = 0, + _minAbs = delay, + _endAbs = delay + total, + _pos = 0, + }, Decoder) + return self +end + + +-- decodes frames until one has samples inside [minAbs, endAbs); false at the end +local function fill(self) +local idx = self._idx + local n = idx.n + local spf = idx.spf + local st = self._st + while self._cur < n do + local f = self._cur + self._cur = f + 1 + local flags = ru8(idx.flags, f) + if band(flags, FLAG_RESET) ~= 0 then + Core.reset(st) + end + local a = ru32(idx.out, f * 4) + if a >= self._endAbs then + self._cur = n + return false + end + local got = Core.decodeFrame(st, self._buf, ru32(idx.off, f * 4), ru16(idx.size, f * 2), self._pcm) + if got > 0 and band(flags, FLAG_OUTPUT) ~= 0 then + if Core.lastChannels < self.channels then + Core.upmix(self._pcm, got) + end + local lo = max(a, self._minAbs) + local hi = min(a + spf, self._endAbs) + if hi > lo then + self._pcmPos = lo - a + self._pcmEnd = hi - a + return true + end + end + end + return false +end + +-- Reads up to maxFrames sample frames: (buffer of interleaved f32, frames read); 0 frames = end of stream. +-- With out (a buffer of at least maxFrames * channels * 4 bytes) the samples go there and out is returned; a +-- smaller out is ignored. +function Decoder.read(self, maxFrames, out) +local ch = self.channels + local want = tonumber(maxFrames) or 4096 + if want ~= want then + want = 0 + end + want = floor(max(0, min(want, self.frames - self._pos))) + if out and buffer.len(out) < want * ch * 4 then + out = nil -- too small: a new buffer (Types.Decoder: out is reused when big enough) + end + local dst = out or buffer.create(want * ch * 4) + local got = 0 + local pcm = self._pcm + while got < want do + if self._pcmPos >= self._pcmEnd then + if not fill(self) then + break + end + end + local k = min(want - got, self._pcmEnd - self._pcmPos) + buffer.copy(dst, got * ch * 4, pcm, self._pcmPos * ch * 4, k * ch * 4) + got =got+ k + self._pcmPos =self._pcmPos+ k + end + self._pos =self._pos+ got + if not out and got < want then + local r = buffer.create(got * ch * 4) + buffer.copy(r, 0, dst, 0, got * ch * 4) + dst = r + end + return dst, got +end + +-- Seeks to a time in seconds (clamped to the stream). Sample-accurate: decoding restarts a few frames earlier +-- (enough to refill the bit reservoir and the filter history) and the output before the target is dropped. +function Decoder.seek(self, seconds) + local hz = self.sampleRate + local target = floor((tonumber(seconds) or 0) * hz + 0.5) + target = max(0, min(target, self.frames)) + self:seekFrame(target) +end + +-- Seeks to a sample frame (0 .. frames). +function Decoder.seekFrame(self, target) + target = tonumber(target) or 0 + if target ~= target then + target = 0 + end + target = max(0, min(floor(target), self.frames)) + local idx = self._idx + local abs = self.delay + target + self._pos = target + self._minAbs = abs + self._pcmPos, self._pcmEnd = 0, 0 + Core.reset(self._st) + local n = idx.n + if abs >= self._endAbs or n == 0 then + self._cur = n + return + end + -- last frame starting at or before abs + local lo, hi = 0, n - 1 + while lo < hi do + local mid = math.floor((lo + hi + 1) / 2 +) if ru32(idx.out, mid * 4) <= abs then + lo = mid + else + hi = mid - 1 + end + end + local j = lo + -- go back >= 2 frames (layer I needs 2 for the polyphase history), and for layer III until the main data + -- before frame j - 1 covers the largest reservoir (511 bytes), stopping at a frame where the decoder resets + local need = idx.layer == 3 and 511 or 0 + local s, back, acc = j, 0, 0 + while s > 0 and band(ru8(idx.flags, s), FLAG_RESET) == 0 do + if back >= 2 and acc >= need then + break + end + s =s- 1 + back =back+ 1 + if back >= 2 then + acc =acc+ ru16(idx.main, s * 2) + end + end + self._cur = s +end + +-- Current position: (seconds, sample frame) +function Decoder.position(self) +return self._pos / self.sampleRate, self._pos +end + +-- Decodes everything from the current position to the end: (buffer of interleaved f32, frames) +function Decoder.readAll(self) +return self:read(max(0, self.frames - self._pos)) +end + +Stream.Decoder = Decoder + +return Stream +end +__FILES["audio/mp3/Tags"] = function() +local __compat = __compat local buffer, bit32, utf8, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.__iter --!strict +--!optimize 2 +-- audio/mp3/Tags: ID3 tags: ID3v2.2 / 2.3 / 2.4 at the start (text frames, COMM, unsynchronisation, extended header) and ID3v1 / +-- ID3v1.1 at the end; APEv2 tags are only skipped. Also finds the byte range that holds the audio, the same way +-- minimp3_ex does (mp3dec_skip_id3). Text is returned as UTF-8. Never throws: malformed tags are cut short. +local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift +local ru8 = buffer.readu8 + +local Tags = {} + +-- ID3v1 genres 0..147 (the original 80 + the Winamp extensions) +local GENRES = { + [0] = "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", + "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", + "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", + "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", + "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", + "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", + "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", + "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", + "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", + "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", + "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", + "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", + "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", + "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", + "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", + "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", + "Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop", +} +Tags.GENRES = GENRES + +-- frame id -> field name (v2.3/2.4 ids and their v2.2 equivalents) +local FIELDS = { + TIT2 = "title", TT2 = "title", + TPE1 = "artist", TP1 = "artist", + TALB = "album", TAL = "album", + TPE2 = "albumartist", TP2 = "albumartist", + TYER = "date", TYE = "date", TDRC = "date", + TRCK = "track", TRK = "track", + TPOS = "disc", TPA = "disc", + TCON = "genre", TCO = "genre", + TCOM = "composer", TCM = "composer", + COMM = "comment", COM = "comment", +} + +local function utf8char(cp) +if cp < 0 or cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + cp = 0xFFFD + end + return utf8.char(cp) +end + +-- bytes [i, j) of b, decoded from ID3 text encoding enc (0 latin-1, 1 UTF-16 + BOM, 2 UTF-16BE, 3 UTF-8) +local function decodeText(b, i, j, enc) +local out = {} + if enc == 1 or enc == 2 then + local le = false + if enc == 1 and j - i >= 2 then + local b0, b1 = ru8(b, i), ru8(b, i + 1) + if b0 == 0xFF and b1 == 0xFE then + le = true + i =i+ 2 + elseif b0 == 0xFE and b1 == 0xFF then + i =i+ 2 + else + le = true -- no BOM: assume little-endian (what most taggers write) + end + end + local pending = 0 + while i + 1 < j do + local u = (le and{(bor(ru8(b, i), lshift(ru8(b, i + 1), 8)) )}or{(bor(lshift(ru8(b, i), 8), ru8(b, i + 1)) +)})[1] i =i+ 2 + if u >= 0xD800 and u <= 0xDBFF then + pending = u + else + if u >= 0xDC00 and u <= 0xDFFF and pending ~= 0 then + u = 0x10000 + lshift(pending - 0xD800, 10) + (u - 0xDC00) + end + pending = 0 + table.insert(out, u == 0 and"\0" or utf8char(u)) + end + end + elseif enc == 3 then + local s = buffer.readstring(b, i, j - i) + if utf8.len(s) then + return s + end + enc = 0 -- invalid UTF-8: fall back to latin-1 + end + if enc == 0 then + for k = i, j - 1 do + local c = ru8(b, k) + table.insert(out, (c < 0x80 and{(string.char(c) )}or{(utf8char(c))})[1]) + end + end + return table.concat(out) +end + +-- trim trailing NULs / spaces, join multi-value NUL separators with " / " +local function clean(s) +s = string.gsub(s, "[%z%s]+$", "") + s = string.gsub(s, "%z+", " / ") + return s +end + +-- "(17)", "(17)Rock", "17" -> "Rock" +local function genreName(s) +local n = tonumber(string.match(s, "^%((%d+)%)$") or string.match(s, "^(%d+)$")) + if n and GENRES[n] then + return GENRES[n] + end + local rest = string.match(s, "^%(%d+%)(.+)$") + return rest or s +end + +local function syncsafe(b, o) +return bor(lshift(band(ru8(b, o), 0x7F), 21), lshift(band(ru8(b, o + 1), 0x7F), 14), lshift(band(ru8(b, o + 2), 0x7F), 7), band(ru8(b, o + 3), 0x7F)) +end + +local function be32(b, o) +return bor(lshift(ru8(b, o), 24), lshift(ru8(b, o + 1), 16), lshift(ru8(b, o + 2), 8), ru8(b, o + 3)) +end + +-- undo unsynchronisation (FF 00 -> FF) of b[i, j) into a new buffer +local function deunsync(b, i, j) +local out = buffer.create(math.max(0, j - i)) + local n = 0 + local k = i + while k < j do + local c = ru8(b, k) + buffer.writeu8(out, n, c) + n =n+ 1 + k =k+ (c == 0xFF and k + 1 < j and ru8(b, k + 1) == 0 and 2 or 1 +) end + local r = buffer.create(n) + buffer.copy(r, 0, out, 0, n) + return r +end + +-- minimp3's ID3v2 detection: total tag size (header + body + footer) or 0 +function Tags.id3v2Size(b, o, len) +if len - o < 10 or buffer.readstring(b, o, 3) ~= "ID3" then + return 0 + end + if band(ru8(b, o + 5), 15) ~= 0 then + return 0 + end + for k = 6, 9 do + if band(ru8(b, o + k), 0x80) ~= 0 then + return 0 + end + end + local size = syncsafe(b, o + 6) + 10 + if band(ru8(b, o + 5), 16) ~= 0 then + size =size+ 10 + end + return size +end + +local function setField(tags, id, text) + tags.raw[id] = text + local f = FIELDS[id] + if f and tags[f] == nil and text ~= "" then + tags[f] = (f == "genre" and{(genreName(text) )}or{text +})[1] end +end + +-- parse an ID3v2 tag at b[o ..] (o .. o + size within the buffer) into tags +local function parseV2(b, o, size, tags) + local ver = ru8(b, o + 3) + local flags = ru8(b, o + 5) + if ver < 2 or ver > 4 then + return + end + tags.id3v2 = "2." .. ver + local bodyEnd = math.min(o + 10 + syncsafe(b, o + 6), buffer.len(b)) + local body = b + local p, e = o + 10, bodyEnd + if band(flags, 0x80) ~= 0 and ver < 4 then + body = deunsync(b, p, e) + 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) + p =p+ (ver == 3 and{(be32(body, p) + 4 )}or{(syncsafe(body, p) +)})[1] end + local hdr = ver == 2 and 6 or 10 + while p + hdr <= e do + local c0 = ru8(body, p) + if c0 == 0 then + break -- padding + end + local id, fsize, fflags + if ver == 2 then + id = buffer.readstring(body, p, 3) + fsize = bor(lshift(ru8(body, p + 3), 16), lshift(ru8(body, p + 4), 8), ru8(body, p + 5)) + fflags = 0 + else + id = buffer.readstring(body, p, 4) + fsize = (ver == 4 and{(syncsafe(body, p + 4) )}or{(be32(body, p + 4) +)})[1] fflags = bor(lshift(ru8(body, p + 8), 8), ru8(body, p + 9)) + end + if not string.match(id, "^[A-Z0-9]+$") or fsize <= 0 or p + hdr + fsize > e then + break + end + local fs, fe = p + hdr, p + hdr + fsize + local fb = body + local skip = false + if ver == 3 then + skip = band(fflags, 0x00C0) ~= 0 -- compressed / encrypted + elseif ver == 4 then + skip = band(fflags, 0x000C) ~= 0 + if not skip and band(fflags, 0x0001) ~= 0 then + fs =fs+ 4 -- data length indicator + end + if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then + fb = deunsync(body, fs, fe) + fs = 0 + fe = buffer.len(fb) + end + end + if not skip and fs < fe then + local first = string.sub(id, 1, 1) + local enc = ru8(fb, fs) + if first == "T" and id ~= "TXXX" and id ~= "TXX" then + setField(tags, id, clean(decodeText(fb, fs + 1, fe, enc))) + elseif (id == "COMM" or id == "COM") and fe - fs >= 4 then + -- encoding, language[3], short description (NUL-terminated in the encoding), text + local q = fs + 4 + local wide = enc == 1 or enc == 2 + while q < fe do + if wide then + if q + 1 < fe and ru8(fb, q) == 0 and ru8(fb, q + 1) == 0 then + q =q+ 2 + break + end + q =q+ 2 + else + if ru8(fb, q) == 0 then + q =q+ 1 + break + end + q =q+ 1 + end + end + if q <= fe then + setField(tags, id, clean(decodeText(fb, q, fe, enc))) + end + end + end + p =p+ (hdr + fsize +) end +end + +local function v1String(b, o, n) +return (string.gsub(decodeText(b, o, o + n, 0), "[%z%s]+$", "")) +end + +-- Parses tags and returns (tags, audio start, audio end) for the buffer b. +-- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?, +-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? } +function Tags.parse(b) +local len = buffer.len(b) + local tags= { raw = {} } + local start, stop = 0, len + local v2 = Tags.id3v2Size(b, 0, len) + if v2 > 0 then + pcall(parseV2, b, 0, v2, tags) + start = math.min(v2, len) + end + -- mp3dec_skip_id3v1 on what follows the ID3v2 tag + local size = stop - start + if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then + local o = start + size - 128 + tags.id3v1 = true + local v1= { + title = v1String(b, o + 3, 30), + artist = v1String(b, o + 33, 30), + album = v1String(b, o + 63, 30), + 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) + v1.track = tostring(ru8(b, o + 126)) + else + v1.comment = v1String(b, o + 97, 30) + end + local g = ru8(b, o + 127) + if GENRES[g] then + v1.genre = GENRES[g] + end + for k, v in __iter(v1) do + if tags[k] == nil and v ~= "" then + tags[k] = v + end + end + size =size- 128 + if size >= 227 and buffer.readstring(b, start + size - 227, 4) == "TAG+" then + size =size- 227 + end + end + if size > 32 and buffer.readstring(b, start + size - 32, 8) == "APETAGEX" then + size =size- 32 + local t = start + size + 12 + local tagSize = bor(ru8(b, t), lshift(ru8(b, t + 1), 8), lshift(ru8(b, t + 2), 16), lshift(ru8(b, t + 3), 24)) + if size >= tagSize then + size =size- tagSize + end + tags.ape = true + end + stop = start + size + return tags, start, stop +end + +return Tags +end +__FILES["audio/mpc"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- audio/mpc: Musepack (.mpc / .mp+ / .mpp), stream versions 7 and 8, through codecs/audio/Musepack (a libmpcdec +-- port). Supports: SV7 (mppenc 1.x) and SV8 (mpcenc 1.30) streams, mono / stereo, every rate (32 / 37.8 / 44.1 / +-- 48 kHz), gapless length (the synthesis delay, SV8 leading silence and the last frame's length are honoured), seeking +-- (SV8: by audio packet, exact; SV7: by frame with 32 frames of pre-roll, as libmpcdec), APEv2 tags +-- (codecs/audio/ApeTag), a leading ID3v2 tag (skipped), ReplayGain values in meta (not applied). Not supported: +-- writing, SV4 - SV6 (UNSUPPORTED), chapters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local Musepack = __include("codecs/audio/Musepack") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpc = { + name = "mpc", + category = "audio", + extensions = { "mpc", "mp+", "mpp" }, + mime = { "audio/x-musepack", "audio/musepack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Musepack" }, + caps = { decode = true, encode = false, codecs = { "musepack" }, versions = { 7, 8 }, streaming = true, lossy = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants +-- the size of an ID3v2 tag at p (0 if none) + + + + + +local function id3v2(b, p, limit) +if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local n = 10 + for i = 6, 9 do + n =n+ bit32.band(buffer.readu8(b, p + i), 127) * 128 ^ (9 - i) + end + return n + (bit32.band(buffer.readu8(b, p + 5), 0x10) ~= 0 and 10 or 0) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpc.sniff(r) +local b, p, limit = r.buf, r.pos, r.limit + p =p+ id3v2(b, p, limit) + local v = Musepack.magic(b, p, limit) + if v == 8 then + return 1 + end + return v == 7 and 0.9 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mpc.open(r, opts) +local o= opts or {} + local b, base, limit = r.buf, r.base, r.limit + local start = base + id3v2(b, base, limit) + local tags, info = ApeTag.find(b, start, limit) + local stop = (info and info.start > start and{info.start }or{limit +})[1] local s, err = Musepack.open(b, start, stop) + if not s then + return nil, err + end + if s.frames > (o.maxFrames or 2 ^ 31) then + return nil, Err.new(Err.LIMIT, "more than " .. (o.maxFrames or 2 ^ 31) .. " frames") + end + local duration = s.frames / s.sampleRate + local dec = { + sampleRate = s.sampleRate, + channels = s.channels, + frames = s.frames, + duration = duration, + bitrate = (duration > 0 and{(math.floor(s.bytes * 8 / duration + 0.5) )}or{0})[1], + tags = tags or {}, + codec = "musepack", + version = s.version, + profile = s.profile, + gain = s.gain, + } + return Stream.packets(dec, s ) +end + +function Mpc.decode(r, opts) +local dec, err = Mpc.open(r, opts) + if not dec then + return nil, err + end + local d= dec + return Pcm.drain(d, { format = "mpc", codec = "musepack", version = d.version, profile = d.profile, gain = d.gain, bitrate = d.bitrate }) +end + +return Mpc +end +__FILES["audio/opus"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- audio/opus: Ogg Opus (RFC 6716 codec, RFC 7845 encapsulation). Absorbed from opus-luau dd2b4e5 (same author; a +-- port of the libopus 1.6 decoder, BSD: licenses/libopus-BSD.txt): the range decoder, CELT (float), SILK +-- (bit-exact fixed point), hybrid, mode transitions, PLC, multistream (mapping families 0, 1, 255). +-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, +-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms +-- pre-roll), damaged files (concealment). Output is always 48 kHz f32. +-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant +-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. +-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics +-- 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 +-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets +-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Decoder = __include("codecs/audio/Opus/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Pcm = __include("codecs/audio/Pcm") +local RangeDecoder = __include("codecs/entropy/RangeCoder/Decoder") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") +local Encode = __include("audio/opus/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Opus = { + name = "opus", + category = "audio", + extensions = { "opus" }, + mime = { "audio/opus", "audio/ogg" }, + 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 +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local SAMPLE_RATE = 48000 + +-- stereo downmix weights for the Vorbis channel orders of mapping family 1 (3 to 8 channels), as in opusfile +local DOWNMIX = { + [3] = { 0.5858, 0, 0.4142, 0.4142, 0, 0.5858 }, + [4] = { 0.4226, 0, 0, 0.4226, 0.366, 0.2114, 0.2114, 0.366 }, + [5] = { 0.651, 0, 0.46, 0.46, 0, 0.651, 0.5636, 0.3254, 0.3254, 0.5636 }, + [6] = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }, + [7] = { 0.4553, 0, 0.322, 0.322, 0, 0.4553, 0.3943, 0.2277, 0.2277, 0.3943, 0.2788, 0.2788, 0.322, 0.322 }, + [8] = { 0.3886, 0, 0.2748, 0.2748, 0, 0.3886, 0.3366, 0.1943, 0.1943, 0.3366, 0.3366, 0.1943, 0.1943, 0.3366, 0.2748, 0.2748 }, +} +local PREROLL = 3840 -- 80 ms, RFC 7845 section 4.6 +local MAX_PACKET = 5760 -- 120 ms + +-- OpusHead (RFC 7845 section 5.1). Returns the header or nil, message. + + + + + + + + + + + + +local function parseHead(b, off, size) +if size < 19 or buffer.readstring(b, off, 8) ~= "OpusHead" then + return nil, "not an OpusHead packet" + end + local version = buffer.readu8(b, off + 8) + if bit32.rshift(version, 4) ~= 0 then + return nil, "unsupported OpusHead version " .. version + end + local channels = buffer.readu8(b, off + 9) + if channels < 1 then + return nil, "OpusHead: zero channels" + end + local head= { + version = version, + channels = channels, + preSkip = buffer.readu16(b, off + 10), + inputSampleRate = buffer.readu32(b, off + 12), + outputGain = buffer.readi16(b, off + 16), + mappingFamily = buffer.readu8(b, off + 18), + streams = 1, + coupled = channels - 1, + mapping = {}, + } + if head.mappingFamily == 0 then + if channels > 2 then + return nil, "OpusHead: mapping family 0 with more than 2 channels" + end + head.mapping = channels == 2 and{ 0, 1 } or{ 0 } + else + if head.mappingFamily == 3 then + return nil, "unsupported channel mapping family 3 (projection)" + end + if size < 21 + channels then + return nil, "OpusHead: truncated channel mapping table" + end + head.streams = buffer.readu8(b, off + 19) + head.coupled = buffer.readu8(b, off + 20) + if head.streams < 1 or head.coupled > head.streams or head.streams + head.coupled > 255 then + return nil, "OpusHead: bad stream counts" + end + for c = 0, channels - 1 do + local m = buffer.readu8(b, off + 21 + c) + if m ~= 255 and m >= head.streams + head.coupled then + return nil, "OpusHead: bad channel mapping" + end + head.mapping[c + 1] = m + end + end + return head, nil +end + +-- 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, off, size) +if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then + return "", {}, {} + end + local p = off + 8 + local e = off + size + local vlen = buffer.readu32(b, p) + p =p+ 4 + if p + vlen > e then + return "", {}, {} + end + local vendor = buffer.readstring(b, p, vlen) + p =p+ vlen + local list = {} + if p + 4 <= e then + local n = buffer.readu32(b, p) + p =p+ 4 + for _ = 1, n do + if p + 4 > e then + break + end + local l = buffer.readu32(b, p) + p =p+ 4 + if p + l > e then + break + end + table.insert(list, buffer.readstring(b, p, l)) + p =p+ l + end + end + local tags, raw = VorbisComment.tags(list) + return vendor, tags, raw +end + +Opus.Decoder = Decoder +Opus.Packet = Packet +Opus.RangeDecoder = RangeDecoder +Opus.Celt = Celt +Opus.Silk = Silk +Opus.parseHead = parseHead +Opus.parseTags = parseTags +Opus.SAMPLE_RATE = SAMPLE_RATE + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when the file starts with an Ogg page whose first packet is an OpusHead +function Opus.sniff(r) +if r:peek(4) ~= "OggS" then + return 0 + end + local nseg = r:peekU8(26) + if nseg < 1 then + return 0 + end + return r:peek(8, 27 + nseg) == "OpusHead" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Audio | nil, Err: the whole stream (48 kHz f32) +function Opus.decode(r, opts) +local dec, err = Opus.open(r, opts) + if not dec then + return nil, err + end + 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 +-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) +function Opus.encode(value, opts) +return Encode.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- Decodes the next packet into the pending buffer. Returns false at the end of the stream. +local function decodeNext(self) +local p = self.demux:nextPacket(self.serial) + if p == nil then + return false + end + local n + if p.size > 0 then + n = Decoder.decodeMultistream(self.ms, p.data, p.offset, p.size, self.pend, 1, MAX_PACKET) + else + n = -1 + end + if n < 0 then + -- corrupt or empty packet: conceal for its nominal duration + local dur = (p.size > 0 and{(Packet.samples(p.data, p.offset, p.size) )}or{(-1 +)})[1] if dur <= 0 then + dur = self.lastDuration + end + n = Decoder.decodeMultistream(self.ms, nil, 0, 0, self.pend, 1, dur) + if n < 0 then + n = dur + for i = 1, n * self.channels do + self.pend[i] = 0 + end + end + end + self.lastDuration = n + self.pendStart = self.decoded + self.pendLen = n + self.pendPos = 0 + self.decoded =self.decoded+ n + return true +end + +-- dec:read(maxFrames, out?) -> buffer of interleaved f32 samples, frames read (0 at the end of the stream). out (if +-- given and big enough) is filled instead of a new buffer. +function Stream.read(self, maxFrames, into) +local ch = self.channels + local mf = (type(maxFrames) == "number" and maxFrames == maxFrames and{maxFrames }or{0 +})[1] local want = math.max(0, math.min(math.floor(mf), self.endSample - self.next)) + local reuse = into ~= nil and buffer.len(into) >= want * ch * 4 + local out = (reuse and{into }or{(buffer.create(want * ch * 4) +)})[1] local got = 0 + local gain = self.gain + while got < want do +local __DARKLUA_CONTINUE_4=false repeat if self.pendPos >= self.pendLen then + if not decodeNext(self) then + break + end + end + -- skip decoded samples before the next wanted one (pre-skip, seek pre-roll) + local s = self.pendStart + self.pendPos + if s < self.next then + self.pendPos = math.min(self.pendLen, self.pendPos + (self.next - s)) +__DARKLUA_CONTINUE_4=true break + end + local n = math.min(self.pendLen - self.pendPos, want - got) + if self.downmix then + 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 =self.pendPos+ n + got =got+ n + self.next =self.next+ n +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end + if got < want then + if not reuse then + local trimmed = buffer.create(got * ch * 4) + buffer.copy(trimmed, 0, out, 0, got * ch * 4) + out = trimmed + end + self.endSample = self.next -- the stream ended early (truncated file) + end + return out, got +end + +-- current playback position in seconds +function Stream.position(self) +return (self.next - self.preSkip) / SAMPLE_RATE +end + +-- seek to a time in seconds (clamped to the stream): granule bisection with 80 ms pre-roll +function Stream.seek(self, seconds) + local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 +})[1] local p = math.floor(math.max(0, math.min(sec, 1e12)) * SAMPLE_RATE + 0.5) + p = math.min(p, self.frames) + local target = p + self.preSkip -- decoded-sample index of the wanted sample + Decoder.resetMultistream(self.ms) + self.pendLen, self.pendPos = 0, 0 + local g = target - PREROLL + self.startGranule + local start = -1 + if g > self.startGranule then + start = self.demux:seekGranule(self.serial, g) or -1 + end + if start < 0 then + self.demux:rewind(self.serial) + self.demux:nextPacket(self.serial) -- OpusHead + self.demux:nextPacket(self.serial) -- OpusTags + self.decoded = 0 + else + self.decoded = start - self.startGranule + end + self.pendStart = self.decoded + self.next = target +end + +-- open(r, opts?) -> Decoder | nil, Err (r: a core/Bytes Reader, or a buffer) +function Opus.open(r, opts) +local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = false } or nil) + if not demux then + return nil, derr + end + local serial = demux:find("opus") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Opus stream in the Ogg file") + end + local hp = demux:nextPacket(serial) + if hp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusHead") + end + local head, herr = parseHead(hp.data, hp.offset, hp.size) + if not head then + return nil, Err.new((string.find(herr or "", "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], herr or "bad OpusHead") + end + local tp = demux:nextPacket(serial) + if tp == nil then + return nil, Err.new(Err.TRUNCATED, "missing OpusTags") + end + 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 + while true do + local p = demux:nextPacket(serial) + if p == nil then + break + end + local d = (p.size > 0 and{(Packet.samples(p.data, p.offset, p.size) )}or{0 +})[1] sum =sum+ math.max(d, 0) + if p.granule ~= -1 then + startGranule = math.max(0, p.granule - sum) + break + end + end + demux:rewind(serial) + demux:nextPacket(serial) + demux:nextPacket(serial) + local info = demux:stream(serial) + local last = (info and info.lastGranule and info.lastGranule >= 0 and{info.lastGranule }or{startGranule +})[1] local frames = math.max(0, last - startGranule - head.preSkip) + local downmix = nil + if opts and opts.stereo and head.channels > 2 then + downmix = DOWNMIX[head.channels] + if downmix == nil or head.mappingFamily ~= 1 then -- unknown layout: every channel to both sides, equally + downmix = table.create(head.channels * 2, 1 / head.channels) + end + end + local self = setmetatable({ + demux = demux, + serial = serial, + 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 = (not downmix and head.mappingFamily == 1 and head.channels > 2 and{Pcm.WAVE_FROM_VORBIS[head.channels] }or{nil})[1], + sampleRate = SAMPLE_RATE, + channels = downmix and 2 or head.channels, + sourceChannels = head.channels, + downmix = downmix, + frames = frames, + duration = frames / SAMPLE_RATE, + bitrate = (frames > 0 and{(math.floor(demux.size * 8 / (frames / SAMPLE_RATE)) )}or{0})[1], + preSkip = head.preSkip, + startGranule = startGranule, + gain = 10 ^ (head.outputGain / (20 * 256)), + ms = Decoder.newMultistream(head.channels, head.streams, head.coupled, head.mapping), + pend = table.create(MAX_PACKET * head.channels, 0), + pendStart = 0, + pendLen = 0, + pendPos = 0, + decoded = 0, -- decoded-sample index of the next packet's first sample + next = head.preSkip, -- decoded-sample index of the next sample read() returns + endSample = head.preSkip + frames, + lastDuration = 960, + }, Stream) + return self, nil +end + + +return Opus +end +__FILES["audio/opus/Encode"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- 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 (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in +-- rosetta. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Ogg = __include("containers/Ogg") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") +local VorbisComment = __include("codecs/audio/VorbisComment") +local CeltEncoder = __include("codecs/audio/Opus/CeltEncoder") + +local Encode = {} + + + + + + + + + +local floor = math.floor + +-- encode(audio | decoder, opts) -> buffer | nil, Err +function Encode.encode(value, opts) +local o= opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + 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 = src.sampleRate + if rate < 1000 or rate > 768000 then + return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) + end + local bitrate = o.bitrate or 64000 * ch + if type(bitrate) == "number" and bitrate > 0 and bitrate < 1000 then + bitrate =bitrate* 1000 -- kbit/s + end + if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then + return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000") + end + -- the whole input at 48 kHz (codecs/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 + src = rs + end + local all, aerr = Pcm.collect(src ) + if not all then + return nil, aerr + end + local n48 = all.frames + local samples = all.samples + local pcm= 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 + local packets = math.floor((n48 + preSkip + FRAME - 1) / FRAME +) -- zero padding to whole frames + for i = n48 * ch + 1, packets * FRAME * ch do + pcm[i] = 0 + end + local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), ch == 2 and 40 or 20, 1275 - 1) + local st = CeltEncoder.new(ch) + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(o.serial or 0x4f707573) + -- OpusHead + local head = Bytes.writer(19) + head:string("OpusHead") + head:u8(1) + head:u8(ch) + head:u16le(preSkip) + head:u32le(floor(rate)) + head:u16le(0) + head:u8(0) + s:packet(head:finish(), 0, { flush = true }) + -- OpusTags + local tags = o.tags or src.tags or {} + local tw = Bytes.writer(256) + tw:string("OpusTags") + local vendor = o.vendor or "rosetta" + tw:u32le(#vendor) + tw:string(vendor) + local fields = VorbisComment.fields(tags) + tw:u32le(#fields) + for _, field in __iter(fields) do + tw:u32le(#field) + tw:string(field) + end + s:packet(tw:finish(), 0, { flush = true }) + -- audio + local toc = 31 * 8 + (ch == 2 and 4 or 0) + for p = 0, packets - 1 do + local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) + local pkt = buffer.create(bytes + 1) + buffer.writeu8(pkt, 0, toc) + buffer.copy(pkt, 1, frame, 0, bytes) + local last = p == packets - 1 + local granule = (last and((preSkip + n48 ))or(((p + 1) * FRAME +))) s:packet(pkt, granule, { eos = last }) + end + return mux:finish(), nil +end + +return Encode +end +__FILES["audio/qoa"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- audio/qoa: QOA, "Quite OK Audio" (.qoa), over codecs/audio/Qoa (a port of qoa.h, phoboslab, MIT). New in +-- rosetta. Decode / open: static files and streaming files (total 0 in the header), 1-255 channels (WAVE order +-- for 1-8, as the spec lays them out), any rate up to 16777215 Hz, frame-accurate seeking (every frame carries its +-- own predictor state), a truncated file decodes its whole frames. Encode (Audio or Decoder, streamed frame by frame): +-- byte-for-byte what qoa.h's qoa_encode writes, 1-8 channels (qoa.h's limit). Not supported: frames whose channel +-- count or rate change mid-stream (Err.UNSUPPORTED). +-- +-- local dec = Qoa.open(Bytes.reader(buf)) -- Types.Decoder +-- local file = Qoa.encode(audio) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local Codec = __include("codecs/audio/Qoa") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoa = { + name = "qoa", + category = "audio", + extensions = { "qoa" }, + mime = { "audio/qoa" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/Qoa" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, seek = true, channels = 8 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + +function Qoa.sniff(r) +return r:peek(4) == "qoaf" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoa.decode(r, opts) +local dec, err = Qoa.open(r) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "qoa", streaming = d.streaming }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoa.encode(value, _opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 8 then + return nil, Err.new(Err.ARG, "QOA (qoa.h) holds at most 8 channels") + end + if rate ~= math.floor(rate) or rate < 1 or rate > 0xFFFFFF then + return nil, Err.new(Err.ARG, "the sample rate must be an integer in 1 .. 16777215") + end + local FL = Codec.FRAME_LEN + local w = Bytes.writer(8 + ((src.frames > 0 and{(Codec.frameSize(ch, math.floor((src.frames + 19) / 20)) + 24 * ch * (math.floor(src.frames / FL )+ 1) )}or{65536})[1])) + w:string("qoaf") + w:u32be(0) + local lms = Codec.newLms(ch) + local fb = buffer.create(FL * ch * 4) + local tmp= nil + local total = 0 + while true do + -- one frame: 5120 sample frames (the last may be shorter), as qoa.h cuts them + local have = 0 + while have < FL do + local b, n = src:read(FL - have, tmp) + if n <= 0 then + break + end + tmp = b + buffer.copy(fb, have * ch * 4, b, 0, n * ch * 4) + have =have+ n + end + if have == 0 then + break + end + local at = w:reserve(Codec.frameSize(ch, math.floor((have + 19) / 20))) + w.pos = at + Codec.encodeFrame(fb, 0, have, ch, rate, lms, w.buf, at) + total =total+ have + if have < FL then + break + end + end + if src.err then + return nil, src.err + end + if total == 0 then + return nil, Err.new(Err.ARG, "QOA needs at least one sample") + end + if total >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "too many samples for QOA") + end + local out = w:finish() + buffer.writeu32(out, 4, bit32.byteswap(total)) + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Qoa.open(r, _opts) +if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + if h:string(4) ~= "qoaf" then + return nil, Err.new(Err.CORRUPT, "not a QOA file") + end + local declared = h:u32be() + if h.err then + return nil, h.err + end + local buf = r.buf + -- the frame index: offsets, first frames + local offs, starts = {}, {} + local p, total = r.base + 8, 0 + local ch, rate = 0, 0 + while p < r.limit do + local info, msg = Codec.frameInfo(buf, p, r.limit - p) + if not info then + if #offs == 0 then + return nil, Err.from(msg, p - r.base) + end + break -- a cut or damaged tail: keep the whole frames + end + if #offs == 0 then + ch, rate = info.channels, info.rate + elseif info.channels ~= ch or info.rate ~= rate then + return nil, Err.new(Err.UNSUPPORTED, "the channel count or rate changes mid-stream", p - r.base) + end + table.insert(offs, p) + table.insert(starts, total) + total =total+ info.samples + p =p+ info.size + if declared > 0 and total >= declared then + break + end + end + if #offs == 0 then + return nil, Err.new(Err.TRUNCATED, "no frames") + end + local frames = (declared > 0 and{(math.min(declared, total) )}or{total +})[1] local pcm = buffer.create(Codec.FRAME_LEN * ch * 4) + local dec= { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = math.floor((p - r.base) * 8 / math.max(frames / rate, 1e-9)), + tags = {}, + streaming = declared == 0, + } + local limit = r.limit + return Stream.packets(dec, { + count = #offs, + start = function(i) +return (i > #offs and{total }or{starts[i] +})[1] end, + decode = function(i) +local n, msg = Codec.decodeFrame(buf, offs[i], limit - offs[i], pcm, 0) + if not n then + return nil, Err.from(msg, offs[i] - r.base) + end + return n, nil + end, + pcm = function() +return pcm + end, + reset = function() end, + stop = frames, + }) +end + +return Qoa +end +__FILES["audio/tta"] = function() +local __compat = __compat local bit32, type = __compat.bit32, __compat.type --!strict +-- audio/tta: True Audio (.tta, TTA1) files around codecs/audio/Tta: an optional ID3v2 tag in front (skipped), the +-- header and seek table, independent frames (sample-accurate seeking), APEv2 tags at the end (codecs/audio/ApeTag). +-- Written from the TTA1 format description; no libtta / ffmpeg code. Supports 8 / 16 / 24 bits, any channel count. +-- Not supported: password-protected files (Err.UNSUPPORTED), TTA2, ID3v2 tag contents, encoding. +-- +-- local dec = Tta.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, readInt +-- local audio = Tta.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local TtaCodec = __include("codecs/audio/Tta") + +-- ------------------------------------------------------------------------------------------------ contract +local Tta = { + name = "tta", + category = "audio", + extensions = { "tta" }, + mime = { "audio/x-tta", "audio/tta" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/Tta" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, depths = { 8, 16, 24 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff +-- the size of an ID3v2 tag at the reader's start (0 when none) + + + + + +local function id3Size(r) +if r:peek(3) ~= "ID3" then + return 0 + end + local sz = 0 + for i = 6, 9 do + local v = r:peekU8(i) + if v < 0 then + return 0 + end + sz = sz * 128 + bit32.band(v, 127) + end + local footer = bit32.band(math.max(r:peekU8(5), 0), 0x10) ~= 0 + return 10 + sz + (footer and 10 or 0) +end + +function Tta.sniff(r) +return r:peek(4, id3Size(r)) == "TTA1" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function Tta.decode(r, opts) +local dec, err = Tta.open(r, opts) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err +function Tta.open(r, opts) +if type(r) == "buffer" then + r = Bytes.reader(r ) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local at = base + id3Size(r) + local tags, tagInfo = ApeTag.find(buf, at, limit) + local stop = (tagInfo and{tagInfo.start }or{limit +})[1] local info, err = TtaCodec.info(buf, at, stop) + if not info then + return nil, err + end + if info.channels * info.frameLength > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels of " .. info.frameLength .. "-sample frames") + end + local codec = TtaCodec.decoder(info, stop) + local frames = info.samples + local dec= { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = false, + source = { format = "tta", bitDepth = info.bitsPerSample, tags = tagInfo and tagInfo.items }, + } + local fl, count = info.frameLength, info.frames + return Stream.packets(dec, { + count = count, + start = function(i) +return (i > count and{frames }or{((i - 1) * fl +)})[1] end, + decode = function(i) +return codec:frame(buf, i) + end, + pcm = function() +return codec.pcm + end, + reset = function() end, + stop = frames, + scale = 1 / 2 ^ (info.bitsPerSample - 1), + ints = true, + }) +end + +return Tta +end +__FILES["audio/vag"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- audio/vag: Sony VAG (PlayStation SPU PS-ADPCM, .vag), and Simon & Schuster / Hyperscan KVAG (IMA ADPCM, the same +-- extension), over codecs/audio/Adpcm. New in rosetta; the header variants and the PS-ADPCM decoding follow +-- vgmstream r2117 (ISC, licenses/vgmstream-LICENSE.txt), whose output it matches bit for bit. Supports: "VAGp" mono +-- (versions 0, 2, 3, 4, 6, 0x20; the name field as tags.title; loop points from the frame flags, as dec.loop and +-- meta.source.loop = { start, stop } in frames, stop exclusive), "VAGi" stereo (interleaved blocks), "KVAG" mono / +-- stereo IMA. The output starts with the blank frame Sony's tools put first (28 silent samples), as vgmstream plays it. +-- Encode (Audio or Decoder): mono to VAGp, stereo to VAGi (2048-byte interleave), loop points from opts.loop (frame +-- aligned: 28 samples). Not supported: HEVAG (VAGp versions 0x00020001 / 0x00030000, Vita / PS4), the many game +-- specific variants vgmstream knows (pGAV, VAG1 / VAG2, Jak, ...). +-- +-- local dec = Vag.open(Bytes.reader(buf)) -- Types.Decoder (+ loop, variant) +-- local file = Vag.encode(audio, { loop = { start = 0, stop = audio.frames } }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Adpcm = __include("codecs/audio/Adpcm") +local Decoder = __include("codecs/audio/Adpcm/Decoder") + +-- ------------------------------------------------------------------------------------------------ contract +local Vag = { + name = "vag", + category = "audio", + extensions = { "vag" }, + mime = { "audio/x-vag" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Adpcm", "codecs/audio/Adpcm/Decoder" }, + caps = { decode = true, encode = true, streaming = true, lossy = true, loops = true, channels = 2 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + +local HEVAG = { [0x00020001] = true, [0x00030000] = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Vag.sniff(r) +local m = r:peek(4) + return (m == "VAGp" or m == "VAGi" or m == "KVAG" )and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vag.decode(r, opts) +local dec, err = Vag.open(r) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, { format = "vag", variant = d.variant, codec = d.codec, loop = d.loop }, limit) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vag.encode(value, opts) +local o= opts or {} + local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local ch, rate = src.channels, src.sampleRate + if ch > 2 then + return nil, Err.new(Err.ARG, "VAG holds mono or stereo") + end + if rate ~= math.floor(rate) or rate < 1 or rate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local il = o.interleave or 2048 + if type(il) ~= "number" or il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.ARG, "interleave must be a multiple of 16") + end + local loop = o.loop + local v = value +if loop == nil and type(v.meta) == "table" and type(v.meta.source) == "table" and type(v.meta.source.loop) == "table" then + loop = v.meta.source.loop + end + local a, cerr = Pcm.collect(src) + if not a then + return nil, cerr + end + local n = a.frames + local nf = math.floor((n + 27) / 28 -- data frames (after the blank one) +) local ls, le = -1, -1 + if loop then + if type(loop.start) ~= "number" or type(loop.stop) ~= "number" or loop.start < 0 or loop.stop > n then + return nil, Err.new(Err.ARG, "loop must be { start, stop } inside the audio") + end + ls, le = math.floor(loop.start / 28), math.floor((loop.stop + 27) / 28 )- 1 + if le <= ls then + return nil, Err.new(Err.ARG, "the loop must span two 28-sample frames") + end + end + local chBytes = (nf + 1) * 16 + local stride = (ch == 1 and{chBytes }or{(math.floor((chBytes + il - 1) / il )* il +)})[1] local start = ch == 1 and 0x30 or 0x800 + local out = buffer.create(start + stride * ch) + local title = o.name or (a.tags and a.tags.title) or "" + buffer.writestring(out, 0, ch == 1 and"VAGp" or"VAGi") + buffer.writeu32(out, 4, bit32.byteswap(0x20)) + if ch == 2 then + buffer.writeu32(out, 8, il) + end + buffer.writeu32(out, 0x0C, bit32.byteswap((ch == 1 and{chBytes }or{stride})[1])) + buffer.writeu32(out, 0x10, bit32.byteswap(rate)) + buffer.writestring(out, 0x20, string.sub(title, 1, 16)) + local st = buffer.create(8 * ch) + local plane = buffer.create(chBytes) + for c = 0, ch - 1 do + buffer.fill(plane, 0, 0) + Adpcm.psxEncode(a.samples, c, ch, n, st, c * 8, plane, 16, 16) + for k = 0, nf - 1 do + local flag = k == ls and 6 or(k == le and 3 or(k > ls and k < le and 2 or 0 +)) if not loop and k == nf - 1 then + flag = 1 + end + buffer.writeu8(plane, 16 + k * 16 + 1, flag) + end + if ch == 1 then + buffer.copy(out, start, plane, 0, chBytes) + else + for b = 0, math.floor(stride / il )- 1 do + local take = math.clamp(chBytes - b * il, 0, il) + if take > 0 then + buffer.copy(out, start + (b * ch + c) * il, plane, b * il, take) + end + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- the loop from the PS-ADPCM frame flags of channel 0 (vgmstream's reading: the first start flag 6, the first end +-- flag 3), or nil +local function findLoop(buf, p, frames, il, ch) +local ls, le = -1, -1 + for k = 0, frames - 1 do + local off = p + math.floor((k * 16) / il )* il * ch + (k * 16) % il + local flag = bit32.band(buffer.readu8(buf, off + 1), 15) + if flag == 6 and ls < 0 then + ls = k * 28 + elseif flag == 3 and le < 0 then + le = k * 28 + 28 + if ls >= 0 then + break + end + end + end + return ls >= 0 and le > ls and{ start = ls, stop = le } or nil +end + +function Vag.open(r, _opts) +if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local h = r:sub(0) + local magic = h:string(4) + local total = r.limit - r.base + if magic == "KVAG" then + local size, rate, stereo = h:u32le(), h:u32le(), h:u16le() + if h.err then + return nil, h.err + end + if rate < 1 or stereo > 1 then + return nil, Err.new(Err.CORRUPT, "bad KVAG header") + end + local dec= { sampleRate = rate, channels = stereo + 1, tags = {}, variant = "KVAG", codec = "ima" } + local d, err = Decoder.nibbles(dec, { buf = r.buf, offset = r.base + 14, size = math.min(size, total - 14), hi = true }) + if d then + d.bitrate = rate * 4 * (stereo + 1) + end + return d, err + end + if magic ~= "VAGp" and magic ~= "VAGi" then + return nil, Err.new(Err.CORRUPT, "not a VAG file") + end + local version, il = h:u32be(), h:u32le() + local chSize, rate = h:u32be(), h:u32be() + local name = r:sub(0x20, 16):cstring(16) + if h.err then + return nil, h.err + end + if HEVAG[version] then + return nil, Err.new(Err.UNSUPPORTED, "HEVAG (Vita / PS4 VAG)") + end + if rate < 1 or rate >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local ch, start = 1, 0x30 + if magic == "VAGi" then + ch, start = 2, 0x800 + if il < 16 or il % 16 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. il) + end + else + il = 16 + end + if total < start then + return nil, Err.new(Err.TRUNCATED, "the header runs past the end") + end + local size = math.min(chSize * ch, total - start) + local p = r.base + start + local frames = math.min(math.floor(chSize / 16), (math.floor(size / (il * ch))) * (math.floor(il / 16)) + math.floor(math.clamp(size % (il * ch) - (ch - 1) * il, 0, il) / 16)) + local loop = (magic == "VAGp" and{(findLoop(r.buf, p, frames, il, ch) )}or{nil -- vgmstream: VAGi never loops +})[1] local tags = {} + if name ~= "" then + tags.title = name + end + local dec= { sampleRate = rate, channels = ch, tags = tags, variant = magic, codec = "psx", loop = loop } + local d, err = Decoder.interleaved(dec, { kind = "psx", buf = r.buf, offset = p, size = size, interleave = il, frames = frames * 28 }) + if d then + d.bitrate = math.floor(rate * 16 * 8 * ch / 28 +) end + return d, err +end + +return Vag +end +__FILES["audio/voc"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- audio/voc: Creative Voice File (.voc, Sound Blaster). New code from the Creative file format description. +-- Supports: decode / open of block types 1 (sound data: 8-bit unsigned, 16-bit), 2 (continuation), 3 (silence), +-- 5 (text: tags.comment), 8 (extended: stereo / high rates for the next type 1 block), 9 (new sound data: 8-bit +-- unsigned, 16-bit signed, A-law, mu-law, any rate / channel count); markers and repeat loops are skipped (played +-- once, as ffmpeg does); truncated files decode the data present. Encode (Audio or Decoder, streamed) as version +-- 1.20 type 9 blocks of u8 / s16 (default) / alaw / ulaw. Not supported: Creative 4 / 2.6 / 2-bit ADPCM +-- (Err.UNSUPPORTED), blocks that change the channel count mid-file (the sample rate of the first block is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Voc = { + name = "voc", + category = "audio", + extensions = { "voc" }, + mime = { "audio/x-voc" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local MAGIC = "Creative Voice File\26" +local T9_CODECS= { [0] = "u8", [4] = "s16le", [6] = "alaw", [7] = "ulaw" } +local T1_CODECS= { [0] = "u8", [4] = "s16le" } +local WRITE = { u8 = { 0, "u8", 8 }, s16 = { 4, "s16le", 16 }, alaw = { 6, "alaw", 8 }, ulaw = { 7, "ulaw", 8 } } +local MAX_BLOCK = 0xFFFFFF - 12 -- payload bytes of one type 9 block (a 24-bit size, 12 header bytes) + +local readu8 = buffer.readu8 +local function u16(b, o) +return readu8(b, o) + readu8(b, o + 1) * 256 +end +local function u24(b, o) +return readu8(b, o) + readu8(b, o + 1) * 256 + readu8(b, o + 2) * 65536 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Voc.sniff(r) +return r:peek(20) == MAGIC and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +function Voc.decode(r, opts) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < 26 or buffer.readstring(b, base, 20) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic", base) + end + local hsize = u16(b, base + 20) + local version = u16(b, base + 22) + if hsize < 26 or hsize > limit - base then + return nil, Err.new(Err.CORRUPT, "bad header size", base + 20) + end + local maxFrames = opts and opts.maxFrames or 2 ^ 28 + local rate, channels = 0, 0 + local extRate, extChannels = 0, 0 -- a type 8 block's settings for the next type 1 block + local lastFmt= nil + local codec = -1 + local segments= {} + local total = 0 + local truncated = false + local tags= {} + local p = base + hsize + -- add(at, bytes, fmt, ch, sr): a run of samples (or silence when fmt is nil and bytes = frames) + local function add(at, bytes, fmt, ch, sr) +if channels == 0 then + channels, rate = ch, sr + elseif ch ~= channels then + return Err.new(Err.UNSUPPORTED, "the channel count changes mid-file", at) + end + local frames = (fmt and{(math.floor(bytes / (ch * Pcm.Convert.SIZE[fmt]) ))}or{bytes +})[1] if frames > 0 then + total =total+ frames + if total > maxFrames then + return Err.new(Err.LIMIT, string.format("over the %d frame limit", maxFrames)) + end + table.insert(segments, { at = at, frames = frames, fmt = fmt }) + end + return nil + end + while p < limit do + local t = readu8(b, p) + if t == 0 then + break + end + if p + 4 > limit then + truncated = true + break + end + local size = u24(b, p + 1) + local d = p + 4 + local avail = math.min(size, limit - d) + if avail < size then + truncated = true + end + local err= nil + if t == 1 then + if avail < 2 then + break + end + local div, c = readu8(b, d), readu8(b, d + 1) + local fmt = T1_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "Creative ADPCM (codec " .. c .. ")", d + 1) + end + local ch, sr = 1, math.floor(1000000 / (256 - div) +) if extChannels > 0 then + ch, sr = extChannels, extRate + extChannels = 0 + end + lastFmt, codec = fmt, c + err = add(d + 2, avail - 2, fmt, ch, sr) + elseif t == 2 then + if lastFmt == nil then + return nil, Err.new(Err.CORRUPT, "continuation block before any sound data", p) + end + err = add(d, avail, lastFmt, channels, rate) + elseif t == 3 then + if avail < 3 then + break + end + local len, div = u16(b, d) + 1, readu8(b, d + 2) + err = add(d, len, nil, (channels > 0 and{channels }or{1})[1], (rate > 0 and{rate }or{(math.floor(1000000 / (256 - div)))})[1]) + elseif t == 5 then + local s = buffer.readstring(b, d, avail) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + tags.comment = (tags.comment and((tags.comment .. "\n" .. s ))or(s +)) elseif t == 8 then + if avail < 4 then + break + end + local tc, mode = u16(b, d), readu8(b, d + 3) + extChannels = mode + 1 + extRate = math.floor(256000000 / (extChannels * (65536 - tc)) +) elseif t == 9 then + if avail < 12 then + break + end + local sr = readu8(b, d) + readu8(b, d + 1) * 256 + readu8(b, d + 2) * 65536 + readu8(b, d + 3) * 16777216 + local ch, c = readu8(b, d + 5), u16(b, d + 6) + local fmt = T9_CODECS[c] + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, "codec " .. c, d + 6) + end + if ch < 1 or sr < 1 then + return nil, Err.new(Err.CORRUPT, "bad channels or sample rate", d) + end + lastFmt, codec = fmt, c + err = add(d + 12, avail - 12, fmt, ch, sr) + end + if err then + return nil, err + end + p = d + size + end + if channels == 0 then + return nil, Err.new((truncated and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no sound data", p) + end + local a = Types.Audio.new(rate, channels, total) + local o = 0 + for _, s in __iter(segments) do + local n = s.frames * channels + if s.fmt then + Pcm.Convert.decode(b, s.at, s.fmt , n, a.samples, o) + end -- silence: the buffer is already zero + o =o+ n * 4 + end + a.tags = tags + a.meta.source = { + format = "voc", + version = string.format("%d.%02d", math.floor(version / 256), version % 256), + codec = codec, + sampleFormat = lastFmt, + bitDepth = lastFmt == "s16le" and 16 or 8, + truncated = truncated or nil, + } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Voc.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local spec = WRITE[o.sampleFormat or "s16"] + if not spec then + return nil, Err.new(Err.ARG, "unknown sampleFormat " .. tostring(o.sampleFormat)) + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be an integer") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + w:u16le(26) + w:u16le(0x0114) + w:u16le((0xFFFF - 0x0114 + 0x1234 + 1) % 65536) -- ~version + 0x1234 + if type(src.tags.comment) == "string" and #src.tags.comment > 0 then + local s = string.sub(src.tags.comment, 1, 0xFFFFFE) + w:u8(5) + w:u24le(#s + 1) + w:string(s) + w:u8(0) + end + local size = Pcm.Convert.SIZE[spec[2] ] + local frameBytes = size * src.channels + local framesPerBlock = math.floor(MAX_BLOCK / frameBytes +) local blockAt, blockFrames = -1, 0 + local tmp= nil + while true do + local bf, n = src:read(math.min(8192, framesPerBlock), tmp) + if n <= 0 then + break + end + tmp = bf + local i = 0 + while i < n do + if blockAt < 0 or blockFrames == framesPerBlock then + blockAt = w:tell() + blockFrames = 0 + w:u8(9) + w:u24le(0) -- patched + w:u32le(src.sampleRate) + w:u8(spec[3]) + w:u8(src.channels) + w:u16le(spec[1]) + w:u32le(0) + end + local take = math.min(n - i, framesPerBlock - blockFrames) + local at = w:reserve(take * frameBytes) + Pcm.Convert.encode(bf, i * src.channels * 4, take * src.channels, spec[2], w.buf, at) + w.pos = at + take * frameBytes + blockFrames =blockFrames+ take + i =i+ take + local len = blockFrames * frameBytes + 12 + w:setU8(blockAt + 1, len % 256) + w:setU8(blockAt + 2, (math.floor(len / 256)) % 256) + w:setU8(blockAt + 3, math.floor(len / 65536)) + end + end + if src.err then + return nil, src.err + end + w:u8(0) -- terminator + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +function Voc.open(r, opts) +local a, err = Voc.decode(r, opts) + if not a then + return nil, err + end + local dec = (Pcm.audioDecoder(a) ) +dec.source = a.meta.source + return dec, nil +end + +return Voc +end +__FILES["audio/vorbis"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!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/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, +-- coupling, sparse / ordered codebooks, lookup types 1 / 2; comment-header tags (lower-cased keys); a packet-level +-- decoder (Vorbis.packetDecoder) for Vorbis in Matroska / WebM / MP4. Encode (audio/vorbis/Encode, new code): a basic +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Packet = __include("codecs/audio/Vorbis/Packet") +local Encode = __include("audio/vorbis/Encode") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") + +-- ------------------------------------------------------------------------------------------------ contract +local Vorbis = { + name = "vorbis", + category = "audio", + extensions = { "ogg", "oga" }, + mime = { "audio/ogg", "audio/vorbis" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels) + + + + + + + + + +local function waveOrder(ch) +local m = Pcm.WAVE_FROM_VORBIS[ch] + if m then + return m + end + 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, raw comment fields | nil, Err +local function headers(h1, h2, h3) +local id, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id then + 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, 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 = (serr == "floor 0" and{Err.UNSUPPORTED }or{Err.CORRUPT +})[1] return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header") + end + local tags, raw = VorbisComment.tags(comments or {}) + return id, setup, vendor, tags, raw, nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vorbis.sniff(r) +if r:remaining() < 35 or r:peek(4) ~= "OggS" then + return 0 + end + local b, p = r.buf, r.pos + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 > r.limit then + return 0 + end + return buffer.readu8(b, d) == 1 and buffer.readstring(b, d + 1, 6) == "vorbis" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vorbis.decode(r, opts) +local dec, err = Vorbis.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audioOrDecoder, opts?) -> an Ogg Vorbis file | nil, Err +function Vorbis.encode(value, opts) +local src, serr = Pcm.source(value) + if not src then + return nil, serr + end + local o= opts or {} + local q = o.quality or 3 + if type(q) ~= "number" or q ~= q or q < -1 or q > 10 then + return nil, Err.new(Err.ARG, "quality must be -1 .. 10") + end + if src.channels > 255 then + return nil, Err.new(Err.ARG, "at most 255 channels") + end + if src.sampleRate ~= math.floor(src.sampleRate) or src.sampleRate < 1 or src.sampleRate >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "the sample rate must be a positive integer") + end + local serial = o.serial or 0x464C5541 + if type(serial) ~= "number" or serial ~= math.floor(serial) or serial < 0 or serial >= 2 ^ 32 then + return nil, Err.new(Err.ARG, "serial must be a 32-bit unsigned integer") + end + local out, msg = Encode.encode(src , { quality = q, vendor = "rosetta Vorbis encoder", serial = serial }) + if not out then + return nil, Err.new(Err.CORRUPT, tostring(msg)) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +local Stream = {} +Stream.__index = Stream + +-- queue the chunk arrays[first .. first + count - 1] whose first sample has granule g0, trimmed to [lo, hi) +local function push(self, arrays, g0, count, hi) + local lo = math.max(g0, self.startG, self.skipTo) + if hi > g0 + count then + hi = g0 + count + end + if hi > lo then + table.insert(self.queue, { arrays, lo - g0 + 1, hi - g0, lo }) + end +end + +local function copyOut(self, count) +local t = table.create(self.channels) + for c = 1, self.channels do + local src = self.st.out[c] + local a = table.create(count, 0) + table.move(src, 1, count, 1, a) + t[c] = a + end + return t +end + +-- decode packets until something is queued; false at the end of the stream +local function decodeMore(self) +local reader, st = self.reader, self.st + while not self.ended do + local p = reader:nextPacket() + if p == nil then + self.ended = true + break + end + if p.gap then + Packet.reset(st) + self.syncing, self.pend, self.pendCount = true, {}, 0 + end + local count = Packet.decode(st, p.data, p.offset, p.size) + if count >= 0 then + local endG = (p.eos and p.granule >= 0 and{p.granule }or{math.huge +})[1] if self.syncing then + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount =self.pendCount+ count + end + if p.granule >= 0 then + -- the position is known again: this packet's output ends at its granule + local g = p.granule - self.pendCount + if p.eos and self.pendCount > 0 then + g = math.max(g, self.pos) -- an end-trimmed last page: keep the running position + end + for _, c in __iter(self.pend) do + push(self, c[1], g, c[2], endG) + g =g+ c[2] + end + self.pos = g + self.syncing, self.pend, self.pendCount = false, {}, 0 + end + else + local g0 = self.pos + self.pos =self.pos+ count + if count > 0 then + push(self, st.out, g0, count, endG) + end + if p.granule >= 0 and not p.eos then + self.pos = p.granule + end + end + if p.eos then + self.ended = true + end + if #self.queue > 0 then + return true + end + end + end + return #self.queue > 0 +end + +function Stream.read(self, n, out) +local ch = self.channels + n = math.max(0, math.floor(n)) + local b = (out and buffer.len(out) >= n * ch * 4 and{out }or{(buffer.create(n * ch * 4) +)})[1] local got = 0 + local writef32 = buffer.writef32 + while got < n do + local q = self.queue[1] + if q == nil then + if not decodeMore(self) then + break + end + q = self.queue[1] + 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[order[c] ] + local o = got * ch * 4 + (c - 1) * 4 + for i = first, first + take - 1 do + writef32(b, o, a[i]) + o =o+ ch * 4 + end + end + got =got+ take + self.next = q[4] + take + if first + take > last then + table.remove(self.queue, 1) + else + q[2] = first + take + q[4]=q[4]+ take + end + end + if got > 0 then + self.skipTo = -math.huge + end + return b, got +end + +function Stream.position(self) +return (self.next - self.startG) / self.sampleRate +end + +-- back to the first audio packet +local function restart(self) + local r = self.reader + r:rewind() + for _ = 1, 3 do + r:nextPacket() + end + Packet.reset(self.st) + self.pos = self.base + self.syncing, self.pend, self.pendCount = false, {}, 0 + self.ended = false + self.queue = {} +end + +function Stream.seek(self, seconds) + local target = self.startG + math.floor(math.max(0, seconds) * self.sampleRate + 0.5) + if target ~= target then + target = self.startG + end + if self.lastG >= 0 and target > self.lastG then + target = self.lastG + end + self.skipTo = target + self.next = target + local r = self.reader + local g = target - self.st.n1 + for _ = 1, 16 do + if g <= self.startG then + break + end + local G = r:seekGranule(g) + if G == nil or G < 0 then + break + end + -- decode forward to the next page boundary to learn the exact position + Packet.reset(self.st) + self.queue = {} + self.ended = false + self.syncing, self.pend, self.pendCount = true, {}, 0 + self.pos = G + local ok = false + while true do + local p = r:nextPacket() + if p == nil then + break + end + local count = Packet.decode(self.st, p.data, p.offset, p.size) + if count > 0 then + table.insert(self.pend, { copyOut(self, count), count }) + self.pendCount =self.pendCount+ count + end + if p.granule >= 0 then + if not p.eos then + local g0 = p.granule - self.pendCount + for _, c in __iter(self.pend) do + push(self, c[1], g0, c[2], math.huge) + g0 =g0+ c[2] + end + self.pos = p.granule + self.syncing, self.pend, self.pendCount = false, {}, 0 + ok = true + end + break + end + end + if ok then + return + end + g = G - 1 -- the last page: start one page earlier + end + restart(self) + self.skipTo = target + self.next = target +end + +function Vorbis.open(r, opts) +local demux, derr = Ogg.open(r, opts and opts.verify == false and{ verify = false } or nil) + if not demux then + return nil, derr + end + local serial = demux:find("vorbis") + if serial == nil then + return nil, Err.new(Err.CORRUPT, "no Vorbis stream in the Ogg file") + end + local reader = demux:reader(serial) + local h1 = reader:nextPacket() + if h1 == nil then + return nil, Err.new(Err.TRUNCATED, "missing identification header") + end + local id0, ierr = Setup.ident(h1.data, h1.offset, h1.size) + if not id0 then + return nil, Err.new(Err.CORRUPT, ierr or "bad identification header") + end + local h2 = reader:nextPacket() + if h2 == nil then + return nil, Err.new(Err.TRUNCATED, "missing comment header") + end + local h2copy = { data = Ogg.copy(h2), offset = 0, size = h2.size } + local h3 = reader:nextPacket() + if h3 == nil then + return nil, Err.new(Err.TRUNCATED, "missing setup header") + end + local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3) + if not id then + return nil, herr + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + -- the granule of the first returned sample: the first granule page minus what its packets return + local base = 0 + do + local prev, sum = 0, 0 + while true do + local p = reader:nextPacket() + if p == nil then + break + end + local bs = Packet.blocksize(st, p.data, p.offset, p.size) + if bs > 0 then + if prev > 0 then + sum =sum+ (math.floor(prev / 4 )+ math.floor(bs / 4 +)) end + prev = bs + end + if p.granule >= 0 then + base = p.granule - sum + if p.eos then + base = 0 -- one page holds the whole stream: the spec trims its end, not its start + end + break + end + end + end + local info = demux:stream(serial) + local lastG = (info and info.lastGranule and info.lastGranule >= 0 and{info.lastGranule }or{(-1 +)})[1] local startG = math.max(base, 0) + local frames = (lastG >= 0 and{(math.max(0, lastG - startG) )}or{0 +})[1] local rate = id.sampleRate + local self = setmetatable({ + sampleRate = rate, + channels = id.channels, + frames = frames, + duration = frames / rate, + bitrate = (frames > 0 and{(math.floor(demux.size * 8 / (frames / rate)) )}or{id.bitrateNominal})[1], + 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, + }, + demux = demux, + reader = reader, + st = st, + base = base, + startG = startG, + lastG = lastG, + pos = base, + next = startG, + skipTo = -math.huge, + queue = {}, + syncing = false, + pend = {}, + pendCount = 0, + ended = false, + }, Stream) + restart(self) + return self , nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- packetDecoder(ident, comment, setup) -> a decoder of raw Vorbis packets (Matroska / WebM / MP4 carry the three +-- headers in their codec private data) | nil, Err. Each argument is a buffer holding one header packet. +-- local pd = Vorbis.packetDecoder(h1, h2, h3) +-- local n = pd:decode(buf, offset, size) -- frames returned (first packet 0; -1 = not audio); pd.out[ch][1 .. n] +-- pd:reset() -- after a seek +function Vorbis.packetDecoder(h1, h2, h3) +local function pk(b) +return { data = b, offset = 0, size = buffer.len(b) } + end + local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3)) + if not id then + return nil, err + end + local st = Packet.new(id, setup) + if not st then + return nil, Err.new(Err.CORRUPT, "bad block sizes") + end + return { + sampleRate = id.sampleRate, + channels = id.channels, + vendor = vendor, + tags = tags, + out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]] + order = waveOrder(id.channels), + decode = function(_self, b, offset, size) +if offset < 0 or size < 0 or offset + size > buffer.len(b) then + return -1 + end + return Packet.decode(st, b, offset, size) + end, + reset = function(_self) + Packet.reset(st) + end, + }, + nil +end + +return Vorbis +end +__FILES["audio/vorbis/Encode"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!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/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 = __include("codecs/audio/Mdct") +local Pcm = __include("codecs/audio/Pcm") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Ogg = __include("containers/Ogg") +local Tables = __include("codecs/audio/Vorbis/Tables") + +local Encode = {} + +local floor, log, exp, abs = math.floor, math.log, math.exp, math.abs +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +local N = 2048 +local N2 = 1024 +local PSIZE_PER_CHANNEL = 16 -- residue partitions hold 16 values per channel (libvorbis needs a multiple of ch) +local MULT = 2 -- floor1 multiplier (range 128) +local RANGE = 128 +local NCLASS = 6 +-- ------------------------------------------------------------------------------------------------ LSB-first bit writer + + + +local function newW(size) +return { buf = buffer.create(size), pos = 0, acc = 0, cnt = 0 } +end + +local function put(w, v, n) + if n == 0 then + return + end + local acc = w.acc + v * POW[w.cnt + 1] + local cnt = w.cnt + n + local b, p = w.buf, w.pos + if p + 8 > buffer.len(b) then + local nb = buffer.create(buffer.len(b) * 2 + 64) + buffer.copy(nb, 0, b, 0, p) + b = nb + w.buf = nb + end + while cnt >= 8 do + local byte = acc % 256 + writeu8(b, p, byte) + p =p+ 1 + acc = (acc - byte) / 256 + cnt =cnt- 8 + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +local function finish(w) +if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out +end + +local function putString(w, s) + for i = 1, #s do + put(w, string.byte(s, i), 8) + end +end + +local function ilog(x) +local n = 0 + while x > 0 do + n =n+ 1 + x = floor(x / 2) + end + return n +end +-- ------------------------------------------------------------------------------------------------ codebooks +-- Huffman code lengths for weights w[1..n] (all > 0), at most 24 bits long (weights are floored to keep it so) + + + + + + + + + + + + +local function huffmanLengths(w) +local n = #w + local total = 0 + for i = 1, n do + total =total+ w[i] + end + local lens = table.create(n, 0) + if n == 1 then + lens[1] = 1 + return lens + end + local minw = total * 2 ^ -20 + -- nodes: leaves 1..n then internal; a simple O(n^2)-free approach with two sorted queues + local order = table.create(n, 0) + for i = 1, n do + order[i] = i + end + local weight = table.create(2 * n, 0) + local parent = table.create(2 * n, 0) + for i = 1, n do + weight[i] = math.max(w[i], minw) + end + table.sort(order, function(a, b) +if weight[a] ~= weight[b] then + return weight[a] < weight[b] + end + return a < b + end) + local q1, h1 = order, 1 -- leaves, ascending + local q2, h2, t2 = table.create(n, 0), 1, 0 -- internal nodes, created in ascending weight order + local nextId = n + local function pop() +local a = (h1 <= n and{q1[h1] }or{nil +})[1] local b = (h2 <= t2 and{q2[h2] }or{nil +})[1] if a and (not b or weight[a] <= weight[b]) then + h1 =h1+ 1 + return a + end + h2 =h2+ 1 + return b +end + for _ = 1, n - 1 do + local a = pop() + local b = pop() + nextId =nextId+ 1 + weight[nextId] = weight[a] + weight[b] + parent[a], parent[b] = nextId, nextId + t2 =t2+ 1 + q2[t2] = nextId + end + for i = 1, n do + local d, x = 0, i + while parent[x] ~= 0 do + x = parent[x] + d =d+ 1 + end + lens[i] = d + end + return lens +end + +-- the spec's codeword assignment (lowest free leaf, in entry order); returns bit-reversed codes +local function assign(lens) +local codes = table.create(#lens, 0) + local available = table.create(33, 0) + local first = true + for i, len in __iter(lens) do + if len > 0 then + local code + if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z =z- 1 + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- the top len bits of the 32-bit left-aligned code, MSB first, reversed for the LSB-first writer + local msb = floor(code / POW[33 - len]) + local rev = 0 + for _ = 1, len do + rev = rev * 2 + msb % 2 + msb = floor(msb / 2) + end + codes[i] = rev + end + end + return codes +end + +local function makeBook(dims, entries, weight, lookup, minimum, delta, values) +local w = table.create(entries, 0) + for e = 0, entries - 1 do + w[e + 1] = weight(e) + end + local lens = huffmanLengths(w) + return { dims = dims, entries = entries, lengths = lens, codes = assign(lens), lookup = lookup, minimum = minimum, delta = delta, values = values } +end + +-- a VQ book of `dims` dimensions over integer values -h .. h times `scale`, Laplacian weights exp(-|v| / s) +local function vqBook(dims, h, scale, s, zeroBoost) +local values = 2 * h + 1 + local entries = values ^ dims + return makeBook(dims, entries, function(e) +local wt = 1 + local x = e + for _ = 1, dims do + local v = x % values - h + x = math.floor(x / values +) wt =wt* (exp(-abs(v) / s) * ((v == 0 and{zeroBoost }or{1})[1]) +) end + return wt + end, 1, -h * scale, scale, values) +end + +local BOOK_FLOOR = makeBook(1, RANGE, function(e) +return exp(-e / 7) + 0.002 +end, 0, 0, 0, 0) +local CLASS_W = { 0.30, 0.30, 0.20, 0.12, 0.06, 0.02 } +local BOOK_CLASS = makeBook(2, NCLASS * NCLASS, function(e) +return CLASS_W[e % NCLASS + 1] * CLASS_W[math.floor(e / NCLASS )+ 1] +end, 0, 0, 0, 0) +local BOOK_A = vqBook(4, 1, 1, 0.6, 2.5) -- |v| <= 1, 4 at a time (mostly zeros) +local BOOK_B = vqBook(2, 4, 1, 1.4, 1) -- |v| <= 4 +local BOOK_C = vqBook(2, 15, 1, 4, 1) -- |v| <= 15 +local BOOK_D = vqBook(2, 15, 16, 3, 1) -- multiples of 16 up to 240 +local BOOK_E = vqBook(2, 15, 256, 3, 1) -- multiples of 256 up to 3840 +local BOOKS = { BOOK_FLOOR, BOOK_CLASS, BOOK_A, BOOK_B, BOOK_C, BOOK_D, BOOK_E } +local FLOOR_BOOK, CLASS_BOOK, A_BOOK, B_BOOK, C_BOOK, D_BOOK, E_BOOK = 0, 1, 2, 3, 4, 5, 6 +-- the books of each residue class per pass (book numbers; -1 = none) +local CLASS_BOOKS = { + { -1, -1, -1 }, + { A_BOOK, -1, -1 }, + { B_BOOK, -1, -1 }, + { C_BOOK, -1, -1 }, + { D_BOOK, C_BOOK, -1 }, + { E_BOOK, D_BOOK, C_BOOK }, +} +local CLASS_MAX = { 0, 1, 4, 15, 255, 4095 } + +-- float32_pack (spec 9.2.2) of an integer-valued x +local function float32Pack(x) +local sign = x < 0 and 2147483648 or 0 + local m = abs(x) + local e = 788 + while m >= 2097152 do + m =m/ 2 + e =e+ 1 + end + return sign + e * 2097152 + floor(m) +end + +local function writeBook(w, b) + put(w, 0x564342, 24) + put(w, b.dims, 16) + put(w, b.entries, 24) + put(w, 0, 1) -- not ordered + put(w, 0, 1) -- not sparse + for i = 1, b.entries do + put(w, b.lengths[i] - 1, 5) + end + put(w, b.lookup, 4) + if b.lookup == 1 then + put(w, float32Pack(b.minimum), 32) + put(w, float32Pack(b.delta), 32) + local vb = ilog(b.values - 1) + put(w, vb - 1, 4) + put(w, 0, 1) -- sequence_p + for j = 0, b.values - 1 do + put(w, j, vb) + end + end +end + +local function putEntry(w, b, e) + put(w, b.codes[e + 1], b.lengths[e + 1]) +end + +-- ------------------------------------------------------------------------------------------------ floor posts +-- x positions: 0, 1024, then 28 log-spaced points in bisection order (coarse first) so predictions are good +local POSTS= { 0, N2 } +do + local xs = {} + local seen = { [0] = true, [N2] = true } + for j = 0, 27 do + local x = floor(3 + 957 * (j / 27) ^ 2.2 + 0.5) -- 3 .. 960, denser at low frequencies + while seen[x] do + x =x+ 1 + end + seen[x] = true + table.insert(xs, x) + end + table.sort(xs) + -- bisection order over the sorted list + local queue = { { 1, #xs } } + local qh = 1 + while qh <= #queue do + local r = queue[qh] + qh =qh+ 1 + if r[1] <= r[2] then + local m = math.floor((r[1] + r[2]) / 2 +) table.insert(POSTS, xs[m]) + table.insert(queue, { r[1], m - 1 }) + table.insert(queue, { m + 1, r[2] }) + end + end +end +local NPOSTS = #POSTS -- 30 +local FLOOR_PARTS = math.floor((NPOSTS - 2) / 4 -- 7 partitions of one class with 4 dimensions +)local SORTED= table.create(NPOSTS, 0) -- post indices (1-based) by increasing x +for i = 1, NPOSTS do + SORTED[i] = i +end +table.sort(SORTED, function(a, b) +return POSTS[a] < POSTS[b] +end) +local LOW, HIGH = table.create(NPOSTS, 0), table.create(NPOSTS, 0) +for j = 3, NPOSTS do + local lo, hi = -1, 65536 + local x = POSTS[j] + for k = 1, j - 1 do + local xv = POSTS[k] + if xv > lo and xv < x then + LOW[j], lo = k, xv + end + if xv < hi and xv > x then + HIGH[j], hi = k, xv + end + end +end +-- the floor value (0..127) closest to an amplitude, through the spec's inverse dB table +local DB = table.create(RANGE, 0) +for y = 0, RANGE - 1 do + DB[y + 1] = 20 * math.log10(Tables[y * MULT + 1]) +end +local function yOf(db) +local y = floor((db - DB[1]) / (DB[RANGE] - DB[1]) * (RANGE - 1) + 0.5) + return math.clamp(y, 0, RANGE - 1) +end + +local function predict(x, x0, x1, y0, y1) +local dy = y1 - y0 + local adx = x1 - x0 + local off = math.floor((abs(dy) * (x - x0)) / adx +) return (dy < 0 and((y0 - off ))or((y0 + off +)))end + +-- render the decoder's floor curve for final Y values into F[1..N2] (only the posts the decoder marks used) +local function renderFloor(Y, used, F) + local lx, ly = 0, Y[1] * MULT + for q = 2, NPOSTS do +local __DARKLUA_CONTINUE_28=false repeat local j = SORTED[q] + if not used[j] then +__DARKLUA_CONTINUE_28=true break + end + local hx, hy = POSTS[j], Y[j] * MULT + -- draw_line(lx, ly, hx, hy) + local dy = hy - ly + local adx = hx - lx + local ady = abs(dy) + local base = (dy < 0 and{(-(math.floor(ady / adx)) )}or{(math.floor(ady / adx +))})[1] local sy = (dy < 0 and((base - 1 ))or((base + 1 +))) ady =ady- abs(base) * adx + local x, y, err = lx, ly, 0 + local x1 = math.min(hx, N2) + if x < x1 then + F[x + 1] = Tables[y % 256 + 1] + x =x+ 1 + while x < x1 do + err =err+ ady + if err >= adx then + err =err- adx + y =y+ sy + else + y =y+ base + end + F[x + 1] = Tables[y % 256 + 1] + x =x+ 1 + end + end + lx, ly = hx, hy +__DARKLUA_CONTINUE_28=true until true if not __DARKLUA_CONTINUE_28 then break end end + for x = lx + 1, N2 do + F[x] = Tables[ly % 256 + 1] + end +end + +-- the coded value for target t at post j given the final values of its neighbours (spec 7.2.4 step 1, inverted) +local function floorVal(Y, j) +local lo, hi = LOW[j], HIGH[j] + local pred = predict(POSTS[j], POSTS[lo], POSTS[hi], Y[lo], Y[hi]) + local t = Y[j] + local d = t - pred + if d == 0 then + return 0 + end + local highroom = RANGE - pred + local lowroom = pred + local room = (highroom < lowroom and((highroom * 2 ))or((lowroom * 2 +))) local cands = { (d > 0 and((2 * d ))or((-2 * d - 1))), d + lowroom, -d + highroom - 1 } + for _, v in __iter(cands) do + if v > 0 and v < RANGE then + local got + if v >= room then + got = (highroom > lowroom and((v - lowroom + pred ))or((pred - v + highroom - 1 +))) elseif v % 2 == 1 then + got = pred - math.floor((v + 1) / 2 +) else + got = pred + math.floor(v / 2 +) end + if got == t then + return v + end + end + end + return 0 -- unreachable for t in range; fall back to the prediction +end + +-- ------------------------------------------------------------------------------------------------ headers +local function identHeader(ch, rate, nominal) +local w = newW(64) + put(w, 1, 8) + putString(w, "vorbis") + put(w, 0, 32) + put(w, ch, 8) + put(w, rate, 32) + put(w, 0, 32) + put(w, nominal, 32) + put(w, 0, 32) + put(w, 8, 4) -- blocksize 0: 256 + put(w, 11, 4) -- blocksize 1: 2048 + put(w, 1, 1) + return finish(w) +end + +local function commentHeader(vendor, tags) +local w = newW(256) + put(w, 3, 8) + putString(w, "vorbis") + put(w, #vendor, 32) + putString(w, vendor) + local fields = VorbisComment.fields(tags) + put(w, #fields, 32) + for _, s in __iter(fields) do + put(w, #s, 32) + putString(w, s) + end + put(w, 1, 1) + return finish(w) +end + +local function setupHeader(ch) +local w = newW(8192) + put(w, 5, 8) + putString(w, "vorbis") + -- codebooks + put(w, #BOOKS - 1, 8) + for _, b in __iter(BOOKS) do + writeBook(w, b) + end + -- time domain placeholders + put(w, 0, 6) + put(w, 0, 16) + -- one floor 1 + put(w, 0, 6) + put(w, 1, 16) + put(w, FLOOR_PARTS, 5) + for _ = 1, FLOOR_PARTS do + put(w, 0, 4) -- class 0 + end + put(w, 3, 3) -- class 0: 4 dimensions + put(w, 0, 2) -- no subclasses + put(w, FLOOR_BOOK + 1, 8) -- its one subclass book (+1) + put(w, MULT - 1, 2) + put(w, 10, 4) -- rangebits: x in 0 .. 1024 + for j = 3, NPOSTS do + put(w, POSTS[j], 10) + end + -- one residue 2 + put(w, 0, 6) + put(w, 2, 16) + put(w, 0, 24) -- begin + put(w, N2 * ch, 24) -- end + put(w, PSIZE_PER_CHANNEL * ch - 1, 24) + put(w, NCLASS - 1, 6) + put(w, CLASS_BOOK, 8) + for c = 1, NCLASS do + local bits = 0 + for pass = 1, 3 do + if CLASS_BOOKS[c][pass] >= 0 then + bits =bits+ POW[pass] + end + end + put(w, bits % 8, 3) + if bits >= 8 then + put(w, 1, 1) + put(w, math.floor(bits / 8), 5) + else + put(w, 0, 1) + end + end + for c = 1, NCLASS do + for pass = 1, 3 do + local b = CLASS_BOOKS[c][pass] + if b >= 0 then + put(w, b, 8) + end + end + end + -- one mapping + put(w, 0, 6) + put(w, 0, 16) + put(w, 0, 1) -- one submap + if ch == 2 then + put(w, 1, 1) + put(w, 0, 8) -- one coupling step + put(w, 0, 1) -- magnitude: channel 0 + put(w, 1, 1) -- angle: channel 1 + else + put(w, 0, 1) + end + put(w, 0, 2) + put(w, 0, 8) -- submap 0: time (unused) + put(w, 0, 8) -- floor 0 + put(w, 0, 8) -- residue 0 + -- one mode: long blocks + put(w, 0, 6) + put(w, 1, 1) + put(w, 0, 16) + put(w, 0, 16) + put(w, 0, 8) + put(w, 1, 1) -- framing + return finish(w) +end +-- ------------------------------------------------------------------------------------------------ encoder +-- the residue of one partition: vectors of each pass for class c + + + + + + + + + + + + + + + +local function writePartition(w, v, o, psize, c, pass) + local b = CLASS_BOOKS[c][pass] + if b < 0 then + return + end + local book = BOOKS[b + 1] + local dims, h = book.dims, math.floor((book.values - 1) / 2 +) local scale = book.delta + local values = book.values + local i = 0 + while i < psize do + local e = 0 + local m = 1 + for k = 0, dims - 1 do + local x = v[o + i + k + 1] + -- the part of x this pass carries (coarse passes take the rounded multiple of their scale) + local q + if pass < 3 and CLASS_BOOKS[c][pass + 1] >= 0 then + q = math.clamp(floor(x / scale + 0.5), -h, h) + else + q = math.clamp(math.floor(x / scale), -h, h) + end + v[o + i + k + 1] = x - q * scale + e =e+ (q + h) * m + m =m* values + end + putEntry(w, book, e) + i =i+ dims + end +end + +function Encode.encode(src, opts) +local ch, rate = src.channels, src.sampleRate + local q = math.clamp(opts.quality, -1, 10) + local snrDb = 2 * q - 1 -- floor level below the band energy (at low frequencies; 8 dB less at the top) + local mux = Ogg.muxer({ pageSize = 4096 }) + local stream = mux:stream(opts.serial) + local nominal = floor(math.clamp(rate * ch * (0.6 + 0.12 * q), 32000, 500000)) + stream:packet(identHeader(ch, rate, nominal), 0, { flush = true }) + stream:packet(commentHeader(opts.vendor, src.tags), 0) + stream:packet(setupHeader(ch), 0, { flush = true }) + local plan = (Mdct.new(N) ) +local win = (Mdct.window("vorbis", N) ) -- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024) + +local frame= (table.create(ch) ) +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) ) +for c = 1, ch do + X[c] = table.create(N2, 0) + R[c] = table.create(N2, 0) + end + local F = table.create(N2, 0) + local Y = table.create(NPOSTS, 0) + local vals = table.create(NPOSTS, 0) + local used = table.create(NPOSTS, false) + local inter = table.create(N2 * ch, 0) + local psize = PSIZE_PER_CHANNEL * ch + local npart = math.floor(N2 * ch / psize +) local classes = table.create(npart + 2, 0) + local total = 0 + local srcDone = false + local tmp= nil + local pending= nil + local pendN, pendOff = 0, 0 + local k = 0 + local lastWanted = -1 -- the last packet index needed (known once the input ends) + while true do + -- shift in the next 1024 input samples (zeros past the end) + for c = 1, ch do + local fr = frame[c] + table.move(fr, N2 + 1, N, 1) + end + local got = 0 + while got < N2 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(N2 - got, pendN) + local pb = pending +for i = 0, take - 1 do + local base = (pendOff + i) * ch * 4 + for c = 1, ch do + frame[order[c] ][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4) + end + end + got =got+ take + pendN =pendN- take + pendOff =pendOff+ take + end + for c = 1, ch do + local fr = frame[c] + for i = N2 + got + 1, N do + fr[i] = 0 + end + end + total =total+ got + if srcDone and lastWanted < 0 then + lastWanted = math.floor((total + N2 - 1) / N2 -- packets 0 .. lastWanted (packet j returns [(j-1)*1024, j*1024)) +) end + -- this frame is centred on k*1024; its first half is [k*1024 - 1024, k*1024) + -- (frame k holds input [(k - 1) * 1024, (k + 1) * 1024): the shift above moved the window by 1024) + -- MDCT per channel + local energy = 0 + for c = 1, ch do + local fr = frame[c] + for i = 1, N do + blk[i] = fr[i] * win[i] + end + Mdct.forward(plan, blk, 1, X[c], 1, 1, 4 / N) + local xc = X[c] + for i = 1, N2 do + energy =energy+ xc[i] * xc[i] + end + end + local w = newW(2048) + put(w, 0, 1) -- audio packet + -- (one mode: 0 bits) long block, previous and next long + put(w, 1, 1) + put(w, 1, 1) + local silent = energy < 1e-18 + if silent then + for _ = 1, ch do + put(w, 0, 1) -- no floor: the channel is zero + end + else + -- the floor from the loudest channel's band energies at each post + for j = 1, NPOSTS do + local x = POSTS[j] + -- the band around x: halfway to the neighbouring posts in x order + local idx = (table.find(SORTED, j) ) +local lo = (idx > 1 and{(math.floor((POSTS[SORTED[idx - 1] ] + x) / 2 ))}or{0 +})[1] local hi = (idx < NPOSTS and{(math.floor((POSTS[SORTED[idx + 1] ] + x) / 2 ))}or{(N2 - 1 +)})[1] if hi < lo then + hi = lo + end + local e = 0 + for c = 1, ch do + local xc = X[c] + local s = 0 + for i = lo + 1, math.min(hi + 1, N2) do + s =s+ xc[i] * xc[i] + end + s =s/ (hi - lo + 1) + if s > e then + e = s + end + end + local db = (e > 0 and((10 * math.log10(e) - snrDb + 8 * x / N2 ))or((-200 +))) Y[j] = yOf(db) + end + -- the decoder's step 2 flags: a point is drawn when its value or a later neighbour's value is nonzero + used[1], used[2] = true, true + for j = 3, NPOSTS do + local v = floorVal(Y, j) + vals[j] = v + used[j] = v ~= 0 + if v ~= 0 then + used[LOW[j] ], used[HIGH[j] ] = true, true + end + end + renderFloor(Y, used, F) + -- residues: X / F rounded, then coupling, then interleaving + for c = 1, ch do + local xc, rc = X[c], R[c] + for i = 1, N2 do + local v = floor(xc[i] / F[i] + 0.5) + rc[i] = math.clamp(v, -4095, 4095) + end + end + if ch == 2 then + local l, r = R[1], R[2] + for i = 1, N2 do + local a, b = l[i], r[i] + local m, an + if abs(a) > abs(b) then + m = a + an = (a > 0 and((a - b ))or((b - a +))) else + m = b + an = (b > 0 and((a - b ))or((b - a +))) end + -- keep the angle inside the books' range + l[i], r[i] = m, math.clamp(an, -4095, 4095) + end + end + for c = 1, ch do + local rc = R[c] + for i = 1, N2 do + inter[(i - 1) * ch + c] = rc[i] + end + end + -- floors + for _ = 1, ch do + put(w, 1, 1) + put(w, Y[1], 7) + put(w, Y[2], 7) + for j = 3, NPOSTS do + putEntry(w, BOOK_FLOOR, vals[j]) + end + end + -- residue classes + for p = 0, npart - 1 do + local m = 0 + for i = 1, psize do + local a = abs(inter[p * psize + i]) + if a > m then + m = a + end + end + local c = 1 + while CLASS_MAX[c] < m do + c =c+ 1 + end + classes[p + 1] = c + end + classes[npart + 1] = 1 + for pass = 1, 3 do + for p = 0, npart - 1, 2 do + if pass == 1 then + putEntry(w, BOOK_CLASS, (classes[p + 1] - 1) * NCLASS + (classes[p + 2] - 1)) -- first partition: the high digit + end + writePartition(w, inter, p * psize, psize, classes[p + 1], pass) + if p + 1 < npart then + writePartition(w, inter, (p + 1) * psize, psize, classes[p + 2], pass) + end + end + end + end + local pk = finish(w) + local last = lastWanted >= 0 and k >= lastWanted + local granule = k == 0 and 0 or math.min(k * N2, (lastWanted >= 0 and{total }or{math.huge})[1]) + stream:packet(pk, granule, last and{ eos = true } or nil) + if last then + break + end + k =k+ 1 + end + if src.err then + return nil, tostring(src.err) + end + return mux:finish(), nil +end + +-- the codebooks (tests check the Huffman lengths are a valid prefix code) +Encode.BOOKS = BOOKS + +return Encode +end +__FILES["audio/wav"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!optimize 2 +-- audio/wav: WAVE in RIFF / RIFX (big-endian) / RF64 / BW64. Absorbed from wav-luau fd9a909 (same author, no +-- third-party code; the streaming decoder) on the shared containers/Riff, plus a new encoder. +-- Decode: PCM 8 / 16 / 24 / 32 bit, IEEE float 32 / 64, A-law, mu-law, IMA ADPCM, MS ADPCM, WAVE_FORMAT_EXTENSIBLE +-- wrapping any of them; odd-sized chunks with or without the pad byte; LIST/INFO tags; a data size of 0 or 0xFFFFFFFF +-- (streamed output) or past the end means "up to the end of the file" (a truncated file decodes what it has). +-- Encode: PCM u8 / s16 / s24 / s32 and float32 from an Audio or a streaming Decoder, WAVE_FORMAT_EXTENSIBLE when +-- there are more than 2 channels, more than 16 bits or over 48 kHz (as ffmpeg), fact for float, LIST/INFO tags, +-- RF64 (ds64) automatically past 4 GiB (Wav.encodeParts streams files over the 1 GiB buffer limit) or on request. +-- Not supported: encoding ADPCM / A-law / mu-law / f64, RIFX output. +-- +-- local dec = Wav.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(4096) -> f32 buffer, frames +-- local audio = Wav.decode(Bytes.reader(buf)) -- Types.Audio +-- local file = Wav.encode(audio, { sampleFormat = "s24" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Riff = __include("containers/Riff") +local Codecs = __include("audio/wav/Codecs") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Wav = { + name = "wav", + category = "audio", + extensions = { "wav", "wave", "rf64", "bw64" }, + mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + +Wav.FORMAT_PCM = 1 +Wav.FORMAT_MS_ADPCM = 2 +Wav.FORMAT_FLOAT = 3 +Wav.FORMAT_ALAW = 6 +Wav.FORMAT_MULAW = 7 +Wav.FORMAT_IMA_ADPCM = 0x11 +Wav.FORMAT_EXTENSIBLE = 0xFFFE + +local FORMAT_NAMES = { + [1] = "pcm", + [2] = "ms_adpcm", + [3] = "float", + [6] = "alaw", + [7] = "mulaw", + [0x11] = "ima_adpcm", +} + +-- LIST/INFO ids -> tag names +local INFO_TAGS = { + INAM = "title", + IART = "artist", + IPRD = "album", + ICMT = "comment", + ICRD = "date", + IGNR = "genre", + ITRK = "track", + IPRT = "track", + ISFT = "encoder", + ICOP = "copyright", + IENG = "engineer", + ISBJ = "subject", + IKEY = "keywords", +} + +-- A-law / mu-law -> f32 tables (G.711, as ffmpeg's alaw2linear / ulaw2linear) +local ALAW, MULAW = buffer.create(1024), buffer.create(1024) +do + for i = 0, 255 do + local a = bit32.bxor(i, 0x55) + local t = bit32.band(a, 15) + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg > 0 then + t = bit32.lshift(t * 2 + 1 + 32, seg + 2) + else + t = bit32.lshift(t * 2 + 1, 3) + end + if bit32.band(a, 0x80) == 0 then + t = -t + end + buffer.writef32(ALAW, i * 4, t / 32768) + local u = bit32.band(bit32.bnot(i), 255) + local m = bit32.lshift(bit32.lshift(bit32.band(u, 15), 3) + 0x84, bit32.rshift(bit32.band(u, 0x70), 4)) + local v = (bit32.band(u, 0x80) ~= 0 and((0x84 - m ))or((m - 0x84 +))) buffer.writef32(MULAW, i * 4, v / 32768) + end +end + +local Decoder = {} +Decoder.__index = Decoder + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function trimTag(s) -- strip trailing NULs / spaces + +local e = #s + while e > 0 do + local c = string.byte(s, e) + if c ~= 0 and c ~= 32 then + break + end + e =e- 1 + end + local z = string.find(s, "\0", 1, true) + if z and z <= e then + e = z - 1 + end + return string.sub(s, 1, e) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Wav.sniff(r) +return Riff.sniff(r) == "WAVE" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole file +function Wav.decode(r, opts) +local dec, err = Wav.open(r, opts) + if not dec then + return nil, err + end + return Pcm.drain(dec, { + format = "wav", + codec = dec.format, + bitDepth = dec.bitsPerSample, + container = dec.container, + channelMask = dec.channelMask, + truncated = dec.truncated, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +local SAMPLE_BYTES = { u8 = 1, s16 = 2, s24 = 3, s32 = 4, f32 = 4 } +-- ffmpeg's default speaker masks per channel count (av_channel_layout_default) +local MASKS = { [1] = 0x4, [2] = 0x3, [3] = 0xB, [4] = 0x107, [5] = 0x37, [6] = 0x3F, [7] = 0x70F, [8] = 0x63F } +local GUID_TAIL = "\0\0\0\0\16\0\128\0\0\170\0\56\155\113" -- KSDATAFORMAT_SUBTYPE_* after the 2-byte format tag +-- tags -> LIST/INFO ids (the first id per name) +local TAG_IDS = { title = "INAM", artist = "IART", album = "IPRD", comment = "ICMT", date = "ICRD", genre = "IGNR", track = "ITRK", encoder = "ISFT", copyright = "ICOP", engineer = "IENG", subject = "ISBJ", keywords = "IKEY" } +local BLOCK = 65536 -- frames per data piece when streaming a Decoder + +-- the body of the encoder: { buffer } pieces of the file | nil, Err +local function encodeParts(value, opts, asParts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs an Audio or a Decoder") + end + local o= opts or {} + local kind = o.sampleFormat or "s16" + local bytes= SAMPLE_BYTES[kind] + if not bytes then + return nil, Err.new(Err.ARG, "encode: sampleFormat must be u8, s16, s24, s32 or f32") + end + local rate, ch= value.sampleRate, value.channels + if type(rate) ~= "number" or rate < 1 or rate > 4294967295 or rate % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad sample rate") + end + if type(ch) ~= "number" or ch < 1 or ch > 65535 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: bad channel count") + end + local isAudio = type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "encode: needs an Audio (samples) or a Decoder (read)") + end + local frameBytes = bytes * ch + local pieces= {} + local frames= 0 + if isAudio then + frames = (value.frames ) or (math.floor(buffer.len(value.samples) / (ch * 4))) + if type(frames) ~= "number" or frames < 0 or buffer.len(value.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "encode: the samples buffer is shorter than frames * channels") + end + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + -- pieces of at most 256 MiB + local per = math.max(1, math.floor(0x10000000 / frameBytes)) + local f0 = 0 + while f0 < frames do + local n = math.min(per, frames - f0) + local b = buffer.create(n * frameBytes) + Codecs.quantize(value.samples, f0 * ch, b, 0, n * ch, kind) + table.insert(pieces, b) + f0 =f0+ n + end + else + local tmp = buffer.create(BLOCK * ch * 4) + while true do + local ok, out, n = pcall(value.read, value, BLOCK, tmp) + if not ok then + return nil, Err.new(Err.ARG, "encode: the decoder failed: " .. tostring(out)) + end + if type(n) ~= "number" or n <= 0 or type(out) ~= "buffer" then + break + end + n = math.min(n, math.floor(buffer.len(out) / (ch * 4))) + local b = buffer.create(n * frameBytes) + Codecs.quantize(out, 0, b, 0, n * ch, kind) + table.insert(pieces, b) + frames =frames+ n + if not asParts and frames * frameBytes > 0x3FFFFF00 then + return nil, Err.new(Err.LIMIT, "encode: over 1 GiB of samples (use Wav.encodeParts)") + end + end + end + local dataSize = frames * frameBytes + local bits = bytes * 8 + local float = kind == "f32" + local tag = float and 3 or 1 + local extensible = ch > 2 or rate > 48000 or (not float and bits > 16) + if o.extensible ~= nil then + extensible = o.extensible + end + local w = Riff.writer("WAVE", { rf64 = (o.rf64 ~= nil and{o.rf64 }or{"auto"})[1], sampleCount = frames, rf64Threshold = o.rf64Threshold }) + local fmt = Bytes.writer(40) + fmt:u16le(extensible and 0xFFFE or tag) + fmt:u16le(ch) + fmt:u32le(rate) + fmt:u32le(rate * frameBytes) + fmt:u16le(frameBytes) + fmt:u16le(bits) + if extensible then + fmt:u16le(22) + fmt:u16le(bits) + fmt:u32le(o.channelMask or MASKS[ch] or 0) + fmt:u16le(tag) + fmt:string(GUID_TAIL) + elseif float then + fmt:u16le(0) -- cbSize + end + w:chunk("fmt ", fmt:finish()) + if float then + local fact = Bytes.writer(4) + fact:u32le((w.rf64 == true or frames > 0xFFFFFFFF )and 0xFFFFFFFF or frames) -- RF64: in ds64 (as ffmpeg) + w:chunk("fact", fact:finish()) + end + local tags = o.tags or value.tags + if type(tags) == "table" then + local items = {} + local keys = {} + for k in __iter(tags) do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in __iter(keys) do + local v = tags[k] + -- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such + local id = TAG_IDS[k] or ((string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") and{(string.upper(k) )}or{nil})[1]) + if id and type(v) == "string" and v ~= "" then + table.insert(items, { id, v }) + end + end + if #items > 0 then + w:list("INFO", items) + end + end + w:chunk("data", pieces) + local _ = dataSize + return w:finish({ parts = asParts }) +end + +-- encode(audio or decoder, opts?) -> buffer | nil, Err +function Wav.encode(value, opts) +return encodeParts(value, opts, false) +end + +-- encodeParts(audio or decoder, opts?) -> { buffer } | nil, Err: the file as pieces to write one after the other +-- (header, sample blocks, ...), without the 1 GiB single-buffer limit; RF64 past 4 GiB +function Wav.encodeParts(value, opts) +return encodeParts(value, opts, true) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> Decoder | nil, Err: the streaming decoder (Types.Decoder) over the file in r's range +function Wav.open(r, _opts) +if type(r) == "buffer" or type(r) == "string" then + r = Bytes.reader((type(r) == "string" and{(buffer.fromstring(r) )}or{r })[1]) + end + local f, ferr = Riff.read(r, { openEnded = { data = true } }) + if not f then + return nil, ferr + end + if f.form ~= "WAVE" then + return nil, Err.new(Err.CORRUPT, "not a WAVE file (" .. f.form .. ")", f.base + 8) + end + local buf = f.buf + local magic = f.container + local be = f.bigEndian + + local fmt= nil + local tags= {} + local dataOff, dataSize = -1, 0 + local truncated = false + local ds64Frames= (f.ds64 and f.ds64.sampleCount > 0 and{f.ds64.sampleCount }or{nil +})[1] local factFrames= nil + local function u16(o) +return Riff.u16(f, o) + end + local function u32(o) +return Riff.u32(f, o) + end + local function i16(o) +local v = u16(o) + return (v >= 32768 and((v - 65536 ))or(v +)) end + for _, c in __iter(f.chunks) do + local id, size, body, avail = c.id, c.size, c.offset, c.avail + if id == "fmt " and avail >= 14 then + fmt = { + tag = u16(body), + channels = u16(body + 2), + rate = u32(body + 4), + byteRate = u32(body + 8), + blockAlign = u16(body + 12), + bits = (avail >= 16 and{(u16(body + 14) )}or{8})[1], + body = body, + avail = avail, + } + elseif id == "fact" and avail >= 4 then + factFrames = u32(body) + elseif id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, sc in __iter(Riff.list(f, c)) do + local name = INFO_TAGS[sc.id] + if sc.avail > 0 then + local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail)) + if v ~= "" then + tags[name or string.lower(sc.id)] = v + end + end + end + elseif id == "data" and dataOff < 0 then + dataOff = body + dataSize = avail + truncated = c.truncated + end + local _ = size + end + + if not fmt then + return nil, Err.new(Err.CORRUPT, "no fmt chunk") + end + if dataOff < 0 then + return nil, Err.new(Err.CORRUPT, "no data chunk") + end + local tag, ch, rate, bits = fmt.tag, fmt.channels, fmt.rate, fmt.bits + local channelMask= nil + local validBits= nil + if tag == 0xFFFE then + if fmt.avail < 40 then + return nil, Err.new(Err.CORRUPT, "WAVE_FORMAT_EXTENSIBLE without its extension") + end + local valid = u16(fmt.body + 18) + channelMask = u32(fmt.body + 20) + tag = u16(fmt.body + 24) -- the GUID's first two bytes are the format tag + -- valid bits < container bits: the samples are left-justified, so decoding the container is right + validBits = valid + end + if ch < 1 or ch > 255 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. ch) + end + if rate < 1 or rate > 4000000 then + return nil, Err.new(Err.CORRUPT, "bad sample rate " .. rate) + end + local name= FORMAT_NAMES[tag] + if not name then + return nil, Err.new(Err.UNSUPPORTED, string.format("format 0x%04X", tag)) + end + + local dec = (setmetatable({}, Decoder) ) +dec.sampleRate = rate + dec.channels = ch + dec.tags = tags + dec.format = name + dec.formatTag = tag + dec.bitsPerSample = bits + dec.container = magic + dec.dataOffset = dataOff + dec.dataSize = dataSize + dec.channelMask = channelMask + dec._buf = buf + dec._pos = 0 + dec._be = be + dec._tmp = buffer.create(8) + dec._cacheBlock = -1 + dec._cacheFrames = 0 + dec._ncoef = 0 + + local blockAlign= fmt.blockAlign + local frames +if name == "pcm" or name == "float" or name == "alaw" or name == "mulaw" then + local bytes + if name == "alaw" or name == "mulaw" then + bytes = 1 + elseif name == "float" then + if bits ~= 32 and bits ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, "float size " .. bits) + end + bytes = math.floor(bits / 8 +) else + if bits < 1 or bits > 32 then + return nil, Err.new(Err.UNSUPPORTED, "PCM size " .. bits) + end + -- container: from blockAlign when it is consistent, else from the bit depth + bytes = math.floor((bits + 7) / 8 +) if blockAlign >= ch and blockAlign % ch == 0 and math.floor(blockAlign / ch )>= bytes and math.floor(blockAlign / ch )<= 4 then + bytes = math.floor(blockAlign / ch +) end + end + blockAlign = bytes * ch + dec._bytes = bytes + dec._kind = name + frames = math.floor(dataSize / blockAlign +) dec._spb = 1 + elseif name == "ima_adpcm" or name == "ms_adpcm" then + if blockAlign < 1 then + return nil, Err.new(Err.CORRUPT, "ADPCM with blockAlign 0") + end + local spb = (fmt.avail >= 20 and{(u16(fmt.body + 18) )}or{0 +})[1] if name == "ima_adpcm" then + if bits ~= 4 then + return nil, Err.new(Err.UNSUPPORTED, "IMA ADPCM size " .. bits) + end + if blockAlign < 4 * ch then + return nil, Err.new(Err.CORRUPT, "IMA ADPCM block too small") + end + local computed = math.floor((blockAlign - 4 * ch) * 2 / ch )+ 1 + if spb < 1 or spb > computed then + spb = computed + end + else + if blockAlign < 7 * ch then + return nil, Err.new(Err.CORRUPT, "MS ADPCM block too small") + end + local computed = math.floor((blockAlign - 7 * ch) * 2 / ch )+ 2 + if spb < 2 or spb > computed then + spb = computed + end + -- coefficients from the fmt extension, else the 7 standard pairs + local c1, c2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local ncoef = 7 + if fmt.avail >= 22 then + local k = u16(fmt.body + 20) + if k >= 1 and k <= 256 and fmt.avail >= 22 + 4 * k then + ncoef = k + c1, c2 = {}, {} + for i = 1, k do + c1[i] = i16(fmt.body + 22 + (i - 1) * 4) + c2[i] = i16(fmt.body + 24 + (i - 1) * 4) + end + end + end + local coefs = buffer.create(ncoef * 8) + for i = 1, ncoef do + buffer.writei32(coefs, (i - 1) * 8, c1[i]) + buffer.writei32(coefs, (i - 1) * 8 + 4, c2[i]) + end + dec._coefs = coefs + dec._ncoef = ncoef + dec._state = buffer.create(20 * ch) + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + dec._kind = name + dec._spb = spb + dec._cache = buffer.create(spb * ch * 4) + local full = math.floor(dataSize / blockAlign +) frames = full * spb + local rest = dataSize - full * blockAlign + if rest > 0 then + -- a partial last block: the frames it holds whole + if name == "ima_adpcm" then + if rest >= 4 * ch then + frames =frames+ math.min(spb, 1 + (math.floor((rest - 4 * ch) / (4 * ch))) * 8) + end + elseif rest >= 7 * ch then + frames =frames+ math.min(spb, 2 + math.floor(((rest - 7 * ch) * 2) / ch)) + end + end + -- fact: the true length (the last block is padded) + if factFrames and factFrames > 0 and factFrames < frames then + frames = factFrames + end + else + return nil, Err.new(Err.UNSUPPORTED, "format " .. name) + end + if ds64Frames and ds64Frames > 0 and ds64Frames < frames then + frames = ds64Frames + end + dec.blockAlign = blockAlign + dec.frames = frames + dec.duration = frames / rate + dec.truncated = truncated + dec.validBits = validBits + dec.bitrate = (fmt.byteRate > 0 and((fmt.byteRate * 8 ))or((math.floor(rate * blockAlign * 8 / dec._spb) +))) return dec, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- Decodes up to maxFrames frames from the current position. Returns a buffer of interleaved f32 samples +-- (frames * channels values; `out` is reused when given and large enough) and the frame count (0 = end). +function Decoder.read(self, maxFrames, out) +local ch = self.channels + local req = math.floor(tonumber(maxFrames) or 0) + if req ~= req then -- NaN (math.min / max treat it differently on LuaJIT) + req = 0 + end + local want = math.max(0, math.min(req, self.frames - self._pos)) + local dst= (out and type(out) == "buffer" and buffer.len(out) >= want * ch * 4 +and{out +}or{(buffer.create(want * ch * 4) +)})[1] if want == 0 then + return dst, 0 + end + local kind = self._kind + if self._spb == 1 then + local off = self.dataOffset + self._pos * self.blockAlign + local count = want * ch + if kind == "pcm" then + Codecs.int(self._buf, off, dst, 0, count, self._bytes, self._be) + elseif kind == "float" then + Codecs.float(self._buf, off, dst, 0, count, self._bytes, self._be, self._tmp) + elseif kind == "alaw" then + Codecs.law(self._buf, off, dst, 0, count, ALAW) + else + Codecs.law(self._buf, off, dst, 0, count, MULAW) + end + self._pos =self._pos+ want + return dst, want + end + -- block formats: decode a block into the cache, copy out of it + local spb, ba = self._spb, self.blockAlign + local cache = self._cache +local done = 0 + while done < want do + local block = math.floor(self._pos / spb +) if block ~= self._cacheBlock then + local off = self.dataOffset + block * ba + local avail = math.min(ba, self.dataOffset + self.dataSize - off) + local got + if kind == "ima_adpcm" then + got = Adpcm.imaWav(self._buf, off, avail, ch, spb, cache, 0) + else + got = Adpcm.msBlock(self._buf, off, avail, ch, spb, cache, 0, self._coefs , self._ncoef, + self._state ) + end + self._cacheBlock = block + self._cacheFrames = got + end + local inBlock = self._pos - block * spb + local k = math.min(want - done, self._cacheFrames - inBlock) + if k <= 0 then + break + end + Codecs.copy(cache, inBlock * ch, dst, done * ch, k * ch) + done =done+ k + self._pos =self._pos+ k + end + return dst, done +end + +-- Moves to a time in seconds (clamped to the stream). +function Decoder.seek(self, seconds) + local f = math.floor((tonumber(seconds) or 0) * self.sampleRate + 0.5) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Moves to a frame index (clamped). +function Decoder.seekFrame(self, frame) + local f = math.floor(tonumber(frame) or 0) + if f ~= f then + f = 0 + end + self._pos = math.clamp(f, 0, self.frames) +end + +-- Current position in seconds. +function Decoder.position(self) +return self._pos / self.sampleRate +end + +-- Current position in frames. +function Decoder.tell(self) +return self._pos +end + +return Wav +end +__FILES["audio/wav/Codecs"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- audio/wav/Codecs: sample conversion loops (native) into interleaved f32, and back (the encoder's quantizers). The +-- ADPCM block decoders moved to codecs/audio/Adpcm. +-- Absorbed from wav-luau fd9a909 (same author); the encoder loops are new. They never throw: audio/wav (init.luau) +-- only calls them with ranges it has checked against the source length and the output size. +local readu8, readi8, readu16, readi16, readu32, readi32 = + buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, writef32, writeu32 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap +local writeu8, writeu16, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writei16, buffer.writei32 + +local Codecs = {} + +-- Integer PCM: count samples of `bytes` bytes each (1 = unsigned 8-bit, 2 / 3 / 4 = signed), little- or big-endian, +-- from src[off] to dst (f32) starting at sample index d. +function Codecs.int(src, off, dst, d, count, bytes, be) + local o = d * 4 + if bytes == 1 then + for i = 0, count - 1 do + writef32(dst, o + i * 4, (readu8(src, off + i) - 128) / 128) + end + elseif bytes == 2 then + if be then + for i = 0, count - 1 do + local s = off + i * 2 + local v = readi8(src, s) * 256 + readu8(src, s + 1) + writef32(dst, o + i * 4, v / 32768) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi16(src, off + i * 2) / 32768) + end + end + elseif bytes == 3 then + if be then + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s) * 65536 + readu8(src, s + 1) * 256 + readu8(src, s + 2) + writef32(dst, o + i * 4, v / 8388608) + end + else + for i = 0, count - 1 do + local s = off + i * 3 + local v = readi8(src, s + 2) * 65536 + readu16(src, s) + writef32(dst, o + i * 4, v / 8388608) + end + end + else + if be then + for i = 0, count - 1 do + local v = byteswap(readu32(src, off + i * 4)) + if v >= 0x80000000 then + v =v- 0x100000000 + end + writef32(dst, o + i * 4, v / 2147483648) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readi32(src, off + i * 4) / 2147483648) + end + end + end +end + +-- IEEE float, 4 or 8 bytes. tmp: an 8-byte scratch buffer for byte-swapping big-endian values. +function Codecs.float(src, off, dst, d, count, bytes, be, + tmp) + local o = d * 4 + if bytes == 4 then + if be then + for i = 0, count - 1 do + writeu32(tmp, 0, byteswap(readu32(src, off + i * 4))) + writef32(dst, o + i * 4, readf32(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(src, off + i * 4)) + end + end + else + if be then + for i = 0, count - 1 do + local s = off + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, s + 4))) + writeu32(tmp, 4, byteswap(readu32(src, s))) + writef32(dst, o + i * 4, readf64(tmp, 0)) + end + else + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf64(src, off + i * 8)) + end + end + end +end + +-- 8-bit companded (A-law / mu-law) through a 256-entry f32 table +function Codecs.law(src, off, dst, d, count, tbl) + local o = d * 4 + for i = 0, count - 1 do + writef32(dst, o + i * 4, readf32(tbl, readu8(src, off + i) * 4)) + end +end + +-- copy frames from a block cache into the output: count f32 values +function Codecs.copy(src, sOff, dst, dOff, count) + buffer.copy(dst, dOff * 4, src, sOff * 4, count * 4) +end + +-- Encoder: count f32 samples from src (sample index s) to dst[off] as `kind` ("u8", "s16", "s24", "s32", "f32"), +-- little-endian, rounding to nearest and clamping to the integer range. Ranges are checked by the caller. +function Codecs.quantize(src, s, dst, off, count, kind) + local so = s * 4 + if kind == "f32" then + buffer.copy(dst, off, src, so, count * 4) + elseif kind == "s16" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + writei16(dst, off + i * 2, v) + end + elseif kind == "s24" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 8388608 + 0.5) + if v > 8388607 then + v = 8388607 + elseif v < -8388608 then + v = -8388608 + elseif v ~= v then + v = 0 + end + if v < 0 then + v =v+ 16777216 + end + local o = off + i * 3 + writeu16(dst, o, v % 65536) + writeu8(dst, o + 2, math.floor(v / 65536)) + end + elseif kind == "s32" then + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 2147483648 + 0.5) + if v > 2147483647 then + v = 2147483647 + elseif v < -2147483648 then + v = -2147483648 + elseif v ~= v then + v = 0 + end + writei32(dst, off + i * 4, v) + end + else -- u8 + for i = 0, count - 1 do + local v = math.floor(readf32(src, so + i * 4) * 128 + 0.5) + if v > 127 then + v = 127 + elseif v < -128 then + v = -128 + elseif v ~= v then + v = 0 + end + writeu8(dst, off + i, v + 128) + end + end +end + +return Codecs +end +__FILES["audio/wavpack"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- audio/wavpack: WavPack (.wv) files: the block sequence around codecs/audio/WavPack, APEv2 tags, the .wvc correction +-- file of hybrid lossless files. Written from the WavPack 5 file format document (David Bryant) and the WavPack 5.9.0 +-- library's file handling (open_utils.c; BSD 3-clause, licenses/wavpack-LICENSE.txt). +-- Supports: lossless and hybrid streams, integer 8 - 32 bit and 32-bit float, 1 - 4096 channels (WAV order, as the +-- encoder stores them), non-standard sample rates, the correction file (opts.correction, else opts.resolve("<name>c") +-- on hosts with files) which makes a hybrid file lossless, garbage between blocks (resync), sample-accurate seeking +-- (every block is independent), APEv2 tags at the end (codecs/audio/ApeTag). Without a correction file a hybrid file +-- decodes lossy (as wvunpack does). Not supported: DSD (Err.UNSUPPORTED), WavPack 1 - 3 files, encoding. +-- +-- local dec = WavPack.open(Bytes.reader(buf)) -- Types.Decoder + bitsPerSample, float, hybrid, lossless, ... +-- local f32, n = dec:read(4096) +-- local i32, n = dec:readInt(4096) -- integer streams: the samples as wvunpack writes them +-- local audio = WavPack.decode(Bytes.reader(buf)) -- Types.Audio + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Stream = __include("codecs/audio/Stream") +local ApeTag = __include("codecs/audio/ApeTag") +local WavPackCodec = __include("codecs/audio/WavPack") + +-- ------------------------------------------------------------------------------------------------ contract +local WavPack = { + name = "wavpack", + category = "audio", + extensions = { "wv" }, + mime = { "audio/x-wavpack", "audio/wavpack" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Stream", "codecs/audio/ApeTag", "codecs/audio/WavPack" }, + caps = { decode = true, encode = false, streaming = true, seek = true, lossless = true, hybrid = true, float = true, depths = { 8, 12, 16, 20, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function WavPack.sniff(r) +if r:peek(4) ~= "wvpk" then + return 0 + end + local v = r:peekU8(9) + return v == 4 and 1 or 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Audio | nil, Err: the whole stream +function WavPack.decode(r, opts) +local dec, err = WavPack.open(r, opts) + if not dec then + return nil, err + end + local d = dec +local limit = opts and opts.maxFrames or 2 ^ 28 + 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 + return Pcm.drain(d, d.source, limit) +end +-- ------------------------------------------------------------------------------------------------ open +-- index(buf, base, limit) -> the frames (block offsets per frame) of a .wv / .wvc block sequence + + + +local function index(buf, base, limit) +local at = base + local idx= { offsets = {}, starts = {}, samples = {}, total = -1, first = -1 } + local cur= nil + local initial = -1 + local resyncs = 0 + while at + 32 <= limit do +local __DARKLUA_CONTINUE_1=false repeat local h = WavPackCodec.header(buf, at, limit) + if not h then + -- garbage (or a tag) between blocks: search the next header + if resyncs > 64 then + break + end + local s = buffer.readstring(buf, at + 1, math.min(limit - at - 1, 1048576)) + local k = string.find(s, "wvpk", 1, true) + if not k then + break + end + at = at + k + resyncs =resyncs+ 1 +__DARKLUA_CONTINUE_1=true break + end + if initial < 0 then + initial = h.index + idx.total = h.total + end + if h.samples > 0 then + if bit32.band(h.flags, WavPackCodec.INITIAL) ~= 0 or not cur then + cur = { at } + table.insert(idx.offsets, cur) + table.insert(idx.starts, h.index - initial) + table.insert(idx.samples, h.samples) + if idx.first < 0 then + idx.first = at + end + else + table.insert(cur, at) + end + if bit32.band(h.flags, WavPackCodec.FINAL) ~= 0 then + cur = nil + end + else + idx.md5 = idx.md5 or WavPackCodec.md5(buf, at, limit) + end + at =at+ h.size +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + if idx.first < 0 then + return nil, "no audio blocks" + end + return idx, nil +end + +local function correctionFile(opts) +if not opts then + return nil + end + local c = opts.correction + if type(c) == "string" then + return buffer.fromstring(c) + elseif type(c) == "buffer" then + return c + end + if type(opts.resolve) == "function" and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") + if base then + local ok, b = pcall(opts.resolve, base .. "c") + if ok and type(b) == "buffer" then + return b + end + end + end + return nil +end + +-- open(r, opts?) -> Decoder | nil, Err +function WavPack.open(r, opts) +if type(r) == "buffer" then + r = Bytes.reader(r ) + end + if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "open: expected a Reader") + end + local buf, base, limit = r.buf, r.base, r.limit + local tags, tagInfo = ApeTag.find(buf, base, limit) + local stop = (tagInfo and{tagInfo.start }or{limit +})[1] local idx, ierr = index(buf, base, stop) + if not idx then + return nil, Err.from(ierr, base) + end + local info, err = WavPackCodec.info(buf, idx.first, stop) + if not info then + return nil, err + end + if info.channels > 256 then + return nil, Err.new(Err.LIMIT, info.channels .. " channels") + end + local count = #idx.offsets + local last = idx.starts[count] + idx.samples[count] + local frames = (idx.total >= 0 and{(math.min(idx.total, last) )}or{last +})[1] -- the correction file: its frames by start sample + local cbuf = (info.hybrid and{(correctionFile(opts) )}or{nil +})[1] local cfor= {} + if cbuf then + local cidx = index(cbuf, 0, buffer.len(cbuf)) + if cidx then + for i, offs in __iter(cidx.offsets) do + cfor[cidx.starts[i] ] = offs + end + else + cbuf = nil + end + end + local codec = WavPackCodec.decoder(info.channels) + local dec= { + sampleRate = info.sampleRate, + channels = info.channels, + frames = frames, + duration = frames / info.sampleRate, + bitrate = (frames > 0 and{(math.floor((stop - base) * 8 * info.sampleRate / frames) )}or{0})[1], + tags = tags or {}, + bitsPerSample = info.bitsPerSample, + float = info.float, + hybrid = info.hybrid, + lossless = not info.hybrid or cbuf ~= nil, + channelMask = info.channelMask, + md5 = idx.md5, + source = { format = "wavpack", bitDepth = info.bitsPerSample, float = info.float, hybrid = info.hybrid, correction = cbuf ~= nil, version = info.version, tags = tagInfo and tagInfo.items }, + } + local starts, offsets = idx.starts, idx.offsets + return Stream.packets(dec, { + count = count, + start = function(i) +return (i > count and{last }or{starts[i] +})[1] end, + decode = function(i) +local co = (cbuf and{cfor[starts[i] ] }or{nil +})[1] return codec:frame(buf, offsets[i], (co and{cbuf }or{nil})[1], co) + end, + pcm = function() +return codec.pcm + end, + reset = function() end, + stop = frames, + scale = info.float and 1 or 1 / 2 ^ (info.bytesPerSample * 8 - 1), + ints = not info.float, + }) +end + +return WavPack +end +__FILES["cad/step"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). +-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / +-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and +-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; +-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to +-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, +-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / +-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same +-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). +-- +-- B-rep bodies and tessellation come from an injected kernel, never required by rosetta: +-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, +-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } +-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } +-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / +-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / +-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, +-- millimetres (meta.unit = 0.001). +-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), +-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("cad/step/Parse") +local Write = __include("cad/step/Write") +local Brep = __include("cad/step/Brep") + +-- ------------------------------------------------------------------------------------------------ contract +local Step = { + name = "step", + category = "cad", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + +Step.NULL = table.freeze({ null = true }) -- $ +Step.DERIVED = table.freeze({ derived = true }) -- * + +local SCHEMAS = { + AP203 = "CONFIG_CONTROL_DESIGN", + AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", + AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", +} +Step.SCHEMAS = SCHEMAS + +-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself +local function schemaOf(name) +local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) + if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then + return "AP203" + elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then + return "AP214" + elseif string.find(n, "^AP242") then + return "AP242" + end + return n +end +Step.schemaOf = schemaOf + +-- ------------------------------------------------------------------------------------------------ sniff +function Step.sniff(r) +local head = Sniff.text(r, 256) + head = string.gsub(head, "^%s*/%*.-%*/", "") + if string.find(head, "^%s*ISO%-10303%-21%s*;") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Step.decode(r, opts) +local size = r.limit - r.base + if size > (opts and opts.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "file over maxBytes") + end + local s = buffer.readstring(r.buf, r.base, size) + local bom = 0 + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + bom = 3 + end + local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) + if not res then + local off = (at and((r.base + bom + at - 1 ))or(nil +)) if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) + end + local m = msg or "parse error" + if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then + return nil, Err.new(Err.TRUNCATED, m, off) + end + return nil, Err.new(Err.CORRUPT, m, off) + end + local fs = res.header.FILE_SCHEMA + local schemaName = (fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" and{fs[1][1] }or{"" +})[1] local cad= { + kind = "cad", + schema = (schemaName ~= "" and{(schemaOf(schemaName) )}or{"unknown"})[1], + header = res.header, + entities = res.entities, + meta = { + count = res.count, + headerOrder = res.headerOrder, + source = { + format = "step", + schemaName = schemaName, + sections = res.sections, + extra = (#res.extra > 0 and{res.extra }or{nil})[1], + duplicates = (res.duplicates > 0 and{res.duplicates }or{nil})[1], + terminated = res.terminated, + }, + }, + } + return cad, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function headerArgs(cad, o) +local h = (type(cad.header) == "table" and{cad.header }or{{} +})[1] local out= {} + for k, v in __iter(h) do + out[k] = v + end + if type(out.FILE_DESCRIPTION) ~= "table" then + out.FILE_DESCRIPTION = { { "rosetta" }, "2;1" } + end + if type(out.FILE_NAME) ~= "table" then + out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "rosetta", "rosetta", "" } + end + local schema = o.schema or ((type(out.FILE_SCHEMA) ~= "table" and{cad.schema }or{nil})[1]) + if schema then + out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } + end + return out +end + +function Step.encode(cad, opts) +if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") + end + local o= opts or {} + local nl = o.crlf and"\r\n" or"\n" + local ctx= { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } + local out = ctx.out + table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) + local header = headerArgs(cad, o) + local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } + local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } + local meta= (type(cad.meta) == "table" and{cad.meta }or{{} +})[1] local rest = {} + for _, k in __iter(((type(meta.headerOrder) == "table" and{meta.headerOrder }or{{}})[1])) do + if type(k) == "string" and header[k] and not seen[k] then + seen[k] = true + table.insert(order, k) + end + end + for k in __iter(header) do + if type(k) == "string" and not seen[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in __iter(rest) do + table.insert(order, k) + end + for _, k in __iter(order) do + if not Write.record(ctx, k, header[k]) then + return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + table.insert(out, "ENDSEC;" .. nl) + local source = (type(meta.source) == "table" and{meta.source }or{{} +})[1] if type(source.extra) == "table" then + for _, x in __iter(source.extra) do + if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then + table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) + end + end + end + -- entities by section, in id order + local ids = {} + for id, e in __iter(cad.entities) do + if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then + return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") + end + table.insert(ids, id) + end + table.sort(ids) + local sections = (type(source.sections) == "table" and #source.sections > 1 and{source.sections }or{{ {} } +})[1] for si, sec in __iter(sections) do + if #sections > 1 then + table.insert(out, "DATA") + local params = {} + if sec.name ~= nil then + params[1] = sec.name + params[2] = (sec.schema ~= nil and{sec.schema }or{{} +})[1] if not Write.list(ctx, params, 0) then + return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) + end + end + table.insert(out, ";" .. nl) + else + table.insert(out, "DATA;" .. nl) + end + for _, id in __iter(ids) do + local e= cad.entities[id] + local esec = (type(e.section) == "number" and{e.section }or{1 +})[1] if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then + table.insert(out, string.format("#%.0f=", id)) + if e.type == "COMPLEX" or type(e.parts) == "table" then + if type(e.parts) ~= "table" or #e.parts == 0 then + return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") + end + table.insert(out, "(") + for _, p in __iter(e.parts) do + if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) + end + end + table.insert(out, ")") + elseif not Write.record(ctx, e.type, e.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + end + table.insert(out, "ENDSEC;" .. nl) + end + table.insert(out, "END-ISO-10303-21;" .. nl) + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- get(cad, id | { ref = id }) -> the entity +function Step.get(cad, id) +if type(id) == "table" then + id = id.ref + end + return cad.entities[id] +end + +-- ids(cad) -> the instance ids in ascending order +function Step.ids(cad) +local out = {} + for id in __iter(cad.entities) do + table.insert(out, id) + end + table.sort(out) + return out +end + +-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending +function Step.byType(cad, name) +local n = string.upper(name) + local out = {} + for id, e in __iter(cad.entities) do + if e.type == n then + table.insert(out, id) + elseif e.parts then + for _, p in __iter(e.parts) do + if p.type == n then + table.insert(out, id) + break + end + end + end + end + table.sort(out) + return out +end + +-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) +function Step.part(e, name) +if not e then + return nil + end + if e.type == name then + return e.args + end + if e.parts then + for _, p in __iter(e.parts) do + if p.type == name then + return p.args + end + end + end + return nil +end + +-- add(cad, type, args) -> id: a new instance after the highest id +function Step.add(cad, type, args) +local top = 0 + for id in __iter(cad.entities) do + if id > top then + top = id + end + end + local id = top + 1 + cad.entities[id] = { id = id, type = string.upper(type), args = args } + cad.meta.count = (cad.meta.count or 0) + 1 + return id +end + +-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) +function Step.real(t, key) +local mt= getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true + return t +end + +-- new(schema?) -> an empty Cad ("AP214" by default) +function Step.new(schema) +return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } +end + +-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason +Step.plugin = Brep.plugin + +local function textOf(cad) +local buf, err = Step.encode(cad) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err +function Step.toBodies(cad, opts) +local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = textOf(cad) + if not text then + return nil, err + end + local bodies, res, rerr = Brep.read(plug, text, opts) + if not bodies then + return nil, rerr + end + return bodies, res +end + +-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err +function Step.fromBodies(bodies, opts) +if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a list of bodies") + end + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = Brep.write(plug, bodies, opts) + if not text then + return nil, err + end + return Step.decode(Bytes.reader(buffer.fromstring(text))) +end + +-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err +function Step.tessellate(value, opts) +local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local bodies = value + if type(value) == "table" and value.kind == "cad" then + local b, err = Step.toBodies(value, opts) + if not b then + return nil, err + end + bodies = b + end + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") + end + return Brep.scene(plug, bodies, opts) +end + +return Step +end +__FILES["cad/step/Brep"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- cad/step/Brep: the injected B-rep plug-in (Rosetta.plugins.brep; rosetta never requires a kernel). Normalises +-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a +-- Scene. Interpreted on purpose: the plug-in's errors unwind through here. +-- +-- The interface (every function may throw; results are checked): +-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, +-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) +-- write(bodies: { Body }, opts) -> string bodies -> STEP text +-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based +-- triples }, faceOf = { [triangle] = Face (face.color?) }? } +-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = +-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +local Err = __include("core/Err") +local Types = __include("Types") + +local Brep = {} + + + + + + + +local function rgbOf(c) +if c == nil then + return nil, nil, nil + end + local ok, r, g, b = pcall(function() +if type(c) == "table" then + return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] + end + return (c ).R, (c ).G, (c ).B -- Color3 + end) + if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then + return r, g, b + end + return nil, nil, nil +end + +-- plugin(p) -> the normalised interface, or nil + the reason +function Brep.plugin(p) +if type(p) ~= "table" then + return nil, "needs the B-rep plug-in (Rosetta.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" + end + if type(p.read) == "function" then + return { + read = p.read, + write = (type(p.write) == "function" and{p.write }or{nil})[1], + tessellate = (type(p.tessellate) == "function" and{p.tessellate }or{nil})[1], + }, nil + end + local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess + if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then + return { + read = function(text, opts) +return SB.read(S.parse(text), opts) + end, + write = type(SW) == "table" and type(SW.write) == "function" +and function(bodies, opts) +local o = (type(opts) == "table" and{(table.clone(opts) )}or{{} +})[1] if o.colors == nil then + local colors = {} + for i, b in __iter(bodies) do + local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) + if r then + colors[i] = { r, g, bl } + end + end + o.colors = colors + end + return SW.write(bodies, o) + end +or nil, + tessellate = type(Tess) == "table" and type(Tess.body) == "function" +and function(body, opts) +return Tess.body(body, opts) + end +or nil, + }, nil + end + return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" +end + +-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep +function Brep.find(opts) +local p = nil + if type(opts) == "table" then + p = opts.brep + if p == nil and type(opts.plugins) == "table" then + p = opts.plugins.brep + end + end + local plug, why = Brep.plugin(p) + if not plug then + return nil, Err.new(Err.UNSUPPORTED, why ) + end + return plug, nil +end + +-- read(plug, text, opts) -> bodies, result | nil, Err +function Brep.read(plug, text, opts) +local ok, res = pcall(plug.read, text, opts) + if not ok then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) + end + if type(res) ~= "table" or type(res.bodies) ~= "table" then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") + end + return res.bodies, res, nil +end + +-- write(plug, bodies, opts) -> text | nil, Err +function Brep.write(plug, bodies, opts) +local w = plug.write + if not w then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") + end + local ok, res = pcall(w, bodies, opts) + if not ok then + return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) + end + if type(res) ~= "string" then + return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") + end + return res, nil +end + +local function xyz(p) +if type(p) == "table" then + return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 + end + return (p ).X, (p ).Y, (p ).Z -- vector / Vector3 +end + +local function linear(c) +c = math.clamp(c, 0, 1) + return (c <= 0.04045 and((c / 12.92 ))or((((c + 0.055) / 1.055) ^ 2.4 +)))end + +-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by +-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +function Brep.scene(plug, bodies, opts) +local tess = plug.tessellate + if not tess then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") + end + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.001 + local tessOpts = (type(opts) == "table" and type(opts.tess) == "table" +and{opts.tess +}or{{ chord = (type(opts) == "table" and type(opts.chord) == "number" and{opts.chord }or{0.05 })[1]} +})[1] local matByKey= {} + local function material(r, g, b) +local key = (r and{(string.format("%.6f,%.6f,%.6f", r, g , b ) )}or{"default" +})[1] local m = matByKey[key] + if m then + return m + end + local mat = Types.Scene.material((r and(("step_" .. #scene.materials + 1 ))or("default"))) + if r then + mat.baseColor = { linear(r), linear(g ), linear(b ), 1 } + mat.extras = { color = { r, g, b } } + else + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + end + mat.metallic, mat.roughness = 0, 0.5 + table.insert(scene.materials, mat) + matByKey[key] = #scene.materials + return #scene.materials + end + for bi, body in __iter(bodies) do + local ok, mesh = pcall(tess, body, tessOpts) + if not ok then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) + end + if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") + end + local cok, prims = pcall(function() +local P, N, I = mesh.positions, mesh.normals, mesh.indices + local nv = #P + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + local nrm = (type(N) == "table" and #N == nv and{(Types.Scene.accessor(nil, "f32", 3, nv) )}or{nil +})[1] for i = 1, nv do + local x, y, z = xyz(P[i]) + buffer.writef32(pos.data, (i - 1) * 12, x) + buffer.writef32(pos.data, (i - 1) * 12 + 4, y) + buffer.writef32(pos.data, (i - 1) * 12 + 8, z) + if nrm then + local a, b, c = xyz(N[i]) + buffer.writef32(nrm.data, (i - 1) * 12, a) + buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) + buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) + end + end + local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) + -- triangles grouped by colour, in first-seen order + local groups= {} + local byMat= {} + local faceOf = (type(mesh.faceOf) == "table" and{mesh.faceOf }or{{} +})[1] local nt = math.floor(#I / 3 +) for t = 1, nt do + local f = faceOf[t] + local r, g, b = rgbOf(type(f) == "table" and f.color or nil) + if not r then + r, g, b = br, bg, bb + end + local m = material(r, g, b) + local grp = byMat[m] + if not grp then + grp = { mat = m, tris = {} } + byMat[m] = grp + table.insert(groups, grp) + end + table.insert(grp.tris, t) + end + local out= {} + for _, grp in __iter(groups) do + local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) + for k, t in __iter(grp.tris) do + for c = 0, 2 do + local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 + buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) + end + end + local attrs= { POSITION = pos } + if nrm then + attrs.NORMAL = nrm + end + table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" , material = grp.mat }) + end + return out + end) + if not cok then + return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) + end + local name = (type(body) == "table" and type(body.name) == "string" and{body.name }or{("body_" .. bi +)})[1] table.insert(scene.meshes, { name = name, primitives = prims }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } + return scene, nil +end + +return Brep +end +__FILES["cad/step/Parse"] = function() +local __compat = __compat local type = __compat.type --!strict +--!native +-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass +-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), +-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every +-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, +-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. +-- +-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; +-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) +-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so +-- the writer prints it back as a real; integral numbers without that mark are written as integers. +local Parse = {} + +local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor + +local MAX_DEPTH = 100 + + + + + + + + + + +local function fail(ctx, msg, at) +if not ctx.err then + ctx.err, ctx.errAt = msg, at + end + return nil +end + +-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) +local function skip(ctx, i) +local s, n = ctx.s, ctx.n + while i <= n do + local c = sbyte(s, i) + if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then + i =i+ 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, e = sfind(s, "*/", i + 2, true) + if not e then + fail(ctx, "unterminated comment", i) + return n + 1 + end + i = e + 1 + else + return i + end + end + return i +end + +local function isAlpha(c) +return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end +local function isWord(c) +return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) +end + +-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none +local function keyword(ctx, i) +local s, n = ctx.s, ctx.n + local j = i + if j <= n and sbyte(s, j) == 33 then -- '!' user-defined + j =j+ 1 + end + if j > n or not isAlpha((sbyte(s, j) )) then + return nil, i + end + j =j+ 1 + while j <= n and isWord((sbyte(s, j) )) do + j =j+ 1 + end + return string.upper(ssub(s, i, j - 1)), j +end + +-- UTF-8 of a code point +local function utf8char(cp) +if cp < 0x80 then + return schar(cp) + elseif cp < 0x800 then + return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) + elseif cp < 0x10000 then + return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + elseif cp < 0x110000 then + return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + end + return "\239\191\189" +end +Parse.utf8char = utf8char + +local function hexAt(s, i, k) +local h = ssub(s, i, i + k - 1) + if #h ~= k or sfind(h, "[^%x]") then + return nil + end + return tonumber(h, 16) +end + +-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, +-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) +-- pass through. +function Parse.unescape(raw) +if not sfind(raw, "[\\']") then + return raw + end + local out = {} + local i, n = 1, #raw + local plain = 1 + while i <= n do + local c = sbyte(raw, i) + if c == 39 then -- '' -> ' + table.insert(out, ssub(raw, plain, i)) + i =i+ 2 + plain = i + elseif c == 92 then + table.insert(out, ssub(raw, plain, i - 1)) + local d = sbyte(raw, i + 1) + if d == 92 then + table.insert(out, "\\") + i =i+ 2 + elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c + table.insert(out, utf8char((((sbyte(raw, i + 3) )) + 128) % 256)) + i =i+ 4 + elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page + i =i+ 4 + elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh + local h = hexAt(raw, i + 3, 2) + if h then + table.insert(out, utf8char(h)) + i =i+ 5 + else + table.insert(out, "\\") + i =i+ 1 + end + elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then + local k = sbyte(raw, i + 2) == 50 and 4 or 8 + local j = i + 4 + local hi= nil + while j <= n do + if sbyte(raw, j) == 92 then + break + end + local cp = hexAt(raw, j, k) + if not cp then + break + end + if k == 4 and cp >= 0xD800 and cp < 0xDC00 then + hi = cp + elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then + table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) + hi = nil + else + table.insert(out, utf8char(cp)) + hi = nil + end + j =j+ k + end + if ssub(raw, j, j + 3) == "\\X0\\" then + j =j+ 4 + end + i = j + else + table.insert(out, "\\") + i =i+ 1 + end + plain = i + else + i =i+ 1 + end + end + table.insert(out, ssub(raw, plain, n)) + return table.concat(out) +end + +local function markReal(t, key) + local mt= getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true +end + +-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) +local value + +local function list(ctx, i, depth) -- i is just past "(" + +local s = ctx.s + local out = {} + i = skip(ctx, i) + if sbyte(s, i) == 41 then + return out, i + 1 + end + local k = 0 + while true do + local v, j, intReal = value(ctx, i, depth + 1) + if v == nil then + return nil, j + end + k =k+ 1 + out[k] = v + if intReal then + markReal(out, k) + end + j = skip(ctx, j) + local c = sbyte(s, j) + if c == 44 then + i = skip(ctx, j + 1) + elseif c == 41 then + return out, j + 1 + elseif c == nil then + return fail(ctx, "truncated list", j), j + else + return fail(ctx, "expected , or ) in a list", j), j + end + end +end +Parse.list = list + +value = function(ctx, i, depth) +if depth > MAX_DEPTH then + return fail(ctx, "lists nested too deeply", i), i, false + end + local s = ctx.s + i = skip(ctx, i) + local c = sbyte(s, i) + if c == nil then + return fail(ctx, "truncated parameter", i), i, false + elseif c == 35 then -- #ref + local _, e = sfind(s, "^%d+", i + 1) + if not e then + return fail(ctx, "bad entity reference", i), i, false + end + return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false + elseif c == 39 then -- 'string' + local j = i + 1 + while true do + local q = sfind(s, "'", j, true) + if not q then + return fail(ctx, "unterminated string", i), i, false + end + if sbyte(s, q + 1) == 39 then + j = q + 2 + else + return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false + end + end + elseif c == 36 then + return ctx.null, i + 1, false + elseif c == 42 then + return ctx.derived, i + 1, false + elseif c == 40 then + local l, j = list(ctx, i + 1, depth) + return l, j, false + elseif c == 46 then -- .ENUM. + local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) + if not e then + return fail(ctx, "bad enumeration", i), i, false + end + return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif c == 34 then -- "binary" + local _, e = sfind(s, "^[0-3]%x*\"", i + 1) + if not e then + return fail(ctx, "bad binary literal", i), i, false + end + return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then + local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) + local tok = ssub(s, i, e ) + local num = tonumber((c == 43 and{(ssub(tok, 2) )}or{tok})[1]) + if num == nil then + -- "1.E" without digits and the like + local core = string.match(tok, "^[+-]?%d*%.?%d*") + num = core and tonumber((c == 43 and{(ssub(core, 2) )}or{core})[1]) + if num == nil then + return fail(ctx, "bad number", i), i, false + end + e = i + #(core ) - 1 + end + local real = sfind(tok, "[.eE]") ~= nil + local nv = num +return nv, (e ) + 1, real and nv == floor(nv) and nv == nv + elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) + local word, j = keyword(ctx, i) + j = skip(ctx, j) + if word == nil or sbyte(s, j) ~= 40 then + return fail(ctx, "expected a parameter", i), i, false + end + local v, k, intReal = value(ctx, j + 1, depth + 1) + if v == nil then + return nil, k, false + end + k = skip(ctx, k) + if sbyte(s, k) ~= 41 then + return fail(ctx, "expected ) after a typed parameter", k), k, false + end + local t = { typed = word, value = v } + if intReal then + markReal(t, "value") + end + return t, k + 1, false + end + return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false +end +Parse.value = value + +-- the simple record at i: NAME(params) -> type, args, next +local function record(ctx, i) +local word, j = keyword(ctx, i) + if not word then + return fail(ctx, "expected an entity name", i), nil, i + end + j = skip(ctx, j) + if sbyte(ctx.s, j) ~= 40 then + return fail(ctx, "expected ( after " .. word, j), nil, j + end + local args, k = list(ctx, j + 1, 0) + if not args then + return nil, nil, k + end + return word, args, k +end + +-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil +local function expect(ctx, i, ch, what) +i = skip(ctx, i) + if sbyte(ctx.s, i) ~= ch then + if i > ctx.n then + return fail(ctx, "truncated: expected " .. what, i) + end + return fail(ctx, "expected " .. what, i) + end + return i + 1 +end + +local function at(s, i, word) +return ssub(s, i, i + #word - 1) == word +end + +-- parse(s, opts) -> Result | nil, message, offset (1-based position in s) + + + + + + + + + + + +function Parse.parse(s, null, derived, maxEntities) +local ctx= { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } + local res= { + header = {}, + headerOrder = {}, + entities = {}, + count = 0, + sections = {}, + extra = {}, + duplicates = 0, + terminated = false, + } + local i = skip(ctx, 1) + if not at(s, i, "ISO-10303-21") then + return nil, "no ISO-10303-21 magic", i + end + local ni = expect(ctx, i + 12, 59, ";") + if not ni then + return nil, ctx.err, ctx.errAt + end + i = ni + local sawData = false + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + if i > ctx.n then + if not sawData then + return nil, "truncated: no DATA section", i + end + break + end + if at(s, i, "END-ISO-10303-21") then + res.terminated = true + local e = expect(ctx, i + 16, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + break + end + local word, j = keyword(ctx, i) + if word == "HEADER" then + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + if i > ctx.n then + return nil, "truncated header", i + end + local t, args, k = record(ctx, i) + if not t then + return nil, ctx.err, ctx.errAt + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if res.header[t] == nil then + table.insert(res.headerOrder, t) + end + res.header[t] = args +i = e2 + end + elseif word == "DATA" then + sawData = true + local sec= {} + j = skip(ctx, j) + if sbyte(s, j) == 40 then + local params, k = list(ctx, j + 1, 0) + if not params then + return nil, ctx.err, ctx.errAt + end + sec.name, sec.schema = params[1], params[2] + j = k + end + table.insert(res.sections, sec) + local secIndex = #res.sections + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + local c = sbyte(s, i) + if c == nil then + return nil, "truncated: the DATA section has no ENDSEC", i + end + if c ~= 35 then + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + return nil, "expected an entity instance (#id = ...)", i + end + local _, idEnd = sfind(s, "^%d+", i + 1) + if not idEnd then + return nil, "bad entity instance name", i + end + local id = (tonumber(ssub(s, i + 1, idEnd)) ) +local k = expect(ctx, idEnd + 1, 61, "=") + if not k then + return nil, ctx.err, ctx.errAt + end + k = skip(ctx, k) + local ent +if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) + local parts = {} + k = skip(ctx, k + 1) + while sbyte(s, k) ~= 41 do + if k > ctx.n then + return nil, "truncated complex instance", k + end + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + table.insert(parts, { type = t, args = args }) + k = skip(ctx, k2) + end + if #parts == 0 then + return nil, "empty complex instance", k + end + ent = { id = id, type = "COMPLEX", args = {}, parts = parts } + k =k+ 1 + else + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + ent = { id = id, type = t, args = args } + k = k2 + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if secIndex > 1 then + ent.section = secIndex + end + if res.entities[id] then + res.duplicates =res.duplicates+ 1 + else + res.count =res.count+ 1 + if res.count > maxEntities then + return nil, "LIMIT", i + end + end + res.entities[id] = ent + i = e2 + end + elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then + -- kept as raw text (to the ENDSEC outside strings) + local k = j + local stop= nil + while k <= ctx.n do + local c = sbyte(s, k) + if c == 39 then + local q = k + 1 + while true do + local p = sfind(s, "'", q, true) + if not p then + return nil, "unterminated string", k + end + if sbyte(s, p + 1) == 39 then + q = p + 2 + else + k = p + 1 + break + end + end + elseif c == 69 and at(s, k, "ENDSEC") then + stop = k + break + else + k =k+ 1 + end + end + if not stop then + return nil, "truncated " .. word .. " section", i + end + table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) + local e2 = expect(ctx, stop + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + else + return nil, "unknown section " .. tostring(word), i + end + end + if not sawData then + return nil, "no DATA section", i + end + return res, nil, nil +end + +return Parse +end +__FILES["cad/step/Write"] = function() +local __compat = __compat local type = __compat.type --!strict +--!native +-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings +-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid +-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: +-- failures return nil, message. +local Write = {} + +local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge + +local MAX_DEPTH = 100 + +-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +function Write.real(v) +if v ~= v or v == huge or v == -huge then + return nil + end + local s = sformat("%.15g", v) + if tonumber(s) ~= v then + s = sformat("%.16g", v) + if tonumber(s) ~= v then + s = sformat("%.17g", v) + end + end + s = string.upper(s) + local e = sfind(s, "E", 1, true) + if not sfind(s, ".", 1, true) then + if e then + s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) + else + s =s.. "." + end + end + return s +end + +local HEX = "0123456789ABCDEF" +local function hex(v, k) +local out = table.create(k) + for i = k, 1, -1 do + local d = v % 16 + out[i] = ssub(HEX, d + 1, d + 1) + v = floor(v / 16) + end + return table.concat(out) +end + +-- a string's Part 21 literal (with the quotes) +function Write.str(s) +if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ + return "'" .. s .. "'" + end + local out = { "'" } + local i, n = 1, #s + local wide= nil -- 4 (\X2\) or 8 (\X4\) while in an extended run + local function close() + if wide then + table.insert(out, "\\X0\\") + wide = nil + end + end + while i <= n do + local c = (sbyte(s, i) ) +if c >= 32 and c < 127 then + close() + if c == 39 then + table.insert(out, "''") + elseif c == 92 then + table.insert(out, "\\\\") + else + table.insert(out, string.char(c)) + end + i =i+ 1 + else + -- a UTF-8 sequence -> code point + local cp= nil + local len = 1 + if c >= 0xC2 and c < 0xE0 then + local c2 = sbyte(s, i + 1) + if c2 and c2 >= 0x80 and c2 < 0xC0 then + cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 + end + elseif c >= 0xE0 and c < 0xF0 then + local c2, c3 = sbyte(s, i + 1, i + 2) + if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then + local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) + if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then + cp, len = v, 3 + end + end + elseif c >= 0xF0 and c < 0xF5 then + local c2, c3, c4 = sbyte(s, i + 1, i + 3) + if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then + local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) + if v >= 0x10000 and v < 0x110000 then + cp, len = v, 4 + end + end + end + if cp == nil then + close() + table.insert(out, "\\X\\" .. hex(c, 2)) + i =i+ 1 + else + local k = cp >= 0x10000 and 8 or 4 + if wide ~= k then + close() + table.insert(out, k == 4 and"\\X2\\" or"\\X4\\") + wide = k + end + table.insert(out, hex(cp, k)) + i =i+ len + end + end + end + close() + table.insert(out, "'") + return table.concat(out) +end + +local function isName(s) +return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil +end +Write.isName = isName + + + +local value + +local function reals(t) +local mt = getmetatable(t) + return (type(mt) == "table" and type(mt.__reals) == "table" and{mt.__reals }or{nil +})[1]end + +local function list(ctx, t, depth) +local out = ctx.out + table.insert(out, "(") + local marks = reals(t) + local n = #t + for i = 1, n do + if i > 1 then + table.insert(out, ",") + end + if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then + return false + end + end + table.insert(out, ")") + return true +end +Write.list = list + +value = function(ctx, v, real, depth) +local out = ctx.out + if depth > MAX_DEPTH then + ctx.err = "values nested too deeply (or a cycle)" + return false + end + local tv = type(v) + if tv == "number" then + if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then + table.insert(out, sformat("%.0f", v)) + return true + end + local r = Write.real(v) + if not r then + ctx.err = "a number that STEP cannot hold (nan / inf)" + return false + end + table.insert(out, r) + return true + elseif tv == "string" then + table.insert(out, Write.str(v)) + return true + elseif tv == "boolean" then + table.insert(out, v and".T." or".F.") + return true + elseif tv == "table" then + if v == ctx.null then + table.insert(out, "$") + return true + elseif v == ctx.derived then + table.insert(out, "*") + return true + end + local ref = v.ref + if ref ~= nil then + if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then + ctx.err = "bad entity reference " .. tostring(ref) + return false + end + table.insert(out, sformat("#%.0f", ref)) + return true + end + local enum = v.enum + if enum ~= nil then + if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then + ctx.err = "bad enumeration " .. tostring(enum) + return false + end + table.insert(out, "." .. string.upper(enum) .. ".") + return true + end + local bin = v.binary + if bin ~= nil then + if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then + ctx.err = "bad binary literal" + return false + end + table.insert(out, "\"" .. string.upper(bin) .. "\"") + return true + end + local typed = v.typed + if typed ~= nil then + if not isName(typed) then + ctx.err = "bad typed parameter name " .. tostring(typed) + return false + end + if v.value == nil then + ctx.err = "typed parameter " .. typed .. " without a value" + return false + end + local marks = reals(v) + table.insert(out, string.upper(typed) .. "(") + if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then + return false + end + table.insert(out, ")") + return true + end + return list(ctx, v, depth) + end + ctx.err = "cannot write a " .. tv .. " value" + return false +end +Write.value = value + +-- record(ctx, type, args) -> appends TYPE(args) +function Write.record(ctx, t, args) +if not isName(t) then + ctx.err = "bad entity type " .. tostring(t) + return false + end + if type(args) ~= "table" then + ctx.err = "entity " .. t .. " without an args list" + return false + end + table.insert(ctx.out, string.upper(t)) + return list(ctx, args, 0) +end + +return Write +end +__FILES["codecs/audio/Aac"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- 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/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("rosetta.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, ... } +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bits = __include("core/Bits") +local Decode = __include("codecs/audio/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP= { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + + + + + + + + + + + + + +local function rateIndex(rate) -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + +local best, bi = math.huge, 4 + for i, r in __iter(Aac.RATES) do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br) +local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br) +local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- pce(br) -> channels (program_config_element) +local function pce(br) +br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels =channels+ (br:read(1) == 1 and 2 or 1 +) br:read(4) + end + channels =channels+ lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig +function Aac.config(asc) +if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate= nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, aot == 1 and"AAC Main" or"AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig +function Aac.asc(aot, sfIndex, channelConfig) +local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) + + + + + + + + + + + +function Aac.adts(b, o, limit) +if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = protected and 9 or 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + + + + + + + +local function decode(self, buf, offset, length) +local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + -- an empty frame (only fill elements): silence + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self) + for _, c in __iter(self.state.ch) do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err +function Aac.decoder(asc) +local cfg +if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } +else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac +end +__FILES["codecs/audio/Aac/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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/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 = __include("codecs/audio/Mdct") +local Tables = __include("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 + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- ------------------------------------------------------------------------------------------------ bit reader +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B= buffer.create(16) +local BP = 0 -- bit position +local BL = 0 -- bit limit +local OVER = false + +local function getBits(n) +local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function peekBits(n) +local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function getLong(n) +if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +-- ------------------------------------------------------------------------------------------------ Huffman +local PEEK = 10 + + +local function book(codes, bits) +local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK= {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +-- the next symbol of a book, -1 for an invalid code +local function huff(bk) +local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP =BP+ band(e, 31) + return rshift(e, 5) + end + -- a code longer than PEEK bits + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +-- per codebook: dimension, unsigned, modulus, offset +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +-- ------------------------------------------------------------------------------------------------ windows +local SINE_LONG = (Mdct.window("sine", 2048) ) +local KBD_LONG = (Mdct.window("kbd", 2048, 4) ) +local SINE_SHORT = (Mdct.window("sine", 256) ) +local KBD_SHORT = (Mdct.window("kbd", 256, 6) ) +local PLAN_LONG = (Mdct.new(2048) ) +local PLAN_SHORT = (Mdct.new(256) )-- ------------------------------------------------------------------------------------------------ state + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function newChannel() +return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +-- ------------------------------------------------------------------------------------------------ ics +local function icsInfo(st, c) +if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng]=gl[ng]+ 1 + else + ng =ng+ 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +local function sectionData(c) +local long = c.windowSequence ~= EIGHT_SHORT + local bits = long and 5 or 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len =len+ inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k =k+ len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +local function scaleFactors(c, globalGain) +local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is =is+ (d - 60 +) sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise =noise+ (getBits(9) - 256 +) firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise =noise+ (d - 60 +) end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv =sfv+ (d - 60 +) if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +local function tnsData(st, c) +local short = c.windowSequence == EIGHT_SHORT + local nw = short and 8 or 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(short and 1 or 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(short and 4 or 6) + local order = getBits(short and 3 or 5) + local f = { length, order, 0 } + if order > (short and 7 or 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v =v- 2 ^ nb + end + tmp[k] = math.sin(v / ((v >= 0 and{iq }or{iqm})[1])) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +local function applyTns(st, c) + local short = c.windowSequence == EIGHT_SHORT + local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] +})[1] local numSwb = (short and{Tables.NUM_SWB_SHORT[st.sfIndex + 1] }or{Tables.NUM_SWB_LONG[st.sfIndex + 1] +})[1] local maxBands = (short and{Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] }or{Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] +})[1] local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in __iter(c.tnsFilters) do + local bottom = numSwb + for _, f in __iter(list) do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = (m < order and{m }or{order +})[1] for i = 1, lim do + y =y- spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p =p+ inc + end + end + end + end + end +end + +-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) +local function spectralData(st, c, pulses) +local short = c.windowSequence == EIGHT_SHORT + local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] +})[1] local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do +local __DARKLUA_CONTINUE_26=false repeat local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then +__DARKLUA_CONTINUE_26=true -- zeros (intensity bands are filled from the other channel later) + break + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = (r >= 2147483648 and((r - 4294967296 ))or(r +)) spec[base + k] = v + energy =energy+ v * v + end + st.random = r + local m = (energy > 0 and((scale / sqrt(energy) ))or(0 +)) for k = 1, width do +do local __DARKLUA_VAR=base + k spec[__DARKLUA_VAR]=spec[__DARKLUA_VAR]* m +end end + end +__DARKLUA_CONTINUE_26=true break + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1, vals2, vals3, vals4 +if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = (e == 1 and{vals1 }or{vals2 +})[1] if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n =n+ 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k =k+ dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = (q < 0 and{(-q )}or{q +})[1] local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = (q < 0 and{(-v )}or{v +})[1] end + end + end + end +__DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 then break end end + win =win+ glen + end + if pulses then + -- long window: add the pulses to the quantised values, then dequantise every band + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = (q > 0 and((q + pulses[i + 1] ))or((q - pulses[i + 1] +))) end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = (q < 0 and{(-q )}or{q +})[1] local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = (q < 0 and{(-v )}or{v +})[1] end + end + end + end + end + return nil +end + +-- individual_channel_stream +local function ics(st, c, commonWindow) +local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses= nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos =pos+ getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +-- ------------------------------------------------------------------------------------------------ stereo +local function msStereo(st, l, r, mask) + local short = l.windowSequence == EIGHT_SHORT + local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] +})[1] local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win =win+ glen + end +end + +local function intensity(st, l, r, mask, msPresent) + local short = r.windowSequence == EIGHT_SHORT + local swb = (short and{Tables.SWB_SHORT[st.sfIndex + 1] }or{Tables.SWB_LONG[st.sfIndex + 1] +})[1] local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = cb == INTENSITY_HCB and 1 or-1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win =win+ glen + end +end + +-- ------------------------------------------------------------------------------------------------ filterbank +local function filterbank(st, c, out, stride, offset) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = (prev == 1 and{KBD_SHORT }or{SINE_SHORT +})[1] local wcur = (shape == 1 and{KBD_SHORT }or{SINE_SHORT +})[1] for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = (w == 0 and{rise0 }or{wcur +})[1] local base = 448 + w * 128 + for n = 1, 128 do +do local __DARKLUA_VAR=base + n frame[__DARKLUA_VAR]=frame[__DARKLUA_VAR]+ tmp[n] * rise[n] +end do local __DARKLUA_VAR0=base + 128 + n frame[__DARKLUA_VAR0]=frame[__DARKLUA_VAR0]+ tmp[128 + n] * wcur[128 + n] +end end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + -- left half + if seq == LONG_STOP then + local rise = (prev == 1 and{KBD_SHORT }or{SINE_SHORT +})[1] for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = (prev == 1 and{KBD_LONG }or{SINE_LONG +})[1] for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + -- right half + if seq == LONG_START then + local fall = (shape == 1 and{KBD_SHORT }or{SINE_SHORT +})[1] for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = (shape == 1 and{KBD_LONG }or{SINE_LONG +})[1] for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p =p+ stride + end + c.prevShape = shape +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. +function Decode.frame(st, buf, off, len) +if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order= {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh =nextCh+ 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh =nextCh+ 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count =count+ getBits(8) + end + if align == 1 then + BP = math.floor((BP + 7) / 8 )* 8 + end + BP =BP+ count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count =count+ (getBits(8) - 1 +) end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions =st.extensions+ 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in __iter(order) do + local o = (map and map[i] and{map[i] }or{i +})[1] filterbank(st, c, pcm, n, o) + end + return n, nil +end + +function Decode.state(sfIndex) +return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode +end +__FILES["codecs/audio/Aac/Tables"] = function() +--!strict +-- 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. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables +end +__FILES["codecs/audio/Ac3"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- codecs/audio/Ac3: AC-3 (Dolby Digital, ATSC A/52) syncframes: the syncinfo / BSI header, the CRC check, and the +-- decoder (codecs/audio/Ac3/Decode). Written from ATSC A/52:2018; no third-party code. A codec (layer 3): audio/ac3 +-- (raw .ac3 files) builds on it, and the AC-3 tracks of MKV / MP4 / MPEG-TS / AVI reach it through +-- containers/AudioWrap. +-- Supports: every acmod (1+1, 1/0 .. 3/2) with or without LFE, 32 / 44.1 / 48 kHz, all bit rates, coupling with phase +-- flags, rematrixing, block switching, delta bit allocation, dither, dynamic range control (off by default, +-- `drc` = 0 .. 1 scales it). Output: every channel in WAVE order (L R C LFE surrounds), no downmix. Not supported: +-- E-AC-3 (bsid 11 .. 16) and the reduced-rate bsid 9 / 10 streams (UNSUPPORTED). +-- +-- local h = Ac3.header(buf, offset, limit) -- { sampleRate, frameSize, channels, acmod, lfeon, bsid, bitrate } +-- local dec = Ac3.decoder({ drc = 0 }) -- dec:decode(buf, offset, length) -> 1536, dec.pcm (interleaved) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local T = __include("codecs/audio/Ac3/Tables") +local Decode = __include("codecs/audio/Ac3/Decode") + +local Ac3 = {} + +local readu8 = buffer.readu8 +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +-- header(buf, o, limit) -> Header | nil (not an AC-3 / E-AC-3 syncframe header at o). E-AC-3 headers (bsid > 10) +-- come back with frameSize from their own frmsiz field so a scanner can step over them. + + + + + + + + + + +function Ac3.header(b, o, limit) +if o < 0 or o + 8 > limit or o + 8 > buffer.len(b) then + return nil + end + if readu8(b, o) ~= 0x0B or readu8(b, o + 1) ~= 0x77 then + return nil + end + local bsid = bit32.rshift(readu8(b, o + 5), 3) + if bsid > 10 then + if bsid > 16 then + return nil + end + -- E-AC-3: strmtyp(2) substreamid(3) frmsiz(11) fscod(2) ... + local words = bit32.band(readu8(b, o + 2), 7) * 256 + readu8(b, o + 3) + 1 + local fs = bit32.rshift(readu8(b, o + 4), 6) + return { + sampleRate = (fs < 3 and{T.RATES[fs + 1] }or{0})[1], + frameSize = words * 2, + bitrate = 0, + channels = 0, + acmod = bit32.band(bit32.rshift(readu8(b, o + 4), 1), 7), + lfeon = false, + bsid = bsid, + } + end + local b4 = readu8(b, o + 4) + local fscod, frmsizecod = bit32.rshift(b4, 6), bit32.band(b4, 63) + local words = T.frameWords(fscod, frmsizecod) + if words == 0 then + return nil + end + local acmod = bit32.rshift(readu8(b, o + 6), 5) + -- lfeon: after acmod and the optional cmixlev / surmixlev / dsurmod fields + local skip = 0 + if bit32.band(acmod, 1) == 1 and acmod ~= 1 then + skip =skip+ 2 + end + if bit32.band(acmod, 4) ~= 0 then + skip =skip+ 2 + end + if acmod == 2 then + skip =skip+ 2 + end + local w = readu8(b, o + 6) * 256 + readu8(b, o + 7) + local lfeon = bit32.extract(w, 12 - skip, 1) == 1 + local shift = (bsid > 8 and((bsid - 8 ))or(0 +)) return { + sampleRate = math.floor(T.RATES[fscod + 1] / 2 ^ shift), + frameSize = words * 2, + bitrate = math.floor(T.BITRATES[math.floor(frmsizecod / 2 )+ 1] * 1000 / 2 ^ shift), + channels = NFCHANS[acmod] + (lfeon and 1 or 0), + acmod = acmod, + lfeon = lfeon, + bsid = bsid, + } +end + +-- the CRC-16 of A/52 section 7.10.1 (x^16 + x^15 + x^2 + 1, MSB first, zero start): a syncframe checks when the CRC of +-- everything after the sync word is 0 +local CRC = table.create(256, 0) +for i = 0, 255 do + local c = i * 256 + for _ = 1, 8 do + c = (c >= 0x8000 and{(bit32.bxor(bit32.band(c * 2, 0xFFFF), 0x8005) )}or{(c * 2 +)})[1] end + CRC[i + 1] = c +end + +function Ac3.crc(b, o, n) +local c = 0 + for i = o, o + n - 1 do + c = bit32.bxor(bit32.band(c * 256, 0xFFFF), CRC[bit32.bxor(bit32.rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + + + + + + + + +function Ac3.decoder(opts) +local o= opts or {} + local drc = math.max(0, o.drc or 0) + local checkCrc = o.crc ~= false + local st = Decode.state() + local scratch = buffer.create(3840 + Decode.PAD) + local dec +dec = { + pcm = st.pcm, + channels = 0, + sampleRate = 0, + blocks = st.blocks, + decode = function(self, buf, offset, length) +local off = offset or 0 + if type(buf) ~= "buffer" or off < 0 or off >= buffer.len(buf) then + return nil, Err.new(Err.ARG, "frame range out of the buffer") + end + local h = Ac3.header(buf, off, buffer.len(buf)) + if not h then + return nil, Err.new(Err.CORRUPT, "no AC-3 syncframe", off) + end + local n = h.frameSize + if length and length < n or off + n > buffer.len(buf) then + return nil, Err.new(Err.TRUNCATED, "truncated syncframe", off) + end + if checkCrc and Ac3.crc(buf, off + 2, n - 2) ~= 0 then + return nil, Err.new(Err.CHECKSUM, "syncframe CRC", off) + end + buffer.copy(scratch, 0, buf, off, n) + local frames, msg = Decode.frame(st, scratch, n, drc) + if not frames then + return nil, Err.from(msg, off) + end + self.pcm = st.pcm + self.channels = st.channels + self.sampleRate = h.sampleRate + return frames, nil + end, + reset = function(_self) + Decode.reset(st) + end, + } + return dec +end + +return Ac3 +end +__FILES["codecs/audio/Ac3/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/audio/Ac3/Decode: one AC-3 syncframe (6 audio blocks of 256 samples) -> PCM. Written from ATSC A/52:2018 +-- (section 5.3 syntax, 7.1 exponents, 7.2 parametric bit allocation with delta bit allocation, 7.3 mantissas with +-- grouping and dither, 7.4 coupling with phase flags, 7.5 rematrixing, 7.7.1 dynamic range, 7.9 the 512 / 2 x 256 +-- inverse transforms with block switching) on codecs/audio/Mdct; no third-party code. The bit reader is module state +-- over a frame the caller pads by PAD bytes; every section stops when the position passes the frame. No error / +-- assert: failures return nil, "message". +local T = __include("codecs/audio/Ac3/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local readu32, bswap, extract, band, rshift = buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.rshift +local max, min = math.max, math.min + +local Decode = {} +Decode.PAD = 2048 + +local CPL, LFE = 7, 6 -- channel slots: 1 .. 5 full bandwidth, 6 LFE, 7 the coupling channel +local NFCHANS = { [0] = 2, 1, 2, 3, 3, 4, 4, 5 } + +local SLOWDEC, FASTDEC, SLOWGAIN, DBPBTAB, FLOORTAB, FASTGAIN = T.SLOWDEC, T.FASTDEC, T.SLOWGAIN, T.DBPBTAB, T.FLOORTAB, T.FASTGAIN +local BNDTAB, BNDSZ, MASKTAB, LATAB, HTH, BAPTAB = T.BNDTAB, T.BNDSZ, T.MASKTAB, T.LATAB, T.HTH, T.BAPTAB + +-- 2^-e for the exponents 0 .. 24 +local POW2 = table.create(32, 0) +for e = 0, 31 do + POW2[e + 1] = 2 ^ -e +end +-- symmetric quantiser values (Tables 7.19 - 7.23): Q1[code + 1] etc. +local function levels(n) +local t = {} + for c = 0, n - 1 do + t[c + 1] = (2 * c - (n - 1)) / n + end + return t +end +local Q1, Q2, Q3, Q4, Q5 = levels(3), levels(5), levels(7), levels(11), levels(15) +-- bits of the asymmetric quantisers (bap 6 .. 15) +local QBITS = { [6] = 5, [7] = 6, [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 14, [15] = 16 } + +local WINDOW = (Mdct.window("kbd", 512, 5) ) +local PLAN512 = (Mdct.new(512) ) +local PLAN256 = (Mdct.new(256) ) +-- ------------------------------------------------------------------------------------------------ bit reader + +local B= buffer.create(0) +local P = 0 + +local function bits(n) +if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P =P+ n + return v +end +-- ------------------------------------------------------------------------------------------------ state + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function arrays(n, size, v) +local t = {} + for i = 1, n do + t[i] = table.create(size, v) + end + return t +end + +function Decode.state() +return { + fscod = 0, + acmod = 2, + lfeon = false, + nfchans = 2, + channels = 2, + map = { 1, 2, 3, 4, 5, 6 }, + drc = 0, + exp = arrays(7, 264, 0), + bap = arrays(7, 264, 0), + coef = arrays(7, 256, 0), + delay = arrays(6, 256, 0), + endmant = table.create(7, 0), + chexpstr = table.create(7, 0), + blksw = table.create(7, false), + dithflag = table.create(7, false), + fsnroffst = table.create(7, 0), + fgaincod = table.create(7, 0), + dbaOn = table.create(7, false), + dbaOffst = arrays(7, 8, 0), + dbaLen = arrays(7, 8, 0), + dbaBa = arrays(7, 8, 0), + cplinu = false, + chincpl = table.create(7, false), + phsflginu = false, + cplbegf = 0, + cplendf = 0, + cplbndstrc = table.create(18, false), + cplco = arrays(5, 18, 0), + phsflg = table.create(18, false), + cplfleak = 0, + cplsleak = 0, + rematflg = table.create(4, false), + sdcycod = 0, + fdcycod = 0, + sgaincod = 0, + dbpbcod = 0, + floorcod = 0, + csnroffst = 0, + dynrng = { 1, 1 }, + seed = 1, + psd = table.create(256, 0), + bndpsd = table.create(50, 0), + excite = table.create(50, 0), + mask = table.create(50, 0), + y = table.create(512, 0), + pcm = table.create(1536 * 2, 0), + blocks = table.create(6, 0), + } +end + +-- reset(st): forget the overlap (before a seek) +function Decode.reset(st) + for _, d in __iter(st.delay) do + for i = 1, 256 do + d[i] = 0 + end + end +end + +-- ------------------------------------------------------------------------------------------------ exponents +-- read ngrps grouped exponents (7 bits = 3 deltas each) after absexp into e[first + 1 ..] (bins first ..), grpsize +-- bins per delta; false when an exponent leaves 0 .. 24 +local function exponents(e, absexp, ngrps, grpsize, first) +local prev = absexp + local k = first + 1 + for _ = 1, ngrps do + local g = bits(7) + if g >= 125 then + return false + end + local d1 = math.floor(g / 25 +) local d2 = math.floor((g % 25) / 5 +) local d3 = g % 5 + for m = 1, 3 do + local d = (m == 1 and{d1 }or{(m == 2 and{d2 }or{d3 +})[1]})[1] prev =prev+ (d - 2 +) if prev < 0 or prev > 24 then + return false + end + for _ = 1, grpsize do + e[k] = prev + k =k+ 1 + end + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ bit allocation +local function logadd(a, b) +local c = a - b + local adr = min(rshift((c >= 0 and{c }or{(-c)})[1], 1), 255) + return (c >= 0 and((a + LATAB[adr + 1] ))or((b + LATAB[adr + 1] +)))end + +local function lowcomp(a, b0, b1, bin) +if bin < 7 then + if b0 + 256 == b1 then + a = 384 + elseif b0 > b1 then + a = max(0, a - 64) + end + elseif bin < 20 then + if b0 + 256 == b1 then + a = 320 + elseif b0 > b1 then + a = max(0, a - 64) + end + else + a = max(0, a - 128) + end + return a +end + +-- section 7.2.2: the bap of bins [start, stop) of channel slot ch +local function allocate(st, ch, start, stop, fgain, snroffset, isLfe) + local e, bap = st.exp[ch], st.bap[ch] + local psd, bndpsd, excite, mask = st.psd, st.bndpsd, st.excite, st.mask + local sdecay, fdecay = SLOWDEC[st.sdcycod + 1], FASTDEC[st.fdcycod + 1] + local sgain, dbknee, floor = SLOWGAIN[st.sgaincod + 1], DBPBTAB[st.dbpbcod + 1], FLOORTAB[st.floorcod + 1] + if floor >= 0x8000 then + floor =floor- 0x10000 -- 0xf800: a negative 16-bit value + end + for bin = start, stop - 1 do + psd[bin + 1] = 3072 - e[bin + 1] * 128 + end + -- PSD integration + local j = start + local k = MASKTAB[start + 1] + local lastbin + repeat + lastbin = min(BNDTAB[k + 1] + BNDSZ[k + 1], stop) + local v = psd[j + 1] + j =j+ 1 + while j < lastbin do + v = logadd(v, psd[j + 1]) + j =j+ 1 + end + bndpsd[k + 1] = v + k =k+ 1 + until stop <= lastbin + -- excitation + local bndstrt = MASKTAB[start + 1] + local bndend = MASKTAB[stop] + 1 + local fastleak, slowleak = 0, 0 + local begin + if bndstrt == 0 then + local lc = 0 + lc = lowcomp(lc, bndpsd[1], bndpsd[2], 0) + excite[1] = bndpsd[1] - fgain - lc + lc = lowcomp(lc, bndpsd[2], bndpsd[3], 1) + excite[2] = bndpsd[2] - fgain - lc + begin = 7 + for bin = 2, 6 do + local last = isLfe and bin == 6 + if not last then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = bndpsd[bin + 1] - fgain + slowleak = bndpsd[bin + 1] - sgain + excite[bin + 1] = fastleak - lc + if not last and bndpsd[bin + 1] <= bndpsd[bin + 2] then + begin = bin + 1 + break + end + end + for bin = begin, min(bndend, 22) - 1 do + if not (isLfe and bin == 6) then + lc = lowcomp(lc, bndpsd[bin + 1], bndpsd[bin + 2], bin) + end + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak - lc, slowleak) + end + begin = 22 + else + begin = bndstrt + fastleak = st.cplfleak * 256 + 768 + slowleak = st.cplsleak * 256 + 768 + end + for bin = begin, bndend - 1 do + fastleak = max(fastleak - fdecay, bndpsd[bin + 1] - fgain) + slowleak = max(slowleak - sdecay, bndpsd[bin + 1] - sgain) + excite[bin + 1] = max(fastleak, slowleak) + end + -- masking curve + local hth = HTH[st.fscod + 1] + for bin = bndstrt, bndend - 1 do + local x = excite[bin + 1] + local p = bndpsd[bin + 1] + if p < dbknee then + x =x+ math.floor((dbknee - p) / 4 +) end + mask[bin + 1] = max(x, hth[bin + 1]) + end + -- delta bit allocation + if st.dbaOn[ch] then + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + local b = 0 + for seg = 1, #offs do + b =b+ offs[seg] + local ba = bas[seg] + local delta = (ba >= 4 and(((ba - 3) * 128 ))or(((ba - 4) * 128 +))) for _ = 1, lens[seg] do + if b < 50 then +do local __DARKLUA_VAR=b + 1 mask[__DARKLUA_VAR]=mask[__DARKLUA_VAR]+ delta +end end + b =b+ 1 + end + end + end + -- bit allocation pointers + local i = start + j = MASKTAB[start + 1] + repeat + lastbin = min(BNDTAB[j + 1] + BNDSZ[j + 1], stop) + local m = mask[j + 1] - snroffset - floor + if m < 0 then + m = 0 + end + m = band(m, 0x1fe0) + floor + while i < lastbin do + local adr = math.floor((psd[i + 1] - m) / 32 +) bap[i + 1] = BAPTAB[min(63, max(0, adr)) + 1] + i =i+ 1 + end + j =j+ 1 + until stop <= lastbin +end + +-- ------------------------------------------------------------------------------------------------ mantissas +-- grouped mantissa state (bap 1, 2, 4 share groups across channels within a block) +local G1, G2, G4 = table.create(3, 0), table.create(3, 0), table.create(2, 0) +local n1, n2, n4 = 0, 0, 0 + +local function dither(st) +local s = (st.seed * 1664525 + 1013904223) % 4294967296 + st.seed = s + return (s / 2147483648 - 1) * 0.707 +end + +-- the mantissas of bins [start, stop) of slot ch into out[], scaled by their exponents (bap 0: dither when asked) +local function mantissas(st, ch, start, stop, out, dith) + local e, bap = st.exp[ch], st.bap[ch] + for bin = start, stop - 1 do + local b = bap[bin + 1] + local v + if b == 0 then + v = (dith and{(dither(st) )}or{0 +})[1] elseif b == 1 then + if n1 == 0 then + local g = bits(5) + if g > 26 then + g = 26 + end + G1[1], G1[2], G1[3] = Q1[math.floor(g / 9 )+ 1], Q1[math.floor((g % 9) / 3 )+ 1], Q1[g % 3 + 1] + n1 = 3 + end + v = G1[4 - n1] + n1 =n1- 1 + elseif b == 2 then + if n2 == 0 then + local g = bits(7) + if g > 124 then + g = 124 + end + G2[1], G2[2], G2[3] = Q2[math.floor(g / 25 )+ 1], Q2[math.floor((g % 25) / 5 )+ 1], Q2[g % 5 + 1] + n2 = 3 + end + v = G2[4 - n2] + n2 =n2- 1 + elseif b == 3 then + v = Q3[min(bits(3), 6) + 1] + elseif b == 4 then + if n4 == 0 then + local g = bits(7) + if g > 120 then + g = 120 + end + G4[1], G4[2] = Q4[math.floor(g / 11 )+ 1], Q4[g % 11 + 1] + n4 = 2 + end + v = G4[3 - n4] + n4 =n4- 1 + elseif b == 5 then + v = Q5[min(bits(4), 14) + 1] + else + local nb = QBITS[b] + local m = bits(nb) + local half = 2 ^ (nb - 1) + if m >= half then + m =m- 2 * half + end + v = m / half + end + out[bin + 1] = v * POW2[e[bin + 1] + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ audio block +local function readDba(st, ch) + local nseg = bits(3) + 1 + local offs, lens, bas = st.dbaOffst[ch], st.dbaLen[ch], st.dbaBa[ch] + table.clear(offs) + table.clear(lens) + table.clear(bas) + for seg = 1, nseg do + offs[seg] = bits(5) + lens[seg] = bits(4) + bas[seg] = bits(3) + end +end + +local EXPGRP = { 3, 6, 12 } -- bins per group of 3 deltas, by strategy (D15 / D25 / D45) + +local function audblk(st, blk, limit) +local nf, acmod = st.nfchans, st.acmod + for ch = 1, nf do + st.blksw[ch] = bits(1) == 1 + end + for ch = 1, nf do + st.dithflag[ch] = bits(1) == 1 + end + for i = 1, acmod == 0 and 2 or 1 do + if bits(1) == 1 then + local v = bits(8) + local x = rshift(v, 5) + if x >= 4 then + x =x- 8 + end + local g = 2 ^ (x + 1) * (32 + band(v, 31)) / 64 + st.dynrng[i] = (st.drc == 1 and{g }or{(g ^ st.drc +)})[1] elseif blk == 0 then + st.dynrng[i] = 1 + end + end + -- coupling strategy + if bits(1) == 1 then + st.cplinu = bits(1) == 1 + if st.cplinu then + if acmod < 2 then + return nil, "coupling in a mono / dual mono stream" + end + for ch = 1, nf do + st.chincpl[ch] = bits(1) == 1 + end + st.phsflginu = (acmod == 2 and{(bits(1) == 1 )}or{false +})[1] st.cplbegf = bits(4) + st.cplendf = bits(4) + if st.cplendf + 3 <= st.cplbegf then + return nil, "bad coupling range" + end + st.cplbndstrc[st.cplbegf + 1] = false + for sbnd = st.cplbegf + 1, st.cplendf + 2 do + st.cplbndstrc[sbnd + 1] = bits(1) == 1 + end + else + for ch = 1, nf do + st.chincpl[ch] = false + end + st.phsflginu = false + end + elseif blk == 0 then + return nil, "no coupling strategy in block 0" + end + local cplinu = st.cplinu + local cplbegf, cplendf = st.cplbegf, st.cplendf + local cplstrt = 37 + 12 * cplbegf + local cplend = 37 + 12 * (cplendf + 3) + -- coupling coordinates (per sub-band, duplicated over each coupling band) + if cplinu then + local anyNew = false + for ch = 1, nf do + if st.chincpl[ch] then + if bits(1) == 1 then + anyNew = true + local mstr = bits(2) * 3 + local co = st.cplco[ch] + local v = 0 + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + local ex, mant = bits(4), bits(4) + local m = (ex == 15 and((mant / 16 ))or(((mant + 16) / 32 +))) v = m * 2 ^ -(ex + mstr) + end + co[sbnd + 1] = v + end + end + end + end + if acmod == 2 and st.phsflginu and anyNew then + local f = false + for sbnd = cplbegf, cplendf + 2 do + if not st.cplbndstrc[sbnd + 1] then + f = bits(1) == 1 + end + st.phsflg[sbnd + 1] = f + end + end + end + -- rematrixing + if acmod == 2 then + if bits(1) == 1 then + local n = (not cplinu or cplbegf > 2 )and 4 or(cplbegf > 0 and 3 or 2 +) for r = 1, 4 do + st.rematflg[r] = (r <= n and{(bits(1) == 1 )}or{false +})[1] end + elseif blk == 0 then + for r = 1, 4 do + st.rematflg[r] = false + end + end + end + -- exponent strategies + local chexpstr = st.chexpstr + chexpstr[CPL] = (cplinu and{(bits(2) )}or{0 +})[1] for ch = 1, nf do + chexpstr[ch] = bits(2) + end + chexpstr[LFE] = (st.lfeon and{(bits(1) )}or{0 +})[1] if blk == 0 then + for ch = 1, nf do + if chexpstr[ch] == 0 then + return nil, "exponent reuse in block 0" + end + end + if (cplinu and chexpstr[CPL] == 0) or (st.lfeon and chexpstr[LFE] == 0) then + return nil, "exponent reuse in block 0" + end + end + local endmant = st.endmant + for ch = 1, nf do + if chexpstr[ch] ~= 0 then + if st.chincpl[ch] then + endmant[ch] = cplstrt + else + local bw = bits(6) + if bw > 60 then + return nil, "bad channel bandwidth code" + end + endmant[ch] = 37 + 3 * (bw + 12) + end + end + end + endmant[LFE] = 7 + -- exponents + if cplinu and chexpstr[CPL] ~= 0 then + local abs = bits(4) * 2 + local grp = EXPGRP[chexpstr[CPL] ] + if not exponents(st.exp[CPL], abs, math.floor((cplend - cplstrt) / grp), math.floor(grp / 3), cplstrt) then + return nil, "bad coupling exponents" + end + end + for ch = 1, nf do + local s = chexpstr[ch] + if s ~= 0 then + local grp = EXPGRP[s] + local ngrps + if s == 1 then + ngrps = math.floor((endmant[ch] - 1) / 3 +) elseif s == 2 then + ngrps = math.floor((endmant[ch] - 1 + 3) / 6 +) else + ngrps = math.floor((endmant[ch] - 1 + 9) / 12 +) end + local e = st.exp[ch] + e[1] = bits(4) + if not exponents(e, e[1], ngrps, math.floor(grp / 3), 1) then + return nil, "bad exponents" + end + bits(2) -- gainrng + end + end + if st.lfeon and chexpstr[LFE] ~= 0 then + local e = st.exp[LFE] + e[1] = bits(4) + if not exponents(e, e[1], 2, 1, 1) then + return nil, "bad LFE exponents" + end + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation parameters + if bits(1) == 1 then + st.sdcycod, st.fdcycod, st.sgaincod, st.dbpbcod, st.floorcod = bits(2), bits(2), bits(2), bits(2), bits(3) + elseif blk == 0 then + return nil, "no bit allocation parameters in block 0" + end + if bits(1) == 1 then + st.csnroffst = bits(6) + if cplinu then + st.fsnroffst[CPL], st.fgaincod[CPL] = bits(4), bits(3) + end + for ch = 1, nf do + st.fsnroffst[ch], st.fgaincod[ch] = bits(4), bits(3) + end + if st.lfeon then + st.fsnroffst[LFE], st.fgaincod[LFE] = bits(4), bits(3) + end + elseif blk == 0 then + return nil, "no SNR offsets in block 0" + end + if cplinu then + if bits(1) == 1 then + st.cplfleak, st.cplsleak = bits(3), bits(3) + end + end + -- delta bit allocation + if bits(1) == 1 then + local modes = table.create(7, 0) + if cplinu then + modes[CPL] = bits(2) + end + for ch = 1, nf do + modes[ch] = bits(2) + end + if cplinu and modes[CPL] == 1 then + readDba(st, CPL) + end + for ch = 1, nf do + if modes[ch] == 1 then + readDba(st, ch) + end + end + for _, ch in __iter({ 1, 2, 3, 4, 5, CPL }) do + if modes[ch] == 1 then + st.dbaOn[ch] = true + elseif modes[ch] == 2 or modes[ch] == 3 then + st.dbaOn[ch] = false + end + end + elseif blk == 0 then + for ch = 1, 7 do + st.dbaOn[ch] = false + end + end + -- skip field + if bits(1) == 1 then + P =P+ bits(9) * 8 + end + if P > limit then + return nil, "truncated block" + end + -- bit allocation + local zero = st.csnroffst == 0 + if zero then + for ch = 1, nf do + if st.fsnroffst[ch] ~= 0 then + zero = false + end + end + if (cplinu and st.fsnroffst[CPL] ~= 0) or (st.lfeon and st.fsnroffst[LFE] ~= 0) then + zero = false + end + end + local function alloc(ch, start, stop, isLfe) + if zero then + for i = start + 1, stop do + st.bap[ch][i] = 0 + end + else + local snr = ((st.csnroffst - 15) * 16 + st.fsnroffst[ch]) * 4 + allocate(st, ch, start, stop, FASTGAIN[st.fgaincod[ch] + 1], snr, isLfe) + end + end + if cplinu then + alloc(CPL, cplstrt, cplend, false) + end + for ch = 1, nf do + alloc(ch, 0, endmant[ch], false) + end + if st.lfeon then + alloc(LFE, 0, 7, true) + end + -- mantissas + n1, n2, n4 = 0, 0, 0 + local gotCpl = false + local coef = st.coef + for ch = 1, nf do + local c = coef[ch] + mantissas(st, ch, 0, endmant[ch], c, st.dithflag[ch]) + for i = endmant[ch] + 1, 256 do + c[i] = 0 + end + if cplinu and st.chincpl[ch] and not gotCpl then + mantissas(st, CPL, cplstrt, cplend, coef[CPL], false) + gotCpl = true + end + if P > limit then + return nil, "truncated block" + end + end + if st.lfeon then + local c = coef[LFE] + mantissas(st, LFE, 0, 7, c, false) + for i = 8, 256 do + c[i] = 0 + end + end + if P > limit then + return nil, "truncated block" + end + -- decoupling (section 7.4): dither the coupling channel's zero-bit mantissas per channel + if cplinu then + local cc, cbap, cexp = coef[CPL], st.bap[CPL], st.exp[CPL] + for ch = 1, nf do + if st.chincpl[ch] then + local c, co = coef[ch], st.cplco[ch] + local dith = st.dithflag[ch] + local flip = acmod == 2 and ch == 2 and st.phsflginu + for sbnd = cplbegf, cplendf + 2 do + local f = co[sbnd + 1] * 8 + if flip and st.phsflg[sbnd + 1] then + f = -f + end + for k = 37 + 12 * sbnd + 1, 37 + 12 * sbnd + 12 do + local v = cc[k] + if cbap[k] == 0 then + v = (dith and((dither(st) * POW2[cexp[k] + 1] ))or(0 +)) end + c[k] = v * f + end + end + for k = cplend + 1, 256 do + c[k] = 0 + end + end + end + end + -- rematrixing (section 7.5) + if acmod == 2 then + local stop = (cplinu and{cplstrt }or{(min(endmant[1], endmant[2]) +)})[1] local l, r = coef[1], coef[2] + local edges = { 13, 25, 37, 61, 253 } + for rb = 1, 4 do + if st.rematflg[rb] then + for k = edges[rb] + 1, min(edges[rb + 1], stop) do + local a, b = l[k], r[k] + l[k], r[k] = a + b, a - b + end + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +-- the inverse transform of slot ch (long or two short), windowed, overlap-added into out[base + i * step] +local function synth(st, ch, short, gain, out, base, step) + local x, y, d, w = st.coef[ch], st.y, st.delay[ch], WINDOW + if short then + -- two 256-point transforms of the interleaved coefficients, phases alpha = -1 (n0 = 0) and +1 (n0 = N / 2) + local z = st.psd -- 256 scratch + Mdct.inverse(PLAN256, x, 1, 2, z, 1, -2 * gain) + for n = 0, 63 do + y[n + 1] = -z[n + 193] + end + for n = 64, 255 do + y[n + 1] = z[n - 63] + end + Mdct.inverse(PLAN256, x, 2, 2, z, 1, -2 * gain) + for n = 0, 191 do + y[257 + n] = z[n + 65] + end + for n = 192, 255 do + y[257 + n] = -z[n - 191] + end + else + Mdct.inverse(PLAN512, x, 1, 1, y, 1, -2 * gain) + end + local p = base + for n = 1, 256 do + out[p] = y[n] * w[n] + d[n] + d[n] = y[n + 256] * w[n + 256] + p =p+ step + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- the output index of each slot (1 .. 5 full bandwidth, 6 LFE) in WAVE order: L R C LFE surrounds +local ORDER= { + [0] = { 1, 2 }, + { 1 }, + { 1, 2 }, + { 1, 3, 2 }, + { 1, 2, 3 }, + { 1, 3, 2, 4 }, + { 1, 2, 3, 4 }, + { 1, 3, 2, 4, 5 }, +} +local HAS_C = { [0] = false, true, false, true, false, true, false, true } + +-- frame(st, buf, len, drc) -> 1536 | nil, message: decodes the syncframe at buf[0 .. len) (padded by PAD bytes) +-- into st.pcm (1536 * st.channels interleaved floats, WAVE order). drc: the dynamic range scale (0 = off, 1 = full). +function Decode.frame(st, buf, len, drc) +if len < 8 or buffer.len(buf) < len + Decode.PAD then + return nil, "truncated frame" + end + B, P = buf, 32 + local fscod = bits(2) + bits(6) + local bsid = bits(5) + if bsid > 8 then + B = buffer.create(0) + return nil, "unsupported: bsid " .. bsid .. (bsid > 10 and" (E-AC-3)" or" (reduced sample rate)") + end + if fscod == 3 then + B = buffer.create(0) + return nil, "bad sample rate code" + end + bits(3) -- bsmod + local acmod = bits(3) + if band(acmod, 1) == 1 and acmod ~= 1 then + bits(2) + end + if band(acmod, 4) ~= 0 then + bits(2) + end + if acmod == 2 then + bits(2) + end + local lfeon = bits(1) == 1 + for _ = 1, acmod == 0 and 2 or 1 do + bits(5) + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(8) + end + if bits(1) == 1 then + bits(7) + end + end + bits(2) + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + bits(14) + end + if bits(1) == 1 then + P =P+ (bits(6) + 1) * 8 + end + local nf = NFCHANS[acmod] + local channels = nf + (lfeon and 1 or 0) + if st.acmod ~= acmod or st.lfeon ~= lfeon then + -- a new channel layout: build the output map and forget the overlap + local order = ORDER[acmod] + local map = table.create(6, 0) + local nfront = HAS_C[acmod] and 3 or(acmod == 1 and 1 or 2 +) for ch = 1, nf do + local o = order[ch] + map[ch] = (lfeon and o > nfront and((o + 1 ))or(o +)) end + if lfeon then + map[LFE] = nfront + 1 + end + st.map = map + st.pcm = table.create(1536 * channels, 0) + Decode.reset(st) + end + st.fscod, st.acmod, st.lfeon, st.nfchans, st.channels, st.drc = fscod, acmod, lfeon, nf, channels, drc + local pcm = st.pcm + local limit = len * 8 - 16 -- crc2 + for blk = 0, 5 do + st.blocks[blk + 1] = P + local ok, err = audblk(st, blk, limit) + if not ok then + B = buffer.create(0) + return nil, err + end + local base = blk * 256 * channels + for ch = 1, nf do + local g = st.dynrng[acmod == 0 and ch == 2 and 2 or 1] + synth(st, ch, st.blksw[ch], g, pcm, base + st.map[ch], channels) + end + if lfeon then + synth(st, LFE, false, st.dynrng[1], pcm, base + st.map[LFE], channels) + end + end + B = buffer.create(0) + return 1536, nil +end + +return Decode +end +__FILES["codecs/audio/Ac3/Tables"] = function() +--!strict +-- codecs/audio/Ac3/Tables: the AC-3 constant tables, transcribed from ATSC A/52:2018 (Digital Audio Compression +-- Standard) section 7.2.3 (bit allocation: slowdec, fastdec, slowgain, dbpbtab, floortab, fastgain, bndtab / bndsz, +-- latab, hth, baptab) and section 5.4 (frame sizes). masktab is derived from bndtab / bndsz, the transform window +-- (Table 7.33) is the Kaiser-Bessel-derived window with alpha 5 (codecs/audio/Mdct), which Table 7.33 rounds to five +-- decimals. No third-party code. +local T = {} + +T.SLOWDEC = { 0x0f, 0x11, 0x13, 0x15 } +T.FASTDEC = { 0x3f, 0x53, 0x67, 0x7b } +T.SLOWGAIN = { 0x540, 0x4d8, 0x478, 0x410 } +T.DBPBTAB = { 0x000, 0x700, 0x900, 0xb00 } +T.FLOORTAB = { 0x2f0, 0x2b0, 0x270, 0x230, 0x1f0, 0x170, 0x0f0, 0xf800 } +T.FASTGAIN = { 0x080, 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400 } + +-- the 50 bit allocation bands: first bin and width (Table 7.12) +T.BNDTAB = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 31, 34, 37, 40, 43, 46, 49, 55, 61, 67, 73, 79, 85, 97, 109, 121, 133, 157, 181, 205, 229, +} +T.BNDSZ = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 24, 24, 24, 24, 24, +} +-- masktab[bin + 1]: the band of each bin (Table 7.13; bins 253 .. 255 map to 0) +T.MASKTAB = table.create(256, 0) +for b = 1, 50 do + for k = T.BNDTAB[b], T.BNDTAB[b] + T.BNDSZ[b] - 1 do + T.MASKTAB[k + 1] = b - 1 + end +end + +-- log-addition table (Table 7.14) +T.LATAB = { + 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003b, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0034, 0x0034, 0x0033, 0x0032, + 0x0031, 0x0030, 0x002f, 0x002f, 0x002e, 0x002d, 0x002c, 0x002c, 0x002b, 0x002a, 0x0029, 0x0029, 0x0028, 0x0027, 0x0026, 0x0026, + 0x0025, 0x0024, 0x0024, 0x0023, 0x0023, 0x0022, 0x0021, 0x0021, 0x0020, 0x0020, 0x001f, 0x001e, 0x001e, 0x001d, 0x001d, 0x001c, + 0x001c, 0x001b, 0x001b, 0x001a, 0x001a, 0x0019, 0x0019, 0x0018, 0x0018, 0x0017, 0x0017, 0x0016, 0x0016, 0x0015, 0x0015, 0x0015, + 0x0014, 0x0014, 0x0013, 0x0013, 0x0013, 0x0012, 0x0012, 0x0012, 0x0011, 0x0011, 0x0011, 0x0010, 0x0010, 0x0010, 0x000f, 0x000f, + 0x000f, 0x000e, 0x000e, 0x000e, 0x000d, 0x000d, 0x000d, 0x000d, 0x000c, 0x000c, 0x000c, 0x000c, 0x000b, 0x000b, 0x000b, 0x000b, + 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0009, 0x0009, 0x0009, 0x0009, 0x0009, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, + 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0006, 0x0005, 0x0005, + 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0005, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, + 0x0004, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0003, 0x0002, + 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, + 0x0002, 0x0002, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, + 0x0001, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, +} + +-- hearing threshold per band (Table 7.15): HTH[fscod + 1][band + 1] +T.HTH = { + { + 0x04d0, 0x04d0, 0x0440, 0x0400, 0x03e0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0370, 0x0370, + 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, + 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, 0x0340, 0x0390, 0x03e0, 0x0420, + 0x0460, 0x0490, 0x04a0, 0x0460, 0x0440, 0x0440, 0x0520, 0x0800, 0x0840, 0x0840, + }, + { + 0x04f0, 0x04f0, 0x0460, 0x0410, 0x03e0, 0x03d0, 0x03c0, 0x03b0, 0x03b0, 0x03a0, + 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, + 0x0370, 0x0370, 0x0360, 0x0360, 0x0350, 0x0350, 0x0340, 0x0340, 0x0320, 0x0310, + 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0320, 0x0350, 0x0390, 0x03e0, + 0x0420, 0x0450, 0x04a0, 0x0490, 0x0460, 0x0440, 0x0480, 0x0630, 0x0840, 0x0840, + }, + { + 0x0580, 0x0580, 0x04b0, 0x0450, 0x0420, 0x03f0, 0x03e0, 0x03d0, 0x03c0, 0x03b0, + 0x03b0, 0x03b0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, 0x03a0, + 0x0390, 0x0390, 0x0390, 0x0390, 0x0380, 0x0380, 0x0380, 0x0370, 0x0360, 0x0350, + 0x0340, 0x0330, 0x0320, 0x0310, 0x0300, 0x02f0, 0x02f0, 0x02f0, 0x0300, 0x0310, + 0x0330, 0x0350, 0x03c0, 0x0410, 0x0470, 0x04a0, 0x0460, 0x0440, 0x0450, 0x04e0, + }, +} + +-- bit allocation pointers (Table 7.16) +T.BAPTAB = { + 0, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, + 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, +} + +-- words per syncframe (Table 5.18) for frmsizecod // 2 (the nominal bit rate in kbps) and fscod: 48 kHz = 2 x rate, +-- 32 kHz = 3 x rate, 44.1 kHz = floor(rate x 1536000 / 705600) + (frmsizecod & 1) +T.BITRATES = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640 } +T.RATES = { 48000, 44100, 32000 } + +function T.frameWords(fscod, frmsizecod) +local kbps = T.BITRATES[math.floor(frmsizecod / 2 )+ 1] + if not kbps or fscod > 2 then + return 0 + end + if fscod == 0 then + return 2 * kbps + elseif fscod == 2 then + return 3 * kbps + end + return math.floor(kbps * 1536000 / 705600 )+ frmsizecod % 2 +end + +return T +end +__FILES["codecs/audio/Adpcm"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/audio/Adpcm: the 4-bit ADPCM family, decode (and encode where it is cheap). New in rosetta; the IMA and +-- MS block decoders moved here from audio/wav/Codecs (wav-luau, same author). ADX coefficients, PS-ADPCM and Nintendo +-- DSP decoding follow vgmstream r2117 (ISC licence, licenses/vgmstream-LICENSE.txt) so the output is bit-exact with it: +-- the ADX scale + 1 and the version 3 rounding, PS-ADPCM's float filter (exact in integers below 2^17), DSP's 1024 +-- rounding. Codec kernels only: the formats (wav, aiff, caf, adx, vag, brstm, adpcm, ...) walk the layouts. +-- +-- Decoders write f32 (sample / 32768) to dst at float index d, every ds floats (interleaving), and keep their running +-- state in a caller-owned buffer `st` at byte offset `so` (i32 pairs: IMA pred / step index, the others hist1 / hist2), +-- so a decoder can stop between calls and snapshot the state for seeking (codecs/audio/Adpcm/Decoder). +-- +-- Adpcm.ima(src, p, q0, qs, count, hi, st, so, dst, d, ds) -- IMA nibbles: count samples, nibble q0, q0+qs, ... +-- Adpcm.imaQt(src, p, st, so, dst, d, ds) -- Apple ima4: one 34-byte packet -> 64 samples +-- Adpcm.imaWav(src, off, avail, ch, spb, dst, d) -> frames -- Microsoft IMA block (WAV / AVI) +-- Adpcm.msBlock(src, off, avail, ch, spb, dst, d, coefs, ncoef, st) -> frames -- MS ADPCM block +-- Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, st, so, dst, d, ds) -- CRI ADX: 18-byte frames, 32 samples +-- Adpcm.adxCoefs(cutoff, rate) -> c1, c2 +-- Adpcm.psx(src, p, pstride, nframes, st, so, dst, d, ds) -- Sony PS-ADPCM (VAG): 16-byte frames, 28 samples +-- Adpcm.dsp(src, p, count, coefs, co, st, so, dst, d, ds) -- Nintendo DSP: 8-byte frames, 14 samples +-- Adpcm.modplug(src, p, count, dst, d) -- ModPlug ADPCM (XM / MOD samples) +-- Adpcm.swfFrames(src, p, n, ch) -> frames -- Flash (SWF / FLV) ADPCM: one packet's length +-- Adpcm.swf(src, p, n, ch, dst, d) -> frames -- Flash ADPCM: one packet of n bytes +-- encoders: imaEncode, imaWavEncode, msEncode, adxEncode, psxEncode, dspEncode (see each) +-- +-- Every function reads only the bytes its arguments describe: the caller checks the ranges (byte counts per call are +-- documented on each). Never throws. +local readu8, readi16, readu16, readi32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readi32 +local writef32, readf32, writei32, writeu8, writeu16 = buffer.writef32, buffer.readf32, buffer.writei32, buffer.writeu8, buffer.writeu16 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift +local floor = math.floor + +local Adpcm = {} + +-- ------------------------------------------------------------------------------------------------ IMA +local IMA_STEP = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, +} +local IMA_ADJ = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 } +-- IMA_DIFF[index * 8 + (nibble & 7) + 1]: the shift-and-add difference (step/8 + bits of step/4, step/2, step), as +-- the IMA reference computes it (not (2n + 1) * step / 8, which rounds differently) +local IMA_DIFF = table.create(89 * 8, 0) +-- IMA_NEXT[index * 16 + nibble + 1]: the next step index +local IMA_NEXT = table.create(89 * 16, 0) +for i = 0, 88 do + local step = IMA_STEP[i + 1] + for n = 0, 7 do + local d = rshift(step, 3) + if band(n, 1) ~= 0 then + d =d+ rshift(step, 2) + end + if band(n, 2) ~= 0 then + d =d+ rshift(step, 1) + end + if band(n, 4) ~= 0 then + d =d+ step + end + IMA_DIFF[i * 8 + n + 1] = d + end + for n = 0, 15 do + IMA_NEXT[i * 16 + n + 1] = math.clamp(i + IMA_ADJ[n + 1], 0, 88) + end +end +Adpcm.IMA_STEP = IMA_STEP + +-- ima: `count` samples of one channel from a nibble stream at byte p: nibble q0, q0 + qs, q0 + 2 qs, ... (nibble q is +-- in byte p + q // 2, the low half first unless hi). State: st[so] predictor, st[so + 4] step index. Reads bytes +-- p .. p + (q0 + (count - 1) * qs) // 2. +function Adpcm.ima(src, p, q0, qs, count, hi, st, so, + dst, d, ds) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + local o = d * 4 + local os = ds * 4 + for _ = 1, count do + local b = readu8(src, p + rshift(q, 1)) + local nib + if (band(q, 1) == 0) == hi then + nib = rshift(b, 4) + else + nib = band(b, 15) + end + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred =pred- diff + if pred < -32768 then + pred = -32768 + end + else + pred =pred+ diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o, pred / 32768) + o =o+ os + q =q+ qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaQt: one Apple ima4 packet (34 bytes at p: a big-endian header, the predictor's top 9 bits and the 7-bit step +-- index, then 64 nibbles low first) -> 64 samples. Apple's decoders keep the running full-precision predictor while +-- the header agrees with it (the same step index, the predictor within 127): st carries it from packet to packet +-- (zeros before the first). +function Adpcm.imaQt(src, p, st, so, dst, d, ds) + local h = readu8(src, p) * 256 + readu8(src, p + 1) + local pred = band(h, 0xFF80) + if pred >= 32768 then + pred =pred- 65536 + end + local index = band(h, 0x7F) + if index ~= readi32(st, so + 4) or math.abs(pred - readi32(st, so)) > 0x7F then + writei32(st, so, pred) + writei32(st, so + 4, index) + end + Adpcm.ima(src, p + 2, 0, 1, 64, false, st, so, dst, d, ds) +end + +-- imaWav: one Microsoft IMA ADPCM block (WAV / AVI) at src[off]: per channel a 4-byte header (s16 predictor = the +-- first sample, u8 step index, pad), then groups of 4 bytes (8 nibbles, low first) per channel in turn. avail: the +-- bytes present (a truncated last block decodes the whole groups it has). Writes interleaved frames to dst from float +-- index d; returns the frame count (<= spb). +function Adpcm.imaWav(src, off, avail, ch, spb, dst, d) +if avail < 4 * ch then + return 0 + end + local groups = math.floor((avail - 4 * ch) / (4 * ch) +) local frames = math.min(spb, 1 + groups * 8) + local o = d * 4 + for c = 0, ch - 1 do + local pred = readi16(src, off + c * 4) + local index = math.min(readu8(src, off + c * 4 + 2), 88) + writef32(dst, o + c * 4, pred / 32768) + local f = 1 + local g = 0 + while f < frames do + local p = off + 4 * ch + (g * ch + c) * 4 + local k = 0 + while k < 8 and f < frames do + local b = readu8(src, p + rshift(k, 1)) + local nib = (band(k, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) +)})[1] local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + if nib >= 8 then + pred =pred- diff + if pred < -32768 then + pred = -32768 + end + else + pred =pred+ diff + if pred > 32767 then + pred = 32767 + end + end + index = IMA_NEXT[index * 16 + nib + 1] + writef32(dst, o + (f * ch + c) * 4, pred / 32768) + f =f+ 1 + k =k+ 1 + end + g =g+ 1 + end + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ MS ADPCM +local MS_ADAPT = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 } +Adpcm.MS_COEF1 = { 256, 512, 0, 192, 240, 460, 392 } +Adpcm.MS_COEF2 = { 0, -256, 0, 64, 0, -208, -232 } + +-- msBlock: one MS ADPCM block: per channel u8 predictor index, s16 delta, s16 sample 1, s16 sample 2 (each field for +-- every channel in turn), then nibbles high first, channels interleaved per nibble. coefs: i32 pairs (coef1, coef2) x +-- ncoef (256 = 1.0). state: 20 * ch bytes of scratch. avail: the bytes present. Writes interleaved frames to dst from +-- float index d; returns the frame count (<= spb). +function Adpcm.msBlock(src, off, avail, ch, spb, dst, d, + coefs, ncoef, state) +local hdr = 7 * ch + if avail < hdr or ncoef < 1 then + return 0 + end + local frames = math.min(spb, 2 + math.floor(((avail - hdr) * 2) / ch)) + local o = d * 4 + for c = 0, ch - 1 do + local pi = math.min(readu8(src, off + c), ncoef - 1) + local idelta = readi16(src, off + ch + c * 2) + local s1 = readi16(src, off + 3 * ch + c * 2) + local s2 = readi16(src, off + 5 * ch + c * 2) + local so = c * 20 + writei32(state, so, readi32(coefs, pi * 8)) + writei32(state, so + 4, readi32(coefs, pi * 8 + 4)) + writei32(state, so + 8, idelta) + writei32(state, so + 12, s1) + writei32(state, so + 16, s2) + writef32(dst, o + c * 4, s2 / 32768) + if frames > 1 then + writef32(dst, o + (ch + c) * 4, s1 / 32768) + end + end + local total = (frames - 2) * ch + for k = 0, total - 1 do + local b = readu8(src, off + hdr + rshift(k, 1)) + local nib = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) +)})[1] local so = (k % ch) * 20 + local c1, c2 = readi32(state, so), readi32(state, so + 4) + local idelta = readi32(state, so + 8) + local s1, s2 = readi32(state, so + 12), readi32(state, so + 16) + local p = s1 * c1 + s2 * c2 + p = (p >= 0 and{(math.floor(p / 256 ))}or{(-(math.floor((-p) / 256)) +)})[1] p =p+ ((nib >= 8 and((nib - 16 ))or(nib))) * idelta + if p > 32767 then + p = 32767 + elseif p < -32768 then + p = -32768 + end + idelta = math.floor((MS_ADAPT[nib + 1] * idelta) / 256 +) if idelta < 16 then + idelta = 16 + elseif idelta > 2796202 then -- INT_MAX / 768 + idelta = 2796202 + end + writei32(state, so + 8, idelta) + writei32(state, so + 12, p) + writei32(state, so + 16, s1) + writef32(dst, o + (2 * ch + k) * 4, p / 32768) + end + return frames +end + +-- ------------------------------------------------------------------------------------------------ CRI ADX +local F32 = buffer.create(4) +local function f32(x) +writef32(F32, 0, x) + return readf32(F32, 0) +end + +-- adxCoefs(cutoff, rate) -> coef1, coef2 (fixed point, 12 fractional bits): the 2-pole high-pass predictor from the +-- header's cutoff frequency, in single precision as CRI's decoders (and vgmstream) compute it +function Adpcm.adxCoefs(cutoff, rate) +if rate <= 0 then + return 0, 0 + end + local z = f32(math.cos(f32(2 * math.pi * cutoff / rate))) + local a = f32(math.sqrt(2) - z) + local b = f32(math.sqrt(2) - 1) + local c = f32(f32(a - f32(math.sqrt(f32(f32(a + b) * f32(a - b))))) / b) + local c1 = c * 8192 + local c2 = f32(c * c) * -4096 + c1 = (c1 >= 0 and{(floor(c1) )}or{(-floor(-c1) +)})[1] c2 = (c2 >= 0 and{(floor(c2) )}or{(-floor(-c2) +)})[1] return c1, c2 +end + +-- adx: nframes 18-byte frames of one channel (s16 big-endian scale, 32 nibbles high first), pstride bytes apart from +-- p. v3: the version 3 rounding (each product shifted on its own). A scale of 0x8001 (CRI's end marker) decodes as +-- silence. Reads p .. p + (nframes - 1) * pstride + 17; writes 32 * nframes samples. +function Adpcm.adx(src, p, pstride, nframes, c1, c2, v3, + st, so, dst, d, ds) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local scale = readu8(src, fp) * 256 + readu8(src, fp + 1) + if scale == 0x8001 then + scale = 0 + elseif scale >= 32768 then + scale =scale- 65535 -- the signed value + 1 + else + scale =scale+ 1 + end + for k = 0, 31 do + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) +)})[1] if n >= 8 then + n =n- 16 + end + local s + if v3 then + s = n * scale + math.floor((c1 * h1) / 4096 )+ math.floor((c2 * h2) / 4096 +) else + s = n * scale + math.floor((c1 * h1 + c2 * h2) / 4096 +) end + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o =o+ os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ PS-ADPCM +local PSX1 = { 0, 60, 115, 98, 122 } +local PSX2 = { 0, 0, -52, -55, -60 } + +-- the filter term (c1 * h1 + c2 * h2) / 64 * 256 truncated, as vgmstream's single-precision float code computes it: +-- exact in integers while the products fit a float's 24 bits +local function psxPred(f, h1, h2) +local x = PSX1[f] * h1 + PSX2[f] * h2 + if h1 > -65536 and h1 < 65536 and h2 > -65536 and h2 < 65536 then + return 4 * x + end + local v = f32(f32(f32(PSX1[f] / 64) * h1) + f32(f32(PSX2[f] / 64) * h2)) * 256 + return (v >= 0 and{(floor(v) )}or{(-floor(-v) +)})[1]end + +-- psx: nframes 16-byte frames of one channel (filter << 4 | shift, flags, 28 nibbles low first), pstride bytes apart +-- from p. Filters past 4 decode as 0 and shifts past 12 as 9 (as vgmstream); a frame with flags 7 is silence. The +-- history keeps the unclipped value. Reads p .. p + (nframes - 1) * pstride + 15; writes 28 * nframes samples. +function Adpcm.psx(src, p, pstride, nframes, st, so, dst, + d, ds) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + for f = 0, nframes - 1 do + local fp = p + f * pstride + local head = readu8(src, fp) + local filter = rshift(head, 4) + local shift = band(head, 15) + if filter > 4 then + filter = 0 + end + if shift > 12 then + shift = 9 + end + local mul = 2 ^ (20 - shift) + local fi = filter + 1 + local silent = band(readu8(src, fp + 1), 15) == 7 + for k = 0, 27 do + local s = 0 + if not silent then + local b = readu8(src, fp + 2 + rshift(k, 1)) + local n = (band(k, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) +)})[1] if n >= 8 then + n =n- 16 + end + s = math.floor((n * mul + psxPred(fi, h1, h2)) / 256 +) end + h2 = h1 + h1 = s + if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + writef32(dst, o, s / 32768) + o =o+ os + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ Nintendo DSP +-- dsp: count samples of one channel from 8-byte frames at p (predictor << 4 | scale shift, 14 nibbles high first). +-- coefs: 16 i32 at byte co (8 pairs, 11 fractional bits); a predictor index past 7 uses pair 7. Reads p .. +-- p + ceil(count / 14) * 8 - 1. +function Adpcm.dsp(src, p, count, coefs, co, st, so, + dst, d, ds) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local o = d * 4 + local os = ds * 4 + local done = 0 + local fp = p + while done < count do + local head = readu8(src, fp) + local pi = math.min(rshift(head, 4), 7) + local scale = 2 ^ band(head, 15) * 2048 + local c1, c2 = readi32(coefs, co + pi * 8), readi32(coefs, co + pi * 8 + 4) + local n14 = math.min(14, count - done) + for k = 0, n14 - 1 do + local b = readu8(src, fp + 1 + rshift(k, 1)) + local n = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) +)})[1] if n >= 8 then + n =n- 16 + end + local s = math.floor((n * scale + 1024 + c1 * h1 + c2 * h2) / 2048 +) if s > 32767 then + s = 32767 + elseif s < -32768 then + s = -32768 + end + h2 = h1 + h1 = s + writef32(dst, o, s / 32768) + o =o+ os + end + done =done+ n14 + fp =fp+ 8 + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ encoders +-- the nearest s16 to x * 32768 (NaN -> 0) +local function toS16(x) +local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end +Adpcm.toS16 = toS16 + +-- the IMA nibble for x from (pred, index): the one whose decoded value lands nearest (greedy, all 16 tried) +local function imaNibble(x, pred, index) +local base = index * 8 + 1 + local best, bestErr = 0, math.huge + for m = 0, 7 do + local diff = IMA_DIFF[base + m] + local up = math.min(pred + diff, 32767) + local e = math.abs(x - up) + if e < bestErr then + best, bestErr = m, e + end + local down = math.max(pred - diff, -32768) + e = math.abs(x - down) + if e < bestErr then + best, bestErr = m + 8, e + end + end + return best +end + +-- imaEncode: count samples of one channel, f32 at float index xi every xs floats of x, into nibbles q0, q0 + qs, ... +-- of out at byte p (the other half of each byte is kept). State as Adpcm.ima. Writes bytes p .. +-- p + (q0 + (count - 1) * qs) // 2. +function Adpcm.imaEncode(x, xi, xs, count, st, so, out, + p, q0, qs, hi) + local pred = readi32(st, so) + local index = math.clamp(readi32(st, so + 4), 0, 88) + local q = q0 + for i = 0, count - 1 do + local v = toS16(readf32(x, (xi + i * xs) * 4)) + local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = (nib >= 8 and{(math.max(pred - diff, -32768) )}or{(math.min(pred + diff, 32767) +)})[1] index = IMA_NEXT[index * 16 + nib + 1] + local bp = p + rshift(q, 1) + local b = readu8(out, bp) + if (band(q, 1) == 0) == hi then + b = bor(band(b, 0x0F), lshift(nib, 4)) + else + b = bor(band(b, 0xF0), nib) + end + writeu8(out, bp, b) + q =q+ qs + end + writei32(st, so, pred) + writei32(st, so + 4, index) +end + +-- imaWavEncode: one Microsoft IMA block of spb frames (spb = 1 + 8k) from interleaved f32 x at frame xf (frames +-- available: n; the rest is padded with the last sample) to out[off] (4 * ch + (spb - 1) / 2 * ch bytes). st: 8 * ch +-- bytes carrying the step index from block to block. +function Adpcm.imaWavEncode(x, xf, n, ch, spb, st, out, off) + local groups = math.floor((spb - 1) / 8 +) for c = 0, ch - 1 do + local so = c * 8 + local first = (n > 0 and{(toS16(readf32(x, (xf * ch + c) * 4)) )}or{0 +})[1] writei32(st, so, first) + local index = math.clamp(readi32(st, so + 4), 0, 88) + writei32(st, so + 4, index) + buffer.writei16(out, off + c * 4, first) + writeu8(out, off + c * 4 + 2, index) + writeu8(out, off + c * 4 + 3, 0) + local pred = first + for g = 0, groups - 1 do + local gp = off + 4 * ch + (g * ch + c) * 4 + for k = 0, 7 do + local f = 1 + g * 8 + k + local v = (f < n and{(toS16(readf32(x, ((xf + f) * ch + c) * 4)) )}or{pred +})[1] local nib = imaNibble(v, pred, index) + local diff = IMA_DIFF[index * 8 + band(nib, 7) + 1] + pred = (nib >= 8 and{(math.max(pred - diff, -32768) )}or{(math.min(pred + diff, 32767) +)})[1] index = IMA_NEXT[index * 16 + nib + 1] + local bp = gp + rshift(k, 1) + if band(k, 1) == 0 then + writeu8(out, bp, nib) + else + writeu8(out, bp, bor(readu8(out, bp), lshift(nib, 4))) + end + end + end + writei32(st, so + 4, index) + end +end + +-- one MS ADPCM channel run for the encoder: the nibbles for samples 2 .. n - 1 with predictor (c1, c2) and the first +-- delta; returns the squared error and the nibbles in nibs (when given) +local function msTrial(xs, n, c1, c2, delta0, nibs) +local s1, s2 = xs[2], xs[1] + local idelta = delta0 + local err = 0 + for i = 3, n do + local p = s1 * c1 + s2 * c2 + p = (p >= 0 and{(math.floor(p / 256 ))}or{(-(math.floor((-p) / 256)) +)})[1] local e = xs[i] - p + local nib = (e >= 0 and{(math.floor((e + math.floor(idelta / 2)) / idelta ))}or{(-(math.floor((-e + math.floor(idelta / 2)) / idelta)) +)})[1] nib = math.clamp(nib, -8, 7) + local v = math.clamp(p + nib * idelta, -32768, 32767) + err =err+ (xs[i] - v) * (xs[i] - v) + if nibs then + nibs[i] = band(nib, 15) + end + idelta = math.clamp(math.floor((MS_ADAPT[band(nib, 15) + 1] * idelta) / 256), 16, 2796202) + s2 = s1 + s1 = v + end + return err +end + +-- msEncode: one MS ADPCM block of spb frames (standard 7 coefficient pairs) from interleaved f32 x at frame xf +-- (frames available: n; the rest is padded with silence) to out[off] (7 * ch + (spb - 2) * ch / 2 bytes). Each channel +-- takes the predictor with the least error. +function Adpcm.msEncode(x, xf, n, ch, spb, out, off) + local C1, C2 = Adpcm.MS_COEF1, Adpcm.MS_COEF2 + local xs = table.create(spb, 0) + local nibs = table.create(spb, 0) + local all = table.create(spb * ch, 0) + for c = 0, ch - 1 do + for i = 1, spb do + xs[i] = (i <= n and{(toS16(readf32(x, ((xf + i - 1) * ch + c) * 4)) )}or{0 +})[1] end + -- the first delta from the first steps + local sum = 0 + for i = 3, math.min(spb, 10) do + sum =sum+ math.abs(xs[i] - xs[i - 1]) + end + local delta0 = math.clamp(math.floor(sum / 16), 16, 32767) + local best, bestErr = 1, math.huge + for k = 1, 7 do + local e = msTrial(xs, spb, C1[k], C2[k], delta0, nil) + if e < bestErr then + best, bestErr = k, e + end + end + msTrial(xs, spb, C1[best], C2[best], delta0, nibs) + writeu8(out, off + c, best - 1) + writeu16(out, off + ch + c * 2, delta0) + buffer.writei16(out, off + 3 * ch + c * 2, xs[2] or 0) + buffer.writei16(out, off + 5 * ch + c * 2, xs[1]) + for i = 3, spb do + all[(i - 3) * ch + c + 1] = nibs[i] + end + end + local total = (spb - 2) * ch + for k = 0, total - 1, 2 do + writeu8(out, off + 7 * ch + math.floor(k / 2), all[k + 1] * 16 + (all[k + 2] or 0)) + end +end + +-- one ADX frame for the encoder: the squared error of encoding xs[1..32] with scale from (h1, h2) (v4 rounding), and +-- the nibbles in nibs when given; returns the error and the new history +local function adxTrial(xs, scale, c1, c2, h1, h2, nibs) +local err = 0 + for k = 1, 32 do + local pred = math.floor((c1 * h1 + c2 * h2) / 4096 +) local e = xs[k] - pred + local n = (e >= 0 and{(math.floor((e + math.floor(scale / 2)) / scale ))}or{(-(math.floor((-e + math.floor(scale / 2)) / scale)) +)})[1] n = math.clamp(n, -8, 7) + local s = math.clamp(n * scale + pred, -32768, 32767) + err =err+ (xs[k] - s) * (xs[k] - s) + if nibs then + nibs[k] = band(n, 15) + end + h2 = h1 + h1 = s + end + return err, h1, h2 +end + +-- adxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 32) ADX frames +-- (v4 rounding, the scale stored minus one as CRI's decoders add it back) at out[p], pstride bytes apart; the frame +-- past count is padded with silence. State as Adpcm.adx. +function Adpcm.adxEncode(x, xi, xs, count, c1, c2, st, so, + out, p, pstride) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(32, 0) + local nibs = table.create(32, 0) + for f = 0, math.floor((count + 31) / 32 )- 1 do + local peak = 0 + local a, b = h1, h2 + for k = 1, 32 do + local i = f * 32 + k - 1 + local s = (i < count and{(toS16(readf32(x, (xi + i * xs) * 4)) )}or{0 +})[1] v[k] = s + peak = math.max(peak, math.abs(s - math.floor((c1 * a + c2 * b) / 4096))) + b = a + a = s + end + -- the scale that covers the open-loop residual peak, and a few around it, closed loop + local base = math.max(1, math.floor((peak + 6) / 7)) + local best, bestErr = base, math.huge + for _, m in __iter({ 1, 0.75, 1.25, 0.5, 1.6 }) do + local sc = math.clamp(floor(base * m + 0.5), 1, 0x7FFF) + local e = adxTrial(v, sc, c1, c2, h1, h2, nil) + if e < bestErr then + best, bestErr = sc, e + end + end + local _, n1, n2 = adxTrial(v, best, c1, c2, h1, h2, nibs) + h1, h2 = n1, n2 + local fp = p + f * pstride + writeu8(out, fp, rshift(best - 1, 8)) + writeu8(out, fp + 1, band(best - 1, 255)) + for k = 0, 15 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] * 16 + nibs[k * 2 + 2]) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- psxEncode: count samples of one channel (f32 at float index xi every xs floats of x) as ceil(count / 28) PS-ADPCM +-- frames at out[p], pstride bytes apart, flags byte 0 (the caller sets loop / end flags); every filter and shift is +-- tried per frame against Adpcm.psx's decoding, the least squared error wins. State as Adpcm.psx. +function Adpcm.psxEncode(x, xi, xs, count, st, so, out, + p, pstride) + local h1, h2 = readi32(st, so), readi32(st, so + 4) + local v = table.create(28, 0) + local nibs = table.create(28, 0) + for f = 0, math.floor((count + 27) / 28 )- 1 do + for k = 1, 28 do + local i = f * 28 + k - 1 + v[k] = (i < count and{(toS16(readf32(x, (xi + i * xs) * 4)) )}or{0 +})[1] end + local bestErr, bestHead = math.huge, 0 + for fi = 1, 5 do + for shift = 0, 12 do + local mul = 2 ^ (20 - shift) + local a, b = h1, h2 + local err = 0 + for k = 1, 28 do + local pred = psxPred(fi, a, b) + local n = floor((v[k] * 256 - pred) / mul + 0.5) + n = n > 7 and 7 or(n < -8 and-8 or n +) local s = math.floor((n * mul + pred) / 256 +) local c = s > 32767 and 32767 or(s < -32768 and-32768 or s +) err =err+ (v[k] - c) * (v[k] - c) + if err >= bestErr then + break + end + b = a + a = s + end + if err < bestErr then + bestErr, bestHead = err, (fi - 1) * 16 + shift + end + end + end + -- the winner again, for its nibbles and history + local fi, shift = rshift(bestHead, 4) + 1, band(bestHead, 15) + local mul = 2 ^ (20 - shift) + for k = 1, 28 do + local pred = psxPred(fi, h1, h2) + local n = math.clamp(floor((v[k] * 256 - pred) / mul + 0.5), -8, 7) + nibs[k] = band(n, 15) + h2 = h1 + h1 = math.floor((n * mul + pred) / 256 +) end + local fp = p + f * pstride + writeu8(out, fp, bestHead) + writeu8(out, fp + 1, 0) + for k = 0, 13 do + writeu8(out, fp + 2 + k, nibs[k * 2 + 1] + nibs[k * 2 + 2] * 16) + end + end + writei32(st, so, h1) + writei32(st, so + 4, h2) +end + +-- ------------------------------------------------------------------------------------------------ ModPlug +-- modplug: ModPlug / OpenMPT ADPCM samples (XM / MOD sample data marked 0xAD): a table of 16 signed byte deltas at +-- p, then count nibbles (low first) at p + 16, each adding its table delta to a running signed byte (wrapping). +-- Writes count f32 (value / 128) to dst from float index d. Reads p .. p + 16 + ceil(count / 2) - 1. +function Adpcm.modplug(src, p, count, dst, d) + local tab = table.create(16, 0) + for k = 0, 15 do + tab[k + 1] = buffer.readi8(src, p + k) + end + local v = 0 + for i = 0, count - 1 do + local b = readu8(src, p + 16 + rshift(i, 1)) + local nib = (band(i, 1) == 0 and{(band(b, 15) )}or{(rshift(b, 4) +)})[1] v = (v + tab[nib + 1] + 128) % 256 - 128 + writef32(dst, (d + i) * 4, v / 128) + end +end + +-- ------------------------------------------------------------------------------------------------ Flash ADPCM +-- The SWF / FLV ADPCM (SoundFormat 1, Adobe's SWF specification, "ADPCM compression"): an MSB-first bit stream of +-- 2 bits (code size - 2), then blocks of 4096 frames: per channel a signed 16-bit first sample and a 6-bit step +-- index, then 4095 frames of `bits`-bit codes, channels interleaved. A code is IMA generalised to 2..5 bits: sign in +-- the top bit, the magnitude bits adding step, step/2, ... and the final step/2^(bits-1) (as ffmpeg's adpcm_swf and +-- the spec's reference decoder do); the step index moves by SWF_INDEX[bits]. The last block may be short. +local SWF_INDEX= { + { -1, 2 }, + { -1, -1, 2, 4 }, + { -1, -1, -1, -1, 2, 4, 6, 8 }, + { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }, +} + +-- swfFrames: the frame count of one Flash ADPCM packet (n bytes at p, n >= 1) +function Adpcm.swfFrames(src, p, n, ch) +if n < 1 or ch < 1 then + return 0 + end + local bits = rshift(readu8(src, p), 6) + 2 + local total = n * 8 - 2 + local hdr = 22 * ch + local block = hdr + bits * ch * 4095 + local blocks = math.floor(total / block +) local left = total - blocks * block + local frames = blocks * 4096 + if left >= hdr then + frames =frames+ (1 + math.floor((left - hdr) / (bits * ch) +)) end + return frames +end + +-- the k-bit (k <= 16) MSB-first value at bit position pos of src[p ..]; bytes at or past e read as 0 +local function msb(src, p, e, pos, k) +local q = p + rshift(pos, 3) + local v = readu8(src, q) * 65536 + if q + 1 < e then + v =v+ readu8(src, q + 1) * 256 + end + if q + 2 < e then + v =v+ readu8(src, q + 2) + end + return band(rshift(v, 24 - band(pos, 7) - k), lshift(1, k) - 1) +end + +-- swf: one Flash ADPCM packet (n bytes at p, ch channels) -> interleaved f32 frames to dst from float index d; returns +-- the frame count (Adpcm.swfFrames). Reads p .. p + n - 1 only. +function Adpcm.swf(src, p, n, ch, dst, d) +local frames = Adpcm.swfFrames(src, p, n, ch) + if frames == 0 then + return 0 + end + local e = p + n + local bits = rshift(readu8(src, p), 6) + 2 + local tab = SWF_INDEX[bits - 1] + local k0 = lshift(1, bits - 2) + local sign = lshift(1, bits - 1) + local mask = sign - 1 + local pred = table.create(ch, 0) + local index = table.create(ch, 0) + local pos = 2 + local o = d * 4 + local done = 0 + while done < frames do + for c = 1, ch do + local v = msb(src, p, e, pos, 16) + if v >= 32768 then + v =v- 65536 + end + pred[c] = v + index[c] = msb(src, p, e, pos + 16, 6) + pos =pos+ 22 + writef32(dst, o, v / 32768) + o =o+ 4 + end + done =done+ 1 + local m = math.min(4095, frames - done) + for _ = 1, m do + for c = 1, ch do + local code = msb(src, p, e, pos, bits) + pos =pos+ bits + local step = IMA_STEP[math.clamp(index[c], 0, 88) + 1] + local diff = 0 + local k = k0 + while k > 0 do + if band(code, k) ~= 0 then + diff =diff+ step + end + step = rshift(step, 1) + k = rshift(k, 1) + end + diff =diff+ step + local v = pred[c] + if band(code, sign) ~= 0 then + v =v- diff + else + v =v+ diff + end + v = math.clamp(v, -32768, 32767) + pred[c] = v + index[c] = math.clamp(index[c] + tab[band(code, mask) + 1], 0, 88) + writef32(dst, o, v / 32768) + o =o+ 4 + end + end + done =done+ m + end + return frames +end + +return Adpcm +end +__FILES["codecs/audio/Adpcm/Decoder"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- codecs/audio/Adpcm/Decoder: the streaming Decoder (Types.Decoder) over an ADPCM stream cut into packets, for the +-- formats whose state carries from packet to packet (ADX, VAG, BRSTM, raw IMA): codecs/audio/Stream.packets plus +-- exact seeking. The codec state (one buffer the packet decoder advances) is snapshotted at every packet start it +-- passes; a seek restores the snapshot, else the format's own state for that packet (BRSTM's ADPC history), else +-- decodes forward from the nearest earlier snapshot. New in rosetta. +-- +-- local dec, err = Decoder.packets(dec, { -- dec: the Decoder table (sampleRate, channels, frames, ...) +-- count = n, packetFrames = 4096, -- packets of packetFrames frames (the last may be shorter) +-- frames = total, -- output frames +-- state = st, -- the codec state buffer decode advances +-- decode = function(i, out) return frames end, -- packet i (1-based) as interleaved f32 into out from 0 +-- restore = function(i) return false end, -- optional: set st for packet i, true if it could +-- }) +-- +-- The layouts the formats share, each returning the Decoder (dec gets read / seek / position) | nil, Err: +-- Decoder.interleaved(dec, spec) psx / adx / dsp frames (or s16 / s8 PCM), channels interleaved every +-- spec.interleave bytes (VAG, ADX, BRSTM / BCSTM / BFSTM, raw PS-ADPCM) +-- Decoder.nibbles(dec, spec) an IMA nibble stream, channels interleaved by nibble (raw IMA, KVAG) +-- Decoder.blocks(dec, spec) self-contained blocks: "ms" / "ima_wav" (blockAlign bytes), "ima_qt" (34 bytes +-- per channel), raw or inside AIFF-C / CAF +-- +-- Never throws (decode failures end the stream and land in dec.error, see codecs/audio/Stream). +local Err = __include("core/Err") +local Stream = __include("codecs/audio/Stream") +local Adpcm = __include("codecs/audio/Adpcm") + +local Decoder = {} + + + + + + + + + + +function Decoder.packets(dec, spec) +local ch = dec.channels + local pf = spec.packetFrames + local st = spec.state + local out = buffer.create(pf * ch * 4) + local decodeP = spec.decode + local restore = spec.restore + local snaps= {} + local nextPacket = 1 + local function snap(i) + if not snaps[i] then + local b = buffer.create(buffer.len(st)) + buffer.copy(b, 0, st) + snaps[i] = b + end + end + snap(1) + local function decode(i) +if i ~= nextPacket then + if snaps[i] then + buffer.copy(st, 0, snaps[i]) + elseif restore and restore(i) then + -- the format set the state (BRSTM's seek table) + else + local j = i - 1 + while j > 1 and not snaps[j] do + j =j- 1 + end + buffer.copy(st, 0, snaps[j]) + for k = j, i - 1 do + local n, e = decodeP(k, out) + if not n then + return nil, e + end + snap(k + 1) + end + end + end + local n, e = decodeP(i, out) + if n then + nextPacket = i + 1 + snap(i + 1) + end + return n, e + end + return Stream.packets(dec, { + count = spec.count, + start = function(i) +return (i - 1) * pf + end, + decode = decode, + pcm = function() +return out + end, + reset = function() end, + stop = spec.frames, + }) +end + +-- ------------------------------------------------------------------------------------------------ layouts +local FRAME= { psx = 16, adx = 18, dsp = 8, s16be = 2, s16le = 2, s8 = 1 } -- bytes per frame +local SPF= { psx = 28, adx = 32, dsp = 14, s16be = 1, s16le = 1, s8 = 1 } -- samples per frame + +-- PCM samples of one channel into every ds-th float of dst from float d +local function pcm(kind, src, p, n, dst, d, ds) + if kind == "s8" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi8(src, p + k) / 128) + end + elseif kind == "s16le" then + for k = 0, n - 1 do + buffer.writef32(dst, (d + k * ds) * 4, buffer.readi16(src, p + k * 2) / 32768) + end + else + for k = 0, n - 1 do + local v = buffer.readu8(src, p + k * 2) * 256 + buffer.readu8(src, p + k * 2 + 1) + buffer.writef32(dst, (d + k * ds) * 4, ((v >= 32768 and((v - 65536 ))or(v))) / 32768) + end + end +end + +-- interleaved(dec, spec) -> Decoder | nil, Err + + + + + + + + + + + + + + + + +function Decoder.interleaved(dec, spec) +local ch = dec.channels + local kind = spec.kind + local fsize, spf = FRAME[kind], SPF[kind] + local il = spec.interleave + local last = spec.lastInterleave or il + if not fsize or ch < 1 or il < fsize or il % fsize ~= 0 or last < 0 or last > il then + return nil, Err.new(Err.CORRUPT, "bad interleave " .. tostring(il)) + end + local buf, base, size = spec.buf, spec.offset, spec.size + local rowBytes = il * ch + -- rows: the full ones, then the last (which may be shorter, and may be cut by a truncated file) + local rows = math.max(1, math.ceil(size / rowBytes)) + local function rowFrames(r) +local width = (r == rows - 1 and{last }or{il +})[1] -- channel c sits at c * width in the row: the last channel is the one a cut file shortens + local per = math.clamp(size - r * rowBytes - (ch - 1) * width, 0, width) + return (math.floor(per / fsize)) * spf + end + local fullFrames = (math.floor(il / fsize)) * spf + local total = (rows - 1) * fullFrames + rowFrames(rows - 1) + local frames = math.min(spec.frames or total, total) + local st = buffer.create(8 * ch) + if spec.hist then + for c = 0, ch - 1 do + buffer.writei32(st, c * 8, spec.hist[c * 2 + 1] or 0) + buffer.writei32(st, c * 8 + 4, spec.hist[c * 2 + 2] or 0) + end + end + local rowsPer = spec.restore and 1 or math.max(1, math.floor(4096 / fullFrames)) + local pf = rowsPer * fullFrames + local c1, c2, v3, coefs = spec.c1 or 0, spec.c2 or 0, spec.v3 == true, spec.coefs + local restore = spec.restore + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / pf)), + packetFrames = pf, + frames = frames, + state = st, + restore = restore +and function(i) +return restore(i - 1, st) + end +or nil, + decode = function(i, out) +local got = 0 + for r = (i - 1) * rowsPer, math.min(i * rowsPer, rows) - 1 do + local n = math.min(rowFrames(r), frames - r * fullFrames) + if n <= 0 then + break + end + local nf = math.ceil(n / spf) + local width = (r == rows - 1 and{last }or{il +})[1] for c = 0, ch - 1 do + local p = base + r * rowBytes + c * width + local d = got * ch + c + if kind == "psx" then + Adpcm.psx(buf, p, fsize, nf, st, c * 8, out, d, ch) + elseif kind == "adx" then + Adpcm.adx(buf, p, fsize, nf, c1, c2, v3, st, c * 8, out, d, ch) + elseif kind == "dsp" then + Adpcm.dsp(buf, p, n, coefs , c * 64, st, c * 8, out, d, ch) + else + pcm(kind, buf, p, n, out, d, ch) + end + end + got =got+ n + end + return got, nil + end, + }) +end + +-- nibbles(dec, spec): an IMA stream starting from predictor 0, step index 0, channel c in nibbles c, c + ch, ... + + + + + + + + +function Decoder.nibbles(dec, spec) +local ch = dec.channels + local buf, base = spec.buf, spec.offset + local frames = math.min(spec.frames or math.huge, math.floor((spec.size * 2) / ch)) + local st = buffer.create(8 * ch) + local hi = spec.hi == true + dec.frames = frames + dec.duration = frames / dec.sampleRate + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / 4096)), + packetFrames = 4096, + frames = frames, + state = st, + decode = function(i, out) +local f0 = (i - 1) * 4096 + local n = math.min(4096, frames - f0) + for c = 0, ch - 1 do + Adpcm.ima(buf, base, f0 * ch + c, ch, n, hi, st, c * 8, out, c, ch) + end + return n, nil + end, + }) +end + +-- blockFrames(kind, blockAlign, ch) -> frames per block, or nil when the block cannot hold the headers + + + + + + + + + + +function Decoder.blockFrames(kind, ba, ch) +if kind == "ima_qt" then + return 64 + elseif kind == "ms" then + return (ba >= 7 * ch and((math.floor((ba - 7 * ch) * 2 / ch )+ 2 ))or(nil +)) end + return (ba >= 4 * ch and((math.floor((ba - 4 * ch) * 2 / ch )+ 1 ))or(nil +))end + +-- blocks(dec, spec): self-contained ADPCM blocks (no state across blocks); a truncated last block decodes what it has +function Decoder.blocks(dec, spec) +local ch = dec.channels + local kind = spec.kind + local ba = (kind == "ima_qt" and((34 * ch ))or(spec.blockAlign or 0 +)) local spb = Decoder.blockFrames(kind, ba, ch) + if not spb then + return nil, Err.new(Err.CORRUPT, "block of " .. ba .. " bytes is too small") + end + if spb * ch > 2 ^ 20 then + return nil, Err.new(Err.LIMIT, "ADPCM block too large") + end + local buf, base, size = spec.buf, spec.offset, spec.size + local full = math.floor(size / ba +) local rest = size - full * ba + local total = full * spb + if kind ~= "ima_qt" and rest > 0 then + -- a partial last block: the frames it holds whole + if kind == "ms" then + total =total+ (rest >= 7 * ch and{(math.min(spb, 2 + math.floor(((rest - 7 * ch) * 2) / ch)) )}or{0 +})[1] elseif rest >= 4 * ch then + total =total+ math.min(spb, 1 + (math.floor((rest - 4 * ch) / (4 * ch))) * 8) + end + end + local frames = math.min(spec.frames or total, total) + local ncoef = 7 + local cf = spec.coefs + if cf and #cf >= 2 then + ncoef = math.min(256, math.floor(#cf / 2)) + end + local coefs = buffer.create(ncoef * 8) + for k = 0, ncoef - 1 do + buffer.writei32(coefs, k * 8, (cf and #cf >= 2 and{cf[k * 2 + 1] }or{Adpcm.MS_COEF1[k + 1]})[1]) + buffer.writei32(coefs, k * 8 + 4, (cf and #cf >= 2 and{cf[k * 2 + 2] }or{Adpcm.MS_COEF2[k + 1]})[1]) + end + local scratch = buffer.create(20 * ch) + dec.frames = frames + dec.duration = frames / dec.sampleRate + dec.blockAlign = ba + dec.samplesPerBlock = spb + return Decoder.packets(dec, { + count = math.max(1, math.ceil(frames / spb)), + packetFrames = spb, + frames = frames, + state = scratch, + decode = function(i, out) +local off = base + (i - 1) * ba + local avail = math.min(ba, base + size - off) + if kind == "ms" then + return Adpcm.msBlock(buf, off, avail, ch, spb, out, 0, coefs, ncoef, scratch), nil + elseif kind == "ima_wav" then + return Adpcm.imaWav(buf, off, avail, ch, spb, out, 0), nil + end + if avail < ba then + return 0, nil + end + for c = 0, ch - 1 do + Adpcm.imaQt(buf, off + c * 34, scratch, c * 8, out, c, ch) + end + return 64, nil + end, + }) +end + +return Decoder +end +__FILES["codecs/audio/Alac"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- 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("rosetta.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) +-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) +-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) +-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled +-- +-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Alac/Decode") +local Encode = __include("codecs/audio/Alac/Encode") + +local Alac = {} + +-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count + + + + + + + + + + + + + + +local TO_WAV= { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +-- the element layout (channels per element) the encoder writes +local ELEMENTS= { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +-- config(buf, offset?, length?) -> Config | nil, Err +function Alac.config(buf, offset, length) +local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c= { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +-- cookie(cfg) -> the 24-byte ALACSpecificConfig +function Alac.cookie(c) +local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + +local function decode(self, buf, offset, length) +local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k] ] = src[base + k] + end + end + end + return frames, nil +end + +-- decoder(cfg) -> Decoder +function Alac.decoder(cfg) +return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end +-- ------------------------------------------------------------------------------------------------ encoder + + + + + + + + + +local function encode(self, samples, first, frames) +local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes =self.bytes+ n + self.frames =self.frames+ frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +-- encoder(opts) -> Encoder | nil, Err + + + + + + + +function Alac.encoder(opts) +if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg= { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac +end +__FILES["codecs/audio/Alac/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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. +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + + + + + + + + + + + + + + + + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. +local function bitsAt(b, pos, n) +local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +local function signExtend(v, bits) +local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v =v- m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +local function scalar(b, pos, k, m, bps) +local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos =pos+ 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos =pos+ (pre + 1 +) if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +-- residuals: n values into out[1..n]; returns the new bit position or -1 +local function rice(b, pos, limit, out, n, bps, mult, st) +local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x =x+ signMod + signMod = 0 + out[i] = (x % 2 == 0 and((x / 2 ))or((-(x + 1) / 2 +))) if x > 0xFFFF then + history = 0xFFFF + else + history =history+ (x * mult - floor(history * mult / 512) +) end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = (history > 0 and((31 - countlz(history) ))or(0 +)) k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i =i+ run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i =i+ 1 + end + return pos +end + +-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place +local function predict(err, out, n, bps, coefs, order, quant) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i =i+ 1 + end + local half = (quant > 0 and{POW[quant] }or{0 +})[1] local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val =val+ (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = e > 0 and 1 or-1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = (v > 0 and{es }or{(v < 0 and{(-es )}or{0 +})[1]})[1] coefs[j]=coefs[j]- sgn + e =e- floor(v * sgn / qd) * (order - j + 1) + end + end + i =i+ 1 + end +end + +-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the +-- ALAC element order. +function Decode.frame(st, buf, off, len) +if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 -- next output channel + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos =pos+ 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = tag == 1 and 2 or 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos =pos+ 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos =pos+ 12 + local h = bitsAt(b, pos, 4) + pos =pos+ 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos =pos+ 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos =pos+ 16 + if mixRes >= 128 then + mixRes =mixRes- 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + local x = bitsAt(b, pos, 8) + local y = bitsAt(b, pos + 8, 8) + pos =pos+ 16 + mode[c], denShift[c] = rshift(x, 4), (band(x, 15) ) +pbFactor[c], order[c] = rshift(y, 5), (band(y, 31) ) +if pos + order[c] * 16 > limit then + return nil, "frame runs past the end" + end + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos =pos+ 16 + coefs[c][j] = (v >= 32768 and((v - 65536 ))or(v +)) end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos =pos+ shift * n * nch + end + for c = 1, nch do + local p = (c == 1 and{p0 }or{p1 +})[1] local mb = (c == 1 and{m0 }or{m1 +})[1] pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp =sp+ shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos =pos+ bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + -- unmix + shifted bytes -> interleaved output + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch =ch+ nch + elseif tag == 4 then -- DSE + pos =pos+ 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos =pos+ 9 + if count == 255 then + count =count+ bitsAt(b, pos, 8) + pos =pos+ 8 + end + if align == 1 then + pos = math.floor((pos + 7) / 8 )* 8 + end + pos =pos+ count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos =pos+ 4 + if count == 15 then + count =count+ (bitsAt(b, pos, 8) - 1 +) pos =pos+ 8 + end + pos =pos+ count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + -- missing channels: silence + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +-- the scratch state for a configuration +function Decode.state(cfg) +local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode +end +__FILES["codecs/audio/Alac/Encode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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 +-- input. Written for this library from the ALAC format; no third-party code. Never throws. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +-- ------------------------------------------------------------------------------------------------ bit writer + + + + + + + + + + + + + + + + +local function put(st, v, n) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = (n < free and{n }or{free +})[1] local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos =pos+ take + n =n- take + end + st.pos = pos +end + +local function putBig(st, v, n) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +-- ------------------------------------------------------------------------------------------------ rice code +local function signExtend(v, bits) +local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v =v- m + end + return v +end + +-- the bits of one scalar (no writing) +local function scalarBits(x, k, m, bps) +local pre = (k == 1 and{x }or{(floor(x / m) +)})[1] if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + ((r == 0 and((k - 1 ))or(k))) +end + +local function scalar(st, x, k, m, bps) + local pre = (k == 1 and{x }or{(floor(x / m) +)})[1] if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + -- pre ones and a zero + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +-- code the residuals e[1..n] (write = false: just count the bits) +local function rice(st, e, n, bps, mult, write) +local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = (v >= 0 and((2 * v ))or((-2 * v - 1 +))) local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits =bits+ scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history =history+ (zz * mult - floor(history * mult / 512) +) end + if history < 128 and i < n then + local lg = (history > 0 and((31 - countlz(history) ))or(0 +)) k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run =run+ 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits =bits+ scalarBits(run, k, m, 16) + end + i =i+ run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i =i+ 1 + end + return bits +end + +-- ------------------------------------------------------------------------------------------------ prediction +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +local function residuals(x, e, n, bps, coefs, order, quant) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i =i+ 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val =val+ (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = r > 0 and 1 or-1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = (v > 0 and{es }or{(v < 0 and{(-es )}or{0 +})[1]})[1] coefs[j]=coefs[j]- sgn + r =r- floor(v * sgn / qd) * (order - j + 1) + end + end + i =i+ 1 + end +end + +-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised +local function lpc(x, n, order, work) +local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s =s+ work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1]=ac[1]* 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc =acc- a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv =errv* (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits +local function analyse(st, x, n, bps) +local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in __iter({ 4, 8 }) do +local __DARKLUA_CONTINUE_17=false repeat if order >= n then +__DARKLUA_CONTINUE_17=true break + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end +__DARKLUA_CONTINUE_17=true until true if not __DARKLUA_CONTINUE_17 then break end end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index +-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts +function Encode.frame(st, samples, first, frames, map, elements) +local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = math.floor((need + 8 * 32 * 2 * #elements * 16) / 8 )+ 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in __iter(elements) do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + -- the mix with the smallest first-difference energy + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost =cost+ (abs(uu - pu) + abs(vv - pv) +) pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + -- header + put(st, nch == 2 and 1 or 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, partial and 1 or 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, mixRes == 0 and 0 or 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = (c == 1 and{u }or{v +})[1] local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = (c == 1 and{u }or{v +})[1] local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch =ch+ nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + -- uncompressed frame + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in __iter(elements) do + put(st, nch == 2 and 1 or 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, partial and 1 or 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch =ch+ nch + end + end + put(st, 7, 3) -- END + local bytes = math.floor((st.pos + 7) / 8 +) local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +function Encode.state(cfg) +local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode +end +__FILES["codecs/audio/Ape"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- codecs/audio/Ape: the Monkey's Audio codec (.ape). A codec (layer 3). Ported from the Monkey's Audio SDK 13.28 +-- (Matthew T. Ashland, BSD 3-clause since v10, licenses/monkeys-audio-LICENSE.txt): APEHeader.cpp (the descriptor / +-- header / seek table, and the pre-3.98 header), APEInfo / APEDecompress.cpp (frame bytes and alignment); the frame +-- decoder is codecs/audio/Ape/Decode. Supports file versions 3.95 and later (3.99+ as the current encoder writes; the +-- 3.95 - 3.98 range coder model is ported but has no reference fixture), every compression level (fast, normal, high, +-- extra high, insane), 8 / 16 / 24 / 32-bit integer and 32-bit float, 1 - 32 channels, special frames (silence, +-- pseudo stereo) and the frame CRC. Not supported: versions before 3.95 (UNSUPPORTED), the "interim" 24-bit +-- re-decode for files of the 32-bit era before 8.50, big-endian / signed 8-bit source flags (the samples are returned +-- as numbers either way). +-- +-- local info, err = Ape.info(buf, base, limit) -- header facts + the frame table +-- local dec = Ape.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved; integers, or floats) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/audio/Ape/Decode") + +local Ape = {} + + + + + + + + + + + + + + + + + + + + + +local FLAG_8, FLAG_24, FLAG_PEAK, FLAG_SEEKN, FLAG_WAVHDR, FLAG_FLOAT = 1, 8, 4, 16, 32, 4096 + +-- find(buf, base, limit) -> the offset of "MAC " / "MACF" (after an ID3v2 tag) | nil +function Ape.find(buf, base, limit) +local at = base + if limit - at >= 10 and buffer.readstring(buf, at, 3) == "ID3" then + local size = 0 + for i = 6, 9 do + size = size * 128 + bit32.band(buffer.readu8(buf, at + i), 127) + end + local footer = bit32.band(buffer.readu8(buf, at + 5), 16) ~= 0 + at =at+ (size + (footer and 20 or 10) +) if not footer then + while at < limit and buffer.readu8(buf, at) == 0 do + at =at+ 1 + end + end + end + if at + 4 > limit then + return nil + end + local id = buffer.readstring(buf, at, 4) + if id == "MAC " or id == "MACF" then + return at + end + local s = buffer.readstring(buf, at, math.min(limit - at, 1048576)) + local k = string.find(s, "MAC ", 1, true) + return (k and((at + k - 1 ))or(nil +))end + +-- info(buf, base, limit) -> Info | nil, Err +function Ape.info(buf, base, limit) +local at = Ape.find(buf, base, limit) + if not at then + return nil, Err.new(Err.CORRUPT, "no Monkey's Audio header") + end + local junk = at - base -- seek offsets count from the start of the APE data (after any junk / ID3v2) + local r = Bytes.reader(buf, at, limit - at) + r:skip(4) + local version = r:u16le() + if r.err then + return nil, r.err + end + if version < 3950 then + return nil, Err.new(Err.UNSUPPORTED, "Monkey's Audio file version " .. version .. " (3950 and later are supported)") + end + local info= { version = version, programVersion = 0 } + local seekCount, seekAt + if version >= 3980 then + info.programVersion = r:u16le() + local descBytes, headBytes, seekBytes, hdrDataBytes = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local dataLo, dataHi, termBytes = r:u32le(), r:u32le(), r:u32le() + local md5 = r:string(16) + r:seek(descBytes) + info.level = r:u16le() + info.flags = r:u16le() + info.blocksPerFrame = r:u32le() + info.finalFrameBlocks = r:u32le() + info.totalFrames = r:u32le() + info.bitsPerSample = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + if r.err then + return nil, r.err + end + seekAt = at + descBytes + headBytes + seekCount = math.floor(seekBytes / 4 +) info.dataEnd = seekAt + seekBytes + hdrDataBytes + dataLo + dataHi * 4294967296 + local _ = termBytes + local hex = table.create(16, "") + local any = false + for k = 1, 16 do + local b = string.byte(md5, k) + any = any or b ~= 0 + hex[k] = string.format("%02x", b) + end + info.md5 = (any and{(table.concat(hex) )}or{nil +})[1] else + info.level = r:u16le() + info.flags = r:u16le() + info.channels = r:u16le() + info.sampleRate = r:u32le() + local headerBytes = r:u32le() + r:u32le() -- terminating bytes + info.totalFrames = r:u32le() + info.finalFrameBlocks = r:u32le() + if bit32.band(info.flags, FLAG_PEAK) ~= 0 then + r:skip(4) + end + seekCount = info.totalFrames + if bit32.band(info.flags, FLAG_SEEKN) ~= 0 then + seekCount = r:u32le() + end + if bit32.band(info.flags, FLAG_WAVHDR) == 0 then + r:skip(headerBytes) + end + if r.err then + return nil, r.err + end + info.blocksPerFrame = 73728 * 4 + info.bitsPerSample = bit32.band(info.flags, FLAG_8) ~= 0 and 8 or(bit32.band(info.flags, FLAG_24) ~= 0 and 24 or 16 +) seekAt = r:tell() + info.dataEnd = limit + end + local C, bits = info.channels, info.bitsPerSample + if C < 1 or C > 32 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. C) + end + if bits ~= 8 and bits ~= 16 and bits ~= 24 and bits ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit samples") + end + if info.sampleRate < 1 or info.blocksPerFrame < 1 or info.blocksPerFrame > 10000000 or info.finalFrameBlocks > info.blocksPerFrame then + return nil, Err.new(Err.CORRUPT, "bad header") + end + if info.totalFrames < 1 then + return nil, Err.new(Err.CORRUPT, "no frames") + end + info.float = bit32.band(info.flags, FLAG_FLOAT) ~= 0 and bits == 32 + info.totalBlocks = (info.totalFrames - 1) * info.blocksPerFrame + info.finalFrameBlocks + if seekCount < info.totalFrames or seekAt + seekCount * 4 > limit then + return nil, Err.new(Err.TRUNCATED, "the seek table is incomplete") + end + local starts = table.create(info.totalFrames, 0) + local add, prev = 0, 0 + for i = 1, info.totalFrames do + local v = buffer.readu32(buf, seekAt + (i - 1) * 4) + if v < prev then + add =add+ 4294967296 + end + prev = v + starts[i] = base + junk + add + v + end + for i = 1, info.totalFrames do + if starts[i] < base or (i > 1 and starts[i] < starts[i - 1]) then + return nil, Err.new(Err.CORRUPT, "bad seek table entry " .. i) + end + end + info.frameStart = starts + info.firstFrame = starts[1] + info.dataEnd = math.min(math.max(info.dataEnd, starts[info.totalFrames]), limit) + info.limit = limit + return info , nil +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + +local function frame(self, buf, i) +local info = self.info + if i < 1 or i > info.totalFrames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local start = info.frameStart[i] + local rem = (start - info.firstFrame) % 4 + local want = ((i < info.totalFrames and{info.frameStart[i + 1] }or{info.dataEnd})[1]) + 4 + local stop = math.min(want, info.limit, buffer.len(buf)) + if start + 8 > stop then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " is past the end of the data", start) + end + local n = (i < info.totalFrames and{info.blocksPerFrame }or{info.finalFrameBlocks +})[1] local n2, msg = Decode.frame(self.state, buf, start - rem, rem, stop, n, self.pcm, info.float, stop < want - 4) + if not n2 then + return nil, Err.from(msg, start) + end + return n2, nil +end + +-- decoder(info) -> Decoder | nil, Err +function Ape.decoder(info) +local st, msg = Decode.state(info.version, info.level, info.bitsPerSample, info.channels) + if not st then + return nil, Err.from(msg) + end + return { + info = info, + pcm = table.create(math.min(info.blocksPerFrame, 1048576) * info.channels, 0), + frame = frame, + state = st, + }, nil +end + +return Ape +end +__FILES["codecs/audio/Ape/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/audio/Ape/Decode: one Monkey's Audio frame -> samples. Ported from the Monkey's Audio SDK 13.28 (Matthew T. +-- Ashland, BSD 3-clause, licenses/monkeys-audio-LICENSE.txt): UnBitArray.cpp (the range coder and its value model, +-- 3.99+) and Old/UnBitArrayOld.cpp (CUnBitArray3891To3989, the 3.95 - 3.98 model), NNFilter / NNFilterCommon.h (the +-- neural-net filters of the normal .. insane levels), NewPredictor.cpp (CPredictorDecompress3950toCurrent, its int32 +-- and int64 flavours), ScaledFirstOrderFilter.h, Prepare.cpp (Unprepare: X / Y -> channels), APEDecompressCore.cpp +-- (special frames, the frame CRC) and FloatTransform.cpp. Never throws: returns nil, message. +local Crc32 = __include("core/Crc32") + +local readu8, readu32, writeu32, byteswap = buffer.readu8, buffer.readu32, buffer.writeu32, bit32.byteswap +local writeu8, writei16, writeu16, writei32, readf32 = buffer.writeu8, buffer.writei16, buffer.writeu16, buffer.writei32, buffer.readf32 +local readi16, readi32 = buffer.readi16, buffer.readi32 +local band, bor, bnot, rshift, lshift, bxor = bit32.band, bit32.bor, bit32.bnot, bit32.rshift, bit32.lshift, bit32.bxor +local sign = math.sign + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local PAD = 64 + +-- the range coder's symbol models (UnBitArrayBase.h) +local RT1 = { 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926, 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419, 65450, 65469, 65480, 65487, 65491, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local RT2 = { 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435, 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482, 65485, 65488, 65490, 65491, 65492, 65493, 65494, 65495, 65496, 65497, 65498, 65499, 65500, 65501, 65502, 65503, 65504, 65505, 65506, 65507, 65508, 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65518, 65519, 65520, 65521, 65522, 65523, 65524, 65525, 65526, 65527, 65528, 65529, 65530, 65531, 65532, 65533, 65534, 65535, 65536 } +local KMIN = { 0, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 0, 0, 0, 0, 0 } + +-- symbol(total) lookup buffers (RangeOverflowTable), built on first use +local OVT= {} +local function overflowTable(rt) +local t = OVT[rt[2] ] + if t then + return t + end + t = buffer.create(65536) + local o = 0 + for z = 0, 65535 do + if z >= rt[o + 2] then + o =o+ 1 + end + writeu8(t, z, o) + end + OVT[rt[2] ] = t + return t +end + +local function wrap32(v) +if v >= TWO31 or v < -TWO31 then + return (v + TWO31) % TWO32 - TWO31 + end + return v +end + +-- C integer division by 2 (toward zero) +local function half(v) +return (v >= 0 and{(math.floor(v / 2 ))}or{(-(math.floor((-v) / 2)) +)})[1]end + + + + + + + + + + + + + + + +local FILTERS= { -- level -> { order, shift, ... } in m_spNNFilter, 1, 2 order + [1000] = {}, + [2000] = { 16, 11 }, + [3000] = { 64, 11 }, + [4000] = { 256, 13, 32, 10 }, + [5000] = { 1280, 15, 256, 13, 16, 11 }, +} + +-- state(version, level, bits, channels) -> State | nil, message +function Decode.state(version, level, bits, channels) +local spec = FILTERS[level] + if not spec then + return nil, "unsupported: compression level " .. level + end + local filters= {} + for k = 1, #spec, 2 do + local order = spec[k] + local es = bits >= 32 and 4 or 2 + table.insert(filters, { + order = order, + shift = spec[k + 1], + M = buffer.create(order * es), + I = buffer.create((512 + order + 1) * es), + D = buffer.create((512 + order + 1) * es), + }) + end + local V = {} + for c = 1, channels do + V[c] = {} + end + return { + version = version, + bits = bits, + channels = channels, + filters = filters, + V = V, + S = buffer.create(1024), + crcbuf = buffer.create(1024), + scratch = buffer.create(4), + lastX = 0, + rc = { q = 0, low = 0, range = 0, prev = 0 }, + }, nil +end +-- ------------------------------------------------------------------------------------------------ entropy +-- the range coder as a record (the 3.95 - 3.98 model's RangeDecodeFastWithUpdate) + + +local function rcBits(rc, S, nb) +local q, low, range, prev = rc.q, rc.low, rc.range, rc.prev + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / 2 ^ nb +) local r = 0 + if range > 0 then + r = math.floor(low / range +) low =low% range + end + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + return r +end + +-- values(st, q, n, order, old) -> q | nil, message: n blocks of range-coded values into st.V[c] for the channels of +-- `order` (decode order), from byte q of st.S (the range coder starts there) +local function values(st, q, lim, n, order, old) +local S = st.S + local V = st.V + local version = st.version + -- FlushBitArray: a dummy byte, then the first byte + local prev = readu8(S, q + 1) + q =q+ 2 + local low = rshift(prev, 1) + local range = 128 + local nch = #order + local ksum = table.create(nch, 16384) + local kk = table.create(nch, 10) + local ovt = overflowTable((old and{RT1 }or{RT2})[1]) + local RT = (old and{RT1 }or{RT2 +})[1] for b = 1, n do + for ci = 1, nch do + if q > lim then + return nil, "overrun" + end + local ks = ksum[ci] + local value + -- the overflow symbol (RangeDecodeFast(16) + the model) + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / 65536 +) local total = math.floor(low / range +) if total >= 65536 then + return nil, "bad range code" + end + local ov = readu8(ovt, total) + low =low- range * RT[ov + 1] + range =range* (RT[ov + 2] - RT[ov + 1] +) if not old then + local pivot = math.max(math.floor(ks / 32), 1) + while ov == 63 do + -- escape: 32 bits of overflow (two 16-bit range decodes); 1 = the overflow signal + local r = 0 + for _ = 1, 2 do + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / 65536 +) if range == 0 then + return nil, "bad range code" + end + r = r * 65536 + math.floor(low / range +) low =low% range + end + ov = r + if ov == 1 then + pivot = 32768 + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / 65536 +) total = math.floor(low / range +) if total >= 65536 then + return nil, "bad range code" + end + ov = readu8(ovt, total) + low =low- range * RT[ov + 1] + range =range* (RT[ov + 2] - RT[ov + 1] +) else + break + end + end + local base + if pivot >= 65536 then + local pbits = 0 + while math.floor(pivot / 2 ^ pbits )> 0 do + pbits =pbits+ 1 + end + local split = 2 ^ ((pbits >= 16 and((pbits - 16 ))or(0))) + local pa = math.floor(pivot / split )+ 1 + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / pa +) local ba = math.floor(low / range +) low =low% range + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / split +) local bb = math.floor(low / range +) low =low% range + base = ba * split + bb + else + while range <= 8388608 do + local byte = readu8(S, q) + q =q+ 1 + low = low * 256 + bor(lshift(band(prev, 1), 7), rshift(byte, 1)) + prev = byte + range =range* 256 + end + range = math.floor(range / pivot +) base = math.floor(low / range +) low =low% range + end + value = base + ov * pivot + else + -- 3.95 - 3.98: k bits (escape: k in 5 bits) + local rc = st.rc + rc.q, rc.low, rc.range, rc.prev = q, low, range, prev + local k + if ov == 63 then + k = rcBits(rc, S, 5) + ov = 0 + else + k = math.max(kk[ci] - 1, 0) + end + if k <= 16 or version < 3910 then + value = rcBits(rc, S, k) + else + local x1 = rcBits(rc, S, 16) + value = x1 + rcBits(rc, S, k - 16) * 65536 + end + value =value+ ov * 2 ^ k + q = rc.q + low = rc.low + range = rc.range + prev = rc.prev + end + ks = (ks + math.floor((value + 1) / 2 )- math.floor((ks + 16) / 32)) % TWO32 + ksum[ci] = ks + if old then + local k = kk[ci] + if ks < KMIN[k + 1] then + kk[ci] = k - 1 + elseif KMIN[k + 2] ~= 0 and ks >= KMIN[k + 2] then + kk[ci] = k + 1 + end + end + V[order[ci] ][b] = (value % 2 == 1 and((math.floor((value - 1) / 2 )+ 1 ))or((-(math.floor(value / 2)) +))) end + end + return q, nil +end + +-- ------------------------------------------------------------------------------------------------ NN filters +-- ((v >> s) & m) ~= 0 for an int64 v (s given as 2^s) +local function negBit(v, p2, m) +return band((math.floor(v / p2)) % TWO32, m) ~= 0 +end + +-- the int16 dot product of the weights and the inputs from byte b (span bytes) +local function dot16(M, I, b, span) +local dot = 0 + for k = 0, span - 16, 16 do + local bb = b + k + dot =dot+ (readi16(I, bb) * readi16(M, k) + readi16(I, bb + 2) * readi16(M, k + 2) + + readi16(I, bb + 4) * readi16(M, k + 4) + readi16(I, bb + 6) * readi16(M, k + 6) + + readi16(I, bb + 8) * readi16(M, k + 8) + readi16(I, bb + 10) * readi16(M, k + 10) + + readi16(I, bb + 12) * readi16(M, k + 12) + readi16(I, bb + 14) * readi16(M, k + 14) +) end + return dot +end + +-- the same, adapting each weight after its use: M += D * dm (int16, wrapping) +local function dotAdapt16(M, I, D, b, span, dm) +local dot = 0 + for k = 0, span - 8, 8 do + local bb = b + k + local m0, m1, m2, m3 = readi16(M, k), readi16(M, k + 2), readi16(M, k + 4), readi16(M, k + 6) + dot =dot+ (readi16(I, bb) * m0 + readi16(I, bb + 2) * m1 + readi16(I, bb + 4) * m2 + readi16(I, bb + 6) * m3 +) writei16(M, k, m0 + readi16(D, bb) * dm) + writei16(M, k + 2, m1 + readi16(D, bb + 2) * dm) + writei16(M, k + 4, m2 + readi16(D, bb + 4) * dm) + writei16(M, k + 6, m3 + readi16(D, bb + 6) * dm) + end + return dot +end + +-- one CNNFilter over n values of v, in place (DecompressGeneric). The weights, inputs and deltas live in buffers of +-- the C types (int16 for 8 - 24-bit files, int32 for 32-bit ones: `wide`), so the weights wrap as the C shorts do +local function nnFilter(f, v, n, newDelta, wide) + local order, M, I, D = f.order, f.M, f.I, f.D + local es = wide and 4 or 2 + local shift = 2 ^ f.shift + local round = math.floor(shift / 2 +) buffer.fill(M, 0, 0, order * es) + buffer.fill(I, 0, 0, (order + 1) * es) + buffer.fill(D, 0, 0, (order + 1) * es) + local p = order -- the current element (0-based); its history is p - order .. p - 1 + local total = 512 + order + local avg = 0 + local span = order * 2 + for t = 1, n do + local x = v[t] + local dm = -sign(x) -- the weights move by +delta when x < 0, -delta when x > 0 + local dot = 0 + if wide then + local b = (p - order) * 4 + for k = 0, order * 4 - 4, 4 do + local m = readi32(M, k) + local pr = readi32(I, b + k) * m + if pr >= TWO31 or pr < -TWO31 then + pr = (pr + TWO31) % TWO32 - TWO31 + end + dot =dot+ pr + if dm ~= 0 then + writei32(M, k, m + readi32(D, b + k) * dm) + end + end + else + local b = (p - order) * 2 + dot = (dm == 0 and{(dot16(M, I, b, span) )}or{(dotAdapt16(M, I, D, b, span, dm) +)})[1] dot = wrap32(dot) + end + local o = x + math.floor((dot + round) / shift +) if not wide then + o = wrap32(o) + end + local d = 0 + local a = (o < 0 and{(-o )}or{o +})[1] if newDelta then + if a > avg * 3 then + d = ((wide and{(negBit(o, 33554432, 64) )}or{(o < 0)})[1]) and 32 or-32 + elseif a > math.floor((avg * 4) / 3 )then + d = ((wide and{(negBit(o, 67108864, 32) )}or{(o < 0)})[1]) and 16 or-16 + elseif a > 0 then + d = ((wide and{(negBit(o, 134217728, 16) )}or{(o < 0)})[1]) and 8 or-8 + end + local dd = a - avg + avg =avg+ (dd >= 0 and{(math.floor(dd / 16 ))}or{(-(math.floor((-dd) / 16)) +)})[1] else + d = o == 0 and 0 or(o < 0 and 4 or-4 +) end + local sat = o > 32767 and 32767 or(o < -32768 and-32768 or o +) if wide then + local q = p * 4 + writei32(D, q, d) + if newDelta then + writei32(D, q - 4, math.floor(readi32(D, q - 4) / 2)) + writei32(D, q - 8, math.floor(readi32(D, q - 8) / 2)) + else + writei32(D, q - 16, math.floor(readi32(D, q - 16) / 2)) + end + writei32(D, q - 32, math.floor(readi32(D, q - 32) / 2)) + writei32(I, q, sat) + else + local q = p * 2 + writei16(D, q, d) + if newDelta then + writei16(D, q - 2, math.floor(readi16(D, q - 2) / 2)) + writei16(D, q - 4, math.floor(readi16(D, q - 4) / 2)) + else + writei16(D, q - 8, math.floor(readi16(D, q - 8) / 2)) + end + writei16(D, q - 16, math.floor(readi16(D, q - 16) / 2)) + writei16(I, q, sat) + end + v[t] = o + p =p+ 1 + if p == total then + buffer.copy(I, 0, I, (p - order) * es, order * es) + buffer.copy(D, 0, D, (p - order) * es, order * es) + p = order + end + end +end + +-- ------------------------------------------------------------------------------------------------ predictor +-- the adapt sign of a 32-bit file's int64 prediction value: ((v >> 30) & 2) - 1, or 0 +local function adaptWide(v) +if v == 0 then + return 0 + end + return (math.floor(v / 1073741824)) % 4 >= 2 and 1 or-1 +end + +-- predict(st, a, b?, n) : CPredictorDecompress3950toCurrent over channel a's values (nB = channel b's outputs of the +-- block, or 0), single-channel form; stereo uses predictStereo +local function predictOne(st, v, n) + local wide = st.bits >= 32 + local lastA, prevA0, A1, A2, A3 = 0, 0, 0, 0, 0 + local MA0, MA1, MA2, MA3 = 360, 317, -109, 98 + local stage = 0 + for t = 1, n do + local nA = v[t] + local A0 = lastA + A3 = A2 + A2 = A1 + A1 = A0 - prevA0 + prevA0 = A0 + local predA = A0 * MA0 + A1 * MA1 + A2 * MA2 + A3 * MA3 + local cur + if wide then + cur = nA + math.floor(predA / 1024 +) else + cur = wrap32(nA + math.floor(wrap32(predA) / 1024)) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + MA0 =MA0+ adaptWide(A0) * s + MA1 =MA1+ adaptWide(A1) * s + MA2 =MA2+ adaptWide(A2) * s + MA3 =MA3+ adaptWide(A3) * s + else + MA0 =MA0+ sign(A0) * s + MA1 =MA1+ sign(A1) * s + MA2 =MA2+ sign(A2) * s + MA3 =MA3+ sign(A3) * s + end + end + stage = wrap32(cur + math.floor((stage * 31) / 32)) + lastA = cur + v[t] = stage + end +end + +-- the stereo predictors: Y = P1(nY, last X), X = P0(nX, Y); X into V[1], Y into V[2] +local function predictStereo(st, X, Y, n) + local wide = st.bits >= 32 + -- predictor 1 (Y) + local yLast, yPrev, yA1, yA2, yA3 = 0, 0, 0, 0, 0 + local yBin, yBprev, yB1, yB2, yB3, yB4 = 0, 0, 0, 0, 0, 0 + local yMA0, yMA1, yMA2, yMA3 = 360, 317, -109, 98 + local yMB0, yMB1, yMB2, yMB3, yMB4 = 0, 0, 0, 0, 0 + local yStage = 0 + -- predictor 0 (X) + local xLast, xPrev, xA1, xA2, xA3 = 0, 0, 0, 0, 0 + local xBin, xBprev, xB1, xB2, xB3, xB4 = 0, 0, 0, 0, 0, 0 + local xMA0, xMA1, xMA2, xMA3 = 360, 317, -109, 98 + local xMB0, xMB1, xMB2, xMB3, xMB4 = 0, 0, 0, 0, 0 + local xStage = 0 + local lastX = 0 + for t = 1, n do + -- Y + local nA = Y[t] + local A0 = yLast + yA3 = yA2 + yA2 = yA1 + yA1 = A0 - yPrev + yPrev = A0 + local B0 = lastX - math.floor((yBin * 31) / 32 +) yBin = lastX + yB4 = yB3 + yB3 = yB2 + yB2 = yB1 + yB1 = B0 - yBprev + yBprev = B0 + local predA = A0 * yMA0 + yA1 * yMA1 + yA2 * yMA2 + yA3 * yMA3 + local predB = B0 * yMB0 + yB1 * yMB1 + yB2 * yMB2 + yB3 * yMB3 + yB4 * yMB4 + local cur + if wide then + cur = nA + math.floor((predA + math.floor(predB / 2)) / 1024 +) else + cur = wrap32(nA + math.floor(wrap32(wrap32(predA) + math.floor(wrap32(predB) / 2)) / 1024)) + end + local s = sign(nA) + if s ~= 0 then + if wide then + s = -s + yMA0 =yMA0+ adaptWide(A0) * s + yMA1 =yMA1+ adaptWide(yA1) * s + yMA2 =yMA2+ adaptWide(yA2) * s + yMA3 =yMA3+ adaptWide(yA3) * s + yMB0 =yMB0+ adaptWide(B0) * s + yMB1 =yMB1+ adaptWide(yB1) * s + yMB2 =yMB2+ adaptWide(yB2) * s + yMB3 =yMB3+ adaptWide(yB3) * s + yMB4 =yMB4+ adaptWide(yB4) * s + else + yMA0 =yMA0+ sign(A0) * s + yMA1 =yMA1+ sign(yA1) * s + yMA2 =yMA2+ sign(yA2) * s + yMA3 =yMA3+ sign(yA3) * s + yMB0 =yMB0+ sign(B0) * s + yMB1 =yMB1+ sign(yB1) * s + yMB2 =yMB2+ sign(yB2) * s + yMB3 =yMB3+ sign(yB3) * s + yMB4 =yMB4+ sign(yB4) * s + end + end + yStage = wrap32(cur + math.floor((yStage * 31) / 32)) + yLast = cur + local yv = yStage + -- X + nA = X[t] + A0 = xLast + xA3 = xA2 + xA2 = xA1 + xA1 = A0 - xPrev + xPrev = A0 + B0 = yv - math.floor((xBin * 31) / 32 +) xBin = yv + xB4 = xB3 + xB3 = xB2 + xB2 = xB1 + xB1 = B0 - xBprev + xBprev = B0 + predA = A0 * xMA0 + xA1 * xMA1 + xA2 * xMA2 + xA3 * xMA3 + predB = B0 * xMB0 + xB1 * xMB1 + xB2 * xMB2 + xB3 * xMB3 + xB4 * xMB4 + if wide then + cur = nA + math.floor((predA + math.floor(predB / 2)) / 1024 +) else + cur = wrap32(nA + math.floor(wrap32(wrap32(predA) + math.floor(wrap32(predB) / 2)) / 1024)) + end + s = sign(nA) + if s ~= 0 then + if wide then + s = -s + xMA0 =xMA0+ adaptWide(A0) * s + xMA1 =xMA1+ adaptWide(xA1) * s + xMA2 =xMA2+ adaptWide(xA2) * s + xMA3 =xMA3+ adaptWide(xA3) * s + xMB0 =xMB0+ adaptWide(B0) * s + xMB1 =xMB1+ adaptWide(xB1) * s + xMB2 =xMB2+ adaptWide(xB2) * s + xMB3 =xMB3+ adaptWide(xB3) * s + xMB4 =xMB4+ adaptWide(xB4) * s + else + xMA0 =xMA0+ sign(A0) * s + xMA1 =xMA1+ sign(xA1) * s + xMA2 =xMA2+ sign(xA2) * s + xMA3 =xMA3+ sign(xA3) * s + xMB0 =xMB0+ sign(B0) * s + xMB1 =xMB1+ sign(xB1) * s + xMB2 =xMB2+ sign(xB2) * s + xMB3 =xMB3+ sign(xB3) * s + xMB4 =xMB4+ sign(xB4) * s + end + end + xStage = wrap32(cur + math.floor((xStage * 31) / 32)) + xLast = cur + lastX = xStage + X[t], Y[t] = xStage, yv + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, at, rem, stop, n, P, float) -> n | nil, message: the frame whose words start at byte `at` (its first +-- byte at at + rem), reading at most up to `stop`; n blocks into P (interleaved integers, or floats when float); cut: +-- the data ends at `stop` before the frame does (a running-over decode is then "truncated", else corrupt) +function Decode.frame(st, buf, at, rem, stop, n, P, float, cut) +local C, bits = st.channels, st.bits + local len = math.max(0, stop - at) + local words = math.floor((len + 3) / 4 +) local S = st.S + if buffer.len(S) < words * 4 + PAD then + S = buffer.create(words * 4 + PAD + 4096) + st.S = S + end + buffer.fill(S, 0, 0, words * 4 + PAD) + -- the bit array: 32-bit little-endian words read MSB first + for w = 0, words - 1 do + local o = at + w * 4 + if o + 4 <= stop then + writeu32(S, w * 4, byteswap(readu32(buf, o))) + else + for k = 0, 3 do + if o + k < stop then + writeu8(S, w * 4 + 3 - k, readu8(buf, o + k)) + end + end + end + end + local function u32be(q) +return readu8(S, q) * 16777216 + readu8(S, q + 1) * 65536 + readu8(S, q + 2) * 256 + readu8(S, q + 3) + end + local q = rem + if q + 16 > words * 4 + PAD then + return nil, "truncated frame" + end + local stored = u32be(q) + q =q+ 4 + local special = 0 + if st.version > 3820 then + if stored >= TWO31 then + special = u32be(q) + q =q+ 4 + end + stored =stored% TWO31 + end + -- the values + local V = st.V + local order +local mode -- "silence", "pseudo", "stereo", "mono", "multi" + if C == 1 then + if band(special, 1) ~= 0 then + mode = "silence" + order = {} + else + mode = "mono" + order = { 1 } + end + elseif C == 2 then + if band(special, 3) == 3 then + mode = "silence" + order = {} + elseif band(special, 4) ~= 0 then + mode = "pseudo" + order = { 1 } + else + mode, order = "stereo", { 2, 1 } + end + else + mode = "multi" + order = {} + for c = 1, C do + order[c] = c + end + end + local lim = words * 4 + PAD - 40 + if #order > 0 then + local qe = values(st, q, lim, n, order, st.version < 3990) + if not qe or qe > words * 4 + 8 then + return nil, cut and"truncated frame" or"bad frame: the values run over its data" + end + -- the NN filters (last level first), then the predictors + local newDelta = st.version >= 3980 + local filters = st.filters + for _, c in __iter(order) do + for f = #filters, 1, -1 do + nnFilter(filters[f], V[c], n, newDelta, bits >= 32) + end + end + if mode == "stereo" then + predictStereo(st, V[1], V[2], n) + else + for _, c in __iter(order) do + predictOne(st, V[c], n) + end + end + end + -- Unprepare: values -> channels, the CRC over the output bytes as the WAV holds them + local bps = math.floor(bits / 8 +) local cb = st.crcbuf + if buffer.len(cb) < n * C * bps then + cb = buffer.create(n * C * bps + 1024) + st.crcbuf = cb + end + local paired= {} -- first channel (0-based) of an X / Y pair + if C == 2 and mode == "stereo" then + paired[0] = true + elseif C == 4 and (bits == 16 or bits == 24) then + paired[0], paired[2] = true, true + elseif C >= 6 and (bits == 16 or bits == 24) then + paired[0], paired[4] = true, true + if C >= 8 then + paired[6] = true + end + end + local o = 0 + local mono = mode == "mono" or mode == "pseudo" + local X = V[1] + for t = 1, n do + local base = (t - 1) * C + local c = 0 + while c < C do + local a, b2= 0, 0 + local pair = paired[c] + if mode == "silence" then + a = 0 + b2 = 0 + elseif mono then + a = X[t] + b2 = a + elseif pair then + local x, y = V[c + 1][t], V[c + 2][t] + a = x - half(y) + b2 = a + y + else + a = V[c + 1][t] + end + local width = (pair or (C == 2) )and 2 or 1 + for k = 0, width - 1 do + local s= (k == 0 and{a }or{b2 +})[1] if bits == 16 then + if s < -32768 or s > 32767 then + return nil, "sample out of range" + end + writei16(cb, o, s) + o =o+ 2 + elseif bits == 8 then + s = (s + 128) % 256 - 128 + writeu8(cb, o, s + 128) + o =o+ 1 + elseif bits == 24 then + s = (s + 8388608) % 16777216 - 8388608 + local u = s % 16777216 + writeu16(cb, o, u % 65536) + writeu8(cb, o + 2, math.floor(u / 65536)) + o =o+ 3 + else + s = wrap32(s) + writei32(cb, o, s) + o =o+ 4 + end + P[base + c + k + 1] = s + end + c =c+ width + end + end + local crc = Crc32.of(cb, 0, o) + if math.floor(crc / 2 )~= stored then + return nil, "checksum: frame CRC mismatch" + end + if float then + local sc = st.scratch + for k = 1, n * C do + local u = P[k] % TWO32 + local out = bor(band(u, 0xC3FFFFFF), bxor(bnot(band(u, 0x3C000000)), 0xC3FFFFFF)) + if out >= TWO31 then + out = bor(bnot(out), 0x80000000) + end + writeu32(sc, 0, out) + P[k] = readf32(sc, 0) + end + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/ApeTag"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- codecs/audio/ApeTag: APEv1 / APEv2 tags (the tag block of Monkey's Audio, WavPack, Musepack, TTA, OptimFROG and +-- some MP3s) -> Types.Tags. Written from the APEv2 specification (wiki.hydrogenaud.io "APEv2 specification"); no +-- third-party code. A tag sits at the end of the file (before an optional ID3v1 tag) as items + a 32-byte footer +-- "APETAGEX", with an optional 32-byte header in front (APEv2). Item keys become lower case tag keys (Year -> date, +-- Track -> track, Album Artist -> albumartist, Disc -> disc, Comment -> comment); text values holding several +-- values (NUL separated) are joined with "; "; binary items (cover art) and external links stay in info.items. +-- Never throws. +-- +-- local tags, info = ApeTag.find(buf, start, limit) -- the tag ending at limit (or before an ID3v1 tag there) +-- -- tags: { title = ..., artist = ... } | nil (no tag / malformed) +-- -- info: { start = first byte (the header when present), stop = past the footer, version = 1000 | 2000, +-- -- items = { { key = "Title", value = "...", kind = "text" | "binary" | "link" } } } +-- local tags, info = ApeTag.parse(buf, footer, start) -- the tag whose footer is at byte `footer` (>= start) +local ApeTag = {} + + + + +local TO_TAG= { + year = "date", + ["album artist"] = "albumartist", + albumartist = "albumartist", + tracknumber = "track", + discnumber = "disc", + description = "comment", +} +local KINDS = { [0] = "text", "binary", "link", "text" } + +-- tagKey(itemKey) -> the Types.Tags key +function ApeTag.tagKey(key) +local k = string.lower(key) + return TO_TAG[k] or k +end + +-- parse(buf, footer, start?) -> tags, info | nil: the tag whose 32-byte footer starts at byte `footer`; the items +-- must lie at or after `start` (default 0) +function ApeTag.parse(buf, footer, start) +local lo = start or 0 + local n = buffer.len(buf) + if footer < lo or footer + 32 > n or buffer.readstring(buf, footer, 8) ~= "APETAGEX" then + return nil, nil + end + local version = buffer.readu32(buf, footer + 8) + local size = buffer.readu32(buf, footer + 12) -- items + footer + local count = buffer.readu32(buf, footer + 16) + local flags = buffer.readu32(buf, footer + 20) + if size < 32 or footer + 32 - size < lo then + return nil, nil + end + local p = footer + 32 - size + local first = p + if version >= 2000 and bit32.band(flags, 0x80000000) ~= 0 and p - 32 >= lo and buffer.readstring(buf, p - 32, 8) == "APETAGEX" then + first = p - 32 + end + local stop = footer + local tags= {} + local items= {} + for _ = 1, math.min(count, 65536) do + if p + 9 > stop then + break + end + local len = buffer.readu32(buf, p) + local iflags = buffer.readu32(buf, p + 4) + local k = p + 8 + while k < stop and buffer.readu8(buf, k) ~= 0 do + k =k+ 1 + end + if k >= stop then + break + end + local key = buffer.readstring(buf, p + 8, k - p - 8) + local v0 = k + 1 + if len > stop - v0 then + break + end + local value = buffer.readstring(buf, v0, len) + local kind = (version >= 2000 and{KINDS[bit32.band(bit32.rshift(iflags, 1), 3)] }or{"text" +})[1] table.insert(items, { key = key, value = value, kind = kind }) + if kind == "text" and key ~= "" then + local tk = ApeTag.tagKey(key) + local s = (string.gsub(value, "%z+$", "")) + s = (string.gsub(s, "%z", "; ")) + local old = tags[tk] + tags[tk] = (old and((old .. "; " .. s ))or(s +)) end + p = v0 + len + end + return tags, { start = first, stop = footer + 32, version = version, items = items } +end + +-- find(buf, start, limit) -> tags, info | nil: the tag at the end of [start, limit), or just before a 128-byte +-- ID3v1 tag ("TAG") there +function ApeTag.find(buf, start, limit) +if limit > buffer.len(buf) then + limit = buffer.len(buf) + end + if limit - start >= 32 then + local tags, info = ApeTag.parse(buf, limit - 32, start) + if tags then + return tags, info + end + end + if limit - start >= 160 and buffer.readstring(buf, limit - 128, 3) == "TAG" then + return ApeTag.parse(buf, limit - 160, start) + end + return nil, nil +end + +return ApeTag +end +__FILES["codecs/audio/Flac"] = function() +--!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 = __include("codecs/audio/Flac/Frame"), + Encode = __include("codecs/audio/Flac/Encode"), +} + +return Flac +end +__FILES["codecs/audio/Flac/Encode"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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/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 = __include("core/Bits") +local Md5 = __include("core/Md5") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Frame = __include("codecs/audio/Flac/Frame") + +local Encode = {} + +local floor, abs, log = math.floor, math.abs, math.log +local readf32, writeu8 = buffer.readf32, buffer.writeu8 + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ CRCs +-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here) +local function crc8(b, o, n) +return Frame.crc8(b, o, o + n) +end +local function crc16(b, o, n) +return Frame.crc16(b, o, o + n) +end +Encode.crc8, Encode.crc16 = crc8, crc16 +-- ------------------------------------------------------------------------------------------------ bit writer (MSB first) + + + +local function ensure(w, n) + local need = w.pos + n + 16 + local cap = buffer.len(w.buf) + if need > cap then + local nb = buffer.create(math.max(cap * 2, need)) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end +end + +local put = Bits.msbPut + +local function putSigned(w, v, n) + put(w, (v < 0 and((v + POW[n + 1] ))or(v)), n) +end + +local function alignByte(w) + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end +end + +local function putUtf8(w, v) + if v < 0x80 then + put(w, v, 8) + return + end + local n = v < 0x800 and 2 or(v < 0x10000 and 3 or(v < 0x200000 and 4 or(v < 0x4000000 and 5 or(v < 0x80000000 and 6 or 7 +)))) local first = n == 7 and 0xFE or(math.floor(0xFF00 / POW[n + 1])) % 256 -- n leading ones + local shift = 6 * (n - 1) + put(w, first + floor(v / POW[shift + 1]), 8) + for k = n - 2, 0, -1 do + put(w, 0x80 + floor(v / POW[6 * k + 1]) % 64, 8) + end +end +-- ------------------------------------------------------------------------------------------------ presets + + + + + + + + +local PRESETS= { + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 1152, maxLpcOrder = 0, maxPartitionOrder = 3, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 6, maxPartitionOrder = 4, stereo = "independent", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 4, stereo = "adaptive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 5, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 8, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = false }, + { blockSize = 4096, maxLpcOrder = 12, maxPartitionOrder = 6, stereo = "exhaustive", exhaustiveOrder = true }, +} +Encode.PRESETS = PRESETS +-- ------------------------------------------------------------------------------------------------ analysis +-- a subframe plan for one channel signal + + + + + + + + + + + + + + + + + +local function newPlan(n) +return { + kind = 1, + bits = 0, + order = 0, + wasted = 0, + bps = 16, + res = table.create(n, 0), + porder = 0, + params = table.create(64, 0), + method = 0, + qlp = table.create(32, 0), + shift = 0, + precision = 0, + x = table.create(n, 0), + } +end +-- scratch per encoder +-- rice(res, n, order, maxP, plan?) -> bits, porder, method (fills scratch.bestKs with the parameters) + + + + + + + + + + + + + + + + +local function rice(sc, res, n, order, maxP) -- the finest usable partition order + +local p = maxP + while p > 0 and (n % POW[p + 1] ~= 0 or math.floor(n / POW[p + 1] )<= order) do + p =p- 1 + end + local sums, counts = sc.sums, sc.counts + local parts = POW[p + 1] + local ps = math.floor(n / parts +) -- sums of zig-zag values at the finest order + for j = 0, parts - 1 do + local s = 0 + local a = (j == 0 and((order + 1 ))or((j * ps + 1 +))) local e = (j + 1) * ps + for i = a, e do + local r = res[i] + s =s+ (r >= 0 and((2 * r ))or((-2 * r - 1 +))) end + sums[j + 1] = s + counts[j + 1] = e - a + 1 + end + local bestBits, bestP, bestMethod = math.huge, 0, 0 + local ks, bestKs = sc.ks, sc.bestKs + local q = p + while true do + local np = POW[q + 1] + local total = 0 + local maxk = 0 + for j = 1, np do + local s, c = sums[j], counts[j] + local k = 0 + local cost = s + c -- k = 0: unary s, plus one stop bit per sample + if c > 0 and s > c then + local k0 = floor(log(s / c) / 0.6931471805599453) + for kk = math.max(0, k0 - 1), math.min(30, k0 + 1) do + local cc = c * (kk + 1) + floor(s / POW[kk + 1]) + if cc < cost then + cost, k = cc, kk + end + end + end + ks[j] = k + if k > maxk then + maxk = k + end + total =total+ cost + end + local method = maxk > 14 and 1 or 0 + total =total+ (np * (method == 1 and 5 or 4) + 2 + 4 +) if total < bestBits then + bestBits, bestP, bestMethod = total, q, method + for j = 1, np do + bestKs[j] = ks[j] + end + end + if q == 0 then + break + end + -- merge pairs into the next coarser order + for j = 1, math.floor(np / 2 )do + sums[j] = sums[2 * j - 1] + sums[2 * j] + counts[j] = counts[2 * j - 1] + counts[2 * j] + end + q =q- 1 + end + return bestBits, bestP, bestMethod +end + +local function keepRice(sc, plan, porder, method) + plan.porder, plan.method = porder, method + local params = plan.params + for j = 1, POW[porder + 1] do + params[j] = sc.bestKs[j] + end +end + +-- fixed predictor residuals +local function fixedResidual(x, n, order, res) + for i = 1, order do + res[i] = 0 + end + if order == 0 then + for i = 1, n do + res[i] = x[i] + end + elseif order == 1 then + for i = 2, n do + res[i] = x[i] - x[i - 1] + end + elseif order == 2 then + for i = 3, n do + res[i] = x[i] - 2 * x[i - 1] + x[i - 2] + end + elseif order == 3 then + for i = 4, n do + res[i] = x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3] + end + else + for i = 5, n do + res[i] = x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4] + end + end +end + +-- the fixed order with the smallest residual magnitude (libFLAC's estimate) +local function bestFixedOrder(x, n) +if n <= 4 then + return 0, 0 + end + local s0, s1, s2, s3, s4 = 0, 0, 0, 0, 0 + local a, b, c, d = x[4], x[4] - x[3], x[4] - 2 * x[3] + x[2], x[4] - 3 * x[3] + 3 * x[2] - x[1] + for i = 5, n do + local e0 = x[i] + local e1 = e0 - a + local e2 = e1 - b + local e3 = e2 - c + local e4 = e3 - d + s0 =s0+ abs(e0) + s1 =s1+ abs(e1) + s2 =s2+ abs(e2) + s3 =s3+ abs(e3) + s4 =s4+ abs(e4) + a, b, c, d = e0, e1, e2, e3 + end + local best, bs = 0, s0 + if s1 < bs then + best, bs = 1, s1 + end + if s2 < bs then + best, bs = 2, s2 + end + if s3 < bs then + best, bs = 3, s3 + end + if s4 < bs then + best, bs = 4, s4 + end + return best, bs +end +Encode.bestFixedOrder = bestFixedOrder + +-- libFLAC's default QLP coefficient precision for a block size +local function qlpPrecision(bps, n) +if bps > 16 then + return 15 + end + if n <= 192 then + return 7 + elseif n <= 384 then + return 8 + elseif n <= 576 then + return 9 + elseif n <= 1152 then + return 10 + elseif n <= 2304 then + return 11 + elseif n <= 4608 then + return 12 + end + return 13 +end + +-- quantize coefficients lp[1..order] to precision bits: qlp[1..order], shift | nil +local function quantize(lp, order, precision, qlp) +local cmax = 0 + for i = 1, order do + local a = abs(lp[i]) + if a > cmax then + cmax = a + end + end + if cmax <= 0 or cmax ~= cmax or cmax == math.huge then + return nil + end + local log2cmax = 0 + while cmax >= 1 do + cmax =cmax/ 2 + log2cmax =log2cmax+ 1 + end + while cmax < 0.5 do + cmax =cmax* 2 + log2cmax =log2cmax- 1 + end + -- frexp: cmax = m * 2^log2cmax with m in [0.5, 1) + log2cmax =log2cmax- 1 + local p = precision - 1 + local qmax = POW[p + 1] - 1 + local qmin = -POW[p + 1] + local shift = p - log2cmax - 1 + if shift > 15 then + shift = 15 + elseif shift < 0 then + return nil + end + local err = 0 + local scale = POW[shift + 1] + for i = 1, order do + err =err+ lp[i] * scale + local q = floor(err + 0.5) + if q > qmax then + q = qmax + elseif q < qmin then + q = qmin + end + err =err- q + qlp[i] = q + end + return shift +end + +local function lpcResidual(x, n, order, qlp, shift, res) + local d = POW[shift + 1] + for i = 1, order do + res[i] = 0 + end + for i = order + 1, n do + local s = 0 + for j = 1, order do + s =s+ qlp[j] * x[i - j] + end + res[i] = x[i] - floor(s / d) + end +end + +-- Levinson-Durbin: sc.lpc[o][1..o] and sc.err[o] for o = 1 .. maxOrder; returns the highest usable order +local function levinson(sc, maxOrder) +local r = sc.autoc + local e = r[1] + if e <= 0 then + return 0 + end + local a = table.create(maxOrder + 1, 0) + local tmp = table.create(maxOrder + 1, 0) + for o = 1, maxOrder do + local acc = r[o + 1] + for j = 1, o - 1 do + acc =acc- a[j] * r[o - j + 1] + end + local k = acc / e + for j = 1, o - 1 do + tmp[j] = a[j] - k * a[o - j] + end + for j = 1, o - 1 do + a[j] = tmp[j] + end + a[o] = k + e =e* (1 - k * k) + local row = sc.lpc[o] + for j = 1, o do + row[j] = a[j] + end + sc.err[o] = e + if e <= 0 then + return o + end + end + return maxOrder +end + +-- choose the subframe for signal x (n samples, bps bits) into plan (reusing its arrays) +local function analyze(sc, cfg, src, n, bps, plan) + local x = plan.x + -- constant? + local first = src[1] + local constant = true + for i = 1, n do + local v = src[i] + if v ~= first then + constant = false + end + end + if constant then + plan.kind, plan.bits, plan.wasted, plan.bps = 0, 8 + bps, 0, bps + plan.res[1] = first + return + end + -- wasted bits: the common trailing zeros + local wasted = 0 + do + local w = 0 + while w < bps - 1 do + local m = POW[w + 2] + local all = true + for i = 1, n do + if src[i] % m ~= 0 then + all = false + break + end + end + if not all then + break + end + w =w+ 1 + end + wasted = w + end + local d = POW[wasted + 1] + for i = 1, n do + x[i] = src[i] / d + end + local b = bps - wasted + local hdr = 8 + wasted + plan.wasted, plan.bps = wasted, b + -- verbatim + plan.kind, plan.bits = 1, hdr + n * b + -- fixed + local fo = bestFixedOrder(x, n) + if n > fo then + local tmp = sc.tmpRes + fixedResidual(x, n, fo, tmp) + local rb, po, me = rice(sc, tmp, n, fo, cfg.maxPartitionOrder) + local bits = hdr + fo * b + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 2, bits, fo + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + -- lpc + local maxOrder = math.min(cfg.maxLpcOrder, n - 1, 32) + if maxOrder > 0 then + -- windowed autocorrelation + local win = sc.win + if sc.winN ~= n then + -- tukey(0.5) + local np = floor(0.25 * n) + for i = 1, n do + win[i] = 1 + end + if np > 0 then + for i = 0, np - 1 do + local v = 0.5 - 0.5 * math.cos(math.pi * i / np) + win[i + 1] = v + win[n - i] = v + end + end + sc.winN = n + end + local wx = sc.wx + for i = 1, n do + wx[i] = x[i] * win[i] + end + local ac = sc.autoc + for lag = 0, maxOrder do + local s = 0 + for i = lag + 1, n do + s =s+ wx[i] * wx[i - lag] + end + ac[lag + 1] = s + end + local top = levinson(sc, maxOrder) + if top > 0 then + local precision = qlpPrecision(b, n) + local orders = {} + if cfg.exhaustiveOrder then + for o = 1, top do + table.insert(orders, o) + end + else + -- estimated bits: (n - o) * 0.5 * log2(err_o / n) + o * precision + local bestO, bestE = 1, math.huge + for o = 1, top do + local e = sc.err[o] + local est = (e > 0 and(((n - o) * 0.5 * log(e / n) / 0.6931471805599453 + o * (precision + b) ))or((-math.huge +))) if est < bestE then + bestO, bestE = o, est + end + end + orders[1] = bestO + end + local qlp = sc.qlp + for _, o in __iter(orders) do + local prec = precision + local shift = quantize(sc.lpc[o], o, prec, qlp) + if shift then + local tmp = sc.tmpRes + lpcResidual(x, n, o, qlp, shift, tmp) + local rb, po, me = rice(sc, tmp, n, o, cfg.maxPartitionOrder) + local bits = hdr + o * b + 4 + 5 + o * prec + rb + if bits < plan.bits then + plan.kind, plan.bits, plan.order = 3, bits, o + plan.shift, plan.precision = shift, prec + for j = 1, o do + plan.qlp[j] = qlp[j] + end + sc.tmpRes, plan.res = plan.res, tmp + keepRice(sc, plan, po, me) + end + end + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ writing +local function writeResidual(w, plan, n) + local method = plan.method + put(w, method, 2) + local porder = plan.porder + put(w, porder, 4) + local parts = POW[porder + 1] + local ps = math.floor(n / parts +) local res = plan.res + local pbits = method == 1 and 5 or 4 + for j = 0, parts - 1 do + local k = plan.params[j + 1] + put(w, k, pbits) + local a = (j == 0 and((plan.order + 1 ))or((j * ps + 1 +))) local e = (j + 1) * ps + local mk = POW[k + 1] + for i = a, e do + local r = res[i] + local u = (r >= 0 and((2 * r ))or((-2 * r - 1 +))) local hi = floor(u / mk) + local lo = u - hi * mk + if hi + 1 + k <= 32 then + put(w, mk + lo, hi + 1 + k) + else + local q = hi + while q > 24 do + put(w, 0, 24) + q =q- 24 + end + put(w, 1, q + 1) + put(w, lo, k) + end + end + end +end + +local function writeSubframe(w, plan, n) + local kind = plan.kind + local typ = kind == 0 and 0 or(kind == 1 and 1 or(kind == 2 and((8 + plan.order ))or((32 + plan.order - 1 +)))) put(w, 0, 1) + put(w, typ, 6) + if kind ~= 0 and plan.wasted > 0 then + put(w, 1, 1) + put(w, 1, plan.wasted) -- k - 1 zeros, then a one + else + put(w, 0, 1) + end + local b = plan.bps + if kind == 0 then + putSigned(w, plan.res[1], b) + return + end + local x = plan.x + if kind == 1 then + for i = 1, n do + putSigned(w, x[i], b) + end + return + end + for i = 1, plan.order do + putSigned(w, x[i], b) + end + if kind == 3 then + put(w, plan.precision - 1, 4) + put(w, plan.shift, 5) + for j = 1, plan.order do + putSigned(w, plan.qlp[j], plan.precision) + end + end + writeResidual(w, plan, n) +end + +local RATE_CODES= { + [88200] = 1, + [176400] = 2, + [192000] = 3, + [8000] = 4, + [16000] = 5, + [22050] = 6, + [24000] = 7, + [32000] = 8, + [44100] = 9, + [48000] = 10, + [96000] = 11, +} +local SIZE_CODES= { [8] = 1, [12] = 2, [16] = 4, [20] = 5, [24] = 6, [32] = 7 } + +local function blockCode(n) +if n == 192 then + return 1, 0 + end + for k = 2, 5 do + if n == 576 * POW[k - 1] then + return k, 0 + end + end + for k = 8, 15 do + if n == 256 * POW[k - 7] then + return k, 0 + end + end + if n <= 256 then + return 6, 8 + end + return 7, 16 +end +-- ------------------------------------------------------------------------------------------------ encoder +-- encode(src, opts) -> buffer | nil, message + + + + + + + + + + + + + + + + + + +function Encode.encode(src, opts) +local cfg = PRESETS[opts.level + 1] + local ch, rate, bps = src.channels, src.sampleRate, opts.bits + local bs = opts.blockSize or cfg.blockSize + local w= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + -- metadata + put(w, 0x664C6143, 32) -- "fLaC" + put(w, 0, 1) + put(w, 0, 7) + put(w, 34, 24) + local siData = w.pos + for _ = 1, 34 do + put(w, 0, 8) + end + -- seek table placeholders (when the length is known) + local seekPoints = 0 + local seekAt = 0 + local interval = floor(opts.seekInterval * rate) + if interval > 0 and src.frames > 0 then + seekPoints = math.floor((src.frames - 1) / interval )+ 1 + if seekPoints > math.floor(65535 / 18 )* 18 then + seekPoints = 0 + end + end + -- vorbis comment + local comments = VorbisComment.fields(src.tags) + local vendor = opts.vendor + local vcLen = 4 + #vendor + 4 + for _, c in __iter(comments) do + vcLen =vcLen+ (4 + #c +) end + -- SEEKTABLE + if seekPoints > 0 then + put(w, 0, 1) + put(w, 3, 7) + put(w, seekPoints * 18, 24) + seekAt = w.pos + ensure(w, seekPoints * 18) + for _ = 1, seekPoints do + put(w, 0xFFFFFFFF, 32) -- sample number: a placeholder until a frame fills it + put(w, 0xFFFFFFFF, 32) + put(w, 0, 32) -- byte offset + put(w, 0, 32) + put(w, 0, 16) -- frame samples + end + end + -- VORBIS_COMMENT (little-endian lengths) + local function le32(v) + put(w, v % 256, 8) + put(w, (math.floor(v / 256)) % 256, 8) + put(w, (math.floor(v / 65536)) % 256, 8) + put(w, math.floor(v / 16777216), 8) + end + ensure(w, vcLen + 8) + put(w, opts.padding > 0 and 0 or 1, 1) -- the last metadata block unless PADDING follows + put(w, 4, 7) + put(w, vcLen, 24) + le32(#vendor) + for i = 1, #vendor do + put(w, string.byte(vendor, i), 8) + end + le32(#comments) + for _, c in __iter(comments) do + ensure(w, #c + 8) + le32(#c) + for i = 1, #c do + put(w, string.byte(c, i), 8) + end + end + if opts.padding > 0 then + ensure(w, opts.padding + 8) + put(w, 1, 1) + put(w, 1, 7) + put(w, opts.padding, 24) + for _ = 1, opts.padding do + put(w, 0, 8) + end + end + local audioStart = w.pos + -- frames + local md5 = Md5.new() + local mbytes = math.floor((bps + 7) / 8 +) local mbuf = buffer.create(bs * ch * mbytes) + local scale = POW[bps] + local maxv, minv = scale - 1, -scale + local X= (table.create(ch) ) +for c = 1, ch do + X[c] = table.create(bs, 0) + end + local side = table.create(bs, 0) + local mid = table.create(bs, 0) + local plans = {} + for i = 1, 4 do + plans[i] = newPlan(bs) + end + for c = 1, ch do + plans[4 + c] = newPlan(bs) + end + local lpcRows = {} + for o = 1, 32 do + lpcRows[o] = table.create(o, 0) + end + local sc= { + sums = table.create(64, 0), + counts = table.create(64, 0), + ks = table.create(64, 0), + bestKs = table.create(64, 0), + tmpRes = table.create(bs, 0), + win = table.create(bs, 0), + winN = 0, + wx = table.create(bs, 0), + autoc = table.create(33, 0), + lpc = lpcRows, + err = table.create(32, 0), + qlp = table.create(32, 0), + } + local frameNo = 0 + local total = 0 + local minFrame, maxFrame = math.huge, 0 + local seekNext = 0 + local seekIdx = 0 + local rateCode = RATE_CODES[rate] or 0 + local sizeCode = SIZE_CODES[bps] or 0 + local tmp= nil + local pendingBuf= nil + local pendingN, pendingOff = 0, 0 + -- read exactly bs frames (fewer only at the end) + local function readBlock() +local out = buffer.create(bs * ch * 4) + local got = 0 + while got < bs do + if pendingN == 0 then + local b, n = src:read(math.max(bs, 4096), tmp) + if n <= 0 then + break + end + tmp = b + pendingBuf, pendingN, pendingOff = b, n, 0 + end + local take = math.min(bs - got, pendingN) + buffer.copy(out, got * ch * 4, pendingBuf , pendingOff * ch * 4, take * ch * 4) + got =got+ take + pendingN =pendingN- take + pendingOff =pendingOff+ take + end + return out, got + end + while true do + local fb, n = readBlock() + if n <= 0 or fb == nil then + break + end + -- to integers (+ the MD5 bytes, signed little endian) + local mo = 0 + for i = 0, n - 1 do + for c = 1, ch do + local v = floor(readf32(fb, (i * ch + c - 1) * 4) * scale + 0.5) + if v ~= v then + v = 0 + elseif v > maxv then + v = maxv + elseif v < minv then + v = minv + end + X[c][i + 1] = v + local u = (v < 0 and((v + 4294967296 ))or(v +)) for k = 0, mbytes - 1 do + writeu8(mbuf, mo, floor(u / POW[8 * k + 1]) % 256) + mo =mo+ 1 + end + end + end + md5:update(mbuf, 0, mo) + -- channel decorrelation + local assign = ch - 1 + local chosen= {} + if ch == 2 and cfg.stereo ~= "independent" then + local L, R = X[1], X[2] + for i = 1, n do + local l, r = L[i], R[i] + side[i] = l - r + mid[i] = floor((l + r) / 2) + end + local pl, pr, pm, ps = plans[1], plans[2], plans[3], plans[4] + if cfg.stereo == "adaptive" then + local _, el = bestFixedOrder(L, n) + local _, er = bestFixedOrder(R, n) + local _, em = bestFixedOrder(mid, n) + local _, es = bestFixedOrder(side, n) + -- the estimate picks one decorrelated pair; it is kept only if it beats left / right for real + local best = math.min(el + es, er + es, em + es) + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + chosen, assign = { pl, pr }, 1 + if best < el + er then + analyze(sc, cfg, side, n, bps + 1, ps) + if best == em + es then + analyze(sc, cfg, mid, n, bps, pm) + if pm.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pm, ps }, 10 + end + elseif best == el + es then + if pl.bits + ps.bits < pl.bits + pr.bits then + chosen, assign = { pl, ps }, 8 + end + elseif ps.bits + pr.bits < pl.bits + pr.bits then + chosen, assign = { ps, pr }, 9 + end + end + else + analyze(sc, cfg, L, n, bps, pl) + analyze(sc, cfg, R, n, bps, pr) + analyze(sc, cfg, mid, n, bps, pm) + analyze(sc, cfg, side, n, bps + 1, ps) + local lr, ls, rs, msb = pl.bits + pr.bits, pl.bits + ps.bits, ps.bits + pr.bits, pm.bits + ps.bits + local best = math.min(lr, ls, rs, msb) + if best == lr then + chosen, assign = { pl, pr }, 1 + elseif best == msb then + chosen, assign = { pm, ps }, 10 + elseif best == ls then + chosen, assign = { pl, ps }, 8 + else + chosen, assign = { ps, pr }, 9 + end + end + else + for c = 1, ch do + analyze(sc, cfg, X[c], n, bps, plans[4 + c]) + chosen[c] = plans[4 + c] + end + end + -- the frame + local need = n * ch * 4 + 64 + for _, p in __iter(chosen) do + need =need+ ((math.floor(p.bits / 8)) + 8 +) end + ensure(w, need) + local start = w.pos + -- seek points: the first frame at or after each multiple of the interval + while seekIdx < seekPoints and total >= seekNext do + local at = seekAt + seekIdx * 18 + local sn, off = total, start - audioStart + local tb = w.buf + for k = 0, 7 do + writeu8(tb, at + k, floor(sn / POW[8 * (7 - k) + 1]) % 256) + writeu8(tb, at + 8 + k, floor(off / POW[8 * (7 - k) + 1]) % 256) + end + writeu8(tb, at + 16, math.floor(n / 256)) + writeu8(tb, at + 17, n % 256) + seekIdx =seekIdx+ 1 + seekNext = seekIdx * interval + end + put(w, 0x3FFE, 14) + put(w, 0, 1) + put(w, 0, 1) -- fixed block size + local bcode, bextra = blockCode(n) + put(w, bcode, 4) + put(w, rateCode, 4) + put(w, assign, 4) + put(w, sizeCode, 3) + put(w, 0, 1) + putUtf8(w, frameNo) + if bextra > 0 then + put(w, n - 1, bextra) + end + put(w, crc8(w.buf, start, w.pos - start), 8) + for _, p in __iter(chosen) do + writeSubframe(w, p, n) + end + alignByte(w) + local c16 = crc16(w.buf, start, w.pos - start) + put(w, c16, 16) + local fsize = w.pos - start + if fsize < minFrame then + minFrame = fsize + end + if fsize > maxFrame then + maxFrame = fsize + end + frameNo =frameNo+ 1 + total =total+ n + if n < bs then + break + end + end + if src.err then + return nil, tostring(src.err) + end + -- unused seek points stay placeholders; STREAMINFO + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + local si = Encode.streaminfo(bs, (frameNo > 0 and{minFrame }or{0})[1], maxFrame, rate, ch, bps, total, md5:digest()) + buffer.copy(out, siData, si, 0, 34) + return out, nil +end + +-- streaminfo(...) -> the 34-byte STREAMINFO body +function Encode.streaminfo(bs, minFrame, maxFrame, rate, ch, bps, total, md5) +local w= { buf = buffer.create(64), pos = 0, acc = 0, cnt = 0 } + put(w, bs, 16) + put(w, bs, 16) + put(w, minFrame, 24) + put(w, maxFrame, 24) + put(w, rate, 20) + put(w, ch - 1, 3) + put(w, bps - 1, 5) + put(w, floor(total / 2 ^ 32), 4) + put(w, total % 2 ^ 32, 32) + for i = 1, 16 do + put(w, string.byte(md5, i), 8) + end + local out = buffer.create(34) + buffer.copy(out, 0, w.buf, 0, 34) + return out +end + +return Encode +end +__FILES["codecs/audio/Flac/Frame"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 +-- words without bounds checks and instead compares its position with the data end once per sample. Nothing here +-- throws: bad data gives nil, err. +-- Absorbed from flac-luau 7083d0d (same author, no third-party code). +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, bxor, lshift, rshift, countlz, byteswap = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift, + bit32.countlz, bit32.byteswap +local floor = math.floor + +local Frame = {} +Frame.PAD = 32 + +-- CRC-8 (poly 0x07) and CRC-16 (poly 0x8005), MSB first, init 0 +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 = (band(c, 0x80) ~= 0 and{(band(bxor(lshift(c, 1), 0x07), 0xFF) )}or{(band(lshift(c, 1), 0xFF) +)})[1] end + CRC8[i + 1] = c + local d = lshift(i, 8) + for _ = 1, 8 do + d = (band(d, 0x8000) ~= 0 and{(band(bxor(lshift(d, 1), 0x8005), 0xFFFF) )}or{(band(lshift(d, 1), 0xFFFF) +)})[1] end + CRC16[i + 1] = d +end + +local function crc16(b, from, to) +local c = 0 + for i = from, to - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), CRC16[bxor(rshift(c, 8), readu8(b, i)) + 1]) + end + return c +end +Frame.crc16 = crc16 + +local function crc8(b, from, to) +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 +end + +local BLOCK = { [1] = 192, [2] = 576, [3] = 1152, [4] = 2304, [5] = 4608, [8] = 256, [9] = 512, [10] = 1024, + [11] = 2048, [12] = 4096, [13] = 8192, [14] = 16384, [15] = 32768 } +local RATE = { [1] = 88200, [2] = 176400, [3] = 192000, [4] = 8000, [5] = 16000, [6] = 22050, [7] = 24000, + [8] = 32000, [9] = 44100, [10] = 48000, [11] = 96000 } +local BITS = { [1] = 8, [2] = 12, [4] = 16, [5] = 20, [6] = 24, [7] = 32 } + +-- Parse the frame header at pos (data ends at len; the buffer is padded). si gives the STREAMINFO defaults +-- (sampleRate, bitsPerSample) for the "from STREAMINFO" codes. Returns nil when it is not a valid header. + + + + + + + + + + + + +function Frame.header(b, pos, len, si) +if pos < 0 or pos + 6 > len then + return nil + end + if readu8(b, pos) ~= 0xFF then + return nil + end + local b1 = readu8(b, pos + 1) + if band(b1, 0xFE) ~= 0xF8 then + return nil + end + local b2 = readu8(b, pos + 2) + local b3 = readu8(b, pos + 3) + local bsCode, rCode = rshift(b2, 4), band(b2, 15) + local chCode, sCode = rshift(b3, 4), band(rshift(b3, 1), 7) + if bsCode == 0 or rCode == 15 or chCode > 10 or sCode == 3 or band(b3, 1) ~= 0 then + return nil + end + -- UTF-8-like coded number + local p = pos + 4 + local x = readu8(b, p) + p =p+ 1 + local num, more + if x < 0x80 then + num, more = x, 0 + elseif x >= 0xC0 and x < 0xE0 then + num, more = band(x, 0x1F), 1 + elseif x >= 0xE0 and x < 0xF0 then + num, more = band(x, 0x0F), 2 + elseif x >= 0xF0 and x < 0xF8 then + num, more = band(x, 0x07), 3 + elseif x >= 0xF8 and x < 0xFC then + num, more = band(x, 0x03), 4 + elseif x >= 0xFC and x < 0xFE then + num, more = band(x, 0x01), 5 + elseif x == 0xFE then + num, more = 0, 6 + else + return nil + end + for _ = 1, more do + local c = readu8(b, p) + p =p+ 1 + if band(c, 0xC0) ~= 0x80 then + return nil + end + num = num * 64 + band(c, 0x3F) + end + local variable = band(b1, 1) == 1 + if not variable and more > 5 then + return nil + end + local bs = BLOCK[bsCode] + if bsCode == 6 then + bs = readu8(b, p) + 1 + p =p+ 1 + elseif bsCode == 7 then + bs = readu8(b, p) * 256 + readu8(b, p + 1) + 1 + p =p+ 2 + end + local rate = RATE[rCode] + if rCode == 0 then + rate = si and si.sampleRate or 0 + elseif rCode == 12 then + rate = readu8(b, p) * 1000 + p =p+ 1 + elseif rCode == 13 then + rate = readu8(b, p) * 256 + readu8(b, p + 1) + p =p+ 2 + elseif rCode == 14 then + rate = (readu8(b, p) * 256 + readu8(b, p + 1)) * 10 + p =p+ 2 + end + local bps = BITS[sCode] + if sCode == 0 then + bps = si and si.bitsPerSample or 0 + end + if not bs or not bps or bps < 4 or bps > 32 or p + 1 > len then + return nil + end + -- CRC-8 over the header + if crc8(b, pos, p) ~= readu8(b, p) then + return nil + end + return { + offset = pos, + size = p + 1 - pos, + blockSize = bs, + sampleRate = rate or 0, + channels = (chCode < 8 and((chCode + 1 ))or(2)), + assignment = chCode, + bps = bps, + variable = variable, + number = num, + } +end + +-- The first valid header at an offset in [pos, limit) +function Frame.find(b, pos, limit, len, si) +local lim = math.min(limit, len - 6) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0xFF then + local b1 = readu8(b, pos + 1) + if b1 == 0xF8 or b1 == 0xF9 then + local h = Frame.header(b, pos, len, si) + if h then + return h + end + end + end + pos =pos+ 1 + end + return nil +end + +-- Bit reading for the header parts of subframes: n <= 32 bits at bit position p (unsigned) +local function bits(b, p, n) +if n == 0 then + return 0 + elseif n <= 24 then + return rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - n) + end + local hi = rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), 32 - (n - 16)) + local q = p + n - 16 + return hi * 65536 + rshift(lshift(byteswap(readu32(b, rshift(q, 3))), band(q, 7)), 16) +end + +local function sbits(b, p, n) +local v = bits(b, p, n) + if n > 0 and v >= POW2[n] then + v =v- POW2[n + 1] + end + return v +end + +-- Residual coding: fills s[order + 1 .. n] with residuals. Returns the new bit position, or -1. +local function residual(b, p, lim, s, n, order) +local method = bits(b, p, 2) + if method > 1 then + return -1 + end + local porder = bits(b, p + 2, 4) + p =p+ 6 + local pbits = method == 0 and 4 or 5 + local escape = method == 0 and 15 or 31 + local parts = POW2[porder + 1] + local psize = rshift(n, porder) + if psize * parts ~= n or psize < order then + return -1 + end + local i = order + 1 + for part = 0, parts - 1 do + if p > lim then + return -1 + end + local k = bits(b, p, pbits) + p =p+ pbits + local stop = (part + 1) * psize + if k == escape then + local nb = bits(b, p, 5) + p =p+ 5 + if nb == 0 then + for j = i, stop do + s[j] = 0 + end + else + local half, full = POW2[nb], POW2[nb + 1] + for j = i, stop do + if p > lim then + return -1 + end + local v = bits(b, p, nb) + p =p+ nb + if v >= half then + v =v- full + end + s[j] = v + end + end + elseif k <= 24 then + -- the hot loop: unary quotient + k-bit remainder, zigzag + local pk = POW2[k + 1] + local rk = 32 - k + for j = i, stop do + if p > lim then + return -1 + end + local sh = band(p, 7) + local w = lshift(byteswap(readu32(b, rshift(p, 3))), sh) + local q, r + if w ~= 0 then + q = countlz(w) + local used = q + 1 + k + if used <= 32 - sh then + r = k == 0 and 0 or rshift(lshift(w, q + 1), rk) + p =p+ used + else + p =p+ (q + 1 +) r = k == 0 and 0 or rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p =p+ k + end + else + -- a long run of zeros + q = 32 - sh + p =p+ q + while true do + if p > lim then + return -1 + end + local w2 = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w2 ~= 0 then + local z = countlz(w2) + q =q+ z + p =p+ (z + 1 +) break + end + local adv = 32 - band(p, 7) + q =q+ adv + p =p+ adv + end + r = k == 0 and 0 or rshift(lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)), rk) + p =p+ k + end + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = (h + h == u and{h }or{(-h - 1 +)})[1] end + else + -- k = 25..30 (Rice2): the remainder takes two reads + local pk = POW2[k + 1] + for j = i, stop do + if p > lim then + return -1 + end + local q = 0 + while true do + if p > lim then + return -1 + end + local w = lshift(byteswap(readu32(b, rshift(p, 3))), band(p, 7)) + if w ~= 0 then + local z = countlz(w) + q =q+ z + p =p+ (z + 1 +) break + end + local adv = 32 - band(p, 7) + q =q+ adv + p =p+ adv + end + local r = bits(b, p, k) + p =p+ k + local u = q * pk + r + local h = floor(u * 0.5) + s[j] = (h + h == u and{h }or{(-h - 1 +)})[1] end + end + i = stop + 1 + end + return p +end + +local function fixed(s, n, order) + if order == 1 then + local a = s[1] + for i = 2, n do + a =a+ s[i] + s[i] = a + end + elseif order == 2 then + local a, c = s[2], s[1] + for i = 3, n do + local v = s[i] + 2 * a - c + s[i] = v + c = a + a = v + end + elseif order == 3 then + local a, c, d = s[3], s[2], s[1] + for i = 4, n do + local v = s[i] + 3 * a - 3 * c + d + s[i] = v + d = c + c = a + a = v + end + elseif order == 4 then + local a, c, d, e = s[4], s[3], s[2], s[1] + for i = 5, n do + local v = s[i] + 4 * a - 6 * c + 4 * d - e + s[i] = v + e = d + d = c + c = a + a = v + end + end +end + +-- LPC restoration: s[i] += floor(sum(coef[j] * s[i - j]) / 2^shift); unrolled for orders up to 12 +local function lpc(s, n, cf, order, shift) + local div = POW2[shift + 1] + local inv = 1 / div + if order <= 4 then + local c1, c2, c3, c4 = cf[1], cf[2] or 0, cf[3] or 0, cf[4] or 0 + local s1, s2, s3, s4 = s[order], s[order - 1] or 0, s[order - 2] or 0, s[order - 3] or 0 + for i = order + 1, n do + local v = s[i] + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4) * inv) + s[i] = v + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 8 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6] or 0, cf[7] or 0, cf[8] or 0 + local s1, s2, s3, s4, s5 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4] + local s6, s7, s8 = s[order - 5] or 0, s[order - 6] or 0, s[order - 7] or 0 + for i = order + 1, n do + local v = s[i] + + floor((c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + c7 * s7 + c8 * s8) * inv) + s[i] = v + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + elseif order <= 12 then + local c1, c2, c3, c4, c5, c6, c7, c8 = cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7], cf[8] + local c9, c10, c11, c12 = cf[9], cf[10] or 0, cf[11] or 0, cf[12] or 0 + local s1, s2, s3, s4, s5, s6 = s[order], s[order - 1], s[order - 2], s[order - 3], s[order - 4], s[order - 5] + local s7, s8, s9 = s[order - 6], s[order - 7], s[order - 8] + local s10, s11, s12 = s[order - 9] or 0, s[order - 10] or 0, s[order - 11] or 0 + for i = order + 1, n do + local v = s[i] + + floor( + ( + c1 * s1 + c2 * s2 + c3 * s3 + c4 * s4 + c5 * s5 + c6 * s6 + + c7 * s7 + c8 * s8 + c9 * s9 + c10 * s10 + c11 * s11 + c12 * s12 + ) * inv + ) + s[i] = v + s12 = s11 + s11 = s10 + s10 = s9 + s9 = s8 + s8 = s7 + s7 = s6 + s6 = s5 + s5 = s4 + s4 = s3 + s3 = s2 + s2 = s1 + s1 = v + end + else + for i = order + 1, n do + local sum = 0 + for j = 1, order do + sum =sum+ cf[j] * s[i - j] + end + s[i]=s[i]+ floor(sum * inv) + end + end +end + +-- One subframe into s[1..n]. Returns the new bit position, or -1. +local function subframe(b, p, lim, s, n, bps, cf) +if p > lim then + return -1 + end + local hdr = bits(b, p, 8) + p =p+ 8 + if hdr >= 128 then + return -1 + end + local typ = rshift(hdr, 1) + local wasted = 0 + if band(hdr, 1) == 1 then + -- unary count of wasted bits (minus one) + while true do + if p > lim or wasted > 32 then + return -1 + end + local bit = bits(b, p, 1) + p =p+ 1 + wasted =wasted+ 1 + if bit == 1 then + break + end + end + bps =bps- wasted + if bps < 1 then + return -1 + end + end + if typ == 0 then + local v = sbits(b, p, bps) + p =p+ bps + for i = 1, n do + s[i] = v + end + elseif typ == 1 then + for i = 1, n do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p =p+ bps + end + elseif typ >= 8 and typ <= 12 then + local order = typ - 8 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p =p+ bps + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + fixed(s, n, order) + elseif typ >= 32 then + local order = typ - 31 + if order > n then + return -1 + end + for i = 1, order do + if p > lim then + return -1 + end + s[i] = sbits(b, p, bps) + p =p+ bps + end + local prec = bits(b, p, 4) + 1 + p =p+ 4 + if prec == 16 then + return -1 + end + local shift = sbits(b, p, 5) + p =p+ 5 + if shift < 0 then + return -1 + end + for j = 1, order do + if p > lim then + return -1 + end + cf[j] = sbits(b, p, prec) + p =p+ prec + end + for j = order + 1, 12 do + cf[j] = 0 -- the unrolled filters read up to 12 coefficients + end + p = residual(b, p, lim, s, n, order) + if p < 0 then + return -1 + end + lpc(s, n, cf, order, shift) + else + return -1 + end + if wasted > 0 then + local m = POW2[wasted + 1] + for i = 1, n do + s[i]=s[i]* m + end + end + return p +end + +-- Decode the frame whose header h was parsed (data ends at len). chans[c] are tables of at least h.blockSize +-- numbers; they receive the samples. Returns the byte offset after the frame, or nil, err. +function Frame.decode(b, len, h, chans, cf, checkCrc) +local n = h.blockSize + local lim = len * 8 + local p = (h.offset + h.size) * 8 + local asg = h.assignment + for c = 1, h.channels do + local bps = h.bps + if (asg == 8 and c == 2) or (asg == 9 and c == 1) or (asg == 10 and c == 2) then + bps =bps+ 1 -- the side channel + end + p = subframe(b, p, lim, chans[c], n, bps, cf) + if p < 0 then + return nil, "bad subframe" + end + end + local e = rshift(p + 7, 3) -- byte align + if e + 2 > len then + return nil, "truncated frame" + end + if checkCrc then + local want = readu8(b, e) * 256 + readu8(b, e + 1) + if crc16(b, h.offset, e) ~= want then + return nil, "crc16 mismatch" + end + end + if asg >= 8 then + local l, r = chans[1], chans[2] + if asg == 8 then + for i = 1, n do + r[i] = l[i] - r[i] + end + elseif asg == 9 then + for i = 1, n do + l[i]=l[i]+ r[i] + end + else + for i = 1, n do + local side = r[i] + local m = l[i] * 2 + (side % 2) + l[i] = (m + side) * 0.5 + r[i] = (m - side) * 0.5 + end + end + end + return e + 2, nil +end + +return Frame +end +__FILES["codecs/audio/Hively"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/audio/Hively: the AHX / HivelyTracker engine behind music/ahx and music/hvl: the loader for both file formats +-- (Load), the replayer with its waveform generator (Tables: triangle / sawtooth / square / noise and the 31 + 31 +-- filtered copies) and integer mixer (Player), and the render glue to a Types.Decoder (stereo f32). A port of +-- HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt): +-- at hvl2wav's settings the output equals hvl2wav's 16-bit samples / 32768, sample for sample. +-- +-- local Hively = require("rosetta.codecs.audio.Hively") +-- local tune, err = Hively.parse(buf, 0, buffer.len(buf)) -- the replayer's Tune +-- local song = Hively.module(tune) -- a Types.Module-shaped value with render() +-- local dec = Hively.decoder(tune, { sampleRate = 44100 }) -- a Types.Decoder +-- +-- Not supported: hvl2wav's -a auto gain; a speed multiplier of 4 at 44.1 kHz renders 880 samples per 50 Hz frame +-- (hvl2wav pads each frame to 882 with stale samples). +local Err = __include("core/Err") +local Types = __include("Types") +local Load = __include("codecs/audio/Hively/Load") +local Player = __include("codecs/audio/Hively/Player") +local Pcm = __include("codecs/audio/Pcm") + +local Hively = {} + +-- parse(b, base?, limit?) -> Tune | nil, Err + + + + + + + + + +function Hively.parse(b, base, limit) +local tune, msg, kind = Load.parse(b, base or 0, limit or buffer.len(b)) + if not tune then + return nil, Err.from(msg or "corrupt", nil, kind) + end + return tune, nil +end + +local function settings(tune, opts) +local o= opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 8000 or rate > 192000 or rate % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, "render: sampleRate must be an integer 8000..192000") + end + local sub = o.subsong or 0 + if type(sub) ~= "number" or sub < 0 or sub > #tune.subsongs or sub % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, string.format("render: subsong must be 0..%d", #tune.subsongs)) + end + return rate, sub, tonumber(o.stereo) or 0, nil +end + +-- frameCount(tune, opts?) -> 50 Hz frames until the song end (as hvl2wav stops), capped by maxDuration +function Hively.frameCount(tune, opts) +local rate, sub, stereo = settings(tune, opts) + local st = rate and Player.new(tune, rate , stereo, sub) + if not st then + return 0 + end + local maxFrames = math.floor(((opts and opts.maxDuration) or 600) * 50) + local n = 0 + while n < maxFrames and not st.songEndReached do + for _ = 1, tune.speedMultiplier do + Player.irq(st, false) + end + n =n+ 1 + end + return n +end + +-- decoder(tune, opts?) -> Types.Decoder | nil, Err +function Hively.decoder(tune, opts) +local rate, sub, stereo, err = settings(tune, opts) + if not rate then + return nil, err + end + local sr = rate +local mult = tune.speedMultiplier + local perIrq = math.floor(math.floor(sr / 50 )/ mult +) local perFrame = perIrq * mult + local nframes = Hively.frameCount(tune, opts) + local frames = nframes * perFrame + local loop = opts ~= nil and opts.loop == true + local st = (Player.new(tune, sr, stereo, sub) ) +local fbuf = buffer.create(perFrame * 8) + local fpos, ffill = 0, 0 -- read position / filled frames inside fbuf + local pos = 0 + + local function nextFrame() + for k = 0, mult - 1 do + Player.irq(st, true) + Player.mix(st, fbuf, k * perIrq, perIrq) + end + fpos, ffill = 0, perFrame + end + + local dec = { + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = (tune.title ~= "" and{tune.title }or{nil })[1]} , + } + local function read(_self, n, out) +n = math.max(0, math.floor(n)) + if not loop then + n = math.min(n, frames - pos) + end + local b = out + if not b or buffer.len(b) < n * 8 then + b = buffer.create(math.max(n, 1) * 8) + end + local ob = b +local done = 0 + while done < n do + if fpos >= ffill then + nextFrame() + end + local k = math.min(n - done, ffill - fpos) + buffer.copy(ob, done * 8, fbuf, fpos * 8, k * 8) + fpos =fpos+ k + done =done+ k + end + pos =pos+ n + return ob, n + end + dec.read = read +local scratch = buffer.create(4096 * 8) + dec.seek = function(_self, seconds) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * sr)) + if not loop then + target = math.min(target, frames) + end + if target < pos then + st = (Player.new(tune, sr, stereo, sub) ) +pos, fpos, ffill = 0, 0, 0 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end +dec.position = function(_self) +return pos / sr + end +return (dec ) , nil +end + +-- module(tune) -> a Types.Module-shaped value (kind "music"): tracks as patterns (rows * 6 bytes: note, instrument, +-- fx, param, fxb, paramb), positions, instruments with their play lists, and render(opts) -> Decoder +function Hively.module(tune) +local patterns = {} + for t = 0, tune.trackNr do + local data = buffer.create(tune.trackLength * 6) + buffer.copy(data, 0, tune.tracks, t * 64 * 6, tune.trackLength * 6) + patterns[t + 1] = { rows = tune.trackLength, data = data } + end + local order, positions = {}, {} + for i = 0, tune.positionNr - 1 do + order[i + 1] = i + local tr, tp = {}, {} + for c = 0, tune.channels - 1 do + tr[c + 1] = buffer.readu8(tune.positions, (i * 16 + c) * 2) + tp[c + 1] = buffer.readi8(tune.positions, (i * 16 + c) * 2 + 1) + end + positions[i + 1] = { tracks = tr, transpose = tp } + end + local m= { + kind = "music", + format = tune.format, + title = tune.title, + channels = tune.channels, + speed = 6, + tempo = 125 * tune.speedMultiplier, -- 50 Hz player calls per speed multiplier (a tick lasts 2.5 / tempo s) + patterns = patterns, + order = order, + positions = positions, + restart = tune.restart, + subsongs = table.clone(tune.subsongs), + instruments = tune.instruments, + samples = {}, + meta = { + source = { + format = tune.format, + version = tune.version, + speedMultiplier = tune.speedMultiplier, + trackLength = tune.trackLength, + tracks = tune.trackNr + 1, + mixgain = (tune.format == "hvl" and{tune.mixgain }or{nil})[1], + stereo = (tune.format == "hvl" and{tune.stereo }or{nil})[1], + }, + }, + tune = tune, + } + m.render = function(self, opts) +local dec, derr = Hively.decoder(self.tune, opts) + if dec then + return dec + end + -- the Types contract returns a Decoder: a failed render is an empty one carrying the Err + local empty= Pcm.audioDecoder(Types.Audio.new(44100, 2, 0)) + empty.err = derr + return empty + end + return m +end + +return Hively +end +__FILES["codecs/audio/Hively/Load"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- codecs/audio/Hively/Load: AHX ("THX\0".."THX\2") and HivelyTracker ("HVL\0", "HVL\1") module files -> the replayer's +-- Tune. Ported from hvl2wav's replay.c 1.9 loaders (hvl_load_ahx / hvl_reset; BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt), with bounds checks the C code does not have. Errors are returned as +-- (nil, message, kind) for core/Err.from. +local Load = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function cstring(b, p, limit, max) +local e = p + while e < limit and e - p < max and readu8(b, e) ~= 0 do + e =e+ 1 + end + return buffer.readstring(b, p, e - p), e +end + +-- parse(b, base, limit) -> Tune | nil, message, kind +function Load.parse(b, base, limit) +local size = limit - base + if size < 14 then + return nil, "truncated header", "truncated" + end + local function u8(o) +return readu8(b, base + o) + end + local magic = buffer.readstring(b, base, 3) + local ahx = magic == "THX" and u8(3) < 3 + if not ahx and not (magic == "HVL" and u8(3) <= 1) then + return nil, "not an AHX / HVL module", nil + end + if not ahx and size < 16 then + return nil, "truncated header", "truncated" + end + local posn = bit32.band(u8(6), 0x0f) * 256 + u8(7) + local insn, ssn, trkl, trkn = u8(12), u8(13), u8(10), u8(11) + local chnn = ahx and 4 or bit32.rshift(u8(8), 2) + 4 + local tune= { + format = ahx and"ahx" or"hvl", + version = u8(3), + title = "", + channels = chnn, + positionNr = posn, + restart = (ahx and{(u8(8) * 256 + u8(9) )}or{(bit32.band(u8(8), 3) * 256 + u8(9))})[1], + speedMultiplier = bit32.band(bit32.rshift(u8(6), 5), 3) + 1, + trackLength = trkl, + trackNr = trkn, + instrumentNr = insn, + subsongs = {}, + positions = buffer.create(math.max(posn, 1) * 32), + tracks = buffer.create(257 * 64 * 6), + instruments = {}, + mixgain = ahx and 256 or math.floor((u8(14) * 256) / 100), + stereo = ahx and 0 or math.min(u8(15), 4), + emptyTrack0 = bit32.band(u8(6), 0x80) ~= 0, + } + if posn == 0 or posn > 1000 or trkl > 64 or trkl == 0 or insn > 64 then + return nil, string.format("bad header (positions %d, track length %d, instruments %d)", posn, trkl, insn), nil + end + if chnn > 16 then + return nil, "unsupported: more than 16 channels", "unsupported" + end + if tune.restart >= posn then + tune.restart = posn - 1 + end + local nameAt = u8(4) * 256 + u8(5) + local nptr = limit + if nameAt < size then + local title, e = cstring(b, base + nameAt, limit, 128) + tune.title = title + nptr = e + 1 + end + + local p = base + (ahx and 14 or 16) + local function need(n) +return p + n <= limit + end + if not need(ssn * 2 + posn * chnn * 2) then + return nil, "truncated position list", "truncated" + end + for i = 1, ssn do + local s = readu8(b, p) * 256 + readu8(b, p + 1) + if s >= posn then + s = 0 + end + tune.subsongs[i] = s + p =p+ 2 + end + for i = 0, posn - 1 do + for j = 0, chnn - 1 do + buffer.writeu8(tune.positions, (i * 16 + j) * 2, readu8(b, p)) + buffer.writei8(tune.positions, (i * 16 + j) * 2 + 1, readi8(b, p + 1)) + p =p+ 2 + end + end + local tracks = tune.tracks + for i = 0, trkn do + if not (tune.emptyTrack0 and i == 0) then + for j = 0, trkl - 1 do + local o = (i * 64 + j) * 6 + if ahx then + if not need(3) then + return nil, "truncated track data", "truncated" + end + local b0, b1 = readu8(b, p), readu8(b, p + 1) + buffer.writeu8(tracks, o, bit32.band(bit32.rshift(b0, 2), 0x3f)) + buffer.writeu8(tracks, o + 1, bit32.band(b0, 3) * 16 + bit32.rshift(b1, 4)) + buffer.writeu8(tracks, o + 2, bit32.band(b1, 0xf)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 2)) + p =p+ 3 + else + if not need(1) then + return nil, "truncated track data", "truncated" + end + if readu8(b, p) == 0x3f then + p =p+ 1 + else + if not need(5) then + return nil, "truncated track data", "truncated" + end + local fx = readu8(b, p + 2) + buffer.writeu8(tracks, o, readu8(b, p)) + buffer.writeu8(tracks, o + 1, readu8(b, p + 1)) + buffer.writeu8(tracks, o + 2, bit32.rshift(fx, 4)) + buffer.writeu8(tracks, o + 3, readu8(b, p + 3)) + buffer.writeu8(tracks, o + 4, bit32.band(fx, 0xf)) + buffer.writeu8(tracks, o + 5, readu8(b, p + 4)) + p =p+ 5 + end + end + end + end + end + local plSize = ahx and 4 or 5 + for i = 1, insn do + if not need(22) then + return nil, "truncated instrument", "truncated" + end + local function at(k) +return readu8(b, p + k) + end + local name = "" + if nptr < limit then + local e + name, e = cstring(b, nptr, limit, 128) + nptr = e + 1 + end + local plen = at(21) + local ins= { + name = name, + volume = at(0), + filterSpeed = bit32.bor(bit32.band(bit32.rshift(at(1), 3), 0x1f), bit32.band(bit32.rshift(at(12), 2), 0x20)), + waveLength = bit32.band(at(1), 7), + envelope = { aFrames = at(2), aVolume = at(3), dFrames = at(4), dVolume = at(5), sFrames = at(6), rFrames = at(7), rVolume = at(8) }, + filterLower = bit32.band(at(12), 0x7f), + vibratoDelay = at(13), + hardCutReleaseFrames = bit32.band(bit32.rshift(at(14), 4), 7), + hardCutRelease = bit32.band(at(14), 0x80) ~= 0 and 1 or 0, + vibratoDepth = bit32.band(at(14), 0x0f), + vibratoSpeed = at(15), + squareLower = at(16), + squareUpper = at(17), + squareSpeed = at(18), + filterUpper = bit32.band(at(19), 0x3f), + plist = { speed = at(20), length = plen, entries = {} }, + } + p =p+ 22 + if not need(plen * plSize) then + return nil, "truncated instrument play list", "truncated" + end + for j = 1, plen do + local e +local b0, b1, b2, b3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + if ahx then + local k = bit32.band(bit32.rshift(b0, 5), 7) + k = k == 6 and 12 or(k == 7 and 15 or k +) local l = bit32.band(bit32.rshift(b0, 2), 7) + l = l == 6 and 12 or(l == 7 and 15 or l +) e = { + fx = { l, k }, + waveform = bit32.band(b0 * 2, 6) + bit32.rshift(b1, 7), + fixed = bit32.band(bit32.rshift(b1, 6), 1), + note = bit32.band(b1, 0x3f), + param = { b2, b3 }, + } + -- 1.6: version 0 modules (before filters) drop the "toggle filter" half of command 4 + if tune.version == 0 and l == 4 and bit32.band(b2, 0xf0) ~= 0 then + e.param[1] = bit32.band(b2, 0x0f) + end + if tune.version == 0 and k == 4 and bit32.band(b3, 0xf0) ~= 0 then + e.param[2] = bit32.band(b3, 0x0f) + end + else + e = { + fx = { bit32.band(b0, 0xf), bit32.band(bit32.rshift(b1, 3), 0xf) }, + waveform = bit32.band(b1, 7), + fixed = bit32.band(bit32.rshift(b2, 6), 1), + note = bit32.band(b2, 0x3f), + param = { b3, readu8(b, p + 4) }, + } + end + ins.plist.entries[j] = e + p =p+ plSize + end + tune.instruments[i] = ins + end + return tune, nil, nil +end + +return Load +end +__FILES["codecs/audio/Hively/Player"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- codecs/audio/Hively/Player: the AHX / HivelyTracker replayer: positions and tracks (two effect columns in HVL), the +-- instrument engine (ADSR, vibrato, the PList performance list, square modulation, the resonant filter sweep, hard cut, +-- ring modulation and panning for HVL) and the integer mixer, all as hvl2wav's replay.c 1.9 computes them so the output +-- matches hvl2wav sample for sample. Ported from HivelyTracker (BSD-3-Clause, (c) 2006-2018 Pete Gordon; +-- licenses/hivelytracker-LICENSE.txt). Where the C code reads outside its arrays on bad data this port clamps instead. +local Tables = __include("codecs/audio/Hively/Tables") +local Load = __include("codecs/audio/Hively/Load") + +local Player = {} + +local readu8, readi8, writei8, writef32 = buffer.readu8, buffer.readi8, buffer.writei8, buffer.writef32 +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift + +local FILTER_SET = Tables.FILTER_SET +local WO_TRIANGLE_04, WO_SAWTOOTH_04 = Tables.WO_TRIANGLE_04, Tables.WO_SAWTOOTH_04 +local WO_SQUARES, WO_WHITENOISE = Tables.WO_SQUARES, Tables.WO_WHITENOISE +local OFFSETS, VIB, PERIOD = Tables.OFFSETS, Tables.VIB, Tables.PERIOD +local WAVEFORM_AT = { [0] = WO_TRIANGLE_04, WO_SAWTOOTH_04, 0, WO_WHITENOISE } +local WRAP = 0x280 * 65536 +local TWO32 = 4294967296 + +local f32scratch = buffer.create(4) + +local function s16(v) +return (v + 32768) % 65536 - 32768 +end + +local function tdiv(a, b) +local q = a / b + return (q >= 0 and{(math.floor(q) )}or{(-math.floor(-q) +)})[1]end + +local function period(i) +return PERIOD[i] or 0 +end + +-- (3546897.f * 65536.f) / period as a float, then / mix rate as a double, truncated +local function deltaOf(p, freq) +if p == 0 then + return 1 + end + writef32(f32scratch, 0, 232449441792 / p) -- 3546897 * 65536 = 232449441792 (exact in a float) + local d = math.floor(buffer.readf32(f32scratch, 0) / freq) + if d < 0 then + d = 0 + end + if d > WRAP then + d =d- WRAP + end + if d == 0 then + d = 1 + end + return d +end + + + + + + + + + + + + + + + + + + + + + + + + +local function newVoice(i) +return { + track = 0, nextTrack = 0, transpose = 0, nextTranspose = 0, overrideTranspose = 1000, + adsrVolume = 0, aFrames = 0, aVolume = 0, dFrames = 0, dVolume = 0, sFrames = 0, rFrames = 0, rVolume = 0, + instrument = false , samplePos = 0, delta = 1, instrPeriod = 0, trackPeriod = 0, vibratoPeriod = 0, + waveLength = 0, noteMaxVolume = 0, perfSubVolume = 0, newWaveform = false, waveform = 0, plantPeriod = false, + voiceVolume = 0, plantSquare = false, ignoreSquare = 0, fixedNote = 0, volumeSlideUp = 0, volumeSlideDown = 0, + hardCut = 0, hardCutRelease = 0, hardCutReleaseF = 0, periodSlideOn = false, periodSlideSpeed = 0, + periodSlidePeriod = 0, periodSlideLimit = 0, periodSlideWithLimit = false, periodPerfSlideSpeed = 0, + periodPerfSlidePeriod = 0, periodPerfSlideOn = false, vibratoDelay = 0, vibratoSpeed = 0, vibratoCurrent = 0, + vibratoDepth = 0, squareOn = 0, squareInit = 0, squareWait = 0, squareLowerLimit = 0, squareUpperLimit = 0, + squarePos = 0, squareSign = 0, squareSlidingIn = false, squareReverse = false, filterOn = 0, filterInit = 0, + filterWait = 0, filterSpeed = 0, filterUpperLimit = 0, filterLowerLimit = 0, filterPos = 0, filterSign = 0, + filterSlidingIn = false, ignoreFilter = 0, perfCurrent = 0, perfSpeed = 0, perfWait = 0, perfList = false , + audioSrc = false , audioOff = 0, noteDelayOn = false, noteCutOn = false, noteDelayWait = 0, noteCutWait = 0, + audioPeriod = 0, audioVolume = 0, wnHi = 0, wnLo = 0x280, + squareBuf = buffer.create(0x80), voiceBuf = buffer.create(0x284), voiceNum = i, trackMasterVolume = 0x40, + pan = 0, setPan = 0, panMultLeft = 0, panMultRight = 0, + ringSamplePos = 0, ringDelta = 0, ringMix = false, ringPlantPeriod = false, ringBasePeriod = 0, + ringAudioPeriod = 0, ringAudioOff = -1, ringNewWaveform = false, ringWaveform = 0, ringFixedPeriod = 0, + ringBuf = buffer.create(0x284), + } +end + +-- new(tune, freq, stereo, subsong) -> State | nil (subsong out of range). stereo: AHX separation 0..4 (HVL: the file's) +function Player.new(tune, freq, stereo, subsong) +if subsong < 0 or subsong > #tune.subsongs then + return nil + end + local t = Tables.get() + local defstereo = (tune.format == "ahx" and{(math.clamp(math.floor(stereo), 0, 4) )}or{tune.stereo +})[1] local mixgain = tune.mixgain + if tune.format == "ahx" then + local defgain = { [0] = 71, 72, 76, 85, 100 } + mixgain = math.floor((defgain[defstereo] * 256) / 100 +) end + local st= { + tune = tune, freq = freq, version = (tune.format == "hvl" and{tune.version }or{0})[1], + channels = tune.channels, voices = {}, tempo = 6, posNr = (subsong > 0 and{tune.subsongs[subsong] }or{0})[1], + posJump = 0, posJumpNote = 0, noteNr = 0, stepWaitFrames = 0, getNewPosition = true, patternBreak = false, + songEndReached = false, playingTime = 0, mixgain = mixgain, waves = t.waves, panL = t.panL, panR = t.panR, + } + local left, right = Tables.STEREO_LEFT[defstereo], Tables.STEREO_RIGHT[defstereo] + for i = 0, 15 do + local v = newVoice(i) + local p = ((i % 4 == 0 or i % 4 == 3 )and{left }or{right +})[1] v.pan, v.setPan, v.panMultLeft, v.panMultRight = p, p, t.panL[p], t.panR[p] + st.voices[i + 1] = v + end + return st +end + +-- ------------------------------------------------------------------------------------------------ steps +local function setPan(st, v, p) + v.pan = p + v.panMultLeft, v.panMultRight = st.panL[p], st.panR[p] +end + +local function stepfx1(st, v, fx, param) + if fx == 0x0 then + local lo = band(param, 0x0f) + if lo > 0 and lo <= 9 then + st.posJump = lo + end + elseif fx == 0x5 or fx == 0xa then + v.volumeSlideDown = band(param, 0x0f) + v.volumeSlideUp = rshift(param, 4) + elseif fx == 0x7 then + if param > 127 then + param =param- 256 + end + setPan(st, v, param + 128) + v.setPan = param + 128 + elseif fx == 0xb then + st.posJump = (st.posJump * 100 + band(param, 0x0f) + rshift(param, 4) * 10) % 65536 + st.patternBreak = true + if st.posJump <= st.posNr then + st.songEndReached = true + end + elseif fx == 0xd then + st.posJump = st.posNr + 1 + st.posJumpNote = band(param, 0x0f) + rshift(param, 4) * 10 + st.patternBreak = true + if st.posJumpNote > st.tune.trackLength then + st.posJumpNote = 0 + end + elseif fx == 0xe then + if rshift(param, 4) == 0xc and band(param, 0x0f) < st.tempo then + v.noteCutWait = band(param, 0x0f) + if v.noteCutWait ~= 0 then + v.noteCutOn = true + v.hardCutRelease = 0 + end + end + elseif fx == 0xf then + st.tempo = param + if param == 0 then + st.songEndReached = true + end + end +end + +local function stepfx2(v, fx, param, note) +if fx == 0x9 then + v.squarePos = rshift(param, 5 - v.waveLength) + v.ignoreSquare = 1 + elseif fx == 0x3 or fx == 0x5 then + if fx == 0x3 and param ~= 0 then + v.periodSlideSpeed = param + end + if note ~= 0 then + local new = period(note) + local diff = period(v.trackPeriod) - new + new = diff + v.periodSlidePeriod + if new ~= 0 then + v.periodSlideLimit = s16(-diff) + end + end + v.periodSlideOn = true + v.periodSlideWithLimit = true + note = 0 + end + return note +end + +local function stepfx3(st, v, fx, param) + if fx == 0x01 then + v.periodSlideSpeed = -param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x02 then + v.periodSlideSpeed = param + v.periodSlideOn = true + v.periodSlideWithLimit = false + elseif fx == 0x04 then + if param == 0 or param == 0x40 then + return + end + if param < 0x40 then + v.ignoreFilter = param + return + end + if param > 0x7f then + return + end + v.filterPos = param - 0x40 + elseif fx == 0x0c then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param =param- 0x50 + if param < 0 then + return + end + if param <= 0x40 then + for i = 1, st.channels do + st.voices[i].trackMasterVolume = param + end + return + end + param =param- (0xa0 - 0x50 +) if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 0xe then + local sub, lo = rshift(param, 4), band(param, 0x0f) + if sub == 0x1 then + v.periodSlidePeriod = s16(v.periodSlidePeriod - lo) + v.plantPeriod = true + elseif sub == 0x2 then + v.periodSlidePeriod = s16(v.periodSlidePeriod + lo) + v.plantPeriod = true + elseif sub == 0x4 then + v.vibratoDepth = lo + elseif sub == 0xa then + v.noteMaxVolume = math.min(v.noteMaxVolume + lo, 0x40) + elseif sub == 0xb then + v.noteMaxVolume = math.max(v.noteMaxVolume - lo, 0) + elseif sub == 0xf then + if st.version >= 1 and lo == 1 then + v.overrideTranspose = v.transpose + end + end + end +end + +local function processStep(st, v) + v.volumeSlideUp, v.volumeSlideDown = 0, 0 + local tune = st.tune + local track = readu8(tune.positions, (st.posNr * 16 + v.voiceNum) * 2) + local so = (track * 64 + st.noteNr) * 6 + local tracks = tune.tracks + local note, instr = readu8(tracks, so), readu8(tracks, so + 1) + local fx, fxp, fxb, fxbp = band(readu8(tracks, so + 2), 0xf), readu8(tracks, so + 3), band(readu8(tracks, so + 4), 0xf), readu8(tracks, so + 5) + + local doneNoteDel = false + if fx == 0xe and band(fxp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + doneNoteDel = true + elseif band(fxp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + if not doneNoteDel and fxb == 0xe and band(fxbp, 0xf0) == 0xd0 then + if v.noteDelayOn then + v.noteDelayOn = false + elseif band(fxbp, 0x0f) < st.tempo then + v.noteDelayWait = band(fxbp, 0x0f) + if v.noteDelayWait ~= 0 then + v.noteDelayOn = true + return + end + end + end + + if note ~= 0 then + v.overrideTranspose = 1000 + end + stepfx1(st, v, fx, fxp) + stepfx1(st, v, fxb, fxbp) + + if instr ~= 0 and instr <= tune.instrumentNr then + local ins = tune.instruments[instr] + setPan(st, v, v.setPan) + v.periodSlideSpeed, v.periodSlidePeriod, v.periodSlideLimit = 0, 0, 0 + v.perfSubVolume = 0x40 + v.adsrVolume = 0 + v.instrument = ins + v.samplePos = 0 + local env = ins.envelope + v.aFrames = env.aFrames + v.aVolume = s16((v.aFrames ~= 0 and{(tdiv(env.aVolume * 256, v.aFrames) )}or{(env.aVolume * 256)})[1]) + v.dFrames = env.dFrames + v.dVolume = s16((v.dFrames ~= 0 and{(tdiv((env.dVolume - env.aVolume) * 256, v.dFrames) )}or{(env.dVolume * 256)})[1]) + v.sFrames = env.sFrames + v.rFrames = env.rFrames + v.rVolume = s16((v.rFrames ~= 0 and{(tdiv((env.rVolume - env.dVolume) * 256, v.rFrames) )}or{(env.rVolume * 256)})[1]) + v.waveLength = math.min(ins.waveLength, 5) + v.noteMaxVolume = ins.volume + v.vibratoCurrent = 0 + v.vibratoDelay = ins.vibratoDelay + v.vibratoDepth = ins.vibratoDepth + v.vibratoSpeed = ins.vibratoSpeed + v.vibratoPeriod = 0 + v.hardCutRelease = ins.hardCutRelease + v.hardCut = ins.hardCutReleaseFrames + v.ignoreSquare, v.squareSlidingIn = 0, false + v.squareWait, v.squareOn = 0, 0 + local lower = rshift(ins.squareLower, 5 - v.waveLength) + local upper = rshift(ins.squareUpper, 5 - v.waveLength) + if upper < lower then + lower, upper = upper, lower + end + v.squareUpperLimit, v.squareLowerLimit = upper, lower + v.ignoreFilter, v.filterWait, v.filterOn = 0, 0, 0 + v.filterSlidingIn = false + local d6, d3, d4 = ins.filterSpeed, ins.filterLower, ins.filterUpper + v.filterSpeed = d6 + if d3 > d4 then + d3, d4 = d4, d3 + end + v.filterUpperLimit, v.filterLowerLimit = d4, d3 + v.filterPos = 32 + v.perfWait, v.perfCurrent = 0, 0 + v.perfSpeed = ins.plist.speed + v.perfList = ins.plist + v.ringMix = false + v.ringSamplePos = 0 + v.ringPlantPeriod = false + v.ringNewWaveform = false + end + + v.periodSlideOn = false + note = stepfx2(v, fx, fxp, note) + note = stepfx2(v, fxb, fxbp, note) + if note ~= 0 then + v.trackPeriod = note + v.plantPeriod = true + end + stepfx3(st, v, fx, fxp) + stepfx3(st, v, fxb, fxbp) +end + +-- ------------------------------------------------------------------------------------------------ frames +local function plistCommand(st, v, fx, param) + if fx == 0 then + if param > 0 and param < 0x40 then + if v.ignoreFilter ~= 0 then + v.filterPos = v.ignoreFilter + v.ignoreFilter = 0 + else + v.filterPos = param + end + v.newWaveform = true + end + elseif fx == 1 then + v.periodPerfSlideSpeed = param + v.periodPerfSlideOn = true + elseif fx == 2 then + v.periodPerfSlideSpeed = -param + v.periodPerfSlideOn = true + elseif fx == 3 then + if v.ignoreSquare == 0 then + v.squarePos = rshift(param, 5 - v.waveLength) + else + v.ignoreSquare = 0 + end + elseif fx == 4 then + if param == 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = 1 + else + if band(param, 0x0f) ~= 0 then + v.squareOn = 1 - v.squareOn + v.squareInit = v.squareOn + v.squareSign = band(param, 0x0f) == 0x0f and-1 or 1 + end + if band(param, 0xf0) ~= 0 then + v.filterOn = 1 - v.filterOn + v.filterInit = v.filterOn + v.filterSign = band(param, 0xf0) == 0xf0 and-1 or 1 + end + end + elseif fx == 5 then + v.perfCurrent = param + elseif fx == 7 or fx == 8 then + if param >= 1 and param <= 0x3c then + v.ringBasePeriod = param + v.ringFixedPeriod = 1 + elseif param >= 0x81 and param <= 0xbc then + v.ringBasePeriod = param - 0x80 + v.ringFixedPeriod = 0 + else + v.ringBasePeriod = 0 + v.ringFixedPeriod = 0 + v.ringNewWaveform = false + v.ringAudioOff = -1 + v.ringMix = false + return + end + v.ringWaveform = fx - 7 + v.ringNewWaveform = true + v.ringPlantPeriod = true + elseif fx == 9 then + if param > 127 then + param =param- 256 + end + setPan(st, v, param + 128) + elseif fx == 12 then + if param <= 0x40 then + v.noteMaxVolume = param + return + end + param =param- 0x50 + if param < 0 then + return + end + if param <= 0x40 then + v.perfSubVolume = param + return + end + param =param- (0xa0 - 0x50 +) if param < 0 then + return + end + if param <= 0x40 then + v.trackMasterVolume = param + end + elseif fx == 15 then + v.perfSpeed = param + v.perfWait = param + end +end + +-- the noise offset generator (vc_WNRandom, a 64-bit `long` in hvl2wav): W += 2239384; +-- W = ((((W >> 8) | (W << 24)) + 782323) ^ 75) - 6735 +local function wnStep(v) + local hi, lo = v.wnHi, v.wnLo + 2239384 + if lo >= TWO32 then + lo =lo- TWO32 + hi = (hi + 1) % TWO32 + end + local shi = rshift(hi, 8) + if hi >= 0x80000000 then + shi = bor(shi, 0xff000000) + end + local nlo = bor(rshift(lo, 8), lshift(band(hi, 0xff), 24), lshift(lo, 24)) + local nhi = bor(shi, lshift(hi, 24), rshift(lo, 8)) + nlo =nlo+ 782323 + if nlo >= TWO32 then + nlo =nlo- TWO32 + nhi = (nhi + 1) % TWO32 + end + nlo = bit32.bxor(nlo, 75) + nlo =nlo- 6735 + if nlo < 0 then + nlo =nlo+ TWO32 + nhi = (nhi + TWO32 - 1) % TWO32 + end + v.wnHi, v.wnLo = nhi, nlo +end + +local function processFrame(st, v) + local tune = st.tune + if v.noteDelayOn then + if v.noteDelayWait <= 0 then + processStep(st, v) + else + v.noteDelayWait =v.noteDelayWait- 1 + end + end + + if v.hardCut ~= 0 then + local row = st.noteNr + 1 + local nextinst + if row < tune.trackLength then + nextinst = readu8(tune.tracks, ((v.track * 64) + row) * 6 + 1) + else + nextinst = readu8(tune.tracks, (v.nextTrack * 64) * 6 + 1) + end + if nextinst ~= 0 then + local d1 = math.max(st.tempo - v.hardCut, 0) + if not v.noteCutOn then + v.noteCutOn = true + v.noteCutWait = d1 + v.hardCutReleaseF = -(d1 - st.tempo) + else + v.hardCut = 0 + end + end + end + + if v.noteCutOn then + if v.noteCutWait <= 0 then + v.noteCutOn = false + if v.hardCutRelease ~= 0 then + local ins = v.instrument + local f = v.hardCutReleaseF + v.rVolume = (f ~= 0 and{(s16(tdiv(-(v.adsrVolume - ins.envelope.rVolume * 256), f)) )}or{0 +})[1] v.rFrames = f + v.aFrames, v.dFrames, v.sFrames = 0, 0, 0 + else + v.noteMaxVolume = 0 + end + else + v.noteCutWait =v.noteCutWait- 1 + end + end + + -- ADSR envelope + if v.aFrames ~= 0 then + v.adsrVolume =v.adsrVolume+ v.aVolume + v.aFrames =v.aFrames- 1 + if v.aFrames <= 0 then + v.adsrVolume = v.instrument.envelope.aVolume * 256 + end + elseif v.dFrames ~= 0 then + v.adsrVolume =v.adsrVolume+ v.dVolume + v.dFrames =v.dFrames- 1 + if v.dFrames <= 0 then + v.adsrVolume = v.instrument.envelope.dVolume * 256 + end + elseif v.sFrames ~= 0 then + v.sFrames =v.sFrames- 1 + elseif v.rFrames ~= 0 then + v.adsrVolume =v.adsrVolume+ v.rVolume + v.rFrames =v.rFrames- 1 + if v.rFrames <= 0 then + v.adsrVolume = v.instrument.envelope.rVolume * 256 + end + end + + -- volume slide + v.noteMaxVolume = math.clamp(v.noteMaxVolume + v.volumeSlideUp - v.volumeSlideDown, 0, 0x40) + + -- portamento + if v.periodSlideOn then + if v.periodSlideWithLimit then + local d0 = v.periodSlidePeriod - v.periodSlideLimit + local d2 = v.periodSlideSpeed + if d0 > 0 then + d2 = -d2 + end + if d0 ~= 0 then + local sum = d0 + d2 + -- (d0 + d2) ^ d0 >= 0: the same sign (or zero) + if (sum >= 0) == (d0 >= 0) then + d0 = v.periodSlidePeriod + d2 + else + d0 = v.periodSlideLimit + end + v.periodSlidePeriod = s16(d0) + v.plantPeriod = true + end + else + v.periodSlidePeriod = s16(v.periodSlidePeriod + v.periodSlideSpeed) + v.plantPeriod = true + end + end + + -- vibrato + if v.vibratoDepth ~= 0 then + if v.vibratoDelay <= 0 then + v.vibratoPeriod = math.floor((VIB[v.vibratoCurrent] * v.vibratoDepth) / 128 +) v.plantPeriod = true + v.vibratoCurrent = band(v.vibratoCurrent + v.vibratoSpeed, 0x3f) + else + v.vibratoDelay =v.vibratoDelay- 1 + end + end + + -- PList + local pl = v.perfList + if pl then + if v.instrument and v.perfCurrent < v.instrument.plist.length then + local overflow = v.perfWait == 128 + v.perfWait = s16(v.perfWait - 1) + local w8 = (v.perfWait + 128) % 256 - 128 + if overflow or w8 <= 0 then + local cur = v.perfCurrent + v.perfCurrent =v.perfCurrent+ 1 + v.perfWait = v.perfSpeed + local e = pl.entries[cur + 1] + if e then + if e.waveform ~= 0 then + v.waveform = e.waveform - 1 + v.newWaveform = true + v.periodPerfSlideSpeed, v.periodPerfSlidePeriod = 0, 0 + end + v.periodPerfSlideOn = false + plistCommand(st, v, e.fx[1], e.param[1]) + plistCommand(st, v, e.fx[2], e.param[2]) + if e.note ~= 0 then + v.instrPeriod = e.note + v.plantPeriod = true + v.fixedNote = e.fixed + end + end + end + else + if v.perfWait ~= 0 then + v.perfWait =v.perfWait- 1 + else + v.periodPerfSlideSpeed = 0 + end + end + end + + -- perf portamento + if v.periodPerfSlideOn then + v.periodPerfSlidePeriod = s16(v.periodPerfSlidePeriod - v.periodPerfSlideSpeed) + if v.periodPerfSlidePeriod ~= 0 then + v.plantPeriod = true + end + end + + if v.waveform == 2 and v.squareOn ~= 0 then + v.squareWait =v.squareWait- 1 + if v.squareWait <= 0 then + local d1, d2, d3 = v.squareLowerLimit, v.squareUpperLimit, v.squarePos + if v.squareInit ~= 0 then + v.squareInit = 0 + if d3 <= d1 then + v.squareSlidingIn = true + v.squareSign = 1 + elseif d3 >= d2 then + v.squareSlidingIn = true + v.squareSign = -1 + end + end + if d1 == d3 or d2 == d3 then + if v.squareSlidingIn then + v.squareSlidingIn = false + else + v.squareSign = -v.squareSign + end + end + d3 =d3+ v.squareSign + v.squarePos = s16(d3) + v.plantSquare = true + local ins= v.instrument + v.squareWait = (ins and{ins.squareSpeed }or{0 +})[1] end + end + + if v.filterOn ~= 0 then + v.filterWait =v.filterWait- 1 + if v.filterWait <= 0 then + local d1, d2, d3 = v.filterLowerLimit, v.filterUpperLimit, v.filterPos + if v.filterInit ~= 0 then + v.filterInit = 0 + if d3 <= d1 then + v.filterSlidingIn = true + v.filterSign = 1 + elseif d3 >= d2 then + v.filterSlidingIn = true + v.filterSign = -1 + end + end + local fmax = (v.filterSpeed < 4 and((5 - v.filterSpeed ))or(1 +)) for _ = 1, fmax do + if d1 == d3 or d2 == d3 then + if v.filterSlidingIn then + v.filterSlidingIn = false + else + v.filterSign = -v.filterSign + end + end + d3 =d3+ v.filterSign + end + v.filterPos = math.clamp(d3, 1, 63) + v.newWaveform = true + v.filterWait = math.max(v.filterSpeed - 3, 1) + end + end + + local waves = st.waves + local fpos = math.clamp(v.filterPos, 1, 63) + if v.waveform == 2 or v.plantSquare then + -- CalcSquare + local sp = WO_SQUARES + (fpos - 0x20) * FILTER_SET + local x = v.squarePos * 2 ^ (5 - v.waveLength) + if x > 0x20 then + x = 0x40 - x + v.squareReverse = true + end + if x > 0 then + sp =sp+ (x - 1) * 128 + end + local delta = math.floor(32 / 2 ^ v.waveLength +) local sb = v.squareBuf + for i = 0, 4 * 2 ^ v.waveLength - 1 do + writei8(sb, i, readi8(waves, sp)) + sp =sp+ delta + end + v.newWaveform = true + v.waveform = 2 + v.plantSquare = false + end + + if v.waveform == 3 then + v.newWaveform = true + end + + if v.ringNewWaveform then + if v.ringWaveform > 1 then + v.ringWaveform = 1 + end + v.ringAudioOff = WAVEFORM_AT[v.ringWaveform] + OFFSETS[v.waveLength] + end + + if v.newWaveform and v.waveform <= 3 then + if v.waveform == 2 then + v.audioSrc, v.audioOff = v.squareBuf, 0 + else + local off = WAVEFORM_AT[v.waveform] + (fpos - 0x20) * FILTER_SET + if v.waveform < 2 then + off =off+ OFFSETS[v.waveLength] + else + off =off+ band(band(v.wnLo, 2 * 0x280 - 1), 0xfffffffe) + wnStep(v) + end + v.audioSrc, v.audioOff = waves, off + end + end + + -- ring modulation period + if v.ringAudioOff >= 0 then + local rp = v.ringBasePeriod + if v.ringFixedPeriod == 0 then + if v.overrideTranspose ~= 1000 then + rp =rp+ (v.overrideTranspose + v.trackPeriod - 1 +) else + rp =rp+ (v.transpose + v.trackPeriod - 1 +) end + end + rp = period(math.clamp(s16(rp), 0, 60)) + if v.ringFixedPeriod == 0 then + rp =rp+ v.periodSlidePeriod + end + rp = s16(rp + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.ringAudioPeriod = math.clamp(rp, 0x71, 0xd60) + end + + -- the period + local ap = v.instrPeriod + if v.fixedNote == 0 then + if v.overrideTranspose ~= 1000 then + ap =ap+ (v.overrideTranspose + v.trackPeriod - 1 +) else + ap =ap+ (v.transpose + v.trackPeriod - 1 +) end + end + ap = period(math.clamp(s16(ap), 0, 60)) + if v.fixedNote == 0 then + ap =ap+ v.periodSlidePeriod + end + ap = s16(ap + v.periodPerfSlidePeriod + v.vibratoPeriod) + v.audioPeriod = math.clamp(ap, 0x71, 0xd60) + + local vol = math.floor((math.floor(v.adsrVolume / 256 )* v.noteMaxVolume) / 64 +) vol = math.floor((vol * v.perfSubVolume) / 64 +) vol = math.floor((vol * v.trackMasterVolume) / 64 +) v.audioVolume = s16(vol) +end + +-- fill the 0x280-byte voice buffer with repeats of the 4 << waveLength cycle at (src, off) +local function fillCycles(dst, src, off, len) + if off < 0 or off + len > buffer.len(src) then + buffer.fill(dst, 0, 0, 0x281) + return + end + buffer.copy(dst, 0, src, off, len) + local filled = len + while filled < 0x280 do + local k = math.min(filled, 0x280 - filled) + buffer.copy(dst, filled, dst, 0, k) + filled =filled+ k + end + writei8(dst, 0x280, readi8(dst, 0)) +end + +local function setAudio(st, v) + v.voiceVolume = v.audioVolume % 256 + if v.plantPeriod then + v.plantPeriod = false + v.delta = deltaOf(v.audioPeriod, st.freq) + end + local src= v.audioSrc or nil + if v.newWaveform and src then + fillCycles(v.voiceBuf, src, v.audioOff, v.waveform == 3 and 0x280 or 4 * 2 ^ v.waveLength) + end + if v.ringPlantPeriod then + v.ringPlantPeriod = false + v.ringDelta = deltaOf(v.ringAudioPeriod, st.freq) + end + if v.ringNewWaveform and v.ringAudioOff >= 0 then + fillCycles(v.ringBuf, st.waves, v.ringAudioOff, 4 * 2 ^ v.waveLength) + v.ringMix = true + end +end + +-- irq(st, audio): one player call (hvl_play_irq); audio = false skips the audio side (duration scans) +function Player.irq(st, audio) + local tune = st.tune + local nch = st.channels + local voices = st.voices + if st.stepWaitFrames == 0 then + if st.getNewPosition then + local nextpos = st.posNr + 1 == tune.positionNr and 0 or st.posNr + 1 + local P = tune.positions + for i = 0, nch - 1 do + local v = voices[i + 1] + v.track = readu8(P, (st.posNr * 16 + i) * 2) + v.transpose = readi8(P, (st.posNr * 16 + i) * 2 + 1) + v.nextTrack = readu8(P, (nextpos * 16 + i) * 2) + v.nextTranspose = readi8(P, (nextpos * 16 + i) * 2 + 1) + end + st.getNewPosition = false + end + for i = 1, nch do + processStep(st, voices[i]) + end + st.stepWaitFrames = st.tempo + end + for i = 1, nch do + processFrame(st, voices[i]) + end + st.playingTime =st.playingTime+ 1 + st.stepWaitFrames = s16(st.stepWaitFrames - 1) + if st.stepWaitFrames == 0 then + if not st.patternBreak then + st.noteNr =st.noteNr+ 1 + if st.noteNr >= tune.trackLength then + st.posJump = st.posNr + 1 + st.posJumpNote = 0 + st.patternBreak = true + end + end + if st.patternBreak then + st.patternBreak = false + st.posNr = st.posJump + st.noteNr = st.posJumpNote + if st.posNr >= tune.positionNr then + -- (past the end is bad data: the C code reads outside its position list) + st.songEndReached = true + st.posNr = tune.restart + end + st.posJumpNote = 0 + st.posJump = 0 + st.getNewPosition = true + end + end + if audio then + for i = 1, nch do + setAudio(st, voices[i]) + end + end +end + +-- mix(st, out, at, n): n stereo frames of f32 into out at frame `at` (hvl_mixchunk: integer mixing, s16 clipping, / 32768) +function Player.mix(st, out, at, n) + local nch = st.channels + local voices = st.voices + local src, rsrc, delta, rdelta, vol, pos, rpos, panl, panr = {}, {}, {}, {}, {}, {}, {}, {}, {} + for i = 1, nch do + local v = voices[i] + delta[i] = math.max(v.delta, 1) + vol[i] = v.voiceVolume + pos[i] = v.samplePos + src[i] = v.voiceBuf + panl[i] = v.panMultLeft + panr[i] = v.panMultRight + rdelta[i] = math.max(v.ringDelta, 1) + rpos[i] = v.ringSamplePos + rsrc[i] = (v.ringMix and{v.ringBuf }or{false +})[1] end + local gain = st.mixgain + local o = at * 8 + local samples = n + while samples > 0 do + local loops = samples + for i = 1, nch do + if pos[i] >= WRAP then + pos[i]=pos[i]- WRAP + end + local cnt = math.floor((WRAP - pos[i] - 1) / delta[i] )+ 1 + if cnt < loops then + loops = cnt + end + if rsrc[i] then + if rpos[i] >= WRAP then + rpos[i]=rpos[i]- WRAP + end + cnt = math.floor((WRAP - rpos[i] - 1) / rdelta[i] )+ 1 + if cnt < loops then + loops = cnt + end + end + end + samples =samples- loops + for _ = 1, loops do + local a, b = 0, 0 + for i = 1, nch do + local j + local r = rsrc[i] + if r then + j = (math.floor((readi8(src[i], math.floor(pos[i] / 65536)) * readi8(r, math.floor(rpos[i] / 65536))) / 128)) * vol[i] + rpos[i]=rpos[i]+ rdelta[i] + else + j = readi8(src[i], math.floor(pos[i] / 65536)) * vol[i] + end + a =a+ math.floor((j * panl[i]) / 128 +) b =b+ math.floor((j * panr[i]) / 128 +) pos[i]=pos[i]+ delta[i] + end + a = math.floor((a * gain) / 256 +) b = math.floor((b * gain) / 256 +) if a < -32768 then + a = -32768 + elseif a > 32767 then + a = 32767 + end + if b < -32768 then + b = -32768 + elseif b > 32767 then + b = 32767 + end + writef32(out, o, a / 32768) + writef32(out, o + 4, b / 32768) + o =o+ 8 + end + end + for i = 1, nch do + voices[i].samplePos = pos[i] + voices[i].ringSamplePos = rpos[i] + end +end + +return Player +end +__FILES["codecs/audio/Hively/Tables"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- codecs/audio/Hively/Tables: the AHX / HivelyTracker replayer's tables: the waveform block (triangle and sawtooth at +-- six lengths, 32 square pulse widths, white noise, and the 31 low-pass and 31 high-pass filtered copies of all of +-- them, generated as hvl_replay.c does), the sine panning tables, the vibrato sine and the Amiga period table. Ported +-- from HivelyTracker's hvl2wav replay.c 1.9 (BSD-3-Clause, (c) 2006-2018 Pete Gordon; licenses/hivelytracker-LICENSE.txt) +-- as hvl2wav builds on 64-bit Linux (`long` is 64-bit there: the noise generator's shifts do not wrap at 32 bits). +local Tables = {} + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift + +-- the offsets inside `waves` (bytes) +local FILTER_SET = 0xfc + 0xfc + 0x80 * 0x1f + 0x80 + 3 * 0x280 -- 6520: one filtered copy of every waveform +local WHITENOISELEN = 0x280 * 3 +local WO_LOWPASSES = 0 +local WO_TRIANGLE_04 = WO_LOWPASSES + FILTER_SET * 31 +local WO_SAWTOOTH_04 = WO_TRIANGLE_04 + 0xfc +local WO_SQUARES = WO_SAWTOOTH_04 + 0xfc +local WO_WHITENOISE = WO_SQUARES + 0x80 * 0x20 +local WO_HIGHPASSES = WO_WHITENOISE + WHITENOISELEN +local WAVES_SIZE = WO_HIGHPASSES + FILTER_SET * 31 + +Tables.FILTER_SET = FILTER_SET +Tables.WO_TRIANGLE_04 = WO_TRIANGLE_04 +Tables.WO_SAWTOOTH_04 = WO_SAWTOOTH_04 +Tables.WO_SQUARES = WO_SQUARES +Tables.WO_WHITENOISE = WO_WHITENOISE +Tables.WAVES_SIZE = WAVES_SIZE +-- offset of the waveform of length 4 << n inside the triangle / sawtooth runs +Tables.OFFSETS = { [0] = 0x00, 0x04, 0x04 + 0x08, 0x04 + 0x08 + 0x10, 0x04 + 0x08 + 0x10 + 0x20, 0x04 + 0x08 + 0x10 + 0x20 + 0x40 } + +Tables.VIB = { + [0] = 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, + 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24, + 0, -24, -49, -74, -97, -120, -141, -161, -180, -197, -212, -224, -235, -244, -250, -253, -255, + -253, -250, -244, -235, -224, -212, -197, -180, -161, -141, -120, -97, -74, -49, -24, +} + +Tables.PERIOD = { + [0] = 0x0000, 0x0D60, 0x0CA0, 0x0BE8, 0x0B40, 0x0A98, 0x0A00, 0x0970, + 0x08E8, 0x0868, 0x07F0, 0x0780, 0x0714, 0x06B0, 0x0650, 0x05F4, + 0x05A0, 0x054C, 0x0500, 0x04B8, 0x0474, 0x0434, 0x03F8, 0x03C0, + 0x038A, 0x0358, 0x0328, 0x02FA, 0x02D0, 0x02A6, 0x0280, 0x025C, + 0x023A, 0x021A, 0x01FC, 0x01E0, 0x01C5, 0x01AC, 0x0194, 0x017D, + 0x0168, 0x0153, 0x0140, 0x012E, 0x011D, 0x010D, 0x00FE, 0x00F0, + 0x00E2, 0x00D6, 0x00CA, 0x00BE, 0x00B4, 0x00AA, 0x00A0, 0x0097, + 0x008F, 0x0087, 0x007F, 0x0078, 0x0071, +} + +Tables.STEREO_LEFT = { [0] = 128, 96, 64, 32, 0 } +Tables.STEREO_RIGHT = { [0] = 128, 160, 193, 225, 255 } + +local function i8(v) +v = v % 256 + return (v >= 128 and((v - 256 ))or(v +))end + +local function genSawtooth(w, at, len) + local add = math.floor(256 / (len - 1) +) local val = -128 + for i = 0, len - 1 do + buffer.writei8(w, at + i, i8(val)) + val =val+ add + end +end + +local function genTriangle(w, at, len) + local d5 = math.floor(len / 4 +) local d1 = math.floor(128 / d5 +) local d4 = -(math.floor(len / 2)) + local p = at + local val = 0 + for _ = 1, d5 do + buffer.writei8(w, p, i8(val)) + p =p+ 1 + val =val+ d1 + end + buffer.writei8(w, p, 0x7f) + p =p+ 1 + if d5 ~= 1 then + val = 128 + for _ = 1, d5 - 1 do + val =val- d1 + buffer.writei8(w, p, i8(val)) + p =p+ 1 + end + end + local q = p + d4 + for _ = 1, d5 * 2 do + local c = buffer.readi8(w, q) + q =q+ 1 + buffer.writei8(w, p, c == 0x7f and-128 or i8(-c)) + p =p+ 1 + end +end + +local function genSquare(w, at) + local p = at + for i = 1, 0x20 do + for _ = 1, (0x40 - i) * 2 do + buffer.writei8(w, p, -128) + p =p+ 1 + end + for _ = 1, i * 2 do + buffer.writei8(w, p, 0x7f) + p =p+ 1 + end + end +end + +-- hvl_GenWhiteNoise with `unsigned long` = 64 bits: (hi, lo) halves +local function genWhiteNoise(w, at, len) + local hi, lo = 0, 0x41595321 + for i = 0, len - 1 do + local s = i8(band(lo, 0xff)) + if band(lo, 0x100) ~= 0 then + s = 0x7f -- (int32)(ays & 0xffff) >= 0 always holds + end + buffer.writei8(w, at + i, s) + -- ays = (ays >> 5) | (ays << 27) + local nlo = bor(rshift(lo, 5), lshift(band(hi, 31), 27), lshift(lo, 27)) + -- (the high half is masked off next: ays & 0xffffff00 zero-extends) + lo = bor(band(nlo, 0xffffff00), bxor(band(nlo, 0xff), 0x9a)) + local bx = band(lo, 0xffff) + -- ays = (ays << 2) | (ays >> 30) + lo = bor(lshift(lo, 2), rshift(lo, 30)) + local ax = band(lo, 0xffff) + bx = band(bx + ax, 0xffff) + ax = bxor(ax, bx) + lo = bor(band(lo, 0xffff0000), ax) + -- ays = (ays >> 3) | (ays << 29) + hi = rshift(lo, 3) + lo = bor(rshift(lo, 3), lshift(lo, 29)) + end +end + +local LENTAB = { 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 3, 7, 0xf, 0x1f, 0x3f, 0x7f } +for _ = 1, 32 do + table.insert(LENTAB, 0x7f) +end +table.insert(LENTAB, 0x280 * 3 - 1) + +local function clip(x) +if x > 127 then + return 127 + elseif x < -128 then + return -128 + end + return x +end + +local function trunc8(x) +return (x >= 0 and{(math.floor(x) )}or{(-math.floor(-x) +)})[1]end + +local function genFilterWaves(w) + local low, high = WO_LOWPASSES, WO_HIGHPASSES + local freq = 8 + for _ = 0, 30 do + local a0 = WO_TRIANGLE_04 + local fre = freq * 1.25 / 100.0 + for wv = 1, 45 do + local n = LENTAB[wv] + local mid, lo = 0, 0 + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + end + for i = 0, n do + local h = clip(buffer.readi8(w, a0 + i) - mid - lo) + mid = clip(mid + h * fre) + lo = clip(lo + mid * fre) + buffer.writei8(w, low, trunc8(lo)) + buffer.writei8(w, high, trunc8(h)) + low =low+ 1 + high =high+ 1 + end + a0 =a0+ (n + 1 +) end + freq =freq+ 3 + end +end + +local cache= nil + +-- get() -> { waves (int8 buffer), panL, panR (0-based, 256 entries) }: built once, shared read only +function Tables.get() +if cache then + return cache + end + local w = buffer.create(WAVES_SIZE) + local n = 4 + for k = 0, 5 do + genSawtooth(w, WO_SAWTOOTH_04 + Tables.OFFSETS[k], n) + genTriangle(w, WO_TRIANGLE_04 + Tables.OFFSETS[k], n) + n =n* 2 + end + genSquare(w, WO_SQUARES) + genWhiteNoise(w, WO_WHITENOISE, WHITENOISELEN) + genFilterWaves(w) + -- sine panning: the start angle is a float expression in the C source ((3.14159265f * 2.0f) / 4.0f) + local f = buffer.create(4) + buffer.writef32(f, 0, 3.14159265) + local aa = buffer.readf32(f, 0) * 2 / 4 + local ab = 0.0 + local step = (3.14159265 * 2.0 / 4.0) / 256.0 + local pl, pr= {}, {} + for i = 0, 255 do + pl[i] = math.floor(math.sin(aa) * 255.0) + pr[i] = math.floor(math.sin(ab) * 255.0) + aa =aa+ step + ab =ab+ step + end + pl[255] = 0 + pr[0] = 0 + cache = { waves = w, panL = pl, panR = pr } + return cache +end + +return Tables +end +__FILES["codecs/audio/Mdct"] = function() +local __compat = __compat local type = __compat.type --!strict +--!native +--!optimize 2 +-- 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. +-- +-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 +-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 +-- +-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley +-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays +-- 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("rosetta.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 +-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values +-- +-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller +-- sizes them). +local Fft = __include("codecs/audio/Mdct/Fft") + +local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt + +local Mdct = {} +Mdct.Fft = Fft + +-- new(N) -> Plan | nil + + + + + + + + + + + +function Mdct.new(n) +if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then + return nil + end + local m = math.floor(n / 2 +) local q = math.floor(n / 4 +) local fft = Fft.new(q) + if not fft then + return nil + end + local twc, tws = table.create(q, 0), table.create(q, 0) + for p = 0, q - 1 do + local a = pi * (p + 0.125) / m + twc[p + 1], tws[p + 1] = cos(a), sin(a) + end + return { + n = n, + m = m, + fft = fft, + twc = twc, + tws = tws, + re = table.create(q, 0), + im = table.create(q, 0), + c = table.create(m, 0), + } +end + +-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] +local function dct4Post(plan, out, oi, os, scale) + local q, m = math.floor(plan.n / 4), plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + Fft.forward(plan.fft, re, im) + for k = 0, q - 1 do + local c, s = twc[k + 1], tws[k + 1] + local tr, ti = re[k + 1], im[k + 1] + out[oi + 2 * k * os] = (tr * c + ti * s) * scale + out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale + end +end + +-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the +-- plan's M = N / 2 (its own inverse up to 2 / M) +function Mdct.dct4(plan, u, ui, us, out, oi, os, scale) + local q, m = math.floor(plan.n / 4), plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + for p = 0, q - 1 do + local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os, scale or 1) +end + +-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] +function Mdct.forward(plan, x, xi, out, oi, os, scale) + local q, m = math.floor(plan.n / 4), plan.m + local h = math.floor(m / 2 -- N / 4 +) local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) + local b3 = xi + 3 * h + for p = 0, q - 1 do + local j = 2 * p + local a + if j < h then + a = -x[b3 - 1 - j] - x[b3 + j] + else + a = x[xi + j - h] - x[b3 - 1 - j] + end + j = m - 1 - 2 * p + local b + if j < h then + b = -x[b3 - 1 - j] - x[b3 + j] + else + b = x[xi + j - h] - x[b3 - 1 - j] + end + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os or 1, scale or 1) +end + +-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) +function Mdct.inverse(plan, inp, ii, is, y, yi, scale) + local m = plan.m + local h = math.floor(m / 2 +) local c = plan.c + Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) + -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) + for j = 0, h - 1 do + y[yi + j] = c[h + j + 1] + y[yi + h + j] = -c[m - j] + y[yi + m + j] = -c[h - j] + y[yi + 3 * h + j] = -c[j + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ windows +local function besselI0(x) +local sum, term = 1, 1 + local k = 1 + while k < 200 do + term =term* (x / (2 * k)) ^ 2 + sum =sum+ term + if term < sum * 1e-17 then + break + end + k =k+ 1 + end + return sum +end +Mdct.besselI0 = besselI0 + +-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 +-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +function Mdct.window(kind, n, alpha) +if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then + return nil + end + local w = table.create(n, 0) + if kind == "sine" then + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + elseif kind == "vorbis" then + for i = 0, n - 1 do + local s = sin(pi * (i + 0.5) / n) + w[i + 1] = sin(pi / 2 * s * s) + end + elseif kind == "kbd" then + local half = math.floor(n / 2 +) local a = alpha or 4 + local kais = table.create(half + 1, 0) + local total = 0 + for i = 0, half do + local r = 2 * i / half - 1 + kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) + total =total+ kais[i + 1] + end + local acc = 0 + for i = 0, half - 1 do + acc =acc+ kais[i + 1] + local v = sqrt(acc / total) + w[i + 1] = v + w[n - i] = v + end + else + return nil + end + return w +end + +-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) +function Mdct.fft(n) +return Fft.new(n) +end + +return Mdct +end +__FILES["codecs/audio/Mdct/Fft"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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. +local Fft = {} + + + + + + + + + + + + + + +local cos, sin, pi = math.cos, math.sin, math.pi + +-- new(n) -> Plan | nil (n < 1 or not an integer) +function Fft.new(n) +if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then + return nil + end + local factors = {} + local m = n + while m % 4 == 0 do + table.insert(factors, 4) + m =math.floor(m/ 4 +) end + while m % 2 == 0 do + table.insert(factors, 2) + m =math.floor(m/ 2 +) end + local f = 3 + while m > 1 do + while m % f == 0 do + table.insert(factors, f) + m =math.floor(m/ f +) end + f =f+ 2 + if f * f > m and m > 1 then + table.insert(factors, m) + m = 1 + end + end + local twr, twi, rr, ri = {}, {}, {}, {} + local l1 = 1 + for k, p in __iter(factors) do + local ido = math.floor(n / (l1 * p) +) local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) + for u = 1, p - 1 do + for i = 0, ido - 1 do + local a = -2 * pi * u * i * l1 / n + tr[(u - 1) * ido + i + 1] = cos(a) + ti[(u - 1) * ido + i + 1] = sin(a) + end + end + twr[k], twi[k] = tr, ti + local cr, ci = table.create(p, 0), table.create(p, 0) + for j = 0, p - 1 do + cr[j + 1] = cos(-2 * pi * j / p) + ci[j + 1] = sin(-2 * pi * j / p) + end + rr[k], ri[k] = cr, ci + l1 =l1* p + end + return { + n = n, + factors = factors, + twr = twr, + twi = twi, + rr = rr, + ri = ri, + sre = table.create(n, 0), + sim = table.create(n, 0), + } +end + +-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] +local function pass(p, ido, l1, ar, ai, br, bi, tr, ti, cr, ci) + local lp = ido * l1 + if p == 4 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 4 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] + local t0r, t0i = a0r + a2r, a0i + a2i + local t1r, t1i = a0r - a2r, a0i - a2i + local t2r, t2i = a1r + a3r, a1i + a3i + local t3r, t3i = a1r - a3r, a1i - a3i + local d = 1 + i + ido * k + br[d], bi[d] = t0r + t2r, t0i + t2i + local y1r, y1i = t1r + t3i, t1i - t3r + local y2r, y2i = t0r - t2r, t0i - t2i + local y3r, y3i = t1r - t3i, t1i + t3r + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r + end + end + end + elseif p == 2 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 2 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local d = 1 + i + ido * k + br[d], bi[d] = a0r + a1r, a0i + a1i + local yr, yi = a0r - a1r, a0i - a1i + if i == 0 then + br[d + lp], bi[d + lp] = yr, yi + else + local wr, wi = tr[i + 1], ti[i + 1] + br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr + end + end + end + elseif p == 3 then + local c = 0.86602540378443864676 -- sin(pi / 3) + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 3 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local tr_, ti_ = a1r + a2r, a1i + a2i + local sr, si = a1r - a2r, a1i - a2i + local d = 1 + i + ido * k + br[d], bi[d] = a0r + tr_, a0i + ti_ + local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ + local y1r, y1i = mr + c * si, mi - c * sr + local y2r, y2i = mr - c * si, mi + c * sr + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + end + end + end + else + -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * p * k + local d = 1 + i + ido * k + for u = 0, p - 1 do + local yr, yi = 0, 0 + local j = 0 + for v = 0, p - 1 do + local xr, xi = ar[s + v * ido], ai[s + v * ido] + local wr, wi = cr[j + 1], ci[j + 1] + yr =yr+ (xr * wr - xi * wi +) yi =yi+ (xr * wi + xi * wr +) j =j+ u + if j >= p then + j =j- p + end + end + if u > 0 and i > 0 then + local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] + yr, yi = yr * wr - yi * wi, yr * wi + yi * wr + end + br[d + u * lp], bi[d + u * lp] = yr, yi + end + end + end + end +end + +-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. +-- The inverse (without the 1 / n) is forward(plan, im, re). +function Fft.forward(plan, re, im) + local n = plan.n + local ar, ai, br, bi = re, im, plan.sre, plan.sim + local l1 = 1 + for k, p in __iter(plan.factors) do + local ido = math.floor(n / (l1 * p) +) pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) + ar, ai, br, bi = br, bi, ar, ai + l1 =l1* p + end + if ar ~= re then + for j = 1, n do + re[j], im[j] = ar[j], ai[j] + end + end +end + +return Fft +end +__FILES["codecs/audio/MidiRender"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in +-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). +-- Format 2: each track is its own song with its own tempo map, played one after another. Shared by every format that +-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method. +local Err = __include("core/Err") +local Types = __include("Types") +local SoundFont = __include("codecs/audio/SoundFont") + +local Synth = SoundFont.Synth + +local Render = {} + + + +local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } + +local function tempoOf(ev) +if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then + return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3] + end + return nil +end + +-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2) +function Render.tempoMap(midi, track) +local changes= {} + for ti, t in __iter(midi.tracks) do + if track == nil or track == ti then + for i, ev in __iter(t.events) do + local us = tempoOf(ev) + if us then + table.insert(changes, { ev.tick, ti, i, us }) + end + end + end + end + table.sort(changes, function(a, b) +if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local map= { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division } + local div = midi.division + for _, c in __iter(changes) do + local n = #map.ticks + local tick = c[1] + local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div + if tick == map.ticks[n] then + map.us[n] = c[4] + else + table.insert(map.ticks, tick) + table.insert(map.secs, sec) + table.insert(map.us, c[4]) + end + end + return map +end + +-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time) +function Render.seconds(map, tick) +local div = map.division + if div < 0 then + local fps = -(math.floor(div / 256)) + local tpf = div % 256 + if tpf == 0 then + return 0 + end + return tick / ((fps == 29 and 29.97 or fps) * tpf) + end + local ticks = map.ticks + -- binary search for the last change at or before tick + local lo, hi = 1, #ticks + while lo < hi do + local mid = math.floor((lo + hi + 1) / 2 +) if ticks[mid] <= tick then + lo = mid + else + hi = mid - 1 + end + end + return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div +end + +-- length(midi) -> seconds to the last event (format 2: the tracks one after another) +function Render.length(midi) +if #midi.tracks == 0 then + return 0 + end + if midi.format == 2 then + local total = 0 + for ti, t in __iter(midi.tracks) do + local map = Render.tempoMap(midi, ti) + local last = 0 + for _, ev in __iter(t.events) do + last = math.max(last, ev.tick) + end + total =total+ Render.seconds(map, last) + end + return total + end + local map = Render.tempoMap(midi) + local last = 0 + for _, t in __iter(midi.tracks) do + for _, ev in __iter(t.events) do + last = math.max(last, ev.tick) + end + end + return Render.seconds(map, last) +end + +-- timeline(midi) -> the channel messages in play order with their times in seconds + + +function Render.timeline(midi) +local items= {} + local offset = 0 + local function add(map, ti, t, base) + for i, ev in __iter(t.events) do + local st = STATUS[ev.type] + if st and type(ev.data) == "table" then + local ch = ev.channel or 0 + table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 }) + end + end + end + if midi.format == 2 then + for ti, t in __iter(midi.tracks) do + local map = Render.tempoMap(midi, ti) + add(map, ti, t, offset) + local last = 0 + for _, ev in __iter(t.events) do + last = math.max(last, ev.tick) + end + offset =offset+ Render.seconds(map, last) + end + else + local map = Render.tempoMap(midi) + for ti, t in __iter(midi.tracks) do + add(map, ti, t, 0) + end + end + table.sort(items, function(a, b) +if a[1] ~= b[1] then + return a[1] < b[1] + end + if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + local tl= { time = (table.create(#items) ), status = (table.create(#items) ), d1 = (table.create(#items) ), d2 = (table.create(#items) ), length = Render.length(midi) } + for i, it in __iter(items) do + tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128 + end + return tl +end + +-- decoder(midi, opts?) -> Types.Decoder | nil, Err + + + + + + + + +function Render.decoder(midi, opts) +if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then + return nil, Err.new(Err.ARG, "render: needs a Midi value") + end + local o= opts or {} + local rate = o.sampleRate or 44100 + if type(rate) ~= "number" or rate < 1000 or rate > 384000 then + return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000") + end + local sf = o.soundfont + if sf == nil then + sf = SoundFont.fallback() + elseif not SoundFont.isSoundFont(sf) then + local parsed, err = SoundFont.parse(sf) + if not parsed then + return nil, err + end + sf = parsed + end + local tl = Render.timeline(midi) + local tail = o.tail or 1 + local frames = math.max(0, math.ceil((tl.length + tail) * rate)) + local nev = #tl.time + local evFrame= (table.create(nev) ) +for i = 1, nev do + evFrame[i] = math.floor(tl.time[i] * rate + 0.5) + end + local gain, maxVoices = o.gain, o.maxVoices + local state = Synth.new(sf, rate, gain, maxVoices) + local pos, nextEv = 0, 1 + + local dec = { + sampleRate = rate, + channels = 2, + frames = frames, + duration = frames / rate, + bitrate = 0, + tags = {} , + } + local mtags = type(midi.meta) == "table" and midi.meta.tags + if type(mtags) == "table" then + for k, v in __iter(mtags) do + if type(k) == "string" and type(v) == "string" then + dec.tags[k] = v + end + end + end + for _, t in __iter(midi.tracks) do + if t.name and not dec.tags.title then + dec.tags.title = t.name + end + end + + local function read(_self, n, out) +n = math.max(0, math.min(math.floor(n), frames - pos)) + local buf = out + if not buf or buffer.len(buf) < n * 8 then + buf = buffer.create(math.max(n, 1) * 8) + end + local b = buf +buffer.fill(b, 0, 0, n * 8) + local i = 0 + while i < n do + while nextEv <= nev and evFrame[nextEv] <= pos + i do + Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv]) + nextEv =nextEv+ 1 + end + local stop = n + if nextEv <= nev then + stop = math.min(n, evFrame[nextEv] - pos) + end + if stop > i then + Synth.render(state, b, i, stop - i) + i = stop + end + end + pos =pos+ n + return b, n + end + dec.read = read +local scratch = buffer.create(4096 * 8) + dec.seek = function(_self, seconds) + local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames) + if target < pos then + Synth.reset(state) + pos, nextEv = 0, 1 + end + while pos < target do + read(nil, math.min(4096, target - pos), scratch) + end + end +dec.position = function(_self) +return pos / rate + end +return (dec ) , nil +end + +-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last +-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI) +function Render.tempoBytes(division, ticksPerSecond) +local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF) + return { math.floor(us / 65536), (math.floor(us / 256)) % 256, us % 256 } +end +-- ------------------------------------------------------------------------------------------------ durations +-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI). +-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note +-- started earlier goes before the file's events, an off of a zero-length note after them. + + + +function Render.merge(events, offs) +for i, o in __iter(offs) do + (o ).seq = i + end + table.sort(offs, function(a, b) +if a.tick ~= b.tick then + return a.tick < b.tick + end + return a.seq < b.seq + end) + local out= (table.create(#events + #offs) ) +local k = 1 + for _, ev in __iter(events) do + while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do + table.insert(out, offs[k].ev) + k =k+ 1 + end + table.insert(out, ev) + end + for j = k, #offs do + table.insert(out, offs[j].ev) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ attach +local function render(self, opts) +local dec, err = Render.decoder(self, opts) + if not dec then + -- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err) + local empty= { + sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err, + read = function(_self, _n, out) +return out or buffer.create(0), 0 + end, + seek = function() end, + position = function() +return 0 + end, + } + return empty + end + return dec +end + +-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events +function Render.summarize(midi) + local tempos, sigs, keys = {}, {}, {} + local map = Render.tempoMap(midi) + for ti, t in __iter(midi.tracks) do + for _, ev in __iter(t.events) do + if ev.type == "meta" then + local d = ev.data +if ev.meta == 0x51 and #d >= 3 then + table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) }) + elseif ev.meta == 0x58 and #d >= 4 then + table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] }) + elseif ev.meta == 0x59 and #d >= 2 then + table.insert(keys, { tick = ev.tick, track = ti, sharps = (d[1] >= 128 and((d[1] - 256 ))or(d[1])), minor = d[2] == 1 }) + end + end + end + end + midi.meta.tempos = tempos + midi.meta.timeSignatures = sigs + midi.meta.keySignatures = keys + midi.meta.length = Render.length(midi) +end + +-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method +function Render.attach(midi, source) + Render.summarize(midi) + midi.meta.source = source + midi.render = render +end + +return Render +end +__FILES["codecs/audio/Mpa"] = function() +--!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 = __include("codecs/audio/Mpa/Header"), + Core = __include("codecs/audio/Mpa/Core"), + Encode3 = __include("codecs/audio/Mpa/Encode3"), + Encode2 = __include("codecs/audio/Mpa/Encode2"), +} + +return Mpa +end +__FILES["codecs/audio/Mpa/Analysis"] = function() +--!strict +--!native +--!optimize 2 +-- 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 +-- 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 = __include("codecs/audio/Mpa/EncTables") + +local Analysis = {} + +local C = table.create(512, 0) +for i = 1, 512 do + C[i] = E.D[i] / 32 +end +local M = table.create(32 * 64, 0) -- M[k * 64 + i + 1] +for k = 0, 31 do + for i = 0, 63 do + M[k * 64 + i + 1] = math.cos((2 * k + 1) * (i - 16) * math.pi / 64) + end +end + + + +function Analysis.new() +return { x = table.create(1024, 0), off = 0, y = table.create(64, 0) } +end + +-- run(st, s, si, out, oi): s[si .. si + 31] (oldest first) -> out[oi .. oi + 31] (subbands 0 .. 31) +function Analysis.run(st, s, si, out, oi) + -- the window X is kept twice (x[p] and x[p + 512]) so X[i] = x[off + i + 1] without a modulo + local x = st.x + local off = (st.off - 32) % 512 + st.off = off + for j = 0, 31 do + local v = s[si + j] + local p = (off + 31 - j) % 512 + 1 -- X[31 - j]: the first new sample goes to X[31], the newest to X[0] + x[p] = v + x[p + 512] = v + end + local y = st.y + for i = 0, 63 do + local acc = 0 + local b = off + i + 1 + for j = 0, 7 do + acc =acc+ C[i + 64 * j + 1] * x[b + 64 * j] + end + y[i + 1] = acc + end + for k = 0, 31 do + local acc = 0 + local mb = k * 64 + for i = 1, 64 do + acc =acc+ M[mb + i] * y[i] + end + out[oi + k] = acc + end +end + +return Analysis +end +__FILES["codecs/audio/Mpa/Core"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 = __include("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 +local rf, wf = buffer.readf32, buffer.writef32 +local bcopy, bfill, bcreate = buffer.copy, buffer.fill, buffer.create +local min, max = math.min, math.max + +local MAX_BITRESERVOIR_BYTES = 511 +local MAX_FRAME = 2304 + 8 -- largest frame (free format) incl. padding, rounded up +local SCALE = 1 / 32768 + +---------------------------------------------------------------------------------------------------------------- +-- tables (floats rounded to f32 like the C arrays) + +local F32 = bcreate(4) +local function f32(x) +wf(F32, 0, x) + return rf(F32, 0) +end + +local function fbuf(list, n) +local b = bcreate(n * 4) + for i = 0, n - 1 do + wf(b, i * 4, list[i]) + end + return b +end + +-- scalefactor band widths: long (8 x 23) | short (8 x 40) | mixed (8 x 40), one u8 buffer +local SFB_LONG, SFB_SHORT, SFB_MIXED = 0, 184, 504 +local SFB = bcreate(824 + 8) +for i = 0, 183 do + wu8(SFB, SFB_LONG + i, T.g_scf_long[i]) +end +for i = 0, 319 do + wu8(SFB, SFB_SHORT + i, T.g_scf_short[i]) + wu8(SFB, SFB_MIXED + i, T.g_scf_mixed[i]) +end + +local TABS = bcreate(2164 * 2) +for i = 0, 2163 do + buffer.writei16(TABS, i * 2, T.tabs[i]) +end +local TAB32, TAB33 = T.tab32, T.tab33 +local TABINDEX, LINBITS = T.tabindex, T.g_linbits +local SCF_PARTITIONS, SCFC_DECODE, GMOD, PREAMP = T.g_scf_partitions, T.g_scfc_decode, T.g_mod, T.g_preamp +local EXPFRAC = { [0] = f32(T.g_expfrac[0]), f32(T.g_expfrac[1]), f32(T.g_expfrac[2]), f32(T.g_expfrac[3]) } +local PAN = {} +for i = 0, 13 do + PAN[i] = f32(T.g_pan[i]) +end +local BITALLOC_CODE = T.g_bitalloc_code_tab +local HALFRATE = T.halfrate + +-- L3_pow_43 for every value a Huffman pair can give (15 + 8191 linbits), evaluated in f32 like the C code +local POW43 = bcreate(8207 * 4) +do + local g = {} + for i = 0, 144 do + g[i] = f32(T.g_pow43[i]) + end + local c43, c29 = f32(4 / 3), f32(2 / 9) + for x0 = 0, 8206 do + local v + if x0 < 129 then + v = g[16 + x0] + else + local x, mult = x0, 256 + if x < 1024 then + mult = 16 + x =x* 8 + end + local sign = band(2 * x, 64) + local frac = f32((band(x, 63) - sign) / (band(x, bit32.bnot(63)) + sign)) + v = f32(f32(g[16 + rshift(x + sign, 6)] * f32(1 + f32(frac * f32(c43 + f32(frac * c29))))) * mult) + end + wf(POW43, x0 * 4, v) + end +end + +-- L12 dequantizer: 9.53674316e-07f / x (and two more steps of 2^(-1/3)) for 3, 7, ..., 65535, 3, 5, 9 +local DEQ_L12 = {} +do + local div = { 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 3, 5, 9 } + local base = { f32(9.53674316e-07), f32(7.56931807e-07), f32(6.00777173e-07) } + for i = 0, 17 do + for j = 0, 2 do + DEQ_L12[i * 3 + j] = f32(base[j + 1] / div[i + 1]) + end + end +end + +local AA = fbuf(T.g_aa, 16) +local TWID3 = fbuf(T.g_twid3, 6) +local MDCT_WIN0, MDCT_WIN1 = table.create(18, 0), table.create(18, 0) -- g_mdct_window[2][18], 1-based +for i = 0, 17 do + MDCT_WIN0[i + 1] = f32(T.g_mdct_window[i]) + MDCT_WIN1[i + 1] = f32(T.g_mdct_window[18 + i]) +end +local WINT = table.create(240, 0) -- g_win as a 1-based Luau array (f32 values) +for i = 0, 239 do + WINT[i + 1] = f32(T.g_win[i]) +end + +---------------------------------------------------------------------------------------------------------------- +-- scratch + +local FRAME = bcreate(MAX_FRAME + 64) -- the current frame, copied (bit reader reads up to 4 bytes ahead) +local MAIN = bcreate(MAX_BITRESERVOIR_BYTES + MAX_FRAME + 4096) -- layer III main data (reservoir + frame) +local GRBUF = bcreate(576 * 2 * 4) -- [ch][576] f32 +local SCF = bcreate(40 * 4) -- layer III scalefactor gains, f32 +local SYN = bcreate((18 + 15) * 64 * 4) -- synthesis lines / reorder scratch, f32 +local IST = bcreate(2 * 39 + 8) -- ist_pos[2][39], u8 +local ISCF = bcreate(48) -- integer scalefactors, u8 +local TMP = bcreate(18 * 4 * 2) -- imdct scratch: co[9] si[9] / short block copy[18] +local L12SCF = bcreate(192 * 4) -- L12 scalefactors [band*2 + ch][3], f32 +local BA = bcreate(64) -- L12 bit allocation +local SCFCOD = bcreate(64) + +-- layer III side info, per granule x channel (0..3) +local GR_P23, GR_BV, GR_SFC, GR_GAIN, GR_BT, GR_MIXED = {}, {}, {}, {}, {}, {} +local GR_NLONG, GR_NSHORT, GR_SFB, GR_PRE, GR_SCALE, GR_C1, GR_SCFSI = {}, {}, {}, {}, {}, {}, {} +local GR_TS, GR_RC, GR_SBG = {}, {}, {} -- [gr * 3 + k] +for i = 0, 3 do + GR_P23[i], GR_BV[i], GR_SFC[i], GR_GAIN[i], GR_BT[i], GR_MIXED[i] = 0, 0, 0, 0, 0, 0 + GR_NLONG[i], GR_NSHORT[i], GR_SFB[i], GR_PRE[i], GR_SCALE[i], GR_C1[i], GR_SCFSI[i] = 0, 0, 0, 0, 0, 0, 0 + for k = 0, 2 do + GR_TS[i * 3 + k], GR_RC[i * 3 + k], GR_SBG[i * 3 + k] = 0, 0, 0 + end +end +local MAXB = { [0] = -1, -1, -1 } +local SCFSIZE = { [0] = 0, 0, 0, 0 } + +-- per-stream state of the frame being decoded (set by decodeFrame) +local OVL= bcreate(4) -- mdct_overlap[2][9*32] +local QMF= bcreate(4) -- qmf_state[15*2*32] +local PCM= bcreate(4) + +---------------------------------------------------------------------------------------------------------------- +-- bit reader (bs_t): position and limit in bits + +local bsBuf= FRAME +local bsPos = 0 +local bsLimit = 0 + +-- n <= 25 +local function getBits(n) +local pos = bsPos + bsPos = pos + n + if pos + n > bsLimit then + return 0 + end + local w = lshift(bswap(ru32(bsBuf, rshift(pos, 3))), band(pos, 7)) + return rshift(w, 32 - n) +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III side info (L3_read_side_info): fills GR_*, returns main_data_begin or -1 + +local function readSideInfo(h1, h2, h3) +local mono = band(h3, 0xC0) == 0xC0 + local mpeg1 = band(h1, 8) ~= 0 + local srIdx = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + if srIdx ~= 0 then + srIdx =srIdx- 1 + end + local grCount = mono and 1 or 2 + local scfsi = 0 + local mdb + if mpeg1 then + grCount =grCount* 2 + mdb = getBits(9) + scfsi = getBits(7 + grCount) + else + mdb = rshift(getBits(8 + grCount), grCount) + end + local part23sum = 0 + for gr = 0, grCount - 1 do + if mono then + scfsi = lshift(scfsi, 4) + end + local p23 = getBits(12) + GR_P23[gr] = p23 + part23sum =part23sum+ p23 + local bv = getBits(9) + if bv > 288 then + return -1 + end + GR_BV[gr] = bv + GR_GAIN[gr] = getBits(8) + local sfc = getBits(mpeg1 and 4 or 9) + GR_SFC[gr] = sfc + GR_SFB[gr] = SFB_LONG + srIdx * 23 + GR_NLONG[gr] = 22 + GR_NSHORT[gr] = 0 + local tables + local g3 = gr * 3 + if getBits(1) ~= 0 then + local bt = getBits(2) + if bt == 0 then + return -1 + end + GR_BT[gr] = bt + local mixed = getBits(1) + GR_MIXED[gr] = mixed + GR_RC[g3] = 7 + GR_RC[g3 + 1] = 255 + if bt == 2 then + scfsi = band(scfsi, 0x0F0F) + if mixed == 0 then + GR_RC[g3] = 8 + GR_SFB[gr] = SFB_SHORT + srIdx * 40 + GR_NLONG[gr] = 0 + GR_NSHORT[gr] = 39 + else + GR_SFB[gr] = SFB_MIXED + srIdx * 40 + GR_NLONG[gr] = mpeg1 and 8 or 6 + GR_NSHORT[gr] = 30 + end + end + tables = lshift(getBits(10), 5) + GR_SBG[g3] = getBits(3) + GR_SBG[g3 + 1] = getBits(3) + GR_SBG[g3 + 2] = getBits(3) + else + GR_BT[gr] = 0 + GR_MIXED[gr] = 0 + tables = getBits(15) + GR_RC[g3] = getBits(4) + GR_RC[g3 + 1] = getBits(3) + GR_RC[g3 + 2] = 255 + end + GR_TS[g3] = rshift(tables, 10) + GR_TS[g3 + 1] = band(rshift(tables, 5), 31) + GR_TS[g3 + 2] = band(tables, 31) + GR_PRE[gr] = (mpeg1 and{(getBits(1) )}or{sfc >= 500 and 1 or 0 +})[1] GR_SCALE[gr] = getBits(1) + GR_C1[gr] = getBits(1) + GR_SCFSI[gr] = band(rshift(scfsi, 12), 15) + scfsi = lshift(scfsi, 4) + end + if part23sum + bsPos > bsLimit + mdb * 8 then + return -1 + end + return mdb +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III scalefactors + +local function ldexpQ2(y, e) +repeat + local s = (e < 120 and{e }or{120 +})[1] y = f32(y * EXPFRAC[band(s, 3)] * lshift(1, 30 - arshift(s, 2))) + e =e- s + until e <= 0 + return y +end + +-- L3_read_scalefactors + L3_decode_scalefactors -> SCF[0 .. nLong + nShort) +local function decodeScalefactors(h1, h3, istOff, gr, ch) + local mpeg1 = band(h1, 8) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local part = ((nShort ~= 0 and 1 or 0) + (nLong == 0 and 1 or 0)) * 28 + local scfShift = GR_SCALE[gr] + 1 + local scfsi = GR_SCFSI[gr] + if mpeg1 then + local p = SCFC_DECODE[GR_SFC[gr] ] + local hi, lo = rshift(p, 2), band(p, 3) + SCFSIZE[0], SCFSIZE[1], SCFSIZE[2], SCFSIZE[3] = hi, hi, lo, lo + else + local ist = band(h3, 0x10) ~= 0 and ch ~= 0 and 1 or 0 + local sfc = rshift(GR_SFC[gr], ist) + local k = ist * 12 + while sfc >= 0 do + local modprod = 1 + for i = 3, 0, -1 do + SCFSIZE[i] = (math.floor(sfc / modprod)) % GMOD[k + i] + modprod =modprod* GMOD[k + i] + end + sfc =sfc- modprod + k =k+ 4 + end + part =part+ k + end + -- L3_read_scalefactors + local sp, ip = 0, istOff + for i = 0, 3 do + local cnt = SCF_PARTITIONS[part + i] + if cnt == 0 then + break + end + if mpeg1 and band(scfsi, 8) ~= 0 then + bcopy(ISCF, sp, IST, ip, cnt) + else + local bits = SCFSIZE[i] + if bits == 0 then + bfill(ISCF, sp, 0, cnt) + bfill(IST, ip, 0, cnt) + else + local maxScf = mpeg1 and-1 or lshift(1, bits) - 1 + for k = 0, cnt - 1 do + local s = getBits(bits) + wu8(IST, ip + k, s == maxScf and 255 or s) + wu8(ISCF, sp + k, s) + end + end + end + sp =sp+ cnt + ip =ip+ cnt + scfsi =scfsi* 2 + end + wu8(ISCF, sp, 0) + wu8(ISCF, sp + 1, 0) + wu8(ISCF, sp + 2, 0) + + if nShort ~= 0 then + local sh = 3 - scfShift + local g3 = gr * 3 + local s0, s1, s2 = lshift(GR_SBG[g3], sh), lshift(GR_SBG[g3 + 1], sh), lshift(GR_SBG[g3 + 2], sh) + for i = 0, nShort - 1, 3 do + local o = nLong + i + wu8(ISCF, o, band(ru8(ISCF, o) + s0, 255)) + wu8(ISCF, o + 1, band(ru8(ISCF, o + 1) + s1, 255)) + wu8(ISCF, o + 2, band(ru8(ISCF, o + 2) + s2, 255)) + end + elseif GR_PRE[gr] ~= 0 then + for i = 0, 9 do + wu8(ISCF, 11 + i, band(ru8(ISCF, 11 + i) + PREAMP[i], 255)) + end + end + + local gainExp = GR_GAIN[gr] - 4 - 210 - (band(h3, 0xE0) == 0x60 and 2 or 0) + local gain = ldexpQ2(2048, 44 - gainExp) + for i = 0, nLong + nShort - 1 do + wf(SCF, i * 4, ldexpQ2(gain, lshift(ru8(ISCF, i), scfShift))) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III Huffman decoding (L3_huffman) into GRBUF[dst ..], reads MAIN through a 32-bit cache + +local function huffman(dst, gr, limit) + local b = bsBuf + local one = 0.0 + local ireg = 0 + local bigValCnt = GR_BV[gr] + local sfb = GR_SFB[gr] + local scf = 0 + local pos = bsPos + local nextPtr = rshift(pos, 3) + local cache = lshift(bswap(ru32(b, nextPtr)), band(pos, 7)) + local sh = band(pos, 7) - 8 + nextPtr =nextPtr+ 4 + local g3 = gr * 3 + local d = dst * 4 + + while bigValCnt > 0 do + if ireg > 2 then + break + end + local tabNum = GR_TS[g3 + ireg] + local sfbCnt = GR_RC[g3 + ireg] + ireg =ireg+ 1 + local cb = TABINDEX[tabNum] + local linbits = LINBITS[tabNum] + repeat + local np = rshift(ru8(SFB, sfb), 1) + sfb =sfb+ 1 + if np == 0 then + bigValCnt = 0 + break + end + local pairs = (bigValCnt < np and{bigValCnt }or{np +})[1] one = rf(SCF, scf) + scf =scf+ 4 + for _ = 1, pairs do + local w = 5 + local leaf = ri16(TABS, (cb + rshift(cache, 27)) * 2) + while leaf < 0 do + cache = lshift(cache, w) + sh =sh+ w + w = band(leaf, 7) + leaf = ri16(TABS, (cb + rshift(cache, 32 - w) - math.floor(leaf / 8)) * 2) + end + local l = rshift(leaf, 8) + cache = lshift(cache, l) + sh =sh+ l + for _ = 1, 2 do + local lsb = band(leaf, 15) + if lsb == 15 and linbits ~= 0 then + lsb =lsb+ rshift(cache, 32 - linbits) + cache = lshift(cache, linbits) + sh =sh+ linbits + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr =nextPtr+ 1 + sh =sh- 8 + end + end + local v = rf(POW43, lsb * 4) * one + if lsb ~= 0 then + if cache >= 0x80000000 then + v = -v + end + cache = lshift(cache, 1) + sh =sh+ 1 + end + wf(GRBUF, d, v) + d =d+ 4 + leaf = rshift(leaf, 4) + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr =nextPtr+ 1 + sh =sh- 8 + end + end + bigValCnt =bigValCnt- np + sfbCnt =sfbCnt- 1 + until not (bigValCnt > 0 and sfbCnt >= 0) + end + + -- count1 quadruples + local np = 1 - bigValCnt + local cb1 = (GR_C1[gr] ~= 0 and{TAB33 }or{TAB32 +})[1] local dend = 576 * 4 * 2 + while true do + local leaf = cb1[rshift(cache, 28)] + if band(leaf, 8) == 0 then + leaf = cb1[rshift(leaf, 3) + rshift(lshift(cache, 4), 32 - band(leaf, 3))] + end + local l = band(leaf, 7) + cache = lshift(cache, l) + sh =sh+ l + if nextPtr * 8 - 24 + sh > limit or d + 16 > dend then + break + end + np =np- 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb =sfb+ 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf =scf+ 4 + end + if band(leaf, 128) ~= 0 then + wf(GRBUF, d, (cache >= 0x80000000 and{(-one )}or{one})[1]) + cache = lshift(cache, 1) + sh =sh+ 1 + end + if band(leaf, 64) ~= 0 then + wf(GRBUF, d + 4, (cache >= 0x80000000 and{(-one )}or{one})[1]) + cache = lshift(cache, 1) + sh =sh+ 1 + end + np =np- 1 + if np == 0 then + np = rshift(ru8(SFB, sfb), 1) + sfb =sfb+ 1 + if np == 0 then + break + end + one = rf(SCF, scf) + scf =scf+ 4 + end + if band(leaf, 32) ~= 0 then + wf(GRBUF, d + 8, (cache >= 0x80000000 and{(-one )}or{one})[1]) + cache = lshift(cache, 1) + sh =sh+ 1 + end + if band(leaf, 16) ~= 0 then + wf(GRBUF, d + 12, (cache >= 0x80000000 and{(-one )}or{one})[1]) + cache = lshift(cache, 1) + sh =sh+ 1 + end + while sh >= 0 do + cache = bor(cache, lshift(ru8(b, nextPtr), sh)) + nextPtr =nextPtr+ 1 + sh =sh- 8 + end + d =d+ 16 + end + bsPos = limit +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III stereo + +-- L3_midside_stereo on GRBUF[left .. left + n) and its right channel at + 576 +local function midside(left, n) + for i = left * 4, (left + n - 1) * 4, 4 do + local a, c = rf(GRBUF, i), rf(GRBUF, i + 2304) + wf(GRBUF, i, a + c) + wf(GRBUF, i + 2304, a - c) + end +end + +local function intensityStereo(h1, h3, gr) + local mpeg1 = band(h1, 8) ~= 0 + local ms = band(h3, 0x20) ~= 0 + local nLong, nShort = GR_NLONG[gr], GR_NSHORT[gr] + local nSfb = nLong + nShort + local maxBlocks = nShort ~= 0 and 3 or 1 + local sfb0 = GR_SFB[gr] + -- L3_stereo_top_band on the right channel + MAXB[0], MAXB[1], MAXB[2] = -1, -1, -1 + local right = 576 + for i = 0, nSfb - 1 do + local n = ru8(SFB, sfb0 + i) + for k = right, right + n - 1, 2 do + if rf(GRBUF, k * 4) ~= 0 or rf(GRBUF, k * 4 + 4) ~= 0 then + MAXB[i % 3] = i + break + end + end + right =right+ n + end + if nLong ~= 0 then + local m = max(MAXB[0], MAXB[1], MAXB[2]) + MAXB[0], MAXB[1], MAXB[2] = m, m, m + end + for i = 0, maxBlocks - 1 do + local defaultPos = mpeg1 and 3 or 0 + local itop = nSfb - maxBlocks + i + local prev = itop - maxBlocks + wu8(IST, 39 + itop, (MAXB[i] >= prev and{defaultPos }or{(ru8(IST, 39 + prev))})[1]) + end + -- L3_stereo_process + local mpeg2sh = band(GR_SFC[gr + 1], 1) + local maxPos = mpeg1 and 7 or 64 + local s = (ms and{(f32(1.41421356) )}or{1 +})[1] local left = 0 + local i = 0 + while true do + local n = ru8(SFB, sfb0 + i) + if n == 0 then + break + end + local ipos = ru8(IST, 39 + i) + if i > MAXB[i % 3] and ipos < maxPos then + local kl, kr + if mpeg1 then + kl, kr = PAN[2 * ipos], PAN[2 * ipos + 1] + else + kl = 1 + kr = ldexpQ2(1, lshift(rshift(ipos + 1, 1), mpeg2sh)) + if band(ipos, 1) ~= 0 then + kl = kr + kr = 1 + end + end + 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) + wf(GRBUF, k, v * kl) + end + elseif ms then + midside(left, n) + end + left =left+ n + i =i+ 1 + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layer III reorder, antialias, IMDCT + +local function reorder(g, sfb) + local src, dst = g, 0 + while true do + local len = ru8(SFB, sfb) + if len == 0 then + break + end + for i = 0, len - 1 do + local s = (src + i) * 4 + wf(SYN, dst, rf(GRBUF, s)) + wf(SYN, dst + 4, rf(GRBUF, s + len * 4)) + wf(SYN, dst + 8, rf(GRBUF, s + len * 8)) + dst =dst+ 12 + end + src =src+ 3 * len + sfb =sfb+ 3 + end + bcopy(GRBUF, g * 4, SYN, 0, dst) +end + +local AA0 = table.create(8, 0) +local AA1 = table.create(8, 0) +for i = 0, 7 do + AA0[i + 1] = rf(AA, i * 4) + AA1[i + 1] = rf(AA, 32 + i * 4) +end + +local function antialias(g, nbands) + local o = g * 4 + for _ = 1, nbands do + for i = 0, 7 do + local ui, di = o + (18 + i) * 4, o + (17 - i) * 4 + local u, d = rf(GRBUF, ui), rf(GRBUF, di) + local c0, c1 = AA0[i + 1], AA1[i + 1] + wf(GRBUF, ui, u * c0 - d * c1) + wf(GRBUF, di, u * c1 + d * c0) + end + o =o+ 72 + end +end + +-- BEGIN generated by tools/gen_dsp.py + +-- L3_dct3_9 on 9 values +local function dct3_9(s0, s1, s2, s3, s4, s5, s6, s7, s8) + local t0 = s0 + s6 * 0.5 + s0 =s0- s6 + local t4 = (s4 + s2) * 0.939692616 + local t2 = (s8 + s2) * 0.766044438 + s6 = (s4 - s8) * 0.173648179 + s4 =s4+ (s8 - s2 +) s2 = s0 - s4 * 0.5 + local y4 = s4 + s0 + s8 = t0 - t2 + s6 + s0 = t0 - t4 + t2 + s4 = t0 + t4 - s6 + s3 =s3* 0.866025388 + t0 = (s5 + s1) * 0.98480773 + t4 = (s5 - s7) * 0.342020154 + t2 = (s1 + s7) * 0.642787635 + s1 = (s1 - s5 - s7) * 0.866025388 + s5 = t0 - s3 - t2 + s7 = t4 - s3 - t0 + s3 = t4 + s3 - t2 + return s4 - s7, s2 + s1, s0 - s3, s8 + s5, y4, s8 - s5, s0 + s3, s2 - s1, s4 + s7 +end + +-- L3_imdct36: GRBUF[g ..], OVL[ov ..] (float indices), window W (1-based, 18 values) +local function imdct36(g, ov, W, nbands) + local w0 = W[1] + local w1 = W[2] + local w2 = W[3] + local w3 = W[4] + local w4 = W[5] + local w5 = W[6] + local w6 = W[7] + local w7 = W[8] + local w8 = W[9] + local w9 = W[10] + local w10 = W[11] + local w11 = W[12] + local w12 = W[13] + local w13 = W[14] + local w14 = W[15] + local w15 = W[16] + local w16 = W[17] + local w17 = W[18] + for _ = 1, nbands do + local gb = g * 4 + local g0 = rf(GRBUF, gb + 0) + local g1 = rf(GRBUF, gb + 4) + local g2 = rf(GRBUF, gb + 8) + local g3 = rf(GRBUF, gb + 12) + local g4 = rf(GRBUF, gb + 16) + local g5 = rf(GRBUF, gb + 20) + local g6 = rf(GRBUF, gb + 24) + local g7 = rf(GRBUF, gb + 28) + local g8 = rf(GRBUF, gb + 32) + local g9 = rf(GRBUF, gb + 36) + local g10 = rf(GRBUF, gb + 40) + local g11 = rf(GRBUF, gb + 44) + local g12 = rf(GRBUF, gb + 48) + local g13 = rf(GRBUF, gb + 52) + local g14 = rf(GRBUF, gb + 56) + local g15 = rf(GRBUF, gb + 60) + local g16 = rf(GRBUF, gb + 64) + local g17 = rf(GRBUF, gb + 68) + local c0, c1, c2, c3, c4, c5, c6, c7, c8 = dct3_9(-g0, g1 + g2, -(g3 + g4), g5 + g6, -(g7 + g8), g9 + g10, -(g11 + g12), g13 + g14, -(g15 + g16)) + local s0, s1, s2, s3, s4, s5, s6, s7, s8 = dct3_9(g17, g16 - g15, g13 - g14, g12 - g11, g9 - g10, g8 - g7, g5 - g6, g4 - g3, g1 - g2) + s1, s3, s5, s7 = -s1, -s3, -s5, -s7 + local ob = ov * 4 + do + local ovl = rf(OVL, ob + 0) + local sum = c0 * 0.675590217 + s0 * 0.737277329 + wf(OVL, ob + 0, c0 * 0.737277329 - s0 * 0.675590217) + wf(GRBUF, gb + 0, ovl * w0 - sum * w9) + wf(GRBUF, gb + 68, ovl * w9 + sum * w0) + end + do + local ovl = rf(OVL, ob + 4) + local sum = c1 * 0.60876143 + s1 * 0.793353319 + wf(OVL, ob + 4, c1 * 0.793353319 - s1 * 0.60876143) + wf(GRBUF, gb + 4, ovl * w1 - sum * w10) + wf(GRBUF, gb + 64, ovl * w10 + sum * w1) + end + do + local ovl = rf(OVL, ob + 8) + local sum = c2 * 0.537299633 + s2 * 0.843391478 + wf(OVL, ob + 8, c2 * 0.843391478 - s2 * 0.537299633) + wf(GRBUF, gb + 8, ovl * w2 - sum * w11) + wf(GRBUF, gb + 60, ovl * w11 + sum * w2) + end + do + local ovl = rf(OVL, ob + 12) + local sum = c3 * 0.4617486 + s3 * 0.887010813 + wf(OVL, ob + 12, c3 * 0.887010813 - s3 * 0.4617486) + wf(GRBUF, gb + 12, ovl * w3 - sum * w12) + wf(GRBUF, gb + 56, ovl * w12 + sum * w3) + end + do + local ovl = rf(OVL, ob + 16) + local sum = c4 * 0.382683426 + s4 * 0.923879504 + wf(OVL, ob + 16, c4 * 0.923879504 - s4 * 0.382683426) + wf(GRBUF, gb + 16, ovl * w4 - sum * w13) + wf(GRBUF, gb + 52, ovl * w13 + sum * w4) + end + do + local ovl = rf(OVL, ob + 20) + local sum = c5 * 0.300705791 + s5 * 0.953716934 + wf(OVL, ob + 20, c5 * 0.953716934 - s5 * 0.300705791) + wf(GRBUF, gb + 20, ovl * w5 - sum * w14) + wf(GRBUF, gb + 48, ovl * w14 + sum * w5) + end + do + local ovl = rf(OVL, ob + 24) + local sum = c6 * 0.216439605 + s6 * 0.976296008 + wf(OVL, ob + 24, c6 * 0.976296008 - s6 * 0.216439605) + wf(GRBUF, gb + 24, ovl * w6 - sum * w15) + wf(GRBUF, gb + 44, ovl * w15 + sum * w6) + end + do + local ovl = rf(OVL, ob + 28) + local sum = c7 * 0.130526185 + s7 * 0.991444886 + wf(OVL, ob + 28, c7 * 0.991444886 - s7 * 0.130526185) + wf(GRBUF, gb + 28, ovl * w7 - sum * w16) + wf(GRBUF, gb + 40, ovl * w16 + sum * w7) + end + do + local ovl = rf(OVL, ob + 32) + local sum = c8 * 0.0436193794 + s8 * 0.999048233 + wf(OVL, ob + 32, c8 * 0.999048233 - s8 * 0.0436193794) + wf(GRBUF, gb + 32, ovl * w8 - sum * w17) + wf(GRBUF, gb + 36, ovl * w17 + sum * w8) + end + g =g+ 18 + ov =ov+ 9 + end +end + +-- mp3d_DCT_II (scalar path) over the n time slots of a channel at GRBUF[g ..]: t[4][8] in locals +local function dctII(g, n) + for k = 0, n - 1 do + local y = (g + k) * 4 + local t0_0, t1_0, t2_0, t3_0 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 0), rf(GRBUF, y + 1080), rf(GRBUF, y + 1152), rf(GRBUF, y + 2232) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 10.1900082, (x0 - x3) * 0.50060302 + t0_0 = a + b + t1_0 = (a - b) * 0.502419293 + t2_0 = d + c + t3_0 = (d - c) * 0.502419293 + end + local t0_1, t1_1, t2_1, t3_1 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 72), rf(GRBUF, y + 1008), rf(GRBUF, y + 1224), rf(GRBUF, y + 2160) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 3.40760851, (x0 - x3) * 0.505470932 + t0_1 = a + b + t1_1 = (a - b) * 0.522498608 + t2_1 = d + c + t3_1 = (d - c) * 0.522498608 + end + local t0_2, t1_2, t2_2, t3_2 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 144), rf(GRBUF, y + 936), rf(GRBUF, y + 1296), rf(GRBUF, y + 2088) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 2.05778098, (x0 - x3) * 0.515447319 + t0_2 = a + b + t1_2 = (a - b) * 0.566944063 + t2_2 = d + c + t3_2 = (d - c) * 0.566944063 + end + local t0_3, t1_3, t2_3, t3_3 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 216), rf(GRBUF, y + 864), rf(GRBUF, y + 1368), rf(GRBUF, y + 2016) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.4841646, (x0 - x3) * 0.531042576 + t0_3 = a + b + t1_3 = (a - b) * 0.646821797 + t2_3 = d + c + t3_3 = (d - c) * 0.646821797 + end + local t0_4, t1_4, t2_4, t3_4 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 288), rf(GRBUF, y + 792), rf(GRBUF, y + 1440), rf(GRBUF, y + 1944) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 1.16943991, (x0 - x3) * 0.553103924 + t0_4 = a + b + t1_4 = (a - b) * 0.788154602 + t2_4 = d + c + t3_4 = (d - c) * 0.788154602 + end + local t0_5, t1_5, t2_5, t3_5 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 360), rf(GRBUF, y + 720), rf(GRBUF, y + 1512), rf(GRBUF, y + 1872) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.972568214, (x0 - x3) * 0.582934976 + t0_5 = a + b + t1_5 = (a - b) * 1.06067765 + t2_5 = d + c + t3_5 = (d - c) * 1.06067765 + end + local t0_6, t1_6, t2_6, t3_6 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 432), rf(GRBUF, y + 648), rf(GRBUF, y + 1584), rf(GRBUF, y + 1800) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.839349627, (x0 - x3) * 0.622504115 + t0_6 = a + b + t1_6 = (a - b) * 1.72244716 + t2_6 = d + c + t3_6 = (d - c) * 1.72244716 + end + local t0_7, t1_7, t2_7, t3_7 + do + local x0, x1, x2, x3 = rf(GRBUF, y + 504), rf(GRBUF, y + 576), rf(GRBUF, y + 1656), rf(GRBUF, y + 1728) + local a, b = x0 + x3, x1 + x2 + local c, d = (x1 - x2) * 0.744536281, (x0 - x3) * 0.674808323 + t0_7 = a + b + t1_7 = (a - b) * 5.10114861 + t2_7 = d + c + t3_7 = (d - c) * 5.10114861 + end + do -- row 0 + local x0, x1, x2, x3, x4, x5, x6, x7 = t0_0, t0_1, t0_2, t0_3, t0_4, t0_5, t0_6, t0_7 + local xt = x0 - x7 + x0 =x0+ x7 + x7 = x1 - x6 + x1 =x1+ x6 + x6 = x2 - x5 + x2 =x2+ x5 + x5 = x3 - x4 + x3 =x3+ x4 + x4 = x0 - x3 + x0 =x0+ x3 + x3 = x1 - x2 + x1 =x1+ x2 + t0_0 = x0 + x1 + t0_4 = (x0 - x1) * 0.707106769 + x5 =x5+ x6 + x6 = (x6 + x7) * 0.707106769 + x7 =x7+ xt + x3 = (x3 + x4) * 0.707106769 + x5 =x5- x7 * 0.198912367 + x7 =x7+ x5 * 0.382683426 + x5 =x5- x7 * 0.198912367 + x0 = xt - x6 + xt =xt+ x6 + t0_1 = (xt + x7) * 0.509795606 + t0_2 = (x4 + x3) * 0.541196108 + t0_3 = (x0 - x5) * 0.601344883 + t0_5 = (x0 + x5) * 0.899976194 + t0_6 = (x4 - x3) * 1.30656302 + t0_7 = (xt - x7) * 2.56291556 + end + do -- row 1 + local x0, x1, x2, x3, x4, x5, x6, x7 = t1_0, t1_1, t1_2, t1_3, t1_4, t1_5, t1_6, t1_7 + local xt = x0 - x7 + x0 =x0+ x7 + x7 = x1 - x6 + x1 =x1+ x6 + x6 = x2 - x5 + x2 =x2+ x5 + x5 = x3 - x4 + x3 =x3+ x4 + x4 = x0 - x3 + x0 =x0+ x3 + x3 = x1 - x2 + x1 =x1+ x2 + t1_0 = x0 + x1 + t1_4 = (x0 - x1) * 0.707106769 + x5 =x5+ x6 + x6 = (x6 + x7) * 0.707106769 + x7 =x7+ xt + x3 = (x3 + x4) * 0.707106769 + x5 =x5- x7 * 0.198912367 + x7 =x7+ x5 * 0.382683426 + x5 =x5- x7 * 0.198912367 + x0 = xt - x6 + xt =xt+ x6 + t1_1 = (xt + x7) * 0.509795606 + t1_2 = (x4 + x3) * 0.541196108 + t1_3 = (x0 - x5) * 0.601344883 + t1_5 = (x0 + x5) * 0.899976194 + t1_6 = (x4 - x3) * 1.30656302 + t1_7 = (xt - x7) * 2.56291556 + end + do -- row 2 + local x0, x1, x2, x3, x4, x5, x6, x7 = t2_0, t2_1, t2_2, t2_3, t2_4, t2_5, t2_6, t2_7 + local xt = x0 - x7 + x0 =x0+ x7 + x7 = x1 - x6 + x1 =x1+ x6 + x6 = x2 - x5 + x2 =x2+ x5 + x5 = x3 - x4 + x3 =x3+ x4 + x4 = x0 - x3 + x0 =x0+ x3 + x3 = x1 - x2 + x1 =x1+ x2 + t2_0 = x0 + x1 + t2_4 = (x0 - x1) * 0.707106769 + x5 =x5+ x6 + x6 = (x6 + x7) * 0.707106769 + x7 =x7+ xt + x3 = (x3 + x4) * 0.707106769 + x5 =x5- x7 * 0.198912367 + x7 =x7+ x5 * 0.382683426 + x5 =x5- x7 * 0.198912367 + x0 = xt - x6 + xt =xt+ x6 + t2_1 = (xt + x7) * 0.509795606 + t2_2 = (x4 + x3) * 0.541196108 + t2_3 = (x0 - x5) * 0.601344883 + t2_5 = (x0 + x5) * 0.899976194 + t2_6 = (x4 - x3) * 1.30656302 + t2_7 = (xt - x7) * 2.56291556 + end + do -- row 3 + local x0, x1, x2, x3, x4, x5, x6, x7 = t3_0, t3_1, t3_2, t3_3, t3_4, t3_5, t3_6, t3_7 + local xt = x0 - x7 + x0 =x0+ x7 + x7 = x1 - x6 + x1 =x1+ x6 + x6 = x2 - x5 + x2 =x2+ x5 + x5 = x3 - x4 + x3 =x3+ x4 + x4 = x0 - x3 + x0 =x0+ x3 + x3 = x1 - x2 + x1 =x1+ x2 + t3_0 = x0 + x1 + t3_4 = (x0 - x1) * 0.707106769 + x5 =x5+ x6 + x6 = (x6 + x7) * 0.707106769 + x7 =x7+ xt + x3 = (x3 + x4) * 0.707106769 + x5 =x5- x7 * 0.198912367 + x7 =x7+ x5 * 0.382683426 + x5 =x5- x7 * 0.198912367 + x0 = xt - x6 + xt =xt+ x6 + t3_1 = (xt + x7) * 0.509795606 + t3_2 = (x4 + x3) * 0.541196108 + t3_3 = (x0 - x5) * 0.601344883 + t3_5 = (x0 + x5) * 0.899976194 + t3_6 = (x4 - x3) * 1.30656302 + t3_7 = (xt - x7) * 2.56291556 + end + wf(GRBUF, y + 0, t0_0) + wf(GRBUF, y + 72, t2_0 + t3_0 + t3_1) + wf(GRBUF, y + 144, t1_0 + t1_1) + wf(GRBUF, y + 216, t2_1 + t3_0 + t3_1) + wf(GRBUF, y + 288, t0_1) + wf(GRBUF, y + 360, t2_1 + t3_1 + t3_2) + wf(GRBUF, y + 432, t1_1 + t1_2) + wf(GRBUF, y + 504, t2_2 + t3_1 + t3_2) + wf(GRBUF, y + 576, t0_2) + wf(GRBUF, y + 648, t2_2 + t3_2 + t3_3) + wf(GRBUF, y + 720, t1_2 + t1_3) + wf(GRBUF, y + 792, t2_3 + t3_2 + t3_3) + wf(GRBUF, y + 864, t0_3) + wf(GRBUF, y + 936, t2_3 + t3_3 + t3_4) + wf(GRBUF, y + 1008, t1_3 + t1_4) + wf(GRBUF, y + 1080, t2_4 + t3_3 + t3_4) + wf(GRBUF, y + 1152, t0_4) + wf(GRBUF, y + 1224, t2_4 + t3_4 + t3_5) + wf(GRBUF, y + 1296, t1_4 + t1_5) + wf(GRBUF, y + 1368, t2_5 + t3_4 + t3_5) + wf(GRBUF, y + 1440, t0_5) + wf(GRBUF, y + 1512, t2_5 + t3_5 + t3_6) + wf(GRBUF, y + 1584, t1_5 + t1_6) + wf(GRBUF, y + 1656, t2_6 + t3_5 + t3_6) + wf(GRBUF, y + 1728, t0_6) + wf(GRBUF, y + 1800, t2_6 + t3_6 + t3_7) + wf(GRBUF, y + 1872, t1_6 + t1_7) + wf(GRBUF, y + 1944, t2_7 + t3_6 + t3_7) + wf(GRBUF, y + 2016, t0_7) + wf(GRBUF, y + 2088, t2_7 + t3_7) + wf(GRBUF, y + 2160, t1_7) + wf(GRBUF, y + 2232, t3_7) + end +end + +-- END generated + + +-- L3_imdct12: x = TMP f32 index (stride 3), dst buffer + float index, ov = OVL float index +local function imdct12(x, dst, d, ov) + local xb = x * 4 + local x0, x3, x6, x9, x12, x15 = + rf(TMP, xb), rf(TMP, xb + 12), rf(TMP, xb + 24), rf(TMP, xb + 36), rf(TMP, xb + 48), rf(TMP, xb + 60) + -- L3_idct3(-x0, x6 + x3, x12 + x9) -> co + local c0, c1, c2 = -x0, (x6 + x3), (x12 + x9) + local m1 = (c1 * 0.86602540) + local a1 = (c0 - c2 * 0.5) + local co1 = c0 + c2 + local co0, co2 = a1 + m1, a1 - m1 + -- L3_idct3(x15, x12 - x9, x6 - x3) -> si + c0, c1, c2 = x15, (x12 - x9), (x6 - x3) + m1 = (c1 * 0.86602540) + a1 = (c0 - c2 * 0.5) + local si1 = -(c0 + c2) + local si0, si2 = a1 + m1, a1 - m1 + local ob, db = ov * 4, d * 4 + for i = 0, 2 do + local co = (i == 0 and{co0 }or{(i == 1 and{co1 }or{co2 +})[1]})[1] local si = (i == 0 and{si0 }or{(i == 1 and{si1 }or{si2 +})[1]})[1] local ovl = rf(OVL, ob + i * 4) + local sum = (co * rf(TWID3, (3 + i) * 4) + si * rf(TWID3, i * 4)) + wf(OVL, ob + i * 4, co * rf(TWID3, i * 4) - si * rf(TWID3, (3 + i) * 4)) + wf(dst, db + i * 4, ovl * rf(TWID3, (2 - i) * 4) - sum * rf(TWID3, (5 - i) * 4)) + wf(dst, db + (5 - i) * 4, ovl * rf(TWID3, (5 - i) * 4) + sum * rf(TWID3, (2 - i) * 4)) + end +end + +local function imdctShort(g, ov, nbands) + for _ = 1, nbands do + bcopy(TMP, 0, GRBUF, g * 4, 72) + bcopy(GRBUF, g * 4, OVL, ov * 4, 24) + imdct12(0, GRBUF, g + 6, ov + 6) + imdct12(1, GRBUF, g + 12, ov + 6) + imdct12(2, OVL, ov, ov + 6) + g =g+ 18 + ov =ov+ 9 + end +end + +local function changeSign(g) + local o = (g + 18) * 4 + for _ = 0, 15 do + for i = 1, 17, 2 do + wf(GRBUF, o + i * 4, -rf(GRBUF, o + i * 4)) + end + o =o+ 144 + end +end + +local function imdctGr(g, ov, bt, nLongBands) + if nLongBands ~= 0 then + imdct36(g, ov, MDCT_WIN0, nLongBands) + g =g+ 18 * nLongBands + ov =ov+ 9 * nLongBands + end + if bt == 2 then + imdctShort(g, ov, 32 - nLongBands) + else + imdct36(g, ov, (bt == 3 and{MDCT_WIN1 }or{MDCT_WIN0})[1], 32 - nLongBands) + end +end + +-- L3_decode: one granule, side info at gr = grBase + ch +local function l3Decode(h1, h2, h3, grBase, nch) + for ch = 0, nch - 1 do + local gr = grBase + ch + local limit = bsPos + GR_P23[gr] + decodeScalefactors(h1, h3, ch * 39, gr, ch) + huffman(ch * 576, gr, limit) + end + if band(h3, 0x10) ~= 0 then + intensityStereo(h1, h3, grBase) + elseif band(h3, 0xE0) == 0x60 then + midside(0, 576) + end + local mySr = band(rshift(h2, 2), 3) + (band(rshift(h1, 3), 1) + band(rshift(h1, 4), 1)) * 3 + for ch = 0, nch - 1 do + local gr = grBase + ch + local aaBands = 31 + local nLongBands = (GR_MIXED[gr] ~= 0 and{(mySr == 2 and 4 or 2) }or{0 +})[1] local g = ch * 576 + if GR_NSHORT[gr] ~= 0 then + aaBands = nLongBands - 1 + reorder(g + nLongBands * 18, GR_SFB[gr] + GR_NLONG[gr]) + end + antialias(g, aaBands) + imdctGr(g, ch * 288, GR_BT[gr], nLongBands) + changeSign(g) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- polyphase synthesis (mp3d_DCT_II, mp3d_synth, mp3d_synth_granule) + + +-- mp3d_synth_pair: z = SYN float index, dst = PCM float index +local function synthPair(dst, nch, z) + local zb = z * 4 + local a = (rf(SYN, zb + 14 * 256) - rf(SYN, zb)) * 29 + a =a+ (rf(SYN, zb + 1 * 256) + rf(SYN, zb + 13 * 256)) * 213 + a =a+ (rf(SYN, zb + 12 * 256) - rf(SYN, zb + 2 * 256)) * 459 + a =a+ (rf(SYN, zb + 3 * 256) + rf(SYN, zb + 11 * 256)) * 2037 + a =a+ (rf(SYN, zb + 10 * 256) - rf(SYN, zb + 4 * 256)) * 5153 + a =a+ (rf(SYN, zb + 5 * 256) + rf(SYN, zb + 9 * 256)) * 6574 + a =a+ (rf(SYN, zb + 8 * 256) - rf(SYN, zb + 6 * 256)) * 37489 + a =a+ rf(SYN, zb + 7 * 256) * 75038 + wf(PCM, dst * 4, a * SCALE) + zb =zb+ 8 + a = rf(SYN, zb + 14 * 256) * 104 + a =a+ rf(SYN, zb + 12 * 256) * 1567 + a =a+ rf(SYN, zb + 10 * 256) * 9727 + a =a+ rf(SYN, zb + 8 * 256) * 64019 + a =a+ rf(SYN, zb + 6 * 256) * -9975 + a =a+ rf(SYN, zb + 4 * 256) * -45 + a =a+ rf(SYN, zb + 2 * 256) * 146 + a =a+ rf(SYN, zb) * -5 + wf(PCM, (dst + 16 * nch) * 4, a * SCALE) +end + +-- mp3d_synth: two time slots of 32 subbands -> 64 samples per channel. xl = GRBUF float index of the left +-- channel's slot, dstl = PCM float index, lins = SYN float index +local function synth(xl, dstl, nch, lins) + local xr = xl + 576 * (nch - 1) + local dstr = dstl + (nch - 1) + local zlin = lins + 15 * 64 + local zb = zlin * 4 + local xlb, xrb = xl * 4, xr * 4 + wf(SYN, zb + 60 * 4, rf(GRBUF, xlb + 288 * 4)) + wf(SYN, zb + 61 * 4, rf(GRBUF, xrb + 288 * 4)) + wf(SYN, zb + 62 * 4, rf(GRBUF, xlb)) + wf(SYN, zb + 63 * 4, rf(GRBUF, xrb)) + wf(SYN, zb + 124 * 4, rf(GRBUF, xlb + 289 * 4)) + wf(SYN, zb + 125 * 4, rf(GRBUF, xrb + 289 * 4)) + wf(SYN, zb + 126 * 4, rf(GRBUF, xlb + 4)) + wf(SYN, zb + 127 * 4, rf(GRBUF, xrb + 4)) + if nch == 2 then + synthPair(dstr, nch, lins + 4 * 15 + 1) + synthPair(dstr + 32 * nch, nch, lins + 4 * 15 + 64 + 1) + end + synthPair(dstl, nch, lins + 4 * 15) + synthPair(dstl + 32 * nch, nch, lins + 4 * 15 + 64) + + local w = 1 + for i = 14, 0, -1 do + local zi = zb + 16 * i + local s1 = (18 * (31 - i)) * 4 + local s2 = (18 * (1 + i)) * 4 + wf(SYN, zi, rf(GRBUF, xlb + s1)) + wf(SYN, zi + 4, rf(GRBUF, xrb + s1)) + wf(SYN, zi + 8, rf(GRBUF, xlb + s1 + 4)) + wf(SYN, zi + 12, rf(GRBUF, xrb + s1 + 4)) + wf(SYN, zi + 256, rf(GRBUF, xlb + s2 + 4)) + wf(SYN, zi + 260, rf(GRBUF, xrb + s2 + 4)) + wf(SYN, zi - 248, rf(GRBUF, xlb + s2)) + wf(SYN, zi - 244, rf(GRBUF, xrb + s2)) + -- the 8 window steps, even k (a += z w0 - y w1) and odd k (a += y w1 - z w0) in pairs; mono needs lanes 0, 2 + local a0, a1, a2, a3, b0, b1, b2, b3 = 0, 0, 0, 0, 0, 0, 0, 0 + local vz, vy = zi, zi - 15 * 256 + if nch == 2 then + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w =w+ 4 + local z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12) + local y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12) + b0 =b0+ (z0 * w1 + y0 * w0 +) b1 =b1+ (z1 * w1 + y1 * w0 +) b2 =b2+ (z2 * w1 + y2 * w0 +) b3 =b3+ (z3 * w1 + y3 * w0 +) a0 =a0+ (z0 * w0 - y0 * w1 +) a1 =a1+ (z1 * w0 - y1 * w1 +) a2 =a2+ (z2 * w0 - y2 * w1 +) a3 =a3+ (z3 * w0 - y3 * w1 +) vz =vz- 256 + vy =vy+ 256 + 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 =b0+ (z0 * w3 + y0 * w2 +) b1 =b1+ (z1 * w3 + y1 * w2 +) b2 =b2+ (z2 * w3 + y2 * w2 +) b3 =b3+ (z3 * w3 + y3 * w2 +) a0 =a0+ (y0 * w3 - z0 * w2 +) a1 =a1+ (y1 * w3 - z1 * w2 +) a2 =a2+ (y2 * w3 - z2 * w2 +) a3 =a3+ (y3 * w3 - z3 * w2 +) vz =vz- 256 + vy =vy+ 256 + end + wf(PCM, (dstr + (15 - i) * 2) * 4, a1 * SCALE) + wf(PCM, (dstr + (17 + i) * 2) * 4, b1 * SCALE) + wf(PCM, (dstr + (47 - i) * 2) * 4, a3 * SCALE) + wf(PCM, (dstr + (49 + i) * 2) * 4, b3 * SCALE) + else + for _ = 0, 3 do + local w0, w1, w2, w3 = WINT[w], WINT[w + 1], WINT[w + 2], WINT[w + 3] + w =w+ 4 + local z0, z2 = rf(SYN, vz), rf(SYN, vz + 8) + local y0, y2 = rf(SYN, vy), rf(SYN, vy + 8) + b0 =b0+ (z0 * w1 + y0 * w0 +) b2 =b2+ (z2 * w1 + y2 * w0 +) a0 =a0+ (z0 * w0 - y0 * w1 +) a2 =a2+ (z2 * w0 - y2 * w1 +) vz =vz- 256 + vy =vy+ 256 + z0 = rf(SYN, vz) + z2 = rf(SYN, vz + 8) + y0 = rf(SYN, vy) + y2 = rf(SYN, vy + 8) + b0 =b0+ (z0 * w3 + y0 * w2 +) b2 =b2+ (z2 * w3 + y2 * w2 +) a0 =a0+ (y0 * w3 - z0 * w2 +) a2 =a2+ (y2 * w3 - z2 * w2 +) vz =vz- 256 + vy =vy+ 256 + end + end + wf(PCM, (dstl + (15 - i) * nch) * 4, a0 * SCALE) + wf(PCM, (dstl + (17 + i) * nch) * 4, b0 * SCALE) + wf(PCM, (dstl + (47 - i) * nch) * 4, a2 * SCALE) + wf(PCM, (dstl + (49 + i) * nch) * 4, b2 * SCALE) + end +end + +local function synthGranule(nbands, nch, pcm) + for ch = 0, nch - 1 do + dctII(576 * ch, nbands) + end + bcopy(SYN, 0, QMF, 0, 15 * 64 * 4) + for i = 0, nbands - 1, 2 do + synth(i, pcm + 32 * nch * i, nch, i * 64) + end + if nch == 1 then + local src = nbands * 64 * 4 + for i = 0, 15 * 64 * 4 - 8, 8 do + wf(QMF, i, rf(SYN, src + i)) + end + else + bcopy(QMF, 0, SYN, nbands * 64 * 4, 15 * 64 * 4) + end +end + +---------------------------------------------------------------------------------------------------------------- +-- layers I and II + +local ALLOC_L1 = { 76, 4, 32 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } + +local totalBands, stereoBands = 0, 0 + +local function l12ReadScaleInfo(h1, h2, h3, kbpsHdr) + local mode = rshift(h3, 6) + local sb = mode == 3 and 0 or(mode == 1 and{(band(rshift(h3, 4), 3) * 4 + 4 )}or{32 +})[1] local layer1 = band(h1, 6) == 6 + local alloc, nbands + if layer1 then + alloc, nbands = ALLOC_L1, 32 + elseif band(h1, 8) == 0 then + alloc, nbands = ALLOC_L2M2, 30 + else + local srIdx = band(rshift(h2, 2), 3) + local kbps = (mode ~= 3 and{(rshift(kbpsHdr, 1) )}or{kbpsHdr +})[1] if kbps == 0 then + kbps = 192 + end + alloc, nbands = ALLOC_L2M1, 27 + if kbps < 56 then + alloc, nbands = ALLOC_L2M1_LOW, srIdx == 2 and 12 or 8 + elseif kbps >= 96 and srIdx ~= 1 then + nbands = 30 + end + end + totalBands = nbands + stereoBands = min(sb, nbands) + local k, baBits, codeOff, ai = 0, 0, 0, 1 + for i = 0, nbands - 1 do + if i == k then + codeOff, baBits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai =ai+ 3 + end + local ba = BITALLOC_CODE[codeOff + getBits(baBits)] + wu8(BA, 2 * i, ba) + if i < stereoBands then + ba = BITALLOC_CODE[codeOff + getBits(baBits)] + end + wu8(BA, 2 * i + 1, (stereoBands ~= 0 and{ba }or{0})[1]) + end + for i = 0, 2 * nbands - 1 do + wu8(SCFCOD, i, (ru8(BA, i) ~= 0 and{(layer1 and 2 or getBits(2)) }or{6})[1]) + end + -- L12_read_scalefactors + local so = 0 + for i = 0, 2 * nbands - 1 do + local s = 0 + local ba = ru8(BA, i) + local mask = (ba ~= 0 and{(4 + band(rshift(19, ru8(SCFCOD, i)), 3) )}or{0 +})[1] local m = 4 + while m ~= 0 do + if band(mask, m) ~= 0 then + local b = getBits(6) + s = f32(DEQ_L12[ba * 3 - 6 + b % 3] * rshift(lshift(1, 21), math.floor(b / 3))) + end + wf(L12SCF, so, s) + so =so+ 4 + m = rshift(m, 1) + end + end + for i = stereoBands, nbands - 1 do + wu8(BA, 2 * i + 1, 0) + end +end + +local function l12Dequantize(g, groupSize) +local choff = 576 + for j = 0, 3 do + local dst = g + groupSize * j + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + local half = lshift(1, ba - 1) - 1 + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, getBits(ba) - half) + end + else + local mod = lshift(2, ba - 17) + 1 + local code = getBits(mod + 2 - rshift(mod, 3)) + for k = 0, groupSize - 1 do + wf(GRBUF, (dst + k) * 4, code % mod - math.floor(mod / 2)) + code =math.floor(code/ mod +) end + end + end + dst =dst+ choff + choff = 18 - choff + end + end + return groupSize * 4 +end + +local function l12ApplyScf(scfOff) + local sb, tb = stereoBands, totalBands + bcopy(GRBUF, (576 + sb * 18) * 4, GRBUF, sb * 18 * 4, (tb - sb) * 18 * 4) + for i = 0, tb - 1 do + local d = i * 72 + local s0 = rf(L12SCF, (scfOff + i * 6) * 4) + local s1 = rf(L12SCF, (scfOff + i * 6 + 3) * 4) + for k = 0, 11 do + local p = d + k * 4 + wf(GRBUF, p, rf(GRBUF, p) * s0) + wf(GRBUF, p + 2304, rf(GRBUF, p + 2304) * s1) + end + end +end + +---------------------------------------------------------------------------------------------------------------- +-- API + +local Core = {} + +Core.MAX_FRAME = MAX_FRAME + + + + + + + + + +function Core.newState() +return { + overlap = bcreate(2 * 9 * 32 * 4), + qmf = bcreate(15 * 2 * 32 * 4), + reserv = bcreate(MAX_BITRESERVOIR_BYTES + 8), + reservLen = 0, + needReset = false, + } +end + +-- memset(dec, 0): what minimp3 does whenever it has to re-sync +function Core.reset(st) + bfill(st.overlap, 0, 0) + bfill(st.qmf, 0, 0) + st.reservLen = 0 + st.needReset = false +end + +Core.lastChannels = 0 + +-- pcm holds n mono samples: spread them to n interleaved stereo pairs (in place) +function Core.upmix(pcm, n) + if buffer.len(pcm) < n * 8 then + return + end + for i = n - 1, 0, -1 do + local v = rf(pcm, i * 4) + wf(pcm, i * 8, v) + wf(pcm, i * 8 + 4, v) + end +end + +-- Decodes the frame b[off, off + size) (a whole frame found by the index, header included) into pcm +-- (interleaved f32, frame samples x channels) and returns the samples per channel (0 = no output: an +-- unfilled bit reservoir, or corrupt data). Core.lastChannels = the frame's channel count. +function Core.decodeFrame(st, b, off, size, pcm) +if size < 4 or size > MAX_FRAME or off < 0 or off + size > buffer.len(b) then + st.needReset = true + return 0 + end + if st.needReset then + Core.reset(st) + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + OVL, QMF, PCM = st.overlap, st.qmf, pcm + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + local nch = band(h3, 0xC0) == 0xC0 and 1 or 2 + Core.lastChannels = nch + local layer = 4 - band(rshift(h1, 1), 3) + local spf = band(h1, 6) == 6 and 384 or(band(h1, 14) == 2 and 576 or 1152 +) if buffer.len(pcm) < spf * nch * 4 then + return 0 + end + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) -- CRC + end + if layer == 3 then + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + st.needReset = true + return 0 + end + -- L3_restore_reservoir + local frameBytes = math.floor((bsLimit - bsPos) / 8 +) local reserv = st.reservLen + local have = min(reserv, mdb) + if have > 0 then + bcopy(MAIN, 0, st.reserv, max(0, reserv - mdb), have) + end + bcopy(MAIN, have, FRAME, math.floor(bsPos / 8), frameBytes) + bfill(MAIN, have + frameBytes, 0, 8) + local success = reserv >= mdb + bsBuf, bsPos, bsLimit = MAIN, 0, (have + frameBytes) * 8 + if success then + local ngr = band(h1, 8) ~= 0 and 2 or 1 + local p = 0 + for igr = 0, ngr - 1 do + bfill(GRBUF, 0, 0) + l3Decode(h1, h2, h3, igr * nch, nch) + synthGranule(18, nch, p) + p =p+ 576 * nch + end + end + -- L3_save_reservoir + local pos = math.floor((bsPos + 7) / 8 +) local remains = math.floor(bsLimit / 8 )- pos + if remains > MAX_BITRESERVOIR_BYTES then + pos =pos+ (remains - MAX_BITRESERVOIR_BYTES +) remains = MAX_BITRESERVOIR_BYTES + end + if remains > 0 and pos >= 0 then + bcopy(st.reserv, 0, MAIN, pos, remains) + end + st.reservLen = max(0, remains) + bsBuf = FRAME + return (success and{spf }or{0 +})[1] end + -- layers I / II + local kbps = 2 * HALFRATE[(band(h1, 8) ~= 0 and 45 or 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + bfill(GRBUF, 0, 0) + local i = 0 + local p = 0 + local group = bor(layer, 1) + for igr = 0, 2 do + i =i+ l12Dequantize(i, group) + if i == 12 then + i = 0 + l12ApplyScf(igr) + synthGranule(12, nch, p) + bfill(GRBUF, 0, 0) + p =p+ 384 * nch + end + if bsPos > bsLimit then + st.needReset = true + return 0 + end + end + return spf +end + +-- Layer III side info of the frame b[off, off + size): main_data_begin (-1 = corrupt), the sum of its +-- part2_3 lengths in bits, and the main data bytes in the frame. Used by the stream index. +function Core.probeL3(b, off, size) +local n = min(size, 64) + if size < 4 or off + n > buffer.len(b) then + return -1, 0, 0 + end + bcopy(FRAME, 0, b, off, n) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local mdb = readSideInfo(h1, h2, h3) + if mdb < 0 or bsPos > bsLimit then + return -1, 0, 0 + end + local ngr = (band(h3, 0xC0) == 0xC0 and 1 or 2) * (band(h1, 8) ~= 0 and 2 or 1) + local sum = 0 + for gr = 0, ngr - 1 do + sum =sum+ GR_P23[gr] + end + return mdb, sum, math.floor((bsLimit - bsPos) / 8 +)end + +-- Layer I / II: false when the frame b[off, off + size) needs more bits than it has (minimp3 then drops it). +function Core.probeL12(b, off, size) +if size < 4 or size > MAX_FRAME or off + size > buffer.len(b) then + return false + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + local layer = 4 - band(rshift(h1, 1), 3) + local kbps = 2 * HALFRATE[(band(h1, 8) ~= 0 and 45 or 0) + (band(rshift(h1, 1), 3) - 1) * 15 + rshift(h2, 4)] + l12ReadScaleInfo(h1, h2, h3, kbps) + -- the samples: 3 calls of l12Dequantize, each 4 groups of (layer | 1) samples per allocated band + local group = bor(layer, 1) + local bits = 0 + for i = 0, 2 * totalBands - 1 do + local ba = ru8(BA, i) + if ba ~= 0 then + if ba < 17 then + bits =bits+ ba * group + else + local mod = lshift(2, ba - 17) + 1 + bits =bits+ (mod + 2 - rshift(mod, 3) +) end + end + end + return bsPos + 12 * bits <= bsLimit +end + +-- mp3dec_check_vbrtag on the frame b[off, off + size): 0 = no tag, -1 = a Xing / Info tag without a frame +-- count, 1 = tag; then frames, encoder delay + 529, padding - 529 (both 0 without a LAME extension) +function Core.vbrTag(b, off, size) +if size < 12 or size > MAX_FRAME or off + size > buffer.len(b) then + return 0, 0, 0, 0 + end + bcopy(FRAME, 0, b, off, size) + bfill(FRAME, size, 0, 8) + local h1, h2, h3 = ru8(FRAME, 1), ru8(FRAME, 2), ru8(FRAME, 3) + bsBuf, bsPos, bsLimit = FRAME, 32, size * 8 + if band(h1, 1) == 0 then + getBits(16) + end + if readSideInfo(h1, h2, h3) < 0 then + return 0, 0, 0, 0 + end + local t = math.floor(bsPos / 8 +) if t > size or size - t < 8 then + return 0, 0, 0, 0 + end + local tag = buffer.readstring(FRAME, t, 4) + if tag ~= "Xing" and tag ~= "Info" then + return 0, 0, 0, 0 + end + local flags = ru8(FRAME, t + 7) + if band(flags, 1) == 0 then + return -1, 0, 0, 0 + end + t =t+ 8 + if size - t < 4 then + return 0, 0, 0, 0 + end + local frames = bswap(ru32(FRAME, t)) + t =t+ 4 + if band(flags, 2) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t =t+ 4 + end + if band(flags, 4) ~= 0 then + if size - t < 100 then + return 0, 0, 0, 0 + end + t =t+ 100 + end + if band(flags, 8) ~= 0 then + if size - t < 4 then + return 0, 0, 0, 0 + end + t =t+ 4 + end + if size - t < 1 then + return 0, 0, 0, 0 + end + local delay, padding = 0, 0 + if ru8(FRAME, t) ~= 0 then + if size - t <= 35 then + return 0, 0, 0, 0 + end + t =t+ 21 + local t0, t1, t2 = ru8(FRAME, t), ru8(FRAME, t + 1), ru8(FRAME, t + 2) + delay = bor(lshift(t0, 4), rshift(t1, 4)) + 529 + padding = bor(lshift(band(t1, 15), 8), t2) - 529 + end + return 1, frames, delay, padding +end + +return Core +end +__FILES["codecs/audio/Mpa/EncTables"] = function() +--!strict +-- 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 +-- byte: right offset), otherwise a leaf (x << 4 | y; count1 tables: v w x y bits). +local E = {} +E.D = { + 0.000000000, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000015259, -0.000030518, + -0.000030518, -0.000030518, -0.000030518, -0.000045776, -0.000045776, -0.000061035, -0.000061035, -0.000076294, + -0.000076294, -0.000091553, -0.000106812, -0.000106812, -0.000122070, -0.000137329, -0.000152588, -0.000167847, + -0.000198364, -0.000213623, -0.000244141, -0.000259399, -0.000289917, -0.000320435, -0.000366211, -0.000396729, + -0.000442505, -0.000473022, -0.000534058, -0.000579834, -0.000625610, -0.000686646, -0.000747681, -0.000808716, + -0.000885010, -0.000961304, -0.001037598, -0.001113892, -0.001205444, -0.001296997, -0.001388550, -0.001480103, + -0.001586914, -0.001693726, -0.001785278, -0.001907349, -0.002014160, -0.002120972, -0.002243042, -0.002349854, + -0.002456665, -0.002578735, -0.002685547, -0.002792358, -0.002899170, -0.002990723, -0.003082275, -0.003173828, + 0.003250122, 0.003326416, 0.003387451, 0.003433228, 0.003463745, 0.003479004, 0.003479004, 0.003463745, + 0.003417969, 0.003372192, 0.003280640, 0.003173828, 0.003051758, 0.002883911, 0.002700806, 0.002487183, + 0.002227783, 0.001937866, 0.001617432, 0.001266479, 0.000869751, 0.000442505, -0.000030518, -0.000549316, + -0.001098633, -0.001693726, -0.002334595, -0.003005981, -0.003723145, -0.004486084, -0.005294800, -0.006118774, + -0.007003784, -0.007919312, -0.008865356, -0.009841919, -0.010848999, -0.011886597, -0.012939453, -0.014022827, + -0.015121460, -0.016235352, -0.017349243, -0.018463135, -0.019577026, -0.020690918, -0.021789551, -0.022857666, + -0.023910522, -0.024932861, -0.025909424, -0.026840210, -0.027725220, -0.028533936, -0.029281616, -0.029937744, + -0.030532837, -0.031005859, -0.031387329, -0.031661987, -0.031814575, -0.031845093, -0.031738281, -0.031478882, + 0.031082153, 0.030517578, 0.029785156, 0.028884888, 0.027801514, 0.026535034, 0.025085449, 0.023422241, + 0.021575928, 0.019531250, 0.017257690, 0.014801025, 0.012115479, 0.009231567, 0.006134033, 0.002822876, + -0.000686646, -0.004394531, -0.008316040, -0.012420654, -0.016708374, -0.021179199, -0.025817871, -0.030609131, + -0.035552979, -0.040634155, -0.045837402, -0.051132202, -0.056533813, -0.061996460, -0.067520142, -0.073059082, + -0.078628540, -0.084182739, -0.089706421, -0.095169067, -0.100540161, -0.105819702, -0.110946655, -0.115921021, + -0.120697021, -0.125259399, -0.129562378, -0.133590698, -0.137298584, -0.140670776, -0.143676758, -0.146255493, + -0.148422241, -0.150115967, -0.151306152, -0.151962280, -0.152069092, -0.151596069, -0.150497437, -0.148773193, + -0.146362305, -0.143264771, -0.139450073, -0.134887695, -0.129577637, -0.123474121, -0.116577148, -0.108856201, + 0.100311279, 0.090927124, 0.080688477, 0.069595337, 0.057617188, 0.044784546, 0.031082153, 0.016510010, + 0.001068115, -0.015228271, -0.032379150, -0.050354004, -0.069168091, -0.088775635, -0.109161377, -0.130310059, + -0.152206421, -0.174789429, -0.198059082, -0.221984863, -0.246505737, -0.271591187, -0.297210693, -0.323318481, + -0.349868774, -0.376800537, -0.404083252, -0.431655884, -0.459472656, -0.487472534, -0.515609741, -0.543823242, + -0.572036743, -0.600219727, -0.628295898, -0.656219482, -0.683914185, -0.711318970, -0.738372803, -0.765029907, + -0.791213989, -0.816864014, -0.841949463, -0.866363525, -0.890090942, -0.913055420, -0.935195923, -0.956481934, + -0.976852417, -0.996246338, -1.014617920, -1.031936646, -1.048156738, -1.063217163, -1.077117920, -1.089782715, + -1.101211548, -1.111373901, -1.120223999, -1.127746582, -1.133926392, -1.138763428, -1.142211914, -1.144287109, + 1.144989014, 1.144287109, 1.142211914, 1.138763428, 1.133926392, 1.127746582, 1.120223999, 1.111373901, + 1.101211548, 1.089782715, 1.077117920, 1.063217163, 1.048156738, 1.031936646, 1.014617920, 0.996246338, + 0.976852417, 0.956481934, 0.935195923, 0.913055420, 0.890090942, 0.866363525, 0.841949463, 0.816864014, + 0.791213989, 0.765029907, 0.738372803, 0.711318970, 0.683914185, 0.656219482, 0.628295898, 0.600219727, + 0.572036743, 0.543823242, 0.515609741, 0.487472534, 0.459472656, 0.431655884, 0.404083252, 0.376800537, + 0.349868774, 0.323318481, 0.297210693, 0.271591187, 0.246505737, 0.221984863, 0.198059082, 0.174789429, + 0.152206421, 0.130310059, 0.109161377, 0.088775635, 0.069168091, 0.050354004, 0.032379150, 0.015228271, + -0.001068115, -0.016510010, -0.031082153, -0.044784546, -0.057617188, -0.069595337, -0.080688477, -0.090927124, + 0.100311279, 0.108856201, 0.116577148, 0.123474121, 0.129577637, 0.134887695, 0.139450073, 0.143264771, + 0.146362305, 0.148773193, 0.150497437, 0.151596069, 0.152069092, 0.151962280, 0.151306152, 0.150115967, + 0.148422241, 0.146255493, 0.143676758, 0.140670776, 0.137298584, 0.133590698, 0.129562378, 0.125259399, + 0.120697021, 0.115921021, 0.110946655, 0.105819702, 0.100540161, 0.095169067, 0.089706421, 0.084182739, + 0.078628540, 0.073059082, 0.067520142, 0.061996460, 0.056533813, 0.051132202, 0.045837402, 0.040634155, + 0.035552979, 0.030609131, 0.025817871, 0.021179199, 0.016708374, 0.012420654, 0.008316040, 0.004394531, + 0.000686646, -0.002822876, -0.006134033, -0.009231567, -0.012115479, -0.014801025, -0.017257690, -0.019531250, + -0.021575928, -0.023422241, -0.025085449, -0.026535034, -0.027801514, -0.028884888, -0.029785156, -0.030517578, + 0.031082153, 0.031478882, 0.031738281, 0.031845093, 0.031814575, 0.031661987, 0.031387329, 0.031005859, + 0.030532837, 0.029937744, 0.029281616, 0.028533936, 0.027725220, 0.026840210, 0.025909424, 0.024932861, + 0.023910522, 0.022857666, 0.021789551, 0.020690918, 0.019577026, 0.018463135, 0.017349243, 0.016235352, + 0.015121460, 0.014022827, 0.012939453, 0.011886597, 0.010848999, 0.009841919, 0.008865356, 0.007919312, + 0.007003784, 0.006118774, 0.005294800, 0.004486084, 0.003723145, 0.003005981, 0.002334595, 0.001693726, + 0.001098633, 0.000549316, 0.000030518, -0.000442505, -0.000869751, -0.001266479, -0.001617432, -0.001937866, + -0.002227783, -0.002487183, -0.002700806, -0.002883911, -0.003051758, -0.003173828, -0.003280640, -0.003372192, + -0.003417969, -0.003463745, -0.003479004, -0.003479004, -0.003463745, -0.003433228, -0.003387451, -0.003326416, + 0.003250122, 0.003173828, 0.003082275, 0.002990723, 0.002899170, 0.002792358, 0.002685547, 0.002578735, + 0.002456665, 0.002349854, 0.002243042, 0.002120972, 0.002014160, 0.001907349, 0.001785278, 0.001693726, + 0.001586914, 0.001480103, 0.001388550, 0.001296997, 0.001205444, 0.001113892, 0.001037598, 0.000961304, + 0.000885010, 0.000808716, 0.000747681, 0.000686646, 0.000625610, 0.000579834, 0.000534058, 0.000473022, + 0.000442505, 0.000396729, 0.000366211, 0.000320435, 0.000289917, 0.000259399, 0.000244141, 0.000213623, + 0.000198364, 0.000167847, 0.000152588, 0.000137329, 0.000122070, 0.000106812, 0.000106812, 0.000091553, + 0.000076294, 0.000076294, 0.000061035, 0.000061035, 0.000045776, 0.000045776, 0.000030518, 0.000030518, + 0.000030518, 0.000030518, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, 0.000015259, +} +E.LINBITS = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, 0, 0 } +-- trees by table number (tables 16..23 share 16's tree, 24..31 share 24's) +E.TREES = { + [1] = { + 0x0201, 0x0000, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, + }, + [2] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [3] = { + 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0011, 0x0201, 0x0010, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, 0x0002, + 0x0022, + }, + [5] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0013, 0x0201, 0x0031, 0x0201, 0x0032, 0x0201, 0x0023, 0x0033, + }, + [6] = { + 0x0601, 0x0401, 0x0201, 0x0000, 0x0010, 0x0011, 0x0601, 0x0201, 0x0001, 0x0201, 0x0020, 0x0021, 0x0601, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0030, 0x0032, 0x0201, 0x0023, 0x0201, 0x0003, 0x0033, + }, + [7] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, 0x1201, 0x0601, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0030, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, 0x0004, + 0x0a01, 0x0401, 0x0201, 0x0040, 0x0041, 0x0201, 0x0014, 0x0201, 0x0042, 0x0024, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0033, 0x0043, + 0x0050, 0x0401, 0x0201, 0x0034, 0x0005, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, 0x0035, + 0x0401, 0x0201, 0x0053, 0x0054, 0x0201, 0x0045, 0x0055, + }, + [8] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0021, 0x0012, 0x0e01, 0x0401, 0x0201, 0x0020, + 0x0002, 0x0201, 0x0022, 0x0401, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0201, 0x0014, 0x0042, 0x0c01, 0x0601, 0x0201, 0x0024, 0x0201, 0x0033, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0051, 0x0601, 0x0201, 0x0015, 0x0201, 0x0005, 0x0052, 0x0601, 0x0201, 0x0025, 0x0201, 0x0044, 0x0035, + 0x0201, 0x0053, 0x0201, 0x0045, 0x0201, 0x0054, 0x0055, + }, + [9] = { + 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0a01, 0x0401, 0x0201, 0x0020, 0x0021, 0x0201, 0x0012, 0x0201, + 0x0002, 0x0022, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0030, 0x0003, 0x0031, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0c01, 0x0401, + 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0040, 0x0033, 0x0201, 0x0042, 0x0024, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0050, + 0x0043, 0x0201, 0x0034, 0x0051, 0x0801, 0x0401, 0x0201, 0x0015, 0x0052, 0x0201, 0x0025, 0x0044, 0x0601, 0x0401, 0x0201, 0x0005, + 0x0054, 0x0053, 0x0201, 0x0035, 0x0201, 0x0045, 0x0055, + }, + [10] = { + 0x0201, 0x0000, 0x0401, 0x0201, 0x0010, 0x0001, 0x0a01, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x1c01, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0031, 0x0013, 0x0801, 0x0401, 0x0201, 0x0003, 0x0032, 0x0201, 0x0023, + 0x0040, 0x0401, 0x0201, 0x0041, 0x0014, 0x0401, 0x0201, 0x0004, 0x0033, 0x0201, 0x0042, 0x0024, 0x1c01, 0x0a01, 0x0601, 0x0401, + 0x0201, 0x0050, 0x0005, 0x0060, 0x0201, 0x0061, 0x0016, 0x0c01, 0x0601, 0x0401, 0x0201, 0x0043, 0x0034, 0x0051, 0x0201, 0x0015, + 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0026, 0x0036, 0x0071, 0x1401, 0x0801, 0x0201, 0x0017, 0x0401, 0x0201, 0x0044, 0x0053, + 0x0006, 0x0601, 0x0401, 0x0201, 0x0035, 0x0045, 0x0062, 0x0201, 0x0070, 0x0201, 0x0007, 0x0064, 0x0e01, 0x0401, 0x0201, 0x0072, + 0x0027, 0x0601, 0x0201, 0x0063, 0x0201, 0x0054, 0x0055, 0x0201, 0x0046, 0x0073, 0x0801, 0x0401, 0x0201, 0x0037, 0x0065, 0x0201, + 0x0056, 0x0074, 0x0601, 0x0201, 0x0047, 0x0201, 0x0066, 0x0075, 0x0401, 0x0201, 0x0057, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [11] = { + 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0801, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0012, 0x1801, 0x0801, + 0x0201, 0x0021, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0201, 0x0041, 0x0014, 0x1e01, 0x1001, 0x0a01, 0x0401, 0x0201, 0x0042, 0x0024, 0x0401, 0x0201, 0x0033, + 0x0043, 0x0050, 0x0401, 0x0201, 0x0034, 0x0051, 0x0061, 0x0601, 0x0201, 0x0016, 0x0201, 0x0006, 0x0026, 0x0201, 0x0062, 0x0201, + 0x0015, 0x0201, 0x0005, 0x0052, 0x1001, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0025, 0x0044, 0x0060, 0x0201, 0x0063, 0x0036, 0x0401, + 0x0201, 0x0070, 0x0017, 0x0071, 0x1001, 0x0601, 0x0401, 0x0201, 0x0007, 0x0064, 0x0072, 0x0201, 0x0027, 0x0401, 0x0201, 0x0053, + 0x0035, 0x0201, 0x0054, 0x0045, 0x0a01, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, 0x0201, 0x0065, 0x0056, 0x0a01, 0x0601, + 0x0401, 0x0201, 0x0055, 0x0057, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [12] = { + 0x0c01, 0x0401, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0201, 0x0000, 0x0201, 0x0020, 0x0002, 0x1001, 0x0401, 0x0201, 0x0021, + 0x0012, 0x0401, 0x0201, 0x0022, 0x0031, 0x0201, 0x0013, 0x0201, 0x0030, 0x0201, 0x0003, 0x0040, 0x1a01, 0x0801, 0x0401, 0x0201, + 0x0032, 0x0023, 0x0201, 0x0041, 0x0033, 0x0a01, 0x0401, 0x0201, 0x0014, 0x0042, 0x0201, 0x0024, 0x0201, 0x0004, 0x0050, 0x0401, + 0x0201, 0x0043, 0x0034, 0x0201, 0x0051, 0x0015, 0x1c01, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0052, 0x0025, 0x0201, 0x0053, 0x0035, + 0x0401, 0x0201, 0x0060, 0x0016, 0x0061, 0x0401, 0x0201, 0x0062, 0x0026, 0x0601, 0x0401, 0x0201, 0x0005, 0x0006, 0x0044, 0x0201, + 0x0054, 0x0045, 0x1201, 0x0a01, 0x0401, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0070, 0x0007, 0x0071, 0x0401, 0x0201, 0x0017, + 0x0064, 0x0201, 0x0046, 0x0072, 0x0a01, 0x0601, 0x0201, 0x0027, 0x0201, 0x0055, 0x0073, 0x0201, 0x0037, 0x0056, 0x0801, 0x0401, + 0x0201, 0x0065, 0x0074, 0x0201, 0x0047, 0x0066, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0076, 0x0201, 0x0067, 0x0077, + }, + [13] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x1c01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0801, 0x0401, 0x0201, 0x0022, 0x0030, 0x0201, 0x0003, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0032, 0x0023, 0x0401, + 0x0201, 0x0040, 0x0004, 0x0041, 0x4601, 0x1c01, 0x0e01, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, + 0x0050, 0x0201, 0x0043, 0x0034, 0x0401, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0005, 0x0052, 0x0201, 0x0025, 0x0201, 0x0044, + 0x0053, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0060, 0x0006, 0x0201, 0x0061, 0x0016, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0035, 0x0062, 0x0201, 0x0026, 0x0054, 0x0401, 0x0201, 0x0045, 0x0063, 0x0201, 0x0036, 0x0070, 0x0601, + 0x0401, 0x0201, 0x0007, 0x0055, 0x0071, 0x0201, 0x0017, 0x0201, 0x0027, 0x0037, 0x4801, 0x1801, 0x0c01, 0x0401, 0x0201, 0x0018, + 0x0082, 0x0201, 0x0028, 0x0401, 0x0201, 0x0064, 0x0046, 0x0072, 0x0801, 0x0401, 0x0201, 0x0084, 0x0048, 0x0201, 0x0090, 0x0009, + 0x0201, 0x0091, 0x0019, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0073, 0x0065, 0x0201, 0x0056, 0x0074, 0x0401, 0x0201, 0x0047, + 0x0066, 0x0083, 0x0601, 0x0201, 0x0038, 0x0201, 0x0075, 0x0057, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0067, + 0x0085, 0x0201, 0x0058, 0x0039, 0x0201, 0x0093, 0x0201, 0x0049, 0x0086, 0x0601, 0x0201, 0x00a0, 0x0201, 0x0068, 0x000a, 0x0201, + 0x00a1, 0x001a, 0x4401, 0x1801, 0x0c01, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0401, 0x0201, 0x0095, 0x0059, 0x0201, 0x00a3, 0x003a, + 0x0801, 0x0401, 0x0201, 0x004a, 0x0096, 0x0201, 0x00b0, 0x000b, 0x0201, 0x00b1, 0x001b, 0x1401, 0x0801, 0x0201, 0x00b2, 0x0401, + 0x0201, 0x0076, 0x0077, 0x0094, 0x0601, 0x0401, 0x0201, 0x0087, 0x0078, 0x00a4, 0x0401, 0x0201, 0x0069, 0x00a5, 0x002b, 0x0c01, + 0x0601, 0x0401, 0x0201, 0x005a, 0x0088, 0x00b3, 0x0201, 0x003b, 0x0201, 0x0079, 0x00a6, 0x0601, 0x0401, 0x0201, 0x006a, 0x00b4, + 0x00c0, 0x0401, 0x0201, 0x000c, 0x0098, 0x00c1, 0x3c01, 0x1601, 0x0a01, 0x0601, 0x0201, 0x001c, 0x0201, 0x0089, 0x00b5, 0x0201, + 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x003c, 0x0401, 0x0201, 0x00b6, 0x006b, 0x0201, 0x00c4, 0x004c, 0x1001, 0x0801, 0x0401, + 0x0201, 0x00a8, 0x008a, 0x0201, 0x00d0, 0x000d, 0x0201, 0x00d1, 0x0201, 0x004b, 0x0201, 0x0097, 0x00a7, 0x0c01, 0x0601, 0x0201, + 0x00c3, 0x0201, 0x007a, 0x0099, 0x0401, 0x0201, 0x00c5, 0x005c, 0x00b7, 0x0401, 0x0201, 0x001d, 0x00d2, 0x0201, 0x002d, 0x0201, + 0x007b, 0x00d3, 0x3401, 0x1c01, 0x0c01, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e0, 0x0a01, + 0x0401, 0x0201, 0x00e1, 0x001e, 0x0401, 0x0201, 0x000e, 0x002e, 0x00e2, 0x0801, 0x0401, 0x0201, 0x00e3, 0x006d, 0x0201, 0x008c, + 0x00e4, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x00f0, 0x2601, 0x1001, 0x0401, 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00aa, + 0x009b, 0x00b9, 0x0201, 0x003e, 0x0201, 0x00d6, 0x00c8, 0x0c01, 0x0601, 0x0201, 0x004e, 0x0201, 0x00d7, 0x007d, 0x0201, 0x00ab, + 0x0201, 0x005e, 0x00c9, 0x0601, 0x0201, 0x000f, 0x0201, 0x009c, 0x006e, 0x0201, 0x00f2, 0x002f, 0x2001, 0x1001, 0x0601, 0x0401, + 0x0201, 0x00d8, 0x008d, 0x003f, 0x0601, 0x0201, 0x00f3, 0x0201, 0x00e6, 0x00ca, 0x0201, 0x00f4, 0x004f, 0x0801, 0x0401, 0x0201, + 0x00bb, 0x00ac, 0x0201, 0x00e7, 0x00f5, 0x0401, 0x0201, 0x00d9, 0x009d, 0x0201, 0x005f, 0x00e8, 0x1e01, 0x0c01, 0x0601, 0x0201, + 0x006f, 0x0201, 0x00f6, 0x00cb, 0x0401, 0x0201, 0x00bc, 0x00ad, 0x00da, 0x0801, 0x0201, 0x00f7, 0x0401, 0x0201, 0x007e, 0x007f, + 0x008e, 0x0601, 0x0401, 0x0201, 0x009e, 0x00ae, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00db, 0x00bd, + 0x0201, 0x00ea, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00eb, 0x0201, 0x00be, 0x0201, 0x00cd, 0x00fa, 0x0e01, 0x0401, 0x0201, 0x00dd, + 0x00ec, 0x0601, 0x0401, 0x0201, 0x00e9, 0x00af, 0x00dc, 0x0201, 0x00ce, 0x00fb, 0x0801, 0x0401, 0x0201, 0x00bf, 0x00de, 0x0201, + 0x00cf, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00ef, 0x0201, 0x00ff, 0x0201, 0x00ed, 0x0201, 0x00fd, 0x0201, 0x00fc, 0x00fe, + }, + [15] = { + 0x1001, 0x0601, 0x0201, 0x0000, 0x0201, 0x0010, 0x0001, 0x0201, 0x0011, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, 0x0012, + 0x3201, 0x1001, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0031, 0x0601, 0x0201, 0x0013, 0x0201, 0x0003, 0x0040, 0x0201, 0x0032, + 0x0023, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0004, 0x0014, 0x0041, 0x0401, 0x0201, 0x0033, 0x0042, 0x0201, 0x0024, 0x0043, 0x0a01, + 0x0601, 0x0201, 0x0034, 0x0201, 0x0050, 0x0005, 0x0201, 0x0051, 0x0015, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, 0x0201, 0x0044, + 0x0053, 0x0061, 0x5a01, 0x2401, 0x1201, 0x0a01, 0x0601, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0201, 0x0016, 0x0062, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0a01, 0x0601, 0x0201, 0x0036, 0x0201, 0x0070, 0x0007, 0x0201, 0x0071, 0x0055, + 0x0401, 0x0201, 0x0017, 0x0064, 0x0201, 0x0072, 0x0027, 0x1801, 0x1001, 0x0801, 0x0401, 0x0201, 0x0046, 0x0073, 0x0201, 0x0037, + 0x0065, 0x0401, 0x0201, 0x0056, 0x0080, 0x0201, 0x0008, 0x0074, 0x0401, 0x0201, 0x0081, 0x0018, 0x0201, 0x0082, 0x0028, 0x1001, + 0x0801, 0x0401, 0x0201, 0x0047, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, 0x0601, + 0x0401, 0x0201, 0x0090, 0x0019, 0x0091, 0x0401, 0x0201, 0x0092, 0x0076, 0x0201, 0x0067, 0x0029, 0x5c01, 0x2401, 0x1201, 0x0a01, + 0x0401, 0x0201, 0x0085, 0x0058, 0x0401, 0x0201, 0x0009, 0x0077, 0x0093, 0x0401, 0x0201, 0x0039, 0x0094, 0x0201, 0x0049, 0x0086, + 0x0a01, 0x0601, 0x0201, 0x0068, 0x0201, 0x00a0, 0x000a, 0x0201, 0x00a1, 0x001a, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, + 0x0059, 0x1a01, 0x0e01, 0x0601, 0x0201, 0x00a3, 0x0201, 0x003a, 0x0087, 0x0401, 0x0201, 0x0078, 0x00a4, 0x0201, 0x004a, 0x0096, + 0x0601, 0x0401, 0x0201, 0x0069, 0x00b0, 0x00b1, 0x0401, 0x0201, 0x001b, 0x00a5, 0x00b2, 0x0e01, 0x0801, 0x0401, 0x0201, 0x005a, + 0x002b, 0x0201, 0x0088, 0x0097, 0x0201, 0x00b3, 0x0201, 0x0079, 0x003b, 0x0801, 0x0401, 0x0201, 0x006a, 0x00b4, 0x0201, 0x004b, + 0x00c1, 0x0401, 0x0201, 0x0098, 0x0089, 0x0201, 0x001c, 0x00b5, 0x5001, 0x2201, 0x1001, 0x0601, 0x0401, 0x0201, 0x005b, 0x002c, + 0x00c2, 0x0601, 0x0401, 0x0201, 0x000b, 0x00c0, 0x00a6, 0x0201, 0x00a7, 0x007a, 0x0a01, 0x0401, 0x0201, 0x00c3, 0x003c, 0x0401, + 0x0201, 0x000c, 0x0099, 0x00b6, 0x0401, 0x0201, 0x006b, 0x00c4, 0x0201, 0x004c, 0x00a8, 0x1401, 0x0a01, 0x0401, 0x0201, 0x008a, + 0x00c5, 0x0401, 0x0201, 0x00d0, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x0201, 0x000d, 0x002d, 0x0c01, + 0x0401, 0x0201, 0x00d2, 0x00d3, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x00a9, 0x0601, 0x0401, 0x0201, 0x009a, 0x00b8, + 0x00d4, 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x4401, 0x2201, 0x1201, 0x0a01, 0x0401, 0x0201, 0x00d5, 0x005d, + 0x0401, 0x0201, 0x00e0, 0x000e, 0x00e1, 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x002e, 0x0801, 0x0401, 0x0201, 0x00b9, + 0x009b, 0x0201, 0x00e3, 0x00d6, 0x0401, 0x0201, 0x006d, 0x003e, 0x0201, 0x00c8, 0x008c, 0x1001, 0x0801, 0x0401, 0x0201, 0x00e4, + 0x004e, 0x0201, 0x00d7, 0x007d, 0x0401, 0x0201, 0x00e5, 0x00ba, 0x0201, 0x00ab, 0x005e, 0x0801, 0x0401, 0x0201, 0x00c9, 0x009c, + 0x0201, 0x00f1, 0x001f, 0x0601, 0x0401, 0x0201, 0x00f0, 0x006e, 0x00f2, 0x0201, 0x002f, 0x00e6, 0x2601, 0x1201, 0x0801, 0x0401, + 0x0201, 0x00d8, 0x00f3, 0x0201, 0x003f, 0x00f4, 0x0601, 0x0201, 0x004f, 0x0201, 0x008d, 0x00d9, 0x0201, 0x00bb, 0x00ca, 0x0801, + 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00f5, 0x0801, 0x0401, 0x0201, 0x009d, 0x005f, 0x0201, 0x00e8, 0x008e, 0x0201, + 0x00f6, 0x00cb, 0x2201, 0x1201, 0x0a01, 0x0601, 0x0401, 0x0201, 0x000f, 0x00ae, 0x006f, 0x0201, 0x00bc, 0x00da, 0x0401, 0x0201, + 0x00ad, 0x00f7, 0x0201, 0x007f, 0x00e9, 0x0801, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00f8, 0x008f, 0x0401, 0x0201, 0x00db, + 0x00bd, 0x0201, 0x00ea, 0x00f9, 0x1001, 0x0801, 0x0401, 0x0201, 0x009f, 0x00dc, 0x0201, 0x00cd, 0x00eb, 0x0401, 0x0201, 0x00be, + 0x00fa, 0x0201, 0x00af, 0x00dd, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00ec, 0x00ce, 0x00fb, 0x0401, 0x0201, 0x00bf, 0x00ed, 0x0201, + 0x00de, 0x00fc, 0x0601, 0x0401, 0x0201, 0x00cf, 0x00fd, 0x00ee, 0x0401, 0x0201, 0x00df, 0x00fe, 0x0201, 0x00ef, 0x00ff, + }, + [16] = { + 0x0201, 0x0000, 0x0601, 0x0201, 0x0010, 0x0201, 0x0001, 0x0011, 0x2a01, 0x0801, 0x0401, 0x0201, 0x0020, 0x0002, 0x0201, 0x0021, + 0x0012, 0x0a01, 0x0601, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0201, 0x0031, 0x0013, 0x0a01, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0601, 0x0201, 0x0014, 0x0201, 0x0033, 0x0042, 0x0401, 0x0201, 0x0024, 0x0050, 0x0201, + 0x0043, 0x0034, 0x8a01, 0x2801, 0x1001, 0x0601, 0x0401, 0x0201, 0x0005, 0x0015, 0x0051, 0x0401, 0x0201, 0x0052, 0x0025, 0x0401, + 0x0201, 0x0044, 0x0035, 0x0053, 0x0a01, 0x0601, 0x0401, 0x0201, 0x0060, 0x0006, 0x0061, 0x0201, 0x0016, 0x0062, 0x0801, 0x0401, + 0x0201, 0x0026, 0x0054, 0x0201, 0x0045, 0x0063, 0x0401, 0x0201, 0x0036, 0x0070, 0x0071, 0x2801, 0x1201, 0x0801, 0x0201, 0x0017, + 0x0201, 0x0007, 0x0201, 0x0055, 0x0064, 0x0401, 0x0201, 0x0072, 0x0027, 0x0401, 0x0201, 0x0046, 0x0065, 0x0073, 0x0a01, 0x0601, + 0x0201, 0x0037, 0x0201, 0x0056, 0x0008, 0x0201, 0x0080, 0x0081, 0x0601, 0x0201, 0x0018, 0x0201, 0x0074, 0x0047, 0x0201, 0x0082, + 0x0201, 0x0028, 0x0066, 0x1801, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0083, 0x0038, 0x0201, 0x0075, 0x0084, 0x0401, 0x0201, 0x0048, + 0x0090, 0x0091, 0x0601, 0x0201, 0x0019, 0x0201, 0x0009, 0x0076, 0x0201, 0x0092, 0x0029, 0x0e01, 0x0801, 0x0401, 0x0201, 0x0085, + 0x0058, 0x0201, 0x0093, 0x0039, 0x0401, 0x0201, 0x00a0, 0x000a, 0x001a, 0x0801, 0x0201, 0x00a2, 0x0201, 0x0067, 0x0201, 0x0057, + 0x0049, 0x0601, 0x0201, 0x0094, 0x0201, 0x0077, 0x0086, 0x0201, 0x00a1, 0x0201, 0x0068, 0x0095, 0xdc01, 0x7e01, 0x3201, 0x1a01, + 0x0c01, 0x0601, 0x0201, 0x002a, 0x0201, 0x0059, 0x003a, 0x0201, 0x00a3, 0x0201, 0x0087, 0x0078, 0x0801, 0x0401, 0x0201, 0x00a4, + 0x004a, 0x0201, 0x0096, 0x0069, 0x0401, 0x0201, 0x00b0, 0x000b, 0x00b1, 0x0a01, 0x0401, 0x0201, 0x001b, 0x00b2, 0x0201, 0x002b, + 0x0201, 0x00a5, 0x005a, 0x0601, 0x0201, 0x00b3, 0x0201, 0x00a6, 0x006a, 0x0401, 0x0201, 0x00b4, 0x004b, 0x0201, 0x000c, 0x00c1, + 0x1e01, 0x0e01, 0x0601, 0x0401, 0x0201, 0x00b5, 0x00c2, 0x002c, 0x0401, 0x0201, 0x00a7, 0x00c3, 0x0201, 0x006b, 0x00c4, 0x0801, + 0x0201, 0x001d, 0x0401, 0x0201, 0x0088, 0x0097, 0x003b, 0x0401, 0x0201, 0x00d1, 0x00d2, 0x0201, 0x002d, 0x00d3, 0x1201, 0x0601, + 0x0401, 0x0201, 0x001e, 0x002e, 0x00e2, 0x0601, 0x0401, 0x0201, 0x0079, 0x0098, 0x00c0, 0x0201, 0x001c, 0x0201, 0x0089, 0x005b, + 0x0e01, 0x0601, 0x0201, 0x003c, 0x0201, 0x007a, 0x00b6, 0x0401, 0x0201, 0x004c, 0x0099, 0x0201, 0x00a8, 0x008a, 0x0601, 0x0201, + 0x000d, 0x0201, 0x00c5, 0x005c, 0x0401, 0x0201, 0x003d, 0x00c6, 0x0201, 0x006c, 0x009a, 0x5801, 0x5601, 0x2401, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008b, 0x004d, 0x0201, 0x00c7, 0x007c, 0x0401, 0x0201, 0x00d5, 0x005d, 0x0201, 0x00e0, 0x000e, 0x0801, 0x0201, + 0x00e3, 0x0401, 0x0201, 0x00d0, 0x00b7, 0x007b, 0x0601, 0x0401, 0x0201, 0x00a9, 0x00b8, 0x00d4, 0x0201, 0x00e1, 0x0201, 0x00aa, + 0x00b9, 0x1801, 0x0a01, 0x0601, 0x0401, 0x0201, 0x009b, 0x00d6, 0x006d, 0x0201, 0x003e, 0x00c8, 0x0601, 0x0401, 0x0201, 0x008c, + 0x00e4, 0x004e, 0x0401, 0x0201, 0x00d7, 0x00e5, 0x0201, 0x00ba, 0x00ab, 0x0c01, 0x0401, 0x0201, 0x009c, 0x00e6, 0x0401, 0x0201, + 0x006e, 0x00d8, 0x0201, 0x008d, 0x00bb, 0x0801, 0x0401, 0x0201, 0x00e7, 0x009d, 0x0201, 0x00e8, 0x008e, 0x0401, 0x0201, 0x00cb, + 0x00bc, 0x009e, 0x00f1, 0x0201, 0x001f, 0x0201, 0x000f, 0x002f, 0x4201, 0x3801, 0x0201, 0x00f2, 0x3401, 0x3201, 0x1401, 0x0801, + 0x0201, 0x00bd, 0x0201, 0x005e, 0x0201, 0x007d, 0x00c9, 0x0601, 0x0201, 0x00ca, 0x0201, 0x00ac, 0x007e, 0x0401, 0x0201, 0x00da, + 0x00ad, 0x00cc, 0x0a01, 0x0601, 0x0201, 0x00ae, 0x0201, 0x00db, 0x00dc, 0x0201, 0x00cd, 0x00be, 0x0601, 0x0401, 0x0201, 0x00eb, + 0x00ed, 0x00ee, 0x0601, 0x0401, 0x0201, 0x00d9, 0x00ea, 0x00e9, 0x0201, 0x00de, 0x0401, 0x0201, 0x00dd, 0x00ec, 0x00ce, 0x003f, + 0x00f0, 0x0401, 0x0201, 0x00f3, 0x00f4, 0x0201, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0a01, 0x0201, 0x00ff, 0x0401, 0x0201, 0x00f6, + 0x006f, 0x0201, 0x00f7, 0x007f, 0x0c01, 0x0601, 0x0201, 0x008f, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00fa, 0x00af, + 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [24] = { + 0x3c01, 0x0801, 0x0401, 0x0201, 0x0000, 0x0010, 0x0201, 0x0001, 0x0011, 0x0e01, 0x0601, 0x0401, 0x0201, 0x0020, 0x0002, 0x0021, + 0x0201, 0x0012, 0x0201, 0x0022, 0x0201, 0x0030, 0x0003, 0x0e01, 0x0401, 0x0201, 0x0031, 0x0013, 0x0401, 0x0201, 0x0032, 0x0023, + 0x0401, 0x0201, 0x0040, 0x0004, 0x0041, 0x0801, 0x0401, 0x0201, 0x0014, 0x0033, 0x0201, 0x0042, 0x0024, 0x0601, 0x0401, 0x0201, + 0x0043, 0x0034, 0x0051, 0x0601, 0x0401, 0x0201, 0x0050, 0x0005, 0x0015, 0x0201, 0x0052, 0x0025, 0xfa01, 0x6201, 0x2201, 0x1201, + 0x0a01, 0x0401, 0x0201, 0x0044, 0x0053, 0x0201, 0x0035, 0x0201, 0x0060, 0x0006, 0x0401, 0x0201, 0x0061, 0x0016, 0x0201, 0x0062, + 0x0026, 0x0801, 0x0401, 0x0201, 0x0054, 0x0045, 0x0201, 0x0063, 0x0036, 0x0401, 0x0201, 0x0071, 0x0055, 0x0201, 0x0064, 0x0046, + 0x2001, 0x0e01, 0x0601, 0x0201, 0x0072, 0x0201, 0x0027, 0x0037, 0x0201, 0x0073, 0x0401, 0x0201, 0x0070, 0x0007, 0x0017, 0x0a01, + 0x0401, 0x0201, 0x0065, 0x0056, 0x0401, 0x0201, 0x0080, 0x0008, 0x0081, 0x0401, 0x0201, 0x0074, 0x0047, 0x0201, 0x0018, 0x0082, + 0x1001, 0x0801, 0x0401, 0x0201, 0x0028, 0x0066, 0x0201, 0x0083, 0x0038, 0x0401, 0x0201, 0x0075, 0x0057, 0x0201, 0x0084, 0x0048, + 0x0801, 0x0401, 0x0201, 0x0091, 0x0019, 0x0201, 0x0092, 0x0076, 0x0401, 0x0201, 0x0067, 0x0029, 0x0201, 0x0085, 0x0058, 0x5c01, + 0x2201, 0x1001, 0x0801, 0x0401, 0x0201, 0x0093, 0x0039, 0x0201, 0x0094, 0x0049, 0x0401, 0x0201, 0x0077, 0x0086, 0x0201, 0x0068, + 0x00a1, 0x0801, 0x0401, 0x0201, 0x00a2, 0x002a, 0x0201, 0x0095, 0x0059, 0x0401, 0x0201, 0x00a3, 0x003a, 0x0201, 0x0087, 0x0201, + 0x0078, 0x004a, 0x1601, 0x0c01, 0x0401, 0x0201, 0x00a4, 0x0096, 0x0401, 0x0201, 0x0069, 0x00b1, 0x0201, 0x001b, 0x00a5, 0x0601, + 0x0201, 0x00b2, 0x0201, 0x005a, 0x002b, 0x0201, 0x0088, 0x00b3, 0x1001, 0x0a01, 0x0601, 0x0201, 0x0090, 0x0201, 0x0009, 0x00a0, + 0x0201, 0x0097, 0x0079, 0x0401, 0x0201, 0x00a6, 0x006a, 0x00b4, 0x0c01, 0x0601, 0x0201, 0x001a, 0x0201, 0x000a, 0x00b0, 0x0201, + 0x003b, 0x0201, 0x000b, 0x00c0, 0x0401, 0x0201, 0x004b, 0x00c1, 0x0201, 0x0098, 0x0089, 0x4301, 0x2201, 0x1001, 0x0801, 0x0401, + 0x0201, 0x001c, 0x00b5, 0x0201, 0x005b, 0x00c2, 0x0401, 0x0201, 0x002c, 0x00a7, 0x0201, 0x007a, 0x00c3, 0x0a01, 0x0601, 0x0201, + 0x003c, 0x0201, 0x000c, 0x00d0, 0x0201, 0x00b6, 0x006b, 0x0401, 0x0201, 0x00c4, 0x004c, 0x0201, 0x0099, 0x00a8, 0x1001, 0x0801, + 0x0401, 0x0201, 0x008a, 0x00c5, 0x0201, 0x005c, 0x00d1, 0x0401, 0x0201, 0x00b7, 0x007b, 0x0201, 0x001d, 0x00d2, 0x0901, 0x0401, + 0x0201, 0x002d, 0x00d3, 0x0201, 0x003d, 0x00c6, 0x55fa, 0x0401, 0x0201, 0x006c, 0x00a9, 0x0201, 0x009a, 0x00d4, 0x2001, 0x1001, + 0x0801, 0x0401, 0x0201, 0x00b8, 0x008b, 0x0201, 0x004d, 0x00c7, 0x0401, 0x0201, 0x007c, 0x00d5, 0x0201, 0x005d, 0x00e1, 0x0801, + 0x0401, 0x0201, 0x001e, 0x00e2, 0x0201, 0x00aa, 0x00b9, 0x0401, 0x0201, 0x009b, 0x00e3, 0x0201, 0x00d6, 0x006d, 0x1401, 0x0a01, + 0x0601, 0x0201, 0x003e, 0x0201, 0x002e, 0x004e, 0x0201, 0x00c8, 0x008c, 0x0401, 0x0201, 0x00e4, 0x00d7, 0x0401, 0x0201, 0x007d, + 0x00ab, 0x00e5, 0x0a01, 0x0401, 0x0201, 0x00ba, 0x005e, 0x0201, 0x00c9, 0x0201, 0x009c, 0x006e, 0x0801, 0x0201, 0x00e6, 0x0201, + 0x000d, 0x0201, 0x00e0, 0x000e, 0x0401, 0x0201, 0x00d8, 0x008d, 0x0201, 0x00bb, 0x00ca, 0x4a01, 0x0201, 0x00ff, 0x4001, 0x3a01, + 0x2001, 0x1001, 0x0801, 0x0401, 0x0201, 0x00ac, 0x00e7, 0x0201, 0x007e, 0x00d9, 0x0401, 0x0201, 0x009d, 0x00e8, 0x0201, 0x008e, + 0x00cb, 0x0801, 0x0401, 0x0201, 0x00bc, 0x00da, 0x0201, 0x00ad, 0x00e9, 0x0401, 0x0201, 0x009e, 0x00cc, 0x0201, 0x00db, 0x00bd, + 0x1001, 0x0801, 0x0401, 0x0201, 0x00ea, 0x00ae, 0x0201, 0x00dc, 0x00cd, 0x0401, 0x0201, 0x00eb, 0x00be, 0x0201, 0x00dd, 0x00ec, + 0x0801, 0x0401, 0x0201, 0x00ce, 0x00ed, 0x0201, 0x00de, 0x00ee, 0x000f, 0x0401, 0x0201, 0x00f0, 0x001f, 0x00f1, 0x0401, 0x0201, + 0x00f2, 0x002f, 0x0201, 0x00f3, 0x003f, 0x1201, 0x0801, 0x0401, 0x0201, 0x00f4, 0x004f, 0x0201, 0x00f5, 0x005f, 0x0401, 0x0201, + 0x00f6, 0x006f, 0x0201, 0x00f7, 0x0201, 0x007f, 0x008f, 0x0a01, 0x0401, 0x0201, 0x00f8, 0x00f9, 0x0401, 0x0201, 0x009f, 0x00af, + 0x00fa, 0x0801, 0x0401, 0x0201, 0x00fb, 0x00bf, 0x0201, 0x00fc, 0x00cf, 0x0401, 0x0201, 0x00fd, 0x00df, 0x0201, 0x00fe, 0x00ef, + }, + [32] = { + 0x0201, 0x0000, 0x0801, 0x0401, 0x0201, 0x0008, 0x0004, 0x0201, 0x0001, 0x0002, 0x0801, 0x0401, 0x0201, 0x000c, 0x000a, 0x0201, + 0x0003, 0x0006, 0x0601, 0x0201, 0x0009, 0x0201, 0x0005, 0x0007, 0x0401, 0x0201, 0x000e, 0x000d, 0x0201, 0x000f, 0x000b, + }, + [33] = { + 0x1001, 0x0801, 0x0401, 0x0201, 0x0000, 0x0001, 0x0201, 0x0002, 0x0003, 0x0401, 0x0201, 0x0004, 0x0005, 0x0201, 0x0006, 0x0007, + 0x0801, 0x0401, 0x0201, 0x0008, 0x0009, 0x0201, 0x000a, 0x000b, 0x0401, 0x0201, 0x000c, 0x000d, 0x0201, 0x000e, 0x000f, + }, +} +return E +end +__FILES["codecs/audio/Mpa/Encode2"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 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 (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 Bits = __include("core/Bits") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode2 = {} + +local floor, log = math.floor, math.log +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- the allocation tables: { bit-allocation-code offset into g_bitalloc_code_tab, bits, band count } runs (minimp3) +local ALLOC_L2M1 = { 0, 4, 3, 16, 4, 8, 32, 3, 12, 40, 2, 7 } +local ALLOC_L2M1_LOW = { 44, 4, 2, 44, 3, 10 } +local ALLOC_L2M2 = { 60, 4, 4, 44, 3, 7, 44, 2, 19 } +local CODE = T.g_bitalloc_code_tab + +-- quantizer classes (minimp3's ba): 1..16 -> 2^ba - 1 levels in ba bits; 17 / 18 / 19 -> 3 / 5 / 9 levels grouped +local function levels(ba) +if ba >= 17 then + return ba == 17 and 3 or(ba == 18 and 5 or 9 +) end + return POW[ba + 1] - 1 +end +-- bits for the 3 samples of one granule +local function tripleBits(ba) +if ba >= 17 then + return ba == 17 and 5 or(ba == 18 and 7 or 10 +) end + return 3 * ba +end +-- the quantizer's signal-to-noise ratio in dB (ISO 11172-3 table C.5) +local SNR= {} +do + local byLevels = { + [3] = 7.00, + [5] = 11.00, + [7] = 16.00, + [9] = 20.84, + [15] = 25.28, + [31] = 31.59, + [63] = 37.75, + [127] = 43.84, + [255] = 49.89, + [511] = 55.93, + [1023] = 61.96, + [2047] = 67.98, + [4095] = 74.01, + [8191] = 80.03, + [16383] = 86.05, + [32767] = 92.01, + [65535] = 98.01, + } + for ba = 1, 19 do + SNR[ba] = byLevels[levels(ba)] or (6.02 * ba) + end +end + +-- scalefactors 2^(1 - i/3), i = 0 .. 62 +local SCF = table.create(63, 0) +for i = 0, 62 do + SCF[i + 1] = 2 ^ (1 - i / 3) +end + +local RATES = { + [44100] = { 3, 0 }, + [48000] = { 3, 1 }, + [32000] = { 3, 2 }, + [22050] = { 2, 0 }, + [24000] = { 2, 1 }, + [16000] = { 2, 2 }, +} +Encode2.RATES = RATES +local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 } +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 } + + +local put = Bits.msbPut + +-- encode(src, opts) -> buffer | nil, message + + + + + + + + + +function Encode2.encode(src, opts) +local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex = info[1], info[2] + local mpeg1 = version == 3 + local inCh = src.channels + local nch = opts.mode == "mono" and 1 or 2 + local kbps = opts.bitrate + local list = (mpeg1 and{BITRATES_V1 }or{BITRATES_V2 +})[1] local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + -- the allocation table (the decoder's choice from the header) + local alloc, nbands + if not mpeg1 then + alloc, nbands = ALLOC_L2M2, 30 + else + local perCh = (nch == 2 and{(math.floor(kbps / 2 ))}or{kbps +})[1] alloc, nbands = ALLOC_L2M1, 27 + if perCh < 56 then + alloc, nbands = ALLOC_L2M1_LOW, srIndex == 2 and 12 or 8 + elseif perCh >= 96 and srIndex ~= 1 then + nbands = 30 + end + end + local bandOff, bandBits = table.create(nbands, 0), table.create(nbands, 0) + do + local k, ai = 0, 1 + local off, bits = 0, 0 + for i = 0, nbands - 1 do + if i == k then + off, bits, k = alloc[ai], alloc[ai + 1], k + alloc[ai + 2] + ai =ai+ 3 + end + bandOff[i + 1], bandBits[i + 1] = off, bits + end + end + -- per band: the classes it can take, in increasing order (index into the code table = the value written) + local steps= {} + for i = 1, nbands do + local s = {} + for v = 1, POW[bandBits[i] + 1] - 1 do + local ba = CODE[bandOff[i] + v] + if ba and ba > 0 then + table.insert(s, { v, ba }) + end + end + steps[i] = s + end + local w= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix +if buffer.len(pf) > buffer.len(w.buf) - 16 then + w.buf = buffer.create(buffer.len(pf) + 65536) + end + buffer.copy(w.buf, 0, pf, 0, buffer.len(pf)) + w.pos = buffer.len(pf) + end + local ana = { Analysis.new(), Analysis.new() } + local pcm = { table.create(1152, 0), table.create(1152, 0) } + -- subband samples: sb[c][band * 36 + t + 1], t = 0 .. 35 + local sbs = { table.create(32 * 36, 0), table.create(32 * 36, 0) } + local sub = table.create(32, 0) + local scf = { table.create(32 * 3, 0), table.create(32 * 3, 0) } -- scalefactor index per band and part + local bal = { table.create(32, 0), table.create(32, 0) } -- allocation step (0 = none) per band + local slot = 144000 * kbps + local rest = 0 + local tmp= nil + local pending= nil + local pendN, pendOff = 0, 0 + local srcDone, flushed = false, false + while true do + local got = 0 + while got < 1152 and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(1152 - got, pendN) + local pb = pending +for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = (inCh > 1 and{(buffer.readf32(pb, base + 4) )}or{l +})[1] if nch == 1 then + pcm[1][got + i + 1] = (inCh > 1 and(((l + r) * 0.5 ))or(l +)) else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got =got+ take + pendN =pendN- take + pendOff =pendOff+ take + end + if got == 0 then + if flushed then + break + end + flushed = true + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, 1152 do + s[i] = 0 + end + local sb = sbs[c] + for t = 0, 35 do + Analysis.run(ana[c], s, t * 32 + 1, sub, 1) + for b = 0, 31 do + sb[b * 36 + t + 1] = sub[b + 1] + end + end + -- scalefactors: the smallest scalefactor (largest index) still >= the part's peak + local sc = scf[c] + for b = 0, nbands - 1 do + for part = 0, 2 do + local m = 0 + local o = b * 36 + part * 12 + for t = 1, 12 do + local v = math.abs(sb[o + t]) + if v > m then + m = v + end + end + local idx = 62 + if m > 0 then + idx = math.clamp(floor(3 * (1 - log(m) / log(2))), 0, 62) + while idx > 0 and SCF[idx + 1] < m do + idx =idx- 1 + end + while idx < 62 and SCF[idx + 2] >= m do + idx =idx+ 1 + end + end + sc[b * 3 + part + 1] = idx + end + end + end + -- the frame size and the bits left for scalefactors and samples + local frameBytes = math.floor(slot / rate +) rest =rest+ slot % rate + local padding = 0 + if rest >= rate then + rest =rest- rate + padding = 1 + frameBytes =frameBytes+ 1 + end + local avail = frameBytes * 8 - 32 + for b = 1, nbands do + avail =avail- bandBits[b] * nch + end + -- greedy allocation: the band with the most noise gets its next step while it fits + local level = { table.create(nbands, 0), table.create(nbands, 0) } -- signal level (dB) per band + for c = 1, nch do + local sc = scf[c] + for b = 1, nbands do + local best = math.min(sc[(b - 1) * 3 + 1], sc[(b - 1) * 3 + 2], sc[(b - 1) * 3 + 3]) + level[c][b] = 20 * math.log10(SCF[best + 1]) + bal[c][b] = 0 + end + end + while true do + local bestC, bestB, bestNoise, bestCost = 0, 0, -math.huge, 0 + for c = 1, nch do + for b = 1, nbands do + local st = bal[c][b] + local s = steps[b] + if st < #s and level[c][b] > -110 then + local cur = st == 0 and 0 or s[st][2] + local nxt = s[st + 1][2] + local noise = level[c][b] - (st == 0 and 0 or SNR[cur]) + local cost = 12 * tripleBits(nxt) - (st == 0 and 0 or 12 * tripleBits(cur)) + if st == 0 then + cost =cost+ (2 + 18 -- scfsi + three scalefactors +) end + if cost <= avail and noise > bestNoise then + bestC, bestB, bestNoise, bestCost = c, b, noise, cost + end + end + end + end + if bestC == 0 then + break + end +do local __DARKLUA_VAR= bal[bestC]__DARKLUA_VAR[bestB]=__DARKLUA_VAR[bestB]+ 1 +end avail =avail- bestCost + end + -- write the frame + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 2, 2) -- layer II + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, nch == 1 and 3 or 0, 2) + put(w, 0, 2) + put(w, 0, 1) + put(w, 1, 1) + put(w, 0, 2) + -- bit allocation + for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + put(w, st == 0 and 0 or steps[b][st][1], bandBits[b]) + end + end + -- scfsi (0: three scalefactors) and the scalefactors + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + put(w, 0, 2) + end + end + end + for b = 1, nbands do + for c = 1, nch do + if bal[c][b] > 0 then + for part = 1, 3 do + put(w, scf[c][(b - 1) * 3 + part], 6) + end + end + end + end + -- samples: 12 granules of 3, band by band, channel by channel + for gr = 0, 11 do + local part = math.floor(gr / 4 +) for b = 1, nbands do + for c = 1, nch do + local st = bal[c][b] + if st > 0 then + local ba = steps[b][st][2] + local L = levels(ba) + local inv = 1 / SCF[scf[c][(b - 1) * 3 + part + 1] + 1] + local o = (b - 1) * 36 + gr * 3 + local sb = sbs[c] + local q0, q1, q2 + do + local function quant(x) +local q = floor((x * inv + 1) * L / 2) + return q < 0 and 0 or(q > L - 1 and((L - 1 ))or(q +)) end + 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)) + else + put(w, q0, ba) + put(w, q1, ba) + put(w, q2, ba) + end + end + end + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos =w.pos+ 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode2 +end +__FILES["codecs/audio/Mpa/Encode3"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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 (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 (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws. +local Bits = __include("core/Bits") +local E = __include("codecs/audio/Mpa/EncTables") +local T = __include("codecs/audio/Mpa/Tables") +local Analysis = __include("codecs/audio/Mpa/Analysis") + +local Encode3 = {} + +local floor, sqrt, cos, pi = math.floor, math.sqrt, math.cos, math.pi +local writeu8 = buffer.writeu8 + +local POW = table.create(40, 0) +for i = 0, 39 do + POW[i + 1] = 2 ^ i +end + +-- ------------------------------------------------------------------------------------------------ Huffman codes +-- CODE[t][x * 16 + y + 1], LEN[t][...] for the pair tables 1..31 (16..23 and 24..31 share a tree); count1 tables A +-- (32) and B (33) indexed by v * 8 + w * 4 + x * 2 + y + 1 +local CODE= {} +local LEN= {} +local XLEN= {} + +local function walk(tree, codes, lens, p, code, len) + local v = tree[p + 1] + if bit32.band(v, 0xFF00) == 0 then + local idx = bit32.band(v, 0xFF) + 1 + if lens[idx] == 0 then + codes[idx], lens[idx] = code, len + end + return + end + -- left (bit 0): offsets of 250+ chain + local q = p + while bit32.rshift(tree[q + 1], 8) >= 250 do + q =q+ bit32.rshift(tree[q + 1], 8) + end + q =q+ bit32.rshift(tree[q + 1], 8) + walk(tree, codes, lens, q, code * 2, len + 1) + q = p + while bit32.band(tree[q + 1], 0xFF) >= 250 do + q =q+ bit32.band(tree[q + 1], 0xFF) + end + q =q+ bit32.band(tree[q + 1], 0xFF) + walk(tree, codes, lens, q, code * 2 + 1, len + 1) +end + +for t = 1, 33 do + local src = t >= 16 and t <= 23 and 16 or(t >= 24 and t <= 31 and 24 or t +) local tree = E.TREES[src] + if tree then + local codes, lens = table.create(256, 0), table.create(256, 0) + walk(tree, codes, lens, 0, 0, 0) + -- the leaf value of pair tables is x << 4 | y: index x * 16 + y + 1 (count1: the 4-bit vwxy) + CODE[t], LEN[t] = codes, lens + local xl = 0 + for idx = 1, 256 do + if lens[idx] > 0 then + local x = math.floor((idx - 1) / 16 +) if x + 1 > xl then + xl = x + 1 + end + end + end + XLEN[t] = xl + end +end +local LINBITS = E.LINBITS +-- the tables that hold values up to m (m <= 15), smallest first +local SMALL= {} +for m = 0, 15 do + local list = {} + for _, t in __iter({ 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 }) do + if XLEN[t] and XLEN[t] - 1 >= m then + table.insert(list, t) + end + end + SMALL[m] = list +end +-- ------------------------------------------------------------------------------------------------ bit writer + + + +local put = Bits.msbPut +Encode3.put = put + +-- ------------------------------------------------------------------------------------------------ constants +local RATES = { + -- rate -> version bits (3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5), sample rate index, scalefactor band group (g_scf_long) + [44100] = { 3, 0, 5 }, + [48000] = { 3, 1, 6 }, + [32000] = { 3, 2, 7 }, + [22050] = { 2, 0, 2 }, + [24000] = { 2, 1, 3 }, + [16000] = { 2, 2, 4 }, + [11025] = { 0, 0, 0 }, + [12000] = { 0, 1, 0 }, + [8000] = { 0, 2, 1 }, +} +Encode3.RATES = RATES +local BITRATES_V1 = { 32, 40, 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 } +Encode3.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 } + +-- the 36-point MDCT (long blocks): X[k] = 1/9 sum_i w_i z_i cos(pi/72 (2i + 19)(2k + 1)), w_i = sin(pi/36 (i + 1/2)) +local MDCT = table.create(18 * 36, 0) +for k = 0, 17 do + for i = 0, 35 do + MDCT[k * 36 + i + 1] = math.sin(pi / 36 * (i + 0.5)) * cos(pi / 72 * (2 * i + 19) * (2 * k + 1)) / 9 + end +end +-- alias reduction coefficients +local CI = { -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037 } +local CS, CA = table.create(8, 0), table.create(8, 0) +for i = 1, 8 do + local s = sqrt(1 + CI[i] * CI[i]) + CS[i], CA[i] = 1 / s, CI[i] / s +end +-- ------------------------------------------------------------------------------------------------ Huffman planning + + + + + + + + + + + + + +local function newPlan() +return { bits = 0, bigValues = 0, count1 = 0, tables = { 0, 0, 0 }, region0 = 0, region1 = 0, c1table = 0, addr1 = 0, addr2 = 0 } +end + +-- bits of the pairs ix[a .. b) with table t (ix 1-based: ix[i + 1] is coefficient i) +local function pairBits(ix, a, b, t) +if t == 0 then + return 0 + end + local lens = LEN[t] + local lb = LINBITS[t] + local bits = 0 + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local extra = 0 + if x > 14 then + x = 15 + extra =extra+ lb + end + if y > 14 then + y = 15 + extra =extra+ lb + end + bits =bits+ (lens[x * 16 + y + 1] + extra +) if x ~= 0 then + bits =bits+ 1 + end + if y ~= 0 then + bits =bits+ 1 + end + end + return bits +end + +-- the best table for the pairs ix[a .. b): table, bits +local function chooseTable(ix, a, b) +if b <= a then + return 0, 0 + end + local m = 0 + for i = a + 1, b do + local v = ix[i] + if v > m then + m = v + end + end + if m == 0 then + return 0, 0 + end + if m <= 15 then + local best, bestBits = 0, math.huge + for _, t in __iter(SMALL[m]) do + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + end + return best, bestBits + end + local need = m - 15 + local best, bestBits = 0, math.huge + for _, group in __iter({ 16, 24 }) do + for t = group, group + 7 do + if POW[LINBITS[t] + 1] - 1 >= need then + local bits = pairBits(ix, a, b, t) + if bits < bestBits then + best, bestBits = t, bits + end + break + end + end + end + return best, bestBits +end + +-- plan the Huffman coding of ix (576 values, max <= 8206) into p; bounds = scalefactor band starts (1-based list) +local function plan(ix, bounds, p) + local i = 576 + while i > 1 and ix[i] == 0 and ix[i - 1] == 0 do + i =i- 2 + end + -- count1 region: quadruples of values <= 1 + local c1 = 0 + while i > 3 and ix[i] <= 1 and ix[i - 1] <= 1 and ix[i - 2] <= 1 and ix[i - 3] <= 1 do + i =i- 4 + c1 =c1+ 1 + end + local bv = i -- big_values * 2 coefficients + p.bigValues, p.count1 = math.floor(bv / 2), c1 + -- count1 bits, table A vs B + local ba, bb = 0, 0 + local lensA = LEN[32] + for q = 0, c1 - 1 do + local o = bv + q * 4 + local v, w, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local s = v + w + x + y + ba =ba+ (lensA[v * 8 + w * 4 + x * 2 + y + 1] + s +) bb =bb+ (4 + s +) end + p.c1table = bb < ba and 1 or 0 + local bits = (bb < ba and{bb }or{ba +})[1] -- regions: region 0 / 1 / 2 split at scalefactor band boundaries + local j = 0 + while j + 1 < #bounds and bounds[j + 2] <= bv do + j =j+ 1 + end + local r0 = math.clamp(floor((j + 1) / 3), 0, 15) + local r1 = math.clamp(floor((j + 1) / 3), 0, 7) + if r0 + r1 + 2 > 22 then + r1 = 22 - r0 - 2 + end + local a1 = math.min(bounds[r0 + 2] or 576, bv) + local a2 = math.min(bounds[r0 + r1 + 3] or 576, bv) + p.region0, p.region1, p.addr1, p.addr2 = r0, r1, a1, a2 + local t1, b1 = chooseTable(ix, 0, a1) + local t2, b2 = chooseTable(ix, a1, a2) + local t3, b3 = chooseTable(ix, a2, bv) + p.tables[1], p.tables[2], p.tables[3] = t1, t2, t3 + p.bits = bits + b1 + b2 + b3 +end + +local function writePairs(w, ix, sign, a, b, t) + if t == 0 then + return + end + local codes, lens = CODE[t], LEN[t] + local lb = LINBITS[t] + for i = a, b - 1, 2 do + local x, y = ix[i + 1], ix[i + 2] + local cx, cy = x > 14 and 15 or x, y > 14 and 15 or y + local idx = cx * 16 + cy + 1 + put(w, codes[idx], lens[idx]) + if cx == 15 then + put(w, x - 15, lb) + end + if x ~= 0 then + put(w, sign[i + 1] and 1 or 0, 1) + end + if cy == 15 then + put(w, y - 15, lb) + end + if y ~= 0 then + put(w, sign[i + 2] and 1 or 0, 1) + end + end +end + +local function writeHuffman(w, ix, sign, p) + local bv = p.bigValues * 2 + writePairs(w, ix, sign, 0, p.addr1, p.tables[1]) + writePairs(w, ix, sign, p.addr1, p.addr2, p.tables[2]) + writePairs(w, ix, sign, p.addr2, bv, p.tables[3]) + local codesA, lensA = CODE[32], LEN[32] + for q = 0, p.count1 - 1 do + local o = bv + q * 4 + local v, ww, x, y = ix[o + 1], ix[o + 2], ix[o + 3], ix[o + 4] + local idx = v * 8 + ww * 4 + x * 2 + y + if p.c1table == 1 then + put(w, 15 - idx, 4) -- table B: the 4 bits inverted + else + put(w, codesA[idx + 1], lensA[idx + 1]) + end + for k = 1, 4 do + if ix[o + k] ~= 0 then + put(w, sign[o + k] and 1 or 0, 1) + end + end + end +end +-- ------------------------------------------------------------------------------------------------ quantization + + + + + + + + + + +local function newUnit() +return { + xr = table.create(576, 0), + xa = table.create(576, 0), + ix = table.create(576, 0), + sign = table.create(576, false), + plan = newPlan(), + gain = 210, + } +end + +-- quantize with global gain g: false when a value overflows 8206 +local function quantize(u, g) +local step = 2 ^ (-(g - 210) * 3 / 16) + local xa, ix = u.xa, u.ix + for i = 1, 576 do + local v = floor(xa[i] * step + 0.4054) + if v > 8206 then + return false + end + ix[i] = v + end + return true +end + +-- the finest global gain whose Huffman size fits budget bits +local function rateLoop(u, budget, bounds) + local xr, xa, sign = u.xr, u.xa, u.sign + local maxa = 0 + for i = 1, 576 do + local v = xr[i] + sign[i] = v < 0 + local a = math.abs(v) ^ 0.75 + xa[i] = a + if a > maxa then + maxa = a + end + end + local p = u.plan + if maxa < 1e-12 then + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + u.gain = 0 + return + end + -- the gain where the largest value quantizes to 0: an upper bound + local lo, hi = 0, 255 + local best = -1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) if quantize(u, mid) then + plan(u.ix, bounds, p) + if p.bits <= budget then + best = mid + hi = mid - 1 + else + lo = mid + 1 + end + else + lo = mid + 1 + end + end + if best < 0 then + best = 255 + end + quantize(u, best) + plan(u.ix, bounds, p) + if p.bits > budget then -- give up on this granule: silence fits any budget + for i = 1, 576 do + u.ix[i] = 0 + end + plan(u.ix, bounds, p) + end + u.gain = best +end +-- ------------------------------------------------------------------------------------------------ encoder +-- encode(src, opts) -> buffer | nil, message + + + + + + + + + + + + + + +function Encode3.encode(src, opts) +local rate = src.sampleRate + local info = RATES[rate] + if not info then + return nil, "unsupported sample rate" + end + local version, srIndex, group = info[1], info[2], info[3] + local mpeg1 = version == 3 + local granules = mpeg1 and 2 or 1 + local spf = 576 * granules + local inCh = src.channels + local mode = opts.mode + local nch = mode == "mono" and 1 or 2 + local kbps = opts.bitrate + local list = (mpeg1 and{BITRATES_V1 }or{BITRATES_V2 +})[1] local brIndex = table.find(list, kbps) + if not brIndex then + return nil, "unsupported bit rate" + end + local sideBytes = (mpeg1 and{(nch == 1 and 17 or 32) }or{(nch == 1 and 9 or 17) +})[1] local slotNum = (mpeg1 and 144000 or 72000) * kbps -- frame bytes * rate + -- scalefactor band starts (long blocks) + local bounds = { 0 } + do + local acc = 0 + for k = 0, 21 do + acc =acc+ T.g_scf_long[group * 23 + k] + table.insert(bounds, acc) + end + end + local w= { buf = buffer.create(65536), pos = 0, acc = 0, cnt = 0 } + if opts.prefix then + local pf = opts.prefix +local need = buffer.len(pf) + if need > buffer.len(w.buf) - 16 then + w.buf = buffer.create(need + 65536) + end + buffer.copy(w.buf, 0, pf, 0, need) + w.pos = need + end + local ana = { Analysis.new(), Analysis.new() } + local prev = { table.create(576, 0), table.create(576, 0) } -- previous granule's subband samples [sb * 18 + k + 1] + local cur = { table.create(576, 0), table.create(576, 0) } + local units = {} + for g = 1, 2 do + units[g] = { newUnit(), newUnit() } + end + local pcm = { table.create(spf, 0), table.create(spf, 0) } + local sub = table.create(32, 0) + local z = table.create(36, 0) + local rest = 0 + local tmp= nil + local pending= nil + local pendN, pendOff = 0, 0 + local srcDone = false + local flushed = false + while true do + -- one frame of input (zero padded at the end; one more silent frame flushes the filterbank delay) + local got = 0 + while got < spf and not srcDone do + if pendN == 0 then + local b, n = src:read(4096, tmp) + if n <= 0 then + srcDone = true + break + end + tmp = b + pending, pendN, pendOff = b, n, 0 + end + local take = math.min(spf - got, pendN) + local pb = pending +for i = 0, take - 1 do + local base = (pendOff + i) * inCh * 4 + local l = buffer.readf32(pb, base) + local r = (inCh > 1 and{(buffer.readf32(pb, base + 4) )}or{l +})[1] if nch == 1 then + if inCh > 1 then + l = (l + r) * 0.5 + end + pcm[1][got + i + 1] = l + else + pcm[1][got + i + 1] = l + pcm[2][got + i + 1] = r + end + end + got =got+ take + pendN =pendN- take + pendOff =pendOff+ take + end + if got == 0 then + if flushed then + break + end + flushed = true -- one silent frame after the input pushes its tail through the filterbank delay + end + for c = 1, nch do + local s = pcm[c] + for i = got + 1, spf do + s[i] = 0 + end + end + -- analysis + MDCT per granule and channel + for g = 1, granules do + for c = 1, nch do + local cu, pv = cur[c], prev[c] + local s = pcm[c] + for k = 0, 17 do + Analysis.run(ana[c], s, (g - 1) * 576 + k * 32 + 1, sub, 1) + for sb = 0, 31 do + local v = sub[sb + 1] + if sb % 2 == 1 and k % 2 == 1 then + v = -v -- frequency inversion of the odd subbands + end + cu[sb * 18 + k + 1] = v + end + end + local xr = units[g][c].xr + for sb = 0, 31 do + local o = sb * 18 + for i = 1, 18 do + z[i] = pv[o + i] + z[i + 18] = cu[o + i] + end + for k = 0, 17 do + local acc = 0 + local mb = k * 36 + for i = 1, 36 do + acc =acc+ MDCT[mb + i] * z[i] + end + xr[o + k + 1] = acc + end + end + -- alias reduction butterflies (the inverse of the decoder's) + for sb = 1, 31 do + local o = sb * 18 + for i = 0, 7 do + local a, b = xr[o - i], xr[o + i + 1] + xr[o - i] = a * CS[i + 1] + b * CA[i + 1] + xr[o + i + 1] = b * CS[i + 1] - a * CA[i + 1] + end + end + prev[c], cur[c] = cu, pv + end + if mode == "joint" then + local x0, x1 = units[g][1].xr, units[g][2].xr + local r2 = sqrt(0.5) + for i = 1, 576 do + local l, r = x0[i], x1[i] + x0[i], x1[i] = (l + r) * r2, (l - r) * r2 + end + end + end + -- the frame size + local frameBytes = math.floor(slotNum / rate +) rest =rest+ slotNum % rate + local padding = 0 + if rest >= rate then + rest =rest- rate + padding = 1 + frameBytes =frameBytes+ 1 + end + local avail = (frameBytes - 4 - sideBytes) * 8 + local left = avail + local nUnits = granules * nch + local done = 0 + for g = 1, granules do + for c = 1, nch do + local budget = math.min(4095, math.floor(left / (nUnits - done))) + local u = units[g][c] + rateLoop(u, budget, bounds) + left =left- u.plan.bits + done =done+ 1 + end + end + -- header + if w.pos + frameBytes + 64 > buffer.len(w.buf) then + local nb = buffer.create(buffer.len(w.buf) * 2 + frameBytes) + buffer.copy(nb, 0, w.buf, 0, w.pos) + w.buf = nb + end + local start = w.pos + put(w, 0x7FF, 11) + put(w, version, 2) + put(w, 1, 2) -- layer III + put(w, 1, 1) -- no CRC + put(w, brIndex, 4) + put(w, srIndex, 2) + put(w, padding, 1) + put(w, 0, 1) + put(w, mode == "mono" and 3 or(mode == "joint" and 1 or 0), 2) + put(w, mode == "joint" and 2 or 0, 2) -- mode extension: mid / side on, intensity off + put(w, 0, 1) + put(w, 1, 1) -- original + put(w, 0, 2) + -- side info + if mpeg1 then + put(w, 0, 9) -- main_data_begin + put(w, 0, nch == 1 and 5 or 3) + for _ = 1, nch do + put(w, 0, 4) -- scfsi + end + else + put(w, 0, 8) + put(w, 0, nch == 1 and 1 or 2) + end + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + local p = u.plan + put(w, p.bits, 12) -- part2_3_length (no scalefactor bits) + put(w, p.bigValues, 9) + put(w, u.gain, 8) + put(w, 0, mpeg1 and 4 or 9) -- scalefac_compress + put(w, 0, 1) -- window switching off + put(w, p.tables[1], 5) + put(w, p.tables[2], 5) + put(w, p.tables[3], 5) + put(w, p.region0, 4) + put(w, p.region1, 3) + if mpeg1 then + put(w, 0, 1) -- preflag + end + put(w, 0, 1) -- scalefac_scale + put(w, p.c1table, 1) + end + end + -- main data + for g = 1, granules do + for c = 1, nch do + local u = units[g][c] + writeHuffman(w, u.ix, u.sign, u.plan) + end + end + if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + -- ancillary padding to the frame size + while w.pos < start + frameBytes do + writeu8(w.buf, w.pos, 0) + w.pos =w.pos+ 1 + end + end + if src.err then + return nil, tostring(src.err) + end + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Encode3 +end +__FILES["codecs/audio/Mpa/Header"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 = __include("codecs/audio/Mpa/Tables") + +local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift +local ru8 = buffer.readu8 + +local HALFRATE = T.halfrate +local HZ = { [0] = 44100, 48000, 32000 } + +local H = {} + +H.MAX_FREE_FORMAT_FRAME_SIZE = 2304 +H.MAX_FRAME_SYNC_MATCHES = 10 + +-- hdr_valid +function H.valid(b, o) +if ru8(b, o) ~= 0xFF then + return false + end + local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + return (band(h1, 0xF0) == 0xF0 or band(h1, 0xFE) == 0xE2) + and band(rshift(h1, 1), 3) ~= 0 + and rshift(h2, 4) ~= 15 + and band(rshift(h2, 2), 3) ~= 3 +end +local valid = H.valid + +-- hdr_compare: h2 is a valid header of the same version / layer / sample rate / free-format-ness as h1 +function H.compare(b, o1, o2) +if not valid(b, o2) then + return false + end + local a1, a2 = ru8(b, o1 + 1), ru8(b, o1 + 2) + local c1, c2 = ru8(b, o2 + 1), ru8(b, o2 + 2) + return band(bxor(a1, c1), 0xFE) == 0 + and band(bxor(a2, c2), 0x0C) == 0 + and (band(a2, 0xF0) == 0) == (band(c2, 0xF0) == 0) +end +local compare = H.compare + +-- from the header bytes h1 = byte 1, h2 = byte 2 +function H.bitrateKbps(h1, h2) +local mpeg1 = band(h1, 8) ~= 0 and 1 or 0 + local layer = band(rshift(h1, 1), 3) + return 2 * HALFRATE[mpeg1 * 45 + (layer - 1) * 15 + rshift(h2, 4)] +end +local bitrateKbps = H.bitrateKbps + +function H.sampleRate(h1, h2) +local hz = HZ[band(rshift(h2, 2), 3)] + if band(h1, 8) == 0 then + hz =math.floor(hz/ 2 +) end + if band(h1, 0x10) == 0 then + hz =math.floor(hz/ 2 +) end + return hz +end +local sampleRate = H.sampleRate + +function H.frameSamples(h1) +if band(h1, 6) == 6 then + return 384 + elseif band(h1, 14) == 2 then + return 576 + end + return 1152 +end +local frameSamples = H.frameSamples + +-- hdr_frame_bytes (without padding); free format = 0 -> freeSize +function H.frameBytes(b, o, freeSize) +local h1, h2 = ru8(b, o + 1), ru8(b, o + 2) + local hz = sampleRate(h1, h2) + local fb = math.floor(frameSamples(h1) * bitrateKbps(h1, h2) * 125 / hz +) if band(h1, 6) == 6 then + fb = band(fb, 0xFFFFFFFC) + end + return (fb ~= 0 and{fb }or{freeSize +})[1]end +local frameBytes = H.frameBytes + +function H.padding(b, o) +if band(ru8(b, o + 2), 2) == 0 then + return 0 + end + return band(ru8(b, o + 1), 6) == 6 and 4 or 1 +end +local padding = H.padding + +-- mp3d_match_frame: the frames chained after o (n bytes left) keep comparing equal +local function matchFrame(b, o, n, fb) +local i = 0 + for nmatch = 0, H.MAX_FRAME_SYNC_MATCHES - 1 do + i =i+ (frameBytes(b, o + i, fb) + padding(b, o + i) +) if i + 4 > n then + return nmatch > 0 + end + if not compare(b, o, o + i) then + return false + end + end + return true +end + +-- mp3d_find_frame over b[base, base + n): returns (skip, frame bytes incl. padding or 0, free format size) +function H.findFrame(b, base, n, ffb) +for i = 0, n - 5 do + local o = base + i + if valid(b, o) then + local fb = frameBytes(b, o, ffb) + local fap = fb + padding(b, o) + local k = 4 + while fb == 0 and k < H.MAX_FREE_FORMAT_FRAME_SIZE and i + 2 * k < n - 4 do + if compare(b, o, o + k) then + local f = k - padding(b, o) + local nextfb = f + padding(b, o + k) + if not (i + k + nextfb + 4 > n or not compare(b, o, o + k + nextfb)) then + fap = k + fb = f + ffb = f + end + end + k =k+ 1 + end + if (fb ~= 0 and i + fap <= n and matchFrame(b, o, n - i, fb)) or (i == 0 and fap == n) then + return i, fap, ffb + end + ffb = 0 + end + end + return n, 0, ffb +end + +return H +end +__FILES["codecs/audio/Mpa/Tables"] = function() +--!strict +-- 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, + 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80, 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, + 48, 56, 64, 72, 80, 0, 16, 24, 28, 32, 40, 48, 56, 64, 72, 80, 88, 96, 112, 128, 0, 16, 20, 24, + 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 0, 16, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, + 160, 192, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, +} +T.g_bitalloc_code_tab = { [0] = 0, + 17, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 17, 18, 3, 19, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 16, 0, 17, 18, 3, 19, 4, 5, 16, 0, 17, 18, 16, 0, 17, 18, 19, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 17, 18, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +T.g_scf_long = { [0] = 6, + 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 12, 12, + 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, 0, 6, 6, 6, + 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 6, 6, 6, 6, + 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, 0, 6, 6, 6, 6, 6, + 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, 0, 4, 4, 4, 4, 4, 4, + 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, 0, 4, 4, 4, 4, 4, 4, 6, + 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, 0, 4, 4, 4, 4, 4, 4, 6, 6, + 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, 0, +} +T.g_scf_short = { [0] = 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, + 18, 18, 24, 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, + 40, 40, 40, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 8, + 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, + 14, 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, + 42, 42, 42, 12, 12, 12, 0, +} +T.g_scf_mixed = { [0] = 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 30, 30, 30, 40, 40, 40, 18, 18, 18, 0, 0, 0, 0, 12, 12, 12, 4, 4, 4, 8, 8, 8, + 12, 12, 12, 16, 16, 16, 20, 20, 20, 24, 24, 24, 28, 28, 28, 36, 36, 36, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 26, 26, 26, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, + 10, 14, 14, 14, 18, 18, 18, 26, 26, 26, 32, 32, 32, 42, 42, 42, 18, 18, 18, 0, 0, 0, 0, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, + 24, 24, 32, 32, 32, 44, 44, 44, 12, 12, 12, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 24, 24, 24, 30, 30, 30, 40, 40, 40, + 18, 18, 18, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 8, 8, 8, + 10, 10, 10, 12, 12, 12, 14, 14, 14, 18, 18, 18, 22, 22, 22, 30, 30, 30, 56, 56, 56, 0, 0, 4, + 4, 4, 4, 4, 4, 6, 6, 4, 4, 4, 6, 6, 6, 6, 6, 6, 10, 10, 10, 12, 12, 12, 14, 14, + 14, 16, 16, 16, 20, 20, 20, 26, 26, 26, 66, 66, 66, 0, 0, 4, 4, 4, 4, 4, 4, 6, 6, 4, + 4, 4, 6, 6, 6, 8, 8, 8, 12, 12, 12, 16, 16, 16, 20, 20, 20, 26, 26, 26, 34, 34, 34, 42, + 42, 42, 12, 12, 12, 0, 0, +} +T.g_expfrac = { [0] = 9.31322575e-10, + 7.83145814e-10, 6.58544508e-10, 5.53767716e-10, +} +T.g_scf_partitions = { [0] = 6, + 5, 5, 5, 6, 5, 5, 5, 6, 5, 7, 3, 11, 10, 0, 0, 7, 7, 7, 0, 6, 6, 6, 3, 8, + 8, 5, 0, 8, 9, 6, 12, 6, 9, 9, 9, 6, 9, 12, 6, 15, 18, 0, 0, 6, 15, 12, 0, 6, + 12, 9, 6, 6, 18, 9, 0, 9, 9, 6, 12, 9, 9, 9, 9, 9, 9, 12, 6, 18, 18, 0, 0, 12, + 12, 12, 0, 12, 9, 9, 6, 15, 12, 9, 0, +} +T.g_scfc_decode = { [0] = 0, + 1, 2, 3, 12, 5, 6, 7, 9, 10, 11, 13, 14, 15, 18, 19, +} +T.g_mod = { [0] = 5, + 5, 4, 4, 5, 5, 4, 1, 4, 3, 1, 1, 5, 6, 6, 1, 4, 4, 4, 1, 4, 3, 1, 1, +} +T.g_preamp = { [0] = 1, + 1, 1, 1, 2, 2, 3, 3, 3, 2, +} +T.g_pow43 = { [0] = 0, + -1, -2.519842, -4.326749, -6.349604, -8.549880, -10.902724, -13.390518, -16.000000, -18.720754, -21.544347, -24.463781, -27.473142, -30.567351, -33.741992, -36.993181, 0, 1, 2.519842, 4.326749, 6.349604, 8.549880, 10.902724, 13.390518, 16.000000, + 18.720754, 21.544347, 24.463781, 27.473142, 30.567351, 33.741992, 36.993181, 40.317474, 43.711787, 47.173345, 50.699631, 54.288352, 57.937408, 61.644865, 65.408941, 69.227979, 73.100443, 77.024898, 81.000000, 85.024491, 89.097188, 93.216975, 97.382800, 101.593667, + 105.848633, 110.146801, 114.487321, 118.869381, 123.292209, 127.755065, 132.257246, 136.798076, 141.376907, 145.993119, 150.646117, 155.335327, 160.060199, 164.820202, 169.614826, 174.443577, 179.305980, 184.201575, 189.129918, 194.090580, 199.083145, 204.107210, 209.162385, 214.248292, + 219.364564, 224.510845, 229.686789, 234.892058, 240.126328, 245.389280, 250.680604, 256.000000, 261.347174, 266.721841, 272.123723, 277.552547, 283.008049, 288.489971, 293.998060, 299.532071, 305.091761, 310.676898, 316.287249, 321.922592, 327.582707, 333.267377, 338.976394, 344.709550, + 350.466646, 356.247482, 362.051866, 367.879608, 373.730522, 379.604427, 385.501143, 391.420496, 397.362314, 403.326427, 409.312672, 415.320884, 421.350905, 427.402579, 433.475750, 439.570269, 445.685987, 451.822757, 457.980436, 464.158883, 470.357960, 476.577530, 482.817459, 489.077615, + 495.357868, 501.658090, 507.978156, 514.317941, 520.677324, 527.056184, 533.454404, 539.871867, 546.308458, 552.764065, 559.238575, 565.731879, 572.243870, 578.774440, 585.323483, 591.890898, 598.476581, 605.080431, 611.702349, 618.342238, 625.000000, 631.675540, 638.368763, 645.079578, +} +T.tabs = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 785, 785, 785, 785, 784, 784, 784, 784, 513, 513, 513, 513, 513, 513, 513, 513, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, -255, 1313, 1298, 1282, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 290, + 288, -255, 1313, 1298, 1282, 769, 769, 769, 769, 529, 529, 529, 529, 529, 529, 529, 529, 528, 528, 528, 528, 528, 528, 528, + 528, 512, 512, 512, 512, 512, 512, 512, 512, 290, 288, -253, -318, -351, -367, 785, 785, 785, 785, 784, 784, 784, 784, 769, + 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 819, 818, 547, 547, 275, + 275, 275, 275, 561, 560, 515, 546, 289, 274, 288, 258, -254, -287, 1329, 1299, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 784, + 784, 784, 784, 529, 529, 529, 529, 529, 529, 529, 529, 769, 769, 769, 769, 768, 768, 768, 768, 563, 560, 306, 306, 291, + 259, -252, -413, -477, -542, 1298, -575, 1041, 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -383, -399, 1107, 1092, 1106, 1061, 849, 849, 789, 789, 1104, 1091, 773, 773, 1076, + 1075, 341, 340, 325, 309, 834, 804, 577, 577, 532, 532, 516, 516, 832, 818, 803, 816, 561, 561, 531, 531, 515, 546, 289, + 289, 288, 258, -252, -429, -493, -559, 1057, 1057, 1042, 1042, 529, 529, 529, 529, 529, 529, 529, 529, 784, 784, 784, 784, 769, + 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, -382, 1077, -415, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, + 1075, 834, 834, 597, 581, 340, 340, 339, 324, 804, 833, 532, 532, 832, 772, 818, 803, 817, 787, 816, 771, 290, 290, 290, + 290, 288, 258, -253, -349, -414, -447, -463, 1329, 1299, -479, 1314, 1312, 1057, 1057, 1042, 1042, 1026, 1026, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, 768, 768, 768, 768, -319, 851, 821, -335, 836, 850, 805, 849, 341, 340, 325, 336, 533, + 533, 579, 579, 564, 564, 773, 832, 578, 548, 563, 516, 321, 276, 306, 291, 304, 259, -251, -572, -733, -830, -863, -879, 1041, + 1041, 784, 784, 784, 784, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, -511, -527, -543, 1396, 1351, 1381, 1366, 1395, 1335, 1380, -559, 1334, 1138, 1138, 1063, 1063, 1350, 1392, 1031, 1031, 1062, 1062, 1364, + 1363, 1120, 1120, 1333, 1348, 881, 881, 881, 881, 375, 374, 359, 373, 343, 358, 341, 325, 791, 791, 1123, 1122, -703, 1105, 1045, + -719, 865, 865, 790, 790, 774, 774, 1104, 1029, 338, 293, 323, 308, -799, -815, 833, 788, 772, 818, 803, 816, 322, 292, 307, + 320, 561, 531, 515, 546, 289, 274, 288, 258, -251, -525, -605, -685, -765, -831, -846, 1298, 1057, 1057, 1312, 1282, 785, 785, 785, + 785, 784, 784, 784, 784, 769, 769, 769, 769, 512, 512, 512, 512, 512, 512, 512, 512, 1399, 1398, 1383, 1367, 1382, 1396, 1351, + -511, 1381, 1366, 1139, 1139, 1079, 1079, 1124, 1124, 1364, 1349, 1363, 1333, 882, 882, 882, 882, 807, 807, 807, 807, 1094, 1094, 1136, + 1136, 373, 341, 535, 535, 881, 775, 867, 822, 774, -591, 324, 338, -671, 849, 550, 550, 866, 864, 609, 609, 293, 336, 534, + 534, 789, 835, 773, -751, 834, 804, 308, 307, 833, 788, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, 290, -252, + -397, -477, -557, -622, -653, -719, -735, -750, 1329, 1299, 1314, 1057, 1057, 1042, 1042, 1312, 1282, 1024, 1024, 785, 785, 785, 785, 784, + 784, 784, 784, 769, 769, 769, 769, -383, 1127, 1141, 1111, 1126, 1140, 1095, 1110, 869, 869, 883, 883, 1079, 1109, 882, 882, 375, + 374, 807, 868, 838, 881, 791, -463, 867, 822, 368, 263, 852, 837, 836, -543, 610, 610, 550, 550, 352, 336, 534, 534, 865, + 774, 851, 821, 850, 805, 593, 533, 579, 564, 773, 832, 578, 578, 548, 548, 577, 577, 307, 276, 306, 291, 516, 560, 259, + 259, -250, -2107, -2507, -2764, -2909, -2974, -3007, -3023, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, 256, 256, 256, 256, 256, 256, -767, -1052, -1213, -1277, -1358, -1405, -1469, -1535, -1550, -1582, -1614, -1647, -1662, -1694, -1726, + -1759, -1774, -1807, -1822, -1854, -1886, 1565, -1919, -1935, -1951, -1967, 1731, 1730, 1580, 1717, -1983, 1729, 1564, -1999, 1548, -2015, -2031, 1715, 1595, + -2047, 1714, -2063, 1610, -2079, 1609, -2095, 1323, 1323, 1457, 1457, 1307, 1307, 1712, 1547, 1641, 1700, 1699, 1594, 1685, 1625, 1442, 1442, 1322, + 1322, -780, -973, -910, 1279, 1278, 1277, 1262, 1276, 1261, 1275, 1215, 1260, 1229, -959, 974, 974, 989, 989, -943, 735, 478, 478, 495, + 463, 506, 414, -1039, 1003, 958, 1017, 927, 942, 987, 957, 431, 476, 1272, 1167, 1228, -1183, 1256, -1199, 895, 895, 941, 941, 1242, + 1227, 1212, 1135, 1014, 1014, 490, 489, 503, 487, 910, 1013, 985, 925, 863, 894, 970, 955, 1012, 847, -1343, 831, 755, 755, 984, + 909, 428, 366, 754, 559, -1391, 752, 486, 457, 924, 997, 698, 698, 983, 893, 740, 740, 908, 877, 739, 739, 667, 667, 953, + 938, 497, 287, 271, 271, 683, 606, 590, 712, 726, 574, 302, 302, 738, 736, 481, 286, 526, 725, 605, 711, 636, 724, 696, + 651, 589, 681, 666, 710, 364, 467, 573, 695, 466, 466, 301, 465, 379, 379, 709, 604, 665, 679, 316, 316, 634, 633, 436, + 436, 464, 269, 424, 394, 452, 332, 438, 363, 347, 408, 393, 448, 331, 422, 362, 407, 392, 421, 346, 406, 391, 376, 375, + 359, 1441, 1306, -2367, 1290, -2383, 1337, -2399, -2415, 1426, 1321, -2431, 1411, 1336, -2447, -2463, -2479, 1169, 1169, 1049, 1049, 1424, 1289, 1412, + 1352, 1319, -2495, 1154, 1154, 1064, 1064, 1153, 1153, 416, 390, 360, 404, 403, 389, 344, 374, 373, 343, 358, 372, 327, 357, 342, + 311, 356, 326, 1395, 1394, 1137, 1137, 1047, 1047, 1365, 1392, 1287, 1379, 1334, 1364, 1349, 1378, 1318, 1363, 792, 792, 792, 792, 1152, + 1152, 1032, 1032, 1121, 1121, 1046, 1046, 1120, 1120, 1030, 1030, -2895, 1106, 1061, 1104, 849, 849, 789, 789, 1091, 1076, 1029, 1090, 1060, + 1075, 833, 833, 309, 324, 532, 532, 832, 772, 818, 803, 561, 561, 531, 560, 515, 546, 289, 274, 288, 258, -250, -1179, -1579, + -1836, -1996, -2124, -2253, -2333, -2413, -2477, -2542, -2574, -2607, -2622, -2655, 1314, 1313, 1298, 1312, 1282, 785, 785, 785, 785, 1040, 1040, 1025, + 1025, 768, 768, 768, 768, -766, -798, -830, -862, -895, -911, -927, -943, -959, -975, -991, -1007, -1023, -1039, -1055, -1070, 1724, 1647, -1103, + -1119, 1631, 1767, 1662, 1738, 1708, 1723, -1135, 1780, 1615, 1779, 1599, 1677, 1646, 1778, 1583, -1151, 1777, 1567, 1737, 1692, 1765, 1722, 1707, + 1630, 1751, 1661, 1764, 1614, 1736, 1676, 1763, 1750, 1645, 1598, 1721, 1691, 1762, 1706, 1582, 1761, 1566, -1167, 1749, 1629, 767, 766, 751, + 765, 494, 494, 735, 764, 719, 749, 734, 763, 447, 447, 748, 718, 477, 506, 431, 491, 446, 476, 461, 505, 415, 430, 475, + 445, 504, 399, 460, 489, 414, 503, 383, 474, 429, 459, 502, 502, 746, 752, 488, 398, 501, 473, 413, 472, 486, 271, 480, + 270, -1439, -1455, 1357, -1471, -1487, -1503, 1341, 1325, -1519, 1489, 1463, 1403, 1309, -1535, 1372, 1448, 1418, 1476, 1356, 1462, 1387, -1551, 1475, + 1340, 1447, 1402, 1386, -1567, 1068, 1068, 1474, 1461, 455, 380, 468, 440, 395, 425, 410, 454, 364, 467, 466, 464, 453, 269, 409, + 448, 268, 432, 1371, 1473, 1432, 1417, 1308, 1460, 1355, 1446, 1459, 1431, 1083, 1083, 1401, 1416, 1458, 1445, 1067, 1067, 1370, 1457, 1051, + 1051, 1291, 1430, 1385, 1444, 1354, 1415, 1400, 1443, 1082, 1082, 1173, 1113, 1186, 1066, 1185, 1050, -1967, 1158, 1128, 1172, 1097, 1171, 1081, + -1983, 1157, 1112, 416, 266, 375, 400, 1170, 1142, 1127, 1065, 793, 793, 1169, 1033, 1156, 1096, 1141, 1111, 1155, 1080, 1126, 1140, 898, + 898, 808, 808, 897, 897, 792, 792, 1095, 1152, 1032, 1125, 1110, 1139, 1079, 1124, 882, 807, 838, 881, 853, 791, -2319, 867, 368, + 263, 822, 852, 837, 866, 806, 865, -2399, 851, 352, 262, 534, 534, 821, 836, 594, 594, 549, 549, 593, 593, 533, 533, 848, + 773, 579, 579, 564, 578, 548, 563, 276, 276, 577, 576, 306, 291, 516, 560, 305, 305, 275, 259, -251, -892, -2058, -2620, -2828, + -2957, -3023, -3039, 1041, 1041, 1040, 1040, 769, 769, 769, 769, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, + 256, 256, 256, -511, -527, -543, -559, 1530, -575, -591, 1528, 1527, 1407, 1526, 1391, 1023, 1023, 1023, 1023, 1525, 1375, 1268, 1268, 1103, + 1103, 1087, 1087, 1039, 1039, 1523, -604, 815, 815, 815, 815, 510, 495, 509, 479, 508, 463, 507, 447, 431, 505, 415, 399, -734, + -782, 1262, -815, 1259, 1244, -831, 1258, 1228, -847, -863, 1196, -879, 1253, 987, 987, 748, -767, 493, 493, 462, 477, 414, 414, 686, + 669, 478, 446, 461, 445, 474, 429, 487, 458, 412, 471, 1266, 1264, 1009, 1009, 799, 799, -1019, -1276, -1452, -1581, -1677, -1757, -1821, + -1886, -1933, -1997, 1257, 1257, 1483, 1468, 1512, 1422, 1497, 1406, 1467, 1496, 1421, 1510, 1134, 1134, 1225, 1225, 1466, 1451, 1374, 1405, 1252, + 1252, 1358, 1480, 1164, 1164, 1251, 1251, 1238, 1238, 1389, 1465, -1407, 1054, 1101, -1423, 1207, -1439, 830, 830, 1248, 1038, 1237, 1117, 1223, + 1148, 1236, 1208, 411, 426, 395, 410, 379, 269, 1193, 1222, 1132, 1235, 1221, 1116, 976, 976, 1192, 1162, 1177, 1220, 1131, 1191, 963, + 963, -1647, 961, 780, -1663, 558, 558, 994, 993, 437, 408, 393, 407, 829, 978, 813, 797, 947, -1743, 721, 721, 377, 392, 844, + 950, 828, 890, 706, 706, 812, 859, 796, 960, 948, 843, 934, 874, 571, 571, -1919, 690, 555, 689, 421, 346, 539, 539, 944, + 779, 918, 873, 932, 842, 903, 888, 570, 570, 931, 917, 674, 674, -2575, 1562, -2591, 1609, -2607, 1654, 1322, 1322, 1441, 1441, 1696, + 1546, 1683, 1593, 1669, 1624, 1426, 1426, 1321, 1321, 1639, 1680, 1425, 1425, 1305, 1305, 1545, 1668, 1608, 1623, 1667, 1592, 1638, 1666, 1320, + 1320, 1652, 1607, 1409, 1409, 1304, 1304, 1288, 1288, 1664, 1637, 1395, 1395, 1335, 1335, 1622, 1636, 1394, 1394, 1319, 1319, 1606, 1621, 1392, + 1392, 1137, 1137, 1137, 1137, 345, 390, 360, 375, 404, 373, 1047, -2751, -2767, -2783, 1062, 1121, 1046, -2799, 1077, -2815, 1106, 1061, 789, + 789, 1105, 1104, 263, 355, 310, 340, 325, 354, 352, 262, 339, 324, 1091, 1076, 1029, 1090, 1060, 1075, 833, 833, 788, 788, 1088, + 1028, 818, 818, 803, 803, 561, 561, 531, 531, 816, 771, 546, 546, 289, 274, 288, 258, -253, -317, -381, -446, -478, -509, 1279, + 1279, -811, -1179, -1451, -1756, -1900, -2028, -2189, -2253, -2333, -2414, -2445, -2511, -2526, 1313, 1298, -2559, 1041, 1041, 1040, 1040, 1025, 1025, 1024, + 1024, 1022, 1007, 1021, 991, 1020, 975, 1019, 959, 687, 687, 1018, 1017, 671, 671, 655, 655, 1016, 1015, 639, 639, 758, 758, 623, + 623, 757, 607, 756, 591, 755, 575, 754, 559, 543, 543, 1009, 783, -575, -621, -685, -749, 496, -590, 750, 749, 734, 748, 974, + 989, 1003, 958, 988, 973, 1002, 942, 987, 957, 972, 1001, 926, 986, 941, 971, 956, 1000, 910, 985, 925, 999, 894, 970, -1071, + -1087, -1102, 1390, -1135, 1436, 1509, 1451, 1374, -1151, 1405, 1358, 1480, 1420, -1167, 1507, 1494, 1389, 1342, 1465, 1435, 1450, 1326, 1505, 1310, + 1493, 1373, 1479, 1404, 1492, 1464, 1419, 428, 443, 472, 397, 736, 526, 464, 464, 486, 457, 442, 471, 484, 482, 1357, 1449, 1434, + 1478, 1388, 1491, 1341, 1490, 1325, 1489, 1463, 1403, 1309, 1477, 1372, 1448, 1418, 1433, 1476, 1356, 1462, 1387, -1439, 1475, 1340, 1447, 1402, + 1474, 1324, 1461, 1371, 1473, 269, 448, 1432, 1417, 1308, 1460, -1711, 1459, -1727, 1441, 1099, 1099, 1446, 1386, 1431, 1401, -1743, 1289, 1083, + 1083, 1160, 1160, 1458, 1445, 1067, 1067, 1370, 1457, 1307, 1430, 1129, 1129, 1098, 1098, 268, 432, 267, 416, 266, 400, -1887, 1144, 1187, + 1082, 1173, 1113, 1186, 1066, 1050, 1158, 1128, 1143, 1172, 1097, 1171, 1081, 420, 391, 1157, 1112, 1170, 1142, 1127, 1065, 1169, 1049, 1156, + 1096, 1141, 1111, 1155, 1080, 1126, 1154, 1064, 1153, 1140, 1095, 1048, -2159, 1125, 1110, 1137, -2175, 823, 823, 1139, 1138, 807, 807, 384, + 264, 368, 263, 868, 838, 853, 791, 867, 822, 852, 837, 866, 806, 865, 790, -2319, 851, 821, 836, 352, 262, 850, 805, 849, + -2399, 533, 533, 835, 820, 336, 261, 578, 548, 563, 577, 532, 532, 832, 772, 562, 562, 547, 547, 305, 275, 560, 515, 290, + 290, 288, 258, +} +T.tab32 = { [0] = 130, + 162, 193, 209, 44, 28, 76, 140, 9, 9, 9, 9, 9, 9, 9, 9, 190, 254, 222, 238, 126, 94, 157, 157, 109, + 61, 173, 205, +} +T.tab33 = { [0] = 252, + 236, 220, 204, 188, 172, 156, 140, 124, 108, 92, 76, 60, 44, 28, 12, +} +T.tabindex = { [0] = 0, + 32, 64, 98, 0, 132, 180, 218, 292, 364, 426, 538, 648, 746, 0, 1126, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1460, 1842, + 1842, 1842, 1842, 1842, 1842, 1842, 1842, +} +T.g_linbits = { [0] = 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, + 5, 6, 7, 8, 9, 11, 13, +} +T.g_pan = { [0] = 0, + 1, 0.21132487, 0.78867513, 0.36602540, 0.63397460, 0.5, 0.5, 0.63397460, 0.36602540, 0.78867513, 0.21132487, 1, 0, +} +T.g_aa = { [0] = 0.85749293, + 0.88174200, 0.94962865, 0.98331459, 0.99551782, 0.99916056, 0.99989920, 0.99999316, 0.51449576, 0.47173197, 0.31337745, 0.18191320, 0.09457419, 0.04096558, 0.01419856, 0.00369997, +} +T.g_twid9 = { [0] = 0.73727734, + 0.79335334, 0.84339145, 0.88701083, 0.92387953, 0.95371695, 0.97629601, 0.99144486, 0.99904822, 0.67559021, 0.60876143, 0.53729961, 0.46174861, 0.38268343, 0.30070580, 0.21643961, 0.13052619, 0.04361938, +} +T.g_twid3 = { [0] = 0.79335334, + 0.92387953, 0.99144486, 0.60876143, 0.38268343, 0.13052619, +} +T.g_mdct_window = { [0] = 0.99904822, + 0.99144486, 0.97629601, 0.95371695, 0.92387953, 0.88701083, 0.84339145, 0.79335334, 0.73727734, 0.04361938, 0.13052619, 0.21643961, 0.30070580, 0.38268343, 0.46174861, 0.53729961, 0.60876143, 0.67559021, 1, 1, 1, 1, 1, 1, 0.99144486, + 0.92387953, 0.79335334, 0, 0, 0, 0, 0, 0, 0.13052619, 0.38268343, 0.60876143, +} +T.g_sec = { [0] = 10.19000816, + 0.50060302, 0.50241929, 3.40760851, 0.50547093, 0.52249861, 2.05778098, 0.51544732, 0.56694406, 1.48416460, 0.53104258, 0.64682180, 1.16943991, 0.55310392, 0.78815460, 0.97256821, 0.58293498, 1.06067765, 0.83934963, 0.62250412, 1.72244716, 0.74453628, 0.67480832, 5.10114861, +} +T.g_win = { [0] = -1, + 26, -31, 208, 218, 401, -519, 2063, 2000, 4788, -5517, 7134, 5959, 35640, -39336, 74992, -1, 24, -35, 202, 222, 347, -581, 2080, 1952, + 4425, -5879, 7640, 5288, 33791, -41176, 74856, -1, 21, -38, 196, 225, 294, -645, 2087, 1893, 4063, -6237, 8092, 4561, 31947, -43006, 74630, -1, + 19, -41, 190, 227, 244, -711, 2085, 1822, 3705, -6589, 8492, 3776, 30112, -44821, 74313, -1, 17, -45, 183, 228, 197, -779, 2075, 1739, + 3351, -6935, 8840, 2935, 28289, -46617, 73908, -1, 16, -49, 176, 228, 153, -848, 2057, 1644, 3004, -7271, 9139, 2037, 26482, -48390, 73415, -2, + 14, -53, 169, 227, 111, -919, 2032, 1535, 2663, -7597, 9389, 1082, 24694, -50137, 72835, -2, 13, -58, 161, 224, 72, -991, 2001, 1414, + 2330, -7910, 9592, 70, 22929, -51853, 72169, -2, 11, -63, 154, 221, 36, -1064, 1962, 1280, 2006, -8209, 9750, -998, 21189, -53534, 71420, -2, + 10, -68, 147, 215, 2, -1137, 1919, 1131, 1692, -8491, 9863, -2122, 19478, -55178, 70590, -3, 9, -73, 139, 208, -29, -1210, 1870, 970, + 1388, -8755, 9935, -3300, 17799, -56778, 69679, -3, 8, -79, 132, 200, -57, -1283, 1817, 794, 1095, -8998, 9966, -4533, 16155, -58333, 68692, -4, + 7, -85, 125, 189, -83, -1356, 1759, 605, 814, -9219, 9959, -5818, 14548, -59838, 67629, -4, 7, -91, 117, 177, -106, -1428, 1698, 402, + 545, -9416, 9916, -7154, 12980, -61289, 66494, -5, 6, -97, 111, 163, -127, -1498, 1634, 185, 288, -9585, 9838, -8540, 11455, -62684, 65290, +} +return T +end +__FILES["codecs/audio/Musepack"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- codecs/audio/Musepack: Musepack (MPC) stream versions 7 and 8: the stream headers (SV7's 32-bit word-swapped +-- header, SV8's key / size packets: SH with its CRC, RG, EI, AP, SE), the frame / audio packet index, and the +-- decoder (codecs/audio/Musepack/Decode: subband bitstream, requantisation, polyphase synthesis). A port of libmpcdec +-- (musepack_src_r475: mpc_demux.c, streaminfo.c, mpc_decoder.c; BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt), gapless like libmpcdec (the 481-sample synthesis delay and SV8's leading silence are +-- dropped, the length is exact). Not supported: SV4 - SV6 (UNSUPPORTED), the SV8 seek table (the packets are indexed +-- instead), chapters. +-- +-- local s, err = Musepack.open(buf, start, limit) -- start: the "MP+" / "MPCK" magic (after an ID3v2 tag) +-- -- s: { version, sampleRate, channels, frames, maxBand, ms, profile, encoder, gapless, gain, ... } plus the +-- -- codecs/audio/Stream spec: count, start(i), decode(i), pcm(), reset(), skip, stop, preroll +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Musepack/Decode") + +local Musepack = {} + +local RATES = { 44100, 48000, 37800, 32000 } +local FRAME, DELAY, PAD = Decode.FRAME, Decode.DELAY, Decode.PAD +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ SV7 +-- SV7 reads the stream as little-endian 32-bit words, most significant bit first: swap them into a padded copy + + + + + + + + + + + + + + + + + + + + + + + + + +local function swapped(buf, p, limit) +local n = limit - p + local words = math.floor((n + 3) / 4 +) local out = buffer.create(words * 4 + PAD) + buffer.copy(out, 0, buf, p, n) + for i = 0, words - 1 do + buffer.writeu32(out, i * 4, bit32.byteswap(buffer.readu32(out, i * 4))) + end + return out +end + +local function sv7(buf, start, limit) +if limit - start < 32 then + return nil, Err.new(Err.TRUNCATED, "SV7 header", start) + end + local ver = bit32.band(readu8(buf, start + 3), 15) + if ver ~= 7 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. ver .. " (SV7 and SV8 only)", start) + end + local s = swapped(buf, start + 4, limit) + local totalBits = (limit - start - 4) * 8 + local at = Decode.bitsAt + local frames = at(s, 0, 16) * 65536 + at(s, 16, 16) + local ms = at(s, 33, 1) == 1 + local maxBand = at(s, 34, 6) + local profile = at(s, 40, 4) + local rate = RATES[at(s, 46, 2) + 1] + local gainTitle, peakTitle = at(s, 64, 16), at(s, 80, 16) + local gainAlbum, peakAlbum = at(s, 96, 16), at(s, 112, 16) + local gapless = at(s, 128, 1) == 1 + local last = at(s, 129, 11) + local encoder = at(s, 160, 8) + if maxBand == 0 or maxBand >= 32 then + return nil, Err.new(Err.CORRUPT, "bad band count " .. maxBand, start) + end + if last == 0 then + last = FRAME + elseif last > FRAME then + return nil, Err.new(Err.CORRUPT, "bad last frame length", start) + end + if frames == 0 then + return nil, Err.new(Err.CORRUPT, "no frames", start) + end + if frames > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, "more than 2^24 frames", start) + end + local samples = frames * FRAME - ((gapless and((FRAME - last ))or(DELAY))) + -- the frame index: a 20-bit size in front of each frame (the last one has 11 more bits: its length) + local offs, sizes= {}, {} + local pos = 168 + for i = 1, frames do + if pos + 20 > totalBits then + break + end + local size = at(s, pos, 20) + local stop = pos + 20 + size + (i == frames and 11 or 0) + if stop > totalBits then + break -- a truncated last frame + end + offs[i], sizes[i] = pos + 20, size + pos = stop + end + local have = #offs + if have == 0 then + return nil, Err.new(Err.TRUNCATED, "no complete frame", start) + end + -- frames past the stream (a truncated file, or the synthesis tail of a gapless stream) decode as silence + local need = math.min(math.floor((samples + DELAY + FRAME - 1) / FRAME), have + 1) + local stopAt = math.min(samples + DELAY, have * FRAME + (have < frames and 0 or FRAME)) + local st = Decode.state(7, maxBand, ms, 2) + local pcm = table.create(FRAME * 2, 0) + local prev = 0 + local out= { + version = 7, + sampleRate = rate, + channels = 2, + frames = math.max(0, stopAt - DELAY), + maxBand = maxBand, + ms = ms, + profile = profile, + encoder = encoder, + gapless = gapless, + gain = { titleGain = gainTitle, titlePeak = peakTitle, albumGain = gainAlbum, albumPeak = peakAlbum }, + blockFrames = 1, + bytes = limit - start, + count = need, + start = function(i) +return (i - 1) * FRAME + end, + decode = function(i) +if i ~= prev + 1 then + Decode.reset(st, i == 1 and 0 or 0x01010101) + end + prev = i + local o= offs[i] + if o == nil then + Decode.frame(st, s, -1, 0, false, pcm, 1) + return FRAME, nil + end + local e, msg = Decode.frame(st, s, o, o + sizes[i], false, pcm, 1) + if not e then + return nil, Err.from(msg, start + 4 + math.floor(o / 8)) + end + if e ~= o + sizes[i] then + return nil, Err.new(Err.CORRUPT, "frame " .. i .. " has the wrong size", start + 4 + math.floor(o / 8)) + end + return FRAME, nil + end, + pcm = function() +return pcm + end, + reset = function() + prev = -1 + end, + skip = DELAY, + stop = stopAt, + preroll = 32, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +-- a packet size: 7 bits per byte, most significant first, bit 7 = more +local function varint(buf, p, limit) +local v = 0 + for k = 0, 7 do + if p + k >= limit then + return -1, p + end + local b = readu8(buf, p + k) + v = v * 128 + bit32.band(b, 127) + if b < 128 then + return v, p + k + 1 + end + end + return -1, p +end + +local function sv8(buf, start, limit) +local p = start + 4 + local sh= nil + local gain, pns, profile, encoder = nil, nil, 0, 0 + local apOff, apSize= {}, {} + while p + 2 < limit do + local k1, k2 = readu8(buf, p), readu8(buf, p + 1) + if k1 < 65 or k1 > 90 or k2 < 65 or k2 > 90 then + return nil, Err.new(Err.CORRUPT, "bad packet key", p) + end + local key = buffer.readstring(buf, p, 2) + local size, body = varint(buf, p + 2, limit) + if size < 0 or size < body - p then + return nil, Err.new(Err.CORRUPT, "bad packet size", p) + end + local stop = p + size + if stop > limit then + if key == "AP" then + break -- a truncated last packet + end + return nil, Err.new(Err.TRUNCATED, key .. " packet", p) + end + if key == "SH" then + if stop - body < 6 then + return nil, Err.new(Err.CORRUPT, "short stream header", p) + end + local crc = buffer.readu32(buf, body) + crc = bit32.byteswap(crc) + if Crc32.of(buf, body + 4, stop - body - 4) ~= crc then + return nil, Err.new(Err.CHECKSUM, "stream header CRC", p) + end + if readu8(buf, body + 4) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "Musepack stream version " .. readu8(buf, body + 4), p) + end + local samples, q = varint(buf, body + 5, stop) + local silence, q2 = varint(buf, q, stop) + if samples < 0 or silence < 0 or q2 + 2 > stop then + return nil, Err.new(Err.CORRUPT, "bad stream header", p) + end + local b0, b1 = readu8(buf, q2), readu8(buf, q2 + 1) + sh = { + samples = samples, + silence = silence, + rate = RATES[bit32.rshift(b0, 5) + 1], + maxBand = bit32.band(b0, 31) + 1, + channels = bit32.rshift(b1, 4) + 1, + ms = bit32.band(b1, 8) ~= 0, + blockPwr = bit32.band(b1, 7) * 2, + } + elseif key == "RG" and stop - body >= 9 and readu8(buf, body) == 1 then + local function u16(o) +return readu8(buf, body + o) * 256 + readu8(buf, body + o + 1) + end + gain = { titleGain = u16(1), titlePeak = u16(3), albumGain = u16(5), albumPeak = u16(7) } + elseif key == "EI" and stop - body >= 4 then + local b = readu8(buf, body) + profile = bit32.rshift(b, 1) / 8 + pns = bit32.band(b, 1) == 1 + encoder = readu8(buf, body + 1) * 2 ^ 24 + readu8(buf, body + 2) * 2 ^ 16 + readu8(buf, body + 3) * 2 ^ 8 + elseif key == "AP" then + table.insert(apOff, body) + table.insert(apSize, stop - body) + elseif key == "SE" then + break + end + p = stop + end + if not sh then + return nil, Err.new(Err.CORRUPT, "no stream header", start) + end + local h = sh +local samples, silence, maxBand, channels = h.samples, h.silence, h.maxBand, h.channels + if maxBand >= 32 or channels > 2 or silence > samples then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bands, %d channels", maxBand, channels), start) + end + if samples > 2 ^ 34 then + return nil, Err.new(Err.LIMIT, "too many samples", start) + end + if #apOff == 0 then + return nil, Err.new(Err.CORRUPT, "no audio packet", start) + end + local per = 2 ^ h.blockPwr + if per * FRAME * channels > 2 ^ 22 then + return nil, Err.new(Err.LIMIT, per .. " frames per audio packet", start) + end + local needFrames = math.floor((samples + DELAY + FRAME - 1) / FRAME +) local count = math.min(#apOff, math.floor((needFrames + per - 1) / per)) + local stopAt = math.min(samples + DELAY, count * per * FRAME) + local st = Decode.state(8, maxBand, h.ms, channels) + local pcm = table.create(per * FRAME * channels, 0) + local scratch = buffer.create(0) + local out= { + version = 8, + sampleRate = h.rate, + channels = channels, + frames = math.max(0, stopAt - DELAY - silence), + maxBand = maxBand, + ms = h.ms, + profile = profile, + encoder = encoder, + gapless = true, + pns = pns, + gain = gain, + blockFrames = per, + bytes = limit - start, + count = count, + start = function(i) +return (i - 1) * per * FRAME + end, + decode = function(i) +local o, size= apOff[i], apSize[i] + if buffer.len(scratch) < size + PAD then + scratch = buffer.create(size + PAD) + end + buffer.copy(scratch, 0, buf, o, size) + local nf = math.min(per, needFrames - (i - 1) * per) + local pos = 0 + for f = 1, nf do + local e, msg = Decode.frame(st, scratch, pos, size * 8, f == 1, pcm, (f - 1) * FRAME * channels + 1) + if not e then + return nil, Err.from(msg, o) + end + pos = e + end + if nf == per and size * 8 - pos > 7 then + return nil, Err.new(Err.CORRUPT, "audio packet " .. i .. " has unused data", o) + end + return nf * FRAME, nil + end, + pcm = function() +return pcm + end, + reset = function() + Decode.reset(st, 0) + end, + skip = DELAY + silence, + stop = stopAt, + preroll = 1, + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- magic(buf, p, limit) -> 7 | 8 | 0 (other: "MP+" with another version is 7's family, reported by open) +function Musepack.magic(buf, p, limit) +if p + 4 > limit then + return 0 + end + local m = buffer.readstring(buf, p, 4) + if m == "MPCK" then + return 8 + end + if string.sub(m, 1, 3) == "MP+" then + return 7 + end + return 0 +end + +-- open(buf, start, limit) -> Stream | nil, Err +function Musepack.open(buf, start, limit) +local v = Musepack.magic(buf, start, limit) + if v == 8 then + return sv8(buf, start, limit) + elseif v == 7 then + return sv7(buf, start, limit) + end + return nil, Err.new(Err.CORRUPT, "not a Musepack stream", start) +end + +return Musepack +end +__FILES["codecs/audio/Musepack/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/audio/Musepack/Decode: one Musepack SV7 / SV8 frame (1152 samples per channel): the bitstream (band +-- resolutions, scalefactor indices, quantised subband samples, with SV8's canonical Huffman / enumerative codes), +-- requantisation (M/S or L/R) and the 32-band polyphase synthesis. A line-by-line port of libmpcdec's mpc_decoder.c, +-- requant.c and synth_filter.c (musepack_src_r475, BSD-3-Clause, (c) The Musepack Development Team, +-- licenses/libmpcdec-BSD.txt) in double precision float. The bit reader is module state (decoding is synchronous) over +-- a buffer the caller pads by at least PAD bytes past `limit`: the band loops stop as soon as the position passes the +-- limit, so every read stays inside the buffer. No error / assert: failures return nil, "message". +local T = __include("codecs/audio/Musepack/Tables") + +local readu32, bswap, extract, band, bor, rshift, lshift, bnot, bxor = + buffer.readu32, bit32.byteswap, bit32.extract, bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.bnot, bit32.bxor +local abs = math.abs + +local Decode = {} +Decode.PAD = 8192 +Decode.DELAY = 481 -- MPC_DECODER_SYNTH_DELAY +Decode.FRAME = 1152 + +-- ------------------------------------------------------------------------------------------------ tables +local L = T.lut +local HDR, SCFI7, DSCF7 = L(T.HuffHdr), L(T.HuffSCFI), L(T.HuffDSCF) +local Q7= { + { L(T.HuffQ1_0), L(T.HuffQ1_1) }, + { L(T.HuffQ2_0), L(T.HuffQ2_1) }, + { L(T.HuffQ3_0), L(T.HuffQ3_1) }, + { L(T.HuffQ4_0), L(T.HuffQ4_1) }, + { L(T.HuffQ5_0), L(T.HuffQ5_1) }, + { L(T.HuffQ6_0), L(T.HuffQ6_1) }, + { L(T.HuffQ7_0), L(T.HuffQ7_1) }, +} +local BANDS8 = L(T.H_Bands, T.S_Bands) +local SCFI8 = { L(T.H_SCFI_1, T.S_SCFI_1), L(T.H_SCFI_2, T.S_SCFI_2) } +local DSCF8 = { L(T.H_DSCF_1, T.S_DSCF_1), L(T.H_DSCF_2, T.S_DSCF_2) } +local RES8 = { L(T.H_Res_1, T.S_Res_1), L(T.H_Res_2, T.S_Res_2) } +local Q1_8 = L(T.H_Q1, T.S_Q1) +local Q9UP = L(T.H_Q9up, T.S_Q9up) +-- mpc_can_Q[res - 2][0 / 1] for res 2 and 5 .. 8; res 3 / 4 use Q34[res - 2] +local Q8= { + [2] = { L(T.H_Q2_1, T.S_Q2_1), L(T.H_Q2_2, T.S_Q2_2) }, + [5] = { L(T.H_Q5_1, T.S_Q5_1), L(T.H_Q5_2, T.S_Q5_2) }, + [6] = { L(T.H_Q6_1, T.S_Q6_1), L(T.H_Q6_2, T.S_Q6_2) }, + [7] = { L(T.H_Q7_1, T.S_Q7_1), L(T.H_Q7_2, T.S_Q7_2) }, + [8] = { L(T.H_Q8_1, T.S_Q8_1), L(T.H_Q8_2, T.S_Q8_2) }, +} +local Q34 = { L(T.H_Q3, T.S_Q3), L(T.H_Q4, T.S_Q4) } +local THRES = { [2] = 3, [5] = 1, [6] = 3, [7] = 4, [8] = 8 } +local CC, DC, RES_BIT = T.CC, T.DC, T.RES_BIT +local CNK, CNK_LEN, CNK_LOST, LOG2, LOG2_LOST = T.CNK, T.CNK_LEN, T.CNK_LOST, T.LOG2, T.LOG2_LOST + +-- the f32 rounding of the C tables (libmpcdec decodes in single precision) +local F32 = buffer.create(4) +local function f32(x) +buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +for i, v in __iter(CC) do + CC[i] = f32(v) +end + +-- SCF[i]: the scalefactor of index i (0 .. 255, the index's low byte): 2^-15 * 0.83298...^(s - 1), s = i as int8 +-- (libmpcdec's mpc_decoder_scale_output in float mode: 1 dB steps, the table filled outwards from index 1) +local SCF = table.create(256, 0) +do + local f1 = 1 / 32768 + local f2 = f1 + SCF[2] = f32(f1) + f1 =f1* 0.83298066476582673961 + f2 =f2* (1 / 0.83298066476582673961 +) for n = 1, 128 do + SCF[band(1 + n, 255) + 1] = f32(f1) + SCF[band(1 - n, 255) + 1] = f32(f2) + f1 =f1* 0.83298066476582673961 + f2 =f2* (1 / 0.83298066476582673961 +) end +end + +-- the synthesis window D (Di_opt / 65536), 32 x 16, row-major +local DW = table.create(512, 0) +for i, v in __iter(T.DI) do + DW[i] = f32(v / 65536) +end + +-- ------------------------------------------------------------------------------------------------ bit reader +local B= buffer.create(0) +local P = 0 -- bit position + +local function bits(n) +if n <= 0 then + return 0 + end + if n > 24 then + local hi = bits(n - 16) + return hi * 65536 + bits(16) + end + local w = bswap(readu32(B, rshift(P, 3))) + local v = extract(w, 32 - band(P, 7) - n, n) + P =P+ n + return v +end + +local function peek16() +local w = bswap(readu32(B, rshift(P, 3))) + return extract(w, 16 - band(P, 7), 16) +end + +-- a table-driven Huffman symbol (plain or canonical) +local function huff(t) +local code = peek16() + local k = rshift(code, 8) + 1 + local n = t.len[k] + if n > 0 then + P =P+ n + return t.val[k] + end + local j = t.val[k] + local codes = t.codes + while code < codes[j] do + j =j+ 1 + end + n = t.lens[j] + P =P+ n + local sym = t.sym + if sym then + return sym[band(t.vals[j] - rshift(code, 16 - n), 255) + 1] or 0 + end + return t.vals[j] +end + +-- mpc_bits_log_dec: 0 .. max +local function logDec(max) +if max <= 0 then + return 0 + end + local v = 0 + local len, lost = LOG2[max], LOG2_LOST[max] + if len > 1 then + v = bits(len - 1) + end + if v >= lost then + v = v * 2 + bits(1) - lost + end + return v +end + +-- mpc_bits_enum_dec: an n-bit word with k bits set +local function enumDec(k, n) +local out = 0 + local code = bits(CNK_LEN[k][n] - 1) + local lost = CNK_LOST[k][n] + if code >= lost then + code = code * 2 + bits(1) - lost + end + repeat + n =n- 1 + local c = CNK[k][n + 1] + if code >= c then + out = bor(out, lshift(1, n)) + code =code- c + k =k- 1 + end + until k <= 0 or n <= 0 + return out +end + +-- mpc_random_int: two polynomial counters, XORed +local PARITY = table.create(256, 0) +for i = 0, 255 do + local p, v = 0, i + while v > 0 do + p = bxor(p, band(v, 1)) + v = rshift(v, 1) + end + PARITY[i + 1] = p +end + +-- ------------------------------------------------------------------------------------------------ synthesis +-- mpc_compute_new_V: 32 subband samples Y[y .. y + 31] -> 64 V values at V[o .. o + 63] (the ISO 11172-3 matrixing +-- through Byeong Gi Lee's fast DCT) +local function newV(Y, y, V, o) + local A00 = Y[y] + Y[y + 31] + local A01 = Y[y + 1] + Y[y + 30] + local A02 = Y[y + 2] + Y[y + 29] + local A03 = Y[y + 3] + Y[y + 28] + local A04 = Y[y + 4] + Y[y + 27] + local A05 = Y[y + 5] + Y[y + 26] + local A06 = Y[y + 6] + Y[y + 25] + local A07 = Y[y + 7] + Y[y + 24] + local A08 = Y[y + 8] + Y[y + 23] + local A09 = Y[y + 9] + Y[y + 22] + local A10 = Y[y + 10] + Y[y + 21] + local A11 = Y[y + 11] + Y[y + 20] + local A12 = Y[y + 12] + Y[y + 19] + local A13 = Y[y + 13] + Y[y + 18] + local A14 = Y[y + 14] + Y[y + 17] + local A15 = Y[y + 15] + Y[y + 16] + local B00 = A00 + A15 + local B01 = A01 + A14 + local B02 = A02 + A13 + local B03 = A03 + A12 + local B04 = A04 + A11 + local B05 = A05 + A10 + local B06 = A06 + A09 + local B07 = A07 + A08 + local B08 = (A00 - A15) * 0.5024192929 + local B09 = (A01 - A14) * 0.5224986076 + local B10 = (A02 - A13) * 0.5669440627 + local B11 = (A03 - A12) * 0.6468217969 + local B12 = (A04 - A11) * 0.7881546021 + local B13 = (A05 - A10) * 1.0606776476 + local B14 = (A06 - A09) * 1.7224471569 + local B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = B00 + B01 + A01 = (B00 - B01) * 0.7071067691 + A02 = B02 + B03 + A03 = (B02 - B03) * 0.7071067691 + A04 = B04 + B05 + A05 = (B04 - B05) * 0.7071067691 + A06 = B06 + B07 + A07 = (B06 - B07) * 0.7071067691 + A08 = B08 + B09 + A09 = (B08 - B09) * 0.7071067691 + A10 = B10 + B11 + A11 = (B10 - B11) * 0.7071067691 + A12 = B12 + B13 + A13 = (B12 - B13) * 0.7071067691 + A14 = B14 + B15 + A15 = (B14 - B15) * 0.7071067691 + V[o + 48] = -A00 + V[o] = A01 + V[o + 8] = A03 + V[o + 40] = -A02 - A03 + V[o + 12] = A07 + local t = A05 + A07 + V[o + 4] = t + V[o + 36] = -(t + A06) + V[o + 44] = -A04 - A06 - A07 + V[o + 14] = A15 + t = A11 + A15 + V[o + 10] = t + V[o + 6] = t + A13 + t = A09 + A13 + A15 + V[o + 2] = t + t = -t - A14 + V[o + 34] = t + V[o + 38] = t + A09 - A10 - A11 + t = -(A12 + A14 + A15) + V[o + 46] = t - A08 + V[o + 42] = t - A10 - A11 + A00 = (Y[y] - Y[y + 31]) * 0.5006030202 + A01 = (Y[y + 1] - Y[y + 30]) * 0.5054709315 + A02 = (Y[y + 2] - Y[y + 29]) * 0.5154473186 + A03 = (Y[y + 3] - Y[y + 28]) * 0.5310425758 + A04 = (Y[y + 4] - Y[y + 27]) * 0.5531039238 + A05 = (Y[y + 5] - Y[y + 26]) * 0.5829349756 + A06 = (Y[y + 6] - Y[y + 25]) * 0.6225041151 + A07 = (Y[y + 7] - Y[y + 24]) * 0.6748083234 + A08 = (Y[y + 8] - Y[y + 23]) * 0.7445362806 + A09 = (Y[y + 9] - Y[y + 22]) * 0.8393496275 + A10 = (Y[y + 10] - Y[y + 21]) * 0.9725682139 + A11 = (Y[y + 11] - Y[y + 20]) * 1.1694399118 + A12 = (Y[y + 12] - Y[y + 19]) * 1.4841645956 + A13 = (Y[y + 13] - Y[y + 18]) * 2.0577809811 + A14 = (Y[y + 14] - Y[y + 17]) * 3.4076085091 + A15 = (Y[y + 15] - Y[y + 16]) * 10.1900081635 + B00 = A00 + A15 + B01 = A01 + A14 + B02 = A02 + A13 + B03 = A03 + A12 + B04 = A04 + A11 + B05 = A05 + A10 + B06 = A06 + A09 + B07 = A07 + A08 + B08 = (A00 - A15) * 0.5024192929 + B09 = (A01 - A14) * 0.5224986076 + B10 = (A02 - A13) * 0.5669440627 + B11 = (A03 - A12) * 0.6468217969 + B12 = (A04 - A11) * 0.7881546021 + B13 = (A05 - A10) * 1.0606776476 + B14 = (A06 - A09) * 1.7224471569 + B15 = (A07 - A08) * 5.1011486053 + A00 = B00 + B07 + A01 = B01 + B06 + A02 = B02 + B05 + A03 = B03 + B04 + A04 = (B00 - B07) * 0.5097956061 + A05 = (B01 - B06) * 0.6013448834 + A06 = (B02 - B05) * 0.8999761939 + A07 = (B03 - B04) * 2.5629155636 + A08 = B08 + B15 + A09 = B09 + B14 + A10 = B10 + B13 + A11 = B11 + B12 + A12 = (B08 - B15) * 0.5097956061 + A13 = (B09 - B14) * 0.6013448834 + A14 = (B10 - B13) * 0.8999761939 + A15 = (B11 - B12) * 2.5629155636 + B00 = A00 + A03 + B01 = A01 + A02 + B02 = (A00 - A03) * 0.5411961079 + B03 = (A01 - A02) * 1.3065630198 + B04 = A04 + A07 + B05 = A05 + A06 + B06 = (A04 - A07) * 0.5411961079 + B07 = (A05 - A06) * 1.3065630198 + B08 = A08 + A11 + B09 = A09 + A10 + B10 = (A08 - A11) * 0.5411961079 + B11 = (A09 - A10) * 1.3065630198 + B12 = A12 + A15 + B13 = A13 + A14 + B14 = (A12 - A15) * 0.5411961079 + B15 = (A13 - A14) * 1.3065630198 + A00 = (B00 + B01) + A01 = (B00 - B01) * 0.7071067691 + A02 = (B02 + B03) + A03 = (B02 - B03) * 0.7071067691 + A04 = (B04 + B05) + A05 = (B04 - B05) * 0.7071067691 + A06 = (B06 + B07) + A07 = (B06 - B07) * 0.7071067691 + A08 = (B08 + B09) + A09 = (B08 - B09) * 0.7071067691 + A10 = (B10 + B11) + A11 = (B10 - B11) * 0.7071067691 + A12 = (B12 + B13) + A13 = (B12 - B13) * 0.7071067691 + A14 = (B14 + B15) + A15 = (B14 - B15) * 0.7071067691 + V[o + 15] = A15 + t = A07 + A15 + V[o + 13] = t + t =t+ A11 + V[o + 11] = t + V[o + 5] = t + A05 + A13 + t = A03 + A11 + A15 + V[o + 9] = t + V[o + 7] = t + A13 + t = A01 + A09 + A13 + A15 + V[o + 1] = t + V[o + 33] = -t - A14 + t = A05 + A07 + A09 + A13 + A15 + V[o + 3] = t + V[o + 35] = -t - A06 - A14 + t = -(A10 + A11 + A13 + A14 + A15) + V[o + 37] = t - A05 - A06 - A07 + V[o + 39] = t - A02 - A03 + t =t+ (A13 - A12 +) V[o + 41] = t - A02 - A03 + V[o + 43] = t - A04 - A06 - A07 + t = -(A08 + A12 + A14 + A15) + V[o + 47] = t - A00 + V[o + 45] = t - A04 - A06 - A07 + for i = 0, 15 do + V[o + 32 - i] = -V[o + i] + end + for i = 33, 47 do + V[o + 96 - i] = V[o + i] + end +end +-- ------------------------------------------------------------------------------------------------ state + + + + + + + + + + + + + + + + + + + + + + + + + +function Decode.state(version, maxBand, ms, channels) +local st= { + version = version, + maxBand = maxBand, + ms = ms, + channels = channels, + resL = table.create(33, 0), + resR = table.create(33, 0), + scfL = table.create(99, 0), + scfR = table.create(99, 0), + scfiL = table.create(33, 0), + scfiR = table.create(33, 0), + dscfL = table.create(33, false), + dscfR = table.create(33, false), + msf = table.create(33, false), + qL = table.create(32 * 36, 0), + qR = table.create(32 * 36, 0), + yL = table.create(36 * 32, 0), + yR = table.create(36 * 32, 0), + vL = table.create(2304 + 960, 0), + vR = table.create(2304 + 960, 0), + r1 = 1, + r2 = 1, + lastMaxBand = 0, + } + return st +end + +-- reset(st, scf): forget the history (before a seek); scf = the scalefactor indices to assume (libmpcdec: 0 at the +-- start of the stream, 0x01010101 in the middle of an SV7 stream). The noise generator restarts too, so a seek +-- decodes like libmpcdec seeking in a freshly opened stream. +function Decode.reset(st, scf) + for i = 1, 99 do + st.scfL[i] = scf + st.scfR[i] = scf + end + for i = 1, 33 do + st.resL[i], st.resR[i] = 0, 0 + st.dscfL[i], st.dscfR[i] = false, false + st.msf[i] = false + end + for i = 1, 2304 + 960 do + st.vL[i], st.vR[i] = 0, 0 + end + st.lastMaxBand = 0 + st.r1, st.r2 = 1, 1 +end + +local function noise(st, q, o) + local r1, r2 = st.r1, st.r2 + for k = 0, 35 do + local t1 = PARITY[band(r1, 0xF5) + 1] + local t2 = PARITY[band(rshift(r2, 25), 0x63) + 1] + r1 = bor(rshift(r1, 1), lshift(t1, 31)) + r2 = bor(band(lshift(r2, 1), 0xFFFFFFFF), t2) + local t = bxor(r1, r2) + q[o + k] = band(rshift(t, 24), 255) + band(rshift(t, 16), 255) + band(rshift(t, 8), 255) + band(t, 255) - 510 + end + st.r1, st.r2 = r1, r2 +end + +-- ------------------------------------------------------------------------------------------------ SV7 +-- mpc_decoder_read_bitstream_sv7 -> true | nil, message +local function readSv7(st, limit) +local resL, resR, msf = st.resL, st.resR, st.msf + local maxUsed = 0 + local ms = st.ms + resL[1] = bits(4) + resR[1] = bits(4) + if resL[1] ~= 0 or resR[1] ~= 0 then + if ms then + msf[1] = bits(1) == 1 + end + maxUsed = 1 + end + for n = 1, st.maxBand do + local idx = huff(HDR) + resL[n + 1] = (idx ~= 4 and((resL[n] + idx ))or((bits(4) +))) idx = huff(HDR) + resR[n + 1] = (idx ~= 4 and((resR[n] + idx ))or((bits(4) +))) local l, r = resL[n + 1], resR[n + 1] + if l < -1 or l > 17 or r < -1 or r > 17 then + return nil, "bad band resolution" + end + if l ~= 0 or r ~= 0 then + if ms then + msf[n + 1] = bits(1) == 1 + end + maxUsed = n + 1 + end + end + if resL[1] > 17 or resR[1] > 17 then + return nil, "bad band resolution" + end + -- SCFI + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + if resL[n] ~= 0 then + scfiL[n] = huff(SCFI7) + end + if resR[n] ~= 0 then + scfiR[n] = huff(SCFI7) + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = (c == 1 and{resL[n] }or{resR[n] +})[1] if res ~= 0 then + local scf = (c == 1 and{st.scfL }or{st.scfR +})[1] local scfi = (c == 1 and{scfiL[n] }or{scfiR[n] +})[1] local o = (n - 1) * 3 + local idx = huff(DSCF7) + local s0 = (idx ~= 8 and((scf[o + 3] + idx ))or((bits(6) +))) local s1, s2 + if scfi == 1 then + idx = huff(DSCF7) + s1 = (idx ~= 8 and((s0 + idx ))or((bits(6) +))) s2 = s1 + elseif scfi == 3 then + s1, s2 = s0, s0 + elseif scfi == 2 then + s1 = s0 + idx = huff(DSCF7) + s2 = (idx ~= 8 and((s1 + idx ))or((bits(6) +))) else + idx = huff(DSCF7) + s1 = (idx ~= 8 and((s0 + idx ))or((bits(6) +))) idx = huff(DSCF7) + s2 = (idx ~= 8 and((s1 + idx ))or((bits(6) +))) end + scf[o + 1] = s0 > 1024 and 0x8080 or s0 + scf[o + 2] = s1 > 1024 and 0x8080 or s1 + scf[o + 3] = s2 > 1024 and 0x8080 or s2 + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = (c == 1 and{resL[n] }or{resR[n] +})[1] local q = (c == 1 and{st.qL }or{st.qR +})[1] local o = (n - 1) * 36 + 1 + if res == -1 then + noise(st, q, o) + elseif res == 1 then + local tab = Q7[1][bits(1) + 1] + for k = 0, 35, 3 do + local idx = huff(tab) + q[o + k] = idx % 3 - 1 + q[o + k + 1] = (math.floor(idx / 3)) % 3 - 1 + q[o + k + 2] = math.floor(idx / 9 )- 1 + end + elseif res == 2 then + local tab = Q7[2][bits(1) + 1] + for k = 0, 35, 2 do + local idx = huff(tab) + q[o + k] = idx % 5 - 2 + q[o + k + 1] = math.floor(idx / 5 )- 2 + end + elseif res >= 3 and res <= 7 then + local tab = Q7[res][bits(1) + 1] + for k = 0, 35 do + q[o + k] = huff(tab) + end + elseif res >= 8 then + local nb, dc = RES_BIT[res], DC[res + 2] + for k = 0, 35 do + q[o + k] = bits(nb) - dc + end + end + if P > limit then + return nil, "truncated frame" + end + end + end + -- bands above maxUsed: silent + for n = maxUsed + 1, st.maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ SV8 +local function readSv8(st, key, limit) +local resL, resR, msf = st.resL, st.resR, st.msf + local maxBand = st.maxBand + local maxUsed + if key then + maxUsed = logDec(maxBand + 1) + else + maxUsed = st.lastMaxBand + huff(BANDS8) + if maxUsed > 32 then + maxUsed =maxUsed- 33 + end + end + if maxUsed > maxBand + 1 then + return nil, "bad band count" + end + st.lastMaxBand = maxUsed + if maxUsed > 0 then + local l, r = huff(RES8[1]), huff(RES8[1]) + resL[maxUsed] = (l > 15 and((l - 17 ))or(l +)) resR[maxUsed] = (r > 15 and((r - 17 ))or(r +)) for n = maxUsed - 1, 1, -1 do + l = huff(RES8[resL[n + 1] > 2 and 2 or 1]) + resL[n + 1] + resL[n] = (l > 15 and((l - 17 ))or(l +)) r = huff(RES8[resR[n + 1] > 2 and 2 or 1]) + resR[n + 1] + resR[n] = (r > 15 and((r - 17 ))or(r +)) end + if st.ms then + local tot = 0 + for n = 1, maxUsed do + if resL[n] ~= 0 or resR[n] ~= 0 then + tot =tot+ 1 + end + end + local cnt = logDec(tot) + local tmp = 0 + if cnt ~= 0 and cnt ~= tot then + tmp = enumDec(math.min(cnt, tot - cnt), tot) + end + if cnt * 2 > tot then + tmp = bnot(tmp) + end + for n = maxUsed, 1, -1 do + if resL[n] ~= 0 or resR[n] ~= 0 then + msf[n] = band(tmp, 1) == 1 + tmp = rshift(tmp, 1) + end + end + end + end + for n = maxUsed + 1, maxBand + 1 do + resL[n], resR[n] = 0, 0 + end + -- SCFI + local dscfL, dscfR = st.dscfL, st.dscfR + if key then + for n = 1, 32 do + dscfL[n], dscfR[n] = true, true + end + end + local scfiL, scfiR = st.scfiL, st.scfiR + for n = 1, maxUsed do + local cnt = -1 + if resL[n] ~= 0 then + cnt =cnt+ 1 + end + if resR[n] ~= 0 then + cnt =cnt+ 1 + end + if cnt >= 0 then + local tmp = huff(SCFI8[cnt + 1]) + if resL[n] ~= 0 then + scfiL[n] = rshift(tmp, 2 * cnt) + end + if resR[n] ~= 0 then + scfiR[n] = band(tmp, 3) + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- SCF / DSCF + for n = 1, maxUsed do + for c = 1, 2 do + local res = (c == 1 and{resL[n] }or{resR[n] +})[1] if res ~= 0 then + local scf = (c == 1 and{st.scfL }or{st.scfR +})[1] local scfi = (c == 1 and{scfiL[n] }or{scfiR[n] +})[1] local dscf = (c == 1 and{dscfL }or{dscfR +})[1] local o = (n - 1) * 3 + if dscf[n] then + scf[o + 1] = bits(7) - 6 + dscf[n] = false + else + local tmp = huff(DSCF8[2]) + if tmp == 64 then + tmp =tmp+ bits(6) + end + scf[o + 1] = band(scf[o + 3] - 25 + tmp, 127) - 6 + end + for m = 0, 1 do + if band(lshift(scfi, m), 2) == 0 then + local tmp = huff(DSCF8[1]) + if tmp == 31 then + tmp = 64 + bits(6) + end + scf[o + m + 2] = band(scf[o + m + 1] - 25 + tmp, 127) - 6 + else + scf[o + m + 2] = scf[o + m + 1] + end + end + end + end + end + if P > limit then + return nil, "truncated frame" + end + -- samples + for n = 1, maxUsed do + for c = 1, 2 do + local res = (c == 1 and{resL[n] }or{resR[n] +})[1] local q = (c == 1 and{st.qL }or{st.qR +})[1] local o = (n - 1) * 36 + 1 + if res == 2 then + local tabs = Q8[2] + local thres = 3 + local idx = 6 + for k = 0, 35, 3 do + local tmp = huff(tabs[idx > thres and 2 or 1]) + local a, b, cc = tmp % 5 - 2, (math.floor(tmp / 5)) % 5 - 2, math.floor(tmp / 25 )- 2 + q[o + k], q[o + k + 1], q[o + k + 2] = a, b, cc + idx = rshift(idx, 1) + abs(a) + abs(b) + abs(cc) + end + elseif res == 1 then + local k = 0 + while k < 36 do + local kmax = k + 18 + local cnt = huff(Q1_8) + local idx = 0 + if cnt > 0 and cnt < 18 then + idx = enumDec((cnt <= 9 and{cnt }or{(18 - cnt)})[1], 18) + end + if cnt > 9 then + idx = bnot(idx) + end + while k < kmax do + q[o + k] = 0 + if band(idx, 0x20000) ~= 0 then + q[o + k] = bits(1) * 2 - 1 + end + idx = lshift(idx, 1) + k =k+ 1 + end + end + elseif res == -1 then + noise(st, q, o) + elseif res == 3 or res == 4 then + local tab = Q34[res - 2] + for k = 0, 35, 2 do + local s = band(huff(tab), 255) + local s1, s2 = band(s, 15), rshift(s, 4) + q[o + k] = (s1 >= 8 and((s1 - 16 ))or(s1 +)) q[o + k + 1] = (s2 >= 8 and((s2 - 16 ))or(s2 +)) end + elseif res >= 5 and res <= 8 then + local tabs = Q8[res] + local thres = THRES[res] + local idx = 2 * thres + for k = 0, 35 do + local v = huff(tabs[idx > thres and 2 or 1]) + q[o + k] = v + idx = rshift(idx, 1) + abs(v) + end + elseif res >= 9 then + local sh = res - 9 + local dc = DC[res + 2] + for k = 0, 35 do + local v = band(huff(Q9UP), 255) + if sh > 0 then + v = v * 2 ^ sh + bits(sh) + end + q[o + k] = v - dc + end + elseif res < -1 then + return nil, "bad band resolution" + end + if P > limit then + return nil, "truncated frame" + end + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ requantisation +local function requant(st) + local resL, resR, msf = st.resL, st.resR, st.msf + local scfL, scfR, qL, qR, yL, yR = st.scfL, st.scfR, st.qL, st.qR, st.yL, st.yR + for b = 1, st.maxBand + 1 do + local rl, rr = resL[b], resR[b] + local ccl, ccr = CC[rl + 2] or 0, CC[rr + 2] or 0 + local ms = msf[b] + local o = (b - 1) * 36 + 1 + for part = 0, 2 do + local fl = (rl ~= 0 and{(f32(ccl * SCF[band(scfL[(b - 1) * 3 + part + 1], 255) + 1]) )}or{0 +})[1] local fr = (rr ~= 0 and{(f32(ccr * SCF[band(scfR[(b - 1) * 3 + part + 1], 255) + 1]) )}or{0 +})[1] local y = part * 12 * 32 + b + local qo = o + part * 12 + if ms then + for k = 0, 11 do + local l, r = fl * qL[qo + k], fr * qR[qo + k] + yL[y], yR[y] = l + r, l - r + y =y+ 32 + end + else + for k = 0, 11 do + yL[y], yR[y] = fl * qL[qo + k], fr * qR[qo + k] + y =y+ 32 + end + end + end + end +end + + +-- mpc_synthese_filter_float for one channel: 36 x 32 subband samples -> 1152 samples at out[base + i * step] +local function synth(V, Y, out, base, step) + table.move(V, 1, 960, 2305) + local o = 2304 + 1 + local dw = DW + local p = base + for n = 0, 35 do + o =o- 64 + newV(Y, n * 32 + 1, V, o) + for k = 0, 31 do + local v = o + k + local d = k * 16 + 1 + out[p] = V[v] * dw[d] + V[v + 96] * dw[d + 1] + V[v + 128] * dw[d + 2] + V[v + 224] * dw[d + 3] + + V[v + 256] * dw[d + 4] + V[v + 352] * dw[d + 5] + V[v + 384] * dw[d + 6] + V[v + 480] * dw[d + 7] + + V[v + 512] * dw[d + 8] + V[v + 608] * dw[d + 9] + V[v + 640] * dw[d + 10] + V[v + 736] * dw[d + 11] + + V[v + 768] * dw[d + 12] + V[v + 864] * dw[d + 13] + V[v + 896] * dw[d + 14] + V[v + 992] * dw[d + 15] + p =p+ step + end + end +end + +-- ------------------------------------------------------------------------------------------------ frames +-- frame(st, buf, bitPos, limitBits, key, out, base) -> the bit position after the frame | nil, message: decodes one +-- frame from buf (padded by PAD bytes past limitBits / 8) into out[base ..] (1152 * channels interleaved floats). +-- key: an SV8 key frame (the first of a block). bitPos < 0 decodes a silent frame (the synthesis tail). +function Decode.frame(st, buf, bitPos, limitBits, key, out, base) +if bitPos >= 0 then + if rshift(limitBits, 3) + Decode.PAD > buffer.len(buf) or bitPos > limitBits then + return nil, "truncated frame" + end + B, P = buf, bitPos + local ok, err + if st.version == 8 then + ok, err = readSv8(st, key, limitBits) + else + ok, err = readSv7(st, limitBits) + end + B = buffer.create(0) + if not ok then + return nil, err + end + else + for b = 1, st.maxBand + 1 do + st.resL[b], st.resR[b] = 0, 0 + end + end + local pos = P + requant(st) + local ch = st.channels + synth(st.vL, st.yL, out, base, ch) + if ch > 1 then + synth(st.vR, st.yR, out, base + 1, ch) + end + return (bitPos >= 0 and{pos }or{bitPos})[1], nil +end + +-- bitsAt(buf, bitPos, n) -> n (1 .. 24) bits at bitPos (frame headers: the SV7 frame size); the caller keeps +-- bitPos / 8 + 4 inside buf +function Decode.bitsAt(buf, bitPos, n) +local w = bswap(readu32(buf, rshift(bitPos, 3))) + return extract(w, 32 - band(bitPos, 7) - n, n) +end + +return Decode +end +__FILES["codecs/audio/Musepack/Tables"] = function() +local __compat = __compat local bit32 = __compat.bit32 --!strict +-- codecs/audio/Musepack/Tables: the Musepack SV7 / SV8 Huffman tables, the synthesis window and the requantisation +-- constants. Ported from libmpcdec (musepack_src_r475: huffman.c, synth_filter.c, requant.c, mpc_bits_reader.c; +-- BSD-3-Clause, (c) The Musepack Development Team, licenses/libmpcdec-BSD.txt); the tables are transcribed by script. +-- Each Huffman table is a flat { code, length, value, ... } list sorted by descending left-aligned 16-bit code; +-- canonical (SV8) tables map value - (code >> (16 - length)) through their symbol list. lut(table, sym?) builds the +-- 8-bit first-level lookup the decoder uses. +local T = {} + +T.HuffHdr = { + 32768, 1, 0, 24576, 3, 1, 24064, 7, -4, 23936, 9, 3, 23808, 9, 4, 23552, 8, -5, 22528, 6, 2, 20480, 5, -3, 16384, 4, -2, 0, 2, -1, +} +T.HuffSCFI = { + 32768, 1, 1, 24576, 3, 2, 16384, 3, 0, 0, 2, 3, +} +T.HuffDSCF = { + 63488, 5, 5, 61440, 5, -4, 57344, 4, 3, 53248, 4, -3, 49152, 4, 8, 40960, 3, 1, 36864, 4, 0, 34816, 5, -5, 33792, 6, 7, 32768, 6, -7, + 24576, 3, -1, 16384, 3, 2, 12288, 4, 4, 10240, 5, 6, 8192, 5, -6, 0, 3, -2, +} +T.HuffQ1_0 = { + 57344, 3, 13, 56320, 6, 26, 55296, 6, 0, 54272, 6, 20, 53248, 6, 6, 49152, 4, 14, 45056, 4, 12, 40960, 4, 4, 36864, 4, 22, 35840, 6, 8, + 34816, 6, 18, 33792, 6, 24, 32768, 6, 2, 28672, 4, 16, 24576, 4, 10, 22528, 5, 17, 20480, 5, 9, 18432, 5, 1, 16384, 5, 25, 14336, 5, 5, + 12288, 5, 21, 10240, 5, 3, 8192, 5, 11, 6144, 5, 15, 4096, 5, 23, 2048, 5, 19, 0, 5, 7, +} +T.HuffQ1_1 = { + 32768, 1, 13, 32256, 7, 15, 31744, 7, 1, 31232, 7, 11, 30720, 7, 7, 30208, 7, 17, 29696, 7, 25, 29184, 7, 19, 29056, 9, 8, 28928, 9, 18, + 28800, 9, 2, 28672, 9, 24, 28160, 7, 3, 27648, 7, 23, 27136, 7, 21, 26624, 7, 5, 26368, 8, 0, 26112, 8, 26, 25856, 8, 6, 25600, 8, 20, + 24576, 6, 9, 20480, 4, 14, 16384, 4, 12, 12288, 4, 4, 8192, 4, 22, 4096, 4, 16, 0, 4, 10, +} +T.HuffQ2_0 = { + 61440, 4, 13, 57344, 4, 17, 53248, 4, 7, 49152, 4, 11, 48128, 6, 1, 47104, 6, 23, 46592, 7, 4, 46080, 7, 20, 45568, 7, 0, 45056, 7, 24, + 43008, 5, 22, 40960, 5, 10, 32768, 3, 12, 30720, 5, 2, 28672, 5, 14, 24576, 4, 6, 20480, 4, 18, 16384, 4, 8, 12288, 4, 16, 10240, 5, 9, + 8192, 5, 5, 6144, 5, 15, 4096, 5, 21, 2048, 5, 19, 0, 5, 3, +} +T.HuffQ2_1 = { + 63488, 5, 18, 61440, 5, 6, 59392, 5, 8, 59136, 8, 3, 59072, 10, 24, 59008, 10, 4, 58944, 10, 0, 58880, 10, 20, 58368, 7, 23, 57856, 7, 1, + 57344, 7, 19, 55296, 5, 16, 54784, 7, 15, 54272, 7, 21, 53760, 7, 9, 53248, 7, 5, 52224, 6, 2, 51200, 6, 10, 50176, 6, 14, 49152, 6, 22, + 32768, 2, 12, 24576, 3, 13, 16384, 3, 17, 8192, 3, 11, 0, 3, 7, +} +T.HuffQ3_0 = { + 57344, 3, 1, 53248, 4, 3, 49152, 4, -3, 40960, 3, 2, 32768, 3, -2, 16384, 2, 0, 0, 2, -1, +} +T.HuffQ3_1 = { + 49152, 2, 0, 32768, 2, -1, 16384, 2, 1, 12288, 4, -2, 10240, 5, 3, 8192, 5, -3, 0, 3, 2, +} +T.HuffQ4_0 = { + 57344, 3, 0, 49152, 3, -1, 40960, 3, 1, 32768, 3, -2, 24576, 3, 2, 20480, 4, -4, 16384, 4, 4, 8192, 3, 3, 0, 3, -3, +} +T.HuffQ4_1 = { + 57344, 3, 1, 53248, 4, 2, 49152, 4, -3, 32768, 2, 0, 24576, 3, -2, 20480, 4, 3, 18432, 5, -4, 16384, 5, 4, 0, 2, -1, +} +T.HuffQ5_0 = { + 61440, 4, 2, 59392, 5, 5, 58368, 6, -7, 57344, 6, 7, 53248, 4, -3, 49152, 4, 3, 47104, 5, -6, 45056, 5, 6, 40960, 4, -4, 36864, 4, 4, + 32768, 4, -5, 24576, 3, 0, 16384, 3, -1, 8192, 3, 1, 0, 3, -2, +} +T.HuffQ5_1 = { + 61440, 4, 3, 59392, 5, 4, 58880, 7, 6, 58624, 8, -7, 58368, 8, 7, 57344, 6, -6, 49152, 3, 0, 40960, 3, -1, 32768, 3, 1, 24576, 3, -2, + 16384, 3, 2, 14336, 5, -5, 12288, 5, 5, 8192, 4, -4, 0, 3, -3, +} +T.HuffQ6_0 = { + 63488, 5, 3, 61440, 5, -4, 60416, 6, -11, 59392, 6, 12, 57344, 5, 4, 55296, 5, 6, 53248, 5, -5, 51200, 5, 5, 49152, 5, 7, 47104, 5, -7, + 46080, 6, -12, 45056, 6, -13, 43008, 5, -6, 40960, 5, 8, 38912, 5, -8, 36864, 5, 9, 34816, 5, -9, 33792, 6, 13, 33280, 7, -15, 32768, 7, 15, + 28672, 4, 0, 26624, 5, -10, 24576, 5, 10, 20480, 4, -1, 16384, 4, 2, 12288, 4, 1, 8192, 4, -2, 7168, 6, 14, 6144, 6, -14, 4096, 5, 11, + 0, 4, -3, +} +T.HuffQ6_1 = { + 63488, 5, -6, 61440, 5, 6, 57344, 4, 1, 53248, 4, -1, 52736, 7, 10, 52224, 7, -10, 51968, 8, -11, 51840, 9, -12, 51808, 11, 13, 51800, 13, 15, + 51792, 13, -14, 51784, 13, 14, 51776, 13, -15, 51712, 10, -13, 51456, 8, 11, 51200, 8, 12, 50176, 6, -9, 49152, 6, 9, 45056, 4, -2, 40960, 4, 2, + 36864, 4, 3, 32768, 4, -3, 30720, 5, -7, 28672, 5, 7, 24576, 4, -4, 20480, 4, 4, 18432, 5, -8, 16384, 5, 8, 12288, 4, 5, 8192, 4, -5, + 0, 3, 0, +} +T.HuffQ7_0 = { + 64512, 6, 7, 63488, 6, 8, 62464, 6, 9, 61440, 6, -8, 60416, 6, 11, 59904, 7, 21, 59648, 8, -28, 59392, 8, 28, 58368, 6, -9, 57856, 7, -22, + 57344, 7, -21, 56320, 6, -10, 55296, 6, -11, 54272, 6, 10, 53248, 6, 12, 52224, 6, -13, 51712, 7, 22, 51200, 7, 23, 50176, 6, -12, 49152, 6, 13, + 48128, 6, 14, 47104, 6, -14, 46592, 7, -23, 46336, 8, -29, 46080, 8, 29, 45056, 6, -15, 44032, 6, 15, 43008, 6, 16, 41984, 6, -16, 41472, 7, -24, + 40960, 7, 24, 39936, 6, 17, 39424, 7, -25, 39168, 8, -30, 38912, 8, 30, 37888, 6, -17, 36864, 6, 18, 35840, 6, -18, 35328, 7, 25, 34816, 7, 26, + 33792, 6, 19, 33280, 7, -26, 32768, 7, -27, 30720, 5, 2, 29696, 6, -19, 28672, 6, 20, 26624, 5, -1, 26368, 8, -31, 26112, 8, 31, 25600, 7, 27, + 24576, 6, -20, 22528, 5, 1, 20480, 5, -5, 18432, 5, -3, 16384, 5, 3, 14336, 5, 0, 12288, 5, -2, 10240, 5, -4, 8192, 5, 4, 6144, 5, 5, + 4096, 5, -6, 2048, 5, 6, 0, 5, -7, +} +T.HuffQ7_1 = { + 63488, 5, -1, 61440, 5, 2, 59392, 5, -2, 57344, 5, 3, 57088, 8, -20, 57024, 10, 24, 57020, 14, 28, 57016, 14, -28, 57012, 14, -30, 57008, 14, 30, + 56992, 12, -27, 56988, 14, 29, 56984, 14, -29, 56980, 14, 31, 56976, 14, -31, 56960, 12, 27, 56832, 9, -22, 56320, 7, -17, 55296, 6, -11, 53248, 5, -3, + 51200, 5, 4, 49152, 5, -4, 48640, 7, 17, 48384, 8, 20, 48256, 9, 22, 48192, 10, -25, 48128, 10, -26, 47104, 6, 12, 45056, 5, 5, 43008, 5, -5, + 40960, 5, 6, 38912, 5, -6, 37888, 6, -12, 37376, 7, -18, 36864, 7, 18, 35840, 6, 13, 34816, 6, -13, 32768, 5, -7, 31744, 6, 14, 31488, 8, 21, + 31232, 8, -21, 30720, 7, -19, 28672, 5, 7, 26624, 5, 8, 25600, 6, -14, 24576, 6, -15, 22528, 5, -8, 21504, 6, 15, 20992, 7, 19, 20928, 10, 25, + 20864, 10, 26, 20736, 9, -23, 20608, 9, 23, 20480, 9, -24, 18432, 5, -9, 16384, 5, 9, 15360, 6, 16, 14336, 6, -16, 12288, 5, 10, 8192, 4, 0, + 6144, 5, -10, 4096, 5, 11, 0, 4, 1, +} +T.H_SCFI_1 = { + 32768, 1, 1, 16384, 2, 2, 0, 3, 3, +} +T.H_SCFI_2 = { + 32768, 2, 3, 16384, 3, 5, 6144, 5, 11, 1024, 6, 14, 0, 7, 15, +} +T.H_DSCF_1 = { + 40960, 3, 7, 16384, 4, 12, 10240, 5, 16, 6144, 6, 21, 3584, 7, 27, 1792, 8, 34, 896, 9, 41, 320, 10, 48, 128, 11, 53, 48, 12, 57, + 24, 13, 60, 0, 14, 63, +} +T.H_DSCF_2 = { + 24576, 3, 7, 12288, 4, 10, 6144, 5, 13, 4096, 6, 16, 2560, 7, 20, 1536, 8, 25, 896, 9, 31, 448, 10, 38, 224, 11, 45, 80, 12, 52, + 32, 13, 57, 12, 14, 61, 0, 15, 64, +} +T.H_Bands = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 5, 6, 2048, 6, 8, 1536, 7, 10, 768, 8, 13, 512, 9, 16, 320, 10, 20, 192, 11, 25, + 16, 12, 31, 0, 13, 32, +} +T.H_Res_1 = { + 32768, 1, 1, 16384, 2, 2, 8192, 3, 3, 4096, 4, 4, 2048, 5, 5, 1024, 6, 6, 512, 7, 7, 256, 8, 8, 128, 9, 9, 64, 10, 10, + 32, 11, 11, 16, 12, 12, 8, 13, 13, 4, 14, 14, 2, 15, 15, 0, 16, 16, +} +T.H_Res_2 = { + 16384, 2, 3, 8192, 3, 4, 4096, 4, 5, 2048, 5, 6, 1024, 6, 7, 512, 7, 8, 256, 8, 9, 128, 9, 10, 64, 10, 11, 32, 11, 12, + 16, 12, 13, 0, 14, 16, +} +T.H_Q1 = { + 24576, 3, 7, 4096, 4, 10, 2048, 5, 11, 1024, 6, 12, 512, 7, 13, 256, 8, 14, 128, 9, 15, 64, 10, 16, 32, 11, 17, 0, 12, 18, +} +T.H_Q2_1 = { + 57344, 3, 7, 32768, 4, 14, 15360, 6, 38, 10752, 7, 53, 4608, 8, 74, 1536, 9, 92, 960, 10, 104, 96, 11, 119, 32, 12, 122, 0, 13, 124, +} +T.H_Q2_2 = { + 61440, 4, 15, 28672, 5, 30, 18432, 6, 44, 15360, 7, 62, 3072, 8, 92, 1920, 9, 104, 192, 10, 119, 64, 11, 122, 0, 12, 124, +} +T.H_Q3 = { + 57344, 3, 7, 32768, 4, 14, 20480, 5, 22, 9216, 6, 32, 2560, 7, 41, 512, 8, 46, 0, 9, 48, +} +T.H_Q4 = { + 61440, 4, 15, 36864, 5, 30, 13312, 6, 48, 6144, 7, 61, 1280, 8, 73, 256, 9, 78, 0, 10, 80, 0, 0, 90, +} +T.H_Q5_1 = { + 49152, 2, 3, 16384, 3, 6, 8192, 4, 8, 4096, 5, 10, 2048, 6, 12, 0, 7, 14, +} +T.H_Q5_2 = { + 24576, 3, 7, 8192, 4, 10, 4096, 5, 12, 0, 6, 14, +} +T.H_Q6_1 = { + 49152, 2, 3, 32768, 3, 6, 16384, 4, 10, 10240, 5, 14, 3072, 6, 19, 2048, 7, 22, 1024, 8, 26, 0, 9, 30, +} +T.H_Q6_2 = { + 20480, 4, 15, 8192, 5, 20, 4096, 6, 24, 1024, 7, 28, 0, 8, 30, +} +T.H_Q7_1 = { + 49152, 2, 3, 32768, 3, 6, 24576, 4, 10, 16384, 5, 16, 10240, 6, 24, 5120, 7, 34, 2560, 8, 44, 1024, 9, 54, 0, 10, 62, +} +T.H_Q7_2 = { + 24576, 5, 31, 9216, 6, 43, 4096, 7, 52, 512, 8, 60, 0, 9, 62, +} +T.H_Q8_1 = { + 49152, 2, 3, 32768, 3, 6, 28672, 4, 10, 22528, 5, 17, 14336, 6, 28, 10240, 7, 42, 6400, 8, 62, 3328, 9, 87, 640, 10, 113, 96, 11, 123, + 0, 12, 126, +} +T.H_Q8_2 = { + 38912, 6, 63, 10752, 7, 101, 1024, 8, 122, 0, 9, 126, +} +T.H_Q9up = { + 63488, 6, 63, 44032, 7, 125, 9728, 8, -45, 640, 9, -7, 64, 10, -2, 0, 11, -1, +} +T.S_SCFI_1 = { + 2, 3, 1, 0, +} +T.S_SCFI_2 = { + 15, 10, 14, 11, 13, 9, 7, 6, 5, 12, 8, 3, 2, 0, 4, 1, +} +T.S_DSCF_1 = { + 35, 34, 33, 36, 32, 30, 29, 27, 26, 37, 28, 25, 39, 38, 24, 23, 40, 22, 21, 20, 19, 43, 42, 41, 18, 17, 16, 15, 46, 45, 44, 14, + 13, 12, 11, 49, 48, 47, 31, 10, 9, 8, 7, 6, 52, 51, 50, 5, 4, 3, 54, 53, 2, 1, 0, 57, 56, 55, 63, 62, 61, 60, 59, 58, +} +T.S_DSCF_2 = { + 33, 32, 31, 30, 29, 34, 28, 27, 36, 35, 26, 37, 25, 38, 24, 23, 40, 39, 22, 21, 42, 41, 20, 19, 18, 45, 44, 43, 17, 16, 15, 14, + 48, 47, 46, 13, 12, 11, 10, 64, 52, 51, 50, 49, 9, 8, 7, 6, 55, 54, 53, 5, 4, 3, 58, 57, 56, 2, 1, 63, 62, 61, 60, 59, + 0, +} +T.S_Bands = { + 0, 32, 1, 31, 2, 30, 3, 4, 29, 6, 5, 28, 7, 27, 26, 8, 25, 24, 23, 9, 22, 21, 20, 18, 17, 16, 15, 14, 12, 11, 10, 19, + 13, +} +T.S_Res_1 = { + 0, 1, 16, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 11, 12, 14, 13, +} +T.S_Res_2 = { + 16, 1, 0, 2, 15, 3, 14, 4, 5, 13, 6, 12, 7, 11, 10, 9, 8, +} +T.S_Q1 = { + 7, 6, 5, 4, 3, 10, 9, 8, 2, 1, 11, 0, 12, 13, 14, 15, 16, 18, 17, +} +T.S_Q2_1 = { + 62, 87, 67, 63, 61, 57, 37, 93, 92, 88, 86, 83, 82, 81, 68, 66, 58, 56, 42, 41, 38, 36, 32, 31, 112, 91, 72, 64, 60, 52, 43, 33, + 12, 117, 113, 111, 107, 97, 89, 85, 77, 73, 71, 69, 65, 59, 55, 53, 51, 47, 39, 35, 27, 17, 13, 11, 7, 118, 116, 108, 106, 98, 96, 94, + 90, 84, 80, 78, 76, 48, 46, 44, 40, 34, 30, 28, 26, 18, 16, 8, 6, 122, 110, 102, 74, 70, 54, 50, 22, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 14, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q2_2 = { + 62, 92, 87, 86, 82, 68, 67, 66, 63, 61, 58, 57, 56, 42, 38, 37, 32, 93, 91, 88, 83, 81, 43, 41, 36, 33, 31, 112, 72, 64, 60, 52, + 12, 118, 117, 116, 113, 111, 108, 107, 106, 98, 97, 96, 94, 90, 89, 85, 84, 80, 78, 77, 76, 73, 71, 69, 65, 59, 55, 53, 51, 48, 47, 46, + 44, 40, 39, 35, 34, 30, 28, 27, 26, 18, 17, 16, 13, 11, 8, 7, 6, 122, 110, 74, 70, 54, 50, 22, 14, 2, 123, 121, 119, 115, 114, 109, + 105, 103, 102, 101, 99, 95, 79, 75, 49, 45, 29, 25, 23, 21, 19, 15, 10, 9, 5, 3, 1, 124, 104, 20, 0, 120, 100, 24, 4, +} +T.S_Q3 = { + 0, 17, 16, 1, 15, -16, -1, 32, 31, 2, 14, -15, -32, 34, 33, 47, 46, 18, 30, -14, -2, -31, -17, -18, 49, 48, 63, 19, 29, 3, 13, -13, + -3, -30, -47, -48, -33, 50, 62, 35, 45, -29, -19, -46, -34, 51, 61, -45, -35, +} +T.S_Q4 = { + 0, 32, 17, 16, 31, 2, 1, 15, 14, -15, -16, -1, -32, 49, 48, 34, 33, 47, 46, 19, 18, 30, 29, 3, 13, -13, -14, -2, -3, -30, -31, -17, + -18, -47, -48, -33, 64, 50, 63, 62, 35, 45, 4, 12, -29, -19, -46, -34, -64, -49, 66, 65, 79, 78, 51, 61, 36, 44, 20, 28, -12, -4, -28, -20, + -45, -35, -62, -63, -50, 67, 77, 52, 60, -44, -36, -61, -51, 68, 76, -60, -52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +} +T.S_Q5_1 = { + 0, 2, 1, -1, -2, 3, -3, 4, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q5_2 = { + 2, 1, 0, -1, -2, 4, 3, -3, -4, 5, -5, 7, 6, -6, -7, +} +T.S_Q6_1 = { + 0, 1, -1, 3, 2, -2, -3, 4, -4, -5, 8, 7, 6, 5, -6, -7, -8, 9, -9, 11, 10, -10, -11, 15, 14, 13, 12, -12, -13, -14, -15, +} +T.S_Q6_2 = { + 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 8, 7, 6, -6, -7, -8, 10, 9, -9, -10, 13, 12, 11, -11, -12, -13, 15, 14, -14, -15, +} +T.S_Q7_1 = { + 0, 1, -1, 2, -2, 4, 3, -3, -4, 7, 6, 5, -5, -6, -7, 13, 11, 10, 9, 8, -8, -9, -10, -11, -12, 17, 16, 15, 14, 12, -13, -14, + -15, -16, -17, 28, 27, 21, 20, 19, 18, -18, -19, -20, -21, -27, -28, 31, 30, 29, 26, 25, 24, 23, 22, -22, -23, -24, -25, -26, -29, -30, -31, +} +T.S_Q7_2 = { + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 17, 16, 15, 14, 13, 12, 11, -10, -11, -12, -13, -14, + -15, -16, -17, 22, 21, 20, 19, 18, -18, -19, -20, -21, -22, 29, 28, 27, 26, 25, 24, 23, -23, -24, -25, -26, -27, -28, -29, 31, 30, -30, -31, +} +T.S_Q8_1 = { + 0, 1, -1, -2, 3, 2, -3, 7, 6, 5, 4, -4, -5, -6, -7, 11, 10, 9, 8, -8, -9, -10, -11, 19, 18, 17, 16, 15, 14, 13, 12, -12, + -13, -14, -15, -16, -17, -19, 56, 55, 31, 28, 27, 26, 25, 24, 23, 22, 21, 20, -18, -20, -21, -22, -23, -24, -25, -26, -27, -33, -54, -56, 63, 62, + 61, 60, 59, 58, 57, 54, 53, 43, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, -28, -29, -30, -31, -32, -34, -35, -36, -37, -38, -39, -40, -41, + -43, -53, -55, -57, -58, -59, -60, -61, 49, 47, 46, 45, 44, 42, 41, -42, -44, -45, -46, -47, -48, -49, -50, -62, -63, 52, 51, 50, 48, -51, -52, +} +T.S_Q8_2 = { + 13, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 12, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, + 44, 43, 42, 41, 40, -42, -43, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, 63, 62, 61, 60, -60, -61, -62, -63, +} +T.S_Q9up = { + -128, 127, -108, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, + 115, 114, 113, 112, 111, 110, 109, 108, -44, -45, -46, -47, -48, -49, -50, -51, -52, -53, -54, -55, -56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, + -68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, -80, -81, -82, -83, -84, -85, -86, -87, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, + -100, -101, -102, -103, -104, -105, -106, -107, -109, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, + 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, + 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 40, 20, 19, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, + -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, -43, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 25, 24, 23, 22, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, -3, -4, -5, -6, 4, 3, 2, 1, 0, -1, -2, +} + +-- Di_opt[32][16] (times 65536) +T.DI = { + 0, -29, 213, -459, 2037, -5153, 6574, -37489, 75038, 37489, 6574, 5153, 2037, 459, 213, 29, + -1, -31, 218, -519, 2000, -5517, 5959, -39336, 74992, 35640, 7134, 4788, 2063, 401, 208, 26, + -1, -35, 222, -581, 1952, -5879, 5288, -41176, 74856, 33791, 7640, 4425, 2080, 347, 202, 24, + -1, -38, 225, -645, 1893, -6237, 4561, -43006, 74630, 31947, 8092, 4063, 2087, 294, 196, 21, + -1, -41, 227, -711, 1822, -6589, 3776, -44821, 74313, 30112, 8492, 3705, 2085, 244, 190, 19, + -1, -45, 228, -779, 1739, -6935, 2935, -46617, 73908, 28289, 8840, 3351, 2075, 197, 183, 17, + -1, -49, 228, -848, 1644, -7271, 2037, -48390, 73415, 26482, 9139, 3004, 2057, 153, 176, 16, + -2, -53, 227, -919, 1535, -7597, 1082, -50137, 72835, 24694, 9389, 2663, 2032, 111, 169, 14, + -2, -58, 224, -991, 1414, -7910, 70, -51853, 72169, 22929, 9592, 2330, 2001, 72, 161, 13, + -2, -63, 221, -1064, 1280, -8209, -998, -53534, 71420, 21189, 9750, 2006, 1962, 36, 154, 11, + -2, -68, 215, -1137, 1131, -8491, -2122, -55178, 70590, 19478, 9863, 1692, 1919, 2, 147, 10, + -3, -73, 208, -1210, 970, -8755, -3300, -56778, 69679, 17799, 9935, 1388, 1870, -29, 139, 9, + -3, -79, 200, -1283, 794, -8998, -4533, -58333, 68692, 16155, 9966, 1095, 1817, -57, 132, 8, + -4, -85, 189, -1356, 605, -9219, -5818, -59838, 67629, 14548, 9959, 814, 1759, -83, 125, 7, + -4, -91, 177, -1428, 402, -9416, -7154, -61289, 66494, 12980, 9916, 545, 1698, -106, 117, 7, + -5, -97, 163, -1498, 185, -9585, -8540, -62684, 65290, 11455, 9838, 288, 1634, -127, 111, 6, + -5, -104, 146, -1567, -45, -9727, -9975, -64019, 64019, 9975, 9727, 45, 1567, -146, 104, 5, + -6, -111, 127, -1634, -288, -9838, -11455, -65290, 62684, 8540, 9585, -185, 1498, -163, 97, 5, + -7, -117, 106, -1698, -545, -9916, -12980, -66494, 61289, 7154, 9416, -402, 1428, -177, 91, 4, + -7, -125, 83, -1759, -814, -9959, -14548, -67629, 59838, 5818, 9219, -605, 1356, -189, 85, 4, + -8, -132, 57, -1817, -1095, -9966, -16155, -68692, 58333, 4533, 8998, -794, 1283, -200, 79, 3, + -9, -139, 29, -1870, -1388, -9935, -17799, -69679, 56778, 3300, 8755, -970, 1210, -208, 73, 3, + -10, -147, -2, -1919, -1692, -9863, -19478, -70590, 55178, 2122, 8491, -1131, 1137, -215, 68, 2, + -11, -154, -36, -1962, -2006, -9750, -21189, -71420, 53534, 998, 8209, -1280, 1064, -221, 63, 2, + -13, -161, -72, -2001, -2330, -9592, -22929, -72169, 51853, -70, 7910, -1414, 991, -224, 58, 2, + -14, -169, -111, -2032, -2663, -9389, -24694, -72835, 50137, -1082, 7597, -1535, 919, -227, 53, 2, + -16, -176, -153, -2057, -3004, -9139, -26482, -73415, 48390, -2037, 7271, -1644, 848, -228, 49, 1, + -17, -183, -197, -2075, -3351, -8840, -28289, -73908, 46617, -2935, 6935, -1739, 779, -228, 45, 1, + -19, -190, -244, -2085, -3705, -8492, -30112, -74313, 44821, -3776, 6589, -1822, 711, -227, 41, 1, + -21, -196, -294, -2087, -4063, -8092, -31947, -74630, 43006, -4561, 6237, -1893, 645, -225, 38, 1, + -24, -202, -347, -2080, -4425, -7640, -33791, -74856, 41176, -5288, 5879, -1952, 581, -222, 35, 1, + -26, -208, -401, -2063, -4788, -7134, -35640, -74992, 39336, -5959, 5517, -2000, 519, -218, 31, 1, +} + +-- requantisation: Cc[res] = 65536 / steps (res -1 .. 17, stored at res + 2), Dc[res] = (steps - 1) / 2, bits per +-- sample of the plain quantisers (res 8 .. 17) +T.CC = { + 111.285962475327, 65536.000000000000, 21845.333333333332, 13107.200000000001, 9362.285714285713, + 7281.777777777777, 4369.066666666666, 2114.064516129032, 1040.253968253968, 516.031496062992, 257.003921568627, + 128.250489236790, 64.062561094819, 32.015632633121, 16.003907203907, 8.000976681723, 4.000244155527, + 2.000061037018, 1.000015259021, +} +T.DC = { 2, 0, 1, 2, 3, 4, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767 } +T.RES_BIT = { [8] = 7, [9] = 8, [10] = 9, [11] = 10, [12] = 11, [13] = 12, [14] = 13, [15] = 14, [16] = 15, [17] = 16 } + +-- log_dec(max): ceil(log2(max + 2)) bits and the unused codes (index max + 1, max = 0 .. 31) +T.LOG2 = { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 } +T.LOG2_LOST = { 0, 1, 0, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 31 } + +-- enum_dec: CNK[k][n + 1] = C(n, k) (k = 1 .. 16, n = 0 .. 31), the code length ceil(log2 C(n, k)) and the unused +-- codes 2^len - C(n, k) (computed: libmpcdec's tables, whose last entry is 0) +T.CNK, T.CNK_LEN, T.CNK_LOST = {}, {}, {} +do + for k = 1, 16 do + local c, l, lost = table.create(32, 0), table.create(32, 0), table.create(32, 0) + for n = 0, 32 do + local v = 0 + if n >= k then + v = 1 + for i = 1, k do + v = v * (n - k + i) / i + end + v = math.floor(v + 0.5) + end + if n <= 31 then + c[n + 1] = v + end + if n >= 1 then + local bits = 0 + while 2 ^ bits < v do + bits =bits+ 1 + end + l[n] = bits + lost[n] = (v > 0 and((2 ^ bits - v ))or(0 +)) end + end + T.CNK[k], T.CNK_LEN[k], T.CNK_LOST[k] = c, l, lost + end + T.CNK_LOST[16][32] = 0 +end + +-- lut(table, sym?) -> Lut + + + + + + + + + +function T.lut(tab, sym) +local codes, lens, vals = {}, {}, {} + for i = 1, #tab, 3 do + table.insert(codes, tab[i]) + table.insert(lens, tab[i + 1]) + table.insert(vals, tab[i + 2]) + end + local function find(code) +local j = 1 + while code < codes[j] do + j =j+ 1 + end + return j + end + local function symbol(j, code) +if sym then + local idx = bit32.band(vals[j] - bit32.rshift(code, 16 - lens[j]), 255) + return sym[idx + 1] or 0 + end + return vals[j] + end + local len, val = table.create(256, 0), table.create(256, 0) + for p = 0, 255 do + local lo, hi = find(p * 256), find(p * 256 + 255) + if lo == hi and lens[lo] <= 8 then + len[p + 1] = lens[lo] + val[p + 1] = symbol(lo, p * 256) + else + len[p + 1] = 0 + val[p + 1] = hi + end + end + return { len = len, val = val, codes = codes, lens = lens, vals = vals, sym = sym } +end + +return T +end +__FILES["codecs/audio/Opus"] = function() +--!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 = __include("codecs/audio/Opus/Packet"), + Decoder = __include("codecs/audio/Opus/Decoder"), + Celt = __include("codecs/audio/Opus/Celt"), + Silk = __include("codecs/audio/Opus/Silk"), + CeltEncoder = __include("codecs/audio/Opus/CeltEncoder"), +} + +return Opus +end +__FILES["codecs/audio/Opus/Celt"] = function() +local __compat = __compat local bit32 = __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local Mdct = __include("codecs/audio/Opus/Mdct") +local T = __include("codecs/audio/Opus/CeltTables") + +local Celt = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, exp, cos = math.min, math.max, math.sqrt, math.floor, math.exp, math.cos +local decBitLogp, decIcdf, decBits, decUint = RD.bitLogp, RD.icdf, RD.bits, RD.uint +local decDecode, decDecodeBin, decUpdate = RD.decode, RD.decodeBin, RD.update +local tell, tellFrac = RD.tell, RD.tellFrac + +local NB_EBANDS = 21 +local EFF_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local MAX_LM = 3 +local DECODE_BUFFER_SIZE = 2048 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local QTHETA_OFFSET_TWOPHASE = 16 +local SPREAD_AGGRESSIVE = 3 +local PREEMPH = 0.85000610 +local COMBFILTER_MINPERIOD = 15 +local FRAME_NONE, FRAME_NORMAL, FRAME_PLC_NOISE = 0, 1, 2 + +-- eBands (1-based: EB[i + 1] is eBands[i]) +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, 3.750000, 3.750000, 3.750000, 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { -- [LM][4 * isTransient + 2 * tf_select + flag] + { 0, -1, 0, -1, 0, -1, 0, -1 }, + { 0, -1, 0, -2, 1, 0, 1, -1 }, + { 0, -2, 0, -3, 2, 0, 1, -1 }, + { 0, -2, 0, -3, 3, 0, 1, -1 }, +} +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local TAPSET_ICDF = { 2, 1, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local ORDERY = { 1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5 } +local BIT_INTERLEAVE = { 0, 1, 1, 1, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3 } +local BIT_DEINTERLEAVE = { 0x00, 0x03, 0x0C, 0x0F, 0x30, 0x33, 0x3C, 0x3F, 0xC0, 0xC3, 0xCC, 0xCF, 0xF0, 0xF3, 0xFC, 0xFF } +local COMB_GAINS = { + { 0.3066406250, 0.2170410156, 0.1296386719 }, + { 0.4638671875, 0.2680664062, 0.0 }, + { 0.7998046875, 0.1000976562, 0.0 }, +} + +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +Celt.window = WINDOW + +-- PVQ codebook sizes U(n, k) (cwrs.c), flat: U[n * UK + k + 1], n, k in 0 .. 176 +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end + +-- shared workspace (decoding is not re-entrant) +local NORM_BASE = 1920 +local W = table.create(4096, 0) +local TMP = table.create(256, 0) +local IY = table.create(256, 0) +local FREQ = table.create(960, 0) +local FREQ2 = table.create(960, 0) +local COLLAPSE = table.create(42, 0) +local TF_RES = table.create(21, 0) +local CAP = table.create(21, 0) +local OFFSETS = table.create(21, 0) +local FINE_QUANT = table.create(21, 0) +local PULSES = table.create(21, 0) +local FINE_PRIORITY = table.create(21, 0) +local BITS1 = table.create(21, 0) +local BITS2 = table.create(21, 0) +local THRESH = table.create(21, 0) +local TRIM_OFFSET = table.create(21, 0) + +local function imin(a, b) +return (a < b and{a }or{b +})[1]end +local function imax(a, b) +return (a > b and{a }or{b +})[1]end +-- C integer division (truncates toward zero) +local function tdiv(a, b) +local q = a / b + return (q >= 0 and{(floor(q) )}or{(-floor(-q) +)})[1]end + +local function exp2(x) +return exp(0.6931471805599453094 * x) +end + +local function lcg(seed) +return (1664525 * seed + 1013904223) % 4294967296 +end + +local function signed32(x) +return (x >= 2147483648 and((x - 4294967296 ))or(x +))end + +local function fracMul16(a, b) +return math.floor((16384 + a * b) / 32768 +)end + +local function bitexactCos(x) +local tmp = math.floor((4096 + x * x) / 8192 +) local x2 = tmp + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end + +local function bitexactLog2tan(isin, icos) +local lc = RD.ilog(icos) + local ls = RD.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- --------------------------------------------------------------------------------------------------------------- +-- energy (quant_bands.c, laplace.c) + +local function laplaceDecode(dec, fs, decay) +local val = 0 + local fm = decDecodeBin(dec, 15) + local fl = 0 + if fm >= fs then + val =val+ 1 + fl = fs + fs = math.floor(((32768 - 32 - fs) * (16384 - decay)) / 32768 )+ 1 + while fs > 1 and fm >= fl + 2 * fs do + fs =fs* 2 + fl =fl+ fs + fs = math.floor(((fs - 2) * decay) / 32768 +) fs =fs+ 1 + val =val+ 1 + end + if fs <= 1 then + local di = rshift(fm - fl, 1) + val =val+ di + fl =fl+ 2 * di + end + if fm < fl + fs then + val = -val + else + fl =fl+ fs + end + end + decUpdate(dec, fl, imin(fl + fs, 32768), 32768) + return val +end + +local function unquantCoarseEnergy(st, start, endb, intra, dec, C, LM) + local oldE = st.oldBandE + local probBase = LM * 84 + (intra and 42 or 0) -- e_prob_model[LM][intra], 0-based + local coef, beta + if intra then + coef = 0 + beta = BETA_INTRA + else + beta = BETA_COEF[LM + 1] + coef = PRED_COEF[LM + 1] + end + local prev0, prev1 = 0, 0 + local budget = dec.storage * 8 + for i = start, endb - 1 do + for c = 0, C - 1 do + local t = tell(dec) + local qi + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceDecode(dec, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = decIcdf(dec, SMALL_ENERGY_ICDF, 1, 2) + qi = (band(qi, 1) ~= 0 and{(-rshift(qi, 1) - 1 )}or{(rshift(qi, 1) +)})[1] elseif budget - t >= 1 then + qi = decBitLogp(dec, 1) and-1 or 0 + else + qi = -1 + end + local q = qi + local k = i + c * NB_EBANDS + 1 + local e = max(-9, oldE[k]) + local prev = (c == 0 and{prev0 }or{prev1 +})[1] oldE[k] = coef * e + prev + q + prev = prev + q - beta * q + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function unquantFineEnergy(st, start, endb, fineQuant, dec, C) + local oldE = st.oldBandE + for i = start, endb - 1 do +local __DARKLUA_CONTINUE_7=false repeat local extra = fineQuant[i + 1] + if extra <= 0 then +__DARKLUA_CONTINUE_7=true break + end + if tell(dec) + C * extra > dec.storage * 8 then +__DARKLUA_CONTINUE_7=true break + end + for c = 0, C - 1 do + local q2 = decBits(dec, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 +do local __DARKLUA_VAR=i + c * NB_EBANDS + 1 oldE[__DARKLUA_VAR]=oldE[__DARKLUA_VAR]+ offset +end end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end +end + +local function unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, bitsLeft, dec, C) + local oldE = st.oldBandE + for prio = 0, 1 do + local i = start + while i < endb and bitsLeft >= C do +local __DARKLUA_CONTINUE_10=false repeat if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i =i+ 1 +__DARKLUA_CONTINUE_10=true break + end + for c = 0, C - 1 do + local q2 = decBits(dec, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) +do local __DARKLUA_VAR=i + c * NB_EBANDS + 1 oldE[__DARKLUA_VAR]=oldE[__DARKLUA_VAR]+ offset +end bitsLeft =bitsLeft- 1 + end + i =i+ 1 +__DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- bit allocation (rate.c) + +local function bits2pulses(bandI, LM, bits) +local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits =bits- 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = lo == 0 and-1 or CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI, LM, pulses) +if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i) +if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation + interp_bits2pulses (decoder side). Returns codedBands, balance, intensity, dualStereo. +local function computeAllocation(start, endb, offsets, cap, allocTrim, + total, pulses, ebits, finePriority, C, LM, ec) + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = total >= 8 and 8 or 0 + total =total- skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total =total- intensityRsv + dualStereoRsv = total >= 8 and 8 or 0 + total =total- dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = BITS1, BITS2, THRESH, TRIM_OFFSET + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, math.floor((3 * w * 2 ^ LM * 8) / 16)) + trimOffset[j + 1] = math.floor((C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) / 64 +) if w * 2 ^ LM == 1 then +do local __DARKLUA_VAR=j + 1 trimOffset[__DARKLUA_VAR]=trimOffset[__DARKLUA_VAR]- C * 8 +end end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local N = EB[j + 2] - EB[j + 1] + local bitsj = math.floor((C * N * ALLOC[mid * len + j + 1] * 2 ^ LM) / 4 +) if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj =bitsj+ offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum =psum+ imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum =psum+ C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo =lo- 1 + for j = start, endb - 1 do + local N = EB[j + 2] - EB[j + 1] + local bits1j = math.floor((C * N * ALLOC[lo * len + j + 1] * 2 ^ LM) / 4 +) local bits2j = (hi >= NB_ALLOC_VECTORS and{cap[j + 1] }or{(math.floor((C * N * ALLOC[hi * len + j + 1] * 2 ^ LM) / 4 +))})[1] if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j =bits1j+ offsets[j + 1] + end + bits2j =bits2j+ offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = C > 1 and 1 or 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + math.floor((mid * bits2[j + 1]) / 64 +) if tmp >= thresh[j + 1] or done then + done = true + psum =psum+ imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum =psum+ allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + math.floor((lo * bits2[j + 1]) / 64 +) if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum =psum+ tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total =total+ skipRsv + break + end + local left = total - psum + local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) +) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + if decBitLogp(ec, 1) then + break + end + psum =psum+ 8 + bandBits =bandBits- 8 + end + psum =psum- (bits[j + 1] + intensityRsv +) if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum =psum+ intensityRsv + if bandBits >= allocFloor then + psum =psum+ allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands =codedBands- 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = start + decUint(ec, codedBands + 1 - start) + end + if intensity <= start then + total =total+ dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = decBitLogp(ec, 1) + end + local left = total - psum + local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) +) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ percoeff * (EB[j + 2] - EB[j + 1]) +end end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ tmp +end left =left- tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local N = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if N > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * N + (C == 2 and N > 2 and not dualStereo and j < intensity and 1 or 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (math.floor(NClogN / 2)) - den * FINE_OFFSET + if N == 2 then + offset =offset+ math.floor((den * 8) / 4 +) end + if bits[j + 1] + offset < den * 2 * 8 then + offset =offset+ math.floor(NClogN / 4 +) elseif bits[j + 1] + offset < den * 3 * 8 then + offset =offset+ math.floor(NClogN / 8 +) end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = math.floor((math.floor(eb / den)) / 8 +) if C * eb > (math.floor(bits[j + 1] / 8)) then + eb = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 +) end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = eb * (den * 8) >= bits[j + 1] + offset and 1 or 0 +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]- C * eb * 8 +end ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(math.floor(excess / 2 ^ (stereo + BITRES)), MAX_FINE_BITS - ebits[j + 1]) +do local __DARKLUA_VAR=j + 1 ebits[__DARKLUA_VAR]=ebits[__DARKLUA_VAR]+ extraFine +end local extraBits = extraFine * C * 8 + finePriority[j + 1] = extraBits >= excess - balance and 1 or 0 + excess =excess- extraBits + end + balance = excess + j =j+ 1 + end + while j < endb do + ebits[j + 1] = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 +) bits[j + 1] = 0 + finePriority[j + 1] = ebits[j + 1] < 1 and 1 or 0 + j =j+ 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- --------------------------------------------------------------------------------------------------------------- +-- PVQ (cwrs.c, vq.c) + +local function cwrsi(n, k, i, iy) +local yy = 0 + local idx = 1 + local p, k0, val + while n > 2 do + if k >= n then + local rowBase = n * UK + 1 + p = U[rowBase + k + 1] + local neg = i >= p + if neg then + i =i- p + end + k0 = k + local q = U[rowBase + n] + if q > i then + k = n + repeat + k =k- 1 + p = U[k * UK + n + 1] + until p <= i + else + p = U[rowBase + k] + while p > i do + k =k- 1 + p = U[rowBase + k] + end + end + i =i- p + val = (neg and((k - k0 ))or((k0 - k +))) iy[idx] = val + idx =idx+ 1 + yy =yy+ val * val + else + p = U[k * UK + n + 1] + local q = U[(k + 1) * UK + n + 1] + if p <= i and i < q then + i =i- p + iy[idx] = 0 + idx =idx+ 1 + else + local neg = i >= q + if neg then + i =i- q + end + k0 = k + repeat + k =k- 1 + p = U[k * UK + n + 1] + until p <= i + i =i- p + val = (neg and((k - k0 ))or((k0 - k +))) iy[idx] = val + idx =idx+ 1 + yy =yy+ val * val + end + end + n =n- 1 + end + -- n == 2 + p = 2 * k + 1 + local neg = i >= p + if neg then + i =i- p + end + k0 = k + k = rshift(i + 1, 1) + if k ~= 0 then + i =i- (2 * k - 1 +) end + val = (neg and((k - k0 ))or((k0 - k +))) iy[idx] = val + yy =yy+ val * val + -- n == 1 + val = (i ~= 0 and{(-k )}or{k +})[1] iy[idx + 1] = val + yy =yy+ val * val + return yy +end + +local function expRotation1(X, len, stride, c, s) + local ms = -s + local p = X + 1 + for _ = 0, len - stride - 1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p =p+ 1 + end + p = X + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = W[p] + local x2 = W[p + stride] + W[p + stride] = c * x2 + s * x1 + W[p] = c * x1 + ms * x2 + p =p- 1 + end +end + +local SPREAD_FACTOR = { 15, 10, 5 } +local function expRotation(X, len, dir, stride, K, spread) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 =stride2+ 1 + end + end + len = math.floor(len / stride +) for i = 0, stride - 1 do + local x = X + i * len + if dir < 0 then + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, c) + end + expRotation1(x, len, 1, c, s) + else + expRotation1(x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(x, len, stride2, s, -c) + end + end + end +end + +local function renormaliseVector(X, N, gain) + local E = 1e-15 + for i = X + 1, X + N do + local v = W[i] + E =E+ v * v + end + local g = gain / sqrt(E) + for i = X + 1, X + N do + W[i]=W[i]* g + end +end + +local function algUnquant(X, N, K, spread, B, dec, gain) +local iy = IY + local ft = U[N * UK + K + 1] + U[N * UK + K + 2] + local Ryy = cwrsi(N, K, decUint(dec, ft), iy) + local g = gain / sqrt(Ryy) + for i = 1, N do + W[X + i] = iy[i] * g + end + expRotation(X, N, -1, B, K, spread) + if B <= 1 then + return 1 + end + local N0 = math.floor(N / B +) local mask = 0 + for i = 0, B - 1 do + for j = 1, N0 do + if iy[i * N0 + j] ~= 0 then + mask = bor(mask, lshift(1, i)) + break + end + end + end + return mask +end +-- --------------------------------------------------------------------------------------------------------------- +-- bands (bands.c) + + + + + + + + + + + + + +local ctx= { + i = 0, + intensity = 0, + spread = 0, + tf_change = 0, + ec = (nil ), + remaining_bits = 0, + seed = 0, + disable_inv = false, + avoid_split_noise = false, +} + +local function haar1(X, N0, stride) + N0 = rshift(N0, 1) + local s = 0.70710678 + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + local a = X + stride * 2 * j + i + 1 + local b = a + stride + local t1 = s * W[a] + local t2 = s * W[b] + W[a] = t1 + t2 + W[b] = t1 - t2 + end + end +end + +local function deinterleaveHadamard(X, N0, stride, hadamard) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[o + j + 1] = W[X + j * stride + i + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[i * N0 + j + 1] = W[X + j * stride + i + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function interleaveHadamard(X, N0, stride, hadamard) + local N = N0 * stride + local tmp = TMP + if hadamard then + local ob = stride - 2 + for i = 0, stride - 1 do + local o = ORDERY[ob + i + 1] * N0 + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + o + j + 1] + end + end + else + for i = 0, stride - 1 do + for j = 0, N0 - 1 do + tmp[j * stride + i + 1] = W[X + i * N0 + j + 1] + end + end + end + for k = 1, N do + W[X + k] = tmp[k] + end +end + +local function computeQn(N, b, offset, pulseCap, stereo) +local N2 = 2 * N - 1 + if stereo and N == 2 then + N2 =N2- 1 + end + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- returns b, fill, inv, imid, iside, delta, itheta, qalloc +local function computeTheta(N, b, B, B0, LM, stereo, fill) + local i = ctx.i + local ec = ctx.ec + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (math.floor(pulseCap / 2)) - ((stereo and N == 2 and{QTHETA_OFFSET_TWOPHASE }or{QTHETA_OFFSET})[1]) + local qn = computeQn(N, b, offset, pulseCap, stereo) + if stereo and i >= ctx.intensity then + qn = 1 + end + local t0 = tellFrac(ec) + local itheta = 0 + local inv = false + if qn ~= 1 then + if stereo and N > 2 then + local p0 = 3 + local x0 = math.floor(qn / 2 +) local ft = p0 * (x0 + 1) + x0 + local fs = decDecode(ec, ft) + local x + if fs < (x0 + 1) * p0 then + x = math.floor(fs / p0 +) else + x = x0 + 1 + (fs - (x0 + 1) * p0) + end + if x <= x0 then + decUpdate(ec, p0 * x, p0 * (x + 1), ft) + else + decUpdate(ec, (x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0, ft) + end + itheta = x + elseif B0 > 1 or stereo then + itheta = decUint(ec, qn + 1) + else + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fm = decDecode(ec, ft) + local fs, fl + if fm < rshift(h * (h + 1), 1) then + itheta = rshift(floor(sqrt(8 * fm + 1)) - 1, 1) + fs = itheta + 1 + fl = rshift(itheta * (itheta + 1), 1) + else + itheta = rshift(2 * (qn + 1) - floor(sqrt(8 * (ft - fm - 1) + 1)), 1) + fs = qn + 1 - itheta + fl = ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + end + decUpdate(ec, fl, fl + fs, ft) + end + itheta = math.floor((itheta * 16384) / qn +) elseif stereo then + if b > 16 and ctx.remaining_bits > 16 then + inv = decBitLogp(ec, 2) + end + if ctx.disable_inv then + inv = false + end + itheta = 0 + end + local qalloc = tellFrac(ec) - t0 + b =b- qalloc + local imid, iside, delta + if itheta == 0 then + imid = 32767 + iside = 0 + fill = band(fill, lshift(1, B) - 1) + delta = -16384 + elseif itheta == 16384 then + imid = 0 + iside = 32767 + fill = band(fill, lshift(lshift(1, B) - 1, B)) + delta = 16384 + else + imid = bitexactCos(itheta) + iside = bitexactCos(16384 - itheta) + delta = fracMul16((N - 1) * 128, bitexactLog2tan(iside, imid)) + end + return b, fill, inv, imid, iside, delta, itheta, qalloc +end + +local function quantBandN1(X, Y, lowbandOut) +local x = X + local ec = ctx.ec + for _ = 0, (Y >= 0 and 1 or 0) do + local sign = 0 + if ctx.remaining_bits >= 8 then + sign = decBits(ec, 1) + ctx.remaining_bits =ctx.remaining_bits- 8 + end + W[x + 1] = sign ~= 0 and-1 or 1 + x = Y + end + if lowbandOut >= 0 then + W[lowbandOut + 1] = W[X + 1] + end + return 1 +end + +local function quantPartition(X, N, b, B, lowband, LM, gain, fill) +local i = ctx.i + local B0 = B + local cm = 0 + local split = false + if LM ~= -1 and N > 2 then + local base = CACHE_INDEX[(LM + 1) * NB_EBANDS + i + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + N = rshift(N, 1) + local Y = X + N + LM =LM- 1 + if B == 1 then + fill = bor(band(fill, 1), lshift(fill, 1)) + end + B = rshift(B + 1, 1) + local _inv, imid, iside, delta, itheta, qalloc + b, fill, _inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B0, LM, false, fill) + local mid = imid / 32768 + local side = iside / 32768 + if B0 > 1 and band(itheta, 0x3fff) ~= 0 then + if itheta > 8192 then + delta =delta- math.floor(delta / 2 ^ (4 - LM) +) else + delta = imin(0, delta + math.floor((N * 8) / 2 ^ (5 - LM))) + end + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits =ctx.remaining_bits- qalloc + local nextLowband2 = (lowband >= 0 and((lowband + N ))or((-1 +))) local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits =sbits+ (rebalance - 24 +) end + cm = bor(cm, lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1))) + else + cm = lshift(quantPartition(Y, N, sbits, B, nextLowband2, LM, gain * side, rshift(fill, B)), rshift(B0, 1)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits =mbits+ (rebalance - 24 +) end + cm = bor(cm, quantPartition(X, N, mbits, B, lowband, LM, gain * mid, fill)) + end + else + local q = bits2pulses(i, LM, b) + local currBits = pulses2bits(i, LM, q) + ctx.remaining_bits =ctx.remaining_bits- currBits + while ctx.remaining_bits < 0 and q > 0 do + ctx.remaining_bits =ctx.remaining_bits+ currBits + q =q- 1 + currBits = pulses2bits(i, LM, q) + ctx.remaining_bits =ctx.remaining_bits- currBits + end + if q ~= 0 then + cm = algUnquant(X, N, getPulses(q), ctx.spread, B, ctx.ec, gain) + else + local cmMask = lshift(1, B) - 1 + fill = band(fill, cmMask) + if fill == 0 then + for j = X + 1, X + N do + W[j] = 0 + end + else + local seed = ctx.seed + if lowband < 0 then + for j = X + 1, X + N do + seed = lcg(seed) + W[j] = math.floor(signed32(seed) / 1048576 +) end + cm = cmMask + else + for j = 0, N - 1 do + seed = lcg(seed) + local tmp = band(seed, 0x8000) ~= 0 and 1 / 256 or-1 / 256 + W[X + j + 1] = W[lowband + j + 1] + tmp + end + cm = fill + end + ctx.seed = seed + renormaliseVector(X, N, gain) + end + end + end + return cm +end + +local function quantBand(X, N, b, B, lowband, LM, lowbandOut, + gain, lowbandScratch, fill) +local N0 = N + local NB = N + local B0 = B + local timeDivide = 0 + local recombine = 0 + local longBlocks = B0 == 1 + local tfChange = ctx.tf_change + NB = math.floor(NB / B +) if N == 1 then + return quantBandN1(X, -1, lowbandOut) + end + if tfChange > 0 then + recombine = tfChange + end + if lowbandScratch >= 0 and lowband >= 0 and (recombine ~= 0 or (band(NB, 1) == 0 and tfChange < 0) or B0 > 1) then + for j = 1, N do + W[lowbandScratch + j] = W[lowband + j] + end + lowband = lowbandScratch + end + for k = 0, recombine - 1 do + if lowband >= 0 then + haar1(lowband, rshift(N, k), lshift(1, k)) + end + fill = bor(BIT_INTERLEAVE[band(fill, 0xF) + 1], lshift(BIT_INTERLEAVE[rshift(fill, 4) + 1], 2)) + end + B = rshift(B, recombine) + NB = lshift(NB, recombine) + while band(NB, 1) == 0 and tfChange < 0 do + if lowband >= 0 then + haar1(lowband, NB, B) + end + fill = bor(fill, lshift(fill, B)) + B = lshift(B, 1) + NB = rshift(NB, 1) + timeDivide =timeDivide+ 1 + tfChange =tfChange+ 1 + end + B0 = B + local NB0 = NB + if B0 > 1 and lowband >= 0 then + deinterleaveHadamard(lowband, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + local cm = quantPartition(X, N, b, B, lowband, LM, gain, fill) + if B0 > 1 then + interleaveHadamard(X, rshift(NB, recombine), lshift(B0, recombine), longBlocks) + end + NB = NB0 + B = B0 + for _ = 0, timeDivide - 1 do + B = rshift(B, 1) + NB = lshift(NB, 1) + cm = bor(cm, rshift(cm, B)) + haar1(X, NB, B) + end + for k = 0, recombine - 1 do + cm = BIT_DEINTERLEAVE[cm + 1] + haar1(X, rshift(N0, k), lshift(1, k)) + end + B = lshift(B, recombine) + if lowbandOut >= 0 then + local n = sqrt(N0) + for j = 1, N0 do + W[lowbandOut + j] = n * W[X + j] + end + end + return band(cm, lshift(1, B) - 1) +end + +local function stereoMerge(X, Y, mid, N) + local xp, side = 0, 0 + for j = 1, N do + local y = W[Y + j] + xp =xp+ y * W[X + j] + side =side+ y * y + end + xp = mid * xp + local mm = mid * mid + local El = mm + side - 2 * xp + local Er = mm + side + 2 * xp + if Er < 6e-4 or El < 6e-4 then + for j = 1, N do + W[Y + j] = W[X + j] + end + return + end + local lgain = 1 / sqrt(El) + local rgain = 1 / sqrt(Er) + for j = 1, N do + local l = mid * W[X + j] + local r = W[Y + j] + W[X + j] = lgain * (l - r) + W[Y + j] = rgain * (l + r) + end +end + +local function quantBandStereo(X, Y, N, b, B, lowband, LM, + lowbandOut, lowbandScratch, fill) +if N == 1 then + return quantBandN1(X, Y, lowbandOut) + end + local origFill = fill + local inv, imid, iside, delta, itheta, qalloc + b, fill, inv, imid, iside, delta, itheta, qalloc = computeTheta(N, b, B, B, LM, true, fill) + local mid = imid / 32768 + local side = iside / 32768 + local cm + if N == 2 then + local mbits = b + local sbits = 0 + if itheta ~= 0 and itheta ~= 16384 then + sbits = 8 + end + mbits =mbits- sbits + local c = itheta > 8192 + ctx.remaining_bits =ctx.remaining_bits- (qalloc + sbits +) local x2, y2 = X, Y + if c then + x2, y2 = Y, X + end + local sign = 0 + if sbits ~= 0 then + sign = decBits(ctx.ec, 1) + end + sign = 1 - 2 * sign + cm = quantBand(x2, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, origFill) + W[y2 + 1] = -sign * W[x2 + 2] + W[y2 + 2] = sign * W[x2 + 1] + local x0, x1 = mid * W[X + 1], mid * W[X + 2] + local y0, y1 = side * W[Y + 1], side * W[Y + 2] + W[X + 1] = x0 - y0 + W[Y + 1] = x0 + y0 + W[X + 2] = x1 - y1 + W[Y + 2] = x1 + y1 + else + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + ctx.remaining_bits =ctx.remaining_bits- qalloc + local rebalance = ctx.remaining_bits + if mbits >= sbits then + cm = quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill) + rebalance = mbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 0 then + sbits =sbits+ (rebalance - 24 +) end + cm = bor(cm, quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B))) + else + cm = quantBand(Y, N, sbits, B, -1, LM, -1, side, -1, rshift(fill, B)) + rebalance = sbits - (rebalance - ctx.remaining_bits) + if rebalance > 24 and itheta ~= 16384 then + mbits =mbits+ (rebalance - 24 +) end + cm = bor(cm, quantBand(X, N, mbits, B, lowband, LM, lowbandOut, 1, lowbandScratch, fill)) + end + end + if N ~= 2 then + stereoMerge(X, Y, mid, N) + end + if inv then + for j = Y + 1, Y + N do + W[j] = -W[j] + end + end + return cm +end + +local function quantAllBands(start, endb, hasY, N, collapse, + pulses, shortBlocks, spread, dualStereo, intensity, + tfRes, totalBits, balance, ec, LM, codedBands, + seed, disableInv) +local M = lshift(1, LM) + local B = (shortBlocks and{M }or{1 +})[1] local normOffset = M * EB[start + 1] + local C = hasY and 2 or 1 + local norm = NORM_BASE + local norm2 = NORM_BASE + M * EB[NB_EBANDS] - normOffset + local lowbandScratch = M * EB[EFF_EBANDS] + local lowbandOffset = 0 + local updateLowband = true + ctx.ec = ec + ctx.intensity = intensity + ctx.seed = seed + ctx.spread = spread + ctx.disable_inv = disableInv + ctx.avoid_split_noise = B > 1 + for i = start, endb - 1 do + ctx.i = i + local last = i == endb - 1 + local X = M * EB[i + 1] + local Y = (hasY and((N + M * EB[i + 1] ))or((-1 +))) local Nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(ec) + if i ~= start then + balance =balance- t + end + local remainingBits = totalBits - t - 1 + ctx.remaining_bits = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if (M * EB[i + 1] - Nb >= M * EB[start + 1] or i == start + 1) and (updateLowband or lowbandOffset == 0) then + lowbandOffset = i + end + if i == start + 1 then + local n1 = M * (EB[start + 2] - EB[start + 1]) + local n2 = M * (EB[start + 3] - EB[start + 2]) + for k = 0, n2 - n1 - 1 do + W[norm + n1 + k + 1] = W[norm + 2 * n1 - n2 + k + 1] + end + if dualStereo then + for k = 0, n2 - n1 - 1 do + W[norm2 + n1 + k + 1] = W[norm2 + 2 * n1 - n2 + k + 1] + end + end + end + local tfChange = tfRes[i + 1] + ctx.tf_change = tfChange + if last then + lowbandScratch = -1 + end + local effectiveLowband = -1 + local xcm, ycm + if lowbandOffset ~= 0 and (spread ~= SPREAD_AGGRESSIVE or B > 1 or tfChange < 0) then + effectiveLowband = imax(0, M * EB[lowbandOffset + 1] - normOffset - Nb) + local foldStart = lowbandOffset + repeat + foldStart =foldStart- 1 + until M * EB[foldStart + 1] <= effectiveLowband + normOffset + local foldEnd = lowbandOffset - 1 + repeat + foldEnd =foldEnd+ 1 + until not (foldEnd < i and M * EB[foldEnd + 1] < effectiveLowband + normOffset + Nb) + xcm, ycm = 0, 0 + local fi = foldStart + repeat + xcm = bor(xcm, collapse[fi * C + 1]) + ycm = bor(ycm, collapse[fi * C + C]) + fi =fi+ 1 + until fi >= foldEnd + else + xcm = lshift(1, B) - 1 + ycm = xcm + end + if dualStereo and i == intensity then + dualStereo = false + for j = 1, M * EB[i + 1] - normOffset do + W[norm + j] = 0.5 * (W[norm + j] + W[norm2 + j]) + end + end + if dualStereo then + xcm = quantBand(X, Nb, math.floor(b / 2), B, (effectiveLowband ~= -1 and((norm + effectiveLowband ))or((-1))), LM, +last and-1 or norm + M * EB[i + 1] - normOffset, 1, lowbandScratch, xcm) + ycm = quantBand(Y, Nb, math.floor(b / 2), B, (effectiveLowband ~= -1 and((norm2 + effectiveLowband ))or((-1))), LM, +last and-1 or norm2 + M * EB[i + 1] - normOffset, 1, lowbandScratch, ycm) + else + local lb = (effectiveLowband ~= -1 and((norm + effectiveLowband ))or((-1 +))) local lo = last and-1 or norm + M * EB[i + 1] - normOffset + if hasY then + xcm = quantBandStereo(X, Y, Nb, b, B, lb, LM, lo, lowbandScratch, bor(xcm, ycm)) + else + xcm = quantBand(X, Nb, b, B, lb, LM, lo, 1, lowbandScratch, bor(xcm, ycm)) + end + ycm = xcm + end + collapse[i * C + 1] = band(xcm, 255) + collapse[i * C + C] = band(ycm, 255) + balance =balance+ (pulses[i + 1] + t +) updateLowband = b > Nb * 8 + ctx.avoid_split_noise = false + end + return ctx.seed +end + +local function antiCollapse(st, C, size, LM, start, endb, + collapse, pulses, seed) + local logE, prev1logE, prev2logE = st.oldBandE, st.oldLogE, st.oldLogE2 + for i = start, endb - 1 do + local N0 = EB[i + 2] - EB[i + 1] + local depth = rshift(math.floor((1 + pulses[i + 1]) / N0), LM) + local thresh = 0.5 * exp2(-0.125 * depth) + local sqrt1 = 1 / sqrt(N0 * 2 ^ LM) + for c = 0, C - 1 do + local k0 = c * NB_EBANDS + i + 1 + local prev1 = prev1logE[k0] + local prev2 = prev2logE[k0] + if C == 1 then + prev1 = max(prev1, prev1logE[NB_EBANDS + i + 1]) + prev2 = max(prev2, prev2logE[NB_EBANDS + i + 1]) + end + local Ediff = max(0, logE[k0] - min(prev1, prev2)) + local r = 2 * exp2(-Ediff) + if LM == 3 then + r =r* 1.41421356 + end + r = min(thresh, r) * sqrt1 + local X = c * size + EB[i + 1] * 2 ^ LM + local renorm = false + local cmask = collapse[i * C + c + 1] + for k = 0, 2 ^ LM - 1 do + if band(cmask, lshift(1, k)) == 0 then + for j = 0, N0 - 1 do + seed = lcg(seed) + W[X + j * 2 ^ LM + k + 1] = (band(seed, 0x8000) ~= 0 and{r }or{(-r +)})[1] end + renorm = true + end + end + if renorm then + renormaliseVector(X, N0 * 2 ^ LM, 1) + end + end + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- synthesis + +local function denormaliseBands(X, freq, logE, eoff, start, endb, M, silence) + local N = M * SHORT_MDCT + local bound = M * EB[endb + 1] + if silence then + bound = 0 + start = 0 + endb = 0 + end + local f = 1 + local x = X + M * EB[start + 1] + if start ~= 0 then + for _ = 1, M * EB[start + 1] do + freq[f] = 0 + f =f+ 1 + end + end + for i = start, endb - 1 do + local bandEnd = M * EB[i + 2] + local lg = logE[eoff + i + 1] + E_MEANS[i + 1] + local g = exp2(min(32, lg)) + for _ = M * EB[i + 1], bandEnd - 1 do + freq[f] = W[x + 1] * g + f =f+ 1 + x =x+ 1 + end + end + for k = bound + 1, N do + freq[k] = 0 + end +end + +local function celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + local M = lshift(1, LM) + local B, NB, shift + if isTransient then + B = M + NB = SHORT_MDCT + shift = MAX_LM + else + B = 1 + NB = SHORT_MDCT * M + shift = MAX_LM - LM + end + local outBase = DECODE_BUFFER_SIZE - N + 1 + local oldE = st.oldBandE + local freq = FREQ + if CC == 2 and C == 1 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + for c = 1, 2 do + local mem = st.mem[c] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + elseif CC == 1 and C == 2 then + denormaliseBands(0, freq, oldE, 0, start, effEnd, M, silence) + denormaliseBands(N, FREQ2, oldE, NB_EBANDS, start, effEnd, M, silence) + local f2 = FREQ2 + for k = 1, N do + freq[k] = 0.5 * freq[k] + 0.5 * f2[k] + end + local mem = st.mem[1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + else + for c = 0, CC - 1 do + denormaliseBands(c * N, freq, oldE, c * NB_EBANDS, start, effEnd, M, silence) + local mem = st.mem[c + 1] + for b = 0, B - 1 do + Mdct.backward(freq, b + 1, mem, outBase + NB * b, WINDOW, OVERLAP, shift, B) + end + end + end +end + +-- comb_filter, in place on mem (1-based base index of sample 0) +local function combFilter(mem, base, T0, T1, N, g0, g1, + tapset0, tapset1, overlap) + if g0 == 0 and g1 == 0 then + return + end + T0 = imax(T0, COMBFILTER_MINPERIOD) + T1 = imax(T1, COMBFILTER_MINPERIOD) + local ga, gb = COMB_GAINS[tapset0 + 1], COMB_GAINS[tapset1 + 1] + local g00, g01, g02 = g0 * ga[1], g0 * ga[2], g0 * ga[3] + local g10, g11, g12 = g1 * gb[1], g1 * gb[2], g1 * gb[3] + local x1 = mem[base - T1 + 1] + local x2 = mem[base - T1] + local x3 = mem[base - T1 - 1] + local x4 = mem[base - T1 - 2] + if g0 == g1 and T0 == T1 and tapset0 == tapset1 then + overlap = 0 + end + local i = 0 + while i < overlap do + local p = base + i + local x0 = mem[p - T1 + 2] + local w = WINDOW[i + 1] + local f = w * w + local of = 1 - f + mem[p] = mem[p] + (of * g00) * mem[p - T0] + (of * g01) * (mem[p - T0 + 1] + mem[p - T0 - 1]) + + (of * g02) * (mem[p - T0 + 2] + mem[p - T0 - 2]) + (f * g10) * x2 + (f * g11) * (x1 + x3) + + (f * g12) * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + i =i+ 1 + end + if g1 == 0 then + return + end + -- constant part (comb_filter_const) + local p = base + i + x4 = mem[p - T1 - 2] + x3 = mem[p - T1 - 1] + x2 = mem[p - T1] + x1 = mem[p - T1 + 1] + for q = p, base + N - 1 do + local x0 = mem[q - T1 + 2] + mem[q] = mem[q] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4) + x4 = x3 + x3 = x2 + x2 = x1 + x1 = x0 + end +end + +local function deemphasis(st, CC, N, pcm, pbase, accum) + local coef0 = PREEMPH + local xbase = DECODE_BUFFER_SIZE - N + for c = 0, CC - 1 do + local x = st.mem[c + 1] + local m = st.preemph[c + 1] + local y = pbase + c + if accum then + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y]=pcm[y]+ tmp * (1 / 32768) + y =y+ CC + end + else + for j = 1, N do + local tmp = x[xbase + j] + 1e-30 + m + m = coef0 * tmp + pcm[y] = tmp * (1 / 32768) + y =y+ CC + end + end + st.preemph[c + 1] = m + end +end + +-- --------------------------------------------------------------------------------------------------------------- +-- decoder state + +local function resetState(st) + st.rng = 0 + st.error = 0 + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NONE + st.skip_plc = true + st.postfilter_period = 0 + st.postfilter_period_old = 0 + st.postfilter_gain = 0 + st.postfilter_gain_old = 0 + st.postfilter_tapset = 0 + st.postfilter_tapset_old = 0 + st.preemph[1] = 0 + st.preemph[2] = 0 + for c = 1, st.channels do + local m = st.mem[c] + for k = 1, DECODE_BUFFER_SIZE + OVERLAP do + m[k] = 0 + end + end + for k = 1, 2 * NB_EBANDS do + st.oldBandE[k] = 0 + st.oldLogE[k] = -28 + st.oldLogE2[k] = -28 + st.backgroundLogE[k] = 0 + end +end + +-- celt_decoder_init(48000, channels) +function Celt.new(channels) +local st = { + channels = channels, + stream_channels = channels, + start = 0, + ["end"] = EFF_EBANDS, + disable_inv = channels == 1, + mem = {}, + preemph = { 0, 0 }, + oldBandE = table.create(2 * NB_EBANDS, 0), + oldLogE = table.create(2 * NB_EBANDS, -28), + oldLogE2 = table.create(2 * NB_EBANDS, -28), + backgroundLogE = table.create(2 * NB_EBANDS, 0), + } + for c = 1, channels do + st.mem[c] = table.create(DECODE_BUFFER_SIZE + OVERLAP, 0) + end + resetState(st) + return st +end + +Celt.reset = resetState + +-- noise-based concealment (celt_decode_lost, FRAME_PLC_NOISE) +local function decodeLost(st, N, LM) + local C = st.channels + local start = st.start + local endb = st["end"] + local effEnd = imax(start, imin(endb, EFF_EBANDS)) + for c = 1, C do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + local decay = 2 ^ LM * 0.0625 + if st.last_frame_type ~= FRAME_PLC_NOISE then + decay =decay+ max(1, imin(160, st.loss_duration) * 0.0625) + end + local oldE, bg = st.oldBandE, st.backgroundLogE + for c = 0, C - 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + oldE[k] = max(bg[k], oldE[k] - decay) + end + end + local seed = st.rng + for c = 0, C - 1 do + for i = start, effEnd - 1 do + local boffs = N * c + EB[i + 1] * 2 ^ LM + local blen = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + for j = 1, blen do + seed = lcg(seed) + W[boffs + j] = math.floor(signed32(seed) / 1048576 +) end + renormaliseVector(boffs, blen, 1) + end + end + st.rng = seed + celtSynthesis(st, C, C, start, effEnd, false, LM, false, N) + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, C do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, st.postfilter_period, N - SHORT_MDCT, + st.postfilter_gain, st.postfilter_gain, st.postfilter_tapset, st.postfilter_tapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.skip_plc = true + st.loss_duration = imin(10000, st.loss_duration + 2 ^ LM) + st.plc_duration = imin(10000, st.plc_duration + 2 ^ LM) + st.last_frame_type = FRAME_PLC_NOISE +end + +-- celt_decode_with_ec. pcm[pbase + j * channels + c]; frameSize at 48 kHz. dec may be nil (a new range decoder over +-- buf[off, off + len)). buf == nil or len <= 1 conceals. Returns the samples per channel, or < 0 on error. +function Celt.decode(st, buf, off, len, pcm, pbase, frameSize, + dec, accum) +local CC = st.channels + local C = st.stream_channels + local start = st.start + local endb = st["end"] + local LM = 0 + while LM <= MAX_LM and lshift(SHORT_MDCT, LM) ~= frameSize do + LM =LM+ 1 + end + if LM > MAX_LM then + return -1 + end + local M = lshift(1, LM) + if len < 0 or len > 1275 then + return -1 + end + local N = M * SHORT_MDCT + local effEnd = imin(endb, EFF_EBANDS) + if buf == nil or len <= 1 then + decodeLost(st, N, LM) + deemphasis(st, CC, N, pcm, pbase, accum) + return frameSize + end + if st.loss_duration == 0 then + st.skip_plc = false + end + if dec == nil then + dec = RD.new(buf , off, len) + end + local ec = dec +local oldBandE, oldLogE, oldLogE2, bgLogE = st.oldBandE, st.oldLogE, st.oldLogE2, st.backgroundLogE + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[i] = max(oldBandE[i], oldBandE[NB_EBANDS + i]) + end + end + local totalBits = len * 8 + local t = tell(ec) + local silence + if t >= totalBits then + silence = true + elseif t == 1 then + silence = decBitLogp(ec, 15) + else + silence = false + end + if silence then + t = len * 8 + ec.nbits_total =ec.nbits_total+ (t - tell(ec) +) end + local postfilterGain, postfilterPitch, postfilterTapset = 0, 0, 0 + if start == 0 and t + 16 <= totalBits then + if decBitLogp(ec, 1) then + local octave = decUint(ec, 6) + postfilterPitch = lshift(16, octave) + decBits(ec, 4 + octave) - 1 + local qg = decBits(ec, 3) + if tell(ec) + 2 <= totalBits then + postfilterTapset = decIcdf(ec, TAPSET_ICDF, 1, 2) + end + postfilterGain = 0.09375 * (qg + 1) + end + t = tell(ec) + end + local isTransient = false + if LM > 0 and t + 3 <= totalBits then + isTransient = decBitLogp(ec, 3) + t = tell(ec) + end + local shortBlocks = isTransient + local intraEner = (t + 3 <= totalBits and{(decBitLogp(ec, 3) )}or{false +})[1] if not intraEner and st.loss_duration ~= 0 then + local missing = imin(10, rshift(st.loss_duration, LM)) + local safety = LM == 0 and 1.5 or(LM == 1 and 0.5 or 0 +) for c = 0, 1 do + for i = start, endb - 1 do + local k = c * NB_EBANDS + i + 1 + if oldBandE[k] < max(oldLogE[k], oldLogE2[k]) then + local E0, E1, E2 = oldBandE[k], oldLogE[k], oldLogE2[k] + local slope = max(E1 - E0, 0.5 * (E2 - E0)) + slope = min(slope, 2) + E0 =E0- max(0, (1 + missing) * slope) + oldBandE[k] = max(-20, E0) + else + oldBandE[k] = min(min(oldBandE[k], oldLogE[k]), oldLogE2[k]) + end + oldBandE[k]=oldBandE[k]- safety + end + end + end + unquantCoarseEnergy(st, start, endb, intraEner, ec, C, LM) + + -- tf_decode + local tfRes = TF_RES + do + local budget = ec.storage * 8 + local tt = tell(ec) + local logp = isTransient and 2 or 4 + local tfSelectRsv = LM > 0 and tt + logp + 1 <= budget + if tfSelectRsv then + budget =budget- 1 + end + local tfChanged, curr = 0, 0 + for i = start, endb - 1 do + if tt + logp <= budget then + if decBitLogp(ec, logp) then + curr = bit32.bxor(curr, 1) + end + tt = tell(ec) + tfChanged = bor(tfChanged, curr) + end + tfRes[i + 1] = curr + logp = isTransient and 4 or 5 + end + local tfSelect = 0 + local row = TF_SELECT[LM + 1] + local ti = isTransient and 4 or 0 + if tfSelectRsv and row[ti + tfChanged + 1] ~= row[ti + 2 + tfChanged + 1] then + tfSelect = decBitLogp(ec, 1) and 1 or 0 + end + for i = start, endb - 1 do + tfRes[i + 1] = row[ti + 2 * tfSelect + tfRes[i + 1] + 1] + end + end + + t = tell(ec) + local spread = 2 + if t + 4 <= totalBits then + spread = decIcdf(ec, SPREAD_ICDF, 1, 5) + end + local cap = CAP + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = OFFSETS + local dynallocLogp = 6 + totalBits =totalBits* 8 + t = tellFrac(ec) + for i = start, endb - 1 do + local width = C * (EB[i + 2] - EB[i + 1]) * 2 ^ LM + local quanta = imin(width * 8, imax(48, width)) + local loopLogp = dynallocLogp + local boost = 0 + while t + loopLogp * 8 < totalBits and boost < cap[i + 1] do + local flag = decBitLogp(ec, loopLogp) + t = tellFrac(ec) + if not flag then + break + end + boost =boost+ quanta + totalBits =totalBits- quanta + loopLogp = 1 + end + offsets[i + 1] = boost + if boost > 0 then + dynallocLogp = imax(2, dynallocLogp - 1) + end + end + local allocTrim = (t + 48 <= totalBits and{(decIcdf(ec, TRIM_ICDF, 1, 7) )}or{5 +})[1] local bits = len * 64 - tellFrac(ec) - 1 + local antiCollapseRsv = isTransient and LM >= 2 and bits >= (LM + 2) * 8 and 8 or 0 + bits =bits- antiCollapseRsv + local pulses, fineQuant, finePriority = PULSES, FINE_QUANT, FINE_PRIORITY + local codedBands, balance, intensity, dualStereo = computeAllocation(start, endb, offsets, cap, allocTrim, bits, + pulses, fineQuant, finePriority, C, LM, ec) + unquantFineEnergy(st, start, endb, fineQuant, ec, C) + + -- shift the decoder memory by one frame + for c = 1, CC do + table.move(st.mem[c], N + 1, DECODE_BUFFER_SIZE + OVERLAP, 1) + end + + local collapse = COLLAPSE + st.rng = quantAllBands(start, endb, C == 2, N, collapse, pulses, shortBlocks, spread, dualStereo, intensity, tfRes, + len * 64 - antiCollapseRsv, balance, ec, LM, codedBands, st.rng, st.disable_inv) + + local antiCollapseOn = false + if antiCollapseRsv > 0 then + antiCollapseOn = decBits(ec, 1) ~= 0 + end + unquantEnergyFinalise(st, start, endb, fineQuant, finePriority, len * 8 - tell(ec), ec, C) + if antiCollapseOn then + antiCollapse(st, C, N, LM, start, endb, collapse, pulses, st.rng) + end + if silence then + for i = 1, C * NB_EBANDS do + oldBandE[i] = -28 + end + end + + celtSynthesis(st, C, CC, start, effEnd, isTransient, LM, silence, N) + + local base = DECODE_BUFFER_SIZE - N + 1 + for c = 1, CC do + st.postfilter_period = imax(st.postfilter_period, COMBFILTER_MINPERIOD) + st.postfilter_period_old = imax(st.postfilter_period_old, COMBFILTER_MINPERIOD) + combFilter(st.mem[c], base, st.postfilter_period_old, st.postfilter_period, SHORT_MDCT, st.postfilter_gain_old, + st.postfilter_gain, st.postfilter_tapset_old, st.postfilter_tapset, OVERLAP) + if LM ~= 0 then + combFilter(st.mem[c], base + SHORT_MDCT, st.postfilter_period, postfilterPitch, N - SHORT_MDCT, + st.postfilter_gain, postfilterGain, st.postfilter_tapset, postfilterTapset, OVERLAP) + end + end + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + st.postfilter_period = postfilterPitch + st.postfilter_gain = postfilterGain + st.postfilter_tapset = postfilterTapset + if LM ~= 0 then + st.postfilter_period_old = st.postfilter_period + st.postfilter_gain_old = st.postfilter_gain + st.postfilter_tapset_old = st.postfilter_tapset + end + + if C == 1 then + for i = 1, NB_EBANDS do + oldBandE[NB_EBANDS + i] = oldBandE[i] + end + end + if not isTransient then + for i = 1, 2 * NB_EBANDS do + oldLogE2[i] = oldLogE[i] + oldLogE[i] = oldBandE[i] + end + else + for i = 1, 2 * NB_EBANDS do + oldLogE[i] = min(oldLogE[i], oldBandE[i]) + end + end + local maxBgIncrease = imin(160, st.loss_duration + M) * 0.001 + for i = 1, 2 * NB_EBANDS do + bgLogE[i] = min(bgLogE[i] + maxBgIncrease, oldBandE[i]) + end + for c = 0, 1 do + for i = 0, start - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + for i = endb, NB_EBANDS - 1 do + local k = c * NB_EBANDS + i + 1 + oldBandE[k] = 0 + oldLogE[k] = -28 + oldLogE2[k] = -28 + end + end + st.rng = ec.rng + deemphasis(st, CC, N, pcm, pbase, accum) + st.loss_duration = 0 + st.plc_duration = 0 + st.last_frame_type = FRAME_NORMAL + if tell(ec) > 8 * len then + return -3 + end + if ec.error ~= 0 then + st.error = 1 + end + return frameSize +end + +return Celt +end +__FILES["codecs/audio/Opus/CeltEncoder"] = function() +local __compat = __compat local bit32 = __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct. +-- Never throws. +local RE = __include("codecs/entropy/RangeCoder/Encoder") +local T = __include("codecs/audio/Opus/CeltTables") +local Mdct = __include("codecs/audio/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +-- the MDCT window (the decoder's) and plan +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +local PLAN = (Mdct.new(2 * N) )-- 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] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +local function pvqU(n, k) +return U[n * UK + k + 1] +end + +local function imin(a, b) +return (a < b and{a }or{b +})[1]end +local function imax(a, b) +return (a > b and{a }or{b +})[1]end +local function tdiv(a, b) +local q = a / b + return (q >= 0 and{(floor(q) )}or{(-floor(-q) +)})[1]end +local function fracMul16(a, b) +return math.floor((16384 + a * b) / 32768 +)end +local function bitexactCos(x) +local x2 = math.floor((4096 + x * x) / 8192 +) x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +local function bitexactLog2tan(isin, icos) +local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ------------------------------------------------------------------------------------------------ energy +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +local function laplaceEncode(enc, value, fs, decay) +local fl = 0 + local val = value + if val ~= 0 then + local s = val < 0 and-1 or 0 + val = (val < 0 and{(-val )}or{val +})[1] fl = fs + fs = math.floor(((32768 - 32 - fs) * (16384 - decay)) / 32768 -- ec_laplace_get_freq1 +) local i = 1 + while fs > 0 and i < val do + fs =fs* 2 + fl =fl+ (fs + 2 +) fs = math.floor((fs * decay) / 32768 +) i =i+ 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl =fl+ (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = (s ~= 0 and{(-(i + di) )}or{(i + di +)})[1] else + fs =fs+ 1 + if s == 0 then + fl =fl+ fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +-- new(channels) -> State + + + + + + + + + + + + + + + + + + +function CeltEncoder.new(channels) +local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +local function quantCoarseEnergy(st, intra, enc, C, budget, nbBytes) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (intra and 42 or 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = (c == 0 and{prev0 }or{prev1 +})[1] local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi =qi+ tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, qi < 0 and 1 or 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function quantFineEnergy(st, fineQuant, enc, C) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do +local __DARKLUA_CONTINUE_8=false repeat local extra = fineQuant[i + 1] + if extra <= 0 then +__DARKLUA_CONTINUE_8=true break + end + if tell(enc) + C * extra > enc.storage * 8 then +__DARKLUA_CONTINUE_8=true break + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k]=oldE[k]+ offset + err[k]=err[k]- offset + end +__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end +end + +local function quantEnergyFinalise(st, fineQuant, finePriority, bitsLeft, enc, C) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do +local __DARKLUA_CONTINUE_11=false repeat if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i =i+ 1 +__DARKLUA_CONTINUE_11=true break + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = err[k] < 0 and 0 or 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k]=oldE[k]+ offset + err[k]=err[k]- offset + bitsLeft =bitsLeft- 1 + end + i =i+ 1 +__DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end + end +end + +-- ------------------------------------------------------------------------------------------------ allocation +local function bits2pulses(bandI, lm, bits) +local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits =bits- 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = lo == 0 and-1 or CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI, lm, pulses) +if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i) +if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +local function computeAllocation(offsets, cap, allocTrim, total, + pulses, ebits, finePriority, C, enc, wantDual) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = total >= 8 and 8 or 0 + total =total- skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total =total- intensityRsv + dualStereoRsv = total >= 8 and 8 or 0 + total =total- dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, math.floor((3 * w * 2 ^ LM * 8) / 16)) + trimOffset[j + 1] = math.floor((C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) / 64 +) if w * 2 ^ LM == 1 then +do local __DARKLUA_VAR=j + 1 trimOffset[__DARKLUA_VAR]=trimOffset[__DARKLUA_VAR]- C * 8 +end end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = math.floor((C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) / 4 +) if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj =bitsj+ offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum =psum+ imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum =psum+ C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo =lo- 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = math.floor((C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) / 4 +) local bits2j = (hi >= NB_ALLOC_VECTORS and{cap[j + 1] }or{(math.floor((C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) / 4 +))})[1] if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j =bits1j+ offsets[j + 1] + end + bits2j =bits2j+ offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = C > 1 and 1 or 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + math.floor((mid * bits2[j + 1]) / 64 +) if tmp >= thresh[j + 1] or done then + done = true + psum =psum+ imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum =psum+ allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + math.floor((lo * bits2[j + 1]) / 64 +) if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum =psum+ tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total =total+ skipRsv + break + end + local left = total - psum + local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) +) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum =psum- (bits[j + 1] + intensityRsv +) if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum =psum+ intensityRsv + if bandBits >= allocFloor then + psum =psum+ allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands =codedBands- 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total =total+ dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = math.floor(left / (EB[codedBands + 1] - EB[start + 1]) +) left =left- (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ percoeff * (EB[j + 2] - EB[j + 1]) +end end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]+ tmp +end left =left- tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (C == 2 and Nw > 2 and not dualStereo and j < intensity and 1 or 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (math.floor(NClogN / 2)) - den * FINE_OFFSET + if Nw == 2 then + offset =offset+ math.floor((den * 8) / 4 +) end + if bits[j + 1] + offset < den * 2 * 8 then + offset =offset+ math.floor(NClogN / 4 +) elseif bits[j + 1] + offset < den * 3 * 8 then + offset =offset+ math.floor(NClogN / 8 +) end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = math.floor((math.floor(eb / den)) / 8 +) if C * eb > (math.floor(bits[j + 1] / 8)) then + eb = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 +) end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = eb * (den * 8) >= bits[j + 1] + offset and 1 or 0 +do local __DARKLUA_VAR=j + 1 bits[__DARKLUA_VAR]=bits[__DARKLUA_VAR]- C * eb * 8 +end ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(math.floor(excess / 2 ^ (stereo + BITRES)), MAX_FINE_BITS - ebits[j + 1]) +do local __DARKLUA_VAR=j + 1 ebits[__DARKLUA_VAR]=ebits[__DARKLUA_VAR]+ extraFine +end local extraBits = extraFine * C * 8 + finePriority[j + 1] = extraBits >= excess - balance and 1 or 0 + excess =excess- extraBits + end + balance = excess + j =j+ 1 + end + while j < endb do + ebits[j + 1] = math.floor((math.floor(bits[j + 1] / 2 ^ stereo)) / 8 +) bits[j + 1] = 0 + finePriority[j + 1] = ebits[j + 1] < 1 and 1 or 0 + j =j+ 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- ------------------------------------------------------------------------------------------------ PVQ +-- icwrs: the index of the pulse vector iy[1..n] +local function icwrs(n, iy) +local j = n -- 1-based position of _y[n - 1] + local i = iy[j] < 0 and 1 or 0 + local k = math.abs(iy[j]) + repeat + j =j- 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i =i+ pvqU(nn, k) + k =k+ math.abs(iy[j]) + if iy[j] < 0 then + i =i+ pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +local function expRotation1(X, xo, len, stride, c, s) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p =p+ 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p =p- 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +local function expRotation(X, xo, len, stride, K, spread) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 =stride2+ 1 + end + end + len = math.floor(len / stride +) for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +local function pvqSearch(X, xo, n, K, iy, y, absx) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = (v < 0 and{(-v )}or{v +})[1] sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum =sum+ absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy =yy+ p * p + xy =xy+ absx[j] * p + sign[j] = 2 * p + pulsesLeft =pulsesLeft- p + end + end + if pulsesLeft > n + 3 then + yy =yy+ (pulsesLeft * pulsesLeft + pulsesLeft * sign[1] +) iy[1]=iy[1]+ pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy =yy+ 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy =xy+ absx[best] + yy =yy+ sign[best] + sign[best]=sign[best]+ 2 + iy[best]=iy[best]+ 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +local function algQuant(st, X, xo, n, K, enc) + -- rotate a copy (the original band stays for nothing else, but keep it intact) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +-- ------------------------------------------------------------------------------------------------ bands +local function computeQn(n, b, offset, pulseCap) +local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +local function quantPartition(st, bandI, X, xo, n, b, lm, enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm =lm- 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (math.floor(pulseCap / 2)) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid =emid+ X[xo + j] * X[xo + j] + eside =eside+ X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = math.floor((it * qn + 8192) / 16384 +) local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = (itheta <= h and((itheta + 1 ))or((qn + 1 - itheta +))) local fl = (itheta <= h and{(rshift(itheta * (itheta + 1), 1) )}or{(ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) +)})[1] encEncode(enc, fl, fl + fs, ft) + itheta = math.floor((itheta * 16384) / qn +) end + local qalloc = tellFrac(enc) - t0 + b =b- qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining =st.remaining- qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits =sbits+ (rebalance - 24 +) end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits =mbits+ (rebalance - 24 +) end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining =st.remaining- currBits + while st.remaining < 0 and q > 0 do + st.remaining =st.remaining+ currBits + q =q- 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining =st.remaining- currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +local function quantBandStereo(st, i, n, xo, b, enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (math.floor(pulseCap / 2)) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid =emid+ m * m + eside =eside+ sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = math.floor((itheta * qn + 8192) / 16384 +) local p0 = 3 + local x0 = math.floor(qn / 2 +) local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = math.floor((itheta * 16384) / qn +) if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b =b- qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining =st.remaining- qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits =sbits+ (rebalance - 24 +) end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits =mbits+ (rebalance - 24 +) end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +local function quantAllBands(st, C, pulses, dualStereo, totalBits, + balance, enc, codedBands, intensity) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance =balance- t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, math.floor(b / 2), LM, enc) + quantPartition(st, i, st.X[2], xo, nb, math.floor(b / 2), LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance =balance+ (pulses[i + 1] + t +) end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel +-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) +function CeltEncoder.encodeFrame(st, pcm, base, stride, nbBytes) +local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s =s+ X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k]=X[k]* g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + -- silence + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total =enc.nbits_total+ (totalBits - tell(enc) +) RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames =st.frames+ 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget =budget- 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames =st.frames+ 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder +end +__FILES["codecs/audio/Opus/CeltTables"] = function() +--!strict +-- 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, +}, +cache_index50 = { + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, + 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, + 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, + 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, + 343, 343, 343, 351, 351, 370, 376, 382, 387, +}, +cache_bits50 = { + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, + 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, + 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, + 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, + 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, + 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, + 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, + 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, + 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, + 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, + 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, + 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, + 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, + 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, + 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, + 122, 175, 224, 4, 67, 127, 182, 234, +}, +cache_caps50 = { + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, + 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, + 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, + 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, + 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, + 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, + 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +}, +e_prob_model = { + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, + 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11, 24, 179, 48, 138, 54, 135, + 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, + 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50, 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, + 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, + 189, 6, 190, 8, 177, 9, 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, + 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45, + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, + 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10, 21, 178, 59, 110, 71, 86, + 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, + 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42, 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, + 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, + 184, 10, 150, 13, 139, 15, 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, + 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40, +}, +} +end +__FILES["codecs/audio/Opus/Decoder"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local Packet = __include("codecs/audio/Opus/Packet") +local Celt = __include("codecs/audio/Opus/Celt") +local Silk = __include("codecs/audio/Opus/Silk") + +local Decoder = {} + +local MODE_SILK, MODE_HYBRID, MODE_CELT = Packet.MODE_SILK_ONLY, Packet.MODE_HYBRID, Packet.MODE_CELT_ONLY +local BW_NB, BW_MB, BW_WB, BW_SWB = Packet.BW_NB, Packet.BW_MB, Packet.BW_WB, Packet.BW_SWB +local F20, F10, F5, F2_5 = 960, 480, 240, 120 +local min, max = math.min, math.max +local readu8 = buffer.readu8 + +local WINDOW = Celt.window +local TRANS = table.create(F5 * 2, 0) +local REDUND = table.create(F5 * 2, 0) +local SILKTMP = table.create(F10 * 2, 0) +local SILENCE = buffer.create(2) +buffer.writeu8(SILENCE, 0, 0xFF) +buffer.writeu8(SILENCE, 1, 0xFF) +local EMPTY_EC = RD.new(buffer.create(0), 0, 0) +local OFFS = table.create(48, 0) +local SIZES = table.create(48, 0) + + + + + + + + + + + + + + + + +function Decoder.new(channels) +return { + channels = channels, + celt = Celt.new(channels), + silk = Silk.new(channels), + ctrl = { + nChannelsAPI = channels, + nChannelsInternal = channels, + API_sampleRate = 48000, + internalSampleRate = 16000, + payloadSize_ms = 20, + }, + stream_channels = channels, + frame_size = 120, + mode = 0, + bandwidth = 0, + prev_mode = 0, + prev_redundancy = false, + last_packet_duration = 0, + rangeFinal = 0, + } +end + +function Decoder.reset(st) + Celt.reset(st.celt) + Silk.reset(st.silk) + st.stream_channels = st.channels + st.frame_size = 120 + st.mode = 0 + st.bandwidth = 0 + st.prev_mode = 0 + st.prev_redundancy = false + st.last_packet_duration = 0 + st.rangeFinal = 0 +end + +-- out = w^2 * in2 + (1 - w^2) * in1 over `overlap` samples per channel +local function smoothFade(in1, b1, in2, b2, out, bo, overlap, ch) + for c = 0, ch - 1 do + for i = 0, overlap - 1 do + local w = WINDOW[i + 1] + w =w* w + local k = i * ch + c + out[bo + k] = w * in2[b2 + k] + (1 - w) * in1[b1 + k] + end + end +end + +local function decodeFrame(st, buf, off, len, pcm, pbase, frameSize) +local ch = st.channels + local celt = st.celt + if frameSize < F2_5 then + return -2 + end + frameSize = min(frameSize, 2880) + local data = buf + if len <= 1 then + data = nil + frameSize = min(frameSize, st.frame_size) + end + local audiosize, mode, bandwidth + local dec = EMPTY_EC + if data then + audiosize = st.frame_size + mode = st.mode + bandwidth = st.bandwidth + dec = RD.new(data, off, len) + else + audiosize = frameSize + mode = (st.prev_redundancy and{MODE_CELT }or{st.prev_mode +})[1] bandwidth = 0 + if mode == 0 then + for i = 0, audiosize * ch - 1 do + pcm[pbase + i] = 0 + end + return audiosize + end + if audiosize > F20 then + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase, min(audiosize, F20)) + if ret < 0 then + return ret + end + pbase =pbase+ ret * ch + audiosize =audiosize- ret + until audiosize <= 0 + return frameSize + elseif audiosize < F20 then + if audiosize > F10 then + audiosize = F10 + elseif mode ~= MODE_SILK and audiosize > F5 and audiosize < F10 then + audiosize = F5 + end + end + end + local celtAccum = mode ~= MODE_CELT + local transition = false + if data and st.prev_mode > 0 + and ((mode == MODE_CELT and st.prev_mode ~= MODE_CELT and not st.prev_redundancy) + or (mode ~= MODE_CELT and st.prev_mode == MODE_CELT)) then + transition = true + end + if transition and mode == MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if audiosize > frameSize then + return -1 + end + frameSize = audiosize + + -- SILK + if mode ~= MODE_CELT then + local tooSmall = frameSize < F10 + local sarr, sbase = pcm, pbase + if tooSmall then + sarr, sbase = SILKTMP, 1 + end + if st.prev_mode == MODE_CELT then + Silk.reset(st.silk) + end + local ctrl = st.ctrl + ctrl.payloadSize_ms = max(10, math.floor(1000 * audiosize / 48000)) + if data then + ctrl.nChannelsInternal = st.stream_channels + if mode == MODE_SILK then + ctrl.internalSampleRate = bandwidth == BW_NB and 8000 or(bandwidth == BW_MB and 12000 or 16000 +) else + ctrl.internalSampleRate = 16000 + end + end + local lost = data == nil and 1 or 0 + local decoded = 0 + repeat + local ret, n = Silk.decode(st.silk, ctrl, lost, decoded == 0, dec, sarr, sbase + decoded * ch) + if ret ~= 0 or n <= 0 then + if lost ~= 0 or n <= 0 then + n = frameSize - decoded + for i = 0, n * ch - 1 do + sarr[sbase + decoded * ch + i] = 0 + end + else + return -3 + end + end + decoded =decoded+ n + until decoded >= frameSize + if tooSmall then + for i = 0, frameSize * ch - 1 do + pcm[pbase + i] = SILKTMP[i + 1] + end + end + end + + local startBand = 0 + local redundancy, celtToSilk = false, false + local redundancyBytes = 0 + if mode ~= MODE_CELT and data and RD.tell(dec) + 17 + (mode == MODE_HYBRID and 20 or 0) <= 8 * len then + if mode == MODE_HYBRID then + redundancy = RD.bitLogp(dec, 12) + else + redundancy = true + end + if redundancy then + celtToSilk = RD.bitLogp(dec, 1) + redundancyBytes = (mode == MODE_HYBRID and{(RD.uint(dec, 256) + 2 )}or{(len - bit32.rshift(RD.tell(dec) + 7, 3) +)})[1] len =len- redundancyBytes + if len * 8 < RD.tell(dec) then + len = 0 + redundancyBytes = 0 + redundancy = false + end + dec.storage =dec.storage- redundancyBytes + end + end + if mode ~= MODE_CELT then + startBand = 17 + end + if redundancy then + transition = false + end + if transition and mode ~= MODE_CELT then + decodeFrame(st, nil, 0, 0, TRANS, 1, min(F5, audiosize)) + end + if bandwidth ~= 0 then + celt["end"] = bandwidth == BW_NB and 13 or((bandwidth == BW_MB or bandwidth == BW_WB )and 17 or(bandwidth == BW_SWB and 19 or 21 +)) end + celt.stream_channels = st.stream_channels + local redundantRng = 0 + if redundancy and celtToSilk then + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + end + celt.start = startBand + local celtRet = 0 + if mode ~= MODE_SILK then + local celtFrameSize = min(F20, frameSize) + if mode ~= st.prev_mode and st.prev_mode > 0 and not st.prev_redundancy then + Celt.reset(celt) + end + celtRet = Celt.decode(celt, data, off, len, pcm, pbase, celtFrameSize, (data and{dec }or{nil})[1], celtAccum) + st.rangeFinal = celt.rng + else + if st.prev_mode == MODE_HYBRID and not (redundancy and celtToSilk and st.prev_redundancy) then + celt.start = 0 + Celt.decode(celt, SILENCE, 0, 2, pcm, pbase, F2_5, nil, celtAccum) + end + st.rangeFinal = (data and{dec.rng }or{0 +})[1] end + if redundancy and not celtToSilk then + Celt.reset(celt) + celt.start = 0 + Celt.decode(celt, data, off + len, redundancyBytes, REDUND, 1, F5, nil, false) + redundantRng = celt.rng + local b = pbase + ch * (frameSize - F2_5) + smoothFade(pcm, b, REDUND, 1 + ch * F2_5, pcm, b, F2_5, ch) + end + if redundancy and celtToSilk and (st.prev_mode ~= MODE_SILK or st.prev_redundancy) then + for i = 0, F2_5 * ch - 1 do + pcm[pbase + i] = REDUND[1 + i] + end + smoothFade(REDUND, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + end + if transition then + if audiosize >= F5 then + for i = 0, ch * F2_5 - 1 do + pcm[pbase + i] = TRANS[1 + i] + end + smoothFade(TRANS, 1 + ch * F2_5, pcm, pbase + ch * F2_5, pcm, pbase + ch * F2_5, F2_5, ch) + else + smoothFade(TRANS, 1, pcm, pbase, pcm, pbase, F2_5, ch) + end + end + if len <= 1 then + st.rangeFinal = 0 + else + st.rangeFinal = bit32.bxor(st.rangeFinal, redundantRng) + end + st.prev_mode = mode + st.prev_redundancy = redundancy and not celtToSilk + if celtRet < 0 then + return celtRet + end + return audiosize +end + +-- opus_decode_native: decodes one packet (buf == nil or len == 0: conceal frameSize samples). pcm[pbase + i * ch + c]. +-- Returns the samples per channel (or < 0 on error) and the packet's size (self-delimited packets). +function Decoder.decode(st, buf, off, len, pcm, pbase, frameSize, selfDelimited) +local ch = st.channels + if buf == nil or len == 0 then + if frameSize % 120 ~= 0 then + return -1, 0 + end + local count = 0 + repeat + local ret = decodeFrame(st, nil, 0, 0, pcm, pbase + count * ch, frameSize - count) + if ret <= 0 then + return (ret < 0 and{ret }or{(-3)})[1], 0 + end + count =count+ ret + until count >= frameSize + st.last_packet_duration = count + return count, 0 + end + local b = buf +local toc = readu8(b, off) + local packetMode = Packet.mode(toc) + local packetBandwidth = Packet.bandwidth(toc) + local packetFrameSize = Packet.samplesPerFrame(toc, 48000) + local packetChannels = Packet.channels(toc) + local count, _, packetOffset = Packet.parse(b, off, len, OFFS, SIZES, selfDelimited) + if count < 0 then + return -4, 0 + end + if count * packetFrameSize > frameSize then + return -2, 0 + end + st.mode = packetMode + st.bandwidth = packetBandwidth + st.frame_size = packetFrameSize + st.stream_channels = packetChannels + local nb = 0 + for i = 1, count do + local ret = decodeFrame(st, b, OFFS[i], SIZES[i], pcm, pbase + nb * ch, frameSize - nb) + if ret < 0 then + return ret, 0 + end + nb =nb+ ret + end + st.last_packet_duration = nb + return nb, packetOffset +end +-- --------------------------------------------------------------------------------------------------------------- +-- multistream (channel mapping families 0 / 1 / 255) + + + + + + + + + + + +function Decoder.newMultistream(channels, streams, coupled, mapping) +local decs = {} + for s = 0, streams - 1 do + decs[s + 1] = Decoder.new(s < coupled and 2 or 1) + end + return { + channels = channels, + streams = streams, + coupled = coupled, + mapping = mapping, + decoders = decs, + tmp = table.create(5760 * 2, 0), + } +end + +function Decoder.resetMultistream(ms) + for _, d in __iter(ms.decoders) do + Decoder.reset(d) + end +end + +-- copies channel `sc` of src (stride sstride) into every output channel mapped to stream channel index `id` +local function copyOut(ms, id, src, sc, sstride, pcm, pbase, n) + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == id then + local o = pbase + c + local s = 1 + sc + for _ = 1, n do + pcm[o] = src[s] + o =o+ nch + s =s+ sstride + end + end + end +end + +-- opus_multistream_decode_native (float). Returns the samples per channel, or < 0 on error. +function Decoder.decodeMultistream(ms, buf, off, len, pcm, pbase, frameSize) +local doPlc = buf == nil or len == 0 + frameSize = min(frameSize, 5760) + if not doPlc and len < 2 * ms.streams - 1 then + return -4 + end + local tmp = ms.tmp + for s = 0, ms.streams - 1 do + local d = ms.decoders[s + 1] + if not doPlc and len <= 0 then + return -3 + end + local ret, packetOffset = Decoder.decode(d, (doPlc and{nil }or{buf})[1], off, doPlc and 0 or len, tmp, 1, frameSize, s ~= ms.streams - 1) + if not doPlc then + off =off+ packetOffset + len =len- packetOffset + end + if ret <= 0 then + return (ret < 0 and{ret }or{(-3 +)})[1] end + frameSize = ret + if s < ms.coupled then + copyOut(ms, s * 2, tmp, 0, 2, pcm, pbase, frameSize) + copyOut(ms, s * 2 + 1, tmp, 1, 2, pcm, pbase, frameSize) + else + copyOut(ms, s + ms.coupled, tmp, 0, 1, pcm, pbase, frameSize) + end + end + local nch = ms.channels + for c = 0, nch - 1 do + if ms.mapping[c + 1] == 255 then + local o = pbase + c + for _ = 1, frameSize do + pcm[o] = 0 + o =o+ nch + end + end + end + return frameSize +end + +-- writes src[base + 1 .. base + count] * gain to out as f32 from byte offset o +function Decoder.writeF32(src, base, count, gain, out, o) + local writef32 = buffer.writef32 + if gain == 1 then + for i = base + 1, base + count do + writef32(out, o, src[i]) + o =o+ 4 + end + else + for i = base + 1, base + count do + writef32(out, o, src[i] * gain) + o =o+ 4 + end + end +end + +-- Stereo downmix of n frames of srcCh-channel audio (src[base + 1 ..], interleaved): matrix[c * 2 + 1 / + 2] are the +-- left / right weights of channel c. Writes f32 to out from byte offset o. +function Decoder.writeDownmix(src, base, n, srcCh, matrix, gain, out, o) + local writef32 = buffer.writef32 + local p = base + for _ = 1, n do + local l, r = 0, 0 + for c = 0, srcCh - 1 do + local v = src[p + c + 1] + l =l+ v * matrix[c * 2 + 1] + r =r+ v * matrix[c * 2 + 2] + end + writef32(out, o, l * gain) + writef32(out, o + 4, r * gain) + o =o+ 8 + p =p+ srcCh + end +end + +return Decoder +end +__FILES["codecs/audio/Opus/Mdct"] = function() +--!strict +--!native +--!optimize 2 +-- 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 + + + + + + + + + + + + +local FACTORS = { + [0] = { 5, 96, 3, 32, 4, 8, 2, 4, 4, 1 }, + [1] = { 5, 48, 3, 16, 4, 4, 4, 1 }, + [2] = { 5, 24, 3, 8, 2, 4, 4, 1 }, + [3] = { 5, 12, 3, 4, 4, 1 }, +} + +local function bitrevTable(f, fout, fpos, fstride, factors, fi) + local p = factors[fi] + local m = factors[fi + 1] + if m == 1 then + for j = 0, p - 1 do + f[fpos + 1] = fout + j + fpos =fpos+ fstride + end + else + for j = 0, p - 1 do + bitrevTable(f, fout, fpos, fstride * p, factors, fi + 2) + fpos =fpos+ fstride + fout =fout+ m + end + end +end + +local plans= {} +for shift = 0, 3 do + local N = math.floor(1920 / 2 ^ shift +) local n = math.floor(N / 4 +) local factors = FACTORS[shift] + local bitrev = table.create(n, 0) + bitrevTable(bitrev, 0, 0, 1, factors, 1) + local twr, twi = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + local ph = -2 * pi * k / n + twr[k + 1] = cos(ph) + twi[k + 1] = sin(ph) + end + local N2, N4 = math.floor(N / 2), math.floor(N / 4 +) local trig = table.create(N2, 0) + for i = 0, N4 - 1 do + trig[2 * i + 1] = -sin(2 * pi * (i + 0.125) / N) + trig[2 * i + 2] = cos(2 * pi * (i + 0.125) / N) + end + plans[shift + 1] = { + n = n, + factors = factors, + bitrev = bitrev, + twr = twr, + twi = twi, + trig = trig, + fr = table.create(n, 0), + fi = table.create(n, 0), + } +end + +local function bfly2(fr, fi, N) + local tw = 0.7071067812 + local p = 1 + for _ = 1, N do + -- k = 0 + local tr, ti = fr[p + 4], fi[p + 4] + fr[p + 4] = fr[p] - tr + fi[p + 4] = fi[p] - ti + fr[p]=fr[p]+ tr + fi[p]=fi[p]+ ti + -- k = 1 + local a, b = fr[p + 5], fi[p + 5] + tr = (a + b) * tw + ti = (b - a) * tw + fr[p + 5] = fr[p + 1] - tr + fi[p + 5] = fi[p + 1] - ti +do local __DARKLUA_VAR=p + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]+ tr +end do local __DARKLUA_VAR0=p + 1 fi[__DARKLUA_VAR0]=fi[__DARKLUA_VAR0]+ ti +end -- k = 2 + tr = fi[p + 6] + ti = -fr[p + 6] + fr[p + 6] = fr[p + 2] - tr + fi[p + 6] = fi[p + 2] - ti +do local __DARKLUA_VAR1=p + 2 fr[__DARKLUA_VAR1]=fr[__DARKLUA_VAR1]+ tr +end do local __DARKLUA_VAR2=p + 2 fi[__DARKLUA_VAR2]=fi[__DARKLUA_VAR2]+ ti +end -- k = 3 + a, b = fr[p + 7], fi[p + 7] + tr = (b - a) * tw + ti = -(b + a) * tw + fr[p + 7] = fr[p + 3] - tr + fi[p + 7] = fi[p + 3] - ti +do local __DARKLUA_VAR3=p + 3 fr[__DARKLUA_VAR3]=fr[__DARKLUA_VAR3]+ tr +end do local __DARKLUA_VAR4=p + 3 fi[__DARKLUA_VAR4]=fi[__DARKLUA_VAR4]+ ti +end p =p+ 8 + end +end + +local function bfly4(fr, fi, fstride, twr, twi, m, N, mm) + if m == 1 then + local p = 1 + for _ = 1, N do + local r0, i0 = fr[p], fi[p] + local r1, i1 = fr[p + 1], fi[p + 1] + local r2, i2 = fr[p + 2], fi[p + 2] + local r3, i3 = fr[p + 3], fi[p + 3] + local s0r, s0i = r0 - r2, i0 - i2 + r0 =r0+ r2 + i0 =i0+ i2 + local s1r, s1i = r1 + r3, i1 + i3 + fr[p + 2] = r0 - s1r + fi[p + 2] = i0 - s1i + fr[p] = r0 + s1r + fi[p] = i0 + s1i + s1r, s1i = r1 - r3, i1 - i3 + fr[p + 1] = s0r + s1i + fi[p + 1] = s0i - s1r + fr[p + 3] = s0r - s1i + fi[p + 3] = s0i + s1r + p =p+ 4 + end + else + local m2, m3 = 2 * m, 3 * m + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2, t3 = 1, 1, 1 + for _ = 0, m - 1 do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s0r, s0i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m3], fi[p + m3] + wr, wi = twr[t3], twi[t3] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local f0r, f0i = fr[p], fi[p] + local s5r, s5i = f0r - s1r, f0i - s1i + f0r =f0r+ s1r + f0i =f0i+ s1i + local s3r, s3i = s0r + s2r, s0i + s2i + local s4r, s4i = s0r - s2r, s0i - s2i + fr[p + m2] = f0r - s3r + fi[p + m2] = f0i - s3i + t1 =t1+ fstride + t2 =t2+ fstride * 2 + t3 =t3+ fstride * 3 + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m] = s5r + s4i + fi[p + m] = s5i - s4r + fr[p + m3] = s5r - s4i + fi[p + m3] = s5i + s4r + p =p+ 1 + end + end + end +end + +local function bfly3(fr, fi, fstride, twr, twi, m, N, mm) + local m2 = 2 * m + local epi3i = twi[fstride * m + 1] + for i = 0, N - 1 do + local p = i * mm + 1 + local t1, t2 = 1, 1 + for _ = 1, m do + local ar, ai = fr[p + m], fi[p + m] + local wr, wi = twr[t1], twi[t1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p + m2], fi[p + m2] + wr, wi = twr[t2], twi[t2] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + local s3r, s3i = s1r + s2r, s1i + s2i + local s0r, s0i = s1r - s2r, s1i - s2i + t1 =t1+ fstride + t2 =t2+ fstride * 2 + local f0r, f0i = fr[p], fi[p] + local fmr, fmi = f0r - s3r * 0.5, f0i - s3i * 0.5 + s0r =s0r* epi3i + s0i =s0i* epi3i + fr[p] = f0r + s3r + fi[p] = f0i + s3i + fr[p + m2] = fmr + s0i + fi[p + m2] = fmi - s0r + fr[p + m] = fmr - s0i + fi[p + m] = fmi + s0r + p =p+ 1 + end + end +end + +local function bfly5(fr, fi, fstride, twr, twi, m, N, mm) + local yar, yai = twr[fstride * m + 1], twi[fstride * m + 1] + local ybr, ybi = twr[fstride * 2 * m + 1], twi[fstride * 2 * m + 1] + for i = 0, N - 1 do + local p0 = i * mm + 1 + local p1, p2, p3, p4 = p0 + m, p0 + 2 * m, p0 + 3 * m, p0 + 4 * m + for u = 0, m - 1 do + local s0r, s0i = fr[p0], fi[p0] + local k = u * fstride + local ar, ai = fr[p1], fi[p1] + local wr, wi = twr[k + 1], twi[k + 1] + local s1r, s1i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p2], fi[p2] + wr, wi = twr[2 * k + 1], twi[2 * k + 1] + local s2r, s2i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p3], fi[p3] + wr, wi = twr[3 * k + 1], twi[3 * k + 1] + local s3r, s3i = ar * wr - ai * wi, ar * wi + ai * wr + ar, ai = fr[p4], fi[p4] + wr, wi = twr[4 * k + 1], twi[4 * k + 1] + local s4r, s4i = ar * wr - ai * wi, ar * wi + ai * wr + + local s7r, s7i = s1r + s4r, s1i + s4i + local s10r, s10i = s1r - s4r, s1i - s4i + local s8r, s8i = s2r + s3r, s2i + s3i + local s9r, s9i = s2r - s3r, s2i - s3i + + fr[p0] = s0r + (s7r + s8r) + fi[p0] = s0i + (s7i + s8i) + + local s5r = s0r + (s7r * yar + s8r * ybr) + local s5i = s0i + (s7i * yar + s8i * ybr) + local s6r = s10i * yai + s9i * ybi + local s6i = -(s10r * yai + s9r * ybi) + fr[p1] = s5r - s6r + fi[p1] = s5i - s6i + fr[p4] = s5r + s6r + fi[p4] = s5i + s6i + + local s11r = s0r + (s7r * ybr + s8r * yar) + local s11i = s0i + (s7i * ybr + s8i * yar) + local s12r = s9i * yai - s10i * ybi + local s12i = s10r * ybi - s9r * yai + fr[p2] = s11r + s12r + fi[p2] = s11i + s12i + fr[p3] = s11r - s12r + fi[p3] = s11i - s12i + + p0 =p0+ 1 + p1 =p1+ 1 + p2 =p2+ 1 + p3 =p3+ 1 + p4 =p4+ 1 + end + end +end + +-- in-place forward FFT of bit-reversed input (opus_fft_impl) +local function fftImpl(pl) + local factors = pl.factors + local fr, fi, twr, twi = pl.fr, pl.fi, pl.twr, pl.twi + local fstride = { 1 } + local L = 0 + local m + repeat + local p = factors[2 * L + 1] + m = factors[2 * L + 2] + fstride[L + 2] = fstride[L + 1] * p + L =L+ 1 + until m == 1 + m = factors[2 * L] + for i = L - 1, 0, -1 do + local m2 = (i ~= 0 and{factors[2 * i] }or{1 +})[1] local radix = factors[2 * i + 1] + if radix == 2 then + bfly2(fr, fi, fstride[i + 1]) + elseif radix == 4 then + bfly4(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + elseif radix == 3 then + bfly3(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + else + bfly5(fr, fi, fstride[i + 1], twr, twi, m, fstride[i + 1], m2) + end + m = m2 + end +end + +-- clt_mdct_backward: input coefficients inp[inBase + k*stride] (k = 0 .. N/2-1, inBase is the 1-based index of +-- coefficient 0), output written to out[outBase .. outBase + N/2 + overlap/2) with TDAC windowing of the first +-- `overlap` samples (out[outBase] is sample 0). +function Mdct.backward(inp, inBase, out, outBase, window, overlap, shift, stride) + local pl = plans[shift + 1] + local N4 = pl.n + local N2 = N4 * 2 + local trig = pl.trig + local bitrev = pl.bitrev + local fr, fi = pl.fr, pl.fi + -- pre-rotate, storing in bit-reversed order (real and imaginary swapped: an FFT is used instead of an IFFT) + local xp1 = inBase + local xp2 = inBase + stride * (N2 - 1) + for i = 0, N4 - 1 do + local x1 = inp[xp1] + local x2 = inp[xp2] + local t0, t1 = trig[2 * i + 1], trig[2 * i + 2] + local rev = bitrev[i + 1] + 1 + fi[rev] = x2 * t1 + x1 * t0 + fr[rev] = x1 * t1 - x2 * t0 + xp1 =xp1+ 2 * stride + xp2 =xp2- 2 * stride + end + fftImpl(pl) + -- post-rotate + local h = outBase + (math.floor(overlap / 2)) + for k = 0, N4 - 1 do + local re = fi[k + 1] + local im = fr[k + 1] + local t0, t1 = trig[2 * k + 1], trig[2 * k + 2] + out[h + 2 * k] = re * t1 + im * t0 + out[h + N2 - 1 - 2 * k] = re * t0 - im * t1 + end + -- mirror on both sides for TDAC + local xp = outBase + overlap - 1 + local yp = outBase + for i = 0, math.floor(overlap / 2 )- 1 do + local x1 = out[xp] + local x2 = out[yp] + local w1 = window[i + 1] + local w2 = window[overlap - i] + out[yp] = x2 * w2 - x1 * w1 + out[xp] = x2 * w1 + x1 * w2 + xp =xp- 1 + yp =yp+ 1 + end +end + +return Mdct +end +__FILES["codecs/audio/Opus/Packet"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 +local band, rshift = bit32.band, bit32.rshift + +Packet.MODE_SILK_ONLY = 1000 +Packet.MODE_HYBRID = 1001 +Packet.MODE_CELT_ONLY = 1002 + +-- bandwidths as in libopus (OPUS_BANDWIDTH_NARROWBAND .. FULLBAND) +Packet.BW_NB = 1101 +Packet.BW_MB = 1102 +Packet.BW_WB = 1103 +Packet.BW_SWB = 1104 +Packet.BW_FB = 1105 + +function Packet.mode(toc) +if band(toc, 0x80) ~= 0 then + return Packet.MODE_CELT_ONLY + elseif band(toc, 0x60) == 0x60 then + return Packet.MODE_HYBRID + else + return Packet.MODE_SILK_ONLY + end +end + +function Packet.bandwidth(toc) +if band(toc, 0x80) ~= 0 then + local bw = 1102 + band(rshift(toc, 5), 3) + if bw == 1102 then + bw = 1101 + end + return bw + elseif band(toc, 0x60) == 0x60 then + return band(toc, 0x10) ~= 0 and 1105 or 1104 + else + return 1101 + band(rshift(toc, 5), 3) + end +end + +function Packet.channels(toc) +return band(toc, 4) ~= 0 and 2 or 1 +end + +-- samples per frame at rate Fs +function Packet.samplesPerFrame(toc, Fs) +if band(toc, 0x80) ~= 0 then + local a = band(rshift(toc, 3), 3) + return math.floor(bit32.lshift(Fs, a) / 400 +) elseif band(toc, 0x60) == 0x60 then + return (band(toc, 0x08) ~= 0 and{(math.floor(Fs / 50 ))}or{(math.floor(Fs / 100 +))})[1] else + local a = band(rshift(toc, 3), 3) + if a == 3 then + return math.floor(Fs * 60 / 1000 +) end + return math.floor(bit32.lshift(Fs, a) / 100 +) end +end + +-- total samples of a packet at 48 kHz, or -1 if invalid +function Packet.samples(buf, off, len) +if len < 1 then + return -1 + end + local toc = readu8(buf, off) + local c = band(toc, 3) + local count + if c == 0 then + count = 1 + elseif c ~= 3 then + count = 2 + else + if len < 2 then + return -1 + end + count = band(readu8(buf, off + 1), 0x3F) + end + local n = count * Packet.samplesPerFrame(toc, 48000) + if n * 25 > 48000 * 3 then + return -1 + end + return n +end + +local function parseSize(buf, p, len) +if len < 1 then + return -1, -1 + end + local b0 = readu8(buf, p) + if b0 < 252 then + return 1, b0 + elseif len < 2 then + return -1, -1 + end + return 2, 4 * readu8(buf, p + 1) + b0 +end + +-- Splits a packet (opus_packet_parse_impl). Fills offsets[i] / sizes[i] (1-based, absolute buffer offsets) and +-- returns the frame count, the TOC byte and the packet's total size including padding (self-delimited packets, as in +-- multistream, carry an explicit size for the last frame). The count is -1 for an invalid packet. +function Packet.parse(buf, off, len, offsets, sizes, selfDelimited) +if len < 1 then + return -1, 0, 0 + end + local toc = readu8(buf, off) + local framesize = Packet.samplesPerFrame(toc, 48000) + local p = off + 1 + len =len- 1 + local lastSize = len + local count + local cbr = false + local pad = 0 + local c = band(toc, 3) + if c == 0 then + count = 1 + elseif c == 1 then + count = 2 + cbr = true + if not selfDelimited then + if band(len, 1) ~= 0 then + return -1, toc, 0 + end + lastSize = math.floor(len / 2 +) sizes[1] = lastSize + end + elseif c == 2 then + count = 2 + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len =len- bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[1] = s + p =p+ bytes + lastSize = len - s + else + if len < 1 then + return -1, toc, 0 + end + local ch = readu8(buf, p) + p =p+ 1 + count = band(ch, 0x3F) + if count <= 0 or framesize * count > 5760 then + return -1, toc, 0 + end + len =len- 1 + if band(ch, 0x40) ~= 0 then + local pb + repeat + if len <= 0 then + return -1, toc, 0 + end + pb = readu8(buf, p) + p =p+ 1 + len =len- 1 + local tmp = pb == 255 and 254 or pb + len =len- tmp + pad =pad+ tmp + until pb ~= 255 + end + if len < 0 then + return -1, toc, 0 + end + cbr = band(ch, 0x80) == 0 + if not cbr then + lastSize = len + for i = 1, count - 1 do + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len =len- bytes + if s < 0 or s > len then + return -1, toc, 0 + end + sizes[i] = s + p =p+ bytes + lastSize =lastSize- (bytes + s +) end + if lastSize < 0 then + return -1, toc, 0 + end + elseif not selfDelimited then + lastSize = math.floor(len / count +) if lastSize * count ~= len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = lastSize + end + end + end + if selfDelimited then + local bytes, s = parseSize(buf, p, len) + if bytes < 0 then + return -1, toc, 0 + end + len =len- bytes + if s < 0 or s > len then + return -1, toc, 0 + end + p =p+ bytes + sizes[count] = s + if cbr then + if s * count > len then + return -1, toc, 0 + end + for i = 1, count - 1 do + sizes[i] = s + end + elseif bytes + s > lastSize then + return -1, toc, 0 + end + else + if lastSize > 1275 then + return -1, toc, 0 + end + sizes[count] = lastSize + end + for i = 1, count do + offsets[i] = p + p =p+ sizes[i] + end + return count, toc, pad + (p - off) +end + +return Packet +end +__FILES["codecs/audio/Opus/Silk"] = function() +local __compat = __compat local bit32, __iter = __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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/. +-- +-- local st = Silk.new(apiChannels) +-- local ret, n = Silk.decode(st, ctrl, lostFlag, firstFrame, ec, out, outBase) +-- ctrl = { nChannelsAPI, nChannelsInternal, API_sampleRate, internalSampleRate, payloadSize_ms } +-- decodes one 10 / 20 ms SILK frame and writes n samples per channel (at API_sampleRate) to the Luau array +-- `out`, interleaved by nChannelsAPI: out[outBase + i * nChannelsAPI + c], scaled int16 / 32768. +-- +-- 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 = __include("codecs/entropy/RangeCoder/Decoder") +local T = __include("codecs/audio/Opus/SilkTables") + +local icdf = RD.icdf +local bitLogp = RD.bitLogp +local countlz = bit32.countlz +local floor = math.floor + +local Silk = {} + +local P2 = table.create(64, 0) -- P2[s] = 2^s (1-based by s: P2[s] for s >= 1, P2_0 = 1) +for s = 1, 63 do + P2[s] = 2 ^ s +end +local function p2(s) +if s == 0 then + return 1 + end + return P2[s] +end + +-- C helpers ----------------------------------------------------------------------------------------------------- + +local function s16(x) +x = x % 65536 + if x >= 32768 then + return x - 65536 + end + return x +end + +local function i32(x) +x = x % 4294967296 + if x >= 2147483648 then + return x - 4294967296 + end + return x +end + +local function sat16(x) +if x > 32767 then + return 32767 + elseif x < -32768 then + return -32768 + end + return x +end + +local function addSat32(a, b) +local s = a + b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +local function subSat32(a, b) +local s = a - b + if s > 2147483647 then + return 2147483647 + elseif s < -2147483648 then + return -2147483648 + end + return s +end + +-- silk_CLZ32 of a non-negative int32 +local function clz32(x) +return countlz(x) +end + +-- silk_SMULWW (64-bit form): (a * b) >> 16, exact +local function mulww(a, b) +return a * (math.floor(b / 65536)) + math.floor((a * (b % 65536)) / 65536 +)end + +-- floor(a * b / 2^s) for int32 a, b and s >= 16, exact +local function mulshr(a, b, s) +local t = a * (math.floor(b / 65536)) + math.floor((a * (b % 65536)) / 65536 +) if s == 16 then + return t + end + return math.floor(t / P2[s - 16] +)end + +local function smmul(a, b) +return mulshr(a, b, 32) +end + +-- silk_RSHIFT_ROUND (shift >= 1) +local function rround(a, s) +return math.floor((a + p2(s - 1)) / P2[s] +)end + +local function lshiftSat32(a, sh) +if sh == 0 then + return a + end + local m = P2[sh] + local lo, hi = math.floor(-2147483648 / m), math.floor(2147483647 / m +) if a < lo then + a = lo + elseif a > hi then + a = hi + end + return a * m +end + +-- C integer division (truncation toward zero) +local function tdiv(a, b) +local q = a / b + if q >= 0 then + return floor(q) + end + return -floor(-q) +end + +-- low 32 bits of a * b, as int32 +local function imul32(a, b) +a = a % 4294967296 + local ah, al = math.floor(a / 65536), a % 65536 + return i32(((ah * b) % 65536) * 65536 + al * b) +end + +local function silkRand(seed) +return i32(907633515 + imul32(seed, 196314165)) +end + +local function rshift(a, s) +if s == 0 then + return a + end + return math.floor(a / P2[s] +)end + +local function silkINVERSE32_varQ(b32, Qres) +local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, math.floor(b32_nrm / 65536)) + local result = b32_inv * 65536 + local err_Q32 = i32((536870912 - math.floor((b32_nrm * b32_inv) / 65536)) * 8) + result = i32(result + mulww(err_Q32, b32_inv)) + local lshift = 61 - b_headrm - Qres + if lshift <= 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return math.floor(result / P2[lshift] +) end + return 0 +end + +local function silkDIV32_varQ(a32, b32, Qres) +local a_headrm = clz32(math.abs(a32)) - 1 + local a32_nrm = a32 * p2(a_headrm) + local b_headrm = clz32(math.abs(b32)) - 1 + local b32_nrm = b32 * p2(b_headrm) + local b32_inv = tdiv(536870911, math.floor(b32_nrm / 65536)) + local result = math.floor((a32_nrm * s16(b32_inv)) / 65536 +) a32_nrm = i32(a32_nrm - i32(smmul(b32_nrm, result) * 8)) + result = result + math.floor((a32_nrm * s16(b32_inv)) / 65536 +) local lshift = 29 + a_headrm - b_headrm - Qres + if lshift < 0 then + return lshiftSat32(result, -lshift) + elseif lshift < 32 then + return rshift(result, lshift) + end + return 0 +end + +local function silkLog2lin(inLog_Q7) +if inLog_Q7 < 0 then + return 0 + elseif inLog_Q7 >= 3967 then + return 2147483647 + end + local out = p2(math.floor(inLog_Q7 / 128)) + local frac_Q7 = inLog_Q7 % 128 + local t = frac_Q7 + math.floor((frac_Q7 * (128 - frac_Q7) * -174) / 65536 +) if inLog_Q7 < 2048 then + out = out + math.floor((out * t) / 128 +) else + out = out + (math.floor(out / 128)) * t + end + return out +end + +local function silkSQRT_APPROX(x) +if x <= 0 then + return 0 + end + local lz = clz32(x) + local rot = 24 - lz + local r + if rot == 0 then + r = x + elseif rot < 0 then + r = bit32.lrotate(x, -rot) + else + r = bit32.rrotate(x, rot) + end + local frac_Q7 = bit32.band(r, 0x7f) + local y = bit32.band(lz, 1) ~= 0 and 32768 or 46214 + y = math.floor(y / p2(math.floor(lz / 2)) +) y = y + math.floor((y * (213 * frac_Q7)) / 65536 +) return y +end + +-- silk_sum_sqr_shift: energy, shift +local function sumSqrShift(x, xo, len) +local shft = 31 - clz32(len) + local nrg = len + local i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i =i+ 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + shft = math.max(0, shft + 3 - clz32(nrg)) + nrg = 0 + i = 0 + while i < len - 1 do + local a, b = x[xo + i], x[xo + i + 1] + nrg = i32(nrg + rshift(a * a + b * b, shft)) + i =i+ 2 + end + if i < len then + local a = x[xo + i] + nrg = i32(nrg + rshift(a * a, shft)) + end + return nrg, shft +end + +-- LPC helpers --------------------------------------------------------------------------------------------------- + +-- silk_bwexpander (int16 coefficients), ar 1-based +local function bwexpander(ar, d, chirp_Q16) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = s16(math.floor((chirp_Q16 * ar[i] + 32768) / 65536)) + chirp_Q16 =chirp_Q16+ math.floor((chirp_Q16 * chirp_minus_one_Q16 + 32768) / 65536 +) end + ar[d] = s16(math.floor((chirp_Q16 * ar[d] + 32768) / 65536)) +end + +local function bwexpander32(ar, d, chirp_Q16) + local chirp_minus_one_Q16 = chirp_Q16 - 65536 + for i = 1, d - 1 do + ar[i] = i32(mulww(chirp_Q16, ar[i])) + chirp_Q16 =chirp_Q16+ math.floor((chirp_Q16 * chirp_minus_one_Q16 + 32768) / 65536 +) end + ar[d] = i32(mulww(chirp_Q16, ar[d])) +end + +-- silk_LPC_fit: a_QIN (int32, QIN) -> a_QOUT (int16, QOUT) +local function lpcFit(a_QOUT, a_QIN, QOUT, QIN, d) + local sh = QIN - QOUT + local idx = 0 + local i = 0 + while i < 10 do + local maxabs = 0 + for k = 1, d do + local absval = math.abs(a_QIN[k]) + if absval > maxabs then + maxabs = absval + idx = k - 1 + end + end + maxabs = rround(maxabs, sh) + if maxabs > 32767 then + maxabs = math.min(maxabs, 163838) + local chirp_Q16 = 65470 - tdiv((maxabs - 32767) * 16384, math.floor((maxabs * (idx + 1)) / 4)) + bwexpander32(a_QIN, d, chirp_Q16) + else + break + end + i =i+ 1 + end + if i == 10 then + for k = 1, d do + a_QOUT[k] = sat16(rround(a_QIN[k], sh)) + a_QIN[k] = a_QOUT[k] * P2[sh] + end + else + for k = 1, d do + a_QOUT[k] = s16(rround(a_QIN[k], sh)) + end + end +end + +local A_LIMIT = 16773022 +local INV_GAIN_MIN = 107374 +local Atmp_QA = table.create(16, 0) + +-- RSHIFT_ROUND64(SMULL(a, b), Q) +local function mulRound(a, b, Q) +if Q == 1 then + local p = a * b + return math.floor(p / 2 )+ p % 2 + end + if Q - 1 >= 16 then + return math.floor((mulshr(a, b, Q - 1) + 1) / 2 +) end + return math.floor((math.floor((a * b) / P2[Q - 1] )+ 1) / 2 +)end + +local function lpcInversePredGainQA(A_QA, order) +local invGain_Q30 = 1073741824 + local k = order - 1 + while k > 0 do + local ak = A_QA[k + 1] + if ak > A_LIMIT or ak < -A_LIMIT then + return 0 + end + local rc_Q31 = -(ak * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + local mult2Q = 32 - clz32(math.abs(rc_mult1_Q30)) + local rc_mult2 = silkINVERSE32_varQ(rc_mult1_Q30, mult2Q + 30) + for n = 0, math.floor((k + 1) / 2 )- 1 do + local tmp1 = A_QA[n + 1] + local tmp2 = A_QA[k - n] + local t64 = mulRound(subSat32(tmp1, mulRound(tmp2, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[n + 1] = t64 + t64 = mulRound(subSat32(tmp2, mulRound(tmp1, rc_Q31, 31)), rc_mult2, mult2Q) + if t64 > 2147483647 or t64 < -2147483648 then + return 0 + end + A_QA[k - n] = t64 + end + k =k- 1 + end + local a0 = A_QA[1] + if a0 > A_LIMIT or a0 < -A_LIMIT then + return 0 + end + local rc_Q31 = -(a0 * 128) + local rc_mult1_Q30 = 1073741824 - smmul(rc_Q31, rc_Q31) + invGain_Q30 = smmul(invGain_Q30, rc_mult1_Q30) * 4 + if invGain_Q30 < INV_GAIN_MIN then + return 0 + end + return invGain_Q30 +end + +local function lpcInversePredGain(A_Q12, order) +local DC_resp = 0 + for k = 1, order do + DC_resp =DC_resp+ A_Q12[k] + Atmp_QA[k] = A_Q12[k] * 4096 + end + if DC_resp >= 4096 then + return 0 + end + return lpcInversePredGainQA(Atmp_QA, order) +end + +local ordering16 = { 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1 } +local ordering10 = { 0, 9, 6, 3, 4, 5, 8, 1, 2, 7 } +local cos_LSF_QA = table.create(16, 0) +local polyP = table.create(9, 0) +local polyQ = table.create(9, 0) +local a32_QA1 = table.create(16, 0) +local LSFCos = T.LSFCosTab_FIX_Q12 + +-- out[0..dd] (1-based storage), from interleaved cLSF starting at C index c0 +local function findPoly(out, cLSF, c0, dd) + out[1] = 65536 + out[2] = -cLSF[c0 + 1] + for k = 1, dd - 1 do + local ftmp = cLSF[c0 + 2 * k + 1] + out[k + 2] = out[k] * 2 - math.floor((ftmp * out[k + 1] + 32768) / 65536 +) for n = k, 2, -1 do +do local __DARKLUA_VAR=n + 1 out[__DARKLUA_VAR]=out[__DARKLUA_VAR]+ (out[n - 1] - math.floor((ftmp * out[n] + 32768) / 65536 +))end end + out[2]=out[2]- ftmp + end +end + +-- silk_NLSF2A: a_Q12 (1-based, d entries) from NLSF (1-based) +local function nlsf2a(a_Q12, NLSF, d) + local ordering = (d == 16 and{ordering16 }or{ordering10 +})[1] for k = 1, d do + local nl = NLSF[k] + local f_int = math.floor(nl / 256 +) local f_frac = nl - f_int * 256 + local cos_val = LSFCos[f_int + 1] + local delta = LSFCos[f_int + 2] - cos_val + cos_LSF_QA[ordering[k] + 1] = math.floor((cos_val * 256 + delta * f_frac + 8) / 16 +) end + local dd = math.floor(d / 2 +) findPoly(polyP, cos_LSF_QA, 0, dd) + findPoly(polyQ, cos_LSF_QA, 1, dd) + for k = 0, dd - 1 do + local Ptmp = polyP[k + 2] + polyP[k + 1] + local Qtmp = polyQ[k + 2] - polyQ[k + 1] + a32_QA1[k + 1] = -Qtmp - Ptmp + a32_QA1[d - k] = Qtmp - Ptmp + end + lpcFit(a_Q12, a32_QA1, 12, 17, d) + local i = 0 + while lpcInversePredGain(a_Q12, d) == 0 and i < 16 do + bwexpander32(a32_QA1, d, 65536 - P2[i + 1]) + for k = 1, d do + a_Q12[k] = s16(math.floor((a32_QA1[k] + 16) / 32)) + end + i =i+ 1 + end +end + +-- silk_LPC_analysis_filter: out[oo + ix] for ix in [0, len), from inp[io + ix]; B 1-based Q12 +local function lpcAnalysisFilter(out, oo, inp, io, B, len, d) + for ix = d, len - 1 do + local base = io + ix - 1 + local acc = 0 + for j = 0, d - 1 do + acc =acc+ inp[base - j] * B[j + 1] + end + local out32_Q12 = i32(inp[base + 1] * 4096 - acc) + out[oo + ix] = sat16(math.floor((out32_Q12 + 2048) / 4096)) + end + for j = 0, d - 1 do + out[oo + j] = 0 + end +end + +-- NLSF ---------------------------------------------------------------------------------------------------------- + +local CB_NB_MB = { + nVectors = 32, + order = 10, + quantStepSize_Q16 = 11796, + CB1_NLSF_Q8 = T.NLSF_CB1_NB_MB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_NB_MB, + pred_Q8 = T.NLSF_PRED_NB_MB_Q8, + ec_sel = T.NLSF_CB2_SELECT_NB_MB, + ec_iCDF = T.NLSF_CB2_iCDF_NB_MB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_NB_MB_Q15, +} +local CB_WB = { + nVectors = 32, + order = 16, + quantStepSize_Q16 = 9830, + CB1_NLSF_Q8 = T.NLSF_CB1_WB_Q8, + CB1_Wght_Q9 = T.NLSF_CB1_WB_Wght_Q9, + CB1_iCDF = T.NLSF_CB1_iCDF_WB, + pred_Q8 = T.NLSF_PRED_WB_Q8, + ec_sel = T.NLSF_CB2_SELECT_WB, + ec_iCDF = T.NLSF_CB2_iCDF_WB, + deltaMin_Q15 = T.NLSF_DELTA_MIN_WB_Q15, +} + +local ec_ix = table.create(16, 0) +local pred_Q8 = table.create(16, 0) +local res_Q10 = table.create(16, 0) + +local function nlsfUnpack(CB, CB1_index) + local order = CB.order + local sel = CB.ec_sel + local pq = CB.pred_Q8 + local p = math.floor(CB1_index * order / 2 +) for i = 0, order - 1, 2 do + p =p+ 1 + local entry = sel[p] + ec_ix[i + 1] = (bit32.band(math.floor(entry / 2), 7)) * 9 + pred_Q8[i + 1] = pq[i + bit32.band(entry, 1) * (order - 1) + 1] + ec_ix[i + 2] = (bit32.band(math.floor(entry / 32), 7)) * 9 + pred_Q8[i + 2] = pq[i + bit32.band(math.floor(entry / 16), 1) * (order - 1) + 2] + end +end + +local function nlsfStabilize(NLSF, NDeltaMin, L) + local loops = 0 + while loops < 20 do + local min_diff = NLSF[1] - NDeltaMin[1] + local I = 0 + for i = 1, L - 1 do + local diff = NLSF[i + 1] - (NLSF[i] + NDeltaMin[i + 1]) + if diff < min_diff then + min_diff = diff + I = i + end + end + local diff = 32768 - (NLSF[L] + NDeltaMin[L + 1]) + if diff < min_diff then + min_diff = diff + I = L + end + if min_diff >= 0 then + return + end + if I == 0 then + NLSF[1] = NDeltaMin[1] + elseif I == L then + NLSF[L] = 32768 - NDeltaMin[L + 1] + else + local min_center = 0 + for k = 0, I - 1 do + min_center =min_center+ NDeltaMin[k + 1] + end + min_center =min_center+ math.floor(NDeltaMin[I + 1] / 2 +) local max_center = 32768 + for k = L, I + 1, -1 do + max_center =max_center- NDeltaMin[k + 1] + end + max_center =max_center- math.floor(NDeltaMin[I + 1] / 2 +) local c = math.floor((NLSF[I] + NLSF[I + 1] + 1) / 2 +) -- silk_LIMIT_32(c, min_center, max_center) + if min_center > max_center then + if c > min_center then + c = min_center + elseif c < max_center then + c = max_center + end + else + if c > max_center then + c = max_center + elseif c < min_center then + c = min_center + end + end + c = s16(c) + NLSF[I] = s16(c - math.floor(NDeltaMin[I + 1] / 2)) + NLSF[I + 1] = s16(NLSF[I] + NDeltaMin[I + 1]) + end + loops =loops+ 1 + end + -- fall back: insertion sort, then clamp + for i = 2, L do + local value = NLSF[i] + local j = i - 1 + while j >= 1 and value < NLSF[j] do + NLSF[j + 1] = NLSF[j] + j =j- 1 + end + NLSF[j + 1] = value + end + NLSF[1] = math.max(NLSF[1], NDeltaMin[1]) + for i = 2, L do + NLSF[i] = math.max(NLSF[i], sat16(NLSF[i - 1] + NDeltaMin[i])) + end + NLSF[L] = math.min(NLSF[L], 32768 - NDeltaMin[L + 1]) + for i = L - 1, 1, -1 do + NLSF[i] = math.min(NLSF[i], NLSF[i + 1] - NDeltaMin[i + 1]) + end +end + +-- silk_NLSF_decode: pNLSF_Q15 (1-based) from indices (1-based: [1] = CB1 index) +local function nlsfDecode(pNLSF_Q15, NLSFIndices, CB) + nlsfUnpack(CB, NLSFIndices[1]) + local order = CB.order + local step = CB.quantStepSize_Q16 + local out_Q10 = 0 + for i = order - 1, 0, -1 do + local pred = math.floor((out_Q10 * pred_Q8[i + 1]) / 256 +) out_Q10 = NLSFIndices[i + 2] * 1024 + if out_Q10 > 0 then + out_Q10 =out_Q10- 102 + elseif out_Q10 < 0 then + out_Q10 =out_Q10+ 102 + end + out_Q10 = pred + math.floor((out_Q10 * step) / 65536 +) res_Q10[i + 1] = out_Q10 + end + local base = NLSFIndices[1] * order + local cb, w = CB.CB1_NLSF_Q8, CB.CB1_Wght_Q9 + for i = 1, order do + local v = tdiv(res_Q10[i] * 16384, w[base + i]) + cb[base + i] * 128 + if v < 0 then + v = 0 + elseif v > 32767 then + v = 32767 + end + pNLSF_Q15[i] = v + end + nlsfStabilize(pNLSF_Q15, CB.deltaMin_Q15, order) +end + +-- Resampler (decoder side: 8 / 12 / 16 kHz up to the API rate) ---------------------------------------------------- + +local RES_COPY, RES_UP2, RES_IIR_FIR = 0, 1, 2 +local up2_hq_0 = { 1746, 14986, 39083 - 65536 } +local up2_hq_1 = { 6854, 25769, 55542 - 65536 } +local FIR12 = T.resampler_frac_FIR_12 +local delay_matrix_dec = { + { 4, 0, 2, 0, 0, 0 }, + { 0, 9, 4, 7, 4, 4 }, + { 0, 3, 12, 7, 7, 7 }, +} + +local function rateID(R) +local a = math.floor(R / 4096 )- (R > 16000 and 1 or 0) + if R > 24000 then + a = math.floor(a / 2 +) end + return math.min(5, a - 1) +end + +local function newResampler() +return { + sIIR = table.create(6, 0), + sFIR = table.create(8, 0), + delayBuf = table.create(96, 0), + buf = table.create(2 * 160 + 8, 0), + resampler_function = RES_COPY, + batchSize = 0, + invRatio_Q16 = 0, + inputDelay = 0, + Fs_in_kHz = 0, + Fs_out_kHz = 0, + } +end + +local function copyResampler(dst, src) + for i = 1, 6 do + dst.sIIR[i] = src.sIIR[i] + end + for i = 1, 8 do + dst.sFIR[i] = src.sFIR[i] + end + for i = 1, 96 do + dst.delayBuf[i] = src.delayBuf[i] + end + dst.resampler_function = src.resampler_function + dst.batchSize = src.batchSize + dst.invRatio_Q16 = src.invRatio_Q16 + dst.inputDelay = src.inputDelay + dst.Fs_in_kHz = src.Fs_in_kHz + dst.Fs_out_kHz = src.Fs_out_kHz +end + +local function resamplerInit(S, Fs_Hz_in, Fs_Hz_out) +table.clear(S.sIIR) + table.clear(S.sFIR) + table.clear(S.delayBuf) + for i = 1, 6 do + S.sIIR[i] = 0 + end + for i = 1, 8 do + S.sFIR[i] = 0 + end + for i = 1, 96 do + S.delayBuf[i] = 0 + end + if (Fs_Hz_in ~= 8000 and Fs_Hz_in ~= 12000 and Fs_Hz_in ~= 16000) or Fs_Hz_out < Fs_Hz_in then + return -1 -- the decoder only upsamples (or copies) + end + S.inputDelay = delay_matrix_dec[rateID(Fs_Hz_in) + 1][rateID(Fs_Hz_out) + 1] or 0 + S.Fs_in_kHz = math.floor(Fs_Hz_in / 1000 +) S.Fs_out_kHz = math.floor(Fs_Hz_out / 1000 +) S.batchSize = S.Fs_in_kHz * 10 + local up2x = 0 + if Fs_Hz_out > Fs_Hz_in then + if Fs_Hz_out == Fs_Hz_in * 2 then + S.resampler_function = RES_UP2 + else + S.resampler_function = RES_IIR_FIR + up2x = 1 + end + else + S.resampler_function = RES_COPY + end + local inv = math.floor((Fs_Hz_in * p2(14 + up2x)) / Fs_Hz_out )* 4 + while mulww(inv, Fs_Hz_out) < Fs_Hz_in * p2(up2x) do + inv =inv+ 1 + end + S.invRatio_Q16 = inv + return 0 +end + +-- silk_resampler_private_up2_HQ: out[oo + 2k], out[oo + 2k + 1] from inp[io + k] +local function up2HQ(S, out, oo, inp, io, len) + local s0, s1, s2, s3, s4, s5 = S[1], S[2], S[3], S[4], S[5], S[6] + local c00, c01, c02 = up2_hq_0[1], up2_hq_0[2], up2_hq_0[3] + local c10, c11, c12 = up2_hq_1[1], up2_hq_1[2], up2_hq_1[3] + for k = 0, len - 1 do + local in32 = inp[io + k] * 1024 + local Y = in32 - s0 + local X = math.floor((Y * c00) / 65536 +) local out32_1 = s0 + X + s0 = in32 + X + Y = out32_1 - s1 + X = math.floor((Y * c01) / 65536 +) local out32_2 = s1 + X + s1 = out32_1 + X + Y = out32_2 - s2 + X = Y + math.floor((Y * c02) / 65536 +) out32_1 = s2 + X + s2 = out32_2 + X + out[oo + 2 * k] = sat16(math.floor((out32_1 + 512) / 1024)) + Y = in32 - s3 + X = math.floor((Y * c10) / 65536 +) out32_1 = s3 + X + s3 = in32 + X + Y = out32_1 - s4 + X = math.floor((Y * c11) / 65536 +) out32_2 = s4 + X + s4 = out32_1 + X + Y = out32_2 - s5 + X = Y + math.floor((Y * c12) / 65536 +) out32_1 = s5 + X + s5 = out32_2 + X + out[oo + 2 * k + 1] = sat16(math.floor((out32_1 + 512) / 1024)) + end + S[1], S[2], S[3], S[4], S[5], S[6] = s0, s1, s2, s3, s4, s5 +end + +-- returns the next output index +local function iirFirInterpol(out, oo, buf, max_index_Q16, incr) +local index_Q16 = 0 + while index_Q16 < max_index_Q16 do + local ti = math.floor(((index_Q16 % 65536) * 12) / 65536 +) local b = math.floor(index_Q16 / 65536 )+ 1 -- buf is 1-based + local f0 = ti * 4 + local f1 = (11 - ti) * 4 + local res_Q15 = buf[b] * FIR12[f0 + 1] + + buf[b + 1] * FIR12[f0 + 2] + + buf[b + 2] * FIR12[f0 + 3] + + buf[b + 3] * FIR12[f0 + 4] + + buf[b + 4] * FIR12[f1 + 4] + + buf[b + 5] * FIR12[f1 + 3] + + buf[b + 6] * FIR12[f1 + 2] + + buf[b + 7] * FIR12[f1 + 1] + out[oo] = sat16(math.floor((res_Q15 + 16384) / 32768)) + oo =oo+ 1 + index_Q16 =index_Q16+ incr + end + return oo +end + +local function iirFir(S, out, oo, inp, io, inLen) + local buf = S.buf + local sFIR = S.sFIR + for i = 1, 8 do + buf[i] = sFIR[i] + end + local incr = S.invRatio_Q16 + local nSamplesIn + while true do + nSamplesIn = math.min(inLen, S.batchSize) + up2HQ(S.sIIR, buf, 9, inp, io, nSamplesIn) + oo = iirFirInterpol(out, oo, buf, nSamplesIn * 131072, incr) + io =io+ nSamplesIn + inLen =inLen- nSamplesIn + if inLen > 0 then + local o = nSamplesIn * 2 + for i = 1, 8 do + buf[i] = buf[o + i] + end + else + break + end + end + local o = nSamplesIn * 2 + for i = 1, 8 do + sFIR[i] = buf[o + i] + end +end + +local function resampleBlock(S, out, oo, inp, io, len) + local f = S.resampler_function + if f == RES_IIR_FIR then + iirFir(S, out, oo, inp, io, len) + elseif f == RES_UP2 then + up2HQ(S.sIIR, out, oo, inp, io, len) + else + for i = 0, len - 1 do + out[oo + i] = inp[io + i] + end + end +end + +-- silk_resampler: out[1..] from inp[io .. io + inLen - 1] +local function resampler(S, out, inp, io, inLen) + local fin = S.Fs_in_kHz + local delay = S.inputDelay + local nSamples = fin - delay + local db = S.delayBuf + for i = 0, nSamples - 1 do + db[delay + i + 1] = inp[io + i] + end + resampleBlock(S, out, 1, db, 1, fin) + resampleBlock(S, out, 1 + S.Fs_out_kHz, inp, io + nSamples, inLen - fin) + for i = 0, delay - 1 do + db[i + 1] = inp[io + inLen - delay + i] + end +end + +-- Decoder state ------------------------------------------------------------------------------------------------- + +local function newChannel() +return { + prev_gain_Q16 = 65536, + exc_Q14 = table.create(320, 0), + sLPC_Q14_buf = table.create(16, 0), + outBuf = table.create(480, 0), + lagPrev = 0, + LastGainIndex = 0, + fs_kHz = 0, + fs_API_hz = 0, + nb_subfr = 0, + frame_length = 0, + subfr_length = 0, + ltp_mem_length = 0, + LPC_order = 0, + prevNLSF_Q15 = table.create(16, 0), + first_frame_after_reset = 1, + pitch_lag_low_bits_iCDF = T.uniform4_iCDF, + pitch_contour_iCDF = T.pitch_contour_iCDF, + nFramesDecoded = 0, + nFramesPerPacket = 0, + ec_prevSignalType = 0, + ec_prevLagIndex = 0, + VAD_flags = { 0, 0, 0 }, + LBRR_flag = 0, + LBRR_flags = { 0, 0, 0 }, + resampler_state = newResampler(), + psNLSF_CB = CB_NB_MB, + indices = { + signalType = 0, + quantOffsetType = 0, + GainsIndices = { 0, 0, 0, 0 }, + NLSFIndices = table.create(17, 0), + NLSFInterpCoef_Q2 = 0, + lagIndex = 0, + contourIndex = 0, + PERIndex = 0, + LTPIndex = { 0, 0, 0, 0 }, + LTP_scaleIndex = 0, + Seed = 0, + }, + sCNG = { + CNG_exc_buf_Q14 = table.create(320, 0), + CNG_smth_NLSF_Q15 = table.create(16, 0), + CNG_synth_state = table.create(16, 0), + CNG_smth_Gain_Q16 = 0, + rand_seed = 3176576, + fs_kHz = 0, + }, + lossCnt = 0, + prevSignalType = 0, + sPLC = { + pitchL_Q8 = 0, + LTPCoef_Q14 = table.create(5, 0), + prevLPC_Q12 = table.create(16, 0), + last_frame_lost = 0, + rand_seed = 0, + randScale_Q14 = 0, + conc_energy = 0, + conc_energy_shift = 0, + prevLTP_scale_Q14 = 0, + prevGain_Q16 = { 65536, 65536 }, + fs_kHz = 0, + nb_subfr = 2, + subfr_length = 20, + }, + -- per-frame decoder control (silk_decoder_control) and scratch + ctrl = { + pitchL = { 0, 0, 0, 0 }, + Gains_Q16 = { 0, 0, 0, 0 }, + PredCoef_Q12 = { table.create(16, 0), table.create(16, 0) }, + LTPCoef_Q14 = table.create(20, 0), + LTP_scale_Q14 = 0, + }, + pulses = table.create(336, 0), + out = table.create(322, 0), -- samplesOut1_tmp: [1], [2] = the 2 buffered samples, frame from [3] + } +end + +local function decoderSetFs(ch, fs_kHz, fs_API_Hz) +local ret = 0 + ch.subfr_length = 5 * fs_kHz + local frame_length = ch.nb_subfr * ch.subfr_length + if ch.fs_kHz ~= fs_kHz or ch.fs_API_hz ~= fs_API_Hz then + ret =ret+ resamplerInit(ch.resampler_state, fs_kHz * 1000, fs_API_Hz) + ch.fs_API_hz = fs_API_Hz + end + if ch.fs_kHz ~= fs_kHz or frame_length ~= ch.frame_length then + if fs_kHz == 8 then + ch.pitch_contour_iCDF = (ch.nb_subfr == 4 and{T.pitch_contour_NB_iCDF }or{T.pitch_contour_10_ms_NB_iCDF +})[1] else + ch.pitch_contour_iCDF = (ch.nb_subfr == 4 and{T.pitch_contour_iCDF }or{T.pitch_contour_10_ms_iCDF +})[1] end + if ch.fs_kHz ~= fs_kHz then + ch.ltp_mem_length = 20 * fs_kHz + if fs_kHz == 8 or fs_kHz == 12 then + ch.LPC_order = 10 + ch.psNLSF_CB = CB_NB_MB + else + ch.LPC_order = 16 + ch.psNLSF_CB = CB_WB + end + if fs_kHz == 16 then + ch.pitch_lag_low_bits_iCDF = T.uniform8_iCDF + elseif fs_kHz == 12 then + ch.pitch_lag_low_bits_iCDF = T.uniform6_iCDF + else + ch.pitch_lag_low_bits_iCDF = T.uniform4_iCDF + end + ch.first_frame_after_reset = 1 + ch.lagPrev = 100 + ch.LastGainIndex = 10 + ch.prevSignalType = 0 + local ob, sl = ch.outBuf, ch.sLPC_Q14_buf + for i = 1, 480 do + ob[i] = 0 + end + for i = 1, 16 do + sl[i] = 0 + end + end + ch.fs_kHz = fs_kHz + ch.frame_length = frame_length + end + return ret +end + +-- Bitstream: indices and pulses --------------------------------------------------------------------------------- + +local LTP_gain_iCDF = { T.LTP_gain_iCDF_0, T.LTP_gain_iCDF_1, T.LTP_gain_iCDF_2 } +local LTP_vq_Q7 = { T.LTP_gain_vq_0, T.LTP_gain_vq_1, T.LTP_gain_vq_2 } +local LBRR_flags_iCDF = { T.LBRR_flags_2_iCDF, T.LBRR_flags_3_iCDF } + +local function decodeIndices(ch, d, FrameIndex, decode_LBRR, condCoding) + local ind = ch.indices + local Ix + if decode_LBRR or ch.VAD_flags[FrameIndex + 1] ~= 0 then + Ix = icdf(d, T.type_offset_VAD_iCDF, 1, 8) + 2 + else + Ix = icdf(d, T.type_offset_no_VAD_iCDF, 1, 8) + end + local signalType = math.floor(Ix / 2 +) ind.signalType = signalType + ind.quantOffsetType = Ix % 2 + local gi = ind.GainsIndices + if condCoding == 2 then + gi[1] = icdf(d, T.delta_gain_iCDF, 1, 8) + else + gi[1] = icdf(d, T.gain_iCDF, signalType * 8 + 1, 8) * 8 + gi[1]=gi[1]+ icdf(d, T.uniform8_iCDF, 1, 8) + end + for i = 2, ch.nb_subfr do + gi[i] = icdf(d, T.delta_gain_iCDF, 1, 8) + end + local CB = ch.psNLSF_CB + local ni = ind.NLSFIndices + ni[1] = icdf(d, CB.CB1_iCDF, (math.floor(signalType / 2)) * CB.nVectors + 1, 8) + nlsfUnpack(CB, ni[1]) + for i = 1, CB.order do + Ix = icdf(d, CB.ec_iCDF, ec_ix[i] + 1, 8) + if Ix == 0 then + Ix =Ix- icdf(d, T.NLSF_EXT_iCDF, 1, 8) + elseif Ix == 8 then + Ix =Ix+ icdf(d, T.NLSF_EXT_iCDF, 1, 8) + end + ni[i + 1] = Ix - 4 + end + if ch.nb_subfr == 4 then + ind.NLSFInterpCoef_Q2 = icdf(d, T.NLSF_interpolation_factor_iCDF, 1, 8) + else + ind.NLSFInterpCoef_Q2 = 4 + end + if signalType == 2 then + local absolute = true + if condCoding == 2 and ch.ec_prevSignalType == 2 then + local delta = icdf(d, T.pitch_delta_iCDF, 1, 8) + if delta > 0 then + ind.lagIndex = s16(ch.ec_prevLagIndex + delta - 9) + absolute = false + end + end + if absolute then + ind.lagIndex = icdf(d, T.pitch_lag_iCDF, 1, 8) * (math.floor(ch.fs_kHz / 2)) + ind.lagIndex =ind.lagIndex+ icdf(d, ch.pitch_lag_low_bits_iCDF, 1, 8) + end + ch.ec_prevLagIndex = ind.lagIndex + ind.contourIndex = icdf(d, ch.pitch_contour_iCDF, 1, 8) + ind.PERIndex = icdf(d, T.LTP_per_index_iCDF, 1, 8) + local tab = LTP_gain_iCDF[ind.PERIndex + 1] + for k = 1, ch.nb_subfr do + ind.LTPIndex[k] = icdf(d, tab, 1, 8) + end + if condCoding == 0 then + ind.LTP_scaleIndex = icdf(d, T.LTPscale_iCDF, 1, 8) + else + ind.LTP_scaleIndex = 0 + end + end + ch.ec_prevSignalType = signalType + ind.Seed = icdf(d, T.uniform4_iCDF, 1, 8) +end + +local shell0, shell1, shell2, shell3 = T.shell_code_table0, T.shell_code_table1, T.shell_code_table2, T.shell_code_table3 +local shellOff = T.shell_code_table_offsets + +local function split(d, p, tab) +if p > 0 then + local a = icdf(d, tab, shellOff[p + 1] + 1, 8) + return a, p - a + end + return 0, 0 +end + +local function shellDecoder(out, o, d, pulses4) + local p3a, p3b = split(d, pulses4, shell3) + local p2a, p2b = split(d, p3a, shell2) + local p1a, p1b = split(d, p2a, shell1) + out[o], out[o + 1] = split(d, p1a, shell0) + out[o + 2], out[o + 3] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 4], out[o + 5] = split(d, p1a, shell0) + out[o + 6], out[o + 7] = split(d, p1b, shell0) + p2a, p2b = split(d, p3b, shell2) + p1a, p1b = split(d, p2a, shell1) + out[o + 8], out[o + 9] = split(d, p1a, shell0) + out[o + 10], out[o + 11] = split(d, p1b, shell0) + p1a, p1b = split(d, p2b, shell1) + out[o + 12], out[o + 13] = split(d, p1a, shell0) + out[o + 14], out[o + 15] = split(d, p1b, shell0) +end + +local sum_pulses = table.create(20, 0) +local nLshifts = table.create(20, 0) +local signIcdf = { 0, 0 } + +-- pulses[1 .. frame_length (rounded up to 16)] +local function decodePulses(d, pulses, signalType, quantOffsetType, frame_length) + local RateLevelIndex = icdf(d, T.rate_levels_iCDF, (math.floor(signalType / 2)) * 9 + 1, 8) + local iter = math.floor(frame_length / 16 +) if iter * 16 < frame_length then + iter =iter+ 1 + end + local ppb = T.pulses_per_block_iCDF + for i = 1, iter do + nLshifts[i] = 0 + local s = icdf(d, ppb, RateLevelIndex * 18 + 1, 8) + while s == 17 do + nLshifts[i]=nLshifts[i]+ 1 + s = icdf(d, ppb, 9 * 18 + 1 + (nLshifts[i] == 10 and 1 or 0), 8) + if nLshifts[i] > 30 then + break -- corrupt stream guard + end + end + sum_pulses[i] = s + end + for i = 1, iter do + local o = (i - 1) * 16 + 1 + if sum_pulses[i] > 0 then + shellDecoder(pulses, o, d, sum_pulses[i]) + else + for k = 0, 15 do + pulses[o + k] = 0 + end + end + end + local lsb = T.lsb_iCDF + for i = 1, iter do + local nLS = nLshifts[i] + if nLS > 0 then + local o = (i - 1) * 16 + 1 + for k = 0, 15 do + local abs_q = pulses[o + k] + for _ = 1, nLS do + abs_q = abs_q * 2 + icdf(d, lsb, 1, 8) + end + pulses[o + k] = abs_q + end + sum_pulses[i]=sum_pulses[i]+ nLS * 32 + end + end + -- silk_decode_signs + local signTab = T.sign_iCDF + local base = 7 * (quantOffsetType + signalType * 2) + local blocks = math.floor((frame_length + 8) / 16 +) for i = 1, blocks do + local p = sum_pulses[i] + if p > 0 then + signIcdf[1] = signTab[base + math.min(p % 32, 6) + 1] + local o = (i - 1) * 16 + 1 + for j = 0, 15 do + local q = pulses[o + j] + if q > 0 then + pulses[o + j] = q * (icdf(d, signIcdf, 1, 8) * 2 - 1) + end + end + end + end +end + +-- Parameters ---------------------------------------------------------------------------------------------------- + +local pNLSF_Q15 = table.create(16, 0) +local pNLSF0_Q15 = table.create(16, 0) + +local function gainsDequant(gain_Q16, ind, ch, conditional, nb_subfr) + local prev = ch.LastGainIndex + for k = 1, nb_subfr do + if k == 1 and not conditional then + prev = math.max(ind[k], prev - 16) + else + local ind_tmp = ind[k] - 4 + local thr = 8 + prev + if ind_tmp > thr then + prev =prev+ (ind_tmp * 2 - thr +) else + prev =prev+ ind_tmp + end + end + if prev < 0 then + prev = 0 + elseif prev > 63 then + prev = 63 + end + gain_Q16[k] = silkLog2lin(math.min(math.floor((1907825 * prev) / 65536 )+ 2090, 3967)) + end + ch.LastGainIndex = prev +end + +local CB_lags = { + [8] = { [4] = { T.CB_lags_stage2, 11 }, [2] = { T.CB_lags_stage2_10_ms, 3 } }, + [0] = { [4] = { T.CB_lags_stage3, 34 }, [2] = { T.CB_lags_stage3_10_ms, 12 } }, +} + +local function decodeParameters(ch, ctrl, condCoding) + local ind = ch.indices + gainsDequant(ctrl.Gains_Q16, ind.GainsIndices, ch, condCoding == 2, ch.nb_subfr) + local order = ch.LPC_order + nlsfDecode(pNLSF_Q15, ind.NLSFIndices, ch.psNLSF_CB) + nlsf2a(ctrl.PredCoef_Q12[2], pNLSF_Q15, order) + if ch.first_frame_after_reset == 1 then + ind.NLSFInterpCoef_Q2 = 4 + end + local prevNLSF = ch.prevNLSF_Q15 + if ind.NLSFInterpCoef_Q2 < 4 then + local c = ind.NLSFInterpCoef_Q2 + for i = 1, order do + pNLSF0_Q15[i] = prevNLSF[i] + math.floor((c * (pNLSF_Q15[i] - prevNLSF[i])) / 4 +) end + nlsf2a(ctrl.PredCoef_Q12[1], pNLSF0_Q15, order) + else + local a, b = ctrl.PredCoef_Q12[1], ctrl.PredCoef_Q12[2] + for i = 1, order do + a[i] = b[i] + end + end + for i = 1, order do + prevNLSF[i] = pNLSF_Q15[i] + end + if ch.lossCnt ~= 0 then + bwexpander(ctrl.PredCoef_Q12[1], order, 63570) + bwexpander(ctrl.PredCoef_Q12[2], order, 63570) + end + if ind.signalType == 2 then + -- silk_decode_pitch + local fs = ch.fs_kHz + local cbinfo = CB_lags[fs == 8 and 8 or 0][ch.nb_subfr] + local cb, cbk_size = cbinfo[1], cbinfo[2] + local min_lag, max_lag = 2 * fs, 18 * fs + local lag = min_lag + ind.lagIndex + for k = 0, ch.nb_subfr - 1 do + local v = lag + cb[k * cbk_size + ind.contourIndex + 1] + if v < min_lag then + v = min_lag + elseif v > max_lag then + v = max_lag + end + ctrl.pitchL[k + 1] = v + end + local vq = LTP_vq_Q7[ind.PERIndex + 1] + for k = 0, ch.nb_subfr - 1 do + local Ix = ind.LTPIndex[k + 1] + for i = 1, 5 do + ctrl.LTPCoef_Q14[k * 5 + i] = vq[Ix * 5 + i] * 128 + end + end + ctrl.LTP_scale_Q14 = T.LTPScales_table_Q14[ind.LTP_scaleIndex + 1] + else + for k = 1, ch.nb_subfr do + ctrl.pitchL[k] = 0 + end + for k = 1, 5 * ch.nb_subfr do + ctrl.LTPCoef_Q14[k] = 0 + end + ind.PERIndex = 0 + ctrl.LTP_scale_Q14 = 0 + end +end + +-- Core synthesis ------------------------------------------------------------------------------------------------ + +local sLTP = table.create(320, 0) +local sLTP_Q15 = table.create(640, 0) +local res_Q14 = table.create(80, 0) +local sLPC_Q14 = table.create(96, 0) +local A_Q12_tmp = table.create(16, 0) +local QuantOffsets = { { 100, 240 }, { 32, 100 } } + +-- silk_decode_core: xq[xo .. xo + frame_length - 1] +local function decodeCore(ch, ctrl, xq, xo, pulses) + local ind = ch.indices + local exc = ch.exc_Q14 + local offset_Q10 = QuantOffsets[math.floor(ind.signalType / 2 )+ 1][ind.quantOffsetType + 1] + local NLSF_interpolation_flag = ind.NLSFInterpCoef_Q2 < 4 + local frame_length = ch.frame_length + local subfr_length = ch.subfr_length + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local outBuf = ch.outBuf + + local rand_seed = ind.Seed + for i = 1, frame_length do + rand_seed = silkRand(rand_seed) + local p = pulses[i] + local e = p * 16384 + if e > 0 then + e =e- 1280 + elseif e < 0 then + e =e+ 1280 + end + e =e+ offset_Q10 * 16 + if rand_seed < 0 then + e = -e + end + exc[i] = e + rand_seed = i32(rand_seed + p) + end + + local sl = ch.sLPC_Q14_buf + for i = 1, 16 do + sLPC_Q14[i] = sl[i] + end + local pexc = 0 -- C offset into exc + local pxq = xo + local sLTP_buf_idx = ltp_mem_length -- C index into sLTP_Q15 + local lag = 0 + for k = 0, ch.nb_subfr - 1 do + local A_Q12 = ctrl.PredCoef_Q12[math.floor(k / 2 )+ 1] + for i = 1, order do + A_Q12_tmp[i] = A_Q12[i] + end + local Bo = k * 5 -- C offset into LTPCoef_Q14 + local B = ctrl.LTPCoef_Q14 + local signalType = ind.signalType + local gain = ctrl.Gains_Q16[k + 1] + local Gain_Q10 = math.floor(gain / 64 +) local inv_gain_Q31 = silkINVERSE32_varQ(gain, 47) + local gain_adj_Q16 + if gain ~= ch.prev_gain_Q16 then + gain_adj_Q16 = silkDIV32_varQ(ch.prev_gain_Q16, gain, 16) + for i = 1, 16 do + sLPC_Q14[i] = i32(mulww(gain_adj_Q16, sLPC_Q14[i])) + end + else + gain_adj_Q16 = 65536 + end + ch.prev_gain_Q16 = gain + if ch.lossCnt ~= 0 and ch.prevSignalType == 2 and ind.signalType ~= 2 and k < 2 then + for i = 1, 5 do + B[Bo + i] = 0 + end + B[Bo + 3] = 4096 + signalType = 2 + ctrl.pitchL[k + 1] = ch.lagPrev + end + if signalType == 2 then + lag = ctrl.pitchL[k + 1] + if k == 0 or (k == 2 and NLSF_interpolation_flag) then + local start_idx = ltp_mem_length - lag - order - 2 + if start_idx < 1 then + start_idx = 1 -- corrupt stream guard (C asserts start_idx > 0) + end + if k == 2 then + for i = 0, 2 * subfr_length - 1 do + outBuf[ltp_mem_length + i + 1] = xq[xo + i] + end + end + lpcAnalysisFilter(sLTP, start_idx + 1, outBuf, start_idx + k * subfr_length + 1, A_Q12, ltp_mem_length - start_idx, order) + if k == 0 then + inv_gain_Q31 = (math.floor((inv_gain_Q31 * ctrl.LTP_scale_Q14) / 65536)) * 4 + end + for i = 0, lag + 1 do + sLTP_Q15[sLTP_buf_idx - i] = math.floor((inv_gain_Q31 * sLTP[ltp_mem_length - i]) / 65536 +) end + else + if gain_adj_Q16 ~= 65536 then + for i = 0, lag + 1 do + local j = sLTP_buf_idx - i + sLTP_Q15[j] = i32(mulww(gain_adj_Q16, sLTP_Q15[j])) + end + end + end + end + local presArr, presOff + if signalType == 2 then + local b0, b1, b2, b3, b4 = B[Bo + 1], B[Bo + 2], B[Bo + 3], B[Bo + 4], B[Bo + 5] + local pl = sLTP_buf_idx - lag + 2 + 1 -- 1-based index of pred_lag_ptr[0] + for i = 1, subfr_length do + local pred = 2 + pred =pred+ math.floor((sLTP_Q15[pl] * b0) / 65536 +) pred =pred+ math.floor((sLTP_Q15[pl - 1] * b1) / 65536 +) pred =pred+ math.floor((sLTP_Q15[pl - 2] * b2) / 65536 +) pred =pred+ math.floor((sLTP_Q15[pl - 3] * b3) / 65536 +) pred =pred+ math.floor((sLTP_Q15[pl - 4] * b4) / 65536 +) pl =pl+ 1 + local r = exc[pexc + i] + pred * 2 + res_Q14[i] = r + sLTP_buf_idx =sLTP_buf_idx+ 1 + sLTP_Q15[sLTP_buf_idx] = r * 2 + end + presArr, presOff = res_Q14, 0 + else + presArr, presOff = exc, pexc + end + local a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = + A_Q12_tmp[1], A_Q12_tmp[2], A_Q12_tmp[3], A_Q12_tmp[4], A_Q12_tmp[5], + A_Q12_tmp[6], A_Q12_tmp[7], A_Q12_tmp[8], A_Q12_tmp[9], A_Q12_tmp[10] + local wide = order == 16 + local a10, a11, a12, a13, a14, a15 = A_Q12_tmp[11], A_Q12_tmp[12], A_Q12_tmp[13], A_Q12_tmp[14], A_Q12_tmp[15], A_Q12_tmp[16] + for i = 1, subfr_length do + local j = 16 + i -- 1-based index of sLPC_Q14[MAX_LPC_ORDER + i - 1 (C)] + 1 + local pred = math.floor(order / 2 +) pred =pred+ math.floor((sLPC_Q14[j - 1] * a0) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 2] * a1) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 3] * a2) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 4] * a3) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 5] * a4) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 6] * a5) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 7] * a6) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 8] * a7) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 9] * a8) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 10] * a9) / 65536 +) if wide then + pred =pred+ math.floor((sLPC_Q14[j - 11] * a10) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 12] * a11) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 13] * a12) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 14] * a13) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 15] * a14) / 65536 +) pred =pred+ math.floor((sLPC_Q14[j - 16] * a15) / 65536 +) end + pred = i32(pred) + local v = addSat32(presArr[presOff + i], lshiftSat32(pred, 4)) + sLPC_Q14[j] = v + xq[pxq + i - 1] = sat16(math.floor((mulww(v, Gain_Q10) + 128) / 256)) + end + for i = 1, 16 do + sLPC_Q14[i] = sLPC_Q14[subfr_length + i] + end + pexc =pexc+ subfr_length + pxq =pxq+ subfr_length + end + for i = 1, 16 do + sl[i] = sLPC_Q14[i] + end +end + +-- PLC / CNG ----------------------------------------------------------------------------------------------------- + +local HARM_ATT_Q15 = { 32440, 31130 } +local PLC_RAND_ATTENUATE_V_Q15 = { 31130, 26214 } +local PLC_RAND_ATTENUATE_UV_Q15 = { 32440, 29491 } + +local function plcReset(ch) + local plc = ch.sPLC + plc.pitchL_Q8 = ch.frame_length * 128 + plc.prevGain_Q16[1] = 65536 + plc.prevGain_Q16[2] = 65536 + plc.subfr_length = 20 + plc.nb_subfr = 2 +end + +local function cngReset(ch) + local step = tdiv(32767, ch.LPC_order + 1) + local acc = 0 + local cng = ch.sCNG + for i = 1, ch.LPC_order do + acc =acc+ step + cng.CNG_smth_NLSF_Q15[i] = acc + end + cng.CNG_smth_Gain_Q16 = 0 + cng.rand_seed = 3176576 +end + +local function plcUpdate(ch, ctrl) + local plc = ch.sPLC + local nb = ch.nb_subfr + ch.prevSignalType = ch.indices.signalType + local LTP_Gain_Q14 = 0 + local coef = plc.LTPCoef_Q14 + if ch.indices.signalType == 2 then + local j = 0 + while j * ch.subfr_length < ctrl.pitchL[nb] do + if j == nb then + break + end + local t = 0 + local o = (nb - 1 - j) * 5 + for i = 1, 5 do + t =t+ ctrl.LTPCoef_Q14[o + i] + end + if t > LTP_Gain_Q14 then + LTP_Gain_Q14 = t + for i = 1, 5 do + coef[i] = ctrl.LTPCoef_Q14[o + i] + end + plc.pitchL_Q8 = ctrl.pitchL[nb - j] * 256 + end + j =j+ 1 + end + for i = 1, 5 do + coef[i] = 0 + end + coef[3] = LTP_Gain_Q14 + if LTP_Gain_Q14 < 11469 then + local scale_Q10 = tdiv(11469 * 1024, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = math.floor((s16(coef[i]) * s16(scale_Q10)) / 1024 +) end + elseif LTP_Gain_Q14 > 15565 then + local scale_Q14 = tdiv(15565 * 16384, math.max(LTP_Gain_Q14, 1)) + for i = 1, 5 do + coef[i] = math.floor((s16(coef[i]) * s16(scale_Q14)) / 16384 +) end + end + else + plc.pitchL_Q8 = ch.fs_kHz * 18 * 256 + for i = 1, 5 do + coef[i] = 0 + end + end + local p = ctrl.PredCoef_Q12[2] + for i = 1, ch.LPC_order do + plc.prevLPC_Q12[i] = p[i] + end + plc.prevLTP_scale_Q14 = ctrl.LTP_scale_Q14 + plc.prevGain_Q16[1] = ctrl.Gains_Q16[nb - 1] + plc.prevGain_Q16[2] = ctrl.Gains_Q16[nb] + plc.subfr_length = ch.subfr_length + plc.nb_subfr = nb +end + +local excBuf = table.create(160, 0) +local plcLTP = table.create(320, 0) +local plcLTP_Q14 = table.create(640, 0) +local A_plc = table.create(16, 0) + +local function plcConceal(ch, ctrl, frame, fo) + local plc = ch.sPLC + local ltp_mem_length = ch.ltp_mem_length + local order = ch.LPC_order + local prevGain_Q10_0 = math.floor(plc.prevGain_Q16[1] / 64 +) local prevGain_Q10_1 = math.floor(plc.prevGain_Q16[2] / 64 +) if ch.first_frame_after_reset ~= 0 then + for i = 1, 16 do + plc.prevLPC_Q12[i] = 0 + end + end + -- silk_PLC_energy + local sl, nb = ch.subfr_length, ch.nb_subfr + local exc = ch.exc_Q14 + for k = 0, 1 do + local g = (k == 0 and{prevGain_Q10_0 }or{prevGain_Q10_1 +})[1] for i = 0, sl - 1 do + excBuf[k * sl + i + 1] = sat16(math.floor(i32(mulww(exc[i + (k + nb - 2) * sl + 1], g)) / 256)) + end + end + local energy1, shift1 = sumSqrShift(excBuf, 1, sl) + local energy2, shift2 = sumSqrShift(excBuf, sl + 1, sl) + local rand_off -- C offset into exc_Q14 + if rshift(energy1, shift2) < rshift(energy2, shift1) then + rand_off = math.max(0, (plc.nb_subfr - 1) * plc.subfr_length - 128) + else + rand_off = math.max(0, plc.nb_subfr * plc.subfr_length - 128) + end + local B = plc.LTPCoef_Q14 + local rand_scale_Q14 = plc.randScale_Q14 + local att = math.min(1, ch.lossCnt) + 1 + local harm_Gain_Q15 = HARM_ATT_Q15[att] + local rand_Gain_Q15 = (ch.prevSignalType == 2 and{PLC_RAND_ATTENUATE_V_Q15[att] }or{PLC_RAND_ATTENUATE_UV_Q15[att] +})[1] bwexpander(plc.prevLPC_Q12, order, 64881) + for i = 1, order do + A_plc[i] = plc.prevLPC_Q12[i] + end + if ch.lossCnt == 0 then + rand_scale_Q14 = 16384 + if ch.prevSignalType == 2 then + for i = 1, 5 do + rand_scale_Q14 =rand_scale_Q14- B[i] + end + rand_scale_Q14 = math.max(3277, s16(rand_scale_Q14)) + rand_scale_Q14 = s16(math.floor((rand_scale_Q14 * s16(plc.prevLTP_scale_Q14)) / 16384)) + else + local invGain_Q30 = lpcInversePredGain(plc.prevLPC_Q12, order) + local down = math.min(math.floor(1073741824 / 8), invGain_Q30) + down = math.max(math.floor(1073741824 / 256), down) + down = down * 8 + rand_Gain_Q15 = math.floor((math.floor((down * s16(rand_Gain_Q15)) / 65536)) / 16384 +) end + end + local rand_seed = plc.rand_seed + local lag = math.floor((plc.pitchL_Q8 + 128) / 256 +) local sLTP_buf_idx = ltp_mem_length + local idx = ltp_mem_length - lag - order - 2 + if idx < 1 then + idx = 1 + end + lpcAnalysisFilter(plcLTP, idx + 1, ch.outBuf, idx + 1, A_plc, ltp_mem_length - idx, order) + local inv_gain_Q30 = silkINVERSE32_varQ(plc.prevGain_Q16[2], 46) + inv_gain_Q30 = math.min(inv_gain_Q30, 1073741823) + for i = idx + order, ltp_mem_length - 1 do + plcLTP_Q14[i + 1] = math.floor((inv_gain_Q30 * plcLTP[i + 1]) / 65536 +) end + for _ = 0, ch.nb_subfr - 1 do + local pl = sLTP_buf_idx - lag + 2 + 1 + local b0, b1, b2, b3, b4 = B[1], B[2], B[3], B[4], B[5] + for _ = 1, sl do + local pred = 2 + pred =pred+ math.floor((plcLTP_Q14[pl] * b0) / 65536 +) pred =pred+ math.floor((plcLTP_Q14[pl - 1] * b1) / 65536 +) pred =pred+ math.floor((plcLTP_Q14[pl - 2] * b2) / 65536 +) pred =pred+ math.floor((plcLTP_Q14[pl - 3] * b3) / 65536 +) pred =pred+ math.floor((plcLTP_Q14[pl - 4] * b4) / 65536 +) pl =pl+ 1 + rand_seed = silkRand(rand_seed) + local ri = (math.floor(rand_seed / 33554432)) % 128 + sLTP_buf_idx =sLTP_buf_idx+ 1 + plcLTP_Q14[sLTP_buf_idx] = i32((pred + math.floor((exc[rand_off + ri + 1] * s16(rand_scale_Q14)) / 65536)) * 4) + end + for j = 1, 5 do + B[j] = math.floor((harm_Gain_Q15 * s16(B[j])) / 32768 +) end + rand_scale_Q14 = math.floor((s16(rand_scale_Q14) * s16(rand_Gain_Q15)) / 32768 +) plc.pitchL_Q8 = plc.pitchL_Q8 + math.floor((plc.pitchL_Q8 * 655) / 65536 +) plc.pitchL_Q8 = math.min(plc.pitchL_Q8, 18 * ch.fs_kHz * 256) + lag = math.floor((plc.pitchL_Q8 + 128) / 256 +) end + -- LPC synthesis in place over plcLTP_Q14, starting at C offset ltp_mem_length - 16 + local base = ltp_mem_length - 16 -- C offset of sLPC_Q14_ptr + local slb = ch.sLPC_Q14_buf + for i = 1, 16 do + plcLTP_Q14[base + i] = slb[i] + end + for i = 0, ch.frame_length - 1 do + local j = base + 16 + i + 1 -- 1-based index of sLPC_Q14_ptr[16 + i] + local pred = math.floor(order / 2 +) for t = 1, order do + pred =pred+ math.floor((plcLTP_Q14[j - t] * A_plc[t]) / 65536 +) end + pred = i32(pred) + local v = addSat32(plcLTP_Q14[j], lshiftSat32(pred, 4)) + plcLTP_Q14[j] = v + frame[fo + i] = sat16(math.floor((mulww(v, prevGain_Q10_1) + 128) / 256)) + end + for i = 1, 16 do + slb[i] = plcLTP_Q14[base + ch.frame_length + i] + end + plc.rand_seed = rand_seed + plc.randScale_Q14 = s16(rand_scale_Q14) + for i = 1, 4 do + ctrl.pitchL[i] = lag + end +end + +local function plcGlueFrames(ch, frame, fo, length) + local plc = ch.sPLC + if ch.lossCnt ~= 0 then + plc.conc_energy, plc.conc_energy_shift = sumSqrShift(frame, fo, length) + plc.last_frame_lost = 1 + else + if plc.last_frame_lost ~= 0 then + local energy, energy_shift = sumSqrShift(frame, fo, length) + if energy_shift > plc.conc_energy_shift then + plc.conc_energy = rshift(plc.conc_energy, energy_shift - plc.conc_energy_shift) + elseif energy_shift < plc.conc_energy_shift then + energy = rshift(energy, plc.conc_energy_shift - energy_shift) + end + if energy > plc.conc_energy then + local LZ = clz32(plc.conc_energy) - 1 + plc.conc_energy = i32(plc.conc_energy * p2(LZ)) + energy = rshift(energy, math.max(24 - LZ, 0)) + local frac_Q24 = tdiv(plc.conc_energy, math.max(energy, 1)) + local gain_Q16 = silkSQRT_APPROX(frac_Q24) * 16 + local slope_Q16 = tdiv(65536 - gain_Q16, length) * 4 + for i = 0, length - 1 do + frame[fo + i] = math.floor((gain_Q16 * frame[fo + i]) / 65536 +) gain_Q16 =gain_Q16+ slope_Q16 + if gain_Q16 > 65536 then + break + end + end + end + end + plc.last_frame_lost = 0 + end +end + +local A_cng = table.create(16, 0) +local CNG_sig = table.create(336, 0) + +local function cng(ch, ctrl, frame, fo, length) + local c = ch.sCNG + if ch.fs_kHz ~= c.fs_kHz then + cngReset(ch) + c.fs_kHz = ch.fs_kHz + end + local order = ch.LPC_order + if ch.lossCnt == 0 and ch.prevSignalType == 0 then + local sm = c.CNG_smth_NLSF_Q15 + for i = 1, order do + sm[i]=sm[i]+ math.floor(((ch.prevNLSF_Q15[i] - sm[i]) * 16348) / 65536 +) end + local max_Gain_Q16, subfr = 0, 0 + for i = 0, ch.nb_subfr - 1 do + if ctrl.Gains_Q16[i + 1] > max_Gain_Q16 then + max_Gain_Q16 = ctrl.Gains_Q16[i + 1] + subfr = i + end + end + local eb = c.CNG_exc_buf_Q14 + local sl = ch.subfr_length + for i = (ch.nb_subfr - 1) * sl, 1, -1 do + eb[sl + i] = eb[i] + end + for i = 1, sl do + eb[i] = ch.exc_Q14[subfr * sl + i] + end + for i = 1, ch.nb_subfr do + local g = ctrl.Gains_Q16[i] + c.CNG_smth_Gain_Q16 =c.CNG_smth_Gain_Q16+ math.floor(((g - c.CNG_smth_Gain_Q16) * 4634) / 65536 +) if mulww(c.CNG_smth_Gain_Q16, 46396) > g then + c.CNG_smth_Gain_Q16 = g + end + end + end + if ch.lossCnt ~= 0 then + local gain_Q16 = i32(mulww(ch.sPLC.randScale_Q14, ch.sPLC.prevGain_Q16[2])) + if gain_Q16 >= 2097152 or c.CNG_smth_Gain_Q16 > 8388608 then + gain_Q16 = (math.floor(gain_Q16 / 65536)) * (math.floor(gain_Q16 / 65536)) + gain_Q16 = i32((math.floor(c.CNG_smth_Gain_Q16 / 65536)) * (math.floor(c.CNG_smth_Gain_Q16 / 65536)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 65536) + else + gain_Q16 = i32(mulww(gain_Q16, gain_Q16)) + gain_Q16 = i32(i32(mulww(c.CNG_smth_Gain_Q16, c.CNG_smth_Gain_Q16)) - gain_Q16 * 32) + gain_Q16 = i32(silkSQRT_APPROX(gain_Q16) * 256) + end + local gain_Q10 = math.floor(gain_Q16 / 64 +) -- silk_CNG_exc + local exc_mask = 255 + while exc_mask > length do + exc_mask =math.floor(exc_mask/ 2 +) end + local seed = c.rand_seed + for i = 1, length do + seed = silkRand(seed) + local idx = bit32.band((math.floor(seed / 16777216)) % 256, exc_mask) + CNG_sig[16 + i] = c.CNG_exc_buf_Q14[idx + 1] + end + c.rand_seed = seed + nlsf2a(A_cng, c.CNG_smth_NLSF_Q15, order) + for i = 1, 16 do + CNG_sig[i] = c.CNG_synth_state[i] + end + for i = 0, length - 1 do + local j = 16 + i + 1 + local pred = math.floor(order / 2 +) for t = 1, order do + pred =pred+ math.floor((CNG_sig[j - t] * A_cng[t]) / 65536 +) end + pred = i32(pred) + local v = addSat32(CNG_sig[j], lshiftSat32(pred, 4)) + CNG_sig[j] = v + frame[fo + i] = sat16(frame[fo + i] + sat16(math.floor((mulww(v, gain_Q10) + 128) / 256))) + end + for i = 1, 16 do + c.CNG_synth_state[i] = CNG_sig[length + i] + end + else + for i = 1, order do + c.CNG_synth_state[i] = 0 + end + end +end + +-- Frame decode -------------------------------------------------------------------------------------------------- + +-- silk_decode_frame: writes frame_length samples to out[fo ..] +local function decodeFrame(ch, d, out, fo, lostFlag, condCoding) +local L = ch.frame_length + local ctrl = ch.ctrl + ctrl.LTP_scale_Q14 = 0 + if lostFlag == 0 or (lostFlag == 2 and ch.LBRR_flags[ch.nFramesDecoded + 1] == 1) then + local pulses = ch.pulses + decodeIndices(ch, d, ch.nFramesDecoded, lostFlag ~= 0, condCoding) + decodePulses(d, pulses, ch.indices.signalType, ch.indices.quantOffsetType, L) + decodeParameters(ch, ctrl, condCoding) + decodeCore(ch, ctrl, out, fo, pulses) + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + -- silk_PLC (update) + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcUpdate(ch, ctrl) + ch.lossCnt = 0 + ch.prevSignalType = ch.indices.signalType + ch.first_frame_after_reset = 0 + else + if ch.fs_kHz ~= ch.sPLC.fs_kHz then + plcReset(ch) + ch.sPLC.fs_kHz = ch.fs_kHz + end + plcConceal(ch, ctrl, out, fo) + ch.lossCnt =ch.lossCnt+ 1 + local mv_len = ch.ltp_mem_length - L + local ob = ch.outBuf + for i = 1, mv_len do + ob[i] = ob[L + i] + end + for i = 0, L - 1 do + ob[mv_len + i + 1] = out[fo + i] + end + end + cng(ch, ctrl, out, fo, L) + plcGlueFrames(ch, out, fo, L) + ch.lagPrev = ctrl.pitchL[ch.nb_subfr] + return L +end + +-- Stereo -------------------------------------------------------------------------------------------------------- + +local function stereoDecodePred(d, pred_Q13) + local n = icdf(d, T.stereo_pred_joint_iCDF, 1, 8) + local ix02 = math.floor(n / 5 +) local ix12 = n - 5 * ix02 + local ix00 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix01 = icdf(d, T.uniform5_iCDF, 1, 8) + local ix10 = icdf(d, T.uniform3_iCDF, 1, 8) + local ix11 = icdf(d, T.uniform5_iCDF, 1, 8) + local q = T.stereo_pred_quant_Q13 + for c = 1, 2 do + local a = (c == 1 and((ix00 + 3 * ix02 ))or((ix10 + 3 * ix12 +))) local b = (c == 1 and{ix01 }or{ix11 +})[1] local low_Q13 = q[a + 1] + local step_Q13 = math.floor(((q[a + 2] - low_Q13) * 6554) / 65536 +) pred_Q13[c] = low_Q13 + s16(step_Q13) * (2 * b + 1) + end + pred_Q13[1]=pred_Q13[1]- pred_Q13[2] +end + +-- x1, x2: samplesOut1_tmp arrays (C index j at [j + 1]) +local function stereoMSToLR(state, x1, x2, pred_Q13, fs_kHz, frame_length) + x1[1], x1[2] = state.sMid[1], state.sMid[2] + x2[1], x2[2] = state.sSide[1], state.sSide[2] + state.sMid[1], state.sMid[2] = x1[frame_length + 1], x1[frame_length + 2] + state.sSide[1], state.sSide[2] = x2[frame_length + 1], x2[frame_length + 2] + local pred0 = state.pred_prev_Q13[1] + local pred1 = state.pred_prev_Q13[2] + local interp = 8 * fs_kHz + local denom_Q16 = tdiv(65536, interp) + local delta0 = math.floor((s16(pred_Q13[1] - pred0) * s16(denom_Q16) + 32768) / 65536 +) local delta1 = math.floor((s16(pred_Q13[2] - pred1) * s16(denom_Q16) + 32768) / 65536 +) for n = 0, frame_length - 1 do + if n < interp then + pred0 =pred0+ delta0 + pred1 =pred1+ delta1 + elseif n == interp then + pred0 = pred_Q13[1] + pred1 = pred_Q13[2] + end + local sum = (x1[n + 1] + x1[n + 3] + x1[n + 2] * 2) * 512 + sum = x2[n + 2] * 256 + math.floor((sum * s16(pred0)) / 65536 +) sum = sum + math.floor(((x1[n + 2] * 2048) * s16(pred1)) / 65536 +) x2[n + 2] = sat16(math.floor((sum + 128) / 256)) + end + if frame_length <= interp then + -- the second loop never ran; the C code still ends with pred = pred_Q13 + end + state.pred_prev_Q13[1] = pred_Q13[1] + state.pred_prev_Q13[2] = pred_Q13[2] + for n = 0, frame_length - 1 do + local a, b = x1[n + 2], x2[n + 2] + x1[n + 2] = sat16(a + b) + x2[n + 2] = sat16(a - b) + end +end +-- API ----------------------------------------------------------------------------------------------------------- + + + + +function Silk.new(apiChannels) +return { + ch = { newChannel(), newChannel() }, + sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } }, + nChannelsAPI = 0, + nChannelsInternal = 0, + prev_decode_only_middle = 0, + MS_pred_Q13 = { 0, 0 }, + resampOut = table.create(960, 0), + apiChannels = apiChannels, + } +end + +-- silk_ResetDecoder (keeps nChannelsAPI / nChannelsInternal, like libopus) +function Silk.reset(st) + st.ch[1] = newChannel() + st.ch[2] = newChannel() + for _, ch in __iter(st.ch) do + cngReset(ch) + plcReset(ch) + end + st.sStereo = { pred_prev_Q13 = { 0, 0 }, sMid = { 0, 0 }, sSide = { 0, 0 } } + st.prev_decode_only_middle = 0 +end + +local function initChannel(st, n) + local ch = newChannel() + cngReset(ch) + plcReset(ch) + st.ch[n] = ch +end + +function Silk.decode(st, ctrl, lostFlag, firstFrame, d, out, outBase) +local ret = 0 + local nInt = ctrl.nChannelsInternal + local nAPI = ctrl.nChannelsAPI + local chs = st.ch + local decode_only_middle = 0 + local MS_pred_Q13 = st.MS_pred_Q13 + MS_pred_Q13[1], MS_pred_Q13[2] = 0, 0 + if nInt ~= 1 and nInt ~= 2 then + return -200, 0 + end + if firstFrame then + for n = 1, nInt do + chs[n].nFramesDecoded = 0 + end + end + if nInt > st.nChannelsInternal then + initChannel(st, 2) + end + local ch1 = chs[1] + local stereo_to_mono = nInt == 1 and st.nChannelsInternal == 2 and ctrl.internalSampleRate == 1000 * ch1.fs_kHz + if ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + local ms = ctrl.payloadSize_ms + if ms == 0 or ms == 10 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 2 + elseif ms == 20 then + ch.nFramesPerPacket = 1 + ch.nb_subfr = 4 + elseif ms == 40 then + ch.nFramesPerPacket = 2 + ch.nb_subfr = 4 + elseif ms == 60 then + ch.nFramesPerPacket = 3 + ch.nb_subfr = 4 + else + return -203, 0 + end + local fs_kHz_dec = math.floor(ctrl.internalSampleRate / 1024 )+ 1 + if fs_kHz_dec ~= 8 and fs_kHz_dec ~= 12 and fs_kHz_dec ~= 16 then + return -200, 0 + end + ret =ret+ decoderSetFs(ch, fs_kHz_dec, ctrl.API_sampleRate) + end + end + if nAPI == 2 and nInt == 2 and (st.nChannelsAPI == 1 or st.nChannelsInternal == 1) then + local s = st.sStereo + s.pred_prev_Q13[1], s.pred_prev_Q13[2] = 0, 0 + s.sSide[1], s.sSide[2] = 0, 0 + copyResampler(chs[2].resampler_state, ch1.resampler_state) + end + st.nChannelsAPI = nAPI + st.nChannelsInternal = nInt + if ctrl.API_sampleRate > 48000 or ctrl.API_sampleRate < 8000 then + return -200, 0 + end + if lostFlag ~= 1 and ch1.nFramesDecoded == 0 then + for n = 1, nInt do + local ch = chs[n] + for i = 1, ch.nFramesPerPacket do + ch.VAD_flags[i] = bitLogp(d, 1) and 1 or 0 + end + ch.LBRR_flag = bitLogp(d, 1) and 1 or 0 + end + for n = 1, nInt do + local ch = chs[n] + ch.LBRR_flags[1], ch.LBRR_flags[2], ch.LBRR_flags[3] = 0, 0, 0 + if ch.LBRR_flag ~= 0 then + if ch.nFramesPerPacket == 1 then + ch.LBRR_flags[1] = 1 + else + local sym = icdf(d, LBRR_flags_iCDF[ch.nFramesPerPacket - 1], 1, 8) + 1 + for i = 0, ch.nFramesPerPacket - 1 do + ch.LBRR_flags[i + 1] = bit32.band(bit32.rshift(sym, i), 1) + end + end + end + end + if lostFlag == 0 then + -- skip all LBRR data + for i = 0, ch1.nFramesPerPacket - 1 do + for n = 1, nInt do + local ch = chs[n] + if ch.LBRR_flags[i + 1] ~= 0 then + if nInt == 2 and n == 1 then + stereoDecodePred(d, MS_pred_Q13) + if chs[2].LBRR_flags[i + 1] == 0 then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + end + end + local condCoding = i > 0 and ch.LBRR_flags[i] ~= 0 and 2 or 0 + decodeIndices(ch, d, i, true, condCoding) + decodePulses(d, ch.pulses, ch.indices.signalType, ch.indices.quantOffsetType, ch.frame_length) + end + end + end + end + end + if nInt == 2 then + local fd = ch1.nFramesDecoded + if lostFlag == 0 or (lostFlag == 2 and ch1.LBRR_flags[fd + 1] == 1) then + stereoDecodePred(d, MS_pred_Q13) + if (lostFlag == 0 and chs[2].VAD_flags[fd + 1] == 0) or (lostFlag == 2 and chs[2].LBRR_flags[fd + 1] == 0) then + decode_only_middle = icdf(d, T.stereo_only_code_mid_iCDF, 1, 8) + else + decode_only_middle = 0 + end + else + MS_pred_Q13[1] = st.sStereo.pred_prev_Q13[1] + MS_pred_Q13[2] = st.sStereo.pred_prev_Q13[2] + end + end + if nInt == 2 and decode_only_middle == 0 and st.prev_decode_only_middle == 1 then + local c2 = chs[2] + for i = 1, 480 do + c2.outBuf[i] = 0 + end + for i = 1, 16 do + c2.sLPC_Q14_buf[i] = 0 + end + c2.lagPrev = 100 + c2.LastGainIndex = 10 + c2.prevSignalType = 0 + c2.first_frame_after_reset = 1 + end + local has_side + if lostFlag == 0 then + has_side = decode_only_middle == 0 + else + has_side = st.prev_decode_only_middle == 0 + or (nInt == 2 and lostFlag == 2 and chs[2].LBRR_flags[chs[2].nFramesDecoded + 1] == 1) + end + local nSamplesOutDec = ch1.frame_length + for n = 1, nInt do + local ch = chs[n] + if n == 1 or has_side then + local FrameIndex = ch1.nFramesDecoded - (n - 1) + local condCoding + if FrameIndex <= 0 then + condCoding = 0 + elseif lostFlag == 2 then + condCoding = ch.LBRR_flags[FrameIndex] ~= 0 and 2 or 0 + elseif n > 1 and st.prev_decode_only_middle ~= 0 then + condCoding = 1 + else + condCoding = 2 + end + nSamplesOutDec = decodeFrame(ch, d, ch.out, 3, lostFlag, condCoding) + else + local o = ch.out + for i = 3, nSamplesOutDec + 2 do + o[i] = 0 + end + end + ch.nFramesDecoded =ch.nFramesDecoded+ 1 + end + local o1 = ch1.out + if nAPI == 2 and nInt == 2 then + stereoMSToLR(st.sStereo, o1, chs[2].out, MS_pred_Q13, ch1.fs_kHz, nSamplesOutDec) + else + local sMid = st.sStereo.sMid + o1[1], o1[2], sMid[1], sMid[2] = sMid[1], sMid[2], o1[nSamplesOutDec + 1], o1[nSamplesOutDec + 2] + end + local nSamplesOut = math.floor((nSamplesOutDec * ctrl.API_sampleRate) / (ch1.fs_kHz * 1000) +) local ro = st.resampOut + local scale = 1 / 32768 + for n = 1, math.min(nAPI, nInt) do + resampler(chs[n].resampler_state, ro, chs[n].out, 2, nSamplesOutDec) + if nAPI == 2 then + local b = outBase + n - 1 + for i = 0, nSamplesOut - 1 do + out[b + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + i] = ro[i + 1] * scale + end + end + end + if nAPI == 2 and nInt == 1 then + if stereo_to_mono then + resampler(chs[2].resampler_state, ro, o1, 2, nSamplesOutDec) + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = ro[i + 1] * scale + end + else + for i = 0, nSamplesOut - 1 do + out[outBase + 1 + 2 * i] = out[outBase + 2 * i] + end + end + end + if lostFlag == 1 then + for i = 1, st.nChannelsInternal do + chs[i].LastGainIndex = 10 + end + else + st.prev_decode_only_middle = decode_only_middle + end + return ret, nSamplesOut +end + +-- the pitch lag of the last frame at 48 kHz (decControl->prevPitchLag), 0 when unvoiced +function Silk.prevPitchLag(st) +local ch = st.ch[1] + if ch.prevSignalType == 2 then + local mult = { 6, 4, 3 } + return ch.lagPrev * mult[math.floor((ch.fs_kHz - 8) / 4 )+ 1] + end + return 0 +end + +return Silk +end +__FILES["codecs/audio/Opus/SilkTables"] = function() +--!strict +--!optimize 2 +-- 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 = { + 179, 99, 0, +} +T.LTP_gain_iCDF_0 = { + 71, 56, 43, 30, 21, 12, 6, 0, +} +T.LTP_gain_iCDF_1 = { + 199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0, +} +T.LTP_gain_iCDF_2 = { + 241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, + 44, 38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0, +} +T.LTP_gain_vq_0 = { + 4, 6, 24, 7, 5, 0, 0, 2, 0, 0, 12, 28, 41, 13, -4, -9, 15, 42, 25, 14, + 1, -2, 62, 41, -9, -10, 37, 65, -4, 3, -6, 4, 66, 7, -8, 16, 14, 38, -3, 33, +} +T.LTP_gain_vq_1 = { + 13, 22, 39, 23, 12, -1, 36, 64, 27, -6, -7, 10, 55, 43, 17, 1, 1, 8, 1, 1, + 6, -11, 74, 53, -9, -12, 55, 76, -12, 8, -3, 3, 93, 27, -4, 26, 39, 59, 3, -8, + 2, 0, 77, 11, 9, -8, 22, 44, -6, 7, 40, 9, 26, 3, 9, -7, 20, 101, -7, 4, + 3, -8, 42, 26, 0, -15, 33, 68, 2, 23, -2, 55, 46, -2, 15, 3, -1, 21, 16, 41, +} +T.LTP_gain_vq_2 = { + -6, 27, 61, 39, 5, -11, 42, 88, 4, 1, -2, 60, 65, 6, -4, -1, -5, 73, 56, 1, + -9, 19, 94, 29, -9, 0, 12, 99, 6, 4, 8, -19, 102, 46, -13, 3, 2, 13, 3, 2, + 9, -21, 84, 72, -18, -11, 46, 104, -22, 8, 18, 38, 48, 23, 0, -16, 70, 83, -21, 11, + 5, -11, 117, 22, -8, -6, 23, 117, -12, 3, 3, -8, 95, 28, 4, -10, 15, 77, 60, -15, + -1, 4, 124, 2, -4, 3, 38, 84, 24, -25, 2, 13, 42, 13, 31, 21, -4, 56, 46, -1, + -1, 35, 79, -13, 19, -7, 65, 88, -9, -14, 20, 4, 81, 49, -29, 20, 0, 75, 3, -17, + 5, -9, 44, 92, -8, 1, -3, 22, 69, 31, -6, 95, 41, -12, 5, 39, 67, 16, -4, 1, + 0, -6, 120, 55, -36, -13, 44, 122, 4, -24, 81, 5, 11, 3, 7, 2, 0, 9, 10, 88, +} +T.NLSF_CB1_WB_Q8 = { + 7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239, 13, 25, 41, 55, + 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236, 15, 21, 34, 51, 61, 78, 92, 106, + 126, 136, 152, 167, 185, 205, 225, 240, 10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, + 189, 205, 221, 237, 17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240, + 10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236, 8, 21, 37, 51, + 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218, 12, 15, 34, 55, 63, 78, 87, 108, + 118, 131, 148, 167, 185, 203, 219, 236, 16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, + 186, 204, 220, 237, 11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241, + 6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225, 11, 19, 30, 44, + 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234, 12, 19, 29, 46, 57, 71, 88, 100, + 120, 132, 148, 165, 182, 199, 216, 233, 17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, + 185, 204, 222, 237, 14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240, + 9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237, 16, 19, 36, 48, + 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236, 12, 17, 29, 54, 71, 81, 94, 104, + 126, 136, 149, 164, 182, 201, 221, 237, 15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, + 194, 208, 223, 238, 8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239, + 17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235, 14, 19, 36, 45, + 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238, 12, 18, 31, 45, 60, 76, 91, 107, + 123, 138, 154, 171, 187, 204, 221, 236, 13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, + 185, 203, 220, 237, 17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240, + 8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239, 13, 16, 41, 66, + 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241, 17, 25, 37, 52, 63, 75, 92, 102, + 119, 132, 144, 160, 175, 191, 212, 231, 19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, + 200, 213, 227, 242, 18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239, + 16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240, 15, 21, 35, 50, + 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237, +} +T.NLSF_CB1_WB_Wght_Q9 = { + 3657, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2925, 2963, 2963, 2925, 2846, 3216, 3085, 2972, 3056, + 3056, 3010, 3010, 3010, 2963, 2963, 3010, 2972, 2888, 2846, 2846, 2726, 3920, 4014, 2981, 3207, 3207, 2934, 3056, 2846, + 3122, 3244, 2925, 2846, 2620, 2553, 2780, 2925, 3516, 3197, 3010, 3103, 3019, 2888, 2925, 2925, 2925, 2925, 2888, 2888, + 2888, 2888, 2888, 2753, 5054, 5054, 2934, 3573, 3385, 3056, 3085, 2793, 3160, 3160, 2972, 2846, 2513, 2540, 2753, 2888, + 4428, 4149, 2700, 2753, 2972, 3010, 2925, 2846, 2981, 3019, 2925, 2925, 2925, 2925, 2888, 2726, 3620, 3019, 2972, 3056, + 3056, 2873, 2806, 3056, 3216, 3047, 2981, 3291, 3291, 2981, 3310, 2991, 5227, 5014, 2540, 3338, 3526, 3385, 3197, 3094, + 3376, 2981, 2700, 2647, 2687, 2793, 2846, 2673, 5081, 5174, 4615, 4428, 2460, 2897, 3047, 3207, 3169, 2687, 2740, 2888, + 2846, 2793, 2846, 2700, 3122, 2888, 2963, 2925, 2925, 2925, 2925, 2963, 2963, 2963, 2963, 2925, 2925, 2963, 2963, 2963, + 4202, 3207, 2981, 3103, 3010, 2888, 2888, 2925, 2972, 2873, 2916, 3019, 2972, 3010, 3197, 2873, 3760, 3760, 3244, 3103, + 2981, 2888, 2925, 2888, 2972, 2934, 2793, 2793, 2846, 2888, 2888, 2660, 3854, 4014, 3207, 3122, 3244, 2934, 3047, 2963, + 2963, 3085, 2846, 2793, 2793, 2793, 2793, 2580, 3845, 4080, 3357, 3516, 3094, 2740, 3010, 2934, 3122, 3085, 2846, 2846, + 2647, 2647, 2846, 2806, 5147, 4894, 3225, 3845, 3441, 3169, 2897, 3413, 3451, 2700, 2580, 2673, 2740, 2846, 2806, 2753, + 4109, 3789, 3291, 3160, 2925, 2888, 2888, 2925, 2793, 2740, 2793, 2740, 2793, 2846, 2888, 2806, 5081, 5054, 3047, 3545, + 3244, 3056, 3085, 2944, 3103, 2897, 2740, 2740, 2740, 2846, 2793, 2620, 4309, 4309, 2860, 2527, 3207, 3376, 3376, 3075, + 3075, 3376, 3056, 2846, 2647, 2580, 2726, 2753, 3056, 2916, 2806, 2888, 2740, 2687, 2897, 3103, 3150, 3150, 3216, 3169, + 3056, 3010, 2963, 2846, 4375, 3882, 2925, 2888, 2846, 2888, 2846, 2846, 2888, 2888, 2888, 2846, 2888, 2925, 2888, 2846, + 2981, 2916, 2916, 2981, 2981, 3056, 3122, 3216, 3150, 3056, 3010, 2972, 2972, 2972, 2925, 2740, 4229, 4149, 3310, 3347, + 2925, 2963, 2888, 2981, 2981, 2846, 2793, 2740, 2846, 2846, 2846, 2793, 4080, 4014, 3103, 3010, 2925, 2925, 2925, 2888, + 2925, 2925, 2846, 2846, 2846, 2793, 2888, 2780, 4615, 4575, 3169, 3441, 3207, 2981, 2897, 3038, 3122, 2740, 2687, 2687, + 2687, 2740, 2793, 2700, 4149, 4269, 3789, 3657, 2726, 2780, 2888, 2888, 3010, 2972, 2925, 2846, 2687, 2687, 2793, 2888, + 4215, 3554, 2753, 2846, 2846, 2888, 2888, 2888, 2925, 2925, 2888, 2925, 2925, 2925, 2963, 2888, 5174, 4921, 2261, 3432, + 3789, 3479, 3347, 2846, 3310, 3479, 3150, 2897, 2460, 2487, 2753, 2925, 3451, 3685, 3122, 3197, 3357, 3047, 3207, 3207, + 2981, 3216, 3085, 2925, 2925, 2687, 2540, 2434, 2981, 3010, 2793, 2793, 2740, 2793, 2846, 2972, 3056, 3103, 3150, 3150, + 3150, 3103, 3010, 3010, 2944, 2873, 2687, 2726, 2780, 3010, 3432, 3545, 3357, 3244, 3056, 3010, 2963, 2925, 2888, 2846, + 3019, 2944, 2897, 3010, 3010, 2972, 3019, 3103, 3056, 3056, 3010, 2888, 2846, 2925, 2925, 2888, 3920, 3967, 3010, 3197, + 3357, 3216, 3291, 3291, 3479, 3704, 3441, 2726, 2181, 2460, 2580, 2607, +} +T.NLSF_CB1_iCDF_WB = { + 225, 204, 201, 184, 183, 175, 158, 154, 153, 135, 119, 115, 113, 110, 109, 99, 98, 95, 79, 68, + 52, 50, 48, 45, 43, 32, 31, 27, 18, 10, 3, 0, 255, 251, 235, 230, 212, 201, 196, 182, + 167, 166, 163, 151, 138, 124, 110, 104, 90, 78, 76, 70, 69, 57, 45, 34, 24, 21, 11, 6, + 5, 4, 3, 0, +} +T.NLSF_CB2_SELECT_WB = { + 0, 0, 0, 0, 0, 0, 0, 1, 100, 102, 102, 68, 68, 36, 34, 96, 164, 107, 158, 185, + 180, 185, 139, 102, 64, 66, 36, 34, 34, 0, 1, 32, 208, 139, 141, 191, 152, 185, 155, 104, + 96, 171, 104, 166, 102, 102, 102, 132, 1, 0, 0, 0, 0, 16, 16, 0, 80, 109, 78, 107, + 185, 139, 103, 101, 208, 212, 141, 139, 173, 153, 123, 103, 36, 0, 0, 0, 0, 0, 0, 1, + 48, 0, 0, 0, 0, 0, 0, 32, 68, 135, 123, 119, 119, 103, 69, 98, 68, 103, 120, 118, + 118, 102, 71, 98, 134, 136, 157, 184, 182, 153, 139, 134, 208, 168, 248, 75, 189, 143, 121, 107, + 32, 49, 34, 34, 34, 0, 17, 2, 210, 235, 139, 123, 185, 137, 105, 134, 98, 135, 104, 182, + 100, 183, 171, 134, 100, 70, 68, 70, 66, 66, 34, 131, 64, 166, 102, 68, 36, 2, 1, 0, + 134, 166, 102, 68, 34, 34, 66, 132, 212, 246, 158, 139, 107, 107, 87, 102, 100, 219, 125, 122, + 137, 118, 103, 132, 114, 135, 137, 105, 171, 106, 50, 34, 164, 214, 141, 143, 185, 151, 121, 103, + 192, 34, 0, 0, 0, 0, 0, 1, 208, 109, 74, 187, 134, 249, 159, 137, 102, 110, 154, 118, + 87, 101, 119, 101, 0, 2, 0, 36, 36, 66, 68, 35, 96, 164, 102, 100, 36, 0, 2, 33, + 167, 138, 174, 102, 100, 84, 2, 2, 100, 107, 120, 119, 36, 197, 24, 0, +} +T.NLSF_CB2_iCDF_WB = { + 255, 254, 253, 244, 12, 3, 2, 1, 0, 255, 254, 252, 224, 38, 3, 2, 1, 0, 255, 254, + 251, 209, 57, 4, 2, 1, 0, 255, 254, 244, 195, 69, 4, 2, 1, 0, 255, 251, 232, 184, + 84, 7, 2, 1, 0, 255, 254, 240, 186, 86, 14, 2, 1, 0, 255, 254, 239, 178, 91, 30, + 5, 1, 0, 255, 248, 227, 177, 100, 19, 2, 1, 0, +} +T.NLSF_PRED_WB_Q8 = { + 175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182, 68, 62, 66, 60, 72, + 117, 85, 90, 118, 136, 151, 142, 160, 142, 155, +} +T.NLSF_DELTA_MIN_WB_Q15 = { + 100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347, +} +T.NLSF_CB1_NB_MB_Q8 = { + 12, 35, 60, 83, 108, 132, 157, 180, 206, 228, 15, 32, 55, 77, 101, 125, 151, 175, 201, 225, + 19, 42, 66, 89, 114, 137, 162, 184, 209, 230, 12, 25, 50, 72, 97, 120, 147, 172, 200, 223, + 26, 44, 69, 90, 114, 135, 159, 180, 205, 225, 13, 22, 53, 80, 106, 130, 156, 180, 205, 228, + 15, 25, 44, 64, 90, 115, 142, 168, 196, 222, 19, 24, 62, 82, 100, 120, 145, 168, 190, 214, + 22, 31, 50, 79, 103, 120, 151, 170, 203, 227, 21, 29, 45, 65, 106, 124, 150, 171, 196, 224, + 30, 49, 75, 97, 121, 142, 165, 186, 209, 229, 19, 25, 52, 70, 93, 116, 143, 166, 192, 219, + 26, 34, 62, 75, 97, 118, 145, 167, 194, 217, 25, 33, 56, 70, 91, 113, 143, 165, 196, 223, + 21, 34, 51, 72, 97, 117, 145, 171, 196, 222, 20, 29, 50, 67, 90, 117, 144, 168, 197, 221, + 22, 31, 48, 66, 95, 117, 146, 168, 196, 222, 24, 33, 51, 77, 116, 134, 158, 180, 200, 224, + 21, 28, 70, 87, 106, 124, 149, 170, 194, 217, 26, 33, 53, 64, 83, 117, 152, 173, 204, 225, + 27, 34, 65, 95, 108, 129, 155, 174, 210, 225, 20, 26, 72, 99, 113, 131, 154, 176, 200, 219, + 34, 43, 61, 78, 93, 114, 155, 177, 205, 229, 23, 29, 54, 97, 124, 138, 163, 179, 209, 229, + 30, 38, 56, 89, 118, 129, 158, 178, 200, 231, 21, 29, 49, 63, 85, 111, 142, 163, 193, 222, + 27, 48, 77, 103, 133, 158, 179, 196, 215, 232, 29, 47, 74, 99, 124, 151, 176, 198, 220, 237, + 33, 42, 61, 76, 93, 121, 155, 174, 207, 225, 29, 53, 87, 112, 136, 154, 170, 188, 208, 227, + 24, 30, 52, 84, 131, 150, 166, 186, 203, 229, 37, 48, 64, 84, 104, 118, 156, 177, 201, 230, +} +T.NLSF_CB1_Wght_Q9 = { + 2897, 2314, 2314, 2314, 2287, 2287, 2314, 2300, 2327, 2287, 2888, 2580, 2394, 2367, 2314, 2274, 2274, 2274, 2274, 2194, + 2487, 2340, 2340, 2314, 2314, 2314, 2340, 2340, 2367, 2354, 3216, 2766, 2340, 2340, 2314, 2274, 2221, 2207, 2261, 2194, + 2460, 2474, 2367, 2394, 2394, 2394, 2394, 2367, 2407, 2314, 3479, 3056, 2127, 2207, 2274, 2274, 2274, 2287, 2314, 2261, + 3282, 3141, 2580, 2394, 2247, 2221, 2207, 2194, 2194, 2114, 4096, 3845, 2221, 2620, 2620, 2407, 2314, 2394, 2367, 2074, + 3178, 3244, 2367, 2221, 2553, 2434, 2340, 2314, 2167, 2221, 3338, 3488, 2726, 2194, 2261, 2460, 2354, 2367, 2207, 2101, + 2354, 2420, 2327, 2367, 2394, 2420, 2420, 2420, 2460, 2367, 3779, 3629, 2434, 2527, 2367, 2274, 2274, 2300, 2207, 2048, + 3254, 3225, 2713, 2846, 2447, 2327, 2300, 2300, 2274, 2127, 3263, 3300, 2753, 2806, 2447, 2261, 2261, 2247, 2127, 2101, + 2873, 2981, 2633, 2367, 2407, 2354, 2194, 2247, 2247, 2114, 3225, 3197, 2633, 2580, 2274, 2181, 2247, 2221, 2221, 2141, + 3178, 3310, 2740, 2407, 2274, 2274, 2274, 2287, 2194, 2114, 3141, 3272, 2460, 2061, 2287, 2500, 2367, 2487, 2434, 2181, + 3507, 3282, 2314, 2700, 2647, 2474, 2367, 2394, 2340, 2127, 3423, 3535, 3038, 3056, 2300, 1950, 2221, 2274, 2274, 2274, + 3404, 3366, 2087, 2687, 2873, 2354, 2420, 2274, 2474, 2540, 3760, 3488, 1950, 2660, 2897, 2527, 2394, 2367, 2460, 2261, + 3028, 3272, 2740, 2888, 2740, 2154, 2127, 2287, 2234, 2247, 3695, 3657, 2025, 1969, 2660, 2700, 2580, 2500, 2327, 2367, + 3207, 3413, 2354, 2074, 2888, 2888, 2340, 2487, 2247, 2167, 3338, 3366, 2846, 2780, 2327, 2154, 2274, 2287, 2114, 2061, + 2327, 2300, 2181, 2167, 2181, 2367, 2633, 2700, 2700, 2553, 2407, 2434, 2221, 2261, 2221, 2221, 2340, 2420, 2607, 2700, + 3038, 3244, 2806, 2888, 2474, 2074, 2300, 2314, 2354, 2380, 2221, 2154, 2127, 2287, 2500, 2793, 2793, 2620, 2580, 2367, + 3676, 3713, 2234, 1838, 2181, 2753, 2726, 2673, 2513, 2207, 2793, 3160, 2726, 2553, 2846, 2513, 2181, 2394, 2221, 2181, +} +T.NLSF_CB1_iCDF_NB_MB = { + 212, 178, 148, 129, 108, 96, 85, 82, 79, 77, 61, 59, 57, 56, 51, 49, 48, 45, 42, 41, + 40, 38, 36, 34, 31, 30, 21, 12, 10, 3, 1, 0, 255, 245, 244, 236, 233, 225, 217, 203, + 190, 176, 175, 161, 149, 136, 125, 114, 102, 91, 81, 71, 60, 52, 43, 35, 28, 20, 19, 18, + 12, 11, 5, 0, +} +T.NLSF_CB2_SELECT_NB_MB = { + 16, 0, 0, 0, 0, 99, 66, 36, 36, 34, 36, 34, 34, 34, 34, 83, 69, 36, 52, 34, + 116, 102, 70, 68, 68, 176, 102, 68, 68, 34, 65, 85, 68, 84, 36, 116, 141, 152, 139, 170, + 132, 187, 184, 216, 137, 132, 249, 168, 185, 139, 104, 102, 100, 68, 68, 178, 218, 185, 185, 170, + 244, 216, 187, 187, 170, 244, 187, 187, 219, 138, 103, 155, 184, 185, 137, 116, 183, 155, 152, 136, + 132, 217, 184, 184, 170, 164, 217, 171, 155, 139, 244, 169, 184, 185, 170, 164, 216, 223, 218, 138, + 214, 143, 188, 218, 168, 244, 141, 136, 155, 170, 168, 138, 220, 219, 139, 164, 219, 202, 216, 137, + 168, 186, 246, 185, 139, 116, 185, 219, 185, 138, 100, 100, 134, 100, 102, 34, 68, 68, 100, 68, + 168, 203, 221, 218, 168, 167, 154, 136, 104, 70, 164, 246, 171, 137, 139, 137, 155, 218, 219, 139, +} +T.NLSF_CB2_iCDF_NB_MB = { + 255, 254, 253, 238, 14, 3, 2, 1, 0, 255, 254, 252, 218, 35, 3, 2, 1, 0, 255, 254, + 250, 208, 59, 4, 2, 1, 0, 255, 254, 246, 194, 71, 10, 2, 1, 0, 255, 252, 236, 183, + 82, 8, 2, 1, 0, 255, 252, 235, 180, 90, 17, 2, 1, 0, 255, 248, 224, 171, 97, 30, + 4, 1, 0, 255, 254, 236, 173, 95, 37, 7, 1, 0, +} +T.NLSF_PRED_NB_MB_Q8 = { + 179, 138, 140, 148, 151, 149, 153, 151, 163, 116, 67, 82, 59, 92, 72, 100, 89, 92, +} +T.NLSF_DELTA_MIN_NB_MB_Q15 = { + 250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461, +} +T.pitch_lag_iCDF = { + 253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, + 13, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, +} +T.pitch_delta_iCDF = { + 210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, + 0, +} +T.pitch_contour_iCDF = { + 223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, + 24, 21, 18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0, +} +T.pitch_contour_NB_iCDF = { + 188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0, +} +T.pitch_contour_10_ms_iCDF = { + 165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0, +} +T.pitch_contour_10_ms_NB_iCDF = { + 113, 63, 0, +} +T.stereo_pred_quant_Q13 = { + -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732, +} +T.stereo_pred_joint_iCDF = { + 249, 247, 246, 245, 244, 234, 210, 202, 201, 200, 197, 174, 82, 59, 56, 55, 54, 46, 22, 12, + 11, 10, 9, 7, 0, +} +T.stereo_only_code_mid_iCDF = { + 64, 0, +} +T.LBRR_flags_2_iCDF = { + 203, 150, 0, +} +T.LBRR_flags_3_iCDF = { + 215, 195, 166, 125, 110, 82, 0, +} +T.lsb_iCDF = { + 120, 0, +} +T.LTPscale_iCDF = { + 128, 64, 0, +} +T.type_offset_VAD_iCDF = { + 232, 158, 10, 0, +} +T.type_offset_no_VAD_iCDF = { + 230, 0, +} +T.NLSF_interpolation_factor_iCDF = { + 243, 221, 192, 181, 0, +} +T.LTPScales_table_Q14 = { + 15565, 12288, 8192, +} +T.uniform3_iCDF = { + 171, 85, 0, +} +T.uniform4_iCDF = { + 192, 128, 64, 0, +} +T.uniform5_iCDF = { + 205, 154, 102, 51, 0, +} +T.uniform6_iCDF = { + 213, 171, 128, 85, 43, 0, +} +T.uniform8_iCDF = { + 224, 192, 160, 128, 96, 64, 32, 0, +} +T.NLSF_EXT_iCDF = { + 100, 40, 16, 7, 3, 1, 0, +} +T.gain_iCDF = { + 224, 112, 44, 15, 3, 2, 1, 0, 254, 237, 192, 132, 70, 23, 4, 0, 255, 252, 226, 155, + 61, 11, 2, 0, +} +T.delta_gain_iCDF = { + 250, 245, 234, 203, 71, 50, 42, 38, 35, 33, 31, 29, 28, 27, 26, 25, 24, 23, 22, 21, + 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, + 0, +} +T.LSFCosTab_FIX_Q12 = { + 8192, 8190, 8182, 8170, 8152, 8130, 8104, 8072, 8034, 7994, 7946, 7896, 7840, 7778, 7714, 7644, 7568, 7490, 7406, 7318, + 7226, 7128, 7026, 6922, 6812, 6698, 6580, 6458, 6332, 6204, 6070, 5934, 5792, 5648, 5502, 5352, 5198, 5040, 4880, 4718, + 4552, 4382, 4212, 4038, 3862, 3684, 3502, 3320, 3136, 2948, 2760, 2570, 2378, 2186, 1990, 1794, 1598, 1400, 1202, 1002, + 802, 602, 402, 202, 0, -202, -402, -602, -802, -1002, -1202, -1400, -1598, -1794, -1990, -2186, -2378, -2570, -2760, -2948, + -3136, -3320, -3502, -3684, -3862, -4038, -4212, -4382, -4552, -4718, -4880, -5040, -5198, -5352, -5502, -5648, -5792, -5934, -6070, -6204, + -6332, -6458, -6580, -6698, -6812, -6922, -7026, -7128, -7226, -7318, -7406, -7490, -7568, -7644, -7714, -7778, -7840, -7896, -7946, -7994, + -8034, -8072, -8104, -8130, -8152, -8170, -8182, -8190, -8192, +} +T.pulses_per_block_iCDF = { + 125, 51, 26, 18, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 198, 105, + 45, 22, 15, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 213, 162, 116, 83, + 59, 43, 32, 24, 18, 15, 12, 9, 7, 6, 5, 3, 2, 0, 239, 187, 116, 59, 28, 16, + 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 250, 229, 188, 135, 86, 51, 30, 19, + 13, 10, 8, 6, 5, 4, 3, 2, 1, 0, 249, 235, 213, 185, 156, 128, 103, 83, 66, 53, + 42, 33, 26, 21, 17, 13, 10, 0, 254, 249, 235, 206, 164, 118, 77, 46, 27, 16, 10, 7, + 5, 4, 3, 2, 1, 0, 255, 253, 249, 239, 220, 191, 156, 119, 85, 57, 37, 23, 15, 10, + 6, 4, 2, 0, 255, 253, 251, 246, 237, 223, 203, 179, 152, 124, 98, 75, 55, 40, 29, 21, + 15, 0, 255, 254, 253, 247, 220, 162, 106, 67, 42, 28, 18, 12, 9, 6, 4, 3, 2, 0, +} +T.rate_levels_iCDF = { + 241, 190, 178, 132, 87, 74, 41, 14, 0, 223, 193, 157, 140, 106, 57, 39, 18, 0, +} +T.shell_code_table0 = { + 128, 0, 214, 42, 0, 235, 128, 21, 0, 244, 184, 72, 11, 0, 248, 214, 128, 42, 7, 0, + 248, 225, 170, 80, 25, 5, 0, 251, 236, 198, 126, 54, 18, 3, 0, 250, 238, 211, 159, 82, + 35, 15, 5, 0, 250, 231, 203, 168, 128, 88, 53, 25, 6, 0, 252, 238, 216, 185, 148, 108, + 71, 40, 18, 4, 0, 253, 243, 225, 199, 166, 128, 90, 57, 31, 13, 3, 0, 254, 246, 233, + 212, 183, 147, 109, 73, 44, 23, 10, 2, 0, 255, 250, 240, 223, 198, 166, 128, 90, 58, 33, + 16, 6, 1, 0, 255, 251, 244, 231, 210, 181, 146, 110, 75, 46, 25, 12, 5, 1, 0, 255, + 253, 248, 238, 221, 196, 164, 128, 92, 60, 35, 18, 8, 3, 1, 0, 255, 253, 249, 242, 229, + 208, 180, 146, 110, 76, 48, 27, 14, 7, 3, 1, 0, +} +T.shell_code_table1 = { + 129, 0, 207, 50, 0, 236, 129, 20, 0, 245, 185, 72, 10, 0, 249, 213, 129, 42, 6, 0, + 250, 226, 169, 87, 27, 4, 0, 251, 233, 194, 130, 62, 20, 4, 0, 250, 236, 207, 160, 99, + 47, 17, 3, 0, 255, 240, 217, 182, 131, 81, 41, 11, 1, 0, 255, 254, 233, 201, 159, 107, + 61, 20, 2, 1, 0, 255, 249, 233, 206, 170, 128, 86, 50, 23, 7, 1, 0, 255, 250, 238, + 217, 186, 148, 108, 70, 39, 18, 6, 1, 0, 255, 252, 243, 226, 200, 166, 128, 90, 56, 30, + 13, 4, 1, 0, 255, 252, 245, 231, 209, 180, 146, 110, 76, 47, 25, 11, 4, 1, 0, 255, + 253, 248, 237, 219, 194, 163, 128, 93, 62, 37, 19, 8, 3, 1, 0, 255, 254, 250, 241, 226, + 205, 177, 145, 111, 79, 51, 30, 15, 6, 2, 1, 0, +} +T.shell_code_table2 = { + 129, 0, 203, 54, 0, 234, 129, 23, 0, 245, 184, 73, 10, 0, 250, 215, 129, 41, 5, 0, + 252, 232, 173, 86, 24, 3, 0, 253, 240, 200, 129, 56, 15, 2, 0, 253, 244, 217, 164, 94, + 38, 10, 1, 0, 253, 245, 226, 189, 132, 71, 27, 7, 1, 0, 253, 246, 231, 203, 159, 105, + 56, 23, 6, 1, 0, 255, 248, 235, 213, 179, 133, 85, 47, 19, 5, 1, 0, 255, 254, 243, + 221, 194, 159, 117, 70, 37, 12, 2, 1, 0, 255, 254, 248, 234, 208, 171, 128, 85, 48, 22, + 8, 2, 1, 0, 255, 254, 250, 240, 220, 189, 149, 107, 67, 36, 16, 6, 2, 1, 0, 255, + 254, 251, 243, 227, 201, 166, 128, 90, 55, 29, 13, 5, 2, 1, 0, 255, 254, 252, 246, 234, + 213, 183, 147, 109, 73, 43, 22, 10, 4, 2, 1, 0, +} +T.shell_code_table3 = { + 130, 0, 200, 58, 0, 231, 130, 26, 0, 244, 184, 76, 12, 0, 249, 214, 130, 43, 6, 0, + 252, 232, 173, 87, 24, 3, 0, 253, 241, 203, 131, 56, 14, 2, 0, 254, 246, 221, 167, 94, + 35, 8, 1, 0, 254, 249, 232, 193, 130, 65, 23, 5, 1, 0, 255, 251, 239, 211, 162, 99, + 45, 15, 4, 1, 0, 255, 251, 243, 223, 186, 131, 74, 33, 11, 3, 1, 0, 255, 252, 245, + 230, 202, 158, 105, 57, 24, 8, 2, 1, 0, 255, 253, 247, 235, 214, 179, 132, 84, 44, 19, + 7, 2, 1, 0, 255, 254, 250, 240, 223, 196, 159, 112, 69, 36, 15, 6, 2, 1, 0, 255, + 254, 253, 245, 231, 209, 176, 136, 93, 55, 27, 11, 3, 2, 1, 0, 255, 254, 253, 252, 239, + 221, 194, 158, 117, 76, 42, 18, 4, 3, 2, 1, 0, +} +T.shell_code_table_offsets = { + 0, 0, 2, 5, 9, 14, 20, 27, 35, 44, 54, 65, 77, 90, 104, 119, 135, +} +T.sign_iCDF = { + 254, 49, 67, 77, 82, 93, 99, 198, 11, 18, 24, 31, 36, 45, 255, 46, 66, 78, 87, 94, + 104, 208, 14, 21, 32, 42, 51, 66, 255, 94, 104, 109, 112, 115, 118, 248, 53, 69, 80, 88, + 95, 102, +} +T.CB_lags_stage2_10_ms = { + 0, 1, 0, 0, 0, 1, +} +T.CB_lags_stage3_10_ms = { + 0, 0, 1, -1, 1, -1, 2, -2, 2, -2, 3, -3, 0, 1, 0, 1, -1, 2, -1, 2, + -2, 3, -2, 3, +} +T.CB_lags_stage2 = { + 0, 2, -1, -1, -1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 2, 1, 0, 1, 1, + 0, 0, -1, -1, +} +T.CB_lags_stage3 = { + 0, 0, 1, -1, 0, 1, -1, 0, -1, 1, -2, 2, -2, -2, 2, -3, 2, 3, -3, -4, + 3, -4, 4, 4, -5, 5, -6, -5, 6, -7, 6, 5, 8, -9, 0, 0, 1, 0, 0, 0, + 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0, 1, -1, -1, 1, -1, 2, 1, -1, 2, + -2, -2, 2, -2, 2, 2, 3, -3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 1, -1, 1, 0, 0, 2, 1, -1, 2, -1, -1, 2, -1, 2, 2, -1, 3, -2, -2, + -2, 3, 0, 1, 0, 0, 1, 0, 1, -1, 2, -1, 2, -1, 2, 3, -2, 3, -2, -2, + 4, 4, -3, 5, -3, -4, 6, -4, 6, 5, -5, 8, -6, -5, -7, 9, +} +T.resampler_frac_FIR_12 = { + 189, -600, 617, 30567, 117, -159, -1070, 29704, 52, 221, -2392, 28276, -4, 529, -3350, 26341, -48, 758, -3956, 23973, + -80, 905, -4235, 21254, -99, 972, -4222, 18278, -107, 967, -3957, 15143, -103, 896, -3487, 11950, -91, 773, -2865, 8798, + -71, 611, -2143, 5784, -46, 425, -1375, 2996, +} +return T +end +__FILES["codecs/audio/Pcm"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- 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. +-- +-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else +-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read +-- local audio = Pcm.collect(src) -- read everything into a Types.Audio +-- 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/audio/Pcm/Convert) +-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767] +-- local x = Pcm.fromInt(s16, 16) -- s / 32768 +-- +-- Sample formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw. +-- Never throws (a decoder's read that throws is caught and ends the stream). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Convert = __include("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 +} + + + + + + + + + + + +local function audioRead(self, n, out) +local a = self._audio + local ch = a.channels + local left = a.frames - self._pos + if n > left then + n = left + end + if n <= 0 then + return out or buffer.create(0), 0 + end + local bytes = n * ch * 4 + local b = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) +)})[1] buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes) + self._pos =self._pos+ n + return b, n +end + +local function decoderRead(self, n, out) +if self._done then + return out or buffer.create(0), 0 + end + local ok, b, got = pcall(self._dec.read, self._dec, n, out) + if not ok then + self._done = true + self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b)) + return out or buffer.create(0), 0 + end + if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then + self._done = true + return out or buffer.create(0), 0 + end + local ch = self.channels + if buffer.len(b) < got * ch * 4 then + got = math.floor(buffer.len(b) / (ch * 4) +) end + return b, got +end + +-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read) +function Pcm.source(v) +if type(v) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") + end + local sr, ch = v.sampleRate, v.channels + if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then + return nil, Err.new(Err.ARG, "bad sampleRate or channels") + end + if v.kind == "audio" and type(v.samples) == "buffer" then + local frames = v.frames + if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then + return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4") + end + return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } , nil + end + if type(v.read) == "function" then + local frames = (type(v.frames) == "number" and v.frames > 0 and{v.frames }or{0 +})[1] return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } , nil + end + return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder") +end + +-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames) +function Pcm.collect(src, maxFrames) +local ch = src.channels + local cap = math.max(src.frames, 4096) + local data = buffer.create(cap * ch * 4) + local total = 0 + local limit = maxFrames or 2 ^ 31 + local tmp= 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 + break + end + tmp = b + if total + n > limit then + return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit)) + end + if total + n > cap then + cap = math.max(cap * 2, total + n) + local nd = buffer.create(cap * ch * 4) + buffer.copy(nd, 0, data, 0, total * ch * 4) + data = nd + end + buffer.copy(data, total * ch * 4, b, 0, n * ch * 4) + total =total+ n + end + if src.err then + return nil, src.err + end + local a = Types.Audio.new(src.sampleRate, ch, 0) + a.frames = total + if buffer.len(data) == total * ch * 4 then + a.samples = data + else + a.samples = buffer.create(total * ch * 4) + buffer.copy(a.samples, 0, data, 0, total * ch * 4) + end + a.tags = table.clone(src.tags) + 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, source, maxFrames) +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) +function Pcm.rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags) +local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + if channels < 1 or sampleRate <= 0 or frames < 0 or offset < 0 or offset + frames * channels * size > buffer.len(buf) then + return nil, Err.new(Err.ARG, "bad raw PCM layout") + end + local pos = 0 + local frameBytes = channels * size + local dec = { + sampleRate = sampleRate, + channels = channels, + frames = frames, + duration = frames / sampleRate, + bitrate = sampleRate * frameBytes * 8, + tags = tags or {}, + } + function dec.read(_self, n, out) +n = math.clamp(math.floor(n), 0, frames - pos) + local bytes = n * channels * 4 + local b = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) +)})[1] if n > 0 then + Convert.decode(buf, offset + pos * frameBytes, fmt, n * channels, b, 0) + pos =pos+ n + end + return b, n + end + function dec.seek(_self, seconds) + local f = math.floor(seconds * sampleRate + 0.5) + pos = f ~= f and 0 or math.clamp(f, 0, frames) + end + function dec.position(_self) +return pos / sampleRate + end + return dec , nil +end + +-- audioDecoder(audio) -> Types.Decoder over a decoded Audio (no copy of the samples) +function Pcm.audioDecoder(a) +local d = (Pcm.rawDecoder(a.samples, 0, a.frames, a.channels, a.sampleRate, "f32le", a.tags) ) +d.bitrate = a.sampleRate * a.channels * 32 + return d +end + +-- encode(src, fmt, w) -> frames written | nil, Err: drains src into the Writer w as fmt samples +function Pcm.encode(src, fmt, w) +local size = Convert.SIZE[fmt] + if not size then + return nil, Err.new(Err.ARG, "unknown sample format " .. tostring(fmt)) + end + local ch = src.channels + local total = 0 + local tmp= nil + while true do + local b, n = src:read(8192, tmp) + if n <= 0 then + break + end + tmp = b + local at = w:reserve(n * ch * size) + Convert.encode(b, 0, n * ch, fmt, w.buf, at) + w.pos = at + n * ch * size + total =total+ n + end + if src.err then + return nil, src.err + end + return total, nil +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, offset, frames, channels, map) + 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, bits) +local s = 2 ^ (bits - 1) + local v = math.floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- fromInt(v, bits) -> v / 2^(bits-1) +function Pcm.fromInt(v, bits) +return v / 2 ^ (bits - 1) +end + +return Pcm +end +__FILES["codecs/audio/Pcm/Convert"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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). +-- +-- Formats: u8 s8 s16le s16be s24le s24be s32le s32be f32le f32be f64le f64be alaw ulaw (u8: offset binary). +-- Never throws: callers check ranges (Convert.SIZE[fmt] * count bytes) before calling. +local Convert = {} + +local readu8, readi8, readi16, readi32, readu32 = buffer.readu8, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readu32 +local readf32, readf64, writef32, writef64 = buffer.readf32, buffer.readf64, buffer.writef32, buffer.writef64 +local writeu8, writeu16, writeu32, writei16, writei32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei16, buffer.writei32 +local floor = math.floor +local byteswap = bit32.byteswap + +local SIZE= { + u8 = 1, + s8 = 1, + s16le = 2, + s16be = 2, + s24le = 3, + s24be = 3, + s32le = 4, + s32be = 4, + f32le = 4, + f32be = 4, + f64le = 8, + f64be = 8, + alaw = 1, + ulaw = 1, +} +Convert.SIZE = SIZE +-- the integer bit depth of each format (float: 32 / 64; G.711: 16 after expansion) +Convert.BITS = { + u8 = 8, + s8 = 8, + s16le = 16, + s16be = 16, + s24le = 24, + s24be = 24, + s32le = 32, + s32be = 32, + f32le = 32, + f32be = 32, + f64le = 64, + f64be = 64, + alaw = 16, + ulaw = 16, +} + +-- ------------------------------------------------------------------------------------------------ G.711 +local ALAW = table.create(256, 0) -- code -> linear s16 +local ULAW = table.create(256, 0) +for code = 0, 255 do + -- A-law + local a = bit32.bxor(code, 0x55) + local t = bit32.band(a, 0x0F) * 16 + local seg = bit32.rshift(bit32.band(a, 0x70), 4) + if seg == 0 then + t =t+ 8 + elseif seg == 1 then + t =t+ 0x108 + else + t = (t + 0x108) * 2 ^ (seg - 1) + end + ALAW[code + 1] = (bit32.band(a, 0x80) ~= 0 and{t }or{(-t +)})[1] -- mu-law + local u = bit32.bxor(code, 0xFF) + local m = (bit32.band(u, 0x0F) * 8 + 0x84) * 2 ^ bit32.rshift(bit32.band(u, 0x70), 4) + ULAW[code + 1] = (bit32.band(u, 0x80) ~= 0 and((0x84 - m ))or((m - 0x84 +)))end + +local SEG_AEND = { 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF } +local SEG_UEND = { 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF } +local function segment(v, ends) +for i = 1, 8 do + if v <= ends[i] then + return i - 1 + end + end + return 8 +end + +-- linear s16 -> A-law code +local function alawEncode(pcm) +local mask + local v = floor(pcm / 8) -- 13-bit magnitude domain + if v >= 0 then + mask = 0xD5 + else + mask = 0x55 + v = -v - 1 + end + local seg = segment(v, SEG_AEND) + local aval + if seg >= 8 then + aval = 0x7F + else + aval = seg * 16 + if seg < 2 then + aval =aval+ bit32.band(floor(v / 2), 0x0F) + else + aval =aval+ bit32.band(floor(v / 2 ^ seg), 0x0F) + end + end + return bit32.bxor(aval, mask) +end + +-- linear s16 -> mu-law code +local function ulawEncode(pcm) +local v = floor(pcm / 4) -- 14-bit + local mask + if v < 0 then + v = -v + mask = 0x7F + else + mask = 0xFF + end + if v > 8159 then + v = 8159 + end + v =v+ 0x21 + local seg = segment(v, SEG_UEND) + local uval + if seg >= 8 then + uval = 0x7F + else + uval = seg * 16 + bit32.band(floor(v / 2 ^ (seg + 1)), 0x0F) + end + return bit32.bxor(uval, mask) +end +Convert.alawEncode = alawEncode +Convert.ulawEncode = ulawEncode +Convert.ALAW = ALAW +Convert.ULAW = ULAW + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, so, fmt, count, dst, do_) -> true | false (unknown fmt): count samples at src[so] -> f32 at dst[do_] +function Convert.decode(src, so, fmt, count, dst, d) +if fmt == "s16le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi16(src, so + i * 2) / 32768) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local p = so + i * 2 + local v = readu8(src, p) * 256 + readu8(src, p + 1) + if v >= 32768 then + v =v- 65536 + end + writef32(dst, d + i * 4, v / 32768) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, (readu8(src, so + i) - 128) / 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi8(src, so + i) / 128) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readu8(src, p) + readu8(src, p + 1) * 256 + readi8(src, p + 2) * 65536 + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local p = so + i * 3 + local v = readi8(src, p) * 65536 + readu8(src, p + 1) * 256 + readu8(src, p + 2) + writef32(dst, d + i * 4, v / 8388608) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readi32(src, so + i * 4) / 2147483648) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + local v = byteswap(readu32(src, so + i * 4)) + if v >= 2147483648 then + v =v- 4294967296 + end + writef32(dst, d + i * 4, v / 2147483648) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, readf64(src, so + i * 8)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + local p = so + i * 8 + writeu32(tmp, 0, byteswap(readu32(src, p + 4))) + writeu32(tmp, 4, byteswap(readu32(src, p))) + writef32(dst, d + i * 4, readf64(tmp, 0)) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ALAW[readu8(src, so + i) + 1] / 32768) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writef32(dst, d + i * 4, ULAW[readu8(src, so + i) + 1] / 32768) + end + else + return false + end + return true +end + +-- ------------------------------------------------------------------------------------------------ encode +local function q(x, s) +local v = floor(x * s + 0.5) + if v ~= v then + return 0 + end + if v >= s then + return s - 1 + elseif v < -s then + return -s + end + return v +end + +-- encode(src, so, count, fmt, dst, do_) -> true | false: count f32 samples at src[so] -> fmt at dst[do_] +function Convert.encode(src, so, count, fmt, dst, d) +if fmt == "s16le" then + for i = 0, count - 1 do + writei16(dst, d + i * 2, q(readf32(src, so + i * 4), 32768)) + end + elseif fmt == "s16be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 32768) % 65536 + writeu16(dst, d + i * 2, (v % 256) * 256 + math.floor(v / 256)) + end + elseif fmt == "u8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) + 128) + end + elseif fmt == "s8" then + for i = 0, count - 1 do + writeu8(dst, d + i, q(readf32(src, so + i * 4), 128) % 256) + end + elseif fmt == "s24le" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, v % 256) + writeu8(dst, p + 1, (math.floor(v / 256)) % 256) + writeu8(dst, p + 2, math.floor(v / 65536)) + end + elseif fmt == "s24be" then + for i = 0, count - 1 do + local v = q(readf32(src, so + i * 4), 8388608) % 16777216 + local p = d + i * 3 + writeu8(dst, p, math.floor(v / 65536)) + writeu8(dst, p + 1, (math.floor(v / 256)) % 256) + writeu8(dst, p + 2, v % 256) + end + elseif fmt == "s32le" then + for i = 0, count - 1 do + writei32(dst, d + i * 4, q(readf32(src, so + i * 4), 2147483648)) + end + elseif fmt == "s32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(q(readf32(src, so + i * 4), 2147483648) % 4294967296)) + end + elseif fmt == "f32le" then + buffer.copy(dst, d, src, so, count * 4) + elseif fmt == "f32be" then + for i = 0, count - 1 do + writeu32(dst, d + i * 4, byteswap(readu32(src, so + i * 4))) + end + elseif fmt == "f64le" then + for i = 0, count - 1 do + writef64(dst, d + i * 8, readf32(src, so + i * 4)) + end + elseif fmt == "f64be" then + local tmp = buffer.create(8) + for i = 0, count - 1 do + writef64(tmp, 0, readf32(src, so + i * 4)) + local p = d + i * 8 + writeu32(dst, p, byteswap(readu32(tmp, 4))) + writeu32(dst, p + 4, byteswap(readu32(tmp, 0))) + end + elseif fmt == "alaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, alawEncode(q(readf32(src, so + i * 4), 32768))) + end + elseif fmt == "ulaw" then + for i = 0, count - 1 do + writeu8(dst, d + i, ulawEncode(q(readf32(src, so + i * 4), 32768))) + end + else + return false + end + return true +end + +return Convert +end +__FILES["codecs/audio/Qoa"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/audio/Qoa: the "Quite OK Audio" codec (QOA): frames of up to 256 slices per channel, each slice a 4-bit scale +-- factor and 20 3-bit residuals over a 4-tap sign-sign LMS predictor. Ported from qoa.h (phoboslab/qoa, Dominic +-- Szablewski, MIT: licenses/qoa-LICENSE.txt): the tables, the predictor, the decoder and the encoder's brute-force +-- scale factor search, so encoding is byte-for-byte qoa.h's (including its 32-bit wrap in the reciprocal division). +-- The 64-bit slices are handled as two 32-bit halves. +-- +-- local info = Qoa.frameInfo(buf, p, avail) -- { channels, rate, samples, size } | nil, message +-- local n, msg = Qoa.decodeFrame(buf, p, avail, dst, d) -- one frame -> interleaved f32 at float index d +-- local size = Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) -- n frames of f32 at frame xf -> bytes at out[p] +-- local lms = Qoa.newLms(ch) -- the encoder state (history 0, weights 0, 0, -1, 2) +-- +-- Never throws: decodeFrame checks the frame against avail before reading; encodeFrame needs Qoa.frameSize bytes. +local readu8, readu32, readf32, writef32, writeu32 = buffer.readu8, buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local readi32, writei32 = buffer.readi32, buffer.writei32 +local band, rshift, bor, lshift, byteswap = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Qoa = {} + +Qoa.SLICE_LEN = 20 +Qoa.SLICES_PER_FRAME = 256 +Qoa.FRAME_LEN = 256 * 20 +Qoa.MAX_CHANNELS = 255 + +local QUANT = { 7, 7, 7, 5, 5, 3, 3, 1, 0, 0, 2, 2, 4, 4, 6, 6, 6 } -- residual -8 .. 8 -> code +local RECIP = { 65536, 9363, 3121, 1457, 781, 475, 311, 216, 156, 117, 90, 71, 57, 47, 39, 32 } +-- DEQ[sf * 8 + q + 1] +local DEQ = { + 1, -1, 3, -3, 5, -5, 7, -7, + 5, -5, 18, -18, 32, -32, 49, -49, + 16, -16, 53, -53, 95, -95, 147, -147, + 34, -34, 113, -113, 203, -203, 315, -315, + 63, -63, 210, -210, 378, -378, 588, -588, + 104, -104, 345, -345, 621, -621, 966, -966, + 158, -158, 528, -528, 950, -950, 1477, -1477, + 228, -228, 760, -760, 1368, -1368, 2128, -2128, + 316, -316, 1053, -1053, 1895, -1895, 2947, -2947, + 422, -422, 1405, -1405, 2529, -2529, 3934, -3934, + 548, -548, 1828, -1828, 3290, -3290, 5117, -5117, + 696, -696, 2320, -2320, 4176, -4176, 6496, -6496, + 868, -868, 2893, -2893, 5207, -5207, 8099, -8099, + 1064, -1064, 3548, -3548, 6386, -6386, 9933, -9933, + 1286, -1286, 4288, -4288, 7718, -7718, 12005, -12005, + 1536, -1536, 5120, -5120, 9216, -9216, 14336, -14336, +} + +local function be32(b, p) +return byteswap(readu32(b, p)) +end + +local function s16(v) +return (v >= 32768 and((v - 65536 ))or(v +))end + +-- frameSize(channels, slices) -> bytes +function Qoa.frameSize(ch, slices) +return 8 + 16 * ch + 8 * slices * ch +end + +-- frameInfo(buf, p, avail) -> the frame header's facts, checked against avail and the slice count | nil, message + + +function Qoa.frameInfo(b, p, avail) +if avail < 8 then + return nil, "truncated frame header" + end + local hi, lo = be32(b, p), be32(b, p + 4) + local ch = rshift(hi, 24) + local rate = band(hi, 0xFFFFFF) + local samples = rshift(lo, 16) + local size = band(lo, 0xFFFF) + if ch == 0 or rate == 0 or samples == 0 then + return nil, "bad frame header" + end + local slices = math.floor((samples + 19) / 20 +) local head = 8 + 16 * ch + if slices > 256 or size < head or slices * ch > math.floor((size - head) / 8 )then + return nil, "bad frame size" + end + if size > avail then + return nil, "truncated frame" + end + return { channels = ch, rate = rate, samples = samples, size = size }, nil +end + +-- decodeFrame(buf, p, avail, dst, d) -> samples per channel, frame bytes | nil, message: one frame (its own LMS state +-- in the header) as interleaved f32 into dst from float index d (dst holds samples * channels floats there) +function Qoa.decodeFrame(b, p, avail, dst, d) +local info, msg = Qoa.frameInfo(b, p, avail) + if not info then + return nil, msg +end + local ch, samples = info.channels, info.samples + for c = 0, ch - 1 do + local lp = p + 8 + c * 16 + local hA, hB, hC, hD = be32(b, lp), be32(b, lp + 4), be32(b, lp + 8), be32(b, lp + 12) + local h0, h1, h2, h3 = s16(rshift(hA, 16)), s16(band(hA, 0xFFFF)), s16(rshift(hB, 16)), s16(band(hB, 0xFFFF)) + local w0, w1, w2, w3 = s16(rshift(hC, 16)), s16(band(hC, 0xFFFF)), s16(rshift(hD, 16)), s16(band(hD, 0xFFFF)) + local sp = p + 8 + 16 * ch + c * 8 + local o = (d + c) * 4 + local os = ch * 4 + local s0 = 0 + while s0 < samples do + local hi, lo = be32(b, sp), be32(b, sp + 4) + local base = rshift(hi, 28) * 8 + 1 + local n = math.min(20, samples - s0) + for k = 0, n - 1 do + local q + if k < 9 then + q = band(rshift(hi, 25 - 3 * k), 7) + elseif k == 9 then + q = band(hi, 1) * 4 + rshift(lo, 30) + else + q = band(rshift(lo, 57 - 3 * k), 7) + end + local pred = math.floor((w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) / 8192 +) local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + writef32(dst, o, r / 32768) + o =o+ os + local delta = math.floor(dq / 16 +) w0 =w0+ (h0 < 0 and{(-delta )}or{delta +})[1] w1 =w1+ (h1 < 0 and{(-delta )}or{delta +})[1] w2 =w2+ (h2 < 0 and{(-delta )}or{delta +})[1] w3 =w3+ (h3 < 0 and{(-delta )}or{delta +})[1] h0, h1, h2, h3 = h1, h2, h3, r + end + s0 =s0+ 20 + sp =sp+ 8 * ch + end + end + return samples, info.size +end + +-- ------------------------------------------------------------------------------------------------ encoder +-- newLms(ch) -> the encoder's LMS state: 8 i32 per channel (history 0..3, weights 0..3), weights 0, 0, -1, 2 (<< 13) +function Qoa.newLms(ch) +local st = buffer.create(32 * ch) + for c = 0, ch - 1 do + writei32(st, c * 32 + 24, -8192) + writei32(st, c * 32 + 28, 16384) + end + return st +end + +-- the nearest s16 to x * 32768 (NaN -> 0) +local function toS16(x) +local v = floor(x * 32768 + 0.5) + if v ~= v then + return 0 + elseif v > 32767 then + return 32767 + elseif v < -32768 then + return -32768 + end + return v +end + +-- qoa.h's qoa_div: a rounding division by the scale factor through its .16 reciprocal (in 32-bit int arithmetic, which +-- wraps for big residuals at scale factor 0), rounding away from zero +local function qdiv(v, sf) +local x = v * RECIP[sf + 1] + 32768 + if x >= 2147483648 or x < -2147483648 then + x = (x + 2147483648) % 4294967296 - 2147483648 + end + local n = math.floor(x / 65536 +) local sv = v > 0 and 1 or(v < 0 and-1 or 0 +) local sn = n > 0 and 1 or(n < 0 and-1 or 0 +) return n + sv - sn +end + +-- encodeFrame(x, xf, n, ch, rate, lms, out, p) -> bytes written: frames xf .. xf + n - 1 (n <= 5120) of interleaved f32 x +-- as one QOA frame at out[p] (Qoa.frameSize(ch, ceil(n / 20)) bytes); lms carries the encoder state between frames +function Qoa.encodeFrame(x, xf, n, ch, rate, lms, out, p) +local slices = math.floor((n + 19) / 20 +) local size = Qoa.frameSize(ch, slices) + writeu32(out, p, byteswap(bor(lshift(ch, 24), rate))) + writeu32(out, p + 4, byteswap(bor(lshift(n, 16), size))) + for c = 0, ch - 1 do + local so = c * 32 + -- the history and weights as big-endian i16 x 4 + for i = 0, 3 do + local hv = band(readi32(lms, so + i * 4), 0xFFFF) + local wv = band(readi32(lms, so + 16 + i * 4), 0xFFFF) + buffer.writeu8(out, p + 8 + c * 16 + i * 2, rshift(hv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + i * 2 + 1, band(hv, 255)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2, rshift(wv, 8)) + buffer.writeu8(out, p + 8 + c * 16 + 8 + i * 2 + 1, band(wv, 255)) + end + end + local xs = table.create(20, 0) + local codes = table.create(20, 0) + local best = table.create(20, 0) + local prevSf = table.create(ch, 0) + local sp = p + 8 + 16 * ch + for s = 0, slices - 1 do + local len = math.min(20, n - s * 20) + for c = 0, ch - 1 do + for k = 1, len do + xs[k] = toS16(readf32(x, ((xf + s * 20 + k - 1) * ch + c) * 4)) + end + local so = c * 32 + local H0, H1, H2, H3 = readi32(lms, so), readi32(lms, so + 4), readi32(lms, so + 8), readi32(lms, so + 12) + local W0, W1, W2, W3 = readi32(lms, so + 16), readi32(lms, so + 20), readi32(lms, so + 24), readi32(lms, so + 28) + local bestRank, bestSf = math.huge, 0 + local b0, b1, b2, b3, bw0, bw1, bw2, bw3 = H0, H1, H2, H3, W0, W1, W2, W3 + for sfi = 0, 15 do + local sf = (sfi + prevSf[c + 1]) % 16 + local h0, h1, h2, h3, w0, w1, w2, w3 = H0, H1, H2, H3, W0, W1, W2, W3 + local rank = 0 + local base = sf * 8 + 1 + for k = 1, len do + local v = xs[k] + local pred = math.floor((w0 * h0 + w1 * h1 + w2 * h2 + w3 * h3) / 8192 +) local res = v - pred + local sc = qdiv(res, sf) + if sc > 8 then + sc = 8 + elseif sc < -8 then + sc = -8 + end + local q = QUANT[sc + 9] + local dq = DEQ[base + q] + local r = pred + dq + if r > 32767 then + r = 32767 + elseif r < -32768 then + r = -32768 + end + local sq = w0 * w0 + w1 * w1 + w2 * w2 + w3 * w3 + if sq >= 2147483648 then -- C int arithmetic + sq = (sq + 2147483648) % 4294967296 - 2147483648 + end + local pen = math.floor(sq / 262144 )- 0x8ff + if pen < 0 then + pen = 0 + end + local e = v - r + rank =rank+ (e * e + pen * pen +) if rank > bestRank then + break + end + local delta = math.floor(dq / 16 +) w0 =w0+ (h0 < 0 and{(-delta )}or{delta +})[1] w1 =w1+ (h1 < 0 and{(-delta )}or{delta +})[1] w2 =w2+ (h2 < 0 and{(-delta )}or{delta +})[1] w3 =w3+ (h3 < 0 and{(-delta )}or{delta +})[1] h0, h1, h2, h3 = h1, h2, h3, r + codes[k] = q + end + if rank < bestRank then + bestRank, bestSf = rank, sf + b0, b1, b2, b3, bw0, bw1, bw2, bw3 = h0, h1, h2, h3, w0, w1, w2, w3 + for k = 1, len do + best[k] = codes[k] + end + end + end + prevSf[c + 1] = bestSf + writei32(lms, so, b0) + writei32(lms, so + 4, b1) + writei32(lms, so + 8, b2) + writei32(lms, so + 12, b3) + writei32(lms, so + 16, bw0) + writei32(lms, so + 20, bw1) + writei32(lms, so + 24, bw2) + writei32(lms, so + 28, bw3) + -- the slice: sf in the top 4 bits, then the codes, unused codes 0 + local hi, lo = bestSf * 268435456, 0 + for k = 0, 19 do + local q = (k < len and{best[k + 1] }or{0 +})[1] if k < 9 then + hi =hi+ q * 2 ^ (25 - 3 * k) + elseif k == 9 then + hi =hi+ rshift(q, 2) + lo =lo+ band(q, 3) * 1073741824 + else + lo =lo+ q * 2 ^ (57 - 3 * k) + end + end + writeu32(out, sp, byteswap(hi)) + writeu32(out, sp + 4, byteswap(lo)) + sp =sp+ 8 + end + end + return size +end + +return Qoa +end +__FILES["codecs/audio/Resample"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!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 rosetta (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 = {} + + + + + + + + + + + + + + + + +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) +local sum, term = 1, 1 + for k = 1, 80 do + term =term* (x / (2 * k)) ^ 2 + sum =sum+ term + if term < sum * 1e-16 then + break + end + end + return sum +end + +local function gcd(a, b) +while b ~= 0 do + a, b = b, a % b + end + return a +end + +-- 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, phases, exact, zc, beta, cut) +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 = (exact and{phases }or{(phases + 1 +)})[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 = x == 0 and 1 or sin(pi * x) / (pi * x) + v = s * besselI0(beta * sqrt(1 - r * r)) / i0b + end + h[base + k + 1] = v + sum =sum+ v + end + if sum ~= 0 then + for k = 1, taps do +do local __DARKLUA_VAR=base + k h[__DARKLUA_VAR]=h[__DARKLUA_VAR]/ sum +end 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) +-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive) + + + + + + + + + + + + + + + + + + +local function run(st, limitOut, out) +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 = (out and buffer.len(out) >= bytes and{out }or{(buffer.create(bytes) +)})[1] local exact = f.exact + local phases = f.phases + local o = 0 + for j = j0, jmax - 1 do + local num = j * M + local ip = math.floor(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 = (rel < 0 and{(-rel )}or{0 +})[1] 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 =acc+ hist[hi] * h[hb + k] + hi =hi+ ch + end + writef32(b, o, acc) + o =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 =acc+ x * h[hb + k] + acc2 =acc2+ x * h[hb2 + k] + hi =hi+ ch + end + writef32(b, o, acc + (acc2 - acc) * a) + o =o+ 4 + end + end + end + st.outPos = jmax + -- drop history no future output needs (keep from the next output's first tap) + local keepFrom = math.floor((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= (table.create((histFrames - drop) * ch) ) +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, src, frames, out) +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), math.floor(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 =self.histFrames+ frames + self.inFrames =self.inFrames+ frames + return run(self, math.huge, out) +end + +local function flush(self, out) +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, to, channels, opts) +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= 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 = (from ~= floor(from) or to ~= floor(to) )and 1000 or 1 + local fi= floor(from * scale + 0.5) + local ti= floor(to * scale + 0.5) + local g= gcd(fi, ti) + local L, M= math.floor(ti / g), math.floor(fi / g +) local exact = L <= MAX_EXACT + local phases = (exact and{L }or{INTERP_PHASES +})[1] local st= { + from = from, + to = to, + channels = channels, + -- the same rate: a pass-through (tap 0 is the input frame itself) + f = L == 1 and M == 1 and{ taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } or 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 , nil +end + +-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message +function Resample.buffer(src, frames, channels, from, to, opts) +local rs, err = Resample.new(from, to, channels, opts) + if not rs then + return nil, err +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= 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 =got+ m + end + pos =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 =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, to, opts) +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 = (src.frames > 0 and{(floor(src.frames * to / src.sampleRate + 0.5) )}or{0})[1], + tags = src.tags, + err = nil , + } + local inTmp= nil + function out.read(self, n, dst) +n = floor(n) + while pendingFrames - pendingPos <= 0 and not ended do + local b, m= (src ):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp) + inTmp = b + local r, k +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 = (dst and buffer.len(dst) >= bytes and{dst }or{(buffer.create(bytes) +)})[1] buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes) + pendingPos =pendingPos+ k + return b, k + end + return out, nil +end + +return Resample +end +__FILES["codecs/audio/SoundFont"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- 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("rosetta.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) +-- SoundFont.Synth.render(s, out, frame, n) -- mix n stereo f32 frames into out at frame +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Parse = __include("codecs/audio/SoundFont/Parse") +local Synth = __include("codecs/audio/SoundFont/Synth") +local Fallback = __include("codecs/audio/SoundFont/Fallback") + +local SoundFont = {} + + + + +SoundFont.Synth = Synth +SoundFont.defaultRegion = Parse.defaultRegion + +-- sniff(r) -> true when r starts with RIFF....sfbk +function SoundFont.sniff(r) +return r:peek(4) == "RIFF" and r:peek(4, 8) == "sfbk" +end + +-- parse(src, opts?) -> SoundFont | nil, Err. src: buffer | string | Reader. opts.maxRegions (default 10^6), +-- opts.maxSamples (default 2^28) +function SoundFont.parse(src, opts) +local r +if type(src) == "string" then + r = Bytes.reader(buffer.fromstring(src)) + elseif type(src) == "buffer" then + r = Bytes.reader(src) + elseif type(src) == "table" and type(src.buf) == "buffer" then + r = Bytes.reader(src.buf, src.pos, src.limit - src.pos) + else + return nil, Err.new(Err.ARG, "soundfont: expected a buffer, string or Reader") + end + local ok, sf, err = pcall(Parse.parse, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "soundfont parser failed: " .. tostring(sf)) + end + return sf, err +end + +-- fallback() -> the built-in General MIDI waveform set +function SoundFont.fallback() +return Fallback.build() +end + +-- isSoundFont(v) -> true for a parsed / fallback SoundFont value +function SoundFont.isSoundFont(v) +return type(v) == "table" and v.kind == "soundfont" and type(v.samples) == "buffer" and type(v.presets) == "table" +end + +-- synth(sf?, sampleRate?, opts?) -> State. opts.gain (linear, default 0.5), opts.maxVoices (default 256) +function SoundFont.synth(sf, sampleRate, opts) +return Synth.new(sf or Fallback.build(), sampleRate or 44100, opts and opts.gain, opts and opts.maxVoices) +end + +return SoundFont +end +__FILES["codecs/audio/SoundFont/Fallback"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- 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 = __include("codecs/audio/SoundFont/Parse") + +local Fallback = {} + +local CYCLE = 256 +local NOISE = 32768 +local C4 = 261.6255653005986 + +local function hzToCents(hz) +return 1200 * math.log(hz / 8.176, 2) +end + +local cached= nil + +-- build() -> a SoundFont value (kind "soundfont"); built once, shared (the synth never writes to it) +function Fallback.build() +if cached then + return cached + end + local waves = { "sine", "triangle", "square", "saw" } + local count = #waves * CYCLE + NOISE + local samples = buffer.create((count + 1) * 4) + local starts= {} + for w, name in __iter(waves) do + local base = (w - 1) * CYCLE + starts[name] = base + for i = 0, CYCLE - 1 do + local ph = i / CYCLE + local v + if name == "sine" then + v = math.sin(2 * math.pi * ph) + elseif name == "triangle" then + v = (ph < 0.25 and((4 * ph ))or((ph < 0.75 and((2 - 4 * ph ))or((4 * ph - 4 +))))) elseif name == "square" then + v = ph < 0.5 and 0.6 or-0.6 + else + v = (1 - 2 * ph) * 0.7 + end + buffer.writef32(samples, (base + i) * 4, v) + end + end + local noiseStart = #waves * CYCLE + starts.noise = noiseStart + local seed = 12345 + for i = 0, NOISE - 1 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writef32(samples, (noiseStart + i) * 4, (seed / 1073741824 - 1) * 0.7) + end + + local function region(wave, fields) +local r = Parse.defaultRegion() + local s = starts[wave] + r.offset = s + r.loopMode = 1 + r.loopStart = s + if wave == "noise" then + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + NOISE, s + NOISE - 1, 44100, 60 + else + r.stop, r.loopEnd, r.sampleRate, r.keycenter = s + CYCLE, s + CYCLE - 1, CYCLE * C4, 60 + end + r.aRelease = 0.08 + for k, v in __iter(fields) do + r[k] = v + end + return r + end + + -- the 16 GM families: wave + envelope / filter / vibrato + local families= { + { "piano", "triangle", { aDecay = 2.5, aSustain = 0, aRelease = 0.25 } }, + { "chromatic", "sine", { aDecay = 1.2, aSustain = 0, aRelease = 0.3 } }, + { "organ", "square", { aAttack = 0.005, aRelease = 0.05, filterFc = hzToCents(5000) } }, + { "guitar", "saw", { aDecay = 1.5, aSustain = 0, aRelease = 0.15, filterFc = hzToCents(3000) } }, + { "bass", "triangle", { aDecay = 1.5, aSustain = 0.4, aRelease = 0.1 } }, + { "strings", "saw", { aAttack = 0.08, aRelease = 0.3, filterFc = hzToCents(4000), freqVibLFO = hzToCents(5.5), vibLfoToPitch = 8, delayVibLFO = 0.2 } }, + { "ensemble", "saw", { aAttack = 0.12, aRelease = 0.4, filterFc = hzToCents(3500), freqVibLFO = hzToCents(5), vibLfoToPitch = 10 } }, + { "brass", "saw", { aAttack = 0.03, aRelease = 0.12, filterFc = hzToCents(1200), mAttack = 0.05, mDecay = 0.3, mSustain = 0.4, modEnvToFilterFc = 2400 } }, + { "reed", "square", { aAttack = 0.02, aRelease = 0.08, filterFc = hzToCents(2500) } }, + { "pipe", "sine", { aAttack = 0.04, aRelease = 0.12, freqVibLFO = hzToCents(5), vibLfoToPitch = 12, delayVibLFO = 0.3 } }, + { "lead", "square", { aAttack = 0.005, aRelease = 0.1, filterFc = hzToCents(6000) } }, + { "pad", "saw", { aAttack = 0.4, aRelease = 0.8, filterFc = hzToCents(1800), freqModLFO = hzToCents(0.5), modLfoToFilterFc = 600 } }, + { "synthfx", "triangle", { aAttack = 0.2, aRelease = 1.0, freqModLFO = hzToCents(3), modLfoToVolume = 60 } }, + { "ethnic", "saw", { aDecay = 1.0, aSustain = 0, aRelease = 0.2, filterFc = hzToCents(3000) } }, + { "percussive", "sine", { aDecay = 0.4, aSustain = 0, aRelease = 0.1, mDecay = 0.1, mSustain = 0, modEnvToPitch = 1200 } }, + { "sfx", "noise", { aAttack = 0.05, aRelease = 0.5, filterFc = hzToCents(3000) } }, + } + local presets = {} + for program = 0, 127 do + local f = families[math.floor(program / 8 )+ 1] + table.insert(presets, { name = "fallback " .. f[1], preset = program, bank = 0, regions = { region(f[2], f[3]) } }) + end + + -- the drum kit (bank 128, every program): one region per key + local kit = {} + -- fields.semis: the pitch (semitones from the sample's natural pitch) at keytrack 0 + local function drum(lo, hi, wave, fields) + local r = region(wave, fields) + r.lokey, r.hikey = lo, hi + r.sampleRate =r.sampleRate* 2 ^ ((fields.semis or 0) / 12) + r.semis = nil +table.insert(kit, r) + end + local sweep = { mDecay = 0.06, mSustain = 0, modEnvToPitch = 2400 } + local function with(a, b) +local c = table.clone(a) + for k, v in __iter(b) do + c[k] = v + end + return c + end + drum(0, 34, "noise", { aDecay = 0.1, aSustain = 0, keytrack = 0, filterFc = hzToCents(4000) }) + drum(35, 36, "sine", with(sweep, { aDecay = 0.35, aSustain = 0, aRelease = 0.05, keytrack = 0, semis = -26 })) + drum(37, 37, "noise", { aDecay = 0.05, aSustain = 0, keytrack = 0, filterFc = hzToCents(5000) }) + drum(38, 38, "noise", { aDecay = 0.2, aSustain = 0, keytrack = 0, filterFc = hzToCents(6000) }) + drum(39, 39, "noise", { aDecay = 0.15, aSustain = 0, keytrack = 0, filterFc = hzToCents(8000) }) + drum(40, 40, "noise", { aDecay = 0.18, aSustain = 0, keytrack = 0, filterFc = hzToCents(7000) }) + for _, k in __iter({ 41, 43, 45, 47, 48, 50 }) do + drum(k, k, "sine", with(sweep, { aDecay = 0.4, aSustain = 0, semis = (k - 41) - 12, keytrack = 0 })) + end + drum(42, 42, "noise", { aDecay = 0.05, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(44, 44, "noise", { aDecay = 0.08, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(46, 46, "noise", { aDecay = 0.45, aSustain = 0, group = 1, keytrack = 0, semis = 12 }) + drum(49, 49, "noise", { aDecay = 1.5, aSustain = 0, keytrack = 0, semis = 7 }) + drum(51, 51, "noise", { aDecay = 1.0, aSustain = 0, keytrack = 0, semis = 10, filterFc = hzToCents(9000) }) + drum(52, 59, "noise", { aDecay = 1.2, aSustain = 0, keytrack = 0, semis = 5 }) + drum(60, 127, "noise", { aDecay = 0.12, aSustain = 0, keytrack = 30, filterFc = hzToCents(5000) }) + table.insert(presets, { name = "fallback drums", preset = 0, bank = 128, regions = kit }) + + cached = { + kind = "soundfont", + info = { name = "rosetta fallback" }, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = {}, + instruments = {}, + meta = { source = { format = "fallback" } }, + } + return cached +end + +return Fallback +end +__FILES["codecs/audio/SoundFont/Parse"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- 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) +-- does (tsf_load_presets / tsf_region_operator / tsf_region_envtosecs), with every index and sample offset clamped +-- so the synth never reads outside the sample buffer. +-- Differences from tsf.h: initialAttenuation is cB * 0.04 dB (FluidSynth's EMU-compatible scale; tsf uses 0.01); +-- SF3 (Ogg samples) is not supported; modulators (pmod / imod) are read but not applied (as in tsf.h). +-- Never throws: a bad file returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Parse = {} +-- a region (one sample zone of a preset), in "absolute" form: envelope / LFO times in seconds, sustain as a level + + + + + + + + + + + + + + + + +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 + +-- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address +-- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) +local LIM12K5K = { 1, -12000, 5000 } +local LIM12K8K = { 1, -12000, 8000 } +local LIM1200 = { 1, -1200, 1200 } +local GEN= { + [0] = { "offset", "a" }, + [1] = { "stop", "a" }, + [2] = { "loopStart", "a" }, + [3] = { "loopEnd", "a" }, + [4] = { "offset", "a15" }, + [5] = { "modLfoToPitch", "i", { 1, -12000, 12000 } }, + [6] = { "vibLfoToPitch", "i", { 1, -12000, 12000 } }, + [7] = { "modEnvToPitch", "i", { 1, -12000, 12000 } }, + [8] = { "filterFc", "i", { 1, 1500, 13500 } }, + [9] = { "filterQ", "i", { 1, 0, 960 } }, + [10] = { "modLfoToFilterFc", "i", { 1, -12000, 12000 } }, + [11] = { "modEnvToFilterFc", "i", { 1, -12000, 12000 } }, + [12] = { "stop", "a15" }, + [13] = { "modLfoToVolume", "i", { 1, -960, 960 } }, + [17] = { "pan", "f", { 0.001, -0.5, 0.5 } }, + [21] = { "delayModLFO", "f", LIM12K5K }, + [22] = { "freqModLFO", "i", { 1, -16000, 4500 } }, + [23] = { "delayVibLFO", "f", LIM12K5K }, + [24] = { "freqVibLFO", "i", { 1, -16000, 4500 } }, + [25] = { "mDelay", "f", LIM12K5K }, + [26] = { "mAttack", "f", LIM12K8K }, + [27] = { "mHold", "f", LIM12K5K }, + [28] = { "mDecay", "f", LIM12K8K }, + [29] = { "mSustain", "f", { 1, 0, 1000 } }, + [30] = { "mRelease", "f", LIM12K8K }, + [31] = { "mKeyHold", "f", LIM1200 }, + [32] = { "mKeyDecay", "f", LIM1200 }, + [33] = { "aDelay", "f", LIM12K5K }, + [34] = { "aAttack", "f", LIM12K8K }, + [35] = { "aHold", "f", LIM12K5K }, + [36] = { "aDecay", "f", LIM12K8K }, + [37] = { "aSustain", "f", { 1, 0, 1440 } }, + [38] = { "aRelease", "f", LIM12K8K }, + [39] = { "aKeyHold", "f", LIM1200 }, + [40] = { "aKeyDecay", "f", LIM1200 }, + [43] = { "", "kr" }, + [44] = { "", "vr" }, + [45] = { "loopStart", "a15" }, + [48] = { "attenuation", "f", { 0.04, 0, 57.6 } }, + [50] = { "loopEnd", "a15" }, + [51] = { "transpose", "i" }, + [52] = { "tune", "i" }, + [54] = { "loopMode", "loop" }, + [56] = { "keytrack", "i" }, + [57] = { "group", "group" }, + [58] = { "keycenter", "key" }, +} +-- the merged fields: value generators once each (several ops share a field), then the four address fields +local MERGE= {} +do + local seen= {} + for op = 0, 58 do + local g = GEN[op] + if g and (g[2] == "f" or g[2] == "i" or g[2] == "a") and not seen[g[1] ] then + seen[g[1] ] = true + table.insert(MERGE, g) + end + end +end + +local FIELDS = { + "loopMode", "sampleRate", "lokey", "hikey", "lovel", "hivel", "group", "offset", "stop", "loopStart", "loopEnd", + "transpose", "tune", "keycenter", "keytrack", "attenuation", "pan", "filterQ", "filterFc", "modEnvToPitch", + "modEnvToFilterFc", "modLfoToFilterFc", "modLfoToVolume", "delayModLFO", "freqModLFO", "modLfoToPitch", + "delayVibLFO", "freqVibLFO", "vibLfoToPitch", "aDelay", "aAttack", "aHold", "aDecay", "aSustain", "aRelease", + "aKeyHold", "aKeyDecay", "mDelay", "mAttack", "mHold", "mDecay", "mSustain", "mRelease", "mKeyHold", "mKeyDecay", + "sampleIndex", +} + +-- clear(relative): tsf_region_clear. relative = a preset zone (all zero: values add to the instrument's) +local function clear(relative) +local r= {} + for _, f in __iter(FIELDS) do + r[f] = 0 + end + r.hikey, r.hivel, r.keycenter = 127, 127, 60 + if relative then + return r + end + r.keytrack = 100 + r.keycenter = -1 + for _, p in __iter({ "a", "m" }) do + for _, s in __iter({ "Delay", "Attack", "Hold", "Decay", "Release" }) do + r[p .. s] = -12000 + end + end + r.filterFc = 13500 + r.delayModLFO, r.delayVibLFO = -12000, -12000 + return r +end + +local function copy(r) +local c= {} + for k, v in __iter(r) do + c[k] = v + end + return c +end + +-- the region defaults in absolute form (seconds, levels): what Fallback builds its regions from +function Parse.defaultRegion() +local r = clear(false) + r.keycenter = 60 + for _, p in __iter({ "a", "m" }) do + for _, s in __iter({ "Delay", "Attack", "Hold", "Decay", "Release" }) do + r[p .. s] = 0 + end + end + r.aSustain, r.mSustain = 1, 1 + r.delayModLFO, r.delayVibLFO = 0, 0 + return r +end + +-- set one generator (tsf_region_operator with an amount); lo / hi = the two bytes, s = signed 16, w = unsigned 16 +local function operator(r, op, lo, hi, s, w) + local g = GEN[op] + if not g then + return + end + local mode = g[2] + if mode == "f" or mode == "i" then + r[g[1] ] = s + elseif mode == "a" then +do local __DARKLUA_VAR=g[1] r[__DARKLUA_VAR]=r[__DARKLUA_VAR]+ s +end elseif mode == "a15" then +do local __DARKLUA_VAR=g[1] r[__DARKLUA_VAR]=r[__DARKLUA_VAR]+ s * 32768 +end elseif mode == "kr" then + r.lokey, r.hikey = lo, hi + elseif mode == "vr" then + r.lovel, r.hivel = lo, hi + elseif mode == "loop" then + local m = w % 4 + r.loopMode = m == 3 and 2 or(m == 1 and 1 or 0 +) elseif mode == "group" then + r.group = w + elseif mode == "key" then + r.keycenter = s + end +end + +-- merge(zone, preset): zone += preset, then clamp (tsf_region_operator without an amount) +local function merge(z, p) + for _, g in __iter(MERGE) do + local f = g[1] + local v = z[f] + p[f] + local lim = g[3] + if lim then + v =v* lim[1] + v = math.clamp(v, lim[2], lim[3]) + end + z[f] = v + end +end + +local function tc2s(tc) +return 2 ^ (tc / 1200) +end + +-- envtosecs (tsf_region_envtosecs): timecents to seconds; hold / decay stay in timecents when they scale by key +local function envToSecs(r, p, sustainIsGain) + for _, s in __iter({ "Delay", "Attack", "Release" }) do + local v = r[p .. s] + r[p .. s] = v < -11950 and 0 or tc2s(v) + end + if r[p .. "KeyHold"] == 0 then + local v = r[p .. "Hold"] + r[p .. "Hold"] = v < -11950 and 0 or tc2s(v) + end + if r[p .. "KeyDecay"] == 0 then + local v = r[p .. "Decay"] + r[p .. "Decay"] = v < -11950 and 0 or tc2s(v) + end + local sus = r[p .. "Sustain"] + if sus < 0 then + sus = 0 + elseif sustainIsGain then + sus = (-sus / 10 > -100 and((10 ^ (-sus / 10 * 0.05) ))or(0 +)) else + sus = 1 - sus / 1000 + end + r[p .. "Sustain"] = sus +end +-- ------------------------------------------------------------------------------------------------ RIFF +-- record layouts: field byte widths (2 / 4 = little endian unsigned, -2 signed, 20 = name, 1 = byte, -1 = signed byte) + + + +local LAYOUT= { + phdr = { 20, 2, 2, 2, 4, 4, 4 }, + pbag = { 2, 2 }, + pmod = { 2, 2, -2, 2, 2 }, + pgen = { 2, 2 }, + inst = { 20, 2 }, + ibag = { 2, 2 }, + imod = { 2, 2, -2, 2, 2 }, + igen = { 2, 2 }, + shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, +} +local RECSIZE= { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } + +local INFO_NAMES = { + isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", + ICOP = "copyright", ICMT = "comment", ISFT = "software", +} + +-- parse(r, opts?) -> SoundFont | nil, Err + + +function Parse.parse(r, opts) +local maxRegions = opts and opts.maxRegions or 1000000 + local maxSamples = opts and opts.maxSamples or 2 ^ 28 + if r:string(4) ~= "RIFF" then + return r:fail(Err.CORRUPT, "not a RIFF file") + end + local riffSize = r:u32le() + if r:string(4) ~= "sfbk" then + return r:fail(Err.CORRUPT, "not a SoundFont (no sfbk)") + end + if r.err then + return nil, r.err + end + local body = r:sub(12, math.max(0, riffSize - 4)) + local info= {} + local hydra= {} + local smpl= nil + local sm24= nil + local version = "" + while body:remaining() >= 8 do + local id, size = body:string(4), body:u32le() + local chunk = body:slice(size) + if size % 2 == 1 and body:remaining() > 0 then + body:skip(1) + end + if id == "LIST" and chunk:remaining() >= 4 then + local kind = chunk:string(4) + while chunk:remaining() >= 8 do + local sid, ssize = chunk:string(4), chunk:u32le() + local sub = chunk:slice(ssize) + if ssize % 2 == 1 and chunk:remaining() > 0 then + chunk:skip(1) + end + if kind == "INFO" then + if sid == "ifil" and sub:remaining() >= 4 then + local major, minor = sub:u16le(), sub:u16le() + version = string.format("%d.%02d", major, minor) + elseif INFO_NAMES[sid] then + info[INFO_NAMES[sid] ] = sub:fixed(sub:remaining()) + end + elseif kind == "sdta" then + if sid == "smpl" and not smpl then + smpl = sub + elseif sid == "sm24" then + sm24 = sub + end + elseif kind == "pdta" then + local layout = LAYOUT[sid] + if layout and not hydra[sid] then + local rs = RECSIZE[sid] + local n = math.floor(sub:remaining() / rs +) local recs = (table.create(n) ) +for i = 1, n do + local rec = {} + for _, w in __iter(layout) do + if w == 20 then + table.insert(rec, 0) -- the name is read separately + sub:skip(20) + elseif w == 4 then + table.insert(rec, sub:u32le()) + elseif w == 2 then + table.insert(rec, sub:u16le()) + elseif w == -2 then + table.insert(rec, sub:i16le()) + elseif w == 1 then + table.insert(rec, sub:u8()) + else + table.insert(rec, sub:i8()) + end + end + recs[i] = rec + end + hydra[sid] = recs + if sid == "phdr" or sid == "inst" or sid == "shdr" then + local names = table.create(n) + for i = 0, n - 1 do + names[i + 1] = sub:sub(i * rs, 20):fixed(20) + end + hydra[sid .. "Names"] = names +end + end + end + end + end + end + if not smpl then + return nil, Err.new(Err.CORRUPT, "no sample data (sdta smpl)") + end + for _, k in __iter({ "phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr" }) do + if not hydra[k] or #hydra[k] == 0 then + return nil, Err.new(Err.CORRUPT, "incomplete hydra: no " .. k .. " records") + end + end + -- samples + local sr = smpl +local count = math.floor(sr:remaining() / 2 +) if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("%d samples is over the %d sample limit", count, maxSamples)) + end + local samples = buffer.create((count + 1) * 4) + do + local b, p = sr.buf, sr.pos + local readi16, writef32 = buffer.readi16, buffer.writef32 + local s24 = sm24 + if s24 and s24:remaining() >= count then + local q = s24.pos + local readu8 = buffer.readu8 + for i = 0, count - 1 do + writef32(samples, i * 4, (readi16(b, p + i * 2) * 256 + readu8(s24.buf, q + i)) / 8388607) + end + else + s24 = nil + for i = 0, count - 1 do + writef32(samples, i * 4, readi16(b, p + i * 2) / 32767) + end + end + sm24 = s24 + end + -- presets (tsf_load_presets) + local phdr, pbag, pgen = hydra.phdr, hydra.pbag, hydra.pgen + local inst, ibag, igen, shdr = hydra.inst, hydra.ibag, hydra.igen, hydra.shdr + local phdrNames, instNames, shdrNames = (hydra ).phdrNames, (hydra ).instNames, (hydra ).shdrNames + local nInst = #inst - 1 -- the last record of each list is the terminal one + local nShdr = #shdr - 1 + local function range(list, i, field, limit) -- [list[i][field], list[i + 1][field]) clamped to [1, limit] (1-based record indexes) + +local a = list[i][field] + 1 + local b = (list[i + 1] and((list[i + 1][field] + 1 ))or(a +)) return math.max(1, a), math.min(b, limit + 1) + end + local presets= {} + local regionTotal = 0 + for pi = 1, #phdr - 1 do + local ph = phdr[pi] + local preset= { name = phdrNames[pi], preset = ph[2], bank = ph[3], regions = {} } + local globalRegion = clear(true) + local b0, b1 = range(phdr, pi, 4, #pbag) + for bi = b0, b1 - 1 do + local presetRegion = copy(globalRegion) + local hadInstrument = false + local g0, g1 = range(pbag, bi, 1, #pgen) + for gi = g0, g1 - 1 do + local pg = pgen[gi] + local op, amount = pg[1], pg[2] + local lo, hi = amount % 256, math.floor(amount / 256 +) local s = (amount >= 32768 and((amount - 65536 ))or(amount +)) if op == GEN_INSTRUMENT then + hadInstrument = true + if amount < nInst then + local instRegion = clear(false) + local ib0, ib1 = range(inst, amount + 1, 2, #ibag) + for ibi = ib0, ib1 - 1 do + local zone = copy(instRegion) + local hadSample = false + local ig0, ig1 = range(ibag, ibi, 1, #igen) + for igi = ig0, ig1 - 1 do + local ig = igen[igi] + local iop, iamt = ig[1], ig[2] + if iop == GEN_SAMPLEID then + hadSample = true + if iamt >= nShdr then + break + end + local ok = not (zone.hikey < presetRegion.lokey or zone.lokey > presetRegion.hikey) + and not (zone.hivel < presetRegion.lovel or zone.lovel > presetRegion.hivel) + if ok then + local z = copy(zone) + z.lokey = math.max(z.lokey, presetRegion.lokey) + z.hikey = math.min(z.hikey, presetRegion.hikey) + z.lovel = math.max(z.lovel, presetRegion.lovel) + z.hivel = math.min(z.hivel, presetRegion.hivel) + merge(z, presetRegion) + envToSecs(z, "a", true) + envToSecs(z, "m", false) + z.delayModLFO = z.delayModLFO < -11950 and 0 or tc2s(z.delayModLFO) + z.delayVibLFO = z.delayVibLFO < -11950 and 0 or tc2s(z.delayVibLFO) + local sh = shdr[iamt + 1] + local sStart, sEnd, sLoopStart, sLoopEnd = sh[2], sh[3], sh[4], sh[5] + z.offset = math.clamp(z.offset + sStart, 0, count) + local stop = z.stop + sEnd + if stop > 0 and stop < count then + stop =stop+ 1 + else + stop = count + end + z.stop = math.clamp(stop, 0, count) + z.loopStart = math.clamp(z.loopStart + sLoopStart, 0, count) + local le = z.loopEnd + sLoopEnd + if sLoopEnd > 0 then + le =le- 1 + end + z.loopEnd = math.clamp(le, 0, count) + if z.keycenter == -1 then + z.keycenter = sh[7] + end + z.tune =z.tune+ sh[8] + z.sampleRate = sh[6] + z.sampleIndex = iamt + regionTotal =regionTotal+ 1 + if regionTotal > maxRegions then + return nil, Err.new(Err.LIMIT, "over " .. maxRegions .. " regions") + end + table.insert(preset.regions, z) + end + break -- sampleID ends a zone's generator list + else + local ilo, ihi = iamt % 256, math.floor(iamt / 256 +) operator(zone, iop, ilo, ihi, (iamt >= 32768 and((iamt - 65536 ))or(iamt)), iamt) + end + end + if ibi == ib0 and not hadSample then + instRegion = zone -- the instrument's global zone + end + end + end + break -- instrument ends a preset zone's generator list + else + operator(presetRegion, op, lo, hi, s, amount) + end + end + if bi == b0 and not hadInstrument then + globalRegion = presetRegion -- the preset's global zone + end + end + table.insert(presets, preset) + end + -- sorted by bank, then preset, then file order (tsf's sortedIndex) + for i, p in __iter(presets) do + (p )._order = i + end + table.sort(presets, function(a, b) +if a.bank ~= b.bank then + return a.bank < b.bank + end + if a.preset ~= b.preset then + return a.preset < b.preset + end + return (a )._order < (b )._order + end) + for _, p in __iter(presets) do + (p )._order = nil + end + local headers = (table.create(nShdr) ) +for i = 1, nShdr do + local sh = shdr[i] + headers[i] = { + name = shdrNames[i], + start = sh[2], + stop = sh[3], + loopStart = sh[4], + loopEnd = sh[5], + sampleRate = sh[6], + originalPitch = sh[7], + pitchCorrection = sh[8], + link = sh[9], + type = sh[10], + } + end + local instruments = (table.create(nInst) ) +for i = 1, nInst do + instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } + end + local sf= { + kind = "soundfont", + info = info, + samples = samples, + sampleCount = count, + presets = presets, + sampleHeaders = headers, + instruments = instruments, + meta = { source = { format = "sf2", version = version, sm24 = sm24 ~= nil } }, + } + return sf, nil +end + +return Parse +end +__FILES["codecs/audio/SoundFont/Synth"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +-- 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 +-- interpolation, loop modes (none / continuous / until release), 3 dB pan law, exclusive classes; channels with +-- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, +-- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not +-- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. +-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, +-- the sample buffer has a zero pad sample, the output range is checked before mixing). +local Synth = {} + +local readf32, writef32, blen = buffer.readf32, buffer.writef32, buffer.len +local exp, log, sqrt, tan, floor = math.exp, math.log, math.sqrt, math.tan, math.floor + +local NONE, DELAY, ATTACK, HOLD, DECAY, SUSTAIN, RELEASE, DONE = 0, 1, 2, 3, 4, 5, 6, 7 +local BLOCK = 64 -- TSF_RENDER_EFFECTSAMPLEBLOCK: envelopes / LFOs / filter cutoff update per block +local FASTRELEASE = 0.01 +local PI = math.pi +local LOOP_NONE, LOOP_SUSTAIN = 0, 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function tc2s(tc) +return 2 ^ (tc / 1200) +end +local function cents2Hz(c) +return 8.176 * 2 ^ (c / 1200) +end +local function db2gain(db) +return (db > -100 and((10 ^ (db * 0.05) ))or(0 +))end +local function gain2db(g) +return g <= 0.00001 and-100 or 20 * math.log10(g) +end + +-- ------------------------------------------------------------------------------------------------ envelope +local function releaseSamples(e, rate) +return floor(((e.release <= 0 and{FASTRELEASE }or{e.release})[1]) * rate) +end + +local function nextSegment(e, active, rate) + local seg = active + if seg == NONE then + e.untilNext = floor(e.delay * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = DELAY, false, 0, 0 + return + end + seg = DELAY + end + if seg == DELAY then + e.untilNext = floor(e.attack * rate) + if e.untilNext > 0 then + if not e.isAmp then + -- the mod env attack scales with velocity (1 = full duration, 127 = 0.125 x) + e.untilNext = floor(e.attack * ((145 - e.vel) / 144) * rate) + end + e.segment, e.isExp, e.level = ATTACK, false, 0 + e.slope = (e.untilNext > 0 and((1 / e.untilNext ))or(1 +)) return + end + seg = ATTACK + end + if seg == ATTACK then + e.untilNext = floor(e.hold * rate) + if e.untilNext > 0 then + e.segment, e.isExp, e.level, e.slope = HOLD, false, 1, 0 + return + end + seg = HOLD + end + if seg == HOLD then + e.untilNext = floor(e.decay * rate) + if e.untilNext > 0 then + e.segment, e.level = DECAY, 1 + if e.isAmp then + local mystery = -9.226 / e.untilNext -- LinuxSampler's decay curve (as tsf.h) + e.slope = exp(mystery) + e.isExp = true + if e.sustain > 0 then + e.untilNext = floor(log(e.sustain) / mystery) + end + else + e.slope = -1 / e.untilNext + e.untilNext = floor(e.decay * (1 - e.sustain) * rate) + e.isExp = false + end + return + end + seg = DECAY + end + if seg == DECAY then + e.segment, e.level, e.slope, e.untilNext, e.isExp = SUSTAIN, e.sustain, 0, 0x7FFFFFFF, false + return + end + if seg == SUSTAIN then + e.segment = RELEASE + e.untilNext = math.max(1, releaseSamples(e, rate)) + if e.isAmp then + e.slope = exp(-9.226 / e.untilNext) + e.isExp = true + else + e.slope = -e.level / e.untilNext + e.isExp = false + end + return + end + e.segment, e.isExp, e.level, e.slope, e.untilNext = DONE, false, 0, 0, 0x7FFFFFF +end + +local function envSetup(e, r, p, key, vel, isAmp, rate) + e.delay, e.attack, e.hold, e.decay = r[p .. "Delay"], r[p .. "Attack"], r[p .. "Hold"], r[p .. "Decay"] + e.sustain, e.release = r[p .. "Sustain"], r[p .. "Release"] + local kh, kd = r[p .. "KeyHold"], r[p .. "KeyDecay"] + if kh ~= 0 then + local h = e.hold + kh * (60 - key) + e.hold = h < -10000 and 0 or tc2s(h) + end + if kd ~= 0 then + local d = e.decay + kd * (60 - key) + e.decay = d < -10000 and 0 or tc2s(d) + end + e.vel, e.isAmp = vel, isAmp + nextSegment(e, NONE, rate) +end + +local function envProcess(e, n, rate) + local slope = e.slope + if slope ~= 0 then + if e.isExp then + e.level =e.level* slope ^ n + else + e.level =e.level+ slope * n + end + end + e.untilNext =e.untilNext- n + if e.untilNext <= 0 then + nextSegment(e, e.segment, rate) + end +end + +local function newEnv() +return { segment = DONE, isExp = false, isAmp = false, vel = 0, level = 0, slope = 0, untilNext = 0, delay = 0, attack = 0, hold = 0, decay = 0, sustain = 0, release = 0 } +end + +-- ------------------------------------------------------------------------------------------------ filter / lfo +local function lowpassSetup(v, fc) + -- the biquad from earlevel.com (as tsf.h) + local k = tan(PI * fc) + local kk = k * k + local norm = 1 / (1 + k * v.qinv + kk) + v.a0 = kk * norm + v.a1 = 2 * v.a0 + v.b1 = 2 * (kk - 1) * norm + v.b2 = (1 - k * v.qinv + kk) * norm +end + +local function lfoSetup(l, delay, freqCents, rate) + l.untilStart = floor(delay * rate) + l.delta = 4 * cents2Hz(freqCents) / rate + l.level = 0 +end + +local function lfoProcess(l, n) + if l.untilStart > n then + l.untilStart =l.untilStart- n + return + end + l.level =l.level+ l.delta * n + if l.level > 1 then + l.delta = -l.delta + l.level = 2 - l.level + elseif l.level < -1 then + l.delta = -l.delta + l.level = -2 - l.level + end +end + +-- ------------------------------------------------------------------------------------------------ voices +local function calcPitch(v, shift, rate) + local r = v.region + local note = v.key + r.transpose + r.tune / 100 + local adjusted = r.keycenter + (note - r.keycenter) * (r.keytrack / 100) + shift + v.pitchIn = adjusted * 100 + v.pitchOut = r.sampleRate / (tc2s(r.keycenter * 100) * rate) +end + +local function setPan(v, pan) + if pan <= -0.5 then + v.panL, v.panR = 1, 0 + elseif pan >= 0.5 then + v.panL, v.panR = 0, 1 + else + v.panL, v.panR = sqrt(0.5 - pan), sqrt(0.5 + pan) + end +end + +local function channelShift(c) +return (c.pitchWheel == 8192 and{c.tuning }or{((c.pitchWheel / 16383 * c.pitchRange * 2) - c.pitchRange + c.tuning +)})[1]end + +local function voiceEnd(s, v) + nextSegment(v.amp, SUSTAIN, s.rate) + nextSegment(v.mod, SUSTAIN, s.rate) + if v.region.loopMode == LOOP_SUSTAIN then + v.loopEnd = v.loopStart -- keep playing, stop looping + end +end + +local function voiceEndQuick(s, v) + v.amp.release = 0 + nextSegment(v.amp, SUSTAIN, s.rate) + v.mod.release = 0 + nextSegment(v.mod, SUSTAIN, s.rate) +end + +local function newVoice() +return { + preset = -1, key = 0, channel = 0, held = false, region = {}, pitchIn = 0, pitchOut = 0, pos = 0, gainDB = 0, + panL = 0, panR = 0, playIndex = 0, loopStart = 0, loopEnd = 0, amp = newEnv(), mod = newEnv(), + lpActive = false, qinv = 0, a0 = 0, a1 = 0, b1 = 0, b2 = 0, z1 = 0, z2 = 0, + modlfo = { untilStart = 0, level = 0, delta = 0 }, viblfo = { untilStart = 0, level = 0, delta = 0 }, + } +end + +local function newChannel() +return { + preset = 1, bank = 0, pitchWheel = 8192, midiPan = 8192, midiVolume = 16383, midiExpression = 16383, + midiRPN = 0xFFFF, midiData = 0, sustain = false, panOffset = 0, gainDB = 0, pitchRange = 2, tuning = 0, + } +end + +-- new(sf, sampleRate, opts) -> State. sf: { presets, samples } (Parse.parse or Fallback.build). +-- opts.gain: output gain (linear, default 0.5); opts.maxVoices (default 256) +function Synth.new(sf, rate, gain, maxVoices) +local lookup= {} + for i, p in __iter(sf.presets) do + local k = p.bank * 128 + p.preset + if lookup[k] == nil then + lookup[k] = i + end + end + local s= { + presets = sf.presets, + lookup = lookup, + samples = sf.samples, + rate = rate, + gainDB = gain2db(gain or 0.5), + voices = {}, + maxVoices = maxVoices or 256, + playIndex = 0, + channels = {}, + } + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end + return s +end + +local function presetIndex(s, bank, preset) +return s.lookup[bank * 128 + preset] or -1 +end + +-- noteOn(s, channel, key, velocity 0..127) +function Synth.noteOn(s, ch, key, velocity) + local c = s.channels[ch + 1] + if not c then + return + end + if velocity <= 0 then + Synth.noteOff(s, ch, key) + return + end + local pi = c.preset + local preset = s.presets[pi] + if not preset then + return + end + local vel = math.min(velocity, 127) / 127 + local midiVel = floor(vel * 127) + local rate = s.rate + local voices = s.voices + local playIndex = s.playIndex + s.playIndex =s.playIndex+ 1 + for _, region in __iter(preset.regions) do +local __DARKLUA_CONTINUE_4=false repeat if key < region.lokey or key > region.hikey or midiVel < region.lovel or midiVel > region.hivel then +__DARKLUA_CONTINUE_4=true break + end + local voice= nil + if region.group ~= 0 then + for _, v in __iter(voices) do + if v.preset == pi and v.region.group == region.group then + voiceEndQuick(s, v) + elseif v.preset == -1 and not voice then + voice = v + end + end + else + for _, v in __iter(voices) do + if v.preset == -1 then + voice = v + break + end + end + end + if not voice then + if #voices < s.maxVoices then + local v = newVoice() + table.insert(voices, v) + voice = v + else + local best = -1e18 + for _, v in __iter(voices) do + if v.amp.segment == RELEASE then + local done = releaseSamples(v.amp, rate) - v.amp.untilNext + if done > best then + best, voice = done, v + end + end + end + if not voice then +__DARKLUA_CONTINUE_4=true break + end + end + end + local v = voice +v.region = region + v.preset = pi + v.key = key + v.channel = ch + v.playIndex = playIndex + v.held = false + v.gainDB = s.gainDB - region.attenuation - gain2db(1 / vel) + c.gainDB + calcPitch(v, channelShift(c), rate) + setPan(v, region.pan + c.panOffset) + v.pos = region.offset + local doLoop = region.loopMode ~= LOOP_NONE and region.loopStart < region.loopEnd + v.loopStart = (doLoop and{region.loopStart }or{0 +})[1] v.loopEnd = (doLoop and{region.loopEnd }or{0 +})[1] envSetup(v.amp, region, "a", key, midiVel, true, rate) + envSetup(v.mod, region, "m", key, midiVel, false, rate) + local fc = (region.filterFc <= 13500 and((cents2Hz(region.filterFc) / rate ))or(1 +)) v.qinv = 1 / 10 ^ ((region.filterQ / 10) / 20) + v.z1, v.z2 = 0, 0 + v.lpActive = fc < 0.499 + if v.lpActive then + lowpassSetup(v, fc) + end + lfoSetup(v.modlfo, region.delayModLFO, region.freqModLFO, rate) + lfoSetup(v.viblfo, region.delayVibLFO, region.freqVibLFO, rate) +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end +end + +-- noteOff(s, channel, key): ends the oldest matching note (all its regions); held while sustain is down +function Synth.noteOff(s, ch, key) + local c = s.channels[ch + 1] + if not c then + return + end + local first = -1 + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held then + if first == -1 or v.playIndex < first then + first = v.playIndex + end + end + end + if first == -1 then + return + end + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch and v.key == key and v.amp.segment < RELEASE and not v.held and v.playIndex == first then + if c.sustain then + v.held = true + else + voiceEnd(s, v) + end + end + end +end + +local function applyPitch(s, ch, c) + local shift = channelShift(c) + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch then + calcPitch(v, shift, s.rate) + end + end +end + +local function setVolume(s, ch, c, volume) + local db = gain2db(volume) + if db == c.gainDB then + return + end + local change = db - c.gainDB + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch then + v.gainDB =v.gainDB+ change + end + end + c.gainDB = db +end + +local function setChannelPan(s, ch, c, pan) + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch then + setPan(v, v.region.pan + pan - 0.5) + end + end + c.panOffset = pan - 0.5 +end + +local function setTuning(s, ch, c, tuning) + if c.tuning ~= tuning then + c.tuning = tuning + applyPitch(s, ch, c) + end +end + +local function setPitchRange(s, ch, c, range) + if c.pitchRange ~= range then + c.pitchRange = range + if c.pitchWheel ~= 8192 then + applyPitch(s, ch, c) + end + end +end + +local function setSustain(s, ch, c, on) + if c.sustain == on then + return + end + c.sustain = on + if on then + return + end + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE and v.held then + voiceEnd(s, v) + end + end +end + +-- program(s, channel, program): bank select + program change (channel 9: drums, bank 128) +function Synth.program(s, ch, program) + local c = s.channels[ch + 1] + if not c then + return + end + local bank = c.bank % 32768 + local idx + if ch == 9 then + idx = presetIndex(s, 128 + bank, program) + if idx == -1 then + idx = presetIndex(s, 128, program) + end + if idx == -1 then + idx = presetIndex(s, 128, 0) + end + if idx == -1 then + idx = presetIndex(s, bank, program) + end + else + idx = presetIndex(s, bank, program) + end + if idx == -1 then + idx = presetIndex(s, 0, program) + end + if idx ~= -1 then + c.preset = idx + end +end + +-- pitchBend(s, channel, 0..16383) +function Synth.pitchBend(s, ch, value) + local c = s.channels[ch + 1] + if not c or c.pitchWheel == value then + return + end + c.pitchWheel = value + applyPitch(s, ch, c) +end + +-- control(s, channel, controller, value 0..127) +function Synth.control(s, ch, cc, value) + local c = s.channels[ch + 1] + if not c then + return + end + local volume, pan, data = false, false, false + if cc == 7 then + c.midiVolume = c.midiVolume % 128 + value * 128 + volume = true + elseif cc == 39 then + c.midiVolume = c.midiVolume - c.midiVolume % 128 + value + volume = true + elseif cc == 11 then + c.midiExpression = c.midiExpression % 128 + value * 128 + volume = true + elseif cc == 43 then + c.midiExpression = c.midiExpression - c.midiExpression % 128 + value + volume = true + elseif cc == 10 then + c.midiPan = c.midiPan % 128 + value * 128 + pan = true + elseif cc == 42 then + c.midiPan = c.midiPan - c.midiPan % 128 + value + pan = true + elseif cc == 6 then + c.midiData = c.midiData % 128 + value * 128 + data = true + elseif cc == 38 then + c.midiData = c.midiData - c.midiData % 128 + value + data = true + elseif cc == 0 then + c.bank = 0x8000 + value -- bank select MSB alone acts like LSB (as tsf.h) + elseif cc == 32 then + c.bank = ((c.bank >= 0x8000 and(((c.bank % 128) * 128 ))or(0))) + value + elseif cc == 101 then + local rpn = c.midiRPN == 0xFFFF and 0 or c.midiRPN + c.midiRPN = rpn % 128 + value * 128 + elseif cc == 100 then + local rpn = c.midiRPN == 0xFFFF and 0 or c.midiRPN + c.midiRPN = rpn - rpn % 128 + value + elseif cc == 98 or cc == 99 then + c.midiRPN = 0xFFFF + elseif cc == 64 then + setSustain(s, ch, c, value >= 64) + elseif cc == 120 then + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch and (v.amp.segment < RELEASE or v.amp.release ~= 0) then + voiceEndQuick(s, v) + end + end + elseif cc == 123 then + for _, v in __iter(s.voices) do + if v.preset ~= -1 and v.channel == ch and v.amp.segment < RELEASE then + voiceEnd(s, v) + end + end + elseif cc == 121 then + c.midiVolume, c.midiExpression, c.midiPan, c.bank, c.midiRPN, c.midiData = 16383, 16383, 8192, 0, 0xFFFF, 0 + setVolume(s, ch, c, 1) + setChannelPan(s, ch, c, 0.5) + setPitchRange(s, ch, c, 2) + setTuning(s, ch, c, 0) + end + if volume then + -- the cube gives a decent MIDI volume curve (tsf.h) + setVolume(s, ch, c, ((c.midiVolume / 16383) * (c.midiExpression / 16383)) ^ 3) + elseif pan then + setChannelPan(s, ch, c, c.midiPan / 16383) + elseif data then + if c.midiRPN == 0 then + setPitchRange(s, ch, c, math.floor(c.midiData / 128 )+ 0.01 * (c.midiData % 128)) + elseif c.midiRPN == 1 then + local t = c.tuning + setTuning(s, ch, c, ((t < 0 and{(math.ceil(t) )}or{(floor(t))})[1]) + (c.midiData - 8192) / 8192) + elseif c.midiRPN == 2 and cc == 6 then + local t = c.tuning + setTuning(s, ch, c, (value - 64) + (t - ((t < 0 and{(math.ceil(t) )}or{(floor(t))})[1]))) + end + end +end + +-- midi(s, status, d1, d2): one channel message +function Synth.midi(s, status, d1, d2) + local kind, ch = math.floor(status / 16), status % 16 + if kind == 9 then + Synth.noteOn(s, ch, d1, d2) + elseif kind == 8 then + Synth.noteOff(s, ch, d1) + elseif kind == 11 then + Synth.control(s, ch, d1, d2) + elseif kind == 12 then + Synth.program(s, ch, d1) + elseif kind == 14 then + Synth.pitchBend(s, ch, d1 + d2 * 128) + end +end + +-- reset(s): all voices off, channels back to their defaults +function Synth.reset(s) + for _, v in __iter(s.voices) do + v.preset = -1 + end + for ch = 1, 16 do + s.channels[ch] = newChannel() + end + for ch = 0, 15 do + Synth.program(s, ch, 0) + end +end + +-- active(s) -> the number of sounding voices +function Synth.active(s) +local n = 0 + for _, v in __iter(s.voices) do + if v.preset ~= -1 then + n =n+ 1 + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ render +local function voiceRender(s, v, out, frame, numSamples) + local region = v.region + local input = s.samples + local rate = s.rate + local modEnvToPitch, modEnvToFilterFc = region.modEnvToPitch, region.modEnvToFilterFc + local modLfoToPitch, modLfoToFilterFc, modLfoToVolume = region.modLfoToPitch, region.modLfoToFilterFc, region.modLfoToVolume + local vibLfoToPitch = region.vibLfoToPitch + local updateModEnv = modEnvToPitch ~= 0 or modEnvToFilterFc ~= 0 + local updateModLfo = v.modlfo.delta ~= 0 and (modLfoToPitch ~= 0 or modLfoToFilterFc ~= 0 or modLfoToVolume ~= 0) + local updateVibLfo = v.viblfo.delta ~= 0 and vibLfoToPitch ~= 0 + local loopStart, loopEnd = v.loopStart, v.loopEnd + local isLooping = loopStart < loopEnd + local endD = region.stop + local loopEndD = loopEnd + 1 + local loopLen = loopEnd - loopStart + 1 + local pos = v.pos + local lpActive, a0, a1, b1, b2, z1, z2 = v.lpActive, v.a0, v.a1, v.b1, v.b2, v.z1, v.z2 + local dynamicLowpass = modLfoToFilterFc ~= 0 or modEnvToFilterFc ~= 0 + local dynamicPitch = modLfoToPitch ~= 0 or modEnvToPitch ~= 0 or vibLfoToPitch ~= 0 + local dynamicGain = modLfoToVolume ~= 0 + local filterFc = region.filterFc + local pitchRatio = dynamicPitch and 0 or tc2s(v.pitchIn) * v.pitchOut + local noteGain = dynamicGain and 0 or db2gain(v.gainDB) + local o = frame * 8 + while numSamples > 0 do + local block = (numSamples > BLOCK and{BLOCK }or{numSamples +})[1] numSamples =numSamples- block + if dynamicLowpass then + local fres = filterFc + v.modlfo.level * modLfoToFilterFc + v.mod.level * modEnvToFilterFc + local fc = (fres <= 13500 and((cents2Hz(fres) / rate ))or(1 +)) lpActive = fc < 0.499 + if lpActive then + lowpassSetup(v, fc) + a0, a1, b1, b2 = v.a0, v.a1, v.b1, v.b2 + end + end + if dynamicPitch then + pitchRatio = tc2s(v.pitchIn + (v.modlfo.level * modLfoToPitch + v.viblfo.level * vibLfoToPitch + v.mod.level * modEnvToPitch)) * v.pitchOut + end + if dynamicGain then + noteGain = db2gain(v.gainDB + v.modlfo.level * modLfoToVolume * 0.1) + end + local gainMono = noteGain * v.amp.level + envProcess(v.amp, block, rate) + if updateModEnv then + envProcess(v.mod, block, rate) + end + if updateModLfo then + lfoProcess(v.modlfo, block) + end + if updateVibLfo then + lfoProcess(v.viblfo, block) + end + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono + local k = block + while k > 0 and pos < endD do + k =k- 1 + local ip = floor(pos) + local np = (ip >= loopEnd and isLooping and{loopStart }or{(ip + 1 +)})[1] local s0 = readf32(input, ip * 4) + local val = s0 + (readf32(input, np * 4) - s0) * (pos - ip) + if lpActive then + local y = val * a0 + z1 + z1 = val * a1 + z2 - b1 * y + z2 = val * a0 - b2 * y + val = y + end + val =val* g + g =g+ step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) + o =o+ 8 + pos =pos+ pitchRatio + if pos >= loopEndD and isLooping then + pos =pos- loopLen + end + end + o =o+ k * 8 + if not (pos < endD) or v.amp.segment == DONE then + v.preset = -1 + return + end + end + v.pos = pos + v.lpActive, v.z1, v.z2 = lpActive, z1, z2 +end + +-- render(s, out, frame, n): mixes n stereo frames into out (interleaved f32) starting at frame; out-of-range +-- requests are clipped to the buffer +function Synth.render(s, out, frame, n) + local room = math.floor(blen(out) / 8 )- frame + if frame < 0 or room <= 0 then + return + end + if n > room then + n = room + end + if n <= 0 then + return + end + -- the sample buffer must hold every region's range + the pad sample (Parse / Fallback guarantee it; checked here + -- once so a hand-made SoundFont cannot index outside it) + local count = math.floor(blen(s.samples) / 4 )- 1 + for _, v in __iter(s.voices) do + if v.preset ~= -1 then + local r = v.region + if r.stop > count or r.loopEnd > count or r.offset < 0 or r.loopStart < 0 or v.pos < 0 then + v.preset = -1 + else + voiceRender(s, v, out, frame, n) + end + end + end +end + +return Synth +end +__FILES["codecs/audio/Stream"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!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 rosetta +-- (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; or a buffer of f32) 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) +-- scale = 1 / 32768, -- optional: read() writes pcm() values * scale (default 1) +-- ints = true, -- optional: pcm() holds integers; adds dec:readInt(n, out?), the +-- }) -- same frames as read() as i32 (bit-exact checks) +-- +-- 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 = __include("core/Err") + +local Stream = {} + +-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed) + + + + + + + + + + + + + + +function Stream.packets(dec, spec) +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= nil + dec.error = nil + + local function fill() +while true do + if nextPacket > count or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket =nextPacket+ 1 + local first = (spec.cumulative and{decoded }or{(startOf(i) +)})[1] 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 + + local scale = spec.scale or 1 + local function pull(n, out, asInt) +local want = math.max(0, math.floor(n)) + local need = want * ch * 4 + local ob = (out and buffer.len(out) >= need and{out }or{(buffer.create(need) +)})[1] local got = 0 + local writef32, writei32 = buffer.writef32, buffer.writei32 + 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 + if type(src) == "buffer" then + if scale == 1 and not asInt then + buffer.copy(ob, q, src, s * 4, take * ch * 4) + else + for k = 0, take * ch - 1 do + local v = buffer.readf32(src, (s + k) * 4) + if asInt then + writei32(ob, q, v) + else + writef32(ob, q, v * scale) + end + q =q+ 4 + end + end + elseif asInt then + for k = 1, take * ch do + writei32(ob, q, src[s + k]) + q =q+ 4 + end + elseif scale == 1 then + for k = 1, take * ch do + writef32(ob, q, src[s + k]) + q =q+ 4 + end + else + for k = 1, take * ch do + writef32(ob, q, src[s + k] * scale) + q =q+ 4 + end + end + pendPos =pendPos+ take + got =got+ take + end + pos =pos+ got + return ob, got + end + + function dec.read(_self, n, out) +return pull(n, out, false) + end + if spec.ints then + function dec.readInt(_self, n, out) +return pull(n, out, true) + end + end + + function dec.seek(_self, seconds) + local sec = (type(seconds) == "number" and seconds == seconds and{seconds }or{0 +})[1] 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 = math.floor((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 = (count > 0 and{(startOf(found) )}or{0 +})[1] dropUntil = target + pendPos, pendN = 0, 0 + failed = nil + dec.error = nil + pos = target - skip + end + + function dec.position(_self) +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 +end +__FILES["codecs/audio/Tracker"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it, and the loaders +-- that map other trackers onto those four effect families (music/mtm, 669, stm, ult, okt, med, ptm, far; helpers in +-- codecs/audio/Tracker/Load). The 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("rosetta.codecs.audio.Tracker") +-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder +-- local seconds = Tracker.duration(module) -- one pass, song loops detected +-- +-- Module (Types.Module plus the engine fields; pattern / instrument / sample numbers are as in the file): +-- format the file format ("mod", "s3m", "xm", "it", "mtm", "669", ...): what the module was read from +-- engine "mod" | "s3m" | "xm" | "it": the effect family the engine plays (default: format, so the four +-- families need no engine field). Other formats map their effects onto one family (music/mtm: "xm", +-- music/669: "s3m", ...) and set the quirks they need in flags. +-- preamp optional 0..256: the output gain as OpenMPT's sample pre-amp (gain = preamp / 128); default per family +-- title, channels, speed (ticks per row), tempo (BPM: a tick lasts 2.5 / tempo s) +-- globalVolume 0..128 (S3M / XM 0..64 are stored doubled), mixVolume 0..128 (IT mix volume, S3M master volume) +-- order { pattern number (0-based) | 254 skip ("+++") | 255 end ("---") }, restart (0-based order index) +-- linear linear frequency slides (XM / IT flag) or Amiga periods +-- instrumentMode XM, IT with instruments: notes go through Instrument keymaps; otherwise the instrument column +-- is a sample number (MOD, S3M, IT sample mode) +-- flags { oldEffects, compatGxx (IT), fastSlides (ST3.00 volume slides: also on tick 0; any family), +-- amigaLimits (MOD), and the quirks of the other formats (any family): +-- periods = "amiga" (ProTracker period table + PAL clock, as MOD) | "hz" (periods are frequencies in +-- Hz: 669, FAR; slides move hzSlide Hz per unit, tone portamento hzSlide * hzTonePorta), +-- fastPortas (slides on tick 0 too), autoTonePorta (a tone portamento keeps running on later rows), +-- autoReset (669: any effect stops the auto slides), st2Tempo (S3M family A: Scream Tracker 2 tempo), +-- oktSlides (Oktalyzer note slides), panLaw = "ft2" (square-root panning, OpenMPT's FT2 mix levels), +-- envRowHold (MED: envelopes do not advance on a row's first tick) } +-- channelPan { 0..256 per channel (128 centre; 512 = surround); MOD: 64 / 192 (Amiga L R R L at half width, +-- as OpenMPT plays it; set 0 / 256 or render with stereoSeparation = 200 for hard panning) }, channelVolume { 0..64 }, channelMute { bool } +-- patterns { Pattern } (pattern n at patterns[n + 1]); Pattern = { rows, data }: data holds rows * channels +-- cells of 5 bytes: note, instrument, volume column, effect, parameter. Notes: 0 none, 1..120 (1 = +-- C-0; C-4 = 49 plays an XM / MOD sample at its base rate, C-5 = 61 an S3M / IT sample at its C5 +-- speed), 253 note fade, 254 note cut, 255 key off. The volume column and effects are kept in the +-- file's own coding: MOD / XM effects 0..35 (XM letters G.. = 16..), XM volume byte as stored; +-- S3M / IT effects 1..26 (A = 1), S3M volume 0 = none else volume + 1, IT volume byte + 1 +-- (0 = none). Engine extension effects (any family, for the other formats): Tracker.EXT (0x40 note +-- slide up, 0x41 down, 0x42 / 0x43 the same with retrigger: param = ticks per step << 4 | semitones; +-- 0x44 / 0x45 auto portamento up / down (669: every tick until another effect), 0x46 frequency +-- adjust (+ param * 80 Hz, 669), 0x47 / 0x48 / 0x49 tempo 256 / 512 / 768 + param (MED)). +-- Tracker.cell / Tracker.setCell read and write cells. +-- samples { Sample }: { name, data (f32, interleaved when stereo), length (frames), channels, bits (8 | 16, +-- for writers), loopStart, loopEnd (frames, end exclusive), loopType (0 none, 1 forward, 2 ping-pong), +-- susStart, susEnd, susType (IT sustain loop), volume 0..64, globalVolume 0..64, pan (0..256 or nil), +-- c5speed (S3M / IT), relativeNote, finetune -128..127 (MOD / XM), vibType / vibSweep / vibDepth / +-- vibRate (IT auto-vibrato) } +-- instruments { Instrument }: { name, sampleMap = { [note] = sample number }, noteMap = { [note] = note }, +-- volEnv / panEnv / pitchEnv (Envelope?), fadeout (as stored: XM 0..4095, IT 0..1024), nna (0 cut, +-- 1 continue, 2 note off, 3 fade), dct (0 off, 1 note, 2 sample, 3 instrument), dca (0 cut, 1 off, +-- 2 fade), globalVolume 0..128, pan (0..256 or nil), pps, ppc (pitch-pan separation / centre), +-- cutoff, resonance (0..127 or nil), vibType / vibSweep / vibDepth / vibRate (XM auto-vibrato) } +-- Envelope { enabled, ticks = { tick }, values = { volume 0..64 | pan / pitch -32..32 }, loop, loopStart, +-- loopEnd, sustain, susStart, susEnd (1-based point indexes), filter (IT pitch envelope as filter) } +-- +-- Pitch: two period spaces. Linear: P = (ref - note) * 64 - transpose (64 per semitone), frequency = base * 2^(-P/768). +-- Amiga: P = 1712 * 8363 / base * 2^(Plinear / 768), frequency = 8363 * 1712 / P (FT2 / ST3 period units; slides add +-- 4 per effect unit in both). MOD / XM: base 8363, ref 49, transpose = relativeNote * 64 + finetune / 2; S3M / IT: +-- base = c5speed, ref 61. +-- +-- Not supported: MIDI macros other than IT's default filter macros (Z00..Z8F), glissando, ST3 / IT finetune effects +-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation. +local Err = __include("core/Err") +local Types = __include("Types") +local Player = __include("codecs/audio/Tracker/Player") +local Mixer = __include("codecs/audio/Tracker/Mixer") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Tracker = {} + +Tracker.Pcm = Pcm +Tracker.Tables = Tables + + + + + + + + + + + + + + + + + + + + + + + + + + +local CELL = 5 + +-- engine extension effects (see the Module notes above) +Tracker.EXT = Player.EXT + +-- st2Tempo(byte) -> speed, tempo (BPM): a Scream Tracker 2 tempo byte +Tracker.st2Tempo = Tables.st2Tempo + +local FAMILIES = { mod = true, s3m = true, xm = true, it = true } + +-- family(module) -> "mod" | "s3m" | "xm" | "it" | nil: the effect family a module plays as +function Tracker.family(m) +local f = m.engine or m.format + return (type(f) == "string" and FAMILIES[f] and{f }or{nil +})[1]end + +-- ------------------------------------------------------------------------------------------------ constructors +-- newModule(format, channels, engine?) -> an empty Module (no patterns / samples) with the defaults of the effect family +-- (engine, default format) +function Tracker.newModule(format, channels, engine) +local fam = engine or format + local m = { + kind = "music", + format = format, + engine = engine, + title = "", + channels = channels, + speed = 6, + tempo = 125, + globalVolume = 128, + mixVolume = 48, + order = {}, + restart = 0, + linear = fam == "xm" or fam == "it", + instrumentMode = fam == "xm" or fam == "it", + flags = {}, + channelPan = {}, + channelVolume = {}, + channelMute = {}, + patterns = {}, + instruments = {}, + samples = {}, + meta = {}, + render = Tracker.renderMethod, + } + for i = 1, channels do + m.channelVolume[i] = 64 + if fam == "mod" then + local k = (i - 1) % 4 + m.channelPan[i] = (k == 0 or k == 3 )and 64 or 192 -- the Amiga's L R R L, at OpenMPT's default width + else + m.channelPan[i] = 128 + end + end + return m +end + +-- newPattern(rows, channels) -> an empty Pattern +function Tracker.newPattern(rows, channels) +return { rows = rows, data = buffer.create(rows * channels * CELL) } +end + +-- newSample() -> an empty Sample +function Tracker.newSample(name) +return { + name = name or "", + data = buffer.create(0), + length = 0, + channels = 1, + bits = 8, + loopStart = 0, + loopEnd = 0, + loopType = 0, + susStart = 0, + susEnd = 0, + susType = 0, + volume = 64, + globalVolume = 64, + pan = nil , + c5speed = 8363, + relativeNote = 0, + finetune = 0, + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +function Tracker.newEnvelope() +return { enabled = false, ticks = {}, values = {}, loop = false, loopStart = 1, loopEnd = 1, sustain = false, susStart = 1, susEnd = 1 } +end + +-- newInstrument() -> an Instrument mapping every note to sample 0 (none) +function Tracker.newInstrument(name) +local sm, nm = table.create(120, 0), table.create(120, 0) + for i = 1, 120 do + nm[i] = i + end + return { + name = name or "", + sampleMap = sm, + noteMap = nm, + volEnv = nil , + panEnv = nil , + pitchEnv = nil , + fadeout = 0, + nna = 0, + dct = 0, + dca = 0, + globalVolume = 128, + pan = nil , + pps = 0, + ppc = 60, + cutoff = nil , + resonance = nil , + vibType = 0, + vibSweep = 0, + vibDepth = 0, + vibRate = 0, + } +end + +-- cell(module, pattern, row, channel) -> note, instrument, volume, effect, parameter (pattern 0-based, row 0-based, +-- channel 1-based); nil when out of range +function Tracker.cell(m, pattern, row, channel) +local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return nil, 0, 0, 0, 0 + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + return buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) +end + +-- setCell(module, pattern, row, channel, note, instrument, volume, effect, parameter) -> true | false (out of range) +function Tracker.setCell(m, pattern, row, channel, note, ins, vol, fx, param) +local p = m.patterns[pattern + 1] + if not p or row < 0 or row >= p.rows or channel < 1 or channel > m.channels then + return false + end + local o = (row * m.channels + channel - 1) * CELL + local d = p.data + buffer.writeu8(d, o, note % 256) + buffer.writeu8(d, o + 1, ins % 256) + buffer.writeu8(d, o + 2, vol % 256) + buffer.writeu8(d, o + 3, fx % 256) + buffer.writeu8(d, o + 4, param % 256) + return true +end + +-- ------------------------------------------------------------------------------------------------ validation +local function num(v, lo, hi) +return type(v) == "number" and v == v and v >= lo and v <= hi +end + +local function fixEnvelope(e) +if e == nil then + return nil + end + if type(e) ~= "table" or type(e.ticks) ~= "table" or type(e.values) ~= "table" then + return nil, "bad envelope" + end + local n = math.min(#e.ticks, #e.values) + local last = -1 + for i = 1, n do + local t, v = e.ticks[i], e.values[i] + if not num(t, 0, 1e6) or not num(v, -64, 64) or t <= last then + -- points must go forward: keep the valid prefix + n = i - 1 + break + end + last = t + end + for i = #e.ticks, n + 1, -1 do + e.ticks[i] = nil + end + for i = #e.values, n + 1, -1 do + e.values[i] = nil + end + if n == 0 then + e.enabled = false + end + local function idx(v) +return (num(v, 1, math.max(1, n)) and{(math.floor(v) )}or{1 +})[1] end + e.loopStart, e.loopEnd = idx(e.loopStart), idx(e.loopEnd) + e.susStart, e.susEnd = idx(e.susStart), idx(e.susEnd) + if e.loopEnd < e.loopStart then + e.loop = false + end + if e.susEnd < e.susStart then + e.sustain = false + end + return e +end + +local function fixLoop(s0, e0, t0, len) +if not num(t0, 0, 2) or t0 == 0 or not num(s0, -2 ^ 52, 2 ^ 52) or not num(e0, -2 ^ 52, 2 ^ 52) then + return 0, 0, 0 + end + local s= math.floor(math.clamp(s0, 0, len)) + local e= math.floor(math.clamp(e0, 0, len)) + local t= math.floor(t0) + if e - s < 1 or t == 0 then + return 0, 0, 0 + end + if t == 2 and e - s < 2 then + t = 1 + end + return s, e, t +end + +-- validate(module) -> true | nil, Err: checks the structure the engine relies on, clamps loops, envelopes and +-- numbers into range (in place) +function Tracker.validate(m) +if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "not a module") + end + if not Tracker.family(m) then + return nil, Err.new(Err.ARG, "unknown tracker format " .. tostring(m.engine or m.format)) + end + if m.preamp ~= nil and not num(m.preamp, 0, 256) then + m.preamp = nil + end + if not num(m.channels, 1, 128) or m.channels % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad channel count") + end + if type(m.order) ~= "table" or type(m.patterns) ~= "table" or type(m.samples) ~= "table" then + return nil, Err.new(Err.ARG, "module without order / patterns / samples") + end + m.instruments = (type(m.instruments) == "table" and{m.instruments }or{{} +})[1] m.flags = (type(m.flags) == "table" and{m.flags }or{{} +})[1] m.channelPan = (type(m.channelPan) == "table" and{m.channelPan }or{{} +})[1] m.channelVolume = (type(m.channelVolume) == "table" and{m.channelVolume }or{{} +})[1] m.channelMute = (type(m.channelMute) == "table" and{m.channelMute }or{{} +})[1] for i = 1, m.channels do + local p = m.channelPan[i] + if p ~= 512 and not num(p, 0, 256) then + m.channelPan[i] = 128 + end + if not num(m.channelVolume[i], 0, 64) then + m.channelVolume[i] = 64 + end + end + m.speed = (num(m.speed, 1, 255) and{(math.floor(m.speed) )}or{6 +})[1] m.tempo = (num(m.tempo, 1, 1000) and{m.tempo }or{125 +})[1] m.globalVolume = (num(m.globalVolume, 0, 128) and{m.globalVolume }or{128 +})[1] m.mixVolume = (num(m.mixVolume, 0, 256) and{m.mixVolume }or{48 +})[1] m.restart = (num(m.restart, 0, 1e6) and{(math.floor(m.restart) )}or{0 +})[1] for i, o in __iter(m.order) do + if not num(o, 0, 255) then + return nil, Err.new(Err.ARG, "bad order entry " .. i) + end + end + for i, p in __iter(m.patterns) do + if type(p) ~= "table" or not num(p.rows, 1, 1024) or type(p.data) ~= "buffer" or buffer.len(p.data) < p.rows * m.channels * CELL then + return nil, Err.new(Err.ARG, "bad pattern " .. (i - 1)) + end + end + for i, s in __iter(m.samples) do + if type(s) ~= "table" then + return nil, Err.new(Err.ARG, "bad sample " .. i) + end + local nch = s.channels == 2 and 2 or 1 + s.channels = nch + if not num(s.length, 0, 2 ^ 31) or type(s.data) ~= "buffer" or buffer.len(s.data) < math.floor(s.length) * nch * 4 then + return nil, Err.new(Err.ARG, "sample " .. i .. ": data shorter than its length") + end + s.length = math.floor(s.length) + s.loopStart, s.loopEnd, s.loopType = fixLoop(s.loopStart or 0, s.loopEnd or 0, s.loopType or 0, s.length) + s.susStart, s.susEnd, s.susType = fixLoop(s.susStart or 0, s.susEnd or 0, s.susType or 0, s.length) + s.volume = (num(s.volume, 0, 64) and{s.volume }or{64 +})[1] s.globalVolume = (num(s.globalVolume, 0, 64) and{s.globalVolume }or{64 +})[1] if s.pan ~= nil and not num(s.pan, 0, 256) then + s.pan = nil + end + s.c5speed = (num(s.c5speed, 1, 1e7) and{s.c5speed }or{8363 +})[1] s.relativeNote = (num(s.relativeNote, -128, 127) and{s.relativeNote }or{0 +})[1] s.finetune = (num(s.finetune, -128, 127) and{s.finetune }or{0 +})[1] end + for i, ins in __iter(m.instruments) do + if type(ins) ~= "table" or type(ins.sampleMap) ~= "table" or type(ins.noteMap) ~= "table" then + return nil, Err.new(Err.ARG, "bad instrument " .. i) + end + for n = 1, 120 do + if not num(ins.sampleMap[n], 0, 1e6) then + ins.sampleMap[n] = 0 + end + if not num(ins.noteMap[n], 1, 120) then + ins.noteMap[n] = n + end + end + local err + ins.volEnv, err = fixEnvelope(ins.volEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.panEnv, err = fixEnvelope(ins.panEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.pitchEnv, err = fixEnvelope(ins.pitchEnv) + if err then + return nil, Err.new(Err.ARG, "instrument " .. i .. ": " .. err) + end + ins.fadeout = (num(ins.fadeout, 0, 65535) and{ins.fadeout }or{0 +})[1] ins.globalVolume = (num(ins.globalVolume, 0, 128) and{ins.globalVolume }or{128 +})[1] if ins.pan ~= nil and not num(ins.pan, 0, 256) then + ins.pan = nil + end + if ins.cutoff ~= nil and not num(ins.cutoff, 0, 127) then + ins.cutoff = nil + end + if ins.resonance ~= nil and not num(ins.resonance, 0, 127) then + ins.resonance = nil + end + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ rendering +local Decoder = {} +Decoder.__index = Decoder + +-- duration(module, opts?) -> seconds of one pass (song loops and the end of the order list detected), or nil, Err +function Tracker.duration(m, opts) +local ok, err = Tracker.validate(m) + if not ok then + return nil, err + end + local sr = opts and opts.sampleRate or 44100 + local maxFrames = (opts and opts.maxDuration or 3600) * sr + local st = Player.new(m, sr, { stereoSeparation = 100 }) + local frames = 0 + while frames < maxFrames do + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + frames =frames+ f + end + return math.min(frames, maxFrames) / sr, nil +end + +local function newPlayer(self) + self.st = Player.new(self.module, self.sampleRate, self.opts) + self.st.ramp = math.max(1, math.floor(self.sampleRate * 0.0015)) + self.left = 0 + self.pos = 0 +end + +-- render(module, opts?) -> Types.Decoder (stereo f32) | nil, Err +function Tracker.render(m, opts) +local o= opts or {} + local sr = o.sampleRate or 44100 + if type(sr) ~= "number" or sr < 1000 or sr > 384000 then + return nil, Err.new(Err.ARG, "sampleRate must be 1000..384000") + end + local seconds, err = Tracker.duration(m, o) + if not seconds then + return nil, err + end + local frames = math.floor(seconds * sr + 0.5) + local self = setmetatable({ + sampleRate = sr, + channels = 2, + frames = frames, + duration = frames / sr, + bitrate = 0, + tags = { title = m.title or "" }, + module = m, + opts = o, + linear = o.interpolation ~= "none", + maxFrames = (o.maxDuration or 3600) * sr, + st = nil , + left = 0, + pos = 0, + }, Decoder) + newPlayer(self) + return self , nil +end + +-- the Module method: module:render(opts) +function Tracker.renderMethod(self, opts) +local dec = Tracker.render(self, opts) + return dec +end + +-- run(self, out?, n) -> frames produced (out nil: advance without mixing) +local function run(self, out, n) +local st = self.st + local done = 0 + while done < n do +local __DARKLUA_CONTINUE_13=false repeat if self.left <= 0 then + if self.pos + done >= self.maxFrames then + break + end + local f = Player.tick(st) + if f == 0 and st.ended then + break + end + self.left = f + if f == 0 then +__DARKLUA_CONTINUE_13=true break + end + end + local k = math.min(self.left, n - done) + Mixer.mix(st, out, done, k, self.linear) + self.left =self.left- k + done =done+ k +__DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end + self.pos =self.pos+ done + return done +end + +-- read(n, out?) -> interleaved stereo f32 buffer, frames read (0 at the end) +function Decoder.read(self, n, out) +n = math.max(0, math.floor(tonumber(n) or 0)) + local o = out + if o == nil or buffer.len(o) < n * 8 then + o = buffer.create(n * 8) + else + buffer.fill(o, 0, 0, n * 8) + end + local got = run(self, o, n) + return o , got +end + +-- seek(seconds): replays the song silently up to the position (sample positions included) +function Decoder.seek(self, seconds) + local target = math.max(0, math.floor((tonumber(seconds) or 0) * self.sampleRate)) + newPlayer(self) + local chunk = 65536 + while self.pos < target do + local got = run(self, nil, math.min(chunk, target - self.pos)) + if got == 0 then + break + end + end + -- the gains ramp in from silence after a seek + for _, v in __iter(self.st.voices) do + v.gl, v.gr = 0, 0 + end +end + +function Decoder.position(self) +return self.pos / self.sampleRate +end + +return Tracker +end +__FILES["codecs/audio/Tracker/Load"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/audio/Tracker/Load: helpers shared by the tracker loaders that map another format's effects onto one of the +-- engine's families (music/mtm, 669, stm, ult, okt, med, ptm, far). Effects are first named the way OpenMPT's loaders +-- name them ("portaup", "volslide", "modex", ...), then written in the family's own cell coding: S3M / IT letter +-- codes (A = 1) with the IT volume column, or MOD / XM numbers. Ported from OpenMPT's ModCommand helpers +-- (ConvertModCommand, ConvertToVolCommand, FillInTwoCommands, GetEffectWeight, CPattern::WriteEffect; BSD licence, +-- licenses/openmpt-LICENSE.txt), reduced to what the engine plays. +local Err = __include("core/Err") +local Player = __include("codecs/audio/Tracker/Player") +local Pcm = __include("codecs/audio/Tracker/Pcm") +local Tables = __include("codecs/audio/Tracker/Tables") + +local Load = {} + +local EXT = Player.EXT + +-- the S3M / IT letter code of each effect name (engine extension effects included) +local IT= { + speed = 1, + jump = 2, + ["break"] = 3, + volslide = 4, + portadown = 5, + portaup = 6, + toneporta = 7, + vibrato = 8, + tremor = 9, + arpeggio = 10, + vibratovol = 11, + toneportavol = 12, + chanvol = 13, + chanvolslide = 14, + offset = 15, + panslide = 16, + retrig = 17, + tremolo = 18, + s3mex = 19, + tempo = 20, + finevibrato = 21, + globalvol = 22, + globalvolslide = 23, + panning8 = 24, + panbrello = 25, + noteslideup = EXT.NOTE_SLIDE_UP, + noteslidedown = EXT.NOTE_SLIDE_DOWN, + noteslideupretrig = EXT.NOTE_SLIDE_UP_RETRIG, + noteslidedownretrig = EXT.NOTE_SLIDE_DOWN_RETRIG, + autoportaup = EXT.AUTO_PORTA_UP, + autoportadown = EXT.AUTO_PORTA_DOWN, + freqadjust = EXT.FREQ_ADJUST, +} +Load.IT = IT + +-- OpenMPT's effect weights (low to high): which of two effects a cell keeps when only one fits +local WEIGHT= {} +for i, n in + __iter({ + "none", "keyoff", "tremolo", "finevibrato", "vibrato", "panbrello", "s3mex", "modex", "panslide", "panning8", + "noteslideupretrig", "noteslideup", "noteslidedownretrig", "noteslidedown", "portaup", "autoportaup", + "portadown", "autoportadown", "volslide", "vibratovol", "volume", "volume8", "offset", "tremor", "retrig", + "arpeggio", "toneporta", "toneportavol", "chanvolslide", "chanvol", "globalvolslide", "globalvol", "tempo", + "speed", "jump", "break", + }) +do + WEIGHT[n] = i +end + +local GLOBAL = { jump = true, ["break"] = true, speed = true, tempo = true, globalvol = true, globalvolslide = true } + +-- isGlobal(name, param) -> the effect acts on the whole song (OpenMPT's IsGlobalCommand) +function Load.isGlobal(name, param) +if name == nil then + return false + end + if GLOBAL[name] then + return true + end + local x = math.floor(param / 16 +) if name == "modex" then + return x == 0 or x == 6 or x == 0xE + elseif name == "s3mex" then + return x == 6 or x == 0xB or x == 0xE + end + return false +end + +-- modCommand(cmd, param) -> name?, param: a MOD / XM effect number (0..F, XM letters 16..) by name (ConvertModCommand) +local MODFX= { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [5] = "toneportavol", + [6] = "vibratovol", [7] = "tremolo", [8] = "panning8", [9] = "offset", [10] = "volslide", [11] = "jump", + [12] = "volume", [13] = "break", [14] = "modex", [15] = "tempo", [16] = "globalvol", [17] = "globalvolslide", + [20] = "keyoff", [25] = "panslide", [27] = "retrig", [29] = "tremor", +} +function Load.modCommand(cmd, param) +if cmd == 0 and param == 0 then + return nil, 0 + elseif cmd == 0xF and param < 0x20 then + return "speed", param + end + local n = MODFX[cmd] + if n == "break" then + param = (math.floor(param / 16)) * 10 + param % 16 + end + return n, param +end + +-- itVolume(name, param, force) -> the IT volume-column byte + 1 (the engine's coding) for an effect that fits there, +-- or nil (OpenMPT's ConvertToVolCommand; force: fit it with some loss of precision) +function Load.itVolume(name, param, force) +if name == "volume" then + return math.min(param, 64) + 1 + elseif name == "volume8" then + if not force and param % 4 ~= 0 then + return nil + end + return math.floor((param + 3) / 4 )+ 1 + elseif name == "portaup" or name == "portadown" then + if not force and (param % 4 ~= 0 or param >= 0xE0) then + return nil + end + return (name == "portaup" and 115 or 105) + math.min(math.floor(param / 4), 9) + 1 + elseif name == "toneporta" then + if param >= 0xF0 then + return 193 + 9 + 1 + end + for n = 0, 9 do + local v = Tables.IT_VOLPORTA[n + 1] + if (force and param <= v) or param == v then + return 193 + n + 1 + end + end + return nil + elseif name == "vibrato" then + if force then + param = math.min(param % 16, 9) + elseif param % 16 > 9 or param >= 16 then + return nil + end + return 203 + param % 16 + 1 + elseif name == "panning8" then + return 128 + (param == 255 and 64 or math.floor(param / 4)) + 1 + elseif name == "volslide" then + local x, y = math.floor(param / 16), param % 16 + if param == 0 then + return nil + elseif y == 0 then + return 85 + math.min(x, 9) + 1 + elseif x == 0 then + return 95 + math.min(y, 9) + 1 + elseif y == 0xF then + return 65 + math.min(x, 9) + 1 + elseif x == 0xF then + return 75 + math.min(y, 9) + 1 + end + return nil + elseif name == "s3mex" and math.floor(param / 16 )== 8 then + return 128 + (param % 16) * 4 + 2 + 1 + end + return nil +end + +-- itEffect(name, param) -> effect code, param in S3M / IT coding (0, 0 for none or an effect the family lacks; MOD's +-- extended E commands become their S3M equivalents) +function Load.itEffect(name, param) +if name == nil then + return 0, 0 + end + if name == "modex" then + local x, y = math.floor(param / 16), param % 16 + if x == 1 then + return IT.portaup, 0xF0 + y + elseif x == 2 then + return IT.portadown, 0xF0 + y + elseif x == 9 then + return IT.retrig, y + elseif x == 0xA then + return IT.volslide, y * 16 + 0xF + elseif x == 0xB then + return IT.volslide, 0xF0 + y + end + local s = ({ [3] = 1, [4] = 3, [5] = 2, [6] = 0xB, [7] = 4, [8] = 8, [0xC] = 0xC, [0xD] = 0xD, [0xE] = 0xE })[x] + if s then + return IT.s3mex, s * 16 + y + end + return 0, 0 + end + local code = IT[name] + if code == nil then + return 0, 0 + end + return code, param +end + +-- fillTwo(name1, param1, name2, param2, lowResOffset?) -> volume byte (engine IT coding, 0 none), effect name, param, +-- lost name?, lost param: two effects of one cell into the IT volume column and the effect column, keeping the +-- heavier one when both cannot fit (OpenMPT's FillInTwoCommands) +function Load.fillTwo(e1, p1, e2, p2) +if e1 ~= nil and e1 == e2 then + e2 = nil -- the same effect twice: keep one (most are absolute; slides are kept once too, a simplification) + end + for n = 0, 3 do + local v = Load.itVolume(e1, p1, n > 1) + if e1 == nil or v then + if v == nil and (e2 == "volume" or e2 == "volume8") then + -- the engine's IT family sets volumes in the volume column only + return Load.itVolume(e2, p2, true) or 0, nil, 0, nil, 0 + end + return v or 0, e2, p2, nil, 0 + end + e1, p1, e2, p2 = e2, p2, e1, p1 + end + if (WEIGHT[e1 ] or 0) > (WEIGHT[e2 ] or 0) then + e1, p1, e2, p2 = e2, p2, e1, p1 + end + return 0, e2, p2, e1, p1 +end + +-- writeEffect(m, pattern (0-based), row, fx, param, retry?, channel?, multiple?) -> true when written: puts an effect +-- into a free effect slot of the row (any channel, or the given 1-based one); none free: the next row (retry "next") or +-- the previous one ("prev"). The same effect already on the row counts as written unless multiple (OpenMPT's +-- CPattern::WriteEffect). +function Load.writeEffect(m, pattern, row, fx, param, retry, channel, multiple) +local p = m.patterns[pattern + 1] + if not p then + return false + end + local fam = m.engine or m.format + local modLike = fam == "mod" or fam == "xm" + local nch = m.channels + local d = p.data + local guard = 0 + while row >= 0 and row < p.rows and guard < 1024 do + guard =guard+ 1 + local c0, c1 = 1, nch + if channel then + c0, c1 = channel, channel + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + if not multiple and buffer.readu8(d, o + 3) == fx and (fx ~= 0 or not modLike) then + return true + end + end + for c = c0, c1 do + local o = (row * nch + c - 1) * 5 + local f, q = buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if f == 0 and (not modLike or q == 0) then + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + return true + end + end + if retry == "next" then + row =row+ 1 + elseif retry == "prev" then + row =row- 1 + else + return false + end + end + return false +end + +-- readSample(buf, offset, frames, spec, sample, budget) -> true | nil, Err: decodes raw PCM (codecs/audio/Tracker/Pcm +-- spec) at the absolute buffer offset into the sample (data, length, bits, channels). A short file keeps the frames +-- that are there (end = the buffer's length, or spec.limit). budget = { left = f32 bytes still allowed } (maxBytes). +function Load.readSample(buf, offset, frames, spec, s, budget) +local nch = spec.channels or 1 + local bps = math.floor(spec.bits / 8 +) local limit = math.min(spec.limit or buffer.len(buf), buffer.len(buf)) + local avail = math.floor(math.max(0, limit - offset) / (nch * bps) +) local n = math.max(0, math.min(math.floor(frames), avail)) + budget.left =budget.left- n * nch * 4 + if budget.left < 0 then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, offset, n, spec) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", offset) + end + s.data, s.length, s.bits, s.channels = data, n, spec.bits, nch + return true, nil +end + +-- bcd(n) -> n as the two decimal digits S3M / MOD pattern breaks store (0..99) +function Load.bcd(n) +n = math.clamp(math.floor(n), 0, 99) + return (math.floor(n / 10)) * 16 + n % 10 +end + +return Load +end +__FILES["codecs/audio/Tracker/Mixer"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +-- 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/audio/Tracker) +-- validates the sample buffers' sizes. +local floor, ceil, min = math.floor, math.ceil, math.min +local readf32, writef32 = buffer.readf32, buffer.writef32 + +local Mixer = {} + +-- mixVoice(v, out?, off, n, linear, ramp): n frames of voice v added at frame off of out (nil: only advance) +local function mixVoice(v, out, off, n, linear, ramp) + local data= v.data + local nch = v.nch + local inc = v.inc + if not (inc > 0 and inc < 1e6) then + return + end + local len = v.len + local hi = len - 1 + local i = 0 + local guard = 0 + while i < n do +local __DARKLUA_CONTINUE_1=false repeat guard =guard+ 1 + if guard > n + 64 then + return + end + local s, e, t + if v.keyOn and v.susT > 0 then + s, e, t = v.susS, v.susE, v.susT + elseif v.loopT > 0 then + s, e, t = v.loopS, v.loopE, v.loopT + else + s, e, t = 0, len, 0 + end + local p = v.p + local dir = v.dir + local count + if dir > 0 then + local lim = (t == 2 and((e - 1 ))or(e +)) if p >= lim then + if t == 0 then + v.active = false + return + elseif t == 1 then + p = s + (p - e) % (e - s) + else + p = 2 * (e - 1) - p + if p < s then + p = s + end + v.dir = -1 + end + v.p = p +__DARKLUA_CONTINUE_1=true break + end + count = ceil((lim - p) / inc) + else + if p < s then + p = 2 * s - p + if p > e - 1 then + p = e - 1 + end + v.p = p + v.dir = 1 +__DARKLUA_CONTINUE_1=true break + end + count = floor((p - s) / inc) + 1 + end + if count < 1 then + count = 1 + end + local m = min(n - i, count) + local step = inc * dir + if out == nil then + v.p = p + step * m + i =i+ m +__DARKLUA_CONTINUE_1=true break + end + local wrapJ = (t == 1 and{s }or{(e - 1 +)})[1] local gl, gr = v.gl, v.gr + local rl = v.rampN + local dl, dr = 0, 0 + local tl, tr = v.tl, v.tr + if rl > 0 then + dl, dr = (tl - gl) / rl, (tr - gr) / rl + end + local fOn = v.fOn + local fa, fb0, fb1 = v.fa, v.fb0, v.fb1 + local y1l, y2l, y1r, y2r = v.y1l, v.y2l, v.y1r, v.y2r + local o = (off + i) * 8 + for _ = 1, m do + local idx = floor(p) + if idx > hi then + idx = hi + elseif idx < 0 then + idx = 0 + end + local j = idx + 1 + if j >= e then + j = wrapJ + end + if j > hi then + j = hi + end + local xl, xr + if nch == 1 then + local a = readf32(data, idx * 4) + if linear then + local b = readf32(data, j * 4) + xl = a + (b - a) * (p - idx) + else + xl = a + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + end + xr = xl + else + local al = readf32(data, idx * 8) + local ar = readf32(data, idx * 8 + 4) + if linear then + local f = p - idx + xl = al + (readf32(data, j * 8) - al) * f + xr = ar + (readf32(data, j * 8 + 4) - ar) * f + else + xl, xr = al, ar + end + if fOn then + local y = xl * fa + y1l * fb0 + y2l * fb1 + y2l, y1l = y1l, y + xl = y + y = xr * fa + y1r * fb0 + y2r * fb1 + y2r, y1r = y1r, y + xr = y + end + end + if rl > 0 then + gl =gl+ dl + gr =gr+ dr + rl =rl- 1 + if rl == 0 then + gl, gr = tl, tr + end + end + writef32(out, o, readf32(out, o) + xl * gl) + writef32(out, o + 4, readf32(out, o + 4) + xr * gr) + o =o+ 8 + p =p+ step + end + v.p = p + v.gl, v.gr, v.rampN = gl, gr, rl + v.y1l, v.y2l, v.y1r, v.y2r = y1l, y2l, y1r, y2r + i =i+ m +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + local _ = ramp +end + +-- mix(st, out?, off, n, linear): every active voice of player st; out nil only advances the sample positions +function Mixer.mix(st, out, off, n, linear) + for _, v in __iter(st.voices) do + if v.active and v.data then + mixVoice(v, out, off, n, linear, 0) + end + end +end + +return Mixer +end +__FILES["codecs/audio/Tracker/Pcm"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- 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). +local readu8, readi8, readu16, readi16 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16 +local writef32, readf32, writeu8, writei16 = buffer.writef32, buffer.readf32, buffer.writeu8, buffer.writei16 +local floor = math.floor + +local Pcm = {} + +-- bytes(frames, spec) -> the size of the raw data + + + + + + + + + +function Pcm.bytes(frames, spec) +return frames * (spec.channels or 1) * (math.floor(spec.bits / 8)) +end + +-- decode(buf, off, frames, spec) -> f32 buffer (frames * channels, interleaved) | nil when the source is too short +function Pcm.decode(buf, off, frames, spec) +local nch = spec.channels or 1 + local bps = math.floor(spec.bits / 8 +) local total = frames * nch + if frames < 0 or off < 0 or off + total * bps > buffer.len(buf) then + return nil + end + local out = buffer.create(total * 4) + local planar = spec.planar and nch == 2 + for c = 0, nch - 1 do + local acc = 0 + for i = 0, frames - 1 do + local k = (planar and((c * frames + i ))or((i * nch + c +))) local v + if bps == 1 then + if spec.signed then + v = readi8(buf, off + k) + else + v = readu8(buf, off + k) - 128 + end + if spec.delta then + acc = (acc + v + 128) % 256 - 128 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 128) + else + local p = off + k * 2 + if spec.bigEndian then + v = readu8(buf, p) * 256 + readu8(buf, p + 1) + if spec.signed and v >= 32768 then + v =v- 65536 + end + elseif spec.signed then + v = readi16(buf, p) + else + v = readu16(buf, p) + end + if not spec.signed then + v =v- 32768 + end + if spec.delta then + acc = (acc + v + 32768) % 65536 - 32768 + v = acc + end + writef32(out, (i * nch + c) * 4, v / 32768) + end + end + end + return out +end + +-- encode(samples, frames, spec) -> raw PCM (signed or unsigned, optional delta, interleaved or planar) +function Pcm.encode(samples, frames, spec) +local nch = spec.channels or 1 + local bps = math.floor(spec.bits / 8 +) local out = buffer.create(frames * nch * bps) + local planar = spec.planar and nch == 2 + local avail = math.floor(buffer.len(samples) / 4 +) for c = 0, nch - 1 do + local prev = 0 + for i = 0, frames - 1 do + local si = i * nch + c + local x = (si < avail and{(readf32(samples, si * 4) )}or{0 +})[1] local k = (planar and((c * frames + i ))or((i * nch + c +))) if bps == 1 then + local v = math.clamp(floor(x * 128 + 0.5), -128, 127) + local w = v + if spec.delta then + w = (v - prev) % 256 + prev = v + else + w = (spec.signed and((v % 256 ))or((v + 128 +))) end + writeu8(out, k, w) + else + local v = math.clamp(floor(x * 32768 + 0.5), -32768, 32767) + local w = v + if spec.delta then + w = (v - prev + 32768) % 65536 - 32768 + prev = v + elseif not spec.signed then + w = v + 32768 + if w >= 32768 then + w =w- 65536 + end + end + writei16(out, k * 2, w) + end + end + end + return out +end + +-- bits(samples) -> 8 when every value is exactly representable in 8 bits (data loaded from 8-bit), else 16 +function Pcm.bitsNeeded(samples) +for i = 0, math.floor(buffer.len(samples) / 4 )- 1 do + local x = readf32(samples, i * 4) * 128 + if x ~= floor(x) then + return 16 + end + end + return 8 +end + +return Pcm +end +__FILES["codecs/audio/Tracker/Player"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +-- 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/audio/Tracker/Mixer. +-- +-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is +-- guarded. +local Tables = __include("codecs/audio/Tracker/Tables") + +local wave64, autoWave = Tables.wave64, Tables.autoWave +local AMIGA = Tables.AMIGA +local AMIGA_PAL = Tables.AMIGA_PAL +local floor, min, max, clamp, abs = math.floor, math.min, math.max, math.clamp, math.abs +local readu8 = buffer.readu8 + +local Player = {} + +local MOD, S3M, XM, IT = 1, 2, 3, 4 +Player.MOD, Player.S3M, Player.XM, Player.IT = MOD, S3M, XM, IT +local FAMILY = { mod = MOD, s3m = S3M, xm = XM, it = IT } + +-- engine extension effects: format-specific commands of the other tracker formats, in any family (see +-- codecs/audio/Tracker) +local EXT = { + NOTE_SLIDE_UP = 0x40, + NOTE_SLIDE_DOWN = 0x41, + NOTE_SLIDE_UP_RETRIG = 0x42, + NOTE_SLIDE_DOWN_RETRIG = 0x43, + AUTO_PORTA_UP = 0x44, + AUTO_PORTA_DOWN = 0x45, + FREQ_ADJUST = 0x46, + TEMPO_256 = 0x47, -- set the tempo to 256 + param (0x48: 512 + param, 0x49: 768 + param) +} +Player.EXT = EXT + +local BG_VOICES = 64 -- voices beyond one per channel, for IT new note actions + +-- ------------------------------------------------------------------------------------------------ state +local function newVoice() +return { + active = false, + chan = 0, + bg = false, + data = nil , + nch = 1, + len = 0, + loopS = 0, + loopE = 0, + loopT = 0, + susS = 0, + susE = 0, + susT = 0, + p = 0, + dir = 1, + inc = 0, + smp = nil , + smpIdx = 0, + ins = nil , + insIdx = 0, + note = 0, + vol = 0, + pan = 128, + chanVol = 64, + period = 0, + periodOut = 0, + base = 8363, + keyOn = true, + fading = false, + fade = 65536, + volEnvPos = 0, + panEnvPos = 0, + pitchEnvPos = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + envVol = 64, + envPan = 0, + envPitch = 0, + avPos = 0, + avAmp = 0, + gl = 0, + gr = 0, + tl = 0, + tr = 0, + started = false, + cutoff = 127, + reso = 0, + fOn = false, + fa = 1, + fb0 = 0, + fb1 = 0, + y1l = 0, + y2l = 0, + y1r = 0, + y2r = 0, + tremorMute = false, + surround = false, + rampN = 0, + owner = 0, -- the channel whose foreground voice this is (0: free or background) + order = 0, -- allocation age + } +end + +local function newChannel(i, pan, vol) +return { + idx = i, + voice = nil , + note = 0, + realNote = 0, + insIdx = 0, + smpIdx = 0, + smp = nil , + vol = 0, + pan = pan, + basePan = pan, + chanVol = vol, + period = 0, + target = 0, + portaSpeed = 0, + base = 8363, + finetune = nil , + fx = 0, + param = 0, + vcmd = 0, + -- memories + mPortaUp = 0, + mPortaDn = 0, + mFineUp = 0, + mFineDn = 0, + mXFineUp = 0, + mXFineDn = 0, + mVolSlide = 0, + mFineVolUp = 0, + mFineVolDn = 0, + mOffset = 0, + mHighOffset = 0, + mPanSlide = 0, + mGVolSlide = 0, + mRetrig = 0, + mTremor = 0, + mArp = 0, + mS3M = 0, + mEF = 0, + mChanVolSlide = 0, + mTempo = 0, + mVolCol = 0, + mS = 0, + vibSpeed = 0, + vibDepth = 0, + vibPos = 0, + vibWave = 0, + tremSpeed = 0, + tremDepth = 0, + tremPos = 0, + tremWave = 0, + panbSpeed = 0, + panbDepth = 0, + panbPos = 0, + panbWave = 0, + vibDelta = 0, + tremDelta = 0, + panbDelta = 0, + arp = 0, + loopRow = 0, + loopCount = 0, + retrigCount = 0, + tremorCount = 0, + tremorOn = true, + delayTick = -1, + dNote = 0, + dIns = 0, + dVol = 0, + cutTick = -1, + keyOffTick = -1, + nna = -1, + surround = false, + cutoff = 127, + reso = 0, + volEnvOn = true, + panEnvOn = true, + pitchEnvOn = true, + muted = false, + triggered = false, + autoPorta = 0, -- auto portamento (EXT 0x44 / 0x45): period units per tick, + down + autoTone = false, -- flags.autoTonePorta: the tone portamento keeps running + hzAdd = 0, -- EXT 0x46: Hz added to the frequency (669) + slideCount = 0, -- note slides: ticks to the next step + mNoteSlide = 0, + tonePortaRow = false, + } +end + +-- new(module, opts) -> player state (module validated by the caller) +function Player.new(m, sampleRate, opts) +local fmt = FAMILY[m.engine or m.format] or MOD + local flags = m.flags + local ptPeriods = fmt == MOD or flags.periods == "amiga" + local st= { + m = m, + fmt = fmt, + sr = sampleRate, + nch = m.channels, + speed = m.speed, + tempo = m.tempo, + gvol = m.globalVolume, + linear = m.linear, + insMode = m.instrumentMode and #m.instruments > 0, + oldFx = m.flags.oldEffects or false, + compatG = m.flags.compatGxx or false, + fastSlides = flags.fastSlides or false, + amigaLimits = flags.amigaLimits or false, + ptPeriods = ptPeriods, -- ProTracker periods (integer table periods, PAL clock) + hz = flags.periods == "hz", -- periods are frequencies in Hz + hzScale = (type(flags.hzSlide) == "number" and{flags.hzSlide }or{1})[1], + hzTone = (type(flags.hzTonePorta) == "number" and{flags.hzTonePorta }or{1})[1], + fastPortas = flags.fastPortas or false, + autoTonePorta = flags.autoTonePorta or false, + autoReset = flags.autoReset or false, + st2Tempo = flags.st2Tempo or false, + oktSlides = flags.oktSlides or false, + ft2Pan = flags.panLaw == "ft2", + envHold = flags.envRowHold or false, + ord = 0, + row = 0, + tick = 0, + pat = nil , + patIdx = -1, + patDelay = 0, + patDelayRep = 0, + fineDelay = 0, + jumpOrd = -1, + ft2BreakPos = 0, + breakRow = -1, + loopJump = -1, + ended = false, + visited = {} , + chans = {}, + voices = {}, + age = 0, + tickFrames = 0, + frac = 0, + separation = math.clamp((opts and opts.stereoSeparation or 100) / 100, 0, 2), + master = 1, + rows = 0, + ramp = 64, + amiga = (ptPeriods and{AMIGA_PAL }or{AMIGA})[1], + loopAllowed = opts and opts.loop or false, + } + for i = 1, m.channels do + local pan = m.channelPan[i] or 128 + local cv = m.channelVolume[i] or 64 + local c = newChannel(i, pan, cv) + c.basePan = pan + c.muted = m.channelMute[i] or false + if pan == 512 then -- surround marker + c.pan = 128 + c.surround = true + end + st.chans[i] = c + end + for i = 1, m.channels + BG_VOICES do + st.voices[i] = newVoice() + end + st.master = Player.masterGain(m, fmt) + Player.startOrder(st, 0, 0) + return st +end + +-- the output scale per format, calibrated against OpenMPT's default mix levels (tools/fixtures: a full-scale sine at +-- volume 64 on one centred channel) +function Player.masterGain(m, fmt) +if type(m.preamp) == "number" then + return m.preamp / 128 -- OpenMPT's sample pre-amp, as set by the format's loader + end + if fmt == IT or fmt == S3M then + return (m.mixVolume or 48) / 128 -- OpenMPT: linear in the mix / master volume, 64 = 0.5 + end + if fmt == XM then + return 0.375 -- OpenMPT's XM pre-amp (48 / 128), whatever the channel count + end + -- MOD: OpenMPT scales by the channel count (4 channels: 0.5; 2 / channels between 2 and 8) + return 2 / clamp(m.channels, 2, 8) +end + +-- ------------------------------------------------------------------------------------------------ orders and rows +-- startOrder(st, ord, row): resolve skip markers / the end of the order list; sets st.pat or st.ended +function Player.startOrder(st, ord, row) + local m = st.m + local order = m.order + local n = #order + local guard = 0 + local o = ord + while true do + guard =guard+ 1 + if guard > n + 2 then + st.ended = true + return + end + if o >= n then + o = m.restart or 0 + if o >= n or o < 0 then + o = 0 + end + if n == 0 then + st.ended = true + return + end + end + local p = order[o + 1] + if p == 255 then + o = n -- the end marker: wrap to the restart position + elseif p == 254 or m.patterns[p + 1] == nil then + o =o+ 1 + else + st.ord = o + st.patIdx = p + st.pat = m.patterns[p + 1] + st.row = (row < st.pat.rows and{row }or{0 +})[1] return + end + end +end + +local function advanceRow(st) + if st.stopAfterRow then + st.ended = true + return + end + local loopRow = st.loopJump + if st.jumpOrd >= 0 or st.breakRow >= 0 then + local o = (st.jumpOrd >= 0 and{st.jumpOrd }or{(st.ord + 1 +)})[1] local r = (st.breakRow >= 0 and{st.breakRow }or{0 +})[1] st.jumpOrd, st.breakRow, st.loopJump = -1, -1, -1 + st.ft2BreakPos = 0 + Player.startOrder(st, o, r) + return + end + if loopRow >= 0 then + st.loopJump = -1 + -- the rows inside a pattern loop are played again on purpose: forget them for the song-end check + for r = loopRow, st.row do + st.visited[st.ord * 1024 + r] = nil + end + st.row = loopRow + return + end + st.row =st.row+ 1 + if st.row >= st.pat.rows then + -- FT2 (XM): the next pattern starts at the row a pattern loop last jumped to (the E6x "bug" FT2 players keep) + local r = (st.fmt == XM and{st.ft2BreakPos }or{0 +})[1] st.ft2BreakPos = 0 + Player.startOrder(st, st.ord + 1, r) + end +end + +-- ------------------------------------------------------------------------------------------------ pitch +-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces) +local function notePeriod(st, note, smp, ft) +local base, ref, tr + if st.fmt == MOD or st.fmt == XM then + base, ref = 8363, 49 + tr = (smp.relativeNote or 0) * 64 + (ft or smp.finetune or 0) / 2 + else + base, ref, tr = smp.c5speed or 8363, 61, 0 + if base <= 0 then + base = 8363 + end + end + local plin = (ref - note) * 64 - tr + if st.hz then + -- periods are frequencies (Hz, rounded as OpenMPT does): the sample's rate at C-5 + return floor((smp.c5speed or 8363) * 2 ^ ((note - 61) / 12)), base + end + if st.ptPeriods then + -- ProTracker: integer periods from the finetune tables (finetune 0 table scaled by 2^(-ft / 96), rounded) + local ftp = (ft or smp.finetune or 0) / 16 + local n = note + (((st.fmt == MOD or st.fmt == XM )and{smp.relativeNote or 0 }or{0})[1]) + return 4 * floor(Tables.noteToPeriod(n) * 2 ^ (-ftp / 12 / 8) + 0.5), base + end + if st.linear then + return plin, base + end + return 1712 * 8363 / base * 2 ^ (plin / 768), base +end + +local function arpPeriod(st, period, semis) +if semis == 0 then + return period + end + if st.hz then + return period * 2 ^ (semis / 12) + end + if st.linear then + return period - semis * 64 + end + return period * 2 ^ (-semis / 12) +end + +local function clampPeriod(st, c) + if st.hz then + c.period = clamp(c.period, 1, 1e6) + elseif st.linear then + c.period = clamp(c.period, -6000, 6000) + elseif st.amigaLimits then + c.period = clamp(c.period, 113 * 4, 856 * 4) + else + c.period = clamp(c.period, 1, 1e6) + end +end + +-- slide(st, c, units): a pitch slide in period units (positive: down; 4 per effect unit); in Hz mode the frequency +-- moves units * hzSlide Hz the other way +local function slide(st, c, units) + if st.hz then + c.period =c.period- units * st.hzScale + else + c.period =c.period+ units + end + clampPeriod(st, c) +end + +-- ------------------------------------------------------------------------------------------------ voices +local function allocVoice(st) +local best, bestScore = nil, math.huge + for _, v in __iter(st.voices) do + if not v.active and v.owner == 0 then + return v + end + if v.bg then + local s = (v.vol * v.envVol * v.fade) / 1e9 + v.order * 1e-9 + if s < bestScore then + best, bestScore = v, s + end + end + end + if best then + best.active = false + return best + end + -- every voice is busy in the foreground (more channels than voices): reuse an inactive one anyway + for _, v in __iter(st.voices) do + if not v.active then + local c = st.chans[v.owner] + if c and c.voice == v then + c.voice = nil + end + return v + end + end + return st.voices[1] -- unreachable: there are more voices than channels +end + +local function keyOff(st, v) + if not v or not v.active then + return + end + v.keyOn = false + local ins = v.ins + if st.fmt == XM then + if not (ins and ins.volEnv and ins.volEnv.enabled) then + v.vol = 0 + local c = st.chans[v.chan] + if c and c.voice == v then + c.vol = 0 + end + else + v.fading = true + end + elseif st.fmt == IT then + if ins then + local env = ins.volEnv + if not (env and env.enabled and v.volEnvOn) or env.loop then + v.fading = true + end + end + end +end + +local function noteFade(v) + if v and v.active then + v.fading = true + end +end + +local function cutVoice(v) + if v then + v.active = false + end +end + +-- start(st, c, smp, smpIdx, ins, insIdx, note, period, base, offset): a fresh voice for channel c +local function startVoice(st, c, smp, smpIdx, ins, insIdx, note, period, base, keepEnv) + local v = c.voice + if v == nil or v.bg then + v = allocVoice(st) + c.voice = v + v.owner = c.idx + end + local wasActive = v.active + v.active = smp.length > 0 and smp.data ~= nil + v.chan = c.idx + v.bg = false + v.smp = smp + v.smpIdx = smpIdx + v.data = smp.data + v.nch = smp.channels or 1 + v.len = smp.length + v.loopS, v.loopE, v.loopT = smp.loopStart, smp.loopEnd, smp.loopType + v.susS, v.susE, v.susT = smp.susStart or 0, smp.susEnd or 0, smp.susType or 0 + v.p = 0 + v.dir = 1 + v.ins = ins + v.insIdx = insIdx + v.note = note + v.period = period + v.periodOut = period + v.base = base + st.age =st.age+ 1 + v.order = st.age + if keepEnv ~= true then + if keepEnv ~= "release" then + v.keyOn = true + v.fading = false + end + v.fade = 65536 + v.volEnvPos, v.panEnvPos, v.pitchEnvPos = 0, 0, 0 + v.avPos, v.avAmp = 0, 0 + v.envVol, v.envPan, v.envPitch = 64, 0, 0 + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + v.y1l, v.y2l, v.y1r, v.y2r = 0, 0, 0, 0 + end + if not wasActive then + v.gl, v.gr = 0, 0 + end + return v +end + +-- IT new note actions on the channel's current voice (and duplicate checks on all its voices) +local function newNoteAction(st, c, ins, insIdx, note, smpIdx) + -- duplicate check: voices of this channel playing the same instrument + if ins and ins.dct and ins.dct > 0 then + for _, u in __iter(st.voices) do + if u.active and u.chan == c.idx and u.insIdx == insIdx then + local dup = (ins.dct == 1 and u.note == note) or (ins.dct == 2 and u.smpIdx == smpIdx) or ins.dct == 3 + if dup then + local a = ins.dca or 0 + if a == 0 then + cutVoice(u) + elseif a == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + end + end + local v = c.voice + if v == nil or not v.active then + return + end + local nna = c.nna + if nna < 0 then + nna = (v.ins and{(v.ins.nna or 0) }or{0 +})[1] end + if nna == 0 then + -- cut: the voice is reused for the new note (a short click is avoided by its ramp from the old gains) + v.active = false + return + end + v.bg = true + v.owner = 0 + c.voice = nil + if nna == 2 then + keyOff(st, v) + elseif nna == 3 then + noteFade(v) + end +end + +-- ------------------------------------------------------------------------------------------------ triggering +local function isPorta(st, fx, vcmd) +local f = st.fmt + if f == MOD then + return fx == 3 or fx == 5 + elseif f == XM then + return fx == 3 or fx == 5 or (vcmd >= 0xF0) + end + -- S3M / IT: G (7) or L (12); IT volume column g (193..202, stored + 1) + return fx == 7 or fx == 12 or (f == IT and vcmd >= 194 and vcmd <= 203) +end + +-- the sample and real note for an instrument number + note +local function resolve(st, insIdx, note) +local m = st.m + if st.insMode then + local ins = m.instruments[insIdx] + if not ins or note < 1 or note > 120 then + return nil, 0, ins, note + end + local si = ins.sampleMap[note] or 0 + local rn = ins.noteMap[note] or note + local smp = m.samples[si] + return smp, si, ins, rn + end + local smp = m.samples[insIdx] + return smp, insIdx, nil, note +end + +local function setInstrumentDefaults(st, c, smp, ins) + if smp then + c.vol = smp.volume + end + if st.fmt == IT then + -- IT: a sample's or instrument's default panning holds for its notes; the channel panning (set by the + -- effects) comes back for the others + local p = (smp and smp.pan) or (ins and ins.pan) + c.pan = p or c.basePan + if p then + c.surround = false + end + elseif smp and smp.pan then + c.pan = smp.pan + c.basePan = c.pan + c.surround = false + end + if ins and st.fmt == IT then + if ins.cutoff then + c.cutoff = ins.cutoff + end + if ins.resonance then + c.reso = ins.resonance + end + end +end + +local function sampleOffset(st, c, v) + local f = st.fmt + local fx, param = c.fx, c.param + local off = -1 + if (f == MOD or f == XM) and fx == 9 then + if param > 0 then + c.mOffset = param + end + off = ((f == XM and{c.mOffset }or{param})[1]) * 256 + elseif (f == S3M or f == IT) and fx == 15 then + if param > 0 then + c.mOffset = param + end + off = c.mOffset * 256 + ((f == IT and((c.mHighOffset * 65536 ))or(0))) + end + if off > 0 and v and v.active then + if off >= v.len then + if v.loopT > 0 and f ~= MOD then + off = v.loopS + elseif f == MOD and v.loopT > 0 then + off = v.loopS + else + v.active = false + return + end + end + v.p = off + end +end + +-- trigger(st, c, note, insIdx, vcmd): the note / instrument / volume column part of a cell +local function trigger(st, c, note, insIdx, vcmd) + local f = st.fmt + local m = st.m + local porta = isPorta(st, c.fx, vcmd) + local hasNote = note >= 1 and note <= 120 + if insIdx > 0 then + local valid = (st.insMode and{(m.instruments[insIdx] ~= nil )}or{(m.samples[insIdx] ~= nil +)})[1] if valid then + c.insIdx = insIdx + local n = (hasNote and{note }or{c.note +})[1] local smp, _, ins = resolve(st, insIdx, (n > 0 and{n }or{61})[1]) + setInstrumentDefaults(st, c, smp, ins) + if not hasNote then + local v = c.voice + if f == XM and v then + -- an instrument number alone (FT2 / OpenMPT): the playing note's envelopes restart (key on, no + -- fadeout); the new instrument applies from the next note + v.keyOn, v.fading, v.fade = true, false, 65536 + v.volEnvPos, v.panEnvPos, v.avPos, v.avAmp = 0, 0, 0, 0 + elseif (f == MOD or f == S3M) and smp then + c.smp, c.smpIdx = smp, insIdx + end + end + elseif f == XM and hasNote then + -- an empty instrument: the note stops the channel + c.insIdx = insIdx + if c.voice then + c.voice.active = false + end + hasNote = false + end + end + if hasNote then + local useIns = c.insIdx + local smp, smpIdx, ins, realNote = resolve(st, useIns, note) + if smp == nil then + if (f == MOD or f == S3M) and c.smp then + smp, smpIdx = c.smp, c.smpIdx + end + end + if smp then + local ft = c.finetune + local period, base = notePeriod(st, realNote, smp, ft) + local v = c.voice + if porta and ((v and v.active) or f == MOD or f == XM) then + -- tone portamento: a new target, no new note (ProTracker / FT2 never start a note with it) + c.target = period + if st.fmt == IT or st.fmt == S3M then + c.note = note + end + else + if f == IT and st.insMode then + newNoteAction(st, c, ins, useIns, realNote, smpIdx) + end + -- FT2: a note without an instrument number restarts the sample only (envelopes, key off and + -- fadeout carry on); with another instrument than the playing one, its envelopes and fadeout start + -- over but a key off stays + local keep= false + if f == XM and insIdx == 0 and c.voice ~= nil then + keep = c.voice.ins == ins and true or"release" + end + c.triggered = true + c.hzAdd = 0 + c.tremorOn = true + c.retrigCount = 0 + v = startVoice(st, c, smp, smpIdx, ins, useIns, realNote, period, base, keep) + v.patNote = note + c.period, c.target, c.base = period, period, base + c.note, c.realNote = note, realNote + c.smp, c.smpIdx = smp, smpIdx + if insIdx > 0 or f == MOD or f == S3M then + -- volume was set by the instrument; MOD / S3M keep the channel volume + end + if c.vibWave < 4 then + c.vibPos = 0 + end + if c.tremWave < 4 then + c.tremPos = 0 + end + v.cutoff, v.reso = c.cutoff, c.reso + v.volEnvOn, v.panEnvOn, v.pitchEnvOn = true, true, true + c.nna = -1 + sampleOffset(st, c, v) + end + elseif f == IT or f == XM then + -- a note mapped to no sample cuts + if c.voice and not porta then + if f == IT and st.insMode then + newNoteAction(st, c, nil, 0, note, 0) + end + if c.voice then + c.voice.active = false + end + end + end + elseif note == 255 then + if f == S3M or f == MOD then + cutVoice(c.voice) + elseif c.voice then + keyOff(st, c.voice) + end + elseif note == 254 then + cutVoice(c.voice) + if f ~= IT then + c.vol = 0 + end + elseif note == 253 then + noteFade(c.voice) + end + -- the volume column's set-volume / set-panning parts (the rest runs with the effects) + if vcmd > 0 then + if f == S3M then + c.vol = min(vcmd - 1, 64) + elseif f == XM then + if vcmd >= 0x10 and vcmd <= 0x50 then + c.vol = vcmd - 0x10 + elseif vcmd >= 0xC0 and vcmd <= 0xCF then + c.pan = (vcmd - 0xC0) * 16 + c.basePan = c.pan + end + elseif f == IT then + local v = vcmd - 1 + if v <= 64 then + c.vol = v + elseif v >= 128 and v <= 192 then + c.pan = (v - 128) * 4 + c.basePan = c.pan + c.surround = false + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ effect helpers +local function volSlideMod(c, param) + local x, y = math.floor(param / 16), param % 16 + if x > 0 then + c.vol = min(64, c.vol + x) + else + c.vol = max(0, c.vol - y) + end +end + +local function tonePorta(st, c, speed) + if c.period == c.target then + return + end + if st.hz then + speed =speed* (st.hzScale * st.hzTone +) end + if c.period < c.target then + c.period = min(c.period + speed, c.target) + else + c.period = max(c.period - speed, c.target) + end +end + +local function vibrato(st, c, scale) + c.vibDelta = wave64(c.vibWave % 4, c.vibPos) * c.vibDepth * scale + c.vibPos = (c.vibPos + c.vibSpeed) % 64 +end + +local function tremolo(c, scale) + c.tremDelta = floor(wave64(c.tremWave % 4, c.tremPos) * c.tremDepth * scale) + c.tremPos = (c.tremPos + c.tremSpeed) % 64 +end + +local function retrigVoice(st, c) + local v = c.voice + if v and v.smp then + v.active = v.smp.length > 0 + v.p = 0 + v.dir = 1 + end +end + +local function retrigVolume(c, x) + if x == 0 or x == 8 then + return + end + local mul = Tables.RETRIG_MUL[x + 1] + if mul ~= 1 then + c.vol = floor(c.vol * mul) + else + c.vol =c.vol+ Tables.RETRIG_ADD[x + 1] + end + c.vol = clamp(c.vol, 0, 64) +end + +-- S3M / IT D-style slide of a value: returns the new value (fine parts only on tick 0, normal parts on other ticks; +-- fast: normal parts on tick 0 too) +local function dSlide(value, param, tick, fast, hi) +local x, y = math.floor(param / 16), param % 16 + if y == 0xF and x > 0 then + if tick == 0 then + return min(hi, value + x) + end + return value + elseif x == 0xF and y > 0 then + if tick == 0 then + return max(0, value - y) + end + return value + end + if tick == 0 and not fast then + return value + end + if y == 0 then + return min(hi, value + x) + elseif x == 0 then + return max(0, value - y) + end + return value +end + +-- ------------------------------------------------------------------------------------------------ MOD / XM effects +local function fxModXm(st, c, tick) + local fx, param = c.fx, c.param + local xm = st.fmt == XM + local x, y = math.floor(param / 16), param % 16 + if fx == 0 then + if param ~= 0 then + local k = tick % 3 + c.arp = (k == 1 and{x }or{(k == 2 and{y }or{0 +})[1]})[1] end + elseif fx == 1 then + if xm and param > 0 then + c.mPortaUp = param + end + if tick > 0 or st.fastPortas then + slide(st, c, -((xm and{c.mPortaUp }or{param})[1]) * 4) + end + elseif fx == 2 then + if xm and param > 0 then + c.mPortaDn = param + end + if tick > 0 or st.fastPortas then + slide(st, c, ((xm and{c.mPortaDn }or{param})[1]) * 4) + end + elseif fx == 3 or fx == 5 then + if fx == 3 and param > 0 then + c.portaSpeed = param + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif fx == 4 or fx == 6 then + if fx == 4 then + if x > 0 then + c.vibSpeed = x + end + if y > 0 then + c.vibDepth = y + end + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif fx == 7 then + if x > 0 then + c.tremSpeed = x + end + if y > 0 then + c.tremDepth = y + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 8 then + if tick == 0 then + c.pan = param + c.basePan = c.pan + c.surround = false + end + elseif fx == 0xB then + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 0xC then + if tick == 0 then + c.vol = min(param, 64) + end + elseif fx == 0xD then + if tick == 0 then + local r = x * 10 + y + if r > 63 then + r = 0 + end + st.breakRow = r + end + elseif fx == 0xE then + if x == 1 then + if xm and y > 0 then + c.mFineUp = y + end + if tick == 0 then + slide(st, c, -((xm and{c.mFineUp }or{y})[1]) * 4) + end + elseif x == 2 then + if xm and y > 0 then + c.mFineDn = y + end + if tick == 0 then + slide(st, c, ((xm and{c.mFineDn }or{y})[1]) * 4) + end + elseif x == 4 then + c.vibWave = y % 8 + elseif x == 6 then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + st.ft2BreakPos = c.loopRow + else + c.loopCount =c.loopCount- 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + end + st.ft2BreakPos = c.loopRow + end + end + elseif x == 7 then + c.tremWave = y % 8 + elseif x == 8 then + if tick == 0 then -- FT2 ignores E8x in XM; OpenMPT (the reference) applies it + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if y > 0 and tick > 0 and tick % y == 0 then + retrigVoice(st, c) + end + elseif x == 0xA then + if xm and y > 0 then + c.mFineVolUp = y + end + if tick == 0 then + c.vol = min(64, c.vol + ((xm and{c.mFineVolUp }or{y})[1])) + end + elseif x == 0xB then + if xm and y > 0 then + c.mFineVolDn = y + end + if tick == 0 then + c.vol = max(0, c.vol - ((xm and{c.mFineVolDn }or{y})[1])) + end + elseif x == 0xC then + if tick == y then + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 0xF then + if tick == 0 then + if param == 0 then + if not xm then + st.stopAfterRow = true -- ProTracker F00: the song stops (after this row, as OpenMPT plays it) + end + elseif param < 32 then + st.speed = param + else + st.tempo = param + end + end + elseif fx == 16 then -- G + if tick == 0 then + st.gvol = min(param, 64) * 2 + end + elseif fx == 17 then -- H + if param > 0 then + c.mGVolSlide = param + end + if tick > 0 then + local p = c.mGVolSlide + local px, py = math.floor(p / 16), p % 16 + if px > 0 then + st.gvol = min(128, st.gvol + px * 2) + else + st.gvol = max(0, st.gvol - py * 2) + end + end + elseif fx == 20 then -- K + if tick == param then + keyOff(st, c.voice) + end + elseif fx == 21 then -- L + if tick == 0 and c.voice then + c.voice.volEnvPos = param + c.voice.panEnvPos = param + end + elseif fx == 25 then -- P + if param > 0 then + c.mPanSlide = param + end + if tick > 0 then + local p = c.mPanSlide + local px, py = math.floor(p / 16), p % 16 + if px > 0 then + c.pan = min(255, c.pan + px) + c.basePan = c.pan + else + c.pan = max(0, c.pan - py) + c.basePan = c.pan + end + end + elseif fx == 27 then -- R + if x > 0 then + c.mRetrig = c.mRetrig % 16 + x * 16 + end + if y > 0 then + c.mRetrig = (math.floor(c.mRetrig / 16)) * 16 + y + end + local interval = c.mRetrig % 16 + if tick == 0 and c.triggered then + c.retrigCount = 0 + else + c.retrigCount =c.retrigCount+ 1 + end + if interval > 0 and c.retrigCount >= interval then + c.retrigCount = 0 + retrigVolume(c, math.floor(c.mRetrig / 16)) + retrigVoice(st, c) + end + elseif fx == 29 then -- T + if param > 0 then + c.mTremor = param + end + elseif fx == 33 then -- X + if x == 1 then + if y > 0 then + c.mXFineUp = y + end + if tick == 0 then + slide(st, c, -c.mXFineUp) + end + elseif x == 2 then + if y > 0 then + c.mXFineDn = y + end + if tick == 0 then + slide(st, c, c.mXFineDn) + end + end + end + -- the volume slide half of 5xy / 6xy and Axy + if fx == 0xA or fx == 5 or fx == 6 then + if xm then + if param > 0 then + c.mVolSlide = param + end + if tick > 0 or st.fastSlides then + volSlideMod(c, c.mVolSlide) + end + elseif tick > 0 or st.fastSlides then + volSlideMod(c, param) + end + end + -- tremor (XM Txy): on x + 1 ticks, off y + 1 ticks + if fx == 29 and tick > 0 then + local on, off = math.floor(c.mTremor / 16 )+ 1, c.mTremor % 16 + 1 + c.tremorCount =c.tremorCount% (on + off +) c.tremorOn = c.tremorCount < on + c.tremorCount =c.tremorCount+ 1 + end +end + +-- the XM volume column (everything but set volume / set panning, done by trigger) +local function volColXm(st, c, tick) + local v = c.vcmd + if v < 0x60 then + return + end + local hi, lo = math.floor(v / 16), v % 16 + if hi == 6 then + if tick > 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 7 then + if tick > 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 8 then + if tick == 0 then + c.vol = max(0, c.vol - lo) + end + elseif hi == 9 then + if tick == 0 then + c.vol = min(64, c.vol + lo) + end + elseif hi == 0xA then + if lo > 0 then + c.vibSpeed = lo + end + elseif hi == 0xB then + if lo > 0 then + c.vibDepth = lo + end + if tick > 0 then + vibrato(st, c, 8 / 255) + end + elseif hi == 0xD then + if tick > 0 then + c.pan = max(0, c.pan - lo) + c.basePan = c.pan + end + elseif hi == 0xE then + if tick > 0 then + c.pan = min(255, c.pan + lo) + c.basePan = c.pan + end + elseif hi == 0xF then + if lo > 0 then + c.portaSpeed = lo * 16 + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ S3M / IT effects +-- the parameter after memory: IT keeps one memory per effect group, ST3 one memory for most effects +local function mem(st, c, field, param) +if st.fmt == S3M then + if param > 0 then + c.mS3M = param + end + return c.mS3M + end + if param > 0 then + c[field] = param + end + return c[field] +end + +local function portaS3m(st, c, p, tick, sign) + if p >= 0xF0 then + if tick == 0 then + slide(st, c, sign * (p % 16) * 4) + end + elseif p >= 0xE0 then + if tick == 0 then + slide(st, c, sign * (p % 16)) + end + elseif tick > 0 or st.fastPortas then + slide(st, c, sign * p * 4) + end +end + +local function fxS3mIt(st, c, tick) + local fx, param = c.fx, c.param + local it = st.fmt == IT + if fx == 1 then -- A speed + if tick == 0 and param > 0 then + if st.st2Tempo then + st.speed, st.tempo = Tables.st2Tempo(param) + else + st.speed = param + end + end + elseif fx == 2 then -- B jump + if tick == 0 then + st.jumpOrd = param + if st.breakRow < 0 then + st.breakRow = 0 + end + end + elseif fx == 3 then -- C break + if tick == 0 then + st.breakRow = (it and{param }or{((math.floor(param / 16)) * 10 + param % 16 +)})[1] end + elseif fx == 4 or fx == 11 or fx == 12 then -- D volume slide (K, L: + vibrato / tone portamento) + local p = mem(st, c, "mVolSlide", param) + c.vol = dSlide(c.vol, p, tick, st.fastSlides, 64) + elseif fx == 5 then -- E porta down + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, 1) + elseif fx == 6 then -- F porta up + local p = mem(st, c, "mEF", param) + portaS3m(st, c, p, tick, -1) + elseif fx == 9 then -- I tremor + local p = mem(st, c, "mTremor", param) + if tick > 0 or not it then + local on, off = math.floor(p / 16), p % 16 + if it and st.oldFx or not it then + on, off = on + 1, off + 1 + end + on, off = max(on, 1), max(off, 1) + c.tremorCount =c.tremorCount% (on + off +) c.tremorOn = c.tremorCount < on + c.tremorCount =c.tremorCount+ 1 + end + elseif fx == 10 then -- J arpeggio + local p = mem(st, c, "mArp", param) + local k = tick % 3 + c.arp = (k == 1 and{(math.floor(p / 16 ))}or{(k == 2 and((p % 16 ))or(0 +))})[1] elseif fx == 13 then -- M channel volume + if tick == 0 and param <= 64 then + c.chanVol = param + end + elseif fx == 14 then -- N channel volume slide + local p = mem(st, c, "mChanVolSlide", param) + c.chanVol = dSlide(c.chanVol, p, tick, false, 64) + elseif fx == 16 then -- P panning slide (0..64 scale x 4) + local p = mem(st, c, "mPanSlide", param) + local pan64 = c.pan / 4 + local x, y = math.floor(p / 16), p % 16 + if y == 0xF and x > 0 then + if tick == 0 then + pan64 = max(0, pan64 - x) + end + elseif x == 0xF and y > 0 then + if tick == 0 then + pan64 = min(64, pan64 + y) + end + elseif tick > 0 then + if y == 0 then + pan64 = max(0, pan64 - x) + elseif x == 0 then + pan64 = min(64, pan64 + y) + end + end + c.pan = pan64 * 4 + c.basePan = c.pan + c.surround = false + elseif fx == 17 then -- Q retrigger + volume change + local p = mem(st, c, "mRetrig", param) + local interval = p % 16 + if interval > 0 then + if tick == 0 and c.retrigCount <= 0 then + c.retrigCount = interval + end + if tick > 0 then + c.retrigCount =c.retrigCount- 1 + if c.retrigCount <= 0 then + c.retrigCount = interval + retrigVolume(c, math.floor(p / 16)) + retrigVoice(st, c) + end + end + end + elseif fx == 18 then -- R tremolo + if math.floor(param / 16 )> 0 then + c.tremSpeed = math.floor(param / 16 +) end + if param % 16 > 0 then + c.tremDepth = param % 16 + end + if tick > 0 then + tremolo(c, 1 / 64) + end + elseif fx == 19 then -- S extended + local p = (it and{(mem(st, c, "mS", param) )}or{(mem(st, c, "mS", param) +)})[1] local x, y = math.floor(p / 16), p % 16 + if x == 3 then + c.vibWave = y % 8 + elseif x == 4 then + c.tremWave = y % 8 + elseif x == 5 then + c.panbWave = y % 8 + elseif x == 6 then + if tick == 0 then + st.fineDelay =st.fineDelay+ y + end + elseif x == 7 then + if tick == 0 then + if y <= 2 then + for _, u in __iter(st.voices) do + if u.active and u.bg and u.chan == c.idx then + if y == 0 then + cutVoice(u) + elseif y == 1 then + keyOff(st, u) + else + noteFade(u) + end + end + end + elseif y <= 6 then + c.nna = y - 3 + else + local v = c.voice + if v then + if y == 7 then + v.volEnvOn = false + elseif y == 8 then + v.volEnvOn = true + elseif y == 9 then + v.panEnvOn = false + elseif y == 10 then + v.panEnvOn = true + elseif y == 11 then + v.pitchEnvOn = false + elseif y == 12 then + v.pitchEnvOn = true + end + end + end + end + elseif x == 8 then + if tick == 0 then + c.pan = y * 17 + c.basePan = c.pan + c.surround = false + end + elseif x == 9 then + if tick == 0 and y == 1 then + c.surround = true + end + elseif x == 0xA then + if tick == 0 then + c.mHighOffset = y + end + elseif x == 0xB then + if tick == 0 then + if y == 0 then + c.loopRow = st.row + elseif c.loopCount == 0 then + c.loopCount = y + st.loopJump = c.loopRow + else + c.loopCount =c.loopCount- 1 + if c.loopCount > 0 then + st.loopJump = c.loopRow + elseif it then + c.loopRow = st.row + 1 + end + end + end + elseif x == 0xC then + local at = y == 0 and it and 1 or y + if tick == at and (y > 0 or it) then + if it then + cutVoice(c.voice) + end + c.vol = 0 + end + elseif x == 0xE then + if tick == 0 and st.patDelayRep == 0 and st.patDelay == 0 then + st.patDelay = y + end + end + elseif fx == 20 then -- T tempo + if param >= 0x20 then + if tick == 0 then + st.tempo = param + end + elseif it then + if param > 0 then + c.mTempo = param + end + local p = c.mTempo + if tick > 0 then + if p >= 0x10 then + st.tempo = min(255, st.tempo + (p - 0x10)) + else + st.tempo = max(32, st.tempo - p) + end + end + end + elseif fx == 22 then -- V global volume + if tick == 0 then + if it then + if param <= 128 then + st.gvol = param + end + else + st.gvol = min(param, 64) * 2 + end + end + elseif fx == 23 then -- W global volume slide + local p = mem(st, c, "mGVolSlide", param) + st.gvol = dSlide(st.gvol, p, tick, false, 128) + elseif fx == 24 then -- X panning + if tick == 0 then + if it then + c.pan = param + c.basePan = c.pan + c.surround = false + elseif param <= 0x80 then + c.pan = param * 2 + c.basePan = c.pan + c.surround = false + elseif param == 0xA4 then + c.surround = true + end + end + elseif fx == 25 then -- Y panbrello + if math.floor(param / 16 )> 0 then + c.panbSpeed = math.floor(param / 16 +) end + if param % 16 > 0 then + c.panbDepth = param % 16 + end + c.panbDelta = wave64(c.panbWave % 4, math.floor(c.panbPos / 4)) * c.panbDepth / 16 + c.panbPos = (c.panbPos + c.panbSpeed) % 256 + elseif fx == 26 then -- Z MIDI macro: the default IT macros (Z00..Z7F cutoff, Z80..Z8F resonance) + if tick == 0 then + if param < 0x80 then + c.cutoff = param + elseif param < 0x90 then + c.reso = (param - 0x80) * 8 + end + if c.voice then + c.voice.cutoff, c.voice.reso = c.cutoff, c.reso + end + end + end + -- tone portamento (G, L) + if fx == 7 or fx == 12 then + if fx == 7 then + if st.fmt == S3M then + if param > 0 then + c.portaSpeed = param + end + elseif st.compatG then + if param > 0 then + c.portaSpeed = param + end + else + if param > 0 then + c.mEF = param + end + c.portaSpeed = c.mEF + end + end + if tick > 0 or st.fastPortas then + tonePorta(st, c, c.portaSpeed * 4) + end + end + -- vibrato (H, U, K) + if fx == 8 or fx == 21 or fx == 11 then + if fx ~= 11 then + if math.floor(param / 16 )> 0 then + c.vibSpeed = math.floor(param / 16 +) end + if param % 16 > 0 then + c.vibDepth = param % 16 + end + end + local scale = fx == 21 and 2 / 255 or 8 / 255 + if it and not st.oldFx then + scale =scale/ 2 + end + if tick > 0 or (it and not st.oldFx) then + vibrato(st, c, scale) + end + end +end + +-- the IT volume column (value stored + 1): slides, portamento, vibrato +local function volColIt(st, c, tick) + local v = c.vcmd - 1 + if v < 65 then + return + end + if v <= 74 then + local p = v - 65 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 84 then + local p = v - 75 + if p > 0 then + c.mVolCol = p + end + if tick == 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 94 then + local p = v - 85 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = min(64, c.vol + c.mVolCol) + end + elseif v <= 104 then + local p = v - 95 + if p > 0 then + c.mVolCol = p + end + if tick > 0 then + c.vol = max(0, c.vol - c.mVolCol) + end + elseif v <= 114 then + local p = (v - 105) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, c.mEF * 4) + end + elseif v <= 124 then + local p = (v - 115) * 4 + if p > 0 then + c.mEF = p + end + if tick > 0 then + slide(st, c, -c.mEF * 4) + end + elseif v >= 193 and v <= 202 then + local p = Tables.IT_VOLPORTA[v - 192] or 0 + if p > 0 then + if st.compatG then + c.portaSpeed = p + else + c.mEF = p + c.portaSpeed = p + end + end + if tick > 0 then + tonePorta(st, c, c.portaSpeed * 4) + end + elseif v >= 203 and v <= 212 then + local d = v - 203 + if d > 0 then + c.vibDepth = d + end + if tick > 0 or not st.oldFx then + vibrato(st, c, st.oldFx and 8 / 255 or 4 / 255) + end + end +end + +-- ------------------------------------------------------------------------------------------------ extension effects +-- the engine extension effects (EXT, codes 0x40..) and the auto slides, in any family +local function fxExt(st, c, tick) + local fx, param = c.fx, c.param + if fx >= EXT.NOTE_SLIDE_UP and fx <= EXT.NOTE_SLIDE_DOWN_RETRIG then + -- note slides (PTM, Oktalyzer): every (param >> 4) ticks by (param & 15) semitones; Oktalyzer (flags.oktSlides): + -- 1x = every tick, 5x = once on the first tick + if tick == 0 then + if math.floor(param / 16 )> 0 then + c.mNoteSlide = (math.floor(param / 16)) * 16 + c.mNoteSlide % 16 + end + if param % 16 > 0 then + c.mNoteSlide = (math.floor(c.mNoteSlide / 16)) * 16 + param % 16 + end + c.slideCount = math.floor(c.mNoteSlide / 16 +) end + local p = c.mNoteSlide + local go + if st.oktSlides then + go = math.floor(p / 16 )== 1 or tick == 0 + else + go = false + if tick > 0 then + c.slideCount =c.slideCount- 1 + go = c.slideCount == 0 + end + end + if go and c.smp and c.realNote > 0 then + c.slideCount = math.floor(p / 16 +) local up = fx == EXT.NOTE_SLIDE_UP or fx == EXT.NOTE_SLIDE_UP_RETRIG + c.realNote = clamp(c.realNote + ((up and((p % 16 ))or((-(p % 16))))), 1, 120) + c.period = notePeriod(st, c.realNote, c.smp, c.finetune) + if fx >= EXT.NOTE_SLIDE_UP_RETRIG then + retrigVoice(st, c) + end + end + elseif fx == EXT.AUTO_PORTA_UP or fx == EXT.AUTO_PORTA_DOWN then + if tick == 0 then + c.autoPorta = ((fx == EXT.AUTO_PORTA_UP and{(-param )}or{param})[1]) * 4 + end + elseif fx == EXT.FREQ_ADJUST then + if tick == 0 then + c.hzAdd = param * 80 + end + elseif fx >= EXT.TEMPO_256 and fx <= EXT.TEMPO_256 + 2 then + if tick == 0 then + st.tempo = (fx - EXT.TEMPO_256 + 1) * 256 + param + end + end + -- auto slides: every tick (fast portamentos) or every tick but the first + if tick > 0 or st.fastPortas then + if c.autoPorta ~= 0 then + slide(st, c, c.autoPorta) + end + if c.autoTone and not c.tonePortaRow then + tonePorta(st, c, c.portaSpeed * 4) + end + end +end + +-- ------------------------------------------------------------------------------------------------ rows and ticks +local function noteDelayOf(st, fx, param) +if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and math.floor(param / 16 )== 0xD then + return param % 16 + elseif (st.fmt == S3M or st.fmt == IT) and fx == 19 and math.floor(param / 16 )== 0xD then + return param % 16 + end + return 0 +end + +local function finetuneOf(st, fx, param) +if (st.fmt == MOD or st.fmt == XM) and fx == 0xE and math.floor(param / 16 )== 5 then + local y = param % 16 + if st.fmt == MOD then + return ((y >= 8 and((y - 16 ))or(y))) * 16 + end + return (y - 8) * 16 + end + return nil +end + +local function runEffects(st, c, tick) + c.vibDelta, c.arp = 0, 0 + if (c.fx >= 0x40 and c.fx < 0x50) or c.autoPorta ~= 0 or c.autoTone then + fxExt(st, c, tick) + end + if st.fmt == MOD or st.fmt == XM then + fxModXm(st, c, tick) + if st.fmt == XM then + volColXm(st, c, tick) + end + else + if st.fmt == IT then + volColIt(st, c, tick) + end + fxS3mIt(st, c, tick) + end + -- keep the tremolo / panbrello offsets only while their effect runs + local fx = c.fx + if st.fmt == MOD or st.fmt == XM then + if fx ~= 7 then + c.tremDelta = 0 + end + -- XM: a tremor that ends in its off phase keeps the channel silent until the next note (OpenMPT / FT2) + else + if fx ~= 18 then + c.tremDelta = 0 + end + if fx ~= 9 then + c.tremorOn = true + end + if fx ~= 25 then + c.panbDelta = 0 + end + end +end + +local function processRow(st) + local m = st.m + local pat = st.pat + local nch = st.nch + local data = pat.data + local base = st.row * nch * 5 + st.visited[st.ord * 1024 + st.row] = true + st.rows =st.rows+ 1 + for i = 1, nch do + local c = st.chans[i] + local o = base + (i - 1) * 5 + local note, ins, vcmd, fx, param = readu8(data, o), readu8(data, o + 1), readu8(data, o + 2), readu8(data, o + 3), readu8(data, o + 4) + if (st.fmt == MOD or st.fmt == XM) and fx == 0 and param == 0 then + fx = 255 + end + c.fx, c.param, c.vcmd = fx, param, vcmd + c.cutTick, c.keyOffTick = -1, -1 + if st.autoReset and fx ~= 0 and fx ~= 255 then + -- 669: any effect stops the auto slides + c.autoPorta, c.autoTone = 0, false + end + local tp = isPorta(st, fx, vcmd) + c.tonePortaRow = tp + if tp and st.autoTonePorta then + c.autoTone = param ~= 0 or not st.autoReset or not isPorta(st, fx, 0) + end + c.triggered = false + local delay = noteDelayOf(st, fx, param) + c.finetune = finetuneOf(st, fx, param) + if delay > 0 then + c.delayTick, c.dNote, c.dIns, c.dVol = delay, note, ins, vcmd + else + c.delayTick = -1 + trigger(st, c, note, ins, vcmd) + end + runEffects(st, c, 0) + end + local _ = m +end + +local function updateEnvelope(env, pos, keyOn, it) -- returns value, next position, ended + +local ticks, values = env.ticks, env.values + local n = #ticks + if n == 0 then + return 0, pos, true + end + local value + if pos <= ticks[1] then + value = values[1] + elseif pos >= ticks[n] then + value = values[n] + else + local i = 1 + while i < n and ticks[i + 1] <= pos do + i =i+ 1 + end + local t0, t1 = ticks[i], ticks[i + 1] + if t1 > t0 then + value = values[i] + (values[i + 1] - values[i]) * (pos - t0) / (t1 - t0) + else + value = values[i + 1] + end + end + local nextPos = pos + 1 + local ended = false + -- sustain / loop: only when the position runs over the end point (a position set past it, by Lxx, runs on) + -- FT2 jumps when the position reaches the end tick (its value is not played: a loop lasts end - start ticks), + -- IT after playing it (end - start + 1 ticks) + local se, le = ticks[env.susEnd], ticks[env.loopEnd] + local over = it and 1 or 0 + if keyOn and env.sustain and se and pos <= se and nextPos >= se + over then + nextPos = ticks[env.susStart] or nextPos + elseif env.loop and le and pos <= le and nextPos >= le + over then + nextPos = ticks[env.loopStart] or nextPos + elseif nextPos > ticks[n] then + nextPos = ticks[n] + ended = true + end + return value, nextPos, ended +end + +-- per-tick voice update: envelopes, fadeout, auto-vibrato, final frequency, gains and filter +local function updateVoice(st, v) + local ins = v.ins + local it = st.fmt == IT + local envVol, envPan, envPitch = 64, 0, 0 + local filterEnv = nil + if ins then + local hold = st.envHold and st.tick == 0 -- MED: the envelopes do not move on a row's first tick + local e = ins.volEnv + if e and e.enabled and v.volEnvOn then + local val, np, ended = updateEnvelope(e, v.volEnvPos, v.keyOn, it) + envVol, v.volEnvPos = val, (hold and{v.volEnvPos }or{np +})[1] if ended and it then + if val <= 0 then + v.active = false + return + end + v.fading = true + end + end + e = ins.panEnv + if e and e.enabled and v.panEnvOn then + local val, np = updateEnvelope(e, v.panEnvPos, v.keyOn, it) + envPan, v.panEnvPos = val, (hold and{v.panEnvPos }or{np +})[1] end + e = ins.pitchEnv + if e and e.enabled and v.pitchEnvOn then + local val, np = updateEnvelope(e, v.pitchEnvPos, v.keyOn, it) + v.pitchEnvPos = (hold and{v.pitchEnvPos }or{np +})[1] if e.filter then + filterEnv = val + else + envPitch = val + end + end + if v.fading then + local fo = ins.fadeout or 0 + v.fade =v.fade- (it and((fo * 64 ))or((fo * 2 +))) if v.fade <= 0 then + v.fade = 0 + v.active = false + return + end + end + end + v.envVol = envVol + -- auto-vibrato: XM per instrument, IT per sample + local avSrc = (it and{v.smp }or{ins +})[1] local avDelta = 0 + if avSrc and (avSrc.vibDepth or 0) > 0 then + local depth = avSrc.vibDepth + local sweep = avSrc.vibSweep or 0 + if it then + -- IT: the depth ramps up by the rate (vibSweep here) every tick, in 1/256 steps + local target = depth * 256 + if sweep == 0 then + v.avAmp = target + elseif v.avAmp < target then + v.avAmp = min(target, v.avAmp + sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, true) * v.avAmp / (256 * 64) * 4 + else + if sweep == 0 then + v.avAmp = depth * 256 + elseif v.keyOn then + v.avAmp = min(depth * 256, v.avAmp + depth * 256 / sweep) + end + avDelta = autoWave(avSrc.vibType or 0, v.avPos, false) * v.avAmp / (256 * 64) + end + v.avPos = (v.avPos + (avSrc.vibRate or 0)) % 256 + end + -- frequency + local P = v.periodOut + avDelta + local freq + if st.hz then + freq = max(0, P + (v.hzAdd or 0)) + elseif st.linear then + freq = v.base * 2 ^ (-P / 768) + else + freq = (P > 0 and((st.amiga / P ))or(0 +)) end + if envPitch ~= 0 then + freq =freq* 2 ^ (envPitch / 24) + end + v.inc = freq / st.sr + -- volume + local smp = v.smp + local vol = v.vol / 64 * envVol / 64 * v.fade / 65536 * st.gvol / 128 + -- channel, sample and instrument global volumes (64 / 64 / 128 unless an IT file, or another format's loader, + -- sets them) + vol =vol* (v.chanVol / 64 * ((smp and(((smp.globalVolume or 64) / 64 ))or(1))) * ((ins and(((ins.globalVolume or 128) / 128 ))or(1))) +) if v.tremorMute then + vol = 0 + end + -- panning + local pan = v.pan + if it and ins and (ins.pps or 0) ~= 0 then + pan = clamp(pan + ((v.patNote or v.note) - (ins.ppc or 60) - 1) * ins.pps / 2, 0, 256) + end + if envPan ~= 0 then + local range = 128 - abs(pan - 128) + pan =pan+ envPan * range / 32 + end + pan = clamp(pan, 0, 256) + pan = clamp(128 + (pan - 128) * st.separation, 0, 256) + local g = vol * st.master + if v.surround then + v.tl, v.tr = g * 0.5, -g * 0.5 + elseif st.ft2Pan then + -- FT2's square-root pan law (OpenMPT's CompatibleFT2 mix levels), pan at most 255 + local p = min(pan, 255) + v.tl, v.tr = g * math.sqrt((256 - p) / 256), g * math.sqrt(p / 256) + else + v.tl, v.tr = g * (256 - pan) / 256, g * pan / 256 + end + v.rampN = st.ramp + -- IT resonant filter + local cutoff = v.cutoff + if filterEnv ~= nil or cutoff < 127 or v.reso > 0 then + local cc = cutoff + if filterEnv ~= nil then + cc = cutoff * (filterEnv + 32) / 64 + end + local fhz = 110 * 2 ^ (0.25 + cc / 24) + fhz = clamp(fhz, 120, min(20000, st.sr / 2)) + local dmp = 10 ^ (-v.reso * (24 / 128) / 20) + local fc = fhz * 2 * math.pi / st.sr + local d = (1 - 2 * dmp) * fc + if d > 2 then + d = 2 + end + d = (2 * dmp - d) / fc + local e = 1 / (fc * fc) + local den = 1 + d + e + v.fa, v.fb0, v.fb1 = 1 / den, (d + e + e) / den, -e / den + v.fOn = not (cc >= 127 and v.reso == 0) + else + v.fOn = false + end +end + +-- tick(st) -> frames to mix for this tick (0 when the song ended) +function Player.tick(st) +if st.ended then + return 0 + end + local tick = st.tick + if tick == 0 and st.patDelayRep == 0 then + local key = st.ord * 1024 + st.row + if st.visited[key] and not st.loopAllowed then + st.ended = true + return 0 + end + if st.visited[key] then + -- looping on: forget the song so far, keep playing + table.clear(st.visited) + end + st.fineDelay = 0 + processRow(st) + else + local t = tick % st.speed + local rep = tick >= st.speed or st.patDelayRep > 0 + for i = 1, st.nch do + local c = st.chans[i] + if c.delayTick == tick and not rep then + c.delayTick = -1 + trigger(st, c, c.dNote, c.dIns, c.dVol) + end + if rep and t == 0 then + c.vibDelta, c.arp = 0, 0 + else + runEffects(st, c, t == 0 and 1 or t) + end + end + end + if st.ended then + return 0 + end + -- channel -> foreground voice + for i = 1, st.nch do + local c = st.chans[i] + local v = c.voice + if v and v.active and v.chan == i and not v.bg then + local P = arpPeriod(st, c.period, c.arp) + ((st.hz and((-c.vibDelta * st.hzScale ))or(c.vibDelta))) + v.period, v.periodOut, v.base = c.period, P, c.base + v.hzAdd = c.hzAdd + v.vol = clamp(c.vol + c.tremDelta, 0, 64) + if c.muted then + v.vol = 0 + end + v.pan = clamp(c.pan + c.panbDelta, 0, 256) + v.surround = c.surround + v.chanVol = c.chanVol + v.tremorMute = not c.tremorOn + v.cutoff, v.reso = c.cutoff, c.reso + end + end + for _, v in __iter(st.voices) do + if v.active then + updateVoice(st, v) + end + end + -- frames for this tick: 2.5 / tempo seconds, truncated per tick (as OpenMPT does) + local frames = floor(st.sr * 2.5 / max(1, st.tempo)) + -- advance + st.tick =st.tick+ 1 + if st.tick >= st.speed + st.fineDelay then + st.tick = 0 + if st.patDelayRep < st.patDelay then + st.patDelayRep =st.patDelayRep+ 1 + else + st.patDelay, st.patDelayRep = 0, 0 + advanceRow(st) + end + end + return frames +end + +return Player +end +__FILES["codecs/audio/Tracker/Tables"] = function() +--!strict +--!native +-- 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). +local Tables = {} + +-- the ProTracker half-sine (32 steps, 0..255) +local SINE32 = { 0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253, 255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24 } + +-- wave64(type, pos) -> -255..255 for pos 0..63: 0 sine, 1 ramp down, 2 square, 3 random (deterministic) +local RANDOM= {} +do + local s = 12345 + for i = 1, 64 do + s = (s * 1103515245 + 12345) % 2147483648 + RANDOM[i] = (math.floor(s / 65536)) % 511 - 255 + end +end +function Tables.wave64(kind, pos) +local p = pos % 64 + if kind == 1 then + return 255 - p * 8 + elseif kind == 2 then + return p < 32 and 255 or-255 + elseif kind == 3 then + return RANDOM[p + 1] + end + local v = SINE32[(p % 32) + 1] + return (p >= 32 and{(-v )}or{v +})[1]end + +-- autoWave(type, pos, it) -> -64..64 for pos 0..255. XM: 0 sine, 1 square, 2 ramp down, 3 ramp up. +-- IT: 0 sine, 1 ramp down, 2 square, 3 random. +local SINE256= {} +for i = 0, 255 do + SINE256[i + 1] = math.floor(math.sin(i * math.pi / 128) * 64 + 0.5) +end +function Tables.autoWave(kind, pos, it) +local p = pos % 256 + if it then + if kind == 1 then + return 64 - math.floor((p + 1) / 2 +) elseif kind == 2 then + return p < 128 and 64 or-64 + elseif kind == 3 then + return math.floor(RANDOM[(p % 64) + 1] / 4 +) end + return SINE256[p + 1] + end + if kind == 1 then + return p < 128 and 64 or-64 + elseif kind == 2 then + return 64 - math.floor((p + 1) / 2 +) elseif kind == 3 then + return math.floor((p + 1) / 2 )- 64 + end + return SINE256[p + 1] +end + +-- ProTracker periods, finetune 0, C-0 .. B-4 (60 notes; ProTracker itself uses C-1 .. B-3). Our note numbers: +-- 1 = C-0 (FT2 numbering), so ProTracker C-1 (856) = note 37 and C-2 (428) = note 49, the note that plays a sample at +-- its base rate (8363 Hz). +local PERIODS = { + 3424, 3232, 3048, 2880, 2712, 2560, 2416, 2280, 2152, 2032, 1920, 1812, + 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906, + 856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, + 428, 404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, + 214, 202, 190, 180, 170, 160, 151, 143, 135, 127, 120, 113, + 107, 101, 95, 90, 85, 80, 75, 71, 67, 63, 60, 56, +} +Tables.PERIODS = PERIODS +Tables.PERIOD_FIRST_NOTE = 13 -- PERIODS[1] is note 13 (C-1 in FT2 numbering = ProTracker octave -1) + +-- periodToNote(period) -> note (1..120), 0 for period 0 +function Tables.periodToNote(period) +if period <= 0 then + return 0 + end + -- exact match first, then the nearest note on a log scale + for i = 1, #PERIODS do + if PERIODS[i] == period then + return i + Tables.PERIOD_FIRST_NOTE - 1 + end + end + local n = 49 + math.floor(12 * math.log(428 / period) / math.log(2) + 0.5) + return math.clamp(n, 1, 120) +end + +-- noteToPeriod(note) -> ProTracker period (finetune 0) for a note, computed past the table's ends +function Tables.noteToPeriod(note) +local i = note - Tables.PERIOD_FIRST_NOTE + 1 + if i >= 1 and i <= #PERIODS then + return PERIODS[i] + end + return math.max(1, math.floor(428 * 2 ^ ((49 - note) / 12) + 0.5)) +end + +-- IT volume column "g" (tone portamento) speeds +Tables.IT_VOLPORTA = { 0, 1, 4, 8, 16, 32, 64, 96, 128, 255 } + +-- XM Rxy / S3M-IT Qxy volume changes: kind 0 add, 1 multiply; value +Tables.RETRIG_ADD = { 0, -1, -2, -4, -8, -16, 0, 0, 0, 1, 2, 4, 8, 16, 0, 0 } +Tables.RETRIG_MUL = { 1, 1, 1, 1, 1, 1, 2 / 3, 0.5, 1, 1, 1, 1, 1, 1, 1.5, 2 } + +-- the Amiga clock constant: frequency = AMIGA / period, with period 1712 playing an 8363 Hz sample at its base rate +-- (FT2 / ST3 period units, 4x ProTracker's) +Tables.AMIGA = 8363 * 1712 +-- MOD: the PAL Amiga clock (7093789.2 Hz / 2 per ProTracker period unit; period 428 plays at 8287 Hz) +Tables.AMIGA_PAL = 7093789.2 / 2 * 4 + +-- st2Tempo(byte) -> speed, tempo: a Scream Tracker 2 tempo byte (high nibble ticks per row, low nibble a fine factor) +-- as OpenMPT plays it (ConvertST2Tempo: ST2's tick length at its 23863 Hz mixing rate, as a fractional BPM) +local ST2_FACTOR = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 } +function Tables.st2Tempo(byte) +local hi, lo = math.floor(byte / 16), byte % 16 + local d = 50 - math.floor((ST2_FACTOR[hi + 1] * lo) / 16 -- never 0; negative at tempo 06..0F (C integer division truncates) +) local spt = (d > 0 and{(math.floor(23863 / d ))}or{(-(math.floor(23863 / -d)) +)})[1] if spt <= 0 then + spt =spt+ 65536 + end + return math.max(hi, 1), math.floor((23863 * 50000 + spt) / (spt * 2)) / 10000 +end + +return Tables +end +__FILES["codecs/audio/Tta"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- codecs/audio/Tta: the TTA1 (True Audio) lossless codec. A codec (layer 3). Written from the TTA1 format description +-- (the 22-byte header with its CRC-32, the seek table of frame sizes with its CRC-32, frames of 256 / 245 seconds); +-- no libtta / ffmpeg code (those are LGPL). The frame decoder is codecs/audio/Tta/Decode. Supports format 1 (plain +-- PCM), 8 / 16 / 24 bits, any channel count, the header / seek table / frame CRCs. Not supported: format 2 +-- (password-protected: UNSUPPORTED), TTA2. +-- +-- local info, err = Tta.info(buf, at, limit) -- the header at `at` (after any ID3v2 tag) + the frame table +-- local dec = Tta.decoder(info) +-- local n, err = dec:frame(buf, i) -- frame i (1-based) -> dec.pcm (interleaved integers) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/audio/Tta/Decode") + +local Tta = {} + +-- info(buf, at, limit) -> Info | nil, Err: the TTA1 header at byte `at` + + + + + + + + + + + + +function Tta.info(buf, at, limit) +if at + 22 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + if buffer.readstring(buf, at, 4) ~= "TTA1" then + return nil, Err.new(Err.CORRUPT, "no TTA1 header") + end + if Crc32.of(buf, at, 18) ~= buffer.readu32(buf, at + 18) then + return nil, Err.new(Err.CHECKSUM, "header CRC mismatch", at) + end + local format = buffer.readu16(buf, at + 4) + local info= { + format = format, + channels = buffer.readu16(buf, at + 6), + bitsPerSample = buffer.readu16(buf, at + 8), + sampleRate = buffer.readu32(buf, at + 10), + samples = buffer.readu32(buf, at + 14), + frameLength = 0, + frames = 0, + offsets = {}, + sizes = {}, + } + if format == 2 then + return nil, Err.new(Err.UNSUPPORTED, "password-protected TTA") + elseif format ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "TTA format " .. format) + end + local bits = info.bitsPerSample + if bits ~= 8 and bits ~= 16 and bits ~= 24 then + return nil, Err.new(Err.UNSUPPORTED, bits .. "-bit TTA") + end + if info.channels < 1 or info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + info.frameLength = math.floor((256 * info.sampleRate) / 245 +) if info.frameLength < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + local frames = math.floor((info.samples + info.frameLength - 1) / info.frameLength +) info.frames = frames + local st = at + 22 + if st + frames * 4 + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "truncated seek table") + end + if Crc32.of(buf, st, frames * 4) ~= buffer.readu32(buf, st + frames * 4) then + return nil, Err.new(Err.CHECKSUM, "seek table CRC mismatch", st) + end + local o = st + frames * 4 + 4 + for i = 1, frames do + local size = buffer.readu32(buf, st + (i - 1) * 4) + info.offsets[i] = o + info.sizes[i] = size + o =o+ size + end + return info, nil +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + + +local function frame(self, buf, i) +local info = self.info + if i < 1 or i > info.frames then + return nil, Err.new(Err.ARG, "no frame " .. i) + end + local o, size = info.offsets[i], info.sizes[i] + if o + size > self.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. i .. " runs past the end", o) + end + local n = (i < info.frames and{info.frameLength }or{(info.samples - (info.frames - 1) * info.frameLength +)})[1] local got, msg = Decode.frame(self.state, buf, o, size, n, self.pcm) + if not got then + return nil, Err.from(msg, o) + end + return got, nil +end + +-- decoder(info, limit) -> Decoder (limit: the end of the file data) +function Tta.decoder(info, limit) +return { + info = info, + pcm = table.create(info.frameLength * info.channels, 0), + limit = limit, + frame = frame, + state = Decode.state(info.channels, math.floor(info.bitsPerSample / 8)), + } +end + +return Tta +end +__FILES["codecs/audio/Tta/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/audio/Tta/Decode: one TTA1 frame -> samples. Written from the TTA1 format description (the True Audio +-- format notes: adaptive Rice codes with two running sums per channel, the order-8 sign-LMS "hybrid" filter, the +-- first-order fixed predictor, inter-channel decorrelation, a CRC-32 per frame); no libtta / ffmpeg code. Checked +-- bit-exact against the ttaenc 3.4.1 decoder (tools/fixtures/tta.py). Never throws: returns nil, message. +local Crc32 = __include("core/Crc32") + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local band, rshift = bit32.band, bit32.rshift +local min, max, floor = math.min, math.max, math.floor + +local Decode = {} + +local TWO31, TWO32 = 2147483648, 4294967296 +local INV31 = 1 / TWO31 +local PAD = 16 +local P2= table.create(40, 0) -- P2[k + 1] = 2^k +for i = 0, 39 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the trailing 1 bits of the byte b +local ONES= table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n =n+ 1 + v =math.floor(v/ 2 +) end + ONES[b + 1] = n +end + +-- longUnary(S, pos, lim) -> the count of 1 bits from pos, the position after the 0 | nil (past lim) +local function longUnary(S, pos, lim) +local unary = 0 + while pos <= lim do + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + return unary + ones, pos + ones + 1 + end + unary =unary+ 8 + pos =pos+ 8 + end + return nil, pos +end + + + + + + + + + + + + + + + +function Decode.state(channels, bytes) +return { + channels = channels, + bytes = bytes, + S = buffer.create(4096), + R = table.create(channels * 4, 0), + Q = table.create(channels * 8, 0), + X = table.create(channels * 8, 0), + L = table.create(channels * 8, 0), + E = table.create(channels, 0), + last = table.create(channels, 0), + cur = table.create(channels, 0), + } +end + +-- frame(st, buf, o, len, n, P) -> n | nil, message: the frame of len bytes at o (its CRC-32 last) holding n samples per +-- channel, into P (interleaved integers) +function Decode.frame(st, buf, o, len, n, P) +if len < 4 then + return nil, "truncated frame" + end + local dlen = len - 4 + if Crc32.of(buf, o, dlen) ~= readu32(buf, o + dlen) then + return nil, "checksum: frame CRC mismatch" + end + local S = st.S + if buffer.len(S) < dlen + PAD then + S = buffer.create(dlen + PAD + 4096) + st.S = S + end + buffer.copy(S, 0, buf, o, dlen) + buffer.fill(S, dlen, 0, PAD) + local C, bytes = st.channels, st.bytes + local shift = bytes == 2 and 9 or 10 -- the filter's precision per sample size + local fdiv = 2 ^ shift + local round = math.floor(fdiv / 2 +) local pk = bytes == 1 and 16 or 32 -- the fixed predictor: last * (pk - 1) / pk + local R, Q, X, L, E, last, cur = st.R, st.Q, st.X, st.L, st.E, st.last, st.cur + for c = 0, C - 1 do + R[c * 4 + 1], R[c * 4 + 2], R[c * 4 + 3], R[c * 4 + 4] = 10, 10, 16384, 16384 + E[c + 1], last[c + 1] = 0, 0 + for i = 1, 8 do + Q[c * 8 + i], X[c * 8 + i], L[c * 8 + i] = 0, 0, 0 + end + end + local pos = 0 -- bit position + local lim = dlen * 8 + local c = 0 -- the channel of the sample at idx + for idx = 1, n * C do + do + if pos > lim then + return nil, "truncated frame" + end + -- the unary prefix: 1 bits up to a 0 (a run past one byte goes to longUnary) + local unary + local w = rshift(readu32(S, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones < 8 then + unary = ones + pos =pos+ (ones + 1 +) else + local u, p2 = longUnary(S, pos, lim) + if not u then + return nil, "truncated frame" + end + unary, pos = u, p2 + end + local rb = c * 4 + local k0, k1, s0, s1 = R[rb + 1], R[rb + 2], R[rb + 3], R[rb + 4] + local deep = unary > 0 + local k + if deep then + k = k1 + unary =unary- 1 + else + k = k0 + end + local value = unary + if k > 0 then + local bits + if k <= 24 then + bits = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), P2[k + 1] - 1) + else + local lo = band(rshift(readu32(S, rshift(pos, 3)), band(pos, 7)), 0xFFFF) + local p2 = pos + 16 + bits = lo + band(rshift(readu32(S, rshift(p2, 3)), band(p2, 7)), P2[k - 15] - 1) * 65536 + end + pos =pos+ k + value = unary * P2[k + 1] + bits + end + if deep then + s1 =s1+ (value - math.floor(s1 / 16 +)) if k1 > 0 and s1 < P2[k1 + 5] then + k1 =k1- 1 + elseif s1 > P2[k1 + 6] then + k1 =k1+ 1 + end + value =value+ P2[k0 + 1] + end + s0 =s0+ (value - math.floor(s0 / 16 +)) if k0 > 0 and s0 < P2[k0 + 5] then + k0 =k0- 1 + elseif s0 > P2[k0 + 6] then + k0 =k0+ 1 + end + R[rb + 1] = math.min(k0, 31) + R[rb + 2] = math.min(k1, 31) + R[rb + 3] = s0 + R[rb + 4] = s1 + local odd = value % 2 -- odd -> (v + 1) / 2, even -> -v / 2 (branch-free) + value = math.floor((value + odd) / 2 )* (2 * odd - 1) + -- the adaptive filter: the weights step toward the sign of the last residual + local fb = c * 8 + local err = E[c + 1] + -- (one assignment per statement: LuaJIT cannot coalesce long multiple assignments) + local dq = max(-1, min(1, err)) + local x1, x2, x3, x4 = X[fb + 1], X[fb + 2], X[fb + 3], X[fb + 4] + local x5, x6, x7, x8 = X[fb + 5], X[fb + 6], X[fb + 7], X[fb + 8] + local q1 = Q[fb + 1] + x1 * dq + local q2 = Q[fb + 2] + x2 * dq + local q3 = Q[fb + 3] + x3 * dq + local q4 = Q[fb + 4] + x4 * dq + local q5 = Q[fb + 5] + x5 * dq + local q6 = Q[fb + 6] + x6 * dq + local q7 = Q[fb + 7] + x7 * dq + local q8 = Q[fb + 8] + x8 * dq + Q[fb + 1] = q1 + Q[fb + 2] = q2 + Q[fb + 3] = q3 + Q[fb + 4] = q4 + Q[fb + 5] = q5 + Q[fb + 6] = q6 + Q[fb + 7] = q7 + Q[fb + 8] = q8 + local l2, l3, l4, l5 = L[fb + 2], L[fb + 3], L[fb + 4], L[fb + 5] + local l6, l7, l8 = L[fb + 6], L[fb + 7], L[fb + 8] + local sum = round + L[fb + 1] * q1 + l2 * q2 + l3 * q3 + l4 * q4 + l5 * q5 + l6 * q6 + l7 * q7 + l8 * q8 + if sum >= TWO31 or sum < -TWO31 then + sum = (sum + TWO31) % TWO32 - TWO31 + end + -- the steps follow the delay line's signs (x 1, 2, 2, 4) + X[fb + 1] = x2 + X[fb + 2] = x3 + X[fb + 3] = x4 + X[fb + 4] = x5 + X[fb + 5] = 1 + 2 * floor(l5 * INV31) -- -1 for a negative value, else 1 (branch-free) + X[fb + 6] = 2 + 4 * floor(l6 * INV31) + X[fb + 7] = 2 + 4 * floor(l7 * INV31) + X[fb + 8] = 4 + 8 * floor(l8 * INV31) + E[c + 1] = value + value =value+ math.floor(sum / fdiv +) -- the delay line: the last value and its first and second differences + local n7 = value - l8 + local n6 = n7 - l7 + L[fb + 1] = l2 + L[fb + 2] = l3 + L[fb + 3] = l4 + L[fb + 4] = l5 + L[fb + 5] = n6 - l6 + L[fb + 6] = n6 + L[fb + 7] = n7 + L[fb + 8] = value + -- the fixed predictor + value =value+ math.floor((last[c + 1] * (pk - 1)) / pk +) last[c + 1] = value + cur[c + 1] = value + end + c =c+ 1 + if c == C then + -- inter-channel decorrelation: the last channel carries half the previous one, the others are differences + c = 0 + local o = idx - C + if C == 1 then + P[idx] = cur[1] + elseif C == 2 then + local a = cur[1] + local b = cur[2] + ((a >= 0 and{(math.floor(a / 2 ))}or{(-(math.floor((-a) / 2)))})[1]) + P[o + 1], P[o + 2] = b - a, b + else + local a = cur[C - 1] + cur[C]=cur[C]+ (a >= 0 and{(math.floor(a / 2 ))}or{(-(math.floor((-a) / 2)) +)})[1] for r = C - 1, 1, -1 do + cur[r] = cur[r + 1] - cur[r] + end + for k = 1, C do + P[o + k] = cur[k] + end + end + end + end + if pos > lim then + return nil, "truncated frame" + end + return n, nil +end + +return Decode +end +__FILES["codecs/audio/Vorbis"] = function() +--!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 = __include("codecs/audio/Vorbis/Setup"), + Codebook = __include("codecs/audio/Vorbis/Codebook"), + Packet = __include("codecs/audio/Vorbis/Packet"), + Tables = __include("codecs/audio/Vorbis/Tables"), +} + +return Vorbis +end +__FILES["codecs/audio/Vorbis/Codebook"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- 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 +-- is a fast table (up to 10 bits) plus a binary tree for longer codes instead of stb's sorted binary search. +-- +-- Never throws. Reading past the packet end gives zero bits and sets br.eop (the spec's end-of-packet condition); +-- an invalid codeword also sets eop and decodes to -1. +local Codebook = {} + +local readu8 = buffer.readu8 +local floor = math.floor + +local POW = table.create(41, 0) +for i = 0, 40 do + POW[i + 1] = 2 ^ i +end +-- ------------------------------------------------------------------------------------------------ bit reader + + + + + + + + + + + +function Codebook.reader(buf, offset, size) +return { buf = buf, pos = offset, limit = offset + size, acc = 0, cnt = 0, pad = 0, eop = false } +end + +-- bits(br, n) -> the next n (0..32) bits as an unsigned number +local function bits(br, n) +if n == 0 then + return 0 + end + local acc, cnt = br.acc, br.cnt + if cnt < n then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc =acc+ readu8(b, p) * POW[cnt + 1] + p =p+ 1 + else + br.pad =br.pad+ 8 + end + cnt =cnt+ 8 + until cnt >= n + br.pos = p + end + local m = POW[n + 1] + local v = acc % m + br.acc = (acc - v) / m + cnt =cnt- n + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + end + return v +end +Codebook.bits = bits + +-- ilog(x): the number of bits needed to hold x (0 for x <= 0) +local function ilog(x) +local n = 0 + while x > 0 do + n =n+ 1 + x = floor(x / 2) + end + return n +end +Codebook.ilog = ilog + +-- float32_unpack (spec 9.2.2) +local function float32Unpack(x) +local mantissa = x % 2097152 + local sign = x >= 2147483648 + local exp = floor((x % 2147483648) / 2097152) + local v = mantissa * 2 ^ (exp - 788) + return (sign and{(-v )}or{v +})[1]end +-- ------------------------------------------------------------------------------------------------ codebooks + + + + + + + + + + + + + + +local MAX_ENTRIES = 2 ^ 20 +local MAX_VQ = 2 ^ 22 + +-- lookup1_values(entries, dims): the largest r with r^dims <= entries +local function lookup1Values(entries, dims) +local r = floor(math.exp(math.log(entries) / dims)) + if floor((r + 1) ^ dims) <= entries then + r =r+ 1 + end + if (r + 1) ^ dims <= entries then + return -1 + end + if floor(r ^ dims) > entries then + return -1 + end + return r +end + +-- assign codewords (spec 3.2.1: in entry order, the lowest free leaf) and build the decode tree + fast table +local function build(book, lengths) +local n = book.entries + local c0, c1 = book.c0, book.c1 + local nodes = 1 + c0[1], c1[1] = 0, 0 + local available = table.create(33, 0) -- available[l]: the free code at depth l, as a 32-bit left-aligned value + 1 (0 = none) + local first = true + local used = 0 + local maxLen = 0 + for i = 0, n - 1 do + local len = lengths[i + 1] + if len > 0 then + local code +if first then + first = false + code = 0 + for l = 1, len do + available[l + 1] = POW[33 - l] + 1 + end + else + local z = len + while z > 0 and available[z + 1] == 0 do + z =z- 1 + end + if z == 0 then + return "over-subscribed codebook" + end + code = available[z + 1] - 1 + available[z + 1] = 0 + for y = len, z + 1, -1 do + available[y + 1] = code + POW[33 - y] + 1 + end + end + -- walk the MSB-first code into the tree + local node = 1 + for d = 1, len do + local bit = floor(code / POW[33 - d]) % 2 + local child = (bit == 0 and{c0[node] }or{c1[node] +})[1] if d == len then + if child ~= 0 then + return "ambiguous codeword" + end + if bit == 0 then + c0[node] = -(i + 1) + else + c1[node] = -(i + 1) + end + else + if child < 0 then + return "ambiguous codeword" + elseif child == 0 then + nodes =nodes+ 1 + c0[nodes], c1[nodes] = 0, 0 + child = nodes + if bit == 0 then + c0[node] = child + else + c1[node] = child + end + end + node = child + end + end + used =used+ 1 + if len > maxLen then + maxLen = len + end + end + end + book.used = used + -- the fast table: every fastBits-bit prefix (read LSB first) walked down the tree + local fb = math.clamp(maxLen, 1, 10) + book.fastBits = fb + local size = POW[fb + 1] + local fl, fs = table.create(size, -1), table.create(size, 0) + for idx = 0, size - 1 do + local node = 1 + local v = idx + for d = 1, fb do + local bit = v % 2 + v = (v - bit) / 2 + local child = (bit == 0 and{c0[node] }or{c1[node] +})[1] if child < 0 then + fl[idx + 1], fs[idx + 1] = d, -child - 1 + break + elseif child == 0 then + break -- invalid (-1) + end + node = child + if d == fb then + fl[idx + 1], fs[idx + 1] = 0, node + end + end + end + book.fastLen, book.fastSym = fl, fs + return nil +end + +-- read(br) -> Book | nil, message: one codebook from the setup header +function Codebook.read(br) +if bits(br, 24) ~= 0x564342 then + return nil, "bad codebook sync" + end + local dims = bits(br, 16) + local entries = bits(br, 24) + local ordered = bits(br, 1) + if br.eop then + return nil, "setup header ends in a codebook" + end + if dims == 0 and entries ~= 0 then + return nil, "codebook with 0 dimensions" + end + if entries > MAX_ENTRIES then + return nil, "codebook with " .. entries .. " entries" + end + local lengths = table.create(entries, 0) + if ordered == 1 then + local cur = 0 + local len = bits(br, 5) + 1 + while cur < entries do + local num = bits(br, ilog(entries - cur)) + if len >= 32 or cur + num > entries or br.eop then + return nil, "bad ordered codebook lengths" + end + for k = cur + 1, cur + num do + lengths[k] = len + end + cur =cur+ num + len =len+ 1 + end + else + local sparse = bits(br, 1) + for j = 1, entries do + if sparse == 0 or bits(br, 1) == 1 then + local l = bits(br, 5) + 1 + if l == 32 then + return nil, "codeword length 32" + end + lengths[j] = l + end + end + end + if br.eop then + return nil, "setup header ends in a codebook" + end + local book= { + dims = dims, + entries = entries, + fastBits = 1, + fastLen = {}, + fastSym = {}, + c0 = {}, + c1 = {}, + lookup = 0, + vq = nil, + used = 0, + } + local err = build(book, lengths) + if err then + return nil, err + end + local lookup = bits(br, 4) + if lookup > 2 then + return nil, "lookup type " .. lookup + end + book.lookup = lookup + if lookup > 0 then + local minimum = float32Unpack(bits(br, 32)) + local delta = float32Unpack(bits(br, 32)) + local valueBits = bits(br, 4) + 1 + local seq = bits(br, 1) == 1 + local nvalues + if lookup == 1 then + nvalues = lookup1Values(entries, dims) + if nvalues < 0 then + return nil, "bad lookup1 size" + end + else + nvalues = entries * dims + end + if nvalues == 0 then + return nil, "empty lookup table" + end + if entries * dims > MAX_VQ or nvalues > MAX_VQ then + return nil, "lookup table too large" + end + local mults = table.create(nvalues, 0) + for j = 1, nvalues do + mults[j] = bits(br, valueBits) + end + if br.eop then + return nil, "setup header ends in a lookup table" + end + -- expand to one vector per entry (spec 3.2.1, "VQ lookup table vector representation") + local vq = table.create(entries * dims, 0) + for e = 0, entries - 1 do + local last = 0 + local div = 1 + for k = 0, dims - 1 do + local off + if lookup == 1 then + off = floor(e / div) % nvalues + div =div* nvalues + else + off = e * dims + k + end + local v = mults[off + 1] * delta + minimum + last + if seq then + last = v + end + vq[e * dims + k + 1] = v + end + end + book.vq = vq + end + return book, nil +end + +-- decode(br, book) -> entry number | -1 (end of packet / invalid codeword: br.eop is set) +local function decode(br, book) +local fb = book.fastBits + local acc, cnt = br.acc, br.cnt + if cnt < fb then + local b, p, lim = br.buf, br.pos, br.limit + repeat + if p < lim then + acc =acc+ readu8(b, p) * POW[cnt + 1] + p =p+ 1 + else + br.pad =br.pad+ 8 + end + cnt =cnt+ 8 + until cnt >= fb + br.pos = p + br.acc, br.cnt = acc, cnt + end + local idx = acc % POW[fb + 1] + 1 + local l = book.fastLen[idx] + if l > 0 then + local m = POW[l + 1] + br.acc = (acc - acc % m) / m + cnt =cnt- l + br.cnt = cnt + if cnt < br.pad then + br.eop = true + br.pad = cnt + return -1 + end + return book.fastSym[idx] + elseif l == 0 then + bits(br, fb) + local node = book.fastSym[idx] + local c0, c1 = book.c0, book.c1 + while true do + local child = (bits(br, 1) == 0 and{c0[node] }or{c1[node] +})[1] if br.eop then + return -1 + end + if child < 0 then + return -child - 1 + elseif child == 0 then + br.eop = true + return -1 + end + node = child + end + end + br.eop = true + return -1 +end +Codebook.decode = decode + +return Codebook +end +__FILES["codecs/audio/Vorbis/Packet"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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 +-- granule positions count exactly the samples returned (the first packet returns none). +-- +-- local st = Packet.new(ident, setup) +-- local n = Packet.decode(st, buf, offset, size) -- frames now in st.out[ch][1 .. n]; -1 = not an audio packet +-- 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 = __include("codecs/audio/Vorbis/Codebook") +local Setup = __include("codecs/audio/Vorbis/Setup") +local Tables = __include("codecs/audio/Vorbis/Tables") +local Mdct = __include("codecs/audio/Mdct") + +local Packet = {} + +local bits, decode = Codebook.bits, Codebook.decode +local ilog = Codebook.ilog +local INV_DB = Tables +local RANGE = { 256, 128, 86, 64 } + + + + + + + + + + + + + + + + + + + + + + +function Packet.new(id, setup) +local n0, n1, ch = id.blocksize0, id.blocksize1, id.channels + local plans= {} + local slopes= {} + for _, n in __iter({ n0, n1 }) do + local p = Mdct.new(n) + if not p then + return nil + end + plans[n] = p + local w = (Mdct.window("vorbis", n) ) +local half = table.create(math.floor(n / 2), 0) + for i = 1, math.floor(n / 2 )do + half[i] = w[i] + end + slopes[math.floor(n / 2)] = half + end + local function arrays(len) +local t = table.create(ch) + for c = 1, ch do + t[c] = table.create(len, 0) + end + return t + end + local partClass = table.create(ch) + for c = 1, ch do + partClass[c] = {} + end + return { + channels = ch, + n0 = n0, + n1 = n1, + setup = setup, + plans = plans, + slopes = slopes, + spec = arrays(math.floor(n1 / 2)), + frame = arrays(n1), + tail = arrays(math.floor(n1 / 2)), + tailLen = 0, + prevN = 0, + out = arrays(n1), + finalY = arrays(math.max(2, setup.maxFloorValues)), + step2 = table.create(math.max(2, setup.maxFloorValues), 0), + inter = table.create(math.floor(n1 / 2 )* ch, 0), + zero = table.create(ch, false), + reallyZero = table.create(ch, false), + partClass = partClass, + } +end + +function Packet.reset(st) + st.prevN = 0 + st.tailLen = 0 +end + +-- blocksize(st, buf, off, size) -> the block size of an audio packet (0 if not audio) +function Packet.blocksize(st, b, off, size) +if size < 1 then + return 0 + end + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return 0 + end + local m = bits(br, st.setup.modeBits) + local mode = st.setup.modes[m + 1] + if not mode or br.eop then + return 0 + end + return (mode.blockflag == 1 and{st.n1 }or{st.n0 +})[1]end + +-- ------------------------------------------------------------------------------------------------ floor 1 +local function predict(x, x0, x1, y0, y1) +local dy = y1 - y0 + local adx = x1 - x0 + local off = math.floor((((dy < 0 and{(-dy )}or{dy})[1]) * (x - x0)) / adx +) return (dy < 0 and((y0 - off ))or((y0 + off +)))end + +-- multiply out[x0 .. x1) by the floor line from (x0, y0) to (x1, y1) (stb draw_line) +local function drawLine(out, x0, y0, x1, y1, n) + local dy = y1 - y0 + local adx = x1 - x0 + local ady = (dy < 0 and{(-dy )}or{dy +})[1] local base = (dy < 0 and{(-(math.floor(ady / adx)) )}or{(math.floor(ady / adx +))})[1] local sy = (dy < 0 and((base - 1 ))or((base + 1 +))) ady =ady- ((base < 0 and{(-base )}or{base})[1]) * adx + if x1 > n then + x1 = n + end + local x, y, err = x0, y0, 0 + if x < x1 then +do local __DARKLUA_VAR=x + 1 out[__DARKLUA_VAR]=out[__DARKLUA_VAR]* INV_DB[y % 256 + 1] +end x =x+ 1 + while x < x1 do + err =err+ ady + if err >= adx then + err =err- adx + y =y+ sy + else + y =y+ base + end +do local __DARKLUA_VAR0=x + 1 out[__DARKLUA_VAR0]=out[__DARKLUA_VAR0]* INV_DB[y % 256 + 1] +end x =x+ 1 + end + end +end + +-- decode the floor of one channel into finalY (-1 = unused point); false = this channel is silent +local function floorDecode(st, br, g, finalY) +if bits(br, 1) == 0 then + return false + end + local books = st.setup.books + local range = RANGE[g.multiplier] + local yb = ilog(range) - 1 + finalY[1] = bits(br, yb) + finalY[2] = bits(br, yb) + local offset = 2 + for j = 1, g.partitions do + local pclass = g.partitionClass[j] + 1 + local cdim = g.classDims[pclass] + local cbits = g.classSubs[pclass] + local csub = 2 ^ cbits + local cval = 0 + if cbits > 0 then + cval = decode(br, books[g.classMaster[pclass] + 1]) + if cval < 0 then + return false + end + end + local subs = g.subBooks[pclass] + for _ = 1, cdim do + local book = subs[cval % csub + 1] + cval = math.floor(cval / csub +) if book >= 0 then + local v = decode(br, books[book + 1]) + if v < 0 then + return false + end + finalY[offset + 1] = v + else + finalY[offset + 1] = 0 + end + offset =offset+ 1 + end + end + if br.eop then + return false + end + -- step 1: amplitude value synthesis + local step2 = st.step2 + step2[1], step2[2] = 1, 1 + local xl, low, high = g.xlist, g.low, g.high + for j = 2, g.values - 1 do + local lo, hi = low[j + 1], high[j + 1] + local pred = predict(xl[j + 1], xl[lo + 1], xl[hi + 1], finalY[lo + 1], finalY[hi + 1]) + local val = finalY[j + 1] + local highroom = range - pred + local lowroom = pred + local room = (highroom < lowroom and((highroom * 2 ))or((lowroom * 2 +))) if val ~= 0 then + step2[lo + 1], step2[hi + 1], step2[j + 1] = 1, 1, 1 + if val >= room then + if highroom > lowroom then + finalY[j + 1] = val - lowroom + pred + else + finalY[j + 1] = pred - val + highroom - 1 + end + elseif val % 2 == 1 then + finalY[j + 1] = pred - math.floor((val + 1) / 2 +) else + finalY[j + 1] = pred + math.floor(val / 2 +) end + else + step2[j + 1] = 0 + finalY[j + 1] = pred + end + end + for j = 1, g.values do + if step2[j] == 0 then + finalY[j] = -1 + end + end + return true +end + +-- multiply target[1 .. n2] by the floor curve (stb do_floor) +local function floorCurve(g, finalY, target, n2) + local mult = g.multiplier + local lx, ly = 0, finalY[1] * mult + local sorted, xl = g.sorted, g.xlist + for q = 2, g.values do + local j = sorted[q] + 1 + local fy = finalY[j] + if fy >= 0 then + local hy = fy * mult + local hx = xl[j] + if lx ~= hx then + drawLine(target, lx, ly, hx, hy, n2) + end + lx, ly = hx, hy + end + end + if lx < n2 then + local v = INV_DB[ly % 256 + 1] + for j = lx + 1, n2 do + target[j]=target[j]* v + end + end +end + +-- ------------------------------------------------------------------------------------------------ residue +-- add the vectors of one partition to target at offset (0-based) .. offset + psize (bounded by limit) +local function partition(br, book, target, offset, psize, rtype, limit) +local vq = book.vq + if not vq then + br.eop = true -- a scalar book in a vector context: invalid stream + return false + end + local dims = book.dims + if rtype == 0 then + local step = math.floor(psize / dims +) for k = 0, step - 1 do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + for i = 0, dims - 1 do + local at = offset + k + i * step + if at < limit then +do local __DARKLUA_VAR=at + 1 target[__DARKLUA_VAR]=target[__DARKLUA_VAR]+ vq[base + i + 1] +end end + end + end + else + local k = 0 + while k < psize do + local e = decode(br, book) + if e < 0 then + return false + end + local base = e * dims + local len = math.min(dims, psize - k) + local at = offset + k + for i = 0, len - 1 do + if at + i < limit then +do local __DARKLUA_VAR=at + i + 1 target[__DARKLUA_VAR]=target[__DARKLUA_VAR]+ vq[base + i + 1] +end end + end + k =k+ dims + end + end + return true +end + +-- decode residue r for the channels `targets` (nil = do not decode) of length n2 each +local function residue(st, br, r, targets, ch, n2) + local books = st.setup.books + local rtype = r.type + local cbook = books[r.classbook + 1] + local classwords = cbook.dims + for j = 1, ch do + local t = targets[j] + if t then + for i = 1, n2 do + (t )[i] = 0 + end + end + end + local any = false + for j = 1, ch do + if targets[j] then + any = true + end + end + if not any then + return + end + local psize = r.partSize + local rb = r.books + local classdata = r.classdata + if rtype == 2 and ch > 1 then + local total = n2 * ch + local inter = st.inter + for i = 1, total do + inter[i] = 0 + end + local lb = math.min(r.begin, total) + local le = math.min(r.finish, total) + local partRead = math.floor((le - lb) / psize +) local pc = st.partClass[1] + local done = false + for pass = 1, 8 do + if done then + break + end + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + local q = decode(br, cbook) + if q < 0 then + done = true + break + end + pc[classSet] = classdata[q + 1] + end + local cls = pc[classSet] + local i = 0 + while i < classwords and pcount < partRead do + local b = rb[cls[i + 1] + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], inter, r.begin + pcount * psize, psize, 1, total) then + done = true + break + end + end + i =i+ 1 + pcount =pcount+ 1 + end + if done then + break + end + classSet =classSet+ 1 + end + end + -- de-interleave into the channels that are decoded + for j = 1, ch do + local t = targets[j] + if t then + local tt = t +local v = j + for i = 1, n2 do + tt[i] = inter[v] + v =v+ ch + end + end + end + return + end + local lb = math.min(r.begin, n2) + local le = math.min(r.finish, n2) + local partRead = math.floor((le - lb) / psize +) local pcs = st.partClass + for pass = 1, 8 do + local pcount, classSet = 0, 1 + while pcount < partRead do + if pass == 1 then + for j = 1, ch do + if targets[j] then + local q = decode(br, cbook) + if q < 0 then + return + end + pcs[j][classSet] = classdata[q + 1] + end + end + end + local i = 0 + while i < classwords and pcount < partRead do + for j = 1, ch do + local t = targets[j] + if t then + local c = pcs[j][classSet][i + 1] + local b = rb[c + 1][pass] + if b >= 0 then + if not partition(br, books[b + 1], t , r.begin + pcount * psize, psize, rtype, n2) then + return + end + end + end + end + i =i+ 1 + pcount =pcount+ 1 + end + classSet =classSet+ 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ packet +-- decode(st, buf, off, size) -> frames returned in st.out (0 for the first packet), -1 for a non-audio / bad packet +function Packet.decode(st, b, off, size) +if size < 1 then + return -1 + end + local setup = st.setup + local br = Codebook.reader(b, off, size) + if bits(br, 1) ~= 0 then + return -1 + end + local mode = setup.modes[bits(br, setup.modeBits) + 1] + if not mode then + return -1 + end + local n, prevLong, nextLong + if mode.blockflag == 1 then + n = st.n1 + prevLong = bits(br, 1) == 1 + nextLong = bits(br, 1) == 1 + else + n = st.n0 + prevLong, nextLong = false, false + end + if br.eop then + return -1 + end + local n2 = math.floor(n / 2 +) local n0 = st.n0 + local leftStart, leftEnd, rightStart, rightEnd + if mode.blockflag == 1 and not prevLong then + leftStart, leftEnd = math.floor((n - n0) / 4), math.floor((n + n0) / 4 +) else + leftStart, leftEnd = 0, n2 + end + if mode.blockflag == 1 and not nextLong then + rightStart, rightEnd = math.floor((n * 3 - n0) / 4), math.floor((n * 3 + n0) / 4 +) else + rightStart, rightEnd = n2, n + end + local map = setup.mappings[mode.mapping + 1] + local ch = st.channels + local spec, zero, reallyZero = st.spec, st.zero, st.reallyZero + -- floors + for c = 1, ch do + local s = map.mux[c] + 1 + local g = setup.floors[map.submapFloor[s] + 1] + local ok = floorDecode(st, br, g, st.finalY[c]) + zero[c] = not ok + reallyZero[c] = not ok + end + -- channels coupled to a non-silent channel are decoded too + for i = 1, map.couplingSteps do + local m, a = map.magnitude[i] + 1, map.angle[i] + 1 + if not zero[m] or not zero[a] then + zero[m], zero[a] = false, false + end + end + -- residues, per submap + for i = 1, map.submaps do + local targets= {} + local k = 0 + for c = 1, ch do + if map.mux[c] == i - 1 then + k =k+ 1 + targets[k] = (zero[c] and{false }or{spec[c] +})[1] end + end + residue(st, br, setup.residues[map.submapResidue[i] + 1], targets, k, n2) + end + -- inverse coupling + for i = map.couplingSteps, 1, -1 do + local m, a = spec[map.magnitude[i] + 1], spec[map.angle[i] + 1] + for j = 1, n2 do + local mv, av = m[j], a[j] + local m2, a2 + if mv > 0 then + if av > 0 then + m2, a2 = mv, mv - av + else + a2, m2 = mv, mv + av + end + else + if av > 0 then + m2, a2 = mv, mv + av + else + a2, m2 = mv, mv - av + end + end + m[j], a[j] = m2, a2 + end + end + -- floor curves, IMDCT, windows + local plan = st.plans[n] + local lslope = st.slopes[leftEnd - leftStart] + local rslope = st.slopes[rightEnd - rightStart] + for c = 1, ch do + local sp = spec[c] + local fr = st.frame[c] + if reallyZero[c] then + for j = 1, n do + fr[j] = 0 + end + else + local s = map.mux[c] + 1 + floorCurve(setup.floors[map.submapFloor[s] + 1], st.finalY[c], sp, n2) + Mdct.inverse(plan, sp, 1, 1, fr, 1) + for j = 1, leftStart do + fr[j] = 0 + end + local L = leftEnd - leftStart + for j = 0, L - 1 do +do local __DARKLUA_VAR=leftStart + j + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]* lslope[j + 1] +end end + local R = rightEnd - rightStart + for j = 0, R - 1 do +do local __DARKLUA_VAR=rightStart + j + 1 fr[__DARKLUA_VAR]=fr[__DARKLUA_VAR]* rslope[R - j] +end end + for j = rightEnd + 1, n do + fr[j] = 0 + end + end + end + -- overlap-add with the previous frame; return the samples between the two centres + local prevN = st.prevN + local count = 0 + if prevN > 0 then + count = math.floor(prevN / 4 )+ math.floor(n / 4 +) local o = math.floor(prevN / 4 )- math.floor(n / 4 -- this frame starts o samples after the previous centre +) local tl = st.tailLen + for c = 1, ch do + local out, tail, fr = st.out[c], st.tail[c], st.frame[c] + for j = 0, count - 1 do + local v = (j < tl and{tail[j + 1] }or{0 +})[1] local fi = j - o + if fi >= 0 then + v =v+ fr[fi + 1] + end + out[j + 1] = v + end + end + end + -- the new tail: this frame from its centre to the end of its window + local tl = rightEnd - n2 + for c = 1, ch do + local tail, fr = st.tail[c], st.frame[c] + for j = 1, tl do + tail[j] = fr[n2 + j] + end + end + st.tailLen = tl + st.prevN = n + return count +end + +return Packet +end +__FILES["codecs/audio/Vorbis/Setup"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +--!native +-- 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 = __include("codecs/audio/Vorbis/Codebook") + +local Setup = {} + +local bits, ilog = Codebook.bits, Codebook.ilog +local readu8, readu32 = buffer.readu8, buffer.readu32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function isVorbis(b, o, n, kind) +return n >= 7 and readu8(b, o) == kind and buffer.readstring(b, o + 1, 6) == "vorbis" +end +Setup.isVorbis = isVorbis + +-- ident(buf, offset, size) -> Ident | nil, message +function Setup.ident(b, o, n) +if not isVorbis(b, o, n, 1) then + return nil, "not a Vorbis identification header" + end + if n < 30 then + return nil, "short identification header" + end + if readu32(b, o + 7) ~= 0 then + return nil, "Vorbis version " .. readu32(b, o + 7) + end + local ch = readu8(b, o + 11) + local rate = readu32(b, o + 12) + local bs = readu8(b, o + 28) + local l0, l1 = bs % 16, math.floor(bs / 16 +) if ch == 0 or rate == 0 then + return nil, "no channels or no sample rate" + end + if l0 < 6 or l0 > 13 or l1 < 6 or l1 > 13 or l0 > l1 then + return nil, "bad blocksizes" + end + if readu8(b, o + 29) % 2 == 0 then + return nil, "identification header framing bit not set" + end + return { + channels = ch, + sampleRate = rate, + bitrateMax = buffer.readi32(b, o + 16), + bitrateNominal = buffer.readi32(b, o + 20), + bitrateMin = buffer.readi32(b, o + 24), + blocksize0 = 2 ^ l0, + blocksize1 = 2 ^ l1, + }, + nil +end + +-- comment(buf, offset, size) -> vendor, { "KEY=value" } | nil, message +function Setup.comment(b, o, n) +if not isVorbis(b, o, n, 3) then + return nil, nil + end + local p, e = o + 7, o + n + if p + 4 > e then + return nil, nil + end + local vlen = readu32(b, p) + p =p+ 4 + if vlen > e - p then + return nil, nil + end + local vendor = buffer.readstring(b, p, vlen) + p =p+ vlen + local list = {} + if p + 4 > e then + return vendor, list + end + local count = readu32(b, p) + p =p+ 4 + for _ = 1, count do + if p + 4 > e then + break + end + local len = readu32(b, p) + p =p+ 4 + if len > e - p then + break + end + table.insert(list, buffer.readstring(b, p, len)) + p =p+ len + end + return vendor, list +end + +-- setup(buf, offset, size, ident) -> Setup | nil, message +function Setup.setup(b, o, n, id) +if not isVorbis(b, o, n, 5) then + return nil, "not a Vorbis setup header" + end + local br = Codebook.reader(b, o + 7, n - 7) + local channels = id.channels + -- codebooks + local books= {} + local nbooks = bits(br, 8) + 1 + for i = 1, nbooks do + local book, err = Codebook.read(br) + if not book then + return nil, "codebook " .. (i - 1) .. ": " .. tostring(err) + end + books[i] = book + end + -- time domain transforms (placeholders) + local ntimes = bits(br, 6) + 1 + for _ = 1, ntimes do + if bits(br, 16) ~= 0 then + return nil, "bad time domain transform" + end + end + -- floors + local floors= {} + local maxValues = 0 + local nfloors = bits(br, 6) + 1 + for i = 1, nfloors do + local ftype = bits(br, 16) + if ftype == 0 then + return nil, "floor 0" + elseif ftype ~= 1 then + return nil, "bad floor type " .. ftype + end + local parts = bits(br, 5) + local pclass = table.create(parts, 0) + local maxClass = -1 + for j = 1, parts do + pclass[j] = bits(br, 4) + if pclass[j] > maxClass then + maxClass = pclass[j] + end + end + local cdims, csubs, cmaster, subBooks = {}, {}, {}, {} + for j = 1, maxClass + 1 do + cdims[j] = bits(br, 3) + 1 + csubs[j] = bits(br, 2) + cmaster[j] = -1 + if csubs[j] > 0 then + cmaster[j] = bits(br, 8) + if cmaster[j] >= nbooks then + return nil, "bad floor master book" + end + end + local sb = {} + for k = 1, 2 ^ csubs[j] do + sb[k] = bits(br, 8) - 1 + if sb[k] >= nbooks then + return nil, "bad floor subclass book" + end + end + subBooks[j] = sb + end + local mult = bits(br, 2) + 1 + local rangebits = bits(br, 4) + local xlist = { 0, 2 ^ rangebits } + for j = 1, parts do + local c = pclass[j] + for _ = 1, cdims[c + 1] do + table.insert(xlist, bits(br, rangebits)) + end + end + local values = #xlist + if values > 65 * 8 then + return nil, "too many floor points" + end + if br.eop then + return nil, "setup header ends in a floor" + end + local order = table.create(values, 0) + for j = 1, values do + order[j] = j - 1 + end + table.sort(order, function(a, c) +return xlist[a + 1] < xlist[c + 1] + end) + for j = 1, values - 1 do + if xlist[order[j] + 1] == xlist[order[j + 1] + 1] then + return nil, "duplicate floor x" + end + end + local low, high = table.create(values, 0), table.create(values, 0) + for j = 2, values - 1 do + local lo, hi = -1, 65536 + local x = xlist[j + 1] + for k = 0, j - 1 do + local xv = xlist[k + 1] + if xv > lo and xv < x then + low[j + 1], lo = k, xv + end + if xv < hi and xv > x then + high[j + 1], hi = k, xv + end + end + end + floors[i] = { + partitions = parts, + partitionClass = pclass, + classDims = cdims, + classSubs = csubs, + classMaster = cmaster, + subBooks = subBooks, + multiplier = mult, + xlist = xlist, + values = values, + sorted = order, + low = low, + high = high, + } + if values > maxValues then + maxValues = values + end + end + -- residues + local residues= {} + local nres = bits(br, 6) + 1 + for i = 1, nres do + local rtype = bits(br, 16) + if rtype > 2 then + return nil, "bad residue type " .. rtype + end + local rbegin, rend = bits(br, 24), bits(br, 24) + local psize = bits(br, 24) + 1 + local ncls = bits(br, 6) + 1 + local cbook = bits(br, 8) + if rend < rbegin then + return nil, "residue end before begin" + end + if cbook >= nbooks then + return nil, "bad residue classbook" + end + local cascade = table.create(ncls, 0) + for j = 1, ncls do + local lowBits = bits(br, 3) + local highBits = (bits(br, 1) == 1 and{(bits(br, 5) )}or{0 +})[1] cascade[j] = highBits * 8 + lowBits + end + local rbooks = {} + for j = 1, ncls do + local row = table.create(8, -1) + local c = cascade[j] + for k = 1, 8 do + if c % 2 == 1 then + row[k] = bits(br, 8) + if row[k] >= nbooks then + return nil, "bad residue book" + end + end + c = math.floor(c / 2 +) end + rbooks[j] = row + end + if br.eop then + return nil, "setup header ends in a residue" + end + -- class numbers of each classbook entry (stb's classdata) + local cb = books[cbook + 1] + local cw = cb.dims + if cb.entries * cw > 2 ^ 22 then + return nil, "residue classbook too large" + end + local classdata = table.create(cb.entries) + for j = 0, cb.entries - 1 do + local row = table.create(cw, 0) + local tmp = j + for k = cw, 1, -1 do + row[k] = tmp % ncls + tmp = math.floor(tmp / ncls +) end + classdata[j + 1] = row + end + residues[i] = { + type = rtype, + begin = rbegin, + finish = rend, + partSize = psize, + classifications = ncls, + classbook = cbook, + books = rbooks, + classdata = classdata, + } + end + -- mappings + local mappings= {} + local nmaps = bits(br, 6) + 1 + local chBits = ilog(channels - 1) + for i = 1, nmaps do + if bits(br, 16) ~= 0 then + return nil, "bad mapping type" + end + local submaps = (bits(br, 1) == 1 and{(bits(br, 4) + 1 )}or{1 +})[1] local steps = 0 + local mag, ang = {}, {} + if bits(br, 1) == 1 then + steps = bits(br, 8) + 1 + if steps > channels then + return nil, "too many coupling steps" + end + for k = 1, steps do + mag[k] = bits(br, chBits) + ang[k] = bits(br, chBits) + if mag[k] >= channels or ang[k] >= channels or mag[k] == ang[k] then + return nil, "bad coupling channels" + end + end + end + if bits(br, 2) ~= 0 then + return nil, "mapping reserved bits set" + end + local mux = table.create(channels, 0) + if submaps > 1 then + for j = 1, channels do + mux[j] = bits(br, 4) + if mux[j] >= submaps then + return nil, "bad channel mux" + end + end + end + local sf, sr = {}, {} + for j = 1, submaps do + bits(br, 8) + sf[j] = bits(br, 8) + sr[j] = bits(br, 8) + if sf[j] >= nfloors or sr[j] >= nres then + return nil, "bad submap floor / residue" + end + end + mappings[i] = { + submaps = submaps, + couplingSteps = steps, + magnitude = mag, + angle = ang, + mux = mux, + submapFloor = sf, + submapResidue = sr, + } + end + -- modes + local modes= {} + local nmodes = bits(br, 6) + 1 + for i = 1, nmodes do + local bf = bits(br, 1) + local wt, tt = bits(br, 16), bits(br, 16) + local m = bits(br, 8) + if wt ~= 0 or tt ~= 0 or m >= nmaps then + return nil, "bad mode" + end + modes[i] = { blockflag = bf, mapping = m } + end + if br.eop then + return nil, "setup header truncated" + end + if bits(br, 1) ~= 1 then + return nil, "setup header framing bit not set" + end + return { + books = books, + floors = floors, + residues = residues, + mappings = mappings, + modes = modes, + modeBits = ilog(nmodes - 1), + maxFloorValues = maxValues, + }, + nil +end + +return Setup +end +__FILES["codecs/audio/Vorbis/Tables"] = function() +--!strict +-- 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, + 1.7623575e-07, 1.8768855e-07, 1.9988561e-07, 2.1287530e-07, 2.2670913e-07, 2.4144197e-07, 2.5713223e-07, 2.7384213e-07, + 2.9163793e-07, 3.1059021e-07, 3.3077411e-07, 3.5226968e-07, 3.7516214e-07, 3.9954229e-07, 4.2550680e-07, 4.5315863e-07, + 4.8260743e-07, 5.1396998e-07, 5.4737065e-07, 5.8294187e-07, 6.2082472e-07, 6.6116941e-07, 7.0413592e-07, 7.4989464e-07, + 7.9862701e-07, 8.5052630e-07, 9.0579828e-07, 9.6466216e-07, 1.0273513e-06, 1.0941144e-06, 1.1652161e-06, 1.2409384e-06, + 1.3215816e-06, 1.4074654e-06, 1.4989305e-06, 1.5963394e-06, 1.7000785e-06, 1.8105592e-06, 1.9282195e-06, 2.0535261e-06, + 2.1869758e-06, 2.3290978e-06, 2.4804557e-06, 2.6416497e-06, 2.8133190e-06, 2.9961443e-06, 3.1908506e-06, 3.3982101e-06, + 3.6190449e-06, 3.8542308e-06, 4.1047004e-06, 4.3714470e-06, 4.6555282e-06, 4.9580707e-06, 5.2802740e-06, 5.6234160e-06, + 5.9888572e-06, 6.3780469e-06, 6.7925283e-06, 7.2339451e-06, 7.7040476e-06, 8.2047000e-06, 8.7378876e-06, 9.3057248e-06, + 9.9104632e-06, 1.0554501e-05, 1.1240392e-05, 1.1970856e-05, 1.2748789e-05, 1.3577278e-05, 1.4459606e-05, 1.5399272e-05, + 1.6400004e-05, 1.7465768e-05, 1.8600792e-05, 1.9809576e-05, 2.1096914e-05, 2.2467911e-05, 2.3928002e-05, 2.5482978e-05, + 2.7139006e-05, 2.8902651e-05, 3.0780908e-05, 3.2781225e-05, 3.4911534e-05, 3.7180282e-05, 3.9596466e-05, 4.2169667e-05, + 4.4910090e-05, 4.7828601e-05, 5.0936773e-05, 5.4246931e-05, 5.7772202e-05, 6.1526565e-05, 6.5524908e-05, 6.9783085e-05, + 7.4317983e-05, 7.9147585e-05, 8.4291040e-05, 8.9768747e-05, 9.5602426e-05, 0.00010181521, 0.00010843174, 0.00011547824, + 0.00012298267, 0.00013097477, 0.00013948625, 0.00014855085, 0.00015820453, 0.00016848555, 0.00017943469, 0.00019109536, + 0.00020351382, 0.00021673929, 0.00023082423, 0.00024582449, 0.00026179955, 0.00027881276, 0.00029693158, 0.00031622787, + 0.00033677814, 0.00035866388, 0.00038197188, 0.00040679456, 0.00043323036, 0.00046138411, 0.00049136745, 0.00052329927, + 0.00055730621, 0.00059352311, 0.00063209358, 0.00067317058, 0.00071691700, 0.00076350630, 0.00081312324, 0.00086596457, + 0.00092223983, 0.00098217216, 0.0010459992, 0.0011139742, 0.0011863665, 0.0012634633, 0.0013455702, 0.0014330129, + 0.0015261382, 0.0016253153, 0.0017309374, 0.0018434235, 0.0019632195, 0.0020908006, 0.0022266726, 0.0023713743, + 0.0025254795, 0.0026895994, 0.0028643847, 0.0030505286, 0.0032487691, 0.0034598925, 0.0036847358, 0.0039241906, + 0.0041792066, 0.0044507950, 0.0047400328, 0.0050480668, 0.0053761186, 0.0057254891, 0.0060975636, 0.0064938176, + 0.0069158225, 0.0073652516, 0.0078438871, 0.0083536271, 0.0088964928, 0.009474637, 0.010090352, 0.010746080, + 0.011444421, 0.012188144, 0.012980198, 0.013823725, 0.014722068, 0.015678791, 0.016697687, 0.017782797, + 0.018938423, 0.020169149, 0.021479854, 0.022875735, 0.024362330, 0.025945531, 0.027631618, 0.029427276, + 0.031339626, 0.033376252, 0.035545228, 0.037855157, 0.040315199, 0.042935108, 0.045725273, 0.048696758, + 0.051861348, 0.055231591, 0.058820850, 0.062643361, 0.066714279, 0.071049749, 0.075666962, 0.080584227, + 0.085821044, 0.091398179, 0.097337747, 0.10366330, 0.11039993, 0.11757434, 0.12521498, 0.13335215, + 0.14201813, 0.15124727, 0.16107617, 0.17154380, 0.18269168, 0.19456402, 0.20720788, 0.22067342, + 0.23501402, 0.25028656, 0.26655159, 0.28387361, 0.30232132, 0.32196786, 0.34289114, 0.36517414, + 0.38890521, 0.41417847, 0.44109412, 0.46975890, 0.50028648, 0.53279791, 0.56742212, 0.60429640, + 0.64356699, 0.68538959, 0.72993007, 0.77736504, 0.82788260, 0.88168307, 0.9389798, 1.0, +}) +end +__FILES["codecs/audio/VorbisComment"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!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 rosetta (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 = {} + + + +local TO_TAG= { tracknumber = "track", discnumber = "disc", description = "comment" } +local TO_FIELD= { track = "TRACKNUMBER", disc = "DISCNUMBER" } + +-- tagKey(fieldName) -> the Types.Tags key +function VorbisComment.tagKey(name) +local k = string.lower(name) + return TO_TAG[k] or k +end + +-- fieldName(tagKey) -> the Vorbis comment field name +function VorbisComment.fieldName(key) +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) +local tags= {} + local raw= {} + for _, s in __iter(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] = (old and((old .. "; " .. v ))or(v +)) end + end + return tags, raw +end + +-- fields(tags) -> "KEY=value" strings in key order (string keys and values only) +function VorbisComment.fields(tags) +local keys = {} + for k, v in __iter(tags) do + if type(k) == "string" and type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + local out= (table.create(#keys) ) +for i, k in __iter(keys) do + out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k] + end + return out +end + +return VorbisComment +end +__FILES["codecs/audio/WavPack"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- codecs/audio/WavPack: the WavPack 4 / 5 audio codec (the blocks of .wv files, and of WavPack in Matroska). A codec +-- (layer 3). Ported from WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt); the hot code is in +-- codecs/audio/WavPack/Block. Lossless and hybrid (lossy, and lossless with the .wvc correction blocks), integer 8 - 32 +-- bit (with the extended int32 modes) and 32-bit float, mono / stereo / multichannel (one block per mono or stereo +-- stream, INITIAL .. FINAL), every decorrelation pass (terms 1 - 8, 17, 18, -1 .. -3), joint stereo, cross +-- decorrelation, noise shaping, block CRCs and block checksums. Not supported: DSD, pre-4.0 streams (version < 0x402). +-- +-- local h, err = WavPack.header(buf, at, limit) -- the 32-byte block header at `at` (nil, message if none) +-- local info, err = WavPack.info(buf, at, limit) -- stream facts from the first audio block (channels, rate, ...) +-- local dec = WavPack.decoder(info.channels) +-- local frames, err = dec:frame(buf, blocks, cbuf?, cblocks?) -- blocks = { offset, ... } of one frame (+ wvc) +-- -- dec.pcm: interleaved samples (integers in the container range, or float values), WAV channel order +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Block = __include("codecs/audio/WavPack/Block") + +local WavPack = {} + + + + + + + + + + + +local RATES = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 } +WavPack.MONO, WavPack.HYBRID, WavPack.FLOAT, WavPack.INITIAL, WavPack.FINAL = 4, 8, 0x80, 0x800, 0x1000 +WavPack.DSD = 0x80000000 + +-- header(buf, at, limit?) -> Header | nil, message: a valid "wvpk" block header at byte `at` whose block ends by limit +function WavPack.header(buf, at, limit) +local lim = math.min(limit or buffer.len(buf), buffer.len(buf)) + if at < 0 or at + 32 > lim then + return nil, "truncated block header" + end + if buffer.readstring(buf, at, 4) ~= "wvpk" then + return nil, "no block header" + end + local ck = buffer.readu32(buf, at + 4) + local version = buffer.readu16(buf, at + 8) + if ck % 2 == 1 or ck < 24 or ck > 0x1000000 then + return nil, "bad block size" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. string.format("0x%x", version) + end + local total = buffer.readu32(buf, at + 12) + local tu8 = buffer.readu8(buf, at + 11) + local h= { + size = ck + 8, + version = version, + index = buffer.readu32(buf, at + 16) + buffer.readu8(buf, at + 10) * 4294967296, + total = total == 0xFFFFFFFF and-1 or total + tu8 * 4294967296 - tu8, + samples = buffer.readu32(buf, at + 20), + flags = buffer.readu32(buf, at + 24), + crc = buffer.readu32(buf, at + 28), + } + if at + h.size > lim then + return nil, "truncated block" + end + return h, nil +end + +-- info(buf, at, limit?) -> Info | nil, Err: the facts of the stream whose first audio block is at `at` + + + + + + + + + + + + +function WavPack.info(buf, at, limit) +local h, herr = WavPack.header(buf, at, limit) + if not h then + return nil, Err.from(herr, at) + end + local m, merr = Block.meta(buf, at, h.size) + if not m then + return nil, Err.from(merr, at) + end + local flags = h.flags + if bit32.band(flags, WavPack.DSD) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "DSD audio") + end + local bytes = bit32.band(flags, 3) + 1 + local info= { + channels = bit32.band(flags, WavPack.MONO) ~= 0 and 1 or 2, + channelMask = 0, + sampleRate = 44100, + bitsPerSample = bytes * 8 - bit32.band(bit32.rshift(flags, 13), 31), + bytesPerSample = bytes, + float = bit32.band(flags, WavPack.FLOAT) ~= 0, + hybrid = bit32.band(flags, WavPack.HYBRID) ~= 0, + version = h.version, + } + info.channelMask = info.channels == 1 and 4 or 3 + local sr = bit32.band(bit32.rshift(flags, 23), 15) + if sr < 15 then + info.sampleRate = RATES[sr + 1] + end + local o = m[0x27] -- ID_SAMPLE_RATE + if o and (m[0x27 + 256] == 3 or m[0x27 + 256] == 4) then + local rate = buffer.readu8(buf, o) + buffer.readu8(buf, o + 1) * 256 + buffer.readu8(buf, o + 2) * 65536 + if m[0x27 + 256] == 4 then + rate =rate+ bit32.band(buffer.readu8(buf, o + 3), 0x7F) * 16777216 + end + info.sampleRate = rate + end + o = m[0xD] -- ID_CHANNEL_INFO + if o then + local len = m[0xD + 256] + if len == 0 or len > 7 then + return nil, Err.new(Err.CORRUPT, "bad channel info", o) + end + local mask = 0 + if len >= 6 then + info.channels = buffer.readu8(buf, o) + bit32.band(buffer.readu8(buf, o + 2), 0xF) * 256 + 1 + mask = buffer.readu8(buf, o + 3) + buffer.readu8(buf, o + 4) * 256 + buffer.readu8(buf, o + 5) * 65536 + if len == 7 then + mask =mask+ buffer.readu8(buf, o + 6) * 16777216 + end + else + info.channels = buffer.readu8(buf, o) + for k = 1, len - 1 do + mask =mask+ buffer.readu8(buf, o + k) * 256 ^ (k - 1) + end + end + info.channelMask = mask + end + if info.channels < 1 then + return nil, Err.new(Err.CORRUPT, "no channels") + end + if info.sampleRate < 1 then + return nil, Err.new(Err.CORRUPT, "bad sample rate") + end + return info, nil +end + +-- md5(buf, at, limit?) -> 32 hex digits | nil: an ID_MD5_CHECKSUM in the block at `at` +function WavPack.md5(buf, at, limit) +local h = WavPack.header(buf, at, limit) + if not h then + return nil + end + local m = Block.meta(buf, at, h.size) + if not m then + return nil + end + local o = m[0x26] + if not o or m[0x26 + 256] ~= 16 then + return nil + end + local hex = table.create(16, "") + for k = 0, 15 do + hex[k + 1] = string.format("%02x", buffer.readu8(buf, o + k)) + end + return table.concat(hex) +end +-- ------------------------------------------------------------------------------------------------ decoder +-- frame(buf, blocks, cbuf?, cblocks?) -> frames | nil, Err: decode one frame (the blocks of one sample range, one per +-- mono / stereo stream, in channel order) into dec.pcm; cblocks are the matching .wvc blocks (hybrid lossless) + + + + + + + + +local function frame(self, buf, blocks, cbuf, cblocks) +local C = self.channels + local n = -1 + local c0 = 0 + for i, at in __iter(blocks) do + if c0 >= C then + break + end + local h, herr = WavPack.header(buf, at) + if not h then + return nil, Err.from(herr, at) + end + if n < 0 then + n = h.samples + if n * C > 16777216 then + return nil, Err.new(Err.LIMIT, "a frame of " .. n .. " samples x " .. C .. " channels", at) + end + if #self.pcm < n * C then + self.pcm = table.create(n * C, 0) + end + elseif h.samples ~= n then + return nil, Err.new(Err.CORRUPT, "blocks of a frame differ in length", at) + end + local cb, cp, cs = nil, nil, nil + if cbuf and cblocks and cblocks[i] then + local ch = WavPack.header(cbuf, cblocks[i]) + if ch and ch.samples == h.samples and ch.index == h.index then + cb, cp, cs = cbuf, cblocks[i], ch.size + end + end + local got, msg = Block.decode(self.state, buf, at, h.size, self.pcm, c0, C, cb, cp, cs) + if not got then + return nil, Err.from(msg, at) + end + c0 =c0+ got + end + if n < 0 then + return 0, nil + end + if c0 < C then + return nil, Err.new(Err.CORRUPT, "a frame is missing channels") + end + return n, nil +end + +-- decoder(channels) -> Decoder +function WavPack.decoder(channels) +return { + channels = channels, + pcm = table.create(4096 * channels, 0), + frame = frame, + state = Block.state(), + } +end + +WavPack.checksum = Block.checksum +WavPack.meta = Block.meta + +return WavPack +end +__FILES["codecs/audio/WavPack/Block"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Block: one WavPack 4 / 5 block (one mono or stereo stream of a frame) -> samples. Ported from +-- WavPack 5.9.0 (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt): unpack.c (the decorrelation passes, joint +-- stereo, the hybrid lossy and hybrid lossless (+ wvc) paths with noise shaping and cross decorrelation, fixup_samples), +-- read_words.c (the median-adaptive entropy decoder: get_words_lossless, get_word, read_code), unpack_floats.c, +-- decorr_utils.c / entropy_utils.c (the metadata) and open_utils.c (metadata parsing, the block checksum). The block +-- CRC (and the wvx CRC) is checked. Not ported: DSD blocks (UNSUPPORTED), pre-4.0 streams, the lossy "mute" heuristics. +-- Never throws: returns nil, message. +local Tables = __include("codecs/audio/WavPack/Tables") + +local readu8, readi8, readu16, readi16, readu32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32 +local writeu32, readf32 = buffer.writeu32, buffer.readf32 +local band, rshift, countlz = bit32.band, bit32.rshift, bit32.countlz +local exp2s, log2, restoreWeight = Tables.exp2s, Tables.log2, Tables.restoreWeight +local sign, clamp = math.sign, math.clamp + +local Block = {} + +local TWO32 = 4294967296 +local P2= table.create(34, 0) -- P2[k + 1] = 2^k +for i = 0, 33 do + P2[i + 1] = 2 ^ i +end +-- ONES[b + 1]: the number of trailing 1 bits of the byte b +local ONES= table.create(256, 0) +for b = 0, 255 do + local n, v = 0, b + while v % 2 == 1 do + n =n+ 1 + v = math.floor(v / 2 +) end + ONES[b + 1] = n +end + +-- header flags +local MONO_FLAG, HYBRID, JOINT, CROSS, SHAPE, FLOAT, INT32 = 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100 +local HBITRATE, HBALANCE, NEW_SHAPING, FALSE_STEREO, DSD = 0x200, 0x400, 0x20000000, 0x40000000, 0x80000000 +local FLOAT_SHIFT_ONES, FLOAT_SHIFT_SAME, FLOAT_SHIFT_SENT, FLOAT_ZEROS_SENT, FLOAT_NEG_ZEROS = 1, 2, 4, 8, 0x10 +local PAD = 64 -- zero bytes after each copied bitstream: reads past the end stay in the buffer +local MAX_SAMPLES = 2 ^ 20 -- per block +local D2, D1 = 17, 9 -- the first data index of the work table (stereo / mono): 8 frames of history in front +-- ------------------------------------------------------------------------------------------------ metadata +-- meta(buf, p, size) -> Meta | nil, message: the metadata sub-blocks of the block at p (header included in size) + + + +function Block.meta(buf, p, size) +local m= {} + local q, stop = p + 32, p + size + while stop - q >= 2 do + local id = readu8(buf, q) + local len = readu8(buf, q + 1) * 2 + q =q+ 2 + if band(id, 0x80) ~= 0 then + if stop - q < 2 then + return nil, "truncated metadata" + end + len =len+ (readu8(buf, q) * 512 + readu8(buf, q + 1) * 131072 +) q =q+ 2 + id =id- 0x80 + end + local odd = 0 + if band(id, 0x40) ~= 0 then + if len == 0 then + return nil, "odd-sized empty metadata" + end + id =id- 0x40 + len =len- 1 + odd = 1 + end + if stop - q < len + odd then + return nil, "truncated metadata" + end + m[id] = q + m[id + 256] = len + q =q+ (len + odd +) end + return m, nil +end + +-- checksum(buf, p, size, m) -> true | false: the ID_BLOCK_CHECKSUM (when there is one) matches +function Block.checksum(buf, p, m) +local o = m[0x2F] + if not o then + return true + end + local len = m[0x2F + 256] + if len ~= 2 and len ~= 4 then + return false + end + local words = math.floor((o - 2 - p) / 2 +) local csum = TWO32 - 1 + for i = 0, words - 1 do + csum = (csum * 3 + readu16(buf, p + i * 2)) % TWO32 + end + if len == 4 then + return readu32(buf, o) == csum + end + csum = bit32.bxor(csum, rshift(csum, 16)) + return readu16(buf, o) == band(csum, 0xFFFF) +end +-- ------------------------------------------------------------------------------------------------ state + + + + +function Block.state() +return { + W = table.create(D2 + 2 * 4096, 0), + term = table.create(16, 0), + delta = table.create(16, 0), + wA = table.create(16, 0), + wB = table.create(16, 0), + sA = table.create(16 * 8, 0), + sB = table.create(16 * 8, 0), + med = table.create(6, 0), + slow = { 0, 0 }, + limit = { 0, 0 }, + bacc = { 0, 0 }, + bdelta = { 0, 0 }, + sacc = { 0, 0 }, + sdelta = { 0, 0 }, + err = { 0, 0 }, + R1 = { b = buffer.create(0), p = 0, e = 0, n = 0 } , + R2 = { b = buffer.create(0), p = 0, e = 0, n = 0 } , + R3 = { b = buffer.create(0), p = 0, e = 0, n = 0 } , + scratch = buffer.create(4), + } +end + +-- open a bitstream: the bytes [o, o + len) copied with PAD zero bytes after them +local function openReader(R, buf, o, len) + if buffer.len(R.b) < len + PAD then + R.b = buffer.create(len + PAD + 1024) + else + buffer.fill(R.b, len, 0, PAD) + end + buffer.copy(R.b, 0, buf, o, len) + R.p = 0 + R.e = len * 8 + R.n = len + PAD +end + +-- ------------------------------------------------------------------------------------------------ bit reading +-- bits(R, n) -> the next n (<= 32) bits, LSB first +local function bits(R, n) +if n <= 0 then + return 0 + end + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 -- overrun: the caller's end check fails + return 0 + end + local b = R.b + if n <= 25 then + R.p = p + n + return band(rshift(readu32(b, byte), band(p, 7)), P2[n + 1] - 1) + end + local lo = band(rshift(readu32(b, byte), band(p, 7)), 0xFFFF) + p =p+ 16 + R.p = p + n - 16 + return lo + band(rshift(readu32(b, rshift(p, 3)), band(p, 7)), P2[n - 15] - 1) * 65536 +end + +local function bit(R) +return bits(R, 1) +end + +-- trailing(R, max) -> the number of 1 bits from the read position (up to max; a byte at a time), consumed with the 0 +-- after them when fewer than max +local function trailing(R, max) +local c = 0 + while c < max do + local p = R.p + local byte = rshift(p, 3) + if byte + 8 > R.n then + R.p = R.e + 1 + return max + end + local ones = ONES[band(rshift(readu32(R.b, byte), band(p, 7)), 255) + 1] + if ones < 8 then + if c + ones >= max then + R.p = p + (max - c) + return max + end + R.p = p + ones + 1 + return c + ones + end + c =c+ 8 + R.p = p + 8 + end + -- (max reached inside a run of 8: give back the extra ones) + R.p =R.p- (c - max +) return max +end + +-- the "Elias gamma"-like count (cbits ones, a zero, cbits - 1 bits) -> value | nil (33 ones) +local function gamma(R) +local c = trailing(R, 33) + if c == 33 then + return nil + end + if c < 2 then + return c + end + return bits(R, c - 1) + P2[c] +end + +-- readCode(R, maxcode) -> 0 .. maxcode (read_code) +local function readCode(R, maxcode) +if maxcode < 2 then + return (maxcode == 1 and{(bits(R, 1) )}or{0 +})[1] end + local bc = 32 - countlz(maxcode) + local extras = P2[bc + 1] - maxcode - 1 + local code = bits(R, bc - 1) + if code >= extras then + code = code * 2 - extras + bits(R, 1) + end + return code +end + +-- ones(R) -> the unary count with its escape (LIMIT_ONES = 16) | nil (the end marker) +local function onesCount(R) +local c = trailing(R, 17) + if c == 17 then + return nil + end + if c == 16 then + local g = gamma(R) + if not g then + return nil + end + c = g + 16 + end + return c +end + +-- ------------------------------------------------------------------------------------------------ lossless entropy +-- wordsLossless(st, n, stereo) -> true | nil: n samples (n * 2 when stereo) into st.W from the data index (the hot +-- loop of get_words_lossless, with the bit reader in locals) +local function wordsLossless(st, count, d) +local R= st.R1 + local b, pos, lim = R.b, R.p, R.e + local W = st.W + local med = st.med + local stereo = d == D2 + -- (a0, a1, a2): the current channel's medians, (c0, c1, c2) the other's; swapped every sample when stereo + local a0, a1, a2, c0, c1, c2 = med[4], med[5], med[6], med[1], med[2], med[3] + if not stereo then + a0, a1, a2, c0, c1, c2 = med[1], med[2], med[3], 0, 0, 0 + end + local hz, ho, za = 0, 0, 0 + for idx = d, d + count - 1 do +local __DARKLUA_CONTINUE_7=false repeat if stereo then + a0, a1, a2, c0, c1, c2 = c0, c1, c2, a0, a1, a2 + end + if pos > lim then + return false + end + if hz ~= 0 then + hz = 0 + local maxcode = math.floor(a0 / 16 +) a0 =a0- (math.floor((a0 + 126) / 128)) * 2 + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local low, used = 0, 0 + if maxcode < 2 then + if maxcode == 1 then + low, used = band(w, 1), 1 + end + else + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low = readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + low = band(w, P2[bc] - 1) + if low >= extras then + low = low * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos =pos+ (used + 1 +)__DARKLUA_CONTINUE_7=true break + end + if a0 < 2 and ho == 0 and c0 < 2 then + if za > 0 then + za =za- 1 + if za > 0 then + W[idx] = 0 +__DARKLUA_CONTINUE_7=true break + end + else + R.p = pos + local g = gamma(R) + pos = R.p + if not g then + return false + end + za = g + if za > 0 then + a0, a1, a2, c0, c1, c2 = 0, 0, 0, 0, 0, 0 + W[idx] = 0 +__DARKLUA_CONTINUE_7=true break + end + end + end + local w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local ones = ONES[band(w, 255) + 1] + if ones == 8 then + ones = 8 + ONES[band(rshift(w, 8), 255) + 1] + end + if ones < 16 then + pos =pos+ (ones + 1 +) else + if band(w, 0x10000) ~= 0 then + return false + end + R.p = pos + 17 + local g = gamma(R) + pos = R.p + if not g then + return false + end + ones = g + 16 + end + local hold = ho + ho = band(ones, 1) + hz = 1 - ho + ones = math.floor(ones / 2 )+ hold + local low, high + if ones == 0 then + low = 0 + high = math.floor(a0 / 16 +) a0 =a0- (math.floor((a0 + 126) / 128)) * 2 + else + low = math.floor(a0 / 16 )+ 1 + a0 =a0+ (math.floor((a0 + 128) / 128)) * 5 + if ones == 1 then + high = low + math.floor(a1 / 16 +) a1 =a1- (math.floor((a1 + 62) / 64)) * 2 + else + low =low+ (math.floor(a1 / 16 )+ 1 +) a1 =a1+ (math.floor((a1 + 64) / 64)) * 5 + if ones == 2 then + high = low + math.floor(a2 / 16 +) a2 =a2- (math.floor((a2 + 30) / 32)) * 2 + else + low =low+ (ones - 2) * (math.floor(a2 / 16 )+ 1) + high = low + math.floor(a2 / 16 +) a2 =a2+ (math.floor((a2 + 32) / 32)) * 5 + end + end + end + local maxcode = high - low + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + local used = 0 + if maxcode < 2 then + if maxcode == 1 then + low =low+ band(w, 1) + used = 1 + end + else + if maxcode >= 536870912 then + return false + end + local bc = 32 - countlz(maxcode) + if bc > 24 then + R.p = pos + low =low+ readCode(R, maxcode) + pos = R.p + w = rshift(readu32(b, rshift(pos, 3)), band(pos, 7)) + else + local extras = P2[bc + 1] - maxcode - 1 + local code = band(w, P2[bc] - 1) + if code >= extras then + code = code * 2 - extras + band(rshift(w, bc - 1), 1) + used = bc + else + used = bc - 1 + end + low =low+ code + end + end + if band(rshift(w, used), 1) ~= 0 then + W[idx] = -low - 1 + else + W[idx] = low + end + pos =pos+ (used + 1 +)__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + R.p = pos + return pos <= lim +end + +-- ------------------------------------------------------------------------------------------------ hybrid entropy +local function updateErrorLimit(st, flags, mono) + local bacc, bdelta, slow, limit = st.bacc, st.bdelta, st.slow, st.limit + bacc[1] = (bacc[1] + bdelta[1]) % TWO32 + local br0 = math.floor(bacc[1] / 65536 +) if mono then + if band(flags, HBITRATE) ~= 0 then + local sl0 = math.floor((slow[1] + 128) / 256 +) limit[1] = (sl0 - br0 > -256 and((exp2s(sl0 - br0 + 256) % TWO32 ))or(0 +)) else + limit[1] = exp2s(br0) % TWO32 + end + return + end + bacc[2] = (bacc[2] + bdelta[2]) % TWO32 + local br1 = math.floor(bacc[2] / 65536 +) if band(flags, HBITRATE) ~= 0 then + local sl0 = math.floor((slow[1] + 128) / 256 +) local sl1 = math.floor((slow[2] + 128) / 256 +) if band(flags, HBALANCE) ~= 0 then + local balance = math.floor((sl1 - sl0 + br1 + 1) / 2 +) if balance > br0 then + br1 = br0 * 2 + br0 = 0 + elseif -balance > br0 then + br0 = br0 * 2 + br1 = 0 + else + br1 = br0 + balance + br0 = br0 - balance + end + end + limit[1] = (sl0 - br0 > -256 and((exp2s(sl0 - br0 + 256) % TWO32 ))or(0 +)) limit[2] = (sl1 - br1 > -256 and((exp2s(sl1 - br1 + 256) % TWO32 ))or(0 +)) else + limit[1] = exp2s(br0) % TWO32 + limit[2] = exp2s(br1) % TWO32 + end +end + +-- getWord(st, chan, flags, mono) -> value, correction | nil (get_word; chan 0 / 1) +local function getWord(st, chan, flags, mono) +local R= st.R1 + local med = st.med + local mb = chan * 3 + local correction = 0 + if R.p > R.e then + return nil, 0 + end + if med[1] < 2 and st.hz == 0 and st.ho == 0 and med[4] < 2 then + if st.za > 0 then + st.za =st.za- 1 + if st.za > 0 then + local s = st.slow +do local __DARKLUA_VAR=chan + 1 s[__DARKLUA_VAR]=s[__DARKLUA_VAR]- math.floor((s[chan + 1] + 128) / 256 +)end return 0, 0 + end + else + local g = gamma(R) + if not g then + return nil, 0 + end + st.za = g + if g > 0 then + local s = st.slow +do local __DARKLUA_VAR=chan + 1 s[__DARKLUA_VAR]=s[__DARKLUA_VAR]- math.floor((s[chan + 1] + 128) / 256 +)end for k = 1, 6 do + med[k] = 0 + end + return 0, 0 + end + end + end + local ones + if st.hz ~= 0 then + ones = 0 + st.hz = 0 + else + local c = onesCount(R) + if not c then + return nil, 0 + end + ones = c + if st.ho ~= 0 then + st.ho = band(ones, 1) + ones = math.floor(ones / 2 )+ 1 + else + st.ho = band(ones, 1) + ones = math.floor(ones / 2 +) end + st.hz = 1 - st.ho + end + if band(flags, HYBRID) ~= 0 and chan == 0 then + updateErrorLimit(st, flags, mono) + end + local m0, m1, m2 = med[mb + 1], med[mb + 2], med[mb + 3] + local low, high + if ones == 0 then + low = 0 + high = math.floor(m0 / 16 +) m0 =m0- (math.floor((m0 + 126) / 128)) * 2 + else + low = math.floor(m0 / 16 )+ 1 + m0 =m0+ (math.floor((m0 + 128) / 128)) * 5 + if ones == 1 then + high = low + math.floor(m1 / 16 +) m1 =m1- (math.floor((m1 + 62) / 64)) * 2 + else + low =low+ (math.floor(m1 / 16 )+ 1 +) m1 =m1+ (math.floor((m1 + 64) / 64)) * 5 + if ones == 2 then + high = low + math.floor(m2 / 16 +) m2 =m2- (math.floor((m2 + 30) / 32)) * 2 + else + low =low+ (ones - 2) * (math.floor(m2 / 16 )+ 1) + high = low + math.floor(m2 / 16 +) m2 =m2+ (math.floor((m2 + 32) / 32)) * 5 + end + end + end + med[mb + 1], med[mb + 2], med[mb + 3] = m0 % TWO32, m1 % TWO32, m2 % TWO32 + low = band(low % TWO32, 0x7FFFFFFF) + high = band(high % TWO32, 0x7FFFFFFF) + if low > high then + high = low + end + local mid = math.floor((high + low + 1) / 2 +) local limit = st.limit[chan + 1] + if limit == 0 then + mid = readCode(R, high - low) + low + else + while high - low > limit do + if R.p > R.e then + return nil, 0 + end + if bits(R, 1) == 1 then + low = mid + mid = math.floor((high + low + 1) / 2 +) else + high = mid - 1 + mid = math.floor((high + low + 1) / 2 +) end + end + end + local sign = bits(R, 1) + if st.wvc and limit ~= 0 then + local value = readCode(st.R2, high - low) + low + correction = (sign == 1 and((mid - value ))or((value - mid +))) end + if band(flags, HBITRATE) ~= 0 then + local s = st.slow + s[chan + 1] = s[chan + 1] - math.floor((s[chan + 1] + 128) / 256 )+ log2(mid) + end + return (sign == 1 and((-mid - 1 ))or(mid)), correction +end + +-- ------------------------------------------------------------------------------------------------ decorrelation +-- the decorrelation passes over the whole block (stereo, from W[D2]): unpack.c decorr_stereo_pass +local function passesStereo(st, n) + local W = st.W + local last = D2 + 2 * n - 2 + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + for t = 1, st.nterms do + local term, delta, wA, wB = terms[t], deltas[t], wAs[t], wBs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1, b0, b1 = sA[so + 1], sA[so + 2], sB[so + 1], sB[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D2, last, 2 do + local sam = a0 + math.floor((a0 - a1) / dv +) local x = W[i] + local o = math.floor((wA * sam + 512) / 1024 )+ x + wA =wA+ delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + sam = b0 + math.floor((b0 - b1) / dv +) x = W[i + 1] + o = math.floor((wB * sam + 512) / 1024 )+ x + wB =wB+ delta * sign(sam * x) + b1, b0 = b0, o + W[i + 1] = o + end + elseif term > 0 then + for j = 0, term - 1 do + W[D2 + 2 * (j - term)] = sA[so + j + 1] + W[D2 + 1 + 2 * (j - term)] = sB[so + j + 1] + end + local back = 2 * term + for i = D2, last, 2 do + local sam = W[i - back] + local x = W[i] + W[i] = math.floor((wA * sam + 512) / 1024 )+ x + wA =wA+ delta * sign(sam * x) + sam = W[i + 1 - back] + x = W[i + 1] + W[i + 1] = math.floor((wB * sam + 512) / 1024 )+ x + wB =wB+ delta * sign(sam * x) + end + elseif term == -1 then + local sa = sA[so + 1] + for i = D2, last, 2 do + local x = W[i] + local sam = x + math.floor((wA * sa + 512) / 1024 +) wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + W[i] = sam + x = W[i + 1] + sa = x + math.floor((wB * sam + 512) / 1024 +) wB = clamp(wB + delta * sign(sam * x), -1024, 1024) + W[i + 1] = sa + end + elseif term == -2 then + local sb = sB[so + 1] + for i = D2, last, 2 do + local x = W[i + 1] + local sam = x + math.floor((wB * sb + 512) / 1024 +) wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i + 1] = sam + x = W[i] + sb = x + math.floor((wA * sam + 512) / 1024 +) wA = clamp(wA + delta * sign(sam * x), -1024, 1024) + W[i] = sb + end + else -- -3 + local sa, sb = sA[so + 1], sB[so + 1] + for i = D2, last, 2 do + local x = W[i] + local samA = x + math.floor((wA * sa + 512) / 1024 +) wA = clamp(wA + delta * sign(sa * x), -1024, 1024) + x = W[i + 1] + local samB = x + math.floor((wB * sb + 512) / 1024 +) wB = clamp(wB + delta * sign(sb * x), -1024, 1024) + W[i], W[i + 1] = samA, samB + sa, sb = samB, samA + end + end + end +end + +-- the decorrelation passes (mono, from W[D1]): unpack.c decorr_mono_pass +local function passesMono(st, n) + local W = st.W + local last = D1 + n - 1 + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + for t = 1, st.nterms do + local term, delta, wA = terms[t], deltas[t], wAs[t] + local so = (t - 1) * 8 + if term > 8 then + local a0, a1 = sA[so + 1], sA[so + 2] + local dv = term - 16 -- 17: 2 a0 - a1, 18: a0 + (a0 - a1) / 2 + for i = D1, last do + local sam = a0 + math.floor((a0 - a1) / dv +) local x = W[i] + local o = math.floor((wA * sam + 512) / 1024 )+ x + wA =wA+ delta * sign(sam * x) + a1, a0 = a0, o + W[i] = o + end + else + for j = 0, term - 1 do + W[D1 + j - term] = sA[so + j + 1] + end + for i = D1, last do + local sam = W[i - term] + local x = W[i] + W[i] = math.floor((wA * sam + 512) / 1024 )+ x + wA =wA+ delta * sign(sam * x) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ hybrid lossless +local function shaped(st, c, flags, correction) -- returns the value to subtract (temp) and updates the error state (noise shaping, unpack.c) + +local sacc, sdelta, err = st.sacc, st.sdelta, st.err + sacc[c] = (sacc[c] + sdelta[c]) % TWO32 + local sw = math.floor(sacc[c] / 65536 +) if sw >= 32768 then + sw =sw- 65536 + end + local temp = -(math.floor((sw * err[c] + 512) / 1024)) + if band(flags, NEW_SHAPING) ~= 0 and sw < 0 and temp ~= 0 then + if temp == err[c] then + temp = (temp < 0 and((temp + 1 ))or((temp - 1 +))) end + err[c] = temp - correction + else + err[c] = -correction + end + return temp +end + +local function hybridMono(st, n, flags) +local W = st.W + local terms, deltas, wAs, sA = st.term, st.delta, st.wA, st.sA + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + for i = 0, n - 1 do + local word, corr = getWord(st, 0, flags, true) + if not word then + return false + end + local rw = word + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + local sam, k + if term > 8 then + sam = (term % 2 == 1 and((2 * sA[so + 1] - sA[so + 2] ))or((math.floor((3 * sA[so + 1] - sA[so + 2]) / 2 +)))) sA[so + 2] = sA[so + 1] + k = 0 + else + sam = sA[so + m + 1] + k = band(m + term, 7) + end + local temp = math.floor((wAs[t] * sam + 512) / 1024 )+ rw + wAs[t]=wAs[t]+ deltas[t] * sign(sam * rw) + sA[so + k + 1] = temp + rw = temp + end + m = band(m + 1, 7) + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, corr) + rw =rw+ (corr - temp +) else + rw =rw+ corr + end + crc = (crc * 3 + rw) % TWO32 + W[D1 + i] = rw + end + st.crcv = crc + return true +end + +local function hybridStereo(st, n, flags) +local W = st.W + local terms, deltas, wAs, wBs, sA, sB = st.term, st.delta, st.wA, st.wB, st.sA, st.sB + local nterms = st.nterms + local m = 0 + local crc = TWO32 - 1 + local cross = band(flags, CROSS) ~= 0 + local joint = band(flags, JOINT) ~= 0 + for i = 0, n - 1 do + local left, corr0 = getWord(st, 0, flags, false) + if not left then + return false + end + local right, corr1 = getWord(st, 1, flags, false) + if not right then + return false + end + local leftc, rightc = 0, 0 + if cross then + leftc, rightc = left + corr0, right + corr1 + for t = 1, nterms do + local term, so = terms[t], (t - 1) * 8 + if term > 0 then + local samA, samB + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = math.floor((3 * sA[so + 1] - sA[so + 2]) / 2 +) samB = math.floor((3 * sB[so + 1] - sB[so + 2]) / 2 +) end + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + end + leftc =leftc+ math.floor((wAs[t] * samA + 512) / 1024 +) rightc =rightc+ math.floor((wBs[t] * samB + 512) / 1024 +) elseif term == -1 then + leftc =leftc+ math.floor((wAs[t] * sA[so + 1] + 512) / 1024 +) rightc =rightc+ math.floor((wBs[t] * leftc + 512) / 1024 +) else + rightc =rightc+ math.floor((wBs[t] * sB[so + 1] + 512) / 1024 +) if term == -3 then + leftc =leftc+ math.floor((wAs[t] * sA[so + 1] + 512) / 1024 +) else + leftc =leftc+ math.floor((wAs[t] * rightc + 512) / 1024 +) end + end + end + if joint then + rightc =rightc- math.floor(leftc / 2 +) leftc =leftc+ rightc + end + end + for t = 1, nterms do + local term, delta, so = terms[t], deltas[t], (t - 1) * 8 + if term > 0 then + local samA, samB, k + if term > 8 then + if term % 2 == 1 then + samA = 2 * sA[so + 1] - sA[so + 2] + samB = 2 * sB[so + 1] - sB[so + 2] + else + samA = math.floor((3 * sA[so + 1] - sA[so + 2]) / 2 +) samB = math.floor((3 * sB[so + 1] - sB[so + 2]) / 2 +) end + sA[so + 2] = sA[so + 1] + sB[so + 2] = sB[so + 1] + k = 0 + else + samA, samB = sA[so + m + 1], sB[so + m + 1] + k = band(m + term, 7) + end + local left2 = math.floor((wAs[t] * samA + 512) / 1024 )+ left + local right2 = math.floor((wBs[t] * samB + 512) / 1024 )+ right + wAs[t]=wAs[t]+ delta * sign(samA * left) + wBs[t]=wBs[t]+ delta * sign(samB * right) + left, right = left2, right2 + sA[so + k + 1], sB[so + k + 1] = left, right + elseif term == -1 then + local sa = sA[so + 1] + local left2 = left + math.floor((wAs[t] * sa + 512) / 1024 +) wAs[t] = clamp(wAs[t] + delta * sign(sa * left), -1024, 1024) + left = left2 + local right2 = right + math.floor((wBs[t] * left2 + 512) / 1024 +) wBs[t] = clamp(wBs[t] + delta * sign(left2 * right), -1024, 1024) + right = right2 + sA[so + 1] = right + else + local sb = sB[so + 1] + local right2 = right + math.floor((wBs[t] * sb + 512) / 1024 +) wBs[t] = clamp(wBs[t] + delta * sign(sb * right), -1024, 1024) + right = right2 + if term == -3 then + right2 = sA[so + 1] + sA[so + 1] = right + end + local left2 = left + math.floor((wAs[t] * right2 + 512) / 1024 +) wAs[t] = clamp(wAs[t] + delta * sign(right2 * left), -1024, 1024) + left = left2 + sB[so + 1] = left + end + end + m = band(m + 1, 7) + if not cross then + leftc, rightc = left + corr0, right + corr1 + if joint then + rightc =rightc- math.floor(leftc / 2 +) leftc =leftc+ rightc + end + end + if joint then + right =right- math.floor(left / 2 +) left =left+ right + end + if band(flags, SHAPE) ~= 0 then + local temp = shaped(st, 1, flags, leftc - left) + left = leftc - temp + temp = shaped(st, 2, flags, rightc - right) + right = rightc - temp + else + left, right = leftc, rightc + end + crc = (crc * 9 + left * 3 + right) % TWO32 + W[D2 + 2 * i], W[D2 + 2 * i + 1] = left, right + end + st.crcv = crc + return true +end + +-- ------------------------------------------------------------------------------------------------ metadata -> state +local function readMeta(st, buf, m, flags, version) +local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local o = m[2] + if o then -- decorrelation terms + local cnt = m[2 + 256] + if cnt > 16 then + return "too many decorrelation terms" + end + st.nterms = cnt + for i = 0, cnt - 1 do + local v = readu8(buf, o + i) + local t = cnt - i + local term = band(v, 0x1F) - 5 + if term == 0 or term < -3 or (term > 8 and term < 17) or term > 18 or (mono and term < 0) then + return "bad decorrelation term" + end + st.term[t] = term + st.delta[t] = band(rshift(v, 5), 7) + end + end + local nterms = st.nterms + o = m[3] + if o then -- weights, from the last pass back + for t = 1, nterms do + st.wA[t], st.wB[t] = 0, 0 + end + local cnt = m[3 + 256] + if not mono then + cnt =math.floor(cnt/ 2 +) end + if cnt > nterms then + return "too many decorrelation weights" + end + local q = o + for t = nterms, nterms - cnt + 1, -1 do + st.wA[t] = restoreWeight(readi8(buf, q)) + q =q+ 1 + if not mono then + st.wB[t] = restoreWeight(readi8(buf, q)) + q =q+ 1 + end + end + end + local sA, sB = st.sA, st.sB + o = m[4] + if o then -- decorrelation samples, from the last pass back + for k = 1, nterms * 8 do + sA[k], sB[k] = 0, 0 + end + local q, stop = o, o + m[4 + 256] + if version == 0x402 and band(flags, HYBRID) ~= 0 then + if q + (mono and 2 or 4) > stop then + return "bad decorrelation samples" + end + st.err[1] = exp2s(readi16(buf, q)) + q =q+ 2 + if not mono then + st.err[2] = exp2s(readi16(buf, q)) + q =q+ 2 + end + end + local t = nterms + while t >= 1 and q < stop do + local term, so = st.term[t], (t - 1) * 8 + if term > 8 then + if q + (mono and 4 or 8) > stop then + return "bad decorrelation samples" + end + sA[so + 1], sA[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q =q+ 4 + if not mono then + sB[so + 1], sB[so + 2] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q =q+ 4 + end + elseif term < 0 then + if q + 4 > stop then + return "bad decorrelation samples" + end + sA[so + 1], sB[so + 1] = exp2s(readi16(buf, q)), exp2s(readi16(buf, q + 2)) + q =q+ 4 + else + for k = 1, term do + if q + (mono and 2 or 4) > stop then + return "bad decorrelation samples" + end + sA[so + k] = exp2s(readi16(buf, q)) + q =q+ 2 + if not mono then + sB[so + k] = exp2s(readi16(buf, q)) + q =q+ 2 + end + end + end + t =t- 1 + end + if q ~= stop then + return "bad decorrelation samples" + end + end + o = m[5] + if o then -- entropy medians + if m[5 + 256] ~= (mono and 6 or 12) then + return "bad entropy variables" + end + for k = 0, (mono and 2 or 5) do + st.med[k + 1] = exp2s(readu16(buf, o + k * 2)) % TWO32 + end + end + o = m[6] + if o then -- hybrid profile + local q, stop = o, o + m[6 + 256] + local w = mono and 2 or 4 + if band(flags, HBITRATE) ~= 0 then + if q + w > stop then + return "bad hybrid profile" + end + st.slow[1] = exp2s(readu16(buf, q)) % TWO32 + if not mono then + st.slow[2] = exp2s(readu16(buf, q + 2)) % TWO32 + end + q =q+ w + end + if q + w > stop then + return "bad hybrid profile" + end + st.bacc[1] = readu16(buf, q) * 65536 + if not mono then + st.bacc[2] = readu16(buf, q + 2) * 65536 + end + q =q+ w + if q < stop then + if q + w > stop then + return "bad hybrid profile" + end + st.bdelta[1] = exp2s(readi16(buf, q)) + if not mono then + st.bdelta[2] = exp2s(readi16(buf, q + 2)) + end + q =q+ w + if q < stop then + return "bad hybrid profile" + end + end + end + o = m[7] + if o then -- noise shaping + local len = m[7 + 256] + if len == 2 then + st.sacc[1] = (restoreWeight(readi8(buf, o)) * 65536) % TWO32 + st.sacc[2] = (restoreWeight(readi8(buf, o + 1)) * 65536) % TWO32 + elseif len >= (mono and 4 or 8) then + st.err[1] = exp2s(readi16(buf, o)) + st.sacc[1] = exp2s(readi16(buf, o + 2)) % TWO32 + if not mono then + st.err[2] = exp2s(readi16(buf, o + 4)) + st.sacc[2] = exp2s(readi16(buf, o + 6)) % TWO32 + end + local q = o + (mono and 4 or 8) + if len == (mono and 6 or 12) then + st.sdelta[1] = exp2s(readi16(buf, q)) % TWO32 + if not mono then + st.sdelta[2] = exp2s(readi16(buf, q + 2)) % TWO32 + end + end + else + return "bad shaping weights" + end + end + o = m[8] + if o then + if m[8 + 256] ~= 4 then + return "bad float info" + end + st.fflags, st.fshift, st.fmaxexp = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2) + end + o = m[9] + if o then + if m[9 + 256] ~= 4 then + return "bad int32 info" + end + st.isent, st.izeros, st.iones, st.idups = readu8(buf, o), readu8(buf, o + 1), readu8(buf, o + 2), readu8(buf, o + 3) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ fixup + output +-- the float conversion of one value (float_values; R = the wvx stream or nil) +local function floatValue(st, v, R) +local fflags, exp = st.fflags, st.fmaxexp + local mant, e, sign = 0, 0, 0 + if v == 0 then + if R then + if band(fflags, FLOAT_ZEROS_SENT) ~= 0 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + if exp >= 25 then + e = bits(R, 8) + end + sign = bits(R, 1) + elseif band(fflags, FLOAT_NEG_ZEROS) ~= 0 then + sign = bits(R, 1) + end + end + end + else + v = (v * P2[band(st.fshift, 31) + 1]) % TWO32 + if v >= 2147483648 then + v =v- TWO32 + end + if v < 0 then + v = -v + sign = 1 + end + if R then + if v == 0x1000000 then + if bits(R, 1) == 1 then + mant = bits(R, 23) + end + e = 255 + else + local shift = 0 + if exp > 0 then + while v < 0x800000 do + exp =exp- 1 + if exp == 0 then + break + end + shift =shift+ 1 + v =v* 2 + end + end + shift = band(shift, 31) + if shift > 0 then + if band(fflags, FLOAT_SHIFT_ONES) ~= 0 or (band(fflags, FLOAT_SHIFT_SAME) ~= 0 and bits(R, 1) == 1) then + v =v+ (P2[shift + 1] - 1 +) elseif band(fflags, FLOAT_SHIFT_SENT) ~= 0 then + local mask = P2[shift + 1] - 1 + local zeros = 0 + local maxOnes, minZeros = st.fmaxones, st.fminzeros + if maxOnes > 0 and shift > maxOnes then + zeros = shift - maxOnes + end + if minZeros > zeros then + zeros = (minZeros > shift and{shift }or{minZeros +})[1] end + local sc = shift - zeros + if sc > 0 then + v = bit32.bor(v % TWO32, band(bits(R, sc) * P2[zeros + 1], mask)) + end + end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + else + if v >= 0x1000000 then + while band(v, 0xF000000) ~= 0 do + v =math.floor(v/ 2 +) exp =exp+ 1 + end + elseif exp > 0 then + local shift = 0 + while v < 0x800000 do + exp =exp- 1 + if exp == 0 then + break + end + shift =shift+ 1 + v =v* 2 + end + shift = band(shift, 31) + if shift > 0 and band(fflags, FLOAT_SHIFT_ONES) ~= 0 then + v =v+ (P2[shift + 1] - 1 +) end + end + mant = band(v % TWO32, 0x7FFFFF) + e = band(exp, 255) + end + end + if R then + st.crcx = (st.crcx * 27 + mant * 9 + e * 3 + sign) % TWO32 + end + local sc = st.scratch + writeu32(sc, 0, sign * 2147483648 + e * 8388608 + mant) + return readf32(sc, 0) +end + +-- emit: fixup_samples + false stereo + interleave into P (stride C, first channel c0 0-based) +local function emit(st, flags, n, d, P, c0, C, lossy) + local W = st.W + local s = d == D2 and 2 or 1 + local count = n * s + local R= (st.wvx and{st.R3 }or{nil +})[1] if band(flags, FLOAT) ~= 0 then + for k = 0, count - 1 do + W[d + k] = floatValue(st, W[d + k], R) + end + else + local shift = band(rshift(flags, 13), 31) + if band(flags, INT32) ~= 0 then + local sent, zeros, ones, dups = band(st.isent, 31), band(st.izeros, 31), band(st.iones, 31), band(st.idups, 31) + if R then + local maxw = st.imaxw + local crc = st.crcx + for k = d, d + count - 1 do + local v = W[k] + if sent > 0 then + if maxw > 0 then + local pv = (v < 0 and((-v - 1 ))or(v +)) local width = (32 - countlz(pv)) + sent + local btr = sent + if width > maxw then + btr =btr- (width - maxw +) end + if width <= maxw or btr > 0 then + v = (v * P2[btr + 1] + bits(R, btr)) * P2[sent - btr + 1] + else + v =v* P2[sent + 1] + end + else + v = v * P2[sent + 1] + bits(R, sent) + end + end + if zeros > 0 then + v =v* P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + v =v% TWO32 + if v >= 2147483648 then + v =v- TWO32 + end + crc = (crc * 9 + (v % 65536) * 3 + (math.floor(v / 65536)) % 65536) % TWO32 + W[k] = v + end + st.crcx = crc + elseif sent == 0 and zeros + ones + dups > 0 then + while lossy and band(flags, 3) == 3 and shift < 8 do + if zeros > 0 then + zeros =zeros- 1 + elseif ones > 0 then + ones =ones- 1 + elseif dups > 0 then + dups =dups- 1 + else + break + end + shift =shift+ 1 + end + for k = d, d + count - 1 do + local v = W[k] + if zeros > 0 then + v =v* P2[zeros + 1] + elseif ones > 0 then + v = (v + 1) * P2[ones + 1] - 1 + elseif dups > 0 then + local lo = v % 2 + v = (v + lo) * P2[dups + 1] - lo + end + W[k] = v + end + else + shift =shift+ (zeros + sent + ones + dups +) end + end + shift = band(shift, 31) + if lossy then + local bytes = band(flags, 3) + local top = bytes == 0 and 127 or(bytes == 1 and 32767 or(bytes == 2 and 8388607 or 2147483647 +)) local minv, maxv = math.floor((-top - 1) / P2[shift + 1]), math.floor(top / P2[shift + 1] +) local mul = P2[shift + 1] + for k = d, d + count - 1 do + local v = W[k] + if v < minv then + v = minv + elseif v > maxv then + v = maxv + end + W[k] = v * mul + end + elseif shift > 0 then + local mul = P2[shift + 1] + for k = d, d + count - 1 do + W[k]=W[k]* mul + end + end + end + -- interleave + if s == 2 then + if c0 == 0 and C == 2 then + for k = 0, count - 1 do + P[k + 1] = W[d + k] + end + elseif c0 + 2 <= C then + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + P[i * C + c0 + 2] = W[d + 2 * i + 1] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + 2 * i] + end + end + elseif band(flags, FALSE_STEREO) ~= 0 and c0 + 2 <= C then + for i = 0, n - 1 do + local v = W[d + i] + P[i * C + c0 + 1] = v + P[i * C + c0 + 2] = v + end + elseif C == 1 then + for k = 0, n - 1 do + P[k + 1] = W[d + k] + end + else + for i = 0, n - 1 do + P[i * C + c0 + 1] = W[d + i] + end + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(st, buf, p, size, P, c0, C, cbuf?, cp?, csize?) -> channels written (1 / 2) | nil, message: the block at p +-- (header included in size) into P (interleaved, stride C, from channel c0), with its correction block if given +function Block.decode(st, buf, p, size, P, c0, C, cbuf, cp, csize) +local version = readu16(buf, p + 8) + local n = readu32(buf, p + 20) + local flags = readu32(buf, p + 24) + local crcWant = readu32(buf, p + 28) + if band(flags, DSD) ~= 0 then + return nil, "unsupported: DSD audio" + end + if version < 0x402 or version > 0x410 then + return nil, "unsupported: stream version " .. version + end + if n > MAX_SAMPLES then + return nil, "limit: block of " .. n .. " samples" + end + if band(flags, MONO_FLAG + FALSE_STEREO) == MONO_FLAG + FALSE_STEREO then + return nil, "bad block flags" + end + local mm, merr = Block.meta(buf, p, size) + if not mm then + return nil, merr + end + local m= mm + local cm= {} + local cb= buf + local hasC = false + if cbuf and cp and csize then + local cmeta, cerr = Block.meta(cbuf, cp, csize) + if not cmeta then + return nil, cerr + end + cm, cb, hasC = cmeta, cbuf, true + crcWant = readu32(cbuf, cp + 28) + end + -- reset + st.nterms = 0 + local sA, sB, wA, wB = st.sA, st.sB, st.wA, st.wB + for k = 1, 128 do + sA[k], sB[k] = 0, 0 + end + for t = 1, 16 do + wA[t], wB[t] = 0, 0 + end + local med = st.med + for k = 1, 6 do + med[k] = 0 + end + st.slow[1], st.slow[2], st.limit[1], st.limit[2] = 0, 0, 0, 0 + st.bacc[1], st.bacc[2], st.bdelta[1], st.bdelta[2] = 0, 0, 0, 0 + st.sacc[1], st.sacc[2], st.sdelta[1], st.sdelta[2], st.err[1], st.err[2] = 0, 0, 0, 0, 0, 0 + st.fflags, st.fshift, st.fmaxexp, st.fminzeros, st.fmaxones = 0, 0, 0, 0, 0 + st.isent, st.izeros, st.iones, st.idups, st.imaxw = 0, 0, 0, 0, 0 + st.hz, st.ho, st.za = 0, 0, 0 + st.crcx = TWO32 - 1 + st.wvc, st.wvx = false, false + local e = readMeta(st, buf, m, flags, version) + if e then + return nil, e + end + if hasC then + e = readMeta(st, cb, cm, flags, version) + if e then + return nil, e + end + end + local mono = band(flags, MONO_FLAG + FALSE_STEREO) ~= 0 + local out = band(flags, MONO_FLAG) ~= 0 and 1 or 2 + if n == 0 then + return out, nil + end + -- bitstreams + local o = m[0xA] + if not o or m[0xA + 256] == 0 or m[0xA + 256] % 2 == 1 then + return nil, "no audio bitstream" + end + openReader(st.R1, buf, o, m[0xA + 256]) + if hasC then + local co = cm[0xB] + if co and cm[0xB + 256] > 0 and cm[0xB + 256] % 2 == 0 then + openReader(st.R2, cb, co, cm[0xB + 256]) + st.wvc = true + end + end + -- the wvx stream: in the wv block (pure lossless) or the wvc block (hybrid lossless) + local xb, xm = buf, m + if hasC and (cm[0xC] or cm[0x2C]) then + xb, xm = cb, cm + end + local xid = xm[0x2C] and 0x2C or(xm[0xC] and 0xC or nil +) if xid then + local xo, xl = xm[xid], xm[xid + 256] + if xl <= 4 or xl % 2 == 1 then + return nil, "bad wvx bitstream" + end + st.crcwvx = readu32(xb, xo) + openReader(st.R3, xb, xo + 4, xl - 4) + st.wvx = true + if xid == 0x2C then + if band(flags, FLOAT) ~= 0 then + st.fminzeros = bits(st.R3, 5) + st.fmaxones = bits(st.R3, 5) + else + st.imaxw = bits(st.R3, 5) + end + end + end + local hybrid = band(flags, HYBRID) ~= 0 + local d = (mono and{D1 }or{D2 +})[1] local W = st.W + if #W < d + 2 * n then + W = table.create(d + 2 * n + 64, 0) + st.W = W + end + local crc = TWO32 - 1 + if not st.wvc then + if hybrid then + if mono then + for i = 0, n - 1 do + local v = getWord(st, 0, flags, true) + if not v then + return nil, "bad audio bitstream" + end + W[d + i] = v + end + else + for i = 0, n - 1 do + local l = getWord(st, 0, flags, false) + local r = l and getWord(st, 1, flags, false) + if not l or not r then + return nil, "bad audio bitstream" + end + W[d + 2 * i], W[d + 2 * i + 1] = l, r + end + end + elseif not wordsLossless(st, (mono and{n }or{(2 * n)})[1], d) then + return nil, "bad audio bitstream" + end + if mono then + passesMono(st, n) + for k = d, d + n - 1 do + crc = (crc * 3 + W[k]) % TWO32 + end + else + passesStereo(st, n) + local last = d + 2 * n - 2 + if band(flags, JOINT) ~= 0 then + for k = d, last, 2 do + local l = W[k] + local r = W[k + 1] - math.floor(l / 2 +) l =l+ r + W[k], W[k + 1] = l, r + crc = (crc * 9 + l * 3 + r) % TWO32 + end + else + for k = d, last, 2 do + crc = (crc * 9 + W[k] * 3 + W[k + 1]) % TWO32 + end + end + end + else + local ok = (mono and{(hybridMono(st, n, flags) )}or{(hybridStereo(st, n, flags) +)})[1] if not ok then + return nil, "bad audio bitstream" + end + crc = st.crcv + end + if st.R1.p > st.R1.e or (st.wvc and st.R2.p > st.R2.e) then + return nil, "truncated audio bitstream" + end + if crc ~= crcWant then + return nil, "checksum: block CRC mismatch" + end + emit(st, flags, n, d, P, c0, C, hybrid and not st.wvc) + if st.wvx and (st.R3.p > st.R3.e or st.crcx ~= st.crcwvx) then + return nil, "checksum: wvx CRC mismatch" + end + return out, nil +end + +Block.bits = bits +Block.bit = bit + +return Block +end +__FILES["codecs/audio/WavPack/Tables"] = function() +local __compat = __compat local bit32 = __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/audio/WavPack/Tables: the WavPack log2 / exp2 tables and the conversions built on them (wp_log2, wp_exp2s, +-- restore_weight). Ported from WavPack 5.9.0 entropy_utils.c (David Bryant, BSD 3-clause, licenses/wavpack-LICENSE.txt). +local band, rshift, lshift, countlz = bit32.band, bit32.rshift, bit32.lshift, bit32.countlz + +local Tables = {} + +-- LOG2[x + 1], EXP2[x + 1] for x = 0 .. 255 +local LOG2= { + 0, 1, 3, 4, 6, 7, 9, 10, 11, 13, 14, 16, 17, 18, 20, 21, 22, 24, 25, 26, 28, 29, 30, 32, 33, 34, 36, 37, 38, 40, 41, 42, + 44, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 57, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 77, 78, 79, 80, 81, + 82, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 178, + 179, 180, 181, 182, 183, 184, 185, 185, 186, 187, 188, 189, 190, 191, 192, 192, 193, 194, 195, 196, 197, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 208, 209, 210, 211, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 228, 228, 229, 230, 231, 231, + 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 249, 250, 251, 252, 252, 253, 254, 255, 255, +} +local EXP2= { + 0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 15, 16, 16, 17, 18, 19, 19, 20, 21, 22, 22, + 23, 24, 25, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 44, 45, 46, 47, 48, + 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 137, 138, + 139, 140, 141, 142, 143, 144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157, 159, 160, 161, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 173, + 175, 176, 177, 178, 179, 180, 182, 183, 184, 185, 186, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, + 214, 215, 216, 217, 219, 220, 221, 222, 224, 225, 226, 228, 229, 230, 232, 233, 234, 236, 237, 238, 240, 241, 242, 244, 245, 246, 248, 249, 250, 252, 253, 255, +} + +-- exp2s(log) -> the int32 the signed log stands for (wp_exp2s) +function Tables.exp2s(lg) +if lg < 0 then + local v = Tables.exp2s(-lg) + v = -((v >= 2147483648 and((v - 4294967296 ))or(v))) + return (v >= 2147483648 and((v - 4294967296 ))or(v +)) end + local value = bit32.bor(EXP2[band(lg, 255) + 1], 0x100) + local k = math.floor(lg / 256 +) local r = (k <= 9 and{(rshift(value, 9 - k) )}or{(lshift(value, band(k - 9, 31)) +)})[1] return (r >= 2147483648 and((r - 4294967296 ))or(r +))end + +-- log2(v) -> wp_log2 of the uint32 v +function Tables.log2(v) +v = (v + rshift(v, 9)) % 4294967296 + if v < 256 then + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(lshift(v, 9 - dbits), 255) + 1] + end + local dbits = 32 - countlz(v) + return dbits * 256 + LOG2[band(rshift(v, dbits - 9), 255) + 1] +end + +-- restoreWeight(signed byte) -> the decorrelation weight (restore_weight) +function Tables.restoreWeight(w) +local r = w * 8 + if r > 0 then + r =r+ math.floor((r + 64) / 128 +) end + return r +end + +return Tables +end +__FILES["codecs/compress/Brotli"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- 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("rosetta.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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") +local Decode = __include("codecs/compress/Brotli/Decode") +local StaticData = __include("codecs/compress/Brotli/Static") + +local Brotli = {} + +-- ------------------------------------------------------------------------------------------------ static data +-- the tables are base64 text (trusted, generated by tools/brotli_static.py) + + + + + +local function unbase64(s) +return Base64.decode(s) or buffer.create(0) +end + +local static= nil + +-- tables() -> the decoded static data (inflated once, on first use) +local function tables() +if static then + return static, nil + end + local z = unbase64(table.concat(StaticData.dictionary)) + local dict, err = Deflate.zlib(z, 0, nil, StaticData.dictionarySize) + if not dict then + return nil, err + end + if Crc32.of(dict) ~= StaticData.dictionaryCrc then + return nil, Err.new(Err.CHECKSUM, "brotli: static dictionary damaged") + end + static = { + dictionary = dict, + context = unbase64(table.concat(StaticData.context)), + prefixSuffix = unbase64(StaticData.prefixSuffix), + prefixSuffixMap = StaticData.prefixSuffixMap, + transforms = StaticData.transforms, + } + return static, nil +end + +-- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders) +function Brotli.dictionary() +local s = tables() + return (s and{s.dictionary }or{nil +})[1]end + +-- ------------------------------------------------------------------------------------------------ decompress + +-- 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, offset, length, opts) +local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes and{opts.maxBytes }or{(2 ^ 30 +)})[1] if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes") + end + local large = not (opts and opts.largeWindow == false) + if l == 0 then + return nil, Err.new(Err.TRUNCATED, "brotli: empty input", o) + end + local S, serr = tables() + if not S then + return nil, serr + end + local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large) + if not out then + local e = Err.from(size, o) + e.message = "brotli: " .. e.message + return nil, e + end + local res = out + if buffer.len(out) ~= size then + res = buffer.create(size) + buffer.copy(res, 0, out, 0, size) + end + return res, consumed +end + +return Brotli +end +__FILES["codecs/compress/Brotli/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 +-- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and +-- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words. +-- +-- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next +-- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits. +-- +-- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each +-- meta-block before it is decoded); bad data returns nil, message. +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 } +local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 } +local BL_OFF = { + 1, 5, 9, 13, 17, 25, 33, 41, 49, 65, 81, 97, 113, 145, 177, 209, 241, 305, 369, 497, 753, 1265, 2289, 4337, 8433, 16625, +} +local BL_BITS = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 24 } +local INS_BASE = { 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578, 1090, 2114, 6210, 22594 } +local INS_EXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24 } +local CPY_BASE = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 18, 22, 30, 38, 54, 70, 102, 134, 198, 326, 582, 1094, 2118 } +local CPY_EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24 } +local CELL_INS = { 0, 0, 0, 0, 8, 8, 0, 16, 8, 16, 16 } +local CELL_CPY = { 0, 8, 0, 8, 0, 8, 16, 0, 16, 8, 16 } +-- static dictionary: bits of the word index per word length 0..24 (index + 1), and the offsets +local NDBITS = { 0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5 } +local DOFF = table.create(25, 0) +do + local o = 0 + for l = 4, 24 do + DOFF[l + 1] = o + o =o+ l * 2 ^ NDBITS[l + 1] + end +end +local NTRANSFORMS = 121 +local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC + +-- 8-bit reversal +local REV8 = bcreate(256) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = math.floor(v / 2 +) end + writeu8(REV8, i, r) +end +local function reverse(code, len) -- len <= 15 + +local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255)) + return rshift(r, 16 - len) +end + +-- ------------------------------------------------------------------------------------------------ prefix tables +local count = table.create(16, 0) +local nextc = table.create(16, 0) +local subBits = table.create(256, 0) +local subOff = table.create(256, 0) + +-- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set. +-- Also leaves count / nextc / subBits ready for build(). +local function prepare(lens, n) +for l = 1, 16 do + count[l] = 0 + end + local used = 0 + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + count[l]=count[l]+ 1 + used =used+ 1 + end + end + if used <= 1 then + return 256 + end + local left = 1 + for l = 1, 15 do + left = left * 2 - count[l] + if left < 0 then + return -1 + end + end + -- canonical codes: the first code of length l is (first(l - 1) + count(l - 1)) * 2 + local code = 0 + for l = 1, 15 do + nextc[l] = code + code = (code + count[l]) * 2 + end + for i = 1, 256 do + subBits[i] = 0 + end + local nc = table.clone(nextc) + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 8 then + local c = nc[l] + nc[l] = c + 1 + local pre = band(reverse(c, l), 255) + local k = l - 8 + if k > subBits[pre + 1] then + subBits[pre + 1] = k + end + elseif l > 0 then + nc[l]=nc[l]+ 1 + end + end + local size = 256 + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + subOff[i] = size + size =size+ lshift(1, k) + end + end + return size +end + +-- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room) +local function build(lens, n, T, at) + local single = -1 + local used = 0 + for s = 0, n - 1 do + if readu8(lens, s) > 0 then + used =used+ 1 + single = s + end + end + if used <= 1 then + local e = (single < 0 and 0 or single) * 32 + for i = 0, 255 do + writeu32(T, (at + i) * 4, e) + end + return + end + for i = 1, 256 do + local k = subBits[i] + if k > 0 then + writeu32(T, (at + i - 1) * 4, subOff[i] * 32 + 16 + k) + end + end + for s = 0, n - 1 do + local l = readu8(lens, s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local rev = reverse(c, l) + local e = s * 32 + l + if l <= 8 then + local step = lshift(1, l) + local i = rev + while i < 256 do + writeu32(T, (at + i) * 4, e) + i =i+ step + end + else + local pre = band(rev, 255) + local sb = subBits[pre + 1] + local base = at + subOff[pre + 1] + local step = lshift(1, l - 8) + local i = rshift(rev, 8) + local lim = lshift(1, sb) + while i < lim do + writeu32(T, (base + i) * 4, e) + i =i+ step + end + end + end + end +end + +-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference +-- decoder's BrotliCalculateDistanceCodeLimit +local function distanceLimit(maxDistance, npostfix, ndirect) +if maxDistance <= ndirect then + return maxDistance + 16 + end + local offset = maxDistance + 1 - ndirect - 1 + offset = rshift(offset, npostfix) + 4 + local ndistbits = 0 + local tmp = math.floor(offset / 2 +) while tmp ~= 0 do + ndistbits =ndistbits+ 1 + tmp = rshift(tmp, 1) + end + ndistbits =ndistbits- 1 + local half = band(rshift(offset, ndistbits), 1) + local group = bor(lshift(ndistbits - 1, 1), half) + if group == 0 then + return ndirect + 16 + end + group =group- 1 + local postfix = lshift(1, npostfix) - 1 + return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1 +end + +-- ------------------------------------------------------------------------------------------------ decoder +-- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message +function Decode.decompress(src, off, len, maxBytes, S, largeWindow) +local lim = off + len + local ip = off + local bb, bc = 0, 0 + + local function fill() + while bc <= 24 do + local byte = 0 + if ip < lim then + byte = readu8(src, ip) + end + ip =ip+ 1 + bb = bor(bb, lshift(byte, bc)) + bc =bc+ 8 + end + end + local function bits(n) +if bc < n then + fill() + end + local v = band(bb, lshift(1, n) - 1) + bb = rshift(bb, n) + bc =bc- n + return v + end + local function bitsLong(n) +if n <= 24 then + return bits(n) + end + local lo = bits(16) + return lo + bits(n - 16) * 65536 + end + local function overrun() +return (ip - lim) * 8 > bc + end + + -- prefix tables of the current meta-block: T (u32 entries), tpos entries used + local T = bcreate(4096 * 4) + local tpos = 0 + local LENS = bcreate(1128) + local CLL = bcreate(18) + local CLT = bcreate(256 * 4) + + local function decodeSym(base) +if bc < 15 then + fill() + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc =bc- l + return rshift(e, 5) + end + + -- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1 + local function install(n) +local size = prepare(LENS, n) + if size < 0 then + return -1 + end + local need = (tpos + size) * 4 + if need > blen(T) then + local nt = bcreate(math.max(blen(T) * 2, need)) + bcopy(nt, 0, T, 0, tpos * 4) + T = nt + end + build(LENS, n, T, tpos) + local base = tpos + tpos =tpos+ size + return base + end + + -- readCode(alphabetMax, limit) -> table base | -1 (corrupt) + local function readCode(alphabetMax, limit) +bfill(LENS, 0, 0, limit) + local hskip = bits(2) + if hskip == 1 then + local nsym = bits(2) + 1 + local maxBits = 0 + local x = alphabetMax - 1 + while x > 0 do + maxBits =maxBits+ 1 + x = rshift(x, 1) + end + local s1, s2, s3, s4 = -1, -1, -1, -1 + for i = 1, nsym do + local v = bits(maxBits) + if v >= limit then + return -1 + end + if i == 1 then + s1 = v + elseif i == 2 then + s2 = v + elseif i == 3 then + s3 = v + else + s4 = v + end + end + if nsym >= 2 and (s1 == s2 or s1 == s3 or s1 == s4 or (nsym >= 3 and (s2 == s3 or s2 == s4)) or (nsym == 4 and s3 == s4)) then + return -1 + end + if nsym == 1 then + writeu8(LENS, s1, 1) + elseif nsym == 2 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 1) + elseif nsym == 3 then + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + else + if bits(1) == 0 then + writeu8(LENS, s1, 2) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 2) + writeu8(LENS, s4, 2) + else + writeu8(LENS, s1, 1) + writeu8(LENS, s2, 2) + writeu8(LENS, s3, 3) + writeu8(LENS, s4, 3) + end + end + return install(limit) + end + -- complex: the code length code + bfill(CLL, 0, 0, 18) + local space, num = 32, 0 + for i = hskip + 1, 18 do + if bc < 4 then + fill() + end + local ix = band(bb, 15) + local v = CLP_VAL[ix + 1] + local dl = CLP_LEN[ix + 1] + bb = rshift(bb, dl) + bc =bc- dl + writeu8(CLL, CL_ORDER[i], v) + if v ~= 0 then + space =space- rshift(32, v) + num =num+ 1 + if space <= 0 then + break + end + end + end + if not (num == 1 or space == 0) then + return -1 + end + -- its table (lengths <= 5) + do + local size = prepare(CLL, 18) + if size ~= 256 then + return -1 + end + build(CLL, 18, CLT, 0) + end + -- the symbol code lengths + local sym, prev, rep, repLen = 0, 8, 0, 0 + space = 32768 + while sym < limit and space > 0 do + if bc < 15 then + fill() + end + local e = readu32(CLT, band(bb, 255) * 4) + local l = band(e, 31) + bb = rshift(bb, l) + bc =bc- l + local cl = rshift(e, 5) + if cl < 16 then + rep = 0 + writeu8(LENS, sym, cl) + if cl ~= 0 then + prev = cl + space =space- rshift(32768, cl) + end + sym =sym+ 1 + else + local extra = cl == 16 and 2 or 3 + local d = bits(extra) + local newLen = (cl == 16 and{prev }or{0 +})[1] if repLen ~= newLen then + rep = 0 + repLen = newLen + end + local old = rep + if rep > 0 then + rep = (rep - 2) * lshift(1, extra) + end + rep =rep+ (d + 3 +) local delta = rep - old + if sym + delta > limit then + return -1 + end + if repLen ~= 0 then + bfill(LENS, sym, repLen, delta) + space =space- delta * rshift(32768, repLen) + end + sym =sym+ delta + end + if overrun() then + return -1 + end + end + if space ~= 0 then + return -1 + end + return install(limit) + end + + local function varLen8() +if bits(1) == 0 then + return 0 + end + local n = bits(3) + if n == 0 then + return 1 + end + return bits(n) + lshift(1, n) + end + + local function blockLen(base) +local code = decodeSym(base) + return BL_OFF[code + 1] + bits(BL_BITS[code + 1]) + end + + -- readContextMap(size) -> ntrees, map buffer | -1 + local function readContextMap(size) +local ntrees = varLen8() + 1 + local map = bcreate(size) + if ntrees < 2 then + return ntrees, map + end + local rleMax = 0 + if bits(1) == 1 then + rleMax = bits(4) + 1 + end + local base = readCode(ntrees + rleMax, ntrees + rleMax) + if base < 0 then + return -1, map + end + local i = 0 + while i < size do + local code = decodeSym(base) + if code == 0 then + i =i+ 1 + elseif code > rleMax then + writeu8(map, i, code - rleMax) + i =i+ 1 + else + local reps = lshift(1, code) + bits(code) + if i + reps > size then + return -1, map + end + i =i+ reps -- zeros (map is zero-filled) + end + if overrun() then + return -1, map + end + end + if bits(1) == 1 then -- inverse move-to-front + local mtf = table.create(256, 0) + for k = 1, 256 do + mtf[k] = k - 1 + end + for k = 0, size - 1 do + local idx = readu8(map, k) + local v = mtf[idx + 1] + writeu8(map, k, v) + if idx > 0 then + table.move(mtf, 1, idx, 2) + mtf[1] = v + end + end + end + return ntrees, map + end + + -- ------------------------------------------------------------------ stream header + fill() + local wbits + local large = false + if bits(1) == 0 then + wbits = 16 + else + local n = bits(3) + if n ~= 0 then + wbits = 17 + n + else + local m = bits(3) + if m == 1 then + if not largeWindow then + return nil, "unsupported: large-window brotli (pass opts.largeWindow = true)" + end + if bits(1) == 1 then + return nil, "bad window bits" + end + large = true + wbits = bits(6) + if wbits < 10 or wbits > 30 then + return nil, "bad large window bits" + end + elseif m ~= 0 then + wbits = 8 + m + else + wbits = 17 + end + end + end + local maxBackward = 2 ^ wbits - 16 + + local dict = S.dictionary + local LUT = S.context + local PS = S.prefixSuffix + local PSMAP = S.prefixSuffixMap + local TRANS = S.transforms + local WORD = bcreate(64) + + local out = bcreate(math.max(256, math.min(len * 4, maxBytes))) + local op = 0 + -- distance ring buffer: last, second, third, fourth + local d0, d1, d2, d3 = 4, 11, 15, 16 + + while true do +local __DARKLUA_CONTINUE_26=false repeat -- ---------------------------------------------------------------- meta-block header + if overrun() then + return nil, "truncated stream" + end + local isLast = bits(1) == 1 + if isLast and bits(1) == 1 then + break -- ISLASTEMPTY + end + local mn = bits(2) + local mlen = 0 + if mn == 3 then + -- metadata + if bits(1) ~= 0 then + return nil, "reserved bit set" + end + local nbytes = bits(2) + for i = 0, nbytes - 1 do + local b = bits(8) + if i + 1 == nbytes and nbytes > 1 and b == 0 then + return nil, "exuberant metadata length byte" + end + mlen =mlen+ b * 2 ^ (8 * i) + end + if nbytes > 0 then + mlen =mlen+ 1 + end + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip =ip- rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated metadata" + end + ip =ip+ mlen + if isLast then + break + end +__DARKLUA_CONTINUE_26=true break + end + local nib = mn + 4 + for i = 0, nib - 1 do + local v = bits(4) + if i + 1 == nib and nib > 4 and v == 0 then + return nil, "exuberant nibble" + end + mlen =mlen+ v * 2 ^ (4 * i) + end + mlen =mlen+ 1 + local uncompressed = false + if not isLast then + uncompressed = bits(1) == 1 + end + if op + mlen > maxBytes then + return nil, "limit: output over " .. maxBytes .. " bytes" + end + if op + mlen + 8 > blen(out) then + local nb = bcreate(math.min(math.max(blen(out) * 2, op + mlen + 8), maxBytes + 8)) + bcopy(nb, 0, out, 0, op) + out = nb + end + if uncompressed then + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding" + end + ip =ip- rshift(bc, 3) + bb, bc = 0, 0 + if ip + mlen > lim then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, ip, mlen) + ip =ip+ mlen + op =op+ mlen + if isLast then + break + end +__DARKLUA_CONTINUE_26=true break + end + + -- ---------------------------------------------------------------- compressed meta-block + tpos = 0 + -- block types / counts: 1 = literals, 2 = commands, 3 = distances + local nbtL, nbtI, nbtD = 1, 1, 1 + local btTreeL, btTreeI, btTreeD = 0, 0, 0 + local blTreeL, blTreeI, blTreeD = 0, 0, 0 + local cntL, cntI, cntD = 1073741824, 1073741824, 1073741824 + for c = 1, 3 do + local nbt = varLen8() + 1 + local btt, blt, cnt = 0, 0, 1073741824 + if nbt >= 2 then + btt = readCode(nbt + 2, nbt + 2) + if btt < 0 then + return nil, "bad block type code" + end + blt = readCode(26, 26) + if blt < 0 then + return nil, "bad block count code" + end + cnt = blockLen(blt) + end + if c == 1 then + nbtL, btTreeL, blTreeL, cntL = nbt, btt, blt, cnt + elseif c == 2 then + nbtI, btTreeI, blTreeI, cntI = nbt, btt, blt, cnt + else + nbtD, btTreeD, blTreeD, cntD = nbt, btt, blt, cnt + end + end + if overrun() then + return nil, "truncated meta-block header" + end + local npostfix = bits(2) + local ndirect = lshift(bits(4), npostfix) + local postMask = lshift(1, npostfix) - 1 + local modes = table.create(nbtL, 0) + for i = 1, nbtL do + modes[i] = bits(2) + end + local ntreesL, cmapL = readContextMap(64 * nbtL) + if ntreesL < 0 then + return nil, "bad literal context map" + end + local ntreesD, cmapD = readContextMap(4 * nbtD) + if ntreesD < 0 then + return nil, "bad distance context map" + end + -- the tree groups + local litBase = table.create(ntreesL, 0) + for i = 1, ntreesL do + local b = readCode(256, 256) + if b < 0 then + return nil, "bad literal code" + end + litBase[i] = b + end + local cmdBase = table.create(nbtI, 0) + for i = 1, nbtI do + local b = readCode(704, 704) + if b < 0 then + return nil, "bad insert-and-copy code" + end + cmdBase[i] = b + end + local distMax = 16 + ndirect + lshift(large and 62 or 24, npostfix + 1) + local distLimit = (large and{(distanceLimit(MAX_ALLOWED_DISTANCE, npostfix, ndirect) )}or{distMax +})[1] local distBase = table.create(ntreesD, 0) + for i = 1, ntreesD do + local b = readCode(distMax, distLimit) + if b < 0 then + return nil, "bad distance code" + end + distBase[i] = b + end + if overrun() then + return nil, "truncated meta-block header" + end + -- context map slices resolved to table bases + local litMap = table.create(64 * nbtL, 0) + for i = 0, 64 * nbtL - 1 do + litMap[i + 1] = litBase[readu8(cmapL, i) + 1] + end + local distMap = table.create(4 * nbtD, 0) + for i = 0, 4 * nbtD - 1 do + distMap[i + 1] = distBase[readu8(cmapD, i) + 1] + end + + -- block state: current type, previous type + local typeL, prevL = 0, 1 + local typeI, prevI = 0, 1 + local typeD, prevD = 0, 1 + local lutBase = modes[1] * 512 + local litSlice = 0 + local cmdTree = cmdBase[1] + local distSlice = 0 + + local remaining = mlen + while remaining > 0 do + if ip > lim + 4 then + return nil, "truncated stream" + end + -- command block switch + if cntI == 0 then + local t = decodeSym(btTreeI) + if t == 1 then + t = typeI + 1 + elseif t == 0 then + t = prevI + else + t =t- 2 + end + if t >= nbtI then + t =t- nbtI + end + prevI, typeI = typeI, t + cntI = blockLen(blTreeI) + cmdTree = cmdBase[t + 1] + end + cntI =cntI- 1 + local cmd = decodeSym(cmdTree) + local cell = rshift(cmd, 6) + local insCode = CELL_INS[cell + 1] + band(rshift(cmd, 3), 7) + local cpyCode = CELL_CPY[cell + 1] + band(cmd, 7) + local insLen = INS_BASE[insCode + 1] + local ie = INS_EXTRA[insCode + 1] + if ie > 0 then + insLen =insLen+ bits(ie) + end + local cpyLen = CPY_BASE[cpyCode + 1] + local ce = CPY_EXTRA[cpyCode + 1] + if ce > 0 then + cpyLen =cpyLen+ bits(ce) + end + -- literals + if insLen > remaining then + return nil, "insert past the meta-block end" + end + if insLen > 0 then + local p1 = (op > 0 and{(readu8(out, op - 1) )}or{0 +})[1] local p2 = (op > 1 and{(readu8(out, op - 2) )}or{0 +})[1] for _ = 1, insLen do + if cntL == 0 then + local t = decodeSym(btTreeL) + if t == 1 then + t = typeL + 1 + elseif t == 0 then + t = prevL + else + t =t- 2 + end + if t >= nbtL then + t =t- nbtL + end + prevL, typeL = typeL, t + cntL = blockLen(blTreeL) + lutBase = modes[t + 1] * 512 + litSlice = t * 64 + end + cntL =cntL- 1 + local ctx = bor(readu8(LUT, lutBase + p1), readu8(LUT, lutBase + 256 + p2)) + local base = litMap[litSlice + ctx + 1] + if bc < 16 then + if ip + 2 <= lim then + bb = bor(bb, lshift(readu16(src, ip), bc)) + ip =ip+ 2 + bc =bc+ 16 + else + fill() + end + end + local e = readu32(T, (base + band(bb, 255)) * 4) + local l = band(e, 31) + if l >= 16 then + e = readu32(T, (base + rshift(e, 5) + band(rshift(bb, 8), lshift(1, l - 16) - 1)) * 4) + l = band(e, 31) + end + bb = rshift(bb, l) + bc =bc- l + local lit = rshift(e, 5) + writeu8(out, op, lit) + op =op+ 1 + p2 = p1 + p1 = lit + end + remaining =remaining- insLen + if remaining == 0 then + break + end + end + -- distance + local dist + local push = true + if cell < 2 then + dist = d0 + push = false + else + if cntD == 0 then + local t = decodeSym(btTreeD) + if t == 1 then + t = typeD + 1 + elseif t == 0 then + t = prevD + else + t =t- 2 + end + if t >= nbtD then + t =t- nbtD + end + prevD, typeD = typeD, t + cntD = blockLen(blTreeD) + distSlice = t * 4 + end + cntD =cntD- 1 + local dctx = cpyLen > 4 and 3 or cpyLen - 2 + local dcode = decodeSym(distMap[distSlice + dctx + 1]) + if dcode < 16 then + if dcode == 0 then + dist = d0 + push = false + elseif dcode == 1 then + dist = d1 + elseif dcode == 2 then + dist = d2 + elseif dcode == 3 then + dist = d3 + elseif dcode < 10 then + local k = math.floor((dcode - 2) / 2 -- 4,5 -> 1; 6,7 -> 2; 8,9 -> 3 +) dist = (dcode % 2 == 0 and((d0 - k ))or((d0 + k +))) else + local k = math.floor((dcode - 8) / 2 -- 10,11 -> 1; ... +) dist = (dcode % 2 == 0 and((d1 - k ))or((d1 + k +))) end + if dist <= 0 then + return nil, "bad distance" + end + elseif dcode < 16 + ndirect then + dist = dcode - 15 + else + local x = dcode - ndirect - 16 + local ndistbits = 1 + rshift(x, npostfix + 1) + local hcode = rshift(x, npostfix) + local lcode = band(x, postMask) + local offset = (2 + band(hcode, 1)) * 2 ^ ndistbits - 4 + dist = (offset + bitsLong(ndistbits)) * 2 ^ npostfix + lcode + ndirect + 1 + end + end + local maxDist = (op < maxBackward and{op }or{maxBackward +})[1] if dist > maxDist then + -- a static dictionary word + if dist > MAX_ALLOWED_DISTANCE or cpyLen < 4 or cpyLen > 24 then + return nil, "bad dictionary reference" + end + local nb = NDBITS[cpyLen + 1] + local addr = dist - maxDist - 1 + local widx = band(addr, lshift(1, nb) - 1) + local tidx = rshift(addr, nb) + if tidx >= NTRANSFORMS then + return nil, "bad dictionary transform" + end + local woff = DOFF[cpyLen + 1] + widx * cpyLen + -- transform into WORD + local pfx = PSMAP[TRANS[tidx * 3 + 1] + 1] + local ttype = TRANS[tidx * 3 + 2] + local sfx = PSMAP[TRANS[tidx * 3 + 3] + 1] + local w = 0 + local pl = readu8(PS, pfx) + for k = 1, pl do + writeu8(WORD, w, readu8(PS, pfx + k)) + w =w+ 1 + end + local wl = cpyLen + local wo = woff + if ttype <= 9 then + wl =wl- ttype + elseif ttype >= 12 and ttype <= 20 then + local skip = ttype - 11 + wo =wo+ skip + wl =wl- skip + end + local ws = w + if wl > 0 then + bcopy(WORD, w, dict, wo, wl) + w =w+ wl + end + if ttype == 10 then + -- uppercase the first character + local c = readu8(WORD, ws) + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, ws, c - 32) + end + elseif c < 0xE0 then + writeu8(WORD, ws + 1, bit32.bxor(readu8(WORD, ws + 1), 32)) + else + writeu8(WORD, ws + 2, bit32.bxor(readu8(WORD, ws + 2), 5)) + end + elseif ttype == 11 then + local p = ws + local left = wl + while left > 0 do + local c = readu8(WORD, p) + local step + if c < 0xC0 then + if c >= 97 and c <= 122 then + writeu8(WORD, p, c - 32) + end + step = 1 + elseif c < 0xE0 then + writeu8(WORD, p + 1, bit32.bxor(readu8(WORD, p + 1), 32)) + step = 2 + else + writeu8(WORD, p + 2, bit32.bxor(readu8(WORD, p + 2), 5)) + step = 3 + end + p =p+ step + left =left- step + end + end + local sl = readu8(PS, sfx) + for k = 1, sl do + writeu8(WORD, w, readu8(PS, sfx + k)) + w =w+ 1 + end + if w == 0 and dist <= 120 then + return nil, "empty dictionary word" + end + if w > remaining then + return nil, "dictionary word past the meta-block end" + end + bcopy(out, op, WORD, 0, w) + op =op+ w + remaining =remaining- w + else + if cpyLen > remaining then + return nil, "copy past the meta-block end" + end + if push then + d3, d2, d1, d0 = d2, d1, d0, dist + end + local from = op - dist + if dist >= cpyLen then + bcopy(out, op, out, from, cpyLen) + else + for k = 0, cpyLen - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op =op+ cpyLen + remaining =remaining- cpyLen + end + end + if isLast then + break + end +__DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 then break end end + -- the final byte's padding bits must be zero + local pad = band(bc, 7) + if pad > 0 and bits(pad) ~= 0 then + return nil, "nonzero padding at the end" + end + ip =ip- rshift(bc, 3) + if ip > lim then + return nil, "truncated stream" + end + return out, op, ip +end + +return Decode +end +__FILES["codecs/compress/Brotli/Static"] = function() +--!strict +-- 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 { + dictionarySize = 122784, + dictionaryCrc = 1362545412, + dictionary = { + "eNo8velyHMe1LvrbiOA7lNpni8Q20QBJTSYGB0dJ3hq4Bcq+2z4ORXZVdncB1VWtyiqATUkR4ICB4ABSnAXOMyUCIDhiIIGI", + "wxeg/pH/FOeiuhsR9yHu962EbBkS0J2VlcMavrVyrZWJX9FeNBgGflEHupgUlNvvRp72VKJMORqMwqBm/ES7flKLqjrsS00S", + "+P26GGs9GMX9id6X1LSKowEdFyKvFuCXYhRXClHUXw1ULfAHdOCHuqyDajmqaON7uhLFfNYLorCUlHVlwNeDRT/0qqqE99ZM", + "MQ2CslZeouOKVm5ZxVoV46iSxKmuqLhfFQKdVqOw7JfKGKcOVOiFetDoAR2GGI+rjC5ESbkamSQ12qsoT5fRpqzx3rJKQlXR", + "n/lhfyGISsbfrwtoj/GhXT/690M8E69vdf5UjgJPh54Z9JPyF+gfw/AG0YfxS2GCtmU1oEvoy2gduioIqiopD2r8N0hNRYdp", + "0Q8qVRUnfZEfJmXfBL5JSlGEsWpvEPMc1AbfFUwFc1eBiTCcKPbdMt5vAmWSRCtMt1Ir4pl+PywN+kGg8fmgir0Cni36sd6D", + "NesPo0GFDvPVsFTB+ieYbBApr4S1NzoohlGiK6lbLmquRViLI7ffd6MwCl0dYJ/K2BPP194n2J84DXQZ66b61D4/LEZukBYC", + "NWgCbUxZBUXDPURf+6NQb+ro+A/8x7jYoL2go1i5uhCk2P80HtS6v4i/yyCaEtYJm4j9xtjLOsSa9PfralJVBp361TiKKp/s", + "/fwz0Eu4t1YFPaJTPNOvdbUYqBLopx+r4xUxnwTjjbHnCWi2L61UE6yWh/4wBnwPCgYtYvS1fqwV1iEpYl9UmkSgjTjvgoZU", + "0A+6rg5gTTz0XwGtY0eTJI3DQoQf0Ak4IYgjo9M42GCw8HEUaDwKUkwMlht7q7GPgZfvq5bAGpUBFdfwTAJaDg0Ixouj6t9A", + "025UrW3Kd+S62lWPSbAQAXbDx8uwPlXwWb7kF7EGiWvMX0qxquEN4bulpDPGfmCMSYB5GuWjO+XhHQ72L+iLyiFopL8axZib", + "SdZ/va3NA112tRd6qlEUFzhvrOHX+d78IOimAn7dXN3X+Sn2MlZh/yD6HlQhaCggMXn/7PhXZ1WlwSDW26Sx/l8b1v9xUPlJ", + "BXsD2jOlSJsSeAJbU6piLO+0tTkB6CcN/QT7xn76QYeVQciPfZUgZ8jTmOLmjuo+LB3GPoj5RkExCtGnHxhVxLfoWVWNCzkQ", + "o+9iEA0WVKFmqio04Iv3MN4P8APWMaD9BHwXDPr9PmRCYhIQTuxj+qX2ADw4qFV/gr3YDZkDvseahAZ72I/trsVpaPrSoAZJ", + "1r8J/ZUiFZQgAgzep72S9r3unNGJeR/f5fvMX97DmP2is8FEEfYRcgJ0mKQFvV+TGkKMQ3ug6QTcHGHrQF5xZdNH1X0uZEAZ", + "617AOPaDlgciLLIytRg8C5oMqhijj/VyQf9b8K4+7H2iSqbgJwa0FYD5kn4IsBC024UFLmHR/tr75RdemtS+oHxRga5FKdY9", + "wRL5YZ/av9+lbKppU/RNeXBwMB/7Bn0WTDXWA5swD/ytN2Ni28GPHsaxpaNjYwF7DirA2OIQssQrRPvyReXHAcaD9WLfcV+K", + "OWu37Bc3vFMFnekBP/hfG3KgibgS4FkP9FCFfN7Y0dHBWXqxGiynYIpqlBTT0CuAj8qxLkKyBP26ZhL0UQa9g/ch13WwCcRo", + "Uj/Bo8FXvb05inzsSe3jXXtzWDOtfNAch+R7BkvbGaqBWgkMkfhV88c///nPGAdko1cDv5vWTueHarn6F8juAHwdDELB7C9v", + "zf6zfV2LA+EEeRXkW1q2fYh+qqkpQ5MkWJpOFzTwn+1d7WVouA+xRpAxSQwZ5rz7rgNtEmA/oV1AVRhExYeM6verCfYfOgr6", + "IdAl0EwVm/Ee1nRdy7oWl/QNmZDHYLoKcY8Gg1aw16XUh5wOsFEGrwaTKEqkqNLuV0rv/vGjzUEKXYt+sZSdIKpaCfRWTiqU", + "EoEXp6XdX+3aFUI+hVjDv4BYA1Ih1n6AOgC8hfVzQP9xrINaATrIgFa8tF+HyihXVfUgaKOUBsW9m7dsLYPWQPdJCTIFwh+6", + "L40hr2qbMP/161s7WztzPRUDoeWDf/zYM5AvBQ3OgRzfu+mjrdh6QwbA/IMPsIhF0MP/HbpoClHNQIbk0UVuz5e9ewsYTz/2", + "rrXzhx+gvGpYN2/D1//V+m2qPOxNvQ0Ktw3/g9Cv4pl1wB3J3k1/3jrgu5B+Xs3ThaQHE4MsC0LNcUaDezd9sNWDbNMDKti7", + "6cOtAdYfdAtyVEEV/BNGAwr8YEo61M7/HTpjoiJkU0Unvshx01XeAtmYxkXggCp0SVcS90Dn+q3fv7MB/9UYV7MAeoJ8iTs6", + "WjsrftDvtLX1+HEUAud4HnhrEPtkIj+opolp7zPtwAa1vZs3b/20d/sXezd3bFWeqmCt8K7NPX0Qgus3OuuhYpO9mzdtdTAf", + "6FmIel9VIFu62qs9JkqDzz79Yhf4EXglxhq8t7WrvKnnI6wtREDXn0Gnezve21oB1tr63gf/AA1oP3TL/wPMBfLimFfWt7aC", + "rmPsSUlDp4K0QuCe0Nu65cN/fBMVv1n/r9ZO0NZGtG0kkIk14oZoMCiAF7a+/8E//qoG1Ba8r+X7H1r+Y8eW/9i65b1/9Oli", + "cdf/s+dTyNLygA91B9I2wBfoY/XblDoU/AD6ga5KsHb5AujQA72WgUUgL4CRwmTrlg/+8cnevXvaNndsKkbQ1Ohj1xc7nX0Q", + "OFvff+8f27/c+T8e+uhs+aFF7/PR/v1/QL8Z0E6y/ofWTmCRBKzeqYDmfvihq/2f/r/yn0H/9Ff+z6NBvCcBzSnPM5AWAdhx", + "X2fLH36AyIpC7GUeiqGj4/1WrEWtD6LegKjAsZCzURFr0eps7ugAjYOHsRiAf8Cp4Im45mJfkxooSwNT+FGYhzJzoedKeC90", + "Yv59rNOecn4n5AGgnuCrEHzdD1qBplEh9OE+0IkLum/xoHPdwK+2Qvh8iOewDh07/7bTfPivnq4EfEkE7P/pT62D2DeAjKgK", + "5RFVE6j8QO/e9t8GdBK2bf5gb0B5Dlr/+qvPnEIaAJdH/Z0/rGv5ZNe2neC5VlUoQF6rcMOmP38EfFamUOhq90FbkCUpcTRw", + "gl/V37e1vNPRsbk1BND/56Z/df7zX50tn0UlB3olWdfyhz9AX5agUysFyKfW79a1dJAmsA/90db/D3INa92zzmxtb3fwIKQi", + "8W1pQ+t3LWjqQG+ux/SqXqqg/1SS/+uej1uxsd+mUYL/toDHISF/WAdSeA8/7+PnA/x8iJ+P8PPnzR3yzyb8bMbPFvyg3Wa0", + "24x2m9FuM9ptRrstaLcF7bag3Ra024J2W9BuC9ptYX/4bBO+24Q2m9C2A8904NkOfNeBNh1o24Fn0AEWAz9oh3+B0PDzEX4+", + "xM8H+HkfP+/hZwt+NuNnE37Q7iO0+wjtPkK7j9DuI7T7CO0+QruP0O4jtPsI7T5Euw/R7kO0+xDtPkS7D9HuQ7T7EO0+RLsP", + "0e4DtPsA7T5Auw/Q7gO0+wDtPkC7D9DuA7T7AO3eR7v30e59tHsf7d5Hu/fR7n20ex/t3ke79zHjDs76vU1b/gy1hMnjf8Cs", + "UeXVdVgTiSboqgLHJJEXlYHLXQgs9Wo2KvgQ0K+mlDKvpgZ8D3rDEHFFkEsRLRL8rlzsref3RbDdIuDUELqYFgWkKTg2KEXf", + "pq/uE9WG6BM6AlAAnAMdVFB9fB/JOVKlVFVTQMwwAksCe0OGBalPVQcjpxbBnlAQjnHVx/sLeGfABkHk+RH4Iua4/NfPXz98", + "/RI/S69f/Dr0+uGvQ78e+vWgfPb09TI+XcJfc2j1Er8/kb+WXj/Dd0v4ZO7X4deX0fYp/pn99Sh6OPr6x1+P/noA3z7C74/w", + "38vs4/Xs66v49yJ6wlOvr72+hc+fvr6EtgfR7op8+gL9P3x9Hj9n8HP510P4fBbve/r6At7/9PX865f47AX+uYHnDr1+9vbA", + "2/E3N9+OvB1+cxc/828PvT2Mv8fezL6ZwTd38f2Rt6Nvx94efjuMn0P4hL+Pvrn35jF+P/zmNp4dlT7G3x7EM6P47Bf0dI+/", + "Sdtx/H4YbfnfQ2+eSK/DaD/8duTNz/hsHG1G3kzJE8P45gne/gTY3STYeB0FsKYTmOWwg7E7QHW0+gk5CsSHMb811P607AF/", + "QEOwLXy36MNyJqiMqzRzoaKB8mBtAZHBTIdIiD3gP6MBatMqPQaG7gIDcqQRB3N/EL/QZIutAAYwpOUOO7sKiQ7sg/fqOIZh", + "HEL3qkKUJvQLAFgmAa3BQMz+BDYJpBmMUKDDuCTuBSO2OamHsNmFWeqmxoXRE9PoCwo0YwjRYIMIlSl6JWC3K9o7Fby75lOz", + "0ltgAL9D2qHsHq8H2oCeARwCPoCSfxeAsRPzgIkdxa6uUkHTkIZGK/mhKuIJ6FI/AZZMNb0Z+AK4BqpT70siQFciZPSMT/Fs", + "mADEG1NI/SAR0xdKQAN9pV4NzOjRvA49Q1MT/8XSlWEK0+ViwJpQa1DHaAzoQ1eARz9FiFUb0EC5plz098G8xoDCCOgvpucF", + "2BQ4CzpSBTEM7JgWrfk2hX7GklR1Oa2oEFqargtf/AvQztD2XgEc6cK0cSlasOLA6OUAdlEoxs8gRI2mQ8fQm2I8dg0REesC", + "pg9rPk3KMJPwLF5nsNhJeZDuGU7aA+m5xGIJlzOtJLAnKFTihM6U2g5Ihn5acDF9S9hQWKqBqmkij7jGd9RSMdO5TC4WNsHm", + "xQ5ALemqmlZpHhtVrQa1T7m/BeCqUlqFcKSfhNSEXrCmhua4wQbFEFDYWgrCfrpaaKYRcAMamBSPVZU8i+5JWyG9LiGJhr4j", + "7e0lsXLg5mNyAERbCHxAb06EhS0q0C/9SjWVggi5WwbTDzR9Fe2coEdvlvEAd2uwygIaSyrpS2G+JmX6KGBXmpCDLtBN4Eb0", + "J9AZxwlqekSMW3P5b4BjOlgMJWv/ILcZeE6HVV+7hPV+UMRENc1Kch70vF+ByapIHT6MQMIeNAcp02WnST1gv9QtF7jOcVQD", + "KjL9GpsHFIP5kSzAYA5XAmA9KcuOEl3VomIRJOFGVc3FhIkFFgd64E5brxzEQkx/CPRHnMREUwq2OKYahdhQETIwMQh3eyky", + "PiPVgVartch1YWrqYrIVuN2UQcUJ1wAmJRmHfjeTxoA7Rb6SBIyN5lqlSdSJ3Ul0nvZXhUwCY08F/0PKMXgZpgp0iyUexKd4", + "L83eEFLQp3PCLX/F/uiKhISM3TLBj6anz9DNaLwoLcCSqoVuAm6iFR4NYi91sUY2gPUCs5h2KShhABsK3qW30uwgX/ZSchF4", + "1/rE0wg7KgDOc3UHLfBeis0q+DOg3wUglxJBJDUMeApz6wQ19PQYuuSMonMCm2c0kSvleCiDxgZUsYT4M6GL1dDHxm9rZDDY", + "5Nh8Q18vBXdM7g5LMKC39HDLSgTd7ZUU8peb7O0hc6Jd6CURpA9ghO9toAO0QI8IPX7spQgjzSd5B4F4fGvFNf8ajCa0ddrb", + "YYIpjwZaqVZNdlHK01rt3EVipS8459K6g3QME3HlwrzI9ZCJgfjVAJ0YsIT9/dqUADwSDPe9njiiYxjf1tjBRtEdhDSeG1N3", + "+CUY0YOQ0J4CAWNBjO6hR0aH33zd++4ft/y5k1h33zckaigCDC3sA+X3qX15RavBgGXKdL059B0TvEOehtCmoRrI9dAJEIrX", + "i95EkAVWA/I+inupe4gysYMQCvQTmz5VFfEQwOz2QXPglFhR5WAem3sUbDhgLzAjuChWubb29r/TBWrohzJ0HJs9ZGLMMilT", + "54V0TvzFYAAJmJckCPBFCZfQ/VrEzmiossFcD9YfjB2nlLFQ9H+jPt9NyZAPdcItaYH5XHO+a6FHkh5zQ7cWSQWr7YEGvuVi", + "J7H4DAtRTMc/ZAeGC2FLv0hCqtR+vJkmlfiz6dMzO8jY4G5IOEp0nhMYOpToCMVa0+ddIbtQq1Ge+kbc215K0az3KVOMwe10", + "j2z8/nsxVKo5jBWbR7dELqJ7oasQt/cUMa/Y0Cfn6WpSduwJANjUpZTnaYM4LzshY0oh3VRmkKPiaDshXLpzdF9DZWFGn2Pm", + "Tj6f72oHdA1LBU6ahyAOPYedPFYAecdxDdICxK6L1BUl/Q3PQfIV0gZgiMK32K4qT1DkoKCrPYl76P4xHLyjQCEUQDR1A4iw", + "feASOg3KPKUxVLgufc2OgRA3gGqhuIaNswGUSie69w0xBF2fRrA7SahfTmKEGcnnHp0AnYNUJ5ib0RtaO3POdsIjPJru66M7", + "vgqZGNDJ09Pa6Rc3tFHIegrAEfDK6N2EVpg9z132abOXqhJKgpPRlZ6CinM9eRO73QklAwRYd84lOiyD1mqb3xPRl6RVH3RZ", + "Iw6rgukxCZCG+KoNZUceAl3z+EAH9A+adteYdp5AdPKIAgIlLRYLPjqlZ9/Q/dfRD05TsGPXtdCrD0yjU93tfPdD50fiBeSR", + "yne0fxUPm1zO1wdZlXm85cTkZ4JUQ89yrqbKUdRKZ/k2IlCeVhkw4qYe2EBpiQ5msdK7abOYH1qxgnR0dlYpVehSNDxfMB37", + "Pujo4KlBTvy4BaqORGHBKj5EGdFbAAbraqdzGTOCcGrj5pGk8phHyx8qZBIH9v6fd2/77672OCrpuEi3/g7yzGY6THnIY+hJ", + "6gJjJgl98WYzxwIIFva3Ot9/7wT0DPI0J/hjB0SaA3JyeG7nDXLFKeA6+9TW//eg8UHVXfTcx4AONR57wH4j/MWCVRPqme2U", + "na3OO92OR8xKrwddLRWoo35dq8C8DHiilqcb26kSO4Onwxo9iYYIJ7eJyzFIQE4PVqV377av9pK2HB84NtzowJanO6GFADc/", + "4AMMiCsV8iUEX0LL8ACM0DoKq+Rf8kxL1AbcwlMJOWox1JQOnW8hvS7fKS8q6PXcTN/r3tRBhdDJ4zonvzlf8XmIlqPbG1AD", + "27ODmKsAcag3c6TY5NY/8Zfv6cQG/0ETl8nimzZ35ByqWIi+nnUtVBDdng8QQI7HF1hwys6WPxaLRTARIAsRXo7wAcoaj7XS", + "+7xJeAE4qxpahzPsIW7FIR5VuFzEHCctp0OmDbzW5tHQank3SDrpeTVb3/voH108u22LUzAaT54cKkig9X4xFaqm28nlOqEM", + "oI+4apt4IgHxr0K60SNKw+6o+z8273YojWCaF3SXXyk5+Mn1bHSKfYa/OTmu3+d7o+p2ntjlQj0Y1HZiT/rd/Vqwsh8QK5NJ", + "3u8pqm9zPfvLbW64qQO72bYp19pJFN7N00LotzSoUZYYOpM6sXpd79BjETg89ICyWye77/TRliDHO9ytPDh3XcsgcQnPPkxK", + "cePxqKMApulPyFvgo5zDM1rgZwyNThDw97eg0TSq+CaCLQIZ6mk526FnxFRTGqCvZiM6TV5dT3xIXKCARNEnIjCep5OgzBRy", + "hn6UmENT6KwCkQq4WoHKitS36aspelWMefU4iFQt9VRR8/iB3hAAo4R2ZoRRJZGhh8UIBfOMNlL0dgRpiUdktYhHk9YBghUh", + "AgBdGPpUOT6FAb2aMhyLAkBLPXHa0HqPgHx1SLwIu8kjwxLs6fjVdcAiztj1477IiNtGxURWgBZpNSrTjSpkgLdBZwCaR1Dv", + "yoQ8xic005yqAgdqHq354geCKHF9VQS05PGRD7iHha1CUkSFFNMkuo4VSCzgn4ooEign3o9+CzTiMASQAV706nEl4iSjPv4J", + "XPNqocwmXIMa4L+rKmkfMDLQUFxMqUjwoqgE+0D5JeDiAa4LHVgAfFh87iWWt4L3gLagr7F3dFmFYQQBBgDlYszgHrpgDRbH", + "p1OqDE0WmwigFyuFVQUzvnocQnLtj+hYEN+UGeCYVTWqYaQhQRYYjp9FLtg5luMj2EgYC4WIy8fo1jL0koQkmvDVddp8vthA", + "sJ1ARq4MV9GWDEgbmDvsAAwDqwF0rQmTdRWaGGqR3eBpxkLQLQZ0Sy8aaKgU0PPGV2MhKgoimdaxXcDQB1V/a99hFI0gNyrT", + "qTfgqz4IXyDoV/epc0jyMWxi0E2fAnmDnmF+qYAaWQeaZjDQnJI9BFiNTJDyuB6bjK4CrhueoIUd008ohMQwBpcHnQN4OUYF", + "IvGiAWAmQ7efUZVCxENbj+18RWwrvKBMCqsdALkPqwvZTyMO0/NdhcV4NdUX8VXYMqWFpygKwAZ+bFIdcASRKYrHhh5GbrdM", + "kOsIy53+KO6qgkUWEZYp0m5C3RBon+EXhSigCxOrBiIE+OKAXh2QfXMZB4MnYGuAGNgjB3SdO40OeC5F1yclyH1SJ5mdfIKZ", + "UCkpAmb85oq9lYDh0RUlC2ithnXDJgUVoMuIAFKcqTQrgFB8TIvTh+wCZWMSEPiUJcDzVXHGisGmRKgZn8e43DLaGwDmEDz4", + "WNN900fkqBVdsuZd2qqdXkQtjY6h8Al6UutUAw0ZOudqhsMXdVHgoUwca4HhLk+v0yoNX5AeDFvKnrQCtYWnQpi6lDyENaBA", + "WAbVtAB9iacYLwM8ZUjnFbBgrBgkROeYAZ/GLiYUyyFrLB4nWBVaoIRmKI5bFvcE9odOx1iXMCo/YZwL2BaWEscJ3o2CtBLS", + "0oohFmlxi8OwR/v0XABIl5JyEfINZmdMFzgWDrgOVAxZSy7GBLR4x9JKBStAyzzm6mqvap1N+2CeeVXIOrcmKiChlU8WBYS3", + "0gR6F5IE1hywRMkT41IcXUachEBSPnZ6UMz1qgYxajJeqQYJmRLr0pFQBHPHjDNCD65QUlQsAgaDDTFAOhChYtNChW4I+gLF", + "yWrSKqN/gNECmEt0E3ni4AU8K/OkOpX+y6DUQRANZio+W/NloU+7ibgFjfX2gqwhW9xyLHFbFYwQBE+fXVloLKSyxTgxR4h7", + "kBrnCn77NlV05CWUOXSwGToguYOchcS08KAK44dZSSsbaxXxcBkWFPrB0n9GmYPpJHRKYW0ptitE8BqyWTNqSHtJVCoFWtzQ", + "oGueHpNufdeFIgUVEVdVatRkgypJYI3I4XVSFCd3WbAlo5tyPYxp0x7ovZgGwsk1sVXFY8J9By2AtlwMh9KpZP2QRu9zGYZC", + "D0CJ+4rxlGUxilDzibjErYfbYL8wNigH6CfGeUTxAClTfyUrRjYHgZEpCS6oh13MxDB6AIBbNiPnEPzRKaOTknh4yFMkINAk", + "0FmRIKEGERpURNDQW+zCTCa3+qHE2ylSyw5x3kWyy+LPhVTxvEDv4gkkxeEgHZgl5dYqwuPY7LRUZmyXFrCt6YMv+SHHraCZ", + "fL4LCsElFocAkbMCT/xkhPaMfVEcfyTnqUI/NTERGQ4BNefS3oQcAL+XPU1JHQstgWOJAVKIi6TCWMGaL55J4TUtrnvzhcgW", + "L6V8sN5EOTswjPrSHiGFdSzBFPIDcC5Wr0RvO893C8I7dOUxGgusYz4W2UWfLC0jelZdWauCeFmBYmNVBR1g96wvDMKDdA5I", + "l9QwC9JeFZZj0mYHUaW8rTDkp0SPIxR8CnEMWc/4FoAf9N3rxn41wRjonCeR0qqByPN8ciodYSR7zrFNvAhYR6wDqBACQQkN", + "8CRFe3SuaG+HrCEWmA60Mp0VKmB8IeMJcw7sG8gNrgls9+/otcEAi/6+SI4LPhE6zzM8ZoML4UEKIL4AXMPkAwXUVf5KJGEi", + "M+I5Bvk8gQzyhP63C6fD+kiTmriGKd9KUdIrEkxR0gOpCUVDKnG0ViOIRZxwB2PNbz4XCS9aCLRN93yv6AIR84Yj0N67YcFU", + "O+nUN1oMcYeqOvS66LZ1eD7uy3lNdw7MCmwh0X3ASgMSPUFraKuzt6wdjx61kpxLme27Pv70C+dzsAT1Mh31rtgDZZHMSkyK", + "T+UtFDyJ2VXBZutekaXgd3CDh7/dxB4LgHfA6b3CF/mWli9DcepojyZLrmcPcLhfFWeWKUtkAnYNPXwpUiKWtRciNqH4E3tF", + "2niaThu6b4Oas0HnS/mCLjPuIiKdYCIgHJ4DaIkCxA9PncS1mxjCQpmVb+zxk7eFBv73hHSeorfVrfEECEpOYl9h0O9nlB6l", + "vdBPT0HXIP3axP9P6VRNRBt6xDOh3h1FdAgoRn+KQ6TlG4rsnHhgRQ4bk3PaYcPlxRqLJDJVKCH+ch+j0Tg+bDCkmT8gnBsW", + "Jcpqp3XH0h7NqWqV2gzMk+uRw0XDGNd+wwhgMcFcemyhbTBnjFZvg1IHSuSyEQRjP/eIhu0qxBjLIJVLLKd04pfR3vff0y3E", + "+ed6fKvFwGOqRs7P9TDWCPJEh7A/IddSyhCAuFDc/GYTPYPfi/rhGuIjOU3J0XODt5OIOjkTJbpMBZvkjIGfgMhjHpQUsRzJ", + "VnE8OHLild8mWkAOloyxx32UG94n1rlPf2D89d7dbR/l5OjR2S5aIO/8HeiGB4V+JP5i4LeQsUEx0GbS99+pRKqQPsXXAgQF", + "AZ8ABYEPYNmUuONkTXpJnO98EysstKoJenHxSnoNcz1lkRhcDB7mkb/lCMnIeWqnLIMnztcuWArC3dzDtjZGtkJC+UkNk2G0", + "CJ5XqXjDnE1ymhEVEvqnidOMElfXRufT0KWjRHs14SAHOgT6RQ6O85To2pMTodo3JNb8bkF0dFxr73PRmIHRjl/cI5gNe92v", + "a62dEksrpnVJsJkcL5udgoF/YJDud2AfNN+OPrvai0LhcrKZLwoeljMK0yWeXh7cOB1VfFZRIDoMS0zgGGYAbDfBJ56cxxlG", + "zfjh++KMolMInEU7IMwTEG1QAyoRGwCr941MSSjBCG8qOSneWBTtJuhLYtFpAWOYG4Q74l7BgaRd9uzVcj0t/0lht7fMbYbm", + "wUz7CGlqjGXvaudRb7EGHIsufNgzcU2OcLt3iBQVR5yj5ITlG4FxPIZVHuXSAHSxi7WV85aWXrEOnJ10BrsEJrGc/BvxaHvb", + "6L52GMEb1Lx/ny/nepgDwHFS4MlpuqHZnBqJR6CT8p//6pQ4hHwphfETAx8w0pUj3MrTWe19SXDh8Fgj50DKpTyRwSbDROBh", + "mJw1Y5UAU4rALtBoO6wlBoMZUlSOhHtF+7S0/B1SOVEgm1iiA7biQUZXx0QniaxertX5k5OTHe8ppOQIOcc1n4uOpsYhkqwK", + "BKRM5jFVrmdAwg7EBo7lLBMaCmCFlmBC11oi2B6bB80UqoGefoY/G8qNXI8cTZtuOR+WA2GnLL11WIZvafk0dBwJk9gDO7Xf", + "b5NFxDsgB7eLxpezQadNaGmzyBzmSOR6OsTl+qVIuTYRTxXSFQiDdMt4RqdD2NGR4Agj1kGrFuuP6NuPGRuXcxxrJEjPbcL8", + "0F+79lW3ypEqcyb8kEY7ECMDOYyca6yTo2+n5Q/kwR4Gh/0Bn3s9LfJtS0GVGTcUc5NKjLQFT5Zg0VZljiau4t8SMTO2MjdV", + "PzfamB5aeXm6MX9g9ZczK8vX6wdm8Hk2+bI+dmpl8cHK3NDK3M/Z8INsYq4xfb1xcqQ5vZBdnswmZlYWb9cvHc/Gr9fPP1s9", + "/wTNVhYWVhbuZqcPNEd/zp7Prrw4sDL3U/3q7calo9nz2ysvLzUPnGk8Xqw/ul6/dKTx8lTjl4v1I0P4vTlzGN3yvcuHOKRf", + "rjXO3KuPPV+9c271+lM+ODRcH0fLmdXz06s3LjQm57LhxytzR5svX9ZPXmo8ubHychmPNF9iVM+yS/caC8src4to2Xx6uH7u", + "YvPuyOqNU9nklezW8frje9nIMb598VL9zLPm+YlsZDibnq+fuNc8fjKbO5hdWqg/G8M6NO4vYF7ZxKls7tDK4tDK/Fh2+2U2", + "cbRx5mr9yWI2udQ4MspvZ89mdw7Wr1yqHzlax7PnHq6eX6xfGsIv9XPz2YuJ7Nj5lYUH9YmTK0uTHPbCifrkk+zWT83li1g0", + "LEhj8Wrj6u3VA6frc3P1sYlsfjk7NZ4NP1tZPIf+m9fvZdNHsuF7jQeyHS9+yk5daC5PNq8faxycz0YXG0fG6pcPNc48zaZO", + "rsyda5w91pxeak5fz4aPN5/M189ebB58lI1fy4Zvc9jj99AtdjY7O4Kdyo7/lE3faJx4iEVbmRuvP32Ouay8PJs9f9RYnGjg", + "2XtDzZk7jcWRxq2l7NhC4+Ji9vJs/dID7N3qpaHmnQMri8/r117Uz8zUjx0A2axeHF49vVQ/cRu/Z9PPssUFDKYOApg4unph", + "uDmzWH98Nls6uvLyeOPlNF5Rf3pidehI/eh9rEb92vPs5ensyPFsbKQxu1g/8SPmmE1eW5kDXd2qXziNVc1Onli9+nhlHjM9", + "3jz0cnUIyziKZqC0xt1TIBJQJj7HS7Nbo9nJMRBPdusuRoLxY+ka18407j9bmTuN9ljS1UP3Vq/PNyan8fbV0WPN5Qv1CzPZ", + "i6Hs7tH6oeFs5ClWtXn4FGiSdHX6QOPIsWxuOhu/j0+yY+dIXQsn2f/UHfx/Zf5adulhdnmo/nSieXesPn4WDUD5jXtHsVD1", + "2YP1oROgIvBLNnQxG7+KcYJK8RUGgFmjcXN6Jrt6AkQIysFCcU9fztaPTjYPXMhuPqxfOLGyuMjdOXA7W3heP/uwfny6sXSC", + "3Dr7svnyzsri0cbi8ZWXI5gFV+zpAdAqWBJcBm7lXGYu1y8sNW4tkJAWJrPjZ7ERYFtQFNa8fuUkxz+5VD8/DFLEyLPh55gX", + "OgGVZmPnwTXYx2zuHCgtmxlpXDsAtiLdnribjT3js8cWsqsLIA+sLUaF9iCq1dHjnCOod+FYdu5S/cENUC+oEV1hkckFC5PN", + "oUPNmbOgdpLi1fnm9BQGTII8s5wtXKqPYbsXGidmshuHVu9crM/NZCePcRnvzYIS8NTqEETNUDb9E/du4hQ3/fSB+rXRbHRE", + "XneiefdmNvIYI8TCikw7iv6zifHmk5tY0vrYOUgYMAJkzsriTXBc4+4MFiS7DW5dwDpzpmeGsjPT2SiG8bBxZxESJls4A5mD", + "ZUF7UCOG1HhxrrkEwXIV3Ae515y5QSrF1l8C/z6mcLhyOFsaA+/Xf5yqn1lqLB5uLI5ijo2pc43JJ+AakEQ2Plm/fBt0Vb94", + "cPXcaQrPsYeNQ1Or5++hk9Uz06BerPPq5SvZ3Fzz6GxzZqpxcSlbuJPNHatfmiQ93H5cnznTXDrU4BhGmncPc2XIidMk+PP3", + "6odBnwcaj5ayl/fr5yHGKZ1Wf7lAaXMPgmt+9fIN7OPq6Kns1mHIfIiX1YsnQYqQeKunn4HdyCmY1NjIysIvjSP3yRqLE82T", + "t+vPIWGucYTTz7CzjbvHQXIih59jUmS68evUJqfGm9MPIUmofRaPNp/cWx2daJx5TlJ8OZudPp69OEsVMH4bLTFm7sXyL6tD", + "V7Mf72FVufUPf4Ikx0QaZx43Z0il9WvXsSPNmdvZiZFs4lE28TO4oLl8BmK/+WRqZf5hdvJ44+5DESYjoCgy4MwT8hTE8sKZ", + "bOq+yM/T1C/3jmYLE6CT5tiD+qVD2enr7I2b+CybPrSyfLk+fqs5BJlzZmVxPLt1v/Hz+WziJkRrfehAY/wZ/31kPhv7pTl9", + "C6/LlodXry9C5kMjZA8n+NKxU9kQqZTf/vwj9G92bLh+9MHqwZuQD3gvJSHk58gwxdFJTG2enA7+vTuCma5evAHGpN5cHsVQ", + "G2dmoVNIqJCcowuyzsfxVX3qJqQ6Jli/cLV+dnhl4Sjoh/r32ijmSPk/fr25dBqciDeC/LDjjetD0BcUZQsjZJnFhcYU6Pk0", + "tBsV0MlDkLckKiiXsR+zmXm8t3kE/D5DjTxyjPwLWXHpauOnw3z2l6ONqSONhbsQ5tkViKaJ1Z+PZdNXyONjzzB9DBVQAeNp", + "TC0Jvx/NTlzNxibr569RTUADAhIMHSWuAHePjdaPjWbHz5MLzk+tTo5kkzdEJwpzQa1PXqtP3WoM3wWV1p/PZpceY44kOejT", + "51eEzq+CyDEe6JHmMub1AgqCzE55eBqcK3qEuoZqZeYwVFvz7pFs6Tw55fgJqrOFqWz6GIinfvgqv5o+0rw5jAbg0NWD09QR", + "EIMLd1ZvXiUKuviycfhZ8+UDopTx2+xt+iGRDGT7dbz3GBifu/bwFMXIaUiwS83by+BEbOLq8I/Zwnk8Dn23snih/mAJEgDq", + "nlILuzx9jAKWyOQcNB006eqNkWzmBVEW5ntsERQCucH/L05kw3Nc1clr2fzjbAJccBhcmd24Aj6tXz4JdESyvHFlZf4o3tU8", + "QE1aPzuGHSdtzz8BMIOyI8WCIMG2M0eAN6C2Vpan62fms4mDK3Mn6kdOZ8cfgkMhjSnlbjxs3j1IcDJ1gWDs0VLj9pXmieey", + "UPcx2cbi3cbi1MrLa8AhlP/QifeuAylBlBFvQAbeuro6Ody8eKJ+Gurs0urNE8AY5Menz6HlSZ8vTwPVNK5OEbJevo6Vrz9a", + "bJw731w+SYSzcBezgLqHxMOyNMeAYMdAmcSfk1eBEMhWZydWgaBI24fxCqLHh4cotB+PEjECwY7faz65CgWRjYBP0dUywCeo", + "t37uJeHNxPnm9D0sDnkWCHni+OqdMaKsFwsUv0N3m8cOZWB5IOSjF1denFo9/wjrCSKklrl0vHl3iIJ94iAeAbNASJIHsb/L", + "l5szwFFLK/N3wODciKdHoRkbd4ncwOBcHCiy6Z+aB683blPv1M9NAYkBXVAHYYXHr4B3sJvArqujo5zXydtQXkQj2LvJabLb", + "2Cw0b/3UYaKLS0eof2+NNm++JKqBIL20gKWD1sumzoO8sdGQnxTyI2DYU0RNl2+QI4AeKQ+vQLCwt4dPQGCgXuGmcWCY5sMb", + "+H/94jS4iVJlDmQzvvLiGqXB2C/1qWP1yUf1o7dFj0wSNg8fJwdN/EyNef4ZFfHj0ea98ebSEvgLnMIdnL5BGDl0AL0BeONd", + "MBlolTx5AundePYIuJTIHxpq9GewD5gd74KWAdQBua5evs/9WqCGpRwG3b6AAroJ/Z6NXVu9eIuLPzbXHD+IhQJuwY7UH1yv", + "n52Dys4enqImHfsROA2asX5ERgV+PHmCCHD4nrz3KWTLysvHUDqNqTNQDUQay5dXf7oEoYcX1W8OgcawF9g76AJMs/7oR240", + "ZPXcXOPMT83RxxzPyRFiQiA96EpAmluAxM/w0uaV49n8XOPOBDE/UNbLG1RkoyPAupQngKywccYe1ocu1w+BCE9QjxyfABdA", + "E2FqxM+3X4I7aMIcOwJRSVKEBJuHuXSJBPbiF9AMtpvGyxFIj8MgRWx3/fIyaBUgDSILjEZz6cJpzI6QbxycMkkRDZvi+CgW", + "nGp64Q7368h98tTZJwCiGN7q0DVKTtLY+dWr9yFPmk/m2A8miK2cnFs9f4nSGNrh5Sw1HawqyHPgmel5rjCWa1yspMvXIQ9p", + "KgI9TnNrQPACcp5ls8NgHEjO5vIVMCkUUHYcduISHqRp8Pxudvs2RAStGGg9GLCXb1uTFjQM2iPNQJlC6UDaj1/h4oOp74xB", + "o2GDwF+rZy5iozmFk2PAexDp2dALEBgnO3mqcfkm9DJEE62whZ+hnlYvUJ1Roh5Zrh8dhphdPbssHLdAFAGLCVoYtsniE3AZ", + "hHN9fil7fiebeAzuXll8CRKCpgCLwaqC9oeso1EG2jhzNTsF8+omuAnwlTY46OcFqGK+eeQRSA7zwr7TVAQ3QWLAwD8M+jlO", + "UT98l9sHTQrBuHySZAOhtHy++fgmMdszAPLR7NJVQuWnF+uzV2HZUQGduEfoC6MP4788RX165C6tM5Dl0DVIG4IWtJlfFlty", + "oT4x0Vx+mE1cgJVEll+8Sn4/Irxw8X5zZokQ6xglNnEjLDi89MQiddCR47DKaR3MPwEV1S8fxNhAAytzL0G9VN8Xod1G6pd+", + "5hwhb2mkwM69CQlDLHRkLLt8vrnwC3YB880WRjBs4HYSnvAL7fFLV5uz8vkh2AKXCHcPTjemZwEtaKfPHoQSzCbOQZZSG8JQ", + "nZzDyoO1iYrHRlZ/vAq7Bn82rk8TV0NWLx2lZXR5CFZD/QoshYvNGSCiaaKg6cvNJ5chUQlabp7A3OsnxFqHhTXzYzZ9DTwC", + "sUO4df9s85dzjXNL+AqGCSUDRgLB+8tFatLDy41fbtdnJkSkTGW3LEeP4BNqn1v3609ug62IJCceNg7cBEUBo2LK9J/M/Qx9", + "lE1foDsCJgOQ/+Qc1fTYhcbZ24S+eGoJZt0YjaOlZQLpySlQIO3QseVs9mj92gTFEYxErDbIZvRJ4+cDpKgDpwWIPhB3ymkw", + "Rf36TVLs+GMIk2ziTnbrHPl3+BDwPE0AAoYLwGzZ5KRo5+vNn4HST6z+dLJx9wDWist19zBUZ/3ZWPPJfDY8Cy7Lli8AONFJ", + "BSN07g73/eRxTLZx8QV9Iy+GYElRjVKznxdNQUqDxIBNQctRLDj8jt5grYiJehU6moCfaJM+KKIUIIHLV6GqsNfgAsqxYfoo", + "sDhURi8uNO4OYRkB/LAmEKGrB8brY49IRRM36dtZuJU9nCXqWL4M81wsCDDyQbyasoWYii6ybHaWJAd1efgquLU+PU6Kun6l", + "fvJS9vBoNgtleoIG2tjz5pMbtJVuPly9CthGdxA+IZy7/BPlxvwjmEWYHUUcMNXkOC3oi6fwySr4/dgwpLr40J7REnw6SQgH", + "Q+DopAicYxgMZdqFmcalF43L2AtAlCfZPSiISSJJrM/xX+g6eHGhfugayDK7OUphODzbPDJDJ9jwMF00D+5gx1cvAic/w1yI", + "XoBAJmZgk+J10JL0PMBygXVJG2SJHoMbL9DPyovzAL318xP0g8FaxKZg47DRU+hwBpSzOnSQAvbEVew1QBfFIDo5NwpaArRu", + "LC5DyjXuEQU1FsewYjQ6jtyHHUcfy8lLjaMAgZPY8ZW52xR6D+eay5eykYuc8qUjsGQbv2Cdj8B+ac5eB5lhoTjy2y8bi5fx", + "YXb8AA3b5UPN5UlMCoYA9BGdTi8uZOPLbInBP7jZfDqRzcNCOUNnJnACmOvkKdEODymogbuml4AVIXP4lqeHgWDJNdeerP40", + "0bg8ROl06y6dgRdm6jNnSSEXFyirj50jl00fI+Ngs66egPCk+QPxC6V/5DTkbePMDfo37hwUD9U9Wn/LlxuAWJPXGk+uUT4A", + "WwJ7H7xHXDS5RG/k4UlRPeCRm1BbAplo41ODTx+pn/ixDuA3e2R19JhIuUmYbzRs7y+s3jkH8EyL49zh1fuzRNdzR9GG6zAC", + "6578AjN8Zf7I6oXH2fAR7D79US8OrixMZyMABkcbJ+5Txy3dwr4TQz48BaUMOqE9fm+WWnv4ObptnFkEaCF6eUyjFeqeWBRA", + "+tBL0DYdd9cfUEfDsrh0tD43XL/9U/3klcaDU/QSXzuwukhUBsoh2c9ebR6dwHYTnc4tNqavr154Vp9+2ry3mI2MN5YXmzOn", + "IITBONmBn4iIXrxYmT9Bo296hlv2/Hbj6FB9+OjKPADnXOPEDJn6KsTRItd8+SnRyBU6e4HiuJKwlI8tYzpuyjAOHQ74jOvz", + "Yt+TEMnYD33XjxJfV6pRNYq/TbWbMlCFJ55eJAGzoQRsGtY7iJUEzoZhVCnEWuJnw6qOmYSlGL8qIaXG9VNPeXLOHqk0RJ/S", + "j/HkE4maj6uxxnuNLr1aCCWO1AxEjOWQwFLDdJJQlVWBucslOUhjSK6R0EIOm9Eo36Z+1QY+GomtNSoopaFyozjWkU3uZEiv", + "H6s49guMPkRvZRm55gE4DzI4TlUp+GsRiYw7Zai5YaDfq6lQK8btuNoG4UrsqITmFhRDcGOJhcV4UsbpSWxPVGHAZjDAaEB+", + "jvnKKhkJwDUSpBtKVQAlkbyG51CMZuYpu6eZzx0VecYmkZ5G4mEiZk74SoIzOUesmBtVqjZzWxuJ9uGuxXiBL+GZPL+1kZCx", + "xH8aj/E3mGPs+qoaeRgEs7WTyPM5UPxeCCSomFECmGvA+h1+5Ma+8bGbzEPCTqXsAb/rIikEqxJjZSW9SmsGRkUSQC0Ryp6S", + "HlRU5OphBdBUt/HgnCujjJyVG4lVixizZPtnNChWKpK4QSNR1waT9Rlly5wRCaM2sdr/6jHeWfA505QxblGgvSjRIfYXk321", + "YCQ6j9GyfqgY14TxcmWUy7CmyH113fP3S9wnY//wlGR7Ke7+flK4H0TYRY6ZJB+/ur/PxztePa7q/aQqTw28mvJ0pAd4dllV", + "zAKuaIaQM5SVaUBMlyi+uu76gasKeEgigiV81UOfeDrqU1XMQoJhTUEoRCKnjYTRxhItHBZltbHX3HGG+hpJ1+VMMfeCHxRU", + "RI4A4ZArDWOYlMQ3etHrJ68Xf534dVSy5BdeP8TPHLPefz0unzz69YDkyj/G78u/DuHzg9Lm6a9H8HNI8up/kk9m8dtzyalf", + "tJn2r3+UZ5clC3+KvUmPL34dxacvmK2Pvxf5b2bx49klyep/jNZr378+w7G9vsr38jv0Jxn8kmH/4vWC9PdY+n/E3mVsL15f", + "f33v9Un89yGevWtnIc8+km/xJMZ9Q8b8RD7jW1/IfGXW+PZH+QRv+XVYZs2+WWOALZ/gn5fo+Uf7xrWxMdf/x99HiGcPrPXA", + "NkPocfbfFQPm8MRLWdMr8g/XekTe/lDa2DoGrCywJJUDltAzx2nrFyz9egC9Pfnt1tnfbo/+dmv+t9tj8vvQb7fm5JOzv91a", + "kk+O/nbrzG+3Hv5262f59z35dkIa4P/Lv92akqdG+SA/QZtb8tS8/HtEHpyXNjP8hf9eYhs2vo3f+xR5Wlpe4v/51PBvtx78", + "duuO/H7+t1tj8tWS/D4hnUzLG+/9duvpWp8c1e3f/413XZCRXPq9nyF5nfTD359Ky3vyyb3f+0T7IzKL6d9XYFpaYgyP5JM5", + "6W1anrojn5yWp0bkwwfSYEo+eSDd/sQH+dU9aXNe1nZIeht6M//28Nsjb27z329H3zx8c/fNjTfTb2bfzL+ZwT93f/8cP0+l", + "rsPC2/E3s1LJYYT1GdCeNRhG0H72zTO0O/z20NtR/H0Xn469HX57UOo8zEslh7vyOVuwYsPP6Pkgqzug36k399ET3vv2AD57", + "jt7u4e2z0vI2R4XfhtHiLlrOcLRSW2JcKknMv3mGb8ffHsDvU29+kbdybKPo9ybf+ObB2kxG8ftj1qLAeEbezMiYHsu7ZjE7", + "zpRVJR6ylgRa3pTaFMPo0Y74Z5kJRoCnWKPiKZ56gp8pfDIm1SpYDeOujJZP8D2znNfvz2KEN9H3GOZ5F0/fXPt8hG+TsXAm", + "Y/jnIMeLliNvprna8tvP0ucw3nj3zXWZ3bi0Yeun3BtZn9m3B1kdg6vENZZ9mZFx3JT2WGfs3c9cXTwxgs8eoI9hGcPP3JM3", + "D/DbfazSCFqO463DaM9ZLLx5hE9GMIfH3HEZz2Gp0sEVtqM7iPW5J/O+yxVGTzeFRli14zr3RMYxvLZ3h1jRA9+S5n7GNxzV", + "vX+v+mNZmUPyrnmhihmMD+OSt3Id5qW3Uel/lDMH3cy+ec4xSGyY5AYxRpKxp2mQlBnkGhRtBLbAOgY8pVWJRpQwJY+VNaS6", + "g0SqFZUp+1HYZWPsJeQkrgHuSE6vRNMzXZ+622YCmDgNQ8l+jvg4qxEwkldik5ldwzzOQR1I0UXgMzfQaSilF0LNrPZ+ohsV", + "1rwa1KpNyzcS0Deg3Br6ZLR5r50Ry9GgU8+X3IhYS3ZyLPPFGwosP1H2pWiEzQMwa+HKfAvDXXXMeFdGyLD4QJmR0YGNu88r", + "T3IepbKH9ga1RDsLtnSZVO2lLsvc8C+AGYZ8Mp3NVaFNnvBMKtMV0MzcIrfMtIU0ljoWzDJhwZECwEVNopSldKdivqcUbouZ", + "mIDvKopp7tqGJRpZAgKCkFgBgygxzg8gRyc1m48ha81UMonJ9xJAnxLTFBhpaxiWyXi4QHJ3CdZCQneGKNcI4jFcpowzzEmC", + "vphSV5XUhICxTDaXZGMfOsMjeLtsJ+uuoW/7pd7H4FmzlltRYLymq3dxpqa8w9JZUo4ZcrVHwqUdYERb9oGh8YkakOg7GgiY", + "u6QblXQvSIGV7ohn45qnXUY2MVmVySO+4f6x7geWmMUT/IR1Nhm8WJKEuoD0wZQBLS2NDXSS+hisUSH5rizeCHhtsxyMTcow", + "Nj6bRbu4ZiQw7ABjgH3JDiFpeH6JyLzqu1yebbbmSoXGBldeMeg3sDtt02SsRaQCEC4p0mZPtNuweCNxnQCNWuLGGCnL+aUm", + "cQraZnaYv1lqTZlsENQ0k8485kgwYI0B/sJjA34ESImFxOccpSQdCM13tadBz7oWBr2yqEAgdUkkns8PGcHH0E2m8pW0slNh", + "ATSAeonA115V0gzC1L5/p527qySt+++W1RhJmzIpB2zkgsrBI9rbxvIhTMmgfQPSKHGrHBvnZoN6GcdHatiWMussKelE5i6p", + "LYZDwV977Ba7SvjXJsgwz0CSXYjqXc38AW6wrLUh1cEy6d4kb/rECgGn2wn1oLPD7oNNbfJ6SSEq+MLKHsoQX0o4kEnA1+SH", + "HcxuK0k9ogILMjJk0xS05JJILLj2duo0MUzpCUnzEr8f2zo7LCaTDOq15P6gZuz8QFKcdK9lX8iXKslzX9kv+AkTft9pa9th", + "hYfUwGFC9QD3IUolCnQt72UtOWaDFVrVlDagFjndnbMh9w4DzqUwh1DIp2JLck9ABcwiApvVbGKLadvEmoItkogQV3ZYYcXi", + "tKHNCiKBVZlaU2KBFIZJWsEpMfza+5jUH0IKMwvIY2htXOnxYbmknh4sa0tSzATxeu2OuSphoP42qwNsTpEt8ARuCH0+L9JG", + "15jngpXfwezAUlRmyRFV+9hyODOGQLQbrQgSkgIpatalLpEZB0i7hoGJknsFwqcACmr5lhYmC+C1DojMA+2AA7ZDMmBzd1Dq", + "QkliiR2Wm/TRSn8aSy3qnCMZ2DaNw9C+9aUoM7MVPrMivZxKwqMfOmwFSaD82OzACjKdmRmGKijENjzblzyrQFqXtrIOb3fO", + "Zk84a0lKjPTHmoGZK37KLJB+zHZbhWVI1S5PcuP/Zef+udXaTEtxkkgiO7tzVKaB3seoaVJBIpkHBUbODmip+KXjNpt+Z9Pp", + "DGsy4HGW98Xcd4MZitE+KjcGJkNX0WgWYQWVtc+vpJWyFXKQK74X1CCfK1KFFFQCBY9xsuy3xHsbqW2FqWAE2uZWp6z2GiqT", + "1ECeeKvTa3FIzAzFVFOWRJXaVxZWYM1EN1ImU8ChZ7xPCXnn7RJss6hkl0eN7BhdIhd/FUGUJ45N5zB7lOtb0czcgLTqDEr5", + "Ioa7bh3UDst+bxMtuZalYb6x2XosuYRJK1cEBCsoY9+l6Ib2tjoSyptYMFSg1jVJATtR9BPGRWOAvVbAszIp1gwSGB2aSiTy", + "hXXy8B/fOCxozrnHRounBFvB+tTdOVF1IGhWFhpgzD9TEbgPUrm0ormi+/D+is0HjrVNDNqqxa3mYZEc1gVieLYCD4tKHlQ1", + "LrmzLWUeq80yMzss+LJZZUaKwEGPs2iakdQQDEIqYKxrqbKmNTR6LKmRLuuNVxPBbgwkjiVZzQZt2zROFgJjipyzfj0ZDwKE", + "c4cyDSSHFcIcMsSqeQuwtAJZgimZVi3igslqpjUvST6Sceyu5SFBk4hrx/rCPBvU79gcnFiKrjFOn7WK9C4J8ocwFm2/lmS5", + "w0I/X3xmQQhZTuiQyjZ+Y1MimNJBOmNAdK6HQjwgLJTOqAjwXRsgZ/9aGpn2/pqyPDL1UVUqxEELV8zeMlSccSrRfqIbbqMv", + "ZVmY1qgtM0PAU9xtFYraWGb5Le19GdQqABrfWCFpE1mNFKfCxACpQt9dy6K06YyMzwdSFB9uIsJDdsTmx0qRsaBWsomwUiIL", + "9GeL1FDxsRurFC3l51mVouxXWbDHZ2qtiC7JziFMYUEiL01kq5gdymxECxkT+b4kvBYwGYE5hNstngf65Xt/cKQwzx4LJ6Ei", + "Ka1Ysh4kthuEAUFv0xONZNJpbxd5hxqnSG3PVFwAHt5XAGnTq2UubXaVdlsozTyyqMgiJiwfJKWLqK5D5lyyXNaGjtZ2lpLu", + "k+raFBfWjOhNdLWsQyYQ6NCJCmJUSHmmdS2fS+aZwxXDUHOOFL2xKcsGemU3iLyl5XOwkWNzs4zE8mMfrNQr+gLJWCQDQ6PD", + "VMobMusCFoqsEgsmuT6MEYB0Y/osLX2sWSzA2c4iOWnFlibqSQZ9QWYREzNqrO7O8nMKuDzWjk2jYA0Z2mPlmE5EMi3ZUXKy", + "BFxClLJq8boWZ4c17kDr4EmW9DcYIN/uKCNv98E+klrYRbbo6WLlewAJQQ7rWmy+nrFj0XZBthLMohfXIuNNNv1Ayou1OMbu", + "WMHWzLIJp86glrS8jg5brw30DiIEDKUEk8ofEJ4+VbhT8HmtQo3XWzgsaupwA1kcHX+9GyuohE5e18DK26y8FpY2WOLdiX8B", + "VTF5j/TpMzWEpYD4hm1WlPwNsAz25wCIkV+mFDLGZQlCFYhqdbr/boWHVAmDiHVEndpkFa9LSWIvE5GwmM42yN/YFx1X1jt/", + "N1cTKBKP6S4DnBHTljsLioLFsDA3RwYJSKMYIgNrSh3uKNqUtD6BR9nZX5mSCMghmSaS8EY1YdM0bBqIs1tyXRyiGbJvrUpy", + "k9KHLm3Fii91EUPHL1qjKbEJYR4JCK9tt1KgYLNt2sRu2cqKnGL3My07L/lTuR6MDG9NYIMEWqw90rzk/OA7LHLqJ7vlsgGP", + "eU/kC+oBZaQ+Xq4Hs+Q62zRZAEjeGNDDazGcgtwygk1VjkitCg3UuNYumVP5ooUAHvYE6ozFaaDZXIvZpeSB2DK0vvxEtH2Y", + "ikj6q9RQd0RUmoTQD38WpfgkZQG4kmW9WHvTChRnsBxxuCTSlEU0pDCFAcjHeGXpWDJT8t1tQrfplZoFDsv4czejCreTSAlE", + "Rf2HF9mkxa5CjZvpfGEh6h7r7LApryynSfZg4hJ0eS/YA/1JTbegtoeaCRIycniCRcsmpZVMo9TYKgnMGaZ2MpKVbHiFCpaJ", + "9YRoZSnJa6LFDqFjkwg3tNlELDEjcj20ehK/2mtNZ1vpwOxN434MQgqn6jgvJTQ3CC5oaSlYGpTSdbyGg3maa5Ufur9iXYzY", + "k2zyoFblPSi+mMX+7ylELZLqtPWPaSAMJIdmRi5SEAkGU8CV8vACHbSbrvlDjBRTxcR2WieXXdaWrY5UApS6bzzGSiEcKmJQ", + "YavonsL49kl1O0lvXddiqxzk/7KvEjgDcq+N2GqsAMc6Atwk3qmANhr4uK2tpzUPjo032Iw9w8tV8ADrQOF/Ylbv139jGigI", + "RdJEQeOx251r32N9SB6zy+lJEsyXWCC4R0ppOLy1xvHDv7JyW1neTIBpbbUuyUbvUY7AYN7bEK6XK0Xijc4u6+EpwrYjKiPD", + "RPEnKc2h2jY/tjUOZCogG1oun0uZlcDm+pk9a46ljUBVnuPYvME19w9L1EomfREs3WJLYJiP5SYdZ5u1c/hsRYmes5UxABBr", + "LHEnOkBEM9sbSi8gXt+wdhwsc9bJj5iEBhycxDtstZLPUwNkYv5uzSsYVBXBpuK9o7bGen4qeaIbpXZmUGunnfuNAsvInQJS", + "i2DDtlTKLJJFQW7Wu7Xx01A4DpCYO/aJdnhJj00FN9vkMLbW8oc/sOLYThiVGkLI2mqSDJfrYWo3WEZwz369DXZfWVU22NIR", + "31kGqqbSdauosQ0267Fl57a92/7p/CdxInCF2EU0KhKMXhLX6YVjdcWa843U+1svYgayTFI5jV/cQNjwaSLDfZeX0HQ6uR6p", + "Q8sbbkAvX1ofp7ZAl1fiiOxh7mZYEvTjRKGU+xVYUay5lHzkKuuXSqDzB0Na1az5GQ6QPIVRwxI3DN/xChCQcM6BRdyd85iy", + "HVXtGxLMgRRgM2QNjH+OgtUpwc0qcGm8t3aKpLDJggoYgnJ+QNS/+A6hXrdZ7ytr8+o0VtaHJEfaYJUgICYaXJuYqBkjzr9i", + "TQSRVF8p+mRtDNpNdlqsSJMVy9Mie+rYgiuSj4lePpOSB852atioSG0o7sWQF8dQDYJS+umk7E8kOXm9TYzMObaUTfeglabU", + "8l/5pc4WmR/LYXCG27BRGx03TqV+Desa5Hrox0S/UnDTsJgdjWwaBunvhqaxWcEO2JAuCsGK3U7LOil6mURSZOAra7HvsX7h", + "3RZr7KGjgKV5pHTF3/yYpLVWkGGHdWvtsWjU5sJ3VgkVWOtC0eX5mVirjq1jYraFAExhzep35yvr2tllrXJrfhjXUjk2HZRi", + "oRgdKGL1tNlCNF9YPCi5oACZv1eHUCwnZEtyGN6yRHAixYKMSL5CjfpW6nbH/egT9AmCrAF80hXI79C5svKMF0Zh41paeqEo", + "nfVSBXm9rbph+nWNBcNF9wcBU9TRUirWtnbSO6kHHVutx5Fa2RCmscMEZiml0Lk22k7xvUIfSZ63sQmwDr0ROij2Wq/Kbi1J", + "2wOihLXUQzJlemChlhL6l4BkXamZQHXusEoUtafZmfZTKtoyQRvFIPaTQSvyeAsRNkA5kmKc25orJ0mVbwYn2qoTLVJ2KKjZ", + "WjSxaw0HMjp7F1wX9trjBPo78aKA5ZyTWtHaFhTyADXa2lUmpaNJ94oV6ZQtXX8lJU5CqR9gkm0B3SlKlI14PWheCfbN9eQF", + "hnpeJDiraBeE9VfRhv4QlZR3Wo23w7qObc0b02qVDYawBtN4IxxRghVd9Ml9ag3Nol9MNC/BcXgZW15Kd+blWoLQK9py8rDV", + "WEoIPBVIvnYJ8tvtdj7Hy/NiZEP6WWRctQVAlCN1rVl/DUvACvYUAuL/cgpitsS82cyh9Uw177BWgsPgFsH6sVQlWStyxAoK", + "iWinROoBB1HqFWO6WtDZ5+Ks2MTDLvp7YEFC6W237mGi/kgeYIjRgOVbqRAP8Cw17DxeswKRYWs6OFJoRHufWb/3J1IQypEb", + "n2q8OAh/1cTbBGkqBTMkaogQg5Xocz1GRlDiVT+gwe2Sld3KqnXY7NjWXvoYyphnZ9gAB5omZe01z9YjMCwO7IBYrEuPZTa5", + "xdSNWAkldo6lSCkAgEehubzITWUhy6ytL8X0WZmmmFoPlGOLXvTsZrk3U6O2FzjVh830vrbHHhyuuBQiHvLYM0VHnAGuTgVc", + "OJ9be9rm87doGhNhUtDiW4Ms2MH6aP4+EhG1fcV3/9gh/yPhxfRLeYCmji005oi2BWIBscgKAps63VJfmOdArNph9lhQynsM", + "iCMTeW8xFef0gNy5VLK1mKADxMZnbBQsWanirdfqvBjymKaXTjSKuNFc8gercNjSZ228JYb+AhWSWWxmPZbSIRprzUNrbmgV", + "p1FrpxQOtoxHrW2lDU9TqY5in3X5bMkjw/Kr+LGeWfC6Q2G3Q9C2sdWnnO2pGJprNYz2WqsA7Cv0XdWsWlGKPFal26tKpM9t", + "wlRbqbYgWL6SCi2gdIZgyQ2UEEi29MG7n7EgUBAOaocsscOex/01hVQ3FWuv0LVCXSUnEw4kvuFYIOJowEnV8PUbhfhgTUVs", + "HbSIhmQ5WtYnobVBq3ANJkBVEIba8la2apjZzhoPsdT/4QE4+R6i2dIgL890WH4+ht6Od1s3Ux9Pr2F9ii7P5615TGgSstyN", + "w6tTbGki1sMB34fyn8TGJOYcOb6JHdYIpgTF68JIbigTqoMMqVVAgWIQ8HYLHXfYshCEB0C/Fo/n2v/T6XrnnzvESHO6I3GO", + "OLRdwUdytZvnWPRLs8X8W70YxxoXEIZ4YFAOB11jq5/x2kqWTuGNkBSAmD+Xbs1HKtLNcWypuB/Ea7fBFhIss9haIdo3aFWd", + "nZjHWm37wWOOF8E0ia1zPO+Igh4czOewnwUxiEtS8T3aynXDWucdcZxZd5H5/vvvfugc9AUCREVTC+3y8JzUSE1STQ8niZ1V", + "V/bGKhVB6hhbwM4aKl1gp15ApW3WC27N3Ly1BpMd1hoUgsw5f/cDgI+KSWHFFnjnWIrdKvhSWzcvVwJssMUQHVt30EidmKgY", + "siaaCnbYk2zWsguU3FWABZHbAIJam3XxtNkii13tgd/T0pJ3xL0IxiMVQ/zS0b9rzScudb6cAV+JrVZltcoApEfPXpwGgp5j", + "cca5lhsJClivLw0oCMtk+qjfVk/c2G2JaMNa4TTxswIBS5F31mrG8n0ulUuc/+I9q15trRoUi/ezM/Gle9vlilcj1fu72gnq", + "iG1sPUcCeEjhsl8h1dCMKGAbxY7Ls84/S4PD3uS1jpxWEpm8vefRE+dDlcXSkpqlr62+EHTtM3vSqxxhhU90XBAejf1+ULKt", + "h5hfK/coxf/Wjr6rvAQS7CSetNix8tOhjxMmHdAF73ikUxRMEltMJGfjjsNTjwrvLvVjkbTQcX7yXxb5AwtHoR/Zeo3OWnnA", + "NT1hSxLSNUpvaK6VF6ltEGdAwMNtShRbVW1t0Bv32KgBLCPvGHToE+/OOVaf+aE4A7rsMYatbPO3nq7/3Q6RSBcQT6QtWDcs", + "yBoD3ooSljtWlHmn21mPv+kOlWtr4wQrYWvBbN0WqwKQHKUw5u5adxGri3G2cgrYZisGbgQpUW+w+jK+o8oEq+0IuHIhS6nR", + "GVcSfWudt1IVn2Jm7SzSajxMnbW4d1gL0xavMj3WbJWVoNcP2LMQ2JJ6jkRWYCpiFeSrZmvO+Ytjb45JQE486mLJdmyqrbdo", + "pMg+RsY7ROjG8Eg3hBWCEtB5d46KyJ5JMc5juyrAngnt+diamBF3A89gEzmC22YEvtpKdIbc58dkXfoJaXaDfj5hxeEo3Lzm", + "uXRdogtbJNRhOX4enVqY1iq36G2oUpqhe+uTBZv9NQ1qWMY/OTkiXB5w0u0KtEanE+hRLGG6+hy57XT9n9ZDHVpE7NgaalQ2", + "HI6ts2d4uTJ3hWfeaq0QqNNlSYpgSw4h2XIDS7aBEUguMDHAtLwSOu/IuZpcYCIlOvF7rd3yb6EkyAeKgRv+qb3zQi4bAfSz", + "8GBzdZ+zpbqvT24zycutSI6yFVTzMFSIWCw9t3WLT66T9EnVJAVj87ZPR1Sk021rt26krcOb6WxhQFtgik4yBiDxOkxHGVuz", + "1JMCgrGtzd/iUAlHUmWViLpo6YX6MaTH16Hbg0tOdWXPDwctrBgsixeWZ13g4kLcw/s+rS/HsSfE3aKkgCBS2vbaN+I/U7JF", + "zjav4sfi7t2nvU5b/db53MYo7SFdb3QoSWI/IpbiEWIsChb8ztKJ3Tm59oSFoOxhMNGvkpmIkBX0K8JYbj1wsFgVIn/ei+Ww", + "phl4Mk0M5JIp1tBtUYoIAr9A9kRipNlCaUaIL6TDDOxfIWziwYovINHzxam9m4ezMF7FM7fBFs+kP7KKbmych0NioFKgNcEj", + "V547G3ctzIDFrH4vJtdGQw1bBSsZurlma0+adqtGd8QRBqwcW++RVzBwYomYgyIgsA9aNF3rd4wdg4wTgBVYU4+XVUGj7Zb/", + "5SxP5+SKB+UwySOqGSIph3fF8BKN0B4GxxUrwdKCXMEQa4llIxQDRVqY1iPBj5iYlht2v7BHBn5oywFHshh/Z0nW9eYLe6wq", + "RSZVKMcJtANEO0JmEbTZcr01Iiu5Hlc0nq3L+R1hPysBSg1V8KBEhuSt79+RSmEb5N6mXE/KGvq5HqeXDmU6LQZEBUD7QltB", + "f2L/CH1Z8BjCBpO2p3KOY48j6DIBWW3I7fzy8x2RDTgUPmdchJg5zn/ZsA1bU5CHyBJPFFH9DloI3WlhWuKtCWqRIWEFBhV9", + "HszqIR4Wz5elnvWiRaHBpb6vt50hXLBvo8SWCpNaYdYu3lwSX0x1hw0hya/VobZlXyVYocwDWJ47MuiQss6VXkS38aTCsSFc", + "jB0wNBXKUsyQ8VmcAGSDjYXrLlg/Hw0paMzubodulS5Lri1SbpRnWXJUK8y4Vnw0Lxg9CqnYoT7z1ofIMyxaNqDfYhTbArGO", + "rVWIacs9Y5GVkbboX55yUEhMIrR2WG+9sZWAOWjMhkQKjibKwo5acc+9IwmTTnzMyJ7/YWFZlJG0C/gnJQwZeiIwzR5bfVOw", + "8AA4mFc9fGrBui0BvlE5cobDx7EUX0j9P0duANExb31n2Wx2rX6vizsYid98gy1ibFGFiBrMtc0y4B6peylLK7Ai5lZZK+kb", + "W/96o8RZSNipH3kb6XO357fWryaBg3K4vhbjydqVBK61bTYQJZFzw1q/xRqigte1kJuwK4qhV1EYpixaGuywAY7i7GdCkVBr", + "FAuQoNcGi4rmG/GhG8t9ZbZEXpuNazZfujwq42UNNNIsBzj0fOGBndbroOnUI2IxZZ6r8Z62gCd3gXUz4c9uP5GYFQZYDVBO", + "2NBSUShrxQ2NJboWa6TlfZqO0IPW9LJ68xvl8NIxgKF+lry3oVAbiagxsW8sgcplYbx/hCuw0UbbQcHKwhSE8SpyhxzUp9SB", + "d+wZn0M+EzVhiI1tDWXH0pkRNBHXbJF049hDoj02fglChltnY8i9otx6yIN1coccw/sho/QAVKig6TGzLnFeZ8TFYolfWD72", + "YFpigoJAbthzlC3e6diK33l2TQ32mRJcwSPhNPkECwgqEOu6UOPxmrV6eBrm+VI4uiBhTDUxfQJl9ZiRWpeJIY+VSB70voax", + "Lqbm97rSTvfXvXym1x6T2bKYRs5oQY6yAnlKC7zPnrRv5HWQPIdNpV6ksFMQWPDUbuXKN9/YuqyfqBgiz2uXO5esjBNMSe8q", + "Y70YcMEy80CH/TVsnvqaGXCelgPNdS3bElb+VXKEndp7tWobeU90QGMLf+V61qpgym2LjgJcpzcc1MOFlQr22Ly1gG0RAg6r", + "ojrftdj4I94HzUlvFGak9qJ3lJba33n/tOaOu0po4hPWWqYkkqCFtbqS31miZRwdfR5FiU3lgvCOcswPI6vYtzMgaZCxOEnM", + "HEdesoWVFV3KAVTouObaR/HXhpEuXdROBNasS+ubNhslVraePZbDxFtofcodjJoHCLyOjf7dRGwZam3aS3KKYXwbXFa0KmF7", + "WgS4imx5zi5xvkNex9z/aIc9MhArxw9tDdC14HFRnwDesG4HAPZtdXznB16ixRM2hx3JjToq4NFZyPBfysH2JOW1jyxmy4Pw", + "XrBeReJ/eQzY5nQppxzb6xagrJ0vvtzr2HL6G2VPFIRf7Nia+XTTJ1bDiim5rsUq+3zZcoeMkKdgPo9ncmTOXE9UAH5i+WKe", + "aEc5qoeiL4oda7SLwVowxKSaux+KJU/ZDNJXLCKf6L/yNi8d/w997+84hFNYbYYgSPgv5bRjbJQeRkqg8RcbjGrzJdbUtVPw", + "5e5KUbDdOSyGzCgRu/orSbfYaCtAO7aAtmPjUQblHlhQJ/0myqlan1VkBXyb3cBOG3pki6k7tiqyja/Qg1Wri+WCJkfKnmPS", + "ypF4ig2+KLc1x0KnPfvW4f4ag5PEMUF5RfL5zh4LcZSqWsMwyFf07IhXnT77FrlojTpQfOn/O+3o2LJDic/QURLp8Ic/2GhV", + "4UxI0q7eHV99umfvVzaAxVZbb5eg82jf9tqn3obcPkkANRsH7TEnxmKEKIsOuMyW5XcsQDXO13ToytlhWUk5cuyRbHGhxvLa", + "PFCzBx3WsPXabSF+ez1XOBAFxCh4A0/5lGXYgj2+/9Qew4vHuBTxwB4DtWzk2DiyLuuzUJ0sC93VbsugG4mvUolFDjYFINaO", + "rQEu/N1eVo7Y7FUbXfsJ9VE3PWRcZ+ZFAwn8TUnIX/c//9W5oZja2uSmvUfc4XS9QaN+atdF+KHrHXsAZBwbErJd+30SWQUl", + "+OqaZ8P2JSNbpxCo/ZDRJaX9ACYKhCP+to43RVNL9WlmP+D9ib0EpsLUYDeqvrpektsoYXIwSFouVIncJOUVVKmECLMLkr80", + "UPYuBya1m39nxCuefb66z/gJ11fGfqdsDlVk0/FZpZ3pvjbuQoWvFvBcpJj77TFLmLG6FQyiwEsfqdlsSnxkb5KCPdwnNpFg", + "4nK0lm8uWUVexHLqJcaIyqUbTCXnFX68nZE4f8CGq3Kc0asFXsUcie6IjE1timySkL3CSbJOYhag57VOfoQB8ZakiuS4RzZj", + "3GjrDJJrtZj3gqWKaX3qV7NRImE6vDLK80uRXEnhyT6gM3EN+EpZZxxWgtlTpZQO/NgWADBrtQX4l6/FzOeFREzkgvB7NZWk", + "vEgp5L1MzDrnDUgUvX1RUfSKkmwrnrfxOyURchDSkuFusGAMhsbo/VePQwmbSiRfFgO0Sfn2ygPDW39cVi9wXbaE7YOpx3Jx", + "l9yfy6hEXuoTv7pOWyf21yoTmMravjNLfwo4D3QTKrvkUpQBY+HtQj7vtqowc5wS59VCKFeERXIhWIXXhGFZlVQEkHh/xlrI", + "bdkVe20zbTGe1vMwnX8T5DMuCzypgKPW0pB4aaacAPKki04XuaM45h2i9paA32+y0fts2o145LEfdKJSSnKrEjnZ9xiCU1tL", + "RDRrUw7WEunM/jaJdti6lnYDnFBk7o22yQsJ78di2j0rrici32zKiFnL1vGIX/mgBO7KfH3J26L/iY5HRpGRnplZxVB0G0em", + "Ahr3RJ826EjHa7lcQI9GEuhoy4M6Al7fTKy/lrsjwo7qdC2XzkgyAYFGWJN0JVUwEl0pOXo81x2wt3HDmFf7GTsmERSML7TH", + "9OL1xIsHrGxzutbOkmmAMzaDxw8MREuikojCtaQcryC3B7Ee/aBYGmv7Jp42OvLMWnbSZ2v7bL07zJu0+W1y6zXfD3nLGIkK", + "OJCBM78nFliFHdTkYJ0ZNHK7a0y2UFQGRS73ALNZtLhvJSpUbqaRGPuEaUb/P1tv2iTXeV4JyrtR3eh9X69T7WZhXKgC5OkJ", + "N6pQDhAkRcgkxRAgq2c8PYpblbeqLpmVWZ03s4CkpAgQJLiJFGVbpGSZNkURJCEIAEGAAAFw+wD7q4L8ZDDmizuCpKiJmd8w", + "85xznue9b6JHC6oql3vf+67Pcp5z0DaQVSBOp2TsKmQieVywWq6kghTLn7y6s+nbVkQmeoeiQaHMRiwqxbpKoXSWtyCNYi8w", + "zsj6U4yuzVMY+PZ923aoHAh/H2YRVVqHlLjcxPgDaoroHKx+zANi8W1uRnUjggB25RGyiJiPfC57Zs/PTQjfsiGUtkHV3a86", + "EMQ2ZxHXUA4FXoW0ETCfx5j6XaIcJmU9XIV6rEJVnG9ElaFyBshIr55qHGje3Rg0RE0AsIP2A+QKN6zc2sI5sOFFndKGWV6y", + "TWnMMJkKBjqF79I9baJmXXgRosfgJ4Spr9mHKhaerouXH3BsxJhXR0KK2X3X690rdX/BC85iHWq6sb5Ixoi329YLDhubAMes", + "7xEgIt4NoqNdPCSWg0TeVlfZNff6OgFggAuMGif9dQ/wLTsav7uviMLTEeXYgeDHAjoc+4dUAYaIrLP+E0pa66MN1T7bPGcY", + "kUBU7qOoq0XYQoW6qxPKxYPeHgvVPklh0rXK91XOT8YqNiB8gJ5E5Fjrf9DDQKs6rIt5ayt2pIBMpxBCGqLFEyZtvFSokSJP", + "qJr0JgCAYL0q12j7HBB5W6iVMy91hK2D86NLZXQiurRP/wfBm+YdhbS6vGQG59IINTDcj1TqVUHQmaE2thYl3o66pXihPfvd", + "1nmwzLyWuvEC7QbBTEQpBZnAOG4OsJ9H3TgCAnaKVkqOdZZhjcEVUulrXX5NdTNF4aWK9/i+IY6h1REPa6p2aF+D1wO72QN9", + "M17j29A+NwuRtVKQ9uur3EnKBNZ1jMH3HB0PnCUN7obnnSoCuV98JfZ/1cl0vWy7QV4H+8FKbfse8itQBavWhbWqgV4ilBtQ", + "BaZ//ZyZMKFj8+5+GWo9AkZQcE77TavL5lZX+igLy17n3bC8ZKYoHLLWuHrdJCrfHEHelVYX1r9QqACHYp+3VWYeqO1fdjc8", + "o+aNzTczDoTAY7h+mS6wjQwl2/k/7Jhm8WDQrdMc5bZwj0o3CulIdZY7hfSXilmtO2g24n4elZ3h+T1cRbjSOqsudX5gEGru", + "k4teZweTG7p/tBqwroEKAUrD3D5s5V5sLO2QfcXnVarUkKWAMSnbf/U84x4yWUteOeKYA4CoeA7TT7KfS72a85plTTZ01O1m", + "4R0CV6vVkiJ7y5p/iC8KFiqUQ7ULAVycew6ULjYlfThahYdp93Yc2T6uPzuPHSnQ6dUPcYZ5GLHY5W6jF1t1pZszM8PFZguH", + "6sebkHPvc144i0DjsHmGE7An4ZxEtY9HFCc4i3HePzDusuLRS7DnkYbGdQpfwKpxh+IeQfIduE2luUkSeqO024jlGTw/oYFU", + "8pyaLxQW7dYEqxQqfVitdsv8290pVLnqwCgWEWL7c+ieOwmqfiRQqpK7yH3GFqRXJYNxioahzJ/eZF9xG3OAtwkMdBufNlTh", + "sM8Si4aaMtZuFDpX1yZ3mQ+DM59BYBuhqOJxFHTj5bN9ohoI8N/m/PgaCprLzSjsGn7d2TG0D6xOnD8AgQqu7LVedQx25UG3", + "k3vl0SHnk9q7LN1JKlxxvIusZBbryZxWTONlp7MwN30TUJi+E0UU1PHCCaD6xGbBgwILbgCLzgL7znA0XvfCpP2dDueh/XEU", + "uzNxGdxou1QEs/WjrGen8H20i921Udkf98X/CLXoemsR1fJ32LN13EuH7wCdauHZOgXmFmaQkC0oizQLXKqP3PcwXAjdOs9D", + "w1L0Qd04rHFmh3OKOBGHHR62OmyfRUgJ+xvKVWkDM/dAxUaGKFWFwnWwBUdvf0fwnTsdJON2YiP1zE5RDb06vOsxzsnmFtDf", + "IC1BFA8OG+pT/HxZopofDhgBexsnEZmH7hliLIXiS/uDPEXbR2d53gHI2vfAAlKrEm7cW8cRNe9pKG9/10vYCy+ebe5U/SNU", + "jjAPmy/7Pt9xkLyWG3Uth4iLOuNJU7odxBpJa+AdbjfRQbUHmC9U7D4hoqG35jClwkyyjdq8FufoKFgxtFLD04cfN2G2lPX+", + "2g+RDUPQVLsYqhT5/IVjjxsHChdeR1bt/r3f+0//effeDion4Eu68z4sgquDyo379ngGYQQfCXPZCUGa3V6DxBCA9aNjfQq6", + "ce15b9MGQXFUuzDf0vH9bd7Pi66XKjfrqGg0f3Rm5gABCtBAwj7G4NESSABWB92E1+wsI7qEc8kJZgDcHmGjecAmN4JoBGXb", + "cziIfR7kJKzltH0c+6hXKzYqlpzZoeIdzAux7Xg0fnE0EDJjaYE46uXBgz3EA0ovfkM8jlXde7zU1BkQmq/4vHXui24xe9Q2", + "uo1ivtDzwQ7BPkZ7qi22HjrFSuHzqfACi44TVhTOr4IgDe3DRackWPTirEBDaF8re3M+/wJBP6/SiY55Fyy5WfbwHlACq7a7", + "A/UGborRhs1He5AuHZqm+o8wve125tMRlkfxWrs/VxvbL2IUB5MGmqZgs8ruwEtfOohjmJ3TW/J0uNcSLi15EuXroIzZar7p", + "1CGNk0fEtCy8srOg7HYf9r3ynEsrik/2vByq8A238Kp5r19ulhRLLYJnwZlYUBZoe7xAWbCr5N/3JrucjGJUHmNpBcpA8L63", + "e8Y5Jxrs8uMbZxppMx8ZFO6oan7tnDGzCfqqE9s1rQvrhl612dFrNsknQGgOhr3ubUA39bqo1PDh2h/0OO5vb24dWwToe3fh", + "ddlO+tP483S3S9nrdm5sblEFWfEBpHlYVKXy8dgm9/A+nN9CRy95QeXBiO8ggLJWH5vxheLHW7HkG77TZDTMjwE2LzqYonDD", + "ys2bgiXmtm8z/QNqA2eDiVpEZsIwj8T7sx7V7oJ12HecRqmwnjebYFl2EPK40t/DoqF9pOJSxSXQVE3Lxveteal2HqI2qfX/", + "BE5BvG/37jhf0i5mSeqmcFaPhv1k4+TUA5g35qP04fTaZm8zUtig/djpYCM+UCLjiywQ+FEa51DpLK+Xm7qhypYLZEuw3nw+", + "FUiqE/2KXYhxpa19e7eOFfP+Aa9WaRxr/IVe+dAEO2sfcTbrIPYv61+4DXRo7dh5LqDW0oK7m/7+vi8seKDPucMK91sLZbY7", + "hRPeeDradgqHkTmJzMyspOB2zUoMbteGGTej5sG6drtxONi88eP+Xz0yuvHO8MEbr1VggAOzG0OkN37SJ0rMzEoP4rt2NzTT", + "GQlv+ogsY4LTDqsHPo4Dj/bHuijXBys1HCQP4zce4IaKHgyrEvsQzk+EbMY3fmLXp72N70/IkKpuGGzduA633NZ6MwBvqOwL", + "nLvcJxA37SHsQI3EPuJRCEaPEPWmf4HIBrhoPV6Ghoxqa50nFBraWzcu0c8wz9SMKUbkm3Lzxk9g+G4zWmIbA9iHuqQr3aKj", + "xoLVcuhFmIMtFKyhMgT3tedh0gJhUF/gnmxo+D1w6d64NOyaa/IQsiiDh8pIjAiASxVRG1gx/KB9Zc9OHICflDLRdmzj5HFf", + "Kmvic/536UmDxvuvJHdsvT0o8Ye1kZzG9lz4g7yoykPAjwfnTCQrzC4k8gS4jgHC7CU6sV+XiEvifp7isL16lYy6pbW6RwXs", + "mu+vIcqC1xmBh10T/gZDRY0KDDjuyN40KyXDW1UwcskPK4cejxkoSoO/4Vlq/sHAe+DGpW0kDBR/Gw1GN36yCgPD3n8ARMnU", + "lLf2Kx1VwnUdw31CAgQNUHUqihes926cQ5Jgm/0jHjv/HuYRMzuIuw4wn0nOAXXkiqWn2BPwi83PG5fMgRkg0sN+Y3kRROGx", + "yuBfiZ3XdiT2E8fD+mmwpf5nHqHG/WnvDlBMuW3XgRokrgewSr1SDz0uWNKu4boiQLYsNU3tUzfOIRDZvXEJZZTOj4F1x4wK", + "OKlvnBsg9b0Kzhtbudh3ze6BvWwOAvpnBZEYMDsBds7ifTsPS40//C70I8XMh+ulyrMHNM4wuxjvBPpQ4+GZnHPmHGyTZ5g0", + "YA+BRhqUUSPGu1n9p0QT0Ck3zoEdmEzZFZfv+tg+v42vWbtsmYLxONh9G3smOxseYn7mxhsl8iOAO3sCSvG2iicBlVE9v9io", + "ZNLWpS1ewKX1HIAcif9ZJb+V57psHqh/SmffvfDB5Q8fBpMtfn544sOnEw+w/cTfzib8zgfP6XOJuRd8vGDTJc/whyf9c9d4", + "TXAL6zpXdR8w3/Lzfj37v96/QKbhN+w6aM1V+wT/xmfJ2Pse+XivWUsedRbid8VpTFbg96w9+nkNd/rwONpsf+H+4j9+R+9/", + "+B22/Qm//1WwAztr8pvOASzW3gvO83uBbX+D9yTvsH0DjMDPgtEXf/GpT4Bx2a6NluP53uY18P3L/J49l7fP2qPPkEMZ7Wc7", + "0D68QgZk3OfbHz7Gfvo2RoOtAH/wm9ZuMSdf5tXe5HOqny7a7094f73D8blqz3bBGZsfIQvyBfsW2Yrtt/f4xBd8XL79wVvk", + "Z/4O+YovYZzIenzJ+++at/oE2aXftc/o++/5817wn5g9x9mjV+1anBd87WnMG84jMUWTs9nae5U8sI+KD/bmGbCzfnSSvLBi", + "jP0JX79ARtRHyX571k77p8Rue/PHYteFBQAuV7LFXv7oYed8bVlo8c2n7N0n7JU3wcFq74tLV5yzr/HbT4Bn9ubL9u5P7Yrn", + "ybir/58jeyyu8ig5ep8AV+vNKzev33zL2szrOgPwI3wH98dVXycD8KP2qdPe/kduvkl2WXAFnwTHrjPRvgZeXbTL3nsVHL1o", + "qf18i8yy4Islm67aj1Zbi8Xi+4a1/KQ/78NgsP3oBLl5T/J6F52V9ydgyLWfrztj7VPsUbDhiuP4J2CSxXfJtotvnkV/2Gdf", + "Jkfxk84g/Brvfc566Br74Yr99abf45J951H1J3h8+e3Xyb37mnhv7W4/CR5esvNeEWcyx/Rh3d+5es/Y+w/fvMLrovfOs28x", + "Lqe9fa/pfbITg8eYPL3k30Wfn5RVaKP1svfv6+Rsfs3H9DE8D/mbz3BkTpJ/+Dx+07h8zv/zS/7fX/b//qr/93O/9Mu/8qu/", + "9uu/8Ru//mu/+iu//Euf+80dM3/n7+78e3//7/+9nX/378zs+M1/8A//0T/+J//0n/3zf/7P/uk/+cf/6B/+g3/xL//Vv/43", + "//bf/ft//+/+7b/51//qX/6L/9f+E/fA779kP3/Z//9L/v9f4Xvxp//2m/7fz7FRv2JN+bXP/frnfiPiWoqyogIlMuSST1Cs", + "eHMTFUATO3zqHqIsJFeC4X7HkTsWjpGDiZAycxRQpol6TygdVKONtjq7GirmRWKpFR7j5sm5W4/gNUCyw044zOZnMOa8TGoO", + "GPGdwqt17LweKy3DpCUgegMPaylsUfcm8ufE2dtDTKhyEgrQ5qNCEJxgnmMu4pdGvMJggx0Nx0z0A/TCDH4nMlFbqNRHmRBA", + "5GqG55CdWc08QFQvMVKY4BPVMQA6wPCLmDYzafJcds4QnY3vI6VB4q3b6wHzRpNvBfAy0m8NMW1woA+4Y9kEkqLpwpFFLLsp", + "yRIzapOjzjRgFgxxVmZMELcASL85tj1GZJ0Na2lBXJ+gLlTs0W7DpKa11kbMmoH0L17BpQSdeqjqxi26pKzro27MnoWYutGG", + "+cx9mzr3eTKtmF+zljWzuxZhv/NxNut1jVfZh1GzGhR95jKKMYWkrg2raUDNB/dzuxKSDe4/gilIPCJ1gMTgRPHEOkXKwTtp", + "swexaeWo62aTXDX4TEWVdTPXDvSqYwzdl1uKvHUDiNIQt43QlLOj2URaW0OsEskthdmXWcGK9wUutl8WItCI8h4mHxxtu7+z", + "EqPMzN1R0PyxbsY+AyjnjdfKurnbJvbk6GCA/F0pj9uBOI0tEBL8zLCaAbe/w2xZ+N4okSOKoXvQ3A8W04AzDhdubnecDwJ/", + "a2NccHnGQ+zhWgbfEUAGFWnFCkaFUPZON29NqvaOBa4Qc9hCuaoyFTMBeWhYZYPB9fxC2RP5LWkDHQfg5RadBQflV907Y1lt", + "oQLqUH80CzkVBpXHfa8ntXuxyTNKU1oz7rPJQuxgxcQr6KvFpFd1R0cHBRgbGhXFjIQVZOW6Ux13lllD3i9RlqM8Z/d2IpZZ", + "FT1Uin7EhCDK5OEzIEhMHlLUFsbTNHfCmVqxGyw5WHI5EuX23WZMhG7Uoy6qINyu88XKZwJcIaZ/zU2yizPvvsnCqyaAUfN1", + "n1gC0p8JA3Qw9mcHL42bQNmQzgXkf1XgnRoWRmA4+wKUo2B2XUSbnDWi3WWp/ArgzUzXTJwSrjdBdSfHNBLEi0IKOERJ6TXR", + "Zdu+Yfs6eVPwBc7ymhkru7J4OEHJgNWGEC25nvCoABRubQxARVltWudtVQEOaohqAoxiV8SbQcnHKyshRz6pzcEqUnEs+uf0", + "OzbSdtGMPSvo0XWk8ZWGbNIZ4PdC+WDd5YyyNqO6YyV4ym3jti1OUUzPUncDXtVE/nymGTfKuHsGo9jTbNVDnFy9yIXPbNag", + "7TBPTVly6zFn10A8GVWzNoFEYWaN94DXA2Rrq0A77jTM2HsFcupi0+eO7aRaZK/VgBEAgQcUOTVS+mCPiaKVMY7+L3mwsCDS", + "npQOHn7tlr11nLQbmwFwaoBJIbmzsOH9irmR8VBgLSyDyL4ojS48jJekEdinzNNsQEUETZPBIPL8XYxKrm4UgRbp7o686F3V", + "yhCshkUkcIvIJO4j5AGbnS1A5rpx+KKCDpZMD5GK/R3NzFUwuZY6gA44YK6QPQR2g2Neanw3OuMP8E9kjQNlU2wSoGBHCeE7", + "JGddW9Nki8jkDg+xk8eDx/G8zVknS2OBbYkixYF1+9GNQeAUPTDUqE6lhpOuVCVzkUJBYgJsY0/riu23BiTAA7LzTtAy61R2", + "QIIgc2EtxDoj5WLCPOETDD9FFq4LUmAaHLtji6z6GCMA4Xs+NxziBozCskinImleOLds1b3Pw8FFnFZLawA3wLI65AjAohj0", + "V3rjodl1Y2aX+YD1lrhAGnKRFfda/7GKplwZyMxwdl+vLwRsvUIXwLwQpbTtWn2QHxDl190mG2WzdcyB/6u+MXbNKN3fMXum", + "4wg7SlSI1LYIcKSrXAyGgRZrPN1XdQ8DvYcnLLtdJqRmY44UHqKvWNpCLiQ3SsEdbc+B7f1wbO/gLrJuoWjWiOxuwerWdWjX", + "sPkSwup4PPAesFBF2xe4tTyd6jVx1loAnhFYskdZqUEeQijIOmy1o2SkBg/HsUUnctyoQH4PBibCRcfDyL5VkeDr2jFR9sXb", + "4FsTcnc1cKBUIUB7VIlsK+IOh/VMfO+lsAIIj8wwE4GlmeiEpBHzJGxWo8IuVOc7inc+ttOlNaLxQJWB1Q1CKNCPNySWIkF+", + "jcJ71AfZEVQEaoaoHBCe8MSCQQ6LrxSwVF1YjPvOAWjr9EESbXQKp6+LZFclehZySm9WZJ4K3NJkBTsnUh1l4dznHB3MSuwA", + "/dHy0sJ9g+FRO2RhMhNdxGGyLc5xtfBOhrOBpIA9D2T2xDmAQc40kpVM6BbRDX7czLtaAjZ8eTdDm1jbHDggKDTK5jKwllG1", + "lKCrF2EnKphXBNMppaxgi5enln3mQHsEECkEeT6HAh6ohzh3bZKxzg11mWKl2K5QcI4OrpysoR6R68UzWzjBRBoL2oset7gu", + "lDiGg6Nkh+LujrIsUUzYfAv8bbM56IEypWqIwbc9jLYoLXHQa7LCkuDzDbOWWS5HvoXKNzRSo29hFybbKPAILCBi1ZYgvKog", + "AwMIk/oYZe4tuE4/zEvhNe1id8a5TAI1THzK+zWaopt0Iu4XuLzskSQd4489cxUWmjmqIB0ewqQRPkLUVoDL/NYfHSQHZGfZ", + "URiHHVxWOMuCbZUVzmv71nxxiBxKyLWp01TwMEIKVlDCeWGgBIoiKLFxUuzeZHc4qLLZaPyPnBjHxn+3YDZrbmQjV4hOWK9G", + "B1lNSq8f47W0oMTiMkugNr3YuRYlpyzqRkwDNB2BBaapxv2+PyLLIdJ7giXV1dGv1W68mf2nJxUfg50ReFqyffyhbXoPjW0v", + "nRWBQ29CmwzutNJ38OuExwR7z7ZtawUY9bY1bb5WP1hvYbbKuiC4RJRqE1kdR1EoYs3HSR95aAeQwT4UV3M5YgKNpwzZkYYo", + "6eyJ3ser3WnXkZq3q5or2GOV8wUuR0r0EO0xPMIR0Z6y2JWblBcobTYs5sKBcRd2HTtsSUzB05w2NvYphOzZMPSKKHIxazGm", + "R8LsUXkDcorYhDF7+rbvrwMx5Al12xy2UAMGTCTZ3EkJ3FPlp5jBQfQf5zpa3AV5n6Yi9o3SSyydVQX07kqCF+L1BJ2GfZqb", + "flk4B3gP+1hDuiSGZgZrX/ZJWzj1ka1l+ne1dJw2cXCYmdvjOid8paFZ4moo5MMgpz2FA2wufSOwmCqlJkvfuu7lkk5I3DIh", + "af7g5roANeSaA2UX7G9wT1bSn+HXI0mOk3xUbm5BYIN7Lwbli0PS8q6X9JJQ2Cz1DRCSdIsSVYMYsUGfFLgYOHzra/DRvAKc", + "tqjwyEc2aJ8PQykKCCQUJgMq7xDaRjxs9q2DYfvFc3WdtLrCWqxI2b8UyEZHtu2ccTduFQg5HSUBSlguWahvvxdFSDw4zhQ4", + "kDXaSLsDwu6Ui6CSmogFhdw7A+s6mqY4NMU5jJ1R1eZgARiy1LH5angK7gHZPr/OCrRRRR4ALFFUKOqQxKaOiztX+lwAQDrL", + "fi9CxxXWq0T6aEuYghbcE4A2ECcjvEqzcpEHhg17cAMUYDVYO1Q5YDOVCD9wtDU1FjOS9nr2mYApKIZGAgkP05FApjQDg3Em", + "RiFIMbENBxy86XZBsDA+CDUDrGkUh4TggFm5oDcDyL0M6MyS2RE9cDyohZvg0UMA1zaZmRmnLnYuvdFAZTkIXnndRLMcFURh", + "CTu0W1JR4y2OBVJ/GCYq2sLuLh2412PJr287YMI66hpbNHedpeqgjezKSoUu8H0jqkSao4iKmF3Yj0hFlNLuI5feCuIboka3", + "bziBfbEXBhWCgstuafUm4rDFnMTOj2M7ANxFVLSxyphNjbhLIa4qcNlUtq+gV5sIDdmeNTywLoC0wj5ikN/aMEstaklszq4D", + "ZRRFGHNrZrsxxESDAdZH4JSWQELFbRBrhxp2IiyAxUiD4cEKxQBmRCOiCLsFG35Ee+bEc2QPeJgSXzoHETQ3m4SVXLCA4xAP", + "8LRZMhqB5ZEzOKEMWgsiALhN+ETdI2GvglSPW2UMyn6xWQBSjKMfRo5TpoJtpSHUP1Ua2C08ShQx6kkC5a5yywSJoYeIrKO6", + "fda3Y+DInlVEqV8M9xdYY4/rlEWrQqY4m3vHg6FopICOAbmhTfAi0g1gMyFEa0Z23ai7LHujIPU1UbIzZlusunUB5lPUlUcQ", + "bASSO8gsyBjAwRZndoCklpacuWFZ9dnWhsDp9ANovRynzR4SXHB79xq9OQa+UcHMQ5xejRnkpMuVehd2LS+onGM8WjSNgk4X", + "EYPd57TXvclBHp92UuCCot9FdTv6CNOPRy3eovktiKAY2MWMAR6eJg03wu3h0UOzRG6Ik01vVPfaUhlvkiwYVFe2ymcjLrYJ", + "4YJmMCq3ogyzLHzE7kByAFcUfTRPT5ekkGCLNRGsyt/EccRidBlUdjNsT52C5obZJLDy0BuOZ61TRVHj5A+rg4h5FlEcVJIb", + "QaVGYAKySVmyGp66EQ65dE7TesTFCmxcEeD7WBeF2Ghshgge77hGmruMhWPf5QRAC3dGgH2/E2XOdyvZ1VWgzgsFE7BL2HWo", + "hbO04BUn3qma4SAmqViDhzbY0tf3KRRx95F77yEtBHzXyT7n7j64geCg75A8TMhEhgxeuAPF7kCv+kFvrm/U76HkhqU1ZZxN", + "xMahuHotkhQ9lG1Vf/3S2I6x0Xi7/utLf/W0/QnB7L96xn/522uP/u3V7//t1R9/+v1XPn3h7Gdn/lKAvU/OfV+IPfvl/3nu", + "hf/r8rn/+/k3P756/eO3j3987YnPzr/08/Pfh1b92e99dv4Cvnj6O5/99PlPnjn+6QvPfPLUS5/82emPr//JZw9/7+fv/vGn", + "T7z/yQsXPr7+2sfvv/Hxte/+4pHTnzx+/edPPvHzU+99+p0/+eylpz999QV78bPvvvvpj9757P0///jq8U/PvfLp917/+O0f", + "fHL+L35x5unPXn/45z96+JPXvvfJH//g43d++OlzFz595vwn1//00ytPfPbmtc+On/zkqb/85OTZT86f+uz86c/OX//k6euf", + "vvXGJy9c+uTqiU//5Nyn33vP2vPJ09//+PpZe+WTU699cu7Vn3/vxc+uPPXpX7xi//7cHue7j+Hi77/06cOvW5sDTtjY3Ltx", + "znyGAUw3TORypQRsGxmSMUFw1dAxYN0EEjT7qieYE2wt5G1thrtTY0t6TITXyo3ryOmy+lxoISq1kyVA3g2CsUIPOvy07g7C", + "eBtuh5OVkIQAXgHUR5oUgqH6MGZZm65zuYUzJlxkU3uAa6DKaELvVseE36nW+ca5st688RLsi0DJlsOAVw2ZcwHSEuX2vKmZ", + "cTd+soYqfUhkOSZLIDIV0+oWxMlhpr7Ug1a915/bpusAqsYjZnVp2z9SFWXjNduDxkFZoVprPW+NufHS6kh1JQRGeh/WjiSz", + "V9DL7FUsHDY1nsJR3oSrEcZX9rzuhcwL9gK4EMhaCS+9BItTH3qG/Yes+dVDEUA2L7/H2VIGjK9xswxTYAhkZR9IvJeYyQAk", + "lxgxtJmTZKv0bwVasAmYZPT8oAlR7ROUxH7fJbchOn6CwtgSBb/Kf1/hu5f51gV+7PFQIpdI+cN/e+rP/S18/iz/fZWK3dfi", + "OlIlv8YPPxvXOc5m6Kavshmn4+unujWYKgarjUuAo0kX/vaVE9QvP83PnOfvp/j7T/n1CxRHv8oXT0WTLoZsue7+WNziQqiG", + "X4m3rCXP85WLvJ2a9FzcSyLlZ6mnftybil9+yKd4mndUj10MhfLnKXD+ZOiUv8r/nZLOOq+gTrgSeucn+d3v86bn4i7fD7l3", + "9eSFTK9dA/dkiMRz4LyfraMedplzvPWi9zYe8NsUYn8uOuFk3Ov7Idx+ir2R1NZfjI46wQ+rPd+Nm56PHlPL34tBtz+fCpX6", + "H8a9vhtdpAtKEv59vqjevsi+0nw4GwOtx9FcfS969Tg74Sybd5qt1dcfj4Y9htddV17zWXNVo/MkW3suZOwvxFO84FPF+/m8", + "PxfePcN/X4gHfCXudZztvxaq9mrkj+JPffhhPrJW0Cm+mGbLqWjeq2yzfj/jDUabn+YjXIn2vBpT6/W4qZr6OgeXN/I2H3f+", + "Dgh8QT6GxS6RXd85czBwLMUD5XapksUEYKEym9gslrYCm8PEGiXXYANJu2GpjHfFKIktzHVpvrBnL658WFcOEFADtoju6nC8", + "uQJr0jZks66B9HkIu1NPjiquchCSLlDILJ1voyYS2kM/9ymkVfMI6MtW9mi2/dZP7yo+WmZPvrQZdRadIiWxQzFR3ygFKnGV", + "CTMTxyCaL2776oHdw1Qtn1BIDYIOimSzLXSUv1aSg3g0aINv80UyEmtWEOAbCCqsDJHRUH6XPJrytuvEvLu/8/nA3JPnzQ05", + "NxXwvNXRRrLIzhmCvkLitha2RupU9daRNIL3Q8y6dATYVsmI9bgXYzlPx/jLa7MduMo9Ykk8fc1+9iRsIwU++IVfSVnFrydM", + "GNP/5jINuv2Bl8QuMYLNq6A4Ti4pSaG26M2CdtPusr+zlAU46VxQerJu5ml6e0rMrnJw0Hefju4V/N8RBm03LfyUGIemxVjl", + "nJEy0RPZOWNNBWOGqq5n4xyeI29m6atnGAriAI7g7dvTCnCFSaRw+hyAuqlmKdQC+uqUgeoEy0qncBSDnd/JpF9IaJWZ0B5n", + "y8zOA7Z969iiu5pb5jKiwmNjEond1ci7i84OYBrWyHtCsLuVoB8gChPTa4QTK8YJVmBsTDYmWwOKxDbzykbP7lokSxdD2ESN", + "uHowODrxvHexh9ingUHrkNByy1lgnB8D9QZj1eZFdBd9imzJSLlQkSl2603PJ9o8OCggVdQwIt0DJ44m0urqeEvDOoDDtsZy", + "LtRIUtp+OHCUmdeD12JIQJEDuEVil1p3YE692kmVTFSRo6xVyrEvdKsY/dU017bGYEbBVaoeuR9URezjQTVbAQa2wo/nRsI5", + "yapUtiC5it2NvbHywCguVInDD1bF1slp0CBuu8Jc8BfTPjkzcwe91GKU8oTwOGr5f0jHsD5p5LGcEep2N30NMhLB51hKGQGF", + "lRAzug8CPlREW6kmA415cCVVXa8KtL8cSSTGEl8LYgSo+p2EDtg5E7woi4VjdFjTSdliVJ2S2xVE+gn8FHEtcC0xg8+WOhZt", + "50yRIB+BxygKRdD4bCvOu0tWOoWLSPrJ/gvOgqp/P6vnxyhrQsaUiXpgJcyPQT3oZrBHERfCDGjZY2AHlZzHigbFuMXnGQ5h", + "PMNZG8B+2S8cVuSoxIcwEwF4RGAC1ccUtmwiygZGB2Td8HiMeRJQuvGFmBu2WzhOdTYFtckqinmEE4zy8eAh6jh3etfTzMMJ", + "kW5bwgjFTr3Wrt9jiZtDcIi1cS9wVMMG9WhgGhtvEl7C3Crap/hEf2CHoh2yo0Xn/0BgV4xfNQvjhBtyFXBMj3E/ohMB6Fud", + "pNAcSMSRTMEg2f5MNeUh1q8ME5/jZOforSooTW5GrvOezU5PZGMsSXe/J2GLA/Bke06vN1b2cA2MxwzvcvZx679fu5l9eW/6", + "7laDeDROTiKzmENRuSieyGY2XkDmeUAtANvAQONacc0kwHETeYbeZDmBCAdkSwazMYJvQ/ZuvUnMLMS91woJEcyVEo+we9yT", + "LIWv9gOHiTioko0zCfpcK/ho7x4cRGKUYABKPdwv4VNi7kgLhCxnoBGKwxGFnxPLA+thBcuxq+xMN4HdIwDnSFSs1j7ML6BT", + "bB9S9t6BZLqy+HfBx/M/pWx4QJdXQTnp7q6CvrBpYnUvLSS75LbajKk9i0VdLAUcd5XIJoFfEvi3UTQY6y3YjnqT0UA8vURl", + "owZshHDzbif//dZM7Fhefw5bRRXVD5FDqNJ+ABA7H23Z1wzxHAMPSd5blX1W3c7FWqiEQWANOgLOEs4QJgOhxCPJigSUUTjX", + "lbJ5sCKXGwGPpPX2WCjjkoXHYJdSKlOQA8w1asTRvkKgYaMSw5GnvBtFb7G5Ouue7RFKbDUkBaUEMNhhUy4pnfHNl7Tz88R2", + "/FpYHmQ3wkZDzA96kSQ0O9o5iYAS+3Q5OSAJ898wbMskSWR4quaOtIclMH2jPOWYujEqH0WfFJ5dIBUjqaYTlngHAwpEwbh5", + "ir2zCp3SFsnkXN8cHVYpYnknWLfS+MjkJLRz4WgY6+h7xsfMdrPOWQ+mkRJRnEITS5klZNw6MoY7uxYdSHG0FBqNSu4soTDz", + "a39HsIk7ETV2hh6bX75z9iYOQYPXMdjyU3ec9oNUWdH/cna6xB474zBVJIRpJ5Lrl8hem+QwabSOHDJvG7nkqtH5B9IMWwPo", + "gnvnTEqOOiKEIX/UgxKU+Luxi+qka4gq6rmHJpgT/TemtLGPz8Z8mU2o4EZCENgVUh6mWSInLUxoHUHIk5A9hVhueTakcmQW", + "BO9LqYmnn98CpxWBZbRuth107vp/2L1Jf4z7eknKQ7D11pxkgOTLtBSxs9rVbXfn/EPgstoKkFBBNhmSwQKyrisnnOsXgnli", + "sNYcdcDVvHtP1v19Jg1gbxwdIpvbL1YmCUzTJFjoXuw73WF5tOyt9QblaB/IfGtI2hD3kvDnLay/kZI2TqQ7knW9Ag0xWqpb", + "yUeELSCQAe2rPgvKnUUSMEsviCgEGsMqww4nUB880hI5lNJ51XqYa16Y0pCN0qY9QcM67bv3J1+8V8fMOSzPAexdesHMDuzy", + "NJiahE2kfp9EGO5BFbMiBEjGCyogIUamy4mQF0RDeK3ugbRqU4Z38x6BOQfDSYK7fiEVrUB92O0ceJoVR1B9D1m+sMtxN3Bs", + "oCcJS1wxVxGImp6Uhg4n+96Z/KxjQG3mp66zY3SQ8C2UJwABsyelhWaqBKElfGjOddI4Ex3cMbNFtUqgOWTDIfOc8uE214JD", + "LhmWRVtcVRYIpg9ZpOFw8A7gQhDA0gro0/K1HdgZOVL2shDSHriQVMBQSCmVx4FYLcyCJ7qpLNaqo+DPF8ZJ8wf9JxQy0CwJ", + "GbF8AKr0lGYr0pTQHkFCeOfErMhwXJOvI0UhZhTzR55e6H/c404qJhfV+noCfoPZAOlY20HuTzGZg8kKCghxZzldeedCCymQ", + "EpPNiN0PNE33wdt27Vp01RX6Bi27LdYnfHZ/BfcIYEqTMMhFSYg++HQSttIsc8TvMKfuT7EgO09cpPP+FCsQkyBjChUlvK0F", + "LrFAsMpR6iRuVAlYnPDsBGOD9GfPnj0gRRsU66iySh6kYwZgj5NsxWe7AFbdxp5gNwCJa4P+g9WEe8hi6K7uu7sK+1SFIpQA", + "jmKUQpqw9IOGqy5qHpbWdpVAHUXCbBXOTwnLSEyPiJ9IFRQeKTOr2CSA7hNoKRh2duxg3yMqEvaVTVTnvwP6mDYQ8joQmBAN", + "XndcudKdJJsxqrDIxOVnthQonhwmJjkul5ez145EkdIc0lmyn7/ibJ1lX4gBFH/cmayCB20o5eeldRmVf4yMVfrGEJ7rOvD8", + "TVuRCV+oNr91SGbKrRoFNOJApWJYv+uovhJt7tJyC+ywrwBcfDX5EKjdQRzJrE336GGNbJGLUj4sPZ8yrP/tSsLO5KRxjt3e", + "RJ4SQj2ek7P2sSdX0QL6phwjWpFmd1YjWz1jrTMeizqYk/s5m8qpDmZ+aOEoB84wblUQaRjRbbPRcsqmgF1gCvry/f0Ee51x", + "XWIbVZyNiiwGN1BRdoooM7inrqwvwNgzk5B3AowTjaBhJhSjC/FcASErPSV3ecmJDdfHlWNJbAnQgg+gyG2Nc+7S0xxuyv9V", + "JcV4C4xMQOCuqwz3AaHUEgqdPNjyU+YTiux2ISI4+tYrFBZPVZUUJGVdZtW0529UpM2vSsQZ0M1+IV0wGfS7j/qclD1wmCB+", + "PLnbQzVMEZ+d+6gbCgGHgauhYL3eVx0t/lfA4sowS5o6VX1207k6jrrRwObY1gEgIg/YMiLg2xXRfyDxVh0uWd8OCgBljx9V", + "rbBFyu7kMOEnji2mjFKsjyZwJIQbqqQDJotOq2Qp0O4cwUdEZYNwXHNFsDGp1gLnfoLKYh9x0knn8Mb4AhvC430hRSHWq4i3", + "M0EjH6zqydKpUgFwgQoy7XCgc0xkZWYD7zeDjMBVDhcU42pK2oH7RSBx2AcAHYBvkWsVKx5I4aSVJ39Ge854CH8+GEMHrt4i", + "RKV2i6NRbVKkouq5yNRwpx5rPyC8jthv3EOyX6lCu0kgteIO7btAGAtUuHfPHkKneXOXMAtMDBmKXTEbG/Kg8FunqgZCb+6C", + "zbXhmGFoFTqTemcZqlsyYSKKU/bcj+qON11IDou+iJ0NcHet/iLBm1ON7TwSErtZ90JrrlfaoeX4InvsbiqR70lKryhHYofG", + "ZUrKVxGEhU14ILEBFTsKHy8Usx+CxUDgTJ5MCZmaPPDtStg52JgNdlvSwWuUIbLpUsgFbCqopmAOgItTKjzwZ4a1WIcHW46C", + "FBJZa58TtewLSI1zhrkYBgCTdSPhRErYKS5FVuIJ8bFMDMGgwDqg+DhlSlUwhXdXhgFd9zgrXAzWf3AXXfU4HIV7Gl3F56QY", + "XwU2w2yHug3Y8DHTuuAOkNCz1vmqcLN7ir3VJv6/eHuKySykAAdOEjhLdCA9I7GQWAUgNiO7cJRiBbZzjmxrGa5vJBt9Z/DG", + "zq6JXxOCjq43ywgfbZWdM4V5CaWiTStC4sMIAUe6lwRJ3YAxRmIkC4d5YYwOxt4+1xacoAQbrSPzN02dcZMoCArHrdovy+lU", + "S/XpSx40g/Qd4iiErs1L+q+zsACmc8+RkugOMMdge7ezFj7YaulVj0LQd4sAGvZT9kH8tmA+/Jsf/80f/83pv/mzvznz0cNk", + "ebv0fz4NAqUh3Er4+5UUNrnTEJ7TwFNzRBNZzWy68uzhu+OV2j8n26t2NjQiaVpkUJN21kraF3gtobpQxUn3F3PfgVnINzpL", + "GaNbvEdAeOsBVVd4t6g1qwfkO1BbBisOvkpl11UCbzWMQOILjfLx2KHDfkmaHWTTUsaYWXOzDXAeiXlfT6lYUA0tr549j726", + "Ap5CuN6l0F+CW0l7w9oceLQmeOhQ9uOgpcYr/6qHyiBVqKJfAL+y5t+4BNGFRC4BvRdrptk6DykWWTPt7rAxzzZTPCVtvGtI", + "V4iBDTUS4lgLWoWKIql0WchXdIVMRG+IXerDE/4afrsIDqYP3vnwWbIoXeerj5MTCbxTb9jPt+39yx+8Rz6mxEtFVqTr/Ake", + "q/fJM/V2YpO61PJRicmJd3kruJM+PJHeBQfWVXIrXSVr0xVyYLGl+NwHLzp31XX7zJvOlOQMUeK2+vBZewd8WI/oKROP1DVn", + "nMJvaN9x9sE7/FecXuKeupYYsk4mDqgL3hvgy3pHjF/4BFuIb3mbrS3B8oS7PWI9B4ap9/1537Qnv8DvXo3fnN9JfFn4Hlip", + "2vui9e+x19VmMYqRQYx3fpx98Tb/5nfttUfwCpmoNCJvk/tLHFJvpue47KMWo/U4+a9ejHHzz13NrnwtnpqcW3wXbF7ip7L7", + "vUSOquvOOAYurHc++GG6x3WO6CVv73voU2e0wni866MfrGRXxT+GsbQ+xbixD1L/vcf7XiZ/2A/Jn4U+ORX3BZ8Z2uIjJU6y", + "92PmWAvBEvasXU1j+eyHjzl72An75gle400yrF0gs9jJdL0LH/xF6g22hU8SM+KCPTl4zZ7mGF3AtXyUj/Np43OaZ9f5u7N6", + "2Zi/o1krdjP2+1X99uF3fG68w3l0iXMXHGRsH9nKnkmsZRjbd/E0ad6/w3Zr7n7X2nTSrnoRLFo3z9x8/aMnb76Ck8JZwfRT", + "HGLXwAoldinxfpGF6+TNs2TWeuqjJ8C0ZZ8TH1awjMV3r9irr5Cv6mG99tGJm5f8G9ecj+scmMvIIPUoT6wz+M3+PWGtAlvX", + "6+QPwzfeJPcUmLXIZmXvvmX3f8p+c5Ywu7I9B65i93kLrFrkKCOX2c3r1oIz+JZ94zRfA6+VnhWcYedTbzzl7XvDP3fi5mX7", + "rz0D23EycaqR/4yf/2nwscWz8Wm838guJtayR8RrhiuBSY3Phh56nc/zE3J+vYG2qE/BiGavgSHM+8Ce9wS5tx6z755ka8TQ", + "hc9dZk+etB56A0/EfiALnL3PpxGTGBnbToPbLI0CPneJXGInwWQG1jH2Pe74pPjMwI7mn8PdzqonfKStpX43tsaZzbzvnZPu", + "tTTGL2NmgDUuWM78Kuc5lpx/N1/15z2hUSSj2uvW9pP2/K/dfAs9jJlorXmU4/aWva4Zpj7XTD5LprM3Me7qe/vU686U9xZm", + "THP75Ei5DlakWUmNMEO4twUtzK/Xa/6qzmUC30LlWli4njvdnTYLlirGYPyL5MtMN+GneLGqv10PB0SneI6NsBiEZLcAyKqI", + "K9rsls3GYqoqR1mEpxqXFpQGpyeJmJmnuz35H6i1asQgMyP7GxTJbrPR+xJNV2d5TwvwqURCAM/BAT4C4qB21aO7IudxORz3", + "uw94RJOwpoCGkEd4y73IauR6ybPjYW/W4RebeAqmQxphenaDaplOCFMyKFajyW/X3dVGsto8ezP/pfu/+E1ybH0zWUmjSsm7", + "JZBpt5mexaU2W7JhlpJ1F9yumZm7o2xSejGCSiLctA9J5cXVQUIySn+5UObdXFSY9fs7ItVg0xGW+d+qElZ5Iiqpulsbg5GT", + "HAWDDMIOvdFiM94CtFGJH+ByJvexOopmffAyWfdtlsdUv7e/01gjHtIn7miHO7FM9cDe76QyxdJCSDYtjzYY4Vuph91hldiu", + "hF/jPMNIRZ7RI1h11QAw0njGL8Vam5kdydNpkSLdqHijUpSYyBAadp66Onh6ASfo/i/tlGtj4IsM9rIqGQXPIV/CPlOcNLz+", + "NVxRYUPzvw+srTMfMVJo2J25e21yQRl5MJxtzKmDB09UTF8e20olmSwnxCChQknBamnX2o2XWmgRIysqeawpGcoQWt3fpqNp", + "Dd41v64pPruLZjg9rd4dFRTJGFfotN5hrSAzO/VYGflWqSv5qwh8aJG1wQWFI+jkhiIIy3cDltOspFhlAWV5X2R3tGsoeKts", + "Zc23ACABTYXQTDjAxlOQTHk7Kowd1Z8UigN1U5ypkPCSYo8DwgOQcrmXMhEF8kZLLcC13XfsOpTJxiWiQoYbSBFkbijn6AuN", + "yEiSAlXhzEExzuNqqMRDUl6+dOIb7E2oLWgTrT+a7G6TfSBf94GVTCtnB3rfNpYeamMHgBP0MRMJpqwZGxAakSCnr9hkqRHX", + "sG27SDgnh4RhekpLwhP4hBD4GHcrFW8SktIMV/d3FpZaeKOnOIKkxWeqe6rIrC8tpARfyCdif6jJRqW6ZRYHkg4OB9Wq5w48", + "X1AVEqlmMHBeB9p9qAVeH9bSv6sOtPtOUrAETJmxb1Y/KqrHQFuqmy1mWwg2+teT7k6ys3fPnt9GDMU5L5ZayAPLPDHK+zu7", + "5hORUFrzg/6X+5GhKkKwD7kJZyVCAHoo/I7KDbPEgiJn5HrqlcNbwBTNofYYD1g65688dspyFtzZifJJGe9249rbRv8LSeXw", + "CrsWbZFqsidCEGgcgvkN0u59B5AiYgSkc1/bZ0KFd5ZbnD6Dry7fhC84vuG3UrxlcevYYuFnZ8jgIdLouRTGczedH6Lb5gUK", + "B9Apm98MPGS9tPE/x7B0SVexqj5zGoGVSVt90NaDYgsqIvl/VASDisdtAZKGCFu5+t/GtR+siocxuEvForFQi8Kf2K/foLQG", + "sGT74gAogEZCJBqImKqt1ehyUwCiB6iWLrY18t4kIH7UnHECJeT6fOLE600OZZv5qAjORy+cmzB2yop8QA1dloxPD6xjSRC6", + "xOwc0a1QDKGjw8idYb3ZXzhBMFie3OW2qVgjQuPOaFOScoe2T4h5IBaaUJEFhF4UnG5CLVQMGd4l0oQDNR/ZOFL2rBLgmXyd", + "ZYp7RoLeDCKb0mD0G0AdSmqjAgitubYQo9gabtbhCl2hzZ+qFdbUwOs0A96UTVfKACXHodIJxhyicllCH5o/hOxQLJ39IAZS", + "dPWhw18OnSSS3wyGAMm16axC7CJkE3HBLpKU2keDQI0Vy5yW+xLV4SwmHLvEbGVHjcdOIAqhhQeaENqwi0VBNNnCKmGW2rgw", + "qB3dGGmPuhmPTWNy7ZwJEZolhwUf0bm5VWvfAWzLE3Mhmwn6mEAoUCzOGTxoEPUFPxRZoXKgRHMJdDUomnLCQbizNcrKIgGR", + "giMVR12ChzbOxUFen2SyNqEaZ1e4W0JfWE2RjWdqTJSgdW8iRhTBXYNupzcJXTCkSeEPlMRVrvn+jvnr8D372oZKHQQ2C0hY", + "E8qttt5CvMcGlstfRlmzgaWjEvdSVKUgAWKSjC+HphiWNEGKzEp1WpgxMQXYQJt9pNDT12yui/pvo2rR24XT4yL/MOCJz3wv", + "OQ6i6VR8FRuuQKvI7jqlmjVvQ9YkODbsKD/kgnSdsO+sVf2U423BkpwwXmwxM5PZk4kytT17llS7cOc2IWuS6rK7dgok0Cs7", + "vr4OmcdaT0FZNofzSfQJi4aZ15rvHGxPp6iNsadQoorT895xMiJxSCFVYX+2h+UXsKP7B9x6xV+b9bEg8lipRkcrkWeE0Bum", + "RiKa7iWXdhtGTIBAI0FAtK2fWdvVwh1H7ij+C1gBnKyVkB4um/7qRKg7cgXa1xwihvXbbe31NqFfhBNkDZ1PbAMFiSdkShxo", + "jSfsUa7/ExArniJkpQaWjPum+CnmWtcnSl2snfdPRQS8OK8JNtDayTJ043JlBWeD0tLrERFoUo6oaL3xItRQw04VPpP5eZmL", + "Afbm8RVn8N4Q8bav3d1uushWueyqNnpOFMgEk7do6JYCNzEOgKBqLcY8Azo3WpDk5YCZRKjbStXW59ldv3jvEWnAHWitbRjQ", + "bq3cmUIGc/QAaVAm3V/cC9NwhRlhzRIUjm2QrGWDtlhUY7nzWgm1eC/NWwEiATvxjkqomb6I/WgOt8hKwg09Q2+rkVgLO4IO", + "tfZkoAlJwwN9xC52OWxhnvBLfvd2VsvXFG1dKfc+na6aUcypJsob2vckuqjy+iMyyhTy0fhADiHaUBachG5I7daU1dpIaIqV", + "SRrjKDjDCjfHfrQbRKhJQs6MC7d0sQiUvq5REzhorXiccwAJlF2FQ+yWYiMmeQBqToQuwJRrDc65pYV0slbyz+lWpx3mdw+1", + "/kVbIdrQB9jNPN18kSIjIdFFKtdktamUicdXaGqDQQqAZBlwWaWj7T9Rh8NbaOm5FCbGOxGjo5TYSfasEV4PB/ldMNwJSx8k", + "zzKmbfUSB0DRtiidhGETqCdFOIqSGEP739ZWnZj5e9BUDQXnFda8smUkFOLMOKp6AnbAZmXmp1SLj0RNiDkECTrfHGldowDR", + "kaHHK1KREk6zpK3vbKL4CDnvMnmLdiJiYpHIRxrKkExtIaG/n7BxdT/x7lddx0HCUdFPzp1U9UcYG7kt7Lr3ModMGyXohDMs", + "GIz0xjkYbdK25YzBOshyuFR0GuV1D8HmknY29nXnxSSesVs40oigNa0T0Nw1gobIOeG43U+GCupukzvK6zJHye7jksYyACK7", + "oIkG3kEW6bF1ZIEU8WYQpZrNdShVBM21EMRmRDojOm42U8MISXG5speCmmUv5YjNjSJ3kk1nTiOUoj+oOUmHzUYyqU0UZXFs", + "s9dv9g3W95vdksrcUy38sdHBVGvoJOLsNqAUQdMIwCfLqQhKblHcMyHCgT3VmuM+CruTFLRloDrIf7tZ+TaoqBpPnLZID8Rc", + "sGCw0zOGp/6l2dzw4MKB4zCkNlSx2Jbyz8lRJ4bH2vBgVW1pjKPSucEGWFADvdFMhiZI56A78TZeoZNpo8mAK0GYi47BxZIS", + "8oxRMQ+nQS7TGgTyQEyNUJSlKcGJyBpr7wey+gM+Qo7bUCH/bx3qHKjIblAWQmsQaCR2rmIB6C1BHnqTO9ucxM62/MWH0KbD", + "3HJrcO5paypwW6dBdOg+xigqGdzRdfqc0B+fAjoCQQsmeQcQeilHs69vJ8YiKQKX6IAWoDEnratAorL7sLYG8AQws8xDE4yL", + "BgUPd8HGvGQcEyZEE9AlhGoOqDif6tKKQxHfH7HG1AtUE3ctqgy0VdjOrWdjLL1e09mKYLttCmuqKCpt4o8UsNo5s0Nu984Z", + "9K+fZGsC1edqudheuS5o8HmNDtf8oEi2t0IR7LOj8n5xSAwTEJI+jRITQ2rjem6mCK5AcjM28oPIYkiWwLYio1htz6ygzcNC", + "Cfd5VxanKUjQOOg7Csu93yVqK6iCo2XQ2BfQUPAQBPObncFQOqxXhvV4kxXyOupqZ0i1JQ1WUd9T2wJYxh+Am4M+97AK9CkN", + "SD1rSGJjEwMRoG+vcOIVcQnGjLrlPaW+yXryh8xZpqoyJq1iWHZtH/Xd3XKSWP1ROKkDEui7sXTgweXRpszkk2kdN94YIMKB", + "IRdcO3Hju1YE2d25BUn9Q14Axo/AW8faD/r3YgV8GScRYGSqwAxdV+s+8EQhb2J+gSYtFY7Ds9QJGSeZTl7GB8oi8Wajf70N", + "iWe0HnlxAfnPyZtHUwhT3adBoB8ZxiL1Rrt42bKkuKPDx1GLAei2z97fes3S7PDVkrDuR8EWus7q+JWJusZh+w4/dWYuRxFv", + "oRDJHj7q/V29Y6TiG96KZOC9Nqo2z6WnwkGnnIYxEr5YoWIV+KaE+XH9fHX+cHAkTKExQQ7ci0zbWksIgO/4OZ5kOAC3LzZA", + "YEpEKVXbu+Te9KgMM406BAdrwrS6oeWxldFgr3XBnbapAq0pFxXGaWI/Q1bZa0AL7WCad2RPVXrHLw+fLxSESRJbBem7G4Xc", + "jbrdu8QyVsVuv1FvcV16LNMDgsqkht0r3DEpDJX6tt/shKR+NmcJu5RbVJEwuxvaaVV8GBsTRrMXEaDERYNJ626CnV3oVPiv", + "ELNIhXGlR384Qg4HVexVEeS6H1zVo+5y3y2nWtTTJC8GjWJi8aEHyOxLyjStjPoQJfeOCgQ1NokNGVRMgyk9zIi3rDds0KDl", + "bWeJh8jusV3QX01llDiEGyxLkNLe2YZOQokci6EN9bQMM3OufTD0heMWFgk0lSpKsXjls3jk1H3gMB/UlgULz4WLk8zObdA3", + "LRA8ZvXCGs5gFG248DXGonXwwP3T936QrSIXrcXHt5xBZA/1Eg5EDX1yLccJu2OH112pfKuIWjIPhJHM1bwd8fHZ3R6I3Six", + "ZfYnLZfDXAixjKE7sxURARQ3uWYIGGZ9CNysa6aqIEBs86CHFFGvjxB8r17WoiqgNU5jhPprXcnjfg0GliOyWTzdRgRSGBcn", + "juhUyRzcxA6ONeHjBjs8ppyOWo68bB3OXY9XYbIqbCIqYAEwpEexSgN6KJkwVaQtt24SrX/92jJWzYWyTYFJW4b00ah1Mpng", + "SMWmYZ+yxqU6iO0/hWxtWKrkQx5uLf6W32nOqzSEiw6up8ZJ2Onlk4Cf+5kK8PkOTXcvXlHxGSZoVH2gz1wEysyDBBPB6e/a", + "GGBwwPzmiuUiO8b4Vnr4mkaO2yVYTm6tiJ6G642V06IpcCMfpNVtny6wUIM0kRP3UHGuiTuXWS/hIBLlrafV4Yf7EzvRPSxi", + "8Uy4aRlkZvNcsWRA6LsciptfkYugQSLjVEsSrMBwdPveffwAocm9RD2LSi7Fz2yWwzD2EfKngOmzeWsqOe1yX1NzjrQRLakz", + "0Hg63Pr+wXHzheKbjEcVDMCECcRkyFYEKEQzw20w6kLoGqWCi1AFkn0GyZGeYsVwX0hCoeqfPinwuWDMgCQnuz9Jf1BEYs4Z", + "WRolOBREtVOEuyWU7SuWPWyidn/BzTo47e4wwYFVOKSRoklwmszRkJVLw88qSMFp1Jf6W7QX6iNpt1ftFKc9gFGx9IrE373Z", + "hvB9B4fv39LMzZGeHnk2M7fStj3vPBBNHnGp+zsyiNCordpxsm4shiY5TCnhhdhNSh26Ep+o07cjZ+mrkF2icwW/7siIwiCr", + "wCLdrtsaEguidUF9C+6TiMk2WC0enWZloHYk2IgD7RwesURZY3tYzh/0Cg1zj/wWUsUpe04PwvCNIi64m23VCPiUrbyWQvNS", + "iivHfboE3Fa2fd9xYA3WZKpMkmfpNlfKlhwdOOMGEyfyVmHhtat7jj3qNBp9Gnsuz+B79bwX8mJOJJjj6iTRytv2NihA16M0", + "GNO9yg+loBnXRc+XU+IhUR4dcZYB6MkPiZwmcmob4KQtYpdnfLkCp12jfYfJYqcd5L6+ns7NI23ynI1UnNSLcilPmkz3OTfH", + "vyYhpImXQzc9m6r9v3oGRPSpKqYJorhuqe5TiUdL2tvyRCLlssoA0Y1zpeavl8n0o5qlJOxCgunqB2iHt/UnTRTcoI6QIgo8", + "FgEGKTdrEpJVdnWhQ0JBindz0z1IGXmLtgInFeNYI+GxIp7dLbtuWuITq2DO1S0Sca/tNmOXl2/gjoKnl/S9qTamEd3Pqtec", + "jLt1qUIewgXgGor7kR+wVd41W+iBEtzrUVfUDDxXyv71ZCpoUphqXrNnQ5XbUM1B5NisITxx8EeyJ+FncQDo3WqEBLgFJw9L", + "kRxzo8gWf+3bFrCexoKkNnYTkIsF/TejGaJ92Ncp9iWGsAzh2yBcHPpYIbWAHWVhIRE1zXxZmrDCEgXe0X4Hb52nKvYl4U5z", + "jboV2NV3M5zGHTO4zDKAafSglHNbfMFCFm504kwUIM4WGT4oa/9CC8BarRYWjh49Or8+GKz3XGHnoZAVHoS1nGWxFXseel0k", + "HT5FGZXZrNTVwiEBbLtv7++ZfSlxxQmI86JBGdCvzV4S59hm81zxR1hUkFN42/b+5+yaoVFiJ2KW/+5+YU/7md0ZporHM7Je", + "KzZeyy0IBlI7a95BtyX6jtt23TVmMg2ewhxxEdsekkr53/2IogyGfgJ1QfTtPpjQFaGXqrphDrcdWF5d31DWqoDoCWrv24D1", + "/VW/30x629YB5YHWLJ5bwig7Jx+QwwsOHQZLStD8Ay1iS6dnP8sWINObZIi0GYcfCWid0J5lz9yIA0H2leGYmhQIr8WJFUm8", + "/Vkk0CWtpVM83x11oaRjDW4ZJMvewUE78LfNZTCcUCMFai2l0WHWtY3IQJFNFnXcWxYtq8xSW7LaudMOr1XKXdel0B0CWmZo", + "u678LYH0Ez+oPeMd9hlvdJP121ISU7MxTTLfOHRgiK4p2tJyhiGq0hotcSrPfvXwLvjR/S79m1kHGymfOF9kDkagBVarToYy", + "EpadaYLFg4wdHqWnAZBsRPeSdU6Xxn0TiK1l3lKV9c9ilup/YGxmcFAijtwQs/mRp3cOgTdAhsVchs7/HeeVdPw4edQV5GmK", + "JKU97LTcvAmE7kh4lAJgPvurqpZPdbzWn9gfPOnQshcDK7kJPeyQO9/c8n2VRRP7O/ZVMz6jypZ2v6OdGJGQ4NFwXC0eZrX2", + "wsKd91mPY1xcbEU8UkqqIUwce0WGHi0Sy5vNn4NZGxJ3CbjtfuuPIC239l93717+Vhv/n0muB5XcE2hwziWl5Cl7LbnSzkzN", + "cnBkWyoqOBv0CUqzwocmkHbcb5lBKfUaoibBuWh9kp0jRZIyL5id7ce4Z07+QmAlxHaLoKzziYmeSohDnBeutrOUZZm/OKaF", + "K7d0m4DRHkK7HsCN1INcSVtuczPzfeRD6Zu0gH1yBTq6dCbHdiq0ZJvD1rEiS1HsTerk9rxZvcveTQDg0pi25yNhM+6LrzMc", + "qLizeQE4CyStG3U+1v4vJSbvTtHHMqaD0jQtzHC1uj1U1O3zy1k0MTumZrJhLBILWJJo0e6CzSzQ/dlaMEentxb7c2YMF3Er", + "QnGDLy7LfUyU2ImiBfMtR3CBeoS9wlEXS6/tRcc2e/t0BrWsGmC1RfpSki2JPJWOVJUGLAfPJtFte8Iv2fHWuAN+f7bPo/4j", + "yC0Qw9rNm+wbZkfHLneFuL7g0tp2izmMrGaiaIHcH0TJCRNoisSBI34eet8LWeShoIryRt21SbBoQ2rXXyEOV3udmLCSfjfG", + "BQF8d0jx/VD23ZFVR7mabSkmcgGRqNQJcIOixA2F7OukOio1H1sn9w2gDs6pNJdVejUzO1qf1/byFOqpWugcqRiD5HfWXN6C", + "Goa75jtFy1eyle0z+Hw8Msfd8+I72nTOzEzm2COQ1gsOuRYoWdztWY274PW2Z0STwey1r6atGINxG4Z5QXDOYJwtUiiZ09RD", + "Hd9oYVD7soBikYW2i6TcKrRVb+DFIaGPXOXxWXv9QNGCWzNocJGhFbpCban9y3lJizJ1jK+utDl5IsuF76li3JlfjSAzQzbd", + "btVGMdoKtbasp+wdhsTMqPgqxFLsycP66HpYmnfvU7ZVuRBy+ESSuw1rFll5YHOoT63MOeZs29uW9Wbr74BShNOf8JkUHAKt", + "9CD8ha0sF8VNrnf7eAXfyQ7ILMhXyOPnUuoO26iuqGus+T0SpBSJ1u1QZgvRiPN9L3On2klbQMg3jddwY2x/SfqYvlucX/55", + "4rwY7BlqAmVx3yIYzciYxOsQptKwn73N5bBKCUD8HoDzZpNymzovCpUrAQJPIUtHvgJ9FzBlG9CEL3f4AWEQXCNe/UngfyX2", + "j8OkqsTOX/ZbT2bnTEDzHNaS1Ktxwfs8E5QW7xa2V7gW2odbxjqIGJYg/B83nuYLvBQ4F+PMZa7WnzcyRggV6azRv23cr1OI", + "F2mL66g/KFLebVhFiWhvEvse5upyhphnMs1zcvxi6DBmNljkMJRFS0BAduYhbJu1AMTUZVCIDm9RG9LTVnzhYOZ3ZEkFrzXU", + "asZtuKeTj9mNQ4Y/BTCy/fdY1KjiubLtqsjOMuXpnH0WdkbhuSOBeRQCJgebl6ukvLvOGsZOJSzo+SumLomraZCQ9XofbhNJ", + "qzTAQp5ymM38uEOjliwQGdE4f61ZXOKww5V7EsL4QOaDO9KQ0zgr22syG6YvbjG1M0kJgzmKvrCnMktWVPEwMWsjcQQd1Vpf", + "GfS6i4lbTqqayPcSLpQKlbCnteV1tbQmFPGgtGzxtXJYHDo04gohuWoT6zhD73NbLp1ljzn8FqHO+RyhS667hpHfItYg+rq1", + "pVcmwhQp+n0wxVIkzAprohu+iZ8FWf69AEN04Q7N/W3AOdv3Bn3PlBMgk8E3WTMTe4u8ZeFeApjoqDqiNrtZCaPOL1eZV9h3", + "K2op/Gxl37i9TbRWVssetajcNJmZ8h0iAz84S7UqwpI4JtaRzb7YG5ezwylVPHl9pZfINlk5fdPJYjs6H4kXsH219VlCB4Ix", + "B+bQCk7YATZ5N6KdDa4zGmx1Eis4ka8JCZ0jkncGjyuSDW63EK6g7DXzBo0riIwkQp0qexppGkY/u/AI8gHqTy+Oamv6uB96", + "KSB9NI97qFRYfhYaEEDKVC9kV9Ne4XV7OOur4MGT1m7YsUQQl0OKacbewTPUF0GS/WVGMBVrNswh+9o0fwokZl9erVo/EnmA", + "4F/DXAo/BmtTQHbNHCYUjoY/G3W+jjH262flXr5PSiqDh06Cb7VBq8ztnsHnSUEqrlmqtGeJF25JDbTi4Ozs6Sy3nPNikpPe", + "PAsApEhL/9cewGkOHJgVyacmEPjBld3Hrh6s6sgQrsrawKJK2WOWHVQpCYv1Fnn7OmPBD4ycP+8o1g7sVSSB4C9kAP0ZXV0x", + "hEGIJdsuBISlxwf30zNKaCJXKWVfpTN3Lhj9uI4a4OckS9FkcZ4o/58wN2qHraeZQ54W5kgnWTDUJyGpWM5DMPGMWULdZOdU", + "Yn3A1uFrFgFowqloMkBMp5fmvO1vLG5GjLG1EggL39RBTtn0hMg5Sk13rY3AaABd5HhbFqK3+zDYWMcpt+p9y8WfhLxRR0N7", + "8iu0S6PiMecFlh6TKzNgD0Z0uFLpZMriBvzJK31cmJY2AfqtZJ7fy8H9+lpfkONY9zWutmauaiO0h3YwZR512GXb8JqqTGR8", + "aI/V3h702zjyvFLCIyhtTDKzM4cMz/jBHsj0CctZQ22gs/wVWPTFnZuAdkc+XntLEdnFuWQXMRtfJIpk9A+3kXqtms3KnJez", + "B87gh0WVIP5mk5jpE/t5qrzS3ujF2/0B9xwsGtlGseNUycGx8TrUgtzmVrL4j3TqtZ6TrjSsSoGauJ9sUjHCc63al1R5uBqe", + "SW8CYhUW9CGGhlFxOPd2varetI6ZzQLZLXsz8hRu52DDjbhNyXxN6hauWX+yqEEjbtdrVDjPh5rjR1H5MdhMVSIobAj/16uY", + "/CxLe8g89c5Go+D8hh3eCK2QfNW5KPfBuDjkmvXQYTsxzhMK46rRLciSwH1DMwJrQPukelKH+KjncYBR4CzCrm/asgd2Qct2", + "UVNOurX9ErhXMvduK7b1Tk1FvyAkyNNarvuJLkJx+wTrUgHWyNe7g6Csy+zpVAPrWCIHuUzirJbygqq3j9gi0t6lsz+qTX2f", + "GUectiSgy21vooJrgqfTodD2g9lZTZXgbaDCRlx64NrNkWuw0122MTgX0D+t33TYk9gTVXhXguSuVBn3z96F/+N/b37nm/b/", + "/7CwXu36BjyBo0X1rUW3SXiWoyAr8WQHogTC3xuDVEyTylvIAFymOTyE6r1KCJsdWQFQqk5P9o/2ooxHCSzRnsf5g11VltP5", + "4AXy610i095LHx7/4H2yE14lQ93/+Pt7wS8GRq5Pz738i59+7+Or5z59/nGpQvvv1x5Ov3/6wpO/+LPvQnz52asfX7/+6YU/", + "/vR7739y/YVf/OD9Xzz+9CdvvWn/+/mp9z5+54cfX33742tPfvqnz3z87gs/v/T2z99+0T7583PPf3rpuc9ee9TXHdPg1hND", + "wQxCWwUggtWBx+uUKrctknGwLrVxBwEa8HwcPxNMmGUXNZS4/o2XJMocrw8aKdMxugzloZXygZIiy0KBl0rWT6DBrOsDGWCf", + "uKdeGdIepuqwmdpiYnDezTGM18BJRKG4c3k2daT6G/JggmGzfcYykBm4jgSD0IzuQHHaeC7wreh32xfT77hY5M4qyN1tVg5X", + "iHjdIEeJhPSzwCEpgg+0xUrIj5Zk7gNnIBj6fkRmw4fB/NfyQgbv5odPi00S7H/OxdjydoJd8jhZH8nKKPZJu8Jl8m8GW2Gw", + "cYKRMd3rw2cxhzk7L+bXcd5Ocg2KjTLuzb/f/eBdclW+yZl/BX8l5kKwFaZr2qdwxTfIU3ktu1fGjUh+xavkFNU9gxPzcrr+", + "ZbIjBrflVb5HZk3ru78k66ZYDhNPpn267cNHwHNJzsi37XnxLGA0fRKsoc7YeSnjCr3kPXwBDJ1gF/U+AQdly2552Z6e/WPj", + "En0D9saL6Fd7oredefECWUy/bc9+0V5zBtAPLvEq79v3vp1xSF7Onv0C+0nMnW87iyi5J8li+ra37k3xsHLE9JmrfKY3nEcV", + "MwBPRh5P8kGKLfNdu8N1tuCqX8fHEcyVZJa0e9sT4u/H2QLMz9S2D37czlvxYHJuvWM/T/isuZZ9F8/yPvk33wPzJUfxCjhl", + "OQP55Pbd98lpeoH9o/aKm/V9zXUbr6uJKRbvvu88tO/wOfwzU8/yXjYWV3U/zrn32jnMO2sGXI31RX7OEx+8lK2dd8QRCy7R", + "xKJ6ifPoXTwfn7ZdL5fR1zbCXF8ZB+jlliPU2vIIP33RWvGseFR9TYnhVuP7LtcA5u13bOa+y3Vz3H57x/l3n8jbz/V4wVfg", + "NY7/BbLEnuB1cN+37F7tHMY4tuso8aFq1rG/sf/8uXPZWv9k2twnqMJ8IbSkT7r+uDTQITkd0tIuIS2NbPvAM3zrufjlvVDH", + "ts+81EqQt9eRkPSr2TXPhHw5Zabx+gm+ci7UtE9l7TlOifb32s/j38tt2yDqndS6dd9rVPc+Hdd/Lj5zNvTQk0Q1BcT983qK", + "F1zBXNd06fYX23u195WE95P85Tl+/vVMFPsqb6fW6rne4r+P8bmeC1Xu90Oa/AobJiH4aDZe/wE758XpZzzePpe0s11zPPXS", + "cyGA/lpIvZ/M9OWlO6+HPc/7/kV8S/3/cvRJel4b2Xd43/SMJ+IzL/JBrlA1/pkQ6U5j/UKM4Ono27jmK09kguZn4u5prI+H", + "IPjp0Cg/Ec9+JsbouGvEe1/FOOL1s7z+j3jZ1OdqyQW2860Y8RN8MX3m2yHdfnFqPni/XWPXnfJffF2kOXA8nlrC7q/GvV7g", + "k56AXry3/2powV9tHznNW78C+x+ffyHrq8uxgq7ysqejP0+7wH3bZvXVD0JC/WL7XN6rx9mex+PzbB6ufIptvsCePMFeutiO", + "na+j90JK/rFs37gcr59u57D6DXPsbHzlWnxen7ka6/Qam3eKn9R80/x/MfrkVAzKlZgDavMVb7DGvZ2rqQ8fj/X+BK92Jfrk", + "1Wx/OJ49Y7bn+BNFl+K+qT0XqFaf9hneF1c7n82fND+Pxyy9zLcoZO/j9Xw2x07GnHmFN01rTWvh+en98zi/pbV2ns/+flxH", + "81+b/HPTe/61+Myr2ZzRxL6Y7QM/jT45Gzv5Kd+j8JXz0bDv84nS9S/ECnqn7Qe89Vi8dSZG/HSMAluibmnX+/NTe0U7uLHW", + "fJ5f9odN+4P/qbHQ3Hua1+e08V36QnvG+fOmfj7JP6/yM2ejkc/6M/pnrsYAXcye8fH493le4TJffys7Ky/4d7Fv6Lx7JY07", + "2aLBi/0UGZLfJJ/0I4n1+dLNt4Kx+aOHwS790Um+foWMyC1Xs5iUT968SDbvxAOeGJZfyziWX7crvA5ecPBpBzM4Xp3iEH9U", + "zNi430cn/F7hAZNVmrzXev0s2uRs0xecdRy/n8Nn/ZrnPjrBK6k9b5D3Oq75mr13EozUdp2r/nkwdD/GT4Hf+vHgKCeL9MuJ", + "m/yNmz/mU4Br/HR23yfIz822OcO5GKkvkbVbjN/g5j6J52efBjP2G+Q3f0x84+KuJo/4JfJP6/VHyGJ+xvvtMT7laTFW3zyD", + "58d1+OoV8qU/xdfBYn4GfZC+S45u5+s+zW+87tcXb7nag2u/5c943ubBUzcv8YpvJL7un2b/XiaDtvd5y3VuM6Ptk/PgQ/dx", + "P+vs2i13/OPxehpT8Htfw9yLsYhnvPkqWqN+sKs647j112NkLg927xgXzLw3fP68br89wStj/l+3v8CTfpktiLlxmozvZ7xt", + "V/E644qI/MFtb+VEEfnfn8HMxA3u2FNSaqyPhx697LfvkG46wsokH0Y13mBzdheTIeJrmQDFg8ieRLRW6+HqeNMjjvM5NjjH", + "5DdLtyAx29x2RmYFnAd4EDxn2/IpBZ11J4m8B5cmK9C3Iak7b/90gkh0qFR70CciHHYv8jurG2PQnqjYwjO/+5n8i8wMg+wR", + "ht0aQtbaExoZBuLzawFCZ6XAXRnqtdhUFqrsV/YoxLknYHAIjDvhTxZMQZ6kIxBZh6FniSrt7yCymZjODo+3kB4sDkKTK4cW", + "F62uaW8ydx8D3g6T3Tq22Da8pfqrq+bOfO7Mjwb3ICt70LpstkUgkVmghdc5TbIH/e/KQCRzHslW0STGIdF9O0Z5DSwc4Alv", + "yEIC5ed7UV+IKF6/KpFNHJaixRhmuTgJ3aXkYyHFPu8qxraDTM1JbIlFcZrBDaFO2rpt0ntkGKCUw2Yqwvlg55HOYNY4UkGH", + "be7eBRY7wE1zvElLKMMyR1yINZ2A+SRmeGtOkNFwhTm4QZH2xNbrUAqHDSeqa+GwKVqdhGVnc5j1kQwKg6wX0xc2NVTs0CTi", + "4cRFZ698EWlFsvKiPDFPmiKfss0cNapGW9r9/Z3FIitceGDctEUnXlziRGxjpgCU1nPonlAdKHZsQQLCGWsLyHq0+AZTQJGO", + "nMkD3EWOGg6egUrcFYFhsr52hQKJ2pct1krMAs5H7VxVntKw6TJU2oEE60POS6fPJC7BMSIZf/nSgqQVYuvMqzSc7SdgkCzS", + "WrHZ9SAZk4auzlqkynfcJyu97k1aWWZbC8y9iAtkOAUWWsyQoyAuTbR3vYnQa9/MoWzebo52wAKWcrzFIC9uaPn8pdtM2hP7", + "zPq+hWO7mw17lqM2G3e39Shcp+KoZzblvgxBPucoCOFJMnxR1dLZOSrTJRY57bO8S4txRLI3R4zEVh1CsUOKWoJ9KMe4zbUJ", + "TfvoghNh87hLNHki9Aht854TdpSrQhm0lMyA94gX3nPe/YyjMhVSkKoFqU58CryqG4NNxNUlA64C/lIg3jSjsCXl6M9G21nC", + "1Yhrh0DBVCFJFHzVap43OVTv870g/lFCUgydOumKDCPcKVo+i+WpRGoCDjn/UAxe1VWKzGFIh+xs2R2Aku1xr+/DK21wIhaD", + "HDrh14n5DrBYUgM9CLCEJqTgA8HpKXyKnXxJ7rfdYeuy7wQrEnV3iJP+yB+uaIvBbFuez8tMxMEevCKB08LQZ3UvO2cOBSEG", + "4emEPBacL1WOA513YWNJAPv6qaMTnSETs9Px3sxKJ6IA7FGBJBWEL7Go4sOZ5EVCIjeOvNLK8jLIjUFstxmetDfBHr+1FazC", + "ThjO04X7W8Lkm2lFTCo+tjSFPnbgt6rglQZVhvUIksVBoiJaa8q3IgvpEs68pBaviARC55STIhVVERGCiogZL4lIkB9s3y07", + "pkitnPOyplqcK/kmiv0gzbBtIskzt6Vk9jFxZDtVNlKzKY+t2qAoTIhimU3yT+N0DAhnWyLQKWKZidssAWtsIhzId/8WtGct", + "2JEXzmYsf71JXknaxDnJPYR4ZK9z7RaZ3k7R6sg452Ui9Snb2jdS6hBOwx5NG11Ar2VeTNcSWHNEVIeTwU7FtlIAhHeTPjQh", + "WYuW+BswdxKZJKaY9Iudx6/I8fAsXa5LHYetkHFG2VbAPhgNBg8WgfEJ7ijOnaxgqDdZ8j2VP4IsW1snuGxjKhBgVaAE1T6R", + "EQiCQTQKWm3Ltdddz8f+yQt053LzuAke8YlqFXweOHsZBYMJgGw1PW213+HVik742dZyNUfIVupILhiAga7ddzCD480dmnZf", + "/Dxlr2A4Q2LG6Yz8DMZMszvxPFwZmEkd9FezeQlohkbrFBm5JwDhTd0k5qpE5+xQlCgZb4J+lAA4lVe11EMsGOLsycs2m9YS", + "4gV9wo3NKMEhcQSrUMwMvRYTl2EDSTxO+jK6qWt1b7MIhu3dqkJUgW+oJnBSRCGldorWKKkbF70PMj7XZMbe7oA1AcnGqCNZ", + "rajkCQhXy9jWiorYRRwrVhAFXofQsh/vZosFPtBZmbgiWyFeu9qOvBQR52nCimG/7tVetHp3BrQvDuTLOZHs42NOm6GTKVPk", + "KkpWFlWp5CvmNfG3wTsDcz9IBEQ+7AxSMFenbM9Us9qItkOsHEDzfbFlzxqstUTRxF5tVwl8FR1PACAReCqFtA7J69S2a7A+", + "/f8U288JwkZ0JEQfbGFESQT2kHTaUisnqYI0hVfT2yqhY1Zl7DJQ8mGrl/PK7cyBQnminyOofwn+PBa05UQDBZWRo/Q+zjmA", + "HJuc1b6ayQ8JWe7+Ryob8HrlFrqVyOeJLIxKBnGax3Sz+8xMzarEKkq2BqFc+YPciMEF1VpCACETcbzbp3NeCstyIM70phIT", + "7ZaLD6RiW5w/2YS1PbEKTXj360UjBEINovo8ppNvVdrDA1s8kw9J2ePWJTJaLJlUWtmSYcOMiFjAxMkkU4VPzuDQeDgJTGb9", + "bsiPkBcGZWx+tNX9rHBoYVlwrChXzskbMnr2RqdC0H25365dLI+ebXqxHsS8udW07PRewqThx/6caNN79baqpHz2hgJIb3LX", + "IMMKfyW3/TNiO9IatQeacJy+2KOW2gGBAel2Yvgwi5ZbaqsaqNoQCnMeJeBr6QzLn6PvNmoE/xPJ0CRcX3rSsJLTruZ8oOKU", + "yUtZSheueogreCGvsC3z+mKCtEKbJPQ7iDtGUYdcSGujK22VXXCPH0kQYrMY7cXtOjZvB1fK3yR6MXz0ln4KG74L+TEs4gXK", + "qnjMKpntsROU0vHSCZBt79ZsGWa9mGjJ1kg4WXJF5oSzTINVBGbTZrwqcTQpcquG7kuKfvUGZfegWZBmDZO7vY0zi8JLPZXX", + "sJQ9EV16JYoIl3DIEOWZSq6gbp55lMlKxXgx3huqIgHBJ3fLXVW3PSRIhRWA1OR0kcO4yAr40Wf3R4EOQ0Duo3ShBF+gjuco", + "MG2y+QJzGTU2DqJPYNHSNpIEW1/MajKW8rqHSaZmhcOCCNqj1dAsypwcsvxqcHdgI0jbICq6g5yZrU7vwLIjkjv8IevcuhcO", + "L3fYft9eRLkF/Mngrckfu1n20A/jqMF8J+Psji8X9335SHHgniN3fsVJ4mV5sl6lWfj9xq63X0eoQ1VbqK1NwY08MBDA2zGV", + "Z1om6N6kjchg70ucAYMmcxFsVwI/12Zw4Tn1oKZ/zj/Tp7EQhkUL/VYpblQZN9ViXr3Y7sg2cRYzZYp98lyDgTXxu4j4r80Q", + "+Pmis1w9699ZKa0XyuJe25kn4/5g2DxoFt+Dmzde6emP/oQ/xeH11y+RxcvTEKtSigFnXUu+pTxIgoSi4fzDJRlbxbNyc6Ve", + "H3N13DHAmQlt2NvmitvKrrTpPbhWb6JEhTkKMzlCsd05JDJ/IhIq8hH2OTbb/ZicEcRWwXJuRCQSK6ftXkOdg/d3cvIVPpb4", + "qN9hKQ/OLe+Hb/jbv3vgt79wl/1vaSo1Ej9tcph3sjCVBvrWrnxZzjcZNdDsgame2F/0zas4MByWExQZTMV6pk6cxa8CGzwa", + "Uy5jMtdZzjkppu6+vP82zgzbO6vRbYWrT7mNPFfkwfulXp2xklDYMykXZpSi2KtHlFbyJ1L6QwJCnWJmKoCeZFtLl3HbLFTZ", + "BiLOkKRIso5trfA8Gz3vD11MBStEJxG8/BnXPHlJE3FJdzI/FccuDuYpvEYjFY2JGklFgXbvzvv+fpA6FVLCIEmlHwxIrsB4", + "KhKdj0RikqjXVHyCFVTJiFEnp0rasq1cFqNia8eEd7zqvdTO1m1Ws7VH1tQKmFGMrXHrdGpfx06fcQkWU6kV3ySxQUUtYlp/", + "OcOD7Tx5OmJ3pgVn4357qylhV5tydWeWplISGVMv6h5cxUHfW9IU88wMy8xSBbkkD8NmqNtYEiqgdy0WDzTzdbfYbzO+VVfY", + "s+e3O1PbaaF6qIPmbA4AYmf0PIKTa7kxWkxlWPaO8nAI1HWtoSmajTmSVFy2OHs2ffbMP9BkSycTeqV6F7e3yIyz2u5O7Vuz", + "R+cz/bFZmeyjLv4ZLqe4FaZSeSjP5c4VU1GTgw9VdvaE1pynzv8AIk6DzTbrBBsFyT+aJHSsxYkXteOzUyEwMA+2ClkZP15K", + "jkQtXJuaY9KLz3WbeuI25x+yHWhmCSzCtoCSv7o8dRnXTXSHZnYqRb5jagtbnsootdWVaGum2IejPi9PXhaxc8SGPDbne89q", + "OVwhRZVtK91qZsoLjudkpmD3wlTAONO1kxBkthMtTSVkw1GUesqR+r9ff99u/Yf1f3/78ZHCP40byb7wKFG57/N7plILU2mc", + "JRqMzk5UdSO3D+ujU0wdTjNTzm5RrZrl29SlqIFlzUakqmW7QH8uTfkzZGohr2wYZDLBERmt6ZeGJOZUtKFw/94T2Yopx+7m", + "sXQflc6U4zoVfitcAsxHumnfSGTVu7GJA3uBiVhEbsEdCN9fAlQh9EbGtRO7InS29AKnW6q8dslWO1j7g1HrmGGitpWesKjN", + "6wOziYMGpKgZafLWzMSsS5z3xBu0GRs0NCO6c5+sFXw/kKeeikznx9zZdJLQ/1uaOpqLKXNGenLRHvoOie6AO6aXe9cyfFNS", + "u91RyHwSfoDq5LTepFy9TMao5Jgx3IFXGF8DdUsNZhsu8ixabdNjyg7ZObWKi0xpliGU2Ktx0Z1T69bVnv00mUo2izttGDz6", + "1HhLiYksJAFXssi58DLRjxR7WImjxFe4Fm7upYH3I54UplnYVNrBYCXXaXttpRYQYclEsSkvCaBQL4Xd6mwFFEVuGU/hboop", + "X7JYnMIvZUwNXAEZ6Klp2aGIHgA8IAlZZ9ztNo1arjJabFM7eybdd+vZURdTE2bKLgc0yomi0ULy9lOKEnMw0sBiexpWPId9", + "H2EPphz5H0IvLrnlUneMfgOLCicuo6b8XvJkM1K8vVvHMh4NjxY6nzfCA6KY8HW7Y/oB8zgpNkjbi3oe6fEgn9zBJsQTVGM7", + "5eilALGCdhnPp7OAZPW0zs3k0b4UhRHXSx7OnWrmaHYKiSfYCsttUWfbRtgkceqs3lhV5NhIQZx89TVVpP7UL3szNkHP86S+", + "9spxDxs4bb67/ZnuoPd8m5edmUppZrKELuDBjB1TL20dLfYyD8GkvHUizCcKRKlhz8X4kkagaN9KpkgFvqVWl4lCJAgjQdsW", + "K+DrME9boEu5VY/KWLc7ZzK8UePMlEmihGiOsdKkx+695247fb5SkaKEecgEU2uwo3VDu52WVerPqYRJ04yHa1JISZZc4lID", + "csAWIGN3q5Ov29nZevQpFR2U85mhd2jKLg8vK+kWZMp9UhMKdnJGkr2Lq+4dreJ8rNsqQrsHp/wjnaI4zDBqXEpJ6m1qJq9m", + "7Dr2ySmndWe9JpFrCl+tgS9augNBk1+nNHzCxXE03aK+z/tTc8Jp1QZtPgvxuK0qG/cDLVOF3WVmanuL0167APslnSuzU8t/", + "CrDXTMvVStg6xC6UVYsdemE5n2jFFESS62g8BOgztDUSb86iW55ra2vfmpmfmd4oWkEZRi+T9ixSVFMTm4mXtC/RgkgBO/cU", + "wyNqdcXtKlOpAqa4W+zuVFNWMu1G6xHZ9uI/sUNvEMlDCd7kLvRURG23q4+1e0HkGTwD5wRjPBsDtyVGrSQIbndPJHJilGmz", + "sfZJ2eqB4aRWY7Lk/OjBgkeAYaMqsusyux4sNTnUwH7keIkiM5Zmds5Mxcil5pXkcRK8k7ti1k5bM23I3WckUiiOdDjq4goy", + "+F2ZxPee9poQYetM4S0y5doChy33rIjYu/Th/k5/0Ckk9BbSy4cOzZn9a+2iI4+2tFLAEYath5BvapOnHLEcrSgwa/I3SwYZ", + "AqFh/ZKpxSYSt2Ducunu4BZqk1w5m54d7Z7yrptWj8lzYGXSYSAaONHCDAYuQNP2vvw2eQGZj8cfU2cjNo/Mymu9KAmmJaFy", + "sxRammzZZ0zaeVaVvloSeAx8aqZQk84rRrCc39RmgZ/MTfL/WjbQLKgIyzg6XVp6gyIjTHNosq+VEE31ZVbkJ7qiMYH7yPyc", + "Daq8rko6WwL0VZH4ySctmj09EbZkSjxN7SFb8pVDCXTHjlvv3sqbZ8eW9e4ULDAStG6fedbCF8VU8Hw1dgEl5Kbw+XMtRxYg", + "f1P++9IUhtxW2Fbz4GAD3HjNgzbd81jCBz9C7b/YND64htrl9q9k3Wc8C/WW/mJ1OuvRWef9HlkIogI/f+8a68jf9hr563lV", + "ur37F6pF/x+/BwaA9pofPv3BRXIMiAUh+6S9/6xzL5BvgH9dV3W8V3nnd3jZWoB68KusT8+YF+yv9ppgI3h4igsgq4H/8Dtk", + "HQGfA655kXwHqjEHN8LD6Rrvsg798dQrZJNgb7zLevg/ZXX7RVaSP+u98h5ZBq5O1e6DNeAyq9HfJafES1PPh0r9ZxIvw8Pk", + "gnjzw0dwt5blAJ/0yv4LXhl/nfX1aM+7vGu6A0Yp64nL/HmJte/+vfTeOx/8iJ9+m6wGF7wa7bGbZ26+/tGT6benokKIVVxX", + "WMnl9VRtdZuq5lId2xusO3qV1WRRcRd1Ri/bZ67YXy9NVXGpnurMzctZddJr+SfZGrumV1W9rGoqr3tCjd9Z+96j/t4J1kzp", + "KlduXkd1lz/Dw6gBs08+4d97g9Vjp6cq2aItqGCLtrx88zzr397wmq2Hswqyl6f+OsPnfQp1g/jroxNtrVbUgPn9zrNi7C1d", + "kz15xv695pVcT6EKzu+nerRzdpVr9l3VsD3qNWJngjXH+/OJrJ7tZdQhtnfPn8HudAb1a+m966oHhCia2YMC1AwXkxCmTqJQ", + "evEDvzMd1c0khUkHKvmVKILBdocNzXOlyLl8sxXMW/qt7mCVnFQMPjqzp22JFbJES9MB46nMnFm+01v5dHKnaQNh6xXSelMh", + "3RmCSFYhTLtKqG2knuDnA7qo+GFKVuaJmyYiO94qj24o790pMmsvHS7g6RQocWb68ItLRXy8DSPQeZ4KbdMXzfy1XYtTruqU", + "6d9Z3jWdhVuZyum0z7s6GDxY3xJBXPgW+uobsp337VnMNURAB+o65n6p+elkB47ZzDuaQn3NzOTJYzs7l6ZHJUu/4cqdKWxB", + "p63bcFbqIhdh8SRqzCt5bCks2VmeihpOW19L5ujq80cHw24zF9naQulaF/BOrN0ZeyoEI6atNWvV0arXa2ULipzFfed0MMN7", + "xcWwZzLV9jBpPPqblNBH9Yorxrqxl6pWphyefdOpqqViOhUfyQC3Xr5IzftEyTsd4vy8Z15tNt5v3T1piebUjDZtgXogT4NF", + "EIgTudXy7hRTa6WFm2nGw6ltbcovD7F6B8eKgxvj4epGJlyMD0/7vcR3ZYtHQJYNQs3MiPvWrtnc0tJYx+M2CceqS/s0azKA", + "5n3MChCml5am8MsZ1GM87M0yxty6pM0t3k+k5WQOT1VX9pNXmwWs2jQF75v5PRklID7fei4KhBVTSRXGjdr+i+oq93xaQC8R", + "k9O72fLRpGnNqUIq1K+DvByX3p9peGdGf3izwf3rkshmmAanpPueOZF7Fk0Sp2W2ykRrFrIviKZM5dlCHnzcugNFsOQy5JSH", + "IYvct7MRzRFUjMP0euVW2ihZE9lGX5N2pd6V6IwjZlcmmY680yfactaNiHZelzq9tga2qi0NSOtYIIZyuu707umNUSTwyS/M", + "wmThymZxpq/2JbVoT4jBW57egnKQI0Ohg637h4Otcr0MtmTXYM5qUCL6mpV9YIKIVs5c+fU+IKFVH/Gfw4iX2jO2eWfd6BDz", + "UmlU2q2KW2FWGLttc1Z+7HawTk7jWZwLNMX7p2qord3T6B7FcxOcLi92CTR2mwWf2kR3zpiDn0tZpbmqTYY5EcdLYpVphrol", + "sa9uihxkHEeMajoXi2kYDpZGprkj5sNiVpyIu5LKoMQM2yNV4oc5+AubW6pHxYom3ccZ0nSIoCmxAD0TjBznM76pi8H/821n", + "hgFdyemgFbqYcVKdDoqP51peF3z4ojNWnXreaUyc4eeHwZHyPslAzjltjr97xVmYnPUlb1Vilfl+ECslUpHg2sJ94/POoWRN", + "fZJfOR8sNO8Hscy1jFvG2vwIOEbwlR/xyj8m7cmpjHXqhaDKec6v7Jd6MThzxMTyfHbZn5IZ5ulgUzkdzUj8MGJAejXePTtF", + "OuTMJ8H8k4jC0qB4T55yWien5HqYb50NypfX4+snguPl1YwDJyihcKM/j1bpvuJ4eSsa/0LQlD0ZvEan+JZor07wjk/wymIM", + "+3YQOp0JEq2X+fuPg48op38RW9FPgwHmGfaMrvx83Pck5+EzbOd7+PcV0nk5y9BVp9DB76eiD58NZio90bmYPz9AY3ApsYG9", + "yktdjUF81Se2P8K1eN7oSZ9sz/ArifnqtSA7ej9olC5H152K532VVEIvxndPx3WuxBhpbiQeuVdj0p4KSqIXggXoTMZy9lZM", + "Zt3ieKygRD+VWHROxWp6OHaDx7NReC8YgcQv9JJTD+HDz8WIvx6sRKdjLTzil/J19O244Ivs57SfnGi3CO9MNemHMduD18uv", + "LG6fi/HhmLHek4k0LLoOH3vOv4K3RNkUXF748/W40QuxNYFFatg0v5NrbOweTWd5+HLO5T5KIGGm1acN7pmlW2AYxVRdWa9e", + "vsUrHnnN6Lzt5bzU/KodQg+2ma1i+jzZfYtJOxPXT351Oe2y71q8JTcE9HLXzB0ZKPuKW2zVFp9Ec2hf8LF7KLa4XbhklGv3", + "gTIKXcewqpcYiYVGGigCqv1C4LXewi2e3wzgGLneWKJ1Ce3ZbpfwuXvoe1TDhB9WQWzR3DIAC7fECpwD2SzTZmJX2OxMm5B7", + "RyQO39/5OjL3D3aWyUlTtMjLDO0NON7izC0Rg7liOptf0sRuNbtucdaX0v09w7h4SwcIp9CaqsTq5OWZxTTiKXN+VJeZ6XDB", + "CgpXM3zN5OOS/6Gz3LnFo5opiqm0Ki689z9lhR2eb7qjWivNDptVQVeiUClunzwkVXDnqwdx0DdHG/b+N9F/39wGfDVzDbNf", + "BXS5xQ/JMLDAeTQ5Lzi+cFhZpyRpk+sNqwZHy8ftxH2O1EgG5FTJCK7JXugPZCt2luWqtFjJvMSR411M40GnZ9eePb4+dpt5", + "WELwQ0WaKHlRfCjzo0k6Quc/09aDFusqZvCq3PDOtMO/+y4W0DLDXDaD/twty2FHc/vkSLmOjP9ss+uP9vzXW0zbpflbXmhn", + "ggJkt7FZt93mfsNtWX6MHehBoRQEbPF9jmvfou9RFEv65RYfZOThjDR/V27ZXxLHuEStd/3suZ+9bf9962fv/uzaz67/7Oz/", + "V9e19UZ1XeHnjMR/OJkosq16ZqBEVYPHExmbNFRJQKlRUvWhGs+MzcDYQ+eMsa2oUoyBkqSERAolQlVCCgmOG6gDcRgIxlL7", + "B/Abj/BSqf+ie932XvvCiy8z57ova6+91re+b/ccsAFjzJzyIA8w0r2DEfABRuDvINcxRtjN788xUwGRfOT79fMdzPl7j77F", + "s79AhmDgE97GnMCXmEXYwm8pY0GMysj5jL/943UEnvmUmQN3sHse8xiQHdji7MQWZwUe4RNc2j3HPLzEGg05mB3kG14jNlvz", + "/Px+u5/w+21jvgSZss0ZW3574NHb+KzUPltBdmTTRfcVJx7zkqm49nmIdHNcWUX84aeNX/+gMglrwNT2ZJ3Pv/vkPnDm0fWe", + "3AKWMryD4yajsz6yXH0XkO9Nvsf7I9/ehuQRPJ6zb8wTnKVPgmd0nHd8v153ptvXYi02l0+53GLN1VAyYVk1XKPQxiHIjS1d", + "OKmqlhgK0DJds7gi14+a+znZYRVQDCdSVSuFYPE3RQwQ9EJ/EggesToLHFnjSK7sRouBeXPYOYvQX4KUaMsZfFSd7y7gFMbJ", + "LOqe2SGQlOwZi1j2mBv2FLxIC9QqV/3MKKw6EnPmJvTcFoDE21O4Y4oij2N/6yASmR7pF0H1+lxJ5ohC6H2wLXVwQK5dEG9m", + "vDgBonmj2Rutzmmsdx3FftFZEBfC4JNdETvu/M1iw5h/8wNCI7Wq56GB6lOATQYZNIhu2hqgKFExVGU09HhxsT9b+nWxVnAo", + "TQtIPN2qd1RYEsJY1JtZ3sLoeLjaZaE7hEAfieshxkSXU8GjA4JjliSXaBnwK28QkKCKxlXdKuLuZtvLxVrQtXsKUGrTKjVB", + "l52IMSgWDG8GCyogGWcziqNOGo/LLFr1HFTlW9nJdgeQNT2gEgxcR8IaNfp2xFg+JAnCHT3exRBWNsGKuaLgYV+fcwId+y4H", + "Wwsn6qBcAuxuJ82DmG9bJXCxoNXm6vMtth+ukscc/C4JQLGClmgoZeIcHO11EYT1G/PPwgxUDGsiHAHMIioH2ZEQ8aKowAgW", + "hegUrabKzG6SG5Eth4uPS0xNIJgCDnHevTV9GFPMK1KaZtuDZaXAx8LoY+6XQgEyiDxUF8ZEColFKMuDUol2I/eYvzBmymBv", + "Em+qz3V5Hu+RibwndAsKgB/LtNCzGTOjmbYIHi0U3OWtttkKQSFv9i5mMnNXA8G20MHQeBwoZ4ZMm8cfhu3RJTgciCRh8Bxk", + "nagTmahSiCkUlMnfQpSNa9dAqJiIIbXzbsdWxSAyWBd/S0DziPGILdkJV7k67fM26C8KHoXYA6jWxl5US2BjPfQ8YvLafVtW", + "oIV4WUnHDBNW2CTQoi1aqYCCI+iutfyk1ERopL0TYFVsgCgS4J5laPeXuiXj8/asMOPUIsvhAVILVAmb8gFcrtfuNv1Chowa", + "yN9YMT8e5+06Kx4poZBjWeZJWHZRmLCn7IfHX4cIXBw9FC/HpvY4NyFvYTcm9ZkciBPMniw0wjbIfUDi4WNqV0obpbET9WUz", + "32dyjidU9pVdikqqjagzVJy7wtNauz/ogoCVLyERyXjR2PPT9YbZfiGKGJa/1nDx5f2TqsxvKHrm2hGl+4YimqNqJ0i+0i+r", + "Djwpa6ki3TCb4nr/gFnQzLoFeDSZhNHcL0QOWR43kPaeiDsni0aeQ2eKwmMxCx21YrSjVLxmfHt4rFcqna6xy1w92VQDlAak", + "qwQUrwDZ7DorioxDdBJdHdZY5ATqRDnh3TxyQzweaijqzRUkWaBqND8VBOuw9S+sq5p5CRXa6yLlGEmo4o69+uLUkcnp3x89", + "lElXaNIe+lmshTEpr4MxquLj/eBm45GjAXg6Idtc7EBVaWBcjK3wq56gX9+o98zzNnVExzlVXDVNrjLU10ow4MgySHvpZZu9", + "8pOtFcQKmBnDb6FGmtopcH3mLDJNdFQNsR7h5J5nkdvu12RgdUe00JSj1duvpUCL3oFx0lHJdUCu4qi3rB/gE/qVjcIc5epO", + "ZFEj6bDZPhMVCiNVprVAnXuhK9yogM6bouAwNny0KNUI6qOg3+tZGGOajp452tf0Hb4YAlGtXrfHJD5mIe4s5kgg4RVfYvRF", + "q7PRbs8MNSoRttw3k4cnONz0uhkrM93uSYsNcEwZCzRy6jZ3K3XXzihj2WtrXlXvI9NWvwPxswYpxlLy27yJhI9GpS9YW1hh", + "1ckK5Iz4P9LvK9XIWmQiJxayINWuyE4s3SdsYBZ7ziWY7C7QkDZuAm2GYbTMGS9nMedSvPwogH2Bt2POJcQ1qtryBwGdiwMY", + "EEhg3lXn6ExohhuCevNEHTE1doxh3MsLCBsnP2cCIst6qjhhienGXBcNrU3MHydiUmEox3pGRkrYcOsURB7Rh5JabEsLnFGF", + "qtAa6UolqSJ1jMTkRGreBIhHdns6qoalY3R1KsBqIG0IDWAzPHpI8QsEhwI78zYFdlrZaCN4N9CcXcL8mPFlYTBZ/XnroNsp", + "eW7tkmm1POBCMPOU8U4KoXKwC5YXCGGYPS8PasjMlk5BAnlkBrXw4JhTDSX0b7cPxR+5qG0KBRPw8yjed9wn+NW/RNwd7jPt", + "vYFBYLl86vipAGtnRl9kaAuOHVOoj+pAztVFE8F7XT9KC7KOPsYca1GZCMr58dO6wgHfXeB1Rbp5cWTM0fi0iV+25UHtsIlx", + "Uc00RRyXaWFIhrjV9o5lQTLK5yfBcYgrLO71KssliAirm3A/ZtF2Xn9LUTSbfrB/kM3E5znVRk6Xx5/tfvT4Z8Auo14Y6ZSF", + "n9wgFTBEkp+H+C4ruz0IVNhE1Y5jnP4nu5c4qnqXFd4grgpx3R38nyPDj3/AM3cIVY546of4F0V5N839KBp7D1HlHGNGhDfj", + "uvnuFFH+GXX9SNeM7g647wf8FsHzQEwZI7jbHDH+6+4niDw/h7j5Acd6QdnuB44mbyP6exs12rbw/vSmcAzh8OWTB/QWrNIG", + "d/8Uj3+AmnLboPKH+daLAhjYlITsBcyormJu+g5meym/bAEMSneMJZzOySnfSrr2vqTXL0q2mlK6Xyutq28VEoDy3VqBS9AR", + "8LmcBXnnq/j3V4ziYC0hQlxcVcnfMyrtvo7PsKrUfx6p97JoGfsWA7nOZ3jKHdE+WxdwyKbgCj7A629y3pyxBISrIVmcWwIR", + "eSiveQFP0WdRy6h25jbckFOUCo/DGFyUfLoGV+wo5MaGNPKH0hH3FT5HtaEDkFgsgYaCPJKuFzSCQ+P83UEIPM27VYVC+Ukh", + "Z65Li+1I79wTUIQCF3lIj4uigbWBf+wgwuQR6ze5pz0janqEHrnqQ1PuyME38cQz7k3dvTakRy7jWbcZoMJifDTAbkqb3BYF", + "Lmq6GyKzJZpufPfb3uhlPbsL2JIfIHCFYAwfCyiIRO7oef6m2v+8PN5fZDzbdv6ecSkOVvRQRu+6TJ91kaCyY0xQN+4T6qZ1", + "1c5b7joEDuF5sS4zzgpvreMT/kuJwaFiIPx7214nziN5tSmuImXNHLWO1RwbtqpB1IzgmPvm9788dR73ieg0hfmh77hO5AJm", + "qH7ELBVdGWpa1lGxiJ9HNI7UJ3cx23XWZqa+x+dahWoO1vG5Gd4Lj92Sv9SGUkIwS/vL3d5cZd+rr75aWUYSH9gjhEEh3PbC", + "t2OZTQVEURhhbVL6HEVgbxHW7/Fid3a2qCntmMZvDOQ2IFUvoH/jsUQBpeyloD4E3ECdsuIcjvWyXiqmBHz4ZC3owR8VqlE+", + "plI59HYx0zdcAtKSZuvYO4cnocR0Ab0lvuEJ43XTJQ6EiWfUGA9yKnnDRnUyG4/TdFZ82yz27uL9uOeQ8Y3jrs3ACw0iWpKo", + "wHanQFQl0bdx4AlbAjuZkkKv1QpLURrktSD1hrEVzPV718qiHeuBON5SwGihp+7Rr8YhqSwdKwnA7CowIyf74xtfypOQIFYH", + "r+Ac+cIyn8LAhey9gL8ux5aGDp8JwtU+ZBlOVuRLMkSzKJe4z9aZYETOTIS5GdDz5qCA2UvPAaIlmgjteQFVqS3MRKPebM1T", + "XIKQI7mKJAmqR+8q+fHLZtDwJuLgyuHmcLs5QkxyJwSYDVti2WYItdfIGDPOeH0bu+gFr58pRlaLI8aCVW65KheGiaPwBXNg", + "aE0HTl17GXD6GVuOtqcGQWHFgCuM6Aag7NkTfoBUHOz+F+b6QKw4VZ4sx+O+RDwMwgUBgY1RLU0m7B5uV9hU5dZB2ZBKmEmo", + "kyvEIP8n8ccsDkDOt3Nfnq07a3mqRrPjvCnM4+jmpDFj8zPturpYa9kMSCZF4eKUxZzUCVS7cSDQy/5CuMYP2tVnZ0F0oa9e", + "CLHn3MY8rVzwTjHERSFwCazAcYfhEgtNDXXkmeaycHa3rSUDeHIfkdzlUmvGvHMLmUXqkGzs9V3RIq12EAOySTfAGUlc0WZb", + "hQTBsly8zpFd9cgMZdIKQMwKr4fJ22Y/7PqL2B90iVMd7U6jfqougiSOBU0Hbr0hB6UpNORmF3s4TpUdc+1FKgZQ3yFyFs6U", + "QghsxbTBHBDAEbFZ3EFVPzX0XunYROnU8ZWc0A5WpAZwgGZJBRMmo8/GphrwRQPQdsPyGi45imYAGx5xI/SOObNy2DgX15xZ", + "jwZUeXT4hwKRIHXVQ44pmCaYzsB+bIC2YA+IIqBdXt5/6OX9kzzGzD/FkZGxMCIFK6RHUigxbDOs/hjUPYb4WoBZBkYaoZdx", + "nu29EvDITpmZNDwCRnu6PW/+yuIQTNFbVtizcB6S83mCglxUpbPvoFwjpKqV2cX2XI4bUm3gl84y3tjCcVQWL+EycYRe26e+", + "OEj6zkzN6rsioKy3NI0cw3VYrld46E3a0kjsAa13J4bHA9/yjXzuDi7qCXDOTFsx16vPI/7FIiC0wJGAl+z1HNrCK6yV4xIr", + "drx8/qlYTTg0ajmyPqqXv+CjqZWDnvpVrQovqoewMMrpEYhOXVCJHeKtsT43izPJxcS6mfDeitSXfa8v84Tnt6cQP18tNfDZ", + "GIggHeiPjSUWDccY5gRTrHKVqJO0QcyAZRs0Bpsw/x7AKsh8VuGnpybBeTF6H5/9WE290912c3jvyFjRYxy3pc7xVs3lHJzp", + "riVcbh9/SH8FFeoILiEMFGqOEucdvK9itpLJUI2DzA3OasPK0WnPYvOOejqIAkaJTVjmOCjhOHIPmu1THSIWtQw2ueP1ce+L", + "AyPAv2WJNuDkdS4+DuYXE+6jp3alXDdPros4vqIdHUmpYbbb/qWlm0SVwozgfphZMT7uSRqJbmw1RSyC7ZcFnYkgErep1epR", + "x3Fey9seBQXSCCXAPj0NOCKgQW4BO1JOnt0pyHdapqthu0F2ewjVVjYj6liwnX+U6KJalthAIgaHQAkIHIJnI/kyHw6BIxJl", + "gRy+UqlTob+y1M4BS4fZdJyGUp4M9iW4uV94SfOS9MNamFNsN+n9+IXgH5t1tFk1tUBAh3TnzchVjpcnl8g9MJuwL4jHZFko", + "xgchmf7i3OJ/NvJsmHLriyPCh7N75fH27ipmOzYxhxB89vgaZg1WkSOIciP3w9wFIczNOWcxC/BQ8inmepIFcTmEbeIMkuwD", + "cOvE5zJWPvzsGmVRzHUBwz6wGH3Kh2xZVp74ep/Q88ITO64dc39iB9rEz5APR/hNMOb3PSqvn+f42o8cKVxT2PEz9NmTW/CZ", + "v0Ydm34dbElO3pcxlKoWxi/dZTlWz+rIaEJak/FsCMeaGPvI7IBHFUSyKDqUp/ysYmoxUBhxZ5KsN1JQ7ghOt3D6VVNOinzp", + "eTiuKkSYwIzHFfmMcOEMOMjbjZPeKjcsnq1ybP+sCEPF0ylmR9F1H8r1virLUg556GijNx8t01SS4i1d9Cu07erI4OdLwPsJ", + "0/F9M5VLXLZVSPm4RFpT88lraPEKwhFyaEEfG7gUheqLpdIffAKPiXYPnqRWSLRIyjNdejq49nRw5+ngO/h5/+zTwZWng388", + "W/vm2dqnz9auPVu78mzt+rO1q8/Wvvjvrev/++fntuT8/qr5b0TyYpuSvKAsw9cYt/+QU2Cc6JGsDVdcXpR0m60qDTI4Nj1h", + "kwK2CnVDikAHnIWEsy67QlFXO2wri23x7BWVvgkSgh9LEfSO5LC+lMc7J/WkmyrJaKuGbb5yXQp+deJmNSrNvswVppwU0/ms", + "oEz7hhTzXuSidW6Tdayf3ZGvNiRBdlmO3JGU31fqdGqfM/jM+sMNqd71q+D5aTdVFvKGyhDZfqezrsuJt6VVzd2/9oRL7S44", + "RhMC/kC5EaosLRr28It3J6EHAWQr6jZSf4MGK9xfplb9Yi20gTRdEnH55fmOOtYZs4BeSqyn4qRRuxmzCiR8qJQ/XKmFIQ3a", + "1ZTTllvtON2k14bUWdcYfwnmM9iGcjWosu5qi1eqVN7dP1mpTE1PZe+9Mf3Wm9m+8t7M33RJRCbY8DBVlnlc5mnCrRvUSJiG", + "Knirp5ziIhm/NY3+O270VDvmB+dS+78saCze0eJdhoLeHIpjUAgg8q/A/Zoll6zxoV8kMlDV5JJZgETPaNYH5k549VFMvamq", + "L1WO5teRyzhLmv70BPCXM+sgpCJFpud77XqJusC8eW/RbJT+fa9KbR/Og8743jGqQ1fu0ftq449D+0AGzEjJgXr8hRdS8bR6", + "HxTkwyepJZf/5Fuk19VWshnGe8nbtcZTzor2xpvd7GDPOOmdEcW1OEDeRsLy3EFMEPjIPzn8jsc7eUeqMbH28i6xRypMU+IK", + "5lO4wiXihwSED9We+tYzO3rs4JuHJ7PiQr80HRAZQPfFMZVJ+B6iMQw70/lVssTGEC7kuu3T5mDa/Eu2c1+p711QubbT7/Ah", + "lYSHbGbjmK6AVEsLhor6b5tJVqa6lYMIf03aj4X6iTwes+ZKdjs7UkY8PA/e2IfFE3AMx2tNHHXEr1ORLrO7VauCduqr6dUi", + "jlrhQ6k1RFPuJTABOEvSljKOjmAj18vJzUqyWedbx9OvyQpR4WjR4wSHySvlvfuyaX/1twnH59yz+pzuKWbpFSzx8pj2HE+2", + "YX94KEuvC89pr2Iz7cTkgAzuJOAQ8fvT3Kim3RPIJye/wLlUjls6mss88wM3wi6Oz+nCwnOas5qy0/Bez2m2GqIzLykLxdaL", + "MJhSO8+7fod8HDCK0tahA/oSbeUOIhrtdQRrNhB31XrrlwXtdUXBygY+xu1jxQpD3v1NBVyyiLwdRfCzw9dMuPO0cbmMFFOE", + "29oUrNZXqX3Ghr8TuigkT48Q+TXwvXvGjv0foSWBhw==", + }, + context = { + "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwABAgMEBQYH", + "CAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8AAQIDBAUGBwgJCgsMDQ4P", + "EBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/AAECAwQFBgcICQoLDA0ODxAREhMUFRYX", + "GBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAQEBAQICAgIDAwMDBAQEBAUFBQUGBgYGBwcHBwgICAgJCQkJCgoKCgsLCwsMDAwMDQ0NDQ4ODg4PDw8P", + "EBAQEBERERESEhISExMTExQUFBQVFRUVFhYWFhcXFxcYGBgYGRkZGRoaGhobGxsbHBwcHB0dHR0eHh4eHx8fHyAgICAhISEh", + "IiIiIiMjIyMkJCQkJSUlJSYmJiYnJycnKCgoKCkpKSkqKioqKysrKywsLCwtLS0tLi4uLi8vLy8wMDAwMTExMTIyMjIzMzMz", + "NDQ0NDU1NTU2NjY2Nzc3Nzg4ODg5OTk5Ojo6Ojs7Ozs8PDw8PT09PT4+Pj4/Pz8/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAAEAAAAAAAAAAAAAAAAAAAAAAAACAwQDAwUDBAYHAwMIAwkDCwsLCwsLCws", + "LCwgIBgoHAwMMDQ0NDA0NDQwNDQ0NDQwNDQ0NDQwNDQ0NDQYDBwMDAw4PDw8ODw8PDg8PDw8PDg8PDw8PDg8PDw8PBgMHAwA", + "AAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQIDAgMCAwID", + "AgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQECAgICAgICAgICAQEBAQEBAQICAgICAgICAgICAgICAgICAgICAgIC", + "AgICAQEBAQEBAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMBAQEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgICAgIC", + "AgICAgICAgICAgICAgICAgICAgICAgICAAgICAgICAgICAgICAgICBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", + "EBAQEBAQEBAQEBAQEBAQEBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", + "GBgYGBgYGBggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoMDAwMDAwMDAwMDAwMDAwOAABAQEBAQEB", + "AQEBAQEBAQECAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMD", + "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF", + "BQUFBQUFBQUFBQUFBQUFBQYGBgYGBgYGBgYGBgYGBgc=", + }, + prefixSuffix = "ASACLCAIIG9mIHRoZSAEIG9mIAJzIAEuBSBhbmQgBCBpbiABIgQgdG8gAiI+AQoCLiABXQUgZm9yIAMgYSAGIHRoYXQgAScGIHdpdGggBiBmcm9tIAQgYnkgASgGLiBUaGUgBCBvbiAEIGFzIAQgaXMgBGluZyACCgkBOgNlZCACPSIEIGF0IANseSABLAI9JwUuY29tLwcuIFRoaXMgBSBub3QgA2VyIANhbCAEZnVsIARpdmUgBWxlc3MgBGVzdCAEaXplIALCoARvdXMgBSB0aGUgAmUgAA==", + prefixSuffixMap = { 0, 2, 5, 14, 19, 22, 24, 30, 35, 37, 42, 45, 47, 50, 52, 58, 62, 69, 71, 78, 85, 90, 92, 99, 104, 109, 114, 119, 122, 124, 128, 131, 136, 140, 142, 145, 151, 159, 165, 169, 173, 178, 183, 189, 194, 199, 202, 207, 213, 216 }, + transforms = { + 49, 0, 49, 49, 0, 0, 0, 0, 0, 49, 12, 49, 49, 10, 0, 49, 0, 47, 0, 0, 49, 4, 0, 0, 49, 0, 3, 49, 10, 49, + 49, 0, 6, 49, 13, 49, 49, 1, 49, 1, 0, 0, 49, 0, 1, 0, 10, 0, 49, 0, 7, 49, 0, 9, 48, 0, 0, 49, 0, 8, + 49, 0, 5, 49, 0, 10, 49, 0, 11, 49, 3, 49, 49, 0, 13, 49, 0, 14, 49, 14, 49, 49, 2, 49, 49, 0, 15, 49, 0, 16, + 0, 10, 49, 49, 0, 12, 5, 0, 49, 0, 0, 1, 49, 15, 49, 49, 0, 18, 49, 0, 17, 49, 0, 19, 49, 0, 20, 49, 16, 49, + 49, 17, 49, 47, 0, 49, 49, 4, 49, 49, 0, 22, 49, 11, 49, 49, 0, 23, 49, 0, 24, 49, 0, 25, 49, 7, 49, 49, 1, 26, + 49, 0, 27, 49, 0, 28, 0, 0, 12, 49, 0, 29, 49, 20, 49, 49, 18, 49, 49, 6, 49, 49, 0, 21, 49, 10, 1, 49, 8, 49, + 49, 0, 31, 49, 0, 32, 47, 0, 3, 49, 5, 49, 49, 9, 49, 0, 10, 1, 49, 10, 8, 5, 0, 21, 49, 11, 0, 49, 10, 10, + 49, 0, 30, 0, 0, 5, 35, 0, 49, 47, 0, 2, 49, 10, 17, 49, 0, 36, 49, 0, 33, 5, 0, 0, 49, 10, 21, 49, 10, 5, + 49, 0, 37, 0, 0, 30, 49, 0, 38, 0, 11, 0, 49, 0, 39, 0, 11, 49, 49, 0, 34, 49, 11, 8, 49, 10, 12, 0, 0, 21, + 49, 0, 40, 0, 10, 12, 49, 0, 41, 49, 0, 42, 49, 11, 17, 49, 0, 43, 0, 10, 5, 49, 11, 10, 0, 0, 34, 49, 10, 33, + 49, 0, 44, 49, 11, 5, 45, 0, 49, 0, 0, 33, 49, 10, 30, 49, 11, 30, 49, 0, 46, 49, 11, 1, 49, 10, 34, 0, 10, 33, + 0, 11, 30, 0, 11, 1, 49, 11, 33, 49, 11, 21, 49, 11, 12, 0, 11, 5, 49, 11, 34, 0, 11, 12, 0, 10, 30, 0, 11, 34, + 0, 10, 34, + }, +} +end +__FILES["codecs/compress/Bzip2"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- 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("rosetta.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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Bzip2/Decode") + +local Bzip2 = {} + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err + + + + +function Bzip2.decompress(buf, offset, length, opts) +local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes ~= nil and{opts.maxBytes }or{(2 ^ 30 +)})[1] 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.from("bzip2: " .. tostring(nOut), o, consumed) + end + local res = out + if buffer.len(out) ~= nOut then + res = buffer.create(nOut) + buffer.copy(res, 0, out, 0, nOut) + end + return res, consumed +end + +-- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) +function Bzip2.crc(buf, offset, length) +local CT = Decode.crcTable + local o = offset or 0 + local e = o + (length or (buffer.len(buf) - o)) + local c = 0xFFFFFFFF + for i = o, e - 1 do + c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) + end + return bit32.bxor(c, 0xFFFFFFFF) +end + +return Bzip2 +end +__FILES["codecs/compress/Bzip2/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 +-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is +-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. +-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). +-- +-- Never throws: every buffer access is in range by construction; failures return nil, message, kind +-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +local Crc32 = __include("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: core/Crc32) +local CT = Crc32.MSB_TABLE +Decode.crcTable = CT + +local MASK = table.create(33, 0) +for i = 0, 32 do + MASK[i + 1] = i == 32 and 0xFFFFFFFF or 2 ^ i - 1 +end + +local PBITS = 10 -- primary lookup width +local PSIZE = 1024 +local MAXGROUPS = 6 +local MAXALPHA = 258 +local MAXLEN = 20 + +-- scratch tables, reused across calls (single-threaded) +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LENS = bcreate(MAXGROUPS * MAXALPHA) +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length +local MAXL = table.create(MAXGROUPS, 0) +local CFTAB = table.create(257, 0) +local MTF = table.create(256, 0) +local SEQ = table.create(256, 0) + +-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed +local function buildGroup(g, n) +local lbase = g * MAXALPHA + local cbase = g * (MAXLEN + 1) + for l = 0, MAXLEN do + COUNT[cbase + l + 1] = 0 + end + local maxLen = 0 + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) +do local __DARKLUA_VAR=cbase + l + 1 COUNT[__DARKLUA_VAR]=COUNT[__DARKLUA_VAR]+ 1 +end if l > maxLen then + maxLen = l + end + end + MAXL[g + 1] = maxLen + -- canonical codes: by length, then symbol + local code, idx = 0, 0 + for l = 1, MAXLEN do + FIRST[cbase + l + 1] = code + OFFS[cbase + l + 1] = idx + local c = COUNT[cbase + l + 1] + code =code+ c + idx =idx+ c + if code > 2 ^ l then + return false + end + code =code* 2 + end + -- perm + lookup + local pbase = g * MAXALPHA + local tbase = g * PSIZE * 4 + bfill(LOOK, tbase, 0, PSIZE * 4) + local next = table.create(MAXLEN + 1, 0) + for l = 1, MAXLEN do + next[l + 1] = OFFS[cbase + l + 1] + end + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + local k = next[l + 1] + next[l + 1] = k + 1 + PERM[pbase + k + 1] = s + if l <= PBITS then + local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) + local shift = PBITS - l + local from = lshift(c, shift) + local entry = s * 32 + l + for j = from, from + lshift(1, shift) - 1 do + writeu32(LOOK, tbase + j * 4, entry) + end + end + end + return true +end + +local function grow(out, op, need) +local nb = bcreate(math.max(blen(out) * 2, need, 65536)) + bcopy(nb, 0, out, 0, op) + return nb +end + +-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind +function Decode.decode(b, o, e, maxBytes) +local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) + local op = 0 + local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local bb, bc = 0, 0 + local tt= nil + local ttSize = 0 + local streams = 0 + local consumedEnd = o + + while true do + -- stream header (byte aligned) + if streams > 0 then + if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + break -- trailing data after a stream is ignored, as bzip2 -d does + end + end + if p + 4 > e then + return nil, "truncated stream header", "truncated" + end + if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + return nil, "bad magic", "corrupt" + end + local level = readu8(b, p + 3) - 0x30 + if level < 1 or level > 9 then + return nil, "bad block size", "corrupt" + end + local maxBlock = level * 100000 + if ttSize < maxBlock then + tt = bcreate(maxBlock * 4) + ttSize = maxBlock + end + local T = tt +p =p+ 4 + bb, bc = 0, 0 + local combined = 0 + + while true do + -- 48-bit magic + 32-bit CRC + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc =bc- 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc =bc- 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local c1 = band(rshift(bb, bc - 16), 0xFFFF) + bc =bc- 16 + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 + bc =bc- 16 + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block header", "truncated" + end + if m1 == 0x177245 and m2 == 0x385090 then + if storedCrc ~= combined then + return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" + end + -- align to the byte after the stream + p =p- math.floor(bc / 8 +) bb, bc = 0, 0 + break + end + if m1 ~= 0x314159 or m2 ~= 0x265359 then + return nil, "bad block magic", "corrupt" + end + + -- randomised bit, origPtr, symbol map + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local rnd = band(rshift(bb, bc - 1), 1) + bc =bc- 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) + bc =bc- 24 + if rnd ~= 0 then + return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" + end + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local used = band(rshift(bb, bc - 16), 0xFFFF) + bc =bc- 16 + local nInUse = 0 + for i = 0, 15 do + if band(used, lshift(1, 15 - i)) ~= 0 then + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local bits = band(rshift(bb, bc - 16), 0xFFFF) + bc =bc- 16 + for j = 0, 15 do + if band(bits, lshift(1, 15 - j)) ~= 0 then + SEQ[nInUse + 1] = i * 16 + j + nInUse =nInUse+ 1 + end + end + end + end + if nInUse == 0 then + return nil, "no symbols in use", "corrupt" + end + local alphaSize = nInUse + 2 + + -- groups and selectors + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local nGroups = band(rshift(bb, bc - 3), 7) + bc =bc- 3 + local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) + bc =bc- 15 + if nGroups < 2 or nGroups > 6 then + return nil, "bad number of Huffman groups", "corrupt" + end + if nSelectors < 1 then + return nil, "no selectors", "corrupt" + end + local selectors = buffer.create(nSelectors) + local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 + for i = 0, nSelectors - 1 do + local j = 0 + while true do + if bc <= 24 then + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + bc =bc- 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + j =j+ 1 + if j >= nGroups then + return nil, "bad selector", "corrupt" + end + end + -- move-to-front over the group list + local v + if j == 0 then + v = mtfg0 + elseif j == 1 then + v = mtfg1 + mtfg1 = mtfg0 + elseif j == 2 then + v = mtfg2 + mtfg2, mtfg1 = mtfg1, mtfg0 + elseif j == 3 then + v = mtfg3 + mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 + elseif j == 4 then + v = mtfg4 + mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 + else + v = mtfg5 + mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 + end + mtfg0 = v + writeu8(selectors, i, v) + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated selectors", "truncated" + end + + -- code lengths (delta coded) + for g = 0, nGroups - 1 do + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local len = band(rshift(bb, bc - 5), 31) + bc =bc- 5 + for s = 0, alphaSize - 1 do + while true do + if len < 1 or len > MAXLEN then + return nil, "bad code length", "corrupt" + end + if bc <= 24 then + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + bc =bc- 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + bc =bc- 1 + if band(rshift(bb, bc), 1) == 0 then + len =len+ 1 + else + len =len- 1 + end + end + writeu8(LENS, g * MAXALPHA + s, len) + end + if not buildGroup(g, alphaSize) then + return nil, "over-subscribed Huffman code", "corrupt" + end + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated code lengths", "truncated" + end + + -- MTF / RUNA / RUNB symbols -> T low bytes + for i = 0, 255 do + CFTAB[i + 1] = 0 + MTF[i + 1] = i + end + local eob = alphaSize - 1 + local nblock = 0 + local selIdx = 0 + local left = 0 + local g = 0 + local tbase, pbase, cbase, gmax = 0, 0, 0, 0 + local runLen, runBit = 0, 1 + while true do + if left == 0 then + if selIdx >= nSelectors then + return nil, "ran out of selectors", "corrupt" + end + g = readu8(selectors, selIdx) + selIdx =selIdx+ 1 + left = 50 + tbase = g * PSIZE * 4 + pbase = g * MAXALPHA + cbase = g * (MAXLEN + 1) + gmax = MAXL[g + 1] + end + left =left- 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), (p < e and{(readu8(b, p) )}or{0})[1]) + p =p+ 1 + bc =bc+ 8 + end + local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) + local sym + if ent ~= 0 then + bc =bc- band(ent, 31) + sym = rshift(ent, 5) + else + -- a code longer than PBITS: canonical search + local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) + sym = -1 + for l = PBITS + 1, gmax do + local c = rshift(v, gmax - l) + local f = FIRST[cbase + l + 1] + local k = c - f + if k >= 0 and k < COUNT[cbase + l + 1] then + sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] + bc =bc- l + break + end + end + if sym < 0 then + return nil, "bad Huffman code", "corrupt" + end + end + if sym <= 1 then + -- RUNA / RUNB: bijective base-2 run length of the front symbol + runLen =runLen+ runBit * (sym + 1) + runBit =runBit* 2 + if runLen > maxBlock then + return nil, "run past the block size", "corrupt" + end + else + if runLen > 0 then + if nblock + runLen > maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local ch = SEQ[MTF[1] + 1] +do local __DARKLUA_VAR=ch + 1 CFTAB[__DARKLUA_VAR]=CFTAB[__DARKLUA_VAR]+ runLen +end for k = nblock, nblock + runLen - 1 do + writeu32(T, k * 4, ch) + end + nblock =nblock+ runLen + runLen, runBit = 0, 1 + end + if sym == eob then + break + end + local idx = sym - 1 + if idx >= nInUse then + return nil, "bad MTF index", "corrupt" + end + if nblock >= maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local v = MTF[idx + 1] + for k = idx, 1, -1 do + MTF[k + 1] = MTF[k] + end + MTF[1] = v + local ch = SEQ[v + 1] +do local __DARKLUA_VAR=ch + 1 CFTAB[__DARKLUA_VAR]=CFTAB[__DARKLUA_VAR]+ 1 +end writeu32(T, nblock * 4, ch) + nblock =nblock+ 1 + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block data", "truncated" + end + end + if origPtr >= nblock then + return nil, "bad BWT origin pointer", "corrupt" + end + + -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position + local sum = 0 + for i = 0, 255 do + local c = CFTAB[i + 1] + CFTAB[i + 1] = sum + sum =sum+ c + end + for i = 0, nblock - 1 do + local ch = band(readu32(T, i * 4), 255) + local k = CFTAB[ch + 1] + CFTAB[ch + 1] = k + 1 + writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) + end + + -- walk, undo RLE1, CRC + if op + nblock + 4096 > blen(out) then + out = grow(out, op, op + nblock + 4096) + end + local cap = blen(out) + local crc = 0xFFFFFFFF + local tPos = rshift(readu32(T, origPtr * 4), 8) + local last, run = -1, 0 + local i = 0 + while i < nblock do + local v = readu32(T, tPos * 4) + local ch = band(v, 255) + tPos = rshift(v, 8) + i =i+ 1 + if run == 4 then + -- ch is a repeat count for the previous byte + if ch > 0 then + if op + ch > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + if op + ch + 256 > cap then + out = grow(out, op, op + ch + nblock - i + 4096) + cap = blen(out) + end + bfill(out, op, last, ch) + op =op+ ch + for _ = 1, ch do + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) + end + end + run = 0 + last = -1 + else + if ch == last then + run =run+ 1 + else + run = 1 + last = ch + end + if op + 256 > cap then + if op >= maxBytes then + return nil, "output larger than maxBytes", "limit" + end + out = grow(out, op, op + nblock - i + 4096) + cap = blen(out) + end + writeu8(out, op, ch) + op =op+ 1 + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) + end + end + if op > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + crc = bxor(crc, 0xFFFFFFFF) + if crc ~= storedCrc then + return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" + end + combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) + end + streams =streams+ 1 + consumedEnd = p + if p >= e then + break + end + end + return out, op, consumedEnd +end + +return Decode +end +__FILES["codecs/compress/Deflate"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- 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("rosetta.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.inflate(buf, off, len, size, dict) -- with a preset dictionary +-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) +-- local out, err = Deflate.zlib(buf) -- checks the Adler-32 +-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members +-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw +-- +-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Adler32 = __include("core/Adler32") +local Inflate = __include("codecs/compress/Deflate/Inflate") +local Compress = __include("codecs/compress/Deflate/Compress") + +local Deflate = {} + +Deflate.version = "1.1.0" + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function shrink(out, n) +if buffer.len(out) == n then + return out + end + local b = buffer.create(n) + buffer.copy(b, 0, out, 0, n) + return b +end + +local function inflateErr(msg, at) +local code = (string.find(msg, "truncated", 1, true) and{Err.TRUNCATED }or{Err.CORRUPT +})[1] return Err.new(code, "inflate: " .. msg, at) +end + +-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. +-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream +-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. +-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may +-- reach into it; the result holds only the new bytes. +function Deflate.inflate(buf, offset, length, expectedSize, dict) +local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) + if not b then + return nil, aerr + end + local exact = expectedSize ~= nil + local cap + if exact then + if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize)) + end + cap = expectedSize + else + cap = math.max(1024, l * 4) + end + if dict ~= nil and type(dict) ~= "buffer" then + return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap , exact, false, dict) + if not out then + return nil, inflateErr(tostring(n), o) + end + if dict then + local d = buffer.len(dict) + n =n- d + local res = buffer.create(n) + buffer.copy(res, 0, out, d, n) + out = res + end + if exact and n ~= expectedSize then + return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize )) + end + return shrink(out, n), consumed +end + +-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err +function Deflate.zlib(buf, offset, length, expectedSize) +local b, o, l, aerr = args("Deflate.zlib", buf, offset, length) + if not b then + return nil, aerr + end + if l < 6 then + return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o) + end + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 ~= 8 or math.floor(cmf / 16 )> 7 then + return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o) + end + if (cmf * 256 + flg) % 31 ~= 0 then + return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o) + end + if bit32.band(flg, 0x20) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o) + end + local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize) + if not out then + return nil, consumed + end + if consumed + 4 > o + l then + return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed) + end + local want = bit32.byteswap(buffer.readu32(b, consumed)) + local got = Adler32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + return out, consumed + 4 +end + +-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err +local function gzipBody(b, p, e) +local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q =q+ (2 + buffer.readu16(b, q) +) end + for _, bit in __iter({ 8, 16 }) do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q =q+ 1 + end + q =q+ 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q =q+ 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + +-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is +-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. +function Deflate.gunzip(buf, offset, length) +local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local parts, total = {}, 0 + local p = o + repeat + if p + 18 > e then + if #parts > 0 then + break + end + return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p) + end + if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then + if #parts > 0 then + break -- trailing garbage after a member: ignored, as gzip -d does + end + return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p) + end + if buffer.readu8(b, p + 2) ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) + end + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr + end + local out, consumed = Deflate.inflate(b, q, e - q) + if not out then + return nil, consumed + end + if consumed + 8 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed) + end + local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4) + local got = Crc32.raw(out, 0, buffer.len(out)) + if got ~= want then + return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed) + end + if buffer.len(out) % 4294967296 ~= isize then + return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4) + end + table.insert(parts, out) + total =total+ buffer.len(out) + p = consumed + 8 + -- skip zero padding + local z = p + while z < e and buffer.readu8(b, z) == 0 do + z =z+ 1 + end + if z == e then + break + end + until p >= e + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in __iter(parts) do + buffer.copy(res, w, part) + w =w+ buffer.len(part) + end + return res, nil +end + +-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to +-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating +-- the rest or checking checksums: for sniffing compressed files cheaply. +function Deflate.peek(buf, offset, length, n) +local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and math.floor(cmf / 16 )<= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q , e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + + + + + +local function level(opts) +local lv = (opts and opts.level ~= nil and{opts.level }or{6 +})[1] if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then + return nil + end + return lv +end + +-- compress(buf, opts?) -> raw deflate buffer | nil, Err +function Deflate.compress(buf, opts) +local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9") + end + return Compress.raw(b, 0, buffer.len(b), lv), nil +end + +-- zlibCompress(buf, opts?) -> zlib stream | nil, Err +function Deflate.zlibCompress(buf, opts) +local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 6) + local flevel = lv < 2 and 0 or(lv < 6 and 1 or(lv == 6 and 2 or 3 +)) local cmf = 0x78 + local flg = flevel * 64 + flg =flg+ (31 - (cmf * 256 + flg) % 31 +) buffer.writeu8(out, 0, cmf) + buffer.writeu8(out, 1, flg) + buffer.copy(out, 2, raw, 0, n) + buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b)))) + return out, nil +end + +-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err +function Deflate.gzip(buf, opts) +local b = toBuffer(buf) + local lv = level(opts) + if not b or not lv then + return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9") + end + local raw = Compress.raw(b, 0, buffer.len(b), lv) + local n = buffer.len(raw) + local out = buffer.create(n + 18) + buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0") + buffer.writeu8(out, 8, lv >= 9 and 2 or(lv <= 1 and 4 or 0)) + buffer.writeu8(out, 9, 255) + buffer.copy(out, 10, raw, 0, n) + buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b))) + buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296) + return out, nil +end + +-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x +-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that +-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the +-- blocks' output concatenated. +function Deflate.mszip(buf, blocks) +local total = 0 + for _, b in __iter(blocks) do + if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then + return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range") + end + total =total+ b.size + end + local out = buffer.create(total) + local o = 0 + for _, b in __iter(blocks) do + if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then + return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset) + end + local dict= nil + if o > 0 then + local d = math.min(o, 32768) + dict = buffer.create(d) + buffer.copy(dict , 0, out, o - d, d) + end + local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict) + if not part then + return nil, err + end + buffer.copy(out, o, part, 0, b.size) + o =o+ b.size + end + return out, nil +end + +-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) +Deflate.crc32 = function(buf, offset, length, crc) +local b = toBuffer(buf) or buffer.create(0) + return Crc32.of(b, offset, length, crc) +end +Deflate.adler32 = function(buf, offset, length, adler) +local b = toBuffer(buf) or buffer.create(0) + return Adler32.of(b, offset, length, adler) +end + +return Deflate +end +__FILES["codecs/compress/Deflate/Compress"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- 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 = __include("codecs/entropy/Huffman") + +local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local WSIZE = 32768 +local HSIZE = 65536 +local MAXMATCH = 258 +local BLOCKSYMS = 16384 -- symbols per block + +-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no +-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are +-- greedy (no lazy matching). +local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 } +local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 } +local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 } +local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 } + +-- length 3..258 -> code 257..285 (index len), its extra bits and base +local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0) +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +for c = 1, 29 do + local base = LBASE[c] + local top = c == 29 and 258 or(c == 28 and 257 or LBASE[c + 1] - 1 +) for len = base, top do + LCODE[len] = 256 + c + LEXTRA[len] = LEXT[c] + LBASEOF[len] = base + end +end +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above +local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0) +for c = 1, 30 do + local base = DBASE[c] + local top = c == 30 and 32768 or DBASE[c + 1] - 1 + for d = base, math.min(top, 256) do + DSMALL[d] = c - 1 + end + if top > 256 then + for k = math.max(base, 257), top, 128 do + DLARGE[math.floor((k - 1) / 128 )+ 1] = c - 1 + end + end +end +local function dcode(d) +if d <= 256 then + return DSMALL[d] + end + return DLARGE[math.floor((d - 1) / 128 )+ 1] +end + +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- fixed codes +local FIXLEN = table.create(288, 0) +for i = 1, 288 do + FIXLEN[i] = i <= 144 and 8 or(i <= 256 and 9 or(i <= 280 and 7 or 8 +))end +local FIXDLEN = table.create(30, 5) + +-- reversed (LSB-first) canonical codes for lengths +local function revCodes(lens) +local codes = Huffman.codes(lens) + for i, l in __iter(lens) do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return codes +end +local FIXCODE = revCodes(FIXLEN) +local FIXDCODE = revCodes(FIXDLEN) + +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end +-- ------------------------------------------------------------------------------------------------ bit output + + + +local function ensure(o, n) + if o.op + n > blen(o.buf) then + local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n)) + bcopy(nb, 0, o.buf, 0, o.op) + o.buf = nb + end +end + +-- put(v, n): n <= 24 bits, LSB first +local function put(o, v, n) + local acc = o.acc + v * POW[o.cnt + 1] + local cnt = o.cnt + n + if cnt >= 8 then + ensure(o, 4) + local buf, op = o.buf, o.op + while cnt >= 8 do + local byte = acc % 256 + writeu8(buf, op, byte) + op =op+ 1 + acc = (acc - byte) / 256 + cnt =cnt- 8 + end + o.op = op + end + o.acc, o.cnt = acc, cnt +end + +local function alignOut(o) + if o.cnt > 0 then + put(o, 0, 8 - o.cnt) + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals) +local function storedBlock(o, src, s, e, final) + local p = s + repeat + local n = math.min(65535, e - p) + local last = final and p + n >= e + put(o, last and 1 or 0, 3) + alignOut(o) + ensure(o, 4 + n) + writeu16(o.buf, o.op, n) + writeu16(o.buf, o.op + 2, 65535 - n) + bcopy(o.buf, o.op + 4, src, p, n) + o.op =o.op+ (4 + n +) p =p+ n + until p >= e +end + +local function emitSymbols(o, L, D, nsym, lcode, llen, dcodes, dlen) + for i = 1, nsym do + local l = L[i] + if l < 256 then + put(o, lcode[l + 1], llen[l + 1]) + else + local len = l - 256 + local c = LCODE[len] + put(o, lcode[c + 1], llen[c + 1]) + local xb = LEXTRA[len] + if xb > 0 then + put(o, len - LBASEOF[len], xb) + end + local d = D[i] + local dc = dcode(d) + put(o, dcodes[dc + 1], dlen[dc + 1]) + xb = DEXT[dc + 1] + if xb > 0 then + put(o, d - DBASE[dc + 1], xb) + end + end + end + put(o, lcode[257], llen[257]) -- end of block +end + +local function block(o, src, s, e, L, D, nsym, final) + local lf = table.create(286, 0) + local df = table.create(30, 0) + local extra = 0 + for i = 1, nsym do + local l = L[i] + if l < 256 then +do local __DARKLUA_VAR=l + 1 lf[__DARKLUA_VAR]=lf[__DARKLUA_VAR]+ 1 +end else + local len = l - 256 +do local __DARKLUA_VAR=LCODE[len] + 1 lf[__DARKLUA_VAR]=lf[__DARKLUA_VAR]+ 1 +end extra =extra+ LEXTRA[len] + local dc = dcode(D[i]) +do local __DARKLUA_VAR0=dc + 1 df[__DARKLUA_VAR0]=df[__DARKLUA_VAR0]+ 1 +end extra =extra+ DEXT[dc + 1] + end + end + lf[257] = 1 + local llen = Huffman.lengths(lf, 15) + local dlen = Huffman.lengths(df, 15) + local hlit = 286 + while hlit > 257 and llen[hlit] == 0 do + hlit =hlit- 1 + end + local hdist = 30 + while hdist > 1 and dlen[hdist] == 0 do + hdist =hdist- 1 + end + if dlen[1] == 0 and hdist == 1 then + dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes) + end + -- code-length symbols: RLE of the hlit + hdist lengths + local all = table.create(hlit + hdist, 0) + for i = 1, hlit do + all[i] = llen[i] + end + for i = 1, hdist do + all[hlit + i] = dlen[i] + end + local cs, cx = {}, {} -- symbol, extra value + local cf = table.create(19, 0) + local i = 1 + local total = hlit + hdist + while i <= total do + local v = all[i] + local run = 1 + while i + run <= total and all[i + run] == v do + run =run+ 1 + end + if v == 0 and run >= 3 then + local r = math.min(run, 138) + if r >= 11 then + table.insert(cs, 18) + table.insert(cx, r - 11) + cf[19]=cf[19]+ 1 + else + table.insert(cs, 17) + table.insert(cx, r - 3) + cf[18]=cf[18]+ 1 + end + i =i+ r + elseif v ~= 0 and run >= 4 then + table.insert(cs, v) + table.insert(cx, 0) +do local __DARKLUA_VAR=v + 1 cf[__DARKLUA_VAR]=cf[__DARKLUA_VAR]+ 1 +end local r = math.min(run - 1, 6) + table.insert(cs, 16) + table.insert(cx, r - 3) + cf[17]=cf[17]+ 1 + i =i+ (1 + r +) else + table.insert(cs, v) + table.insert(cx, 0) +do local __DARKLUA_VAR=v + 1 cf[__DARKLUA_VAR]=cf[__DARKLUA_VAR]+ 1 +end i =i+ 1 + end + end + local clen = Huffman.lengths(cf, 7) + local hclen = 19 + while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do + hclen =hclen- 1 + end + -- costs in bits + local dyn = 17 + 3 * hclen + extra + for k = 1, 19 do + dyn =dyn+ cf[k] * clen[k] + end + dyn =dyn+ (cf[17] * 2 + cf[18] * 3 + cf[19] * 7 +) local fix = 3 + extra + for k = 1, 286 do + dyn =dyn+ lf[k] * llen[k] + fix =fix+ lf[k] * FIXLEN[k] + end + for k = 1, 30 do + dyn =dyn+ df[k] * dlen[k] + fix =fix+ df[k] * 5 + end + local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7 + if stored <= dyn and stored <= fix then + storedBlock(o, src, s, e, final) + return + end + if fix <= dyn then + put(o, final and 3 or 2, 3) + emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN) + return + end + put(o, final and 5 or 4, 3) + put(o, hlit - 257, 5) + put(o, hdist - 1, 5) + put(o, hclen - 4, 4) + for k = 1, hclen do + put(o, clen[CLORDER[k] + 1], 3) + end + local ccode = revCodes(clen) + for k = 1, #cs do + local c = cs[k] + put(o, ccode[c + 1], clen[c + 1]) + if c == 16 then + put(o, cx[k], 2) + elseif c == 17 then + put(o, cx[k], 3) + elseif c == 18 then + put(o, cx[k], 7) + end + end + emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen) +end + +-- ------------------------------------------------------------------------------------------------ LZ77 +local Compress = {} + +function Compress.raw(src, off, len, level) +local o= { buf = bcreate(math.max(64, math.floor(len / 2 )+ 64)), op = 0, acc = 0, cnt = 0 } + local e = off + len + if level == 0 or len == 0 then + if len == 0 then + put(o, 3, 3) -- one empty fixed block + put(o, 0, 7) + else + storedBlock(o, src, off, e, true) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out + end + local maxChain = CHAIN[level] + local nice = NICE[level] + local good = GOOD[level] + local lazyMax = LAZY[level] + local head = table.create(HSIZE, -1) + local prev = table.create(WSIZE, -1) + local L = table.create(BLOCKSYMS, 0) + local D = table.create(BLOCKSYMS, 0) + local nsym = 0 + local blockStart = off + + local function hash(p) +return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE + end + local function insert(p) + local h = hash(p) + 1 + prev[p % WSIZE + 1] = head[h] + head[h] = p + end + -- longest match at p among earlier positions: len (0 if < 3), dist + local function find(p, steps) +local maxLen = math.min(MAXMATCH, e - p) + if maxLen < 3 then + return 0, 0 + end + local best, bestDist = 2, 0 + local c = head[hash(p) + 1] + local limit = p - WSIZE + while c >= 0 and c > limit and steps > 0 do + if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then + local k = 1 + while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do + k =k+ 1 + end + if k > best then + best, bestDist = k, p - c + if k >= nice or k >= maxLen then + break + end + end + end + local nc = prev[c % WSIZE + 1] + if nc >= c then + break -- the slot was reused by a newer position: the chain ends here + end + c = nc + steps =steps- 1 + end + if best < 3 then + return 0, 0 + end + return best, bestDist + end + local function flush(upto, final) + block(o, src, blockStart, upto, L, D, nsym, final) + nsym = 0 + blockStart = upto + end + + local p = off + local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed + while p < e do + local mlen, mdist = 0, 0 + if p <= stop3 then + mlen, mdist = find(p, maxChain) + insert(p) + if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then + local l2, d2 = find(p + 1, (mlen >= good and{(math.floor(maxChain / 4 ))}or{maxChain})[1]) + if l2 > mlen then + -- a literal now, the longer match from p + 1 + nsym =nsym+ 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p =p+ 1 + insert(p) + mlen, mdist = l2, d2 + end + end + end + if mlen >= 3 then + nsym =nsym+ 1 + L[nsym] = 256 + mlen + D[nsym] = mdist + local q = p + 1 + local qe = math.min(p + mlen, stop3 + 1) + while q < qe do + insert(q) + q =q+ 1 + end + p =p+ mlen + else + nsym =nsym+ 1 + L[nsym] = readu8(src, p) + D[nsym] = 0 + p =p+ 1 + end + if nsym >= BLOCKSYMS - 2 then + flush(p, p >= e) + end + end + if nsym > 0 or blockStart < e then + flush(e, true) + elseif blockStart == e and o.op == 0 and o.cnt == 0 then + put(o, 3, 3) + put(o, 0, 7) + end + alignOut(o) + local out = bcreate(o.op) + bcopy(out, 0, o.buf, 0, o.op) + return out +end + +return Compress +end +__FILES["codecs/compress/Deflate/Inflate"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 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 = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local LITBITS, DISTBITS, CLBITS = 10, 8, 7 +local LITMASK, DISTMASK, CLMASK = 1023, 255, 127 + +-- length codes 257..285 and distance codes 0..29: base value, extra bits +local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 } +local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local DBASE = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, +} +local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 } +-- the order code-length code lengths are sent in +local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 } + +-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case +local LITCAP = Huffman.capacity(288, LITBITS, 15) +local DISTCAP = Huffman.capacity(32, DISTBITS, 15) +local CLCAP = Huffman.capacity(19, CLBITS, 7) + +-- fixed Huffman tables +local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) +local FLITS, FDISTS +do + local l = bcreate(288) + bfill(l, 0, 8, 144) + bfill(l, 144, 9, 112) + bfill(l, 256, 7, 24) + bfill(l, 280, 8, 8) + FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS) + local d = bcreate(30) + bfill(d, 0, 5, 30) + FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS) +end + +local Inflate = {} + +-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity. +local function grow(out, op, need) +local cap = math.max(blen(out) * 2, need, 1024) + local nb = bcreate(cap) + bcopy(nb, 0, out, 0, op) + return nb, cap +end + +-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in +-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and +-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). +-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, +-- distances may reach into it, and outLen includes it (cap does not). +-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. +function Inflate.raw(src, start, endpos, cap, exact, prefix, dict) +local op = 0 + if dict then + op = blen(dict) + cap =cap+ op + end + local out = bcreate(cap) + if dict then + bcopy(out, 0, dict, 0, op) + end + local pos = start + local bitbuf, bitcnt, over = 0, 0, 0 + local lt, dt = bcreate(LITCAP * 4), (bcreate(DISTCAP * 4) ) +local clt = bcreate(CLCAP * 4) + local lens = bcreate(320) + local final = 0 + repeat +local __DARKLUA_CONTINUE_1=false repeat -- block header (3 bits); also up to 14 bits of a dynamic header + if bitcnt < 17 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + final = band(bitbuf, 1) + local btype = band(rshift(bitbuf, 1), 3) + bitbuf = rshift(bitbuf, 3) + bitcnt =bitcnt- 3 + if btype == 0 then + -- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer + local k = band(bitcnt, 7) + bitcnt =bitcnt- k + local real = rshift(bitcnt, 3) - over + if real < 0 then + return nil, "truncated input" + end + pos =pos- real + bitbuf, bitcnt, over = 0, 0, 0 + if pos + 4 > endpos then + return nil, "truncated input" + end + local n = readu16(src, pos) + if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then + return nil, "stored block length mismatch" + end + pos =pos+ 4 + if pos + n > endpos then + return nil, "truncated input" + end + if op + n > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + n) + end + bcopy(out, op, src, pos, n) + op =op+ n + pos =pos+ n +__DARKLUA_CONTINUE_1=true break + end + local lsub, dsub +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) ) +end + local hlit = band(bitbuf, 31) + 257 + local hdist = band(rshift(bitbuf, 5), 31) + 1 + local hclen = band(rshift(bitbuf, 10), 15) + 4 + bitbuf = rshift(bitbuf, 14) + bitcnt =bitcnt- 14 + if hlit > 286 or hdist > 30 then + return nil, "too many length or distance symbols" + end + bfill(lens, 0, 0, 19) + for i = 1, hclen do + if bitcnt < 3 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + writeu8(lens, CLORDER[i], band(bitbuf, 7)) + bitbuf = rshift(bitbuf, 3) + bitcnt =bitcnt- 3 + end + if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then + return nil, "invalid code lengths set" + end + local total = hlit + hdist + local i = 0 + while i < total do + if bitcnt < 14 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + local e = readu32(clt, band(bitbuf, CLMASK) * 4) + local l = band(e, 31) + if l == 0 then + return nil, "invalid code lengths set" + end + bitbuf = rshift(bitbuf, l) + bitcnt =bitcnt- l + local sym = rshift(e, 5) + if sym < 16 then + writeu8(lens, i, sym) + i =i+ 1 + else + local rep, val + if sym == 16 then + if i == 0 then + return nil, "repeat with no first length" + end + val = readu8(lens, i - 1) + rep = 3 + band(bitbuf, 3) + bitbuf = rshift(bitbuf, 2) + bitcnt =bitcnt- 2 + elseif sym == 17 then + val = 0 + rep = 3 + band(bitbuf, 7) + bitbuf = rshift(bitbuf, 3) + bitcnt =bitcnt- 3 + else + val = 0 + rep = 11 + band(bitbuf, 127) + bitbuf = rshift(bitbuf, 7) + bitcnt =bitcnt- 7 + end + if i + rep > total then + return nil, "too many code lengths" + end + bfill(lens, i, val, rep) + i =i+ rep + end + end + if readu8(lens, 256) == 0 then + return nil, "missing end-of-block code" + end + lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS) + dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS) + if lsub < 0 or dsub < 0 then + return nil, "invalid literal/length or distance code set" + end + else + return nil, "invalid block type" + end + local lsmask = lshift(1, lsub) - 1 + local dsmask = lshift(1, dsub) - 1 + -- the symbol loop + while true do + if bitcnt < 15 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + local e = readu32(lt, band(bitbuf, LITMASK) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid literal/length code" + end + e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid literal/length code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt =bitcnt- l + local sym = rshift(e, 5) + if sym < 256 then + if op >= cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + 1) + end + writeu8(out, op, sym) + op =op+ 1 + elseif sym == 256 then + break + else + sym =sym- 256 + if sym > 29 then + return nil, "invalid literal/length code" + end + -- up to 5 length extra bits + a 15-bit distance code + if bitcnt < 20 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + local len = LBASE[sym] + local xb = LEXT[sym] + if xb > 0 then + len =len+ band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt =bitcnt- xb + end + e = readu32(dt, band(bitbuf, DISTMASK) * 4) + l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "invalid distance code" + end + e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "invalid distance code" + end + end + bitbuf = rshift(bitbuf, l) + bitcnt =bitcnt- l + local dsym = rshift(e, 5) + 1 + if dsym > 30 then + return nil, "invalid distance code" + end + local dist = DBASE[dsym] + xb = DEXT[dsym] + if xb > 0 then + if bitcnt < 13 then + if pos + 4 <= endpos then + bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt)) + local nb = rshift(32 - bitcnt, 3) + pos =pos+ nb + bitcnt =bitcnt+ nb * 8 + else + while bitcnt <= 24 do + if pos < endpos then + bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt)) + pos =pos+ 1 + else + over =over+ 1 + if over > 4 then + return nil, "truncated input" + end + end + bitcnt =bitcnt+ 8 + end + end + end + dist =dist+ band(bitbuf, lshift(1, xb) - 1) + bitbuf = rshift(bitbuf, xb) + bitcnt =bitcnt- xb + end + if dist > op then + return nil, "invalid distance too far back" + end + if op + len > cap then + if exact then + if prefix then + return out, op, pos + end + return nil, "output larger than expected" + end + out, cap = grow(out, op, op + len) + end + local s = op - dist + if dist >= len then + if len <= 16 and op + 16 <= cap then + -- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which + -- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones + writeu32(out, op, readu32(out, s)) + writeu32(out, op + 4, readu32(out, s + 4)) + writeu32(out, op + 8, readu32(out, s + 8)) + writeu32(out, op + 12, readu32(out, s + 12)) + elseif len <= 16 then + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, s + k)) + end + else + bcopy(out, op, out, s, len) + end + op =op+ len + elseif dist == 1 then + bfill(out, op, readu8(out, s), len) + op =op+ len + else + -- overlapping: the pattern of period dist, copied in growing non-overlapping chunks + local rem = len + while rem > 0 do + local k = math.min(op - s, rem) + bcopy(out, op, out, s, k) + op =op+ k + rem =rem- k + end + end + end + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end until final == 1 + local consumed = pos + over - rshift(bitcnt, 3) + if consumed > endpos then + return nil, "truncated input" + end + return out, op, consumed +end + +return Inflate +end +__FILES["codecs/compress/Explode"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ +-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented +-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length +-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the +-- decoder itself is new code. +-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops +-- early at maxOut bytes (MPQ sectors whose stream has no end code). +-- +-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err +-- +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Explode = {} + +local MAXBITS = 13 + +-- blast.c's tables: each byte is (count - 1) << 4 | code length +local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, + 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, + 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, + 61, 12, 45, 44, 173 } +local LENLEN = { 2, 35, 36, 53, 38, 23 } +local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } +local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } +local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } + +-- canonical code from run-length coded lengths + + +local function construct(rep) +local lengths= {} + for _, b in __iter(rep) do + local len = b % 16 + for _ = 0, math.floor(b / 16 )do + table.insert(lengths, len) + end + end + local count = table.create(MAXBITS + 1, 0) + for _, l in __iter(lengths) do +do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 +end end + local offs = table.create(MAXBITS + 2, 0) + for l = 1, MAXBITS do + offs[l + 2] = offs[l + 1] + count[l + 1] + end + local symbol = table.create(#lengths, 0) + for s, l in __iter(lengths) do + if l ~= 0 then +do local __DARKLUA_VAR=l + 1 offs[__DARKLUA_VAR]=offs[__DARKLUA_VAR]+ 1 +end symbol[offs[l + 1] ] = s - 1 + end + end + return { count = count, symbol = symbol } +end + +local LIT = construct(LITLEN) +local LEN = construct(LENLEN) +local DIST = construct(DISTLEN) + +-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err +function Explode.decompress(buf, offset, length, maxOut) +local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local src= b + local p, stop = o, o + l + if l < 2 then + return nil, Err.new(Err.TRUNCATED, "implode header", 0) + end + local lit, dict = readu8(src, p), readu8(src, p + 1) + p =p+ 2 + if lit > 1 then + return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) + end + if dict < 4 or dict > 6 then + return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) + end + local limit = maxOut or 2 ^ 30 + local cap = math.max(64, math.min(limit, l * 8)) + local out = buffer.create(cap) + local n = 0 + local bitbuf, bitcnt = 0, 0 + local truncated = false + + local function bits(need) +while bitcnt < need do + if p >= stop then + truncated = true + return 0 + end + bitbuf =bitbuf+ readu8(src, p) * 2 ^ bitcnt + p =p+ 1 + bitcnt =bitcnt+ 8 + end + local v = bitbuf % 2 ^ need + bitbuf = (bitbuf - v) / 2 ^ need + bitcnt =bitcnt- need + return v + end + + local function decode(h) +local code, first, index = 0, 0, 0 + local count, symbol = h.count, h.symbol + for len = 1, MAXBITS do + local bit = bits(1) + if truncated then + return -1 + end + code =code+ (1 - bit +) local c = count[len + 1] + if code < first + c then + return symbol[index + code - first + 1] + end + index =index+ c + first = (first + c) * 2 + code =code* 2 + end + return -2 + end + + while n < limit do + local flag = bits(1) + if truncated then + break + end + if flag == 1 then + local sym = decode(LEN) + if sym < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad length code", p - o) + end + local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) + if truncated then + break + end + if len == 519 then + break + end + local shift = len == 2 and 2 or dict + local d = decode(DIST) + if d < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) + end + local dist = d * 2 ^ shift + bits(shift) + 1 + if truncated then + break + end + if dist > n then + return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) + end + if n + len > limit then + len = limit - n + end + if n + len > cap then + cap = math.max(cap * 2, n + len) + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + local from = n - dist + for k = 0, len - 1 do + writeu8(out, n + k, readu8(out, from + k)) + end + n =n+ len + else + local sym = (lit == 1 and{(decode(LIT) )}or{(bits(8) +)})[1] if truncated then + break + end + if sym < 0 then + return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) + end + if n >= cap then + cap =cap* 2 + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + writeu8(out, n, sym) + n =n+ 1 + end + end + if truncated and n < limit and not maxOut then + return nil, Err.new(Err.TRUNCATED, "no end code", l) + end + local res = buffer.create(n) + buffer.copy(res, 0, out, 0, n) + return res, nil +end + +return Explode +end +__FILES["codecs/compress/Lz4"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +--!native +--!optimize 2 +-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder +-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies, +-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws. +-- +-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err +-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err +-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks) +-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room +-- Lz4.bound(n) -- worst-case block size for n bytes +-- +-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default +-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or +-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Lz4 = {} + + + + + +local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len +local band, rshift = bit32.band, bit32.rshift + +local MINMATCH = 4 +local LASTLITERALS = 5 -- the last 5 bytes are always literals +local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end +local MAX_OFFSET = 65535 +local HASH_BITS = 13 +local HASH_SIZE = 2 ^ HASH_BITS + +-- ------------------------------------------------------------------------------------------------ decode +function Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart) +local lo = histStart or d + if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then + return nil, "corrupt: bad ranges" + end + if p >= limit then + return nil, "truncated: empty block" + end + while true do + if p >= limit then + return nil, "truncated" + end + local token = readu8(src, p) + p =p+ 1 + local lit = rshift(token, 4) + if lit == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p =p+ 1 + lit =lit+ b + end + end + if lit > 0 then + if p + lit > limit then + return nil, "truncated: literals past the end" + end + if d + lit > dstLimit then + return nil, "limit: output larger than expected" + end + bcopy(dst, d, src, p, lit) + p =p+ lit + d =d+ lit + end + if p >= limit then + return d, nil -- the last sequence has no match + end + if p + 2 > limit then + return nil, "truncated" + end + local off = readu16(src, p) + p =p+ 2 + if off == 0 or d - off < lo then + return nil, "corrupt: bad match offset" + end + local ml = band(token, 15) + if ml == 15 then + local b = 255 + while b == 255 do + if p >= limit then + return nil, "truncated" + end + b = readu8(src, p) + p =p+ 1 + ml =ml+ b + end + end + ml =ml+ MINMATCH + if d + ml > dstLimit then + return nil, "limit: output larger than expected" + end + local s = d - off + if off >= ml then + bcopy(dst, d, dst, s, ml) + d =d+ ml + elseif off == 1 then + buffer.fill(dst, d, readu8(dst, s), ml) + d =d+ ml + else + -- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time + local n = ml + while n > 0 do + local c = d - s + if c > n then + c = n + end + bcopy(dst, d, dst, s, c) + d =d+ c + n =n- c + end + end + end +end + +-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be +-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes. +function Lz4.decompress(src, offset, length, outSize, opts) +local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + if outSize ~= nil then + if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize") + end + local out = bcreate(outSize) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize) + if not e then + return nil, Err.from(msg, o) + end + if e ~= outSize then + return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o) + end + return out, nil + end + local max = (opts and opts.maxBytes) or 2 ^ 28 + local size = math.min(math.max(l * 4, 256), max) + while true do + local out = bcreate(size) + local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size) + if e then + local res = bcreate(e) + bcopy(res, 0, out, 0, e) + return res, nil + end + if not (msg and string.sub(msg, 1, 6) == "limit:") then + return nil, Err.from(msg, o) + end + if size >= max then + return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o) + end + size = math.min(size * 4, max) + end +end + +-- ------------------------------------------------------------------------------------------------ encode +-- bound(n) -> the largest block n input bytes can produce +function Lz4.bound(n) +return n + math.floor(n / 255 )+ 16 +end + +-- writes a length's 255-run extension at o; returns the next offset +local function extend(dst, o, n) +while n >= 255 do + writeu8(dst, o, 255) + o =o+ 1 + n =n- 255 + end + writeu8(dst, o, n) + return o + 1 +end + +-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles +local function hash(v) +local vl, vh = band(v, 0xFFFF), rshift(v, 16) + local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536 + return math.floor(((vl * 0x79B1 + mid * 65536) % 4294967296) / (2 ^ (32 - HASH_BITS)) )+ 1 +end + +local hashTable= table.create(HASH_SIZE, -1e9) + +-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n)) +function Lz4.encodeInto(src, p, n, dst, d) +local op = d + local anchor = p + local iend = p + n + local ht = hashTable + for i = 1, HASH_SIZE do + ht[i] = -1e9 + end + if n >= MFLIMIT + 1 then + local mflimit = iend - MFLIMIT -- a match starts before this + local matchEnd = iend - LASTLITERALS -- and ends at or before this + local ip = p + local skip = 64 + while ip < mflimit do + local v = readu32(src, ip) + local h = hash(v) + local ref = ht[h] + ht[h] = ip + if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then + -- back over equal bytes before the match (into the pending literals) + while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do + ip =ip- 1 + ref =ref- 1 + end + local a = ip + MINMATCH + local bpos = ref + MINMATCH + while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do + a =a+ 4 + bpos =bpos+ 4 + end + while a < matchEnd and readu8(src, a) == readu8(src, bpos) do + a =a+ 1 + bpos =bpos+ 1 + end + local ml = a - ip + local lit = ip - anchor + local tok = op + op =op+ 1 + local tl = lit >= 15 and 15 or lit + if lit >= 15 then + op = extend(dst, op, lit - 15) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op =op+ lit + end + writeu16(dst, op, ip - ref) + op =op+ 2 + local m = ml - MINMATCH + local tm = m >= 15 and 15 or m + if m >= 15 then + op = extend(dst, op, m - 15) + end + writeu8(dst, tok, tl * 16 + tm) + ip = a + anchor = ip + skip = 64 + -- index the position just before the next one (better ratio at no cost) + if ip - 2 >= p and ip - 2 < mflimit then + local w = readu32(src, ip - 2) + ht[hash(w)] = ip - 2 + end + else + ip =ip+ rshift(skip, 6) -- step up over incompressible data (the reference's acceleration) + skip =skip+ 1 + end + end + end + -- the last literals + local lit = iend - anchor + local tok = op + op =op+ 1 + if lit >= 15 then + op = extend(dst, op, lit - 15) + writeu8(dst, tok, 0xF0) + else + writeu8(dst, tok, lit * 16) + end + if lit > 0 then + bcopy(dst, op, src, anchor, lit) + op =op+ lit + end + return op - d +end + +-- compress(src, offset?, length?) -> buffer (one block) | nil, Err +function Lz4.compress(src, offset, length) +local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length) + if not b then + return nil, aerr + end + local tmp = bcreate(Lz4.bound(l)) + local n = Lz4.encodeInto(b, o, l, tmp, 0) + local out = bcreate(n) + bcopy(out, 0, tmp, 0, n) + return out, nil +end + +return Lz4 +end +__FILES["codecs/compress/Lzh"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: +-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset +-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5") +-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length +-- offset prefixes, 4 KB window +-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes) +-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman) +-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill +-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill. +-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c, +-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead +-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description). +-- +-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message +-- +-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes +-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7. +local Huffman = __include("codecs/entropy/Huffman") + +local Lzh = {} + +local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local floor = math.floor +-- ------------------------------------------------------------------------------------------------ bit reader +-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and +-- over counts them + + + +local function reader(src, off, len) +return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 } +end + +local function fill(r) + while r.cnt <= 24 do + local b = 0 + if r.pos < r.limit then + b = readu8(r.src, r.pos) + r.pos =r.pos+ 1 + else + r.over =r.over+ 8 + end + r.acc = r.acc * 256 + b + r.cnt =r.cnt+ 8 + end +end + +local function peek(r, n) +if r.cnt < n then + fill(r) + end + return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n +end + +local function skip(r, n) + if r.cnt < n then + fill(r) + end + r.cnt =r.cnt- n + r.acc = r.acc % 2 ^ r.cnt +end + +local function bits(r, n) +if n == 0 then + return 0 + end + local v = peek(r, n) + skip(r, n) + return v +end +-- ------------------------------------------------------------------------------------------------ static Huffman + + + +local function newTable(nsym, P) +return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 } +end + +local function build(t, lens, n) +t.single = -1 + local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P) + if S < 0 then + return false + end + t.S = S + return true +end + +local function decodeSym(r, t) +if t.single >= 0 then + return t.single + end + local P, S = t.P, t.S + local e = readu32(t.tab, peek(r, P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = peek(r, P + S) + e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + skip(r, l) + return rshift(e, 5) +end + +local lens = buffer.create(512) + +local function lengthValue(r) +local len = bits(r, 3) + if len == 7 then + while bits(r, 1) == 1 do + len =len+ 1 + if len > 16 then + return 17 + end + end + end + return len +end + +-- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table +local function readLengths(r, t, nbits, maxN, special) +local n = bits(r, nbits) + if n == 0 then + t.single = bits(r, nbits) + return true + end + n = math.min(n, maxN) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local l = lengthValue(r) + if l > 16 then + return false + end + writeu8(lens, i, l) + if i == special then + local z = bits(r, 2) + i =i+ z -- zeros (already zero) + end + i =i+ 1 + end + return build(t, lens, math.min(i, maxN)) +end + +local function readCodes(r, temp, codes) +local n = bits(r, 9) + if n == 0 then + codes.single = bits(r, 9) + return true + end + n = math.min(n, 510) + buffer.fill(lens, 0, 0, 512) + local i = 0 + while i < n do + local c = decodeSym(r, temp) + if c < 0 then + return false + end + if c <= 2 then + local count = c == 0 and 1 or(c == 1 and{(bits(r, 4) + 3 )}or{(bits(r, 9) + 20 +)})[1] i =i+ count + else + if c - 2 > 16 then + return false + end + writeu8(lens, i, c - 2) + i =i+ 1 + end + end + return build(codes, lens, n) +end + +local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 } + +local function decodeNew(src, off, len, out, n, method) +local r = reader(src, off, len) + local obits = OFFSET_BITS[method] + local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8) + local o = 0 + local remaining = 0 + while o < n do + if remaining == 0 then + remaining = bits(r, 16) + if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then + return r.over > 0 and"truncated" or"bad Huffman table" + end + if r.over > 32 then + return "truncated" + end + if remaining == 0 then + return "empty block" + end + end + remaining =remaining- 1 + local c = decodeSym(r, codes) + if c < 0 then + return "bad code" + end + if c < 256 then + writeu8(out, o, c) + o =o+ 1 + else + local count = c - 256 + 3 + local p = decodeSym(r, offs) + if p < 0 then + return "bad offset code" + end + if p > 1 then + p = lshift(1, p - 1) + bits(r, p - 1) + end + local from = o - p - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, (from >= 0 and{(readu8(out, from) )}or{0x20})[1]) + o =o+ 1 + from =from+ 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ lh1 +local NUM_CODES = 314 +local NUM_NODES = NUM_CODES * 2 - 1 +local REORDER = 32 * 1024 +local FDIST = { 1, 3, 8, 12, 24, 16 } + +local offsetLookup = table.create(256, 0) +local offsetLength = table.create(64, 0) +do + local code, offset = 0, 0 + for i, count in __iter(FDIST) do + local l = i - 1 + 3 + local iter = lshift(1, 8 - l) + for _ = 1, count do + for k = 0, iter - 1 do + offsetLookup[code + k + 1] = offset + end + offsetLength[offset + 1] = l + code =code+ iter + offset =offset+ 1 + end + end +end + +local function decodeLh1(src, off, len, out, n) +local r = reader(src, off, len) + -- node arrays (0-based indexes stored at [i + 1]) + local leaf = table.create(NUM_NODES, false) + local child = table.create(NUM_NODES, 0) + local parent = table.create(NUM_NODES, 0) + local freq = table.create(NUM_NODES, 0) + local group = table.create(NUM_NODES, 0) + local leafNodes = table.create(NUM_CODES, 0) + local groups = table.create(NUM_NODES, 0) + local leader = table.create(NUM_NODES, 0) + local numGroups = 0 + local function initGroups() + for i = 0, NUM_NODES - 1 do + groups[i + 1] = i + end + numGroups = 0 + end + local function allocGroup() +local g = groups[numGroups + 1] + numGroups =numGroups+ 1 + return g + end + local function freeGroup(g) + numGroups =numGroups- 1 + groups[numGroups + 1] = g + end + initGroups() + do + local ni = NUM_NODES - 1 + local lg = allocGroup() + for i = 0, NUM_CODES - 1 do + leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg + leader[lg + 1] = ni + leafNodes[i + 1] = ni + ni =ni- 1 + end + local c = NUM_NODES - 1 + while ni >= 0 do + leaf[ni + 1], child[ni + 1] = false, c + parent[c + 1], parent[c] = ni, ni + freq[ni + 1] = freq[c + 1] + freq[c] + if freq[ni + 1] == freq[ni + 2] then + group[ni + 1] = group[ni + 2] + else + group[ni + 1] = allocGroup() + end + leader[group[ni + 1] + 1] = ni + ni =ni- 1 + c =c- 2 + end + end + local function makeLeader(ni) +local g = group[ni + 1] + local li = leader[g + 1] + if li == ni then + return ni + end + leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1] + child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1] + for _, x in __iter({ ni, li }) do + if leaf[x + 1] then + leafNodes[child[x + 1] + 1] = x + else + parent[child[x + 1] + 1] = x + parent[child[x + 1] ] = x + end + end + return li + end + local function incrementNode(ni) +do local __DARKLUA_VAR=ni + 1 freq[__DARKLUA_VAR]=freq[__DARKLUA_VAR]+ 1 +end if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then +do local __DARKLUA_VAR0=group[ni + 1] + 1 leader[__DARKLUA_VAR0]=leader[__DARKLUA_VAR0]+ 1 +end if freq[ni + 1] == freq[ni] then + group[ni + 1] = group[ni] + else + group[ni + 1] = allocGroup() + leader[group[ni + 1] + 1] = ni + end + elseif freq[ni + 1] == freq[ni] then + freeGroup(group[ni + 1]) + group[ni + 1] = group[ni] + end + end + local function reconstruct() + -- leaves to the front, halved + local li = 0 + for i = 0, NUM_NODES - 1 do + if leaf[i + 1] then + leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], math.floor((freq[i + 1] + 1) / 2 +) li =li+ 1 + end + end + local lp = NUM_CODES - 1 + local c = NUM_NODES - 1 + local i = NUM_NODES - 1 + while i >= 0 do + while c - i < 2 do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i =i- 1 + lp =lp- 1 + end + local f = freq[c + 1] + freq[c] + while lp >= 0 and f >= freq[lp + 1] do + leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1] + leafNodes[child[i + 1] + 1] = i + i =i- 1 + lp =lp- 1 + end + leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c + parent[c + 1], parent[c] = i, i + i =i- 1 + c =c- 2 + end + initGroups() + local g = allocGroup() + group[1] = g + leader[g + 1] = 0 + for k = 1, NUM_NODES - 1 do + if freq[k + 1] == freq[k] then + group[k + 1] = group[k] + else + g = allocGroup() + group[k + 1] = g + leader[g + 1] = k + end + end + end + local o = 0 + while o < n do + local ni = 0 + local guard = 0 + while not leaf[ni + 1] do + ni = child[ni + 1] - bits(r, 1) + guard =guard+ 1 + if guard > NUM_NODES or ni < 0 then + return "bad tree" + end + end + local code = child[ni + 1] + -- increment_for_code + if freq[1] >= REORDER then + reconstruct() + end + freq[1]=freq[1]+ 1 + local x = leafNodes[code + 1] + while x ~= 0 do + x = makeLeader(x) + incrementNode(x) + x = parent[x + 1] + end + if code < 256 then + writeu8(out, o, code) + o =o+ 1 + else + local future = peek(r, 8) + local hi = offsetLookup[future + 1] + skip(r, offsetLength[hi + 1]) + local offset = hi * 64 + bits(r, 6) + local count = code - 256 + 3 + local from = o - offset - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, (from >= 0 and{(readu8(out, from) )}or{0x20})[1]) + o =o+ 1 + from =from+ 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5 +-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances) +local function decodeLzs(src, off, len, out, n) +local r = reader(src, off, len) + local ring = buffer.create(2048) + buffer.fill(ring, 0, 0x20) + local rp = 2048 - 17 + local o = 0 + while o < n do + if bits(r, 1) == 1 then + local b = bits(r, 8) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o =o+ 1 + else + local pos = bits(r, 11) + local l = bits(r, 4) + 2 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (pos + k) % 2048) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 2048 + o =o+ 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +local LZ5_INIT = buffer.create(4096) +do + local p = 0 + for i = 0, 255 do + for _ = 1, 13 do + writeu8(LZ5_INIT, p, i) + p =p+ 1 + end + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, i) + p =p+ 1 + end + for i = 0, 255 do + writeu8(LZ5_INIT, p, 255 - i) + p =p+ 1 + end + p =p+ 128 + for _ = 1, 110 do + writeu8(LZ5_INIT, p, 0x20) + p =p+ 1 + end +end + +local function decodeLz5(src, off, len, out, n) +local ring = buffer.create(4096) + buffer.copy(ring, 0, LZ5_INIT) + local rp = 4096 - 18 + local p = off + local limit = math.min(off + len, buffer.len(src)) + local o = 0 + while o < n do + if p >= limit then + return "truncated" + end + local flags = readu8(src, p) + p =p+ 1 + for bit = 0, 7 do + if o >= n then + break + end + if band(flags, lshift(1, bit)) ~= 0 then + if p >= limit then + return "truncated" + end + local b = readu8(src, p) + p =p+ 1 + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o =o+ 1 + else + if p + 2 > limit then + return "truncated" + end + local c0, c1 = readu8(src, p), readu8(src, p + 1) + p =p+ 2 + local start = lshift(band(c1, 0xF0), 4) + c0 + local l = band(c1, 15) + 3 + for k = 0, l - 1 do + if o >= n then + break + end + local b = readu8(ring, (start + k) % 4096) + writeu8(out, o, b) + writeu8(ring, rp, b) + rp = (rp + 1) % 4096 + o =o+ 1 + end + end + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ ARJ method 4 +local function decodeArj4(src, off, len, out, n) +local r = reader(src, off, len) + local function prefixed(start, stop) +local plus, pwr = 0, lshift(1, start) + local width = start + while width < stop do + if bits(r, 1) == 0 then + break + end + plus =plus+ pwr + pwr =pwr* 2 + width =width+ 1 + end + return ((width ~= 0 and{(bits(r, width) )}or{0})[1]) + plus + end + local o = 0 + while o < n do + local c = prefixed(0, 7) + if c == 0 then + writeu8(out, o, bits(r, 8)) + o =o+ 1 + else + local count = c - 1 + 3 + local pos = prefixed(9, 13) + local from = o - pos - 1 + for _ = 1, count do + if o >= n then + break + end + writeu8(out, o, (from >= 0 and{(readu8(out, from) )}or{0})[1]) + o =o+ 1 + from =from+ 1 + end + end + if r.over > 32 then + return "truncated" + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ api +Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" } + +-- decode(src, off, len, outSize, method) -> buffer | nil, message +function Lzh.decode(src, off, len, outSize, method) +if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then + return nil, "bad arguments" + end + local out = buffer.create(outSize) + if outSize == 0 then + return out, nil + end + local err +if OFFSET_BITS[method] then + err = decodeNew(src, off, len, out, outSize, method) + elseif method == "lh1" then + err = decodeLh1(src, off, len, out, outSize) + elseif method == "lzs" then + err = decodeLzs(src, off, len, out, outSize) + elseif method == "lz5" then + err = decodeLz5(src, off, len, out, outSize) + elseif method == "arj4" then + err = decodeArj4(src, off, len, out, outSize) + else + return nil, "unsupported: method " .. tostring(method) + end + if err then + return nil, err + end + return out, nil +end + +return Lzh +end +__FILES["codecs/compress/Lzma"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- 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("rosetta.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 +-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) +-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) +-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) +-- +-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default +-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types +-- 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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Decode = __include("codecs/compress/Lzma/Decode") +local Filters = __include("codecs/compress/Lzma/Filters") +local Crc64 = __include("codecs/compress/Lzma/Crc64") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Lzma = {} + +local DEFAULT_MAX = 2 ^ 30 + + + + + + +local toBuffer = Bytes.toBuffer +local args = Bytes.span + +local function maxOf(opts) +local m = opts and opts.maxBytes + return (type(m) == "number" and m >= 0 and{m }or{DEFAULT_MAX +})[1]end + +-- a decoder message -> Err +local function fail(msg, at) +local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 5) == "limit" then + code = Err.LIMIT + elseif string.find(s, "truncated", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, at) +end + +-- props byte -> lc, lp, pb | nil +local function propsByte(d) +if d >= 225 then + return nil, 0, 0 + end + return d % 9, (math.floor(d / 9)) % 5, math.floor(d / 45 +)end +Lzma.propsByte = propsByte + +-- ------------------------------------------------------------------------------------------------ LZMA +-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) +local function decodeLzma(st, b, o, e, unpackSize) +local ip, ierr = Decode.rcInit(st, b, o, e) + if not ip then + return nil, fail(ierr, o) + end + local target = (unpackSize and((st.op + unpackSize ))or(math.huge +)) if unpackSize and target > st.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) + end + if unpackSize and not Decode.ensure(st, target) then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + local status, res = Decode.run(st, b, ip, e, target) + if not status then + return nil, fail(res, o) + end + if unpackSize and st.op ~= target then + return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) + end + return res , nil +end + +-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma(buf, offset, length, props, unpackSize, opts) +local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) + if not b then + return nil, aerr + end + local lc, lp, pb + if type(props) == "table" then + lc, lp, pb = props.lc, props.lp, props.pb + else + local pbuf = toBuffer(props) + if not pbuf or buffer.len(pbuf) < 1 then + return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") + end + lc, lp, pb = propsByte(readu8(pbuf, 0)) + if not lc then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") + end + end + if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") + end + if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") + end + local max = maxOf(opts) + local st = Decode.new((unpackSize and{unpackSize }or{(l * 4)})[1], max) + local ok, perr = Decode.setProps(st, lc, lp, pb) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(perr)) + end + local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) + if not consumed then + return nil, err + end + return Decode.finish(st), consumed +end + +-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +function Lzma.alone(buf, offset, length, opts) +local b, o, l, aerr = args("Lzma.alone", buf, offset, length) + if not b then + return nil, aerr + end + if l < 13 then + return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) + end + local lo, hi = readu32(b, o + 5), readu32(b, o + 9) + local size= nil + if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then + if hi >= 2 ^ 21 then + return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) + end + size = hi * 4294967296 + lo + end + return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) +end + +-- ------------------------------------------------------------------------------------------------ LZMA2 +-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte +local function decodeLzma2(st, b, o, e) +local p = o + local needDict, needProps = true, true + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) + end + local c = readu8(b, p) + if c == 0 then + return p + 1, nil + end + if c == 1 or c == 2 then + if p + 3 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + if c == 1 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if p + 3 + n > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) + end + local ok, cerr = Decode.copy(st, n, b, p + 3) + if not ok then + return nil, fail(cerr, p) + end + st.remLen = 0 + p =p+ (3 + n +) elseif c >= 0x80 then + if p + 5 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 + local mode = (math.floor(c / 32)) % 4 + local q = p + 5 + if mode == 3 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if mode >= 2 then + if q >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) + end + local lc, lp, pb = propsByte(readu8(b, q)) + if not lc or lc + lp > 4 then + return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) + end + Decode.setProps(st, lc, lp, pb) + needProps = false + q =q+ 1 + elseif needProps then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) + elseif mode == 1 then + Decode.resetState(st) + end + if q + psize > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) + end + local target = st.op + usize + if target > st.maxBytes then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + Decode.ensure(st, target) + local ip, ierr = Decode.rcInit(st, b, q, q + psize) + if not ip then + return nil, fail(ierr, q) + end + local status, res = Decode.run(st, b, ip, q + psize, target) + if not status then + return nil, fail(res, q) + end + if status ~= "full" or st.op ~= target then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) + end + p = q + psize + else + return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) + end + end +end + +-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma2(buf, offset, length, _dictSize, unpackSize, opts) +local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) + if not b then + return nil, aerr + end + local max = maxOf(opts) + local st = Decode.new((type(unpackSize) == "number" and unpackSize >= 0 and{unpackSize }or{(l * 4)})[1], max) + local consumed, err = decodeLzma2(st, b, o, o + l) + if not consumed then + return nil, err + end + if type(unpackSize) == "number" and st.op ~= unpackSize then + return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) + end + return Decode.finish(st), consumed +end + +-- ------------------------------------------------------------------------------------------------ filters +-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) +Lzma.FILTER = table.freeze({ + delta = 0x03, + x86 = 0x04, + powerpc = 0x05, + ia64 = 0x06, + arm = 0x07, + armthumb = 0x08, + sparc = 0x09, + arm64 = 0x0A, + riscv = 0x0B, + lzma2 = 0x21, +}) +local BCJ= { + [0x04] = Filters.x86, + [0x05] = Filters.powerpc, + [0x07] = Filters.arm, + [0x08] = Filters.armthumb, + [0x09] = Filters.sparc, + [0x0A] = Filters.arm64, +} + +-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the +-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +function Lzma.filter(id, b, o, n, props) +local pb = toBuffer(props) + local plen = (pb and{(buffer.len(pb) )}or{0 +})[1] if id == 0x03 then + if plen ~= 1 then + return nil, Err.new(Err.CORRUPT, "bad delta filter properties") + end + Filters.delta(b, o, n, readu8(pb , 0) + 1) + return true, nil + end + local f = BCJ[id] + if not f then + return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) + end + local start = 0 + if plen == 4 then + start = readu32(pb , 0) + elseif plen ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") + end + f(b, o, n, start) + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ xz +local XZ_MAGIC = "\253" .. "7zXZ\0" +local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } + +-- vli(b, p, e) -> value, next | nil +local function vli(b, p, e) +local v, mul = 0, 1 + for i = 0, 8 do + if p + i >= e then + return nil, p + end + local c = readu8(b, p + i) + v =v+ (c % 128) * mul + if c < 128 then + if c == 0 and i > 0 then + return nil, p -- non-minimal encoding + end + return v, p + i + 1 + end + mul =mul* 128 + end + return nil, p +end +Lzma.vli = vli + +local function crc(b, o, n) +return Crc32.raw(b, o, n) +end + +-- one xz stream at o -> next offset | nil, Err (blocks appended to st) +local function xzStream(st, b, o, e) +if o + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) + end + if buffer.readstring(b, o, 6) ~= XZ_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad xz magic", o) + end + if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then + return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) + end + if crc(b, o + 6, 2) ~= readu32(b, o + 8) then + return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) + end + local check = readu8(b, o + 7) + local csize = CHECK_SIZE[check] + local p = o + 12 + local records= {} + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) + end + local hs = readu8(b, p) + if hs == 0 then + break -- the index + end + local hsize = (hs + 1) * 4 + if p + hsize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) + end + if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then + return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) + end + local flags = readu8(b, p + 1) + if flags % 64 >= 4 then + return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) + end + local nfilters = flags % 4 + 1 + local q = p + 2 + local he = p + hsize - 4 + local csz, usz= nil, nil + if flags >= 128 or (math.floor(flags / 64)) % 2 == 1 then + if (math.floor(flags / 64)) % 2 == 1 then + local v + v, q = vli(b, q, he) + if not v or v == 0 then + return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) + end + csz = v + end + if flags >= 128 then + local v + v, q = vli(b, q, he) + if not v then + return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) + end + usz = v + end + end + local filters= {} + for _ = 1, nfilters do + local id, psz + id, q = vli(b, q, he) + if not id then + return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) + end + psz, q = vli(b, q, he) + if not psz or q + psz > he then + return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) + end + local pr = buffer.create(psz) + buffer.copy(pr, 0, b, q, psz) + q =q+ psz + table.insert(filters, { id = id, props = pr }) + end + for k = q, he - 1 do + if readu8(b, k) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) + end + end + local last = filters[nfilters] + if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) + end + for k = 1, nfilters - 1 do + local id = filters[k].id + if id ~= 0x03 and not BCJ[id] then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) + end + end + -- data + local dstart = p + hsize + local ostart = st.op + local dend = (csz and((dstart + csz ))or(e +)) if dend > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) + end + local cend, derr = decodeLzma2(st, b, dstart, dend) + if not cend then + return nil, derr + end + if csz and cend ~= dend then + return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) + end + local un = st.op - ostart + if usz and un ~= usz then + return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) + end + for k = nfilters - 1, 1, -1 do + local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) + if not ok then + return nil, ferr + end + end + local unpadded = hsize + (cend - dstart) + csize + local pe = cend + while (pe - p) % 4 ~= 0 do + if pe >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) + end + if readu8(b, pe) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) + end + pe =pe+ 1 + end + if pe + csize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) + end + if check == 1 then + if crc(st.out, ostart, un) ~= readu32(b, pe) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) + end + elseif check == 4 then + local hi, lo = Crc64.of(st.out, ostart, un) + if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) + end + end + table.insert(records, { unpadded, un }) + p = pe + csize + end + -- index + local ip = p + local count, q = vli(b, p + 1, e) + if not count or count ~= #records then + return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) + end + for i = 1, count do + local a, u + a, q = vli(b, q, e) + if not a then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + u, q = vli(b, q, e) + if not u then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if a ~= records[i][1] or u ~= records[i][2] then + return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) + end + end + while (q - ip) % 4 ~= 0 do + if q >= e or readu8(b, q) ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) + end + q =q+ 1 + end + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if crc(b, ip, q - ip) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) + end + q =q+ 4 + local isize = q - ip + -- footer + if q + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) + end + if crc(b, q + 4, 6) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) + end + if (readu32(b, q + 4) + 1) * 4 ~= isize then + return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) + end + if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then + return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) + end + return q + 12, nil +end + +-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range +function Lzma.xz(buf, offset, length, opts) +local b, o, l, aerr = args("Lzma.xz", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local st = Decode.new(l * 4, maxOf(opts)) + local p = o + local nstreams = 0 + while true do + local nxt, err = xzStream(st, b, p, e) + if not nxt then + return nil, err + end + nstreams =nstreams+ 1 + p = nxt + -- stream padding: zero bytes in multiples of 4 + local z = p + while z < e and readu8(b, z) == 0 do + z =z+ 1 + end + if z == e then + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + break + end + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + end + return Decode.finish(st), p +end + +-- isXz(buf, offset?) -> true when the bytes start an xz stream +function Lzma.isXz(b, o) +local off = o or 0 + return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC +end + +return Lzma +end +__FILES["codecs/compress/Lzma/Crc64"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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 + +local THI, TLO = table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local hi, lo = 0, n + for _ = 1, 8 do + local low = band(lo, 1) + lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) + hi = rshift(hi, 1) + if low ~= 0 then + hi = bxor(hi, 0xC96C5795) + lo = bxor(lo, 0xD7870F42) + end + end + THI[n + 1], TLO[n + 1] = hi, lo +end + +local Crc64 = {} + +-- of(buf, offset, length) -> hi, lo +function Crc64.of(b, o, n) +local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF + for i = o, o + n - 1 do + local idx = band(bxor(lo, readu8(b, i)), 255) + 1 + lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) + hi = bxor(THI[idx], rshift(hi, 8)) + end + return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) +end + +return Crc64 +end +__FILES["codecs/compress/Lzma/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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. +-- +-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last +-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep +-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by +-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. +-- +-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as +-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local rshift, band = bit32.rshift, bit32.band + +-- probability offsets (u16 entries) +local IS_MATCH = 0 -- 12 states x 16 pos states +local IS_REP = 192 +local IS_REP_G0 = 204 +local IS_REP_G1 = 216 +local IS_REP_G2 = 228 +local IS_REP0_LONG = 240 -- 12 x 16 +local POS_SLOT = 432 -- 4 x 64 +local SPEC_POS = 688 -- 115 +local ALIGN = 803 -- 16 +local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 +local REP_LEN = 1333 +local LITERAL = 1847 -- 0x300 << (lc + lp) + +local TOP = 16777216 -- 2^24 + +local Decode = {} + +-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap + + + + + + + + + + + + + + + + + + + + + +function Decode.new(cap, maxBytes) +local c = math.max(64, math.min(cap, maxBytes)) + return { + out = bcreate(c), + cap = c, + op = 0, + dictStart = 0, + maxBytes = maxBytes, + probs = bcreate(2), + nprobs = 0, + lc = 0, + lp = 0, + pb = 0, + state = 0, + rep0 = 0, + rep1 = 0, + rep2 = 0, + rep3 = 0, + remLen = 0, + range = 0xFFFFFFFF, + code = 0, + } +end + +-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) +function Decode.setProps(st, lc, lp, pb) +if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then + return false, "bad lc / lp / pb" + end + st.lc, st.lp, st.pb = lc, lp, pb + local n = LITERAL + 0x300 * 2 ^ (lc + lp) + if blen(st.probs) < n * 2 then + st.probs = bcreate(n * 2) + end + st.nprobs = n + Decode.resetState(st) + return true, nil +end + +-- resetState(st): probabilities to 1/2, LZ state and reps to 0 +function Decode.resetState(st) + local p = st.probs + for i = 0, st.nprobs - 1 do + writeu16(p, i * 2, 1024) + end + st.state = 0 + st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 + st.remLen = 0 +end + +-- resetDict(st): matches may no longer reach before the current position +function Decode.resetDict(st) + st.dictStart = st.op + st.remLen = 0 +end + +-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes +function Decode.rcInit(st, b, ip, iend) +if ip + 5 > iend then + return nil, "truncated range coder init" + end + if readu8(b, ip) ~= 0 then + return nil, "bad range coder init byte" + end + st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) + st.range = 0xFFFFFFFF + if st.code == st.range then + return nil, "bad range coder init" + end + return ip + 5, nil +end + +-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) +local function ensure(st, need) +if need <= st.cap then + return true + end + if need > st.maxBytes then + return false + end + local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) + local nb = bcreate(c) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + st.cap = c + return true +end +Decode.ensure = ensure + +-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range +function Decode.copy(st, n, b, ip) +if not ensure(st, st.op + n) then + return false, "limit: output over maxBytes" + end + bcopy(st.out, st.op, b, ip, n) + st.op =st.op+ n + return true, nil +end + +-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT +-- traces stay valid across calls; run() is not re-entrant, and never yields) +local EMPTY = bcreate(2) +local probs= EMPTY +local inb= EMPTY +local range, code, ip, iend, over = 0, 0, 0, 0, 0 + +-- decode one bit with the probability at index i +local function bit(i) +local p = i * 2 + local prob = readu16(probs, p) + local bound = rshift(range, 11) * prob + local r + if code < bound then + range = bound + writeu16(probs, p, prob + rshift(2048 - prob, 5)) + r = 0 + else + range =range- bound + code =code- bound + writeu16(probs, p, prob - rshift(prob, 5)) + r = 1 + end + if range < TOP then + range =range* 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code =code* 256 + over =over+ 1 + end + ip =ip+ 1 + end + return r +end + +local function tree(base, nbits) +local m = 1 + for _ = 1, nbits do + m = m * 2 + bit(base + m) + end + return m - 2 ^ nbits +end + +local function reverse(base, nbits) +local m = 1 + local sym = 0 + for i = 0, nbits - 1 do + local b = bit(base + m) + m = m * 2 + b + sym =sym+ b * 2 ^ i + end + return sym +end + +local function direct(nbits) +local res = 0 + for _ = 1, nbits do + range = rshift(range, 1) + local b = 0 + if code >= range then + code =code- range + b = 1 + end + res = res * 2 + b + if range < TOP then + range =range* 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code =code* 256 + over =over+ 1 + end + ip =ip+ 1 + end + end + return res +end + +local function length(base, posState) +if bit(base) == 0 then + return tree(base + 2 + posState * 8, 3) + end + if bit(base + 1) == 0 then + return 8 + tree(base + 130 + posState * 8, 3) + end + return 16 + tree(base + 258, 8) +end + +-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end +-- marker). The range coder must have been initialised (rcInit). +function Decode.run(st, inb0, ip0, iend0, outEnd) +probs = st.probs + inb = inb0 + iend = iend0 + local out = st.out + local cap = st.cap + local op = st.op + local dictStart = st.dictStart + range, code = st.range, st.code + ip = ip0 + over = 0 + local state = st.state + local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 + local lc = st.lc + local lcShift = 2 ^ (8 - lc) + local lpMask = 2 ^ st.lp - 1 + local pbMask = 2 ^ st.pb - 1 + local lcMul = 2 ^ lc + + local status= nil + local msg= nil + + -- a pending match from the previous call + local remLen = st.remLen + if remLen > 0 then + local n = math.min(remLen, outEnd - op) + if n > 0 then + if op + n > cap then + st.op = op + if not ensure(st, op + n) then + probs, inb = EMPTY, EMPTY + return nil, "limit: output over maxBytes" + end + out, cap = st.out, st.cap + end + local src = op - rep0 - 1 + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + op =op+ n + remLen =remLen- n + end + end + + while true do +local __DARKLUA_CONTINUE_6=false repeat if op >= outEnd then + status = "full" + break + end + if over > 0 then + msg = "truncated" + break + end + if op + 273 > cap then + st.op = op + if not ensure(st, math.min(op + 273, outEnd)) then + msg = "limit: output over maxBytes" + break + end + out, cap = st.out, st.cap + end + local pos = op - dictStart + local posState = band(pos, pbMask) + -- is match? (inlined bit) + local pidx = (IS_MATCH + state * 16 + posState) * 2 + local prob = readu16(probs, pidx) + local bound = rshift(range, 11) * prob + if code < bound then + range = bound + writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) + if range < TOP then + range =range* 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code =code* 256 + over =over+ 1 + end + ip =ip+ 1 + end + -- literal + local prev = (op > dictStart and{(readu8(out, op - 1) )}or{0 +})[1] local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + math.floor(prev / lcShift)) + local sym = 1 + if state >= 7 then + local mpos = op - rep0 - 1 + local matchByte = (mpos >= dictStart and{(readu8(out, mpos) )}or{0 +})[1] repeat + local matchBit = band(rshift(matchByte, 7), 1) + matchByte =matchByte* 2 + local b = bit(base + (1 + matchBit) * 256 + sym) + sym = sym * 2 + b + if matchBit ~= b then + break + end + until sym >= 256 + end + while sym < 256 do + local p2 = (base + sym) * 2 + local pr = readu16(probs, p2) + local bd = rshift(range, 11) * pr + if code < bd then + range = bd + writeu16(probs, p2, pr + rshift(2048 - pr, 5)) + sym = sym * 2 + else + range =range- bd + code =code- bd + writeu16(probs, p2, pr - rshift(pr, 5)) + sym = sym * 2 + 1 + end + if range < TOP then + range =range* 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code =code* 256 + over =over+ 1 + end + ip =ip+ 1 + end + end + writeu8(out, op, sym - 256) + op =op+ 1 + state = state < 4 and 0 or(state < 10 and((state - 3 ))or((state - 6 +))) else + range =range- bound + code =code- bound + writeu16(probs, pidx, prob - rshift(prob, 5)) + if range < TOP then + range =range* 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code =code* 256 + over =over+ 1 + end + ip =ip+ 1 + end + local len + if bit(IS_REP + state) == 0 then + -- simple match + len = length(LEN, posState) + state = state < 7 and 7 or 10 + rep3, rep2, rep1 = rep2, rep1, rep0 + local lenState = (len < 3 and{len }or{3 +})[1] local slot = tree(POS_SLOT + lenState * 64, 6) + if slot < 4 then + rep0 = slot + else + local nd = math.floor(slot / 2 )- 1 + local dist = (2 + slot % 2) * 2 ^ nd + if slot < 14 then + dist =dist+ reverse(SPEC_POS + dist - slot, nd) + else + dist =dist+ direct(nd - 4) * 16 + dist =dist+ reverse(ALIGN, 4) + end + rep0 = dist + end + if rep0 == 0xFFFFFFFF then + status = "eos" + break + end + else + if bit(IS_REP_G0 + state) == 0 then + if bit(IS_REP0_LONG + state * 16 + posState) == 0 then + -- short rep: one byte at rep0 + if op == dictStart or rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + state = state < 7 and 9 or 11 + writeu8(out, op, readu8(out, op - rep0 - 1)) + op =op+ 1 +__DARKLUA_CONTINUE_6=true break + end + else + local dist + if bit(IS_REP_G1 + state) == 0 then + dist = rep1 + else + if bit(IS_REP_G2 + state) == 0 then + dist = rep2 + else + dist = rep3 + rep3 = rep2 + end + rep2 = rep1 + end + rep1 = rep0 + rep0 = dist + end + len = length(REP_LEN, posState) + state = state < 7 and 8 or 11 + end + -- copy len + 2 bytes from rep0 + 1 back + if rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + local n = len + 2 + local room = outEnd - op + if n > room then + remLen = n - room + n = room + end + local src = op - rep0 - 1 + if rep0 + 1 >= n then + bcopy(out, op, out, src, n) + else + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + end + op =op+ n + end +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end + st.op = op + st.range, st.code = range, code + st.state = state + st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 + st.remLen = remLen + probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + if msg then + return nil, msg + end + if over > 0 then + return nil, "truncated" + end + return status, ip +end + +-- finish(st) -> a buffer of exactly the decoded bytes +function Decode.finish(st) +if st.cap == st.op then + return st.out + end + local b = bcreate(st.op) + bcopy(b, 0, st.out, 0, st.op) + return b +end + +return Decode +end +__FILES["codecs/compress/Lzma/Filters"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap + +local TWO32 = 4294967296 + +local Filters = {} + +local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } +local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } + +local function msbyte(b) +return b == 0 or b == 0xFF +end + +-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) +function Filters.x86(b, o, n, start) + if n <= 4 then + return + end + local size = n - 4 + local prevPos = -1 + local prevMask = 0 + local i = 0 + while i < size do +local __DARKLUA_CONTINUE_1=false repeat local c = readu8(b, o + i) + if band(c, 0xFE) ~= 0xE8 then + i =i+ 1 +__DARKLUA_CONTINUE_1=true break + end + local d = i - prevPos + if d > 3 then + prevMask = 0 + else + prevMask = band(lshift(prevMask, d - 1), 7) + if prevMask ~= 0 then + local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) + if not MASK_ALLOWED[prevMask] or msbyte(bb) then + prevPos = i + prevMask = bor(lshift(prevMask, 1), 1) + i =i+ 1 +__DARKLUA_CONTINUE_1=true break + end + end + end + prevPos = i + if msbyte(readu8(b, o + i + 4)) then + local src = readu32(b, o + i + 1) + local dest + while true do + dest = (src - (start + i + 5)) % TWO32 + if prevMask == 0 then + break + end + local j = MASK_BITNUM[prevMask] * 8 + local bb = band(rshift(dest, 24 - j), 0xFF) + if not msbyte(bb) then + break + end + src = bxor(dest, 2 ^ (32 - j) - 1) + end + dest = band(dest, 0x01FFFFFF) + if band(dest, 0x01000000) ~= 0 then + dest = bor(dest, 0xFF000000) + end + writeu32(b, o + i + 1, dest) + i =i+ 5 + else + prevMask = bor(lshift(prevMask, 1), 1) + i =i+ 1 + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end +end + +function Filters.arm(b, o, n, start) + local i = 0 + while i + 4 <= n do + if readu8(b, o + i + 3) == 0xEB then + local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 + addr = (addr * 4 - (start + i + 8)) % TWO32 + addr = rshift(addr, 2) + writeu8(b, o + i, band(addr, 255)) + writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) + writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) + end + i =i+ 4 + end +end + +function Filters.armthumb(b, o, n, start) + local i = 0 + while i + 4 <= n do + local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) + if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then + local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) + addr = (addr * 2 - (start + i + 4)) % TWO32 + addr = rshift(addr, 1) + writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) + writeu8(b, o + i, band(rshift(addr, 11), 255)) + writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) + writeu8(b, o + i + 2, band(addr, 255)) + i =i+ 4 + else + i =i+ 2 + end + end +end + +function Filters.powerpc(b, o, n, start) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + if band(instr, 0xFC000003) == 0x48000001 then + instr = band(instr, 0x03FFFFFC) + instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) + instr = bor(instr, 0x48000001) + writeu32(b, o + i, byteswap(instr)) + end + i =i+ 4 + end +end + +function Filters.sparc(b, o, n, start) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + local top = rshift(instr, 22) + if top == 0x100 or top == 0x1FF then + instr = (instr * 4) % TWO32 + instr = (instr - (start + i)) % TWO32 + instr = rshift(instr, 2) + instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) + writeu32(b, o + i, byteswap(instr)) + end + i =i+ 4 + end +end + +function Filters.arm64(b, o, n, start) + local i = 0 + while i + 4 <= n do + local pc = (start + i) % TWO32 + local instr = readu32(b, o + i) + if rshift(instr, 26) == 0x25 then + local src = instr + local p = (TWO32 - rshift(pc, 2)) % TWO32 + writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) + elseif band(instr, 0x9F000000) == 0x90000000 then + local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) + if band(src + 0x00020000, 0x001C0000) == 0 then + local p = (TWO32 - rshift(pc, 12)) % TWO32 + local dest = (src + p) % TWO32 + local v = band(instr, 0x9000001F) + v = bor(v, lshift(band(dest, 3), 29)) + v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) + v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) + writeu32(b, o + i, v) + end + end + i =i+ 4 + end +end + +-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +function Filters.delta(b, o, n, dist) + for i = dist, n - 1 do + writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) + end +end + +return Filters +end +__FILES["codecs/compress/Lzw"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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). +-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code +-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is +-- detected by its first bytes (0x00 then an odd byte) and decoded too. +-- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only). +-- +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff") +-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo") +-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer +-- local codes = Lzw.encode(data, off, len, "tiff") +-- +-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of +-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or +-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that +-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway). +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local blen = buffer.len + +local Lzw = {} + +local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF) +local TABLE = 8192 -- the tables hold 13-bit codes (Zoo) + +-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield) +local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends +local suffix = buffer.create(TABLE) -- u8: its last byte +local first = buffer.create(TABLE) -- u8: its first byte +local length = buffer.create(TABLE * 2) -- u16: its length + +-- ------------------------------------------------------------------------------------------------ decode +-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim) +local function emit(out, o, c, l, lim) + local p = o + l - 1 + if p < lim then + while p >= o do + writeu8(out, p, readu8(suffix, c)) + c = readu16(prefix, c * 2) + p =p- 1 + end + else + while p >= o do + if p < lim then + writeu8(out, p, readu8(suffix, c)) + end + c = readu16(prefix, c * 2) + p =p- 1 + end + end +end + +function Lzw.decode(src, off, len, out, outOff, maxOut, variant, minCodeSize) +local n = blen(src) + if off < 0 or off > n then + return 0, "corrupt" + end + local e = math.min(off + math.max(0, len), n) + local lim = math.min(outOff + math.max(0, maxOut), blen(out)) + if outOff < 0 then + return 0, "corrupt" + end + local msb = variant == "tiff" + local early = 0 -- 1 for TIFF's early change + local min = minCodeSize or 8 + local maxCodes, maxBits = MAX_CODES, 12 + if variant == "zoo" then + min, maxCodes, maxBits = 8, TABLE, 13 + end + if msb then + min = 8 + early = 1 + -- old-style TIFF LZW: LSB-first, no early change (libtiff LZWPreDecode's check) + if e - off >= 2 and readu8(src, off) == 0 and band(readu8(src, off + 1), 1) == 1 then + msb = false + early = 0 + end + end + if min < 1 or min > 11 then + return 0, "corrupt" + end + local clear = lshift(1, min) + local eoi = clear + 1 + for i = 0, clear - 1 do + writeu16(prefix, i * 2, 0) + writeu8(suffix, i, band(i, 255)) + writeu8(first, i, band(i, 255)) + writeu16(length, i * 2, 1) + end + local size = min + 1 + local mask = lshift(1, size) - 1 + local nextc = clear + 2 + local prev = -1 + local o = outOff + local p = off + local acc, nb = 0, 0 + while true do + -- refill (at most 13 + 7 bits held: below 2^21) + while nb < size do + if p >= e then + return o - outOff, "truncated" + end + if msb then + acc = acc * 256 + readu8(src, p) + else + acc =acc+ lshift(readu8(src, p), nb) + end + p =p+ 1 + nb =nb+ 8 + end + local c + if msb then + nb =nb- size + c = band(rshift(acc, nb), mask) + acc = band(acc, lshift(1, nb) - 1) + else + c = band(acc, mask) + acc = rshift(acc, size) + nb =nb- size + end + if c == clear then + size = min + 1 + mask = lshift(1, size) - 1 + nextc = clear + 2 + prev = -1 + elseif c == eoi then + return o - outOff, nil + else + if o >= lim then + return o - outOff, nil -- full: the rest (normally just EOI) is ignored + end + if prev < 0 then + if c >= clear then + return o - outOff, "corrupt" + end + writeu8(out, o, readu8(suffix, c)) + o =o+ 1 + prev = c + else + local l + if c < nextc then + l = readu16(length, c * 2) + emit(out, o, c, l, lim) + if nextc < maxCodes then + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, readu8(first, c)) + writeu8(first, nextc, readu8(first, prev)) + writeu16(length, nextc * 2, readu16(length, prev * 2) + 1) + nextc =nextc+ 1 + end + elseif c == nextc and nextc < maxCodes then + -- KwKwK: the new entry is prev + first(prev) + local f = readu8(first, prev) + writeu16(prefix, nextc * 2, prev) + writeu8(suffix, nextc, f) + writeu8(first, nextc, f) + l = readu16(length, prev * 2) + 1 + writeu16(length, nextc * 2, l) + nextc =nextc+ 1 + emit(out, o, c, l, lim) + else + return o - outOff, "corrupt" + end + o = math.min(o + l, lim) + prev = c + end + if nextc + early >= lshift(1, size) and size < maxBits then + size =size+ 1 + mask = lshift(1, size) - 1 + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ encode +local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries +local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty) +local hval = buffer.create(HASH * 2) -- u16 code + +-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in +-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF). +function Lzw.encode(data, off, len, variant, minCodeSize) +local msb = variant == "tiff" + local min = msb and 8 or math.clamp(minCodeSize or 8, 1, 11) + local early = msb and 1 or 0 + local symMask = lshift(1, min) - 1 + local clear = lshift(1, min) + local eoi = clear + 1 + local n = blen(data) + off = math.clamp(off, 0, n) + local e = math.clamp(off + len, off, n) + local cap = (e - off) * 2 + 64 + local out = buffer.create(cap) + local op = 0 + local acc, nb = 0, 0 + local size = min + 1 + local function put(code) + if op + 4 > cap then + cap =cap* 2 + local nbuf = buffer.create(cap) + buffer.copy(nbuf, 0, out, 0, op) + out = nbuf + end + if msb then + acc = acc * lshift(1, size) + code + nb =nb+ size + while nb >= 8 do + nb =nb- 8 + writeu8(out, op, rshift(acc, nb)) + op =op+ 1 + acc = band(acc, lshift(1, nb) - 1) + end + else + acc =acc+ lshift(code, nb) + nb =nb+ size + while nb >= 8 do + writeu8(out, op, band(acc, 255)) + op =op+ 1 + acc = rshift(acc, 8) + nb =nb- 8 + end + end + end + buffer.fill(hkey, 0, 0, HASH * 4) + local nextc = clear + 2 + put(clear) + if e > off then + local cur = band(readu8(data, off), symMask) + for i = off + 1, e - 1 do + local b = band(readu8(data, i), symMask) + local key = cur * 256 + b + 1 + local h = band(cur * 31 + b * 4099, HASH - 1) + local found = -1 + while true do + local k = buffer.readi32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu16(hval, h * 2) + break + end + h = band(h + 1, HASH - 1) + end + if found >= 0 then + cur = found + else + put(cur) + if nextc >= MAX_CODES - 2 then + put(clear) + size = min + 1 + nextc = clear + 2 + buffer.fill(hkey, 0, 0, HASH * 4) + else + buffer.writei32(hkey, h * 4, key) + writeu16(hval, h * 2, nextc) + nextc =nextc+ 1 + if nextc + early > lshift(1, size) and size < 12 then + size =size+ 1 + end + end + cur = b + end + end + put(cur) + -- the decoder adds an entry for this last code too: its width may grow before EOI + if nextc < MAX_CODES then + nextc =nextc+ 1 + if nextc + early > lshift(1, size) and size < 12 then + size =size+ 1 + end + end + end + put(eoi) + if nb > 0 then + writeu8(out, op, (msb and{(band(lshift(acc, 8 - nb), 255) )}or{(band(acc, 255))})[1]) + op =op+ 1 + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res +end + +return Lzw +end +__FILES["codecs/compress/Lzx"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, +-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and +-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), +-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the +-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets +-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification +-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from +-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). +-- +-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message +-- +-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact +-- uncompressed size. Never throws: bad or truncated data returns nil, message. +local Huffman = __include("codecs/entropy/Huffman") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local writeu8, writei32 = buffer.writeu8, buffer.writei32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Lzx = {} + +local FRAME = 32768 +local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6 +local MAXMAIN = 256 + 8 * 50 +local NLEN = 249 +local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder) + +-- position slots: footer bits and base of each formatted offset slot +local EXTRA = table.create(51, 0) +local BASE = table.create(51, 0) +do + local b = 0 + for i = 0, 50 do + local e = i < 4 and 0 or math.min(math.floor(i / 2 )- 1, 17) + EXTRA[i + 1] = e + BASE[i + 1] = b + b =b+ lshift(1, e) + end +end +local SLOTS= { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } +-- ------------------------------------------------------------------------------------------------ bit reader +-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the +-- end, zero words are read and over counts their bits. + + + +local function refill(s) + while s.cnt <= 16 do + local p = s.pos + local w = 0 + if p + 2 <= s.stop then + w = readu16(s.src, p) + s.pos = p + 2 + elseif p < s.stop then + w = readu8(s.src, p) + s.pos = p + 1 + s.over =s.over+ 8 + else + s.over =s.over+ 16 + end + s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) + s.cnt =s.cnt+ 16 + end +end + +-- bits(s, n) -> the next n (1..17) bits +local function bits(s, n) +if s.cnt < n then + refill(s) + end + local v = rshift(s.bb, 32 - n) + s.bb = lshift(s.bb, n) + s.cnt =s.cnt- n + return v +end + +-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code +local function sym(s, tab, P, S) +if s.cnt < 16 then + refill(s) + end + local e = readu32(tab, rshift(s.bb, 32 - P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + s.bb = lshift(s.bb, l) + s.cnt =s.cnt- l + return rshift(e, 5) +end + +-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +local function readLens(s, lens, first, last, pre, preLens) +for i = 0, 19 do + writeu8(preLens, i, bits(s, 4)) + end + local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP) + if S < 0 then + return false + end + local cap = blen(lens) + local x = first + while x < last do + local z = sym(s, pre, PREP, S) + if z < 0 then + return false + end + if z == 17 or z == 18 then + local run = (z == 17 and{(bits(s, 4) + 4 )}or{(bits(s, 5) + 20 +)})[1] for _ = 1, run do + if x < cap then + writeu8(lens, x, 0) + end + x =x+ 1 + end + elseif z == 19 then + local run = bits(s, 1) + 4 + local d = sym(s, pre, PREP, S) + if d < 0 or d > 16 then + return false + end + local v = (readu8(lens, x) - d + 17) % 17 + for _ = 1, run do + if x < cap then + writeu8(lens, x, v) + end + x =x+ 1 + end + else + writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) + x =x+ 1 + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ decode +-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +local function translate(out, n, size) + local base = 0 + local frame = 0 + while base < n and frame < 32768 do + local fs = math.min(FRAME, n - base) + if fs > 10 then + local i = base + local stop = base + fs - 10 + while i < stop do + if readu8(out, i) == 0xE8 then + local abs = readi32(out, i + 1) + if abs >= -i and abs < size then + writei32(out, i + 1, (abs >= 0 and((abs - i ))or((abs + size)))) + end + i =i+ 5 + else + i =i+ 1 + end + end + end + base =base+ fs + frame =frame+ 1 + end +end + +function Lzx.decode(src, offset, length, outSize, windowBits) +local nslots = SLOTS[windowBits] + if not nslots then + return nil, "unsupported: LZX window 2^" .. tostring(windowBits) + end + if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad arguments" + end + local windowSize = lshift(1, windowBits) + local mainN = 256 + 8 * nslots + local out = bcreate(outSize) + local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20) + local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4) + local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4) + local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4) + local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4) + local s= { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } + local R0, R1, R2= 1, 1, 1 + local intel = 0 + local started = false + local btype, bremain, bsize = 0, 0, 0 + local mainS, lenS, alignS = 0, 0, 0 + local op = 0 + while op < outSize do + local frameEnd = math.min(op + FRAME, outSize) + while op < frameEnd do + if bremain == 0 then + -- a new block + if btype == 3 and band(bsize, 1) == 1 then + s.pos =s.pos+ 1 + end + if not started then + started = true + if bits(s, 1) == 1 then + local hi = bits(s, 16) + intel = hi * 65536 + bits(s, 16) + end + end + btype = bits(s, 3) + local hi = bits(s, 16) + bsize = hi * 256 + bits(s, 8) + bremain = bsize + if s.over > s.cnt then + return nil, "truncated input" + end + if bsize == 0 then + return nil, "empty block" + end + if btype == 2 then + for i = 0, 7 do + writeu8(alignLens, i, bits(s, 3)) + end + alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP) + if alignS < 0 then + return nil, "bad aligned offset tree" + end + end + if btype == 1 or btype == 2 then + if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then + return nil, "bad main tree" + end + mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP) + if mainS < 0 then + return nil, "bad main tree" + end + if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then + return nil, "bad length tree" + end + lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP) + if lenS < 0 then + return nil, "bad length tree" + end + elseif btype == 3 then + -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes + local k = s.cnt % 16 + if k == 0 then + k = 16 + end + local p = s.pos - math.floor((s.cnt - k) / 8 +) s.bb, s.cnt = 0, 0 + if s.over > 0 or p + 12 > s.stop then + return nil, "truncated uncompressed block" + end + R0 = readu32(src, p) + R1 = readu32(src, p + 4) + R2 = readu32(src, p + 8) + s.pos = p + 12 + else + return nil, "bad block type " .. btype + end + if s.over > s.cnt then + return nil, "truncated input" + end + end + local runEnd = op + math.min(bremain, frameEnd - op) + if btype == 3 then + local n = runEnd - op + local p = s.pos + if p + n > s.stop then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, p, n) + s.pos = p + n + op =op+ n + bremain =bremain- n + else + local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over + local stop = s.stop + local aligned = btype == 2 + local start = op + while op < runEnd do + -- refill to at least 17 bits + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos =pos+ 2 + elseif pos < stop then + w = readu8(src, pos) + pos =pos+ 1 + over =over+ 8 + else + over =over+ 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt =cnt+ 16 + end + local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "bad main code" + end + e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "bad main code" + end + end + bb = lshift(bb, l) + cnt =cnt- l + local m = rshift(e, 5) + if m < 256 then + writeu8(out, op, m) + op =op+ 1 + else + m =m- 256 + local len = band(m, 7) + if len == 7 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos =pos+ 2 + else + over =over+ 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt =cnt+ 16 + end + local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4) + local ll = band(le, 31) + if ll == 0 then + if le == 0 then + return nil, "bad length code" + end + le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4) + ll = band(le, 31) + if ll == 0 then + return nil, "bad length code" + end + end + bb = lshift(bb, ll) + cnt =cnt- ll + len =len+ rshift(le, 5) + end + len =len+ 2 + local slot = rshift(m, 3) + local dist +if slot == 0 then + dist = R0 + elseif slot == 1 then + dist = R1 + R1 = R0 + R0 = dist + elseif slot == 2 then + dist = R2 + R2 = R0 + R0 = dist + else + local ex = EXTRA[slot + 1] + dist = BASE[slot + 1] - 2 + if ex > 0 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos =pos+ 2 + else + over =over+ 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt =cnt+ 16 + end + if aligned and ex >= 3 then + if ex > 3 then + dist =dist+ lshift(rshift(bb, 35 - ex), 3) + bb = lshift(bb, ex - 3) + cnt =cnt- (ex - 3 +) while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos =pos+ 2 + else + over =over+ 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt =cnt+ 16 + end + end + local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4) + local al = band(ae, 31) + if al == 0 then + return nil, "bad aligned offset code" + end + bb = lshift(bb, al) + cnt =cnt- al + dist =dist+ rshift(ae, 5) + else + dist =dist+ rshift(bb, 32 - ex) + bb = lshift(bb, ex) + cnt =cnt- ex + end + end + R2 = R1 + R1 = R0 + R0 = dist + end + if dist < 1 or dist > op or dist > windowSize then + return nil, "match offset before the start of the data" + end + if op + len > runEnd then + return nil, "match past the end of its block or frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op =op+ len + end + end + s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over + bremain =bremain- (op - start +) end + end + -- the end of a frame: realign to 16 bits + local k = s.cnt % 16 + s.bb = lshift(s.bb, k) + s.cnt =s.cnt- k + if s.over > s.cnt then + return nil, "truncated input" + end + end + if intel ~= 0 then + translate(out, outSize, intel) + end + return out, nil +end + +return Lzx +end +__FILES["codecs/compress/PackBits"] = function() +local __compat = __compat local buffer = __compat.buffer --!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, p, limit, dst, d, n) +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 =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 =o+ cnt + end + p =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 =p+ 1 + o =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, off, len) +local out = buffer.create(len + math.floor((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 =run+ 1 + end + if run >= 3 then + writeu8(out, o, 257 - run) + writeu8(out, o + 1, v) + o =o+ 2 + p =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 =p+ 1 + n =n+ 1 + end + writeu8(out, o, n - 1) + buffer.copy(out, o + 1, src, s, n) + o =o+ (n + 1 +) end + end + local r = buffer.create(o) + buffer.copy(r, 0, out, 0, o) + return r +end + +return PackBits +end +__FILES["codecs/compress/Quantum"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft +-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with +-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the +-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the +-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and +-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the +-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the +-- models and the window persist across the frames of a folder. Written from the public descriptions of the format +-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. +-- +-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message +-- +-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is +-- their total. Never throws: bad or truncated data returns nil, message. + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local Quantum = {} + +-- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) +local PBASE = table.create(42, 0) +local PEXTRA = table.create(42, 0) +do + local b = 0 + for i = 0, 41 do + local e = i < 4 and 0 or math.floor(i / 2 )- 1 + PEXTRA[i + 1] = e + PBASE[i + 1] = b + b =b+ lshift(1, e) + end +end +local LEXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local LBASE = table.create(27, 0) +do + local b = 0 + for i = 1, 27 do + LBASE[i] = b + b =b+ lshift(1, LEXTRA[i]) + end +end +-- ------------------------------------------------------------------------------------------------ models +-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) + + + +local function model(first, n) +local sym = table.create(n, 0) + local cum = table.create(n + 1, 0) + for i = 1, n do + sym[i] = first + i - 1 + cum[i] = n - i + 1 + end + cum[n + 1] = 0 + return { n = n, sym = sym, cum = cum, shifts = 4 } +end + +local function rescale(m) + local n, sym, cum = m.n, m.sym, m.cum + m.shifts =m.shifts- 1 + if m.shifts > 0 then + for i = n, 1, -1 do + local c = rshift(cum[i], 1) + if c <= cum[i + 1] then + c = cum[i + 1] + 1 + end + cum[i] = c + end + return + end + m.shifts = 50 + -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) + for i = 1, n do + cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) + end + -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) + for i = 1, n - 1 do + for j = i + 1, n do + if cum[i] < cum[j] then + cum[i], cum[j] = cum[j], cum[i] + sym[i], sym[j] = sym[j], sym[i] + end + end + end + for i = n, 1, -1 do + cum[i]=cum[i]+ cum[i + 1] + end +end +-- ------------------------------------------------------------------------------------------------ decode +-- the coder and bit reader of one frame + + + +local function bit(c) +if c.cnt == 0 then + local p = c.pos + if p < c.stop then + c.acc = readu8(c.src, p) + c.pos = p + 1 + else + c.acc = 0 + c.over =c.over+ 1 + end + c.cnt = 8 + end + c.cnt =c.cnt- 1 + return band(rshift(c.acc, c.cnt), 1) +end + +-- raw(c, n) -> the next n (0..19) bits, most significant first +local function raw(c, n) +local v = 0 + for _ = 1, n do + v = v * 2 + bit(c) + end + return v +end + +local function symbol(c, m) +local cum = m.cum + local H, L, C = c.H, c.L, c.C + local range = H - L + 1 + local total = cum[1] + if range <= 0 or C < L or C > H then + -- only corrupt registers get here (the decoder keeps L <= C <= H) + c.bad = true + return 0 + end + local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) + local n = m.n + local i = 2 + while i <= n and cum[i] > f do + i =i+ 1 + end + -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) + local s = m.sym[i - 1] + H = L + floor(cum[i - 1] * range / total) - 1 + L = L + floor(cum[i] * range / total) + for k = 1, i - 1 do + cum[k]=cum[k]+ 8 + end + if cum[1] > 3800 then + rescale(m) + end + while true do + if band(bxor(L, H), 0x8000) ~= 0 then + if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then + -- underflow: L and H straddle the middle + C = bxor(C, 0x4000) + L = band(L, 0x3FFF) + H = bor(H, 0x4000) + else + break + end + end + L = band(lshift(L, 1), 0xFFFF) + H = bor(band(lshift(H, 1), 0xFFFF), 1) + C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) + end + c.H, c.L, c.C = H, L, C + return s +end + +function Quantum.decode(src, blocks, outSize, windowBits) +if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then + return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) + end + if outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad output size" + end + local total = 0 + for _, b in __iter(blocks) do + if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then + return nil, "bad block range" + end + total =total+ b.size + end + if total ~= outSize then + return nil, "block sizes do not add up to the output size" + end + local window = lshift(1, windowBits) + local slots = windowBits * 2 + local selector = model(0, 7) + local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } + local m3 = model(0, math.min(slots, 24)) + local m4 = model(0, math.min(slots, 36)) + local m5 = model(0, slots) + local mlen = model(0, 27) + local out = bcreate(outSize) + local op = 0 + for _, b in __iter(blocks) do + local frameEnd = op + b.size + local c= { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } + c.C = raw(c, 16) + while op < frameEnd do + local sel = symbol(c, selector) + if c.bad then + return nil, "bad arithmetic code" + end + if sel < 4 then + writeu8(out, op, symbol(c, lit[sel + 1])) + op =op+ 1 + else + local len, slot + if sel == 4 then + len = 3 + slot = symbol(c, m3) + elseif sel == 5 then + len = 4 + slot = symbol(c, m4) + elseif sel == 6 then + local ls = symbol(c, mlen) + len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 + slot = symbol(c, m5) + else + return nil, "bad selector" + end + local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 + if dist > op or dist > window then + return nil, "match offset before the start of the data" + end + if op + len > frameEnd then + return nil, "match past the end of its frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op =op+ len + end + if c.bad then + return nil, "bad arithmetic code" + end + if c.over > 4 then + return nil, "truncated frame" + end + end + end + return out, nil +end + +return Quantum +end +__FILES["codecs/compress/UnixCompress"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +--!native +--!optimize 2 +-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code +-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are +-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the +-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width +-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder +-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked +-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read +-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws. +-- +-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file +-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local UnixCompress = {} + + + + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local MAXCODES = 65536 +local CHECK_GAP = 10000 + +-- decoder tables (per call state lives in locals; the tables are reused: decode never yields) +local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends +local suffix = bcreate(MAXCODES) -- u8: its last byte +local first = bcreate(MAXCODES) -- u8: its first byte +local length = bcreate(MAXCODES * 4) -- u32: its length + +-- ------------------------------------------------------------------------------------------------ decode +-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err +function UnixCompress.decompress(buf, offset, len, opts) +local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + if n < 3 then + return nil, Err.new(Err.TRUNCATED, "header past the end", o) + end + if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then + return nil, Err.new(Err.CORRUPT, "bad magic", o) + end + local flags = readu8(b, o + 2) + local maxbits = band(flags, 0x1F) + local block = band(flags, 0x80) ~= 0 + if maxbits < 9 or maxbits > 16 then + return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2) + end + if band(flags, 0x60) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2) + end + local maxmax = lshift(1, maxbits) + for i = 0, 255 do + writeu32(prefix, i * 4, 0) + writeu8(suffix, i, i) + writeu8(first, i, i) + writeu32(length, i * 4, 1) + end + local cap = math.min(math.max(n * 3, 1024), maxBytes) + local out = bcreate(cap) + local op = 0 + local totalBits = (n - 3) * 8 + local base = o + 3 + local pos = 0 -- bit position from the first code + local gbase = 0 -- where the current group sequence starts + local nbits = 9 + local mask = 511 + local maxcode = 511 + local freeEnt = block and 257 or 256 + local prev = -1 + while pos + nbits <= totalBits do +local __DARKLUA_CONTINUE_2=false repeat if freeEnt > maxcode then + local g = nbits * 8 + pos = gbase + math.floor((pos - gbase + g - 1) / g )* g + gbase = pos + nbits =nbits+ 1 + maxcode = (nbits == maxbits and{maxmax }or{(lshift(1, nbits) - 1 +)})[1] mask = lshift(1, nbits) - 1 +__DARKLUA_CONTINUE_2=true break + end + -- the code: up to 23 bits from three bytes + local q = base + rshift(pos, 3) + local acc = readu8(b, q) + if q + 1 < o + n then + acc = bor(acc, lshift(readu8(b, q + 1), 8)) + end + if q + 2 < o + n then + acc = bor(acc, lshift(readu8(b, q + 2), 16)) + end + local c = band(rshift(acc, band(pos, 7)), mask) + pos =pos+ nbits + if c == 256 and block then + local g = nbits * 8 + pos = gbase + math.floor((pos - gbase + g - 1) / g )* g + gbase = pos + nbits = 9 + mask = 511 + maxcode = 511 + freeEnt = 257 + prev = -1 +__DARKLUA_CONTINUE_2=true break + end + local l + if prev < 0 then + if c >= 256 then + return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3)) + end + l = 1 + elseif c < freeEnt then + l = readu32(length, c * 4) + elseif c == freeEnt then + l = readu32(length, prev * 4) + 1 + else + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + if op + l > cap then + if op + l > maxBytes then + return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes") + end + local ncap = math.min(math.max(cap * 2, op + l), maxBytes) + local nb = bcreate(ncap) + bcopy(nb, 0, out, 0, op) + out, cap = nb, ncap + end + -- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it + if prev >= 0 and freeEnt < maxmax then + local f = (c == freeEnt and{(readu8(first, prev) )}or{(readu8(first, c) +)})[1] writeu32(prefix, freeEnt * 4, prev) + writeu8(suffix, freeEnt, f) + writeu8(first, freeEnt, readu8(first, prev)) + writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1) + freeEnt =freeEnt+ 1 + elseif prev >= 0 then + if c == freeEnt then + return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3)) + end + end + local p = op + l - 1 + local k = c + while p >= op do + writeu8(out, p, readu8(suffix, k)) + k = readu32(prefix, k * 4) + p =p- 1 + end + op =op+ l + prev = c +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + local res = bcreate(op) + bcopy(res, 0, out, 0, op) + return res, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries +local hkey = bcreate(HSIZE * 4) +local hval = bcreate(HSIZE * 4) + +-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err +function UnixCompress.compress(buf, offset, len, opts) +local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len) + if not b then + return nil, aerr + end + local maxbits = (opts and opts.maxBits) or 16 + if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxBits must be 9..16") + end + -- at most 17 bits per input byte, plus group padding (< one group per width change / clear) + local cap = 3 + n * 2 + 64 + local out = bcreate(cap) + writeu8(out, 0, 0x1F) + writeu8(out, 1, 0x9D) + writeu8(out, 2, bor(maxbits, 0x80)) + local outbits = 24 + local boff = 24 + local acc, nb = 0, 0 -- pending bits not yet written (below 2^24) + local nbits = 9 + local extcode = 513 + local maxmax = lshift(1, maxbits) + local stcode = true + local freeEnt = 257 + local ratio = 0 + local checkpoint = CHECK_GAP + buffer.fill(hkey, 0, 0, HSIZE * 4) + local function put(code) + acc = bor(acc, lshift(code, nb)) + nb =nb+ nbits + outbits =outbits+ nbits + while nb >= 8 do + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + acc = rshift(acc, 8) + nb =nb- 8 + end + end + local function align() + -- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros + local g = nbits * 8 + local nbits2 = boff + math.floor((outbits - boff + g - 1) / g )* g + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + acc, nb = 0, 0 + outbits = nbits2 + boff = nbits2 + end + if n == 0 then + local res = bcreate(3) + bcopy(res, 0, out, 0, 3) + return res, nil + end + local ent = readu8(b, o) + local e = o + n + local i = o + 1 + -- checks happen with a one-byte current string, right after an output (and at the start) + local function checks(consumed) + if freeEnt >= extcode then + if nbits < maxbits then + align() + nbits =nbits+ 1 + extcode = (nbits < maxbits and{(lshift(1, nbits) + 1 )}or{(lshift(1, nbits) +)})[1] else + extcode = math.huge + stcode = false + end + end + if not stcode and consumed >= checkpoint then + checkpoint = consumed + CHECK_GAP + local outBytes = rshift(outbits, 3) + local rat + if consumed > 0x7FFFFF then + local d = rshift(outBytes, 8) + rat = d == 0 and 0x7FFFFFFF or math.floor(consumed / d +) else + rat = math.floor((consumed * 256) / outBytes +) end + if rat >= ratio then + ratio = rat + else + ratio = 0 + buffer.fill(hkey, 0, 0, HSIZE * 4) + put(256) + align() + nbits = 9 + extcode = 513 + freeEnt = 257 + stcode = true + end + end + end + checks(1) + while i < e do + local c = readu8(b, i) + i =i+ 1 + local key = ent * 256 + c + 1 + local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1) + local found = -1 + while true do + local k = readu32(hkey, h * 4) + if k == 0 then + break + elseif k == key then + found = readu32(hval, h * 4) + break + end + h = band(h + 1, HSIZE - 1) + end + if found >= 0 then + ent = found + else + put(ent) + if stcode then + writeu32(hkey, h * 4, key) + writeu32(hval, h * 4, freeEnt) + freeEnt =freeEnt+ 1 + end + ent = c + checks(i - o) + end + if rshift(outbits, 3) + 8 > cap then + -- grow (rare: only incompressible input passes 2 bytes per byte) + local ncap = cap * 2 + local nbuf = bcreate(ncap) + bcopy(nbuf, 0, out, 0, cap) + out, cap = nbuf, ncap + end + end + put(ent) + if nb > 0 then + local q = rshift(outbits - nb, 3) + if q < cap then + writeu8(out, q, band(acc, 255)) + end + end + local size = rshift(outbits + 7, 3) + local res = bcreate(size) + bcopy(res, 0, out, 0, math.min(size, cap)) + return res, nil +end + +-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file +function UnixCompress.isCompress(b, o) +local p = o or 0 + return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D +end + +return UnixCompress +end +__FILES["codecs/compress/Xxh32"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content +-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. +-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). +-- +-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +local Xxh32 = {} + +local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 +local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 + +-- a * b mod 2^32 (a, b below 2^32) +local function mul(a, b) +local a0 = a % 65536 + local a1 = (a - a0) / 65536 + return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 +end + +local function rotl(x, r) +return bor(lshift(x, r), rshift(x, 32 - r)) +end + +local function round(acc, lane) +return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) +end + +-- hash(buf, offset?, length?, seed?) -> XXH32 +function Xxh32.hash(b, offset, length, seed) +local n0 = buffer.len(b) + local o = math.clamp(offset or 0, 0, n0) + local n = math.clamp(length or (n0 - o), 0, n0 - o) + local s = (seed or 0) % T32 + local p = o + local e = o + n + local h + if n >= 16 then + local v1 = (s + P1 + P2) % T32 + local v2 = (s + P2) % T32 + local v3 = s + local v4 = (s - P1) % T32 + local last = e - 16 + while p <= last do + v1 = round(v1, readu32(b, p)) + v2 = round(v2, readu32(b, p + 4)) + v3 = round(v3, readu32(b, p + 8)) + v4 = round(v4, readu32(b, p + 12)) + p =p+ 16 + end + h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32 + else + h = (s + P5) % T32 + end + h = (h + n) % T32 + while p + 4 <= e do + h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4) + p =p+ 4 + end + while p < e do + h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) + p =p+ 1 + end + h = mul(bxor(h, rshift(h, 15)), P2) + h = mul(bxor(h, rshift(h, 13)), P3) + return bxor(h, rshift(h, 16)) +end + +return Xxh32 +end +__FILES["codecs/compress/Zstd"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- 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("rosetta.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 = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("codecs/compress/Zstd/Decode") + +local Zstd = {} + +-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) + + + + + +Zstd.MAGIC = "\40\181\47\253" + +-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there +function Zstd.isFrame(buf, offset) +local o = offset or 0 + if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then + return false + end + local m = buffer.readu32(buf, o) + return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 +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, offset, length, opts) +local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes ~= nil and{opts.maxBytes }or{(2 ^ 30 +)})[1] if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) + end + 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.from(consumed, at, len) + end + if buffer.len(out) ~= len then + local r = buffer.create(len) + buffer.copy(r, 0, out, 0, len) + out = r + end + return out, consumed +end + +-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves +function Zstd.xxh64(buf, offset, length) +local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + return Decode.hash(buf, o, l) +end + +return Zstd +end +__FILES["codecs/compress/Zstd/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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). +-- +-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's +-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at +-- 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 = __include("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 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local MAGIC = 0xFD2FB528 +local BLOCK_MAX = 131072 + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ tables +-- literal length / match length codes: baseline, extra bits (index = code + 1) +local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } +local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } +local ML_BASE = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, +} +local ML_BITS = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } +local ML_DEFAULT = { + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, +} +local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } + +-- highest set bit of 1..2048 +local HB = table.create(2048, 0) +do + local v = 0 + for i = 1, 2048 do + if i >= lshift(2, v) then + v =v+ 1 + end + HB[i] = v + end +end + +-- ------------------------------------------------------------------------------------------------ bit readers +-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros +local function peek(b, s, o, n) +if n <= 0 then + return 0 + end + local lo = o - n + if lo >= 0 then + local byte = s + rshift(lo, 3) + local bl = blen(b) + if byte + 4 <= bl then + return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) + end + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < bl then + v =v+ readu8(b, byte + k) * m + end + m =m* 256 + end + return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) + end + if o <= 0 then + return 0 + end + return lshift(peek(b, s, o, o), -lo) +end + +-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty +local function streamBits(b, s, e) +if e <= s then + return -1 + end + local last = readu8(b, e - 1) + if last == 0 then + return -1 + end + return (e - 1 - s) * 8 + HB[last] +end + +-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros +local function getF(b, p, e, bp, n) +local byte = p + rshift(bp, 3) + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < e then + v =v+ readu8(b, byte + k) * m + end + m =m* 256 + end + return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ FSE +-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 +local symTmp = bcreate(512) + +-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +local function buildFse(norm, nsym, al, t) +local size = lshift(1, al) + local high = size - 1 + local next = table.create(nsym, 0) + for s = 0, nsym - 1 do + local c = norm[s + 1] + if c == -1 then + if high < 0 then + return nil, "bad FSE distribution" + end + writeu8(symTmp, high, s) + high =high- 1 + next[s + 1] = 1 + else + next[s + 1] = c + end + end + local pos = 0 + local step = rshift(size, 1) + rshift(size, 3) + 3 + local mask = size - 1 + for s = 0, nsym - 1 do + local c = norm[s + 1] + for _ = 1, c do + writeu8(symTmp, pos, s) + local guard = 0 + repeat + pos = band(pos + step, mask) + guard =guard+ 1 + until pos <= high or guard > size + if guard > size then + return nil, "bad FSE distribution" + end + end + end + if pos ~= 0 then + return nil, "bad FSE distribution" + end + for u = 0, size - 1 do + local s = readu8(symTmp, u) + local ns = next[s + 1] + if ns < 1 or ns > 2048 then + return nil, "bad FSE distribution" + end + next[s + 1] = ns + 1 + local nb = al - HB[ns] + if nb < 0 then + return nil, "bad FSE distribution" + end + writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) + end + return true, nil +end + +-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description +local function ncount(b, p, e, maxSym, maxAL, norm) +if p >= e then + return nil, "truncated FSE table" + end + local al = getF(b, p, e, 0, 4) + 5 + if al > maxAL then + return nil, "FSE accuracy log too large" + end + local bp = 4 + local remaining = lshift(1, al) + 1 + local threshold = lshift(1, al) + local nbBits = al + 1 + local sym = 0 + local prev0 = false + while remaining > 1 and sym <= maxSym do + if prev0 then + local n0 = sym + while true do + local v = getF(b, p, e, bp, 2) + bp =bp+ 2 + if v == 3 then + n0 =n0+ 3 + if n0 > maxSym or bp > (e - p) * 8 then + return nil, "bad FSE table" + end + else + n0 =n0+ v + break + end + end + if n0 > maxSym then + return nil, "bad FSE table" + end + while sym < n0 do + norm[sym + 1] = 0 + sym =sym+ 1 + end + end + local max = 2 * threshold - 1 - remaining + local count + local low = getF(b, p, e, bp, nbBits - 1) + if low < max then + count = low + bp =bp+ (nbBits - 1 +) else + count = getF(b, p, e, bp, nbBits) + if count >= threshold then + count =count- max + end + bp =bp+ nbBits + end + count =count- 1 + remaining =remaining- (count < 0 and{(-count )}or{count +})[1] if remaining < 1 then + return nil, "bad FSE table" + end + norm[sym + 1] = count + sym =sym+ 1 + prev0 = count == 0 + while remaining < threshold do + nbBits =nbBits- 1 + threshold = rshift(threshold, 1) + end + end + if remaining ~= 1 then + return nil, "bad FSE table" + end + local used = rshift(bp + 7, 3) + if p + used > e then + return nil, "truncated FSE table" + end + for s = sym, maxSym do + norm[s + 1] = 0 + end + return al, used, sym +end + +local function predefined(dist, al) +local t = bcreate(lshift(1, al) * 4) + buildFse(dist, #dist, al, t) + return t +end +local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) + +-- ------------------------------------------------------------------------------------------------ Huffman +-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +local weights = bcreate(256) +local wfse = bcreate(64 * 4) +local function hufTable(b, p, e, st) +if p >= e then + return nil, "truncated Huffman table" + end + local hdr = readu8(b, p) + local n = 0 + local used + if hdr >= 128 then + n = hdr - 127 + used = 1 + rshift(n + 1, 1) + if p + used > e then + return nil, "truncated Huffman table" + end + for i = 0, n - 1 do + local byte = readu8(b, p + 1 + rshift(i, 1)) + writeu8(weights, i, (band(i, 1) == 0 and{(rshift(byte, 4) )}or{(band(byte, 15))})[1]) + end + else + used = 1 + hdr + if p + used > e then + return nil, "truncated Huffman table" + end + local q, qe = p + 1, p + 1 + hdr + local norm = st.norm + local al, nb = ncount(b, q, qe, 255, 6, norm) + if not al then + return nil, nb + end + local ok, msg = buildFse(norm, 256, al, wfse) + if not ok then + return nil, msg + end + local ss = q + nb + local off = streamBits(b, ss, qe) + if off < 0 then + return nil, "bad Huffman weight stream" + end + local s1 = peek(b, ss, off, al) + off =off- al + local s2 = peek(b, ss, off, al) + off =off- al + while true do + if n > 254 then + return nil, "too many Huffman weights" + end + local e1 = readu32(wfse, s1 * 4) + writeu8(weights, n, band(e1, 255)) + n =n+ 1 + local k = band(rshift(e1, 8), 255) + s1 = rshift(e1, 16) + peek(b, ss, off, k) + off =off- k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) + n =n+ 1 + break + end + local e2 = readu32(wfse, s2 * 4) + writeu8(weights, n, band(e2, 255)) + n =n+ 1 + k = band(rshift(e2, 8), 255) + s2 = rshift(e2, 16) + peek(b, ss, off, k) + off =off- k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) + n =n+ 1 + break + end + end + end + -- the last weight is implied: the total must reach the next power of two + local total = 0 + for i = 0, n - 1 do + local w = readu8(weights, i) + if w > 11 then + return nil, "bad Huffman weight" + end + if w > 0 then + total =total+ lshift(1, w - 1) + end + end + if total == 0 or total >= 2048 then + return nil, "bad Huffman weights" + end + local maxBits = HB[total] + 1 + local rest = lshift(1, maxBits) - total + if band(rest, rest - 1) ~= 0 then + return nil, "bad Huffman weights" + end + writeu8(weights, n, HB[rest] + 1) + local nsym = n + 1 + -- codes: the longest first, in symbol order within a length + local rankCount = table.create(13, 0) + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w +do local __DARKLUA_VAR=bits + 1 rankCount[__DARKLUA_VAR]=rankCount[__DARKLUA_VAR]+ 1 +end end + end + local rankIdx = table.create(13, 0) + rankIdx[maxBits + 1] = 0 + for i = maxBits, 1, -1 do + rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) + end + if rankIdx[1] ~= lshift(1, maxBits) then + return nil, "bad Huffman weights" + end + local t = st.huf + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + local code = rankIdx[bits + 1] + local len = lshift(1, maxBits - bits) + local v = i + bits * 256 + for k = code, code + len - 1 do + writeu16(t, k * 2, v) + end + rankIdx[bits + 1] = code + len + end + end + st.hufBits = maxBits + return used, nil +end + +-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message +local function hufStream(b, s, e, t, mb, lit, dp, cnt) +local off = streamBits(b, s, e) + if off < 0 then + return "bad Huffman stream" + end + local mmask = lshift(1, mb) - 1 + local fastEnd = blen(b) - 4 + for k = dp, dp + cnt - 1 do + local lo = off - mb + local idx + if lo >= 0 then + local byte = s + rshift(lo, 3) + if byte <= fastEnd then + idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) + else + idx = peek(b, s, off, mb) + end + else + idx = peek(b, s, off, mb) + end + local v = readu16(t, idx * 2) + writeu8(lit, k, v) + off =off- rshift(v, 8) + end + if off ~= 0 then + return "Huffman stream size mismatch" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ frames +-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) +local function grow(st, need) +if need > st.maxBytes then + return false + end + local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) + local nb = bcreate(cap) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + return true +end + +-- a compressed block [p, e): nil (ok) | code, message +local function block(b, p, e, st) -- literals section + +local b0 = readu8(b, p) + local ltype = band(b0, 3) + local sf = band(rshift(b0, 2), 3) + local regen + local litSrc, litPos + local lit = st.lit + if ltype <= 1 then + if sf == 0 or sf == 2 then + regen = rshift(b0, 3) + p =p+ 1 + elseif sf == 1 then + if p + 2 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + p =p+ 2 + else + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 + p =p+ 3 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if ltype == 0 then + if p + regen > e then + return "TRUNCATED", "truncated raw literals" + end + litSrc, litPos = b, p + p =p+ regen + else + if p + 1 > e then + return "TRUNCATED", "truncated RLE literals" + end + bfill(lit, 0, readu8(b, p), regen) + litSrc, litPos = lit, 0 + p =p+ 1 + end + else + local csize + if sf <= 1 then + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 + regen = band(rshift(v, 4), 0x3FF) + csize = band(rshift(v, 14), 0x3FF) + p =p+ 3 + elseif sf == 2 then + if p + 4 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFF) + csize = rshift(v, 18) + p =p+ 4 + else + if p + 5 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFFF) + csize = rshift(v, 22) + readu8(b, p + 4) * 1024 + p =p+ 5 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if p + csize > e then + return "TRUNCATED", "truncated compressed literals" + end + local hs, he = p, p + csize + p = he + if ltype == 2 then + local used, herr = hufTable(b, hs, he, st) + if not used then + return "CORRUPT", herr + end + hs =hs+ used + elseif not st.hufBits then + return "CORRUPT", "treeless literals without a previous Huffman table" + end + local t, mb = st.huf, st.hufBits + if sf == 0 then + local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) + if herr then + return "CORRUPT", herr + end + else + if hs + 6 > he then + return "CORRUPT", "truncated jump table" + end + local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) + local s1 = hs + 6 + local s2 = s1 + l1 + local s3 = s2 + l2 + local s4 = s3 + l3 + if s4 > he then + return "CORRUPT", "bad jump table" + end + local seg = rshift(regen + 3, 2) + local last = regen - 3 * seg + if last < 0 then + return "CORRUPT", "bad 4-stream literals size" + end + local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) + or hufStream(b, s2, s3, t, mb, lit, seg, seg) + or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) + or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) + if herr then + return "CORRUPT", herr + end + end + litSrc, litPos = lit, 0 + end + + -- sequences section header + if p >= e then + return "TRUNCATED", "missing sequences header" + end + local nbSeq = readu8(b, p) + p =p+ 1 + if nbSeq >= 128 then + if nbSeq == 255 then + if p + 2 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = readu16(b, p) + 0x7F00 + p =p+ 2 + else + if p + 1 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = (nbSeq - 128) * 256 + readu8(b, p) + p =p+ 1 + end + end + local op = st.op + if nbSeq == 0 then + if p ~= e then + return "CORRUPT", "data after an empty sequences section" + end + if op + regen > blen(st.out) then + if not grow(st, op + regen) then + return "LIMIT", "output over the size limit" + end + end + bcopy(st.out, op, litSrc, litPos, regen) + st.op = op + regen + return nil, nil + end + if p >= e then + return "TRUNCATED", "missing compression modes" + end + local modes = readu8(b, p) + p =p+ 1 + if band(modes, 3) ~= 0 then + return "CORRUPT", "reserved bits set in compression modes" + end + -- the three tables, in the order LL, OF, ML + local tabs = st.tabs + for k = 1, 3 do + local mode = band(rshift(modes, 8 - 2 * k), 3) + local maxSym = k == 1 and 35 or(k == 2 and 31 or 52 +) local maxAL = k == 1 and 9 or(k == 2 and 8 or 9 +) if mode == 0 then + tabs[k] = (k == 1 and{LL_PRE }or{(k == 2 and{OF_PRE }or{ML_PRE +})[1]})[1] tabs[k + 3] = k == 2 and 5 or 6 + elseif mode == 1 then + if p >= e then + return "TRUNCATED", "truncated RLE table" + end + local sym = readu8(b, p) + p =p+ 1 + if sym > maxSym then + return "CORRUPT", "bad RLE symbol" + end + local t = st.rle[k] + writeu32(t, 0, sym) + tabs[k] = t + tabs[k + 3] = 0 + elseif mode == 2 then + local norm = st.norm + local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) + if not al then + return "CORRUPT", used + end + p =p+ used + local t = st.dyn[k] + local ok, msg = buildFse(norm, nsym , al, t) + if not ok then + return "CORRUPT", msg + end + tabs[k] = t + tabs[k + 3] = al + else + if not tabs[k] then + return "CORRUPT", "repeated table without a previous one" + end + end + end + local llT, ofT, mlT = tabs[1] , tabs[2] , tabs[3] +local llAL, ofAL, mlAL = tabs[4] , tabs[5] , tabs[6] + -- the sequences bitstream + +local s = p + local off = streamBits(b, s, e) + if off < 0 then + return "CORRUPT", "bad sequences bitstream" + end + local llS = peek(b, s, off, llAL) + off =off- llAL + local ofS = peek(b, s, off, ofAL) + off =off- ofAL + local mlS = peek(b, s, off, mlAL) + off =off- mlAL + local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 + local out = st.out + local cap = blen(out) + local frameStart = st.frameStart + local lp, litEnd = litPos, litPos + regen + local fastEnd = blen(b) - 4 + for i = 1, nbSeq do + local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) + local ofCode = band(ofE, 255) + local mlCode = band(mlE, 255) + 1 + local llCode = band(llE, 255) + 1 + -- offset bits, then match length bits, then literal length bits + local ofv + if ofCode > 24 then + local hiN = ofCode - 24 + local hi = peek(b, s, off, hiN) + off =off- hiN + ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) + off =off- 24 + elseif ofCode > 0 then + local lo = off - ofCode + local v + if lo >= 0 and s + rshift(lo, 3) <= fastEnd then + v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) + else + v = peek(b, s, off, ofCode) + end + off = lo + ofv = lshift(1, ofCode) + v + else + ofv = 1 + end + local ml = ML_BASE[mlCode] + local nb = ML_BITS[mlCode] + if nb > 0 then + ml =ml+ peek(b, s, off, nb) + off =off- nb + end + local ll = LL_BASE[llCode] + nb = LL_BITS[llCode] + if nb > 0 then + ll =ll+ peek(b, s, off, nb) + off =off- nb + end + -- repeat offsets + local offset + if ofv > 3 then + offset = ofv - 3 + rep3 = rep2 + rep2 = rep1 + rep1 = offset + else + local idx = ofv - 1 + if ll == 0 then + idx =idx+ 1 + end + if idx == 0 then + offset = rep1 + else + if idx == 1 then + offset = rep2 + elseif idx == 2 then + offset = rep3 + else + offset = rep1 - 1 + end + if idx > 1 then + rep3 = rep2 + end + rep2 = rep1 + rep1 = offset + end + end + -- state updates (not after the last sequence): LL, ML, OF + if i < nbSeq then + nb = band(rshift(llE, 8), 255) + llS = rshift(llE, 16) + peek(b, s, off, nb) + off =off- nb + nb = band(rshift(mlE, 8), 255) + mlS = rshift(mlE, 16) + peek(b, s, off, nb) + off =off- nb + nb = band(rshift(ofE, 8), 255) + ofS = rshift(ofE, 16) + peek(b, s, off, nb) + off =off- nb + end + -- execute + if lp + ll > litEnd then + return "CORRUPT", "literal length past the literals" + end + local need = op + ll + ml + if need > cap then + st.op = op + if not grow(st, need) then + return "LIMIT", "output over the size limit" + end + out = st.out + cap = blen(out) + end + if ll > 0 then + bcopy(out, op, litSrc, lp, ll) + op =op+ ll + lp =lp+ ll + end + if offset > op - frameStart or offset < 1 then + return "CORRUPT", "match offset before the frame start" + end + local from = op - offset + if offset >= ml then + bcopy(out, op, out, from, ml) + op =op+ ml + elseif offset == 1 then + bfill(out, op, readu8(out, from), ml) + op =op+ ml + else + -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) + local left = ml + while left > 0 do + local n = (left < offset and{left }or{offset +})[1] bcopy(out, op, out, from, n) + op =op+ n + from =from+ n + left =left- n + end + end + end + if off ~= 0 then + return "CORRUPT", "sequences bitstream size mismatch" + end + local rest = litEnd - lp + if rest > 0 then + if op + rest > cap then + st.op = op + if not grow(st, op + rest) then + return "LIMIT", "output over the size limit" + end + out = st.out + end + bcopy(out, op, litSrc, lp, rest) + op =op+ rest + end + st.op = op + st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 + return nil, nil +end + +-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset +function Decode.decompress(b, start, stop, maxBytes, verify) +local st= { + out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), + op = 0, + maxBytes = maxBytes, + lit = bcreate(BLOCK_MAX + 64), + huf = bcreate(2048 * 2), + hufBits = nil, + norm = table.create(256, 0), + tabs = {}, + rle = { bcreate(4), bcreate(4), bcreate(4) }, + dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, + frameStart = 0, + rep1 = 1, + rep2 = 4, + rep3 = 8, + } + local pos = start + local frames = 0 + if stop - start < 4 then + return nil, "TRUNCATED", "not a zstd stream (too short)", start + end + while pos < stop do +local __DARKLUA_CONTINUE_25=false repeat if pos + 4 > stop then + return nil, "TRUNCATED", "truncated frame magic", pos + end + local magic = readu32(b, pos) + if band(magic, 0xFFFFFFF0) == 0x184D2A50 then + if pos + 8 > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + local size = readu32(b, pos + 4) + if pos + 8 + size > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + pos =pos+ (8 + size +) frames =frames+ 1 +__DARKLUA_CONTINUE_25=true break + end + if magic ~= MAGIC then + return nil, "CORRUPT", frames == 0 and"bad magic" or"unknown data after frame " .. frames, pos + end + pos =pos+ 4 + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local fhd = readu8(b, pos) + pos =pos+ 1 + local fcsFlag = rshift(fhd, 6) + local single = band(fhd, 0x20) ~= 0 + if band(fhd, 8) ~= 0 then + return nil, "CORRUPT", "reserved frame header bit set", pos - 1 + end + local checksum = band(fhd, 4) ~= 0 + local didFlag = band(fhd, 3) + local didSize = didFlag == 3 and 4 or didFlag + local fcsSize = (fcsFlag == 0 and{(single and 1 or 0) }or{(lshift(1, fcsFlag) +)})[1] local hsize = (single and 0 or 1) + didSize + fcsSize + if pos + hsize > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local windowSize = 0 + if not single then + local wd = readu8(b, pos) + pos =pos+ 1 + local wlog = 10 + rshift(wd, 3) + if wlog > 41 then + return nil, "CORRUPT", "bad window size", pos - 1 + end + local base = 2 ^ wlog + windowSize = base + base / 8 * band(wd, 7) + end + local did = 0 + if didSize == 1 then + did = readu8(b, pos) + elseif didSize == 2 then + did = readu16(b, pos) + elseif didSize == 4 then + did = readu32(b, pos) + end + pos =pos+ didSize + if did ~= 0 then + return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize + end + local fcs = -1 + if fcsSize == 1 then + fcs = readu8(b, pos) + elseif fcsSize == 2 then + fcs = readu16(b, pos) + 256 + elseif fcsSize == 4 then + fcs = readu32(b, pos) + elseif fcsSize == 8 then + fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 + end + pos =pos+ fcsSize + if single then + windowSize = fcs + end + local blockMax = math.min(windowSize, BLOCK_MAX) + local frameStart = st.op + if fcs >= 0 then + if frameStart + fcs > st.maxBytes then + return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos + end + if frameStart + fcs > blen(st.out) then + grow(st, frameStart + fcs) + end + end + st.frameStart = frameStart + st.rep1, st.rep2, st.rep3 = 1, 4, 8 + st.hufBits = nil + table.clear(st.tabs) + -- blocks + local last = false + repeat + if pos + 3 > stop then + return nil, "TRUNCATED", "truncated block header", pos + end + local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 + last = band(bh, 1) ~= 0 + local btype = band(rshift(bh, 1), 3) + local bsize = rshift(bh, 3) + pos =pos+ 3 + if bsize > blockMax then + return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 + end + if btype == 0 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated raw block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bcopy(st.out, st.op, b, pos, bsize) + st.op =st.op+ bsize + pos =pos+ bsize + elseif btype == 1 then + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated RLE block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bfill(st.out, st.op, readu8(b, pos), bsize) + st.op =st.op+ bsize + pos =pos+ 1 + elseif btype == 2 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated compressed block", pos + end + if bsize == 0 then + return nil, "CORRUPT", "empty compressed block", pos + end + local code, msg = block(b, pos, pos + bsize, st) + if code then + return nil, code, msg, pos + end + pos =pos+ bsize + else + return nil, "CORRUPT", "reserved block type", pos - 3 + end + until last + local size = st.op - frameStart + if fcs >= 0 and size ~= fcs then + return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos + end + if checksum then + if pos + 4 > stop then + return nil, "TRUNCATED", "missing content checksum", pos + end + if verify then + local _, lo = Xxh64.hash(st.out, frameStart, size) + local want = readu32(b, pos) + if lo ~= want then + return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos + end + end + pos =pos+ 4 + end + frames =frames+ 1 +__DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break end end + return st.out, st.op, pos +end + +Decode.hash = Xxh64.hash + +return Decode +end +__FILES["codecs/compress/Zstd/Xxh64"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- 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). +local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 + +local P1H, P1L = 0x9E3779B1, 0x85EBCA87 +local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F +local P3H, P3L = 0x165667B1, 0x9E3779F9 +local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 +local P5H, P5L = 0x27D4EB2F, 0x165667C5 + +-- (ah, al) * (bh, bl) mod 2^64 +local function mul(ah, al, bh, bl) +local a0 = al % 65536 + local a1 = (al - a0) / 65536 + local b0 = bl % 65536 + local b1 = (bl - b0) / 65536 + local mid = a1 * b0 + a0 * b1 + local mid0 = mid % 65536 + local lo = a0 * b0 + mid0 * 65536 + local lo32 = lo % T32 + local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 + hi =hi+ ((a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) +) return hi % T32, lo32 +end + +local function add(ah, al, bh, bl) +local l = al + bl + local h = ah + bh + if l >= T32 then + l =l- T32 + h =h+ 1 + end + return h % T32, l +end + +-- rotl by r in 1..31 +local function rotl(h, l, r) +return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) +end + +local P1L0, P1L1 = P1L % 65536, math.floor(P1L / 65536 +)local P2L0, P2L1 = P2L % 65536, math.floor(P2L / 65536 +) +-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +local function round(ah, al, ih, il) +local a0 = il % 65536 + local a1 = (il - a0) / 65536 + local mid = a1 * P2L0 + a0 * P2L1 + local mid0 = mid % 65536 + local lo = a0 * P2L0 + mid0 * 65536 + local ml = lo % T32 + local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 + local l = al + ml + local h = ah + mh + if l >= T32 then + l =l- T32 + h =h+ 1 + end + h =h% T32 + -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) + local hb, lb = h % 2, l % 2 + local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 + a0 = rl % 65536 + a1 = (rl - a0) / 65536 + mid = a1 * P1L0 + a0 * P1L1 + mid0 = mid % 65536 + lo = a0 * P1L0 + mid0 * 65536 + ml = lo % T32 + mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 + return mh % T32, ml +end + +local function merge(hh, hl, vh, vl) +local rh, rl = round(0, 0, vh, vl) + hh, hl = bxor(hh, rh), bxor(hl, rl) + hh, hl = mul(hh, hl, P1H, P1L) + return add(hh, hl, P4H, P4L) +end + +local Xxh64 = {} + +-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) +function Xxh64.hash(b, offset, length) +local p = offset + local e = offset + length + local hh, hl = 0, 0 + if length >= 32 then + local v1h, v1l = add(P1H, P1L, P2H, P2L) + local v2h, v2l = P2H, P2L + local v3h, v3l = 0, 0 + local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) + local limit = e - 32 + while p <= limit do + v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) + v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) + v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) + v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) + p =p+ 32 + end + local ah, al = rotl(v1h, v1l, 1) + local bh, bl = rotl(v2h, v2l, 7) + hh, hl = add(ah, al, bh, bl) + bh, bl = rotl(v3h, v3l, 12) + hh, hl = add(hh, hl, bh, bl) + bh, bl = rotl(v4h, v4l, 18) + hh, hl = add(hh, hl, bh, bl) + hh, hl = merge(hh, hl, v1h, v1l) + hh, hl = merge(hh, hl, v2h, v2l) + hh, hl = merge(hh, hl, v3h, v3l) + hh, hl = merge(hh, hl, v4h, v4l) + else + hh, hl = P5H, P5L + end + 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 = rotl(hh, hl, 27) + hh, hl = mul(hh, hl, P1H, P1L) + hh, hl = add(hh, hl, P4H, P4L) + p =p+ 8 + 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 = rotl(hh, hl, 23) + hh, hl = mul(hh, hl, P2H, P2L) + hh, hl = add(hh, hl, P3H, P3L) + p =p+ 4 + 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 = rotl(hh, hl, 11) + hh, hl = mul(hh, hl, P1H, P1L) + p =p+ 1 + end + -- 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))) ) +hh, hl = mul(hh, hl, P3H, P3L) + hl = bxor(hl, hh) -- h ^= h >> 32 + return hh, hl +end + +return Xxh64 +end +__FILES["codecs/entropy/Huffman"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. +-- +-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream: +-- entry = symbol * 32 + length a code of `length` <= P bits +-- entry = offset * 32 (length 0) a link: index offset + the following S bits (subtable of 2^S entries) +-- entry = 0 no code (incomplete code set): the stream is corrupt +-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables +-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27. +-- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a +-- core/Bits reader. +-- +-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values. +-- Never throws: bad code sets return -1 / nil. +local Bits = __include("core/Bits") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local MAXLEN = 16 + +local Huffman = {} +Huffman.MAXLEN = MAXLEN + +-- 8-bit reversal +local REV = table.create(256, 0) +for i = 0, 255 do + local r, v = 0, i + for _ = 1, 8 do + r = r * 2 + v % 2 + v = math.floor(v / 2 +) end + REV[i + 1] = r +end + +-- reverse(code, len) -> the low len bits of code reversed (len <= 16) +local function reverse(code, len) +return rshift(bor(lshift(REV[band(code, 255) + 1], 8), REV[band(rshift(code, 8), 255) + 1]), 16 - len) +end +Huffman.reverse = reverse + +-- capacity(nsym, P, maxLen) -> the table entries (u32) needed for nsym symbols, primary width P, codes up to maxLen +function Huffman.capacity(nsym, P, maxLen) +return 2 ^ P + ((maxLen > P and((nsym * 2 ^ (maxLen - P) ))or(0))) +end + +local count = table.create(MAXLEN + 1, 0) +local nextc = table.create(MAXLEN + 1, 0) + +local function build(lens, off, n, tab, P, msb) +for i = 1, MAXLEN + 1 do + count[i] = 0 + end + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > MAXLEN then + return -1 + end +do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 +end end + count[1] = 0 + local left = 1 + local maxLen = 0 + for l = 1, MAXLEN do + left = left * 2 - count[l + 1] + if left < 0 then + return -1 + end + if count[l + 1] > 0 then + maxLen = l + end + end + local code = 0 + for l = 1, MAXLEN do + code = (code + count[l]) * 2 + nextc[l] = code + end + local psize = lshift(1, P) + bfill(tab, 0, 0, psize * 4) + local S = (maxLen > P and((maxLen - P ))or(0 +)) local ssize = lshift(1, S) + local nextSub = psize + for s = 0, n - 1 do + local l = readu8(lens, off + s) + if l > 0 then + local c = nextc[l] + nextc[l] = c + 1 + local entry = s * 32 + l + if l <= P then + if msb then + -- the code is the top l bits of the P-bit index: fill every completion of the low bits + local first = lshift(c, P - l) + local last = first + lshift(1, P - l) - 1 + for i = first, last do + writeu32(tab, i * 4, entry) + end + else + local step = lshift(1, l) + local i = reverse(c, l) + while i < psize do + writeu32(tab, i * 4, entry) + i =i+ step + end + end + else + local pre, rest + if msb then + pre = rshift(c, l - P) + rest = band(c, lshift(1, l - P) - 1) + else + local rev = reverse(c, l) + pre = band(rev, psize - 1) + rest = rshift(rev, P) + end + local e = readu32(tab, pre * 4) + local sub + if e == 0 then + sub = nextSub + nextSub =nextSub+ ssize + bfill(tab, sub * 4, 0, ssize * 4) + writeu32(tab, pre * 4, sub * 32) + else + sub = rshift(e, 5) + end + local k = l - P -- bits of the code in the subtable index + if msb then + local first = lshift(rest, S - k) + for i = first, first + lshift(1, S - k) - 1 do + writeu32(tab, (sub + i) * 4, entry) + end + else + local step = lshift(1, k) + local i = rest + while i < ssize do + writeu32(tab, (sub + i) * 4, entry) + i =i+ step + end + end + end + end + end + return S +end + +-- buildLsb(lens, off, n, tab, P) -> S: a table for the code lengths lens[off .. off + n - 1] (u8), indexed by the next +-- P bits LSB-first (bit-reversed codes). S = the subtable width (0 when no code is longer than P), -1 = an +-- over-subscribed or invalid code set. tab must hold capacity(n, P, maxLen) u32 entries. +function Huffman.buildLsb(lens, off, n, tab, P) +return build(lens, off, n, tab, P, false) +end + +-- buildMsb(lens, off, n, tab, P) -> S: the same, indexed by the next P bits MSB-first +function Huffman.buildMsb(lens, off, n, tab, P) +return build(lens, off, n, tab, P, true) +end + +-- decodeLsb(br, tab, P, S) -> symbol, or -1 for an invalid code (br: a core/Bits LSB reader) +function Huffman.decodeLsb(br, tab, P, S) +local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + rshift(idx, P)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- decodeMsb(br, tab, P, S) -> symbol, or -1 (br: a core/Bits MSB reader) +function Huffman.decodeMsb(br, tab, P, S) +local e = readu32(tab, br:peek(P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + local idx = br:peek(P + S) + e = readu32(tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + br:skip(l) + return rshift(e, 5) +end + +-- codes(lengths) -> canonical code values (MSB-first, as written by an MSB writer; reverse() them for LSB streams). +-- lengths: { number } indexed 1..n (symbol + 1), 0 = unused. +function Huffman.codes(lengths) +local cnt = table.create(MAXLEN + 1, 0) + for _, l in __iter(lengths) do + if l > 0 then +do local __DARKLUA_VAR=l + 1 cnt[__DARKLUA_VAR]=cnt[__DARKLUA_VAR]+ 1 +end end + end + local nxt = table.create(MAXLEN + 1, 0) + local code = 0 + for l = 1, MAXLEN do + code = (code + cnt[l]) * 2 + nxt[l + 1] = code + end + local out = table.create(#lengths, 0) + for i, l in __iter(lengths) do + if l > 0 then + out[i] = nxt[l + 1] +do local __DARKLUA_VAR=l + 1 nxt[__DARKLUA_VAR]=nxt[__DARKLUA_VAR]+ 1 +end end + end + return out +end + +-- lengths(freqs, maxLen) -> code lengths ({ number }, same indexing as freqs), at most maxLen bits, optimal without +-- the limit; over the limit, the JPEG Annex K.3 adjustment. A single used symbol gets length 1. +function Huffman.lengths(freqs, maxLen) +local n = #freqs + local out = table.create(n, 0) + -- leaves sorted by frequency (ties by symbol, for determinism) + local syms = {} + for i = 1, n do + if freqs[i] > 0 then + table.insert(syms, i) + end + end + if #syms == 0 then + return out + end + if #syms == 1 then + out[syms[1] ] = 1 + return out + end + table.sort(syms, function(a, b) +if freqs[a] ~= freqs[b] then + return freqs[a] < freqs[b] + end + return a < b + end) + -- two-queue Huffman: leaves (sorted) and internal nodes (created in increasing weight order) + local m = #syms + local weight = table.create(2 * m, 0) + local parent = table.create(2 * m, 0) + for i = 1, m do + weight[i] = freqs[syms[i] ] + end + local li, ni, nn = 1, m + 1, m + 1 -- next leaf, next internal node to take, next free node + local function take() +if li <= m and (ni >= nn or weight[li] <= weight[ni]) then + li =li+ 1 + return li - 1 + end + ni =ni+ 1 + return ni - 1 + end + for _ = 1, m - 1 do + local a = take() + local b = take() + weight[nn] = weight[a] + weight[b] + parent[a] = nn + parent[b] = nn + nn =nn+ 1 + end + -- depths: the root is nn - 1 + local depth = table.create(2 * m, 0) + for i = nn - 2, 1, -1 do + depth[i] = depth[parent[i] ] + 1 + end + -- count codes per length; limit (JPEG K.3: move pairs from the deepest level up) + local bl = table.create(m + maxLen + 2, 0) + local deepest = 0 + for i = 1, m do +do local __DARKLUA_VAR=depth[i] bl[__DARKLUA_VAR]=bl[__DARKLUA_VAR]+ 1 +end deepest = math.max(deepest, depth[i]) + end + for l = deepest, maxLen + 1, -1 do + while bl[l] > 0 do + local j = l - 2 + while j > 0 and bl[j] == 0 do + j =j- 1 + end + bl[l]=bl[l]- 2 +do local __DARKLUA_VAR=l - 1 bl[__DARKLUA_VAR]=bl[__DARKLUA_VAR]+ 1 +end do local __DARKLUA_VAR0=j + 1 bl[__DARKLUA_VAR0]=bl[__DARKLUA_VAR0]+ 2 +end bl[j]=bl[j]- 1 + end + end + -- the longest codes go to the least frequent symbols (syms is sorted ascending) + local k = 1 + for l = math.min(deepest, maxLen), 1, -1 do + for _ = 1, bl[l] do + out[syms[k] ] = l + k =k+ 1 + end + end + return out +end + +return Huffman +end +__FILES["codecs/entropy/RangeCoder"] = function() +--!strict +-- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt): +-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and +-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code). +-- +-- local RD = require("rosetta.codecs.entropy.RangeCoder.Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ... +-- local RE = require("rosetta.codecs.entropy.RangeCoder.Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done +local RangeCoder = { + Decoder = __include("codecs/entropy/RangeCoder/Decoder"), + Encoder = __include("codecs/entropy/RangeCoder/Encoder"), +} + +return RangeCoder +end +__FILES["codecs/entropy/RangeCoder/Decoder"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus +-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice +-- backwards. +-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52. +local RangeDecoder = {} + + + + + + + + + + + + + + + + + +local SYM_BITS = 8 +local CODE_BITS = 32 +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_EXTRA = 7 -- (CODE_BITS - 2) % SYM_BITS + 1 +local SYM_MAX = 255 +local UINT_BITS = 8 +local WINDOW_SIZE = 32 + +local countlz = bit32.countlz +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8 = buffer.readu8 + +local function ilog(x) +return 32 - countlz(x) +end +RangeDecoder.ilog = ilog + +local function normalize(d) + local rng, val, rem = d.rng, d.val, d.rem + while rng <= CODE_BOT do + d.nbits_total =d.nbits_total+ SYM_BITS + rng = rng * 256 + local sym = rem + local offs = d.offs + if offs < d.storage then + rem = readu8(d.buf, d.base + offs) + d.offs = offs + 1 + else + rem = 0 + end + sym = rshift(bor(lshift(sym, 8), rem), SYM_BITS - CODE_EXTRA) -- (sym << 8 | rem) >> 1 + val = band(val * 256 + band(SYM_MAX, bit32.bnot(sym)), CODE_TOP - 1) + end + d.rng, d.val, d.rem = rng, val, rem +end + +function RangeDecoder.new(buf, base, storage) +local d= { + buf = buf, + base = base, + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = CODE_BITS + 1 - (math.floor((CODE_BITS - CODE_EXTRA) / SYM_BITS)) * SYM_BITS, + rng = 128, -- 1 << CODE_EXTRA + val = 0, + rem = 0, + ext = 0, + error = 0, + } + local rem = 0 + if storage > 0 then + rem = readu8(buf, base) + d.offs = 1 + end + d.rem = rem + d.val = d.rng - 1 - rshift(rem, SYM_BITS - CODE_EXTRA) + normalize(d) + return d +end + +-- ec_decode: the cumulative frequency of the next symbol, for a total of ft +function RangeDecoder.decode(d, ft) +local ext = math.floor(d.rng / ft +) d.ext = ext + local s = math.floor(d.val / ext +) return ft - math.min(s + 1, ft) +end + +function RangeDecoder.decodeBin(d, bits) +local ext = rshift(d.rng, bits) + d.ext = ext + local s = math.floor(d.val / ext +) local ft = lshift(1, bits) + return ft - math.min(s + 1, ft) +end + +function RangeDecoder.update(d, fl, fh, ft) + local s = d.ext * (ft - fh) + d.val = band(d.val - s, 0xFFFFFFFF) -- uint32 wrap (corrupt streams only) + if fl > 0 then + d.rng = d.ext * (fh - fl) + else + d.rng =d.rng- s + end + normalize(d) +end + +function RangeDecoder.bitLogp(d, logp) +local r = d.rng + local v = d.val + local s = rshift(r, logp) + local ret = v < s + if ret then + d.rng = s + else + d.val = v - s + d.rng = r - s + end + normalize(d) + return ret +end + +-- ec_dec_icdf over a Luau array (1-based) starting at index `off` (icdf[off] is entry 0) +function RangeDecoder.icdf(d, icdf, off, ftb) +local s = d.rng + local v = d.val + local r = rshift(s, ftb) + local ret = -1 + local t + repeat + t = s + ret =ret+ 1 + s = r * icdf[off + ret] + until v >= s + d.val = v - s + d.rng = t - s + normalize(d) + return ret +end + +function RangeDecoder.bits(d, bits) +local window = d.end_window + local available = d.nend_bits + if available < bits then + repeat + local b = 0 + local eo = d.end_offs + if eo < d.storage then + eo =eo+ 1 + d.end_offs = eo + b = readu8(d.buf, d.base + d.storage - eo) + end + window = bor(window, lshift(b, available)) + available =available+ SYM_BITS + until available > WINDOW_SIZE - SYM_BITS + end + local ret = band(window, lshift(1, bits) - 1) + if bits == 32 then + ret = window + end + window = rshift(window, bits) + available =available- bits + d.end_window = window + d.nend_bits = available + d.nbits_total =d.nbits_total+ bits + return ret +end + +function RangeDecoder.uint(d, ft0) +local ft = ft0 - 1 + local ftb = ilog(ft) + if ftb > UINT_BITS then + ftb =ftb- UINT_BITS + local ft1 = rshift(ft, ftb) + 1 + local s = RangeDecoder.decode(d, ft1) + RangeDecoder.update(d, s, s + 1, ft1) + local t = bor(lshift(s, ftb), RangeDecoder.bits(d, ftb)) + if t <= ft then + return t + end + d.error = 1 + return ft + else + local s = RangeDecoder.decode(d, ft0) + RangeDecoder.update(d, s, s + 1, ft0) + return s + end +end + +function RangeDecoder.tell(d) +return d.nbits_total - ilog(d.rng) +end + +local correction = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeDecoder.tellFrac(d) +local nbits = d.nbits_total * 8 + local l = ilog(d.rng) + local r = rshift(d.rng, l - 16) + local b = rshift(r, 12) - 8 + if r > correction[b + 1] then + b =b+ 1 + end + return nbits - (l * 8 + b) +end + +return RangeDecoder +end +__FILES["codecs/entropy/RangeCoder/Encoder"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD: +-- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded +-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain +-- numbers. Never throws: running out of room sets `error`. +local RangeEncoder = {} + + + + + + + + + + + + + + + + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +local function ilog(x) +return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes +function RangeEncoder.new(storage) +return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +local function writeByte(e, v) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs =e.offs+ 1 +end + +local function writeByteAtEnd(e, v) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs =e.end_offs+ 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +local function carryOut(e, c) + if c ~= SYM_MAX then + local carry = c >= 256 and 1 or 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext =e.ext- 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext =e.ext+ 1 + end +end + +local function normalize(e) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng =e.rng* 256 + e.nbits_total =e.nbits_total+ 8 + end +end + +-- encode(fl, fh, ft): the symbol [fl, fh) of ft +function RangeEncoder.encode(e, fl, fh, ft) + local r = floor(e.rng / ft) + if fl > 0 then + e.val =e.val+ (e.rng - r * (ft - fl) +) e.rng = r * (fh - fl) + else + e.rng =e.rng- r * (ft - fh) + end + normalize(e) +end + +-- encodeBin(fl, fh, bits): ft = 2^bits +function RangeEncoder.encodeBin(e, fl, fh, bits) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val =e.val+ (e.rng - r * (ft - fl) +) e.rng = r * (fh - fl) + else + e.rng =e.rng- r * (ft - fh) + end + normalize(e) +end + +-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp +function RangeEncoder.bitLogp(e, v, logp) + local r = e.rng + local s = floor(r / 2 ^ logp) + r =r- s + if v then + e.val =e.val+ r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total +function RangeEncoder.icdf(e, s, icdf, ftb) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val =e.val+ (e.rng - r * icdf[s] +) e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng =e.rng- r * icdf[s + 1] + end + normalize(e) +end + +-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame +function RangeEncoder.bits(e, fl, n) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used =used- 8 + until used < 8 + end + window =window+ fl * 2 ^ used + used =used+ n + e.end_window = window + e.nend_bits = used + e.nbits_total =e.nbits_total+ n +end + +-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 +function RangeEncoder.uint(e, fl, ft) + ft =ft- 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb =ftb- 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +function RangeEncoder.tell(e) +return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeEncoder.tellFrac(e) +local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b =b+ 1 + end + return nbits - (l * 8 + b) +end + +-- done(): flush; the frame is e.buf (storage bytes) +function RangeEncoder.done(e) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l =l+ 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l =l- 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used =used- 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder +end +__FILES["codecs/font/Bitmap"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike +-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels +-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's +-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored, +-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an +-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row +-- packing every bitmap font format shares. New code. +-- +-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } }) +-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized +-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255 +-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer) +-- +-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0). +local Err = __include("core/Err") +local Types = __include("Types") + +local Bitmap = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ bits +-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left +-- pixel unless lsbFirst); bytes past the end of buf read as 0 +function Bitmap.unpack(b, off, w, h, stride, lsbFirst) +local out = buffer.create(math.max(0, w * h)) + local n = buffer.len(b) + for y = 0, h - 1 do + local row = off + y * stride + for x = 0, w - 1 do + local p = row + bit32.rshift(x, 3) + if p >= 0 and p < n then + local byte = readu8(b, p) + local bitn = (lsbFirst and{(bit32.band(x, 7) )}or{(7 - bit32.band(x, 7) +)})[1] if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then + writeu8(out, y * w + x, 255) + end + end + end + end + return out +end + +-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on +function Bitmap.pack(px, w, h, stride, lsbFirst) +local s = stride or math.ceil(w / 8) + local out = buffer.create(math.max(0, s * h)) + local n = buffer.len(px) + for y = 0, h - 1 do + for x = 0, w - 1 do + local i = y * w + x + if i < n and readu8(px, i) >= 128 then + local p = y * s + bit32.rshift(x, 3) + local bitn = (lsbFirst and{(bit32.band(x, 7) )}or{(7 - bit32.band(x, 7) +)})[1] writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn))) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ font +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self, cp) +return self._index[cp] or 0 +end + +function Face.advance(self, g) +local gl = self.bitmap.glyphs[g + 1] + return (gl and{gl.advance }or{0 +})[1]end + +function Face.kern(_self, _a, _b) +return 0 +end + +function Face.outline(_self, _g) +return nil +end + +-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size) +function Face.rasterize(self, g, px) +local gl= self.bitmap.glyphs[g + 1] + if not gl or gl.width < 0 or gl.height < 0 then + return nil + end + local img = Types.Image.new(gl.width, gl.height, "alpha8") + local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels)) + if n > 0 then + buffer.copy(img.pixels, 0, gl.pixels, 0, n) + end + img.meta.left = gl.left + img.meta.top = gl.top + img.meta.advance = gl.advance + img.meta.glyph = g + img.meta.scale = (type(px) == "number" and self.bitmap.size > 0 and((px / self.bitmap.size ))or(1 +)) return img +end + +-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike) +function Bitmap.font(strike, info, meta) +local index= {} + for i, gl in __iter(strike.glyphs) do + local cp = gl.codepoint + if cp and index[cp] == nil then + index[cp] = i - 1 + end + end + if strike.map then + for cp, g in __iter(strike.map) do + if index[cp] == nil and g >= 0 and g < #strike.glyphs then + index[cp] = g + end + end + end + local f = setmetatable({ + kind = "font", + info = info or {}, + unitsPerEm = strike.size, + ascent = strike.ascent, + descent = -strike.descent, + lineGap = 0, + numGlyphs = #strike.glyphs, + bitmap = strike, + meta = meta or {}, + _index = index, + }, Face) + if strike.default then + setmetatable(index, { __index = function() + return strike.default + end }) + end + return f +end +-- ------------------------------------------------------------------------------------------------ strike + + + + + + + +local function codepoints(chars) +if type(chars) == "table" then + return chars + end + local out = {} + if type(chars) == "string" then + for _, c in __iter(utf8.codes(chars)) do + table.insert(out, c) + end + return out + end + for c = 32, 126 do + table.insert(out, c) + end + return out +end + +-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px +function Bitmap.strike(font, opts) +if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then + return font.bitmap, nil + end + if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "font has no glyphs to rasterize") + end + local o= opts or {} + local px = o.px or 16 + if type(px) ~= "number" or px < 1 or px > 1024 then + return nil, Err.new(Err.ARG, "px must be 1..1024") + end + local threshold = o.threshold or 128 + local upm = (type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 and{font.unitsPerEm }or{px +})[1] local scale = px / upm + local ascent = math.ceil((font.ascent or upm) * scale) + local descent = math.ceil(math.abs(font.descent or 0) * scale) + local glyphs= {} + local function add(cp, g) + local ok, img = pcall(font.rasterize, font, g, px) + local adv = 0 + local aok, a = pcall(font.advance, font, g) + if aok and type(a) == "number" then + adv = math.floor(a * scale + 0.5) + end + local gl= { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) } + if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then + local n = img.width * img.height + local pxs = buffer.create(n) + for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do + if readu8(img.pixels, i) >= threshold then + writeu8(pxs, i, 255) + end + end + gl.width, gl.height, gl.pixels = img.width, img.height, pxs + gl.left = math.floor(img.meta.left or 0) + gl.top = math.floor(img.meta.top or 0) + if type(img.meta.advance) == "number" then + gl.advance = math.floor(img.meta.advance + 0.5) + end + end + table.insert(glyphs, gl) + end + add(nil, 0) + for _, cp in __iter(codepoints(o.chars)) do + local ok, g = pcall(font.glyphIndex, font, cp) + if ok and type(g) == "number" and g > 0 then + add(cp, g) + end + end + return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil +end + +return Bitmap +end +__FILES["codecs/font/Cff"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts +-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed +-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands +-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26 +-- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked, +-- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage +-- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll). +-- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting. +-- +-- local cff, err = Cff.parse(buf, offset, length) +-- local cmds, err = Cff.outline(cff, glyphIndex) +-- +-- Never throws: malformed data returns nil, message. +local Cff = {} + +local readu8 = buffer.readu8 +local blen = buffer.len + +local function u8(b, o) +if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function uN(b, o, n) +local v = 0 + for i = 0, n - 1 do + v = v * 256 + u8(b, o + i) + end + return v +end + +-- INDEX at absolute offset p (within [base, limit)) -> Index | nil + + + + + + + + + + + + + + + +local function index(b, p, limit) +if p + 2 > limit then + return nil + end + local count = uN(b, p, 2) + if count == 0 then + return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 } + end + local offSize = u8(b, p + 2) + if offSize < 1 or offSize > 4 then + return nil + end + local offsets = p + 3 + local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based + if data + 1 > limit then + return nil + end + local last = uN(b, offsets + count * offSize, offSize) + if data + last > limit then + return nil + end + return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last } +end + +-- item(idx, i) -> absolute start, length (nil when out of range / corrupt) +local function item(b, idx, i) +if i < 0 or i >= idx.count then + return nil, 0 + end + local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize) + local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize) + if s < 1 or e < s or idx.data + e > idx.next then + return nil, 0 + end + return idx.data + s, e - s +end +Cff.item = item + +-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte) +local function dict(b, p, n) +local out= {} + local ops= {} + local e = p + n + while p < e do + local b0 = u8(b, p) + if b0 <= 21 then + local op = b0 + p =p+ 1 + if b0 == 12 then + op = 1200 + u8(b, p) + p =p+ 1 + end + out[op] = ops + ops = {} + elseif b0 == 28 then + local v = uN(b, p + 1, 2) + table.insert(ops, (v >= 32768 and((v - 65536 ))or(v))) + p =p+ 3 + elseif b0 == 29 then + local v = uN(b, p + 1, 4) + table.insert(ops, (v >= 2147483648 and((v - 4294967296 ))or(v))) + p =p+ 5 + elseif b0 == 30 then -- real number: BCD nibbles + local s = {} + p =p+ 1 + local done = false + while p < e and not done do + local byte = u8(b, p) + p =p+ 1 + for _, nib in __iter({ math.floor(byte / 16), byte % 16 }) do + if nib <= 9 then + table.insert(s, tostring(nib)) + elseif nib == 10 then + table.insert(s, ".") + elseif nib == 11 then + table.insert(s, "E") + elseif nib == 12 then + table.insert(s, "E-") + elseif nib == 14 then + table.insert(s, "-") + elseif nib == 15 then + done = true + break + end + end + end + table.insert(ops, tonumber(table.concat(s)) or 0) + elseif b0 >= 32 and b0 <= 246 then + table.insert(ops, b0 - 139) + p =p+ 1 + elseif b0 >= 247 and b0 <= 250 then + table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108) + p =p+ 2 + elseif b0 >= 251 and b0 <= 254 then + table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108) + p =p+ 2 + else + p =p+ 1 -- reserved + end + if #ops > 48 then + return out + end + end + return out +end + +local function privateSubrs(b, base, limit, d) +local pr = d[18] + if not pr or #pr < 2 then + return nil + end + local size, off = pr[1], pr[2] + local ps = base + off + if size < 0 or off < 0 or ps + size > limit then + return nil + end + local pd = dict(b, ps, size) + local s = pd[19] + if not s or #s < 1 then + return nil + end + return index(b, ps + s[1], limit) +end + +-- parse(buf, offset, length) -> Font | nil, message +function Cff.parse(b, offset, length) +local base, limit = offset, math.min(offset + length, blen(b)) + if limit - base < 4 then + return nil, "truncated CFF header" + end + local major, hdrSize = u8(b, base), u8(b, base + 2) + if major == 2 then + return nil, "unsupported: CFF2 (variable font outlines)" + end + if major ~= 1 then + return nil, "bad CFF version " .. major + end + local names = index(b, base + hdrSize, limit) + if not names then + return nil, "bad name INDEX" + end + local tops = index(b, names.next, limit) + if not tops or tops.count < 1 then + return nil, "bad Top DICT INDEX" + end + local strings = index(b, tops.next, limit) + if not strings then + return nil, "bad String INDEX" + end + local gsubrs = index(b, strings.next, limit) + if not gsubrs then + return nil, "bad global subrs INDEX" + end + local ts, tl = item(b, tops, 0) + if not ts then + return nil, "bad Top DICT" + end + local top = dict(b, ts, tl) + local cso = top[17] + if not cso or #cso < 1 then + return nil, "no CharStrings" + end + local cst = top[1206] + if cst and cst[1] ~= 2 then + return nil, "unsupported: charstring type " .. tostring(cst[1]) + end + local charStrings = index(b, base + cso[1], limit) + if not charStrings then + return nil, "bad CharStrings INDEX" + end + local f= { + buf = b, + base = base, + limit = limit, + charStrings = charStrings, + gsubrs = gsubrs, + subrs = nil, + fdSubrs = nil, + fdSelect = nil, + numGlyphs = charStrings.count, + cid = top[1230] ~= nil, + fontMatrix = top[1207], + } + if f.cid then + local fda, fds = top[1236], top[1237] + if not fda or not fds then + return nil, "CID font without FDArray / FDSelect" + end + local fdArray = index(b, base + fda[1], limit) + if not fdArray then + return nil, "bad FDArray" + end + local list= {} + for i = 0, math.min(fdArray.count, 256) - 1 do + local s, l = item(b, fdArray, i) + list[i + 1] = (s and{(privateSubrs(b, base, limit, dict(b, s, l)) )}or{nil +})[1] end + f.fdSubrs = list + f.fdSelect = base + fds[1] + else + f.subrs = privateSubrs(b, base, limit, top) + end + return f, nil +end + +local function bias(count) +return count < 1240 and 107 or(count < 33900 and 1131 or 32768 +)end + +-- the local subrs of glyph g (CID fonts: through FDSelect) +local function localSubrs(f, g) +if not f.cid then + return f.subrs + end + local b, p = f.buf, f.fdSelect +local fmt = u8(b, p) + local fd = -1 + if fmt == 0 then + fd = u8(b, p + 1 + g) + elseif fmt == 3 then + local n = uN(b, p + 1, 2) + local first = uN(b, p + 3, 2) + for i = 0, n - 1 do + local q = p + 5 + i * 3 + local v = u8(b, q) + local nxt = uN(b, q + 1, 2) + if g >= first and g < nxt then + fd = v + break + end + first = nxt + end + end + local list = f.fdSubrs +return list[fd + 1] +end + +local BUDGET = 200000 -- operators per glyph (subroutine bombs) + +-- outline(f, g) -> path commands | nil, message +function Cff.outline(f, g) +local b = f.buf + local p, len = item(b, f.charStrings, g) + if not p then + return nil, "bad glyph index " .. tostring(g) + end + local e = p + len + local cmds= {} + local s= table.create(48, 0) -- operand stack, 1-based; sp = count + local sp = 0 + local trans = (table.create(32, 0) ) +local x, y = 0, 0 + local open = false + local maskbits = 0 + local inHeader = true + local stack= {} -- return addresses { p, e } + local subrs= nil + local haveSubrs = false + local ops = 0 + local seed = 12345 + + local function moveTo(dx, dy) + if open then + table.insert(cmds, { op = "close" }) + end + x =x+ dx + y =y+ dy + table.insert(cmds, { op = "moveTo", x, y }) + open = true + end + local function lineTo(dx, dy) + if not open then + moveTo(0, 0) + end + x =x+ dx + y =y+ dy + table.insert(cmds, { op = "lineTo", x, y }) + end + local function curveTo(dx1, dy1, dx2, dy2, dx3, dy3) + if not open then + moveTo(0, 0) + end + local x1, y1 = x + dx1, y + dy1 + local x2, y2 = x1 + dx2, y1 + dy2 + x, y = x2 + dx3, y2 + dy3 + table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y }) + end + local function S(i) +return s[i + 1] or 0 + end + + while true do +local __DARKLUA_CONTINUE_7=false repeat if p >= e then + -- the end of a subroutine without return, or of the charstring without endchar + if #stack > 0 then + local r = (table.remove(stack) ) +p, e = r[1], r[2] +__DARKLUA_CONTINUE_7=true break + end + break + end + ops =ops+ 1 + if ops > BUDGET then + return nil, "charstring too long (subroutine loop?)" + end + local b0 = u8(b, p) + p =p+ 1 + local clear = true + local i = 0 + if b0 == 19 or b0 == 20 then -- hintmask, cntrmask + if inHeader then + maskbits =maskbits+ math.floor(sp / 2 +) end + inHeader = false + p =p+ math.floor((maskbits + 7) / 8 +) elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm + maskbits =maskbits+ math.floor(sp / 2 +) elseif b0 == 21 then -- rmoveto + inHeader = false + if sp < 2 then + return nil, "rmoveto stack" + end + moveTo(S(sp - 2), S(sp - 1)) + elseif b0 == 4 then -- vmoveto + inHeader = false + if sp < 1 then + return nil, "vmoveto stack" + end + moveTo(0, S(sp - 1)) + elseif b0 == 22 then -- hmoveto + inHeader = false + if sp < 1 then + return nil, "hmoveto stack" + end + moveTo(S(sp - 1), 0) + elseif b0 == 5 then -- rlineto + if sp < 2 then + return nil, "rlineto stack" + end + while i + 1 < sp do + lineTo(S(i), S(i + 1)) + i =i+ 2 + end + elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate + if sp < 1 then + return nil, "hlineto stack" + end + local horiz = b0 == 6 + while i < sp do + if horiz then + lineTo(S(i), 0) + else + lineTo(0, S(i)) + end + horiz = not horiz + i =i+ 1 + end + elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate + if sp < 4 then + return nil, "hvcurveto stack" + end + local horiz = b0 == 31 + while i + 3 < sp do + local last = (sp - i == 5 and{(S(i + 4) )}or{0 +})[1] if horiz then + curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3)) + else + curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last) + end + horiz = not horiz + i =i+ 4 + end + elseif b0 == 8 then -- rrcurveto + if sp < 6 then + return nil, "rrcurveto stack" + end + while i + 5 < sp do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i =i+ 6 + end + elseif b0 == 24 then -- rcurveline + if sp < 8 then + return nil, "rcurveline stack" + end + while i + 5 < sp - 2 do + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + i =i+ 6 + end + lineTo(S(i), S(i + 1)) + elseif b0 == 25 then -- rlinecurve + if sp < 8 then + return nil, "rlinecurve stack" + end + while i + 1 < sp - 6 do + lineTo(S(i), S(i + 1)) + i =i+ 2 + end + curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5)) + elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto + if sp < 4 then + return nil, "vv/hhcurveto stack" + end + local f0 = 0 + if sp % 2 == 1 then + f0 = S(0) + i = 1 + end + while i + 3 < sp do + if b0 == 27 then + curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0) + else + curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3)) + end + f0 = 0 + i =i+ 4 + end + elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr + if b0 == 10 and not haveSubrs then + subrs = localSubrs(f, g) + haveSubrs = true + end + if sp < 1 then + return nil, "callsubr stack" + end + local idx = (b0 == 10 and{subrs }or{f.gsubrs +})[1] if not idx then + return nil, "no subroutines" + end + local n = math.floor(S(sp - 1)) + bias(idx.count) + sp =sp- 1 + if #stack >= 10 then + return nil, "subroutine recursion limit" + end + local sp0, sl = item(b, idx, n) + if not sp0 then + return nil, "subroutine " .. n .. " not found" + end + table.insert(stack, { p, e }) + p, e = sp0, sp0 + sl + clear = false + elseif b0 == 11 then -- return + if #stack == 0 then + return nil, "return outside a subroutine" + end + local r = (table.remove(stack) ) +p, e = r[1], r[2] + clear = false + elseif b0 == 14 then -- endchar + if open then + table.insert(cmds, { op = "close" }) + end + return cmds, nil + elseif b0 == 12 then -- escape + local b1 = u8(b, p) + p =p+ 1 + if b1 == 34 then -- hflex + if sp < 7 then + return nil, "hflex stack" + end + curveTo(S(0), 0, S(1), S(2), S(3), 0) + curveTo(S(4), 0, S(5), -S(2), S(6), 0) + elseif b1 == 35 then -- flex + if sp < 13 then + return nil, "flex stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), S(10), S(11)) + elseif b1 == 36 then -- hflex1 + if sp < 9 then + return nil, "hflex1 stack" + end + curveTo(S(0), S(1), S(2), S(3), S(4), 0) + curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7))) + elseif b1 == 37 then -- flex1 + if sp < 11 then + return nil, "flex1 stack" + end + local dx = S(0) + S(2) + S(4) + S(6) + S(8) + local dy = S(1) + S(3) + S(5) + S(7) + S(9) + local dx6, dy6 = S(10), S(10) + if math.abs(dx) > math.abs(dy) then + dy6 = -dy + else + dx6 = -dx + end + curveTo(S(0), S(1), S(2), S(3), S(4), S(5)) + curveTo(S(6), S(7), S(8), S(9), dx6, dy6) + else + -- arithmetic and storage operators: they leave results on the stack + clear = false + local top = sp + local a, c = S(top - 2), S(top - 1) + local function set(n, v) + -- pop n operands, push v + sp = math.max(0, sp - n) + sp =sp+ 1 + s[sp] = v + end + if b1 == 3 then + set(2, a ~= 0 and c ~= 0 and 1 or 0) -- and + elseif b1 == 4 then + set(2, (a ~= 0 or c ~= 0 )and 1 or 0) -- or + elseif b1 == 5 then + set(1, c == 0 and 1 or 0) -- not + elseif b1 == 9 then + set(1, math.abs(c)) + elseif b1 == 10 then + set(2, a + c) + elseif b1 == 11 then + set(2, a - c) + elseif b1 == 12 then + set(2, (c ~= 0 and((a / c ))or(0))) + elseif b1 == 14 then + set(1, -c) + elseif b1 == 15 then + set(2, a == c and 1 or 0) + elseif b1 == 18 then + sp = math.max(0, sp - 1) -- drop + elseif b1 == 20 then -- put: val i + local k = math.floor(c) + if k >= 0 and k < 32 then + trans[k + 1] = a + end + sp = math.max(0, sp - 2) + elseif b1 == 21 then -- get + local k = math.floor(c) + set(1, (k >= 0 and k < 32 and{trans[k + 1] }or{0})[1]) + elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2 + local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1) + set(4, (v1 <= v2 and{s1 }or{s2})[1]) + elseif b1 == 23 then -- random (deterministic) + seed = (seed * 1103515245 + 12345) % 2147483648 + set(0, (seed % 65535 + 1) / 65536) + elseif b1 == 24 then + set(2, a * c) + elseif b1 == 26 then + set(1, math.sqrt(math.max(0, c))) + elseif b1 == 27 then + set(0, c) -- dup + elseif b1 == 28 then -- exch + if sp >= 2 then + s[sp - 1], s[sp] = s[sp], s[sp - 1] + end + elseif b1 == 29 then -- index + local k = math.floor(c) + local v = (k < 0 and{(S(top - 2) )}or{(S(top - 2 - k) +)})[1] set(1, v) + elseif b1 == 30 then -- roll: n j + local n, j = math.floor(a), math.floor(c) + sp = math.max(0, sp - 2) + if n > 0 and n <= sp then + local base = sp - n + local tmp = table.create(n, 0) + for k = 0, n - 1 do + tmp[((k + j) % n) + 1] = s[base + k + 1] + end + for k = 0, n - 1 do + s[base + k + 1] = tmp[k + 1] + end + end + else + return nil, "unknown operator 12 " .. b1 + end + if sp > 48 then + return nil, "stack overflow" + end + end + elseif b0 >= 32 or b0 == 28 then -- operands + local v + if b0 == 28 then + v = uN(b, p, 2) + if v >= 32768 then + v =v- 65536 + end + p =p+ 2 + elseif b0 <= 246 then + v = b0 - 139 + elseif b0 <= 250 then + v = (b0 - 247) * 256 + u8(b, p) + 108 + p =p+ 1 + elseif b0 <= 254 then + v = -(b0 - 251) * 256 - u8(b, p) - 108 + p =p+ 1 + else -- 255: 16.16 fixed + v = uN(b, p, 4) + if v >= 2147483648 then + v =v- 4294967296 + end + v =v/ 65536 + p =p+ 4 + end + if sp >= 48 then + return nil, "operand stack overflow" + end + sp =sp+ 1 + s[sp] = v + clear = false + else + return nil, "reserved operator " .. b0 + end + if clear then + sp = 0 + end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + return nil, "no endchar" +end + +return Cff +end +__FILES["codecs/font/GlyphNames"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a +-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause: +-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and +-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name). +-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding. +-- +-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown) +-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef) +local GlyphNames = {} + +-- AGLFN: "name hex" pairs +local AGL = "" .. + "A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " .. + "Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " .. + "106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " .. + "2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " .. + "Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " .. + "F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " .. + "25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " .. + "CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " .. + "Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " .. + "Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " .. + "4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " .. + "Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " .. + "D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " .. + "250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " .. + "251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " .. + "2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " .. + "255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " .. + "2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " .. + "2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " .. + "Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " .. + "16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " .. + "Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " .. + "1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " .. + "Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " .. + "103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " .. + "3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " .. + "aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " .. + "21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " .. + "2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " .. + "asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " .. + "braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " .. + "caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " .. + "A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " .. + "colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " .. + "dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " .. + "dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " .. + "237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " .. + "egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " .. + "14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " .. + "etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " .. + "FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " .. + "215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " .. + "gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " .. + "greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " .. + "hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " .. + "iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " .. + "integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " .. + "invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " .. + "129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " .. + "140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " .. + "longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " .. + "B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " .. + "39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " .. + "obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " .. + "omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " .. + "2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " .. + "ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " .. + "parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " .. + "perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " .. + "220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " .. + "BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " .. + "201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " .. + "reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " .. + "2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " .. + "seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " .. + "263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " .. + "tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " .. + "tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " .. + "25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " .. + "FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " .. + "universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " .. + "upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " .. + "weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " .. + "1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " .. + "" + +-- StandardEncoding: 256 names, "-" = .notdef +local STD = "" .. + "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " .. + "dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " .. + "zero one two three four five six seven eight nine colon semicolon less equal greater question at A " .. + "B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " .. + "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " .. + "asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " .. + "sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " .. + "guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " .. + "quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " .. + "circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " .. + "- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " .. + "- - - dotlessi - - lslash oslash oe germandbls - - - - " .. + "" + +local byName= nil + +local function load() +local t= {} + for name, hex in __iter(string.gmatch(AGL, "(%S+) (%x+)")) do + t[name] = (tonumber(hex, 16) ) +end + byName = t + return t +end + +local STANDARD= {} +do + local i = 0 + for name in __iter(string.gmatch(STD, "%S+")) do + if name ~= "-" then + STANDARD[i] = name + end + i =i+ 1 + end +end +GlyphNames.STANDARD = STANDARD + +-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil +function GlyphNames.unicode(name) +local base = string.match(name, "^([^%.]+)") or name + local t = byName or load() + local v = t[base] + if v then + return v + end + local hex = string.match(base, "^uni(%x%x%x%x)") + if hex then + local c = (tonumber(hex, 16) ) +return (c >= 0xD800 and c < 0xE000 and{nil }or{c +})[1] end + hex = string.match(base, "^u(%x%x%x%x%x?%x?)$") + if hex then + local c = (tonumber(hex, 16) ) +return ((c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) )and{nil }or{c +})[1] end + local first = string.match(base, "^([^_]+)_") + if first then + return GlyphNames.unicode(first) + end + return nil +end + +return GlyphNames +end +__FILES["codecs/font/TrueType"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed +-- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines +-- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments), +-- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all +-- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean +-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's. +-- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix), +-- colour layers (COLR), GSUB substitutions. +-- +-- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err +-- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units +-- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo +-- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px) +-- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt) +-- +-- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods. +local Err = __include("core/Err") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Cff = __include("codecs/font/Cff") +local Glyf = __include("codecs/font/TrueType/Glyf") +local Tables = __include("codecs/font/TrueType/Tables") + +local TrueType = {} + +local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32 + +local function tag(b, o) +if o < 0 or o + 4 > buffer.len(b) then + return "" + end + return buffer.readstring(b, o, 4) +end + +-- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither) +function TrueType.count(b, offset) +local o = offset or 0 + local t = tag(b, o) + if t == "ttcf" then + return u32(b, o + 8) + end + if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then + return 1 + end + return 0 +end + +-- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir +function TrueType.tables(b, file, dir, limit) +local n = u16(b, dir + 4) + if dir + 12 + n * 16 > limit then + return nil, "table directory past the end" + end + local out= {} + for i = 0, n - 1 do + local r = dir + 12 + i * 16 + local t = tag(b, r) + local off, len = u32(b, r + 8), u32(b, r + 12) + if file + off + len <= limit then + out[t] = { file + off, len } + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ the Font value +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self, cp) +return Tables.glyph(self._cmap, cp) +end + +function Face.advance(self, g) +if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh = self._numHMetrics + if nh == 0 then + return 0 + end + local h = self._hmtx + return u16(self._buf, h + 4 * math.min(g, nh - 1)) +end + +function Face.leftSideBearing(self, g) +if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then + return 0 + end + local nh, h = self._numHMetrics, self._hmtx + if g < nh then + return i16(self._buf, h + 4 * g + 2) + end + return i16(self._buf, h + 4 * nh + 2 * (g - nh)) +end + +function Face.kern(self, a, b) +if type(a) ~= "number" or type(b) ~= "number" then + return 0 + end + local key = a * 65536 + b + local cache = self._kernCache + local v = cache[key] + if v then + return v + end + v = 0 + if self._gpos then + v = Tables.gposKern(self._gpos, a, b) + end + if v == 0 and self._kern then + v = self._kern[key] or 0 + end + cache[key] = v + return v +end + +-- kernCodepoints(a, b) -> kern between two code points +function Face.kernCodepoints(self, a, b) +return self:kern(self:glyphIndex(a), self:glyphIndex(b)) +end + +function Face.outline(self, g) +if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then + return nil + end + local ok, cmds, err = pcall(function() + if self._cff then + return Cff.outline(self._cff, g) + end + return Glyf.outline(self._glyf, g) + end) + if not ok then + self.meta.lastError = tostring(cmds) + return nil + end + if not cmds then + self.meta.lastError = err + end + return cmds +end + +-- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph +function Face.bounds(self, g) +local cmds = self:outline(g) + if not cmds then + return nil, 0, 0, 0 + end + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, c in __iter(cmds) do + for i = 1, #c - 1, 2 do + local x, y = c[i], c[i + 1] + x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y) + end + end + if x0 > x1 then + return nil, 0, 0, 0 + end + return x0, y0, x1, y1 +end + +-- scale(px) -> pixels per font unit for an em of px pixels +function Face.scale(self, px) +return px / self.unitsPerEm +end + +-- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels; +-- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty +-- glyphs give a 0 x 0 image. + + + + + + + +function Face.rasterize(self, g, px, opts) +if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local cmds = self:outline(g) + if not cmds then + return nil + end + local o= opts or {} + local sx = (type(o.scaleX) == "number" and{o.scaleX }or{(px / self.unitsPerEm +)})[1] local sy = (type(o.scaleY) == "number" and{o.scaleY }or{sx +})[1] local tx, ty = o.shiftX or 0, o.shiftY or 0 + local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left = 0 + img.meta.top = 0 + end + img.meta.advance = self:advance(g) * sx + img.meta.glyph = g + return img +end +-- ------------------------------------------------------------------------------------------------ parsing +-- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err + + + +function TrueType.font(buf, offset, length, opts) +local b = buf + local file = offset or 0 + local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file))) + if limit - file < 12 then + return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file) + end + local dir = file + local index = (opts and opts.index) or 0 + local count = TrueType.count(b, file) + if tag(b, file) == "ttcf" then + if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count)) + end + dir = file + u32(b, file + 12 + index * 4) + if dir + 12 > limit then + return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file) + end + elseif count == 0 then + return nil, Err.new(Err.CORRUPT, "not an sfnt font", file) + end + local sfntTag = tag(b, dir) + if sfntTag == "typ1" then + return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir) + end + local t, terr = TrueType.tables(b, file, dir, limit) + if not t then + return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir) + end + for _, need in __iter({ "head", "hhea", "maxp", "hmtx" }) do + if not t[need] then + return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir) + end + end + local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1] + if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then + return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir) + end + local upem = u16(b, head + 18) + if upem < 16 or upem > 16384 then + return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18) + end + local numGlyphs = u16(b, maxp + 4) + local nh = math.min(u16(b, hhea + 34), numGlyphs) + if nh * 4 > t.hmtx[2] then + nh = math.floor(t.hmtx[2] / 4 +) end + local font= setmetatable({ + kind = "font", + info = {}, + unitsPerEm = upem, + ascent = i16(b, hhea + 4), + descent = i16(b, hhea + 6), + lineGap = i16(b, hhea + 8), + numGlyphs = numGlyphs, + bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) }, + pages = nil, + meta = {}, + _buf = b, + _hmtx = hmtx, + _numHMetrics = nh, + _kernCache = {}, + }, Face) + -- outlines + if t.glyf and t.loca then + font._glyf = { + buf = b, + glyf = t.glyf[1], + glyfLen = t.glyf[2], + loca = t.loca[1], + locaLen = t.loca[2], + longLoca = i16(b, head + 50) ~= 0, + numGlyphs = numGlyphs, + } + font.meta.outlines = "truetype" + elseif t["CFF "] then + local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2]) + if not cff then + local code = (cerr and string.find(cerr, "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT +})[1] return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1]) + end + font._cff = cff + font.meta.outlines = "cff" + elseif t.CFF2 then + return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir) + else + return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir) + end + -- cmap, kerning, names, OS/2, post + if t.cmap then + font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2]) + end + if t.kern then + font._kern = Tables.kern(b, t.kern[1], t.kern[2]) + end + if t.GPOS then + font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2]) + end + if t.name then + local names = Tables.names(b, t.name[1], t.name[2]) + for k, v in __iter(names) do + font.info[k] = v + end + font.info.family = names.typographicFamily or names.family + font.info.style = names.typographicStyle or names.style + end + if t["OS/2"] and t["OS/2"][2] >= 10 then + font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2]) + end + if t.post and t.post[2] >= 16 then + local p = t.post[1] + font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536 + font.meta.underlinePosition = i16(b, p + 8) + font.meta.underlineThickness = i16(b, p + 10) + font.meta.fixedPitch = u32(b, p + 12) ~= 0 + end + local tags = {} + for k in __iter(t) do + table.insert(tags, k) + end + table.sort(tags) + font.meta.tables = tags + font.meta.sfnt = sfntTag == "OTTO" and"OTTO" or"TrueType" + font.meta.collection = (count > 1 or tag(b, file) == "ttcf" )and{ index = index, count = count } or nil + return font, nil +end + +return TrueType +end +__FILES["codecs/font/TrueType/Glyf"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and +-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale / +-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26 +-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point +-- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the +-- spec do not). No hinting. +-- +-- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message. +local Glyf = {} + +local readu8, readi8 = buffer.readu8, buffer.readi8 +local blen = buffer.len +local band = bit32.band + +local function u8(b, o) +if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b, o) +if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b, o) +local v = u16(b, o) + return (v >= 32768 and((v - 65536 ))or(v +))end +local function u32(b, o) +return u16(b, o) * 65536 + u16(b, o + 2) +end + +-- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index + + + + + + + + + + + +function Glyf.range(f, g) +if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then + return nil, 0 + end + local a, z + if f.longLoca then + if (g + 2) * 4 > f.locaLen then + return nil, 0 + end + a, z = u32(f.buf, f.loca + g * 4), (u32(f.buf, f.loca + g * 4 + 4) ) +else + if (g + 2) * 2 > f.locaLen then + return nil, 0 + end + a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2 + end + if z <= a or z > f.glyfLen then + return nil, 0 + end + return f.glyf + a, z - a +end + +-- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs) +function Glyf.bounds(f, g) +local o, n = Glyf.range(f, g) + if not o or n < 10 then + return nil, 0, 0, 0 + end + local b = f.buf + return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8) +end +-- contours: { { xs, ys, on } } point lists in font units + + + +local MAX_POINTS = 65536 + +local function simple(b, o, len, nc) +local e = o + len + local ends = (table.create(nc) ) +local p = o + 10 + if p + nc * 2 + 2 > e then + return nil, "glyph header past the end" + end + local last = -1 + for i = 1, nc do + local v = u16(b, p) + if v < last then + return nil, "contour end points out of order" + end + ends[i] = v + last = v + p =p+ 2 + end + local n = last + 1 + if n > MAX_POINTS then + return nil, "too many points" + end + local ins = u16(b, p) + p =p+ (2 + ins +) if p > e then + return nil, "instructions past the end" + end + -- flags + local flags = table.create(n, 0) + local i = 1 + while i <= n do + if p >= e then + return nil, "flags past the end" + end + local fl = readu8(b, p) + p =p+ 1 + flags[i] = fl + i =i+ 1 + if band(fl, 8) ~= 0 then + if p >= e then + return nil, "flags past the end" + end + local rep = readu8(b, p) + p =p+ 1 + for _ = 1, rep do + if i > n then + break + end + flags[i] = fl + i =i+ 1 + end + end + end + -- coordinates + local xs = table.create(n, 0) + local x = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 2) ~= 0 then + if p >= e then + return nil, "x coordinates past the end" + end + local d = readu8(b, p) + p =p+ 1 + x =x+ (band(fl, 16) ~= 0 and{d }or{(-d +)})[1] elseif band(fl, 16) == 0 then + if p + 2 > e then + return nil, "x coordinates past the end" + end + x =x+ i16(b, p) + p =p+ 2 + end + xs[k] = x + end + local ys = table.create(n, 0) + local y = 0 + for k = 1, n do + local fl = flags[k] + if band(fl, 4) ~= 0 then + if p >= e then + return nil, "y coordinates past the end" + end + local d = readu8(b, p) + p =p+ 1 + y =y+ (band(fl, 32) ~= 0 and{d }or{(-d +)})[1] elseif band(fl, 32) == 0 then + if p + 2 > e then + return nil, "y coordinates past the end" + end + y =y+ i16(b, p) + p =p+ 2 + end + ys[k] = y + end + local out = (table.create(nc) ) +local s = 1 + for c = 1, nc do + local z = ends[c] + 1 + local cx, cy, con = {}, {}, {} + for k = s, z do + table.insert(cx, xs[k]) + table.insert(cy, ys[k]) + table.insert(con, band(flags[k], 1) ~= 0) + end + out[c] = { x = cx, y = cy, on = con } + s = z + 1 + end + return out, nil +end + +local contours + +local function composite(f, o, len, depth) +local b = f.buf + local e = o + len + local p = o + 10 + local out= {} + local total = 0 + while true do + if p + 4 > e then + return nil, "component past the end" + end + local flags = u16(b, p) + local gi = u16(b, p + 2) + p =p+ 4 + local a1, a2 + if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS + if p + 4 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = i16(b, p), (i16(b, p + 2) ) +else + a1, a2 = u16(b, p), (u16(b, p + 2) ) +end + p =p+ 4 + else + if p + 2 > e then + return nil, "component past the end" + end + if band(flags, 2) ~= 0 then + a1, a2 = readi8(b, p), (readi8(b, p + 1) ) +else + a1, a2 = readu8(b, p), (readu8(b, p + 1) ) +end + p =p+ 2 + end + local m1, m2, m3, m4 = 1, 0, 0, 1 + if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE + m1 = i16(b, p) / 16384 + m4 = m1 + p =p+ 2 + elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE + m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384 + p =p+ 4 + elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO + m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384 + p =p+ 8 + end + if p > e then + return nil, "component past the end" + end + local child, err = contours(f, gi, depth + 1) + if not child then + return nil, err + end + -- transform the child's points + local tc = (table.create(#child) ) +for i, c in __iter(child) do + local nx, ny = (table.create(#c.x) ), (table.create(#c.x) ) +for k = 1, #c.x do + local x, y = c.x[k], c.y[k] + nx[k] = m1 * x + m3 * y + ny[k] = m2 * x + m4 * y + end + tc[i] = { x = nx, y = ny, on = c.on } + end + local dx, dy + if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES + dx, dy = a1, a2 + if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET + dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2 + end + else + -- point matching: parent point a1 (in what is composed so far) meets child point a2 + local function pt(list, idx) +local k = idx + for _, c in __iter(list) do + local n = #c.x + if k < n then + return c.x[k + 1], c.y[k + 1] + end + k =k- n + end + return nil, 0 + end + local px, py = pt(out, a1) + local cx, cy = pt(tc, a2) + if not px or not cx then + return nil, "component point index out of range" + end + dx, dy = px - cx, py - (cy ) + end + for _, c in __iter(tc) do + for k = 1, #c.x do +do local __DARKLUA_VAR= c.x __DARKLUA_VAR[k]=__DARKLUA_VAR[k]+ dx +end do local __DARKLUA_VAR0= c.y __DARKLUA_VAR0[k]=__DARKLUA_VAR0[k]+ dy +end end + total =total+ #c.x + table.insert(out, c) + end + if total > MAX_POINTS then + return nil, "too many points" + end + if band(flags, 0x20) == 0 then -- MORE_COMPONENTS + break + end + end + return out, nil +end + +contours = function(f, g, depth) +if depth > 8 then + return nil, "composite glyphs nested too deep" + end + local o, len = Glyf.range(f, g) + if not o then + return {}, nil -- empty glyph (space) + end + if len < 10 then + return nil, "glyph header past the end" + end + local nc = i16(f.buf, o) + if nc >= 0 then + return simple(f.buf, o, len, nc) + end + return composite(f, o, len, depth) +end + +-- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message +function Glyf.outline(f, g) +local cs, err = contours(f, g, 0) + if not cs then + return nil, err + end + local cmds = {} + for _, c in __iter(cs) do +local __DARKLUA_CONTINUE_14=false repeat local n = #c.x + if n < 2 then +__DARKLUA_CONTINUE_14=true break + end + local xs, ys, on = c.x, c.y, c.on + -- the start: the first on-curve point, or the midpoint of the first two off-curve points + local s = 0 + for k = 1, n do + if on[k] then + s = k + break + end + end + local sx, sy + if s == 0 then + sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2 + s = 1 + -- all off-curve: start at the implied midpoint between the last and the first, then walk from 1 + table.insert(cmds, { op = "moveTo", sx, sy }) + local cx, cy = xs[1], ys[1] + for k = 2, n do + local x, y = xs[k], ys[k] + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + cx, cy = x, y + end + table.insert(cmds, { op = "quadTo", cx, cy, sx, sy }) + table.insert(cmds, { op = "close" }) +__DARKLUA_CONTINUE_14=true break + end + sx, sy = xs[s], ys[s] + table.insert(cmds, { op = "moveTo", sx, sy }) + local off = false + local cx, cy = 0, 0 + for i = 1, n do + local k = (s + i - 1) % n + 1 + local x, y, isOn = xs[k], ys[k], on[k] + if i == n then + x, y, isOn = sx, sy, true -- back to the start + end + if isOn then + if off then + table.insert(cmds, { op = "quadTo", cx, cy, x, y }) + elseif i < n then + table.insert(cmds, { op = "lineTo", x, y }) + end + off = false + else + if off then + table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 }) + end + cx, cy = x, y + off = true + end + end + table.insert(cmds, { op = "close" }) +__DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break end end + return cmds, nil +end + +-- points(f, g) -> the number of points and contours (for tests) +function Glyf.counts(f, g) +local cs = contours(f, g, 0) + if not cs then + return 0, 0 + end + local n = 0 + for _, c in __iter(cs) do + n =n+ #c.x + end + return n, #cs +end + +return Glyf +end +__FILES["codecs/font/TrueType/Tables"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode +-- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair +-- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9), +-- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public +-- domain / MIT) as a reference for cmap 4 and the GPOS walk. +-- +-- Never throws: every read is range-checked (out of range reads as 0). +local Text = __include("codecs/text/Text") +local Tables = {} + +local readu8 = buffer.readu8 +local blen = buffer.len +local band = bit32.band + +local function u8(b, o) +if o < 0 or o + 1 > blen(b) then + return 0 + end + return readu8(b, o) +end +local function u16(b, o) +if o < 0 or o + 2 > blen(b) then + return 0 + end + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function i16(b, o) +local v = u16(b, o) + return (v >= 32768 and((v - 65536 ))or(v +))end +local function u32(b, o) +return u16(b, o) * 65536 + u16(b, o + 2) +end +Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32 +-- ------------------------------------------------------------------------------------------------ cmap +-- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac + + + +function Tables.cmap(b, o, n) +local count = u16(b, o + 2) + local best, bestRank, symbol = -1, 0, false + for i = 0, count - 1 do +local __DARKLUA_CONTINUE_1=false repeat local r = o + 4 + i * 8 + if r + 8 > o + n then + break + end + local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4) + local at = o + off + if off >= n then +__DARKLUA_CONTINUE_1=true break + end + local fmt = u16(b, at) + local rank = 0 + if pid == 3 and eid == 10 then + rank = 6 + elseif pid == 0 and (eid == 4 or eid == 6) then + rank = 5 + elseif pid == 3 and eid == 1 then + rank = 4 + elseif pid == 0 and fmt ~= 14 then + rank = 3 + elseif pid == 3 and eid == 0 then + rank = 2 + elseif pid == 1 and eid == 0 then + rank = 1 + end + if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then + rank = 0 + end + if rank > bestRank then + best, bestRank, symbol = at, rank, pid == 3 and eid == 0 + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + if best < 0 then + return nil + end + return { buf = b, at = best, format = u16(b, best), symbol = symbol } +end + +local function lookup(c, cp) +local b, t, fmt = c.buf, c.at, c.format + if fmt == 0 then + return (cp < 256 and{(u8(b, t + 6 + cp) )}or{0 +})[1] elseif fmt == 6 then + local first, count = u16(b, t + 6), u16(b, t + 8) + if cp >= first and cp < first + count then + return u16(b, t + 10 + (cp - first) * 2) + end + return 0 + elseif fmt == 10 then + local first, count = u32(b, t + 12), u32(b, t + 16) + if cp >= first and cp < first + count then + return u16(b, t + 20 + (cp - first) * 2) + end + return 0 + elseif fmt == 4 then + if cp > 0xFFFF then + return 0 + end + local segX2 = u16(b, t + 6) + local segs = math.floor(segX2 / 2 +) local ends = t + 14 + -- binary search for the first segment whose end >= cp + local lo, hi = 0, segs - 1 + while lo < hi do + local mid = math.floor((lo + hi) / 2 +) if u16(b, ends + mid * 2) < cp then + lo = mid + 1 + else + hi = mid + end + end + if segs == 0 or u16(b, ends + lo * 2) < cp then + return 0 + end + local starts = ends + segX2 + 2 + local start = u16(b, starts + lo * 2) + if cp < start then + return 0 + end + local deltaAt = starts + segX2 + lo * 2 + local delta = u16(b, deltaAt) + local rangeAt = deltaAt + segX2 + local ro = u16(b, rangeAt) + if ro == 0 then + return (cp + delta) % 65536 + end + local g = u16(b, rangeAt + ro + (cp - start) * 2) + if g == 0 then + return 0 + end + return (g + delta) % 65536 + elseif fmt == 12 or fmt == 13 then + local n = u32(b, t + 12) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) local g = t + 16 + mid * 12 + local s, e = u32(b, g), u32(b, g + 4) + if cp < s then + hi = mid - 1 + elseif cp > e then + lo = mid + 1 + else + local gid = u32(b, g + 8) + return (fmt == 12 and((gid + cp - s ))or(gid +)) end + end + return 0 + end + return 0 +end + +-- glyph(cmap, codepoint) -> glyph index (0 = .notdef) +function Tables.glyph(c, cp) +if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then + return 0 + end + local g = lookup(c, cp) + if g == 0 and c.symbol and cp < 256 then + g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes + end + return g +end + +-- ------------------------------------------------------------------------------------------------ kern +-- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value } +function Tables.kern(b, o, n) +local pairs= {} + local e = o + n + local apple = u32(b, o) == 0x00010000 + local count = (apple and{(u32(b, o + 4) )}or{(u16(b, o + 2) +)})[1] local p = (apple and((o + 8 ))or((o + 4 +))) for _ = 1, math.min(count, 64) do + if p + 6 > e then + break + end + local len, fmt, horizontal, cross, minimum, hdr + if apple then + len = u32(b, p) + local cov = u16(b, p + 4) + fmt = band(cov, 0xFF) + horizontal = band(cov, 0x8000) == 0 + cross = band(cov, 0x4000) ~= 0 + minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable + hdr = 8 + else + len = u16(b, p + 2) + local cov = u16(b, p + 4) + fmt = math.floor(cov / 256 +) horizontal = band(cov, 1) ~= 0 + minimum = band(cov, 2) ~= 0 + cross = band(cov, 4) ~= 0 + hdr = 6 + end + if fmt == 0 and horizontal and not cross and not minimum then + local np = u16(b, p + hdr) + local q = p + hdr + 8 + for k = 0, np - 1 do + local r = q + k * 6 + if r + 6 > e then + break + end + local key = u16(b, r) * 65536 + u16(b, r + 2) + pairs[key] = (pairs[key] or 0) + i16(b, r + 4) + end + end + if len < hdr then + break + end + -- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then + if not apple and len < hdr + 8 then + break + end + p =p+ len + end + return pairs +end + +-- ------------------------------------------------------------------------------------------------ GPOS +local function popcount(v) +local c = 0 + while v ~= 0 do + c =c+ band(v, 1) + v = bit32.rshift(v, 1) + end + return c +end + +-- coverage index of glyph g in the Coverage table at t, or -1 +local function coverage(b, t, g) +local fmt = u16(b, t) + if fmt == 1 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) local v = u16(b, t + 4 + mid * 2) + if g < v then + hi = mid - 1 + elseif g > v then + lo = mid + 1 + else + return mid + end + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + g - s + end + end + end + return -1 +end + +local function classOf(b, t, g) +local fmt = u16(b, t) + if fmt == 1 then + local s, n = u16(b, t + 2), u16(b, t + 4) + if g >= s and g < s + n then + return u16(b, t + 6 + (g - s) * 2) + end + elseif fmt == 2 then + local n = u16(b, t + 2) + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) local r = t + 4 + mid * 6 + local s, e = u16(b, r), u16(b, r + 2) + if g < s then + hi = mid - 1 + elseif g > e then + lo = mid + 1 + else + return u16(b, r + 4) + end + end + end + return 0 +end + +-- the x advance adjustment in a value record with format vf at r +local function xAdvance(b, r, vf) +if band(vf, 4) == 0 then + return 0 + end + return i16(b, r + 2 * popcount(band(vf, 3))) +end + +-- one PairPos subtable: (applies, value) +local function pairPos(b, t, l, r) +local fmt = u16(b, t) + local ci = coverage(b, t + u16(b, t + 2), l) + if ci < 0 then + return false, 0 + end + local vf1, vf2 = u16(b, t + 4), u16(b, t + 6) + local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF)) + if fmt == 1 then + local count = u16(b, t + 8) + if ci >= count then + return false, 0 + end + local ps = t + u16(b, t + 10 + ci * 2) + local n = u16(b, ps) + local rec = 2 + s1 + s2 + local lo, hi = 0, n - 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) local q = ps + 2 + mid * rec + local g = u16(b, q) + if r < g then + hi = mid - 1 + elseif r > g then + lo = mid + 1 + else + return true, xAdvance(b, q + 2, vf1) + end + end + return false, 0 + elseif fmt == 2 then + local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10) + local n1, n2 = u16(b, t + 12), u16(b, t + 14) + local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r) + if c1 >= n1 or c2 >= n2 then + return false, 0 + end + local q = t + 16 + (c1 * n2 + c2) * (s1 + s2) + return true, xAdvance(b, q, vf1) + end + return false, 0 +end + +-- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n) + + +function Tables.gpos(b, o, n) +if n < 10 or u16(b, o) ~= 1 then + return nil + end + local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8) + local want= {} + local any = false + local nf = u16(b, fl) + for i = 0, nf - 1 do + local r = fl + 2 + i * 6 + if u32(b, r) == 0x6B65726E then -- "kern" + local f = fl + u16(b, r + 4) + for k = 0, u16(b, f + 2) - 1 do + want[u16(b, f + 4 + k * 2)] = true + any = true + end + end + end + if not any then + return nil + end + local lookups= {} + local nl = u16(b, ll) + for i = 0, nl - 1 do + if want[i] then + local lt = ll + u16(b, ll + 2 + i * 2) + local ty = u16(b, lt) + local subs= {} + for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do + local st = lt + u16(b, lt + 6 + k * 2) + local sty = ty + if ty == 9 and u16(b, st) == 1 then -- extension + sty = u16(b, st + 2) + st =st+ u32(b, st + 4) + end + if sty == 2 then + table.insert(subs, st) + end + end + if #subs > 0 then + table.insert(lookups, subs) + end + end + end + if #lookups == 0 then + return nil + end + return { buf = b, subtables = lookups } +end + +-- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units) +function Tables.gposKern(g, l, r) +local total = 0 + for _, subs in __iter(g.subtables) do + for _, st in __iter(subs) do + local applies, v = pairPos(g.buf, st, l, r) + if applies then + total =total+ v + break + end + end + end + return total +end + +-- ------------------------------------------------------------------------------------------------ name, OS/2 +local MAC_ROMAN_HIGH = { + 0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8, + 0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC, + 0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8, + 0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8, + 0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4, + 0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7, +} + +local function utf16be(b, o, n) +return Text.utf16(b, o, n, true) +end + +local function macRoman(b, o, n) +local out = {} + for k = 0, n - 1 do + local c = u8(b, o + k) + table.insert(out, utf8.char((c < 128 and{c }or{MAC_ROMAN_HIGH[c - 127]})[1])) + end + return table.concat(out) +end + +local NAME_IDS= { + [0] = "copyright", + [1] = "family", + [2] = "style", + [3] = "uniqueId", + [4] = "fullName", + [5] = "version", + [6] = "postScriptName", + [7] = "trademark", + [8] = "manufacturer", + [9] = "designer", + [10] = "description", + [11] = "vendorUrl", + [12] = "designerUrl", + [13] = "license", + [14] = "licenseUrl", + [16] = "typographicFamily", + [17] = "typographicStyle", +} + +-- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman) +function Tables.names(b, o, n) +local out= {} + local rank= {} + local count, strings = u16(b, o + 2), o + u16(b, o + 4) + for i = 0, math.min(count, 4096) - 1 do + local r = o + 6 + i * 12 + if r + 12 > o + n then + break + end + local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6) + local len, off = u16(b, r + 8), u16(b, r + 10) + local key = NAME_IDS[nid] + if key and strings + off + len <= o + n then + local rk, s= 0, nil + if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then + rk = lang == 0x409 and 4 or 2 + s = utf16be(b, strings + off, len) + elseif pid == 0 then + rk = 3 + s = utf16be(b, strings + off, len) + elseif pid == 1 and eid == 0 then + rk = lang == 0 and 1 or 0.5 + s = macRoman(b, strings + off, len) + end + if s and rk > (rank[key] or 0) then + out[key] = s + rank[key] = rk + end + end + end + return out +end + +-- os2(OS/2 table) -> the commonly used fields +function Tables.os2(b, o, n) +local t= { + version = u16(b, o), + xAvgCharWidth = i16(b, o + 2), + weightClass = u16(b, o + 4), + widthClass = u16(b, o + 6), + fsType = u16(b, o + 8), + } + if n >= 78 then + t.fsSelection = u16(b, o + 62) + t.firstChar = u16(b, o + 64) + t.lastChar = u16(b, o + 66) + t.typoAscender = i16(b, o + 68) + t.typoDescender = i16(b, o + 70) + t.typoLineGap = i16(b, o + 72) + t.winAscent = u16(b, o + 74) + t.winDescent = u16(b, o + 76) + end + if n >= 96 and t.version >= 2 then + t.xHeight = i16(b, o + 86) + t.capHeight = i16(b, o + 88) + end + return t +end + +return Tables +end +__FILES["codecs/image/Bcn"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +--!native +--!optimize 2 +-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): +-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, +-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). +-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. +-- +-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) +-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) +-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) +-- +-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by +-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below +-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +local Decode = __include("codecs/image/Bcn/Decode") +local Encode = __include("codecs/image/Bcn/Encode") + +local Bcn = {} + +-- kind -> bytes per 4x4 block +Bcn.BLOCK = (table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) )-- kinds that decode to rgbaf32 + +Bcn.FLOAT = (table.freeze({ bc6h = true, bc6hs = true }) ) + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local BLOCKS= { + bc1 = Decode.bc1, + bc2 = Decode.bc2, + bc3 = Decode.bc3, + bc4 = Decode.bc4, + bc4s = Decode.bc4s, + bc5 = Decode.bc5, + bc5s = Decode.bc5s, + bc7 = Decode.bc7, + bc6h = function(src, p, blk) + Decode.bc6h(src, p, blk, false) + end, + bc6hs = function(src, p, blk) + Decode.bc6h(src, p, blk, true) + end, +} + +-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) +function Bcn.size(kind, w, h) +local b = Bcn.BLOCK[kind] + if not b then + return nil + end + return (math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b +end + +-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. +-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. +function Bcn.decode(kind, src, offset, w, h, out, outOffset) +local fn = BLOCKS[kind] + if not fn then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = (Bcn.size(kind, w, h) ) +if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local float = Bcn.FLOAT[kind] == true + local bpp = float and 16 or 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local bytes = Bcn.BLOCK[kind] + local blk = buffer.create(16 * bpp) + local bw, bh = math.floor((w + 3) / 4), math.floor((h + 3) / 4 +) local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + fn(src, p, blk) + p =p+ bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + if cols == 4 and not float then + for y = 0, rows - 1 do + local d, s = base + y * rowBytes, y * 16 + writeu32(dst, d, readu32(blk, s)) + writeu32(dst, d + 4, readu32(blk, s + 4)) + writeu32(dst, d + 8, readu32(blk, s + 8)) + writeu32(dst, d + 12, readu32(blk, s + 12)) + end + else + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + end + return dst, nil +end + +-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. + + + + +function Bcn.encode(kind, px, w, h, opts) +if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then + return nil, "unsupported: no encoder for " .. tostring(kind) + end + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then + return nil, "needs w x h rgba8 pixels" + end + local t = opts and opts.alphaThreshold or 128 + return Encode.run(kind, px, w, h, t), nil +end + +return Bcn +end +__FILES["codecs/image/Bcn/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's +-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where +-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit +-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate +-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte +-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +local Half = __include("codecs/image/Half") + +local Decode = {} + +local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 +local pal = buffer.create(16) -- 4 rgba8 colours + +local function c565(c) +local r = rshift(band(c, 0xF800), 8) + local g = rshift(band(c, 0x7E0), 3) + local b = lshift(band(c, 0x1F), 3) + return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) +end + +-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +local function colour(src, p, blk, fourColour) + local c0, c1 = readu16(src, p), readu16(src, p + 2) + local r0, g0, b0 = c565(c0) + local r1, g1, b1 = c565(c1) + writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) + writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) + if c0 > c1 or fourColour then + writeu32(pal, 8, math.floor((2 * r0 + r1) / 3 )+ (math.floor((2 * g0 + g1) / 3)) * 256 + (math.floor((2 * b0 + b1) / 3)) * 65536 + 0xFF000000) + writeu32(pal, 12, math.floor((r0 + 2 * r1) / 3 )+ (math.floor((g0 + 2 * g1) / 3)) * 256 + (math.floor((b0 + 2 * b1) / 3)) * 65536 + 0xFF000000) + else + writeu32(pal, 8, math.floor((r0 + r1) / 2 )+ (math.floor((g0 + g1) / 2)) * 256 + (math.floor((b0 + b1) / 2)) * 65536 + 0xFF000000) + writeu32(pal, 12, 0) + end + local idx = readu32(src, p + 4) + for i = 0, 15 do + writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) + end +end + +-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals +local vals = table.create(8, 0) +local function ramp8(a0, a1) + vals[1], vals[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * a0 + i * a1) / 7 +) end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * a0 + i * a1) / 5 +) end + vals[7], vals[8] = 0, 255 + end +end + +-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 +local function ramp8s(u0, u1) + local s0= math.max((u0 >= 128 and((u0 - 256 ))or(u0)), -127) + local s1= math.max((u1 >= 128 and((u1 - 256 ))or(u1)), -127) + vals[1], vals[2] = s0 + 128, s1 + 128 + if s0 > s1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 + end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 + end + vals[7], vals[8] = 1, 255 + end +end + +-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) +local function single(src, p, blk, channel, signed, spread) + if signed then + ramp8s(readu8(src, p), readu8(src, p + 1)) + else + ramp8(readu8(src, p), readu8(src, p + 1)) + end + local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 + local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 + for i = 0, 15 do + local sel = (i < 8 and{(band(rshift(lo, i * 3), 7) )}or{(band(rshift(hi, (i - 8) * 3), 7) +)})[1] local v = vals[sel + 1] + local o = i * 4 + if spread then + writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) + else + writeu8(blk, o + channel, v) + end + end +end + +function Decode.bc1(src, p, blk) + colour(src, p, blk, false) +end + +function Decode.bc2(src, p, blk) + colour(src, p + 8, blk, true) + for i = 0, 15 do + local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) + writeu8(blk, i * 4 + 3, a * 17) + end +end + +function Decode.bc3(src, p, blk) + colour(src, p + 8, blk, true) + single(src, p, blk, 3, false, false) +end + +function Decode.bc4(src, p, blk) + single(src, p, blk, 0, false, true) +end + +function Decode.bc4s(src, p, blk) + single(src, p, blk, 0, true, true) +end + +local function bc5(src, p, blk, signed) + for i = 0, 15 do + writeu32(blk, i * 4, 0xFF000000) + end + single(src, p, blk, 0, signed, false) + single(src, p + 8, blk, 1, signed, false) +end +function Decode.bc5(src, p, blk) + bc5(src, p, blk, false) +end +function Decode.bc5s(src, p, blk) + bc5(src, p, blk, true) +end + +-- ------------------------------------------------------------------------------------------------ BPTC tables +-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices +local SI2 = { + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, + 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, + 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +} +local SI3 = { + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, + 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, + 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, + 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +} +local AI0 = { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +} +local AI1 = { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +} +local AI2 = { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +} +local W2 = { [0] = 0, 21, 43, 64 } +local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } +local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } +local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } +Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS + +local function subset(ns, part, i) +if ns == 2 then + return band(rshift(SI2[part + 1], i), 1) + elseif ns == 3 then + return band(rshift(SI3[part + 1], 2 * i), 3) + end + return 0 +end + +-- the 128-bit block as four u32 words: bits(at, n) for n <= 16 +local w0, w1, w2, w3 = 0, 0, 0, 0 +local function load(src, p) + w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) +end +local function word(i) +return (i == 0 and{w0 }or{(i == 1 and{w1 }or{(i == 2 and{w2 }or{w3 +})[1]})[1]})[1]end +local function bits(at, n) +if n == 0 then + return 0 + end + local wi, sh = rshift(at, 5), band(at, 31) + local v = rshift(word(wi), sh) + if sh + n > 32 and wi < 3 then + v = bor(v, lshift(word(wi + 1), 32 - sh)) + end + return band(v, lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ BC7 +-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 +local MODES7 = { + { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, + { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, + { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, + { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, + { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, + { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, + { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, + { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, +} +local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) + +local function expand(v, n) +v = band(lshift(v, 8 - n), 255) + return bor(v, rshift(v, n)) +end + +function Decode.bc7(src, p, blk) + local m0 = readu8(src, p) + if m0 == 0 then + buffer.fill(blk, 0, 0, 64) + return + end + load(src, p) + local mode = 0 + while band(m0, lshift(1, mode)) == 0 do + mode =mode+ 1 + end + local info = MODES7[mode + 1] + local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] + local bit = mode + 1 + local part = bits(bit, pb) + bit =bit+ pb + local rot = bits(bit, rb) + bit =bit+ rb + local sel = bits(bit, isb) + bit =bit+ isb + local nep = ns * 2 + for i = 1, nep do + er[i] = bits(bit, cb) + bit =bit+ cb + end + for i = 1, nep do + eg[i] = bits(bit, cb) + bit =bit+ cb + end + for i = 1, nep do + eb[i] = bits(bit, cb) + bit =bit+ cb + end + for i = 1, nep do + if ab > 0 then + ea[i] = bits(bit, ab) + bit =bit+ ab + else + ea[i] = 255 + end + end + if epb == 1 then + cb =cb+ 1 + if ab > 0 then + ab =ab+ 1 + end + for i = 1, nep do + local v = bits(bit, 1) + bit =bit+ 1 + er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v + if ab > 0 then + ea[i] = ea[i] * 2 + v + end + end + end + if spb == 1 then + cb =cb+ 1 + if ab > 0 then + ab =ab+ 1 + end + for i = 1, nep, 2 do + local v = bits(bit, 1) + bit =bit+ 1 + for j = i, i + 1 do + er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v + if ab > 0 then + ea[j] = ea[j] * 2 + v + end + end + end + end + for i = 1, nep do + er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) + if ab > 0 then + ea[i] = expand(ea[i], ab) + end + end + local cw = WEIGHTS[ib] + local aw = (ab > 0 and ib2 > 0 and{WEIGHTS[ib2] }or{cw +})[1] local cbit = bit + local abit = cbit + 16 * ib - ns + local a1 = (ns == 2 and{AI0[part + 1] }or{(ns == 3 and{AI1[part + 1] }or{(-1 +)})[1]})[1] local a2 = (ns == 3 and{AI2[part + 1] }or{(-1 +)})[1] for i = 0, 15 do + local s = subset(ns, part, i) * 2 + 1 + local n = ib + if i == 0 or i == a1 or i == a2 then + n =n- 1 + end + local i0 = bits(cbit, n) + cbit =cbit+ n + local wc, wa + if ab > 0 and ib2 > 0 then + local n2 = (i == 0 and((ib2 - 1 ))or(ib2 +)) local i1 = bits(abit, n2) + abit =abit+ n2 + if sel == 1 then + wc, wa = aw[i1], cw[i0] + else + wc, wa = cw[i0], aw[i1] + end + else + wc, wa = cw[i0], cw[i0] + end + local tc, ta = 64 - wc, 64 - wa + local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) + local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) + local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) + local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) + if rot == 1 then + r, a = a, r + elseif rot == 2 then + g, a = a, g + elseif rot == 3 then + b, a = a, b + end + writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end +end + +-- ------------------------------------------------------------------------------------------------ BC6H +-- ns, transformed, pb, epb, rb, gb, bb +local MODES6 = { + { 2, 1, 5, 10, 5, 5, 5 }, + { 2, 1, 5, 7, 6, 6, 6 }, + { 2, 1, 5, 11, 5, 4, 4 }, + { 2, 1, 5, 11, 4, 5, 4 }, + { 2, 1, 5, 11, 4, 4, 5 }, + { 2, 1, 5, 9, 5, 5, 5 }, + { 2, 1, 5, 8, 6, 5, 5 }, + { 2, 1, 5, 8, 5, 6, 5 }, + { 2, 1, 5, 8, 5, 5, 6 }, + { 2, 0, 5, 6, 6, 6, 6 }, + { 1, 0, 0, 10, 10, 10, 10 }, + { 1, 1, 0, 11, 9, 9, 9 }, + { 1, 1, 0, 12, 8, 8, 8 }, + { 1, 1, 0, 16, 4, 4, 4 }, +} +-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) +local PACK6 = { + { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, +} +local ep = table.create(12, 0) +local uq = table.create(12, 0) + +local function signExtend(v, n) +v = band(v, lshift(1, n) - 1) + return (v >= lshift(1, n - 1) and{(v - lshift(1, n) )}or{v +})[1]end + +local function unquantize(x, n, signed) +if not signed then + if n >= 15 or x == 0 then + return x + elseif x == lshift(1, n) - 1 then + return 0xFFFF + end + return rshift(x * 32768 + 0x4000, n - 1) + end + if n >= 16 then + return x + end + local neg = x < 0 + if neg then + x = -x + end + if x ~= 0 then + if x >= lshift(1, n - 1) - 1 then + x = 0x7FFF + else + x = rshift(x * 32768 + 0x4000, n - 1) + end + end + return (neg and{(-x )}or{x +})[1]end + +local function finish(v, signed) +if signed then + if v < 0 then + return -HALF[math.floor((-v * 31) / 32)] + end + return HALF[math.floor((v * 31) / 32)] + end + return HALF[math.floor((v * 31) / 64)] +end + +-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) +function Decode.bc6h(src, p, blk, signed) + load(src, p) + local m = band(w0, 31) + local mode, bit, epbits, ib + local low = band(m, 3) + if low < 2 then + mode, bit, epbits, ib = low, 2, 75, 3 + elseif low == 2 then + mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 + else + mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 + end + if mode >= 14 then + for i = 0, 15 do + local o = i * 16 + writef32(blk, o, 0) + writef32(blk, o + 4, 0) + writef32(blk, o + 8, 0) + writef32(blk, o + 12, 1) + end + return + end + local info = MODES6[mode + 1] + local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] + local nep = ns == 2 and 12 or 6 + for i = 1, 12 do + ep[i] = 0 + end + local pack = PACK6[mode + 1] + for i = 1, epbits do + local d = pack[i] + local e = rshift(d, 4) + 1 + ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) + end + bit =bit+ epbits + local part = bits(bit, pb) + bit =bit+ pb + local mask = lshift(1, epb) - 1 + if signed then + ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) + end + if signed or tr == 1 then + for i = 4, nep, 3 do + ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) + end + end + if tr == 1 then + for i = 4, nep, 3 do + for c = 0, 2 do + local v = band(ep[i + c] + ep[1 + c], mask) + ep[i + c] = (signed and{(signExtend(v, epb) )}or{v +})[1] end + end + end + for i = 1, nep do + uq[i] = unquantize(ep[i], epb, signed) + end + local w = WEIGHTS[ib] + local a1 = (ns == 2 and{AI0[part + 1] }or{(-1 +)})[1] for i = 0, 15 do + local s = subset(ns, part, i) * 6 + 1 + local n = ((i == 0 or i == a1 )and((ib - 1 ))or(ib +)) local wt = w[bits(bit, n)] + bit =bit+ n + local t = 64 - wt + local o = i * 16 + -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would + writef32(blk, o, finish(math.floor((uq[s] * t + uq[s + 3] * wt + 32) / 64), signed)) + writef32(blk, o + 4, finish(math.floor((uq[s + 1] * t + uq[s + 4] * wt + 32) / 64), signed)) + writef32(blk, o + 8, finish(math.floor((uq[s + 2] * t + uq[s + 5] * wt + 32) / 64), signed)) + writef32(blk, o + 12, 1) + end +end + +return Decode +end +__FILES["codecs/image/Bcn/Encode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in rosetta; the approach follows stb_dxt by +-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the +-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping +-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as +-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +local Encode = {} + +local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +local function exp5(v) +return bor(lshift(v, 3), rshift(v, 2)) +end +local function exp6(v) +return bor(lshift(v, 2), rshift(v, 4)) +end + +-- ------------------------------------------------------------------------------------------------ single colours +-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) +-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit +local OM= nil +local function singleTables() +local om = OM + if om then + return om + end + local t= {} + for k = 1, 4 do + local bitsN = k <= 2 and 5 or 6 + local maxq = lshift(1, bitsN) - 1 + local exp= (bitsN == 5 and{exp5 }or{exp6 +})[1] local best = table.create(256, 1e9) + local pick = table.create(256, 0) + for a = 0, maxq do + local ea = exp(a) + for b = 0, maxq do + local eb = exp(b) + local v= (k % 2 == 1 and{(math.floor((2 * ea + eb) / 3 ))}or{(math.floor((ea + eb) / 2 +))})[1] -- prefer endpoints close to each other (less error if the colour shifts) + local e = math.abs(ea - eb) * 0.01 + for target = math.max(0, v - 8), math.min(255, v + 8) do + local err = (target - v) ^ 2 + e + if err < best[target + 1] then + best[target + 1] = err + pick[target + 1] = a * 256 + b + end + end + end + end + t[k] = pick + end + OM = t + return t +end + +-- ------------------------------------------------------------------------------------------------ BC1 colour +local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) +local USE = table.create(16, true) +local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) +local IDX = table.create(16, 0) +local BEST = table.create(16, 0) + +local function palette(c0, c1, four) + local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) + local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) + PR[1], PG[1], PB[1] = r0, g0, b0 + PR[2], PG[2], PB[2] = r1, g1, b1 + if four then + PR[3], PG[3], PB[3] = math.floor((2 * r0 + r1) / 3), math.floor((2 * g0 + g1) / 3), math.floor((2 * b0 + b1) / 3 +) PR[4], PG[4], PB[4] = math.floor((r0 + 2 * r1) / 3), math.floor((g0 + 2 * g1) / 3), math.floor((b0 + 2 * b1) / 3 +) else + PR[3], PG[3], PB[3] = math.floor((r0 + r1) / 2), math.floor((g0 + g1) / 2), math.floor((b0 + b1) / 2 +) PR[4], PG[4], PB[4] = 0, 0, 0 + end +end + +-- indices for the palette into IDX (0-based); returns the squared error of the used pixels +local function assign(four) +local n = four and 4 or 3 + local total = 0 + for i = 1, 16 do + if USE[i] then + local r, g, b = R[i], G[i], B[i] + local bi, be = 0, math.huge + for k = 1, n do + local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] + local e = dr * dr + dg * dg + db * db + if e < be then + be, bi = e, k - 1 + end + end + IDX[i] = bi + total =total+ be + else + IDX[i] = 3 + end + end + return total +end + +local function q565(r, g, b) +local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) + local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) + local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) + return qr * 2048 + qg * 32 + qb +end + +-- the endpoint weights of index k (the e0 share) +local W4 = { 1, 0, 2 / 3, 1 / 3 } +local W3 = { 1, 0, 0.5, 0 } + +-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate +local function refine(four) +local W = (four and{W4 }or{W3 +})[1] local aa, bb, ab = 0, 0, 0 + local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + local w = W[IDX[i] + 1] + local v = 1 - w + aa =aa+ w * w + bb =bb+ v * v + ab =ab+ w * v + ar =ar+ w * R[i] + ag =ag+ w * G[i] + ab_ =ab_+ w * B[i] + br =br+ v * R[i] + bg =bg+ v * G[i] + bb_ =bb_+ v * B[i] + end + end + local det = aa * bb - ab * ab + if math.abs(det) < 1e-9 then + return nil, nil + end + local f = 1 / det + local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f + local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f + return q565(r0, g0, b0), q565(r1, g1, b1) +end + +-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode +-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels +local function colourBlock(out, o, four) + local n, mr, mg, mb = 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + n =n+ 1 + mr =mr+ R[i] + mg =mg+ G[i] + mb =mb+ B[i] + end + end + if n == 0 then + writeu16(out, o, 0) + writeu16(out, o + 2, 0) + writeu32(out, o + 4, 0xFFFFFFFF) + return + end + mr, mg, mb = mr / n, mg / n, mb / n + local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 + local same = true + local fr, fg, fb = -1, -1, -1 + for i = 1, 16 do + if USE[i] then + if fr < 0 then + fr, fg, fb = R[i], G[i], B[i] + elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then + same = false + end + local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb + crr =crr+ dr * dr + cgg =cgg+ dg * dg + cbb =cbb+ db * db + crg =crg+ dr * dg + crb =crb+ dr * db + cgb =cgb+ dg * db + end + end + local c0, c1 + if same then + local t = singleTables() + local k = four and 0 or 1 + local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] + c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) + c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) + local i2 = 2 + if c0 == c1 then + i2 = 0 + end + -- index 2 everywhere (or 0 for an exact endpoint); order fixed below + for i = 1, 16 do + IDX[i] = (USE[i] and{i2 }or{3 +})[1] end + else + -- principal axis + local vr, vg, vb = 1, 1, 1 + for _ = 1, 8 do + local nr = crr * vr + crg * vg + crb * vb + local ng = crg * vr + cgg * vg + cgb * vb + local nb = crb * vr + cgb * vg + cbb * vb + local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) + if m < 1e-9 then + break + end + vr, vg, vb = nr / m, ng / m, nb / m + end + local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 + for i = 1, 16 do + if USE[i] then + local d = R[i] * vr + G[i] * vg + B[i] * vb + if d < lo then + lo, li = d, i + end + if d > hi then + hi, hi_ = d, i + end + end + end + c0 = q565(R[hi_], G[hi_], B[hi_]) + c1 = q565(R[li], G[li], B[li]) + palette(c0, c1, four) + local err = assign(four) + for i = 1, 16 do + BEST[i] = IDX[i] + end + for _ = 1, 2 do + local n0, n1 = refine(four) + if not n0 or not n1 then + break + end + palette(n0, n1, four) + local e2 = assign(four) + if e2 < err then + err, c0, c1 = e2, n0, n1 + for i = 1, 16 do + BEST[i] = IDX[i] + end + else + break + end + end + for i = 1, 16 do + IDX[i] = BEST[i] + end + end + -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 + if four then + if c0 < c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = v == 0 and 1 or(v == 1 and 0 or(v == 2 and 3 or 2 +)) end + elseif c0 == c1 then + for i = 1, 16 do + IDX[i] = 0 + end + end + elseif c0 > c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = v == 0 and 1 or(v == 1 and 0 or v +) end + end + writeu16(out, o, c0) + writeu16(out, o + 2, c1) + local bitsv = 0 + for i = 16, 1, -1 do + bitsv = bitsv * 4 + IDX[i] + end + writeu32(out, o + 4, bitsv) +end + +-- ------------------------------------------------------------------------------------------------ BC4 channel +local V = table.create(16, 0) +local RAMP = table.create(8, 0) +local SEL = table.create(16, 0) +local SELB = table.create(16, 0) + +local function ramp(a0, a1) + RAMP[1], RAMP[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + RAMP[i + 2] = math.floor(((7 - i) * a0 + i * a1) / 7 +) end + else + for i = 1, 4 do + RAMP[i + 2] = math.floor(((5 - i) * a0 + i * a1) / 5 +) end + RAMP[7], RAMP[8] = 0, 255 + end +end + +local function pick() +local total = 0 + for i = 1, 16 do + local v = V[i] + local bi, be = 0, math.huge + for k = 1, 8 do + local d = v - RAMP[k] + local e = d * d + if e < be then + be, bi = e, k - 1 + end + end + SEL[i] = bi + total =total+ be + end + return total +end + +-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] +local function channelBlock(out, o) + local lo, hi = 255, 0 + local lo2, hi2 = 255, 0 + for i = 1, 16 do + local v = V[i] + lo, hi = math.min(lo, v), math.max(hi, v) + if v > 0 and v < 255 then + lo2, hi2 = math.min(lo2, v), math.max(hi2, v) + end + end + local a0, a1 + if lo == hi then + a0, a1 = lo, lo + ramp(a0, a1) + pick() + else + -- 8-value ramp, then a few nudged endpoints + local bestErr, b0, b1 = math.huge, hi, lo + for d0 = 0, 1 do + for d1 = 0, 1 do + local x0, x1 = hi - d0, lo + d1 + if x0 > x1 then + ramp(x0, x1) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, x0, x1 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + end + end + end + -- 6-value ramp with the 0 / 255 extremes + if lo2 > hi2 then + lo2, hi2 = lo, lo + end + ramp(lo2, hi2) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, lo2, hi2 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + a0, a1 = b0, b1 + for i = 1, 16 do + SEL[i] = SELB[i] + end + end + writeu8(out, o, a0) + writeu8(out, o + 1, a1) + local lo24, hi24 = 0, 0 + for i = 8, 1, -1 do + lo24 = lo24 * 8 + SEL[i] + hi24 = hi24 * 8 + SEL[i + 8] + end + writeu8(out, o + 2, band(lo24, 255)) + writeu8(out, o + 3, band(rshift(lo24, 8), 255)) + writeu8(out, o + 4, rshift(lo24, 16)) + writeu8(out, o + 5, band(hi24, 255)) + writeu8(out, o + 6, band(rshift(hi24, 8), 255)) + writeu8(out, o + 7, rshift(hi24, 16)) +end + +-- ------------------------------------------------------------------------------------------------ whole images +-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) +local function gather(px, w, h, bx, by) + for y = 0, 3 do + local sy = math.min(by * 4 + y, h - 1) + for x = 0, 3 do + local sx = math.min(bx * 4 + x, w - 1) + local s = (sy * w + sx) * 4 + local i = y * 4 + x + 1 + R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) + end + end +end + +-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) +function Encode.run(kind, px, w, h, threshold) +local bw, bh = math.floor((w + 3) / 4), math.floor((h + 3) / 4 +) local bytes = (kind == "bc1" or kind == "bc4" )and 8 or 16 + local out = buffer.create(bw * bh * bytes) + local o = 0 + for by = 0, bh - 1 do + for bx = 0, bw - 1 do + gather(px, w, h, bx, by) + if kind == "bc1" then + local any = false + for i = 1, 16 do + local u = A[i] >= threshold + USE[i] = u + any = any or not u + end + colourBlock(out, o, not any) + elseif kind == "bc3" then + for i = 1, 16 do + USE[i] = true + V[i] = A[i] + end + channelBlock(out, o) + colourBlock(out, o + 8, true) + elseif kind == "bc4" then + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + else + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + for i = 1, 16 do + V[i] = G[i] + end + channelBlock(out, o + 8) + end + o =o+ bytes + end + end + return out +end + +return Encode +end +__FILES["codecs/image/Blend"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable +-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer +-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the +-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers. +-- +-- Blend.composite(dst, dw, dh, src, sw, sh, x, y, opacity, "multiply", { clip = false, mask = m }) +-- Blend.MODES.multiply -> true +-- +-- Mode names: normal dissolve darken multiply colorBurn linearBurn darkerColor lighten screen colorDodge linearDodge +-- (= add) lighterColor overlay softLight hardLight vividLight linearLight pinLight hardMix difference exclusion +-- subtract divide hue saturation color luminosity. Unknown names composite as normal. +local Blend = {} + +local readu8, writeu8, readu32, writeu32, blen = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32, buffer.len +local min, max, floor, sqrt, abs = math.min, math.max, math.floor, math.sqrt, math.abs + +local IDS= { + normal = 0, + dissolve = 1, + darken = 2, + multiply = 3, + colorBurn = 4, + linearBurn = 5, + darkerColor = 6, + lighten = 7, + screen = 8, + colorDodge = 9, + linearDodge = 10, + add = 10, + lighterColor = 11, + overlay = 12, + softLight = 13, + hardLight = 14, + vividLight = 15, + linearLight = 16, + pinLight = 17, + hardMix = 18, + difference = 19, + exclusion = 20, + subtract = 21, + divide = 22, + hue = 23, + saturation = 24, + color = 25, + luminosity = 26, +} +local MODES= {} +for k in __iter(IDS) do + MODES[k] = true +end +Blend.MODES = table.freeze(MODES) + +local function burn(cb, cs) +if cb >= 1 then + return 1 + elseif cs <= 0 then + return 0 + end + return 1 - min(1, (1 - cb) / cs) +end +local function dodge(cb, cs) +if cb <= 0 then + return 0 + elseif cs >= 1 then + return 1 + end + return min(1, cb / (1 - cs)) +end + +-- B(cb, cs) of a separable mode +local function sep(m, cb, cs) +if m == 3 then + return cb * cs + elseif m == 8 then + return cb + cs - cb * cs + elseif m == 2 then + return min(cb, cs) + elseif m == 7 then + return max(cb, cs) + elseif m == 12 then -- overlay = hardLight(cs, cb) + if cb <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cb - 1 + return cs + c - cs * c + elseif m == 14 then + if cs <= 0.5 then + return 2 * cb * cs + end + local c = 2 * cs - 1 + return cb + c - cb * c + elseif m == 13 then + if cs <= 0.5 then + return cb - (1 - 2 * cs) * cb * (1 - cb) + end + local d = (cb <= 0.25 and((((16 * cb - 12) * cb + 4) * cb ))or((sqrt(cb) +))) return cb + (2 * cs - 1) * (d - cb) + elseif m == 9 then + return dodge(cb, cs) + elseif m == 4 then + return burn(cb, cs) + elseif m == 5 then + return max(0, cb + cs - 1) + elseif m == 10 then + return min(1, cb + cs) + elseif m == 15 then + if cs <= 0.5 then + return burn(cb, 2 * cs) + end + return dodge(cb, 2 * cs - 1) + elseif m == 16 then + return max(0, min(1, cb + 2 * cs - 1)) + elseif m == 17 then + if cs <= 0.5 then + return min(cb, 2 * cs) + end + return max(cb, 2 * cs - 1) + elseif m == 18 then + return cb + cs >= 1 and 1 or 0 + elseif m == 19 then + return abs(cb - cs) + elseif m == 20 then + return cb + cs - 2 * cb * cs + elseif m == 21 then + return max(0, cb - cs) + elseif m == 22 then + if cs <= 0 then + return cb <= 0 and 0 or 1 + end + return min(1, cb / cs) + end + return cs +end + +-- non-separable helpers (W3C): lum, clip, setLum, sat, setSat +local function lum(r, g, b) +return 0.3 * r + 0.59 * g + 0.11 * b +end +local function clipColor(r, g, b) +local l = lum(r, g, b) + local n = min(r, g, b) + local x = max(r, g, b) + if n < 0 and l - n > 1e-12 then + r, g, b = l + (r - l) * l / (l - n), l + (g - l) * l / (l - n), l + (b - l) * l / (l - n) + end + if x > 1 and x - l > 1e-12 then + r, g, b = l + (r - l) * (1 - l) / (x - l), l + (g - l) * (1 - l) / (x - l), l + (b - l) * (1 - l) / (x - l) + end + return r, g, b +end +local function setLum(r, g, b, l) +local d = l - lum(r, g, b) + return clipColor(r + d, g + d, b + d) +end +local function setSat(r, g, b, s) +local mx = max(r, g, b) + local mn = min(r, g, b) + if mx - mn <= 1e-12 then + return 0, 0, 0 + end + local k = s / (mx - mn) + return (r - mn) * k, (g - mn) * k, (b - mn) * k +end + +-- composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts?): blends the sw x sh rgba8 src onto the dw x dh rgba8 +-- dst with its top-left at (x, y). opacity 0..1. opts.clip: keep the backdrop's alpha (clipping masks). opts.mask: +-- { pixels: buffer (1 byte per pixel), width, height, x, y, default: 0..255 } in dst coordinates (outside it: default). +local function composite(dst, dw, dh, src, sw, sh, x, y, opacity, mode, opts) + x, y = floor(x), floor(y) + if opacity <= 0 or dw <= 0 or dh <= 0 or sw <= 0 or sh <= 0 then + return + end + if blen(dst) < dw * dh * 4 or blen(src) < sw * sh * 4 then + return + end + local op = min(1, opacity) + local m = IDS[mode or "normal"] or 0 + local clip = opts ~= nil and opts.clip == true + local mask = (opts ~= nil and{opts.mask }or{nil +})[1] local mbuf= nil + local mx0, my0, mw, mh, mdef = 0, 0, 0, 0, 1 + if type(mask) == "table" and type(mask.pixels) == "buffer" and type(mask.width) == "number" and type(mask.height) == "number" then + mw, mh = floor(mask.width), (floor(mask.height) ) +if mw > 0 and mh > 0 and blen(mask.pixels) >= mw * mh then + mbuf = mask.pixels + end + mx0, my0 = floor(tonumber(mask.x) or 0), (floor(tonumber(mask.y) or 0) ) +mdef = (tonumber(mask.default) or 255) / 255 + elseif type(mask) == "table" then + mdef = (tonumber(mask.default) or 255) / 255 + end + local x0, y0 = max(0, x), max(0, y) + local x1, y1 = min(dw, x + sw), min(dh, y + sh) + for py = y0, y1 - 1 do + local so = ((py - y) * sw + (x0 - x)) * 4 + local do_ = (py * dw + x0) * 4 + for px = x0, x1 - 1 do + local sa8 = readu8(src, so + 3) + if sa8 ~= 0 then + local sa = sa8 / 255 * op + if mbuf ~= nil or mdef ~= 1 then + local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + sa =sa* mv + end + if m == 1 then -- dissolve: a hash threshold per pixel, full alpha where it shows + local h = (px * 73856093 + py * 19349663) % 65536 / 65536 + sa = h < sa and 1 or 0 + end + local ba8 = readu8(dst, do_ + 3) + if sa > 0 and not (clip and ba8 == 0) then + local sr, sg, sb = readu8(src, so) / 255, readu8(src, so + 1) / 255, readu8(src, so + 2) / 255 + if ba8 == 0 then + -- empty backdrop: the source as it is (alpha scaled) + writeu32(dst, do_, readu32(src, so)) + writeu8(dst, do_ + 3, floor(sa * 255 + 0.5)) + else + local ba = ba8 / 255 + local br, bg, bb = readu8(dst, do_) / 255, readu8(dst, do_ + 1) / 255, readu8(dst, do_ + 2) / 255 + local mr, mg, mb = sr, sg, sb + if m >= 2 and m ~= 6 and m ~= 11 and m < 23 then + mr, mg, mb = sep(m, br, sr), sep(m, bg, sg), (sep(m, bb, sb) ) +elseif m == 6 then + if lum(sr, sg, sb) >= lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 11 then + if lum(sr, sg, sb) < lum(br, bg, bb) then + mr, mg, mb = br, bg, bb + end + elseif m == 23 then + local s = max(br, bg, bb) - min(br, bg, bb) + local r1, g1, b1 = setSat(sr, sg, sb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 24 then + local s = max(sr, sg, sb) - min(sr, sg, sb) + local r1, g1, b1 = setSat(br, bg, bb, s) + mr, mg, mb = setLum(r1, g1, b1, lum(br, bg, bb)) + elseif m == 25 then + mr, mg, mb = setLum(sr, sg, sb, lum(br, bg, bb)) + elseif m == 26 then + mr, mg, mb = setLum(br, bg, bb, lum(sr, sg, sb)) + end + local orr, og, ob, oa + if clip then + -- source-atop: the backdrop's alpha; the mixed colour where the backdrop is opaque + orr = sa * mr + (1 - sa) * br + og = sa * mg + (1 - sa) * bg + ob = sa * mb + (1 - sa) * bb + oa = ba + else + oa = sa + ba * (1 - sa) + local ws, wm, wb = sa * (1 - ba), sa * ba, (1 - sa) * ba + orr = (ws * sr + wm * mr + wb * br) / oa + og = (ws * sg + wm * mg + wb * bg) / oa + ob = (ws * sb + wm * mb + wb * bb) / oa + end + writeu8(dst, do_, floor(max(0, min(1, orr)) * 255 + 0.5)) + writeu8(dst, do_ + 1, floor(max(0, min(1, og)) * 255 + 0.5)) + writeu8(dst, do_ + 2, floor(max(0, min(1, ob)) * 255 + 0.5)) + writeu8(dst, do_ + 3, floor(max(0, min(1, oa)) * 255 + 0.5)) + end + end + end + so =so+ 4 + do_ =do_+ 4 + end + end +end + +-- lerp(dst, from, t, n, w?, mask?): dst = from + (dst - from) * t per byte over n pixels (pass-through group opacity); +-- with a mask ({ pixels, width, height, x, y, default } as for composite, in the coordinates of a w-wide canvas) t is +-- also scaled by the mask value of each pixel +local function lerp(dst, from, t, n, w, mask) + if blen(dst) < n * 4 or blen(from) < n * 4 then + return + end + if mask == nil or w == nil or w <= 0 then + for i = 0, n * 4 - 1 do + local a = readu8(from, i) + writeu8(dst, i, floor(a + (readu8(dst, i) - a) * t + 0.5)) + end + return + end + local mbuf= mask.pixels + local mw, mh = floor(tonumber(mask.width) or 0), floor(tonumber(mask.height) or 0) + local mx0, my0 = floor(tonumber(mask.x) or 0), floor(tonumber(mask.y) or 0) + local mdef = (tonumber(mask.default) or 255) / 255 + if type(mbuf) ~= "buffer" or mw <= 0 or mh <= 0 or blen(mbuf) < mw * mh then + mbuf = nil + end + for p = 0, n - 1 do + local px, py = p % w, math.floor(p / w +) local mv = mdef + local mxx, myy = px - mx0, py - my0 + if mbuf ~= nil and mxx >= 0 and myy >= 0 and mxx < mw and myy < mh then + mv = readu8(mbuf, myy * mw + mxx) / 255 + end + local tt = t * mv + local o = p * 4 + for k = o, o + 3 do + local a = readu8(from, k) + writeu8(dst, k, floor(a + (readu8(dst, k) - a) * tt + 0.5)) + end + end +end +Blend.composite = composite +Blend.lerp = lerp + +-- ------------------------------------------------------------------------------------------------ layer trees +local function isImage(v) +return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function maskOf(l) +local m = l.mask + if type(m) ~= "table" or m.disabled or type(m.image) ~= "table" or type(m.image.pixels) ~= "buffer" then + return nil + end + local img = m.image + local px = img.pixels + if img.format == "rgba8" then -- use the red channel + local n = img.width * img.height + local g = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + px = g + end + return { pixels = px, width = img.width, height = img.height, x = m.x or 0, y = m.y or 0, default = m.default or 255 } +end + +local function compose(layers, canvas, w, h, hidden) + local i = 1 + while i <= #layers do +local __DARKLUA_CONTINUE_8=false repeat local l = layers[i] + i =i+ 1 + if type(l) ~= "table" or (l.visible == false and not hidden) then + -- clipped layers above a hidden base are hidden too + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + i =i+ 1 + end +__DARKLUA_CONTINUE_8=true break + end + local opacity = (tonumber(l.opacity) or 1) * (tonumber(l.fillOpacity) or 1) + local mode = (type(l.blend) == "string" and{l.blend }or{"normal" +})[1] -- the layer's own pixels, as an isolated w x h buffer + local src= nil + if type(l.children) == "table" then + if mode == "passThrough" then + local before = buffer.create(w * h * 4) + buffer.copy(before, 0, canvas, 0, w * h * 4) + compose(l.children, canvas, w, h, hidden) + -- the group's opacity and mask limit how much of its effect reaches the canvas (as in Photoshop) + local gm = maskOf(l) + if opacity < 1 or gm ~= nil then + lerp(canvas, before, opacity, w * h, w, gm) + end +__DARKLUA_CONTINUE_8=true break + end + src = buffer.create(w * h * 4) + compose(l.children, src , w, h, hidden) + elseif isImage(l.image) then + if l.image.width > 0 and l.image.height > 0 then + local b = buffer.create(w * h * 4) + composite(b, w, h, l.image.pixels, l.image.width, l.image.height, tonumber(l.x) or 0, tonumber(l.y) or 0, 1, "normal") + src = b + end + end + -- clipping layers above this one: composited onto it with their alpha limited to it + while i <= #layers and type(layers[i]) == "table" and layers[i].clip do + local c = layers[i] + i =i+ 1 + if src and (c.visible ~= false or hidden) and isImage(c.image) then + composite(src , w, h, c.image.pixels, c.image.width, c.image.height, tonumber(c.x) or 0, tonumber(c.y) or 0, (tonumber(c.opacity) or 1) * (tonumber(c.fillOpacity) or 1), c.blend, { clip = true, mask = maskOf(c) }) + end + end + if src then + composite(canvas, w, h, src , w, h, 0, 0, opacity, mode, { mask = maskOf(l) }) + end +__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end +end + +-- flatten(layers, canvas, w, h, hidden): composites a Types.Layer tree (bottom to top) onto the w x h rgba8 canvas: +-- blend modes, opacity x fillOpacity, groups (isolated, or "passThrough": blended straight onto the canvas, the group +-- opacity and mask then mixing before / after), clipping layers (clip = true: source-atop onto the layer below), grey masks. +-- hidden = true includes invisible layers. +function Blend.flatten(layers, canvas, w, h, hidden) + if blen(canvas) >= w * h * 4 then + compose(layers, canvas, w, h, hidden) + end +end + +return Blend +end +__FILES["codecs/image/Dct"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). +-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with +-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the +-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author). +-- Forward: libjpeg's islow (jfdctint.c) with jcdctmgr.c's rounding quantiser, so an encoder built on it produces +-- the same coefficients as cjpeg. Both are Luau translations of IJG code (licenses/libjpeg-turbo-LICENSE.md). +-- Values are exact integers in doubles: no overflow even on corrupt coefficients; outputs are clamped to 0..maxv. +-- +-- Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv) -- every block of a component +-- Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) -- one 8x8 block (u16 samples) +-- Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) -- one block from u8 samples +local readi16, readu16, writeu16, readu8, writei16 = buffer.readi16, buffer.readu16, buffer.writeu16, buffer.readu8, buffer.writei16 +local clamp = math.clamp + +local Dct = {} + +local ws = table.create(64, 0) + +local function idct8(coef, off, q, plane, out, stride, p1, center, maxv) + local s1 = 2 ^ (13 - p1) + local h1 = s1 / 2 + local s2 = 2 ^ (16 + p1) + local h2 = s2 / 2 + center * s2 + local dcm = 2 ^ p1 + for c = 0, 7 do + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c4, c5, c6, c7 = readi16(coef, o + 64), readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + ws[c + 33] = dc + ws[c + 41] = dc + ws[c + 49] = dc + ws[c + 57] = dc + else + -- even part + local z2 = c2 * readu16(q, qo + 32) + local z3 = c6 * readu16(q, qo + 96) + local z1 = (z2 + z3) * 4433 + local tmp2 = z1 - z3 * 15137 + local tmp3 = z1 + z2 * 6270 + z2 = readi16(coef, o) * readu16(q, qo) + z3 = c4 * readu16(q, qo + 64) + local tmp0 = (z2 + z3) * 8192 + local tmp1 = (z2 - z3) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + -- odd part + local t0 = c7 * readu16(q, qo + 112) + local t1 = c5 * readu16(q, qo + 80) + local t2 = c3 * readu16(q, qo + 48) + local t3 = c1 * readu16(q, qo + 16) + z1 = t0 + t3 + z2 = t1 + t2 + z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 =t0* 2446 + t1 =t1* 16819 + t2 =t2* 25172 + t3 =t3* 12299 + z1 =z1* -7373 + z2 =z2* -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 =t0+ (z1 + z3 +) t1 =t1+ (z2 + z4 +) t2 =t2+ (z2 + z3 +) t3 =t3+ (z1 + z4 +) ws[c + 1] = math.floor((tmp10 + t3 + h1) / s1 +) ws[c + 57] = math.floor((tmp10 - t3 + h1) / s1 +) ws[c + 9] = math.floor((tmp11 + t2 + h1) / s1 +) ws[c + 49] = math.floor((tmp11 - t2 + h1) / s1 +) ws[c + 17] = math.floor((tmp12 + t1 + h1) / s1 +) ws[c + 41] = math.floor((tmp12 - t1 + h1) / s1 +) ws[c + 25] = math.floor((tmp13 + t0 + h1) / s1 +) ws[c + 33] = math.floor((tmp13 - t0 + h1) / s1 +) end + end + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 7 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w4, w5, w6, w7 = ws[b + 5], ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w4 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp(math.floor((w0 + hd) / sd), 0, maxv) + for i = 0, 14, 2 do + writeu16(plane, o + i, v) + end + else + local z1 = (w2 + w6) * 4433 + local tmp2 = z1 - w6 * 15137 + local tmp3 = z1 + w2 * 6270 + local tmp0 = (w0 + w4) * 8192 + local tmp1 = (w0 - w4) * 8192 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local t0, t1, t2, t3 = w7, w5, w3, w1 + z1 = t0 + t3 + local z2 = t1 + t2 + local z3 = t0 + t2 + local z4 = t1 + t3 + local z5 = (z3 + z4) * 9633 + t0 =t0* 2446 + t1 =t1* 16819 + t2 =t2* 25172 + t3 =t3* 12299 + z1 =z1* -7373 + z2 =z2* -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + t0 =t0+ (z1 + z3 +) t1 =t1+ (z2 + z4 +) t2 =t2+ (z2 + z3 +) t3 =t3+ (z1 + z4 +) writeu16(plane, o, clamp(math.floor((tmp10 + t3 + h2) / s2), 0, maxv)) + writeu16(plane, o + 14, clamp(math.floor((tmp10 - t3 + h2) / s2), 0, maxv)) + writeu16(plane, o + 2, clamp(math.floor((tmp11 + t2 + h2) / s2), 0, maxv)) + writeu16(plane, o + 12, clamp(math.floor((tmp11 - t2 + h2) / s2), 0, maxv)) + writeu16(plane, o + 4, clamp(math.floor((tmp12 + t1 + h2) / s2), 0, maxv)) + writeu16(plane, o + 10, clamp(math.floor((tmp12 - t1 + h2) / s2), 0, maxv)) + writeu16(plane, o + 6, clamp(math.floor((tmp13 + t0 + h2) / s2), 0, maxv)) + writeu16(plane, o + 8, clamp(math.floor((tmp13 - t0 + h2) / s2), 0, maxv)) + end + end +end + +local function idct4(coef, off, q, plane, out, stride, p1, center, maxv) + local s1 = 2 ^ (14 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 4 then + local o = off + c * 2 + local qo = c * 2 + local c1, c2, c3 = readi16(coef, o + 16), readi16(coef, o + 32), readi16(coef, o + 48) + local c5, c6, c7 = readi16(coef, o + 80), readi16(coef, o + 96), readi16(coef, o + 112) + if c1 == 0 and c2 == 0 and c3 == 0 and c5 == 0 and c6 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + ws[c + 17] = dc + ws[c + 25] = dc + else + local tmp0 = readi16(coef, o) * readu16(q, qo) * 16384 + local tmp2 = c2 * readu16(q, qo + 32) * 15137 - c6 * readu16(q, qo + 96) * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + local z1 = c7 * readu16(q, qo + 112) + local z2 = c5 * readu16(q, qo + 80) + local z3 = c3 * readu16(q, qo + 48) + local z4 = c1 * readu16(q, qo + 16) + tmp0 = z1 * -1730 + z2 * 11893 + z3 * -17799 + z4 * 8697 + tmp2 = z1 * -4176 + z2 * -4926 + z3 * 7373 + z4 * 20995 + ws[c + 1] = math.floor((tmp10 + tmp2 + h1) / s1 +) ws[c + 25] = math.floor((tmp10 - tmp2 + h1) / s1 +) ws[c + 9] = math.floor((tmp12 + tmp0 + h1) / s1 +) ws[c + 17] = math.floor((tmp12 - tmp0 + h1) / s1 +) end + end + end + local s2 = 2 ^ (17 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 3 do + local b = r * 8 + local w0, w1, w2, w3 = ws[b + 1], ws[b + 2], ws[b + 3], ws[b + 4] + local w5, w6, w7 = ws[b + 6], ws[b + 7], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w2 == 0 and w3 == 0 and w5 == 0 and w6 == 0 and w7 == 0 then + local v = clamp(math.floor((w0 + hd) / sd), 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + writeu16(plane, o + 4, v) + writeu16(plane, o + 6, v) + else + local tmp0 = w0 * 16384 + local tmp2 = w2 * 15137 - w6 * 6270 + local tmp10, tmp12 = tmp0 + tmp2, tmp0 - tmp2 + tmp0 = w7 * -1730 + w5 * 11893 + w3 * -17799 + w1 * 8697 + tmp2 = w7 * -4176 + w5 * -4926 + w3 * 7373 + w1 * 20995 + writeu16(plane, o, clamp(math.floor((tmp10 + tmp2 + h2) / s2), 0, maxv)) + writeu16(plane, o + 6, clamp(math.floor((tmp10 - tmp2 + h2) / s2), 0, maxv)) + writeu16(plane, o + 2, clamp(math.floor((tmp12 + tmp0 + h2) / s2), 0, maxv)) + writeu16(plane, o + 4, clamp(math.floor((tmp12 - tmp0 + h2) / s2), 0, maxv)) + end + end +end + +local function idct2(coef, off, q, plane, out, stride, p1, center, maxv) + local s1 = 2 ^ (15 - p1) + local h1 = s1 / 2 + local dcm = 2 ^ p1 + for c = 0, 7 do + if c ~= 2 and c ~= 4 and c ~= 6 then + local o = off + c * 2 + local qo = c * 2 + local c1, c3 = readi16(coef, o + 16), readi16(coef, o + 48) + local c5, c7 = readi16(coef, o + 80), readi16(coef, o + 112) + if c1 == 0 and c3 == 0 and c5 == 0 and c7 == 0 then + local dc = readi16(coef, o) * readu16(q, qo) * dcm + ws[c + 1] = dc + ws[c + 9] = dc + else + local tmp10 = readi16(coef, o) * readu16(q, qo) * 32768 + local tmp0 = c7 * readu16(q, qo + 112) * -5906 + + c5 * readu16(q, qo + 80) * 6967 + + c3 * readu16(q, qo + 48) * -10426 + + c1 * readu16(q, qo + 16) * 29692 + ws[c + 1] = math.floor((tmp10 + tmp0 + h1) / s1 +) ws[c + 9] = math.floor((tmp10 - tmp0 + h1) / s1 +) end + end + end + local s2 = 2 ^ (18 + p1) + local h2 = s2 / 2 + center * s2 + local sd = 2 ^ (p1 + 3) + local hd = sd / 2 + center * sd + for r = 0, 1 do + local b = r * 8 + local w0, w1, w3, w5, w7 = ws[b + 1], ws[b + 2], ws[b + 4], ws[b + 6], ws[b + 8] + local o = (out + r * stride) * 2 + if w1 == 0 and w3 == 0 and w5 == 0 and w7 == 0 then + local v = clamp(math.floor((w0 + hd) / sd), 0, maxv) + writeu16(plane, o, v) + writeu16(plane, o + 2, v) + else + local tmp10 = w0 * 32768 + local tmp0 = w7 * -5906 + w5 * 6967 + w3 * -10426 + w1 * 29692 + writeu16(plane, o, clamp(math.floor((tmp10 + tmp0 + h2) / s2), 0, maxv)) + writeu16(plane, o + 2, clamp(math.floor((tmp10 - tmp0 + h2) / s2), 0, maxv)) + end + end +end + +-- Inverse-transforms every block of a component: coef (i16, 64 per block, natural order) on a bpl x bpc block +-- grid, quantisation table q (64 u16, natural order), into plane (u16 samples, (bpl * size) per row) at size x +-- size samples per block. p1 is PASS1_BITS (2 for 8-bit, 1 for 12-bit), center the level shift, maxv the top. +-- hook (optional): a cooperative yield point after every block row (pcall'ed: it can't throw through here). +function Dct.idctComponent(coef, q, bpl, bpc, size, plane, p1, center, maxv, hook) + local stride = bpl * size + for by = 0, bpc - 1 do + if hook and by > 0 then + pcall(hook) + end + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + local out = by * size * stride + bx * size + if size == 8 then + idct8(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 4 then + idct4(coef, off, q, plane, out, stride, p1, center, maxv) + elseif size == 2 then + idct2(coef, off, q, plane, out, stride, p1, center, maxv) + else + local v = math.floor((readi16(coef, off) * readu16(q, 0) + 4) / 8 )+ center + writeu16(plane, out * 2, clamp(v, 0, maxv)) + end + end + end +end + +-- idctBlock(coef, off, q, plane, out, stride, p1, center, maxv): one 8x8 block, coef (i16, natural order) at byte +-- offset off, dequantised by q (64 u16), into the u16 plane at sample index out with stride samples per row +function Dct.idctBlock(coef, off, q, plane, out, stride, p1, center, maxv) + idct8(coef, off, q, plane, out, stride, p1, center, maxv) +end + +-- ------------------------------------------------------------------------------------------------ forward +local fw = table.create(64, 0) + +local function quant(coef, off, div, v, i) + local qv = readu16(div, i * 2) * 8 + local h = math.floor(qv / 2 +) if v < 0 then + writei16(coef, off + i * 2, -(math.floor((h - v) / qv))) + else + writei16(coef, off + i * 2, math.floor((v + h) / qv)) + end +end + +-- fdctQuantize(src, stride, x, y, w, h, div, coef, off): the 8x8 block of u8 samples at (x, y) in src (stride bytes +-- per row; samples past w - 1 / h - 1 repeat the edge), level-shifted by 128, forward DCT (jfdctint.c islow), then +-- quantised as jcdctmgr.c: (|v| + q * 4) // (q * 8) with the sign restored, q = div (64 u16, natural order). Writes +-- 64 i16 at coef[off] (natural order). The caller keeps x < w, y < h and the src range valid. +function Dct.fdctQuantize(src, stride, x, y, w, h, div, coef, off) + local lastX, lastY = w - 1, h - 1 + for r = 0, 7 do + local row = math.min(y + r, lastY) * stride + local d0, d1, d2, d3, d4, d5, d6, d7 +if x + 7 <= lastX then + local p = row + x + d0, d1, d2, d3 = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), (readu8(src, p + 3) ) +d4, d5, d6, d7 = readu8(src, p + 4), readu8(src, p + 5), readu8(src, p + 6), (readu8(src, p + 7) ) +else + d0 = readu8(src, row + math.min(x, lastX)) + d1 = readu8(src, row + math.min(x + 1, lastX)) + d2 = readu8(src, row + math.min(x + 2, lastX)) + d3 = readu8(src, row + math.min(x + 3, lastX)) + d4 = readu8(src, row + math.min(x + 4, lastX)) + d5 = readu8(src, row + math.min(x + 5, lastX)) + d6 = readu8(src, row + math.min(x + 6, lastX)) + d7 = readu8(src, row + math.min(x + 7, lastX)) + end + d0 =d0- 128 + d1 =d1- 128 + d2 =d2- 128 + d3 =d3- 128 + d4 =d4- 128 + d5 =d5- 128 + d6 =d6- 128 + d7 =d7- 128 + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local b = r * 8 + 1 + fw[b] = (tmp10 + tmp11) * 4 + fw[b + 4] = (tmp10 - tmp11) * 4 + local z1 = (tmp12 + tmp13) * 4433 + fw[b + 2] = math.floor((z1 + tmp13 * 6270 + 1024) / 2048 +) fw[b + 6] = math.floor((z1 - tmp12 * 15137 + 1024) / 2048 +) z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 =tmp4* 2446 + tmp5 =tmp5* 16819 + tmp6 =tmp6* 25172 + tmp7 =tmp7* 12299 + z1 =z1* -7373 + z2 =z2* -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + fw[b + 7] = math.floor((tmp4 + z1 + z3 + 1024) / 2048 +) fw[b + 5] = math.floor((tmp5 + z2 + z4 + 1024) / 2048 +) fw[b + 3] = math.floor((tmp6 + z2 + z3 + 1024) / 2048 +) fw[b + 1] = math.floor((tmp7 + z1 + z4 + 1024) / 2048 +) end + for c = 1, 8 do + local d0, d1, d2, d3 = fw[c], fw[c + 8], fw[c + 16], fw[c + 24] + local d4, d5, d6, d7 = fw[c + 32], fw[c + 40], fw[c + 48], fw[c + 56] + local tmp0, tmp7 = d0 + d7, d0 - d7 + local tmp1, tmp6 = d1 + d6, d1 - d6 + local tmp2, tmp5 = d2 + d5, d2 - d5 + local tmp3, tmp4 = d3 + d4, d3 - d4 + local tmp10, tmp13 = tmp0 + tmp3, tmp0 - tmp3 + local tmp11, tmp12 = tmp1 + tmp2, tmp1 - tmp2 + local o0 = math.floor((tmp10 + tmp11 + 2) / 4 +) local o4 = math.floor((tmp10 - tmp11 + 2) / 4 +) local z1 = (tmp12 + tmp13) * 4433 + local o2 = math.floor((z1 + tmp13 * 6270 + 16384) / 32768 +) local o6 = math.floor((z1 - tmp12 * 15137 + 16384) / 32768 +) z1 = tmp4 + tmp7 + local z2 = tmp5 + tmp6 + local z3 = tmp4 + tmp6 + local z4 = tmp5 + tmp7 + local z5 = (z3 + z4) * 9633 + tmp4 =tmp4* 2446 + tmp5 =tmp5* 16819 + tmp6 =tmp6* 25172 + tmp7 =tmp7* 12299 + z1 =z1* -7373 + z2 =z2* -20995 + z3 = z3 * -16069 + z5 + z4 = z4 * -3196 + z5 + local o7 = math.floor((tmp4 + z1 + z3 + 16384) / 32768 +) local o5 = math.floor((tmp5 + z2 + z4 + 16384) / 32768 +) local o3 = math.floor((tmp6 + z2 + z3 + 16384) / 32768 +) local o1 = math.floor((tmp7 + z1 + z4 + 16384) / 32768 +) local cc = c - 1 + quant(coef, off, div, o0, cc) + quant(coef, off, div, o1, cc + 8) + quant(coef, off, div, o2, cc + 16) + quant(coef, off, div, o3, cc + 24) + quant(coef, off, div, o4, cc + 32) + quant(coef, off, div, o5, cc + 40) + quant(coef, off, div, o6, cc + 48) + quant(coef, off, div, o7, cc + 56) + end +end + +return Dct +end +__FILES["codecs/image/Etc"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar +-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 +-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new +-- in rosetta. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. +-- +-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels +-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) +-- Etc.size("etc1", w, h) -- bytes of the block data +-- +-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), +-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +local Etc = {} + +Etc.BLOCK = (table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) ) + +local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap + +-- ------------------------------------------------------------------------------------------------ tables +local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b + { 2, 8, -2, -8 }, + { 5, 17, -5, -17 }, + { 9, 29, -9, -29 }, + { 13, 42, -13, -42 }, + { 18, 60, -18, -60 }, + { 24, 80, -24, -80 }, + { 33, 106, -33, -106 }, + { 47, 183, -47, -183 }, +} +local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances +local EAC = { + { -3, -6, -9, -15, 2, 5, 8, 14 }, + { -3, -7, -10, -13, 2, 6, 9, 12 }, + { -2, -5, -8, -13, 1, 4, 7, 12 }, + { -2, -4, -6, -13, 1, 3, 5, 12 }, + { -3, -6, -8, -12, 2, 5, 7, 11 }, + { -3, -7, -9, -11, 2, 6, 8, 10 }, + { -4, -7, -8, -11, 3, 6, 7, 10 }, + { -3, -5, -8, -11, 2, 4, 7, 10 }, + { -2, -6, -8, -10, 1, 5, 7, 9 }, + { -2, -5, -8, -10, 1, 4, 7, 9 }, + { -2, -4, -8, -10, 1, 3, 7, 9 }, + { -2, -5, -7, -10, 1, 4, 6, 9 }, + { -3, -4, -7, -10, 2, 3, 6, 9 }, + { -1, -2, -3, -10, 0, 1, 2, 9 }, + { -4, -6, -8, -9, 3, 5, 7, 8 }, + { -3, -5, -7, -9, 2, 4, 6, 8 }, +} + +local function clamp8(v) +return v < 0 and 0 or(v > 255 and 255 or v +)end +local function rgb(r, g, b) +return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 +end + +-- ------------------------------------------------------------------------------------------------ colour blocks +-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) +local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) + +local function be32(src, p) +return byteswap(readu32(src, p)) +end + +-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) +local function pix(lo, i) +return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) +end + +-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +local function colour(src, p, blk, etc2, punch) + local hi, lo = be32(src, p), be32(src, p + 4) + local diffBit = band(rshift(hi, 1), 1) + local flip = band(hi, 1) + local opaque = not punch or diffBit == 1 + local r1, g1, b1, r2, g2, b2 + if not punch and diffBit == 0 then + r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17 + g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17 + else + local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31) + local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7) + if dR >= 4 then + dR =dR- 8 + end + if dG >= 4 then + dG =dG- 8 + end + if dB >= 4 then + dB =dB- 8 + end + local R2, G2, B2 = R + dR, G + dG, B + dB + if etc2 and (R2 < 0 or R2 > 31) then + -- T mode + local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3) + local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17 + local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1] + P[1] = rgb(c1r, c1g, c1b) + P[2] = rgb(c2r + d, c2g + d, c2b + d) + P[3] = rgb(c2r, c2g, c2b) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (G2 < 0 or G2 > 31) then + -- H mode + local q1r = band(rshift(hi, 27), 15) + local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1) + local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7) + local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15) + local order = q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b and 1 or 0 + local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1] + local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17 + P[1] = rgb(c1r + d, c1g + d, c1b + d) + P[2] = rgb(c1r - d, c1g - d, c1b - d) + P[3] = rgb(c2r + d, c2g + d, c2b + d) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (B2 < 0 or B2 > 31) then + -- planar (always opaque) + local ro = band(rshift(hi, 25), 63) + local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63) + local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7) + local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1) + local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63) + local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63) + ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4) + go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6) + bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4) + for y = 0, 3 do + for x = 0, 3 do + local r = math.floor((x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) / 4 +) local g = math.floor((x * (gh - go) + y * (gv - go) + 4 * go + 2) / 4 +) local b = math.floor((x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) / 4 +) writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b)) + end + end + return + else + r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2) + r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) + end + if not r1 then + -- T / H: the paint colours by index + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local idx = pix(lo, i) + local c = not opaque and idx == 2 and 0 or P[idx + 1] + writeu32(blk, (y * 4 + x) * 4, c) + end + return + end + end + local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1] + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local second = (flip == 0 and{(x >= 2 )}or{(y >= 2 +)})[1] local idx = pix(lo, i) + local c + if not opaque and idx == 2 then + c = 0 + else + local m = (second and{t2[idx + 1] }or{t1[idx + 1] +})[1] if not opaque and idx == 0 then + m = 0 + end + if second then + c = rgb((r2 ) + m, (g2 ) + m, (b2 ) + m) + else + c = rgb((r1 ) + m, (g1 ) + m, (b1 ) + m) + end + end + writeu32(blk, (y * 4 + x) * 4, c) + end +end + +-- ------------------------------------------------------------------------------------------------ EAC +local VALS = table.create(16, 0) + +-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) +local function eac(src, p, mode) + local base = readu8(src, p) + local b1 = readu8(src, p + 1) + local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] + -- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits + local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4) + local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7) + if mode == "s11" then + if base >= 128 then + base =base- 256 + end + if base == -128 then + base = -127 + end + end + for i = 0, 15 do + local idx = (i < 8 and{(band(rshift(hiIdx, 21 - i * 3), 7) )}or{(band(rshift(loIdx, 21 - (i - 8) * 3), 7) +)})[1] local m = tab[idx + 1] + local v + if mode == "alpha" then + v = clamp8(base + m * mult) + elseif mode == "u11" then + v = (mult == 0 and((base * 8 + 4 + m ))or((base * 8 + 4 + m * mult * 8 +))) v = v < 0 and 0 or(v > 2047 and 2047 or v +) else + v = (mult == 0 and((base * 8 + m ))or((base * 8 + m * mult * 8 +))) v = v < -1023 and-1023 or(v > 1023 and 1023 or v +) end + VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v + end +end + +-- 11-bit values -> 8 / 16 bits +local function to8(v, signed) +if signed then + return math.floor(v * 127 / 1023 + 0.5) + 128 + end + return math.floor(v * 255 / 2047 + 0.5) +end +local function to16(v, signed) +if signed then + return math.floor((v + 1023) * 65535 / 2046 + 0.5) + end + return v * 32 + rshift(v, 6) +end + +-- ------------------------------------------------------------------------------------------------ decode +-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind +function Etc.size(kind, w, h) +local b = Etc.BLOCK[kind] + return (b and(((math.floor((w + 3) / 4)) * (math.floor((h + 3) / 4)) * b ))or(nil +))end + +-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC +-- kinds when wide is true. +function Etc.decode(kind, src, offset, w, h, out, outOffset, wide) +local bytes = Etc.BLOCK[kind] + if not bytes then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = (Etc.size(kind, w, h) ) +if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local isEac = string.sub(kind, 1, 3) == "eac" + local w16 = isEac and wide == true + local bpp = w16 and 8 or 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local signed = kind == "eac_r11s" or kind == "eac_rg11s" + local two = kind == "eac_rg11" or kind == "eac_rg11s" + local mode11 = signed and"s11" or"u11" + local etc2 = kind ~= "etc1" + local punch = kind == "etc2_rgba1" + local blk = buffer.create(16 * bpp) + local bw, bh = math.floor((w + 3) / 4), math.floor((h + 3) / 4 +) local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + if isEac then + eac(src, p, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + local q = to16(v, signed) + writeu16(blk, i * 8, q) + writeu16(blk, i * 8 + 2, two and 0 or q) + writeu16(blk, i * 8 + 4, two and 0 or q) + writeu16(blk, i * 8 + 6, 65535) + else + local q = to8(v, signed) + writeu32(blk, i * 4, (two and((q + 0xFF000000 ))or((q + q * 256 + q * 65536 + 0xFF000000)))) + end + end + if two then + eac(src, p + 8, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + writeu16(blk, i * 8 + 2, to16(v, signed)) + else + writeu8(blk, i * 4 + 1, to8(v, signed)) + end + end + end + elseif kind == "etc2_rgba" then + colour(src, p + 8, blk, true, false) + eac(src, p, "alpha") + for i = 0, 15 do + writeu8(blk, i * 4 + 3, VALS[i + 1]) + end + else + colour(src, p, blk, etc2, punch) + end + p =p+ bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + return dst, nil +end + +return Etc +end +__FILES["codecs/image/Half"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, +-- OpenEXR HALF channels). New in rosetta. Never throws. +-- +-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) +-- local f = Half.toFloat(h) -- the same, computed +-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +local Half = {} + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +-- toFloat(h) -> number (h a 16-bit pattern) +local function toFloat(h) +local s = h >= 32768 and-1 or 1 + local e = band(rshift(h, 10), 31) + local m = band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return (m == 0 and((s * math.huge ))or((0 / 0 +))) end + return s * (1024 + m) * 2 ^ (e - 25) +end +Half.toFloat = toFloat + +local TABLE= table.create(65536, 0) +for h = 0, 65535 do + TABLE[h] = toFloat(h) +end +Half.TABLE = TABLE + +local scratch = buffer.create(4) + +-- fromFloat(f) -> the nearest half bit pattern (ties to even) +function Half.fromFloat(f) +if f ~= f then + return 0x7E00 + end + buffer.writef32(scratch, 0, f) + local x = buffer.readu32(scratch, 0) + local sign = band(rshift(x, 16), 0x8000) + local e = band(rshift(x, 23), 0xFF) + local m = band(x, 0x7FFFFF) + if e == 255 then + return bor(sign, 0x7C00) + end + local ne = e - 112 + if ne >= 31 then + return bor(sign, 0x7C00) + elseif ne <= 0 then + if ne < -10 then + return sign + end + m = bor(m, 0x800000) + local shift = 14 - ne + local hm = rshift(m, shift) + local rem = band(m, lshift(1, shift) - 1) + local halfway = lshift(1, shift - 1) + if rem > halfway or (rem == halfway and band(hm, 1) == 1) then + hm =hm+ 1 + end + return sign + hm + end + local hm = rshift(m, 13) + local rem = band(m, 0x1FFF) + if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then + hm =hm+ 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should + end + return sign + ne * 1024 + hm +end + +return Half +end +__FILES["codecs/image/Jpeg"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG +-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and +-- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder) +-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's +-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md. +-- +-- local img, err = Jpeg.decode(buf, off?, len?, opts?) -- one JPEG -> rgba8 (or gray8 / yuv420p) Types.Image +-- local img = Jpeg.decode(frame, 0, n, { yuv = true }) -- video: yuv420p straight from the IDCT planes +-- local out, err = Jpeg.encode(img, opts?) -- rgba8 / rgb8 / gray8 / yuv420p Image -> buffer +-- local info, err = Jpeg.info(buf, off?, len?) -- the headers up to the frame header +-- +-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit +-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt +-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8), EXIF orientation +-- (meta.orientation, applied with opts.orient). Truncated or corrupt scans decode as far as they go +-- (meta.truncated = true). +-- Motion-JPEG: frames without DHT segments use the T.81 annex K tables; the AVI1 APP0 segment is read (its field +-- polarity) and data after EOI is ignored. Two fields back to back (AVI1 interlaced: two JPEGs of half the frame +-- height, polarity 1 or 2, or opts.fields = true) are decoded and woven into one frame, the first field on the even +-- rows (top field first, as ffmpeg, which ignores the polarity value); a missing or different-sized second field +-- leaves the first field alone (meta.source.fields = 1). +-- opts.yuv: 8-bit YCbCr frames come out as yuv420p (full-range BT.601, meta.source.range = "full") without colour +-- conversion or upsampling: 4:2:0 (2x2 luma) as the planes are; 4:2:2 (2x1 luma, the usual Motion-JPEG camera +-- layout) with each pair of chroma rows averaged; 4:4:4 with 2 x 2 chroma averages; grey with chroma 128. Other +-- layouts (RGB, CMYK, 4:1:1, 4:4:0, 12-bit) and scaled decodes fall back to rgba8 (check img.format). +-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or +-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, extra APPn / COM segments +-- (opts.segments); yuv420p input is coded from its planes as they are (4:2:0, no colour conversion). +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, 12-bit or CMYK encoding. +-- Never throws: bad data or arguments return nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Jpeg/Decode") +local Encode = __include("codecs/image/Jpeg/Encode") +local Yuv = __include("codecs/image/Jpeg/Yuv") + +local Jpeg = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function range(buf, off, len) +local n = buffer.len(buf) + local o = math.clamp(math.floor(tonumber(off) or 0), 0, n) + return o, math.clamp(math.floor(tonumber(len) or (n - o)), 0, n - o) +end + +-- the marker parser over [o, o + l): State | nil, Err +local function parse(buf, o, l, opts, headerOnly) +local ok, st, code, msg = pcall(Decode.parse, buf, o, o + l, opts, headerOnly) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(st)) + end + if not st then + return nil, Err.from(msg or "decode failed", o, code) + end + return st, nil +end + +local function samplingOf(f) +local sampling = {} + for _, c in __iter(f.comps) do + table.insert(sampling, { c.h, c.v }) + end + return sampling +end + +-- info(buf, off?, len?) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(buf, off, len) +if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + local o, l = range(buf, off, len) + local st, err = parse(buf, o, l, nil, true) + if not st then + return nil, err + end + local f = st.frame + return { + width = f.width, + height = f.height, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + precision = f.precision, + colorSpace = Decode.colorSpaceOf(f, st.adobe, st.jfif), + sampling = samplingOf(f), + orientation = st.orientation, + adobe = st.adobe, + jfif = st.jfif, + avi1 = st.avi1, + }, + nil +end + +-- the EXIF orientation applied to rgba8 pixels: buffer, width, height +local function orient(px, w, h, o) +if o <= 1 or o > 8 then + return px, w, h + end + local swap = o >= 5 + local ow, oh = (swap and{h }or{w})[1], (swap and{w }or{h +})[1] local out = buffer.create(ow * oh * 4) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for y = 0, oh - 1 do + for x = 0, ow - 1 do + local col, row + if o == 2 then + col, row = w - 1 - x, y + elseif o == 3 then + col, row = w - 1 - x, h - 1 - y + elseif o == 4 then + col, row = x, h - 1 - y + elseif o == 5 then + col, row = y, x + elseif o == 6 then + col, row = y, h - 1 - x + elseif o == 7 then + col, row = w - 1 - y, h - 1 - x + else + col, row = w - 1 - y, x + end + writeu32(out, (y * ow + x) * 4, readu32(px, (row * w + col) * 4)) + end + end + return out, ow, oh +end + +-- one JPEG at [o, o + l): Image, State | nil, Err +local function decodeOne(buf, o, l, opts) +local st, err = parse(buf, o, l, opts, false) + if not st then + return nil, err + end + local s = st +local img = Types.Image.new(0, 0) + local space, mode = nil, nil + if opts and opts.yuv then + local ok, w, h, px, m = pcall(Decode.outputYuv, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if w then + img.width, img.height, img.pixels, img.format = w, h , px , "yuv420p" + mode = m + space = Decode.colorSpaceOf(s.frame, s.adobe, s.jfif) + end + end + if not mode then + local ok, w, h, px, sp = pcall(Decode.output, s) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(w)) + end + if not w then + return nil, Err.from(px, o, h) + end + space = sp + if opts and opts.orient then + px, w, h = orient(px, w, h, s.orientation) + end + img.width, img.height, img.pixels = w, h, px + if opts and opts.native and space == "gray" then + local g = buffer.create(w * h) + for i = 0, w * h - 1 do + buffer.writeu8(g, i, buffer.readu8(px, i * 4)) + end + img.pixels, img.format = g, "gray8" + end + end + local f = s.frame + local meta = img.meta + meta.orientation = s.orientation + meta.oriented = (opts and opts.orient and not mode) or false + meta.exif = s.exif + meta.icc = s.icc + if #s.comments > 0 then + meta.text = { comment = table.concat(s.comments, "\n") } + end + if s.density and s.density.unit > 0 and s.density.x > 0 and s.density.y > 0 then + local k = s.density.unit == 2 and 2.54 or 1 + meta.dpi = { x = s.density.x * k, y = s.density.y * k } + end + meta.truncated = s.truncated + meta.source = { + format = "jpeg", + bitDepth = f.precision, + colorType = space, + components = #f.comps, + progressive = f.progressive, + arithmetic = f.arithmetic, + sampling = samplingOf(f), + scale = s.scale, + adobe = s.adobe, + jfif = s.jfif, + avi1 = s.avi1, + yuv = mode, -- "420" | "422" | "444" | "gray": how the yuv420p planes were made (opts.yuv) + range = mode and"full" or nil, + fields = 1, + } + return img, s +end + +-- the start of a second JPEG (FF D8 FF) at or after p, before e; -1 if none +local function nextSoi(buf, p, e) +local readu8 = buffer.readu8 + while p + 3 <= e do + if readu8(buf, p) == 0xFF and readu8(buf, p + 1) == 0xD8 and readu8(buf, p + 2) == 0xFF then + return p + end + p =p+ 1 + end + return -1 +end + +-- two fields (same size and format) -> one frame of twice the height, field a on the even rows +local function weave(a, b) +local w, hf = a.width, a.height + local h = hf * 2 + local out = Types.Image.new(w, h, a.format) + local dst = out.pixels + if a.format == "yuv420p" then + local cw, chf = math.floor((w + 1) / 2), math.floor((hf + 1) / 2 +) local ch = math.floor((h + 1) / 2 -- = hf +) Yuv.weave(a.pixels, 0, b.pixels, 0, w, h, dst, 0) + for k = 0, 1 do + Yuv.weave(a.pixels, w * hf + k * cw * chf, b.pixels, w * hf + k * cw * chf, cw, ch, dst, w * h + k * cw * ch) + end + else + local bpp = Types.Image.bpp(a.format) or 4 + Yuv.weave(a.pixels, 0, b.pixels, 0, w * bpp, h, dst, 0) + end + out.meta = a.meta + return out +end + +-- decode(buf, off?, len?, opts?) -> Image | nil, Err: one JPEG (or one interlaced Motion-JPEG frame) in [off, off + len) +function Jpeg.decode(buf, off, len, opts) +if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a buffer") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o, l = range(buf, off, len) + local img, st = decodeOne(buf, o, l, opts) + if not img then + return nil, st + end + local s = st +local wantFields = (opts and opts.fields ~= nil and{opts.fields }or{(s.avi1 == 1 or s.avi1 == 2) +})[1] if wantFields and not (opts and opts.orient) then + local e = o + l + local p = nextSoi(buf, s.endPos, e) + if p >= 0 then + local o2 = (table.clone(opts or {}) ) +if o2.maxPixels then + o2.maxPixels = math.max(0, o2.maxPixels - img.width * img.height) + end + local b = decodeOne(buf, p, e - p, o2) + if b and b.width == img.width and b.height == img.height and b.format == img.format then + local truncated = img.meta.truncated or b.meta.truncated + img = weave(img, b) + img.meta.truncated = truncated + local source= img.meta.source + source.fields = 2 + end + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BPP = { rgba8 = 4, rgb8 = 3, gray8 = 1, yuv420p = 0 } + +-- encode(img, opts?) -> buffer | nil, Err: an rgba8 / rgb8 / gray8 / yuv420p Image as a baseline or progressive JPEG +function Jpeg.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local bpp = BPP[img.format] + if not bpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8, gray8 or yuv420p Image (got " .. tostring(img.format) .. ")") + end + local w, h = img.width, img.height + local need = (bpp == 0 and((w * h + 2 * (math.floor((w + 1) / 2)) * (math.floor((h + 1) / 2)) ))or((w * h * bpp +))) if w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < need then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o= opts or {} + local quality = o.quality or 90 + if type(quality) ~= "number" or quality < 1 or quality > 100 then + return nil, Err.new(Err.ARG, "quality must be 1..100") + end + local sub = o.subsampling or "420" + if sub ~= "420" and sub ~= "422" and sub ~= "444" then + return nil, Err.new(Err.ARG, "subsampling must be \"420\", \"422\" or \"444\"") + end + if bpp == 0 then + sub = "420" + end + local restart = o.restart or 0 + if type(restart) ~= "number" or restart < 0 or restart > 65535 or restart % 1 ~= 0 then + return nil, Err.new(Err.ARG, "restart must be 0..65535 MCUs") + end + local gray = o.gray + if gray == nil then + gray = img.format == "gray8" + end + local segments = {} + if o.segments ~= nil then + if type(o.segments) ~= "table" then + return nil, Err.new(Err.ARG, "segments must be a list of { marker, data }") + end + for _, sg in __iter(o.segments) do + if type(sg) ~= "table" or type(sg.data) ~= "buffer" or buffer.len(sg.data) > 65533 or type(sg.marker) ~= "number" then + return nil, Err.new(Err.ARG, "bad segment (marker 0xE0..0xEF / 0xFE, at most 65533 bytes)") + end + if not ((sg.marker >= 0xE0 and sg.marker <= 0xEF) or sg.marker == 0xFE) then + return nil, Err.new(Err.ARG, "bad segment marker (0xE0..0xEF / 0xFE)") + end + table.insert(segments, sg) + end + end + local density = o.density + if density ~= nil then + if type(density) ~= "table" or type(density.unit) ~= "number" or type(density.x) ~= "number" or type(density.y) ~= "number" then + return nil, Err.new(Err.ARG, "bad density") + end + density = { + unit = math.clamp(math.floor(density.unit), 0, 2), + x = math.clamp(math.floor(density.x), 1, 65535), + y = math.clamp(math.floor(density.y), 1, 65535), + } + end + local out = Encode.run(img.pixels, w, h, bpp, { + quality = quality, + sampling = sub, + progressive = o.progressive == true, + optimize = o.optimize == true, + gray = gray, + restart = restart, + segments = segments, + jfif = o.jfif ~= false, + density = density, + }) + return out, nil +end + +return Jpeg +end +__FILES["codecs/image/Jpeg/Arith"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised +-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's +-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table. +-- +-- It reads the destuffed scan data that Scan.destuff produces (0xFF 0x00 already removed, RSTn positions recorded); +-- past the end of a restart segment it reads zero bytes, the convention libjpeg follows when the decoder runs into a +-- marker (libjpeg's encoder also drops trailing zero bytes, so reading past the end is normal and not a sign of +-- truncation: the caller flags a scan that runs into the end of the file instead). Statistics bins live in one buffer: DC tables at [t * 64], AC tables at [256 + t * 256], the fixed 0.5 +-- bin at [1280]. +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local band, bxor = bit32.band, bit32.bxor + +local Arith = {} + +-- jaricom.c: Qe << 16 | Next_Index_MPS << 8 | Switch_MPS << 7 | Next_Index_LPS +local TAB = buffer.create(114 * 4) +do + local raw = { + { 0x5a1d, 1, 1, 1 }, { 0x2586, 14, 2, 0 }, { 0x1114, 16, 3, 0 }, { 0x080b, 18, 4, 0 }, { 0x03d8, 20, 5, 0 }, + { 0x01da, 23, 6, 0 }, { 0x00e5, 25, 7, 0 }, { 0x006f, 28, 8, 0 }, { 0x0036, 30, 9, 0 }, { 0x001a, 33, 10, 0 }, + { 0x000d, 35, 11, 0 }, { 0x0006, 9, 12, 0 }, { 0x0003, 10, 13, 0 }, { 0x0001, 12, 13, 0 }, { 0x5a7f, 15, 15, 1 }, + { 0x3f25, 36, 16, 0 }, { 0x2cf2, 38, 17, 0 }, { 0x207c, 39, 18, 0 }, { 0x17b9, 40, 19, 0 }, { 0x1182, 42, 20, 0 }, + { 0x0cef, 43, 21, 0 }, { 0x09a1, 45, 22, 0 }, { 0x072f, 46, 23, 0 }, { 0x055c, 48, 24, 0 }, { 0x0406, 49, 25, 0 }, + { 0x0303, 51, 26, 0 }, { 0x0240, 52, 27, 0 }, { 0x01b1, 54, 28, 0 }, { 0x0144, 56, 29, 0 }, { 0x00f5, 57, 30, 0 }, + { 0x00b7, 59, 31, 0 }, { 0x008a, 60, 32, 0 }, { 0x0068, 62, 33, 0 }, { 0x004e, 63, 34, 0 }, { 0x003b, 32, 35, 0 }, + { 0x002c, 33, 9, 0 }, { 0x5ae1, 37, 37, 1 }, { 0x484c, 64, 38, 0 }, { 0x3a0d, 65, 39, 0 }, { 0x2ef1, 67, 40, 0 }, + { 0x261f, 68, 41, 0 }, { 0x1f33, 69, 42, 0 }, { 0x19a8, 70, 43, 0 }, { 0x1518, 72, 44, 0 }, { 0x1177, 73, 45, 0 }, + { 0x0e74, 74, 46, 0 }, { 0x0bfb, 75, 47, 0 }, { 0x09f8, 77, 48, 0 }, { 0x0861, 78, 49, 0 }, { 0x0706, 79, 50, 0 }, + { 0x05cd, 48, 51, 0 }, { 0x04de, 50, 52, 0 }, { 0x040f, 50, 53, 0 }, { 0x0363, 51, 54, 0 }, { 0x02d4, 52, 55, 0 }, + { 0x025c, 53, 56, 0 }, { 0x01f8, 54, 57, 0 }, { 0x01a4, 55, 58, 0 }, { 0x0160, 56, 59, 0 }, { 0x0125, 57, 60, 0 }, + { 0x00f6, 58, 61, 0 }, { 0x00cb, 59, 62, 0 }, { 0x00ab, 61, 63, 0 }, { 0x008f, 61, 32, 0 }, { 0x5b12, 65, 65, 1 }, + { 0x4d04, 80, 66, 0 }, { 0x412c, 81, 67, 0 }, { 0x37d8, 82, 68, 0 }, { 0x2fe8, 83, 69, 0 }, { 0x293c, 84, 70, 0 }, + { 0x2379, 86, 71, 0 }, { 0x1edf, 87, 72, 0 }, { 0x1aa9, 87, 73, 0 }, { 0x174e, 72, 74, 0 }, { 0x1424, 72, 75, 0 }, + { 0x119c, 74, 76, 0 }, { 0x0f6b, 74, 77, 0 }, { 0x0d51, 75, 78, 0 }, { 0x0bb6, 77, 79, 0 }, { 0x0a40, 77, 48, 0 }, + { 0x5832, 80, 81, 1 }, { 0x4d1c, 88, 82, 0 }, { 0x438e, 89, 83, 0 }, { 0x3bdd, 90, 84, 0 }, { 0x34ee, 91, 85, 0 }, + { 0x2eae, 92, 86, 0 }, { 0x299a, 93, 87, 0 }, { 0x2516, 86, 71, 0 }, { 0x5570, 88, 89, 1 }, { 0x4ca9, 95, 90, 0 }, + { 0x44d9, 96, 91, 0 }, { 0x3e22, 97, 92, 0 }, { 0x3824, 99, 93, 0 }, { 0x32b4, 99, 94, 0 }, { 0x2e17, 93, 86, 0 }, + { 0x56a8, 95, 96, 1 }, { 0x4f46, 101, 97, 0 }, { 0x47e5, 102, 98, 0 }, { 0x41cf, 103, 99, 0 }, { 0x3c3d, 104, 100, 0 }, + { 0x375e, 99, 93, 0 }, { 0x5231, 105, 102, 0 }, { 0x4c0f, 106, 103, 0 }, { 0x4639, 107, 104, 0 }, { 0x415e, 103, 99, 0 }, + { 0x5627, 105, 106, 1 }, { 0x50e7, 108, 107, 0 }, { 0x4b85, 109, 103, 0 }, { 0x5597, 110, 109, 0 }, { 0x504f, 111, 107, 0 }, + { 0x5a10, 110, 111, 1 }, { 0x5522, 112, 109, 0 }, { 0x59eb, 112, 111, 1 }, { 0x5a1d, 113, 113, 0 }, + } + for i, e in __iter(raw) do + buffer.writeu16(TAB, (i - 1) * 4, e[1]) -- Qe + writeu8(TAB, (i - 1) * 4 + 2, e[4] * 128 + e[2]) -- Switch_MPS << 7 | Next_Index_LPS + writeu8(TAB, (i - 1) * 4 + 3, e[3]) -- Next_Index_MPS + end +end + +local ZZ= buffer.create(80) -- set by Arith.init (Scan.ZIGZAG) + +local STATS = 1281 +local POW2 = buffer.create(8) +for i = 0, 7 do + writeu8(POW2, i, 2 ^ i) +end +local FIXED = 1280 + +-- decoder state (one scan at a time; never yields) +local D= buffer.create(0) +local P = 0 -- next byte +local SEGEND = 0 -- reads at or past this return 0 +local OVER = 0 -- zero bytes supplied past the end +local C, A, CT = 0, 0, -16 +local st= buffer.create(STATS) + +local function decode(s) +while A < 0x8000 do + CT =CT- 1 + if CT < 0 then + local data = 0 + if P < SEGEND then + data = readu8(D, P) + P =P+ 1 + else + OVER =OVER+ 1 + end + C = C * 256 + data + CT =CT+ 8 + if CT < 0 then + CT =CT+ 1 + if CT == 0 then + A = 0x8000 + end + end + end + A =A* 2 + end + local sv = readu8(st, s) + local t = band(sv, 0x7F) * 4 + local qe = buffer.readu16(TAB, t) + local nl = readu8(TAB, t + 2) + local nm = readu8(TAB, t + 3) + local temp = A - qe + A = temp + temp =temp* readu8(POW2, CT) + if C >= temp then + C =C- temp + if A < qe then + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nm)) + else + A = qe + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + end + elseif A < 0x8000 then + if A < qe then + writeu8(st, s, bxor(band(sv, 0x80), nl)) + sv = bxor(sv, 0x80) + else + writeu8(st, s, bxor(band(sv, 0x80), nm)) + end + end + return sv >= 0x80 and 1 or 0 +end + +local function i16(v) +v = band(v, 0xFFFF) + return (v >= 0x8000 and((v - 0x10000 ))or(v +))end + +-- DC difference (F.1.4.4.1 / figures F.19, F.21 - F.24); returns the new predictor or nil on a bad code + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function dcDiff(c, L, U) +local base = c.dcTbl * 64 + local s = base + c.ctx + if decode(s) == 0 then + c.ctx = 0 + return c.pred + end + local sign = decode(s + 1) + s = s + 2 + sign + local m = decode(s) + if m ~= 0 then + s = base + 20 + while decode(s) ~= 0 do + m =m* 2 + if m == 0x8000 then + return nil + end + s =s+ 1 + end + end + if m < math.floor(2 ^ L / 2 )then + c.ctx = 0 + elseif m > math.floor(2 ^ U / 2 )then + c.ctx = 12 + sign * 4 + else + c.ctx = 4 + sign * 4 + end + local v = m + s =s+ 14 + m = math.floor(m / 2 +) while m > 0 do + if decode(s) ~= 0 then + v =v+ m + end + m = math.floor(m / 2 +) end + v =v+ 1 + if sign ~= 0 then + v = -v + end + return band(c.pred + v, 0xFFFF) +end + +-- AC coefficients k = ss..se of one block (figure F.20); false on a bad code +local function acFirst(coef, off, tbl, ss, se, K, mul) +local base = 256 + tbl * 256 + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if decode(s) ~= 0 then + break -- EOB + end + while decode(s + 1) == 0 do + s =s+ 3 + k =k+ 1 + if k > se then + return false + end + end + local sign = decode(FIXED) + s =s+ 2 + local m = decode(s) + if m ~= 0 then + if decode(s) ~= 0 then + m =m* 2 + s = base + (k <= K and 189 or 217) + while decode(s) ~= 0 do + m =m* 2 + if m == 0x8000 then + return false + end + s =s+ 1 + end + end + end + local v = m + s =s+ 14 + m = math.floor(m / 2 +) while m > 0 do + if decode(s) ~= 0 then + v =v+ m + end + m = math.floor(m / 2 +) end + v =v+ 1 + if sign ~= 0 then + v = -v + end + writei16(coef, off + readu8(ZZ, k) * 2, i16(v * mul)) + k =k+ 1 + end + return true +end + +local function acRefine(coef, off, tbl, ss, se, al) +local base = 256 + tbl * 256 + local p1 = 2 ^ al + local m1 = -p1 + local kex = se + while kex > 0 do + if readi16(coef, off + readu8(ZZ, kex) * 2) ~= 0 then + break + end + kex =kex- 1 + end + local k = ss + while k <= se do + local s = base + 3 * (k - 1) + if k > kex then + if decode(s) ~= 0 then + break + end + end + while true do + local o = off + readu8(ZZ, k) * 2 + local cv = readi16(coef, o) + if cv ~= 0 then + if decode(s + 2) ~= 0 then + writei16(coef, o, i16((cv < 0 and((cv + m1 ))or((cv + p1))))) + end + break + end + if decode(s + 1) ~= 0 then + writei16(coef, o, i16((decode(FIXED) ~= 0 and{m1 }or{p1})[1])) + break + end + s =s+ 3 + k =k+ 1 + if k > se then + return false + end + end + k =k+ 1 + end + return true +end + +function Arith.init(zigzag) + ZZ = zigzag +end + +-- run(d, cleanLen, rst, nrst, P) -> truncated: decodes one scan (see Scan.run for the data layout) +function Arith.run(d, cleanLen, rst, nrst, Pm) +local comps = Pm.comps + local nc = #comps + local mode, ss, se, al, ri = Pm.mode, Pm.ss, Pm.se, Pm.al, Pm.ri + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = Pm.mcusX + units = ux * Pm.mcusY + end + local resetDc = mode == 0 or mode == 1 + local resetAc = mode == 0 or mode == 3 or mode == 4 + local function reset() + for i = 1, nc do + local c = comps[i] + if resetDc then + buffer.fill(st, c.dcTbl * 64, 0, 64) + c.pred = 0 + c.ctx = 0 + end + if resetAc then + buffer.fill(st, 256 + c.acTbl * 256, 0, 256) + end + end + C, A, CT = 0, 0, -16 + end + D = d + P = 0 + SEGEND = (nrst >= 1 and{(math.min(rst[1], cleanLen) )}or{cleanLen +})[1] OVER = 0 + writeu8(st, FIXED, 113) + reset() + local rstIdx = 0 + local bad = false + local truncated = false + local mul = 2 ^ al + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx =rstIdx+ 1 + if rstIdx <= nrst then + P = math.min(rst[rstIdx], cleanLen) + SEGEND = (rstIdx + 1 <= nrst and{(math.min(rst[rstIdx + 1], cleanLen) )}or{cleanLen +})[1] bad = false + else + truncated = true + break + end + reset() + end + if not bad then + local my, mx = math.floor(u / ux), u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred)) + if not acFirst(coef, off, c.acTbl, 1, 63, Pm.acK[c.acTbl + 1], 1) then + bad = true + end + end + elseif mode == 1 then + local pred = dcDiff(c, Pm.dcL[c.dcTbl + 1], Pm.dcU[c.dcTbl + 1]) + if not pred then + bad = true + else + c.pred = pred + writei16(coef, off, i16(pred * mul)) + end + elseif mode == 2 then + if decode(FIXED) ~= 0 then + local cv = readi16(coef, off) + if band(cv, mul) == 0 then + writei16(coef, off, i16(cv + mul)) + end + end + elseif mode == 3 then + if not acFirst(coef, off, c.acTbl, ss, se, Pm.acK[c.acTbl + 1], mul) then + bad = true + end + else + if not acRefine(coef, off, c.acTbl, ss, se, al) then + bad = true + end + end + if bad then + break + end + end + if bad then + break + end + end + if bad then + break + end + end + end + end + D = buffer.create(0) + return truncated +end + +return Arith +end +__FILES["codecs/image/Jpeg/Color"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never +-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's +-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md). +-- +-- Upsampling follows libjpeg-turbo's jdsample.c, so the output matches djpeg's defaults: +-- FULL the component is at output resolution +-- H2V1 "fancy" triangle filter, 3/4 nearer + 1/4 further sample, alternating rounding (1, 2) / 4 +-- H2V2 fancy in both directions: vertical 3:1 column sums, then horizontal 3:1, rounding (8, 7) / 16 +-- H1V2 fancy vertical only, rounding 1 (upper row) / 2 (lower row) +-- REPLICATE any other ratio (or no fancy upsampling): nearest sample, as int_upsample +-- Edges replicate the last real sample (downW x downH), as libjpeg does with its context rows. +-- Colour conversion is jdcolor.c's table-driven YCbCr -> RGB (16-bit fixed point), plus grey, RGB, CMYK and +-- YCCK (Adobe inverted CMYK: R = C * K / 255). +local readu16, readi32, readu8, writeu16, writeu32 = buffer.readu16, buffer.readi32, buffer.readu8, buffer.writeu16, buffer.writeu32 +local clamp, min, max = math.clamp, math.min, math.max + +local Color = {} + +Color.FULL = 0 +Color.REPLICATE = 1 +Color.H2V1 = 2 +Color.H2V2 = 3 +Color.H1V2 = 4 + +Color.GRAY = 0 +Color.YCC = 1 +Color.RGB = 2 +Color.CMYK = 3 +Color.YCCK = 4 +Color.CMYK_PLAIN = 5 -- CMYK without an Adobe marker: not inverted +Color.RAW = 6 -- no conversion: components 1..4 as R, G, B, A (opts.raw: BLP1's BGRA JPEGs, ...) + +-- jdcolor.c build_ycc_rgb_table + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function Color.tables(maxv) +local n = maxv + 1 + local center = math.floor(n / 2 +) local crr, cbb, crg, cbg = buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4), buffer.create(n * 4) + local function fix(x) +return math.floor(x * 65536 + 0.5) + end + for i = 0, maxv do + local x = i - center + buffer.writei32(crr, i * 4, math.floor((fix(1.40200) * x + 32768) / 65536)) + buffer.writei32(cbb, i * 4, math.floor((fix(1.77200) * x + 32768) / 65536)) + buffer.writei32(crg, i * 4, -fix(0.71414) * x) + buffer.writei32(cbg, i * 4, -fix(0.34414) * x + 32768) + end + return crr, cbb, crg, cbg +end + +-- fills c.row with output row y; returns the buffer and byte offset of the row's samples +local function fetch(c, y, outW) +local method = c.method + local plane, stride, row = c.plane, c.stride, c.row + if method == 0 then + return plane, min(y, c.rows - 1) * stride * 2 + elseif method == 2 then + local w = c.downW + local b = min(y, c.rows - 1) * stride * 2 + local cur = readu16(plane, b) + writeu16(row, 0, cur) + local nxt = readu16(plane, b + 2) + writeu16(row, 2, math.floor((cur * 3 + nxt + 2) / 4)) + local prev = cur + cur = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b + (i + 1) * 2) + local v3 = cur * 3 + writeu16(row, i * 4, math.floor((v3 + prev + 1) / 4)) + writeu16(row, i * 4 + 2, math.floor((v3 + nxt + 2) / 4)) + prev = cur + cur = nxt + end + writeu16(row, (w - 1) * 4, math.floor((cur * 3 + prev + 1) / 4)) + writeu16(row, (w - 1) * 4 + 2, cur) + return row, 0 + elseif method == 3 then + local w = c.downW + local iy = min(math.floor(y / 2), c.downH - 1) + local oy = (y % 2 == 0 and{(max(iy - 1, 0) )}or{(min(iy + 1, c.downH - 1) +)})[1] local b0, b1 = iy * stride * 2, oy * stride * 2 + local this = readu16(plane, b0) * 3 + readu16(plane, b1) + local nxt = readu16(plane, b0 + 2) * 3 + readu16(plane, b1 + 2) + writeu16(row, 0, math.floor((this * 4 + 8) / 16)) + writeu16(row, 2, math.floor((this * 3 + nxt + 7) / 16)) + local last = this + this = nxt + for i = 1, w - 2 do + nxt = readu16(plane, b0 + (i + 1) * 2) * 3 + readu16(plane, b1 + (i + 1) * 2) + local t3 = this * 3 + writeu16(row, i * 4, math.floor((t3 + last + 8) / 16)) + writeu16(row, i * 4 + 2, math.floor((t3 + nxt + 7) / 16)) + last = this + this = nxt + end + writeu16(row, (w - 1) * 4, math.floor((this * 3 + last + 8) / 16)) + writeu16(row, (w - 1) * 4 + 2, math.floor((this * 4 + 7) / 16)) + return row, 0 + elseif method == 4 then + local iy = min(math.floor(y / 2), c.downH - 1) + local oy, bias + if y % 2 == 0 then + oy, bias = max(iy - 1, 0), 1 + else + oy, bias = min(iy + 1, c.downH - 1), 2 + end + local b0, b1 = iy * stride * 2, oy * stride * 2 + for x = 0, outW - 1 do + writeu16(row, x * 2, math.floor((readu16(plane, b0 + x * 2) * 3 + readu16(plane, b1 + x * 2) + bias) / 4)) + end + return row, 0 + else + local hIn, hOut = c.hIn, c.hOut + local iy = min(math.floor((y * c.vIn) / c.vOut), c.rows - 1) + local b = iy * stride * 2 + local last = stride - 1 + for x = 0, outW - 1 do + writeu16(row, x * 2, readu16(plane, b + min(math.floor((x * hIn) / hOut), last) * 2)) + end + return row, 0 + end +end + +function Color.run(P) + local comps = P.comps + local nc = #comps + local space, outW, outH, maxv, out = P.space, P.outW, P.outH, P.maxv, P.pixels + local crr, cbb, crg, cbg = P.crr, P.cbb, P.crg, P.cbg + local toByte = P.toByte + local o = 0 + local hook = P.hook + for y = 0, outH - 1 do +local __DARKLUA_CONTINUE_6=false repeat if hook and y > 0 and y % 8 == 0 then + pcall(hook) + end + local s0, b0 = fetch(comps[1], y, outW) + if space == 0 or nc < 3 then + for x = 0, outW - 1 do + local v = readu16(s0, b0 + x * 2) + if toByte then + v = readu8(toByte, v) + end + writeu32(out, o, 0xFF000000 + v * 0x10101) + o =o+ 4 + end + else + local s1, b1 = fetch(comps[2], y, outW) + local s2, b2 = fetch(comps[3], y, outW) + local s3, b3 = s0, b0 + if nc >= 4 then + s3, b3 = fetch(comps[4], y, outW) + end + if space == 6 then + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local c3 = (nc >= 4 and{(readu16(s3, b3 + i) )}or{maxv +})[1] if toByte then + c0, c1, c2, c3 = readu8(toByte, c0), readu8(toByte, c1), readu8(toByte, c2), readu8(toByte, c3) + end + writeu32(out, o, c0 + c1 * 256 + c2 * 65536 + c3 * 16777216) + o =o+ 4 + end +__DARKLUA_CONTINUE_6=true break + end + if space == 1 and not toByte then + -- the common case: 8-bit YCbCr + for x = 0, outW - 1 do + local i = x * 2 + local yv, cb, cr = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r = clamp(yv + readi32(crr, cr * 4), 0, 255) + local g = clamp(yv + math.floor((readi32(cbg, cb * 4) + readi32(crg, cr * 4)) / 65536), 0, 255) + local b = clamp(yv + readi32(cbb, cb * 4), 0, 255) + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o =o+ 4 + end +__DARKLUA_CONTINUE_6=true break + end + for x = 0, outW - 1 do + local i = x * 2 + local c0, c1, c2 = readu16(s0, b0 + i), readu16(s1, b1 + i), readu16(s2, b2 + i) + local r, g, b + if space == 2 then + r, g, b = c0, c1, c2 + elseif space == 3 or space == 5 then + local k = readu16(s3, b3 + i) + if space == 5 then + c0, c1, c2, k = maxv - c0, maxv - c1, maxv - c2, maxv - k + end + r = math.floor((c0 * k + math.floor(maxv / 2)) / maxv +) g = math.floor((c1 * k + math.floor(maxv / 2)) / maxv +) b = math.floor((c2 * k + math.floor(maxv / 2)) / maxv +) else + r = clamp(c0 + readi32(crr, c2 * 4), 0, maxv) + g = clamp(c0 + math.floor((readi32(cbg, c1 * 4) + readi32(crg, c2 * 4)) / 65536), 0, maxv) + b = clamp(c0 + readi32(cbb, c1 * 4), 0, maxv) + if space == 4 then + -- YCCK: the YCC part decodes to inverted C, M, Y (libjpeg ycck_cmyk_convert), K as stored + local k = readu16(s3, b3 + i) + r = math.floor(((maxv - r) * k + math.floor(maxv / 2)) / maxv +) g = math.floor(((maxv - g) * k + math.floor(maxv / 2)) / maxv +) b = math.floor(((maxv - b) * k + math.floor(maxv / 2)) / maxv +) end + end + if toByte then + r, g, b = readu8(toByte, r), readu8(toByte, g), readu8(toByte, b) + end + writeu32(out, o, 0xFF000000 + r + g * 256 + b * 65536) + o =o+ 4 + end + end +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end +end + +return Color +end +__FILES["codecs/image/Jpeg/Decode"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan / +-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended: +-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM +-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a +-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows +-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats. +local Scan = __include("codecs/image/Jpeg/Scan") +local Arith = __include("codecs/image/Jpeg/Arith") +local Color = __include("codecs/image/Jpeg/Color") +local Tables = __include("codecs/image/Jpeg/Tables") +local Yuv = __include("codecs/image/Jpeg/Yuv") +local Dct = __include("codecs/image/Dct") + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local Decode = {} + +Arith.init(Scan.ZIGZAG) + +local function be16(b, p) +return readu8(b, p) * 256 + readu8(b, p + 1) +end + +local stdBuilt= {} +local function stdTable(class, slot) +local key = class .. slot + if not stdBuilt[key] then + local def = ((class == "dc" and{Tables.DC }or{Tables.AC})[1])[slot + 1] + if not def then + return nil + end + stdBuilt[key] = Scan.buildTable(def.counts, def.symbols) + end + return stdBuilt[key] +end + +-- the EXIF TIFF block (after "Exif\0\0") and its orientation tag, from an APP1 segment at [p, e) +local function exif(b, p, e) +if e - p < 14 or buffer.readstring(b, p, 6) ~= "Exif\0\0" then + return nil, nil + end + local t = p + 6 + local le + local bo = buffer.readstring(b, t, 2) + if bo == "II" then + le = true + elseif bo == "MM" then + le = false + else + return nil, nil + end + local function r16(at) +if le then + return readu8(b, at) + readu8(b, at + 1) * 256 + end + return readu8(b, at) * 256 + readu8(b, at + 1) + end + local function r32(at) +if le then + return r16(at) + r16(at + 2) * 65536 + end + return r16(at) * 65536 + r16(at + 2) + end + local ifd = t + r32(t + 4) + if ifd + 2 > e then + return t, nil + end + local count = r16(ifd) + for i = 0, count - 1 do + local en = ifd + 2 + i * 12 + if en + 12 > e then + return t, nil + end + if r16(en) == 0x0112 then + local v = r16(en + 8) + return t, (v >= 1 and v <= 8 and{v }or{nil +})[1] end + end + return t, nil +end + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local SOF_REFUSED = { + [0xC3] = "lossless", + [0xC5] = "hierarchical", + [0xC6] = "hierarchical", + [0xC7] = "hierarchical", + [0xCB] = "lossless arithmetic-coded", + [0xCD] = "hierarchical arithmetic-coded", + [0xCE] = "hierarchical arithmetic-coded", + [0xCF] = "hierarchical arithmetic-coded", +} + +-- failures carry a code: "corrupt" | "unsupported" | "limit" | "truncated" +local function parseSof(b, p, e, m) +if e - p < 6 then + return nil, "corrupt", "short SOF" + end + local prec = readu8(b, p) + local height, width, nf = be16(b, p + 1), be16(b, p + 3), readu8(b, p + 5) + if prec ~= 8 and prec ~= 12 then + return nil, "unsupported", "sample precision " .. prec + end + if width == 0 or height == 0 then + if height == 0 and width > 0 then + return nil, "unsupported", "DNL (height 0 in the frame header)" + end + return nil, "corrupt", "bad size " .. width .. "x" .. height + end + if nf ~= 1 and nf ~= 3 and nf ~= 4 then + return nil, "unsupported", "component count " .. nf + end + if e - p < 6 + nf * 3 then + return nil, "corrupt", "short SOF" + end + local comps= {} + local hmax, vmax = 1, 1 + for i = 0, nf - 1 do + local q = p + 6 + i * 3 + local hv = readu8(b, q + 1) + local h, v, tq = rshift(hv, 4), band(hv, 15), (readu8(b, q + 2) ) +if h < 1 or h > 4 or v < 1 or v > 4 then + return nil, "corrupt", "bad sampling factors " .. h .. "x" .. v + end + if tq > 3 then + return nil, "corrupt", "bad quantisation table selector " .. tq + end + local id = readu8(b, q) + for _, c in __iter(comps) do + if c.id == id then + return nil, "corrupt", "duplicate component id " .. id + end + end + hmax, vmax = math.max(hmax, h), (math.max(vmax, v) ) +table.insert(comps, { id = id, h = h, v = v, tq = tq, bpl = 0, bpc = 0, bw = 0, bh = 0, dcTbl = 0, acTbl = 0, pred = 0, ctx = 0 } ) + end + local mcusX = math.ceil(width / (8 * hmax)) + local mcusY = math.ceil(height / (8 * vmax)) + for _, c in __iter(comps) do + c.bpl = mcusX * c.h + c.bpc = mcusY * c.v + c.bw = math.ceil(math.ceil(width * c.h / hmax) / 8) + c.bh = math.ceil(math.ceil(height * c.v / vmax) / 8) + end + return { + width = width, + height = height, + precision = prec, + progressive = m == 0xC2 or m == 0xCA, + arithmetic = m == 0xC9 or m == 0xCA, + comps = comps, + hmax = hmax, + vmax = vmax, + mcusX = mcusX, + mcusY = mcusY, + }, nil, nil +end + +local function colorSpaceOf(frame, adobe, jfif) +local n = #frame.comps + if n == 1 then + return "gray" + elseif n == 3 then + if adobe ~= nil then + return adobe == 0 and"rgb" or"ycbcr" + end + local c = frame.comps + if not jfif and c[1].id == 82 and c[2].id == 71 and c[3].id == 66 then + return "rgb" + end + return "ycbcr" + end + return adobe == 2 and"ycck" or"cmyk" +end +Decode.colorSpaceOf = colorSpaceOf + +-- The IDCT size (8, 4, 2 or 1) for a component at a scale. libjpeg-turbo scales chroma up through a bigger IDCT +-- instead of upsampling it, when the sampling ratios allow (jdmaster.c jpeg_calc_output_dimensions). +local function idctSize(f, c, scale) +local minSize = math.floor(8 / scale +) local ssize = minSize + while ssize < 8 and (f.hmax * minSize) % (c.h * ssize * 2) == 0 and (f.vmax * minSize) % (c.v * ssize * 2) == 0 do + ssize =ssize* 2 + end + return ssize +end + +-- parse(b, base, limit, opts, headerOnly) -> State | nil, code, message. Walks the markers in b[base, limit); with +-- headerOnly it stops at the frame header, otherwise it decodes every scan into the components' coefficients. + + + + + + + + + + + + + + + + + +function Decode.parse(b, base, n, opts, headerOnly) +if n - base < 4 or readu8(b, base) ~= 0xFF or readu8(b, base + 1) ~= 0xD8 then + return nil, "corrupt", "not a JPEG file (no SOI marker)" + end + local scale = (opts and opts.scale) or 1 + if scale ~= 1 and scale ~= 2 and scale ~= 4 and scale ~= 8 then + return nil, "arg", "scale must be 1, 2, 4 or 8" + end + local maxPixels= (opts and opts.maxPixels) or 2 ^ 26 + local quant= {} + local dcT= {} + local acT= {} + local dcL, dcU, acK = { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 5, 5, 5, 5 } + local frame= nil + local st= { + frame = nil, + adobe = nil, + jfif = false, + density = nil, + orientation = 1, + exif = nil, + icc = nil, + comments = {}, + truncated = false, + raw = opts ~= nil and opts.raw == true, + scale = scale, + avi1 = nil, + endPos = n, + hook = (opts and type(opts.yield) == "function" and{opts.yield }or{nil})[1], + } + local iccChunks= {} + local ri = 0 + local scans = 0 + local clean= nil + local rst = {} + local pos = base + 2 + while pos < n do +local __DARKLUA_CONTINUE_6=false repeat -- find the next marker (tolerate garbage and fill bytes) + if readu8(b, pos) ~= 0xFF then + pos =pos+ 1 +__DARKLUA_CONTINUE_6=true break + end + while pos < n and readu8(b, pos) == 0xFF do + pos =pos+ 1 + end + if pos >= n then + break + end + local m = readu8(b, pos) + pos =pos+ 1 + if m == 0xD9 then + st.endPos = pos + break -- EOI + elseif m == 0 or m == 0x01 or m == 0xD8 or (m >= 0xD0 and m <= 0xD7) then +__DARKLUA_CONTINUE_6=true break -- standalone markers (or stray stuffing) + end + if pos + 2 > n then + st.truncated = true + break + end + local len = be16(b, pos) + if len < 2 then + return nil, "corrupt", string.format("bad segment length for marker %02X", m) + end + local p, e = pos + 2, pos + len + if e > n then + if m == 0xDA and frame and not headerOnly then + e = n -- a truncated SOS header still fails below + else + st.truncated = true + break + end + end + pos = e + if m == 0xE0 then + if e - p >= 12 and buffer.readstring(b, p, 5) == "JFIF\0" then + st.jfif = true + st.density = { unit = readu8(b, p + 7), x = be16(b, p + 8), y = be16(b, p + 10) } + elseif e - p >= 5 and buffer.readstring(b, p, 4) == "AVI1" then + st.avi1 = readu8(b, p + 4) + end + elseif m == 0xE1 then + local t, o = exif(b, p, e) + if t and not st.exif then + local x = buffer.create(e - t) + buffer.copy(x, 0, b, t, e - t) + st.exif = x + end + if o then + st.orientation = o + end + elseif m == 0xE2 then + -- ICC_PROFILE\0, sequence number, count, data + if e - p >= 14 and buffer.readstring(b, p, 12) == "ICC_PROFILE\0" then + local seq = readu8(b, p + 12) + local x = buffer.create(e - p - 14) + buffer.copy(x, 0, b, p + 14, e - p - 14) + if seq >= 1 then + iccChunks[seq] = x + end + end + elseif m == 0xEE then + if e - p >= 12 and buffer.readstring(b, p, 5) == "Adobe" then + st.adobe = readu8(b, p + 11) + end + elseif m == 0xFE then + table.insert(st.comments, buffer.readstring(b, p, e - p)) + elseif m == 0xDB then + -- DQT + while p < e do + local pt = readu8(b, p) + local pq, tq = rshift(pt, 4), band(pt, 15) + local size = pq == 0 and 64 or 128 + if tq > 3 or pq > 1 or p + 1 + size > e then + return nil, "corrupt", "bad DQT segment" + end + local q = buffer.create(128) + for k = 0, 63 do + local v = (pq == 0 and{(readu8(b, p + 1 + k) )}or{(be16(b, p + 1 + k * 2) +)})[1] buffer.writeu16(q, readu8(Scan.ZIGZAG, k) * 2, v) + end + quant[tq] = q + p =p+ (1 + size +) end + elseif m == 0xC4 then + -- DHT + while p < e do + if p + 17 > e then + return nil, "corrupt", "bad DHT segment" + end + local tc = readu8(b, p) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DHT table class / slot" + end + local counts, total = {}, 0 + for l = 1, 16 do + counts[l] = readu8(b, p + l) + total =total+ counts[l] + end + if total > 256 or p + 17 + total > e then + return nil, "corrupt", "bad DHT segment" + end + local syms = {} + for i = 1, total do + syms[i] = readu8(b, p + 16 + i) + end + local t = Scan.buildTable(counts, syms) + if class == 0 then + dcT[slot] = t + else + acT[slot] = t + end + p =p+ (17 + total +) end + elseif m == 0xCC then + -- DAC: arithmetic conditioning + while p + 2 <= e do + local tc, v = readu8(b, p), readu8(b, p + 1) + local class, slot = rshift(tc, 4), band(tc, 15) + if class > 1 or slot > 3 then + return nil, "corrupt", "bad DAC segment" + end + if class == 0 then + local L, U = band(v, 15), rshift(v, 4) + if L > U then + return nil, "corrupt", "bad DAC value" + end + dcL[slot + 1], dcU[slot + 1] = L, U + else + if v < 1 or v > 63 then + return nil, "corrupt", "bad DAC value" + end + acK[slot + 1] = v + end + p =p+ 2 + end + elseif m == 0xDD then + if e - p < 2 then + return nil, "corrupt", "bad DRI segment" + end + ri = be16(b, p) + elseif m == 0xC0 or m == 0xC1 or m == 0xC2 or m == 0xC9 or m == 0xCA then + if frame then + return nil, "corrupt", "more than one frame header" + end + local f, code, err = parseSof(b, p, e, m) + if not f then + return nil, code, err + end + if f.width * f.height > maxPixels then + return nil, "limit", string.format("%d x %d is over the %d pixel limit", f.width, f.height, maxPixels) + end + frame = f + st.frame = f + if headerOnly then + return st, nil, nil + end + elseif SOF_REFUSED[m] then + return nil, "unsupported", SOF_REFUSED[m] .. " JPEG" + elseif m == 0xDA then + if headerOnly then + break + end + if not frame then + return nil, "corrupt", "scan before the frame header" + end + local f = frame +local ns = (p < e and{(readu8(b, p) )}or{0 +})[1] if ns < 1 or ns > 4 or e - p < 4 + ns * 2 then + return nil, "corrupt", "bad SOS segment" + end + local sc= {} + local blocks = 0 + for i = 0, ns - 1 do + local id, t = readu8(b, p + 1 + i * 2), readu8(b, p + 2 + i * 2) + local comp = nil + for _, c in __iter(f.comps) do + if c.id == id then + comp = c + end + end + if not comp or table.find(sc, comp) then + return nil, "corrupt", "scan names an unknown component " .. id + end + local td, ta = rshift(t, 4), band(t, 15) + if td > 3 or ta > 3 then + return nil, "corrupt", "bad entropy table selector" + end + comp.dcTbl, comp.acTbl = td, ta + if not f.arithmetic then + comp.dct = dcT[td] or stdTable("dc", td) + comp.act = acT[ta] or stdTable("ac", ta) + end + blocks =blocks+ comp.h * comp.v + table.insert(sc, comp) + end + local q = p + 1 + ns * 2 + local ss, se, a = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + local ah, al = rshift(a, 4), band(a, 15) + if ns > 1 and blocks > 10 then + return nil, "corrupt", "more than 10 blocks per MCU" + end + local mode + if not f.progressive then + mode = 0 + ss, se, ah, al = 0, 63, 0, 0 + else + if se > 63 or ss > se or ah > 13 or al > 13 or (ss == 0 and se ~= 0) or (ss > 0 and ns ~= 1) then + return nil, "corrupt", "bad progressive scan parameters" + end + if ss == 0 then + mode = ah == 0 and 1 or 2 + else + mode = ah == 0 and 3 or 4 + end + end + for _, c in __iter(sc) do + if not f.arithmetic then + if (mode == 0 or mode == 1) and not c.dct then + return nil, "corrupt", "missing DC Huffman table" + end + if (mode == 0 or mode == 3 or mode == 4) and not c.act then + return nil, "corrupt", "missing AC Huffman table" + end + end + if not c.coef then + c.coef = buffer.create(c.bpl * c.bpc * 128) + end + if not c.quant then + c.quant = quant[c.tq] + end + end + if not clean then + clean = buffer.create(n - base + Scan.PAD) + end + local cb = clean +local nextPos, cleanLen, nrst = Scan.destuff(b, pos, n, cb, rst) + if nextPos >= n then + st.truncated = true -- no EOI + end + -- a component decoded through the 1x1 IDCT only needs its DC coefficient: skip its AC scans + if not (mode >= 3 and idctSize(f, sc[1], scale) == 1) then + local params = { + comps = sc , + mcusX = f.mcusX, + mcusY = f.mcusY, + ri = ri, + mode = mode, + ss = ss, + se = se, + al = al, + hook = st.hook, + dcL = dcL, + dcU = dcU, + acK = acK, + } + local short + if f.arithmetic then + short = Arith.run(cb, cleanLen, rst, nrst, params) + else + local _ + _, short = Scan.run(cb, cleanLen, rst, nrst, params) + end + st.truncated = st.truncated or short + end + scans =scans+ 1 + pos = nextPos + end +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end + if not frame then + return nil, st.truncated and"truncated" or"corrupt", "no frame header" + end + if #iccChunks > 0 then + local total = 0 + for _, c in __iter(iccChunks) do + total =total+ buffer.len(c) + end + local icc = buffer.create(total) + local o = 0 + for _, c in __iter(iccChunks) do + buffer.copy(icc, o, c) + o =o+ buffer.len(c) + end + st.icc = icc + end + if headerOnly then + return st, nil, nil + end + if scans == 0 then + return nil, "truncated", "no image data" + end + return st, nil, nil +end + +local SPACE_IDS = { gray = Color.GRAY, ycbcr = Color.YCC, rgb = Color.RGB, cmyk = Color.CMYK, ycck = Color.YCCK } + +local tableCache= {} +local function yccTables(maxv) +local t = tableCache[maxv] + if not t then + local a, b, c, d = Color.tables(maxv) + t = { a, b, c, d } + tableCache[maxv] = t + end + return t +end + +local toByte12= nil + +-- output(st) -> width, height, rgba8 pixels, colour space | nil, code, message +function Decode.output(st) +local f= st.frame + local scale = st.scale + local minSize = math.floor(8 / scale +) local maxv = f.precision == 12 and 4095 or 255 + local center = math.floor((maxv + 1) / 2 +) local p1 = f.precision == 12 and 1 or 2 + local outW = math.ceil(f.width * minSize / 8) + local outH = math.ceil(f.height * minSize / 8) + local fancy = minSize > 1 + local ccomps = {} + local zeroQ = buffer.create(128) + for _, c in __iter(f.comps) do + local ssize = idctSize(f, c, scale) + local stride, rows = c.bpl * ssize, c.bpc * ssize + local plane = buffer.create(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + if c.coef then + return nil, "corrupt", "missing quantisation table " .. c.tq + end + q = zeroQ -- the component never appeared in a scan: mid grey + end + Dct.idctComponent(coef, q , c.bpl, c.bpc, ssize, plane, p1, center, maxv, st.hook) + local hIn, hOut = math.floor(c.h * ssize / minSize), f.hmax + local vIn, vOut = math.floor(c.v * ssize / minSize), f.vmax + local downW = math.ceil(f.width * c.h * ssize / (f.hmax * 8)) + local downH = math.ceil(f.height * c.v * ssize / (f.vmax * 8)) + local method + if hIn == hOut and vIn == vOut then + method = Color.FULL + elseif hIn * 2 == hOut and vIn * 2 == vOut and fancy and downW > 2 then + method = Color.H2V2 + elseif hIn * 2 == hOut and vIn == vOut and fancy and downW > 2 then + method = Color.H2V1 + elseif hIn == hOut and vIn * 2 == vOut and fancy then + method = Color.H1V2 + else + method = Color.REPLICATE + end + table.insert(ccomps, { + plane = plane, + stride = stride, + rows = rows, + downW = downW, + downH = downH, + method = method, + hIn = hIn, + hOut = hOut, + vIn = vIn, + vOut = vOut, + row = buffer.create((math.max(outW, 2 * stride) + 8) * 2), + }) + c.coef = nil -- free the coefficients early + end + local space = colorSpaceOf(f, st.adobe, st.jfif) + local spaceId = SPACE_IDS[space] + if space == "cmyk" and st.adobe == nil then + spaceId = Color.CMYK_PLAIN + end + if st.raw then + spaceId = Color.RAW + end + local t = yccTables(maxv) + local tb = nil + if maxv == 4095 then + if not toByte12 then + local tbuf = buffer.create(4096) + for v = 0, 4095 do + buffer.writeu8(tbuf, v, math.floor((v * 255 + 2047) / 4095)) + end + toByte12 = tbuf + end + tb = toByte12 + end + local pixels = buffer.create(outW * outH * 4) + Color.run({ + comps = ccomps, + space = spaceId, + outW = outW, + outH = outH, + maxv = maxv, + pixels = pixels, + crr = t[1], + cbb = t[2], + crg = t[3], + cbg = t[4], + toByte = tb, + hook = st.hook, + }) + return outW, outH, pixels, space +end + +-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the +-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion +-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half +-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma +-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray": +-- chroma 128). Full scale only (opts.scale = 1). +-- one IDCT plane at a time is live (each is cropped into the output before the next component): frame-sized planes +-- (up to 4 MB) are kept between calls, so a stream of video frames does not allocate them per frame +local scratch= nil +local function scratchPlane(n) +local sc = scratch + if sc and buffer.len(sc) >= n then + return sc + end + local b = buffer.create(n) + if n <= 4 * 1024 * 1024 then + scratch = b + end + return b +end + +function Decode.outputYuv(st) +local f= st.frame + if st.scale ~= 1 or f.precision ~= 8 then + return nil, nil, nil, nil + end + local comps = f.comps + local space = colorSpaceOf(f, st.adobe, st.jfif) + local mode = nil + if space == "gray" then + mode = "gray" + elseif space == "ycbcr" then + -- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere) + local l, cb, cr = comps[1], comps[2], comps[3] + if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then + local rh, rv = math.floor(f.hmax / cb.h), math.floor(f.vmax / cb.v +) if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then + mode = nil + elseif rh == 2 and rv == 2 then + mode = "420" + elseif rh == 2 and rv == 1 then + mode = "422" + elseif rh == 1 and rv == 1 then + mode = "444" + end + end + end + if not mode then + return nil, nil, nil, nil + end + for _, c in __iter(comps) do + if c.coef and not c.quant then + return nil, nil, nil, nil -- output() reports the missing table + end + end + local w, h = f.width, f.height + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local out = buffer.create(w * h + 2 * cw * ch) + local zeroQ= nil + for i, c in __iter(comps) do + local stride, rows = c.bpl * 8, c.bpc * 8 + local plane = scratchPlane(stride * rows * 2) + local coef = c.coef or buffer.create(c.bpl * c.bpc * 128) + local q = c.quant + if not q then + zeroQ = zeroQ or buffer.create(128) -- the component never appeared in a scan: mid grey + q = zeroQ + end + Dct.idctComponent(coef, q , c.bpl, c.bpc, 8, plane, 2, 128, 255, st.hook) + if i == 1 then + Yuv.crop(plane, stride, w, h, out, 0) + elseif mode == "420" then + Yuv.crop(plane, stride, cw, ch, out, w * h + (i - 2) * cw * ch) + elseif mode == "422" then + Yuv.rows(plane, stride, cw, h, out, w * h + (i - 2) * cw * ch) + else + Yuv.box(plane, stride, w, h, out, w * h + (i - 2) * cw * ch) + end + c.coef = nil + end + if mode == "gray" then + buffer.fill(out, w * h, 128, 2 * cw * ch) + end + return w, h, out, mode +end + +return Decode +end +__FILES["codecs/image/Jpeg/Encode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman +-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr +-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG +-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's +-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c +-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication), +-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs, +-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md. +local Dct = __include("codecs/image/Dct") +local Tables = __include("codecs/image/Jpeg/Tables") + +local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16 +local band, countlz = bit32.band, bit32.countlz + +local Encode = {} + +-- natural order index of zigzag position k +local ZZ = buffer.create(64) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i =i+ 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i =i+ 1 + end + end + end +end +Encode.ZIGZAG = ZZ + +-- ------------------------------------------------------------------------------------------------ output +local OUT = buffer.create(0) +local OP = 0 +local CAP = 0 +local ACC, NB = 0, 0 +local GATHER = false + +local function grow(n) + if OP + n > CAP then + local c = math.max(CAP * 2, OP + n + 1024) + local nb = buffer.create(c) + buffer.copy(nb, 0, OUT, 0, OP) + OUT = nb + CAP = c + end +end + +local function byte(v) + grow(1) + writeu8(OUT, OP, v) + OP =OP+ 1 +end + +local function u16be(v) + byte(math.floor(v / 256)) + byte(v % 256) +end + +-- n bits of v (n <= 16), MSB first, with 0xFF stuffing +local function bits(v, n) + if GATHER or n == 0 then + return + end + local p = 2 ^ n + ACC = ACC * p + band(v, p - 1) + NB =NB+ n + while NB >= 8 do + NB =NB- 8 + local d = 2 ^ NB + local b = math.floor(ACC / d +) ACC =ACC- b * d + grow(2) + writeu8(OUT, OP, b) + OP =OP+ 1 + if b == 0xFF then + writeu8(OUT, OP, 0) + OP =OP+ 1 + end + end +end + +local function flushBits() + if NB > 0 then + bits(0x7F, 8 - NB) -- pad with ones + end + ACC, NB = 0, 0 +end + +local function nbits(v) +return v == 0 and 0 or 32 - countlz(v) +end +-- ------------------------------------------------------------------------------------------------ Huffman tables +-- a derived table: u16 code + u8 size per symbol (jpeg_make_c_derived_tbl) + + + +local function derive(counts, symbols) +local code, size = buffer.create(512), buffer.create(256) + local c, k = 0, 1 + for l = 1, 16 do + for _ = 1, counts[l] or 0 do + local s = symbols[k] + if s then + writeu16(code, s * 2, c) + writeu8(size, s, l) + end + k =k+ 1 + c =c+ 1 + end + c =c* 2 + end + return { code = code, size = size } +end + +-- jchuff.c jpeg_gen_optimal_table: freq (0..256, 1-based +1) -> counts, symbols +local function optimal(freqIn) +local freq = table.create(257, 0) + local bitsT = table.create(34, 0) + local codesize = table.create(257, 0) + local others = table.create(257, -1) + local nz = table.create(257, 0) + local n = 0 + for i = 0, 256 do + local f = i == 256 and 1 or freqIn[i + 1] + if f > 0 then + n =n+ 1 + nz[n] = i + freq[n] = f + end + end + while true do + local c1, c2 = -1, -1 + local v, v2 = 1e9, 1e9 + for i = 1, n do + local f = freq[i] + if f <= v2 then + if f <= v then + c2 = c1 + v2 = v + v = f + c1 = i + else + v2 = f + c2 = i + end + end + end + if c2 < 0 then + break + end + freq[c1]=freq[c1]+ freq[c2] + freq[c2] = 1000000001 + codesize[c1]=codesize[c1]+ 1 + while others[c1] >= 0 do + c1 = others[c1] + codesize[c1]=codesize[c1]+ 1 + end + others[c1] = c2 + codesize[c2]=codesize[c2]+ 1 + while others[c2] >= 0 do + c2 = others[c2] + codesize[c2]=codesize[c2]+ 1 + end + end + for i = 1, n do + local cs = math.min(codesize[i], 32) +do local __DARKLUA_VAR=cs + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]+ 1 +end end + local bitPos = table.create(34, 0) + local p = 0 + for i = 1, 32 do + bitPos[i + 1] = p + p =p+ bitsT[i + 1] + end + local i = 32 + while i > 16 do + while bitsT[i + 1] > 0 do + local j = i - 2 + while bitsT[j + 1] == 0 do + j =j- 1 + end +do local __DARKLUA_VAR=i + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]- 2 +end bitsT[i]=bitsT[i]+ 1 +do local __DARKLUA_VAR0=j + 2 bitsT[__DARKLUA_VAR0]=bitsT[__DARKLUA_VAR0]+ 2 +end do local __DARKLUA_VAR1=j + 1 bitsT[__DARKLUA_VAR1]=bitsT[__DARKLUA_VAR1]- 1 +end end + i =i- 1 + end + while bitsT[i + 1] == 0 do + i =i- 1 + end +do local __DARKLUA_VAR=i + 1 bitsT[__DARKLUA_VAR]=bitsT[__DARKLUA_VAR]- 1 +end local counts = table.create(16, 0) + for l = 1, 16 do + counts[l] = bitsT[l + 1] + end + local symbols = table.create(n, 0) + for k = 1, n - 1 do + local cs = math.min(codesize[k], 32) + symbols[bitPos[cs + 1] + 1] = nz[k] +do local __DARKLUA_VAR0=cs + 1 bitPos[__DARKLUA_VAR0]=bitPos[__DARKLUA_VAR0]+ 1 +end end + local total = 0 + for l = 1, 16 do + total =total+ counts[l] + end + local out = table.create(total, 0) + for k = 1, total do + out[k] = symbols[k] + end + return counts, out +end +Encode.optimal = optimal + +-- ------------------------------------------------------------------------------------------------ entropy coding state +local dcTab= {} +local acTab= {} +local dcFreq= {} +local acFreq= {} + +local function symbol(t, freq, s) + if GATHER then +do local __DARKLUA_VAR=s + 1 freq[__DARKLUA_VAR]=freq[__DARKLUA_VAR]+ 1 +end else + bits(readu16(t.code, s * 2), readu8(t.size, s)) + end +end + + + + + + + + + + + + + + + + +local function dcDiff(c, diff) + local t = diff + local t2 = diff + if t < 0 then + t = -t + t2 =t2- 1 + end + local n = nbits(t) + symbol(dcTab[c.td + 1], dcFreq[c.td + 1], n) + if n > 0 then + bits(t2, n) + end +end + +-- jchuff.c encode_one_block +local function blockSeq(c, off) + local coef = c.coef + local dc = readi16(coef, off) + dcDiff(c, dc - c.last) + c.last = dc + local at, af = acTab[c.ta + 1], acFreq[c.ta + 1] + local r = 0 + for k = 1, 63 do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + if v == 0 then + r =r+ 1 + else + while r > 15 do + symbol(at, af, 0xF0) + r =r- 16 + end + local t, t2 = v, v + if t < 0 then + t = -t + t2 =t2- 1 + end + local n = nbits(t) + symbol(at, af, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + symbol(at, af, 0) + end +end + +-- progressive state (jcphuff.c) +local EOBRUN = 0 +local BE = 0 +local CORR = (table.create(1000, 0) ) +local curAc= { code = buffer.create(512), size = buffer.create(256) } +local curAcFreq= {} + +local function emitEobrun() + if EOBRUN > 0 then + local n = nbits(EOBRUN) - 1 + symbol(curAc, curAcFreq, n * 16) + if n > 0 then + bits(EOBRUN, n) + end + EOBRUN = 0 + if not GATHER then + for i = 1, BE do + bits(CORR[i], 1) + end + end + BE = 0 + end +end + +local function blockDcFirst(c, off, al) + local t2 = math.floor(readi16(c.coef, off) / 2 ^ al +) dcDiff(c, t2 - c.last) + c.last = t2 +end + +local function blockAcFirst(c, off, ss, se, al) + local coef = c.coef + local d = 2 ^ al + local r = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t, t2 + if v < 0 then + t = math.floor((-v) / d +) t2 = -t - 1 -- ~t + else + t = math.floor(v / d +) t2 = t + end + if t == 0 then + r =r+ 1 + else + emitEobrun() + while r > 15 do + symbol(curAc, curAcFreq, 0xF0) + r =r- 16 + end + local n = nbits(t) + symbol(curAc, curAcFreq, r * 16 + n) + bits(t2, n) + r = 0 + end + end + if r > 0 then + EOBRUN =EOBRUN+ 1 + if EOBRUN == 0x7FFF then + emitEobrun() + end + end +end + +local absv = table.create(64, 0) + +local function blockAcRefine(c, off, ss, se, al) + local coef = c.coef + local d = 2 ^ al + local eob = 0 + for k = ss, se do + local v = readi16(coef, off + readu8(ZZ, k) * 2) + local t = math.floor(((v < 0 and{(-v )}or{v})[1]) / d +) absv[k + 1] = t + if t == 1 then + eob = k + end + end + local r = 0 + local br = 0 -- correction bits added in this block, at CORR[brStart + 1 ..] + local brStart = BE + for k = ss, se do +local __DARKLUA_CONTINUE_28=false repeat local t = absv[k + 1] + if t == 0 then + r =r+ 1 +__DARKLUA_CONTINUE_28=true break + end + while r > 15 and k <= eob do + emitEobrun() + symbol(curAc, curAcFreq, 0xF0) + r =r- 16 + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + end + if t > 1 then + br =br+ 1 + CORR[brStart + br] = t % 2 +__DARKLUA_CONTINUE_28=true break + end + emitEobrun() + symbol(curAc, curAcFreq, r * 16 + 1) + bits(readi16(coef, off + readu8(ZZ, k) * 2) < 0 and 0 or 1, 1) + if not GATHER then + for i = 1, br do + bits(CORR[brStart + i], 1) + end + end + brStart = 0 + br = 0 + r = 0 +__DARKLUA_CONTINUE_28=true until true if not __DARKLUA_CONTINUE_28 then break end end + if r > 0 or br > 0 then + EOBRUN =EOBRUN+ 1 + BE =BE+ br + if EOBRUN == 0x7FFF or BE > 1000 - 64 + 1 then + emitEobrun() + end + end +end +-- ------------------------------------------------------------------------------------------------ scans +-- iterate the scan's MCUs (or blocks, for one component), calling fn(c, off) per block; restart markers when ri > 0 + + + +local function walk(comps, mcusX, mcusY, ri, onRestart, fn) + local nc = #comps + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = mcusX + units = ux * mcusY + end + local rn = 0 + for u = 0, units - 1 do + if ri > 0 and u > 0 and u % ri == 0 then + onRestart(rn) + rn = (rn + 1) % 8 + end + local my, mx = math.floor(u / ux), u % ux + for ci = 1, nc do + local c = comps[ci] + if nc == 1 then + fn(c, (my * c.bpl + mx) * 128) + else + for by = my * c.v, my * c.v + c.v - 1 do + for bx = mx * c.h, mx * c.h + c.h - 1 do + fn(c, (by * c.bpl + bx) * 128) + end + end + end + end + end +end + +local function dht(class, slot, counts, symbols) + byte(0xFF) + byte(0xC4) + u16be(2 + 17 + #symbols) + byte(class * 16 + slot) + for l = 1, 16 do + byte(counts[l]) + end + for _, s in __iter(symbols) do + byte(s) + end +end + +local function sos(comps, ss, se, ah, al, dcOnly, acOnly) + byte(0xFF) + byte(0xDA) + u16be(6 + 2 * #comps) + byte(#comps) + for _, c in __iter(comps) do + byte(c.id) + local td = acOnly and 0 or c.td + local ta = dcOnly and 0 or c.ta + byte(td * 16 + ta) + end + byte(ss) + byte(se) + byte(ah * 16 + al) +end + +-- ------------------------------------------------------------------------------------------------ planes +-- jccolor.c rgb_ycc_start tables (16-bit fixed point) +local function fix(x) +return math.floor(x * 65536 + 0.5) +end +local YR, YG, YB = fix(0.29900), fix(0.58700), fix(0.11400) +local CBR, CBG, HALF = fix(0.16874), fix(0.33126), fix(0.5) +local CRG, CRB = fix(0.41869), fix(0.08131) +local OFF = 128 * 65536 + 32768 - 1 + +-- pixels (rgba8 / rgb8 / gray8) -> Y, Cb, Cr planes (w * h bytes each; Cb / Cr nil for grey output) +local function planes(px, w, h, bpp, gray) +local n = w * h + local Y = buffer.create(n) + if bpp == 1 then + buffer.copy(Y, 0, px, 0, n) + if gray then + return Y, nil, nil + end + local Cb = buffer.create(n) + buffer.fill(Cb, 0, 128, n) + local Cr = buffer.create(n) + buffer.fill(Cr, 0, 128, n) + return Y, Cb, Cr + end + if gray then + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, math.floor((YR * r + YG * g + YB * b + 32768) / 65536)) + end + return Y, nil, nil + end + local Cb, Cr = buffer.create(n), buffer.create(n) + for i = 0, n - 1 do + local o = i * bpp + local r, g, b = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2) + writeu8(Y, i, math.floor((YR * r + YG * g + YB * b + 32768) / 65536)) + writeu8(Cb, i, math.floor((-CBR * r - CBG * g + HALF * b + OFF) / 65536)) + writeu8(Cr, i, math.floor((HALF * r - CRG * g - CRB * b + OFF) / 65536)) + end + return Y, Cb, Cr +end + +-- jcsample.c: a full-resolution plane (w x h) -> the component's samples, (bw * 8) x ch, for factors hf x vf +-- (1 or 2 each); full-resolution columns past w - 1 repeat the last one, rows past h - 1 the last row +local function downsample(src, w, h, hf, vf, outW, outH) +local out = buffer.create(outW * outH) + for oy = 0, outH - 1 do + local r0 = math.min(oy * vf, h - 1) * w + local r1 = math.min(oy * vf + vf - 1, h - 1) * w + local bias = hf == 2 and vf == 2 and 1 or(hf == 2 and 0 or(vf == 2 and 1 or 0) +) for ox = 0, outW - 1 do + local x0 = math.min(ox * hf, w - 1) + local x1 = math.min(ox * hf + hf - 1, w - 1) + local v + if hf == 2 and vf == 2 then + v = math.floor((readu8(src, r0 + x0) + readu8(src, r0 + x1) + readu8(src, r1 + x0) + readu8(src, r1 + x1) + bias) / 4 +) bias = 3 - bias + elseif hf == 2 then + v = math.floor((readu8(src, r0 + x0) + readu8(src, r0 + x1) + bias) / 2 +) bias = 1 - bias + else + v = math.floor((readu8(src, r0 + x0) + readu8(src, r1 + x0) + bias) / 2 +) bias = 1 - bias + end + writeu8(out, oy * outW + ox, v) + end + end + return out +end +-- ------------------------------------------------------------------------------------------------ encode +-- run(pixels, w, h, bpp, opts) -> buffer. pixels: w * h * bpp bytes (bpp 4 rgba8 / 3 rgb8 / 1 gray8), or bpp 0: +-- yuv420p (w * h luma, then ceil(w / 2) * ceil(h / 2) Cb and Cr; opts.sampling must be "420" unless opts.gray). The +-- caller validated sizes (1..65535), the buffer length and options. + + + + + + + + + + + + + +function Encode.run(px, w, h, bpp, o) +OUT = buffer.create(math.max(1024, math.floor(w * h / 2))) + CAP = buffer.len(OUT) + OP = 0 + ACC, NB = 0, 0 + GATHER = false + EOBRUN, BE = 0, 0 + + local yuv = bpp == 0 + local Y, Cb, Cr + if yuv then + local n, cn = w * h, (math.floor((w + 1) / 2)) * (math.floor((h + 1) / 2)) + Y = px + if not o.gray then + Cb, Cr = buffer.create(cn), buffer.create(cn) + buffer.copy(Cb , 0, px, n, cn) + buffer.copy(Cr , 0, px, n + cn, cn) + end + else + Y, Cb, Cr = planes(px, w, h, bpp, o.gray) + end + local hs, vs = 1, 1 + if not o.gray then + if o.sampling == "420" then + hs, vs = 2, 2 + elseif o.sampling == "422" then + hs, vs = 2, 1 + end + end + local mcusX = math.ceil(w / (8 * hs)) + local mcusY = math.ceil(h / (8 * vs)) + local qt = { Tables.quant(Tables.LUMA, o.quality), Tables.quant(Tables.CHROMA, o.quality) } + local qdiv = {} + for t = 1, 2 do + local b = buffer.create(128) + for i = 1, 64 do + writeu16(b, (i - 1) * 2, qt[t][i]) + end + qdiv[t] = b + end + + -- components and their quantised coefficients + local comps= {} + local srcs = o.gray and{ Y } or{ Y, Cb , Cr } + for i, src in __iter(srcs) do + local ch, cv = (i == 1 and{hs }or{1})[1], (i == 1 and{vs }or{1 +})[1] local cw = math.ceil(w * ch / hs) + local chh = math.ceil(h * cv / vs) + local bw, bh = math.ceil(cw / 8), math.ceil(chh / 8) + local bpl, bpc = mcusX * ch, mcusY * cv + local plane, pw, ph = src, w, h + if yuv and i > 1 then + pw, ph = math.floor((w + 1) / 2), math.floor((h + 1) / 2 -- already 4:2:0: fdctQuantize repeats the edges as jcsample.c does +) elseif ch < hs or cv < vs then + pw, ph = bw * 8, chh + plane = downsample(src, w, h, math.floor(hs / ch), math.floor(vs / cv), pw, ph) + end + local coef = buffer.create(bpl * bpc * 128) + local c= { + id = i, + h = ch, + v = cv, + tq = i == 1 and 0 or 1, + td = i == 1 and 0 or 1, + ta = i == 1 and 0 or 1, + bw = bw, + bh = bh, + bpl = bpl, + bpc = bpc, + coef = coef, + last = 0, + } + local div = qdiv[c.tq + 1] + for by = 0, bpc - 1 do + for bx = 0, bpl - 1 do + local off = (by * bpl + bx) * 128 + if by < bh and bx < bw then + Dct.fdctQuantize(plane, pw, bx * 8, by * 8, pw, ph, div, coef, off) + elseif by < bh then + writei16(coef, off, readi16(coef, off - 128)) -- right edge: the previous block's DC + else + -- bottom: the DC of the MCU's last block in the row above + local lb = (math.floor(bx / ch)) * ch + ch - 1 + writei16(coef, off, readi16(coef, ((by - 1) * bpl + lb) * 128)) + end + end + end + comps[i] = c + end + + -- headers + byte(0xFF) + byte(0xD8) + if o.jfif then + local d = o.density or { unit = 0, x = 1, y = 1 } + byte(0xFF) + byte(0xE0) + u16be(16) + for _, ch in __iter({ 0x4A, 0x46, 0x49, 0x46, 0 }) do + byte(ch) + end + byte(1) + byte(1) + byte(d.unit) + u16be(d.x) + u16be(d.y) + byte(0) + byte(0) + end + for _, s in __iter(o.segments) do + local n = buffer.len(s.data) + byte(0xFF) + byte(s.marker) + u16be(n + 2) + grow(n) + buffer.copy(OUT, OP, s.data, 0, n) + OP =OP+ n + end + for t = 1, (o.gray and 1 or 2) do + byte(0xFF) + byte(0xDB) + u16be(67) + byte(t - 1) + for k = 0, 63 do + byte(qt[t][readu8(ZZ, k) + 1]) + end + end + byte(0xFF) + byte(o.progressive and 0xC2 or 0xC0) + u16be(8 + 3 * #comps) + byte(8) + u16be(h) + u16be(w) + byte(#comps) + for _, c in __iter(comps) do + byte(c.id) + byte(c.h * 16 + c.v) + byte(c.tq) + end + local ntab = o.gray and 1 or 2 + + local function restartMarker(n) + flushBits() + byte(0xFF) + byte(0xD0 + n) + end + + if not o.progressive then + if o.optimize then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + for _, c in __iter(comps) do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, function() + for _, c in __iter(comps) do + c.last = 0 + end + end, blockSeq) + GATHER = false + end + for t = 1, ntab do + local dcC, dcS, acC, acS + if o.optimize then + dcC, dcS = optimal(dcFreq[t]) + acC, acS = optimal(acFreq[t]) + else + local d, a = Tables.DC[t], Tables.AC[t] + dcC, dcS, acC, acS = d.counts, d.symbols, a.counts, a.symbols + end + dcTab[t] = derive(dcC, dcS) + acTab[t] = derive(acC, acS) + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + -- libjpeg emits each table before the scan in component order: DC0, AC0, DC1, AC1 + dht(0, t - 1, dcC, dcS) + dht(1, t - 1, acC, acS) + end + if o.restart > 0 then + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(comps, 0, 63, 0, 0, false, false) + for _, c in __iter(comps) do + c.last = 0 + end + walk(comps, mcusX, mcusY, o.restart, function(n) + restartMarker(n) + for _, c in __iter(comps) do + c.last = 0 + end + end, blockSeq) + flushBits() + else + local script +if o.gray then + script = { + { comps = { 1 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + else + script = { + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 0, al = 1 }, + { comps = { 1 }, ss = 1, se = 5, ah = 0, al = 2 }, + { comps = { 3 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 2 }, ss = 1, se = 63, ah = 0, al = 1 }, + { comps = { 1 }, ss = 6, se = 63, ah = 0, al = 2 }, + { comps = { 1 }, ss = 1, se = 63, ah = 2, al = 1 }, + { comps = { 1, 2, 3 }, ss = 0, se = 0, ah = 1, al = 0 }, + { comps = { 3 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 2 }, ss = 1, se = 63, ah = 1, al = 0 }, + { comps = { 1 }, ss = 1, se = 63, ah = 1, al = 0 }, + } + end + local driSent = false + for _, sc in __iter(script) do + local sComps= {} + for _, ci in __iter(sc.comps) do + table.insert(sComps, comps[ci]) + end + local ss, se, ah, al = sc.ss, sc.se, sc.ah, sc.al + local isDc = ss == 0 + local blockFn +if isDc and ah == 0 then + blockFn = function(c, off) + blockDcFirst(c, off, al) + end + elseif isDc then + blockFn = function(c, off) + bits(band(math.floor(readi16(c.coef, off) / 2 ^ al), 1), 1) + end + elseif ah == 0 then + blockFn = function(c, off) + blockAcFirst(c, off, ss, se, al) + end + else + blockFn = function(c, off) + blockAcRefine(c, off, ss, se, al) + end + end + local function onRestart(n) + emitEobrun() + if not GATHER then + restartMarker(n) + end + for _, c in __iter(sComps) do + c.last = 0 + end + EOBRUN, BE = 0, 0 + end + local function pass() + for _, c in __iter(sComps) do + c.last = 0 + end + EOBRUN, BE = 0, 0 + walk(sComps, mcusX, mcusY, o.restart, onRestart, blockFn) + emitEobrun() + end + -- gather statistics, then emit the optimal tables this scan uses + if not (isDc and ah > 0) then + GATHER = true + for t = 1, ntab do + dcFreq[t] = table.create(257, 0) + acFreq[t] = table.create(257, 0) + end + if not isDc then + curAcFreq = acFreq[sComps[1].ta + 1] + end + pass() + GATHER = false + local sent = {} + for _, c in __iter(sComps) do + local slot = (isDc and{c.td }or{c.ta +})[1] if not sent[slot] then + sent[slot] = true + local counts, syms = optimal((isDc and{dcFreq[slot + 1] }or{acFreq[slot + 1]})[1]) + dht(isDc and 0 or 1, slot, counts, syms) + if isDc then + dcTab[slot + 1] = derive(counts, syms) + else + acTab[slot + 1] = derive(counts, syms) + end + end + end + if not isDc then + curAc = acTab[sComps[1].ta + 1] + end + end + if o.restart > 0 and not driSent then + driSent = true + byte(0xFF) + byte(0xDD) + u16be(4) + u16be(o.restart) + end + sos(sComps, ss, se, ah, al, isDc, not isDc or ah > 0) -- DC refinement uses no table: td = 0 (as libjpeg) + pass() + flushBits() + end + end + byte(0xFF) + byte(0xD9) + local res = buffer.create(OP) + buffer.copy(res, 0, OUT, 0, OP) + OUT = buffer.create(0) + CAP = 0 + return res +end + +return Encode +end +__FILES["codecs/image/Jpeg/Scan"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from +-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header. +-- +-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF, +-- records where each RSTn marker fell, and stops at any other marker. The clean buffer is followed by at least +-- PAD zero bytes, so the bit reader can read 32 bits at any position up to PAD bytes past the end without a +-- bounds check. `run` checks the position once per MCU, and no MCU (at most 10 blocks, enforced by the parser) +-- can consume PAD bytes. So every buffer index stays in range, even on garbage data. +-- +-- The bit reader keeps no state but a bit position: `peek` reads the big-endian 32-bit word that holds it. +-- Huffman tables (built by `buildTable`) are buffers: +-- [0, 1024) fast lookup by the next 9 bits: u16 (length << 8) | symbol, 0 = longer code +-- [1024, 1096) maxcode[l], l = 0..17: u32, one past the last code of length l, left-aligned to 16 bits +-- [1096, 1168) delta[l]: i32, symbol index = code + delta[l] +-- [1168, 1424) symbols +-- [1424, 1426) symbol count +-- [1428, 3476) fast AC lookup by the next 9 bits: i32 value * 256 + run * 16 + total length, when the code +-- and its extra bits fit in 9 bits (0 otherwise) +local readu8, readu16, readu32, readi32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readi16 +local writeu8, writeu16, writeu32, writei32, writei16 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writei32, buffer.writei16 +local band, bor, lshift, rshift, byteswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.byteswap + +local Scan = {} + +Scan.PAD = 4096 +Scan.TABLE_SIZE = 3476 + +local T_MAX = 1024 +local T_DELTA = 1096 +local T_VAL = 1168 +local T_COUNT = 1424 +local T_FASTAC = 1428 + +-- zigzag index -> natural (row-major) index, padded with 63s so a run past the end stays in range +local ZZ = buffer.create(80) +do + local i = 0 + for s = 0, 14 do + local lo, hi = math.max(0, s - 7), math.min(s, 7) + if s % 2 == 0 then + for r = hi, lo, -1 do + writeu8(ZZ, i, r * 8 + (s - r)) + i =i+ 1 + end + else + for r = lo, hi do + writeu8(ZZ, i, r * 8 + (s - r)) + i =i+ 1 + end + end + end + for j = 64, 79 do + writeu8(ZZ, j, 63) + end +end +Scan.ZIGZAG = ZZ + +-- Builds a Huffman table from the 16 code-length counts and the symbols (Luau arrays, 1-based). An +-- over-subscribed table keeps the codes that fit; the rest decode as invalid. +function Scan.buildTable(counts, symbols) +local t = buffer.create(Scan.TABLE_SIZE) + local code, k = 0, 0 + local nsym = #symbols + local codes, sizes = {}, {} + local broken = false + for l = 1, 16 do + writei32(t, T_DELTA + l * 4, k - code) + local n = counts[l] or 0 + for _ = 1, n do + if broken or code >= lshift(1, l) or k >= nsym or k >= 256 then + broken = true + break + end + k =k+ 1 + codes[k] = code + sizes[k] = l + code =code+ 1 + end + writeu32(t, T_MAX + l * 4, broken and 0 or lshift(code, 16 - l)) + code =code* 2 + end + writeu32(t, T_MAX + 17 * 4, 0xFFFFFFFF) + for i = 1, k do + writeu8(t, T_VAL + i - 1, symbols[i]) + end + writeu16(t, T_COUNT, k) + -- fast lookups + for i = 1, k do + local l = sizes[i] + if l <= 9 then + local sym = symbols[i] + local base = lshift(codes[i], 9 - l) + for j = 0, lshift(1, 9 - l) - 1 do + local idx = base + j + writeu16(t, idx * 2, l * 256 + sym) + local r, s = rshift(sym, 4), band(sym, 15) + if s ~= 0 and l + s <= 9 then + local v = band(rshift(idx, 9 - l - s), lshift(1, s) - 1) + if v < lshift(1, s - 1) then + v = v - lshift(1, s) + 1 + end + writei32(t, T_FASTAC + idx * 4, v * 256 + r * 16 + l + s) + end + end + end + end + return t +end + +-- Copies the entropy-coded data at src[pos..n) into dst (at least n - pos + PAD bytes): byte stuffing removed, +-- RSTn offsets (in dst) stored in rst[1..]. Returns the source position of the marker that ended the scan (or n), +-- the clean length, and the RST count. The PAD bytes after the clean data are zeroed. +function Scan.destuff(src, pos, n, dst, rst) +local o, nr = 0, 0 + while pos < n do + local b = readu8(src, pos) + if b ~= 0xFF then + writeu8(dst, o, b) + o =o+ 1 + pos =pos+ 1 + else + local q = pos + 1 + while q < n and readu8(src, q) == 0xFF do + q =q+ 1 + end + if q >= n then + pos = n + break + end + local m = readu8(src, q) + if m == 0 then + writeu8(dst, o, 0xFF) + o =o+ 1 + pos = q + 1 + elseif m >= 0xD0 and m <= 0xD7 then + nr =nr+ 1 + rst[nr] = o + pos = q + 1 + else + pos = q - 1 + break + end + end + end + buffer.fill(dst, o, 0, Scan.PAD) + return pos, o, nr +end + +local function huff(d, pos, t) +local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local f = readu16(t, rshift(w, 23) * 2) + if f ~= 0 then + return band(f, 255), pos + rshift(f, 8) + end + local c = rshift(w, 16) + local l = 10 + while c >= readu32(t, T_MAX + l * 4) do + l =l+ 1 + end + if l > 16 then + return 0, pos + 16 -- invalid code + end + local idx = rshift(c, 16 - l) + readi32(t, T_DELTA + l * 4) + if idx < 0 or idx >= readu16(t, T_COUNT) then + return 0, pos + l + end + return readu8(t, T_VAL + idx), pos + l +end + +-- the next s bits (1 <= s <= 16) as an unsigned number +local function bits(d, pos, s) +return rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 32 - s) +end + +local function extend(v, s) +if v < lshift(1, s - 1) then + return v - lshift(1, s) + 1 + end + return v +end + +-- sequential (baseline / extended) block: returns pos, DC predictor +local function blockSeq(d, pos, coef, off, dct, act, pred) +local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred =pred+ extend(bits(d, pos, s), s) + pos =pos+ s + end + writei16(coef, off, pred) + local k = 1 + while k < 64 do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k =k+ math.floor(low / 16 +) pos =pos+ low % 16 + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, math.floor(fa / 256)) + k =k+ 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, sz = rshift(rs, 4), band(rs, 15) + if sz == 0 then + if r ~= 15 then + break + end + k =k+ 16 + else + k =k+ r + if k > 63 then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, sz), sz)) + pos =pos+ sz + k =k+ 1 + end + end + end + return pos, pred +end + +local function blockDcFirst(d, pos, coef, off, dct, pred, al) +local s + s, pos = huff(d, pos, dct) + if s ~= 0 then + if s > 16 then + s = 16 + end + pred =pred+ extend(bits(d, pos, s), s) + pos =pos+ s + end + writei16(coef, off, pred * lshift(1, al)) + return pos, pred +end + +local function blockAcFirst(d, pos, coef, off, act, ss, se, al, eobrun) +if eobrun > 0 then + return pos, eobrun - 1 + end + local mul = lshift(1, al) + local k = ss + while k <= se do + local w = lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)) + local fa = readi32(act, T_FASTAC + rshift(w, 23) * 4) + if fa ~= 0 then + local low = fa % 256 + k =k+ math.floor(low / 16 +) pos =pos+ low % 16 + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, (math.floor(fa / 256)) * mul) + k =k+ 1 + else + local rs + rs, pos = huff(d, pos, act) + local r, s = rshift(rs, 4), band(rs, 15) + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun =eobrun+ bits(d, pos, r) + pos =pos+ r + end + break + end + k =k+ 16 + else + k =k+ r + if k > se then + break + end + writei16(coef, off + readu8(ZZ, k) * 2, extend(bits(d, pos, s), s) * mul) + pos =pos+ s + k =k+ 1 + end + end + end + return pos, eobrun +end + +-- successive-approximation refinement of AC coefficients ss..se (as stb_image / libjpeg decode_mcu_AC_refine) +local function blockAcRefine(d, pos, coef, off, act, ss, se, al, eobrun) +local bit = lshift(1, al) + if eobrun > 0 then + for k = ss, se do + local o = off + readu8(ZZ, k) * 2 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos =pos+ 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, (p > 0 and((p + bit ))or((p - bit)))) + end + end + end + return pos, eobrun - 1 + end + local k = ss + while k <= se do + local rs + rs, pos = huff(d, pos, act) + local s, r = band(rs, 15), rshift(rs, 4) + local val = 0 + if s == 0 then + if r < 15 then + eobrun = lshift(1, r) - 1 + if r > 0 then + eobrun =eobrun+ bits(d, pos, r) + pos =pos+ r + end + r = 64 -- the rest of the block only refines + end + else + -- s must be 1; anything else is corrupt and treated as 1 + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos =pos+ 1 + val = (b ~= 0 and{bit }or{(-bit +)})[1] end + while k <= se do + local o = off + readu8(ZZ, k) * 2 + k =k+ 1 + local p = readi16(coef, o) + if p ~= 0 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos =pos+ 1 + if b ~= 0 and band(p, bit) == 0 then + writei16(coef, o, (p > 0 and((p + bit ))or((p - bit)))) + end + else + if r == 0 then + if val ~= 0 then + writei16(coef, o, val) + end + break + end + r =r- 1 + end + end + end + -- an EOB run that started in this block counts it already (eobrun = run length - 1) + return pos, eobrun +end + +-- Decodes one scan from the clean data d (cleanLen bytes, then PAD zeros). Returns the final bit position and +-- whether the data ran out (or overran) before the last MCU. + + + + + + + + + + + + + + + + + + + + + + + + +function Scan.run(d, cleanLen, rst, nrst, P) +local comps = P.comps + local nc = #comps + local mode, ss, se, al, ri = P.mode, P.ss, P.se, P.al, P.ri + local endBits = cleanLen * 8 + local units, ux + if nc == 1 then + ux = comps[1].bw + units = ux * comps[1].bh + else + ux = P.mcusX + units = ux * P.mcusY + end + for i = 1, nc do + comps[i].pred = 0 + end + local pos, eobrun, rstIdx = 0, 0, 0 + local truncated, skipping = false, false + local bit = lshift(1, al) + local hook = P.hook + for u = 0, units - 1 do + if hook and u > 0 and u % ux == 0 then + pcall(hook) + end + if ri > 0 and u > 0 and u % ri == 0 then + rstIdx =rstIdx+ 1 + if rstIdx <= nrst then + pos = rst[rstIdx] * 8 + skipping = false + end + for i = 1, nc do + comps[i].pred = 0 + end + eobrun = 0 + end + if pos > endBits then + truncated = true + if ri == 0 or rstIdx >= nrst then + break + end + skipping = true + end + if not skipping then + local my, mx = math.floor(u / ux), u % ux + for ci = 1, nc do + local c = comps[ci] + local bh, bw, by0, bx0 + if nc == 1 then + bh, bw, by0, bx0 = 1, 1, my, mx + else + bh, bw, by0, bx0 = c.v, c.h, my * c.v, mx * c.h + end + local coef, bpl = c.coef, c.bpl + for by = by0, by0 + bh - 1 do + for bx = bx0, bx0 + bw - 1 do + local off = (by * bpl + bx) * 128 + if mode == 0 then + pos, c.pred = blockSeq(d, pos, coef, off, c.dct , c.act , c.pred) + elseif mode == 1 then + pos, c.pred = blockDcFirst(d, pos, coef, off, c.dct , c.pred, al) + elseif mode == 2 then + local b = rshift(lshift(byteswap(readu32(d, rshift(pos, 3))), band(pos, 7)), 31) + pos =pos+ 1 + if b ~= 0 then + writei16(coef, off, bor(readi16(coef, off), bit)) + end + elseif mode == 3 then + pos, eobrun = blockAcFirst(d, pos, coef, off, c.act , ss, se, al, eobrun) + else + pos, eobrun = blockAcRefine(d, pos, coef, off, c.act , ss, se, al, eobrun) + end + end + end + end + end + end + return pos, truncated +end + +return Scan +end +__FILES["codecs/image/Jpeg/Tables"] = function() +--!strict +-- codecs/image/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline +-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation +-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table). +local Tables = {} + +local function range(t, a, b) + for v = a, b do + table.insert(t, v) + end +end + +-- { counts (16 code-length counts), symbols } per table: dc[1] luma, dc[2] chroma, ac[1], ac[2] +local dcl = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 } +local dcc = { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } +local dcv = {} +range(dcv, 0, 11) +local acl = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d } +local aclv = { + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, +} +range(aclv, 0x34, 0x3a) +for hi = 4, 8 do + range(aclv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 9, 13 do + range(aclv, hi * 16 + 2, hi * 16 + 10) +end +range(aclv, 0xe1, 0xea) +range(aclv, 0xf1, 0xfa) +local acc = { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 } +local accv = { + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, +} +range(accv, 0x35, 0x3a) +for hi = 4, 7 do + range(accv, hi * 16 + 3, hi * 16 + 10) +end +for hi = 8, 14 do + range(accv, hi * 16 + 2, hi * 16 + 10) +end +range(accv, 0xf2, 0xfa) + + +Tables.DC = { { counts = dcl, symbols = dcv }, { counts = dcc, symbols = dcv } } +Tables.AC = { { counts = acl, symbols = aclv }, { counts = acc, symbols = accv } } +-- K.1, natural (row-major) order + +Tables.LUMA = { + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, + 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, + 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +} +Tables.CHROMA = { + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, +} + +-- quant(base, quality) -> 64 values (natural order) for quality 1..100, clamped to 1..255 (baseline) +function Tables.quant(base, quality) +local q = math.clamp(math.floor(quality), 1, 100) + local scale = (q < 50 and{(math.floor(5000 / q ))}or{(200 - q * 2 +)})[1] local out = table.create(64, 1) + for i = 1, 64 do + out[i] = math.clamp(math.floor((base[i] * scale + 50) / 100), 1, 255) + end + return out +end + +return Tables +end +__FILES["codecs/image/Jpeg/Yuv"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16 +-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4 +-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG). +-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes. +local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32 + +local Yuv = {} + +-- crop(src, stride, w, h, dst, doff): the top-left w x h samples of a u16 plane (stride samples per row) into u8 +-- samples at dst[doff], w per row +function Yuv.crop(src, stride, w, h, dst, doff) + local quads = math.floor(w / 4 +) local rest = w - quads * 4 + for y = 0, h - 1 do + local s = y * stride * 2 + local d = doff + y * w + -- four samples (two u32 reads of two u16 samples, each 0..255) per u32 write + for _ = 1, quads do + local a, b = readu32(src, s), readu32(src, s + 4) + writeu32(dst, d, a % 65536 + (math.floor(a / 65536)) * 256 + (b % 65536) * 65536 + (math.floor(b / 65536)) * 16777216) + s =s+ 8 + d =d+ 4 + end + for k = 0, rest - 1 do + writeu8(dst, d + k, readu16(src, s + k * 2)) + end + end +end + +-- rows(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:2:2 chroma) -> u8 w x ceil(h / 2), each output +-- row the rounded mean of two source rows (the last row alone when h is odd) +function Yuv.rows(src, stride, w, h, dst, doff) + local oh = math.floor((h + 1) / 2 +) for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = (2 * y + 1 < h and((a + stride * 2 ))or(a +)) local d = doff + y * w + for x = 0, w - 1 do + writeu8(dst, d + x, math.floor((readu16(src, a + x * 2) + readu16(src, b + x * 2) + 1) / 2)) + end + end +end + +-- box(src, stride, w, h, dst, doff): a u16 plane of w x h samples (4:4:4 chroma) -> u8 ceil(w / 2) x ceil(h / 2), +-- each output sample the rounded mean of a 2 x 2 block (edges repeat the last row / column) +function Yuv.box(src, stride, w, h, dst, doff) + local ow, oh = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) for y = 0, oh - 1 do + local a = 2 * y * stride * 2 + local b = (2 * y + 1 < h and((a + stride * 2 ))or(a +)) local d = doff + y * ow + for x = 0, ow - 1 do + local x0 = 2 * x * 2 + local x1 = (2 * x + 1 < w and((x0 + 2 ))or(x0 +)) writeu8(dst, d + x, math.floor((readu16(src, a + x0) + readu16(src, a + x1) + readu16(src, b + x0) + readu16(src, b + x1) + 2) / 4)) + end + end +end + +-- weave(top, toff, bottom, boff, rowBytes, rows, dst, doff): interleave rows of two planes (field 1 on the even rows, field +-- 2 on the odd rows) into rows output rows at dst[doff]; top holds ceil(rows / 2) rows, bottom floor(rows / 2) +function Yuv.weave(top, toff, bottom, boff, rowBytes, rows, dst, doff) + for y = 0, rows - 1 do + local k = math.floor(y / 2 +) if y % 2 == 0 then + buffer.copy(dst, doff + y * rowBytes, top, toff + k * rowBytes, rowBytes) + else + buffer.copy(dst, doff + y * rowBytes, bottom, boff + k * rowBytes, rowBytes) + end + end +end + +return Yuv +end +__FILES["codecs/image/Pixels"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, +-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 / +-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA / +-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops +-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every +-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each +-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A). +local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift + +local Pixels = {} + +-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], +-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, +-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). +function Pixels.palette(src, base, n, bgr) +local pal = buffer.create(1024) + local m = (base >= 0 and{(math.clamp(math.min(n, math.floor((buffer.len(src) - base) / 3)), 0, 256) )}or{0 +})[1] for i = 0, 255 do + local v = 0xFF000000 + if i < m then + local o = base + i * 3 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + if bgr then + r, b = b, r + end + v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) + end + writeu32(pal, i * 4, v) + end + return pal +end + +-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) +function Pixels.indexed(src, base, stride, bpp, dst, w, h, + topDown, pal) + local mask = lshift(1, bpp) - 1 + for r = 0, h - 1 do + local so = base + r * stride + local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 + if bpp == 8 then + for x = 0, w - 1 do + writeu32(dst, d + x * 4, readu32(pal, readu8(src, so + x) * 4)) + end + elseif bpp == 4 then + for x = 0, w - 1 do + local b = readu8(src, so + rshift(x, 1)) + local i = (band(x, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) +)})[1] writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + else + for x = 0, w - 1 do + local bit = x * bpp + local b = readu8(src, so + rshift(bit, 3)) + local i = band(rshift(b, 8 - bpp - band(bit, 7)), mask) + writeu32(dst, d + x * 4, readu32(pal, i * 4)) + end + end + end +end + +-- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding +function Pixels.rgb555(src, base, stride, dst, w, h, topDown) + for r = 0, h - 1 do + local so = base + r * stride + local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 + for x = 0, w - 1 do + local s = readu16(src, so + x * 2) + local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31) + writeu32(dst, d + x * 4, math.floor((cr * 255 + 15) / 31 )+ (math.floor((cg * 255 + 15) / 31)) * 256 + (math.floor((cb * 255 + 15) / 31)) * 65536 + 0xFF000000) + end + end +end + +-- 24 bpp BI_RGB: B, G, R +function Pixels.bgr24(src, base, stride, dst, w, h, topDown) + for r = 0, h - 1 do + local so = base + r * stride + local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 + for x = 0, w - 1 do + local s = so + x * 3 + writeu32(dst, d + x * 4, + bor(readu8(src, s + 2), lshift(readu8(src, s + 1), 8), lshift(readu8(src, s), 16), 0xFF000000)) + end + end +end + +-- 32 bpp B, G, R, A (BI_RGB, or BITFIELDS with the standard masks). Returns the OR of every alpha byte. +function Pixels.bgra32(src, base, stride, dst, w, h, + topDown) +local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 + for x = 0, w - 1 do + local p = readu32(src, so + x * 4) + -- swap R and B: B G R A -> R G B A + writeu32(dst, d + x * 4, bor(band(p, 0xFF00FF00), band(rshift(p, 16), 0xFF), lshift(band(p, 0xFF), 16))) + aor = bor(aor, p) + end + end + return rshift(aor, 24) +end + +-- 16 / 24 / 32 bpp through bit masks. sh* = shift of each mask, m* = mask >> shift, t* = scale tables (u8, one entry +-- per masked value). A channel without a mask has m = 0 and a 1-entry table (0 for colour, 255 for alpha). +-- Returns the OR of every masked alpha value (before scaling). +function Pixels.masked(src, base, stride, bpp, dst, w, h, + topDown, shr, mr, tr, shg, mg, tg, shb, + mb, tb, sha, ma, ta) +local bytes = rshift(bpp, 3) + local aor = 0 + for r = 0, h - 1 do + local so = base + r * stride + local d = ((topDown and{r }or{(h - 1 - r)})[1]) * w * 4 + for x = 0, w - 1 do + local s = so + x * bytes + local p + if bytes == 2 then + p = readu16(src, s) + elseif bytes == 4 then + p = readu32(src, s) + else + p = bor(readu16(src, s), lshift(readu8(src, s + 2), 16)) + end + local a = band(rshift(p, sha), ma) + aor = bor(aor, a) + local o = d + x * 4 + writeu8(dst, o, readu8(tr, band(rshift(p, shr), mr))) + writeu8(dst, o + 1, readu8(tg, band(rshift(p, shg), mg))) + writeu8(dst, o + 2, readu8(tb, band(rshift(p, shb), mb))) + writeu8(dst, o + 3, readu8(ta, a)) + end + end + return aor +end + +-- Sets every alpha byte to 255 (32-bit images whose alpha channel is all zero are opaque). +function Pixels.opaque(dst, n) + for i = 0, n - 1 do + writeu8(dst, i * 4 + 3, 255) + end +end + +-- RLE8 / RLE4 from src[pos, stop) into dst (pre-filled with transparent black; pixels the stream skips with a +-- delta, an early end of line or an early end of bitmap stay transparent). Malformed or truncated data stops the +-- decode and keeps what was drawn. Returns the number of pixels written. +function Pixels.rle(src, pos, stop, rle4, dst, w, h, + topDown, pal) +local x, y = 0, 0 + local written = 0 + local row = (topDown and 0 or h - 1) * w * 4 + local rowStep = (topDown and((w * 4 ))or((-w * 4 +))) while y < h and pos + 1 < stop do + local n = readu8(src, pos) + local v = readu8(src, pos + 1) + pos =pos+ 2 + if n > 0 then + -- encoded run: n pixels of index v (RLE4: alternating high / low nibble) + local e = math.min(x + n, w) + if rle4 then + local hi, lo = readu32(pal, rshift(v, 4) * 4), readu32(pal, band(v, 15) * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, (band(i - x, 1) == 0 and{hi }or{lo})[1]) + end + else + local c = readu32(pal, v * 4) + for i = x, e - 1 do + writeu32(dst, row + i * 4, c) + end + end + if e > x then + written =written+ (e - x +) end + x =x+ n + elseif v == 0 then + -- end of line + x = 0 + y =y+ 1 + row =row+ rowStep + elseif v == 1 then + break -- end of bitmap + elseif v == 2 then + -- delta: right dx, up (in file rows) dy + if pos + 1 >= stop then + break + end + local dx, dy = readu8(src, pos), readu8(src, pos + 1) + pos =pos+ 2 + x =x+ dx + y =y+ dy + row =row+ rowStep * dy + else + -- absolute run of v pixels, padded to a 16-bit boundary + local nb = (rle4 and{(rshift(v + 1, 1) )}or{v +})[1] if pos + nb > stop then + break + end + local e = math.min(x + v, w) + for i = x, e - 1 do + local k = i - x + local idx + if rle4 then + local b = readu8(src, pos + rshift(k, 1)) + idx = (band(k, 1) == 0 and{(rshift(b, 4) )}or{(band(b, 15) +)})[1] else + idx = readu8(src, pos + k) + end + writeu32(dst, row + i * 4, readu32(pal, idx * 4)) + end + if e > x then + written =written+ (e - x +) end + x =x+ v + pos =pos+ (nb + band(nb, 1) +) end + end + return written +end + +-- Encoder: rgba8 (top-down) -> 24 bpp BGR rows, bottom-up, each padded to stride (dst is zero-filled) +function Pixels.encode24(src, w, h, dst, base, stride) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + writeu8(dst, d, band(rshift(v, 16), 255)) + writeu8(dst, d + 1, band(rshift(v, 8), 255)) + writeu8(dst, d + 2, band(v, 255)) + d =d+ 3 + end + end +end + +-- rgba8 -> 32 bpp BGRA, bottom-up +function Pixels.encode32(src, w, h, dst, base) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * w * 4 + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + -- R G B A (little-endian u32: R | G << 8 | B << 16 | A << 24) -> B G R A + writeu32(dst, d + x * 4, bor(band(v, 0xFF00FF00), band(rshift(v, 16), 255), lshift(band(v, 255), 16))) + end + end +end + +-- rgba8 -> 8 bpp indexes through idx (a table colour -> index, colours as R | G << 8 | B << 16), bottom-up +function Pixels.encode8(src, w, h, dst, base, stride, idx) + for y = 0, h - 1 do + local s = y * w * 4 + local d = base + (h - 1 - y) * stride + for x = 0, w - 1 do + writeu8(dst, d + x, idx[band(readu32(src, s + x * 4), 0xFFFFFF)] or 0) + end + end +end + +-- colours(src, n, max) -> the distinct RGB colours in first-appearance order (R | G << 8 | B << 16), whether any +-- alpha is below 255; stops counting at max + 1 colours +function Pixels.colours(src, n, max) +local seen= {} + local list= {} + local alpha = false + for i = 0, n - 1 do + local v = readu32(src, i * 4) + if v < 0xFF000000 then + alpha = true + end + local c = band(v, 0xFFFFFF) + if #list <= max and not seen[c] then + seen[c] = true + list[#list + 1] = c + end + end + return list, alpha +end + +return Pixels +end +__FILES["codecs/image/Quantize"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette +-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel +-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with +-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table +-- iteration order is ever relied on). +-- +-- local pal, exact = Quantize.palette(pixels, w, h, 256, { method = "mediancut" }) -- { {r, g, b, 255} }, boolean +-- local idx = Quantize.map(pixels, w, h, pal, { dither = true, transparentIndex = 255 }) -- buffer of w * h u8 +-- +-- Pixels with alpha < 128 are "transparent": palette() ignores them, map() gives them opts.transparentIndex (0-based) +-- when set (otherwise they map like opaque pixels). When the opaque pixels have at most maxColors distinct colours, +-- palette() returns exactly those (in first-seen order) and exact = true, and map() is then lossless. The octree +-- folds whole nodes, so it may return fewer than maxColors entries; below 8 colours median cut is used instead. +-- Never throws: bad arguments give an empty palette / a zero-filled index buffer. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local floor = math.floor +local blen = buffer.len + +local Quantize = {} + + + + + + + + + + +local BINS = 32768 -- 5 bits per channel + +-- ------------------------------------------------------------------------------------------------ helpers +local function count(pixels, n) -- per bin: u32 count; f64 sums of r, g, b + +local cnt = buffer.create(BINS * 4) + local sums = buffer.create(BINS * 24) + for i = 0, n - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local bin = (math.floor(r / 8)) * 1024 + (math.floor(g / 8)) * 32 + math.floor(b / 8 +) writeu32(cnt, bin * 4, readu32(cnt, bin * 4) + 1) + local s = bin * 24 + writef64(sums, s, readf64(sums, s) + r) + writef64(sums, s + 8, readf64(sums, s + 8) + g) + writef64(sums, s + 16, readf64(sums, s + 16) + b) + end + end + return cnt, sums +end + +local function mean(cnt, sums, bins, lo, hi) +local n, r, g, b = 0, 0, 0, 0 + for i = lo, hi do + local bin = bins[i] + n =n+ readu32(cnt, bin * 4) + r =r+ readf64(sums, bin * 24) + g =g+ readf64(sums, bin * 24 + 8) + b =b+ readf64(sums, bin * 24 + 16) + end + if n == 0 then + return { 0, 0, 0, 255 } + end + return { floor(r / n + 0.5), floor(g / n + 0.5), floor(b / n + 0.5), 255 } +end + +-- ------------------------------------------------------------------------------------------------ median cut +local function medianCut(cnt, sums, maxColors) +local bins= {} + for bin = 0, BINS - 1 do + if readu32(cnt, bin * 4) > 0 then + table.insert(bins, bin) + end + end + if #bins == 0 then + return {} + end + -- boxes: { lo, hi } ranges of the bins array + local boxes= {} + local function channel(bin, c) +if c == 0 then + return math.floor(bin / 1024 +) elseif c == 1 then + return (math.floor(bin / 32)) % 32 + end + return bin % 32 + end + local function stats(box) -- returns the widest channel, its range, the pixel count + +local mins, maxs = { 31, 31, 31 }, { 0, 0, 0 } + local n = 0 + for i = box[1], box[2] do + local bin = bins[i] + n =n+ readu32(cnt, bin * 4) + for c = 0, 2 do + local v = channel(bin, c) + if v < mins[c + 1] then + mins[c + 1] = v + end + if v > maxs[c + 1] then + maxs[c + 1] = v + end + end + end + local best, range = 0, -1 + for c = 0, 2 do + local rg = maxs[c + 1] - mins[c + 1] + if rg > range then + best, range = c, rg + end + end + return best, range, n + end + local function scored(lo, hi) +local c, range, n = stats({ lo, hi }) + return { lo, hi, c, (hi > lo and((range * math.sqrt(n) ))or(0 ))} + end + boxes[1] = scored(1, #bins) + while #boxes < maxColors do + -- split the box with the largest range * sqrt(count) score (ties: the first) + local pick, pickScore = 0, 0 + for i, box in __iter(boxes) do + if box[4] > pickScore then + pick, pickScore = i, box[4] + end + end + if pick == 0 then + break + end + local box = boxes[pick] + local lo, hi, c = box[1], box[2], box[3] + -- sort the range by the channel, ties by bin number: unique numeric keys, no comparator + local keys = (table.create(hi - lo + 1) ) +for i = lo, hi do + keys[i - lo + 1] = channel(bins[i], c) * BINS + bins[i] + end + table.sort(keys) + local total = 0 + for i = 1, #keys do + local bin = keys[i] % BINS + bins[lo + i - 1] = bin + total =total+ readu32(cnt, bin * 4) + end + -- the weighted median, keeping both halves non-empty + local acc, cut = 0, lo + for i = lo, hi - 1 do + acc =acc+ readu32(cnt, bins[i] * 4) + cut = i + if acc * 2 >= total then + break + end + end + boxes[pick] = scored(lo, cut) + table.insert(boxes, scored(cut + 1, hi)) + end + local pal = (table.create(#boxes) ) +for i, box in __iter(boxes) do + pal[i] = mean(cnt, sums, bins, box[1], box[2]) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ octree +-- over the histogram bins: 5 levels (one bit of each channel per level). Nodes are array slots. +local function octree(cnt, sums, maxColors) +local child= {} -- node * 8 + k -> node (0 = none) + local n= {} -- pixel count + local sr, sg, sb= {}, {}, {} + local leaf= {} + local level= {} + local nodes = 1 + n[1], sr[1], sg[1], sb[1], leaf[1], level[1] = 0, 0, 0, 0, false, 0 + for k = 1, 8 do + child[k] = 0 + end + local byLevel= { {}, {}, {}, {}, {} } -- inner nodes per level 0..4, creation order + table.insert(byLevel[1], 1) + local leaves = 0 + for bin = 0, BINS - 1 do + local c = readu32(cnt, bin * 4) + if c > 0 then + local r5, g5, b5 = math.floor(bin / 1024), (math.floor(bin / 32)) % 32, bin % 32 + local node = 1 + for lv = 0, 4 do + local sh = 4 - lv + local k = ((math.floor(r5 / 2 ^ sh)) % 2) * 4 + ((math.floor(g5 / 2 ^ sh)) % 2) * 2 + (math.floor(b5 / 2 ^ sh)) % 2 + local slot = (node - 1) * 8 + k + 1 + local nx = child[slot] + if nx == 0 then + nodes =nodes+ 1 + nx = nodes + child[slot] = nx + for j = 1, 8 do + child[(nx - 1) * 8 + j] = 0 + end + n[nx], sr[nx], sg[nx], sb[nx], level[nx] = 0, 0, 0, 0, lv + 1 + leaf[nx] = lv == 4 + if lv == 4 then + leaves =leaves+ 1 + else + table.insert(byLevel[lv + 2], nx) + end + end + node = nx + end + n[node]=n[node]+ c + sr[node]=sr[node]+ readf64(sums, bin * 24) + sg[node]=sg[node]+ readf64(sums, bin * 24 + 8) + sb[node]=sb[node]+ readf64(sums, bin * 24 + 16) + end + end + -- fold the deepest inner nodes (fewest pixels first, ties by creation order) until few enough leaves remain + local function fold(node) -- merges the children (all leaves) into node; returns how many leaves disappeared + +local merged = 0 + for k = 1, 8 do + local slot = (node - 1) * 8 + k + local ch = child[slot] + if ch ~= 0 then + n[node]=n[node]+ n[ch] + sr[node]=sr[node]+ sr[ch] + sg[node]=sg[node]+ sg[ch] + sb[node]=sb[node]+ sb[ch] + child[slot] = 0 + merged =merged+ 1 + end + end + leaf[node] = true + return merged - 1 + end + local function subtotal(node) +local s = 0 + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + s =s+ n[ch] + end + end + return s + end + for lv = 5, 1, -1 do + if leaves <= maxColors then + break + end + local list = byLevel[lv] + local order = (table.create(#list) ) +for i, node in __iter(list) do + order[i] = { node, subtotal(node), i } + end + table.sort(order, function(a, b) +if a[2] ~= b[2] then + return a[2] < b[2] + end + return a[3] < b[3] + end) + for _, e in __iter(order) do + if leaves <= maxColors then + break + end + leaves =leaves- fold(e[1]) + end + end + -- collect leaves depth first in child order + local pal= {} + local function walk(node) + if leaf[node] then + local c = n[node] + if c > 0 then + table.insert(pal, { floor(sr[node] / c + 0.5), floor(sg[node] / c + 0.5), floor(sb[node] / c + 0.5), 255 }) + end + return + end + for k = 1, 8 do + local ch = child[(node - 1) * 8 + k] + if ch ~= 0 then + walk(ch) + end + end + end + walk(1) + -- the root itself can end up a leaf with everything (maxColors 1) + while #pal > maxColors do + table.remove(pal) + end + return pal +end + +-- ------------------------------------------------------------------------------------------------ palette +-- palette(pixels, w, h, maxColors, opts?) -> palette, exact +function Quantize.palette(pixels, w, h, maxColors, opts) +if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 then + return {}, false + end + local maxc = math.clamp(floor(tonumber(maxColors) or 256), 1, 65536) + local npx = w * h + -- exact colours, in first-seen order (stops counting past maxColors) + local seen= {} + local exact= {} + local over = false + for i = 0, npx - 1 do + local o = i * 4 + if readu8(pixels, o + 3) >= 128 then + local r, g, b = readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2) + local key = r * 65536 + g * 256 + b + if not seen[key] then + if #exact >= maxc then + over = true + break + end + seen[key] = true + table.insert(exact, { r, g, b, 255 }) + end + end + end + if not over then + return exact, true + end + local cnt, sums = count(pixels, npx) + local method = opts and opts.method or "mediancut" + if method == "octree" and maxc >= 8 then -- below 8 the octree can only fold to a single colour + return octree(cnt, sums, maxc), false + end + return medianCut(cnt, sums, maxc), false +end + +-- ------------------------------------------------------------------------------------------------ map +-- map(pixels, w, h, palette, opts?) -> buffer of w * h palette indexes (0-based) +function Quantize.map(pixels, w, h, palette, opts) +if type(pixels) ~= "buffer" or type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or blen(pixels) < w * h * 4 or type(palette) ~= "table" then + return buffer.create(0) + end + local npx = w * h + local out = buffer.create(npx) + local dither = opts and opts.dither or false + local tidx = opts and opts.transparentIndex + -- the searchable entries (the transparent slot is excluded) + local pr, pg, pb, pi= {}, {}, {}, {} + for i, c in __iter(palette) do + if tidx == nil or i - 1 ~= tidx then + table.insert(pr, c[1] or 0) + table.insert(pg, c[2] or 0) + table.insert(pb, c[3] or 0) + table.insert(pi, i - 1) + end + end + local np = #pr + -- sorted by green (the heaviest weight), so the search can stop once 4 * dg^2 alone is worse than the best + do + local order = (table.create(np) ) +for k = 1, np do + order[k] = pg[k] * 65536 + k + end + table.sort(order) + local r2, g2, b2, i2 = (table.create(np) ), (table.create(np) ), (table.create(np) ), (table.create(np) ) +for k = 1, np do + local j = order[k] % 65536 + r2[k], g2[k], b2[k], i2[k] = pr[j], pg[j], pb[j], pi[j] + end + pr, pg, pb, pi = r2, g2, b2, i2 + end + local startAt = table.create(256, np) -- the first entry with green >= g (1-based), np + 1 past the end + do + local k = 1 + for g = 0, 255 do + while k <= np and pg[k] < g do + k =k+ 1 + end + startAt[g + 1] = k + end + end + if np == 0 then + if tidx then + buffer.fill(out, 0, math.clamp(tidx, 0, 255), npx) + end + return out + end + local cache= {} + local function nearest(r, g, b) +local key = r * 65536 + g * 256 + b + local hit = cache[key] + if hit then + return hit + end + local best, bd = 1, math.huge + local up = startAt[math.clamp(g, 0, 255) + 1] + local down = up - 1 + while up <= np or down >= 1 do + if up <= np then + local dg = pg[up] - g + if dg * dg * 4 >= bd then + up = np + 1 + else + local dr, db = r - pr[up], b - pb[up] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = up, d + end + up =up+ 1 + end + end + if down >= 1 then + local dg = g - pg[down] + if dg * dg * 4 >= bd then + down = 0 + else + local dr, db = r - pr[down], b - pb[down] + local d = dr * dr * 2 + dg * dg * 4 + db * db * 3 + if d < bd then + best, bd = down, d + end + down =down- 1 + end + end + end + cache[key] = best + return best + end + local tbyte = (tidx and{(math.clamp(tidx, 0, 255) )}or{0 +})[1] if not dither then + for i = 0, npx - 1 do + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + writeu8(out, i, pi[nearest(readu8(pixels, o), readu8(pixels, o + 1), readu8(pixels, o + 2))]) + end + end + return out + end + -- Floyd-Steinberg: error rows (f64 r, g, b per pixel, one extra pixel each side) + local rowLen = (w + 2) * 24 + local cur, nxt = buffer.create(rowLen), buffer.create(rowLen) + for y = 0, h - 1 do + buffer.fill(nxt, 0, 0, rowLen) + for x = 0, w - 1 do + local i = y * w + x + local o = i * 4 + if tidx and readu8(pixels, o + 3) < 128 then + writeu8(out, i, tbyte) + else + local e = (x + 1) * 24 + local r = math.clamp(floor(readu8(pixels, o) + readf64(cur, e) + 0.5), 0, 255) + local g = math.clamp(floor(readu8(pixels, o + 1) + readf64(cur, e + 8) + 0.5), 0, 255) + local b = math.clamp(floor(readu8(pixels, o + 2) + readf64(cur, e + 16) + 0.5), 0, 255) + local k = nearest(r, g, b) + writeu8(out, i, pi[k]) + local er, eg, eb = r - pr[k], g - pg[k], b - pb[k] + -- 7/16 right, 3/16 down-left, 5/16 down, 1/16 down-right + writef64(cur, e + 24, readf64(cur, e + 24) + er * 0.4375) + writef64(cur, e + 32, readf64(cur, e + 32) + eg * 0.4375) + writef64(cur, e + 40, readf64(cur, e + 40) + eb * 0.4375) + writef64(nxt, e - 24, readf64(nxt, e - 24) + er * 0.1875) + writef64(nxt, e - 16, readf64(nxt, e - 16) + eg * 0.1875) + writef64(nxt, e - 8, readf64(nxt, e - 8) + eb * 0.1875) + writef64(nxt, e, readf64(nxt, e) + er * 0.3125) + writef64(nxt, e + 8, readf64(nxt, e + 8) + eg * 0.3125) + writef64(nxt, e + 16, readf64(nxt, e + 16) + eb * 0.3125) + writef64(nxt, e + 24, readf64(nxt, e + 24) + er * 0.0625) + writef64(nxt, e + 32, readf64(nxt, e + 32) + eg * 0.0625) + writef64(nxt, e + 40, readf64(nxt, e + 40) + eb * 0.0625) + end + end + cur, nxt = nxt, cur + end + return out +end + +-- quantize(pixels, w, h, maxColors, opts?) -> indexes, palette, exact: palette() then map() (opts of both) +function Quantize.quantize(pixels, w, h, maxColors, opts) +local pal, exact = Quantize.palette(pixels, w, h, maxColors, opts) + local mo = opts + if exact and opts and opts.dither then + mo = table.clone(opts) + mo.dither = false -- nothing to diffuse + end + return Quantize.map(pixels, w, h, pal, mo), pal, exact +end + +return Quantize +end +__FILES["codecs/image/Raster"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine +-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and +-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 / +-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an +-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed +-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2. +-- +-- local R = require("rosetta.codecs.image.Raster") +-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list: +-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 }, +-- { op = "close" } } -- (the Font:outline() format) +-- local m = R.mask(cmds, { transform = { 2, 0, 0, 2, 5, 5 }, rule = "evenodd", clip = { 0, 0, 64, 64 } }) +-- -- m = { x, y, width, height, coverage: buffer (u8, width * height) } in device pixels, or nil when empty +-- R.fill(img, cmds, { 255, 0, 0, 255 }, { transform = t }) -- composite onto an rgba8 Image (source over) +-- R.fill(img, cmds, function(x, y) return r, g, b, a end) -- a paint function per covered pixel (gradients) +-- local outline = R.stroke(cmds, { width = 2, join = "round", cap = "butt" }) -- a path to fill (nonzero) +-- +-- Transforms are { a, b, c, d, e, f } (SVG matrix order): x' = a x + c y + e, y' = b x + d y + f. Coordinates are +-- pixels with y down; a pixel (i, j) covers [i, i+1) x [j, j+1). Curves are flattened in device space to +-- opts.tolerance (default 0.1 px). Subpaths are implicitly closed for filling. +-- +-- Never throws: malformed commands (missing or non-number operands) are skipped, non-finite coordinates drop the +-- edge, sizes are bounded by opts.maxPixels (default 2^26), so it is safe for native code and untrusted paths. +local Raster = {} + +local floor, ceil, min, max, abs, sqrt = math.floor, math.ceil, math.min, math.max, math.abs, math.sqrt +local readf32, writef32, readu8, writeu8 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8 +local bcreate = buffer.create + + + + + + + + + + + + + + +local LIMIT = 1e7 -- coordinates beyond this (device pixels) are treated as broken + +-- ------------------------------------------------------------------------------------------------ transforms +Raster.IDENTITY = table.freeze({ 1, 0, 0, 1, 0, 0 }) + +-- multiply(m, n) -> m * n (apply n first, then m) +function Raster.multiply(m, n) +return { + m[1] * n[1] + m[3] * n[2], + m[2] * n[1] + m[4] * n[2], + m[1] * n[3] + m[3] * n[4], + m[2] * n[3] + m[4] * n[4], + m[1] * n[5] + m[3] * n[6] + m[5], + m[2] * n[5] + m[4] * n[6] + m[6], + } +end +function Raster.translate(tx, ty) +return { 1, 0, 0, 1, tx, ty } +end +function Raster.scale(sx, sy) +return { sx, 0, 0, sy or sx, 0, 0 } +end +function Raster.rotate(radians) +local c, s = math.cos(radians), math.sin(radians) + return { c, s, -s, c, 0, 0 } +end +-- invert(m) -> m^-1 | nil (singular) +function Raster.invert(m) +local det = m[1] * m[4] - m[2] * m[3] + if det == 0 or det ~= det then + return nil + end + local id = 1 / det + local a, b, c, d = m[4] * id, -m[2] * id, -m[3] * id, m[1] * id + return { a, b, c, d, -(a * m[5] + c * m[6]), -(b * m[5] + d * m[6]) } +end +-- apply(m, x, y) -> x', y' +function Raster.apply(m, x, y) +return m[1] * x + m[3] * y + m[5], m[2] * x + m[4] * y + m[6] +end + +-- ------------------------------------------------------------------------------------------------ path builder +local Builder = {} +Builder.__index = Builder + +-- path() -> a Builder; every method returns the builder; builder.cmds is the command list (any API taking a path +-- takes a builder too) + +function Raster.path() +return setmetatable({ cmds = {} }, Builder) +end +function Builder.moveTo(self, x, y) +table.insert(self.cmds, { op = "moveTo", x, y }) + return self +end +function Builder.lineTo(self, x, y) +table.insert(self.cmds, { op = "lineTo", x, y }) + return self +end +function Builder.quadTo(self, cx, cy, x, y) +table.insert(self.cmds, { op = "quadTo", cx, cy, x, y }) + return self +end +function Builder.cubicTo(self, c1x, c1y, c2x, c2y, x, y) +table.insert(self.cmds, { op = "cubicTo", c1x, c1y, c2x, c2y, x, y }) + return self +end +function Builder.close(self) +table.insert(self.cmds, { op = "close" } ) + return self +end +-- rect(x, y, w, h), ellipse(cx, cy, rx, ry): closed subpaths +function Builder.rect(self, x, y, w, h) +return self:moveTo(x, y):lineTo(x + w, y):lineTo(x + w, y + h):lineTo(x, y + h):close() +end +function Builder.ellipse(self, cx, cy, rx, ry) +local k = 0.5522847498307936 -- 4/3 (sqrt 2 - 1): cubic quarter circle + self:moveTo(cx + rx, cy) + self:cubicTo(cx + rx, cy + ry * k, cx + rx * k, cy + ry, cx, cy + ry) + self:cubicTo(cx - rx * k, cy + ry, cx - rx, cy + ry * k, cx - rx, cy) + self:cubicTo(cx - rx, cy - ry * k, cx - rx * k, cy - ry, cx, cy - ry) + self:cubicTo(cx + rx * k, cy - ry, cx + rx, cy - ry * k, cx + rx, cy) + return self:close() +end + +local function commands(path) +if type(path) ~= "table" then + return nil + end + if type(path.cmds) == "table" then + return path.cmds + end + return path +end + +-- n numeric operands of a command, or nil +local function operands(c, n) +if type(c) ~= "table" then + return false + end + for i = 1, n do + local v = c[i] + if type(v) ~= "number" or v ~= v or abs(v) > 1e15 then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ flattening +-- flatten(path, transform?, tolerance?) -> polylines: { { x1, y1, x2, y2, ... } } in device space, one per subpath +-- (closed implicitly; the closing point is not repeated), and the bounds x0, y0, x1, y1 (nil when empty) +local function flatten(path, transform, tolerance, minLen) +local cmds = commands(path) + local polys= {} + if not cmds then + return polys, nil, nil, nil, nil + end + local m = transform or Raster.IDENTITY + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + if type(a) ~= "number" or type(b) ~= "number" or type(c) ~= "number" or type(d) ~= "number" or type(e) ~= "number" or type(f) ~= "number" then + return polys, nil, nil, nil, nil + end + local tol = tolerance or 0.1 + if type(tol) ~= "number" or not (tol > 0.001) then + tol = 0.1 + end + local cur= nil + local px, py = 0, 0 -- current point (device) + local sx, sy = 0, 0 -- subpath start (device) + local bx0, by0, bx1, by1 = math.huge, math.huge, -math.huge, -math.huge + local function point(x, y) + local poly = cur +local n = #poly + poly[n + 1] = x + poly[n + 2] = y + if x < bx0 then + bx0 = x + end + if x > bx1 then + bx1 = x + end + if y < by0 then + by0 = y + end + if y > by1 then + by1 = y + end + end + local function start(x, y) + if cur and #cur >= minLen then + table.insert(polys, cur) + end + cur = {} + point(x, y) + sx, sy = x, y + px, py = x, y + end + for _, cmd in __iter(cmds) do + local op = (type(cmd) == "table" and{cmd.op }or{nil +})[1] if op == "moveTo" then + if operands(cmd, 2) then + start(a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f) + end + elseif op == "lineTo" then + if operands(cmd, 2) then + if not cur then + start(px, py) + end + px, py = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + point(px, py) + end + elseif op == "quadTo" then + if operands(cmd, 4) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local ddx, ddy = px - 2 * x1 + x2, py - 2 * y1 + y2 + local n = ceil(sqrt(sqrt(ddx * ddx + ddy * ddy) * 0.25 / tol)) + n = n ~= n and 1 or max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + point(u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2) + end + point(x2, y2) + px, py = x2, y2 + end + elseif op == "cubicTo" then + if operands(cmd, 6) then + if not cur then + start(px, py) + end + local x1, y1 = a * cmd[1] + c * cmd[2] + e, b * cmd[1] + d * cmd[2] + f + local x2, y2 = a * cmd[3] + c * cmd[4] + e, b * cmd[3] + d * cmd[4] + f + local x3, y3 = a * cmd[5] + c * cmd[6] + e, b * cmd[5] + d * cmd[6] + f + local ax, ay = px - 2 * x1 + x2, py - 2 * y1 + y2 + local bxx, byy = x1 - 2 * x2 + x3, y1 - 2 * y2 + y3 + local dd = max(sqrt(ax * ax + ay * ay), sqrt(bxx * bxx + byy * byy)) + local n = ceil(sqrt(dd * 0.75 / tol)) + n = n ~= n and 1 or max(1, min(n, 500)) + local x0, y0 = px, py + for i = 1, n - 1 do + local t = i / n + local u = 1 - t + local w0, w1, w2, w3 = u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t + point(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3, w0 * y0 + w1 * y1 + w2 * y2 + w3 * y3) + end + point(x3, y3) + px, py = x3, y3 + end + elseif op == "close" then + if cur then + if #cur >= minLen then + table.insert(polys, cur) + end + cur = nil + px, py = sx, sy + end + end + end + if cur and #cur >= minLen then + table.insert(polys, cur) + end + if #polys == 0 or bx0 ~= bx0 or by0 ~= by0 or bx1 ~= bx1 or by1 ~= by1 then + return polys, nil, nil, nil, nil + end + return polys, bx0, by0, bx1, by1 +end + +function Raster.flatten(path, transform, tolerance) +return flatten(path, transform, tolerance, 6) +end + +-- ------------------------------------------------------------------------------------------------ accumulation +-- one edge (x0, y0) -> (x1, y1), already inside [0, W] horizontally, into acc (stride S, H rows): the signed area +-- each pixel gains (font-rs's draw_line) +local function line(acc, S, H, x0, y0, x1, y1) + if y0 == y1 then + return + end + local W = S - 2 + local xl, xr = 0, W -- x stays in [0, W] (rounding in the splits and in x + dxdy * dy must never index outside) + local dir = 1 + if y0 > y1 then + dir = -1 + x0, x1 = x1, x0 + y0, y1 = y1, y0 + end + if y1 <= 0 or y0 >= H then + return + end + local dxdy = (x1 - x0) / (y1 - y0) + local x = x0 + if y0 < 0 then + x =x- y0 * dxdy + end + local ystart = max(0, floor(y0)) + local yend = min(H, ceil(y1)) - 1 + for y = ystart, yend do + local ls = y * S + local dy = min(y + 1, y1) - max(y, y0) + local xnext = x + dxdy * dy + if xnext < xl then + xnext = xl + elseif xnext > xr then + xnext = xr + end + if x < xl then + x = xl + elseif x > xr then + x = xr + end + local dd = dy * dir + local xa, xb = x, xnext + if xa > xb then + xa, xb = xb, xa + end + local xaf = floor(xa) + local xai = xaf + local xbc = ceil(xb) + local xbi = xbc + if xbi <= xai + 1 then + local xmf = 0.5 * (x + xnext) - xaf + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd - dd * xmf) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * xmf) + else + local s = 1 / (xb - xa) + local x0f = xa - xaf + local a0 = 0.5 * s * (1 - x0f) * (1 - x0f) + local x1f = xb - xbc + 1 + local am = 0.5 * s * x1f * x1f + local o = (ls + xai) * 4 + writef32(acc, o, readf32(acc, o) + dd * a0) + if xbi == xai + 2 then + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (1 - a0 - am)) + else + local a1 = s * (1.5 - x0f) + writef32(acc, o + 4, readf32(acc, o + 4) + dd * (a1 - a0)) + local ds = dd * s + for xi = xai + 2, xbi - 2 do + local q = (ls + xi) * 4 + writef32(acc, q, readf32(acc, q) + ds) + end + local a2 = a1 + (xbi - xai - 3) * s + local q = (ls + xbi - 1) * 4 + writef32(acc, q, readf32(acc, q) + dd * (1 - a2 - am)) + end + local q = (ls + xbi) * 4 + writef32(acc, q, readf32(acc, q) + dd * am) + end + x = xnext + end +end + +-- an edge in mask coordinates, split where it crosses x = 0 and x = W (in its own order: the direction is the +-- winding sign); the parts outside are pushed onto the border (their area lies outside the mask, their cover still +-- applies to the row) +local function clampx(x, W) +return x < 0 and 0 or(x > W and{W }or{x +})[1]end +local function edge(acc, S, W, H, x0, y0, x1, y1) + if y0 == y1 or not (abs(x0) < LIMIT and abs(y0) < LIMIT and abs(x1) < LIMIT and abs(y1) < LIMIT) then + return -- horizontal, or non-finite (NaN fails every comparison) + end + if (y0 <= 0 and y1 <= 0) or (y0 >= H and y1 >= H) then + return + end + local dx = x1 - x0 + local ta, tb = 2, 2 -- parameters of the crossings with x = 0 and x = W (2 = none) + if dx ~= 0 then + local t0 = (0 - x0) / dx + local tw = (W - x0) / dx + if t0 > 0 and t0 < 1 then + ta = t0 + end + if tw > 0 and tw < 1 then + tb = tw + end + if ta > tb then + ta, tb = tb, ta + end + end + local dy = y1 - y0 + local px, py = x0, y0 + if ta < 1 then + local qx, qy = x0 + dx * ta, y0 + dy * ta + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + if tb < 1 then + local qx, qy = x0 + dx * tb, y0 + dy * tb + line(acc, S, H, clampx(px, W), py, clampx(qx, W), qy) + px, py = qx, qy + end + line(acc, S, H, clampx(px, W), py, clampx(x1, W), y1) +end + +-- ------------------------------------------------------------------------------------------------ masks +-- mask(path, opts?) -> Mask | nil (empty, or over the size limit: then the second result is "limit") +function Raster.mask(path, opts) +local o= opts or {} + local polys, bx0, by0, bx1, by1 = Raster.flatten(path, o.transform, o.tolerance) + if not bx0 then + return nil, nil + end + if abs(bx0 ) > LIMIT or abs(by0 ) > LIMIT or abs(bx1 ) > LIMIT or abs(by1 ) > LIMIT then + return nil, "coordinates out of range" + end + local X0, Y0, X1, Y1 = floor(bx0 ), floor(by0 ), ceil(bx1 ), ceil(by1 ) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + Y0 = max(Y0, floor(clip[2])) + Y1 = min(Y1, ceil(clip[4])) + X1 = min(X1, ceil(clip[3])) + local cx0 = floor(clip[1]) + X0 = max(X0, cx0) + end + local W, H = X1 - X0, Y1 - Y0 + if W <= 0 or H <= 0 then + return nil, nil + end + local maxPixels = (type(o.maxPixels) == "number" and{o.maxPixels }or{(2 ^ 26 +)})[1] if W * H > maxPixels then + return nil, "limit" + end + local S = W + 2 + local acc = bcreate(S * H * 4) + for _, poly in __iter(polys) do + local n = #poly + local lx, ly = poly[n - 1] - X0, poly[n] - Y0 + for i = 1, n - 1, 2 do + local x, y = poly[i] - X0, poly[i + 1] - Y0 + edge(acc, S, W, H, lx, ly, x, y) + lx, ly = x, y + end + end + local cov = bcreate(W * H) + local evenodd = o.rule == "evenodd" + for y = 0, H - 1 do + local sum = 0 + local ls = y * S + local os = y * W + for x = 0, W - 1 do + sum =sum+ readf32(acc, (ls + x) * 4) + local v = abs(sum) + if evenodd then + v = v % 2 + if v > 1 then + v = 2 - v + end + elseif v > 1 then + v = 1 + end + writeu8(cov, os + x, floor(v * 255 + 0.5)) + end + end + return { x = X0, y = Y0, width = W, height = H, coverage = cov }, nil +end + +-- ------------------------------------------------------------------------------------------------ filling +-- fill(img, path, paint, opts?) -> true | false, message. img: an rgba8 Image ({ width, height, pixels }); paint: an +-- { r, g, b, a } colour (0..255) or a function(x, y) -> r, g, b, a called per covered pixel (pixel centres in +-- device space: x + 0.5, y + 0.5). Composites source-over onto the straight-alpha pixels. opts.clip defaults to the +-- image; opts.opacity scales the coverage. +function Raster.fill(img, path, paint, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return false, "fill: expected an rgba8 image" + end + local iw, ih = img.width, img.height + local px = img.pixels + if buffer.len(px) < iw * ih * 4 then + return false, "fill: image pixels too short" + end + local o= table.clone(opts or {} ) + local clip = o.clip + if type(clip) == "table" and type(clip[1]) == "number" and type(clip[2]) == "number" and type(clip[3]) == "number" and type(clip[4]) == "number" then + o.clip = { max(0, clip[1]), max(0, clip[2]), min(iw, clip[3]), min(ih, clip[4]) } + else + o.clip = { 0, 0, iw, ih } + end + local m, why = Raster.mask(path, o) + if not m then + return why == nil, why + end + local opacity = (type(o.opacity) == "number" and{(math.clamp(o.opacity, 0, 1) )}or{1 +})[1] local fn= nil + local cr, cg, cb, ca = 0, 0, 0, 255 + if type(paint) == "function" then + fn = paint + elseif type(paint) == "table" then + cr, cg, cb = tonumber(paint[1]) or 0, tonumber(paint[2]) or 0, tonumber(paint[3]) or 0 + ca = tonumber(paint[4]) or 255 + else + return false, "fill: paint must be a colour or a function" + end + local cov = m.coverage + local mw = m.width + for y = 0, m.height - 1 do + local iy = m.y + y + for x = 0, mw - 1 do + local cv = readu8(cov, y * mw + x) + if cv > 0 then + local ix = m.x + x + local r, g, b, a = cr, cg, cb, ca + if fn then + local ok, r2, g2, b2, a2 = pcall(fn, ix + 0.5, iy + 0.5) + if not ok then + return false, "fill: paint function failed" + end + r, g, b, a = tonumber(r2) or 0, tonumber(g2) or 0, tonumber(b2) or 0, tonumber(a2) or 255 + end + local sa = math.clamp(a, 0, 255) / 255 * cv / 255 * opacity + if sa > 0 then + local p = (iy * iw + ix) * 4 + local da = readu8(px, p + 3) / 255 + local oa = sa + da * (1 - sa) + local k = da * (1 - sa) + writeu8(px, p, floor((math.clamp(r, 0, 255) * sa + readu8(px, p) * k) / oa + 0.5)) + writeu8(px, p + 1, floor((math.clamp(g, 0, 255) * sa + readu8(px, p + 1) * k) / oa + 0.5)) + writeu8(px, p + 2, floor((math.clamp(b, 0, 255) * sa + readu8(px, p + 2) * k) / oa + 0.5)) + writeu8(px, p + 3, floor(oa * 255 + 0.5)) + end + end + end + end + return true, nil +end +-- ------------------------------------------------------------------------------------------------ stroking +-- push a polygon (flat x, y list) as a closed subpath with positive orientation, so overlapping pieces add up +-- under the nonzero rule + + + + + + + + + + +local function polygon(out, pts) + local n = #pts + if n < 6 then + return + end + local area = 0 + for i = 1, n - 1, 2 do + local j = i + 2 > n and 1 or i + 2 + area =area+ (pts[i] * pts[j + 1] - pts[j] * pts[i + 1] +) end + if area == 0 then + return + end + if area > 0 then + table.insert(out, { op = "moveTo", pts[1], pts[2] }) + for i = 3, n - 1, 2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + else + table.insert(out, { op = "moveTo", pts[n - 1], pts[n] }) + for i = n - 3, 1, -2 do + table.insert(out, { op = "lineTo", pts[i], pts[i + 1] }) + end + end + table.insert(out, { op = "close" } ) +end + +local function arcPoints(cx, cy, r, a0, a1, tol, pts) + local da = a1 - a0 + local step = 2 * math.acos(math.clamp(1 - tol / max(r, 1e-9), -1, 1)) + local n = max(1, min(256, ceil(abs(da) / max(step, 0.01)))) + for i = 0, n do + local t = a0 + da * i / n + table.insert(pts, cx + r * math.cos(t)) + table.insert(pts, cy + r * math.sin(t)) + end +end + +-- stroke(path, opts?) -> Path: the outline of the stroke as pieces to fill with the nonzero rule (in the path's own +-- coordinate space: transform it like the path). Dashes are the caller's job (split the path first). +function Raster.stroke(path, opts) +local o= opts or {} + local hw = ((type(o.width) == "number" and o.width > 0 and{o.width }or{1})[1]) / 2 + local join = o.join or "miter" + local cap = o.cap or "butt" + local miterLimit = (type(o.miterLimit) == "number" and o.miterLimit >= 1 and{o.miterLimit }or{4 +})[1] local tol = (type(o.tolerance) == "number" and o.tolerance > 0.0005 and{o.tolerance }or{0.1 +})[1] local out= {} + local cmds = commands(path) + if not cmds then + return out + end + -- subpaths with their closed flag (flatten loses it, so split here) + local subs= {} + local cur= nil + local lx, ly = 0, 0 + for _, c in __iter(cmds) do + local op = (type(c) == "table" and{c.op }or{nil +})[1] if op == "moveTo" and operands(c, 2) then + cur = { c } + table.insert(subs, { cmds = cur , closed = o.closed == true }) + lx, ly = c[1], c[2] + elseif op == "close" then + if cur then + subs[#subs].closed = true + cur = nil + end + elseif op == "lineTo" or op == "quadTo" or op == "cubicTo" then + if not cur then + cur = { { op = "moveTo", lx, ly } } + table.insert(subs, { cmds = cur , closed = o.closed == true }) + end + table.insert(cur , c) + end + end + for _, sub in __iter(subs) do +local __DARKLUA_CONTINUE_18=false repeat local polys = flatten(sub.cmds, nil, tol, 4) + local pts = polys[1] + if not pts then + -- a degenerate subpath (a single point): round / square caps draw a dot + local m = sub.cmds[1] + if #sub.cmds >= 1 and operands(m, 2) and cap ~= "butt" then + local d = {} + if cap == "round" then + arcPoints(m[1], m[2], hw, 0, 2 * math.pi, tol, d) + else + d = { m[1] - hw, m[2] - hw, m[1] + hw, m[2] - hw, m[1] + hw, m[2] + hw, m[1] - hw, m[2] + hw } + end + polygon(out, d) + end +__DARKLUA_CONTINUE_18=true break + end + -- drop repeated points + local p= { pts[1], pts[2] } + for i = 3, #pts - 1, 2 do + if abs(pts[i] - p[#p - 1]) > 1e-9 or abs(pts[i + 1] - p[#p]) > 1e-9 then + table.insert(p, pts[i]) + table.insert(p, pts[i + 1]) + end + end + local closed = sub.closed + if closed and #p >= 4 and abs(p[1] - p[#p - 1]) < 1e-9 and abs(p[2] - p[#p]) < 1e-9 then + table.remove(p) + table.remove(p) + end + local n = math.floor(#p / 2 +) if n < 2 then +__DARKLUA_CONTINUE_18=true break + end + local segs = (closed and{n }or{(n - 1 +)})[1] -- segment bodies + local dirs= {} + for s = 0, segs - 1 do + local i, j = s, (s + 1) % n + local x0, y0, x1, y1 = p[2 * i + 1], p[2 * i + 2], p[2 * j + 1], p[2 * j + 2] + local dx, dy = x1 - x0, y1 - y0 + local len = sqrt(dx * dx + dy * dy) + local ux, uy = dx / len, dy / len + dirs[2 * s + 1], dirs[2 * s + 2] = ux, uy + local nx, ny = -uy * hw, ux * hw + polygon(out, { x0 + nx, y0 + ny, x1 + nx, y1 + ny, x1 - nx, y1 - ny, x0 - nx, y0 - ny }) + end + -- joins + local function joinAt(k, s0, s1) + local x, y = p[2 * k + 1], p[2 * k + 2] + local ax, ay = dirs[2 * s0 + 1], dirs[2 * s0 + 2] + local bx, by = dirs[2 * s1 + 1], dirs[2 * s1 + 2] + local cross = ax * by - ay * bx + if abs(cross) < 1e-12 and ax * bx + ay * by > 0 then + return + end + -- the outer side: left normals when turning right (cross < 0) + local sgn = cross < 0 and 1 or-1 + local n0x, n0y = -ay * hw * sgn, ax * hw * sgn + local n1x, n1y = -by * hw * sgn, bx * hw * sgn + if join == "round" then + local d = { x, y } + local a0 = math.atan2(n0y, n0x) + local a1 = math.atan2(n1y, n1x) + local da = a1 - a0 + while da > math.pi do + da =da- 2 * math.pi + end + while da < -math.pi do + da =da+ 2 * math.pi + end + arcPoints(x, y, hw, a0, a0 + da, tol, d) + polygon(out, d) + else + local cosT = ax * bx + ay * by -- angle between directions + local miter = (join == "miter" and{(1 / sqrt(max(1e-12, (1 + cosT) / 2)) )}or{math.huge +})[1] if join == "miter" and miter <= miterLimit then + local mx, my = n0x + n1x, n0y + n1y + local ml = sqrt(mx * mx + my * my) + if ml > 1e-12 then + local scale = hw * miter / ml + polygon(out, { x, y, x + n0x, y + n0y, x + mx * scale, y + my * scale, x + n1x, y + n1y }) + return + end + end + polygon(out, { x, y, x + n0x, y + n0y, x + n1x, y + n1y }) + end + end + if closed then + for k = 0, n - 1 do + joinAt(k, (k - 1) % n, k) + end + else + for k = 1, n - 2 do + joinAt(k, k - 1, k) + end + -- caps + if cap ~= "butt" then + for _, endInfo in __iter({ { 0, 0, -1 }, { n - 1, segs - 1, 1 } }) do + local k, s, sgn = endInfo[1], endInfo[2], endInfo[3] + local x, y = p[2 * k + 1], p[2 * k + 2] + local ux, uy = dirs[2 * s + 1] * sgn, dirs[2 * s + 2] * sgn -- pointing outwards + local nx, ny = -uy * hw, ux * hw + if cap == "square" then + polygon(out, { x + nx, y + ny, x + nx + ux * hw, y + ny + uy * hw, x - nx + ux * hw, y - ny + uy * hw, x - nx, y - ny }) + else + local d = {} + local a0 = math.atan2(ny, nx) + arcPoints(x, y, hw, a0, a0 - math.pi, tol, d) + polygon(out, d) + end + end + end + end +__DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end + return out +end + +return Raster +end +__FILES["codecs/image/Texel"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers +-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in rosetta. Formats are named +-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, +-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: +-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other +-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. +-- +-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels +-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) +-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode +-- +-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. +-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped +-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 +-- (snorm -> -1..1, integers as their values). +local Half = __include("codecs/image/Half") + +local Texel = {} + + + + + + + + + + + +local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 +local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ formats +local FORMATS= {} +local function array(name, size, typ, order) + FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } +end +for _, o in __iter({ "r", "rg", "rgb", "rgba" }) do + array(o .. "8", 1, "unorm", o) + array(o .. "8s", 1, "snorm", o) + array(o .. "8ui", 1, "uint", o) + array(o .. "8i", 1, "sint", o) + array(o .. "16", 2, "unorm", o) + array(o .. "16s", 2, "snorm", o) + array(o .. "16ui", 2, "uint", o) + array(o .. "16i", 2, "sint", o) + array(o .. "16f", 2, "float", o) + array(o .. "32ui", 4, "uint", o) + array(o .. "32i", 4, "sint", o) + array(o .. "32f", 4, "float", o) +end +array("bgr8", 1, "unorm", "bgr") +array("bgra8", 1, "unorm", "bgra") +array("bgrx8", 1, "unorm", "bgrx") +array("rgbx8", 1, "unorm", "rgbx") +array("a8", 1, "unorm", "a") +array("l8", 1, "unorm", "l") +array("la8", 1, "unorm", "la") +array("l16", 2, "unorm", "l") +array("la16", 2, "unorm", "la") +array("a16", 2, "unorm", "a") + +local function packed(name, bytes, spec) + local ch= {} + for i = 1, #spec, 3 do + table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) + end + FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch } +end +packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 }) +packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 }) +packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 }) +packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 }) +packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 }) +packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 }) +packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 }) +packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 }) +packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 }) +packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 }) +packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 }) +packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 }) +packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 }) +FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" } +FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" } +-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range +FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" } +FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" } +FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" } +FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } +FORMATS.ayuv = { bytes = 4, kind = "ayuv" } +Texel.FORMATS = FORMATS + +-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: +-- the r mask is a luminance channel +function Texel.masked(bytes, r, g, b, a, luminance) +if bytes < 1 or bytes > 4 then + return nil + end + local ch= {} + for i, m in __iter({ r, g, b, a }) do + if m ~= 0 then + local shift = 0 + while band(m, lshift(1, shift)) == 0 and shift < 31 do + shift =shift+ 1 + end + local bits = 0 + while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do + bits =bits+ 1 + end + local name = (i == 1 and{(luminance and"l" or"r") }or{i == 2 and"g" or(i == 3 and"b" or"a" +)})[1] table.insert(ch, { c = name, shift = shift, bits = bits }) + end + end + if #ch == 0 then + return nil + end + return { bytes = bytes, kind = "packed", channels = ch } +end + +-- size(fmt, w, h) -> bytes (rows tightly packed) | nil +function Texel.size(fmt, w, h) +local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt +})[1] if not d then + return nil + end + return (d.kind == "pair" and(((math.floor((w + 1) / 2)) * 4 * h ))or((d.bytes * w * h +)))end + +-- ------------------------------------------------------------------------------------------------ helpers +-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 +local function nativeOf(d) +if d.kind == "array" then + local t, s = d.type, d.size +if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then + return "rgbaf32" + end + return s == 1 and"rgba8" or"rgba16" + elseif d.kind == "packed" then + local wide = false + for _, c in __iter(d.channels) do + wide = wide or c.bits > 8 + end + return wide and"rgba16" or"rgba8" + end + return "rgbaf32" +end +Texel.nativeOf = nativeOf + +local function uf11(v) +local e, m = rshift(v, 6), band(v, 63) + if e == 0 then + return m / 64 * 2 ^ -14 + elseif e == 31 then + return (m == 0 and{math.huge }or{(0 / 0 +)})[1] end + return (1 + m / 64) * 2 ^ (e - 15) +end +local function uf10(v) +local e, m = rshift(v, 5), band(v, 31) + if e == 0 then + return m / 32 * 2 ^ -14 + elseif e == 31 then + return (m == 0 and{math.huge }or{(0 / 0 +)})[1] end + return (1 + m / 32) * 2 ^ (e - 15) +end + +-- one component at q of an array format -> a float (native meaning) and its rgba8 byte +local function component(src, q, size, typ) +if typ == "unorm" then + if size == 1 then + local v = readu8(src, q) + return v / 255, v + elseif size == 2 then + local v = readu16(src, q) + return v / 65535, math.floor((v * 255 + 32767) / 65535 +) end + local v = readu32(src, q) + return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5) + elseif typ == "snorm" then + if size == 1 then + local v = math.max(readi8(src, q), -127) + return v / 127, v + 128 + elseif size == 2 then + local v = math.max(readi16(src, q), -32767) + return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128 + end + local v = math.max(readi32(src, q), -2147483647) + return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128 + elseif typ == "float" then + local f = (size == 2 and{HALF[readu16(src, q)] }or{(readf32(src, q) +)})[1] local c = f ~= f and 0 or(f < 0 and 0 or(f > 1 and 1 or f +)) return f, math.floor(c * 255 + 0.5) + elseif typ == "uint" then + local v = (size == 1 and{(readu8(src, q) )}or{(size == 2 and{(readu16(src, q) )}or{(readu32(src, q) +)})[1]})[1] return v, math.min(v, 255) + end + local v = (size == 1 and{(readi8(src, q) )}or{(size == 2 and{(readi16(src, q) )}or{(readi32(src, q) +)})[1]})[1] return v, math.clamp(v, 0, 255) +end + +-- BT.601 limited-range Y'CbCr -> an rgba8 u32 +local function ycc(y, u, v, a) +local c, d, e = 1.164 * (y - 16), u - 128, v - 128 + local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) + local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) + local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255) + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) +local function yuv(d, src, offset, w, h, pitch, dst) +local n = 0 + local order = d.order or "" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + if d.kind == "ayuv" then + local q = s + x * 4 + writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3))) + else + local q = s + (math.floor(x / 2)) * 4 + local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3) + local odd = x % 2 == 1 + if order == "yuyv" then + writeu32(dst, n, ycc((odd and{b2 }or{b0})[1], b1, b3, 255)) + elseif order == "uyvy" then + writeu32(dst, n, ycc((odd and{b3 }or{b1})[1], b0, b2, 255)) + elseif order == "rgbg" then + writeu32(dst, n, b0 + ((odd and{b3 }or{b1})[1]) * 256 + b2 * 65536 + 0xFF000000) + else + writeu32(dst, n, b1 + ((odd and{b2 }or{b0})[1]) * 256 + b3 * 65536 + 0xFF000000) + end + end + n =n+ 4 + end + end + return dst +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, +-- message. rowPitch: bytes per source row (default tight). +function Texel.decode(fmt, src, offset, w, h, native, rowPitch) +local d = (type(fmt) == "string" and{FORMATS[fmt] }or{fmt +})[1] if not d then + return nil, "unsupported: unknown texel format " .. tostring(fmt) + end + local tb = d.bytes + local rowBytes = (d.kind == "pair" and(((math.floor((w + 1) / 2)) * 4 ))or((tb * w +))) local pitch = rowPitch or rowBytes + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then + return nil, "bad image size" + end + if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then + return nil, "truncated: texel data runs past the end" + end + local out = (native and d.kind ~= "pair" and d.kind ~= "ayuv" and{(nativeOf(d) )}or{"rgba8" +})[1] local bpp = out == "rgba8" and 4 or(out == "rgba16" and 8 or 16 +) local dst = buffer.create(w * h * bpp) + local n = 0 + if d.kind == "array" then + local order, size, typ = d.order , d.size , d.type -- fast paths + +if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then + local swap = order == "bgra" or order == "bgrx" + local opaque = order == "bgrx" or order == "rgbx" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + if swap then + v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16) + end + if opaque then + v = band(v, 0xFFFFFF) + 0xFF000000 + end + writeu32(dst, n, v) + n =n+ 4 + end + end + return dst, out + end + local nc = #order + local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + for i = 1, nc do + local c = string.sub(order, i, i) + map[i] = (c == "r" and{(nc == 1 and 4 or 0) }or{c == "g" and 1 or(c == "b" and 2 or(c == "a" and 3 or(c == "l" and 4 or-1 +)))})[1] end + local f = table.create(4, 0) + local q8 = table.create(4, 0) + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + f[1], f[2], f[3], f[4] = 0, 0, 0, 1 + q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255 + for i = 1, nc do + local m = map[i] + if m >= 0 then + local fv, bv = component(src, s, size, typ) + if m == 4 then + f[1], f[2], f[3] = fv, fv, fv + q8[1], q8[2], q8[3] = bv, bv, bv + else + f[m + 1], q8[m + 1] = fv, bv + end + end + s =s+ size + end + if out == "rgba8" then + writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216) + elseif out == "rgba16" then + for c = 0, 3 do + writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5)) + end + else + for c = 0, 3 do + writef32(dst, n + c * 4, f[c + 1]) + end + end + n =n+ bpp + end + end + return dst, out + elseif d.kind == "packed" then + local chs = d.channels +for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = (tb == 1 and{(readu8(src, s) )}or{(tb == 2 and{(readu16(src, s) )}or{(tb == 3 and{(readu16(src, s) + readu8(src, s + 2) * 65536 )}or{(readu32(src, s) +)})[1]})[1]})[1] s =s+ tb + local r, g, b, a = 0, 0, 0, 1 + for _, c in __iter(chs) do + local maxv = lshift(1, c.bits) - 1 + local x = band(rshift(v, c.shift), maxv) / (c.bits >= 32 and 4294967295 or maxv) + local k = c.c + if k == "r" then + r = x + elseif k == "g" then + g = x + elseif k == "b" then + b = x + elseif k == "a" then + a = x + else + r, g, b = x, x, x + end + end + if out == "rgba8" then + writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216) + else + writeu16(dst, n, math.floor(r * 65535 + 0.5)) + writeu16(dst, n + 2, math.floor(g * 65535 + 0.5)) + writeu16(dst, n + 4, math.floor(b * 65535 + 0.5)) + writeu16(dst, n + 6, math.floor(a * 65535 + 0.5)) + end + n =n+ bpp + end + end + return dst, out + end + if d.kind == "pair" or d.kind == "ayuv" then + return yuv(d, src, offset, w, h, pitch, dst), out + end + -- shared-exponent / packed floats + local nine = d.kind == "rgb9e5" + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = readu32(src, s) + s =s+ 4 + local sc = (nine and{(2 ^ (rshift(v, 27) - 24) )}or{0 +})[1] local r= (nine and{(band(v, 511) * sc )}or{(uf11(band(v, 2047)) +)})[1] local g= (nine and{(band(rshift(v, 9), 511) * sc )}or{(uf11(band(rshift(v, 11), 2047)) +)})[1] local b= (nine and{(band(rshift(v, 18), 511) * sc )}or{(uf10(rshift(v, 22)) +)})[1] if out == "rgba8" then + local function q(x) +return (x ~= x or x <= 0 )and 0 or(x >= 1 and 255 or math.floor(x * 255 + 0.5) +) end + writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) + else + writef32(dst, n, r) + writef32(dst, n + 4, g) + writef32(dst, n + 8, b) + writef32(dst, n + 12, 1) + end + n =n+ bpp + end + end + return dst, out +end + +return Texel +end +__FILES["codecs/image/Texture"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): +-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format +-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one +-- Types.Image, halve() makes the next mip level of an image for writers. New in rosetta. Never throws. +-- +-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format +-- Texture.size("etc2_rgb", w, h) -- bytes of one surface +-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them +-- local smaller = Texture.halve(img) -- box-filtered next mip level +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Etc = __include("codecs/image/Etc") +local Texel = __include("codecs/image/Texel") +local Half = __include("codecs/image/Half") + +local Texture = {} + +-- known(name) -> "bcn" | "etc" | "texel" | nil +function Texture.known(name) +if Bcn.BLOCK[name] then + return "bcn" + elseif Etc.BLOCK[name] then + return "etc" + elseif Texel.FORMATS[name] then + return "texel" + end + return nil +end + +-- size(name, w, h) -> bytes of a w x h surface | nil +function Texture.size(name, w, h) +return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) +end + +-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil +function Texture.block(name) +local b = Bcn.BLOCK[name] or Etc.BLOCK[name] + if b then + return 4, 4, b + end + local d = Texel.FORMATS[name] + if d then + return 1, 1, d.bytes + end + return nil, nil, nil +end + +-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is +-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). +function Texture.decode(name, src, offset, w, h, native) +if Bcn.BLOCK[name] then + local px, err = Bcn.decode(name, src, offset, w, h) + if not px then + return nil, err or "bad block data" + end + if Bcn.FLOAT[name] then + if native then + return px, "rgbaf32" + end + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(out, i * 4 + c, (v ~= v or v <= 0 )and 0 or(v >= 1 and 255 or math.floor(v * 255 + 0.5))) + end + end + return out, "rgba8" + end + return px, "rgba8" + elseif Etc.BLOCK[name] then + local wide = native == true and string.sub(name, 1, 3) == "eac" + local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide) + if not px then + return nil, err or "bad block data" + end + return px, wide and"rgba16" or"rgba8" + end + return Texel.decode(name, src, offset, w, h, native) +end + +-- image(pixels, pixel format, w, h) -> Types.Image +function Texture.image(px, pf, w, h) +local img = Types.Image.new(0, 0, pf ) + img.width, img.height, img.pixels = w, h, px + return img +end + +-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / +-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface + + +function Texture.assemble(list, layout) +local first= nil + local frames= {} + local mips= {} + for _, s in __iter(list) do + if s.level == 0 then + first = first or s.image + local fr= { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + table.insert(frames, fr) + elseif s.layer == 0 and s.face == 0 and s.slice == 0 then + mips[s.level] = s.image + end + end + if not first then + return nil + end + local img = Texture.image(first.pixels, first.format, first.width, first.height) + if #frames > 1 then + img.frames = frames + end + if #mips > 0 then + img.meta.mipmaps = mips + end + img.meta.layout = layout + return img +end + +-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format +-- (rgba8 / rgba16 / rgbaf32) +function Texture.halve(img) +local w, h = img.width, img.height + local nw, nh = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) + local fmt = img.format + local out = Types.Image.new(nw, nh, fmt) + local src, dst = img.pixels, out.pixels + local cs = fmt == "rgba8" and 1 or(fmt == "rgba16" and 2 or 4 +) local function get(x, y, c) +local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs + return (cs == 1 and{(buffer.readu8(src, o) )}or{(cs == 2 and{(buffer.readu16(src, o) )}or{(buffer.readf32(src, o) +)})[1]})[1] end + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local x0, y0 = x * 2, y * 2 + local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4 + local o = ((y * nw + x) * 4 + c) * cs + if cs == 1 then + buffer.writeu8(dst, o, math.floor(v + 0.5)) + elseif cs == 2 then + buffer.writeu16(dst, o, math.floor(v + 0.5)) + else + buffer.writef32(dst, o, v) + end + end + end + end + return out +end + +-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) +function Texture.toHalf(px, n) +local out = buffer.create(n * 8) + local from = Half.fromFloat + for i = 0, n * 4 - 1 do + buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4))) + end + return out +end + +return Texture +end +__FILES["codecs/image/Vp8"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the +-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals +-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause, +-- licenses/libvpx-LICENSE.txt), bit-exact with libvpx / ffmpeg on the official test vectors and libvpx streams. +-- Supports: key and inter frames of every version / profile (0: six-tap filters, normal loop filter; 1-2: bilinear; +-- 3: bilinear with full pixel chroma; the loop filter type is the header's), last / golden / altref references with +-- sign bias, hidden (altref) frames, token partitions, segments, loop filter deltas, probability context save / +-- restore. Not supported: the horizontal / vertical scale bits (ignored, as libwebp and ffmpeg do), error +-- concealment (a damaged frame returns an Err). +-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace +-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps). +-- +-- local Vp8 = require("rosetta.codecs.image.Vp8") +-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image +-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling) +-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames +-- local img, err = dec:decodeFrame(buf, off, len) -- img.meta.source.show == false: a hidden frame +-- dec:reset() -- after a seek: the next frame must be a key frame +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG). +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/image/Vp8/Decode") +local Yuv = __include("codecs/image/Vp8/Yuv") + +local Vp8 = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + + + + + +local function fail(msg, offset) +local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + elseif string.sub(m, 1, 13) == "unsupported: " then + return Err.new(Err.UNSUPPORTED, string.sub(m, 14), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end + +local function range(buf, off, len) +local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, Err +function Vp8.info(buf, off, len) +if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "info: expected a buffer") + end + local o, l = range(buf, off, len) + local h, err = Decode.header(buf, o, l) + if not h then + return nil, fail(err, o) + end + return h, nil +end + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + +-- newDecoder() -> Decoder: decodes successive frames of one stream + + +function Vp8.newDecoder() +return setmetatable({ state = Decode.new() }, DecoderMeta) +end + +-- decoder:decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image (a fresh buffer) | nil, Err. Key and inter frames; +-- meta.source = { format = "vp8", keyFrame, show (false: a hidden frame, decoded as a reference but not displayed), +-- profile, width, height }. An inter frame before the first key frame (or after reset) returns CORRUPT. +function DecoderMeta.decodeFrame(self, buf, off, len, opts) +if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local img = Types.Image.new(f.width, f.height, "yuv420p") + local ny = f.width * f.height + local nc = (math.floor((f.width + 1) / 2)) * (math.floor((f.height + 1) / 2)) + Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc) + local h = f.header + img.meta.source = { format = "vp8", keyFrame = h.keyFrame, show = h.show, profile = h.profile, width = f.width, height = f.height } + return img, nil +end + +-- decoder:reset(): drops the reference frames (after a seek); the next frame must be a key frame +function DecoderMeta.reset(self) + Decode.reset(self.state) +end + +-- decodeFrame(buf, off?, len?, opts?) -> a yuv420p Image | nil, Err (one key frame) +function Vp8.decodeFrame(buf, off, len, opts) +return Vp8.newDecoder():decodeFrame(buf, off, len, opts) +end + +-- decodePlanes(buf, off?, len?, opts?) -> y, u, v, width, height | nil, Err: one key frame as separate planes +function Vp8.decodePlanes(buf, off, len, opts) +if type(buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "decodePlanes: expected a buffer") + end + local o, l = range(buf, off, len) + local f, err = Decode.decodeFrame(Decode.new(), buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS) + if not f then + return nil, fail(err, o) + end + local nc = (math.floor((f.width + 1) / 2)) * (math.floor((f.height + 1) / 2)) + local y, u, v = buffer.create(f.width * f.height), buffer.create(nc), buffer.create(nc) + Decode.cropTo(f, y, 0, u, 0, v, 0) + return y, u, v, f.width, f.height +end + +-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height +function Vp8.planes(img) +local cw, ch = math.floor((img.width + 1) / 2), math.floor((img.height + 1) / 2 +) local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +-- toRgba(yuvImage, fancy?) -> rgba8 Image. fancy (default true): libwebp's bilinear chroma upsampling; false: point +-- sampling (dwebp -nofancy) +function Vp8.toRgba(img, fancy) +if type(img) ~= "table" or img.format ~= "yuv420p" then + return nil, Err.new(Err.ARG, "toRgba: needs a yuv420p Image") + end + local w, h = img.width, img.height + local _, uo, vo, cw, ch = Vp8.planes(img) + local y = buffer.create(w * h) + local u = buffer.create(cw * ch) + local v = buffer.create(cw * ch) + buffer.copy(y, 0, img.pixels, 0, w * h) + buffer.copy(u, 0, img.pixels, uo, cw * ch) + buffer.copy(v, 0, img.pixels, vo, cw * ch) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(y, u, v, w, h, fancy ~= false, out.pixels) + out.meta.source = img.meta.source + return out, nil +end + +-- yuvToRgba(y, u, v, w, h, fancy?) -> rgba8 pixels from separate planes (alpha 255) +function Vp8.yuvToRgba(y, u, v, w, h, fancy) +return Yuv.toRgba(y, u, v, w, h, fancy ~= false) +end + +Vp8.setAlpha = Yuv.setAlpha + +return Vp8 +end +__FILES["codecs/image/Vp8/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter / +-- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra +-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c, +-- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause, +-- licenses/libwebp-LICENSE.txt). Inter frames after libvpx 1.17 vp8/decoder/decodeframe.c, decodemv.c and +-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign +-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas, +-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per +-- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg +-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate +-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg. +-- +-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the +-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when +-- the data ends early). +local Tables = __include("codecs/image/Vp8/Tables") +local Predict = __include("codecs/image/Vp8/Predict") + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bfill, bcopy, bcreate = buffer.fill, buffer.copy, buffer.create +local abs = math.abs + +local COEFF_PROBA0 = Tables.COEFF_PROBA0 +local COEFF_UPDATE_PROBA = Tables.COEFF_UPDATE_PROBA +local BMODES_PROBA = Tables.BMODES_PROBA +local DC_TABLE, AC_TABLE = Tables.DC_TABLE, Tables.AC_TABLE +local BANDS, ZIGZAG = Tables.BANDS, Tables.ZIGZAG +local CAT = { Tables.CAT3, Tables.CAT4, Tables.CAT5, Tables.CAT6 } + +local Decode = {} +-- ------------------------------------------------------------------------------------------------ boolean decoder +-- libwebp's VP8BitReader: `range` is the range minus one (127..254), `value` holds the unread bits, `bits` is the +-- position of the 8-bit window in `value` (< 0: load more). Bytes past the end read as zero once and set eof. +-- SHIFT[r + 1]: the normalisation shift of a range r (1..255) = 7 - floor(log2 r) + + + +local SHIFT = table.create(256, 0) +for r = 1, 255 do + local s, v = 0, r + while v < 128 do + v =v* 2 + s =s+ 1 + end + SHIFT[r + 1] = s +end + +local function load(br) + local p = br.pos + if p + 3 <= br.limit then + local b = br.buf + br.value = br.value * 16777216 + readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + br.pos = p + 3 + br.bits =br.bits+ 24 + elseif p < br.limit then + br.value = br.value * 256 + readu8(br.buf, p) + br.pos = p + 1 + br.bits =br.bits+ 8 + elseif not br.eof then + br.value =br.value* 256 + br.bits =br.bits+ 8 + br.eof = true + else + br.bits = 0 + end +end + +local function newBr(buf, off, len) +local br = { buf = buf, pos = off, limit = off + len, value = 0, bits = -8, range = 254, eof = false } + load(br) + return br +end + +-- getBit without a branch on the decoded bit (one inlined copy per call site keeps LuaJIT's trace count down): +-- bit = 1 when value >> bits > split, then range = bit ? range - split : split + 1, value -= bit * (split + 1) << bits +local function getBit(br, prob) +if br.bits < 0 then + load(br) + end + local range = br.range + local pos = br.bits + local split = rshift(range * prob, 8) + local bit = rshift(split - rshift(br.value, pos), 31) + local r = split + 1 + bit * (range - split - split - 1) + br.value =br.value- bit * lshift(split + 1, pos) + local shift = SHIFT[r + 1] + br.range = lshift(r, shift) - 1 + br.bits = pos - shift + return bit +end + +local function getValue(br, n) +local v = 0 + for i = n - 1, 0, -1 do + v =v+ getBit(br, 0x80) * 2 ^ i + end + return v +end + +local function getSignedValue(br, n) +local v = getValue(br, n) + return (getBit(br, 0x80) == 1 and{(-v )}or{v +})[1]end +-- ------------------------------------------------------------------------------------------------ state + + + +-- a decoded frame / reference: the macroblock aligned planes with a Predict.BORDER pixel border + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function Decode.new() +return { + proba = table.clone(COEFF_PROBA0), + ymodeProb = table.clone(Tables.YMODE_PROB), + uvmodeProb = table.clone(Tables.UVMODE_PROB), + mvProb = table.clone(Tables.MV_DEFAULT), + segProba = { 255, 255, 255 }, + useSegment = false, + updateMap = false, + absoluteDelta = false, + segQuant = { 0, 0, 0, 0 }, + segFilter = { 0, 0, 0, 0 }, + refLfDelta = { 0, 0, 0, 0 }, + modeLfDelta = { 0, 0, 0, 0 }, + signBias = { 0, 0, 0, 0 }, + segMap = {}, + width = 0, + height = 0, + mbw = 0, + mbh = 0, + hasKey = false, + last = nil, + golden = nil, + alt = nil, + pool = {}, + miRef = {}, + miMode = {}, + miMvR = {}, + miMvC = {}, + miSubR = {}, + miSubC = {}, + miN = 0, + pred = nil, + } +end + +-- reset(state): drops the references; the next frame must be a key frame +function Decode.reset(st) + st.hasKey = false + st.last, st.golden, st.alt = nil, nil, nil +end + +-- header(buf, off, len) -> { keyFrame, profile, show, partitionLength, width, height, xscale, yscale } | nil, msg +function Decode.header(buf, off, len) +if len < 3 then + return nil, "truncated: frame tag" + end + local bits = readu8(buf, off) + readu8(buf, off + 1) * 256 + readu8(buf, off + 2) * 65536 + local h = { + keyFrame = band(bits, 1) == 0, + profile = band(rshift(bits, 1), 7), + show = band(rshift(bits, 4), 1) == 1, + partitionLength = rshift(bits, 5), + width = 0, + height = 0, + xscale = 0, + yscale = 0, + } + if h.profile > 3 then + return nil, "bad profile " .. h.profile + end + if h.keyFrame then + if len < 10 then + return nil, "truncated: key frame header" + end + if readu8(buf, off + 3) ~= 0x9d or readu8(buf, off + 4) ~= 0x01 or readu8(buf, off + 5) ~= 0x2a then + return nil, "bad VP8 start code" + end + local w = readu8(buf, off + 6) + readu8(buf, off + 7) * 256 + local ht = readu8(buf, off + 8) + readu8(buf, off + 9) * 256 + h.width, h.xscale = band(w, 0x3fff), rshift(w, 14) + h.height, h.yscale = band(ht, 0x3fff), rshift(ht, 14) + end + return h, nil +end + +-- ------------------------------------------------------------------------------------------------ residuals +local function getLargeValue(br, P, p) +local v + if getBit(br, P[p + 4]) == 0 then + if getBit(br, P[p + 5]) == 0 then + v = 2 + else + v = 3 + getBit(br, P[p + 6]) + end + else + if getBit(br, P[p + 7]) == 0 then + if getBit(br, P[p + 8]) == 0 then + v = 5 + getBit(br, 159) + else + v = 7 + 2 * getBit(br, 165) + v =v+ getBit(br, 145) + end + else + local bit1 = getBit(br, P[p + 9]) + local bit0 = getBit(br, P[p + 10 + bit1]) + local cat = 2 * bit1 + bit0 + v = 0 + for _, pr in __iter(CAT[cat + 1]) do + v = v + v + getBit(br, pr) + end + v =v+ (3 + lshift(8, cat) +) end + end + return v +end + +-- getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) -> the position of the last non-zero coefficient + 1. Writes the +-- dequantized coefficients (int16, as libwebp stores them) into out at byte offset o, in raster order. The boolean +-- decoder is inlined (the hot loop of lossy decoding); getLargeValue goes through br. +local function getCoeffs(br, P, t, ctx, dqDc, dqAc, n, out, o) +local tb = t * 8 + local p = ((tb + BANDS[n + 1]) * 3 + ctx) * 11 + local buf, limit = br.buf, br.limit + local value, bits, range, pos = br.value, br.bits, br.range, br.pos + while n < 16 do + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos =pos+ 3 + bits =bits+ 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 1], 8) + local more = rshift(value, bits) > split + if more then + range =range- split + value =value- lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits =bits- sh + if not more then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return n + end + end + while true do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos =pos+ 3 + bits =bits+ 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 2], 8) + local nonzero = rshift(value, bits) > split + if nonzero then + range =range- split + value =value- lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits =bits- sh + if nonzero then + break + end + n =n+ 1 + if n == 16 then + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 + end + p = (tb + BANDS[n + 1]) * 33 + end + local nb = (tb + BANDS[n + 2]) * 3 + local v + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos =pos+ 3 + bits =bits+ 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * P[p + 3], 8) + local large = rshift(value, bits) > split + if large then + range =range- split + value =value- lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits =bits- sh + if not large then + v = 1 + p = (nb + 1) * 11 + else + br.value, br.bits, br.range, br.pos = value, bits, range, pos + v = getLargeValue(br, P, p) + value, bits, range, pos = br.value, br.bits, br.range, br.pos + p = (nb + 2) * 11 + end + end + do + if bits < 0 then + if pos + 3 <= limit then + value = value * 16777216 + readu8(buf, pos) * 65536 + readu8(buf, pos + 1) * 256 + readu8(buf, pos + 2) + pos =pos+ 3 + bits =bits+ 24 + else + br.value, br.bits, br.pos = value, bits, pos + load(br) + value, bits, pos = br.value, br.bits, br.pos + end + end + local split = rshift(range * 0x80, 8) + local neg = rshift(value, bits) > split + if neg then + range =range- split + value =value- lshift(split + 1, bits) + else + range = split + 1 + end + local sh = SHIFT[range + 1] + range = lshift(range, sh) - 1 + bits =bits- sh + if neg then + v = -v + end + end + if n > 0 then + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqAc) + else + writei16(out, o + ZIGZAG[n + 1] * 2, v * dqDc) + end + n =n+ 1 + end + br.value, br.bits, br.range, br.pos = value, bits, range, pos + return 16 +end + +local function nzCode(acc, nz, dcNz) +return acc * 4 + (nz > 3 and 3 or(nz > 1 and 2 or dcNz)) +end + +-- the inverse Walsh-Hadamard transform of the 16 Y2 coefficients into the DC of the 16 luma blocks +local whtTmp = table.create(16, 0) +local function transformWHT(inp, out, o) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(inp, i * 2), readi16(inp, (4 + i) * 2), readi16(inp, (8 + i) * 2), readi16(inp, (12 + i) * 2) + local a0 = i0 + i12 + local a1 = i4 + i8 + local a2 = i4 - i8 + local a3 = i0 - i12 + whtTmp[1 + i] = a0 + a1 + whtTmp[9 + i] = a0 - a1 + whtTmp[5 + i] = a3 + a2 + whtTmp[13 + i] = a3 - a2 + end + for i = 0, 3 do + local dc = whtTmp[1 + i * 4] + 3 + local a0 = dc + whtTmp[4 + i * 4] + local a1 = whtTmp[2 + i * 4] + whtTmp[3 + i * 4] + local a2 = whtTmp[2 + i * 4] - whtTmp[3 + i * 4] + local a3 = dc - whtTmp[4 + i * 4] + local base = o + i * 128 + writei16(out, base, math.floor((a0 + a1) / 8)) + writei16(out, base + 32, math.floor((a3 + a2) / 8)) + writei16(out, base + 64, math.floor((a0 - a1) / 8)) + writei16(out, base + 96, math.floor((a3 - a2) / 8)) + end +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the work buffer of libwebp (yuv_b): BPS = 32, Y at row 1 column 8, U and V below it side by side +local BPS = 32 +local Y_OFF = BPS + 8 +local U_OFF = Y_OFF + BPS * 16 + BPS +local V_OFF = U_OFF + 16 +local YUV_SIZE = BPS * 17 + BPS * 9 + +local function clip8(v) +return v < 0 and 0 or(v > 255 and 255 or v +)end + +-- the inverse DCT of one block (libwebp TransformOne) added to dst +local C1, C2 = 20091, 35468 +local idctTmp = table.create(16, 0) +local function mul1(a) +return (math.floor((a * C1) / 65536)) + a +end +local function mul2(a) +return math.floor((a * C2) / 65536 +)end +local function transformOne(c, o, b, dst) + for i = 0, 3 do + local i0, i4, i8, i12 = readi16(c, o + i * 2), readi16(c, o + (4 + i) * 2), readi16(c, o + (8 + i) * 2), readi16(c, o + (12 + i) * 2) + local a = i0 + i8 + local bb = i0 - i8 + local cc = mul2(i4) - mul1(i12) + local d = mul1(i4) + mul2(i12) + idctTmp[i * 4 + 1] = a + d + idctTmp[i * 4 + 2] = bb + cc + idctTmp[i * 4 + 3] = bb - cc + idctTmp[i * 4 + 4] = a - d + end + for i = 0, 3 do + local dc = idctTmp[i + 1] + 4 + local a = dc + idctTmp[i + 9] + local bb = dc - idctTmp[i + 9] + local cc = mul2(idctTmp[i + 5]) - mul1(idctTmp[i + 13]) + local d = mul1(idctTmp[i + 5]) + mul2(idctTmp[i + 13]) + local row = dst + i * BPS + writeu8(b, row, clip8(readu8(b, row) + math.floor((a + d) / 8))) + writeu8(b, row + 1, clip8(readu8(b, row + 1) + math.floor((bb + cc) / 8))) + writeu8(b, row + 2, clip8(readu8(b, row + 2) + math.floor((bb - cc) / 8))) + writeu8(b, row + 3, clip8(readu8(b, row + 3) + math.floor((a - d) / 8))) + end +end + +local function transformDC(c, o, b, dst) + local dc = math.floor((readi16(c, o) + 4) / 8 +) for j = 0, 3 do + local row = dst + j * BPS + for i = row, row + 3 do + writeu8(b, i, clip8(readu8(b, i) + dc)) + end + end +end + +-- code: 3 = full transform, 2 = only the first three coefficients (the same result as the full one), 1 = DC only +local function doTransform(code, c, o, b, dst) + if code >= 2 then + transformOne(c, o, b, dst) + elseif code == 1 then + transformDC(c, o, b, dst) + end +end + +local function doUVTransform(bits, c, o, b, dst) + if band(bits, 0xff) ~= 0 then + if band(bits, 0xaa) ~= 0 then + transformOne(c, o, b, dst) + transformOne(c, o + 32, b, dst + 4) + transformOne(c, o + 64, b, dst + 4 * BPS) + transformOne(c, o + 96, b, dst + 4 * BPS + 4) + else + if readi16(c, o) ~= 0 then + transformDC(c, o, b, dst) + end + if readi16(c, o + 32) ~= 0 then + transformDC(c, o + 32, b, dst + 4) + end + if readi16(c, o + 64) ~= 0 then + transformDC(c, o + 64, b, dst + 4 * BPS) + end + if readi16(c, o + 96) ~= 0 then + transformDC(c, o + 96, b, dst + 4 * BPS + 4) + end + end + end +end + +-- prediction: modes 0 DC, 1 TM, 2 VE, 3 HE; 4 DC no top, 5 DC no left, 6 DC no top-left (16x16 and chroma) +local function fill(b, dst, size, v) + for j = 0, size - 1 do + local o = dst + j * BPS + for i = o, o + size - 4, 4 do + writeu32(b, i, v * 0x01010101) + end + end +end + +local function trueMotion(b, dst, size) + local tl = readu8(b, dst - BPS - 1) + for y = 0, size - 1 do + local row = dst + y * BPS + local l = readu8(b, row - 1) - tl + for x = 0, size - 1 do + writeu8(b, row + x, clip8(readu8(b, dst - BPS + x) + l)) + end + end +end + +local function predictBlock(b, dst, size, mode) + local shift = size == 16 and 5 or 4 + if mode == 0 then + local dc = size + for j = 0, size - 1 do + dc =dc+ (readu8(b, dst - 1 + j * BPS) + readu8(b, dst + j - BPS) +) end + fill(b, dst, size, rshift(dc, shift)) + elseif mode == 1 then + trueMotion(b, dst, size) + elseif mode == 2 then + for j = 0, size - 1 do + local o = dst + j * BPS + for i = 0, size - 4, 4 do + writeu32(b, o + i, readu32(b, dst - BPS + i)) + end + end + elseif mode == 3 then + for j = 0, size - 1 do + local o = dst + j * BPS + local v = readu8(b, o - 1) * 0x01010101 + for i = o, o + size - 4, 4 do + writeu32(b, i, v) + end + end + elseif mode == 4 then -- no top: left samples + local dc = math.floor(size / 2 +) for j = 0, size - 1 do + dc =dc+ readu8(b, dst - 1 + j * BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + elseif mode == 5 then -- no left: top samples + local dc = math.floor(size / 2 +) for j = 0, size - 1 do + dc =dc+ readu8(b, dst + j - BPS) + end + fill(b, dst, size, rshift(dc, shift - 1)) + else + fill(b, dst, size, 0x80) + end +end + +local function avg3(a, b, c) +return rshift(a + 2 * b + c + 2, 2) +end +local function avg2(a, b) +return rshift(a + b + 1, 1) +end + +-- 4x4 prediction (libwebp VP8PredLuma4): 0 DC, 1 TM, 2 VE, 3 HE, 4 RD, 5 VR, 6 LD, 7 VL, 8 HD, 9 HU +local function predict4(b, dst, mode) + if mode == 0 then + local dc = 4 + for i = 0, 3 do + dc =dc+ (readu8(b, dst + i - BPS) + readu8(b, dst - 1 + i * BPS) +) end + fill(b, dst, 4, rshift(dc, 3)) + elseif mode == 1 then + trueMotion(b, dst, 4) + elseif mode == 2 then + local t = dst - BPS + local x, a, bb, c, d, e = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3), readu8(b, t + 4) + local v0, v1, v2, v3 = avg3(x, a, bb), avg3(a, bb, c), avg3(bb, c, d), avg3(c, d, e) + for j = 0, 3 do + writeu8(b, dst + j * BPS + 0, v0) + writeu8(b, dst + j * BPS + 1, v1) + writeu8(b, dst + j * BPS + 2, v2) + writeu8(b, dst + j * BPS + 3, v3) + end + elseif mode == 3 then + local A, B, C, D = readu8(b, dst - 1 - BPS), readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS) + local E = readu8(b, dst - 1 + 3 * BPS) + writeu32(b, dst, avg3(A, B, C) * 0x01010101) + writeu32(b, dst + BPS, avg3(B, C, D) * 0x01010101) + writeu32(b, dst + 2 * BPS, avg3(C, D, E) * 0x01010101) + writeu32(b, dst + 3 * BPS, avg3(D, E, E) * 0x01010101) + else + local I, J, K, L = readu8(b, dst - 1), readu8(b, dst - 1 + BPS), readu8(b, dst - 1 + 2 * BPS), readu8(b, dst - 1 + 3 * BPS) + local t = dst - BPS + local X, A, B, C, D = readu8(b, t - 1), readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + local E, F, G, H = readu8(b, t + 4), readu8(b, t + 5), readu8(b, t + 6), readu8(b, t + 7) + if mode == 4 then -- RD + writeu8(b, dst + 96, avg3(J, K, L)) + local v = avg3(I, J, K) + writeu8(b, dst + 97, v) + writeu8(b, dst + 64, v) + v = avg3(X, I, J) + writeu8(b, dst + 98, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 32, v) + v = avg3(A, X, I) + writeu8(b, dst + 99, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 0, v) + v = avg3(B, A, X) + writeu8(b, dst + 67, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 1, v) + v = avg3(C, B, A) + writeu8(b, dst + 35, v) + writeu8(b, dst + 2, v) + writeu8(b, dst + 3, avg3(D, C, B)) + elseif mode == 5 then -- VR + local v = avg2(X, A) + writeu8(b, dst + 0, v) + writeu8(b, dst + 65, v) + v = avg2(A, B) + writeu8(b, dst + 1, v) + writeu8(b, dst + 66, v) + v = avg2(B, C) + writeu8(b, dst + 2, v) + writeu8(b, dst + 67, v) + writeu8(b, dst + 3, avg2(C, D)) + writeu8(b, dst + 96, avg3(K, J, I)) + writeu8(b, dst + 64, avg3(J, I, X)) + v = avg3(I, X, A) + writeu8(b, dst + 32, v) + writeu8(b, dst + 97, v) + v = avg3(X, A, B) + writeu8(b, dst + 33, v) + writeu8(b, dst + 98, v) + v = avg3(A, B, C) + writeu8(b, dst + 34, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 35, avg3(B, C, D)) + elseif mode == 6 then -- LD + writeu8(b, dst + 0, avg3(A, B, C)) + local v = avg3(B, C, D) + writeu8(b, dst + 1, v) + writeu8(b, dst + 32, v) + v = avg3(C, D, E) + writeu8(b, dst + 2, v) + writeu8(b, dst + 33, v) + writeu8(b, dst + 64, v) + v = avg3(D, E, F) + writeu8(b, dst + 3, v) + writeu8(b, dst + 34, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 96, v) + v = avg3(E, F, G) + writeu8(b, dst + 35, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 97, v) + v = avg3(F, G, H) + writeu8(b, dst + 67, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 99, avg3(G, H, H)) + elseif mode == 7 then -- VL + writeu8(b, dst + 0, avg2(A, B)) + local v = avg2(B, C) + writeu8(b, dst + 1, v) + writeu8(b, dst + 64, v) + v = avg2(C, D) + writeu8(b, dst + 2, v) + writeu8(b, dst + 65, v) + v = avg2(D, E) + writeu8(b, dst + 3, v) + writeu8(b, dst + 66, v) + writeu8(b, dst + 32, avg3(A, B, C)) + v = avg3(B, C, D) + writeu8(b, dst + 33, v) + writeu8(b, dst + 96, v) + v = avg3(C, D, E) + writeu8(b, dst + 34, v) + writeu8(b, dst + 97, v) + v = avg3(D, E, F) + writeu8(b, dst + 35, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 67, avg3(E, F, G)) + writeu8(b, dst + 99, avg3(F, G, H)) + elseif mode == 8 then -- HD + local v = avg2(I, X) + writeu8(b, dst + 0, v) + writeu8(b, dst + 34, v) + v = avg2(J, I) + writeu8(b, dst + 32, v) + writeu8(b, dst + 66, v) + v = avg2(K, J) + writeu8(b, dst + 64, v) + writeu8(b, dst + 98, v) + writeu8(b, dst + 96, avg2(L, K)) + writeu8(b, dst + 3, avg3(A, B, C)) + writeu8(b, dst + 2, avg3(X, A, B)) + v = avg3(I, X, A) + writeu8(b, dst + 1, v) + writeu8(b, dst + 35, v) + v = avg3(J, I, X) + writeu8(b, dst + 33, v) + writeu8(b, dst + 67, v) + v = avg3(K, J, I) + writeu8(b, dst + 65, v) + writeu8(b, dst + 99, v) + writeu8(b, dst + 97, avg3(L, K, J)) + else -- HU + writeu8(b, dst + 0, avg2(I, J)) + local v = avg2(J, K) + writeu8(b, dst + 2, v) + writeu8(b, dst + 32, v) + v = avg2(K, L) + writeu8(b, dst + 34, v) + writeu8(b, dst + 64, v) + writeu8(b, dst + 1, avg3(I, J, K)) + v = avg3(J, K, L) + writeu8(b, dst + 3, v) + writeu8(b, dst + 33, v) + v = avg3(K, L, L) + writeu8(b, dst + 35, v) + writeu8(b, dst + 65, v) + writeu8(b, dst + 67, L) + writeu8(b, dst + 66, L) + writeu8(b, dst + 96, L) + writeu8(b, dst + 97, L) + writeu8(b, dst + 98, L) + writeu8(b, dst + 99, L) + end + end +end + +local function checkMode(mbx, mby, mode) +if mode == 0 then + if mbx == 0 then + return mby == 0 and 6 or 5 + end + return mby == 0 and 4 or 0 + end + return mode +end + +-- ------------------------------------------------------------------------------------------------ loop filter +-- the filters are libwebp's DoFilter2 / DoFilter4 / DoFilter6 inlined into their loops (VP8ksclip1 clamps to +-- [-128, 127], VP8ksclip2 to [-16, 15], VP8kclip1 to [0, 255]). Arithmetic shifts of small signed values are +-- logical shifts of the value plus a bias: (a + 4) >> 3 = rshift(a + 4 + 1024, 3) - 128 for a >= -1024. + +-- simpleFilter(b, p, step, along, thresh): SimpleVFilter16 / SimpleHFilter16 (16 positions). A position whose filter +-- value a is 0 changes nothing and is skipped before the mask (flat areas). +local function simpleFilter(b, p, step, along, thresh) + local t2 = 2 * thresh + 1 + for _ = 1, 16 do + local p1, p0, q0, q1 = readu8(b, p - 2 * step), readu8(b, p - step), readu8(b, p), readu8(b, p + step) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (w < -128 and-128 or(w > 127 and 127 or w)) + if a ~= 0 and 4 * abs(p0 - q0) + abs(w) <= t2 then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - step, v < 0 and 0 or(v > 255 and 255 or v)) + v = q0 - a1 + writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) + end + p =p+ along + end +end + +-- filterEdge(b, p, hs, vs, size, thresh, it, hevT): the macroblock edge filter (FilterLoop26) +local function filterEdge(b, p, hs, vs, size, thresh, it, hevT) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + local a = 3 * (q0 - p0) + (w < -128 and-128 or(w > 127 and 127 or w)) + if a ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + if dp > hevT or dq > hevT then + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = q0 - a1 + writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) + else + if a < -128 then + a = -128 + elseif a > 127 then + a = 127 + end + local a1 = rshift(27 * a + 4159, 7) - 32 + local a2 = rshift(18 * a + 4159, 7) - 32 + local a3 = rshift(9 * a + 4159, 7) - 32 + local v = p2 + a3 + writeu8(b, p - 3 * hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = p1 + a2 + writeu8(b, p - 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = p0 + a1 + writeu8(b, p - hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = q0 - a1 + writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) + v = q1 - a2 + writeu8(b, p + hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = q2 - a3 + writeu8(b, p + 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) + end + end + end + end + p =p+ vs + end +end + +-- filterInner(b, p, hs, vs, size, thresh, it, hevT): the inner edge filter (FilterLoop24); nothing changes when +-- q0 == p0 and p1 == q1 +local function filterInner(b, p, hs, vs, size, thresh, it, hevT) + local t2 = 2 * thresh + 1 + for _ = 1, size do + local p1, p0, q0, q1 = readu8(b, p - 2 * hs), readu8(b, p - hs), readu8(b, p), readu8(b, p + hs) + local w = p1 - q1 + if q0 ~= p0 or w ~= 0 then + local dp, dq = abs(p1 - p0), abs(q1 - q0) + if 4 * abs(p0 - q0) + abs(w) <= t2 and dp <= it and dq <= it then + local p3, p2 = readu8(b, p - 4 * hs), readu8(b, p - 3 * hs) + local q2, q3 = readu8(b, p + 2 * hs), readu8(b, p + 3 * hs) + if abs(p3 - p2) <= it and abs(p2 - p1) <= it and abs(q3 - q2) <= it and abs(q2 - q1) <= it then + local hev = dp > hevT or dq > hevT + local a = 3 * (q0 - p0) + if hev then + a =a+ (w < -128 and-128 or(w > 127 and 127 or w +)) end + local a1 = rshift(a + 1028, 3) - 128 + if a1 < -16 then + a1 = -16 + elseif a1 > 15 then + a1 = 15 + end + local a2 = rshift(a + 1027, 3) - 128 + if a2 < -16 then + a2 = -16 + elseif a2 > 15 then + a2 = 15 + end + local v = p0 + a2 + writeu8(b, p - hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = q0 - a1 + writeu8(b, p, v < 0 and 0 or(v > 255 and 255 or v)) + if not hev then + local a3 = rshift(a1 + 17, 1) - 8 + v = p1 + a3 + writeu8(b, p - 2 * hs, v < 0 and 0 or(v > 255 and 255 or v)) + v = q1 - a3 + writeu8(b, p + hs, v < 0 and 0 or(v > 255 and 255 or v)) + end + end + end + end + p =p+ vs + end +end + +-- ------------------------------------------------------------------------------------------------ inter modes +local MODE_CTX = Tables.MODE_CONTEXTS +local SUB_MV_REF_PROB = Tables.SUB_MV_REF_PROB +local SPLIT_OFFSET, SPLIT_FILL, SPLIT_COUNT = Tables.SPLIT_OFFSET, Tables.SPLIT_FILL, Tables.SPLIT_COUNT +local BMODE_PROB = Tables.BMODE_PROB +local MV_UPDATE = Tables.MV_UPDATE + +-- macroblock modes (the row arrays and miMode): 0 DC, 1 TM, 2 V, 3 H (16x16 intra, libwebp's numbering), 4 B_PRED, +-- 5 ZEROMV, 6 NEARESTMV, 7 NEARMV, 8 NEWMV, 9 SPLITMV. Their loop filter mode delta index: +local MODE_LF = { 1, 1, 1, 1, 0, 1, 2, 2, 2, 3 } + +-- a 4x4 intra mode with the fixed probabilities P[o + 1 .. o + 9] (libvpx vp8_bmode_tree, libwebp's numbering) +local function readBMode(br, P, o) +if getBit(br, P[o + 1]) == 0 then + return 0 + elseif getBit(br, P[o + 2]) == 0 then + return 1 + elseif getBit(br, P[o + 3]) == 0 then + return 2 + elseif getBit(br, P[o + 4]) == 0 then + if getBit(br, P[o + 5]) == 0 then + return 3 + end + return getBit(br, P[o + 6]) == 0 and 4 or 5 + elseif getBit(br, P[o + 7]) == 0 then + return 6 + elseif getBit(br, P[o + 8]) == 0 then + return 7 + end + return getBit(br, P[o + 9]) == 0 and 8 or 9 +end + +-- one motion vector component (libvpx read_mvcomponent) with the probabilities P[o + 1 .. o + 19], in quarter pixels +local function readMvComponent(br, P, o) +local x + if getBit(br, P[o + 1]) == 1 then -- long: bits 0-2, then 9-4, then bit 3 (implicit when nothing above it is set) + x = getBit(br, P[o + 10]) + 2 * getBit(br, P[o + 11]) + 4 * getBit(br, P[o + 12]) + for i = 9, 4, -1 do + x =x+ getBit(br, P[o + 10 + i]) * lshift(1, i) + end + if x < 16 or getBit(br, P[o + 13]) == 1 then + x =x+ 8 + end + elseif getBit(br, P[o + 3]) == 0 then -- short tree + if getBit(br, P[o + 4]) == 0 then + x = getBit(br, P[o + 5]) + else + x = 2 + getBit(br, P[o + 6]) + end + elseif getBit(br, P[o + 7]) == 0 then + x = 4 + getBit(br, P[o + 8]) + else + x = 6 + getBit(br, P[o + 9]) + end + if x ~= 0 and getBit(br, P[o + 2]) == 1 then + x = -x + end + return x +end + + + + + + + + + + +local nr, nc, cnt = table.create(4, 0), table.create(4, 0), table.create(4, 0) + +-- readInterMb(st, br, probs, mi, mbx, mby, rows): the modes and motion vectors of one inter frame macroblock (libvpx +-- read_mb_modes_mv with vp8_find_near_mvs); mi: its 1-based index in the mode info arrays +local function readInterMb(st, br, probIntra, probLast, probGf, mi, mbx, mby, rows) + local miRef, miMode, miMvR, miMvC = st.miRef, st.miMode, st.miMvR, st.miMvC + local x1 = mbx + 1 + if getBit(br, probIntra) == 0 then + local P = st.ymodeProb + local ymode + if getBit(br, P[1]) == 0 then + ymode = 0 + elseif getBit(br, P[2]) == 0 then + ymode = getBit(br, P[3]) == 0 and 2 or 3 + else + ymode = getBit(br, P[4]) == 0 and 1 or 4 + end + local modes = rows.modes + if ymode == 4 then + for k = mbx * 16 + 1, mbx * 16 + 16 do + modes[k] = readBMode(br, BMODE_PROB, 0) + end + else + modes[mbx * 16 + 1] = ymode + end + local U = st.uvmodeProb + if getBit(br, U[1]) == 0 then + rows.uv[x1] = 0 + elseif getBit(br, U[2]) == 0 then + rows.uv[x1] = 2 + else + rows.uv[x1] = getBit(br, U[3]) == 0 and 3 or 1 + end + rows.i4[x1] = ymode == 4 + rows.ref[x1] = 0 + rows.mode[x1] = ymode + rows.part[x1] = -1 + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = 0, ymode, 0, 0 + return + end + local ref = 1 + if getBit(br, probLast) == 1 then + ref = 2 + getBit(br, probGf) + end + -- the near motion vectors of the above, left and above-left macroblocks, sign corrected + local bias = st.signBias + local sb = bias[ref + 1] + local a = mi - (st.mbw + 1) + local l = mi - 1 + local al = a - 1 + for k = 1, 4 do + nr[k], nc[k], cnt[k] = 0, 0, 0 + end + local n = 1 + local rf = miRef[a] + if rf ~= 0 then + local r, c = miMvR[a], miMvC[a] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + n = 2 + nr[2], nc[2] = r, c + end + cnt[n]=cnt[n]+ 2 + end + rf = miRef[l] + if rf ~= 0 then + local r, c = miMvR[l], miMvC[l] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n =n+ 1 + nr[n], nc[n] = r, c + end + cnt[n]=cnt[n]+ 2 + else + cnt[1]=cnt[1]+ 2 + end + end + rf = miRef[al] + if rf ~= 0 then + local r, c = miMvR[al], miMvC[al] + if r ~= 0 or c ~= 0 then + if bias[rf + 1] ~= sb then + r, c = -r, -c + end + if r ~= nr[n] or c ~= nc[n] then + n =n+ 1 + nr[n], nc[n] = r, c + end + cnt[n]=cnt[n]+ 1 + else + cnt[1]=cnt[1]+ 1 + end + end + -- clamping bounds (vp8_clamp_mv2), in eighth pixels + local mbw, mbh = st.mbw, st.mbh + local toL, toR = -mbx * 128 - 128, (mbw - 1 - mbx) * 128 + 128 + local toT, toB = -mby * 128 - 128, (mbh - 1 - mby) * 128 + 128 + local mode, mvr, mvc, part = 5, 0, 0, -1 + if getBit(br, MODE_CTX[cnt[1] * 4 + 1]) == 1 then + if cnt[4] > 0 and nr[n] == nr[2] and nc[n] == nc[2] then + cnt[2]=cnt[2]+ 1 + end + if cnt[3] > cnt[2] then + cnt[2], cnt[3] = cnt[3], cnt[2] + nr[2], nr[3] = nr[3], nr[2] + nc[2], nc[3] = nc[3], nc[2] + end + local k + if getBit(br, MODE_CTX[cnt[2] * 4 + 2]) == 0 then + mode, k = 6, 2 + elseif getBit(br, MODE_CTX[cnt[3] * 4 + 3]) == 0 then + mode, k = 7, 3 + else + k = cnt[2] >= cnt[1] and 2 or 1 + end + mvr, mvc = nr[k], nc[k] + if mvc < toL then + mvc = toL + elseif mvc > toR then + mvc = toR + end + if mvr < toT then + mvr = toT + elseif mvr > toB then + mvr = toB + end + if mode == 5 then + -- mvr, mvc: the best vector; new or split + local P = st.mvProb + local sc = (miMode[a] == 9 and 2 or 0) + (miMode[l] == 9 and 2 or 0) + (miMode[al] == 9 and 1 or 0) + if getBit(br, MODE_CTX[sc * 4 + 4]) == 0 then + mode = 8 + mvr =mvr+ readMvComponent(br, P, 0) * 2 + mvc =mvc+ readMvComponent(br, P, 19) * 2 + else + mode = 9 + local bestR, bestC = mvr, mvc + local s, nump + if getBit(br, 110) == 1 then + if getBit(br, 111) == 1 then + s, nump = getBit(br, 150), 2 + else + s, nump = 2, 4 + end + else + s, nump = 3, 16 + end + part = s + local subR, subC = st.miSubR, st.miSubC + local sb0 = (mi - 1) * 16 + local lb, ab = (l - 1) * 16, (a - 1) * 16 + local splitL, splitA = miMode[l] == 9, miMode[a] == 9 + local count = SPLIT_COUNT[s + 1] + for j = 0, nump - 1 do + local b = SPLIT_OFFSET[s * 16 + j + 1] + local lr, lc, ar, ac + if b % 4 ~= 0 then + lr, lc = subR[sb0 + b], subC[sb0 + b] + elseif splitL then + lr, lc = subR[lb + b + 4], subC[lb + b + 4] + else + lr, lc = miMvR[l], miMvC[l] + end + if b >= 4 then + ar, ac = subR[sb0 + b - 3], subC[sb0 + b - 3] + elseif splitA then + ar, ac = subR[ab + b + 13], subC[ab + b + 13] + else + ar, ac = miMvR[a], miMvC[a] + end + local pi = ((ar == 0 and ac == 0 and 4 or 0) + (lr == 0 and lc == 0 and 2 or 0) + (lr == ar and lc == ac and 1 or 0)) * 3 + local r, c + if getBit(br, SUB_MV_REF_PROB[pi + 1]) == 0 then + r, c = lr, lc + elseif getBit(br, SUB_MV_REF_PROB[pi + 2]) == 0 then + r, c = ar, ac + elseif getBit(br, SUB_MV_REF_PROB[pi + 3]) == 0 then + r, c = 0, 0 + else + r = bestR + readMvComponent(br, P, 0) * 2 + c = bestC + readMvComponent(br, P, 19) * 2 + end + local fo = s * 16 + j * count + for i = fo + 1, fo + count do + local q = sb0 + SPLIT_FILL[i] + 1 + subR[q], subC[q] = r, c + end + end + mvr, mvc = subR[sb0 + 16], subC[sb0 + 16] + end + end + end + rows.i4[x1] = mode == 9 + rows.ref[x1] = ref + rows.mode[x1] = mode + rows.part[x1] = part + miRef[mi], miMode[mi], miMvR[mi], miMvC[mi] = ref, mode, mvr, mvc +end +-- ------------------------------------------------------------------------------------------------ frame + + + + + + + + +local BORDER = Predict.BORDER + +local function newRef(mbw, mbh) +local ys, uvs = mbw * 16 + 2 * BORDER, mbw * 8 + 2 * BORDER + return { + Y = bcreate(ys * (mbh * 16 + 2 * BORDER)), + U = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + V = bcreate(uvs * (mbh * 8 + 2 * BORDER)), + ys = ys, + uvs = uvs, + yb = BORDER * ys + BORDER, + uvb = BORDER * uvs + BORDER, + mbw = mbw, + mbh = mbh, + extended = false, + } +end + +-- a frame buffer no reference uses +local function freeRef(st) +for _, r in __iter(st.pool) do + if r ~= st.last and r ~= st.golden and r ~= st.alt then + return r + end + end + local r = newRef(st.mbw, st.mbh) + table.insert(st.pool, r) + return r +end + +-- cropTo(frame, dy, oy, du, ou, dv, ov): copies the visible planes out (luma stride width, chroma ceil(width / 2)) +function Decode.cropTo(f, dy, oy, du, ou, dv, ov) + local r = f.ref + local w, h = f.width, f.height + local cw, chh = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb + for j = 0, h - 1 do + bcopy(dy, oy + j * w, Y, yb + j * ys, w) + end + for j = 0, chh - 1 do + bcopy(du, ou + j * cw, U, uvb + j * uvs, cw) + bcopy(dv, ov + j * cw, V, uvb + j * uvs, cw) + end +end + +-- decodeFrame(state, buf, off, len, maxPixels) -> Frame | nil, message: one key or inter frame of the stream +function Decode.decodeFrame(st, buf, off, len, maxPixels) +local hdr, herr = Decode.header(buf, off, len) + if not hdr then + return nil, herr + end + local key = hdr.keyFrame + local width, height, p, left + if key then + width, height = hdr.width, hdr.height + if width == 0 or height == 0 then + return nil, "zero frame size" + end + if width * height > maxPixels then + return nil, "limit: " .. width .. " x " .. height .. " is over maxPixels" + end + p, left = off + 10, len - 10 + else + if not st.hasKey then + return nil, "inter frame without a key frame" + end + width, height = st.width, st.height + p, left = off + 3, len - 3 + end + if hdr.partitionLength > left then + return nil, "truncated: first partition" + end + local mbw, mbh = math.floor((width + 15) / 16), math.floor((height + 15) / 16 +) if key then + st.hasKey = false + if width ~= st.width or height ~= st.height then + st.width, st.height, st.mbw, st.mbh = width, height, mbw, mbh + st.last, st.golden, st.alt, st.pool = nil, nil, nil, {} + st.miN, st.pred = 0, nil + st.segMap = table.create(mbw * mbh, 0) + end + -- key frames reset the frame context, the segment and loop filter deltas + st.proba = table.clone(COEFF_PROBA0) + st.ymodeProb = table.clone(Tables.YMODE_PROB) + st.uvmodeProb = table.clone(Tables.UVMODE_PROB) + st.mvProb = table.clone(Tables.MV_DEFAULT) + st.segProba = { 255, 255, 255 } + st.useSegment, st.updateMap, st.absoluteDelta = false, false, false + st.segQuant = { 0, 0, 0, 0 } + st.segFilter = { 0, 0, 0, 0 } + st.refLfDelta = { 0, 0, 0, 0 } + st.modeLfDelta = { 0, 0, 0, 0 } + st.signBias = { 0, 0, 0, 0 } + end + local br = newBr(buf, p, hdr.partitionLength) + p =p+ hdr.partitionLength + left =left- hdr.partitionLength + if key then + getValue(br, 1) -- colour space + getValue(br, 1) -- clamping type + end + -- segment header + st.useSegment = getValue(br, 1) == 1 + if st.useSegment then + st.updateMap = getValue(br, 1) == 1 + if getValue(br, 1) == 1 then + st.absoluteDelta = getValue(br, 1) == 1 + for s = 1, 4 do + st.segQuant[s] = (getValue(br, 1) == 1 and{(getSignedValue(br, 7) )}or{0 +})[1] end + for s = 1, 4 do + st.segFilter[s] = (getValue(br, 1) == 1 and{(getSignedValue(br, 6) )}or{0 +})[1] end + end + if st.updateMap then + for s = 1, 3 do + st.segProba[s] = (getValue(br, 1) == 1 and{(getValue(br, 8) )}or{255 +})[1] end + end + else + st.updateMap = false + end + if br.eof then + return nil, "truncated: segment header" + end + -- filter header + local simple = getValue(br, 1) == 1 + local level = getValue(br, 6) + local sharpness = getValue(br, 3) + local useLfDelta = getValue(br, 1) == 1 + if useLfDelta then + if getValue(br, 1) == 1 then + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.refLfDelta[i] = getSignedValue(br, 6) + end + end + for i = 1, 4 do + if getValue(br, 1) == 1 then + st.modeLfDelta[i] = getSignedValue(br, 6) + end + end + end + end + local filterType = level == 0 and 0 or(simple and 1 or 2 +) if br.eof then + return nil, "truncated: filter header" + end + -- partitions + local numParts = lshift(1, getValue(br, 2)) + local lastPart = numParts - 1 + if left < 3 * lastPart then + return nil, "truncated: partition sizes" + end + local parts= {} + local partStart = p + lastPart * 3 + local sizeLeft = left - lastPart * 3 + for k = 0, lastPart - 1 do + local q = p + k * 3 + local psize = readu8(buf, q) + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) * 65536 + if psize > sizeLeft then + psize = sizeLeft + end + parts[k + 1] = newBr(buf, partStart, psize) + partStart =partStart+ psize + sizeLeft =sizeLeft- psize + end + parts[numParts] = newBr(buf, partStart, sizeLeft) + if partStart >= off + len then + return nil, "truncated: partitions" + end + -- quantizers + local baseQ = getValue(br, 7) + local dqy1dc = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 +})[1] local dqy2dc = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 +})[1] local dqy2ac = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 +})[1] local dquvdc = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 +})[1] local dquvac = (getValue(br, 1) == 1 and{(getSignedValue(br, 4) )}or{0 +})[1] local quants= {} + for s = 1, 4 do + local q + if st.useSegment then + q = st.segQuant[s] + if not st.absoluteDelta then + q =q+ baseQ + end + else + q = baseQ + end + local function cq(v, m) +return v < 0 and 0 or(v > m and{m }or{v +})[1] end + local y2ac = math.floor((AC_TABLE[cq(q + dqy2ac, 127) + 1] * 101581) / 65536 +) if y2ac < 8 then + y2ac = 8 + end + quants[s] = { + y1dc = DC_TABLE[cq(q + dqy1dc, 127) + 1], + y1ac = AC_TABLE[cq(q, 127) + 1], + y2dc = DC_TABLE[cq(q + dqy2dc, 127) + 1] * 2, + y2ac = y2ac, + uvdc = DC_TABLE[cq(q + dquvdc, 117) + 1], + uvac = AC_TABLE[cq(q + dquvac, 127) + 1], + } + end + -- reference updates (inter frames) + local refreshGolden, refreshAlt, copyToGolden, copyToAlt = true, true, 0, 0 + if not key then + refreshGolden = getValue(br, 1) == 1 + refreshAlt = getValue(br, 1) == 1 + copyToGolden = refreshGolden and 0 or getValue(br, 2) + copyToAlt = refreshAlt and 0 or getValue(br, 2) + st.signBias[3] = getValue(br, 1) + st.signBias[4] = getValue(br, 1) + end + -- a frame that does not refresh the context decodes with the updates below, then the context comes back + local saved= nil + if getValue(br, 1) == 0 then + saved = { table.clone(st.proba), table.clone(st.ymodeProb), table.clone(st.uvmodeProb), table.clone(st.mvProb) } + end + local refreshLast = key or getValue(br, 1) == 1 + -- token probabilities + local P = st.proba + for i = 1, 1056 do + if getBit(br, COEFF_UPDATE_PROBA[i]) == 1 then + P[i] = getValue(br, 8) + end + end + local useSkip = getValue(br, 1) == 1 + local skipP = (useSkip and{(getValue(br, 8) )}or{0 +})[1] local probIntra, probLast, probGf = 0, 0, 0 + if not key then + probIntra = getValue(br, 8) + probLast = getValue(br, 8) + probGf = getValue(br, 8) + if getValue(br, 1) == 1 then + for i = 1, 4 do + st.ymodeProb[i] = getValue(br, 8) + end + end + if getValue(br, 1) == 1 then + for i = 1, 3 do + st.uvmodeProb[i] = getValue(br, 8) + end + end + local M = st.mvProb + for i = 1, 38 do + if getBit(br, MV_UPDATE[i]) == 1 then + local x = getValue(br, 7) + M[i] = x == 0 and 1 or x * 2 + end + end + end + local function fail(msg) +if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return nil, msg + end + if br.eof then + return fail("truncated: frame header") + end + + -- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold + local lvlTab = table.create(64, 0) + local ilTab, hevTab = table.create(64, 0), table.create(64, 0) + if filterType > 0 then + for s = 0, 3 do + local base + if st.useSegment then + base = st.segFilter[s + 1] + if not st.absoluteDelta then + base =base+ level + end + else + base = level + end + for rf = 0, 3 do + for m = 0, 3 do + local lv = base + if useLfDelta then + lv =lv+ st.refLfDelta[rf + 1] + if rf > 0 or m == 0 then + lv =lv+ st.modeLfDelta[m + 1] + end + end + lvlTab[s * 16 + rf * 4 + m + 1] = lv < 0 and 0 or(lv > 63 and 63 or lv +) end + end + end + for lv = 1, 63 do + local il = lv + if sharpness > 0 then + il = rshift(il, sharpness > 4 and 2 or 1) + if il > 9 - sharpness then + il = 9 - sharpness + end + end + ilTab[lv] = il < 1 and 1 or il + if key then + hevTab[lv] = lv >= 40 and 2 or(lv >= 15 and 1 or 0 +) else + hevTab[lv] = lv >= 40 and 3 or(lv >= 20 and 2 or(lv >= 15 and 1 or 0 +)) end + end + end + + -- the frame buffer (macroblock aligned, with a border) and the references + local cur = freeRef(st) + cur.extended = false + local Y, U, V, ys, uvs, yb, uvb = cur.Y, cur.U, cur.V, cur.ys, cur.uvs, cur.yb, cur.uvb + local refs= {} + local bil, full = hdr.profile > 0, hdr.profile == 3 + if not key then + local rl, rg, ra = st.last , st.golden , st.alt +refs[1], refs[2], refs[3] = rl, rg, ra + for k = 1, 3 do + local r = refs[k] + if not r.extended then + Predict.extend(r) + r.extended = true + end + end + end + local topY, topU, topV = bcreate(mbw * 16), bcreate(mbw * 8), bcreate(mbw * 8) + local yuv = bcreate(YUV_SIZE) + local pred = yuv + if not key then + local nmi = (mbw + 1) * (mbh + 1) + if st.miN ~= nmi then + -- zero top row and left column: never written, they read as intra macroblocks without motion + st.miRef, st.miMode = table.create(nmi, 0), table.create(nmi, 0) + st.miMvR, st.miMvC = table.create(nmi, 0), table.create(nmi, 0) + st.miSubR, st.miSubC = table.create(nmi * 16, 0), table.create(nmi * 16, 0) + st.miN = nmi + st.pred = bcreate(YUV_SIZE * mbw) + end + pred = st.pred +end + local coeffs = bcreate(mbw * 768) + local dcb = bcreate(32) + -- per macroblock column / row state + local intraT = table.create(mbw * 4, 0) + local intraL = table.create(4, 0) + local topNz = table.create(mbw, 0) + local topNzDc = table.create(mbw, 0) + local rows= { + i4 = table.create(mbw, false), + modes = table.create(mbw * 16, 0), + uv = table.create(mbw, 0), + ref = table.create(mbw, 0), + mode = table.create(mbw, 0), + part = table.create(mbw, -1), + } + local mbI4, mbModes, mbUv, mbRef, mbMode, mbPart = rows.i4, rows.modes, rows.uv, rows.ref, rows.mode, rows.part + local mbSeg = table.create(mbw, 0) + local mbSkip = table.create(mbw, 0) + local mbNzY = table.create(mbw, 0) + local mbNzUv = table.create(mbw, 0) + -- filter info for the whole frame: limit, ilevel, inner, hev per macroblock + local fLimit = table.create(mbw * mbh, 0) + local fIlevel = table.create(mbw * mbh, 0) + local fInner = table.create(mbw * mbh, 0) + local fHev = table.create(mbw * mbh, 0) + local segProba = st.segProba + local segMap = st.segMap + local updateMap = st.updateMap + local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC + + for mby = 0, mbh - 1 do + local tbr = parts[band(mby, lastPart) + 1] + -- modes of the row (first partition) + for k = 1, 4 do + intraL[k] = 0 + end + for mbx = 0, mbw - 1 do +local __DARKLUA_CONTINUE_55=false repeat local x1 = mbx + 1 + local si = mby * mbw + x1 + local seg + if updateMap then + if getBit(br, segProba[1]) == 0 then + seg = getBit(br, segProba[2]) + else + seg = getBit(br, segProba[3]) + 2 + end + segMap[si] = seg + elseif key then + seg = 0 + segMap[si] = 0 + else + seg = segMap[si] + end + mbSeg[x1] = seg + mbSkip[x1] = 0 + if useSkip then + mbSkip[x1] = getBit(br, skipP) + end + if not key then + readInterMb(st, br, probIntra, probLast, probGf, (mby + 1) * (mbw + 1) + x1 + 1, mbx, mby, rows) +__DARKLUA_CONTINUE_55=true break + end + mbRef[x1] = 0 + mbPart[x1] = -1 + local i4 = getBit(br, 145) == 0 + mbI4[x1] = i4 + local t0 = mbx * 4 + if not i4 then + local ymode + if getBit(br, 156) == 1 then + ymode = getBit(br, 128) == 1 and 1 or 3 + else + ymode = getBit(br, 163) == 1 and 2 or 0 + end + mbModes[mbx * 16 + 1] = ymode + mbMode[x1] = ymode + for k = 1, 4 do + intraT[t0 + k] = ymode + intraL[k] = ymode + end + else + mbMode[x1] = 4 + for y = 0, 3 do + local ymode = intraL[y + 1] + for x = 0, 3 do + local pr = (intraT[t0 + x + 1] * 10 + ymode) * 9 + if getBit(br, BMODES_PROBA[pr + 1]) == 0 then + ymode = 0 + elseif getBit(br, BMODES_PROBA[pr + 2]) == 0 then + ymode = 1 + elseif getBit(br, BMODES_PROBA[pr + 3]) == 0 then + ymode = 2 + elseif getBit(br, BMODES_PROBA[pr + 4]) == 0 then + if getBit(br, BMODES_PROBA[pr + 5]) == 0 then + ymode = 3 + elseif getBit(br, BMODES_PROBA[pr + 6]) == 0 then + ymode = 4 + else + ymode = 5 + end + elseif getBit(br, BMODES_PROBA[pr + 7]) == 0 then + ymode = 6 + elseif getBit(br, BMODES_PROBA[pr + 8]) == 0 then + ymode = 7 + elseif getBit(br, BMODES_PROBA[pr + 9]) == 0 then + ymode = 8 + else + ymode = 9 + end + intraT[t0 + x + 1] = ymode + mbModes[mbx * 16 + y * 4 + x + 1] = ymode + end + intraL[y + 1] = ymode + end + end + if getBit(br, 142) == 0 then + mbUv[x1] = 0 + elseif getBit(br, 114) == 0 then + mbUv[x1] = 2 + else + mbUv[x1] = getBit(br, 183) == 1 and 1 or 3 + end +__DARKLUA_CONTINUE_55=true until true if not __DARKLUA_CONTINUE_55 then break end end + if br.eof then + return fail("truncated: first partition (modes)") + end + + -- residuals (token partition) + local leftNz, leftNzDc = 0, 0 + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local q = quants[mbSeg[x1] + 1] + local skip = mbSkip[x1] + local i4 = mbI4[x1] + if skip == 0 then + local co = mbx * 768 + bfill(coeffs, co, 0, 768) + local first, acType + local dcNz = 0 + if not i4 then + bfill(dcb, 0, 0, 32) + local ctx = topNzDc[x1] + leftNzDc + local nz = getCoeffs(tbr, P, 1, ctx, q.y2dc, q.y2ac, 0, dcb, 0) + dcNz = nz > 0 and 1 or 0 + topNzDc[x1] = dcNz + leftNzDc = dcNz + if nz > 1 then + transformWHT(dcb, coeffs, co) + else + local dc0 = math.floor((readi16(dcb, 0) + 3) / 8 +) for i = 0, 15 do + writei16(coeffs, co + i * 32, dc0) + end + end + first, acType = 1, 0 + else + first, acType = 0, 3 + end + local tnz = band(topNz[x1], 0x0f) + local lnz = band(leftNz, 0x0f) + local nzY = 0 + local dst = co + for _ = 0, 3 do + local l = band(lnz, 1) + local acc = 0 + for _ = 0, 3 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, acType, ctx, q.y1dc, q.y1ac, first, coeffs, dst) + l = nz > first and 1 or 0 + tnz = bor(rshift(tnz, 1), l * 128) + acc = nzCode(acc, nz, readi16(coeffs, dst) ~= 0 and 1 or 0) + dst =dst+ 32 + end + tnz = rshift(tnz, 4) + lnz = bor(rshift(lnz, 1), l * 128) + nzY = nzY * 256 + acc + end + local outT = tnz + local outL = rshift(lnz, 4) + local nzUv = 0 + for ch = 0, 2, 2 do + local acc = 0 + tnz = band(rshift(topNz[x1], 4 + ch), 255) + lnz = band(rshift(leftNz, 4 + ch), 255) + for _ = 0, 1 do + local l = band(lnz, 1) + for _ = 0, 1 do + local ctx = l + band(tnz, 1) + local nz = getCoeffs(tbr, P, 2, ctx, q.uvdc, q.uvac, 0, coeffs, dst) + l = nz > 0 and 1 or 0 + tnz = bor(rshift(tnz, 1), l * 8) + acc = nzCode(acc, nz, readi16(coeffs, dst) ~= 0 and 1 or 0) + dst =dst+ 32 + end + tnz = rshift(tnz, 2) + lnz = bor(rshift(lnz, 1), l * 32) + end + nzUv = bor(nzUv, lshift(acc, 4 * ch)) + outT = bor(outT, lshift(lshift(tnz, 4), ch)) + outL = bor(outL, lshift(band(lnz, 0xf0), ch)) + end + topNz[x1] = band(outT, 255) + leftNz = band(outL, 255) + mbNzY[x1] = nzY + mbNzUv[x1] = nzUv + -- no coefficient at all (libvpx: eobtotal == 0) skips the inner edges of the loop filter + skip = nzY == 0 and nzUv == 0 and dcNz == 0 and 1 or 0 + else + topNz[x1] = 0 + leftNz = 0 + if not i4 then + topNzDc[x1] = 0 + leftNzDc = 0 + end + mbNzY[x1] = 0 + mbNzUv[x1] = 0 + end + if filterType > 0 then + local lv = lvlTab[mbSeg[x1] * 16 + mbRef[x1] * 4 + MODE_LF[mbMode[x1] + 1] + 1] + local fi = mby * mbw + x1 + if lv > 0 then + local il = ilTab[lv] + fLimit[fi] = 2 * lv + il + fIlevel[fi] = il + fHev[fi] = hevTab[lv] + else + fLimit[fi] = 0 + end + fInner[fi] = (i4 or skip == 0 )and 1 or 0 + end + if tbr.eof then + return fail("truncated: token partition") + end + end + + -- reconstruct the row (libwebp ReconstructRow; inter macroblocks predict from the references) + if not key then + Predict.row(refs , mby, mbw, mbRef, mbPart, miMvR, miMvC, miSubR, miSubC, (mby + 1) * (mbw + 1) + 1, pred, YUV_SIZE, Y_OFF, U_OFF, V_OFF, bil, full) + end + for j = 0, 15 do + writeu8(yuv, Y_OFF + j * BPS - 1, 129) + end + for j = 0, 7 do + writeu8(yuv, U_OFF + j * BPS - 1, 129) + writeu8(yuv, V_OFF + j * BPS - 1, 129) + end + if mby > 0 then + writeu8(yuv, Y_OFF - 1 - BPS, 129) + writeu8(yuv, U_OFF - 1 - BPS, 129) + writeu8(yuv, V_OFF - 1 - BPS, 129) + else + bfill(yuv, Y_OFF - BPS - 1, 127, 16 + 4 + 1) + bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1) + bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1) + end + for mbx = 0, mbw - 1 do + local x1 = mbx + 1 + local co = mbx * 768 + local bits = mbNzY[x1] + local rf = mbRef[x1] + if rf == 0 and mbx > 0 then + -- the left context of an intra macroblock: the previous macroblock's last columns + for j = -1, 15 do + writeu32(yuv, Y_OFF + j * BPS - 4, readu32(yuv, Y_OFF + j * BPS + 12)) + end + for j = -1, 7 do + writeu32(yuv, U_OFF + j * BPS - 4, readu32(yuv, U_OFF + j * BPS + 4)) + writeu32(yuv, V_OFF + j * BPS - 4, readu32(yuv, V_OFF + j * BPS + 4)) + end + end + if mby > 0 then + local t = mbx * 16 + writeu32(yuv, Y_OFF - BPS, readu32(topY, t)) + writeu32(yuv, Y_OFF - BPS + 4, readu32(topY, t + 4)) + writeu32(yuv, Y_OFF - BPS + 8, readu32(topY, t + 8)) + writeu32(yuv, Y_OFF - BPS + 12, readu32(topY, t + 12)) + t = mbx * 8 + writeu32(yuv, U_OFF - BPS, readu32(topU, t)) + writeu32(yuv, U_OFF - BPS + 4, readu32(topU, t + 4)) + writeu32(yuv, V_OFF - BPS, readu32(topV, t)) + writeu32(yuv, V_OFF - BPS + 4, readu32(topV, t + 4)) + end + if rf > 0 then + -- the prediction (Predict.row): luma rows 0..15, then the chroma rows (U and V side by side) + local o = mbx * YUV_SIZE + bcopy(yuv, Y_OFF, pred, o + Y_OFF, 15 * BPS + 16) + bcopy(yuv, U_OFF, pred, o + U_OFF, 7 * BPS + 24) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (math.floor(n / 4)) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + else + if mbI4[x1] then + local tr = Y_OFF - BPS + 16 + if mby > 0 then + if mbx >= mbw - 1 then + writeu32(yuv, tr, readu8(topY, mbx * 16 + 15) * 0x01010101) + else + writeu32(yuv, tr, readu32(topY, mbx * 16 + 16)) + end + end + local trv = readu32(yuv, tr) + writeu32(yuv, tr + 4 * BPS, trv) + writeu32(yuv, tr + 8 * BPS, trv) + writeu32(yuv, tr + 12 * BPS, trv) + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (math.floor(n / 4)) * 4 * BPS + predict4(yuv, dst, mbModes[mbx * 16 + n + 1]) + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + else + predictBlock(yuv, Y_OFF, 16, checkMode(mbx, mby, mbModes[mbx * 16 + 1])) + if bits ~= 0 then + for n = 0, 15 do + local dst = Y_OFF + (n % 4) * 4 + (math.floor(n / 4)) * 4 * BPS + doTransform(band(rshift(bits, 30 - 2 * n), 3), coeffs, co + n * 32, yuv, dst) + end + end + end + local uvm = checkMode(mbx, mby, mbUv[x1]) + predictBlock(yuv, U_OFF, 8, uvm) + predictBlock(yuv, V_OFF, 8, uvm) + end + local buv = mbNzUv[x1] + doUVTransform(buv, coeffs, co + 16 * 32, yuv, U_OFF) + doUVTransform(rshift(buv, 8), coeffs, co + 20 * 32, yuv, V_OFF) + if mby < mbh - 1 then + local t = mbx * 16 + local r = Y_OFF + 15 * BPS + writeu32(topY, t, readu32(yuv, r)) + writeu32(topY, t + 4, readu32(yuv, r + 4)) + writeu32(topY, t + 8, readu32(yuv, r + 8)) + writeu32(topY, t + 12, readu32(yuv, r + 12)) + t = mbx * 8 + r = U_OFF + 7 * BPS + writeu32(topU, t, readu32(yuv, r)) + writeu32(topU, t + 4, readu32(yuv, r + 4)) + writeu32(topV, t, readu32(yuv, r + 16)) + writeu32(topV, t + 4, readu32(yuv, r + 20)) + end + local yo = yb + mby * 16 * ys + mbx * 16 + for j = 0, 15 do + local d, r = yo + j * ys, Y_OFF + j * BPS + writeu32(Y, d, readu32(yuv, r)) + writeu32(Y, d + 4, readu32(yuv, r + 4)) + writeu32(Y, d + 8, readu32(yuv, r + 8)) + writeu32(Y, d + 12, readu32(yuv, r + 12)) + end + local uo = uvb + mby * 8 * uvs + mbx * 8 + for j = 0, 7 do + local d, r = uo + j * uvs, U_OFF + j * BPS + writeu32(U, d, readu32(yuv, r)) + writeu32(U, d + 4, readu32(yuv, r + 4)) + writeu32(V, d, readu32(yuv, r + 16)) + writeu32(V, d + 4, readu32(yuv, r + 20)) + end + end + end + + -- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter) + if filterType > 0 then + for mby = 0, mbh - 1 do + for mbx = 0, mbw - 1 do + local fi = mby * mbw + mbx + 1 + local limit = fLimit[fi] + if limit ~= 0 then + local inner = fInner[fi] == 1 + local yp = yb + mby * 16 * ys + mbx * 16 + if filterType == 1 then + if mbx > 0 then + simpleFilter(Y, yp, 1, ys, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k, 1, ys, limit) + end + end + if mby > 0 then + simpleFilter(Y, yp, ys, 1, limit + 4) + end + if inner then + for k = 1, 3 do + simpleFilter(Y, yp + 4 * k * ys, ys, 1, limit) + end + end + else + local il, hev = fIlevel[fi], fHev[fi] + local up = uvb + mby * 8 * uvs + mbx * 8 + if mbx > 0 then + filterEdge(Y, yp, 1, ys, 16, limit + 4, il, hev) + filterEdge(U, up, 1, uvs, 8, limit + 4, il, hev) + filterEdge(V, up, 1, uvs, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k, 1, ys, 16, limit, il, hev) + end + filterInner(U, up + 4, 1, uvs, 8, limit, il, hev) + filterInner(V, up + 4, 1, uvs, 8, limit, il, hev) + end + if mby > 0 then + filterEdge(Y, yp, ys, 1, 16, limit + 4, il, hev) + filterEdge(U, up, uvs, 1, 8, limit + 4, il, hev) + filterEdge(V, up, uvs, 1, 8, limit + 4, il, hev) + end + if inner then + for k = 1, 3 do + filterInner(Y, yp + 4 * k * ys, ys, 1, 16, limit, il, hev) + end + filterInner(U, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + filterInner(V, up + 4 * uvs, uvs, 1, 8, limit, il, hev) + end + end + end + end + end + end + + -- the references (libvpx swap_frame_buffers; copies read the references of the previous frame, as ffmpeg does) + if key then + st.last, st.golden, st.alt = cur, cur, cur + st.hasKey = true + else + local oldLast, oldGolden, oldAlt = st.last, st.golden, st.alt + if refreshGolden then + st.golden = cur + elseif copyToGolden == 1 then + st.golden = oldLast + elseif copyToGolden == 2 then + st.golden = oldAlt + end + if refreshAlt then + st.alt = cur + elseif copyToAlt == 1 then + st.alt = oldLast + elseif copyToAlt == 2 then + st.alt = oldGolden + end + if refreshLast then + st.last = cur + end + end + if saved then + st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4] + end + return { width = width, height = height, ref = cur, header = hdr }, nil +end + +return Decode +end +__FILES["codecs/image/Vp8/Predict"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the +-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the +-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and +-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels +-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the +-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a +-- block whose taps leave it is first copied with clamped coordinates. Never throws. +local Tables = __include("codecs/image/Vp8/Tables") + +local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local rshift, band = bit32.rshift, bit32.band +local SIX, BIL = Tables.SIXTAP, Tables.BILINEAR + +local Predict = {} + +local BORDER = 32 +Predict.BORDER = BORDER + +-- the work buffer stride (codecs/image/Vp8/Decode: BPS) +local BPS = 32 + +local emu = bcreate(32 * 32) -- a block with its taps, edges replicated +local tmp = bcreate(32 * 32) -- the first (horizontal) pass of a two-dimensional filter + +-- the six-tap filter along rows: dst[i] = clamp((sum of src[i - 2 .. i + 3] * taps + 64) >> 7). Each output reads +-- its six pixels (a sliding window of locals is no faster in Luau and stops LuaJIT's register allocator). +local function sixH(src, so, ss, dst, d, ds, w, h, f) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + for _ = 1, h do + for i = so - 2, so + w - 3 do + local v = readu8(src, i) * t0 + readu8(src, i + 1) * t1 + readu8(src, i + 2) * t2 + readu8(src, i + 3) * t3 + + readu8(src, i + 4) * t4 + readu8(src, i + 5) * t5 + 64 + writeu8(dst, d + i - so + 2, v < 0 and 0 or(v >= 32768 and 255 or rshift(v, 7))) + end + so =so+ ss + d =d+ ds + end +end + +-- the six-tap filter along columns +local function sixV(src, so, ss, dst, d, ds, w, h, f) + local k = f * 6 + local t0, t1, t2, t3, t4, t5 = SIX[k + 1], SIX[k + 2], SIX[k + 3], SIX[k + 4], SIX[k + 5], SIX[k + 6] + local s1, s2, s3 = ss, 2 * ss, 3 * ss + for _ = 1, h do + local p = so - s2 + for i = 0, w - 1 do + local q = p + i + local v = readu8(src, q) * t0 + readu8(src, q + s1) * t1 + readu8(src, q + s2) * t2 + readu8(src, q + s3) * t3 + + readu8(src, q + s2 + s2) * t4 + readu8(src, q + s2 + s3) * t5 + 64 + writeu8(dst, d + i, v < 0 and 0 or(v >= 32768 and 255 or rshift(v, 7))) + end + so =so+ ss + d =d+ ds + end +end + +-- the bilinear filters: dst[i] = (src[i] * t0 + src[i + 1] * t1 + 64) >> 7 +local function bilH(src, so, ss, dst, d, ds, w, h, f) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + i + 1) * t1 + 64, 7)) + end + so =so+ ss + d =d+ ds + end +end + +local function bilV(src, so, ss, dst, d, ds, w, h, f) + local t0, t1 = BIL[f * 2 + 1], BIL[f * 2 + 2] + for _ = 1, h do + for i = 0, w - 1 do + writeu8(dst, d + i, rshift(readu8(src, so + i) * t0 + readu8(src, so + ss + i) * t1 + 64, 7)) + end + so =so+ ss + d =d+ ds + end +end + +-- block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil): predicts the w x h block at plane pixel +-- (x, y) moved by (mvx, mvy) eighth pixels into dst at d (stride BPS). base: the offset of plane pixel (0, 0); wmax, +-- hmax: the last pixel column / row of the (macroblock aligned) plane. +local function block(src, stride, base, wmax, hmax, x, y, mvx, mvy, w, h, dst, d, bil) + local fx, fy = band(mvx, 7), band(mvy, 7) + local px, py = x + math.floor((mvx - fx) / 8), y + math.floor((mvy - fy) / 8 +) local sb, so, ss = src, 0, stride + if px >= 2 - BORDER and py >= 2 - BORDER and px + w + 3 <= wmax + 1 + BORDER and py + h + 3 <= hmax + 1 + BORDER then + so = base + py * stride + px + else + for r = 0, h + 4 do + local sy = py - 2 + r + if sy < 0 then + sy = 0 + elseif sy > hmax then + sy = hmax + end + local row = base + sy * stride + local o = r * 32 + for c = 0, w + 4 do + local sx = px - 2 + c + if sx < 0 then + sx = 0 + elseif sx > wmax then + sx = wmax + end + writeu8(emu, o + c, readu8(src, row + sx)) + end + end + sb, so, ss = emu, 66, 32 + end + if fx == 0 then + if fy == 0 then + for _ = 1, h do + for i = 0, w - 4, 4 do + writeu32(dst, d + i, readu32(sb, so + i)) + end + so =so+ ss + d =d+ BPS + end + elseif bil then + bilV(sb, so, ss, dst, d, BPS, w, h, fy) + else + sixV(sb, so, ss, dst, d, BPS, w, h, fy) + end + elseif fy == 0 then + if bil then + bilH(sb, so, ss, dst, d, BPS, w, h, fx) + else + sixH(sb, so, ss, dst, d, BPS, w, h, fx) + end + elseif bil then + bilH(sb, so, ss, tmp, 0, 32, w, h + 1, fx) + bilV(tmp, 0, 32, dst, d, BPS, w, h, fy) + else + sixH(sb, so - 2 * ss, ss, tmp, 0, 32, w, h + 5, fx) + sixV(tmp, 64, 32, dst, d, BPS, w, h, fy) + end +end + +local function chroma16(v) -- the chroma vector of a whole macroblock: half the luma one, rounded away from zero + +if v < 0 then + return -(math.floor((1 - v) / 2)) + end + return math.floor((v + 1) / 2 +)end + +local function chroma4(s) -- the chroma vector of a 2x2 group of luma blocks: the sum of their 4 vectors / 8, rounded half away from zero + +if s < 0 then + return -(math.floor((4 - s) / 8)) + end + return math.floor((s + 4) / 8 +)end + +-- mb(ref, mbx, mby, mvr, mvc, split, subR, subC, sb, dst, yo, uo, vo, bil, full): the prediction of one inter +-- macroblock into the work buffer (luma at yo, chroma at uo / vo). Not split: one vector (mvr, mvc) in eighth pixels; +-- split: the 16 block vectors subR / subC[sb + 1 .. sb + 16] (part < 3: the four 8x8 quarters share them). + + + + + + + + + + + + +function Predict.mb(ref, mbx, mby, mvr, mvc, part, subR, subC, sb, dst, yo, uo, vo, bil, full) + local Y, U, V, ys, uvs, yb, uvb = ref.Y, ref.U, ref.V, ref.ys, ref.uvs, ref.yb, ref.uvb + local wl, hl = ref.mbw * 16 - 1, ref.mbh * 16 - 1 + local wc, hc = ref.mbw * 8 - 1, ref.mbh * 8 - 1 + local x, y = mbx * 16, mby * 16 + local cx, cy = mbx * 8, mby * 8 + if part < 0 then + block(Y, ys, yb, wl, hl, x, y, mvc, mvr, 16, 16, dst, yo, bil) + local cr, cc = chroma16(mvr), chroma16(mvc) + if full then + cr =cr- band(cr, 7) + cc =cc- band(cc, 7) + end + block(U, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, uo, bil) + block(V, uvs, uvb, wc, hc, cx, cy, cc, cr, 8, 8, dst, vo, bil) + return + end + if part < 3 then + for q = 0, 3 do + local bx, by = (q % 2) * 8, (math.floor(q / 2)) * 8 + local k = sb + by + math.floor(bx / 4 )+ 1 + block(Y, ys, yb, wl, hl, x + bx, y + by, subC[k], subR[k], 8, 8, dst, yo + by * BPS + bx, bil) + end + else + for b = 0, 15, 2 do + local k = sb + b + 1 + local bx, by = (b % 4) * 4, (math.floor(b / 4)) * 4 + local r0, c0 = subR[k], subC[k] + if r0 == subR[k + 1] and c0 == subC[k + 1] then + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 8, 4, dst, yo + by * BPS + bx, bil) + else + block(Y, ys, yb, wl, hl, x + bx, y + by, c0, r0, 4, 4, dst, yo + by * BPS + bx, bil) + block(Y, ys, yb, wl, hl, x + bx + 4, y + by, subC[k + 1], subR[k + 1], 4, 4, dst, yo + by * BPS + bx + 4, bil) + end + end + end + for i = 0, 1 do + local rr, rc = 0, 0 + for j = 0, 1 do + local k = sb + i * 8 + j * 2 + 1 + local cr = chroma4(subR[k] + subR[k + 1] + subR[k + 4] + subR[k + 5]) + local cc = chroma4(subC[k] + subC[k + 1] + subC[k + 4] + subC[k + 5]) + if full then + cr =cr- band(cr, 7) + cc =cc- band(cc, 7) + end + if j == 0 then + rr, rc = cr, cc + elseif cr == rr and cc == rc then + -- both 4x4 chroma blocks of the row share one vector: one 8x4 block + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, cc, cr, 8, 4, dst, vo + i * 4 * BPS, bil) + else + block(U, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, uo + i * 4 * BPS, bil) + block(V, uvs, uvb, wc, hc, cx, cy + i * 4, rc, rr, 4, 4, dst, vo + i * 4 * BPS, bil) + block(U, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, uo + i * 4 * BPS + 4, bil) + block(V, uvs, uvb, wc, hc, cx + 4, cy + i * 4, cc, cr, 4, 4, dst, vo + i * 4 * BPS + 4, bil) + end + end + end +end + +-- row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full): predicts the +-- inter macroblocks of a row (ref[mbx + 1] > 0: refs[ref]) into pred, macroblock mbx at mbx * chunk + yo / uo / vo; +-- mi0 + mbx + 1: the mode info index of macroblock mbx. A loop of its own (LuaJIT traces it apart from the decoder). +function Predict.row(refs, mby, mbw, ref, part, miMvR, miMvC, miSubR, miSubC, mi0, pred, chunk, yo, uo, vo, bil, full) + for mbx = 0, mbw - 1 do + local rf = ref[mbx + 1] + if rf > 0 then + local mi = mi0 + mbx + 1 + local o = mbx * chunk + Predict.mb(refs[rf], mbx, mby, miMvR[mi], miMvC[mi], part[mbx + 1], miSubR, miSubC, (mi - 1) * 16, pred, o + yo, o + uo, o + vo, bil, full) + end + end +end + +-- extend(P, stride, base, w, h): fills the BORDER pixels around a w x h plane with its edge pixels +local function extend(P, stride, base, w, h) + for r = 0, h - 1 do + local o = base + r * stride + bfill(P, o - BORDER, readu8(P, o), BORDER) + bfill(P, o + w, readu8(P, o + w - 1), BORDER) + end + local top = base - BORDER + local bottom = base + (h - 1) * stride - BORDER + for r = 1, BORDER do + bcopy(P, top - r * stride, P, top, stride) + bcopy(P, bottom + r * stride, P, bottom, stride) + end +end + +function Predict.extend(ref) + extend(ref.Y, ref.ys, ref.yb, ref.mbw * 16, ref.mbh * 16) + extend(ref.U, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) + extend(ref.V, ref.uvs, ref.uvb, ref.mbw * 8, ref.mbh * 8) +end + +return Predict +end +__FILES["codecs/image/Vp8/Tables"] = function() +--!strict +-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6 +-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables +-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from +-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c; +-- BSD-3-Clause, licenses/libvpx-LICENSE.txt). Flat 1-based arrays. +local Tables = {} + +-- default token probabilities [type 4][band 8][ctx 3][proba 11]: index ((t * 8 + b) * 3 + c) * 11 + p + 1 +Tables.COEFF_PROBA0 = { + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128, + 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128, 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128, + 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128, 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128, + 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128, 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128, + 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128, 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128, + 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128, 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128, + 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128, 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128, + 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128, 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128, + 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128, 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128, + 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62, 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1, + 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128, 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128, + 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128, 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128, + 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128, 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128, + 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128, 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128, + 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128, 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128, + 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128, 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128, + 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128, 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128, + 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128, 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128, + 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128, 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128, + 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128, 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128, + 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128, 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128, + 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128, 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128, + 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128, 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128, + 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128, 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128, + 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128, 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128, + 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128, 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128, + 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128, 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128, + 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128, 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128, + 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128, 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128, 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128, + 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255, 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128, + 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128, 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128, + 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128, 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128, + 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128, 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128, + 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128, 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128, + 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128, 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128, + 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128, 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128, + 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128, 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128, + 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128, 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128, + 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128, 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128, + 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128, 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, + 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128, +} +-- token probability update probabilities, same layout +Tables.COEFF_UPDATE_PROBA = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255, 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255, 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255, 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255, + 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, + 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255, 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255, 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255, + 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255, 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255, + 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255, + 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255, 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255, + 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255, 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} +-- 4x4 intra mode probabilities [top 10][left 10][9]: index (top * 10 + left) * 9 + i + 1 +Tables.BMODES_PROBA = { + 231, 120, 48, 89, 115, 113, 120, 152, 112, 152, 179, 64, 126, 170, 118, 46, 70, 95, 175, 69, 143, 80, + 85, 82, 72, 155, 103, 56, 58, 10, 171, 218, 189, 17, 13, 152, 114, 26, 17, 163, 44, 195, 21, 10, + 173, 121, 24, 80, 195, 26, 62, 44, 64, 85, 144, 71, 10, 38, 171, 213, 144, 34, 26, 170, 46, 55, + 19, 136, 160, 33, 206, 71, 63, 20, 8, 114, 114, 208, 12, 9, 226, 81, 40, 11, 96, 182, 84, 29, + 16, 36, 134, 183, 89, 137, 98, 101, 106, 165, 148, 72, 187, 100, 130, 157, 111, 32, 75, 80, 66, 102, + 167, 99, 74, 62, 40, 234, 128, 41, 53, 9, 178, 241, 141, 26, 8, 107, 74, 43, 26, 146, 73, 166, + 49, 23, 157, 65, 38, 105, 160, 51, 52, 31, 115, 128, 104, 79, 12, 27, 217, 255, 87, 17, 7, 87, + 68, 71, 44, 114, 51, 15, 186, 23, 47, 41, 14, 110, 182, 183, 21, 17, 194, 66, 45, 25, 102, 197, + 189, 23, 18, 22, 88, 88, 147, 150, 42, 46, 45, 196, 205, 43, 97, 183, 117, 85, 38, 35, 179, 61, + 39, 53, 200, 87, 26, 21, 43, 232, 171, 56, 34, 51, 104, 114, 102, 29, 93, 77, 39, 28, 85, 171, + 58, 165, 90, 98, 64, 34, 22, 116, 206, 23, 34, 43, 166, 73, 107, 54, 32, 26, 51, 1, 81, 43, + 31, 68, 25, 106, 22, 64, 171, 36, 225, 114, 34, 19, 21, 102, 132, 188, 16, 76, 124, 62, 18, 78, + 95, 85, 57, 50, 48, 51, 193, 101, 35, 159, 215, 111, 89, 46, 111, 60, 148, 31, 172, 219, 228, 21, + 18, 111, 112, 113, 77, 85, 179, 255, 38, 120, 114, 40, 42, 1, 196, 245, 209, 10, 25, 109, 88, 43, + 29, 140, 166, 213, 37, 43, 154, 61, 63, 30, 155, 67, 45, 68, 1, 209, 100, 80, 8, 43, 154, 1, + 51, 26, 71, 142, 78, 78, 16, 255, 128, 34, 197, 171, 41, 40, 5, 102, 211, 183, 4, 1, 221, 51, + 50, 17, 168, 209, 192, 23, 25, 82, 138, 31, 36, 171, 27, 166, 38, 44, 229, 67, 87, 58, 169, 82, + 115, 26, 59, 179, 63, 59, 90, 180, 59, 166, 93, 73, 154, 40, 40, 21, 116, 143, 209, 34, 39, 175, + 47, 15, 16, 183, 34, 223, 49, 45, 183, 46, 17, 33, 183, 6, 98, 15, 32, 183, 57, 46, 22, 24, + 128, 1, 54, 17, 37, 65, 32, 73, 115, 28, 128, 23, 128, 205, 40, 3, 9, 115, 51, 192, 18, 6, + 223, 87, 37, 9, 115, 59, 77, 64, 21, 47, 104, 55, 44, 218, 9, 54, 53, 130, 226, 64, 90, 70, + 205, 40, 41, 23, 26, 57, 54, 57, 112, 184, 5, 41, 38, 166, 213, 30, 34, 26, 133, 152, 116, 10, + 32, 134, 39, 19, 53, 221, 26, 114, 32, 73, 255, 31, 9, 65, 234, 2, 15, 1, 118, 73, 75, 32, + 12, 51, 192, 255, 160, 43, 51, 88, 31, 35, 67, 102, 85, 55, 186, 85, 56, 21, 23, 111, 59, 205, + 45, 37, 192, 55, 38, 70, 124, 73, 102, 1, 34, 98, 125, 98, 42, 88, 104, 85, 117, 175, 82, 95, + 84, 53, 89, 128, 100, 113, 101, 45, 75, 79, 123, 47, 51, 128, 81, 171, 1, 57, 17, 5, 71, 102, + 57, 53, 41, 49, 38, 33, 13, 121, 57, 73, 26, 1, 85, 41, 10, 67, 138, 77, 110, 90, 47, 114, + 115, 21, 2, 10, 102, 255, 166, 23, 6, 101, 29, 16, 10, 85, 128, 101, 196, 26, 57, 18, 10, 102, + 102, 213, 34, 20, 43, 117, 20, 15, 36, 163, 128, 68, 1, 26, 102, 61, 71, 37, 34, 53, 31, 243, + 192, 69, 60, 71, 38, 73, 119, 28, 222, 37, 68, 45, 128, 34, 1, 47, 11, 245, 171, 62, 17, 19, + 70, 146, 85, 55, 62, 70, 37, 43, 37, 154, 100, 163, 85, 160, 1, 63, 9, 92, 136, 28, 64, 32, + 201, 85, 75, 15, 9, 9, 64, 255, 184, 119, 16, 86, 6, 28, 5, 64, 255, 25, 248, 1, 56, 8, + 17, 132, 137, 255, 55, 116, 128, 58, 15, 20, 82, 135, 57, 26, 121, 40, 164, 50, 31, 137, 154, 133, + 25, 35, 218, 51, 103, 44, 131, 131, 123, 31, 6, 158, 86, 40, 64, 135, 148, 224, 45, 183, 128, 22, + 26, 17, 131, 240, 154, 14, 1, 209, 45, 16, 21, 91, 64, 222, 7, 1, 197, 56, 21, 39, 155, 60, + 138, 23, 102, 213, 83, 12, 13, 54, 192, 255, 68, 47, 28, 85, 26, 85, 85, 128, 128, 32, 146, 171, + 18, 11, 7, 63, 144, 171, 4, 4, 246, 35, 27, 10, 146, 174, 171, 12, 26, 128, 190, 80, 35, 99, + 180, 80, 126, 54, 45, 85, 126, 47, 87, 176, 51, 41, 20, 32, 101, 75, 128, 139, 118, 146, 116, 128, + 85, 56, 41, 15, 176, 236, 85, 37, 9, 62, 71, 30, 17, 119, 118, 255, 17, 18, 138, 101, 38, 60, + 138, 55, 70, 43, 26, 142, 146, 36, 19, 30, 171, 255, 97, 27, 20, 138, 45, 61, 62, 219, 1, 81, + 188, 64, 32, 41, 20, 117, 151, 142, 20, 21, 163, 112, 19, 12, 61, 195, 128, 48, 4, 24, +} +-- DC dequantization factors, index q + 1 (q 0..127) +Tables.DC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, + 22, 22, 23, 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, + 116, 118, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +} +-- AC dequantization factors, index q + 1 +Tables.AC_TABLE = { + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, + 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, + 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, + 205, 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +} +-- coefficient band of each position (with a sentinel for position 16) +Tables.BANDS = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0 } +-- zigzag scan: coefficient n goes to position ZIGZAG[n + 1] +Tables.ZIGZAG = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +-- extra bits probabilities for the DCT_CAT3..6 tokens +Tables.CAT3 = { 173, 148, 140 } +Tables.CAT4 = { 176, 155, 140, 135 } +Tables.CAT5 = { 180, 157, 141, 134, 130 } +Tables.CAT6 = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 } + +-- inter frames: default intra mode probabilities (16x16 / chroma, kept in the frame context) and the fixed 4x4 ones +Tables.YMODE_PROB = { 112, 86, 140, 37 } +Tables.UVMODE_PROB = { 162, 101, 204 } +Tables.BMODE_PROB = { 120, 90, 79, 133, 87, 85, 80, 111, 151 } + +-- motion vector probabilities, row then column (19 each): is short, sign, short tree (7), long bits (10) +Tables.MV_DEFAULT = { + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, 254, +} +Tables.MV_UPDATE = { + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254, + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254, +} + +-- mode contexts [count 0..5][tree node 0..3]: index count * 4 + node + 1 +Tables.MODE_CONTEXTS = { + 7, 1, 1, 143, + 14, 18, 14, 107, + 135, 64, 57, 68, + 60, 56, 128, 65, + 159, 134, 128, 34, + 234, 188, 128, 28, +} + +-- sub-block motion vector reference probabilities [(above zero << 2) | (left zero << 1) | (left == above)][3] +Tables.SUB_MV_REF_PROB = { + 147, 136, 18, + 223, 1, 34, + 106, 145, 1, + 208, 1, 1, + 179, 121, 1, + 223, 1, 34, + 179, 121, 1, + 208, 1, 1, +} + +-- split partitions (16x8, 8x16, 8x8, 4x4): the first block of each partition [s * 16 + j + 1], the blocks of each +-- partition in order [s * 16 + j * count + i + 1], and the number of blocks per partition +Tables.SPLIT_OFFSET = { + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_FILL = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, +} +Tables.SPLIT_COUNT = { 8, 8, 4, 1 } + +-- the six-tap sub-pixel filters [fraction 0..7][tap 0..5] and the bilinear ones [fraction][2] (versions 1-3) +Tables.SIXTAP = { + 0, 0, 128, 0, 0, 0, + 0, -6, 123, 12, -1, 0, + 2, -11, 108, 36, -8, 1, + 0, -9, 93, 50, -6, 0, + 3, -16, 77, 77, -16, 3, + 0, -6, 50, 93, -9, 0, + 1, -8, 36, 108, -11, 2, + 0, -1, 12, 123, -6, 0, +} +Tables.BILINEAR = { 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112 } + +return Tables +end +__FILES["codecs/image/Vp8/Yuv"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the +-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1 +-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6 +-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt). +local rshift = bit32.rshift +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create + +local Yuv = {} + +local function clip(v) -- VP8Clip8: v in 14-bit fixed point + +if v >= 0 and v < 16384 then + return rshift(v, 6) + end + return v < 0 and 0 or 255 +end + +-- (v * coeff) >> 8 for non-negative v +local function mulHi(v, c) +return rshift(v * c, 8) +end + +-- rgba(y, u, v) -> the pixel as a little-endian u32 (bytes R G B 255) +local function rgba(y, u, v) +local yy = mulHi(y, 19077) + local r = clip(yy + mulHi(v, 26149) - 14234) + local g = clip(yy - mulHi(u, 6419) - mulHi(v, 13320) + 8708) + local b = clip(yy + mulHi(u, 33050) - 17685) + return r + g * 256 + b * 65536 + 0xff000000 +end +Yuv.rgba = rgba + +-- upsamplePair: libwebp UPSAMPLE_FUNC for one or two output rows. ty / by: offsets of the top / bottom luma rows +-- (by < 0: no bottom row), tu / cu: offsets of the top / current chroma rows; dt / db: output row offsets. +local function upsamplePair(Y, U, V, ty, by, tu, cu, out, dt, db, len) + local last = rshift(len - 1, 1) + local tlu, tlv = readu8(U, tu), readu8(V, tu) + local lu, lv = readu8(U, cu), readu8(V, cu) + do + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt, rgba(readu8(Y, ty), u0, v0)) + end + if by >= 0 then + local u0 = rshift(3 * lu + tlu + 2, 2) + local v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db, rgba(readu8(Y, by), u0, v0)) + end + for x = 1, last do + local tu1, tv1 = readu8(U, tu + x), readu8(V, tu + x) + local u1, v1 = readu8(U, cu + x), readu8(V, cu + x) + local avgU = tlu + tu1 + lu + u1 + 8 + local avgV = tlv + tv1 + lv + v1 + 8 + local d12u = rshift(avgU + 2 * (tu1 + lu), 3) + local d03u = rshift(avgU + 2 * (tlu + u1), 3) + local d12v = rshift(avgV + 2 * (tv1 + lv), 3) + local d03v = rshift(avgV + 2 * (tlv + v1), 3) + local px = 2 * x + writeu32(out, dt + (px - 1) * 4, rgba(readu8(Y, ty + px - 1), rshift(d12u + tlu, 1), rshift(d12v + tlv, 1))) + writeu32(out, dt + px * 4, rgba(readu8(Y, ty + px), rshift(d03u + tu1, 1), rshift(d03v + tv1, 1))) + if by >= 0 then + writeu32(out, db + (px - 1) * 4, rgba(readu8(Y, by + px - 1), rshift(d03u + lu, 1), rshift(d03v + lv, 1))) + writeu32(out, db + px * 4, rgba(readu8(Y, by + px), rshift(d12u + u1, 1), rshift(d12v + v1, 1))) + end + tlu, tlv, lu, lv = tu1, tv1, u1, v1 + end + if len % 2 == 0 then + local u0 = rshift(3 * tlu + lu + 2, 2) + local v0 = rshift(3 * tlv + lv + 2, 2) + writeu32(out, dt + (len - 1) * 4, rgba(readu8(Y, ty + len - 1), u0, v0)) + if by >= 0 then + u0 = rshift(3 * lu + tlu + 2, 2) + v0 = rshift(3 * lv + tlv + 2, 2) + writeu32(out, db + (len - 1) * 4, rgba(readu8(Y, by + len - 1), u0, v0)) + end + end +end + +-- toRgba(y, u, v, w, h, fancy, out?) -> rgba8 (alpha 255). Planes are tightly packed (chroma ceil(w / 2) wide). +function Yuv.toRgba(Y, U, V, w, h, fancy, out) +local o = out or bcreate(w * h * 4) + local cw = math.floor((w + 1) / 2 +) local stride = w * 4 + if fancy then + -- libwebp EmitFancyRGB over the whole picture: row 0 alone (chroma mirrored), then pairs of rows between two + -- chroma rows, then the last row of an even height alone + upsamplePair(Y, U, V, 0, -1, 0, 0, o, 0, -1, w) + local y = 1 + local cu = 0 + while y + 1 < h do + upsamplePair(Y, U, V, y * w, (y + 1) * w, cu, cu + cw, o, y * stride, (y + 1) * stride, w) + cu =cu+ cw + y =y+ 2 + end + if h % 2 == 0 and h > 1 then + upsamplePair(Y, U, V, (h - 1) * w, -1, cu, cu, o, (h - 1) * stride, -1, w) + end + else + for y = 0, h - 1 do + local cu = (math.floor(y / 2)) * cw + local yo = y * w + local oo = y * stride + for x = 0, w - 1 do + local c = cu + math.floor(x / 2 +) writeu32(o, oo + x * 4, rgba(readu8(Y, yo + x), readu8(U, c), readu8(V, c))) + end + end + end + return o +end + +-- setAlpha(rgba, a8, n): copy an alpha plane into the A bytes +function Yuv.setAlpha(o, a, n) + for i = 0, n - 1 do + writeu8(o, i * 4 + 3, readu8(a, i)) + end +end + +return Yuv +end +__FILES["codecs/image/Vp8L"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): +-- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. +-- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new +-- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel +-- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, +-- one prefix code group per image or meta codes for big images). +-- +-- local Vp8L = require("rosetta.codecs.image.Vp8L") +-- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 +-- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) +-- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream +-- +-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). +local Err = __include("core/Err") +local Decode = __include("codecs/image/Vp8L/Decode") +local Encode = __include("codecs/image/Vp8L/Encode") + +local Vp8L = {} + +local DEFAULT_MAX_PIXELS = 2 ^ 28 + +local function fail(msg, offset) +local m = msg or "bad data" + if string.sub(m, 1, 11) == "truncated: " then + return Err.new(Err.TRUNCATED, string.sub(m, 12), offset) + elseif string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8), offset) + end + return Err.new(Err.CORRUPT, m, offset) +end +Vp8L.fail = fail + +local function range(buf, off, len) +local n = buffer.len(buf) + local o = math.clamp(off or 0, 0, n) + return o, math.clamp(len or (n - o), 0, n - o) +end + +-- info(buf, off?, len?) -> { width, height, alpha } | nil, Err: the 5-byte header +function Vp8L.info(buf, off, len) +local o, l = range(buf, off, len) + local w, h, alpha, err = Decode.header(buf, o, l) + if not w then + return nil, fail(err, o) + end + return { width = w, height = h, alpha = alpha }, nil +end + +-- decodeArgb(buf, off?, len?, maxPixels?) -> ARGB u32 pixels (0xAARRGGBB), width, height, alphaHint | nil, Err +function Vp8L.decodeArgb(buf, off, len, maxPixels) +local o, l = range(buf, off, len) + local px, w, h, alpha, err = Decode.argb(buf, o, l, maxPixels or DEFAULT_MAX_PIXELS) + if not px then + return nil, fail(err, o) + end + return px, w, h, alpha +end + +-- decode(buf, off?, len?, maxPixels?) -> rgba8 pixels, width, height, alphaHint | nil, Err +function Vp8L.decode(buf, off, len, maxPixels) +local px, w, h, alpha = Vp8L.decodeArgb(buf, off, len, maxPixels) + if not px then + return nil, w + end + return Decode.toRgba(px, w * (h )), w, h, alpha +end + +-- decodeAlpha(buf, off, len, width, height) -> width * height bytes (the green channel) | nil, Err +function Vp8L.decodeAlpha(buf, off, len, width, height) +local o, l = range(buf, off, len) + local px, err = Decode.stream(buf, o, l, width, height) + if not px then + return nil, fail(err, o) + end + return Decode.green(px, width * height), nil +end + +-- toRgba(argb, n) -> rgba8 bytes of n ARGB pixels +Vp8L.toRgba = Decode.toRgba + +-- encode(rgba, width, height, opts?) -> a VP8L bitstream (signature + header + image stream) | nil, Err + + + + + + +function Vp8L.encode(rgba, width, height, opts) +if type(rgba) ~= "buffer" or type(width) ~= "number" or type(height) ~= "number" then + return nil, Err.new(Err.ARG, "encode: needs rgba8 pixels, width, height") + end + if width < 1 or height < 1 or width > 16384 or height > 16384 or width % 1 ~= 0 or height % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: size must be 1..16384") + end + if buffer.len(rgba) < width * height * 4 then + return nil, Err.new(Err.ARG, "encode: pixel buffer too small") + end + local o= opts or {} +local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "encode: effort must be 0..9") + end + return Encode.encode(rgba, width, height, effort, o.exact == true, o.alphaHint, false), nil +end + +-- encodeAlpha(a8, width, height, opts?) -> a headerless stream of the plane in green (an ALPH payload) +function Vp8L.encodeAlpha(a8, width, height, opts) +if type(a8) ~= "buffer" or buffer.len(a8) < width * height then + return nil, Err.new(Err.ARG, "encodeAlpha: plane too small") + end + local rgba = buffer.create(width * height * 4) + for i = 0, width * height - 1 do + buffer.writeu32(rgba, i * 4, 0xff000000 + buffer.readu8(a8, i) * 256) + end + local effort = opts and opts.effort or 5 + return Encode.encode(rgba, width, height, effort, true, false, true), nil +end + +return Vp8L +end +__FILES["codecs/image/Vp8L/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, +-- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, +-- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, +-- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. +-- +-- Pixels are ARGB u32 values (0xAARRGGBB) in a buffer, 4 bytes each, rows top to bottom. Never throws: every +-- function returns nil, "message" (prefixed "truncated: " when the data ends early) on bad data. +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Decode = {} + +local ROOT_BITS = 8 +local MAX_LEN = 15 +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_CACHE_BITS = 11 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- distance map (x offset 8 - (v & 15), y offset v >> 4) as a plain distance for a row width: done per image +Decode.CODE_TO_PLANE = CODE_TO_PLANE +-- ------------------------------------------------------------------------------------------------ bit reader +-- LSB-first; bytes past the end read as zero and are counted in `over`: the stream is overrun when fewer bits are +-- left in the buffer than phantom bits were added (bitcnt < over * 8). + + + + + + + + + + + + + + +local function fill(d) + local bitbuf, bitcnt = d.bitbuf, d.bitcnt + while bitcnt <= 24 do + local p = d.pos + local b = 0 + if p < d.limit then + b = readu8(d.buf, p) + d.pos = p + 1 + else + d.over =d.over+ 1 + end + bitbuf =bitbuf+ lshift(b, bitcnt) + bitcnt =bitcnt+ 8 + end + d.bitbuf, d.bitcnt = bitbuf, bitcnt +end + +-- readBits(d, n) n <= 24 +local function readBits(d, n) +if d.bitcnt < n then + fill(d) + end + local v = band(d.bitbuf, lshift(1, n) - 1) + d.bitbuf = rshift(d.bitbuf, n) + d.bitcnt =d.bitcnt- n + return v +end + +local function eos(d) +return d.bitcnt < d.over * 8 +end + +-- ------------------------------------------------------------------------------------------------ prefix codes +local count = table.create(MAX_LEN + 1, 0) +local offset = table.create(MAX_LEN + 2, 0) + +local function ensure(d, n) + local cap = math.floor(blen(d.tab) / 4 +) if d.tabUsed + n > cap then + local nb = bcreate(math.max(cap * 2, d.tabUsed + n) * 4) + bcopy(nb, 0, d.tab, 0, d.tabUsed * 4) + d.tab = nb + end +end + +local function replicate(tab, at, step, size, entry) + local e = size + repeat + e =e- step + writeu32(tab, (at + e) * 4, entry) + until e <= 0 +end + +local function nextKey(key, len) +local step = lshift(1, len - 1) + while band(key, step) ~= 0 do + step = rshift(step, 1) + end + return (step ~= 0 and{(band(key, step - 1) + step )}or{key +})[1]end + +-- build(d, lens (0-based Lua array), n) -> table offset in d.tab, or -1 for an invalid code set (libwebp +-- BuildHuffmanTable: complete codes only, except a single used symbol, which reads 0 bits) +local sorted = table.create(2400, 0) +local function build(d, lens, n) +for l = 0, MAX_LEN do + count[l + 1] = 0 + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > MAX_LEN then + return -1 + end +do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 +end end + if count[1] == n then + return -1 + end + offset[2] = 0 + for len = 1, MAX_LEN - 1 do + if count[len + 1] > lshift(1, len) then + return -1 + end + offset[len + 2] = offset[len + 1] + count[len + 1] + end + for s = 0, n - 1 do + local l = lens[s + 1] + if l > 0 then + sorted[offset[l + 1] + 1] = s +do local __DARKLUA_VAR=l + 1 offset[__DARKLUA_VAR]=offset[__DARKLUA_VAR]+ 1 +end end + end + local long = 0 + for len = ROOT_BITS + 1, MAX_LEN do + long =long+ count[len + 1] + end + ensure(d, lshift(1, ROOT_BITS) + long * lshift(1, MAX_LEN - ROOT_BITS)) + local tab = d.tab + local root = d.tabUsed + local totalSize = lshift(1, ROOT_BITS) + if offset[MAX_LEN + 1] == 1 then + replicate(tab, root, 1, totalSize, sorted[1] * 32) + d.tabUsed = root + totalSize + return root + end + local key = 0 + local numNodes, numOpen = 1, 1 + local tableBits = ROOT_BITS + local tableSize = lshift(1, tableBits) + local tableAt = root + local low = -1 + local mask = totalSize - 1 + local symbol = 1 + local step = 2 + for len = 1, ROOT_BITS do + numOpen =numOpen* 2 + numNodes =numNodes+ numOpen + numOpen =numOpen- count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + replicate(tab, root + key, step, tableSize, sorted[symbol] * 32 + len) + symbol =symbol+ 1 + key = nextKey(key, len) +do local __DARKLUA_VAR=len + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]- 1 +end end + step =step* 2 + end + step = 2 + for len = ROOT_BITS + 1, MAX_LEN do + numOpen =numOpen* 2 + numNodes =numNodes+ numOpen + numOpen =numOpen- count[len + 1] + if numOpen < 0 then + return -1 + end + while count[len + 1] > 0 do + if band(key, mask) ~= low then + tableAt =tableAt+ tableSize + -- NextTableBitSize + local l2 = len + local left = lshift(1, l2 - ROOT_BITS) + while l2 < MAX_LEN do + left =left- count[l2 + 1] + if left <= 0 then + break + end + l2 =l2+ 1 + left =left* 2 + end + tableBits = l2 - ROOT_BITS + tableSize = lshift(1, tableBits) + totalSize =totalSize+ tableSize + low = band(key, mask) + writeu32(tab, (root + low) * 4, (tableAt - root - low) * 32 + tableBits + ROOT_BITS) + end + replicate(tab, tableAt + rshift(key, ROOT_BITS), step, tableSize, sorted[symbol] * 32 + len - ROOT_BITS) + symbol =symbol+ 1 + key = nextKey(key, len) +do local __DARKLUA_VAR=len + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]- 1 +end end + step =step* 2 + end + if numNodes ~= 2 * offset[MAX_LEN + 1] - 1 then + return -1 + end + d.tabUsed = root + totalSize + return root +end + +-- readSymbol(d, at) -> symbol (the reader is refilled to >= 15 bits first) +local function readSymbol(d, at) +if d.bitcnt < MAX_LEN then + fill(d) + end + local tab = d.tab + local bitbuf = d.bitbuf + local idx = at + band(bitbuf, 255) + local e = readu32(tab, idx * 4) + local nb = band(e, 31) + if nb > ROOT_BITS then + bitbuf = rshift(bitbuf, ROOT_BITS) + d.bitcnt =d.bitcnt- ROOT_BITS + e = readu32(tab, (idx + rshift(e, 5) + band(bitbuf, lshift(1, nb - ROOT_BITS) - 1)) * 4) + nb = band(e, 31) + end + d.bitbuf = rshift(bitbuf, nb) + d.bitcnt =d.bitcnt- nb + return rshift(e, 5) +end + +local codeLengths = table.create(2400, 0) +local clLens = table.create(19, 0) + +-- readCode(d, alphabetSize) -> table offset, or -1 +local function readCode(d, size) +for i = 1, size do + codeLengths[i] = 0 + end + if readBits(d, 1) == 1 then + local numSymbols = readBits(d, 1) + 1 + local first = readBits(d, 1) + local s = readBits(d, first == 0 and 1 or 8) + if s < size then + codeLengths[s + 1] = 1 + end + if numSymbols == 2 then + s = readBits(d, 8) + if s < size then + codeLengths[s + 1] = 1 + end + end + else + for i = 1, 19 do + clLens[i] = 0 + end + local numCodes = readBits(d, 4) + 4 + for i = 1, numCodes do + clLens[CODE_LENGTH_ORDER[i] + 1] = readBits(d, 3) + end + local mark = d.tabUsed + local clt = build(d, clLens, 19) + if clt < 0 then + return -1 + end + local maxSymbol = size + if readBits(d, 1) == 1 then + local nbits = 2 + 2 * readBits(d, 3) + maxSymbol = 2 + readBits(d, nbits) + if maxSymbol > size then + return -1 + end + end + local prev = 8 + local s = 0 + while s < size do + if maxSymbol == 0 then + break + end + maxSymbol =maxSymbol- 1 + local cl = readSymbol(d, clt) + if cl < 16 then + codeLengths[s + 1] = cl + s =s+ 1 + if cl ~= 0 then + prev = cl + end + else + local rep, len + if cl == 16 then + rep, len = readBits(d, 2) + 3, prev + elseif cl == 17 then + rep, len = readBits(d, 3) + 3, 0 + else + rep, len = readBits(d, 7) + 11, 0 + end + if s + rep > size then + return -1 + end + for k = s + 1, s + rep do + codeLengths[k] = len + end + s =s+ rep + end + end + d.tabUsed = mark -- the code length table is temporary + end + if eos(d) then + return -1 + end + return build(d, codeLengths, size) +end + +-- ------------------------------------------------------------------------------------------------ pixel data +local function subSample(size, bits) +return rshift(size + lshift(1, bits) - 1, bits) +end +Decode.subSample = subSample + +local function cacheKey(argb, shift) -- (0x1e35a7bd * argb) mod 2^32 >> shift, exact in doubles + +local lo = argb % 65536 + local hi = (argb - lo) / 65536 + local m = (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 + return rshift(m, shift) +end +Decode.cacheKey = cacheKey + +-- decodeData: the entropy-coded pixels of one level into `data` (w * h u32) +local function decodeData(d, data, w, h, cacheBits, groups, himg, hbits, hxs) +local total = w * h + local cache= (cacheBits > 0 and{(bcreate(lshift(1, cacheBits) * 4) )}or{nil +})[1] local cshift = 32 - cacheBits + local lenLimit = NUM_LITERAL + NUM_LENGTH + local cacheLimit = lenLimit + ((cacheBits > 0 and{(lshift(1, cacheBits) )}or{0})[1]) + local hmask = (himg and{(lshift(1, hbits) - 1 )}or{(-1 +)})[1] local i, col, row = 0, 0, 0 + local gG, gR, gB, gA, gD = groups[1], groups[2], groups[3], groups[4], groups[5] + local function setGroup() + if himg then + local g = readu32(himg, (hxs * rshift(row, hbits) + rshift(col, hbits)) * 4) * 5 + gG, gR, gB, gA, gD = groups[g + 1], groups[g + 2], groups[g + 3], groups[g + 4], groups[g + 5] + end + end + while i < total do + if band(col, hmask) == 0 then + setGroup() + end + local code = readSymbol(d, gG) + if code < NUM_LITERAL then + local r = readSymbol(d, gR) + local b = readSymbol(d, gB) + local a = readSymbol(d, gA) + if d.bitcnt < d.over * 8 then + break + end + local argb = a * 16777216 + r * 65536 + code * 256 + b + writeu32(data, i * 4, argb) + if cache then + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + i =i+ 1 + col =col+ 1 + if col >= w then + col = 0 + row =row+ 1 + end + elseif code < lenLimit then + local ls = code - NUM_LITERAL + local length + if ls < 4 then + length = ls + 1 + else + local eb = rshift(ls - 2, 1) + length = lshift(2 + band(ls, 1), eb) + readBits(d, eb) + 1 + end + local ds = readSymbol(d, gD) + local dc + if ds < 4 then + dc = ds + 1 + else + local eb = rshift(ds - 2, 1) + dc = lshift(2 + band(ds, 1), eb) + readBits(d, eb) + 1 + end + local dist + if dc > 120 then + dist = dc - 120 + else + local v = CODE_TO_PLANE[dc] + dist = rshift(v, 4) * w + 8 - band(v, 15) + if dist < 1 then + dist = 1 + end + end + if d.bitcnt < d.over * 8 then + break + end + if i < dist or total - i < length then + return false, "bad backward reference" + end + if dist >= length then + bcopy(data, i * 4, data, (i - dist) * 4, length * 4) + else + for k = i, i + length - 1 do + writeu32(data, k * 4, readu32(data, (k - dist) * 4)) + end + end + if cache then + for k = i, i + length - 1 do + local argb = readu32(data, k * 4) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + end + end + i =i+ length + col =col+ length + while col >= w do + col =col- w + row =row+ 1 + end + if band(col, hmask) ~= 0 then + setGroup() + end + elseif code < cacheLimit and cache then + if d.bitcnt < d.over * 8 then + break + end + local argb = readu32(cache, (code - lenLimit) * 4) + writeu32(data, i * 4, argb) + writeu32(cache, cacheKey(argb, cshift) * 4, argb) + i =i+ 1 + col =col+ 1 + if col >= w then + col = 0 + row =row+ 1 + end + else + return false, "bad symbol" + end + end + if eos(d) then + return false, "truncated: pixel data" + end + return true, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +local function addPixels(a, b) +return band(band(a, 0xff00ff00) + band(b, 0xff00ff00), 0xff00ff00) + band(band(a, 0x00ff00ff) + band(b, 0x00ff00ff), 0x00ff00ff) +end +Decode.addPixels = addPixels + +local function average2(a, b) +return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end +Decode.average2 = average2 + +local function clip255(v) +return v < 0 and 0 or(v > 255 and 255 or v +)end + +local function sub3(a, b, c) +local pb, pa = b - c, a - c + return ((pb < 0 and{(-pb )}or{pb})[1]) - ((pa < 0 and{(-pa )}or{pa})[1]) +end + +-- select(T, L, TL) +local function select3(a, b, c) +local s = sub3(rshift(a, 24), rshift(b, 24), rshift(c, 24)) + + sub3(band(rshift(a, 16), 255), band(rshift(b, 16), 255), band(rshift(c, 16), 255)) + + sub3(band(rshift(a, 8), 255), band(rshift(b, 8), 255), band(rshift(c, 8), 255)) + + sub3(band(a, 255), band(b, 255), band(c, 255)) + return (s <= 0 and{a }or{b +})[1]end + +local function clampedFull(c0, c1, c2) +local a = clip255(rshift(c0, 24) + rshift(c1, 24) - rshift(c2, 24)) + local r = clip255(band(rshift(c0, 16), 255) + band(rshift(c1, 16), 255) - band(rshift(c2, 16), 255)) + local g = clip255(band(rshift(c0, 8), 255) + band(rshift(c1, 8), 255) - band(rshift(c2, 8), 255)) + local b = clip255(band(c0, 255) + band(c1, 255) - band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +local function half(a, b) +local dd = a - b + -- C division truncates toward zero + local q = (dd >= 0 and{(rshift(dd, 1) )}or{(-rshift(-dd, 1) +)})[1] return clip255(a + q) +end + +local function clampedHalf(c0, c1, c2) +local ave = average2(c0, c1) + local a = half(rshift(ave, 24), rshift(c2, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(c2, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(c2, 8), 255)) + local b = half(band(ave, 255), band(c2, 255)) + return a * 16777216 + r * 65536 + g * 256 + b +end + +-- predict(mode, L, T, TR, TL) -> the predicted pixel (libwebp VP8LPredictors; 14 and 15 are black) +local function predict(mode, L, T, TR, TL) +if mode == 0 then + return ARGB_BLACK + elseif mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + return select3(T, L, TL) + elseif mode == 12 then + return clampedFull(L, T, TL) + elseif mode == 13 then + return clampedHalf(L, T, TL) + end + return ARGB_BLACK +end +Decode.predict = predict + +local function inversePredictor(data, w, h, bits, sub) + local tw = subSample(w, bits) + -- first row: black, then L + writeu32(data, 0, addPixels(readu32(data, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(data, x * 4, addPixels(readu32(data, x * 4), readu32(data, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + local up = row - w + writeu32(data, row * 4, addPixels(readu32(data, row * 4), readu32(data, up * 4))) + local trow = rshift(y, bits) * tw + local x = 1 + while x < w do + local mode = band(rshift(readu32(sub, (trow + rshift(x, bits)) * 4), 8), 15) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + local L = readu32(data, (row + x - 1) * 4) + if mode == 1 then + for k = x, xe - 1 do + L = addPixels(readu32(data, (row + k) * 4), L) + writeu32(data, (row + k) * 4, L) + end + elseif mode == 2 then + for k = x, xe - 1 do + writeu32(data, (row + k) * 4, addPixels(readu32(data, (row + k) * 4), readu32(data, (up + k) * 4))) + end + else + for k = x, xe - 1 do + local p = predict(mode, L, readu32(data, (up + k) * 4), readu32(data, (up + k + 1) * 4), readu32(data, (up + k - 1) * 4)) + L = addPixels(readu32(data, (row + k) * 4), p) + writeu32(data, (row + k) * 4, L) + end + end + x = xe + end + end +end + +local function sint8(v) +return (v >= 128 and((v - 256 ))or(v +))end + +local function inverseCrossColor(data, w, h, bits, sub) + local tw = subSample(w, bits) + for y = 0, h - 1 do + local trow = rshift(y, bits) * tw + local x = 0 + while x < w do + local m = readu32(sub, (trow + rshift(x, bits)) * 4) + local g2r = sint8(band(m, 255)) + local g2b = sint8(band(rshift(m, 8), 255)) + local r2b = sint8(band(rshift(m, 16), 255)) + local xe = math.min(w, lshift(rshift(x, bits) + 1, bits)) + for k = y * w + x, y * w + xe - 1 do + local argb = readu32(data, k * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(band(rshift(argb, 16), 255) + (math.floor((g2r * g) / 32)), 255) + local b = band(band(argb, 255) + (math.floor((g2b * g) / 32)) + (math.floor((r2b * sint8(r)) / 32)), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + r * 65536 + b) + end + x = xe + end + end +end + +local function inverseSubtractGreen(data, n) + for k = 0, n - 1 do + local argb = readu32(data, k * 4) + local g = band(rshift(argb, 8), 255) + writeu32(data, k * 4, band(argb, 0xff00ff00) + band(band(argb, 0x00ff00ff) + g * 65537, 0x00ff00ff)) + end +end + +-- inverseColorIndexing(src (sw x h), w, h, bits, map (2^(8 >> bits) u32)) -> w x h +local function inverseColorIndexing(src, sw, w, h, bits, map) +local out = bcreate(w * h * 4) + if bits == 0 then + for k = 0, w * h - 1 do + writeu32(out, k * 4, readu32(map, band(rshift(readu32(src, k * 4), 8), 255) * 4)) + end + return out + end + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + local vmask = lshift(1, bpp) - 1 + for y = 0, h - 1 do + local packed = 0 + local s = y * sw + local o = y * w + for x = 0, w - 1 do + if band(x, cmask) == 0 then + packed = band(rshift(readu32(src, s * 4), 8), 255) + s =s+ 1 + end + writeu32(out, (o + x) * 4, readu32(map, band(packed, vmask) * 4)) + packed = rshift(packed, bpp) + end + end + return out +end +-- ------------------------------------------------------------------------------------------------ image stream + + + +local decodeStream +-- readCodes(d, xs, ys, cacheBits, level0) -> groups (5 table offsets each), huffman image, bits, image width + +local function readCodes(d, xs, ys, cacheBits, level0) +local himg= nil + local hbits, hxs = 0, 0 + local numGroups = 1 + local mapping= nil + local numMax = 1 + if level0 and readBits(d, 1) == 1 then + hbits = readBits(d, 3) + 2 + hxs = subSample(xs, hbits) + local hys = subSample(ys, hbits) + local img, err = decodeStream(d, hxs, hys, false) + if not img then + return nil, nil, 0, 0, err + end + local n = hxs * hys + for k = 0, n - 1 do + local g = band(rshift(readu32(img, k * 4), 8), 0xffff) + writeu32(img, k * 4, g) + if g >= numMax then + numMax = g + 1 + end + end + if numMax > 1000 or numMax > xs * ys then + -- remap the used groups to [0, numGroups); unused ones are read and checked but not kept + local map = (table.create(numMax, -1) ) +numGroups = 0 + for k = 0, n - 1 do + local g = readu32(img, k * 4) + if map[g + 1] == -1 then + map[g + 1] = numGroups + numGroups =numGroups+ 1 + end + writeu32(img, k * 4, map[g + 1]) + end + mapping = map + else + numGroups = numMax + end + himg = img + end + if eos(d) then + return nil, nil, 0, 0, "truncated: meta codes" + end + local groups = (table.create(numGroups * 5, 0) ) +local cacheSize = (cacheBits > 0 and{(lshift(1, cacheBits) )}or{0 +})[1] for i = 0, numMax - 1 do + local slot = (mapping and{mapping[i + 1] }or{i +})[1] local mark = d.tabUsed + for j = 0, 4 do + local size = (j == 0 and((NUM_LITERAL + NUM_LENGTH + cacheSize ))or((j == 4 and{NUM_DISTANCE }or{NUM_LITERAL +})[1])) local at = readCode(d, size) + if at < 0 then + return nil, nil, 0, 0, eos(d) and"truncated: prefix code" or"bad prefix code" + end + if slot >= 0 then + groups[slot * 5 + j + 1] = at + end + end + if slot < 0 then + d.tabUsed = mark + end + end + return groups, himg, hbits, hxs, nil +end + +decodeStream = function(d, xs, ys, level0) +local transforms= {} + local seen = 0 + local txs = xs + if level0 then + while readBits(d, 1) == 1 do + local kind = readBits(d, 2) + if band(seen, lshift(1, kind)) ~= 0 then + return nil, "repeated transform" + end + seen = bor(seen, lshift(1, kind)) + local t= { kind = kind, xsize = txs, bits = 0, data = nil } + if kind == 0 or kind == 1 then + t.bits = readBits(d, 3) + 2 + local sub, err = decodeStream(d, subSample(txs, t.bits), subSample(ys, t.bits), false) + if not sub then + return nil, err + end + t.data = sub + elseif kind == 3 then + local num = readBits(d, 8) + 1 + local bits = num > 16 and 0 or(num > 4 and 1 or(num > 2 and 2 or 3 +)) t.bits = bits + local pal, err = decodeStream(d, num, 1, false) + if not pal then + return nil, err + end + local final = lshift(1, rshift(8, bits)) + local map = bcreate(final * 4) + local prev = 0 + for k = 0, num - 1 do + prev = addPixels(readu32(pal, k * 4), prev) + writeu32(map, k * 4, prev) + end + t.data = map + txs = subSample(txs, bits) + end + table.insert(transforms, t) + if eos(d) then + return nil, "truncated: transforms" + end + end + end + local cacheBits = 0 + if readBits(d, 1) == 1 then + cacheBits = readBits(d, 4) + if cacheBits < 1 or cacheBits > MAX_CACHE_BITS then + return nil, "bad colour cache size" + end + end + local mark = d.tabUsed + local groups, himg, hbits, hxs, err = readCodes(d, txs, ys, cacheBits, level0) + if not groups then + return nil, err + end + local data = bcreate(txs * ys * 4) + local ok, derr = decodeData(d, data, txs, ys, cacheBits, groups, himg, hbits, hxs) + if not ok then + return nil, derr + end + d.tabUsed = mark + -- inverse transforms, last read first + for k = #transforms, 1, -1 do + local t = transforms[k] + if t.kind == 0 then + inversePredictor(data, t.xsize, ys, t.bits, t.data ) + elseif t.kind == 1 then + inverseCrossColor(data, t.xsize, ys, t.bits, t.data ) + elseif t.kind == 2 then + inverseSubtractGreen(data, t.xsize * ys) + else + data = inverseColorIndexing(data, subSample(t.xsize, t.bits), t.xsize, ys, t.bits, t.data ) + end + end + return data, nil +end + +local function newState(buf, off, len, maxPixels) +return { + buf = buf, + pos = off, + limit = off + len, + bitbuf = 0, + bitcnt = 0, + over = 0, + tab = bcreate(4096 * 4), + tabUsed = 0, + maxPixels = maxPixels, + } +end + +-- header(buf, off, len) -> width, height, alphaHint | nil, message +function Decode.header(buf, off, len) +if len < 5 then + return nil, 0, false, "truncated: header" + end + if readu8(buf, off) ~= 0x2f then + return nil, 0, false, "bad VP8L signature" + end + local v = readu32(buf, off + 1) + local w = band(v, 0x3fff) + 1 + local h = band(rshift(v, 14), 0x3fff) + 1 + local alpha = band(rshift(v, 28), 1) == 1 + if rshift(v, 29) ~= 0 then + return nil, 0, false, "bad VP8L version" + end + return w, h, alpha, nil +end + +-- argb(buf, off, len, maxPixels) -> ARGB pixels, width, height, alphaHint | nil, message +function Decode.argb(buf, off, len, maxPixels) +local w, h, alpha, err = Decode.header(buf, off, len) + if not w then + return nil, 0, 0, false, err + end + if w * h > maxPixels then + return nil, w, h, alpha, "limit: " .. w .. " x " .. h .. " is over maxPixels" + end + local d = newState(buf, off + 5, len - 5, maxPixels) + local data, derr = decodeStream(d, w, h, true) + if not data then + return nil, w, h, alpha, derr + end + return data, w, h, alpha, nil +end + +-- stream(buf, off, len, w, h) -> ARGB pixels | nil, message: a headerless image stream (the ALPH chunk's payload) +function Decode.stream(buf, off, len, w, h) +local d = newState(buf, off, len, w * h) + return decodeStream(d, w, h, true) +end + +-- toRgba(argb, n, out?, outOff?) -> rgba8 bytes +function Decode.toRgba(argb, n, out, outOff) +local o = out or bcreate(n * 4) + local base = outOff or 0 + for k = 0, n - 1 do + local v = readu32(argb, k * 4) + -- 0xAARRGGBB (bytes B G R A) -> bytes R G B A + writeu32(o, base + k * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return o +end + +-- green(argb, n) -> the green channel as bytes (alpha planes) +function Decode.green(argb, n) +local o = bcreate(n) + for k = 0, n - 1 do + writeu8(o, k, band(rshift(readu32(argb, k * 4), 8), 255)) + end + return o +end + +return Decode +end +__FILES["codecs/image/Vp8L/Encode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). +-- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode +-- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash +-- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy +-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. +-- Never throws (the init module validates the arguments). +local Huffman = __include("codecs/entropy/Huffman") + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local log = math.log + +local Encode = {} + +local NUM_LITERAL = 256 +local NUM_LENGTH = 24 +local NUM_DISTANCE = 40 +local MAX_LENGTH = 4096 +local WINDOW = 1048576 - 120 +local ARGB_BLACK = 0xff000000 + +local CODE_LENGTH_ORDER = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } +local CODE_TO_PLANE = { + 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a, 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, + 0x3a, 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b, 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, + 0x3c, 0x03, 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c, 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, + 0x69, 0x12, 0x1e, 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b, 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, + 0x53, 0x5d, 0x11, 0x1f, 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b, 0x31, 0x3f, 0x63, 0x6d, 0x52, + 0x5e, 0x00, 0x74, 0x7c, 0x41, 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f, 0x40, 0x72, 0x7e, 0x61, + 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70, +} +-- PLANE_TO_CODE[v + 1] = the distance code (1..120) of the plane offset v = yoffset * 16 + 8 - xoffset +local PLANE_TO_CODE = table.create(128, 0) +for i, v in __iter(CODE_TO_PLANE) do + PLANE_TO_CODE[v + 1] = i +end +-- ------------------------------------------------------------------------------------------------ bit writer + + + +local function newWriter(cap) +return { buf = bcreate(math.max(64, cap)), pos = 0, acc = 0, cnt = 0 } +end + +-- put(w, v, n): the n <= 24 low bits of v, LSB first +local function put(w, v, n) + local acc = w.acc + v * 2 ^ w.cnt + local cnt = w.cnt + n + if cnt >= 8 then + local pos = w.pos + local buf = w.buf + if pos + 8 > blen(buf) then + local nb = bcreate(blen(buf) * 2) + bcopy(nb, 0, buf, 0, pos) + buf = nb + w.buf = nb + end + repeat + local byte = acc % 256 + writeu8(buf, pos, byte) + pos =pos+ 1 + acc = (acc - byte) / 256 + cnt =cnt- 8 + until cnt < 8 + w.pos = pos + end + w.acc, w.cnt = acc, cnt +end + +local function finish(w) +if w.cnt > 0 then + put(w, 0, 8 - w.cnt) + end + local out = bcreate(w.pos) + bcopy(out, 0, w.buf, 0, w.pos) + return out +end + +-- ------------------------------------------------------------------------------------------------ helpers +local function subSample(size, bits) +return rshift(size + lshift(1, bits) - 1, bits) +end + +-- (0x1e35a7bd * v) mod 2^32: the colour cache hash before its shift +local function mulHash(v) +local lo = v % 65536 + local hi = (v - lo) / 65536 + return (lo * 0xa7bd + ((lo * 0x1e35 + hi * 0xa7bd) % 65536) * 65536) % 4294967296 +end + +-- prefix(v) -> code, extra bits, extra value of a length or distance code value v >= 1 +local function prefix(v) +local d = v - 1 + if d < 4 then + return d, 0, 0 + end + local hb = 0 + local t = d + while t >= 2 do + t = rshift(t, 1) + hb =hb+ 1 + end + local second = band(rshift(d, hb - 1), 1) + local eb = hb - 1 + return 2 * hb + second, eb, band(d, lshift(1, eb) - 1) +end + +-- distCode(xs, dist) -> the distance code value (1..120 for the 2-D plane offsets, else dist + 120) +local function distCode(xs, dist) +local yo = math.floor(dist / xs +) local xo = dist - yo * xs + if xo <= 8 and yo < 8 then + return PLANE_TO_CODE[yo * 16 + 8 - xo + 1] + elseif xo > xs - 8 and yo < 7 then + return PLANE_TO_CODE[(yo + 1) * 16 + 8 + (xs - xo) + 1] + end + return dist + 120 +end + +local function subPixels(a, b) +return band(bor(a, 0x00ff00ff) - band(b, 0xff00ff00), 0xff00ff00) + band(bor(a, 0xff00ff00) - band(b, 0x00ff00ff), 0x00ff00ff) +end + +local function average2(a, b) +return rshift(band(bxor(a, b), 0xfefefefe), 1) + band(a, b) +end + +local function clip255(v) +return v < 0 and 0 or(v > 255 and 255 or v +)end + +local function sub3(a, b, c) +local pb, pa = b - c, a - c + return ((pb < 0 and{(-pb )}or{pb})[1]) - ((pa < 0 and{(-pa )}or{pa})[1]) +end + +local function half(x, y) +local dd = x - y + return clip255(x + ((dd >= 0 and{(rshift(dd, 1) )}or{(-rshift(-dd, 1))})[1])) +end + +-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) +local function predict(mode, L, T, TR, TL) +if mode == 1 then + return L + elseif mode == 2 then + return T + elseif mode == 3 then + return TR + elseif mode == 4 then + return TL + elseif mode == 5 then + return average2(average2(L, TR), T) + elseif mode == 6 then + return average2(L, TL) + elseif mode == 7 then + return average2(L, T) + elseif mode == 8 then + return average2(TL, T) + elseif mode == 9 then + return average2(T, TR) + elseif mode == 10 then + return average2(average2(L, TL), average2(T, TR)) + elseif mode == 11 then + local s = sub3(rshift(T, 24), rshift(L, 24), rshift(TL, 24)) + + sub3(band(rshift(T, 16), 255), band(rshift(L, 16), 255), band(rshift(TL, 16), 255)) + + sub3(band(rshift(T, 8), 255), band(rshift(L, 8), 255), band(rshift(TL, 8), 255)) + + sub3(band(T, 255), band(L, 255), band(TL, 255)) + return (s <= 0 and{T }or{L +})[1] elseif mode == 12 then + local a = clip255(rshift(L, 24) + rshift(T, 24) - rshift(TL, 24)) + local r = clip255(band(rshift(L, 16), 255) + band(rshift(T, 16), 255) - band(rshift(TL, 16), 255)) + local g = clip255(band(rshift(L, 8), 255) + band(rshift(T, 8), 255) - band(rshift(TL, 8), 255)) + local b = clip255(band(L, 255) + band(T, 255) - band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + elseif mode == 13 then + local ave = average2(L, T) + local a = half(rshift(ave, 24), rshift(TL, 24)) + local r = half(band(rshift(ave, 16), 255), band(rshift(TL, 16), 255)) + local g = half(band(rshift(ave, 8), 255), band(rshift(TL, 8), 255)) + local b = half(band(ave, 255), band(TL, 255)) + return a * 16777216 + r * 65536 + g * 256 + b + end + return ARGB_BLACK +end + +-- COST[v + 1]: an estimate of the bits of a residual byte v (small magnitudes, mod 256, are cheap) +local COST = table.create(256, 0) +for v = 0, 255 do + local m = math.min(v, 256 - v) + COST[v + 1] = log(1 + m) / log(2) +end + +local function residualCost(r) +return COST[band(r, 255) + 1] + COST[band(rshift(r, 8), 255) + 1] + COST[band(rshift(r, 16), 255) + 1] + COST[rshift(r, 24) + 1] +end + +-- ------------------------------------------------------------------------------------------------ transforms +local MODES_FAST = { 1, 2, 11 } +local MODES_MID = { 0, 1, 2, 4, 5, 7, 10, 11, 12, 13 } +local MODES_ALL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 } + +-- predictorTransform(px, w, h, bits, effort) -> the modes sub-image; px becomes the residuals +local function predictorTransform(px, w, h, bits, effort) +local tw, th = subSample(w, bits), subSample(h, bits) + local modesImg = bcreate(tw * th * 4) + local modes = (effort <= 2 and{MODES_FAST }or{(effort <= 6 and{MODES_MID }or{MODES_ALL +})[1]})[1] local ts = lshift(1, bits) + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local best, bestCost = 1, math.huge + for _, m in __iter(modes) do + local cost = 0 + for y = math.max(y0, 1), y1 - 1 do + local row = y * w + for x = math.max(x0, 1), x1 - 1 do + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + cost =cost+ residualCost(subPixels(readu32(px, i * 4), p)) + end + if cost >= bestCost then + break + end + end + if cost < bestCost then + best, bestCost = m, cost + end + end + writeu32(modesImg, (ty * tw + tx) * 4, ARGB_BLACK + best * 256) + end + end + -- residuals with the chosen modes (and the decoder's fixed first row and column) + local res = bcreate(w * h * 4) + writeu32(res, 0, subPixels(readu32(px, 0), ARGB_BLACK)) + for x = 1, w - 1 do + writeu32(res, x * 4, subPixels(readu32(px, x * 4), readu32(px, (x - 1) * 4))) + end + for y = 1, h - 1 do + local row = y * w + writeu32(res, row * 4, subPixels(readu32(px, row * 4), readu32(px, (row - w) * 4))) + local trow = rshift(y, bits) * tw + for x = 1, w - 1 do + local m = band(rshift(readu32(modesImg, (trow + rshift(x, bits)) * 4), 8), 15) + local i = row + x + local up = i - w + local p = predict(m, readu32(px, (i - 1) * 4), readu32(px, up * 4), readu32(px, (up + 1) * 4), readu32(px, (up - 1) * 4)) + writeu32(res, i * 4, subPixels(readu32(px, i * 4), p)) + end + end + bcopy(px, 0, res, 0, w * h * 4) + return modesImg +end + +local function sint8(v) +return (v >= 128 and((v - 256 ))or(v +))end + +local function clampM(v) +local m = math.floor(v + 0.5) + return m < -128 and-128 or(m > 127 and 127 or m +)end + +-- crossColorTransform(px, w, h, bits) -> the multipliers sub-image; px is transformed in place. Per tile: the +-- least-squares multipliers (r ~ g2r * g / 32, b ~ g2b * g / 32 + r2b * r / 32), kept when they lower the cost +local function crossColorTransform(px, w, h, bits) +local tw, th = subSample(w, bits), subSample(h, bits) + local img = bcreate(tw * th * 4) + local ts = lshift(1, bits) + local function tileCost(x0, y0, x1, y1, g2r, g2b, r2b) +local c = 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - (math.floor((g2r * g) / 32)), 255) + local nb = band(b - (math.floor((g2b * g) / 32)) - (math.floor((r2b * sint8(r)) / 32)), 255) + c =c+ (COST[nr + 1] + COST[nb + 1] +) end + end + return c + end + for ty = 0, th - 1 do + for tx = 0, tw - 1 do + local x0, y0 = tx * ts, ty * ts + local x1, y1 = math.min(w, x0 + ts), math.min(h, y0 + ts) + local sgg, sgr, sgb, srr, srb = 0, 0, 0, 0, 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local argb = readu32(px, (y * w + x) * 4) + local g = sint8(band(rshift(argb, 8), 255)) + local r = sint8(band(rshift(argb, 16), 255)) + local b = sint8(band(argb, 255)) + sgg =sgg+ g * g + sgr =sgr+ g * r + sgb =sgb+ g * b + srr =srr+ r * r + srb =srb+ r * b + end + end + local g2r, g2b, r2b = 0, 0, 0 + if sgg > 0 then + g2r = clampM(32 * sgr / sgg) + local det = sgg * srr - sgr * sgr + if det > 0 then + g2b = clampM(32 * (sgb * srr - srb * sgr) / det) + r2b = clampM(32 * (srb * sgg - sgb * sgr) / det) + else + g2b = clampM(32 * sgb / sgg) + end + end + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + if tileCost(x0, y0, x1, y1, g2r, g2b, r2b) >= tileCost(x0, y0, x1, y1, 0, 0, 0) then + g2r, g2b, r2b = 0, 0, 0 + end + end + writeu32(img, (ty * tw + tx) * 4, ARGB_BLACK + band(r2b, 255) * 65536 + band(g2b, 255) * 256 + band(g2r, 255)) + if g2r ~= 0 or g2b ~= 0 or r2b ~= 0 then + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local k = (y * w + x) * 4 + local argb = readu32(px, k) + local g = sint8(band(rshift(argb, 8), 255)) + local r = band(rshift(argb, 16), 255) + local b = band(argb, 255) + local nr = band(r - (math.floor((g2r * g) / 32)), 255) + local nb = band(b - (math.floor((g2b * g) / 32)) - (math.floor((r2b * sint8(r)) / 32)), 255) + writeu32(px, k, band(argb, 0xff00ff00) + nr * 65536 + nb) + end + end + end + end + end + return img +end + +-- ------------------------------------------------------------------------------------------------ LZ77 +-- tokens: L[i] >= 0 is a literal ARGB pixel; L[i] < 0 is a copy of -L[i] pixels with the distance code value D[i] +local HASH_BITS = 16 + +local function hash2(a, b) +return rshift(mulHash(bxor(a, (b * 31) % 4294967296)), 32 - HASH_BITS) +end + +local function matchLen(px, i, j, max) +local n = 0 + while n < max and readu32(px, (i + n) * 4) == readu32(px, (j + n) * 4) do + n =n+ 1 + end + return n +end + +local function lz77(px, xs, n, effort) +local L= {} + local D= {} + if effort == 0 then + for i = 0, n - 1 do + L[i + 1] = readu32(px, i * 4) + D[i + 1] = 0 + end + return L, D + end + local head = table.create(lshift(1, HASH_BITS), -1) + local prev = table.create(n, -1) + local maxIter = effort <= 2 and 4 or(effort <= 5 and 16 or(effort <= 7 and 48 or 128 +)) local function insert(i) + if i + 1 < n then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + prev[i + 1] = head[h] + head[h] = i + end + end + -- best(i) -> length, distance (0, 0 when no useful match) + local function best(i) +local max = math.min(MAX_LENGTH, n - i) + if max < 2 then + return 0, 0 + end + local bl, bd, bc = 0, 0, math.huge + local function try(j) + local d = i - j + if d < 1 or d > WINDOW then + return + end + local l = matchLen(px, i, j, max) + if l >= 2 then + local c = distCode(xs, d) + if l > bl or (l == bl and c < bc) then + bl, bd, bc = l, d, c + end + end + end + if i >= 1 then + try(i - 1) + end + if i >= xs then + try(i - xs) + end + if bl < max then + local h = hash2(readu32(px, i * 4), readu32(px, (i + 1) * 4)) + 1 + local j = head[h] + local it = 0 + while j >= 0 and it < maxIter and i - j <= WINDOW do + if j ~= i - 1 and j ~= i - xs then + try(j) + if bl >= max then + break + end + end + j = prev[j + 1] + it =it+ 1 + end + end + -- a 2-pixel copy only pays with a short 2-D distance code + if bl == 2 and bc > 120 then + return 0, 0 + end + return bl, bd + end + local i = 0 + local k = 0 + local lazy = effort >= 4 + local nl, nd = 0, 0 + local haveNext = false + while i < n do + local l, d + if haveNext then + l, d = nl, nd + haveNext = false + else + l, d = best(i) + end + if l >= 2 and lazy and l < 64 and i + 1 < n then + insert(i) + nl, nd = best(i + 1) + if nl > l + 1 then + -- a literal now, the longer match next + k =k+ 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i =i+ 1 + haveNext = true + else + k =k+ 1 + L[k] = -l + D[k] = distCode(xs, d) + for t = i + 1, i + l - 1 do + insert(t) + end + i =i+ l + end + elseif l >= 2 then + k =k+ 1 + L[k] = -l + D[k] = distCode(xs, d) + local stop = i + l + if effort <= 2 and l > 16 then + insert(i) + insert(stop - 1) + else + for t = i, stop - 1 do + insert(t) + end + end + i = stop + else + insert(i) + k =k+ 1 + L[k] = readu32(px, i * 4) + D[k] = 0 + i =i+ 1 + end + end + return L, D +end + +-- ------------------------------------------------------------------------------------------------ prefix codes +local function entropy(h) +local total = 0 + for _, c in __iter(h) do + total =total+ c + end + if total == 0 then + return 0 + end + local bits = 0 + local lt = log(total) + for _, c in __iter(h) do + if c > 0 then + bits =bits+ c * (lt - log(c)) + end + end + return bits / log(2) +end + +-- chooseCache(px, L, effort) -> the colour cache bits (0..10) with the smallest estimated literal cost +local function chooseCache(px, L, effort) +if effort < 2 then + return 0 + end + local cands = effort < 5 and{ 0, 4, 7, 10 } or{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } + local caches= {} + local hg= {} + local hr= {} + local hb= {} + local ha= {} + for c, bits in __iter(cands) do + caches[c] = table.create(lshift(1, bits), -1) + hg[c] = table.create(256 + lshift(1, bits), 0) + hr[c] = table.create(256, 0) + hb[c] = table.create(256, 0) + ha[c] = table.create(256, 0) + end + local pos = 0 + for _, t in __iter(L) do + if t >= 0 then + local hsh = mulHash(t) + for c, bits in __iter(cands) do + local cache = caches[c] + local key = (bits > 0 and{(rshift(hsh, 32 - bits) )}or{0 +})[1] if bits > 0 and cache[key + 1] == t then +do local __DARKLUA_VAR, __DARKLUA_VAR0= hg[c], 257 + key __DARKLUA_VAR[__DARKLUA_VAR0]=__DARKLUA_VAR[__DARKLUA_VAR0]+ 1 +end else +do local __DARKLUA_VAR, __DARKLUA_VAR0= hg[c], band(rshift(t, 8), 255) + 1 __DARKLUA_VAR[__DARKLUA_VAR0]=__DARKLUA_VAR[__DARKLUA_VAR0]+ 1 +end do local __DARKLUA_VAR1, __DARKLUA_VAR2= hr[c], band(rshift(t, 16), 255) + 1 __DARKLUA_VAR1[__DARKLUA_VAR2]=__DARKLUA_VAR1[__DARKLUA_VAR2]+ 1 +end do local __DARKLUA_VAR3, __DARKLUA_VAR4= hb[c], band(t, 255) + 1 __DARKLUA_VAR3[__DARKLUA_VAR4]=__DARKLUA_VAR3[__DARKLUA_VAR4]+ 1 +end do local __DARKLUA_VAR5, __DARKLUA_VAR6= ha[c], rshift(t, 24) + 1 __DARKLUA_VAR5[__DARKLUA_VAR6]=__DARKLUA_VAR5[__DARKLUA_VAR6]+ 1 +end end + if bits > 0 then + cache[key + 1] = t + end + end + pos =pos+ 1 + else + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + local hsh = mulHash(v) + for c, bits in __iter(cands) do + if bits > 0 then + caches[c][rshift(hsh, 32 - bits) + 1] = v + end + end + end + pos =pos- t + end + end + local bestBits, bestCost = 0, math.huge + for c, bits in __iter(cands) do + -- + a rough price for the longer green code lengths + local cost = entropy(hg[c]) + entropy(hr[c]) + entropy(hb[c]) + entropy(ha[c]) + lshift(1, bits) * 0.5 + if cost < bestCost then + bestBits, bestCost = bits, cost + end + end + return bestBits +end + +-- buildCode(freqs, maxLen) -> code lengths, reversed (LSB-first) codes, single (<= 1 used symbol: 0 bits each) + + +local function buildCode(freqs, maxLen) +local lens = Huffman.lengths(freqs, maxLen) + local used = 0 + for _, l in __iter(lens) do + if l > 0 then + used =used+ 1 + end + end + local codes = Huffman.codes(lens) + for i, l in __iter(lens) do + if l > 0 then + codes[i] = Huffman.reverse(codes[i], l) + end + end + return { lens = lens, codes = codes, single = used <= 1 } +end + +local function emit(w, c, sym) + if not c.single then + put(w, c.codes[sym + 1], c.lens[sym + 1]) + end +end + +local function zeroRun(tok, ext, run) + local r = run + while r > 0 do + if r >= 11 then + local k = math.min(r, 138) + table.insert(tok, 18) + table.insert(ext, k - 11) + r =r- k + elseif r >= 3 then + table.insert(tok, 17) + table.insert(ext, r - 3) + r = 0 + else + table.insert(tok, 0) + table.insert(ext, 0) + r =r- 1 + end + end +end + +-- writeCode(w, code, alphabetSize): the code lengths (a simple code when possible, else run-length coded) +local function writeCode(w, c, size) + local syms= {} + for s = 0, size - 1 do + if (c.lens[s + 1] or 0) > 0 then + table.insert(syms, s) + if #syms > 2 then + break + end + end + end + if #syms == 0 then + -- an unused alphabet: the simple code of symbol 0 + put(w, 1, 1) + put(w, 0, 1) + put(w, 0, 1) + put(w, 0, 1) + return + end + if #syms <= 2 and syms[#syms] < 256 then + put(w, 1, 1) + put(w, #syms - 1, 1) + if syms[1] <= 1 then + put(w, 0, 1) + put(w, syms[1], 1) + else + put(w, 1, 1) + put(w, syms[1], 8) + end + if #syms == 2 then + put(w, syms[2], 8) + end + return + end + -- run-length tokens of every length: 0..15 literal, 16 repeats the previous non-zero length (3..6 times; the + -- decoder's "previous" starts at 8), 17 zeros (3..10), 18 zeros (11..138) + local tok= {} + local ext= {} + local keep = 0 -- tokens up to the last non-zero length + local prev = 8 + local s = 1 + while s <= size do + local l = c.lens[s] or 0 + local run = 1 + while s + run <= size and (c.lens[s + run] or 0) == l do + run =run+ 1 + end + if l == 0 then + zeroRun(tok, ext, run) + else + local r = run + if l ~= prev then + table.insert(tok, l) + table.insert(ext, 0) + r =r- 1 + prev = l + end + while r > 0 do + if r >= 3 then + local k = math.min(r, 6) + table.insert(tok, 16) + table.insert(ext, k - 3) + r =r- k + else + table.insert(tok, l) + table.insert(ext, 0) + r =r- 1 + end + end + keep = #tok + end + s =s+ run + end + local ntok = #tok + local trim = keep < ntok and keep >= 2 + if trim then + ntok = keep + end + local hist = table.create(19, 0) + for i = 1, ntok do +do local __DARKLUA_VAR=tok[i] + 1 hist[__DARKLUA_VAR]=hist[__DARKLUA_VAR]+ 1 +end end + local cl = buildCode(hist, 7) + local nc = 19 + while nc > 4 and (cl.lens[CODE_LENGTH_ORDER[nc] + 1] or 0) == 0 do + nc =nc- 1 + end + put(w, 0, 1) + put(w, nc - 4, 4) + for i = 1, nc do + put(w, cl.lens[CODE_LENGTH_ORDER[i] + 1] or 0, 3) + end + if trim then + put(w, 1, 1) + local v = ntok - 2 + local nbits = 0 + while lshift(1, nbits) <= v do + nbits =nbits+ 1 + end + local pairs = math.max(1, math.floor((nbits + 1) / 2)) + put(w, pairs - 1, 3) + put(w, v, pairs * 2) + else + put(w, 0, 1) + end + for i = 1, ntok do + local t = tok[i] + emit(w, cl, t) + if t == 16 then + put(w, ext[i], 2) + elseif t == 17 then + put(w, ext[i], 3) + elseif t == 18 then + put(w, ext[i], 7) + end + end +end + +-- ------------------------------------------------------------------------------------------------ image data +-- writeImage(w, px, xs, n, effort, level0): colour cache bits, [the meta-code bit], the five codes, the pixels +local function writeImage(w, px, xs, n, effort, level0) + local L, D = lz77(px, xs, n, effort) + local cacheBits = (level0 and{(chooseCache(px, L, effort) )}or{0 +})[1] if cacheBits > 0 then + put(w, 1, 1) + put(w, cacheBits, 4) + else + put(w, 0, 1) + end + if level0 then + put(w, 0, 1) -- no meta prefix codes + end + local cacheSize = (cacheBits > 0 and{(lshift(1, cacheBits) )}or{0 +})[1] local cshift = 32 - cacheBits + local hg = table.create(NUM_LITERAL + NUM_LENGTH + cacheSize, 0) + local hr = table.create(256, 0) + local hb = table.create(256, 0) + local ha = table.create(256, 0) + local hd = table.create(NUM_DISTANCE, 0) + -- token kinds after the cache: 0 literal, 1 cache hit, 2 copy + local cache= (cacheBits > 0 and{(table.create(cacheSize, -1) )}or{nil +})[1] local K = table.create(#L, 0) + local pos = 0 + for i, t in __iter(L) do + if t >= 0 then + local hit = false + if cache then + local key = rshift(mulHash(t), cshift) + if cache[key + 1] == t then + hit = true +do local __DARKLUA_VAR=NUM_LITERAL + NUM_LENGTH + key + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 +end end + cache[key + 1] = t + end + if hit then + K[i] = 1 + else +do local __DARKLUA_VAR=band(rshift(t, 8), 255) + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 +end do local __DARKLUA_VAR0=band(rshift(t, 16), 255) + 1 hr[__DARKLUA_VAR0]=hr[__DARKLUA_VAR0]+ 1 +end do local __DARKLUA_VAR1=band(t, 255) + 1 hb[__DARKLUA_VAR1]=hb[__DARKLUA_VAR1]+ 1 +end do local __DARKLUA_VAR2=rshift(t, 24) + 1 ha[__DARKLUA_VAR2]=ha[__DARKLUA_VAR2]+ 1 +end end + pos =pos+ 1 + else + K[i] = 2 +do local __DARKLUA_VAR=NUM_LITERAL + prefix(-t) + 1 hg[__DARKLUA_VAR]=hg[__DARKLUA_VAR]+ 1 +end do local __DARKLUA_VAR0=prefix(D[i]) + 1 hd[__DARKLUA_VAR0]=hd[__DARKLUA_VAR0]+ 1 +end if cache then + for p = pos, pos - t - 1 do + local v = readu32(px, p * 4) + cache[rshift(mulHash(v), cshift) + 1] = v + end + end + pos =pos- t + end + end + local cg, cr, cb, ca, cd = buildCode(hg, 15), buildCode(hr, 15), buildCode(hb, 15), buildCode(ha, 15), buildCode(hd, 15) + writeCode(w, cg, NUM_LITERAL + NUM_LENGTH + cacheSize) + writeCode(w, cr, 256) + writeCode(w, cb, 256) + writeCode(w, ca, 256) + writeCode(w, cd, NUM_DISTANCE) + for i, t in __iter(L) do + local k = K[i] + if k == 0 then + emit(w, cg, band(rshift(t, 8), 255)) + emit(w, cr, band(rshift(t, 16), 255)) + emit(w, cb, band(t, 255)) + emit(w, ca, rshift(t, 24)) + elseif k == 1 then + emit(w, cg, NUM_LITERAL + NUM_LENGTH + rshift(mulHash(t), cshift)) + else + local lc, leb, lev = prefix(-t) + emit(w, cg, NUM_LITERAL + lc) + if leb > 0 then + put(w, lev, leb) + end + local dc, deb, dev = prefix(D[i]) + emit(w, cd, dc) + if deb > 0 then + put(w, dev, deb) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ encode +-- toArgb(rgba, n, exact) -> ARGB pixels, any alpha < 255. Without exact, fully transparent pixels become 0. +local function toArgb(rgba, n, exact) +local px = bcreate(n * 4) + local alpha = false + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + local a = rshift(v, 24) + if a ~= 255 then + alpha = true + end + if a == 0 and not exact then + v = 0 + end + -- bytes R G B A (0xAABBGGRR) -> 0xAARRGGBB + writeu32(px, i * 4, band(v, 0xff00ff00) + band(rshift(v, 16), 255) + band(v, 255) * 65536) + end + return px, alpha +end + +-- palette(px, n) -> the sorted colours when there are at most 256, else nil +local function palette(px, n) +local seen= {} + local list= {} + for i = 0, n - 1 do + local v = readu32(px, i * 4) + if not seen[v] then + if #list == 256 then + return nil + end + seen[v] = true + table.insert(list, v) + end + end + table.sort(list) + return list +end + +-- stream(px, w, h, effort, cfg, bw): the transforms and the main image of one configuration (px is consumed) + + +local function stream(px, w, h, effort, cfg, bw) + local n = w * h + local xs = w + local sub = math.min(effort, 3) + local pal = cfg.palette + if pal then + local num = #pal + local bits = num > 16 and 0 or(num > 4 and 1 or(num > 2 and 2 or 3 +)) put(bw, 1, 1) + put(bw, 3, 2) + put(bw, num - 1, 8) + local pimg = bcreate(num * 4) + local prevc = 0 + local index= {} + for i, c in __iter(pal) do + writeu32(pimg, (i - 1) * 4, subPixels(c, prevc)) + prevc = c + index[c] = i - 1 + end + writeImage(bw, pimg, num, num, sub, false) + xs = subSample(w, bits) + local packed = bcreate(xs * h * 4) + local bpp = rshift(8, bits) + local cmask = lshift(1, bits) - 1 + for y = 0, h - 1 do + local acc = 0 + local o = y * xs + for x = 0, w - 1 do + local sh = band(x, cmask) + acc =acc+ index[readu32(px, (y * w + x) * 4)] * 2 ^ (bpp * sh) + if sh == cmask or x == w - 1 then + writeu32(packed, (o + rshift(x, bits)) * 4, ARGB_BLACK + acc * 256) + acc = 0 + end + end + end + px = packed + elseif cfg.pbits > 0 then + -- subtract green + put(bw, 1, 1) + put(bw, 2, 2) + for i = 0, n - 1 do + local v = readu32(px, i * 4) + local g = band(rshift(v, 8), 255) + writeu32(px, i * 4, band(v, 0xff00ff00) + band(band(v, 0x00ff00ff) + 0x01000100 - g * 65537, 0x00ff00ff)) + end + -- predictor + local pbits = cfg.pbits + local modes = predictorTransform(px, w, h, pbits, effort) + put(bw, 1, 1) + put(bw, 0, 2) + put(bw, pbits - 2, 3) + writeImage(bw, modes, subSample(w, pbits), subSample(w, pbits) * subSample(h, pbits), sub, false) + -- cross colour + if cfg.cc then + local cbits = cfg.ccbits + local cimg = crossColorTransform(px, w, h, cbits) + put(bw, 1, 1) + put(bw, 1, 2) + put(bw, cbits - 2, 3) + writeImage(bw, cimg, subSample(w, cbits), subSample(w, cbits) * subSample(h, cbits), sub, false) + end + end + put(bw, 0, 1) -- no more transforms + writeImage(bw, px, xs, xs * h, effort, true) +end + +-- encode(rgba, w, h, effort, exact, alphaHint?, headerless) -> the VP8L bitstream (headerless: the image stream only, +-- as an ALPH chunk stores it). Efforts 6+ try several transform configurations and keep the smallest. +function Encode.encode(rgba, w, h, effort, exact, alphaHint, headerless) +local n = w * h + local px, usesAlpha = toArgb(rgba, n, exact) + local pal = (effort > 0 and{(palette(px, n) )}or{nil +})[1] local configs= {} + if effort == 0 then + table.insert(configs, { palette = nil, pbits = 0, cc = false, ccbits = 0 }) + else + local pbits = effort >= 5 and 4 or 5 + local plain= { palette = nil, pbits = pbits, cc = effort >= 3, ccbits = effort >= 6 and 4 or 5 } + if pal then + table.insert(configs, { palette = pal, pbits = 0, cc = false, ccbits = 0 }) + if effort >= 6 then + table.insert(configs, plain) + end + else + table.insert(configs, plain) + end + if effort >= 9 then + table.insert(configs, { palette = nil, pbits = 3, cc = true, ccbits = 3 }) + table.insert(configs, { palette = nil, pbits = 5, cc = false, ccbits = 0 }) + end + end + local best= nil + for k, cfg in __iter(configs) do + local bw = newWriter(n + 256) + if not headerless then + put(bw, 0x2f, 8) + put(bw, w - 1, 14) + put(bw, h - 1, 14) + local hint = (alphaHint == nil and{usesAlpha }or{alphaHint +})[1] put(bw, hint and 1 or 0, 1) + put(bw, 0, 3) + end + local work = px + if k < #configs then + work = bcreate(n * 4) + bcopy(work, 0, px, 0, n * 4) + end + stream(work, w, h, effort, cfg, bw) + local out = finish(bw) + if not best or blen(out) < blen(best) then + best = out + end + end + return best +end + +return Encode +end +__FILES["codecs/image/Yuv"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +--!native +--!optimize 2 +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. +-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the +-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma +-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this). +-- +-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) +-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) +-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image +-- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per +-- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) +local Types = __include("Types") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local bcreate = buffer.create +local floor = math.floor + +local Yuv = {} + +-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u +-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224 +local MATRIX= { + bt601 = { kr = 0.299, kb = 0.114 }, + bt709 = { kr = 0.2126, kb = 0.0722 }, +} + + + +local cache= {} +local function coeffs(range, matrix) +local key = (range or "limited") .. (matrix or "bt601") + local c = cache[key] + if c then + return c + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ys = full and 1 or 255 / 219 + local cs = full and 1 or 255 / 224 + c = { + ys = floor(ys * 65536 + 0.5), + yo = full and 0 or 16, + crv = floor(2 * (1 - kr) * cs * 65536 + 0.5), + cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5), + cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5), + cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5), + cs = cs, + } + cache[key] = c + return c +end + +-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279 +local CLIP = bcreate(2304) +for i = 0, 2303 do + writeu8(CLIP, i, math.clamp(i - 1024, 0, 255)) +end + +-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with +-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2)) +function Yuv.toRgba(src, w, h, uo, vo, cw, range, matrix, out) +local dst = out or bcreate(w * h * 4) + local c = coeffs(range, matrix) + local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu + local ch = math.floor((h + 1) / 2 +) if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then + return dst + end + for y = 0, h - 1 do + local yrow = y * w + local crow = (math.floor(y / 2)) * cw + local o = yrow * 4 + for x = 0, w - 1, 2 do + local ci = crow + (math.floor(x / 2)) + local u = readu8(src, uo + ci) - 128 + local v = readu8(src, vo + ci) - 128 + local rv = math.floor((crv * v + 32768) / 65536 +) local gv = math.floor((cgu * u + cgv * v + 32768) / 65536 +) local bu = math.floor((cbu * u + 32768) / 65536 +) local yy = math.floor((ys * (readu8(src, yrow + x) - yo) + 32768) / 65536 )+ 1024 + writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + if x + 1 < w then + yy = math.floor((ys * (readu8(src, yrow + x + 1) - yo) + 32768) / 65536 )+ 1024 + writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000) + end + o =o+ 8 + end + end + return dst +end + +-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p +function Yuv.fromRgba(src, w, h, range, matrix, out) +local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local uo, vo = w * h, w * h + cw * ch + local dst = out or bcreate(w * h + 2 * cw * ch) + if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then + return dst + end + local m = MATRIX[matrix or "bt601"] or MATRIX.bt601 + local kr, kb = m.kr, m.kb + local kg = 1 - kr - kb + local full = range == "full" + local ysc = full and 1 or 219 / 255 + local csc = full and 1 or 224 / 255 + local yof = full and 0.5 or 16.5 + -- fixed point x 65536 + local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5) + local yoff = floor(yof * 65536) + local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5) + local ub = floor(0.5 * csc * 65536 + 0.5) + local vr = ub + local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5) + local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5) + local coff4 = floor(128.5 * 65536) * 4 + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, readu8(CLIP, math.floor((yr * r + yg * g + yb * b + yoff) / 65536 )+ 1024)) + end + for cy = 0, ch - 1 do + local y0 = cy * 2 + local y1 = (y0 + 1 < h and((y0 + 1 ))or(y0 +)) for cx = 0, cw - 1 do + local x0 = cx * 2 + local x1 = (x0 + 1 < w and((x0 + 1 ))or(x0 +)) local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4 + local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d) + local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1) + local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2) + local i = cy * cw + cx + writeu8(dst, uo + i, readu8(CLIP, math.floor((ur * r + ug * g + ub * b + coff4) / 262144 )+ 1024)) + writeu8(dst, vo + i, readu8(CLIP, math.floor((vr * r + vg * g + vb * b + coff4) / 262144 )+ 1024)) + end + end + return dst +end + +-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent +local function info(img) +local m = img.meta + local y = m and m.yuv + if type(y) == "table" then + return y.range or "limited", y.matrix or "bt601" + end + local src = m and m.source + if type(src) == "table" and src.range == "full" then + return "full", "bt601" + end + return "limited", "bt601" +end +Yuv.info = info + +-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer +function Yuv.planes(w, h) +local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) return w * h, w * h + cw * ch, cw, ch +end + +-- FULL_Y / FULL_C: limited -> full range sample maps +local FULL_Y = bcreate(256) +local FULL_C = bcreate(256) +for v = 0, 255 do + writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255)) + writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255)) +end + +-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned) +function Yuv.toFullRange(img) +if img.format ~= "yuv420p" or info(img) == "full" then + return img + end + local w, h = img.width, img.height + local out = Types.Image.new(w, h, "yuv420p") + local src, dst = img.pixels, out.pixels + local ny = w * h + local n = math.min(buffer.len(src), buffer.len(dst)) + for i = 0, math.min(ny, n) - 1 do + writeu8(dst, i, readu8(FULL_Y, readu8(src, i))) + end + for i = ny, n - 1 do + writeu8(dst, i, readu8(FULL_C, readu8(src, i))) + end + out.meta.yuv = { range = "full", matrix = select(2, info(img)) } + out.meta.source = img.meta.source + return out +end + +-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats) +function Yuv.imageToRgba(img) +if img.format == "rgba8" then + return img + end + if img.format ~= "yuv420p" then + return nil + end + local w, h = img.width, img.height + local uo, vo, cw = Yuv.planes(w, h) + local range, matrix = info(img) + local out = Types.Image.new(w, h, "rgba8") + Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels) + out.meta.source = img.meta.source + return out +end + +-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix) +function Yuv.imageFromRgba(img, range, matrix) +if img.format == "yuv420p" then + return img + end + if img.format ~= "rgba8" then + return nil + end + local out = Types.Image.new(img.width, img.height, "yuv420p") + Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels) + out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" } + out.meta.source = img.meta.source + return out +end + +-- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) +local function scalePlane(src, so, sw, sh, dst, d0, dw, dh) + local fx, fy = sw / dw, sh / dh + for y = 0, dh - 1 do + local sy = (y + 0.5) * fy - 0.5 + if sy < 0 then + sy = 0 + end + local y0 = floor(sy) + if y0 > sh - 1 then + y0 = sh - 1 + end + local y1 = (y0 < sh - 1 and((y0 + 1 ))or(y0 +)) local wy = floor((sy - y0) * 256) + local r0, r1 = so + y0 * sw, so + y1 * sw + local o = d0 + y * dw + for x = 0, dw - 1 do + local sx = (x + 0.5) * fx - 0.5 + if sx < 0 then + sx = 0 + end + local x0 = floor(sx) + if x0 > sw - 1 then + x0 = sw - 1 + end + local x1 = (x0 < sw - 1 and((x0 + 1 ))or(x0 +)) local wx = floor((sx - x0) * 256) + local a = readu8(src, r0 + x0) * (256 - wx) + readu8(src, r0 + x1) * wx + local b = readu8(src, r1 + x0) * (256 - wx) + readu8(src, r1 + x1) * wx + writeu8(dst, o + x, math.floor((a * (256 - wy) + b * wy + 32768) / 65536)) + end + end +end + +-- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). +-- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). +function Yuv.scale(src, w, h, width, height, out) +local dw= math.max(1, floor(width)) + local dh= math.max(1, floor(height)) + local cw= math.floor((w + 1) / 2 +) local ch= math.floor((h + 1) / 2 +) local dcw= math.floor((dw + 1) / 2 +) local dch= math.floor((dh + 1) / 2 +) local size = dw * dh + 2 * dcw * dch + local dst = (out and buffer.len(out) >= size and{out }or{(bcreate(size) +)})[1] if w < 1 or h < 1 or buffer.len(src) < w * h + 2 * cw * ch then + return dst + end + scalePlane(src, 0, w, h, dst, 0, dw, dh) + scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch) + scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch) + return dst +end + +function Yuv.imageScale(img, dw, dh) +local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p") + Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels) + out.meta = table.clone(img.meta or {}) + return out +end + +return Yuv +end +__FILES["codecs/model/Draco"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). +-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. +-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions +-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology +-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / +-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, +-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal +-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the +-- dequantization). +-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). +-- +-- local Draco = require("rosetta.codecs.model.Draco") +-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string +-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) +-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, +-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } +-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) +-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } +-- +-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Attributes = __include("codecs/model/Draco/Attributes") + +local Draco = {} + +local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" } +local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" } +Draco.ATTRIBUTE_NAMES = NAMES +Draco.DATA_TYPES = TYPES + +-- sniff(buf, off?) -> whether the bytes start with "DRACO" + + + + + + + + + + + + + + + + + + + + + + +function Draco.sniff(buf, off) +local o = off or 0 + return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" +end + +local function header(d) +if Reader.remaining(d) < 11 then + return nil, "truncated header" + end + if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then + return nil, "not Draco data" + end + d.pos =d.pos+ 5 + local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + local flags = Reader.u16(d) + if kind > 1 then + return nil, "unsupported: geometry type " .. kind + end + return { major = major, minor = minor, kind = kind == 0 and"points" or"mesh", method = method, flags = flags }, nil +end + +-- info(buf, off?, len?) -> the header +function Draco.info(src, off, len) +local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local d = Reader.new(buf, o, o + l, 0) + local h, err = header(d) + if not h then + return nil, Err.from(err, 0) + end + return h, nil +end + +local function metadataElement(d, depth) +if depth > 1000 then + return nil + end + local m= { entries = {}, children = {} } + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + for _ = 1, n do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos =d.pos+ nameLen + local size = Reader.varint(d) + if d.bad or size == 0 or size > Reader.remaining(d) then + return nil + end + local v = buffer.create(size) + buffer.copy(v, 0, d.b, d.pos, size) + d.pos =d.pos+ size + m.entries[name] = v + end + local subs = Reader.varint(d) + if d.bad or subs > Reader.remaining(d) then + return nil + end + for _ = 1, subs do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos =d.pos+ nameLen + local child = metadataElement(d, depth + 1) + if not child then + return nil + end + m.children[name] = child + end + return m +end + +local function metadata(d) +local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + local atts= {} + for _ = 1, n do + local id = Reader.varint(d) + local m = metadataElement(d, 0) + if not m then + return nil + end + atts[id] = m + end + local m = metadataElement(d, 0) + if not m then + return nil + end + m.attributes = atts + return m +end + +local WRITE= { + [1] = buffer.writei8, + [2] = buffer.writeu8, + [3] = buffer.writei16, + [4] = buffer.writeu16, + [5] = buffer.writei32, + [6] = buffer.writeu32, + [9] = buffer.writef32, + [11] = buffer.writeu8, +} + +-- per point output buffer of an attribute +local function expand(a, numPoints) +local size = Attributes.DT_LENGTH[a.dataType] + local comps = a.comps + local stride = size * comps + local out = buffer.create(numPoints * stride) + local map = a.map + local n = a.numValues + if a.raw then + local raw = a.raw +for p = 0, numPoints - 1 do + local e = (map and{map[p + 1] }or{p +})[1] if e >= n then + return nil, "attribute value out of range" + end + buffer.copy(out, p * stride, raw, e * stride, stride) + end + return out, nil + end + local vals = a.values +local w = WRITE[a.dataType] + if not w then + return nil, "unsupported: data type " .. a.dataType + end + for p = 0, numPoints - 1 do + local e = (map and{map[p + 1] }or{p +})[1] if e >= n then + return nil, "attribute value out of range" + end + local o = p * stride + local k = e * comps + for c = 1, comps do + w(out, o, vals[k + c]) + o =o+ size + end + end + return out, nil +end + +local function decode(buf, o, l, opts) +local d = Reader.new(buf, o, o + l, 0) + local h, herr = header(d) + if not h then + return nil, herr, nil + end + local ver = h.major * 256 + h.minor + local maxVer = h.kind == "points" and 0x0203 or 0x0202 + if h.major < 1 or ver > maxVer then + return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil + end + d.ver = ver + local maxPoints = (opts and opts.maxPoints) or 2 ^ 24 + local maxFaces = (opts and opts.maxFaces) or 2 ^ 24 + local meta= nil + if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then + meta = metadata(d) + if not meta then + return nil, d.bad or "bad metadata", nil + end + end + local mesh= nil + local numPoints = 0 + local method + if h.kind == "mesh" then + if h.method == 0 then + method = "sequential" + local m, err = Connectivity.sequential(d) + if not m then + return nil, err, nil + end + mesh = m + elseif h.method == 1 then + method = "edgebreaker" + local kind = Reader.u8(d) + if d.bad then + return nil, d.bad, nil + end + if kind > 2 then + return nil, "unknown edgebreaker traversal " .. kind, nil + end + local m, err = Connectivity.edgebreaker(d, kind) + if not m then + return nil, err, nil + end + mesh = m + else + return nil, "unsupported: mesh encoding method " .. h.method, nil + end + local m = mesh +if m.numFaces > maxFaces then + return nil, "too many faces", "limit" + end + numPoints = m.numPoints + else + if h.method > 1 then + return nil, "unsupported: point cloud encoding method " .. h.method, nil + end + method = h.method == 1 and"kdtree" or"sequential" + numPoints = Reader.i32(d) + if d.bad then + return nil, d.bad, nil + end + if numPoints < 0 then + return nil, "bad point count", nil + end + end + if numPoints > maxPoints then + return nil, "too many points", "limit" + end + local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" }) + if not attrs then + return nil, aerr, nil + end + local g= { + kind = h.kind, + version = h.major .. "." .. h.minor, + method = method, + numPoints = numPoints, + numFaces = 0, + indices = nil, + attributes = {}, + metadata = meta, + } + if mesh then + local nf = mesh.numFaces + local idx = buffer.create(nf * 12) + local faces = mesh.faces + for i = 1, nf * 3 do + local v = faces[i] + if v < 0 or v >= numPoints then + return nil, "face index out of range", nil + end + buffer.writeu32(idx, (i - 1) * 4, v) + end + g.numFaces = nf + g.indices = idx + end + for _, a in __iter(attrs) do + local data, err = expand(a, numPoints) + if not data then + return nil, err, nil + end + table.insert(g.attributes, { + name = NAMES[a.type] or "GENERIC", + typeId = a.type, + uniqueId = a.uniqueId, + components = a.comps, + type = TYPES[a.dataType], + normalized = a.normalized, + data = data, + }) + end + return g, nil, nil +end + +-- decode(src, off?, len?, opts?) -> Geometry | nil, Err +function Draco.decode(src, off, len, opts) +local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local ok, g, msg, kind = pcall(decode, buf, o, l, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g)) + end + if not g then + return nil, Err.from("draco: " .. tostring(msg), nil, kind or (string.find(tostring(msg), "^unsupported") and"unsupported" or(string.find(tostring(msg), "truncated") and"truncated" or nil))) + end + return g, nil +end + +-- attribute(g, uniqueId) -> the attribute with that unique id +function Draco.attribute(g, uniqueId) +for _, a in __iter(g.attributes) do + if a.uniqueId == uniqueId then + return a + end + end + return nil +end + +return Draco +end +__FILES["codecs/model/Draco/Attributes"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear +-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute +-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to +-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream +-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ +-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; +-- Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Predict = __include("codecs/model/Draco/Predict") +local KdTree = __include("codecs/model/Draco/KdTree") + +local Attributes = {} + +-- data type ids (draco::DataType) -> byte length + + +local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 } +Attributes.DT_LENGTH = DT_LENGTH +-- the geometry the attributes decode against + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function zigzag(v) +if v % 2 == 1 then + return -(math.floor(v / 2)) - 1 + end + return math.floor(v / 2 +)end + +-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to +-- integers unless the scheme works in floats) +local function parentGetter(ver, pos, floats) +local old = ver < 0x0200 + local vals = (old and{pos.values }or{pos.portable +})[1] if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then + return nil + end + local map = pos.map + local trunc = old and not floats + return function(point) +local e = (map and{(map[point + 1] or 0) }or{point +})[1] local o = e * 3 + local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0 + if trunc then + x = (x < 0 and{(math.ceil(x) )}or{(math.floor(x) +)})[1] y = (y < 0 and{(math.ceil(y) )}or{(math.floor(y) +)})[1] z = (z < 0 and{(math.ceil(z) )}or{(math.floor(z) +)})[1] end + return x, y, z + end +end + +local function decodeIntegerValues(d, a, points, scheme) +local comps = a.seqType == 3 and 2 or a.comps + local n = #points + local numValues = n * comps + if n == 0 then + return false, "no values" + end + local compressed = Reader.u8(d) + if d.bad then + return false, d.bad + end + local vals +if compressed > 0 then + local s = Reader.symbols(d, numValues, comps) + if not s then + return false, d.bad or "bad values" + end + vals = s + else + local nb = Reader.u8(d) + if d.bad then + return false, d.bad + end + if nb < 1 or nb > 4 then + return false, "bad value byte count" + end + if Reader.remaining(d) < nb * numValues then + return false, "truncated values" + end + vals = table.create(numValues, 0) + local b, p = d.b, d.pos + if nb == 4 then + for i = 1, numValues do + vals[i] = buffer.readu32(b, p) + p =p+ 4 + end + elseif nb == 1 then + for i = 1, numValues do + vals[i] = buffer.readu8(b, p) + p =p+ 1 + end + elseif nb == 2 then + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + p =p+ 2 + end + else + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 + p =p+ 3 + end + end + d.pos = p + end + if not scheme or not scheme.tr.positive then + for i = 1, numValues do + vals[i] = zigzag(vals[i]) + end + else + local i32 = Predict.i32 + for i = 1, numValues do + vals[i] = i32(vals[i]) + end + end + if scheme then + if not Predict.decodeData(scheme, d) then + return false, d.bad or "bad prediction data" + end + local ok, err = Predict.compute(scheme, vals, n, comps, points) + if not ok then + return false, err + end + end + a.portable = vals + a.numValues = n + return true, nil +end + +local function decodeQuantInfo(d, a) +local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false + end + a.quant = { min = mins, range = range, bits = bits } + return true +end + +-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors +local function storeValues(a) +local src = a.portable +local n = a.numValues + local fround = Predict.fround + if a.seqType == 1 then + local dt = a.dataType + local out = table.create(n * a.comps, 0) + for i = 1, n * a.comps do + local v = src[i] + if dt == 1 then + v = (v + 128) % 256 - 128 + elseif dt == 2 or dt == 11 then + v =v% 256 + elseif dt == 3 then + v = (v + 32768) % 65536 - 32768 + elseif dt == 4 then + v =v% 65536 + elseif dt == 6 then + v =v% 4294967296 + elseif dt ~= 5 then + return false, "unsupported: integer attribute of data type " .. dt + end + out[i] = v + end + a.values = out + elseif a.seqType == 2 then + local q = a.quant + if not q then + return false, "no quantization data" + end + local maxQ = 2 ^ q.bits - 1 + local delta = fround(q.range / fround(maxQ)) + local comps = a.comps + local mins = q.min + local out = table.create(n * comps, 0) + local k = 1 + for _ = 1, n do + for c = 1, comps do + out[k] = fround(fround(fround(src[k]) * delta) + mins[c]) + k =k+ 1 + end + end + a.values = out + elseif a.seqType == 3 then + local o = Predict.octahedron(a.octBits or 0) + if not o then + return false, "bad normal quantization" + end + local out = table.create(n * 3, 0) + for i = 0, n - 1 do + local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2]) + out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z + end + a.values = out + end + return true, nil +end + +-- decodes every attribute; returns them in attribute id order +function Attributes.decode(d, g) +local ver = d.ver + local numDecoders = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local mesh = g.mesh + local decoders= {} + for i = 0, numDecoders - 1 do + local dec= { attrs = {}, traversal = nil, md = nil, points = nil } + if g.edgebreaker and mesh then + local attDataId = Reader.i8(d) + local decoderType = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local ad = nil + if attDataId >= 0 then + ad = mesh.attrData[attDataId + 1] + if not ad or ad.decoderId >= 0 then + return nil, "bad attribute data id" + end + ad.decoderId = i + else + if mesh.posDecoderId >= 0 then + return nil, "two position decoders" + end + mesh.posDecoderId = i + end + local method = 0 + if ver >= 0x0102 then + method = Reader.u8(d) + if d.bad or method >= 2 then + return nil, "bad traversal method" + end + end + local ct = mesh.ct +local enc + if decoderType == 0 then + if ad then + enc = ad.enc + ad.used = false + else + enc = mesh.posEnc +end + dec.traversal = { ct = ct, enc = enc, method = method } + else + if method ~= 0 or not ad then + return nil, "bad corner attribute decoder" + end + local cad = ad +enc = cad.enc + dec.traversal = { ct = cad.ct , enc = enc, method = 0 } + end + -- prediction data: the attribute's own corner table when its seams are in use + local pct = (ad and ad.used and{ad.ct }or{ct +})[1] dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } + end + decoders[i + 1] = dec + end + -- the attribute descriptors + local all= {} + for _, dec in __iter(decoders) do + local n = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if n == 0 or n > 5 * Reader.remaining(d) then + return nil, "bad attribute count" + end + for _ = 1, n do + local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + if d.bad then + return nil, d.bad + end + if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then + return nil, "bad attribute descriptor" + end + local uniqueId = (ver < 0x0103 and{(Reader.u16(d) )}or{(Reader.varint(d) +)})[1] local a= { + id = #all, + type = attType, + dataType = dataType, + comps = comps, + normalized = normalized > 0, + uniqueId = uniqueId, + seqType = 0, + map = nil, + numValues = 0, + } + table.insert(all, a) + table.insert(dec.attrs, a) + end + for _, a in __iter((g.kdTree and{} or dec.attrs)) do + local t = Reader.u8(d) + if d.bad then + return nil, d.bad + end + if t > 3 then + return nil, "unknown attribute decoder " .. t + end + if (t == 2 or t == 3) and a.dataType ~= 9 then + return nil, "quantized attribute is not f32" + end + if t == 3 and a.comps ~= 3 then + return nil, "normal attribute without 3 components" + end + a.seqType = t + end + end + if d.bad then + return nil, d.bad + end + local function named(t) +for _, a in __iter(all) do + if a.type == t then + return a + end + end + return nil + end + -- decode + for _, dec in __iter(decoders) do +local __DARKLUA_CONTINUE_17=false repeat if g.kdTree then + local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) + if not ok then + return nil, err + end +__DARKLUA_CONTINUE_17=true break + end + local points +local trav = dec.traversal + if trav then + local faces = (mesh ).faces + local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method) + if not p then + return nil, "bad attribute traversal" + end + points = p + local numPoints = (mesh ).numPoints + for _, a in __iter(dec.attrs) do + local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints) + if not m then + return nil, "bad attribute mapping" + end + a.map = m + end + else + points = table.create(g.numPoints, 0) + for i = 1, g.numPoints do + points[i] = i - 1 + end + end + dec.points = points + -- portable values + for _, a in __iter(dec.attrs) do +local __DARKLUA_CONTINUE_20=false repeat if a.seqType == 0 then + local stride = DT_LENGTH[a.dataType] * a.comps + local size = #points * stride + if Reader.remaining(d) < size then + return nil, "truncated attribute values" + end + local raw = buffer.create(size) + buffer.copy(raw, 0, d.b, d.pos, size) + d.pos =d.pos+ size + a.raw = raw + a.numValues = #points +__DARKLUA_CONTINUE_20=true break + end + local psm = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if psm < -2 or psm >= 7 then + return nil, "bad prediction scheme" + end + local scheme= nil + if psm ~= -2 then + local ptt = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if ptt < -1 or ptt >= 4 then + return nil, "bad prediction transform" + end + if a.seqType == 3 then + if ptt == 2 or ptt == 3 then + scheme = Predict.new(psm, Predict.transform(ptt), dec.md) + end + elseif ptt == 1 then + scheme = Predict.new(psm, Predict.transform(1), dec.md) + end + end + if scheme and Predict.needsParent(scheme) then + local pos = named(0) + local getter = pos and parentGetter(ver, pos, scheme.method == 3) + if not getter then + return nil, "prediction needs the decoded positions" + end + scheme.parent = getter + end + if ver < 0x0200 then + if a.seqType == 2 and not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + local ok, err = decodeIntegerValues(d, a, points, scheme) + if not ok then + return nil, err + end + a.scheme = scheme + if ver < 0x0200 then + local ok2, err2 = storeValues(a) + if not ok2 then + return nil, err2 + end + end +__DARKLUA_CONTINUE_20=true until true if not __DARKLUA_CONTINUE_20 then break end end + -- data needed by the transforms + if ver >= 0x0200 then + for _, a in __iter(dec.attrs) do + if a.seqType == 2 then + if not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + end + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + if d.bad then + return nil, d.bad + end + for _, a in __iter(dec.attrs) do + if a.seqType ~= 0 then + local ok, err = storeValues(a) + if not ok then + return nil, err + end + end + end + end +__DARKLUA_CONTINUE_17=true until true if not __DARKLUA_CONTINUE_17 then break end end + return all, nil +end + +return Attributes +end +__FILES["codecs/model/Draco/Connectivity"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) +-- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute +-- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers +-- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 +-- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, +-- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, +-- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +local Reader = __include("codecs/model/Draco/Reader") + +local Connectivity = {} +-- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner + + +-- encoding data of one attribute connectivity: vertex -> value index, value index -> corner + + + + + + + + + + + + + + +local TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E = 0, 1, 3, 5, 7 +local SYMBOL_TO_TOPOLOGY = { [0] = TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E } + +local function nextC(c) +if c < 0 then + return -1 + end + return (c % 3 == 2 and((c - 2 ))or((c + 1 +)))end +local function prevC(c) +if c < 0 then + return -1 + end + return (c % 3 == 0 and((c + 2 ))or((c - 1 +)))end +Connectivity.next = nextC +Connectivity.prev = prevC + +local function newEnc(nv) +return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } +end + +-- ------------------------------------------------------------------------------------------------ sequential +function Connectivity.sequential(d) +local numFaces, numPoints + if d.ver < 0x0202 then + numFaces, numPoints = Reader.u32(d), Reader.u32(d) + else + numFaces, numPoints = Reader.varint(d), Reader.varint(d) + end + if d.bad then + return nil, d.bad + end + if numFaces > math.floor(0xffffffff / 3 )or numFaces > math.floor(Reader.remaining(d) / 3 )then + return nil, "too many faces" + end + local method = Reader.u8(d) + local n = numFaces * 3 + local faces = table.create(n, 0) + if method == 0 then + local sym = Reader.symbols(d, n, 1) + if not sym then + return nil, d.bad or "bad indices" + end + local last = 0 + for i = 1, n do + local e = sym[i] + local diff = math.floor(e / 2 +) if e % 2 == 1 then + if diff > last then + return nil, "bad index delta" + end + diff = -diff + elseif diff > 0x7fffffff - last then + return nil, "bad index delta" + end + last =last+ diff + faces[i] = last + end + else + local b = d.b + if numPoints < 256 then + if d.pos + n > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu8(b, d.pos + i - 1) + end + d.pos =d.pos+ n + elseif numPoints < 65536 then + if d.pos + n * 2 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu16(b, d.pos + (i - 1) * 2) + end + d.pos =d.pos+ n * 2 + elseif numPoints < 2 ^ 21 and d.ver >= 0x0202 then + for i = 1, n do + faces[i] = Reader.varint(d) + end + else + if d.pos + n * 4 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu32(b, d.pos + (i - 1) * 4) + end + d.pos =d.pos+ n * 4 + end + end + if d.bad then + return nil, d.bad + end + return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil +end +-- ------------------------------------------------------------------------------------------------ edgebreaker +-- the traversal decoders: symbols, start face configurations, attribute seam bits +-- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. +-- Returns the decoder state and the buffer after them. + + + + + + + + + +local function standardStart(buf, numAttributeData, withSymbols) +local st= {} + if withSymbols then + local sym = Reader.copy(buf) + local size = Reader.startBits(sym, true) + if sym.bad then + buf.bad = sym.bad + return nil, buf + end + buf = Reader.copy(sym) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "traversal symbols past the end") + return nil, buf + end + buf.pos =buf.pos+ size + st.sym = sym + end + if buf.ver < 0x0202 then + local sf = Reader.copy(buf) + local size = Reader.startBits(sf, true) + if sf.bad then + buf.bad = sf.bad + return nil, buf + end + buf = Reader.copy(sf) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "start faces past the end") + return nil, buf + end + buf.pos =buf.pos+ size + st.startBuf = sf + else + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.startDec = bd + end + st.seams = {} + for i = 1, numAttributeData do + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.seams[i] = bd + end + return st, buf +end + +local function standardSymbol(sym) +local s = Reader.bits(sym, 1) + if s == TOPOLOGY_C then + return s + end + return s + Reader.bits(sym, 2) * 2 +end + +-- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +local function makeTraversal(kind, buf, numAttributeData, numVertices, numFaces, ct) +local ver = buf.ver + local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) + if not st then + return nil, out + end + local function startFace() +if st.startBuf then + return Reader.bits(st.startBuf, 1) == 1 + end + return Reader.bit(st.startDec) + end + local function seam(i) +return Reader.bit(st.seams[i + 1]) + end + local valences = table.create(numVertices, 0) + local c2v = ct.c2v + local function vtx(c) +return c < 0 and-1 or(c2v[c + 1] or -1) + end + local function addValence(v, k) + if v >= 0 and v < numVertices then +do local __DARKLUA_VAR=v + 1 valences[__DARKLUA_VAR]=valences[__DARKLUA_VAR]+ k +end end + end + local function mergeVertices(dest, src) + if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then +do local __DARKLUA_VAR=dest + 1 valences[__DARKLUA_VAR]=valences[__DARKLUA_VAR]+ valences[src + 1] +end end + end + local lastSymbol = -1 + local function updateValences(corner) + local nx, pv = nextC(corner), prevC(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_S then + addValence(vtx(nx), 1) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_R then + addValence(vtx(corner), 1) + addValence(vtx(nx), 1) + addValence(vtx(pv), 2) + elseif lastSymbol == TOPOLOGY_L then + addValence(vtx(corner), 1) + addValence(vtx(nx), 2) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_E then + addValence(vtx(corner), 2) + addValence(vtx(nx), 2) + addValence(vtx(pv), 2) + end + end + + if kind == 0 then + local sym = st.sym + return { + decodeSymbol = function() +return standardSymbol(sym) + end, + newActiveCorner = function(_c) end, + mergeVertices = function(_a, _b) end, + startFace = startFace, + seam = seam, + }, out + elseif kind == 1 then + -- predictive (deprecated): a bit says whether the predicted symbol (from the pivot's valence) is right + local n = Reader.i32(out) + if out.bad or n < 0 or n >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local pred = Reader.bitDecoder(out) + if not pred then + return nil, out + end + local sym = st.sym + local predicted = -1 + return { + decodeSymbol = function() +if predicted ~= -1 and Reader.bit(pred) then + lastSymbol = predicted + return predicted + end + lastSymbol = standardSymbol(sym) + return lastSymbol + end, + newActiveCorner = function(corner) + updateValences(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then + local pivot = vtx(nextC(corner)) + local val = (pivot >= 0 and pivot < numVertices and{valences[pivot + 1] }or{0 +})[1] predicted = (val < 6 and{TOPOLOGY_R }or{TOPOLOGY_C +})[1] else + predicted = -1 + end + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out + end + -- valence: per-context symbol streams chosen by the valence of the next vertex + local minValence, maxValence = 2, 7 + if ver < 0x0202 then + local nSplit = Reader.count(out, 0x0200) + if out.bad or nSplit >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local mode = Reader.i8(out) + if out.bad or mode ~= 0 then + Reader.fail(out, "unsupported valence mode") + return nil, out + end + end + local contexts= {} + local counters= {} + for i = 1, maxValence - minValence + 1 do + local n = Reader.varint(out) + if out.bad then + return nil, out + end + if n > numFaces then + Reader.fail(out, "too many context symbols") + return nil, out + end + counters[i] = n + contexts[i] = {} + if n > 0 then + -- C++ ignores a failure here (the symbols stay zero) + local save = out.bad + local syms = Reader.symbols(out, n, 1) + if syms then + contexts[i] = syms + else + out.bad = save + end + end + end + local active = -1 + local sym = st.sym + return { + decodeSymbol = function() +if active ~= -1 then + local k = counters[active + 1] - 1 + counters[active + 1] = k + if k < 0 then + return -1 + end + local id = contexts[active + 1][k + 1] or 0 + if id > 4 then + return -1 + end + lastSymbol = SYMBOL_TO_TOPOLOGY[id] + elseif ver < 0x0202 then + lastSymbol = standardSymbol(sym) + else + lastSymbol = TOPOLOGY_E + end + return lastSymbol + end, + newActiveCorner = function(corner) + updateValences(corner) + local v = vtx(nextC(corner)) + local val = (v >= 0 and v < numVertices and{valences[v + 1] }or{0 +})[1] if val < minValence then + val = minValence + elseif val > maxValence then + val = maxValence + end + active = val - minValence + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out +end + +-- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil +local function splitEvents(eb, numFaces) +local ver = eb.ver + local n = Reader.count(eb, 0x0200) + if eb.bad then + return nil + end + local splits = {} + if n > 0 then + if n > numFaces then + Reader.fail(eb, "too many topology splits") + return nil + end + if ver < 0x0102 then + for i = 1, n do + local split = Reader.u32(eb) + local source = Reader.u32(eb) + local edge = Reader.u8(eb) % 2 + splits[i] = { source = source, split = split, edge = edge } + end + else + local last = 0 + for i = 1, n do + local source = Reader.varint(eb) + last + local delta = Reader.varint(eb) + if eb.bad then + return nil + end + if delta > source then + Reader.fail(eb, "bad topology split") + return nil + end + splits[i] = { source = source, split = source - delta, edge = 0 } + last = source + end + Reader.startBits(eb, false) + for i = 1, n do + local e = Reader.bits(eb, ver < 0x0202 and 2 or 1) + splits[i].edge = e % 2 + end + Reader.endBits(eb) + end + end + -- hole events (before 2.1): read and ignored + local holes = 0 + if ver < 0x0200 then + holes = Reader.u32(eb) + elseif ver < 0x0201 then + holes = Reader.varint(eb) + end + if eb.bad then + return nil + end + if holes > Reader.remaining(eb) then + Reader.fail(eb, "too many hole events") + return nil + end + for _ = 1, holes do + if ver < 0x0102 then + Reader.i32(eb) + else + Reader.varint(eb) + end + end + if eb.bad then + return nil + end + return splits +end + +-- MeshAttributeCornerTable from the seam corners (InitEmpty, AddSeamEdge, RecomputeVertices) +local function attributeTable(ct, seams) +local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nc = ct.nf * 3 + local function V(c) +return c < 0 and-1 or(c2v[c + 1] or -1) + end + local edgeSeam= {} + local vertSeam= {} + for _, c in __iter(seams) do + edgeSeam[c] = true + vertSeam[V(nextC(c))] = true + vertSeam[V(prevC(c))] = true + local o = c < 0 and-1 or(opp[c + 1] or -1) + if o ~= -1 then + edgeSeam[o] = true + vertSeam[V(nextC(o))] = true + vertSeam[V(prevC(o))] = true + end + end + local aopp = table.create(nc, -1) + for c = 0, nc - 1 do + aopp[c + 1] = edgeSeam[c] and-1 or(opp[c + 1] or -1) + end + local ac2v = table.create(nc, -1) + local almc= {} + local num = 0 + local function swingLeftA(c) +local n = nextC(c) + local o = n < 0 and-1 or aopp[n + 1] + return nextC(o) + end + local function swingRight(c) +local p = prevC(c) + local o = p < 0 and-1 or(opp[p + 1] or -1) + return prevC(o) + end + for v = 0, ct.nv - 1 do + local c = lmc[v + 1] or -1 + if c ~= -1 then + local id = num + num =num+ 1 + local first = c + if vertSeam[v] then + local act = swingLeftA(first) + while act ~= -1 do + first = act + act = swingLeftA(act) + if act == c then + return nil + end + end + end + ac2v[first + 1] = id + table.insert(almc, first) + local act = swingRight(first) + local guard = 0 + while act ~= -1 and act ~= first do + if edgeSeam[nextC(act)] then + id = num + num =num+ 1 + table.insert(almc, act) + end + ac2v[act + 1] = id + act = swingRight(act) + guard =guard+ 1 + if guard > nc then + return nil + end + end + end + end + return { c2v = ac2v, opp = aopp, lmc = almc, nv = num, nf = ct.nf, vertSeam = vertSeam } +end + +-- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) +function Connectivity.edgebreaker(d, traversalKind) +local ver = d.ver + if ver < 0x0202 then + Reader.count(d, 0x0200) -- num_new_vertices (unused) + end + local numEncodedVertices = Reader.count(d, 0x0200) + local numFaces = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces > math.floor(0xffffffff / 3 )then + return nil, "too many faces" + end + if numEncodedVertices > numFaces * 3 then + return nil, "more vertices than corners" + end + local minEdges = math.floor((3 * numFaces) / 2 +) local maxEdges = numEncodedVertices * (numEncodedVertices - 1) / 2 + if numEncodedVertices == 0 then + maxEdges = 0 + end + if maxEdges < minEdges then + return nil, "too few vertices for the faces" + end + local numAttributeData = Reader.u8(d) + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces < numSymbols or numFaces > numSymbols + math.floor(numSymbols / 3 )then + return nil, "bad symbol count" + end + local numSplitSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numSplitSymbols > numSymbols then + return nil, "bad split symbol count" + end + local maxVertices = numEncodedVertices + numSplitSymbols + + -- the corner table (filled lazily: nil = invalid) + local c2v= {} + local opp= {} + local lmc= {} + local nv = 0 + local ct= { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } + local notHole= {} + + local splits +local splitBytes = 0 + if ver < 0x0202 then + local size = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if size == 0 or size > Reader.remaining(d) then + return nil, "bad connectivity size" + end + local eb = Reader.new(d.b, d.pos + size, d.limit, ver) + splits = splitEvents(eb, numFaces) + if not splits then + return nil, eb.bad or "bad split events" + end + splitBytes = eb.pos - (d.pos + size) + else + splits = splitEvents(d, numFaces) + if not splits then + return nil, d.bad or "bad split events" + end + end + local splitData = splits + +local trav, after = makeTraversal(traversalKind, Reader.copy(d), numAttributeData, maxVertices, numFaces, ct) + if not trav then + return nil, after.bad or "bad traversal data" + end + + local function V(c) +return c < 0 and-1 or(c2v[c + 1] or -1) + end + local function O(c) +return c < 0 and-1 or(opp[c + 1] or -1) + end + local function setOpp(a, b) + if a >= 0 then + opp[a + 1] = b + end + if b >= 0 then + opp[b + 1] = a + end + end + local function setLmc(v, c) + if v >= 0 then + lmc[v + 1] = c + end + end + local function LMC(v) +return v < 0 and-1 or(lmc[v + 1] or -1) + end + local function addVertex() +nv =nv+ 1 + lmc[nv] = -1 + return nv - 1 + end + local function swingLeft(c) +return nextC(O(nextC(c))) + end + local function swingRight(c) +return prevC(O(prevC(c))) + end + + -- the symbols + local stack= {} + local sp = 0 + local splitActive= {} + local invalidVerts= {} + local removeInvalid = numAttributeData == 0 + local nf = 0 + for symbolId = 0, numSymbols - 1 do + local face = nf + nf =nf+ 1 + local checkSplit = false + local symbol = trav.decodeSymbol() + local corner = 3 * face + if symbol == TOPOLOGY_C then + if sp == 0 then + return nil, "bad traversal (C)" + end + local a = stack[sp] + local vx = V(nextC(a)) + local b = nextC(LMC(vx)) + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (C)" + end + setOpp(a, corner + 1) + setOpp(b, corner + 2) + local vap, vbn = V(prevC(a)), V(nextC(b)) + if vx == vap or vx == vbn then + return nil, "bad traversal (C)" + end + c2v[corner + 1] = vx + c2v[corner + 2] = vbn + c2v[corner + 3] = vap + setLmc(vap, corner + 2) + notHole[vx] = true + stack[sp] = corner + elseif symbol == TOPOLOGY_R or symbol == TOPOLOGY_L then + if sp == 0 then + return nil, "bad traversal (R / L)" + end + local a = stack[sp] + if O(a) ~= -1 then + return nil, "bad traversal (R / L)" + end + local oc, cl, cr + if symbol == TOPOLOGY_R then + oc, cl, cr = corner + 2, corner + 1, corner + else + oc, cl, cr = corner + 1, corner, corner + 2 + end + setOpp(oc, a) + local nvx = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + c2v[oc + 1] = nvx + setLmc(nvx, oc) + local vr = V(prevC(a)) + c2v[cr + 1] = vr + setLmc(vr, cr) + c2v[cl + 1] = V(nextC(a)) + stack[sp] = corner + checkSplit = true + elseif symbol == TOPOLOGY_S then + if sp == 0 then + return nil, "bad traversal (S)" + end + local b = stack[sp] + stack[sp] = nil + sp =sp- 1 + local pushed = splitActive[symbolId] + if pushed then + sp =sp+ 1 + stack[sp] = pushed + end + if sp == 0 then + return nil, "bad traversal (S)" + end + local a = stack[sp] + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (S)" + end + setOpp(a, corner + 2) + setOpp(b, corner + 1) + local vp = V(prevC(a)) + c2v[corner + 1] = vp + c2v[corner + 2] = V(nextC(a)) + local vbp = V(prevC(b)) + c2v[corner + 3] = vbp + setLmc(vbp, corner + 2) + local cn = nextC(b) + local vn = V(cn) + trav.mergeVertices(vp, vn) + setLmc(vp, LMC(vn)) + local first = cn + while cn ~= -1 do + c2v[cn + 1] = vp + cn = swingLeft(cn) + if cn == first then + return nil, "bad traversal (S loop)" + end + end + setLmc(vn, -1) + if removeInvalid then + table.insert(invalidVerts, vn) + end + stack[sp] = corner + elseif symbol == TOPOLOGY_E then + local v0 = addVertex() + c2v[corner + 1] = v0 + c2v[corner + 2] = addVertex() + c2v[corner + 3] = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + setLmc(v0, corner) + setLmc(v0 + 1, corner + 1) + setLmc(v0 + 2, corner + 2) + sp =sp+ 1 + stack[sp] = corner + checkSplit = true + else + return nil, "bad traversal symbol" + end + ct.nv = nv + trav.newActiveCorner(stack[sp]) + if checkSplit then + local encId = numSymbols - symbolId - 1 + while true do + local top = splitData[#splitData] + if not top then + break + end + if top.source > encId then + return nil, "bad split symbol id" + end + if top.source ~= encId then + break + end + splitData[#splitData] = nil + local act = stack[sp] + local newActive = (top.edge == 1 and{(nextC(act) )}or{(prevC(act) +)})[1] splitActive[numSymbols - top.split - 1] = newActive + end + end + end + if nv > maxVertices then + return nil, "too many vertices" + end + + -- start faces: interior faces that close the remaining holes + local initFaces = {} + while sp > 0 do + local corner = stack[sp] + stack[sp] = nil + sp =sp- 1 + if trav.startFace() then + if nf >= numFaces then + return nil, "too many faces" + end + local vn = V(nextC(corner)) + local b = nextC(LMC(vn)) + local vx = V(nextC(b)) + local c = nextC(LMC(vx)) + if corner == b or corner == c or b == c or O(corner) ~= -1 or O(b) ~= -1 or O(c) ~= -1 then + return nil, "bad start face" + end + local vp = V(nextC(c)) + local nc = 3 * nf + nf =nf+ 1 + setOpp(nc, corner) + setOpp(nc + 1, b) + setOpp(nc + 2, c) + c2v[nc + 1] = vx + c2v[nc + 2] = vp + c2v[nc + 3] = vn + for k = 0, 2 do + notHole[V(nc + k)] = true + end + table.insert(initFaces, nc) + end + end + if nf ~= numFaces then + return nil, "face count mismatch" + end + + -- compact the vertices removed by S symbols (no attribute data only) + local numVertices = nv + for _, inv in __iter(invalidVerts) do + local src = numVertices - 1 + while src >= 0 and LMC(src) == -1 do + numVertices =numVertices- 1 + src = numVertices - 1 + end + if src >= inv then + -- every corner of src (VertexCornersIterator: left, then right) + local start = LMC(src) + local corners = {} + local cc = start + local left = true + local guard = 0 + while cc ~= -1 do + table.insert(corners, cc) + guard =guard+ 1 + if guard > numFaces * 3 + 3 then + return nil, "bad vertex fan" + end + if left then + cc = swingLeft(cc) + if cc == -1 then + cc = swingRight(start) + left = false + elseif cc == start then + cc = -1 + end + else + cc = swingRight(cc) + end + end + for _, cid in __iter(corners) do + if V(cid) ~= src then + return nil, "bad vertex fan" + end + c2v[cid + 1] = inv + end + setLmc(inv, LMC(src)) + setLmc(src, -1) + notHole[inv] = notHole[src] + notHole[src] = true + numVertices =numVertices- 1 + end + end + + -- continue after the traversal data (and the split events before 2.2) + d.pos = after.pos + d.bad = after.bad + if ver < 0x0202 then + d.pos =d.pos+ splitBytes + end + + -- attribute seams + local attrData= {} + for i = 1, numAttributeData do + attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } + end + if numAttributeData > 0 then + for f = 0, numFaces - 1 do + local base = 3 * f + for k = 0, 2 do + local c = (k == 0 and{base }or{(k == 1 and((base + 1 ))or((base + 2 +)))})[1] local o = O(c) + if o == -1 then + for i = 1, numAttributeData do + table.insert(attrData[i].seams, c) + end + elseif ver < 0x0201 or math.floor(o / 3 )>= f then + for i = 1, numAttributeData do + if trav.seam(i - 1) then + table.insert(attrData[i].seams, c) + end + end + end + end + end + end + ct.nv = nv + for i = 1, numAttributeData do + local act = attributeTable(ct, attrData[i].seams) + if not act then + return nil, "bad attribute seams" + end + attrData[i].ct = act + attrData[i].enc = newEnc(math.max(act.nv, nv)) + end + local posEnc = newEnc(nv) + + -- AssignPointsToCorners + local faces = table.create(numFaces * 3, 0) + local numPoints + if numAttributeData == 0 then + for c = 0, numFaces * 3 - 1 do + faces[c + 1] = V(c) + end + numPoints = numVertices + else + numPoints = 0 + for v = 0, nv - 1 do + local c = LMC(v) + if c ~= -1 then + local first = c + if notHole[v] then + for i = 1, numAttributeData do + local act = attrData[i].ct +if act.vertSeam[V(c)] then + local vid = act.c2v[c + 1] + local a = swingRight(c) + local found = false + while a ~= c do + if a == -1 then + return nil, "bad seam fan" + end + if act.c2v[a + 1] ~= vid then + first = a + found = true + break + end + a = swingRight(a) + end + if found then + break + end + end + end + end + c = first + faces[c + 1] = numPoints + numPoints =numPoints+ 1 + local pc = c + c = swingRight(c) + local guard = 0 + while c ~= -1 and c ~= first do + local seam = false + for i = 1, numAttributeData do + local ac2v = (attrData[i].ct ).c2v + if ac2v[c + 1] ~= ac2v[pc + 1] then + seam = true + break + end + end + if seam then + faces[c + 1] = numPoints + numPoints =numPoints+ 1 + else + faces[c + 1] = faces[pc + 1] + end + pc = c + c = swingRight(c) + guard =guard+ 1 + if guard > numFaces * 3 then + return nil, "bad vertex fan" + end + end + end + end + end + for k = 1, nv do + if not lmc[k] then + lmc[k] = -1 + end + end + return { + faces = faces, + numFaces = numFaces, + numPoints = numPoints, + ct = ct, + attrData = attrData, + posEnc = posEnc, + posDecoderId = -1, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ traversal +-- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). +-- method 0 = depth first, 1 = max prediction degree. +function Connectivity.traverse(ct, faces, enc, method) +local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nf, nvt = ct.nf, ct.nv + local faceVisited = table.create(nf, false) + local vertVisited = table.create(nvt, false) + local points= {} + local v2e, e2c = enc.v2e, enc.e2c + local function V(c) +return c < 0 and-1 or(c2v[c + 1] or -1) + end + local function O(c) +return c < 0 and-1 or(opp[c + 1] or -1) + end + local function faceSeen(c) +if c < 0 then + return true + end + return faceVisited[math.floor(c / 3 )+ 1] == true + end + local function visit(v, c) +if v < 0 or v >= nvt then + return false + end + vertVisited[v + 1] = true + table.insert(points, faces[c + 1]) + table.insert(e2c, c) + v2e[v + 1] = enc.numValues + enc.numValues =enc.numValues+ 1 + return true + end + local function onBoundary(v) +local c = v < 0 and-1 or(lmc[v + 1] or -1) + return nextC(O(nextC(c))) == -1 + end + if method == 0 then + local stack= {} + for f = 0, nf - 1 do + local start = 3 * f + if not faceSeen(start) then + stack[1] = start + for k = #stack, 2, -1 do + stack[k] = nil + end + local nx, pv = V(nextC(start)), V(prevC(start)) + if nx == -1 or pv == -1 then + return nil + end + if not vertVisited[nx + 1] and not visit(nx, nextC(start)) then + return nil + end + if not vertVisited[pv + 1] and not visit(pv, prevC(start)) then + return nil + end + while #stack > 0 do +local __DARKLUA_CONTINUE_41=false repeat local c = stack[#stack] + if c == -1 or faceSeen(c) then + stack[#stack] = nil +__DARKLUA_CONTINUE_41=true break + end + while true do +local __DARKLUA_CONTINUE_42=false repeat faceVisited[math.floor(c / 3 )+ 1] = true + local v = V(c) + if v == -1 then + return nil + end + if not vertVisited[v + 1] then + local boundary = onBoundary(v) + if not visit(v, c) then + return nil + end + if not boundary then + c = O(nextC(c)) + if c == -1 then + -- C++ would index face -1 here; treat as done + stack[#stack] = nil + break + end +__DARKLUA_CONTINUE_42=true break + end + end + local rc, lc = O(nextC(c)), O(prevC(c)) + if faceSeen(rc) then + if faceSeen(lc) then + stack[#stack] = nil + break + end + c = lc + elseif faceSeen(lc) then + c = rc + else + stack[#stack] = lc + table.insert(stack, rc) + break + end +__DARKLUA_CONTINUE_42=true until true if not __DARKLUA_CONTINUE_42 then break end end +__DARKLUA_CONTINUE_41=true until true if not __DARKLUA_CONTINUE_41 then break end end + end + end + return points + end + -- max prediction degree + if nvt == 0 then + return points + end + local degree = table.create(nvt, 0) + local stacks= { {}, {}, {} } + local best = 0 + local function priority(c) +local v = V(c) + if v < 0 or v >= nvt then + return 0 + end + local p = 0 + if not vertVisited[v + 1] then +do local __DARKLUA_VAR=v + 1 degree[__DARKLUA_VAR]=degree[__DARKLUA_VAR]+ 1 +end p = degree[v + 1] > 1 and 1 or 2 + end + return p + end + for f = 0, nf - 1 do + local start = 3 * f + table.insert(stacks[1], start) + best = 0 + local nx, pv, tip = V(nextC(start)), V(prevC(start)), V(start) + for _, pair in __iter({ { nx, nextC(start) }, { pv, prevC(start) }, { tip, start } }) do + local v = pair[1] + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, pair[2]) + end + end + while true do + local c = -1 + for i = best, 2 do + local s = stacks[i + 1] + if #s > 0 then + c = s[#s] + s[#s] = nil + best = i + break + end + end + if c == -1 then + break + end + if not faceSeen(c) then + while true do +local __DARKLUA_CONTINUE_47=false repeat faceVisited[math.floor(c / 3 )+ 1] = true + local v = V(c) + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, c) + end + local rc, lc = O(nextC(c)), O(prevC(c)) + local rSeen, lSeen = faceSeen(rc), faceSeen(lc) + if not lSeen then + local p = priority(lc) + if rSeen and p <= best then + c = lc +__DARKLUA_CONTINUE_47=true break + end + table.insert(stacks[p + 1], lc) + if p < best then + best = p + end + end + if not rSeen then + local p = priority(rc) + if p <= best then + c = rc +__DARKLUA_CONTINUE_47=true break + end + table.insert(stacks[p + 1], rc) + if p < best then + best = p + end + end + break +until true if not __DARKLUA_CONTINUE_47 then break end end + end + end + end + return points +end + +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +function Connectivity.mapping(ct, faces, enc, numPoints) +local map = table.create(numPoints, 0) + local c2v, v2e = ct.c2v, enc.v2e + for c = 0, ct.nf * 3 - 1 do + local p = faces[c + 1] + local v = c2v[c + 1] or -1 + if v == -1 then + return nil + end + local e = v2e[v + 1] or 0 + if p >= numPoints or e >= numPoints then + return nil + end + map[p + 1] = e + end + return map +end + +return Connectivity +end +__FILES["codecs/model/Draco/Int64"] = function() +--!strict +-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / +-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both +-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +local Int64 = {} + +local P32 = 4294967296 +local P31 = 2147483648 + +function Int64.from(n) +if n >= 0 then + return (math.floor(n / P32)) % P32, n % P32 + end + local h, l = Int64.from(-n) + return Int64.neg(h, l) +end + +function Int64.neg(h, l) +if l == 0 then + return (P32 - h) % P32, 0 + end + return P32 - 1 - h, P32 - l +end + +function Int64.add(ah, al, bh, bl) +local l = al + bl + local c = 0 + if l >= P32 then + l =l- P32 + c = 1 + end + return (ah + bh + c) % P32, l +end + +function Int64.sub(ah, al, bh, bl) +local nh, nl = Int64.neg(bh, bl) + return Int64.add(ah, al, nh, nl) +end + +-- the product mod 2^64 (the same bits for signed and unsigned operands) +function Int64.mul(ah, al, bh, bl) +local a0, a1, a2, a3 = al % 65536, math.floor(al / 65536), ah % 65536, math.floor(ah / 65536 +) local b0, b1, b2, b3 = bl % 65536, math.floor(bl / 65536), bh % 65536, math.floor(bh / 65536 +) local c0 = a0 * b0 + local c1 = a1 * b0 + a0 * b1 + local c2 = a2 * b0 + a1 * b1 + a0 * b2 + local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3 + local lo = c0 + (c1 % 65536) * 65536 + local carry = math.floor(lo / P32 +) lo =lo% P32 + local hi = (math.floor(c1 / 65536 )+ c2 + (c3 % 65536) * 65536 + carry) % P32 + return hi, lo +end + +function Int64.isNeg(h) +return h >= P31 +end + +-- the signed value as a number (exact below 2^53 in magnitude) +function Int64.signed(h, l) +if h >= P31 then + return (h - P32) * P32 + l + end + return h * P32 + l +end + +-- the unsigned value as a number (rounded past 2^53) +function Int64.unsigned(h, l) +return h * P32 + l +end + +-- unsigned compare: -1, 0, 1 +function Int64.ucmp(ah, al, bh, bl) +if ah ~= bh then + return ah < bh and-1 or 1 + end + if al ~= bl then + return al < bl and-1 or 1 + end + return 0 +end + +-- signed compare: -1, 0, 1 +function Int64.cmp(ah, al, bh, bl) +local sa = (ah >= P31 and((ah - P32 ))or(ah +)) local sb = (bh >= P31 and((bh - P32 ))or(bh +)) if sa ~= sb then + return sa < sb and-1 or 1 + end + return Int64.ucmp(0, al, 0, bl) +end + +-- unsigned division (b ~= 0): quotient, remainder +function Int64.udivmod(ah, al, bh, bl) +if ah == 0 and bh == 0 then + return 0, math.floor(al / bl), 0, al % bl + end + local qh, ql, rh, rl = 0, 0, 0, 0 + for i = 63, 0, -1 do + -- r = r * 2 + bit i of a + local bit = (i >= 32 and(((math.floor(ah / 2 ^ (i - 32))) % 2 ))or(((math.floor(al / 2 ^ i)) % 2 +))) local over = rh >= P31 + rh = (rh * 2 + math.floor(rl / P31)) % P32 + rl = (rl * 2) % P32 + bit + if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then + rh, rl = Int64.sub(rh, rl, bh, bl) + if i >= 32 then + qh =qh+ 2 ^ (i - 32) + else + ql =ql+ 2 ^ i + end + end + end + return qh, ql, rh, rl +end + +-- signed division truncating toward zero (b ~= 0) +function Int64.div(ah, al, bh, bl) +local na, nb = ah >= P31, bh >= P31 + if na then + ah, al = Int64.neg(ah, al) + end + if nb then + bh, bl = Int64.neg(bh, bl) + end + local qh, ql = Int64.udivmod(ah, al, bh, bl) + if na ~= nb then + return Int64.neg(qh, ql) + end + return qh, ql +end + +-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included) +function Int64.isqrt(h, l) +if h == 0 and l == 0 then + return 0, 0 + end + local acth, actl = h, l + local sh, sl = 0, 1 + while Int64.ucmp(acth, actl, 0, 2) >= 0 do + sh, sl = Int64.add(sh, sl, sh, sl) + acth, actl = Int64.udivmod(acth, actl, 0, 4) + end + repeat + local qh, ql = Int64.udivmod(h, l, sh, sl) + local th, tl = Int64.add(sh, sl, qh, ql) + sh, sl = Int64.udivmod(th, tl, 0, 2) + if sh == 0 and sl == 0 then + return 0, 0 + end + local pph, ppl = Int64.mul(sh, sl, sh, sl) + until Int64.ucmp(pph, ppl, h, l) <= 0 + return sh, sl +end + +return Int64 +end +__FILES["codecs/model/Draco/KdTree"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder +-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the +-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from +-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ +-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, +-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +local Reader = __include("codecs/model/Draco/Reader") +local Predict = __include("codecs/model/Draco/Predict") + +local KdTree = {} +-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out + + + + + +local function direct(d) +local size = Reader.u32(d) + if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then + Reader.fail(d, "kd-tree: bad direct bits") + return nil + end + local b, base, words = d.b, d.pos, math.floor(size / 4 +) d.pos =d.pos+ size + local pos, used = 0, 0 + return { + next = function() +if pos >= words then + return 0 + end + local w = buffer.readu32(b, base + pos * 4) + local bit = bit32.extract(w, 31 - used) + used =used+ 1 + if used == 32 then + pos =pos+ 1 + used = 0 + end + return bit + end, + bits = function(n) +local remaining = 32 - used + if n <= remaining then + if pos >= words then + return nil + end + local w = buffer.readu32(b, base + pos * 4) + local v = bit32.extract(w, 32 - used - n, n) + used =used+ n + if used == 32 then + pos =pos+ 1 + used = 0 + end + return v + end + if pos + 1 >= words then + return nil + end + local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining) + local lo = n - remaining + pos =pos+ 1 + used = lo + local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo) + return hiBits * 2 ^ lo + loBits + end, + } +end + +local function rans(d) +local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + local function nextBit() +return Reader.bit(bd) and 1 or 0 + end + return { + next = nextBit, + bits = function(n) +local v = 0 + for _ = 1, n do + v = v * 2 + nextBit() + end + return v + end, + } +end + +local function folded(d) +local parts= {} + for i = 1, 32 do + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + parts[i] = bd + end + local main = Reader.bitDecoder(d) + if not main then + return nil + end + return { + next = function() +return Reader.bit(main ) and 1 or 0 + end, + bits = function(n) +local v = 0 + for i = 1, n do + v = v * 2 + (Reader.bit(parts[i]) and 1 or 0) + end + return v + end, + } +end + +local function msb(n) +local k = -1 + while n >= 1 do + n = math.floor(n / 2 +) k =k+ 1 + end + return k +end + +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +local function decodePoints(d, level, dim, expected) +local bitLength = Reader.u32(d) + local numPoints = Reader.u32(d) + if d.bad then + return nil, d.bad + end + if bitLength > 32 then + return nil, "kd-tree: bad bit length" + end + if numPoints ~= expected then + return nil, "kd-tree: point count mismatch" + end + local out= {} + if numPoints == 0 then + return out, nil + end + local numbers = (level >= 4 and{(folded(d) )}or{(level >= 2 and{(rans(d) )}or{(direct(d) +)})[1]})[1] local remainingBits = numbers and direct(d) + local axisDec = remainingBits and direct(d) + local half = axisDec and direct(d) + if not numbers or not remainingBits or not axisDec or not half then + return nil, d.bad or "kd-tree: bad bit decoders" + end + local selectAxis = level >= 6 + local zero = table.create(dim, 0) + local baseStack= { table.clone(zero) } + local levelStack= { table.clone(zero) } + local stack = { { numPoints, 0, 0 } } + local decoded = 0 + local p = table.create(dim, 0) + while #stack > 0 do +local __DARKLUA_CONTINUE_5=false repeat local st = stack[#stack] + stack[#stack] = nil + local n, lastAxis, sp = st[1], st[2], st[3] + local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1] + if n > numPoints then + return nil, "kd-tree: bad point count" + end + local axis + if not selectAxis then + axis = lastAxis == dim - 1 and 0 or lastAxis + 1 + elseif n < 64 then + axis = 0 + for a = 1, dim - 1 do + if levels[axis + 1] > levels[a + 1] then + axis = a + end + end + else + axis = (axisDec ).bits(4) or 0 + end + if axis >= dim then + return nil, "kd-tree: bad axis" + end + local lvl = levels[axis + 1] + if bitLength - lvl == 0 then + for _ = 1, n do + table.insert(out, table.clone(oldBase)) + decoded =decoded+ 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end +__DARKLUA_CONTINUE_5=true break + end + if n <= 2 then + for _ = 1, n do + local a = axis + for _ = 1, dim do + local rb = bitLength - levels[a + 1] + local v = 0 + if rb > 0 then + local got = remainingBits.bits(rb) + if got == nil then + return nil, "kd-tree: remaining bits run out" + end + v = got + end + p[a + 1] = bit32.bor(oldBase[a + 1], v) + a = a == dim - 1 and 0 or a + 1 + end + table.insert(out, table.clone(p)) + decoded =decoded+ 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end +__DARKLUA_CONTINUE_5=true break + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + local rbits = bitLength - lvl + local modifier = 2 ^ (rbits - 1) + local nb = table.clone(oldBase) + nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296 + baseStack[sp + 2] = nb + local number = numbers.bits(msb(n)) or 0 + local first = math.floor(n / 2 +) if first < number then + return nil, "kd-tree: bad split" + end + first =first- number + local second = n - first + if first ~= second and half.next() == 0 then + first, second = second, first + end +do local __DARKLUA_VAR=axis + 1 levels[__DARKLUA_VAR]=levels[__DARKLUA_VAR]+ 1 +end levelStack[sp + 2] = table.clone(levels) + if sp + 2 > 32 * dim + 1 then + return nil, "kd-tree: too deep" + end + if first > 0 then + table.insert(stack, { first, axis, sp }) + end + if second > 0 then + table.insert(stack, { second, axis, sp + 1 }) + end +__DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end + if decoded ~= expected then + return nil, "kd-tree: point count mismatch" + end + return out, nil +end + +local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } + +-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) +function KdTree.decode(d, attrs, numPoints) +if d.ver < 0x0203 then + return false, "unsupported: kd-tree point clouds before bitstream 2.3" + end + local level = Reader.u8(d) + if d.bad then + return false, d.bad + end + if level > 6 then + return false, "kd-tree: bad compression level" + end + local dim = 0 + for _, a in __iter(attrs) do + local dt = a.dataType + if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then + return false, "unsupported: kd-tree attribute of data type " .. dt + end + dim =dim+ a.comps + end + local points, err = decodePoints(d, level, dim, numPoints) + if not points then + return false, err + end + -- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types + local off = 0 + for _, a in __iter(attrs) do + local comps = a.comps + local vals = table.create(numPoints * comps, 0) + local mod = (a.dataType == 1 or a.dataType == 2 )and 256 or((a.dataType == 3 or a.dataType == 4 )and 65536 or 4294967296 +) local raw = a.dataType == 9 + for i, pt in __iter(points) do + for c = 1, comps do + local v = pt[off + c] + vals[(i - 1) * comps + c] = (raw and{v }or{(v % mod +)})[1] end + end + a.portable = vals + a.values = vals + a.numValues = numPoints + a.map = nil + off =off+ comps + end + -- the data needed by the transforms: f32 quantization, then the signed minima + for _, a in __iter(attrs) do + if a.dataType == 9 then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false, d.bad or "kd-tree: bad quantization" + end + a.quant = { min = mins, range = range, bits = bits } + end + end + for _, a in __iter(attrs) do + if SIGNED[a.dataType] then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + local v = Reader.varint(d) + mins[c] = (v % 2 == 1 and((-(math.floor(v / 2)) - 1 ))or((math.floor(v / 2 +)))) end + if d.bad then + return false, d.bad + end + a.signedMin = mins + end + end + -- back to the original values + local fround = Predict.fround + for _, a in __iter(attrs) do + local vals = a.portable +local comps = a.comps + if a.dataType == 9 then + local q = a.quant + local delta = fround(q.range / fround(2 ^ q.bits - 1)) + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local v = vals[i] + if v >= 2147483648 then + v =v- 4294967296 + end + out[i] = fround(fround(fround(v) * delta) + q.min[c]) + end + a.values = out + elseif SIGNED[a.dataType] then + -- the C++ reads the stored (already narrowed) unsigned values back + local bits = SIGNED[a.dataType] + local mins = a.signedMin + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local u = vals[i] + if u > 2147483647 then + return false, "kd-tree: signed value out of range" + end + local s = Predict.i32(u + mins[c]) + local m = 2 ^ bits + out[i] = (s + m / 2) % m - m / 2 + end + a.values = out + end + end + return true, nil +end + +return KdTree +end +__FILES["codecs/model/Draco/Predict"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference +-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and +-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. +-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; +-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 +-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, +-- licenses/draco-LICENSE.txt). +local Reader = __include("codecs/model/Draco/Reader") +local Connectivity = __include("codecs/model/Draco/Connectivity") +local Int64 = __include("codecs/model/Draco/Int64") + +local Predict = {} + + + + +local nextC, prevC = Connectivity.next, Connectivity.prev + +local F32 = buffer.create(4) +local function fround(x) +buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +Predict.fround = fround + +local function i32(x) +return (x + 2147483648) % 4294967296 - 2147483648 +end +Predict.i32 = i32 + +local function tdiv(a, b) +local q = a / b + return (q < 0 and{(math.ceil(q) )}or{(math.floor(q) +)})[1]end + +-- static_cast<int> of a float with the decoder's NaN / range guard (INT_MIN) +local function truncInt(x) +if x ~= x or x > 2147483647 or x < -2147483648 then + return -2147483648 + end + return tdiv(x, 1) +end + +-- exact a * b = p + e (Dekker), for integers below 2^53 +local SPLIT = 134217729 +local function twoProd(a, b) +local p = a * b + local t = SPLIT * a + local ah = t - (t - a) + local al = a - ah + t = SPLIT * b + local bh = t - (t - b) + local bl = b - bh + return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl +end + +-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0) +local function mulDiv(a, b, c) +local neg = (a < 0) ~= (b < 0) + a, b = math.abs(a), math.abs(b) + local p = a * b + local q + if p < 9007199254740992 then + q = math.floor(p / c +) else + q = math.floor(p / c) + local ph, pl = twoProd(a, b) + local qh, ql = twoProd(q, c) + local r = (ph - qh) + (pl - ql) + while r < 0 do + q =q- 1 + r =r+ c + end + while r >= c do + q =q+ 1 + r =r- c + end + end + return (neg and{(-q )}or{q +})[1]end + +-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 +local function isqrtProd(a, b) +if a == 0 or b == 0 then + return 0 + end + local s = math.floor(math.sqrt(a) * math.sqrt(b)) + local ph, pl = twoProd(a, b) + local function le(x) +local xh, xl = twoProd(x, x) + if xh ~= ph then + return xh < ph + end + return xl <= pl + end + while s > 0 and not le(s) do + s =s- 1 + end + while le(s + 1) do + s =s+ 1 + end + return s +end +-- ------------------------------------------------------------------------------------------------ octahedron toolbox + + + +function Predict.octahedron(bits) +if bits < 2 or bits > 30 then + return nil + end + local maxQ = 2 ^ bits - 1 + local maxV = maxQ - 1 + return { bits = bits, maxQ = maxQ, maxV = maxV, center = math.floor(maxV / 2), scale = fround(2 / fround(maxV)) } +end + +local function canonicalizeCoords(o, s, t) +local maxV, center = o.maxV, o.center + if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then + return maxV, maxV + elseif s == 0 and t > center then + t = center - (t - center) + elseif s == maxV and t < center then + t = center + (center - t) + elseif t == maxV and s < center then + s = center + (center - s) + elseif t == 0 and s > center then + s = center - (s - center) + end + return s, t +end + +local function intVectorToOct(o, x, y, z) +local s, t + local center, maxV = o.center, o.maxV + if x >= 0 then + s, t = y + center, z + center + else + s = (y < 0 and{(math.abs(z) )}or{(maxV - math.abs(z) +)})[1] t = (z < 0 and{(math.abs(y) )}or{(maxV - math.abs(y) +)})[1] end + return canonicalizeCoords(o, s, t) +end + +local function canonicalizeVector(o, x, y, z) +local sum = math.abs(x) + math.abs(y) + math.abs(z) + local center = o.center + if sum == 0 then + return center, y, z + end + x = mulDiv(x, center, sum) + y = mulDiv(y, center, sum) + if z >= 0 then + z = center - math.abs(x) - math.abs(y) + else + z = -(center - math.abs(x) - math.abs(y)) + end + return x, y, z +end + +local function invertDiamond(o, s, t) +local signS, signT + if s >= 0 and t >= 0 then + signS, signT = 1, 1 + elseif s <= 0 and t <= 0 then + signS, signT = -1, -1 + else + signS = s > 0 and 1 or-1 + signT = t > 0 and 1 or-1 + end + local cs, ctv = signS * o.center, signT * o.center + local us, ut = s + s - cs, t + t - ctv + if signS * signT >= 0 then + us, ut = -ut, -us + else + us, ut = ut, us + end + return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2) +end + +local function modMax(o, x) +if x > o.center then + return x - o.maxQ + elseif x < -o.center then + return x + o.maxQ + end + return x +end + +-- quantized octahedral (s, t) -> unit vector, in f32 like the C++ +function Predict.octToVector(o, s, t) +local y = fround(fround(fround(s) * o.scale) - 1) + local z = fround(fround(fround(t) * o.scale) - 1) + local x = fround(fround(1 - math.abs(y)) - math.abs(z)) + local xo = -x + if xo < 0 then + xo = 0 + end + y = fround((y < 0 and((y + xo ))or((y - xo)))) + z = fround((z < 0 and((z + xo ))or((z - xo)))) + local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z)) + if n2 < 1e-6 then + return 0, 0, 0 + end + local dd = fround(1 / fround(math.sqrt(n2))) + return fround(x * dd), fround(y * dd), fround(z * dd) +end +-- ------------------------------------------------------------------------------------------------ transforms +-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values + + + + + + + + + + +function Predict.transform(kind) +return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } +end + +function Predict.decodeTransform(tr, d) +if tr.kind == 1 then + local mn, mx = Reader.i32(d), Reader.i32(d) + if d.bad or mn > mx then + return false + end + local dif = mx - mn + if dif >= 2147483647 then + return false + end + tr.min, tr.max, tr.maxDif = mn, mx, dif + 1 + return true + end + local maxQ = Reader.i32(d) + if tr.kind == 3 or d.ver < 0x0202 then + Reader.i32(d) -- center value (unused) + end + if d.bad or maxQ <= 0 or maxQ % 2 == 0 then + return false + end + local bits = 0 + while 2 ^ bits <= maxQ do + bits =bits+ 1 + end + local o = Predict.octahedron(bits) + if not o then + return false + end + tr.oct = o + return true +end + +-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] +local function apply(tr, pred, data, off, comps) + if tr.kind == 1 then + local mn, mx, dif = tr.min, tr.max, tr.maxDif + for c = 1, comps do + local p = pred[c] + if p > mx then + p = mx + elseif p < mn then + p = mn + end + local v = i32(p + data[off + c]) + if v > mx then + v =v- dif + elseif v < mn then + v =v+ dif + end + data[off + c] = v + end + return + end + local o = tr.oct +local center = o.center + local ps, pt = pred[1] - center, pred[2] - center + local cs, ct = data[off + 1], data[off + 2] + local inDiamond = math.abs(ps) + math.abs(pt) <= center + if not inDiamond then + ps, pt = invertDiamond(o, ps, pt) + end + local os_, ot= 0, 0 + if tr.kind == 2 then + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + else + local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0) + local rot = 0 + if ps == 0 then + rot = pt == 0 and 0 or(pt > 0 and 3 or 1 +) elseif ps > 0 then + rot = pt >= 0 and 2 or 1 + else + rot = pt <= 0 and 0 or 3 + end + local function rotate(x, y, r) +if r == 1 then + return y, -x + elseif r == 2 then + return -x, -y + elseif r == 3 then + return -y, x + end + return x, y + end + if not bottomLeft then + ps, pt = rotate(ps, pt, rot) + end + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + if not bottomLeft then + os_, ot = rotate(os_, ot, (4 - rot) % 4) + end + end + if not inDiamond then + os_, ot = invertDiamond(o, os_, ot) + end + data[off + 1] = os_ + center + data[off + 2] = ot + center +end +Predict.apply = apply +-- ------------------------------------------------------------------------------------------------ schemes +-- the mesh data of a scheme: corner table, value -> corner, vertex -> value + + +-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) + + + + + + + + + + + + + + + +local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 +Predict.GEOMETRIC_NORMAL = GEONORMAL + +-- whether the scheme needs the position attribute +function Predict.needsParent(s) +return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) +end + +-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta +function Predict.new(method, tr, md) +local m = method + if not md then + m = DELTA + elseif tr.kind ~= 1 then + if m ~= GEONORMAL then + m = DELTA + md = nil + end + elseif m < PARALLELOGRAM or m > GEONORMAL then + m = DELTA + md = nil + end + return { method = m, tr = tr, md = (m == DELTA and{nil }or{md})[1], parent = nil, areaMode = true, ver = 0x0202 } +end + +-- DecodePredictionData +function Predict.decodeData(s, d) +local m = s.method + s.ver = d.ver + if m == CONSTRAINED then + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode ~= 0 then + return false + end + end + local md = s.md +local crease = {} + for i = 1, 4 do + local n = Reader.varint(d) + if d.bad or n > md.ct.nf * 3 then + return false + end + local flags = table.create(n, false) + if n > 0 then + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + for j = 1, n do + flags[j] = Reader.bit(bd) + end + end + crease[i] = flags + end + s.crease = crease + elseif m == TEXPORT then + local n = Reader.i32(d) + if d.bad or n < 0 or n > (s.md ).ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == TEXDEP then + local n = Reader.count(d, 0x0202) + local md = s.md +if d.bad or n == 0 or n > md.ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == GEONORMAL then + if not Predict.decodeTransform(s.tr, d) then + return false + end + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode > 1 then + return false + end + s.areaMode = mode == 1 + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + s.flips = bd + return true + end + return Predict.decodeTransform(s.tr, d) +end + +local function parallelogram(md, p, ci, data, comps, out) +local ct = md.ct + local oci = ci < 0 and-1 or(ct.opp[ci + 1] or -1) + if oci == -1 then + return false + end + local c2v, v2e = ct.c2v, md.v2e + local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1 + if vo < 0 or vn < 0 or vp < 0 then + return false + end + local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0 + if eo < p and en < p and ep < p then + for c = 1, comps do + out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c]) + end + return true + end + return false +end + +local function swingRight(ct, c) +local p = prevC(c) + local o = p < 0 and-1 or(ct.opp[p + 1] or -1) + return prevC(o) +end +local function swingLeft(ct, c) +local n = nextC(c) + local o = n < 0 and-1 or(ct.opp[n + 1] or -1) + return nextC(o) +end + +-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor +-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate +-- edge: predict from a neighbour); or "fail", message. +local function texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, pop) +local pnx, pny, pnz = qx - nx, qy - ny, qz - nz + local cnx, cny, cnz = tx - nx, ty - ny, tz - nz + local pnu, pnv = pu - nu, pv - nv + local B = 67108864 -- 2^26: below it every product and sum stays exact in a double + local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B + if small then + local pn2 = pnx * pnx + pny * pny + pnz * pnz + local dot = pnx * cnx + pny * cny + pnz * cnz + if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then + if pn2 == 0 then + return "fallback" + end + local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv + local dx = tx - (nx + tdiv(dot * pnx, pn2)) + local dy = ty - (ny + tdiv(dot * pny, pn2)) + local dz = tz - (nz + tdiv(dot * pnz, pn2)) + local cx2 = dx * dx + dy * dy + dz * dz + if cx2 < B then + local norm = isqrtProd(cx2, pn2) + local cxu, cxv = pnv * norm, -pnu * norm + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + if o then + return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2)) + end + return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2)) + end + end + end + -- the general case: int64 + local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div + local function dot3(ax, ay, az, bx, by, bz) +local xh, xl = from(ax) + local yh, yl = from(ay) + local zh, zl = from(az) + local uh, ul = from(bx) + local vh, vl = from(by) + local wh, wl = from(bz) + local h1, l1 = mul(xh, xl, uh, ul) + local h2, l2 = mul(yh, yl, vh, vl) + local h3, l3 = mul(zh, zl, wh, wl) + h1, l1 = add(h1, l1, h2, l2) + return add(h1, l1, h3, l3) + end + local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz) + if p2h == 0 and p2l == 0 then + return "fallback" + end + local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz) + local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX + local function absmax(...) +local m = 0 + for _, x in __iter({ ... }) do + m = math.max(m, math.abs(x)) + end + return from(m) + end + local function absI(h, l) +if Int64.isNeg(h) then + return Int64.neg(h, l) + end + return h, l + end + -- the overflow guards (unsigned divisions as in the C++) + local nmh, nml = absmax(nu, nv) + local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l) + if Int64.ucmp(nmh, nml, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local adh, adl = absI(dh, dl) + local pmh, pml = absmax(pnu, pnv) + lh, ll = Int64.div(MAXH, MAXL, pmh, pml) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local nuh, nul = from(nu) + local nvh, nvl = from(nv) + local puh, pul = from(pnu) + local pvh, pvl = from(pnv) + local xuh, xul + do + local ah, al = mul(nuh, nul, p2h, p2l) + local bh, bl = mul(dh, dl, puh, pul) + xuh, xul = add(ah, al, bh, bl) + end + local xvh, xvl + do + local ah, al = mul(nvh, nvl, p2h, p2l) + local bh, bl = mul(dh, dl, pvh, pvl) + xvh, xvl = add(ah, al, bh, bl) + end + local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz)) + local pah, pal = from(pam) + lh, ll = Int64.div(MAXH, MAXL, pah, pal) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + -- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos + local function proj(n, pc, t) +local ph, pl = from(pc) + local mh, ml = mul(dh, dl, ph, pl) + local qh, ql = div(mh, ml, p2h, p2l) + local nh, nl = from(n) + local xh, xl = add(nh, nl, qh, ql) + local th, tl = from(t) + return sub(th, tl, xh, xl) + end + local ax, axl = proj(nx, pnx, tx) + local ay, ayl = proj(ny, pny, ty) + local az, azl = proj(nz, pnz, tz) + local c2h, c2l = mul(ax, axl, ax, axl) + do + local h, l = mul(ay, ayl, ay, ayl) + c2h, c2l = add(c2h, c2l, h, l) + h, l = mul(az, azl, az, azl) + c2h, c2l = add(c2h, c2l, h, l) + end + local prh, prl = mul(c2h, c2l, p2h, p2l) + local sh, sl = Int64.isqrt(prh, prl) + -- cx_uv = (pn_uv.v, -pn_uv.u) * norm + local cuh, cul = mul(pvh, pvl, sh, sl) + local nh, nl = Int64.neg(puh, pul) + local cvh, cvl = mul(nh, nl, sh, sl) + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + local uh, ul, vh, vl + if o then + uh, ul = add(xuh, xul, cuh, cul) + vh, vl = add(xvh, xvl, cvh, cvl) + else + uh, ul = sub(xuh, xul, cuh, cul) + vh, vl = sub(xvh, xvl, cvh, cvl) + end + uh, ul = div(uh, ul, p2h, p2l) + vh, vl = div(vh, vl, p2h, p2l) + -- static_cast<int>: the low 32 bits + return "ok", i32(ul), i32(vl) +end + +-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +function Predict.compute(s, data, numEntries, comps, points) +local tr = s.tr + local m = s.method + local pred = table.create(math.max(comps, 3), 0) + if m == DELTA then + if numEntries == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + for e = 1, numEntries - 1 do + local off = e * comps + for c = 1, comps do + pred[c] = data[off - comps + c] + end + apply(tr, pred, data, off, comps) + end + return true, nil + end + local md = s.md +local e2c = md.e2c + local n = #e2c + if n ~= numEntries then + return false, "prediction: value count mismatch" + end + local ct = md.ct + local function previous(p) + local off = (p - 1) * comps + for c = 1, comps do + pred[c] = data[off + c] + end + end + if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then + if n == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + local para = table.create(comps, 0) + local preds= { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) } + local creasePos = { 0, 0, 0, 0 } + local nc = ct.nf * 3 + for p = 1, n - 1 do + local start = e2c[p + 1] + local off = p * comps + if m == PARALLELOGRAM then + if parallelogram(md, p, start, data, comps, pred) then + apply(tr, pred, data, off, comps) + else + previous(p) + apply(tr, pred, data, off, comps) + end + elseif m == MULTI then + for c = 1, comps do + pred[c] = 0 + end + local count = 0 + local ci = start + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, para) then + for c = 1, comps do + pred[c] = i32(pred[c] + para[c]) + end + count =count+ 1 + end + ci = swingRight(ct, ci) + if ci == start then + ci = -1 + end + guard =guard+ 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + if count == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], count) + end + end + apply(tr, pred, data, off, comps) + else + local count = 0 + local ci = start + local first = true + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, preds[count + 1]) then + count =count+ 1 + if count == 4 then + break + end + end + if first then + ci = swingLeft(ct, ci) + else + ci = swingRight(ct, ci) + end + if ci == start then + break + end + if ci == -1 and first then + first = false + ci = swingRight(ct, start) + end + guard =guard+ 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local used = 0 + if count > 0 then + for c = 1, comps do + pred[c] = 0 + end + local crease = s.crease +for i = 1, count do + local pos = creasePos[count] + 1 + creasePos[count] = pos + local flag = crease[count][pos] + if flag == nil then + return false, "prediction: crease flags run out" + end + if not flag then + used =used+ 1 + for c = 1, comps do + pred[c] = i32(pred[c] + preds[i][c]) + end + end + end + end + if used == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], used) + end + end + apply(tr, pred, data, off, comps) + end + end + return true, nil + end + local parent = s.parent + if not parent then + return false, "prediction: no position attribute" + end + local c2v, v2e = ct.c2v, md.v2e + local function entryOf(c) +local v = c < 0 and-1 or(c2v[c + 1] or -1) + if v < 0 then + return math.huge + end + return v2e[v + 1] or 0 + end + local function posOf(e) +local pt = points[e + 1] + if pt == nil then + return 0, 0, 0 + end + return parent(pt) + end + if m == TEXPORT or m == TEXDEP then + if comps ~= 2 then + return false, "prediction: tex coords need 2 components" + end + local orient = s.orient +local no = #orient + for p = 0, n - 1 do + local ci = e2c[p + 1] + local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci)) + local done = false + if pe < p and ne < p then + local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2] + local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2] + if m == TEXPORT then + if pu == nu and pv == nv then + pred[1], pred[2] = pu, pv + done = true + else + local tx, ty, tz = posOf(p) + local nx, ny, nz = posOf(ne) + local qx, qy, qz = posOf(pe) + local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function() +if no == 0 then + return nil + end + local o = orient[no] + orient[no] = nil + no =no- 1 + return o + end) + if status == "fail" then + return false, u +elseif status == "ok" then + pred[1], pred[2] = u, v + done = true + end + end + else + local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv) + if fpu == fnu and fpv == fnv then + pred[1], pred[2] = truncInt(fpu), truncInt(fpv) + done = true + else + local tx, ty, tz= posOf(p) + local nx, ny, nz= posOf(ne) + local qx, qy, qz= posOf(pe) + tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz) + qx, qy, qz = fround(qx), fround(qy), fround(qz) + local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz) + local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz) + local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz)) + local sv, tv = 0, 0 + if s.ver < 0x0102 or pn2 > 0 then + local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz)) + sv = fround(dot / pn2) + local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv)) + local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez)) + tv = fround(math.sqrt(fround(e2 / pn2))) + end + local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv) + local pnus = fround(fround(pnu * sv) + fnu) + local pnut = fround(pnu * tv) + local pnvs = fround(fround(pnv * sv) + fnv) + local pnvt = fround(pnv * tv) + if no == 0 then + return false, "prediction: orientations run out" + end + local o = orient[no] + orient[no] = nil + no =no- 1 + local u, v= 0, 0 + if o then + u = fround(pnus - pnvt) + v = fround(pnvs + pnut) + else + u = fround(pnus + pnvt) + v = fround(pnvs - pnut) + end + local function toInt(x) +local r = math.floor(x + 0.5) + if r ~= r or r > 2147483647 or r < -2147483648 then + return -2147483648 + end + return r + end + pred[1] = toInt(u) + pred[2] = toInt(v) + done = true + end + end + end + if not done then + local off = -1 + if pe < p then + off = pe * 2 + end + if ne < p then + off = ne * 2 + elseif p > 0 then + off = (p - 1) * 2 + else + off = -1 + end + if off < 0 then + pred[1], pred[2] = 0, 0 + else + pred[1], pred[2] = data[off + 1], data[off + 2] + end + end + apply(tr, pred, data, p * 2, 2) + end + return true, nil + end + -- geometric normal + local o = tr.oct + local flips = s.flips + if not o or not flips or comps ~= 2 then + return false, "prediction: bad geometric normal setup" + end + local nc = ct.nf * 3 + for p = 0, n - 1 do + local ci = e2c[p + 1] + local cx, cy, cz = posOf(entryOf(ci)) + local sx, sy, sz = 0, 0, 0 + -- VertexCornersIterator from ci: swing left, then right from the start + local c = ci + local left = true + local guard = 0 + while c ~= -1 do + local cn, cp + if s.areaMode then + cn, cp = nextC(c), prevC(c) + else + cn, cp = nextC(ci), prevC(ci) + end + local ax, ay, az = posOf(entryOf(cn)) + local bx, by, bz = posOf(entryOf(cp)) + ax, ay, az = ax - cx, ay - cy, az - cz + bx, by, bz = bx - cx, by - cy, bz - cz + sx =sx+ (ay * bz - az * by +) sy =sy+ (az * bx - ax * bz +) sz =sz+ (ax * by - ay * bx +) if left then + c = swingLeft(ct, c) + if c == -1 then + c = swingRight(ct, ci) + left = false + elseif c == ci then + c = -1 + end + else + c = swingRight(ct, c) + end + guard =guard+ 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local upper = 2 ^ 29 + local sum = math.abs(sx) + math.abs(sy) + math.abs(sz) + if sum > upper then + local q = math.floor(sum / upper +) sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q) + end + sx, sy, sz = i32(sx), i32(sy), i32(sz) + sx, sy, sz = canonicalizeVector(o, sx, sy, sz) + if Reader.bit(flips) then + sx, sy, sz = -sx, -sy, -sz + end + pred[1], pred[2] = intVectorToOct(o, sx, sy, sz) + apply(tr, pred, data, p * 2, 2) + end + return true, nil +end + +return Predict +end +__FILES["codecs/model/Draco/Reader"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and +-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit +-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, +-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, +-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). +-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +local Reader = {} + +local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 +local band, rshift = bit32.band, bit32.rshift + + + + + + + + + + + + +function Reader.new(b, pos, limit, ver) +return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 } +end + +-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards) +function Reader.copy(d) +return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff } +end + +function Reader.fail(d, msg) +if not d.bad then + d.bad = msg + end + return 0 +end + +function Reader.remaining(d) +return d.limit - d.pos +end + +function Reader.u8(d) +local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 1 + return readu8(d.b, p) +end + +function Reader.i8(d) +local v = Reader.u8(d) + return (v >= 128 and((v - 256 ))or(v +))end + +function Reader.u16(d) +local p = d.pos + if p + 2 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 2 + return readu16(d.b, p) +end + +function Reader.u32(d) +local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readu32(d.b, p) +end + +function Reader.i32(d) +local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readi32(d.b, p) +end + +-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) +function Reader.u64(d) +local p = d.pos + if p + 8 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 8 + return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296 +end + +function Reader.f32(d) +local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readf32(d.b, p) +end + +-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts +function Reader.varint(d, wide) +local maxBytes = wide and 10 or 5 + local v, mul = 0, 1 + for _ = 1, maxBytes do + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated varint") + end + local c = readu8(d.b, p) + d.pos = p + 1 + v =v+ band(c, 127) * mul + if c < 128 then + if not wide then + v =v% 4294967296 + end + return v + end + mul =mul* 128 + end + return Reader.fail(d, "varint too long") +end + +-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on +function Reader.count(d, fixedBefore) +if d.ver < fixedBefore then + return Reader.u32(d) + end + return Reader.varint(d) +end + +-- ------------------------------------------------------------------------------------------------ bit runs +-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end +-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. +function Reader.startBits(d, decodeSize) +local size = 0 + if decodeSize then + if d.ver < 0x0202 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + end + d.bitMode = true + d.bitStart = d.pos + d.bitOff = 0 + return size +end + +function Reader.bits(d, n) +if not d.bitMode then + return Reader.fail(d, "bit decoder not active") + end + if n > 32 then + return Reader.fail(d, "bit run over 32 bits") + end + local b, start, limit = d.b, d.bitStart, d.limit + local off = d.bitOff + local v, mul = 0, 1 + for _ = 1, n do + local byte = start + rshift(off, 3) + if byte < limit then + if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then + v =v+ mul + end + off =off+ 1 + end + mul =mul* 2 + end + d.bitOff = off + return v +end + +function Reader.endBits(d) + d.bitMode = false + d.pos = d.bitStart + math.floor((d.bitOff + 7) / 8 +)end + +-- ------------------------------------------------------------------------------------------------ rANS symbols +-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 +local function precisionBits(bitLength) +local p = math.floor((3 * bitLength) / 2 +) return p < 12 and 12 or(p > 20 and 20 or p +)end + +-- RAnsSymbolDecoder::Create: the probability table + + + + + + + + + + + + + +local function ransCreate(d, precBits) +local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil + end + if math.floor(numSymbols / 64 )> Reader.remaining(d) then + Reader.fail(d, "rans: too many symbols") + return nil + end + local prec = 2 ^ precBits + local prob = table.create(numSymbols, 0) + local i = 0 + while i < numSymbols do + local data = Reader.u8(d) + if d.bad then + return nil + end + local token = band(data, 3) + if token == 3 then + local offset = rshift(data, 2) + if i + offset >= numSymbols then + Reader.fail(d, "rans: bad zero run") + return nil + end + for j = 0, offset do + prob[i + j + 1] = 0 + end + i =i+ (offset + 1 +) else + local p = rshift(data, 2) + for k = 1, token do + p =p+ Reader.u8(d) * 2 ^ (8 * k - 2) + end + if d.bad then + return nil + end + prob[i + 1] = p + i =i+ 1 + end + end + local lut= {} + local cum = table.create(numSymbols, 0) + if numSymbols > 0 then + lut = table.create(prec, 0) + local c, act = 0, 0 + for s = 1, numSymbols do + cum[s] = c + c =c+ prob[s] + if c > prec then + Reader.fail(d, "rans: probabilities over the precision") + return nil + end + for j = act + 1, c do + lut[j] = s + end + act = c + end + if c ~= prec then + Reader.fail(d, "rans: probabilities do not sum to the precision") + return nil + end + end + return { + b = d.b, + base = 0, + off = 0, + state = 0, + lBase = prec * 4, + precBits = precBits, + lut = lut, + prob = prob, + cum = cum, + numSymbols = numSymbols, + } +end + +-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes +local function ansInit(b, base, size, lBase, allow4) +if size < 1 then + return nil, nil + end + local x = rshift(readu8(b, base + size - 1), 6) + local off, state= 0, 0 + if x == 0 then + off = size - 1 + state = band(readu8(b, base + size - 1), 0x3F) + elseif x == 1 then + if size < 2 then + return nil, nil + end + off = size - 2 + state = band(readu16(b, base + size - 2), 0x3FFF) + elseif x == 2 then + if size < 3 then + return nil, nil + end + off = size - 3 + state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536 + else + if not allow4 or size < 4 then + return nil, nil + end + off = size - 4 + state = band(readu32(b, base + size - 4), 0x3FFFFFFF) + end + state =state+ lBase + if state >= lBase * 256 then + return nil, nil + end + return off, state +end + +-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes +local function ransStart(d, r) +local size + if d.ver < 0x0200 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + if d.bad then + return false + end + if size > Reader.remaining(d) then + Reader.fail(d, "rans: data past the end") + return false + end + local off, state = ansInit(d.b, d.pos, size, r.lBase, true) + if not off then + Reader.fail(d, "rans: bad initial state") + return false + end + r.base, r.off, r.state = d.pos, off, state +d.pos =d.pos+ size + return true +end + +-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) +local function ransRead(r, n, out, first) + local b, base, off, state = r.b, r.base, r.off, r.state + local lBase, bits = r.lBase, r.precBits + local mask = 2 ^ bits - 1 + local lut, prob, cum = r.lut, r.prob, r.cum + for i = first, first + n - 1 do + while state < lBase and off > 0 do + off =off- 1 + state = state * 256 + readu8(b, base + off) + end + local quo, rem = rshift(state, bits), band(state, mask) + local s = lut[rem + 1] + state = quo * prob[s] + rem - cum[s] + out[i] = s - 1 + end + r.off, r.state = off, state +end + +local function decodeTagged(d, n, comps, out) +local tag = ransCreate(d, precisionBits(5)) + if not tag or not ransStart(d, tag) then + return false + end + if n > 0 and tag.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + Reader.startBits(d, false) + local len = { 0 } + local k = 1 + local i = 0 + while i < n do + ransRead(tag, 1, len, 1) + local bitLength = len[1] + for _ = 1, comps do + if k > n then + break + end + out[k] = Reader.bits(d, bitLength) + k =k+ 1 + end + if d.bad then + return false + end + i =i+ comps + end + Reader.endBits(d) + return true +end + +local function decodeRaw(d, n, out) +local maxBitLength = Reader.u8(d) + if d.bad then + return false + end + if maxBitLength < 1 or maxBitLength > 18 then + Reader.fail(d, "rans: bad symbol bit length") + return false + end + local r = ransCreate(d, precisionBits(maxBitLength)) + if not r then + return false + end + if n > 0 and r.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + if not ransStart(d, r) then + return false + end + ransRead(r, n, out, 1) + return true +end + +-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +function Reader.symbols(d, n, comps) +local out = table.create(n, 0) + if n == 0 then + return out + end + local scheme = Reader.u8(d) + if d.bad then + return nil + end + local ok + if scheme == 0 then + ok = decodeTagged(d, n, math.max(comps, 1), out) + elseif scheme == 1 then + ok = decodeRaw(d, n, out) + else + Reader.fail(d, "rans: unknown symbol coding scheme") + ok = false + end + return (ok and{out }or{nil +})[1]end +-- ------------------------------------------------------------------------------------------------ binary rANS +-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes + + + +function Reader.bitDecoder(d) +local p0 = Reader.u8(d) + local size = Reader.count(d, 0x0202) + if d.bad then + return nil + end + if size > Reader.remaining(d) then + Reader.fail(d, "rabs: data past the end") + return nil + end + local off, state = ansInit(d.b, d.pos, size, 4096, false) + if not off then + Reader.fail(d, "rabs: bad initial state") + return nil + end + local bd = { b = d.b, base = d.pos, off = off, state = state , p0 = p0, p = 256 - p0 } + d.pos =d.pos+ size + return bd +end + +-- rabs_desc_read: one bit (true / false) +function Reader.bit(bd) +local state, off = bd.state, bd.off + if state < 4096 and off > 0 then + off =off- 1 + state = state * 256 + readu8(bd.b, bd.base + off) + bd.off = off + end + local quot, rem = rshift(state, 8), band(state, 255) + local p = bd.p + local xn = quot * p + if rem < p then + bd.state = xn + rem + return true + end + bd.state = state - xn - p + return false +end + +return Reader +end +__FILES["codecs/model/Mat4"] = function() +--!strict +-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 +-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a +-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the +-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). +-- +-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S +-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) +-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul +-- local inv = Mat4.inverse(m) -- affine inverse | nil +-- local x, y, z = Mat4.point(m, px, py, pz) +local Types = __include("Types") + +local Mat4 = {} + + + +local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad + +function Mat4.identity() +return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- mul(a, b) -> a * b +Mat4.mul = Types.Scene.mul + +function Mat4.translation(x, y, z) +return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function Mat4.scaling(x, y, z) +return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) +function Mat4.rotation(axis, degrees) +local a = rad(degrees) + local c, s = cos(a), sin(a) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +local AXIS = { x = 1, y = 2, z = 3 } +-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees +function Mat4.euler(x, y, z, order) +local o = order or "xyz" + local deg = { x = x, y = y, z = z } + local m = Mat4.identity() + for i = 1, 3 do + local a = string.sub(o, i, i) + m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m) + end + return m +end + +-- axisAngle(x, y, z, degrees) -> quaternion +function Mat4.axisAngle(x, y, z, degrees) +local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local h = rad(degrees) / 2 + local s = sin(h) / l + return { x * s, y * s, z * s, cos(h) } +end + +-- fromQuat(q) -> the rotation matrix of a quaternion +function Mat4.fromQuat(q) +local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) +function Mat4.quat(m) +local m00, m01, m02 = m[1], m[5], m[9] + local m10, m11, m12 = m[2], m[6], m[10] + local m20, m21, m22 = m[3], m[7], m[11] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = sqrt(tr + 1) * 2 + w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 + w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 + w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 + w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local n = sqrt(x * x + y * y + z * z + w * w) + if n == 0 or n ~= n then + return { 0, 0, 0, 1 } + end + return { x / n, y / n, z / n, w / n } +end + +-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion +function Mat4.eulerXYZ(q) +local m = Mat4.fromQuat(q) + local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) + local y = math.asin(sy) + local x, z + if abs(sy) < 0.9999999 then + x = math.atan2(m[7], m[11]) + z = math.atan2(m[2], m[1]) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return { math.deg(x), math.deg(y), math.deg(z) } +end + +-- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +function Mat4.compose(t, r, s) +local m = (r and{(Mat4.fromQuat(r) )}or{(Mat4.identity() +)})[1] if s then + for k = 0, 2 do +do local __DARKLUA_VAR=k * 4 + 1 m[__DARKLUA_VAR]=m[__DARKLUA_VAR]* s[k + 1] +end do local __DARKLUA_VAR0=k * 4 + 2 m[__DARKLUA_VAR0]=m[__DARKLUA_VAR0]* s[k + 1] +end do local __DARKLUA_VAR1=k * 4 + 3 m[__DARKLUA_VAR1]=m[__DARKLUA_VAR1]* s[k + 1] +end end + end + if t then + m[13], m[14], m[15] = t[1], t[2], t[3] + end + return m +end + +local function det3(m) +return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +local function split(m, strict) +if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then + return nil, nil, nil + end + local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then + return nil, nil, nil + end + if det3(m) < 0 then + sx = -sx + end + local ix = (sx ~= 0 and((1 / sx ))or(0 +)) local iy = (sy ~= 0 and((1 / sy ))or(0 +)) local iz = (sz ~= 0 and((1 / sz ))or(0 +)) local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } + if strict then + local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7] + local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11] + local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11] + if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then + return nil, nil, nil + end + end + return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } +end + +-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +function Mat4.decompose(m) +local t, r, s = split(m, false) + return t , r , s +end + +-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, +-- a zero scale) +function Mat4.decomposeStrict(m) +return split(m, true) +end + +-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular +function Mat4.inverse(m) +local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if det == 0 or det ~= det then + return nil + end + local k = 1 / det + local r = { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } + local tx, ty, tz = m[13], m[14], m[15] + r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) + r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) + r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) + return r +end + +-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular +function Mat4.inverseFull(m) +local a = m + local inv = table.create(16, 0) + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k]=inv[k]/ det + end + return inv +end + +-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) +function Mat4.transpose3(m) +return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } +end + +-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) +function Mat4.fromRows(v, at) +local o = (at or 1) - 1 + local m = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (r == c and 1 or 0) + end + end + return m +end + +-- toRows(m) -> the 16 values row-major +function Mat4.toRows(m) +local v = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + v[r * 4 + c + 1] = m[c * 4 + r + 1] + end + end + return v +end + +-- point(m, x, y, z) -> m * (x, y, z, 1) +function Mat4.point(m, x, y, z) +return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) +function Mat4.normalMatrix(m) +local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) + if not inv then + return Mat4.identity() + end + return Mat4.transpose3(inv) +end + +return Mat4 +end +__FILES["codecs/model/MeshFlatten"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), +-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring +-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, +-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one +-- (ops/MeshOps.merge is the editing-side equivalent). +-- Never throws: bad input returns nil, message. +local Types = __include("Types") + +local Flatten = {} + +local readf32, readf64 = buffer.readf32, buffer.readf64 +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local readi8, readi16, readi32 = buffer.readi8, buffer.readi16, buffer.readi32 + +local SIZE = Types.COMPONENT_SIZE +-- normalized integer types: their scale (raw / scale = the normalized value) +local NORM= { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 } + +-- ------------------------------------------------------------------------------------------------ accessors +-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg + + + + + + + + + + + + + + + + + + + + + + + + +function Flatten.numbers(acc, raw) +if type(acc) ~= "table" or type(acc.data) ~= "buffer" then + return nil, "accessor without a data buffer" + end + local t, comps, count = acc.type, acc.components, acc.count + local size = SIZE[t] + if size == nil then + return nil, "unknown accessor type " .. tostring(t) + end + if type(comps) ~= "number" or type(count) ~= "number" or comps < 1 or comps > 16 or count < 0 or comps % 1 ~= 0 or count % 1 ~= 0 then + return nil, "bad accessor components / count" + end + local n = count * comps + local d= acc.data + if buffer.len(d) < n * size then + return nil, "accessor data shorter than count * components" + end + local out = (table.create(n) ) +if t == "f32" then + for i = 0, n - 1 do + out[i + 1] = readf32(d, i * 4) + end + elseif t == "f64" then + for i = 0, n - 1 do + out[i + 1] = readf64(d, i * 8) + end + elseif t == "u8" or t == "unorm8" then + for i = 0, n - 1 do + out[i + 1] = readu8(d, i) + end + elseif t == "u16" or t == "unorm16" then + for i = 0, n - 1 do + out[i + 1] = readu16(d, i * 2) + end + elseif t == "u32" then + for i = 0, n - 1 do + out[i + 1] = readu32(d, i * 4) + end + elseif t == "i8" or t == "snorm8" then + for i = 0, n - 1 do + out[i + 1] = readi8(d, i) + end + elseif t == "i16" or t == "snorm16" then + for i = 0, n - 1 do + out[i + 1] = readi16(d, i * 2) + end + else -- i32 + for i = 0, n - 1 do + out[i + 1] = readi32(d, i * 4) + end + end + local scale = NORM[t] + if scale and not raw then + local signed = t == "snorm8" or t == "snorm16" + for i = 1, n do + local v = out[i] / scale + out[i] = signed and v < -1 and-1 or v + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ transforms +local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + +local mul = Types.Scene.mul -- column-major 4x4 product a * b + +local function numList(v, n) +if type(v) ~= "table" then + return false + end + for i = 1, n do + if type(v[i]) ~= "number" then + return false + end + end + return true +end + +-- a node's local matrix (nil: none), or nil, message +local function localMatrix(node) +if node.matrix ~= nil then + if not numList(node.matrix, 16) then + return nil, "node matrix is not 16 numbers" + end + local m = (table.create(16) ) +for i = 1, 16 do + m[i] = node.matrix[i] + end + return m, nil + end + local t, q, s = node.translation, node.rotation, node.scale + if t == nil and q == nil and s == nil then + return nil, nil + end + if (t ~= nil and not numList(t, 3)) or (q ~= nil and not numList(q, 4)) or (s ~= nil and not numList(s, 3)) then + return nil, "bad node translation / rotation / scale" + end + local x, y, z, w = 0, 0, 0, 1 + if q then + x, y, z, w = q[1], q[2], q[3], q[4] + end + local sx, sy, sz = 1, 1, 1 + if s then + sx, sy, sz = s[1], s[2], s[3] + end + local tx, ty, tz = 0, 0, 0 + if t then + tx, ty, tz = t[1], t[2], t[3] + end + return { + (1 - 2 * (y * y + z * z)) * sx, + (2 * (x * y + z * w)) * sx, + (2 * (x * z - y * w)) * sx, + 0, + (2 * (x * y - z * w)) * sy, + (1 - 2 * (x * x + z * z)) * sy, + (2 * (y * z + x * w)) * sy, + 0, + (2 * (x * z + y * w)) * sz, + (2 * (y * z - x * w)) * sz, + (1 - 2 * (x * x + y * y)) * sz, + 0, + tx, + ty, + tz, + 1, + }, + nil +end + +local function isIdentity(m) +for i = 1, 16 do + if m[i] ~= IDENTITY[i] then + return false + end + end + return true +end + +-- the primitive instances of a scene in traversal order, or nil, message + + +local function instances(scene) +local out= {} + local nodes, meshes = scene.nodes, scene.meshes + if type(nodes) ~= "table" or type(meshes) ~= "table" then + return nil, "scene without nodes / meshes tables" + end + local function addMesh(mi, node, m) +local mesh = meshes[mi] + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return "node refers to a missing mesh " .. tostring(mi) + end + for _, prim in __iter(mesh.primitives) do + if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return "bad primitive" + end + table.insert(out, { prim = prim, mesh = mesh, node = node, matrix = m }) + end + return nil + end + local visiting= {} + local function visit(ni, parent, depth) +local node = nodes[ni] + if type(node) ~= "table" then + return "missing node " .. tostring(ni) + end + if depth > 256 or visiting[ni] then + return "node hierarchy is cyclic or too deep" + end + visiting[ni] = true + local m, merr = localMatrix(node) + if merr then + return merr + end + local world = (m and parent and{(mul(parent, m) )}or{(m and{m }or{parent +})[1]})[1] if node.mesh ~= nil then + local e = addMesh(node.mesh, node, world) + if e then + return e + end + end + if type(node.children) == "table" then + for _, c in __iter(node.children) do + local e = visit(c, world, depth + 1) + if e then + return e + end + end + end + visiting[ni] = nil + return nil + end + local roots = scene.roots + if type(roots) == "table" and #roots > 0 then + for _, ri in __iter(roots) do + local e = visit(ri, nil, 0) + if e then + return nil, e + end + end + elseif #nodes > 0 then + local isChild= {} + for _, n in __iter(nodes) do + if type(n) == "table" and type(n.children) == "table" then + for _, c in __iter(n.children) do + isChild[c] = true + end + end + end + for i = 1, #nodes do + if not isChild[i] then + local e = visit(i, nil, 0) + if e then + return nil, e + end + end + end + else + for i = 1, #meshes do + local e = addMesh(i, nil, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ faces +-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message +local function faces(prim, nv) +local mode = prim.mode or "triangles" + if mode == "points" then + return "points", nil, nil + elseif mode == "lines" or mode == "line_strip" or mode == "line_loop" then + return "skip", nil, nil + end + local idx +if prim.indices ~= nil then + local v, err = Flatten.numbers(prim.indices, true) + if not v then + return nil, nil, "indices: " .. tostring(err) + end + idx = v + else + idx = (table.create(nv) ) +for i = 1, nv do + idx[i] = i - 1 + end + end + for i = 1, #idx do + local v = idx[i] + if v < 0 or v >= nv or v % 1 ~= 0 then + return nil, nil, string.format("index %s out of range (%d vertices)", tostring(v), nv) + end + end + if mode == "triangles" then + local n = #idx - #idx % 3 + if n ~= #idx then + local c = (table.create(n) ) +table.move(idx, 1, n, 1, c) + idx = c + end + return false, idx, nil + elseif mode == "polygons" then + if prim.faces == nil then + return nil, nil, "polygons primitive without faces" + end + local sizes, err = Flatten.numbers(prim.faces, true) + if not sizes then + return nil, nil, "faces: " .. tostring(err) + end + local total = 0 + for i = 1, #sizes do + local s = sizes[i] + if s < 0 or s % 1 ~= 0 then + return nil, nil, "bad face size" + end + total =total+ s + end + if total ~= #idx then + return nil, nil, "face sizes do not add up to the index count" + end + return sizes, idx, nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local c = {} + for i = 3, #idx do + if mode == "triangle_fan" then + table.insert(c, idx[1]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + elseif i % 2 == 1 then + table.insert(c, idx[i - 2]) + table.insert(c, idx[i - 1]) + table.insert(c, idx[i]) + else + table.insert(c, idx[i - 1]) + table.insert(c, idx[i - 2]) + table.insert(c, idx[i]) + end + end + return false, c, nil + end + return nil, nil, "unknown primitive mode " .. tostring(mode) +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0 +local function fill(name, t, raw) +if string.sub(name, 1, 6) ~= "COLOR_" then + return 0 + end + return (raw and NORM[t] and{NORM[t] }or{1 +})[1]end + +local function f32(v) +local b = buffer.create(4) + buffer.writef32(b, 0, v) + return buffer.readf32(b, 0) +end + +-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always). +-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then). +function Flatten.merge(scene, keep, opts) +if type(scene) ~= "table" then + return nil, "not a scene" + end + local list, lerr = instances(scene) + if not list then + return nil, lerr + end + local triangulate = opts and opts.triangulate or false + -- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count + local types= {} + local comps= {} + local used= {} + for _, inst in __iter(list) do + local mode = inst.prim.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" then + local pos = inst.prim.attributes.POSITION + if type(pos) ~= "table" then + return nil, "primitive without POSITION" + end + table.insert(used, inst) + for name, acc in __iter(inst.prim.attributes) do + if type(name) == "string" and (name == "POSITION" or keep(name)) and type(acc) == "table" then + local t = acc.type + if types[name] == nil then + types[name] = t + elseif types[name] ~= t then + types[name] = "f32" + end + comps[name] = math.max(comps[name] or 0, tonumber(acc.components) or 0) + end + end + end + end + if (comps.POSITION or 3) < 3 then + return nil, "POSITION needs 3 components" + end + local attrs= {} + for name, t in __iter(types) do + local raw = NORM[t] ~= nil + if name == "POSITION" or name == "NORMAL" then + raw = false + end + attrs[name] = { type = (name == "POSITION" or name == "NORMAL" )and"f32" or t, components = (name == "POSITION" or name == "NORMAL" )and 3 or comps[name], raw = raw, values = {} } + end + local merged= { count = 0, attrs = attrs, sizes = nil, corners = {}, parts = {} } + local sizes= {} + local anyFaces = false + local corners = merged.corners + for _, inst in __iter(used) do + local prim= inst.prim + local posAcc = prim.attributes.POSITION + local nv = tonumber(posAcc.count) or 0 + local m = inst.matrix + local identity = m == nil or isIdentity(m ) + local info= { prim = prim, mesh = inst.mesh, node = inst.node, firstVertex = merged.count, vertexCount = nv, firstFace = #sizes, faceCount = 0, identity = identity } + for name, a in __iter(attrs) do + local acc = prim.attributes[name] + local dst = a.values + local n0 = #dst + local ac = a.components + if acc == nil then + local f = fill(name, a.type, a.raw) + for i = 1, nv * ac do + dst[n0 + i] = f + end + else + if acc.count ~= nv then + return nil, name .. " count differs from POSITION" + end + local vals, err = Flatten.numbers(acc, a.raw and acc.type == a.type) + if not vals then + return nil, name .. ": " .. tostring(err) + end + local sc = acc.components + if a.raw and acc.type ~= a.type then + return nil, name .. ": mixed accessor types" + end + local f = fill(name, a.type, a.raw) + if name == "POSITION" and not identity then + local mm = m +for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + dst[n0 + i * 3 + 1] = f32(mm[1] * x + mm[5] * y + mm[9] * z + mm[13]) + dst[n0 + i * 3 + 2] = f32(mm[2] * x + mm[6] * y + mm[10] * z + mm[14]) + dst[n0 + i * 3 + 3] = f32(mm[3] * x + mm[7] * y + mm[11] * z + mm[15]) + end + elseif name == "NORMAL" and not identity and sc >= 3 then + local mm = m -- the cofactor matrix of the upper 3x3 = det * inverse transpose; the sign of det keeps the direction + +local a1, a2, a3, b1, b2, b3, c1, c2, c3 = mm[1], mm[2], mm[3], mm[5], mm[6], mm[7], mm[9], mm[10], mm[11] + local n11, n12, n13 = b2 * c3 - b3 * c2, b3 * c1 - b1 * c3, b1 * c2 - b2 * c1 + local n21, n22, n23 = c2 * a3 - c3 * a2, c3 * a1 - c1 * a3, c1 * a2 - c2 * a1 + local n31, n32, n33 = a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 + local sgn = a1 * n11 + a2 * n12 + a3 * n13 < 0 and-1 or 1 + for i = 0, nv - 1 do + local x, y, z = vals[i * sc + 1], vals[i * sc + 2], vals[i * sc + 3] + -- column j of the cofactor matrix multiplies component j: (inverse transpose) * n + local nx = n11 * x + n21 * y + n31 * z + local ny = n12 * x + n22 * y + n32 * z + local nz = n13 * x + n23 * y + n33 * z + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = sgn * nx / l, sgn * ny / l, sgn * nz / l + end + dst[n0 + i * 3 + 1] = f32(nx) + dst[n0 + i * 3 + 2] = f32(ny) + dst[n0 + i * 3 + 3] = f32(nz) + end + else + for i = 0, nv - 1 do + for c = 1, ac do + dst[n0 + i * ac + c] = (c <= sc and{vals[i * sc + c] }or{f +})[1] end + end + end + end + end + local fs, cs, ferr = faces(prim, nv) + if ferr then + return nil, ferr + end + local flip = false + if not identity then + local mm = m +local det = mm[1] * (mm[6] * mm[11] - mm[7] * mm[10]) - mm[5] * (mm[2] * mm[11] - mm[3] * mm[10]) + mm[9] * (mm[2] * mm[7] - mm[3] * mm[6]) + flip = det < 0 + end + if fs ~= "points" and fs ~= "skip" then + anyFaces = true + local base = merged.count + local cl= cs + local p = 0 + local nf = (fs and((#fs ))or((math.floor(#cl / 3 +)))) for f = 1, nf do + local s = (fs and{fs[f] }or{3 +})[1] if triangulate then + for k = 2, s - 1 do + table.insert(sizes, 3) + local a, b, c = cl[p + 1], cl[p + k], cl[p + k + 1] + if flip then + b, c = c, b + end + table.insert(corners, base + a) + table.insert(corners, base + b) + table.insert(corners, base + c) + end + else + table.insert(sizes, s) + if flip then + table.insert(corners, base + cl[p + 1]) + for k = s, 2, -1 do + table.insert(corners, base + cl[p + k]) + end + else + for k = 1, s do + table.insert(corners, base + cl[p + k]) + end + end + end + p =p+ s + end + end + info.faceCount = #sizes - info.firstFace + merged.count =merged.count+ nv + table.insert(merged.parts, info) + end + merged.sizes = (anyFaces and{sizes }or{nil +})[1] return merged, nil +end + +return Flatten +end +__FILES["codecs/model/Minecraft"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. +-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default +-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids +-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block +-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / +-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. +-- +-- local Mc = require("rosetta.codecs.model.Minecraft") +-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } +-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air +-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks +-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Colors = __include("codecs/model/Minecraft/Colors") +local Legacy = __include("codecs/model/Minecraft/Legacy") +local Packed = __include("codecs/model/Minecraft/Packed") + +local Minecraft = {} + +Minecraft.Packed = Packed +Minecraft.Legacy = Legacy + +-- ------------------------------------------------------------------------------------------------ block states +-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order +function Minecraft.parseState(s) +local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") + local n = name or "" + if n ~= "" and not string.find(n, ":", 1, true) then + n = "minecraft:" .. n + end + local props = {} + local body = rest and string.match(rest , "^%[(.*)%]%s*$") + if body then + for pair in __iter(string.gmatch(body, "[^,]+")) do + local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if k then + table.insert(props, { k, v }) + end + end + end + return n, props +end + +-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) +function Minecraft.stateString(name, props) +if not props or next(props) == nil then + return name + end + local parts = {} + if props[1] ~= nil then + for _, kv in __iter(props) do + table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) + end + else + for _, k in __iter(Types.keys(props)) do + table.insert(parts, tostring(k) .. "=" .. tostring((props )[k])) + end + end + return name .. "[" .. table.concat(parts, ",") .. "]" +end + +-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) +function Minecraft.stateFromNbt(c) +if type(c) ~= "table" or type(c.Name) ~= "string" then + return nil + end + local props = {} + if type(c.Properties) == "table" then + for _, k in __iter(Types.keys(c.Properties)) do + local v = c.Properties[k] + table.insert(props, { k, (type(v) == "string" and{v }or{(tostring(Nbt.number(v) or v) )})[1]}) + end + end + return Minecraft.stateString(c.Name, props) +end + +-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) +function Minecraft.stateToNbt(s) +local name, props = Minecraft.parseState(s) + local c = Types.object({ Name = name }, { "Name" }) + if #props > 0 then + local p, keys = {}, {} + for _, kv in __iter(props) do + p[kv[1] ] = kv[2] + table.insert(keys, kv[1]) + end + Types.set(c, "Properties", Types.object(p, keys)) + end + return c +end + +-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") +function Minecraft.baseName(s) +local name = string.match(s, "^%s*([^%[%s]*)") or "" + return string.match(name, ":(.*)$") or name +end + +local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } +-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) +function Minecraft.isAir(s) +return AIR[Minecraft.baseName(s)] == true +end + +-- ------------------------------------------------------------------------------------------------ colours +local function hex(h) +local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } + if #h >= 8 then + c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 + end + return c +end +local function list(s) +local out = {} + for h in __iter(string.gmatch(s, "%x+")) do + table.insert(out, hex(h)) + end + return out +end + +local EXACT= {} +for name, h in __iter(string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)")) do + EXACT[name ] = hex(h ) +end +local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) +local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) +-- longest prefixes first, so light_blue wins over blue and dark_oak over oak +local function byLength(names) +local out= {} + for i, n in __iter(names) do + table.insert(out, { n, i }) + end + table.sort(out, function(a, b) +return #(a[1] ) > #(b[1] ) + end) + return out +end +local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) +local SUFFIXES = { + "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", + "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", +} +local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL= { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local FALLBACK = hex("909090") + +local function mix(c, w, t) +return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } +end + +local resolve + +local function family(n) +for _, d in __iter(DYES) do + local pre = d[1] .. "_" + if string.sub(n, 1, #pre) == pre then + local rest = string.sub(n, #pre + 1) + local i = d[2] + if rest == "concrete" then + return CONCRETE[i] + elseif rest == "concrete_powder" then + return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) + elseif rest == "terracotta" then + return TERRACOTTA[i] + elseif string.find(rest, "glass", 1, true) then + local c = table.clone(WOOL[i]) + c[4] = 0x80 + return c + end + return WOOL[i] + end + end + local stripped = string.match(n, "^stripped_(.*)$") + for _, w in __iter(WOODS) do + local pre = w[1] .. "_" + local m = stripped or n + if string.sub(m, 1, #pre) == pre then + local rest = string.sub(m, #pre + 1) + local i = w[2] + if stripped then + return PLANKS[i] + elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then + return BARK[i] + elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then + return LEAVES[i] + elseif rest == "block" and w[1] == "bamboo" then + return EXACT.bamboo_block + end + return PLANKS[i] + end + end + return nil +end + +local function keywords(n) +if string.find(n, "copper", 1, true) then + return (string.find(n, "oxidized", 1, true) and{EXACT.oxidized_copper +}or{(string.find(n, "weathered", 1, true) and{EXACT.weathered_copper +}or{(string.find(n, "exposed", 1, true) and{EXACT.exposed_copper +}or{EXACT.copper_block +})[1]})[1]})[1] elseif string.find(n, "coral", 1, true) then + if string.find(n, "dead", 1, true) then + return hex("857e79") + end + for k, c in __iter(CORAL) do + if string.find(n, k, 1, true) then + return c + end + end + elseif string.find(n, "_ore$") then + return (string.find(n, "deepslate", 1, true) and{EXACT.deepslate +}or{(string.find(n, "nether", 1, true) and{EXACT.netherrack +}or{EXACT.stone +})[1]})[1] end + for _, k in __iter({ "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" }) do + if string.find(n, k, 1, true) then + local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } )[k] + return EXACT[alias] + end + end + return nil +end + +resolve = function(n, depth) +if depth > 4 then + return nil + end + local c = EXACT[n] + if c then + return c + end + local renamed = Legacy.RENAMED[n] + if renamed then + return resolve(renamed, depth + 1) + end + for _, p in __iter(PREFIXES) do + if string.sub(n, 1, #p) == p then + return resolve(string.sub(n, #p + 1), depth + 1) + end + end + c = family(n) + if c then + return c + end + for _, sfx in __iter(SUFFIXES) do + if #n > #sfx and string.sub(n, -#sfx) == sfx then + local base = string.sub(n, 1, #n - #sfx) + for _, form in __iter({ base, base .. "s", base .. "_block", base .. "_planks" }) do + local fc = EXACT[form] or family(form) + if fc then + return fc + end + end + return resolve(base, depth + 1) + end + end + return keywords(n) +end + +local cache= {} +-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords +function Minecraft.color(s) +local hit = cache[s] + if hit ~= nil then + return hit or nil + end + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local res= nil + if not AIR[n] then + -- pre-1.13 names whose data value picks the variant + local variants = Legacy.VARIANTS[n] or ((n == "double_wooden_slab" and{Legacy.VARIANTS.planks }or{nil})[1]) + if variants then + local data = 0 + for _, kv in __iter(props) do + if kv[1] == "data" then + data = tonumber(kv[2]) or 0 + end + end + local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] + res = resolve(v, 0) + end + res = res or resolve(n, 0) or FALLBACK + end + cache[s] = res or false + return res +end + +-- ------------------------------------------------------------------------------------------------ legacy ids +local REVERSE= nil +local function reverse() +if REVERSE then + return REVERSE + end + local r= {} + local byName= {} + for i, n in __iter(Legacy.NAMES) do + if n ~= "-" then + byName[n] = i - 1 + end + end + for legacy, modern in __iter(Legacy.RENAMED) do + r[modern] = { byName[legacy], 0 } + end + for legacy, variants in __iter(Legacy.VARIANTS) do + for d, v in __iter(variants) do + if r[v] == nil then + r[v] = { byName[legacy], d - 1 } + end + end + end + for n, id in __iter(byName) do + if r[n] == nil then + r[n] = { id, 0 } + end + end + REVERSE = r + return r +end + +-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the +-- rest of the data value kept as [data=N] so legacyId gives it back exactly) +function Minecraft.legacyState(id, data) +local n = Legacy.NAMES[id + 1] + if n == nil or n == "-" then + return "minecraft:legacy_" .. id .. ((data ~= 0 and(("[data=" .. data .. "]" ))or(""))) + end + local variants = Legacy.VARIANTS[n] + if variants then + local idx = data % (Legacy.MASK[n] or 16) + local v = variants[idx + 1] + if v then + return "minecraft:" .. v .. ((data ~= idx and(("[data=" .. data .. "]" ))or(""))) + end + end + return "minecraft:" .. (Legacy.RENAMED[n] or n) .. ((data ~= 0 and(("[data=" .. data .. "]" ))or(""))) +end + +-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their +-- properties are not converted to data values) +function Minecraft.legacyId(s) +local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local id, data = nil, 0 + local lid = string.match(n, "^legacy_(%d+)$") + if lid then + id = tonumber(lid) + else + local e = reverse()[n] + if e then + id, data = e[1], e[2] + end + end + if id == nil then + return nil, nil + end + for _, kv in __iter(props) do + if kv[1] == "data" then + data = (tonumber(kv[2]) or data) % 16 + end + end + return id, data +end + +-- ------------------------------------------------------------------------------------------------ voxels +-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, +-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into +-- the nearest one) +function Minecraft.voxels(sx, sy, sz, states, indices) +local v = Types.Voxels.new(sx, sy, sz) + local lut = buffer.create(#states) + local slots= {} + local used = 0 + for i, s in __iter(states) do + local c = Minecraft.color(s) + local slot = 0 + if c then + local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) + slot = slots[key] + if not slot then + if used < 255 then + used =used+ 1 + slot = used + v.palette[slot] = { c[1], c[2], c[3], c[4] } + else + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot = best + end + slots[key] = slot + end + end + buffer.writeu8(lut, i - 1, slot) + end + local n = sx * sy * sz + local data, nstates = v.data, #states + for i = 0, n - 1 do + local s = buffer.readu16(indices, i * 2) + buffer.writeu8(data, i, (s < nstates and{(buffer.readu8(lut, s) )}or{0})[1]) + end + v.blocks = { palette = states, data = indices } + return v +end + +-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) +local CANDIDATES= nil +local function candidates() +if CANDIDATES then + return CANDIDATES + end + local out = {} + for _, d in __iter(Colors.DYES) do + for _, kind in __iter({ "wool", "concrete", "terracotta" }) do + local s = "minecraft:" .. d .. "_" .. kind + table.insert(out, { s, Minecraft.color(s) }) + end + end + for _, w in __iter(Colors.WOODS) do + local s = "minecraft:" .. w .. "_planks" + table.insert(out, { s, Minecraft.color(s) }) + end + for _, n in __iter({ "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" }) do + local s = "minecraft:" .. n + table.insert(out, { s, Minecraft.color(s) }) + end + CANDIDATES = out + return out +end + +-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) +function Minecraft.nearestBlock(c) +local a = c[4] or 255 + if a < 200 then + local best, bd = "minecraft:glass", math.huge + for i, d in __iter(Colors.DYES) do + local w = WOOL[i] + local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 + if dist < bd then + best, bd = "minecraft:" .. d .. "_stained_glass", dist + end + end + return best + end + local best, bd = "minecraft:stone", math.huge + for _, cand in __iter(candidates()) do + local k = cand[2] + local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 + if dist < bd then + best, bd = cand[1], dist + end + end + return best +end + +-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per +-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message +function Minecraft.blocksOf(v) +local n = v.size[1] * v.size[2] * v.size[3] + local b = v.blocks + if b then + if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then + return nil, "voxels.blocks must hold a palette and a u16 per cell" + end + if #b.palette == 0 or #b.palette > 65536 then + return nil, "voxels.blocks.palette must have 1 .. 65536 states" + end + return b.palette, b.data + end + local states = { "minecraft:air" } + local slotOf= { [0] = 0 } + local byState= { ["minecraft:air"] = 0 } + local out = buffer.create(n * 2) + local data = v.data + for i = 0, n - 1 do + local p = buffer.readu8(data, i) + local s = slotOf[p] + if s == nil then + local col = v.palette[p] or { 128, 128, 128, 255 } + local st = Minecraft.nearestBlock(col) + s = byState[st] + if s == nil then + table.insert(states, st) + s = #states - 1 + byState[st] = s + end + slotOf[p] = s + end + buffer.writeu16(out, i * 2, s ) + end + return states, out +end + +-- ------------------------------------------------------------------------------------------------ block entities +-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat +-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +local function int(v) +local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end +local function ints(v) +if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and (v )[1] ~= nil then + local out= {} + for i, x in __iter(v) do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end +Minecraft.int = int -- the integer value of an NBT number | nil +Minecraft.ints = ints -- the numbers of an intArray or a list | nil + +local function rest(c, skip) +local out, keys = {}, {} + for _, k in __iter(Types.keys(c)) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Minecraft.blockEntity(c, style) +if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = (type(c.id) == "string" and{c.id }or{nil})[1], data = rest(c, FLAT_SKIP) } + end + local p = ints(c.Pos) or { 0, 0, 0 } + local data = (style == "data" and{((type(c.Data) == "table" and{c.Data }or{(Types.object())})[1]) }or{(rest(c, POS_SKIP) +)})[1] return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = (type(c.Id) == "string" and{c.Id }or{nil})[1], data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Minecraft.flatBlockEntity(be, style) +local o = Types.object() + local data = (type(be.data) == "table" and{be.data }or{(Types.object() +)})[1] if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in __iter(Types.keys(data)) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in __iter(Types.keys(data)) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + +return Minecraft +end +__FILES["codecs/model/Minecraft/Colors"] = function() +--!strict +-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured +-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were +-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / +-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +local Colors = {} + +Colors.BLOCKS = [[ +stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 +polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c +mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 +suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 +red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f +sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d +iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 +netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 +cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 +budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 +obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d +ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd +ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a +carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 +polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 +red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 +warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab +prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c +terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 +chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 +cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 +polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 +cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 +polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 +moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 +bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 +lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 +vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 +kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 +mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 +honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 +lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 +cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 +crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 +mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab +redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c +sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 +chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 +activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 +soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 +fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 +beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 +wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 +cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 +dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 +cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 +trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f +repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a +dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b +orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 +lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 +torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c +flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a +beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c +weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 +frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 +muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea +creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a +]] + +-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) +Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } +Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" +Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" +Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" + +-- wood types: planks, bark (log / wood), leaves +Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } +Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" +Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" +Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" + +return Colors +end +__FILES["codecs/model/Minecraft/Legacy"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with +-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): +-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it +-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +local Legacy = {} + +local function words(s) +local out = {} + for w in __iter(string.gmatch(s, "%S+")) do + table.insert(out, w) + end + return out +end + +-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused +Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava +lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock +bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension +yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt +bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block +crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever +stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch +stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal +lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick +brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate +brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart +enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp +lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire +emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots +potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate +unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs +activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime +barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant +standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 +stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence +birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door +end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks +beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block +red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box +light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box +cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box +black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta +light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta +gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta +blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta +concrete concrete_powder - - structure_block]]) + +-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: +-- lit_furnace, powered_repeater, ... keep their legacy names) +Legacy.RENAMED = { + grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", + melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", + red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", + mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", + tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", + fence = "oak_fence", fence_gate = "oak_fence_gate", + wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", + wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", + wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", + silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", + monster_egg = "infested_stone", + standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", + bed = "red_bed", +} +-- legacy names whose data value selects the variant: the modern names by data value (0-based) + +local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" +local function dyed(suffix) +local out = {} + for i, d in __iter(words(DYED)) do + out[i] = d .. "_" .. suffix + end + return out +end +Legacy.VARIANTS = { + stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, + dirt = { "dirt", "coarse_dirt", "podzol" }, + planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, + wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, + sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, + sand = { "sand", "red_sand" }, + log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 + log2 = { "acacia_log", "dark_oak_log" }, + leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, + leaves2 = { "acacia_leaves", "dark_oak_leaves" }, + sponge = { "sponge", "wet_sponge" }, + sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, + red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, + stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, + quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, + prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, + cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, + red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, + double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, + wool = dyed("wool"), + carpet = dyed("carpet"), + stained_glass = dyed("stained_glass"), + stained_glass_pane = dyed("stained_glass_pane"), + stained_hardened_clay = dyed("terracotta"), + concrete = dyed("concrete"), + concrete_powder = dyed("concrete_powder"), +} +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } + +return Legacy +end +__FILES["codecs/model/Minecraft/Packed"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and +-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding +-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: +-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written +-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +local Packed = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 +local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor + +-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes +function Packed.longsNeeded(count, bits, spanning) +if spanning then + return math.floor((count * bits + 63) / 64 +) end + local per = math.floor(64 / bits +) return math.floor((count + per - 1) / per +)end + +-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte +-- 0); an index >= max is an error. bits 1 .. 16. +function Packed.unpack(longs, bits, count, spanning, out, max) +if bits < 1 or bits > 16 then + return false, "unsupported: " .. bits .. "-bit packed indices" + end + local need = Packed.longsNeeded(count, bits, spanning) + if buffer.len(longs) < need * 8 then + return false, "packed array too short (" .. math.floor(buffer.len(longs) / 8 ).. " longs, need " .. need .. ")" + end + if buffer.len(out) < count * 2 then + return false, "output too small" + end + -- a copy with 4 bytes of padding, so every 32-bit read stays in range + local n = need * 8 + local src = buffer.create(n + 4) + buffer.copy(src, 0, longs, 0, n) + if spanning then + local p = 0 + for i = 0, count - 1 do + local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + p =p+ bits + end + else + local per = math.floor(64 / bits +) local i = 0 + local base = 0 + while i < count do + local p = 0 + for _ = 1, per do + if i >= count then + break + end + local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + i =i+ 1 + p =p+ bits + end + base =base+ 8 + end + end + return true, nil +end + +-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack +function Packed.pack(indices, count, bits, spanning) +local need = Packed.longsNeeded(count, bits, spanning) + local out = buffer.create(need * 8 + 4) + local per = math.floor(64 / bits +) for i = 0, count - 1 do + local v = readu16(indices, i * 2) + local p = (spanning and((i * bits ))or(((math.floor(i / per)) * 64 + (i % per) * bits +))) local at = rshift(p, 3) + local sh = band(p, 7) + -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) + local x = lshift(v, sh) + for k = 0, 2 do + local bits8 = band(rshift(x, k * 8), 0xff) + if bits8 ~= 0 then + writeu8(out, at + k, bor(readu8(out, at + k), bits8)) + end + end + end + local res = buffer.create(need * 8) + buffer.copy(res, 0, out, 0, need * 8) + return res +end + +-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) +function Packed.bitsFor(n, min) +local b = min + while lshift(1, b) < n and b < 31 do + b =b+ 1 + end + return b +end + +-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge +-- BlockData) into out (u16 LE) +function Packed.varints(src, offset, length, count, out, max) +if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then + return false, "bad varint array arguments" + end + local p, e = offset, offset + length + for i = 0, count - 1 do + local v, sh = 0, 0 + while true do + if p >= e then + return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" + end + local c = readu8(src, p) + p =p+ 1 + v =v+ band(c, 0x7f) * 2 ^ sh + if c < 128 then + break + end + sh =sh+ 7 + if sh > 28 then + return false, "varint too long" + end + end + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + end + return true, nil +end + +-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints +function Packed.toVarints(indices, count) +local out = buffer.create(count * 3) + local p = 0 + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + while v >= 128 do + writeu8(out, p, band(v, 0x7f) + 128) + p =p+ 1 + v = rshift(v, 7) + end + writeu8(out, p, v) + p =p+ 1 + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res +end + +-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's +-- AddBlocks: high nibble first) +function Packed.nibble(src, offset, i, highFirst) +local b = readu8(src, offset + rshift(i, 1)) + local odd = band(i, 1) == 1 + if odd == highFirst then + return band(b, 15) + end + return rshift(b, 4) +end + +-- setNibble(dst, offset, i, v, highFirst) +function Packed.setNibble(dst, offset, i, v, highFirst) + local at = offset + rshift(i, 1) + local b = readu8(dst, at) + local odd = band(i, 1) == 1 + if odd == highFirst then + writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) + else + writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) + end +end + +-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then +-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new +-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +function Packed.fromYzx(src, sx, sy, sz, dst, ox, oy, oz, dsx, dsy) +local out = dst or buffer.create(sx * sy * sz * 2) + local bx, by, bz = ox or 0, oy or 0, oz or 0 + local wx, wy = dsx or sx, dsy or sy + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 + for _ = 0, sx - 1 do + writeu16(out, d, readu16(src, i)) + i =i+ 2 + d =d+ 2 + end + end + end + return out +end + +-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) +function Packed.toYzx(src, sx, sy, sz) +local out = buffer.create(sx * sy * sz * 2) + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local s = (sx * (y + sy * z)) * 2 + for _ = 0, sx - 1 do + writeu16(out, i, readu16(src, s)) + i =i+ 2 + s =s+ 2 + end + end + end + return out +end + +return Packed +end +__FILES["codecs/model/Polygon"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map +-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the +-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the +-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so +-- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method +-- (D. Eberly, Triangulation by Ear Clipping); no code taken. +-- +-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } }) +-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair +-- -- (1-based), counter-clockwise +-- +-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored. +local Polygon = {} + + + +local function area(pts) +local a = 0 + local n = #pts + for i = 1, n do + local p, q = pts[i], pts[i % n + 1] + a =a+ (p.x * q.y - q.x * p.y +) end + return a / 2 +end + +local function inside(pts, x, y) +local c = false + local n = #pts + local j = n + for i = 1, n do + local a, b = pts[i], pts[j] + if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then + c = not c + end + j = i + end + return c +end + +local function cross(o, a, b) +return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +end + +-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count) +local function crosses(p1, p2, q1, q2) +if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then + return false + end + local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2) + local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2) + return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)) +end + +local function visible(m, v, rings) +for _, r in __iter(rings) do + local n = #r + for i = 1, n do + if crosses(m, v, r[i], r[i % n + 1]) then + return false + end + end + end + return true +end + +-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible +-- vertices; others = every ring the bridge must not cross +local function bridge(outer, h, others) +local mi = 1 + for i, p in __iter(h) do + if p.x > h[mi].x then + mi = i + end + end + local m = h[mi] + local best, bestD = 0, math.huge + for pass = 1, 2 do + for i, v in __iter(outer) do + if pass == 2 or v.x >= m.x then + local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2 + if d < bestD and visible(m, v, others) then + best, bestD = i, d + end + end + end + if best > 0 then + break + end + end + if best == 0 then + best = 1 + end + local out= {} + for i = 1, best do + table.insert(out, outer[i]) + end + local n = #h + for k = 0, n do + table.insert(out, h[(mi - 1 + k) % n + 1]) + end + for i = best, #outer do + table.insert(out, outer[i]) + end + return out +end + +local function inTri(a, b, c, p) +return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0 +end + +-- ear clipping of one counter-clockwise ring +local function clip(ring, out) + local pts = table.clone(ring) + local guard = #pts * #pts + 16 + while #pts > 3 and guard > 0 do + guard =guard- 1 + local n = #pts + local found, bestI, bestScore = 0, 1, -math.huge + for i = 1, n do + local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + local cr = cross(a, b, c) + if cr > 0 then + local ok = true + for k = 1, n do + local p = pts[k] + if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then + ok = false + break + end + end + if ok then + found = i + break + end + end + if cr > bestScore then + bestI, bestScore = i, cr + end + end + local i = (found > 0 and{found }or{bestI +})[1] local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1] + if cross(a, b, c) ~= 0 then + table.insert(out, a.loop) + table.insert(out, a.index) + table.insert(out, b.loop) + table.insert(out, b.index) + table.insert(out, c.loop) + table.insert(out, c.index) + end + table.remove(pts, i) + end + if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then + for k = 1, 3 do + table.insert(out, pts[k].loop) + table.insert(out, pts[k].index) + end + end +end + +-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly) +function Polygon.triangulate(loops) +local rings= {} + local areas= {} + for li, l in __iter(loops) do + local pts= {} + for k = 1, #l - 1, 2 do + local x, y = l[k], l[k + 1] + if type(x) == "number" and type(y) == "number" and x == x and y == y then + table.insert(pts, { x = x, y = y, loop = li, index = math.floor((k + 1) / 2 )}) + end + end + local a = (#pts >= 3 and{(area(pts) )}or{0 +})[1] if a ~= 0 then + table.insert(rings, pts) + table.insert(areas, math.abs(a)) + if a < 0 then -- counter-clockwise for now; holes are flipped below + local r= {} + for k = #pts, 1, -1 do + table.insert(r, pts[k]) + end + rings[#rings] = r + end + end + end + -- nesting: the parent of a ring is the smallest ring containing its first point + local n = #rings + local depth, parent = table.create(n, 0), table.create(n, 0) + for i = 1, n do + local p = rings[i][1] + for j = 1, n do + if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then + depth[i]=depth[i]+ 1 + if parent[i] == 0 or areas[j] < areas[parent[i] ] then + parent[i] = j + end + end + end + end + local holes= {} + for i = 1, n do + if depth[i] % 2 == 1 and parent[i] > 0 then + local list = holes[parent[i] ] or {} + holes[parent[i] ] = list + table.insert(list, i) + end + end + local out= {} + for i = 1, n do + if depth[i] % 2 == 0 then + local ring = rings[i] + local hs = holes[i] + if hs then + table.sort(hs, function(a, b) +local ma, mb = -math.huge, -math.huge + for _, p in __iter(rings[a]) do + ma = math.max(ma, p.x) + end + for _, p in __iter(rings[b]) do + mb = math.max(mb, p.x) + end + return ma > mb + end) + local flipped= {} + for _, h in __iter(hs) do + local r= {} + local src = rings[h] + for k = #src, 1, -1 do + table.insert(r, src[k]) + end + table.insert(flipped, r) + end + for k, h in __iter(flipped) do + local others= { ring } + for k2 = k + 1, #flipped do + table.insert(others, flipped[k2]) + end + ring = bridge(ring, h, others) + end + end + clip(ring, out) + end + end + return out +end + +return Polygon +end +__FILES["codecs/model/Rbx"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl, +-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the +-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the +-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library, +-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself. +-- +-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... } +-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} } +-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} } +-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests +-- for inst, depth in Rbx.descendants(tree) do ... end +-- +-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor +-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox): +-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes) +-- SharedString string (the content; writers deduplicate) +-- Bool boolean +-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53) +-- Enum, BrickColor, SecurityCapabilities number +-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32 +-- Axes number: bits X 1, Y 2, Z 4 +-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max } +-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1) +-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz } +-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none) +-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... } +-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight, +-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out) +-- Ref an Instance of the tree, or nil +-- UniqueId 32 hex digits: random (16), time (8), index (8) +-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? } +-- Content nil (none) | string (a URI) | an Instance (object) +-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column), +-- index, count }; written back verbatim while the class keeps the same instances in the same order +-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is +-- Name is not a property here: it is inst.name. Never throws. + +local Rbx = {} + +-- ------------------------------------------------------------------------------------------------ tree + + + + + + + + + + + + + + + + + + + +function Rbx.tree(place) +return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} } +end + +function Rbx.instance(className, name) +return { className = className, name = name or className, properties = {}, children = {} } +end + +-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance +function Rbx.add(parent, child) +if parent.kind == "rbxtree" then + child.parent = nil + table.insert(parent.roots, child) + else + child.parent = parent + table.insert(parent.children, child) + end + return child +end + +-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...) +function Rbx.set(inst, name, typ, value) + inst.properties[name] = { type = typ, value = value } +end + +-- get(inst, name) -> the property's value (not the Value table), nil when absent +function Rbx.get(inst, name) +local v = inst.properties[name] + return (v and{v.value }or{nil +})[1]end + +-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children +-- at depth 1) +function Rbx.descendants(root) +local stack= {} + local list = (root.kind == "rbxtree" and{root.roots }or{root.children +})[1] for i = #list, 1, -1 do + table.insert(stack, { list[i], 1 }) + end + return function() +local top = table.remove(stack) + if not top then + return nil, nil + end + local inst, depth = top[1], top[2] + for i = #inst.children, 1, -1 do + table.insert(stack, { inst.children[i], depth + 1 }) + end + return inst, depth + end +end + +-- list(tree) -> every instance, depth first +function Rbx.list(tree) +local out = {} + for inst in __iter(Rbx.descendants(tree)) do + table.insert(out, inst ) + end + return out +end + +-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil +function Rbx.find(root, path) +local cur= root + for part in __iter(string.gmatch(path, "[^/]+")) do + local list = (cur.kind == "rbxtree" and{cur.roots }or{cur.children +})[1] local found = nil + for _, c in __iter(list) do + if c.name == part then + found = c + break + end + end + if not found then + return nil + end + cur = found + end + return (cur.kind == "rbxtree" and{nil }or{cur +})[1]end + +-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root) +function Rbx.fullName(inst) +local parts = {} + local cur= inst + while cur do + table.insert(parts, 1, cur.name) + cur = cur.parent + end + return table.concat(parts, ".") +end + +-- ------------------------------------------------------------------------------------------------ CFrame rotation ids +-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is +-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product. +local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } + +-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation +local ROTATIONS= {} +for a = 0, 5 do + for b = 0, 5 do + if a % 3 ~= b % 3 then + local r, u = AXES[a + 1], AXES[b + 1] + local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] } + -- columns: right, up, back (= right x up) + ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 } + end + end +end +Rbx.ROTATIONS = ROTATIONS + +local function axisIndex(x, y, z) +for i, a in __iter(AXES) do + if a[1] == x and a[2] == y and a[3] == z then + return i - 1 + end + end + return nil +end + +-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned +function Rbx.rotationId(cf) +local a = axisIndex(cf[4], cf[7], cf[10]) + local b = axisIndex(cf[5], cf[8], cf[11]) + if not a or not b then + return 0 + end + local id = 6 * a + b + 1 + local rot = ROTATIONS[id] + if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then + return 0 + end + return id +end + +-- ------------------------------------------------------------------------------------------------ values +-- binary type ids (rbx-dom docs/binary.md) by type name, and back +Rbx.TYPE_IDS = table.freeze({ + String = 0x01, + BinaryString = 0x01, + ProtectedString = 0x01, + ContentId = 0x01, + Bool = 0x02, + Int32 = 0x03, + Float32 = 0x04, + Float64 = 0x05, + UDim = 0x06, + UDim2 = 0x07, + Ray = 0x08, + Faces = 0x09, + Axes = 0x0A, + BrickColor = 0x0B, + Color3 = 0x0C, + Vector2 = 0x0D, + Vector3 = 0x0E, + Vector2int16 = 0x0F, + CFrame = 0x10, + Enum = 0x12, + Ref = 0x13, + Vector3int16 = 0x14, + NumberSequence = 0x15, + ColorSequence = 0x16, + NumberRange = 0x17, + Rect = 0x18, + PhysicalProperties = 0x19, + Color3uint8 = 0x1A, + Int64 = 0x1B, + SharedString = 0x1C, + Bytecode = 0x1D, + OptionalCFrame = 0x1E, + UniqueId = 0x1F, + Font = 0x20, + SecurityCapabilities = 0x21, + Content = 0x22, +} ) +local NAMES= {} +for name, id in __iter(Rbx.TYPE_IDS) do + if NAMES[id] == nil or name == "String" then + NAMES[id] = name + end +end +Rbx.TYPE_NAMES = table.freeze(NAMES) + +-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the +-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1) +local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } +function Rbx.default(typ) +if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then + return "" + elseif typ == "Bool" then + return false + elseif typ == "BrickColor" then + return 194 + elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then + return { 0, 0 } + elseif typ == "UDim2" or typ == "Rect" then + return { 0, 0, 0, 0 } + elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then + return { 0, 0, 0 } + elseif typ == "Ray" then + return { 0, 0, 0, 0, 0, 0 } + elseif typ == "CFrame" then + return table.clone(IDENTITY_CF) + elseif typ == "NumberSequence" then + return { { 0, 0, 0 }, { 1, 0, 0 } } + elseif typ == "ColorSequence" then + return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } } + elseif typ == "UniqueId" then + return string.rep("0", 32) + elseif typ == "Font" then + return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" } + elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then + return nil + end + return 0 +end + +-- STRINGS: the string-valued types (one binary type, several XML tags) +Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } ) + +return Rbx +end +__FILES["codecs/model/Rbx/Binary"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk +-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte +-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated" +-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws. +-- +-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms) +-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message +-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT) +-- +-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none), +-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }. +-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know / +-- a layout it cannot read, which the format keeps raw). +local Rbx = __include("codecs/model/Rbx") +local Bytes = __include("core/Bytes") + +local Binary = {} + +local readu8, readu16, readi16, readu32, readf32, readf64 = + buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64 +local writeu32, readstring = buffer.writeu32, buffer.readstring +local writef32 = buffer.writef32 +local floor = math.floor + +local scratch = buffer.create(8) +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ transforms +-- the rotated float encoding: bits rotated left by one (sign in bit 0) +local function unrotate(x) +writeu32(scratch, 0, math.floor(x / 2 )+ (x % 2) * 2147483648) + return readf32(scratch, 0) +end +local function rotate(v) +writef32(scratch, 0, v) + local bits = readu32(scratch, 0) + return (bits * 2) % TWO32 + math.floor(bits / 2147483648 +)end +local function unzigzag(x) +return (x % 2 == 0 and{(math.floor(x / 2 ))}or{(math.floor(-(x + 1) / 2 +))})[1]end +local function zigzag32(v) +v = floor(v) + return ((v >= 0 and((v * 2 ))or((-v * 2 - 1)))) % TWO32 +end + +-- n big-endian u32 values interleaved at p (4n bytes) +local function u32s(b, p, n) +local out = table.create(n, 0) + local n2, n3 = n * 2, n * 3 + for i = 0, n - 1 do + out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i) + end + return out +end +local function i32s(b, p, n) +local out = u32s(b, p, n) + for i = 1, n do + out[i] = unzigzag(out[i]) + end + return out +end +local function f32s(b, p, n) +local out = u32s(b, p, n) + for i = 1, n do + out[i] = unrotate(out[i]) + end + return out +end +-- n zigzag i64 values (8n interleaved bytes), as doubles +local function i64s(b, p, n) +local out = table.create(n, 0) + for i = 0, n - 1 do + local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i) + local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i) + local half = hi * 2147483648 + math.floor(lo / 2 +) out[i + 1] = (lo % 2 == 0 and{half }or{(-half - 1 +)})[1] end + return out +end + +-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64 +local function putU32s(w, vals) + local n = #vals + local p = w:reserve(4 * n) + local b = w.buf + for i = 0, n - 1 do + local v = vals[i + 1] % TWO32 + buffer.writeu8(b, p + i, math.floor(v / 16777216)) + buffer.writeu8(b, p + n + i, (math.floor(v / 65536)) % 256) + buffer.writeu8(b, p + 2 * n + i, (math.floor(v / 256)) % 256) + buffer.writeu8(b, p + 3 * n + i, v % 256) + end + w.pos = p + 4 * n +end +local function putI32s(w, vals) + local t = table.create(#vals, 0) + for i, v in __iter(vals) do + t[i] = zigzag32(v) + end + putU32s(w, t) +end +local function putF32s(w, vals) + local t = table.create(#vals, 0) + for i, v in __iter(vals) do + t[i] = rotate(v) + end + putU32s(w, t) +end +local function putI64s(w, vals) + local n = #vals + local p = w:reserve(8 * n) + local b = w.buf + for i = 0, n - 1 do + local v = floor(vals[i + 1]) + local z = (v >= 0 and((v * 2 ))or((-v * 2 - 1 +))) local hi, lo = (math.floor(z / TWO32)) % TWO32, z % TWO32 + buffer.writeu8(b, p + i, math.floor(hi / 16777216)) + buffer.writeu8(b, p + n + i, (math.floor(hi / 65536)) % 256) + buffer.writeu8(b, p + 2 * n + i, (math.floor(hi / 256)) % 256) + buffer.writeu8(b, p + 3 * n + i, hi % 256) + buffer.writeu8(b, p + 4 * n + i, math.floor(lo / 16777216)) + buffer.writeu8(b, p + 5 * n + i, (math.floor(lo / 65536)) % 256) + buffer.writeu8(b, p + 6 * n + i, (math.floor(lo / 256)) % 256) + buffer.writeu8(b, p + 7 * n + i, lo % 256) + end + w.pos = p + 8 * n +end + +-- referent arrays: zigzag i32, interleaved, each the difference from the previous one +function Binary.readRefs(b, p, limit, n) +if n < 0 or p + 4 * n > limit then + return nil, p + end + local out = i32s(b, p, n) + local acc = 0 + for i = 1, n do + acc =acc+ out[i] + out[i] = acc + end + return out, p + 4 * n +end +function Binary.writeRefs(w, refs) + local d = table.create(#refs, 0) + local prev = 0 + for i, r in __iter(refs) do + d[i] = r - prev + prev = r + end + putI32s(w, d) +end +-- ------------------------------------------------------------------------------------------------ decode +-- a length-prefixed string at p: string, next p (nil when it runs past limit) + + + + + + + + +local function str(b, p, limit) +if p + 4 > limit then + return nil, p + end + local len = readu32(b, p) + if p + 4 + len > limit then + return nil, p + end + return readstring(b, p + 4, len), p + 4 + len +end + +local function cframes(b, p, limit, n) +local rots= (table.create(n) ) +for i = 1, n do + if p >= limit then + return nil, p + end + local id = readu8(b, p) + p =p+ 1 + if id == 0 then + if p + 36 > limit then + return nil, p + end + local m = table.create(9, 0) + for k = 0, 8 do + m[k + 1] = readf32(b, p + 4 * k) + end + rots[i] = m + p =p+ 36 + else + local m = Rbx.ROTATIONS[id] + if not m then + return nil, -1 + end + rots[i] = m + end + end + if p + 12 * n > limit then + return nil, p + end + local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n) + local out = table.create(n) + for i = 1, n do + local m = rots[i] + out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] } + end + return out, p + 12 * n +end + +local FIXED= { -- bytes per value of the fixed-size types + [0x02] = 1, + [0x03] = 4, + [0x04] = 4, + [0x05] = 8, + [0x06] = 8, + [0x07] = 16, + [0x08] = 24, + [0x09] = 1, + [0x0A] = 1, + [0x0B] = 4, + [0x0C] = 12, + [0x0D] = 8, + [0x0E] = 12, + [0x0F] = 4, + [0x12] = 4, + [0x13] = 4, + [0x14] = 6, + [0x17] = 8, + [0x18] = 16, + [0x1A] = 3, + [0x1B] = 8, + [0x1C] = 4, + [0x1F] = 16, + [0x21] = 8, +} + +-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message +function Binary.decode(t, b, p, limit, n, ctx) +if limit > buffer.len(b) or p < 0 or n < 0 then + return nil, "corrupt: bad ranges" + end + local size = FIXED[t] + if size and p + size * n > limit then + return nil, "truncated property values" + end + if t == 0x01 or t == 0x1D then + local out = table.create(n, "") + for i = 1, n do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated string" + end + out[i] = s + p = q + end + return out, p + elseif t == 0x02 then + local out = table.create(n, false) + for i = 1, n do + out[i] = readu8(b, p + i - 1) ~= 0 + end + return out, p + n + elseif t == 0x03 then + return i32s(b, p, n), p + 4 * n + elseif t == 0x04 then + return f32s(b, p, n), p + 4 * n + elseif t == 0x05 then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readf64(b, p + 8 * (i - 1)) + end + return out, p + 8 * n + elseif t == 0x06 then + local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { s[i], o[i] } + end + return out, p + 8 * n + elseif t == 0x07 then + local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n) + local out = table.create(n) + for i = 1, n do + out[i] = { xs[i], xo[i], ys[i], yo[i] } + end + return out, p + 16 * n + elseif t == 0x08 then + local out = table.create(n) + for i = 1, n do + local q = p + 24 * (i - 1) + out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) } + end + return out, p + 24 * n + elseif t == 0x09 or t == 0x0A then + local out = table.create(n, 0) + for i = 1, n do + out[i] = readu8(b, p + i - 1) + end + return out, p + n + elseif t == 0x0B or t == 0x12 then + return u32s(b, p, n), p + 4 * n + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = t == 0x0D and 2 or(t == 0x18 and 4 or 3 +) local cols= (table.create(k) ) +for c = 1, k do + cols[c] = f32s(b, p + 4 * n * (c - 1), n) + end + local out = table.create(n) + for i = 1, n do + local v = table.create(k, 0) + for c = 1, k do + v[c] = cols[c][i] + end + out[i] = v + end + return out, p + 4 * k * n + elseif t == 0x0F or t == 0x14 then + local k = t == 0x0F and 2 or 3 + local out = table.create(n) + for i = 1, n do + local q = p + 2 * k * (i - 1) + out[i] = k == 2 and{ readi16(b, q), readi16(b, q + 2) } or{ readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) } + end + return out, p + 2 * k * n + elseif t == 0x10 then + local out, q = cframes(b, p, limit, n) + if not out then + return nil, q == -1 and"corrupt: bad CFrame rotation id" or"truncated CFrame values" + end + return out, q + elseif t == 0x13 then + local refs, q = Binary.readRefs(b, p, limit, n) + if not refs then + return nil, "truncated referents" + end + local out = table.create(n) + local ref = ctx.ref + for i = 1, n do + out[i] = (ref and refs[i] >= 0 and{(ref(refs[i]) )}or{nil +})[1] end + return out, q + elseif t == 0x15 or t == 0x16 then + local k = t == 0x15 and 3 or 5 + local out = table.create(n) + for i = 1, n do + if p + 4 > limit then + return nil, "truncated sequence" + end + local count = readu32(b, p) + p =p+ 4 + if p + count * 4 * k > limit then + return nil, "truncated sequence" + end + local seq = table.create(count) + for j = 1, count do + local key = table.create(k, 0) + for c = 1, k do + key[c] = readf32(b, p + 4 * (c - 1)) + end + seq[j] = key + p =p+ 4 * k + end + out[i] = seq + end + return out, p + elseif t == 0x17 then + local out = table.create(n) + for i = 1, n do + out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) } + end + return out, p + 8 * n + elseif t == 0x19 then + local out = table.create(n) + for i = 1, n do + if p >= limit then + return nil, "truncated physical properties" + end + local flag = readu8(b, p) + p =p+ 1 + if flag % 2 == 1 then + local k = math.floor(flag / 2 )% 2 == 1 and 6 or 5 + if p + 4 * k > limit then + return nil, "truncated physical properties" + end + local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out + for c = 1, k do + v[c] = readf32(b, p + 4 * (c - 1)) + end + out[i] = v + p =p+ 4 * k + elseif flag ~= 0 then + return nil, "unknown" + end + end + return out, p + elseif t == 0x1A then + local out = table.create(n) + for i = 1, n do + out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) } + end + return out, p + 3 * n + elseif t == 0x1B or t == 0x21 then + return i64s(b, p, n), p + 8 * n + elseif t == 0x1C then + local idx = u32s(b, p, n) + local shared= ctx.shared or {} + local out= table.create(n, "") + for i = 1, n do + local s = shared[idx[i] + 1] + if s == nil then + return nil, "corrupt: shared string index out of range" + end + out[i] = s + end + return out, p + 4 * n + elseif t == 0x1E then + if p >= limit or readu8(b, p) ~= 0x10 then + return nil, "unknown" + end + local cfs, q = cframes(b, p + 1, limit, n) + if not cfs then + return nil, q == -1 and"corrupt: bad CFrame rotation id" or"truncated CFrame values" + end + if q + 1 + n > limit or readu8(b, q) ~= 0x02 then + return nil, "truncated optional CFrame flags" + end + local out = table.create(n) + for i = 1, n do + out[i] = (readu8(b, q + i) ~= 0 and{cfs[i] }or{nil +})[1] end + return out, q + 1 + n + elseif t == 0x1F then + local out = table.create(n, "") + local hex = table.create(16, "") + for i = 0, n - 1 do + local by = table.create(16, 0) + for k = 0, 15 do + by[k + 1] = readu8(b, p + k * n + i) + end + -- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it + local carry = by[16] % 2 + for k = 9, 16 do + local v = by[k] + by[k] = math.floor(v / 2 )+ carry * 128 + carry = v % 2 + end + for k = 1, 8 do + hex[k] = string.format("%02x", by[8 + k]) + end + for k = 1, 8 do + hex[8 + k] = string.format("%02x", by[k + 4 - (k > 4 and 8 or 0)]) + end + out[i + 1] = table.concat(hex) + end + return out, p + 16 * n + elseif t == 0x20 then + local out = table.create(n) + for i = 1, n do + local fam, q = str(b, p, limit) + if not fam or q + 3 > limit then + return nil, "truncated font" + end + local weight, style = readu16(b, q), readu8(b, q + 2) + local face, q2 = str(b, q + 3, limit) + if not face then + return nil, "truncated font" + end + out[i] = { family = fam, weight = weight, style = style == 1 and"Italic" or"Normal", cachedFaceId = (face ~= "" and{face }or{nil })[1]} + p = q2 + end + return out, p + elseif t == 0x22 then + if p + 4 * n > limit then + return nil, "truncated content" + end + local kinds = i32s(b, p, n) + p =p+ 4 * n + if p + 4 > limit then + return nil, "truncated content" + end + local nu = readu32(b, p) + p =p+ 4 + local uris = table.create(math.min(nu, n)) + for j = 1, nu do + local s, q = str(b, p, limit) + if not s then + return nil, "truncated content" + end + uris[j] = s + p = q + end + if p + 4 > limit then + return nil, "truncated content" + end + local no = readu32(b, p) + local objs, q = Binary.readRefs(b, p + 4, limit, no) + if not objs or q + 4 > limit then + return nil, "truncated content" + end + if readu32(b, q) ~= 0 then + return nil, "unknown" -- external objects: kept raw + end + p = q + 4 + local out = table.create(n) + local iu, io = 1, 1 + for i = 1, n do + local k = kinds[i] + if k == 1 then + if iu > nu then + return nil, "corrupt: content uri count" + end + out[i] = uris[iu] + iu =iu+ 1 + elseif k == 2 then + if io > no then + return nil, "corrupt: content object count" + end + local r = objs[io] + out[i] = (ctx.ref and r >= 0 and{(ctx.ref(r) )}or{nil +})[1] io =io+ 1 + elseif k ~= 0 then + return nil, "unknown" + end + end + return out, p + end + return nil, "unknown" +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(v) +return (type(v) == "number" and v == v and{v }or{0 +})[1]end +-- column c of n array values (missing components 0) +local function column(vals, n, c) +local out = table.create(n, 0) + for i = 1, n do + local v = vals[i] + out[i] = (type(v) == "table" and{(num(v[c]) )}or{0 +})[1] end + return out +end + +local function putString(w, s) + w:u32le(#s) + w:string(s) +end + +local function putCFrames(w, vals, n) + for i = 1, n do + local v = vals[i] + local cf = (type(v) == "table" and{v }or{{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 } +})[1] local id = Rbx.rotationId(cf) + w:u8(id) + if id == 0 then + for k = 4, 12 do + w:f32le(num(cf[k])) + end + end + end + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 2)) + putF32s(w, column(vals, n, 3)) +end + +local function hexByte(s, i) +return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0 +end + +-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are +-- the type's none / default) +function Binary.encode(t, vals, n, w, ctx) +if t == 0x01 or t == 0x1D then + for i = 1, n do + local v = vals[i] + putString(w, (type(v) == "string" and{v }or{""})[1]) + end + elseif t == 0x02 then + for i = 1, n do + w:u8(vals[i] and 1 or 0) + end + elseif t == 0x03 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI32s(w, c) + elseif t == 0x04 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putF32s(w, c) + elseif t == 0x05 then + for i = 1, n do + w:f64le(num(vals[i])) + end + elseif t == 0x06 then + putF32s(w, column(vals, n, 1)) + putI32s(w, column(vals, n, 2)) + elseif t == 0x07 then + putF32s(w, column(vals, n, 1)) + putF32s(w, column(vals, n, 3)) + putI32s(w, column(vals, n, 2)) + putI32s(w, column(vals, n, 4)) + elseif t == 0x08 then + for i = 1, n do + local v = vals[i] + for c = 1, 6 do + w:f32le((type(v) == "table" and{(num(v[c]) )}or{0})[1]) + end + end + elseif t == 0x09 or t == 0x0A then + for i = 1, n do + w:u8(num(vals[i]) % 256) + end + elseif t == 0x0B or t == 0x12 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = floor(num(vals[i])) + end + putU32s(w, c) + elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then + local k = t == 0x0D and 2 or(t == 0x18 and 4 or 3 +) for c = 1, k do + putF32s(w, column(vals, n, c)) + end + elseif t == 0x0F or t == 0x14 then + local k = t == 0x0F and 2 or 3 + for i = 1, n do + local v = vals[i] + for c = 1, k do + local x = floor((type(v) == "table" and{(num(v[c]) )}or{0})[1]) % 65536 + w:u16le(x) + end + end + elseif t == 0x10 then + putCFrames(w, vals, n) + elseif t == 0x13 then + local refs = table.create(n, -1) + local refOf = ctx.refOf + for i = 1, n do + refs[i] = (refOf and vals[i] ~= nil and{(refOf(vals[i]) )}or{(-1 +)})[1] end + Binary.writeRefs(w, refs) + elseif t == 0x15 or t == 0x16 then + local k = t == 0x15 and 3 or 5 + for i = 1, n do + local seq = vals[i] + if type(seq) ~= "table" then + seq = {} + end + w:u32le(#seq) + for _, key in __iter(seq) do + for c = 1, k do + w:f32le((type(key) == "table" and{(num(key[c]) )}or{0})[1]) + end + end + end + elseif t == 0x17 then + for i = 1, n do + local v = vals[i] + w:f32le((type(v) == "table" and{(num(v[1]) )}or{0})[1]) + w:f32le((type(v) == "table" and{(num(v[2]) )}or{0})[1]) + end + elseif t == 0x19 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + w:u8(0) + else + local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out) + w:u8(acoustic and 3 or 1) + for c = 1, acoustic and 6 or 5 do + w:f32le(num(v[c])) + end + end + end + elseif t == 0x1A then + for c = 1, 3 do + for i = 1, n do + local v = vals[i] + w:u8(math.clamp(floor((type(v) == "table" and{(num(v[c]) )}or{0})[1]), 0, 255)) + end + end + elseif t == 0x1B or t == 0x21 then + local c = table.create(n, 0) + for i = 1, n do + c[i] = num(vals[i]) + end + putI64s(w, c) + elseif t == 0x1C then + local idx = table.create(n, 0) + local si = ctx.sharedIndex + for i = 1, n do + local v = vals[i] + idx[i] = (si and{(si((type(v) == "string" and{v }or{""})[1]) )}or{0 +})[1] end + putU32s(w, idx) + elseif t == 0x1E then + w:u8(0x10) + putCFrames(w, vals, n) + w:u8(0x02) + for i = 1, n do + w:u8(type(vals[i]) == "table" and 1 or 0) + end + elseif t == 0x1F then + local p = w:reserve(16 * n) + local b = w.buf + for i = 0, n - 1 do + local s = vals[i + 1] + if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then + return "a UniqueId is 32 hex digits" + end + -- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit + local by = table.create(16, 0) + for k = 1, 4 do + by[k] = hexByte(s, 12 + k) + by[4 + k] = hexByte(s, 8 + k) + end + local top = math.floor(hexByte(s, 1) / 128 +) for k = 1, 8 do + local v = hexByte(s, k) + local nxt = (k < 8 and{(math.floor(hexByte(s, k + 1) / 128 ))}or{top +})[1] by[8 + k] = (v * 2) % 256 + nxt + end + for k = 0, 15 do + buffer.writeu8(b, p + k * n + i, by[k + 1]) + end + end + w.pos = p + 16 * n + elseif t == 0x20 then + for i = 1, n do + local v = vals[i] + if type(v) ~= "table" then + v = Rbx.default("Font") + end + putString(w, (type(v.family) == "string" and{v.family }or{""})[1]) + w:u16le(math.clamp(floor(num(v.weight)), 0, 65535)) + w:u8(v.style == "Italic" and 1 or 0) + putString(w, (type(v.cachedFaceId) == "string" and{v.cachedFaceId }or{""})[1]) + end + elseif t == 0x22 then + local kinds, uris, objs = table.create(n, 0), {}, {} + local refOf = ctx.refOf + for i = 1, n do + local v = vals[i] + if type(v) == "string" then + kinds[i] = 1 + table.insert(uris, v) + elseif type(v) == "table" then + kinds[i] = 2 + table.insert(objs, (refOf and{(refOf(v) )}or{(-1)})[1]) + end + end + putI32s(w, kinds) + w:u32le(#uris) + for _, s in __iter(uris) do + putString(w, s) + end + w:u32le(#objs) + Binary.writeRefs(w, objs) + w:u32le(0) + else + return "unknown type id " .. t + end + return nil +end + +return Binary +end +__FILES["codecs/model/Rig"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each +-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies +-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and +-- keyframed joint TRS tracks as animation channels. New in rosetta. +-- +-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base +-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") +-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } +-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } +-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } +-- +-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Rig = {} + +local Scene = Types.Scene +local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 + +-- ------------------------------------------------------------------------------------------------ morph targets +-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL +-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as +-- many f32 x3 as the base; shorter ones are skipped (false is returned). + + + + + + + + + + +function Rig.morph(prim, frames, normals) +local pos = prim.attributes.POSITION + if not pos or pos.type ~= "f32" or pos.components ~= 3 then + return false + end + local nrm = prim.attributes.NORMAL + local n = pos.count * 3 + local targets= {} + local ok = true + for k, f in __iter(frames) do + if buffer.len(f) < n * 4 then + ok = false + break + end + local t= {} + local d = buffer.create(n * 4) + local base = pos.data + for i = 0, n - 1 do + writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) + end + t.POSITION = Scene.accessor(d, "f32", 3, pos.count) + local fn = normals and normals[k] + if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then + local dn = buffer.create(n * 4) + for i = 0, n - 1 do + writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) + end + t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) + end + targets[k] = t + end + if ok then + prim.targets = targets + end + return ok +end + +-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on +-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR +-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. +function Rig.morphAnimation(scene, node, targets, ranges, interpolation) + for _, rg in __iter(ranges) do + local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) + if last >= first then + local keys = last - first + 1 + local fps = (rg.fps and rg.fps > 0 and{rg.fps }or{10 +})[1] local times = buffer.create(keys * 4) + local weights = buffer.create(keys * targets * 4) + for k = 0, keys - 1 do + writef32(times, k * 4, k / fps) + writef32(weights, (k * targets + first - 1 + k) * 4, 1) + end + table.insert(scene.animations, { + name = rg.name, + channels = { + { + node = node, + path = "weights" , + input = Scene.accessor(times, "f32", 1, keys), + output = Scene.accessor(weights, "f32", 1, keys * targets), + interpolation = (interpolation == "STEP" and"STEP" or"LINEAR") , + }, + }, + }) + end + end +end + +-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a +-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored +-- normals cannot be used (Quake's precomputed normal table is not redistributable here). +function Rig.normals(pos, count, indices) +local out = buffer.create(count * 12) + local acc = table.create(count * 3, 0) + for k = 1, #indices - 2, 3 do + local a, b, c = indices[k], indices[k + 1], indices[k + 2] + if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in __iter({ a, b, c }) do +do local __DARKLUA_VAR=v * 3 + 1 acc[__DARKLUA_VAR]=acc[__DARKLUA_VAR]+ nx +end do local __DARKLUA_VAR0=v * 3 + 2 acc[__DARKLUA_VAR0]=acc[__DARKLUA_VAR0]+ ny +end do local __DARKLUA_VAR1=v * 3 + 3 acc[__DARKLUA_VAR1]=acc[__DARKLUA_VAR1]+ nz +end end + end + end + for v = 0, count - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ skeletons +local function trs(j) +return Mat4.compose(j.translation, j.rotation, j.scale) +end + +-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z +-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons) +function Rig.angles(x, y, z) +local sy, cy = math.sin(z / 2), math.cos(z / 2) + local sp, cp = math.sin(y / 2), math.cos(y / 2) + local sr, cr = math.sin(x / 2), math.cos(x / 2) + return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy } +end + +-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its +-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse +-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's +-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. +function Rig.skeleton(scene, joints, space, root) +local n = #joints + local world= {} + local nodes= {} + for i, j in __iter(joints) do + local p = (j.parent >= 1 and j.parent < i and{j.parent }or{0 +})[1] local m = trs(j) + local lt, lr, ls = j.translation, j.rotation, j.scale + if space == "world" then + world[i] = m + if p > 0 then + local inv = Mat4.inverse(world[p]) + if inv then + local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) + lt, lr, ls = t, r, s + end + end + else + world[i] = (p > 0 and{(Mat4.mul(world[p], m) )}or{m +})[1] end + local node= { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = (ls and{(table.clone(ls) )}or{nil })[1]} + table.insert(scene.nodes, node) + local idx = #scene.nodes + nodes[i] = idx + if p > 0 then + table.insert(scene.nodes[nodes[p] ].children, idx) + elseif root and scene.nodes[root] then + table.insert(scene.nodes[root].children, idx) + else + table.insert(scene.roots, idx) + end + end + local ibm = buffer.create(n * 64) + for i = 1, n do + local inv = Mat4.inverseFull(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = (n > 0 and{nodes[1] }or{nil })[1]}) + return nodes, #scene.skins, world +end + +-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with +-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept +-- and normalised to sum 1. +function Rig.influences(lists) +local n = #lists + local jb, wb = buffer.create(n * 8), buffer.create(n * 16) + for v, l in __iter(lists) do + local pairs_= {} + local at= {} + for k = 1, #l - 1, 2 do + if l[k + 1] > 0 then + local same = at[l[k] ] + if same then + same[2]=same[2]+ l[k + 1] -- the same joint twice: one influence + else + local e = { l[k], l[k + 1] } + at[l[k] ] = e + table.insert(pairs_, e) + end + end + end + table.sort(pairs_, function(a, b) +return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #pairs_) do + sum =sum+ pairs_[k][2] + end + for k = 1, math.min(4, #pairs_) do + writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) + writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) + end + end + return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) +end + +-- ------------------------------------------------------------------------------------------------ animations +local function floats(t, count, comps) +if #t < count * comps then + return nil + end + local b = buffer.create(count * comps * 4) + for i = 1, count * comps do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, count) +end + +-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into +-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks +-- with too few keys are skipped. Default interpolation "LINEAR". +function Rig.animation(scene, name, nodes, times, tracks, interpolation) +local count = #times + local input = floats(times, count, 1) + local channels= {} + local interp= interpolation == "STEP" and"STEP" or"LINEAR" + if input then + for j, tr in __iter(tracks) do + local node = nodes[j] + if node then + for _, path in __iter({ "translation", "rotation", "scale" }) do + local keys = (tr )[path] + local acc = keys and floats(keys, count, path == "rotation" and 4 or 3) + if acc then + table.insert(channels, { node = node, path = path , input = input, output = acc, interpolation = interp }) + end + end + end + end + end + table.insert(scene.animations, { name = name, channels = channels }) + return #scene.animations +end + +return Rig +end +__FILES["codecs/model/Sampler"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for +-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold +-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames +-- (IQM, MD5, BVH, ...). New in rosetta. +-- +-- local sample = Sampler.channel(ch) -- nil for an unreadable channel +-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights +-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique +-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } +-- +-- Never throws on bad data: unreadable channels are skipped. +local Types = __include("Types") + +local Sampler = {} + + + + +local function normalize(q) +local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a, b, s) +local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +-- channel(ch) -> sample(t) | nil +function Sampler.channel(ch) +local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = cubic and 3 or 1 + local comps +if ch.path == "weights" then + comps = math.floor((out.count * out.components) / (n * per) +) else + comps = ch.path == "rotation" and 4 or 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = (table.create(n) ) +for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + -- element e (0-based, of comps values) of the flat output + local function get(e) +local v = (table.create(comps) ) +for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(math.floor(flat / oc), flat % oc) + end + return v + end + local function value(k) +return get((cubic and(((k - 1) * 3 + 1 ))or((k - 1)))) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t) +if t <= times[1] or n == 1 then + return (rot and{(normalize(value(1)) )}or{(value(1) +)})[1] end + if t >= times[n] then + return (rot and{(normalize(value(n)) )}or{(value(n) +)})[1] end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = math.floor((lo + hi) / 2 +) if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = (dt > 0 and(((t - times[lo]) / dt ))or(0 +)) if step then + return (rot and{(normalize(value(lo)) )}or{(value(lo) +)})[1] end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = (table.create(comps) ) +for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return (rot and{(normalize(v) )}or{v +})[1] end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = (table.create(comps) ) +for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +-- times(anim) -> every key time, sorted and unique +function Sampler.times(anim) +local seen= {} + local out= {} + for _, ch in __iter(anim.channels) do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table +-- (reuse it across calls for the same animation) +function Sampler.pose(_scene, anim, t, samplers) +local cache= samplers or {} + local pose= {} + for _, ch in __iter(anim.channels) do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s= cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler +end +__FILES["codecs/model/Vrml"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, +-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding +-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a +-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated +-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. +-- +-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content +-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +local Err = __include("core/Err") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local XmlCodec = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") +local VXml = __include("codecs/model/Vrml/Xml") +local Build = __include("codecs/model/Vrml/Build") +local Write = __include("codecs/model/Vrml/Write") + +local Vrml = {} + +-- the bytes as text: gzip inflated, UTF-8 BOM dropped + + + + + + + + +local function text(data, maxBytes) +local b = (type(data) == "string" and{(buffer.fromstring(data) )}or{data +})[1] if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg) +if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) +function Vrml.parse(s) +local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +-- parseXml(text | XML document) -> the graph of an X3D XML file +function Vrml.parseXml(src) +local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "</X3D>", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n</X3D>\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED +function Vrml.graph(data, opts) +local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve +function Vrml.fetcher(opts) +return function(uri) +if not opts then + return nil + end + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + return (type(v) == "string" and{(buffer.fromstring(v) )}or{(type(v) == "buffer" and{v }or{nil +})[1]})[1] end +end + +-- build(graph, opts?) -> Scene +function Vrml.build(graph, opts) +local o= table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data) +local g, err = Vrml.graph(data, opts) + return g, (err and{err.message }or{nil +})[1] end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +-- decode(bytes, opts?) -> Scene: graph + build +function Vrml.decode(data, opts) +local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files +function Vrml.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml +end +__FILES["codecs/model/Vrml/Build"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. +-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, +-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through +-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when +-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial +-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture +-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: +-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / +-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a +-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in +-- meta.source.skipped. Never throws: bad data returns nil, message. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Fields = __include("codecs/model/Vrml/Fields") +local Geometry = __include("codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + + + + + + + + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +-- nodes with nothing to show (not counted as skipped) +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r) +return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a, b) +return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q, v) +local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v) +return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q) +return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +-- the rotation taking unit vector a onto b +local function between(a, b) +local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + -- opposite: half a turn about any perpendicular axis + return math.abs(a[1]) < 0.9 and{ 0, a[3], -a[2], 0 } or{ -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + + + + + + + + + + + + + + +local function addNode(ctx, n, parent) +local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +-- ------------------------------------------------------------------------------------------------ materials +local function texture(ctx, t) +if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex= { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in __iter(urls) do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = (ext and{MIME[string.lower(ext)] }or{nil +})[1] elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px =math.floor(px/ 256 +) end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], (c == 2 and{b[2] }or{255 +})[1] else + r, g, bl, a = b[1], b[2], b[3], (c == 4 and{b[4] }or{255 +})[1] end + -- the image's first row is the bottom one + local row = h - 1 - math.floor(i / w +) local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = rs and"repeat" or"clamp", wrapT = rt and"repeat" or"clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx, t, xf) +local i = texture(ctx, t) + if not i then + return nil + end + local ref= { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx, app, solid) +if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache )[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x= {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots= { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in __iter(slots) do + local t = node(mat, field) + if t then + (m )[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache )[solid] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ nodes +local walk + +local function shape(ctx, n, parent) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false +return + end + local count = (prim.indices and{prim.indices.count }or{prim.attributes.POSITION.count +})[1] if count == 0 then + -- nothing to draw (no valid faces / points) + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx, n, parent) + local cam +if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd= { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx, n, parent) + local t = n.type + local l= { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd= { name = n.def, children = {} } + local x= { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l ).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx, n, parent) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in __iter(CHILDREN) do + for _, c in __iter(nodes(n, f)) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx, n, parent) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer= { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = (isIdentityQ(qs) and{qr }or{(qmul(qr, qs) +)})[1] if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner= { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx, n, parent) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in __iter(strs(n, "url")) do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline =ctx.inline+ 1 + for _, root in __iter(g.roots) do + walk(ctx, root, holder) + end + ctx.inline =ctx.inline- 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx, n, parent) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth =ctx.depth+ 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in __iter(nodes(n, "shape")) do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source +src.title = str(n, "title") + local info = strs(n, "info") + src.info = (#info > 0 and{info }or{nil +})[1] elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth =ctx.depth- 1 +end + +-- ------------------------------------------------------------------------------------------------ animation +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx, routes) + -- interpolator -> its TimeSensor + local timer= {} + for _, r in __iter(routes) do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims= {} + local order= {} + for _, r in __iter(routes) do +local __DARKLUA_CONTINUE_11=false repeat local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then +__DARKLUA_CONTINUE_11=true break + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then +__DARKLUA_CONTINUE_11=true break + end + local key, kv= nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = path == "rotation" and 4 or 3 + local n = math.min(#key, math.floor(#kv / comps)) + if n == 0 then +__DARKLUA_CONTINUE_11=true break + end + local ts = timer[it] + local cycle = (ts and{(num(ts, "cycleInterval", 1) )}or{1 +})[1] local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = (ts and{ts.def }or{nil})[1], channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in __iter(inst) do + local out = S.accessor(nil, "f32", path == "rotation" and 4 or 3, n) + local prev= nil + for i = 0, n - 1 do + local v +if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path , input = input, output = out, interpolation = "LINEAR" }) + end +__DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end + for _, id in __iter(order) do + table.insert(ctx.scene.animations, anims[id]) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(graph, opts) +local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = (units.length and units.length.factor > 0 and{units.length.factor }or{1 +})[1] local h = graph.header or {} + local skipped= {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx= { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in __iter(graph.roots) do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build +end +__FILES["codecs/model/Vrml/Fields"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding +-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here +-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans +-- true / false). Never throws. +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted +local function mfString(s) +local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return p and{ ((string.match(s, "^%s*(.-)%s*$") )) } or{} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent +function Fields.nums(node, name) +local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in __iter(gmatch(v, "[^%s,]+")) do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in __iter(v) do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in __iter(v) do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, x and 1 or 0) + end + end + return out +end + +function Fields.num(node, name, default) +local v = Fields.nums(node, name) + return (v and type(v[1]) == "number" and{v[1] }or{default +})[1]end + +-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) +function Fields.vec(node, name, default) +local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out= {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node, name, default) +local v = node.fields[name] + if type(v) == "string" then + local w = string.lower((string.match(v, "^%s*(%S*)") )) + return w == "true" and true or(w == "false" and{false }or{default +})[1] end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node, name) +local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in __iter(v) do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node, name, default) +local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +-- nodes(node, name) -> the nodes of an SFNode / MFNode field +function Fields.nodes(node, name) +local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in __iter(v) do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node, name) +return Fields.nodes(node, name)[1] +end + +return Fields +end +__FILES["codecs/model/Vrml/Geometry"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no +-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face +-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets +-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, +-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, +-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, +-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to +-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +local Types = __include("Types") +local Fields = __include("codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + + + +local function f32(list, comps, count) +local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + end + return a +end + +local function u32(list) +local a = S.accessor(nil, "u32", 1, #list) + for i, v in __iter(list) do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end + +-- the colour node's values and component count (Color: 3, ColorRGBA: 4) +local function colors(n) +local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = c.type == "ColorRGBA" and 4 or 3 + return nums(c, "color") or {}, comps +end + +local function points(n, field, sub) +local c = node(n, field) + return (c and{nums(c, sub) or {} }or{nil +})[1]end +-- ------------------------------------------------------------------------------------------------ polygon meshes +-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: +-- the coordinate index) or per-face indices. + + + + + + + + + + + +local function polyMesh(m, o, maxV) +local P, corners, sizes = m.P, m.corners, m.sizes + local np = math.floor(#P / 3 +) local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + -- the attribute index of corner k (1-based) in face f (1-based) + local function idx(list, perFace, f, k, c) +if perFace then + return (list and #list > 0 and{(list[f] or 0) }or{(f - 1 +)})[1] end + return (list and #list > 0 and{(list[k] or c) }or{c +})[1] end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey= {} + local vsrc= {} -- per output vertex: coord, normal, colour, texcoord indices + local out= {} + local outSizes= {} + local k = 0 + for f, size in __iter(sizes) do + local face= {} + local valid = size >= 3 + for q = 1, size do + k =k+ 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts= {} + for q, kk in __iter(face) do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = (N and{(idx(m.nIdx, m.nFace, f, kk, c) )}or{(-1 +)})[1] local ci = (C and{(idx(m.cIdx, m.cFace, f, kk, c) )}or{(-1 +)})[1] local ti = (T and{(idx(m.tIdx, false, f, kk, c) )}or{(-1 +)})[1] local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, math.floor((size + 1) / 2 )do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in __iter(verts) do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = (simple and{np }or{(#vsrc +)})[1] if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = (N and{(S.accessor(nil, "f32", 3, nv) )}or{nil +})[1] local col = (C and{(S.accessor(nil, "f32", cc, nv) )}or{nil +})[1] local tex = (T and{(S.accessor(nil, "f32", 2, nv) )}or{nil +})[1] local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = (simple and{nil }or{vsrc[v + 1] +})[1] local c = (s and{s[1] }or{v +})[1] for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = (s and{s[2] }or{v +})[1] for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = (s and{s[3] }or{v +})[1] for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = (s and{s[4] }or{v +})[1] local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, (flipV and((1 - tt ))or(tt))) + end + end + local attrs= { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim= { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +-- split a -1 separated index list into corners + sizes +local function split(list) +local corners, sizes = {}, {} + local run = 0 + for _, x in __iter(list) do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run =run+ 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list) +if not list or #list == 0 then + return nil + end + local out = {} + for _, x in __iter(list) do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n, o, maxV) +local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m= { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = (nPer and{(cornerList(nums(n, "normalIndex")) )}or{(nums(n, "normalIndex"))})[1], + C = C, cComps = cc, cFace = not cPer, cIdx = (cPer and{(cornerList(nums(n, "colorIndex")) )}or{(nums(n, "colorIndex"))})[1], + T = (tc and tc.type ~= "TextureCoordinateGenerator" and{(nums((tc.type == "MultiTextureCoordinate" and{(node(tc, "texCoord") or tc) }or{tc})[1], "point") or {}) }or{nil})[1], + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts +local function triSet(n, o, maxV) +local t = n.type + local P = points(n, "coord", "point") or {} + local np = math.floor(#P / 3 +) local index = nums(n, "index") + local seq +if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a, b, c) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs() +local out = {} + local counts = nums(n, string.find(t, "Fan", 1, true) and"fanCount" or"stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in __iter(seq) do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in __iter(counts) do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at =at+ c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in __iter(runs()) do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in __iter(runs()) do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m= { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = (tc and tc.type == "TextureCoordinate" and{nums(tc, "point") or {} }or{nil})[1], + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n, o, maxV) +local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h= nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P, T, corners, sizes= {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in __iter({ a, a + nx, a + nx + 1, a + 1 }) do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m= { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = (tc and{nums(tc, "point") or {} }or{T})[1], + } + return polyMesh(m, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ Extrusion +local function cross(a, b) +return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function sub3(a, b) +return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a) +local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return l > 1e-12 and{ a[1] / l, a[2] / l, a[3] / l } or{ 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v, k, a) +local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n, o, maxV) +local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = math.floor(#sp / 3), math.floor(#cs / 2 +) if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a, b) +return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys, Zs= {}, {} + for i = 1, ns do + local prev = (i > 1 and{spine[i - 1] }or{(closedSpine and{spine[ns - 1] }or{nil +})[1]})[1] local nxt = (i < ns and{spine[i + 1] }or{(closedSpine and{spine[2] }or{nil +})[1]})[1] local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = (l > 1e-12 and{z }or{nil +})[1] end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = (l > 1e-12 and{(rotate({ 0, 0, 1 }, axis, ang) )}or{y[2] < 0 and{ 0, 0, -1 } or{ 0, 0, 1 } +})[1] end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = (closedSpine and((ns - 1 ))or(ns +)) local nring = (closedCs and((nc - 1 ))or(nc +)) local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = (#sc >= i * 2 and{i }or{1 +})[1] local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = (#ori >= i * 4 and{i }or{1 +})[1] local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i, j) +return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in __iter({ at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) }) do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ lines, points +local function lines(n, maxV) +local P = points(n, "coord", "point") or {} + local np = math.floor(#P / 3 +) local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs= {} + if n.type == "LineSet" then + local at = 0 + for _, c in __iter(nums(n, "vertexCount") or {}) do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at =at+ c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in __iter(sizes) do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k =k+ s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = (perVertex and{(cornerList(cIdx) )}or{nil +})[1] local vkey= {} + local src= {} + local out= {} + local k = 0 + for li, r in __iter(runs) do + local prev= nil + for _, c in __iter(r) do +local __DARKLUA_CONTINUE_48=false repeat k =k+ 1 + if c == nil or c < 0 or c >= np then + prev = nil +__DARKLUA_CONTINUE_48=true break + end + local ci = not C and-1 or(perVertex and{((cList and{cList[k] or c }or{c})[1]) }or{(cIdx[li] or li - 1) +})[1] local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v +__DARKLUA_CONTINUE_48=true until true if not __DARKLUA_CONTINUE_48 then break end end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = (C and{(S.accessor(nil, "f32", cc, #src) )}or{nil +})[1] for v, s in __iter(src) do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } , indices = u32(out), mode = "lines" } +end + +local function pointSet(n, maxV) +local P = points(n, "coord", "point") or {} + local np = math.floor(#P / 3 +) if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs= { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +-- ------------------------------------------------------------------------------------------------ primitives +-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) +local function direct(P, N, T, I, o) +local nv = math.floor(#P / 3 +) if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n, o) +local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in __iter(FACES) do + local nn, u, v = face[1], face[2], face[3] + for _, c in __iter({ { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }) do + for q = 1, 3 do + local h = (q == 1 and{hx }or{(q == 2 and{hy }or{hz +})[1]})[1] table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in __iter({ 0, 1, 2, 0, 2, 3 }) do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) +-- and runs counter-clockwise seen from +y +local function ring(P, N, T, segs, y, r, t, ny, nr) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +-- a cap disc at height y facing ny (+1 / -1) +local function cap(P, N, T, I, segs, y, r, ny) + local b = math.floor(#P / 3 +) for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, ((ny > 0 and{(-z )}or{z})[1]) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) +local function band(I, a, b, segs) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n, o, segs) +local r = num(n, "radius", 1) + local rings = math.max(2, math.floor(segs / 2)) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n, o, segs, cone) +local r = num(n, cone and"bottomRadius" or"radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = (cone and l > 0 and((r / l ))or(0)), (cone and l > 0 and((h / l ))or(1 +)) ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, cone and 0 or r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +-- ------------------------------------------------------------------------------------------------ dispatch +-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); +-- the second value of a success is the node's solid flag +function Geometry.primitive(n, o) +local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim, err= nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry +end +__FILES["codecs/model/Vrml/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into +-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are +-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, +-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO +-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside +-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, +-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are +-- returned as nil, message ("line N: ..."). +local Parse = {} +-- an IS reference in a PROTO body: fields[name] = { is = "protoField" } + + + + + + + + + + + + + + + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) +local function copy(node, values, defaults, memo) +local done = memo[node] + if done then + return done + end + local out= { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in __iter(node.fields) do + if type(v) == "table" and type((v ).is) == "string" then + local name = (v ).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in __iter(v) do + arr[i] = (type(x) == "table" and x.type and{(copy(x, values, defaults, memo) )}or{x +})[1] end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO +function Parse.expand(proto, values, def, routes) +if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first= nil + for _, n in __iter(proto.body) do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in __iter(proto.routes) do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first +if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out= { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text) +local n = #text + local p = 1 + local graph= { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs= {} + local protos= graph.protos + local routes= graph.routes + local failure= nil + local depth = 0 + + local function line(at) +local l = 1 + for _ in __iter(gmatch(sub(text, 1, at), "\n")) do + l =l+ 1 + end + return l + end + local function fail(msg) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + -- the lexer: skip blanks, commas and comments; returns the next token kind and value + -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = (e and{e }or{(n + 1 +)})[1] else + return + end + end + end + local function token() +skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p =p+ 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e ) + 1 + return "num", num + end + if c == 46 then + p =p+ 1 + return ".", nil + end + -- +inf / -nan style words: read the word + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we ) + 1 + local wl = string.lower(w) + local val = (find(wl, "inf", 1, true) and{((c == 45 and{(-math.huge )}or{math.huge})[1]) }or{find(wl, "nan", 1, true) and 0 or nil +})[1] if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e ) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek() +local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode +local parseProto +local parseRoute + -- a field value (after its name): an array of numbers / strings / booleans / nodes + +local function value() +local k, val = token() + if k == "[" then + local out = {} + -- fast path: a bracket of plain numbers (big coordinate arrays) + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in __iter(gmatch(seg, "[^%s,]+")) do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do +local __DARKLUA_CONTINUE_9=false repeat k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then +__DARKLUA_CONTINUE_9=true break + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end +__DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return node and{ node } or{} + end + fail("missing field value") + return {} + end + + -- the fields of a node body, up to its "}" + local function body(node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: <access> <type> <name> [<value> | IS <name>] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first) +if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def= nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth =depth+ 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node= { type = typ, def = def, fields = {} } + body(node) + depth =depth- 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node ).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path() +local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a ], defs[b ] + if from and dst then + table.insert(routes, { from = from, fromField = af , to = dst, toField = bf }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto= { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() -- the url list + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + -- statements + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse +end +__FILES["codecs/model/Vrml/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, +-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; +-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, +-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> +-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material +-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of +-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or +-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> +-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and +-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). +-- Never throws: returns nil, message. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Xml = __include("codecs/text/Xml") + +local Write = {} +-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers +-- per line), "bool", "str", "mstr" (MFString), "node", "nodes" + + + + + +local format, concat = string.format, table.concat + +local function fmt(v) +if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t, def) +return { type = t, def = def, fields = {} } +end +local function F(n, name, kind, value, per) + table.insert(n.fields, { name, kind, value, per }) +end + +-- names: valid, unique DEF names +local function namer() +local used= {} + return function(name, fallback) +local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. ((s ~= "" and(("_" .. s ))or(""))) + end + local base, k = s, 1 + while used[s] do + k =k+ 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +-- axis-angle of a quaternion (x, y, z, w) +local function axisAngle(q) +local x, y, z, w = q[1], q[2], q[3], q[4] + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function values(acc) +return (Flatten.numbers(acc)) +end + +local function faceSet(prim, doubleSided, o, x3d) +local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n) +return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in __iter(m.sizes) do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p =p+ s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, (o.flipV ~= false and((1 - tt ))or(tt))) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(rgba and"ColorRGBA" or"Color") + local vals = {} + local scale = (col.raw and{(col.type == "unorm8" and 255 or(col.type == "unorm16" and 65535 or 1)) }or{1 +})[1] for i = 0, m.count - 1 do + for k = 1, rgba and 4 or 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, rgba and 4 or 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) +local function coordNode(prim) +local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim, nv, x3d) +local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, rgba and 4 or 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(rgba and"ColorRGBA" or"Color") + F(cn, "color", "mf", vals, rgba and 4 or 3) + return cn +end + +local function lineSet(prim, x3d) +local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind +if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in __iter(ind) do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in __iter(idx) do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim, x3d) +local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene, i, o, written) +if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = (url and not string.find(url, "^data:") and not string.find(url, "[/\\]") and{url }or{(format("%s_%d.%s", base, i, ext) +)})[1] o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene, mi, o, written) +local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (math.floor(p / 256 )% 256) * 65536 + (math.floor(p / 65536 )% 256) * 256 + math.floor(p / 16777216 +) end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +-- ------------------------------------------------------------------------------------------------ the tree +function Write.graph(scene, o) +local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef= {} + local meshShapes= {} + local appDef= {} + local written= {} + local failure= nil + + local function shapes(mi) +local done = meshShapes[mi] + if done then + -- USE the shapes written before + local out = {} + for _, s in __iter(done) do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in __iter(((mesh and{mesh.primitives }or{{}})[1])) do + local mode = prim.mode or "triangles" + local mat = (type(prim.material) == "number" and{scene.materials[prim.material] }or{nil +})[1] local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. ((#mesh.primitives > 1 and(("_" .. pi ))or(""))), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting= {} + local function transform(ni) +local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids= {} + if type(n.mesh) == "number" then + for _, s in __iter(shapes(n.mesh)) do + table.insert(kids, s) + end + end + local cam = (type(n.camera) == "number" and{scene.cameras[n.camera] }or{nil +})[1] if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = (type(n.light) == "number" and{scene.lights[n.light] }or{nil +})[1] if l then + local typ = l.type == "directional" and"DirectionalLight" or(l.type == "spot" and"SpotLight" or"PointLight" +) local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in __iter(n.children or {}) do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots= {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + -- no roots: every node without a parent + local child = {} + for _, n in __iter(scene.nodes) do + for _, c in __iter(n.children or {}) do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in __iter(list) do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in __iter(shapes(mi)) do + table.insert(roots, s) + end + end + end + + -- animations: a TimeSensor per animation, an interpolator per channel + local routes= {} + for ai, anim in __iter(scene.animations or {}) do + local tmax = 0 + local chans = {} + for _, ch in __iter(anim.channels or {}) do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = (tmax > 0 and{tmax }or{1 +})[1] local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in __iter(chans) do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(rot and"OrientationInterpolator" or"PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in __iter(input) do + keys[i] = tv / cycle + end + local comps = rot and 4 or 3 + local stride = math.floor(#output / #input +) -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = (ch.interpolation == "CUBICSPLINE" and stride == comps * 3 and{comps }or{0 +})[1] local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in __iter(v) do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def , "fraction_changed", it.def , "set_fraction" }) + table.insert(routes, { it.def , "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +-- ------------------------------------------------------------------------------------------------ serializers +local function numbers(vals, per, indent) +local out = table.create(#vals) + for i, v in __iter(vals) do + out[i] = fmt(v) + end + if per == 0 then + -- index lists: one face per line + local lines, cur = {}, {} + for i, v in __iter(vals) do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s) +return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots, routes, x3d) +local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by rosetta\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by rosetta\n") + end + local function emit(n, ind) +if n.use then + return "USE " .. n.use + end + local parts = { ((n.def and(("DEF " .. n.def .. " " ))or(""))) .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in __iter(n.fields) do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = v and"TRUE" or"FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in __iter(v) do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in __iter(v) do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in __iter(roots) do + table.insert(out, emit(r, "")) + end + for _, r in __iter(routes) do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +-- the containerField a child element needs when it is not its type's default +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots, routes) +local function element(n, field) +local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs ) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in __iter(n.fields) do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, v and"true" or"false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in __iter(v) do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in __iter(v) do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs , kids) + end + local sceneKids = {} + for _, r in __iter(roots) do + table.insert(sceneKids, element(r, "children")) + end + for _, r in __iter(routes) do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a )) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "rosetta") + local root = Xml.element("X3D", ra , { Xml.element("head", nil, { Xml.element("meta", meta ) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, (err and{err.message }or{"xml" +})[1] end + return s, nil +end + +-- text(scene, opts) -> the file text +function Write.text(scene, o) +local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write +end +__FILES["codecs/model/Vrml/Xml"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one +-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; +-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their +-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; +-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and +-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / +-- meta, UNIT, component and the profile go into the graph header. Never throws. +local Xml = __include("codecs/text/Xml") +local Parse = __include("codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER= { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in __iter(GEOMETRY) do + CONTAINER[g] = "geometry" +end + +local function container(el, typ) +local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc) +local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no <X3D> root element" + end + local graph= { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs= {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure= nil + + local convert +local function route(el) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare + -- the child elements of a node into its fields + +local function children(el, node) + for _, ch in __iter(el.children) do +local __DARKLUA_CONTINUE_2=false repeat if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then +__DARKLUA_CONTINUE_2=true break + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in __iter(Xml.children(ch, "connect")) do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then +__DARKLUA_CONTINUE_2=true break -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, name == "ProtoInstance" and"" or name) + local list = node.fields[f] + if type(list) ~= "table" or (list ).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + end + + -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes + local function fieldValue(el) +if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in __iter(el.children) do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el, extern) + local name = el.attrs.name + if not name then + return + end + local proto= { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = (extern and{el }or{(Xml.child(el, "ProtoInterface") +)})[1] if iface then + for _, f in __iter(Xml.children(iface, "field")) do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in __iter(bodyEl.children) do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el) +local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth =depth+ 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth =depth- 1 + return nil + end + local typ = Xml.localName(el.name) + local node +if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in __iter(Xml.children(el, "fieldValue")) do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in __iter(a) do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth =depth- 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in __iter(root.children) do +local __DARKLUA_CONTINUE_9=false repeat if type(ch) ~= "table" then +__DARKLUA_CONTINUE_9=true break + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in __iter(ch.children) do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene= { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in __iter(scene.fields) do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in __iter(v) do + table.insert(graph.roots, x) + end + end + end + end +__DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml +end +__FILES["codecs/text/Json"] = function() +local __compat = __compat local buffer, typeof, type = __compat.buffer, __compat.typeof, __compat.type --!strict +-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers +-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so +-- they write back as {}; opts.ordered makes every object a Types.object with its key order. +-- +-- local Json = require("rosetta.codecs.text.Json") +-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input +-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err +-- for ev, x in Json.events(text) do ... end -- pull events without building the tree +-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values +-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring() +-- +-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer; +-- writer() builds output incrementally and flush() hands back the text so far. Never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Decode = __include("codecs/text/Json/Decode") +local Encode = __include("codecs/text/Json/Encode") + +local Json = {} + + + + +Json.null = Types.null +Json.object = Types.object +Json.keys = Types.keys +Json.set = Types.set + +local function text(src) +if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function fail(msg, at, n) +local m = tostring(msg) + local code = ((string.find(m, "truncated", 1, true) or string.find(m, "unterminated", 1, true) or (at or 0) >= n +)and{Err.TRUNCATED +}or{(string.find(m, "nested deeper", 1, true) and{Err.LIMIT +}or{Err.CORRUPT +})[1]})[1] return Err.new(code, m, at) +end + +-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is +-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil. +function Json.decode(src, opts) +local s, terr = text(src) + if not s then + return nil, terr + end + local i = string.sub(s, 1, 3) == "\239\187\191" and 4 or 1 + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + local e = (string.match(s, "^[ \t\n\r]*()", ni) ) +if e <= #s then + return nil, Err.new(Err.CORRUPT, "trailing data after the value", e - 1) + end + return v, nil +end + +-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading +-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left. +function Json.decodeAt(src, pos, opts) +local s, terr = text(src) + if not s then + return nil, terr + end + local i = (string.match(s, "^[ \t\n\r]*()", pos or 1) ) +if i > #s then + return nil, nil + end + local v, ni, at = Decode.value(s, i, opts) + if v == nil then + return nil, fail(ni, at, #s) + end + return v, ni +end + +-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A +-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end +function Json.lines(src, opts) +local s, terr = text(src) + local pos = 1 + local index = 0 + local dead = false + return function() +if dead then + return nil + end + index =index+ 1 + if not s then + dead = true + return index, nil, terr + end + local v, ni = Json.decodeAt(s, pos, opts) + if v == nil then + dead = true + if ni == nil then + return nil + end + return index, nil, ni + end + pos = ni + return index, v, nil + end +end + +-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key), +-- "value" (a scalar), and on bad input one final "error", Err. +function Json.events(src, opts) +local s, terr = text(src) + if not s then + local done = false + return function() +if done then + return nil, nil + end + done = true + return "error", terr + end + end + local str= s + local i = string.sub(str, 1, 3) == "\239\187\191" and 4 or 1 + local nextEv = Decode.events(str, i, opts) + return function() +local ev, v, at = nextEv() + if ev == "error" then + return ev, fail(v, at, #str) + end + return ev, v + end +end + +-- encode(value, opts?) -> string | nil, Err +function Json.encode(value, opts) +local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return s, nil +end + +Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes +Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf) +-- ------------------------------------------------------------------------------------------------ writer +-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any +-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key +-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing. + + + + + + + + + + + + + +function Json.writer(opts) +local st = Encode.state(opts) + local ind = st.indent + local kinds= {} -- true = object + local counts= {} + local depth = 0 + local keyDone = false -- an object's key written, its value due + local flushed= {} + local w= { err = nil } + local function bad(msg) + if not w.err then + w.err = Err.new(Err.ARG, msg) + end + end + -- before an element: a comma / newline as needed; false when the position is wrong + local function slot(isKey) +if w.err then + return false + end + if depth == 0 then + if counts[0] and counts[0] > 0 then + bad("one top-level value only") + return false + end + counts[0] = 1 + return true + end + local obj = kinds[depth] + if obj and not isKey then + if not keyDone then + bad("an object member needs a key first") + return false + end + keyDone = false + return true + end + if isKey and not obj then + bad("key outside an object") + return false + end + if isKey and keyDone then + bad("two keys in a row") + return false + end + if counts[depth] > 0 then + table.insert(st.out, ",") + end + counts[depth]=counts[depth]+ 1 + if ind then + table.insert(st.out, "\n" .. string.rep(ind, depth)) + end + return true + end + local function open(obj) + if slot(false) then + table.insert(st.out, obj and"{" or"[") + depth =depth+ 1 + kinds[depth], counts[depth] = obj, 0 + end + return w + end + local function close(obj) + if w.err then + return w + end + if depth == 0 or kinds[depth] ~= obj or (obj and keyDone) then + bad(obj and"unbalanced endObject" or"unbalanced endArray") + return w + end + if ind and counts[depth] > 0 then + table.insert(st.out, "\n" .. string.rep(ind, depth - 1)) + end + table.insert(st.out, obj and"}" or"]") + depth =depth- 1 + return w + end + function w.beginObject(_self) +return open(true) + end + function w.beginArray(_self) +return open(false) + end + function w.endObject(_self) +return close(true) + end + function w.endArray(_self) +return close(false) + end + function w.key(_self, k) +if type(k) ~= "string" then + bad("key must be a string") + elseif slot(true) then + table.insert(st.out, Encode.quote(k, st.ascii, st.slash) .. (ind and": " or":")) + keyDone = true + end + return w + end + function w.value(_self, v) +if slot(false) then + st.n = #st.out + if not Encode.write(st, v, depth) then + bad(st.err or "cannot encode") + end + end + return w + end + function w.flush(_self) +local s = table.concat(st.out) + table.clear(st.out) + st.n = 0 + table.insert(flushed, s) + return s + end + function w.tostring(_self) +if w.err then + return nil, w.err + end + if depth ~= 0 then + return nil, Err.new(Err.ARG, "unclosed object / array") + end + return table.concat(flushed) .. table.concat(st.out), nil + end + return w +end + +return Json +end +__FILES["codecs/text/Json/Decode"] = function() +--!strict +--!native +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting +-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single +-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the +-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char +local tonumber = tonumber +local concat = table.concat + + + + + + + + +local ESC= { + [34] = '"', + [92] = "\\", + [47] = "/", + [98] = "\b", + [102] = "\f", + [110] = "\n", + [114] = "\r", + [116] = "\t", +} + +-- utf8 bytes of a code point (surrogates too: WTF-8) +local utf8char = Text.utf8char +Decode.utf8char = utf8char + +local function hex4(s, i) +local h = match(s, "^%x%x%x%x", i) + if not h then + return nil + end + return tonumber(h, 16) +end + +-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote. +local function str(s, i) +local j = find(s, '[%z\1-\31"\\]', i + 1) + if not j then + return nil, "unterminated string", #s + end + local c = byte(s, j) + if c == 34 then + return sub(s, i + 1, j - 1), j + 1 + end + local parts = {} + local np = 0 + local start = i + 1 + while true do + if c == 34 then + np =np+ 1 + parts[np] = sub(s, start, j - 1) + return concat(parts), j + 1 + elseif c ~= 92 then + return nil, "control character in string", j - 1 + end + np =np+ 1 + parts[np] = sub(s, start, j - 1) + local e = byte(s, j + 1) + if e == nil then + return nil, "unterminated string", #s + end + local simple = ESC[e] + if simple then + np =np+ 1 + parts[np] = simple + start = j + 2 + elseif e == 117 then -- \u + local cp = hex4(s, j + 2) + if not cp then + return nil, "bad \\u escape", j - 1 + end + start = j + 6 + if cp >= 0xD800 and cp <= 0xDBFF and byte(s, start) == 92 and byte(s, start + 1) == 117 then + local lo = hex4(s, start + 2) + if lo and lo >= 0xDC00 and lo <= 0xDFFF then + cp = 0x10000 + (cp - 0xD800) * 1024 + (lo - 0xDC00) + start =start+ 6 + end + end + np =np+ 1 + parts[np] = utf8char(cp) + else + return nil, "bad escape", j - 1 + end + j = find(s, '[%z\1-\31"\\]', start) + if not j then + return nil, "unterminated string", #s + end + c = byte(s, j) + end +end +Decode.string = str + +-- number(s, i) -> value, next | nil, message, offset +local function num(s, i, bigStrings) +local p = i + if byte(s, p) == 45 then + p =p+ 1 + end + local c = byte(s, p) + if c == 48 then + p =p+ 1 + elseif c and c >= 49 and c <= 57 then + p = (match(s, "^%d*()", p + 1) ) +else + return nil, c == nil and"truncated: expected a value" or(p == i and"unexpected character" or"bad number"), p - 1 + end + local int = true + if byte(s, p) == 46 then + local q = match(s, "^%d+()", p + 1) + if not q then + return nil, "bad fraction", p + end + p = q +int = false + end + c = byte(s, p) + if c == 101 or c == 69 then + p =p+ 1 + c = byte(s, p) + if c == 43 or c == 45 then + p =p+ 1 + end + local q = match(s, "^%d+()", p) + if not q then + return nil, "bad exponent", p - 1 + end + p = q +int = false + end + local text = sub(s, i, p - 1) + local n = (tonumber(text) ) +if n == nil then -- LuaJIT: absurd exponents (1e0066999...) -> nil; they overflow / underflow + local m, es = match(text, "^([^eE]*)[eE]([%+%-]?)") + local mv = tonumber(m) or 0 + n = (mv == 0 and{mv }or{(es == "-" and((mv * 0 ))or((mv * math.huge +)))})[1] end + if int and bigStrings and p - i > 15 and (n >= 9007199254740992 or n <= -9007199254740992) then + return text, p + end + return n, p +end +Decode.number = num + +-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace +-- skipped); next is the position after the value (trailing whitespace not skipped). +function Decode.value(s, i, opts) +local o= opts or {} + local ordered = o.ordered == true + local bigStrings = o.bigInts == "string" + local nullv = (o.null ~= nil and{o.null }or{Types.null +})[1] local maxDepth = o.maxDepth or 1000 + local object = Types.object + + local stackT= {} -- containers + local stackK= {} -- object: the pending key; array: the count + local stackO= {} -- object: its key order (or true); array: false + local depth = 0 + local n = #s + local value + +while true do + i = (match(s, "^[ \t\n\r]*()", i) ) +local c = byte(s, i) + local haveValue = true + if c == 123 then -- { + depth =depth+ 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = (match(s, "^[ \t\n\r]*()", i + 1) ) +local t = {} + c = byte(s, i) + if c == 125 then + i =i+ 1 + depth =depth- 1 + value = object(t, {}) + elseif c == 34 then + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = (match(s, "^[ \t\n\r]*()", ni) ) +if byte(s, i) ~= 58 then + return nil, i > n and"truncated object" or"expected ':'", i - 1 + end + i =i+ 1 + stackT[depth], stackK[depth] = t, k + stackO[depth] = ordered and{} or true + haveValue = false + else + return nil, c == nil and"truncated object" or"expected a key", i - 1 + end + elseif c == 91 then -- [ + depth =depth+ 1 + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth, i - 1 + end + i = (match(s, "^[ \t\n\r]*()", i + 1) ) +if byte(s, i) == 93 then + i =i+ 1 + depth =depth- 1 + value = {} + else + stackT[depth], stackK[depth], stackO[depth] = {}, 0, false + haveValue = false + end + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return nil, ni, at + end + value, i = v, ni + elseif c == 116 then + if sub(s, i, i + 3) ~= "true" then + return nil, "bad literal", i - 1 + end + value, i = true, i + 4 + elseif c == 102 then + if sub(s, i, i + 4) ~= "false" then + return nil, "bad literal", i - 1 + end + value, i = false, i + 5 + elseif c == 110 then + if sub(s, i, i + 3) ~= "null" then + return nil, "bad literal", i - 1 + end + value, i = nullv, i + 4 + elseif c == nil then + return nil, "truncated: expected a value", n + else + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return nil, ni, at + end + value, i = v, ni + end + -- attach the value to the open containers, closing them as their ends come + while haveValue do + if depth == 0 then + return value, i + end + local t = stackT[depth] + local ord = stackO[depth] + if ord then + local k = stackK[depth] + if ord ~= true and t[k] == nil then + table.insert(ord, k) + end + t[k] = value + else + local cnt = stackK[depth] + 1 + t[cnt] = value + stackK[depth] = cnt + end + i = (match(s, "^[ \t\n\r]*()", i) ) +c = byte(s, i) + if c == 44 then -- , + i = (match(s, "^[ \t\n\r]*()", i + 1) ) +if ord then + if byte(s, i) ~= 34 then + return nil, i > n and"truncated object" or"expected a key", i - 1 + end + local k, ni, at = str(s, i) + if k == nil then + return nil, ni, at + end + i = (match(s, "^[ \t\n\r]*()", ni) ) +if byte(s, i) ~= 58 then + return nil, i > n and"truncated object" or"expected ':'", i - 1 + end + i =i+ 1 + stackK[depth] = k + end + haveValue = false + elseif ord and c == 125 then + i =i+ 1 + value = (ord ~= true and{(object(t, ord) )}or{(next(t) == nil and{(object(t, {}) )}or{t +})[1]})[1] stackT[depth] = nil + depth =depth- 1 + elseif not ord and c == 93 then + i =i+ 1 + value = t + stackT[depth] = nil + depth =depth- 1 + elseif c == nil then + return nil, ord and"truncated object" or"truncated array", n + else + return nil, ord and"expected ',' or '}'" or"expected ',' or ']'", i - 1 + end + end + end +end + +-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object", +-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes. +function Decode.events(s, i, opts) +local o= opts or {} + local bigStrings = o.bigInts == "string" + local nullv = (o.null ~= nil and{o.null }or{Types.null +})[1] local maxDepth = o.maxDepth or 1000 + local stack= {} -- true = object + local depth = 0 + -- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value), + -- "key" (a key expected), "done", "dead" + local state = "value" + local n = #s + local function fail(msg, at) +state = "dead" + return "error", msg, at + end + return function() +if state == "dead" then + return nil + end + i = (match(s, "^[ \t\n\r]*()", i) ) +local c = byte(s, i) + if state == "done" then + state = "dead" + if c ~= nil then + return "error", "trailing data", i - 1 + end + return nil + end + if state == "after" then + local obj = stack[depth] + if c == 44 then + i = (match(s, "^[ \t\n\r]*()", i + 1) ) +c = byte(s, i) + state = obj and"key" or"value" + elseif c == (obj and 125 or 93) then + i =i+ 1 + stack[depth] = nil + depth =depth- 1 + state = depth == 0 and"done" or"after" + return obj and"endObject" or"endArray", nil + elseif c == nil then + return fail("truncated", n) + else + return fail("expected ',' or a close", i - 1) + end + end + if state == "first" then + local obj = stack[depth] + if c == (obj and 125 or 93) then + i =i+ 1 + stack[depth] = nil + depth =depth- 1 + state = depth == 0 and"done" or"after" + return obj and"endObject" or"endArray", nil + end + state = obj and"key" or"value" + end + if state == "key" then + if c ~= 34 then + return fail(c == nil and"truncated" or"expected a key", i - 1) + end + local k, ni, at = str(s, i) + if k == nil then + return fail(ni, at ) + end + i = (match(s, "^[ \t\n\r]*()", ni) ) +if byte(s, i) ~= 58 then + return fail("expected ':'", i - 1) + end + i =i+ 1 + state = "value" + return "key", k + end + -- a value + local after = depth == 0 and"done" or"after" + if c == 123 or c == 91 then + depth =depth+ 1 + if depth > maxDepth then + return fail("nested deeper than " .. maxDepth, i - 1) + end + stack[depth] = c == 123 + i =i+ 1 + state = "first" + return c == 123 and"object" or"array", nil + elseif c == 34 then + local v, ni, at = str(s, i) + if v == nil then + return fail(ni, at ) + end + i = ni + state = after + return "value", v + elseif c == 116 and sub(s, i, i + 3) == "true" then + i =i+ 4 + state = after + return "value", true + elseif c == 102 and sub(s, i, i + 4) == "false" then + i =i+ 5 + state = after + return "value", false + elseif c == 110 and sub(s, i, i + 3) == "null" then + i =i+ 4 + state = after + return "value", nullv + elseif c == nil then + return fail("truncated: expected a value", n) + end + local v, ni, at = num(s, i, bigStrings) + if v == nil then + return fail(ni, at ) + end + i = ni + state = after + return "value", v + end +end + +return Decode +end +__FILES["codecs/text/Json/Encode"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +--!native +-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key +-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional +-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) +-- return nil, message. +local Types = __include("Types") + +local Encode = {} + +local byte, format, gsub = string.byte, string.format, string.gsub +local floor, huge = math.floor, math.huge +local concat = table.concat + + + + + + + + + + + +local ESCAPES= { + ['"'] = '\\"', + ["\\"] = "\\\\", + ["\b"] = "\\b", + ["\f"] = "\\f", + ["\n"] = "\\n", + ["\r"] = "\\r", + ["\t"] = "\\t", + ["/"] = "\\/", +} +for c = 0, 31 do + local ch = string.char(c) + if not ESCAPES[ch] then + ESCAPES[ch] = format("\\u%04x", c) + end +end + +local function utf16(cp) +if cp < 0x10000 then + return format("\\u%04x", cp) + end + cp =cp- 0x10000 + return format("\\u%04x\\u%04x", 0xD800 + math.floor(cp / 1024), 0xDC00 + cp % 1024) +end + +-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws) +local function asciiSeq(seq) +local out = {} + local i, n = 1, #seq + while i <= n do + local c = byte(seq, i) + local cp, len + if c < 0xC0 then + cp, len = c, 1 + elseif c < 0xE0 then + cp, len = (c % 32) * 64 + (byte(seq, i + 1) or 128) % 64, 2 + elseif c < 0xF0 then + cp, len = (c % 16) * 4096 + ((byte(seq, i + 1) or 128) % 64) * 64 + (byte(seq, i + 2) or 128) % 64, 3 + else + cp, len = (c % 8) * 262144 + ((byte(seq, i + 1) or 128) % 64) * 4096 + ((byte(seq, i + 2) or 128) % 64) * 64 + (byte(seq, i + 3) or 128) % 64, 4 + end + table.insert(out, utf16(cp)) + i =i+ len + end + return concat(out) +end + +-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii) +local function quote(s, ascii, slash) +local pat = slash and'[%z\1-\31"\\/]' or'[%z\1-\31"\\]' + if string.find(s, pat) then + s = gsub(s, pat, ESCAPES) + end + if ascii and string.find(s, "[\127-\255]") then + s = gsub(s, "\127", "\\u007f") + s = gsub(s, "[\192-\255][\128-\191]*", asciiSeq) + s = gsub(s, "[\128-\191]", asciiSeq) + end + return '"' .. s .. '"' +end +Encode.quote = quote + +local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" } +-- number(x) -> the shortest text that reads back as x | nil for NaN / inf +local function number(x) +if x ~= x or x == huge or x == -huge then + return nil + end + if x == floor(x) and x > -1e15 and x < 1e15 then + if x == 0 and 1 / x < 0 then + return "-0" + end + return format("%d", x) + end + for _, f in __iter(FLOAT_FORMATS) do + local t = format(f, x) + if tonumber(t) == x then + return t + end + end + return format("%.17g", x) +end +Encode.number = number + +local function keyLess(a, b) +local ta, tb = type(a), type(b) + if ta ~= tb then + return ta == "number" + end + return a < b +end + +-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object" +local function kind(t, emptyObject) +if Types.isObject(t) then + return "object" + end + local n = #t + if n == 0 then + if next(t) == nil then + return emptyObject and"object" or"array" + end + return "object" + end + local count = 0 + for _ in next, t do + count =count+ 1 + end + return count == n and"array" or"object" +end +Encode.kind = kind + + + + + + + + + + + + + + + +local function put(st, s) + local n = st.n + 1 + st.out[n] = s + st.n = n +end + +local function value(st, v, depth) +local tv = type(v) + if tv == "string" then + put(st, quote(v, st.ascii, st.slash)) + elseif tv == "number" then + local s = number(v) + if not s then + if not st.nanNull then + st.err = "cannot encode " .. tostring(v) + return false + end + s = "null" + end + put(st, s) + elseif tv == "boolean" then + put(st, v and"true" or"false") + elseif v == nil or v == st.null or v == Types.null then + put(st, "null") + elseif tv == "table" then + if Types.Date.is(v) then + put(st, '"' .. tostring(v) .. '"') + return true + end + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + local ind = st.indent + local nl, nl2 = "", "" + if ind then + nl = "\n" .. string.rep(ind, depth + 1) + nl2 = "\n" .. string.rep(ind, depth) + end + if kind(v, st.emptyObject) == "array" then + local n = #v + if n == 0 then + put(st, "[]") + return true + end + put(st, "[") + for i = 1, n do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + if not value(st, v[i], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "]") + else + local keys +if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + local tk = type(k) + if tk ~= "string" and tk ~= "number" then + st.err = "object key of type " .. tk + return false + end + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + put(st, "{}") + return true + end + put(st, "{") + local sep = ind and": " or":" + for i, k in __iter(keys) do + if i > 1 then + put(st, ",") + end + if ind then + put(st, nl) + end + local ks +if type(k) == "string" then + ks = k + elseif type(k) == "number" then + ks = number(k) or tostring(k) + else + st.err = "object key of type " .. type(k) + return false + end + put(st, quote(ks, st.ascii, st.slash)) + put(st, sep) + if not value(st, v[k], depth + 1) then + return false + end + end + if ind then + put(st, nl2) + end + put(st, "}") + end + elseif tv == "buffer" then + st.err = "cannot encode a buffer (encode it as base64 or an array first)" + return false + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +local function state(opts, nullv) +local o= opts or {} + local ind= nil + if type(o.indent) == "number" then + ind = (o.indent > 0 and{(string.rep(" ", o.indent) )}or{nil +})[1] elseif type(o.indent) == "string" then + ind = o.indent + end + return { + out = {}, + n = 0, + indent = ind, + sort = o.sortKeys ~= false, + ascii = o.ascii == true, + slash = o.escapeSlash == true, + nanNull = o.nan == "null", + emptyObject = o.emptyTable == "object", + maxDepth = o.maxDepth or 1000, + null = nullv, + err = nil, + } +end +Encode.state = state +Encode.write = value + +-- encode(v, opts) -> text | nil, message +function Encode.encode(v, opts, nullv) +local st = state(opts, nullv) + if not value(st, v, 0) then + return nil, st.err + end + return concat(st.out), nil +end + +return Encode +end +__FILES["codecs/text/Nbt"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, +-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat +-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ +-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers +-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order +-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. +-- +-- local Nbt = require("rosetta.codecs.text.Nbt") +-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored +-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value +-- v.Data.Difficulty = Nbt.byte(2) +-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts +-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} +-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') +-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag +-- +-- Never throws: bad data and bad values return nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Value = __include("codecs/text/Nbt/Value") +local Binary = __include("codecs/text/Nbt/Binary") +local Snbt = __include("codecs/text/Nbt/Snbt") + +local Nbt = {} + + + + + + + + + + + + + + + + + + + + + + + + + + +Nbt.TAG = Value.IDS -- name -> id +Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos= (setmetatable({}, { __mode = "k" }) ) +-- info(value) -> how a decoded root was stored (nil for values not from decode) + +function Nbt.info(v) +return (type(v) == "table" and{infos[v] }or{nil +})[1]end +-- setInfo(value, info): what encode uses as defaults +function Nbt.setInfo(v, info) + if type(v) == "table" then + infos[v] = info + end +end + +-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag +function Nbt.read(buf, offset, length, opts) +local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts ) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag +function Nbt.write(v, opts) +local out, e = Binary.write(v, opts ) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic +function Nbt.unwrap(buf, offset, length, maxBytes) +local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = (l >= 2 and{(buffer.readu8(b, o) )}or{0 +})[1] local c1 = (l >= 2 and{(buffer.readu8(b, o + 1) )}or{0 +})[1] local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + + + + + + + + + + + + +local function plausibleName(b, p, n) +if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a +-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. +function Nbt.peek(buf, offset, length) +local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head +local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, c0 == 0x1f and"gzip" or"zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p, endian, header) +if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q) +local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return (endian == "big" and((a * 256 + b ))or((b * 256 + a +))) end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res= { compression = comp, endian = endian , header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" -- an empty root compound + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == ((comp == "none" and{l }or{(-1)})[1]) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java +-- or Bedrock) +function Nbt.decode(buf, opts, offset, length) +local o= opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data, start, stop= b, s, e +local function try(endian, from, varint) +return Binary.read(data, from, stop, { endian = endian , varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header= nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info= { + name = name, + endian = (o.varint or o.endian == "little" )and"little" or"big", + varint = o.varint and true or nil, + compression = comp , + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file +function Nbt.encode(v, opts) +local o= opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = (o.varint ~= nil and{o.varint }or{(info and info.varint) +})[1] local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = (o.header ~= nil and{o.header }or{(info and info.header) +})[1] if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (endian == "big" and"gzip" or"none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +-- parse(text, opts?) -> value | nil, Err: SNBT +function Nbt.parse(text, opts) +local s = (type(text) == "buffer" and{(buffer.tostring(text) )}or{text +})[1] if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) +function Nbt.print(v, opts) +local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) +function Nbt.get(v, path) +local cur = v + for part in __iter(string.gmatch(path, "[^%.]+")) do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in __iter(string.gmatch(rest , "%[(%-?%d+)%]")) do + local i = (tonumber(idx) ) +if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt +end +__FILES["codecs/text/Nbt/Binary"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from +-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / +-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against +-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Binary = {} + + + + + + + + + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +-- ------------------------------------------------------------------------------------------------ modified UTF-8 +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) + + +local function fromModified(s) +if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i =i+ 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i =i+ 6 + else + table.insert(out, string.char(c)) + i =i+ 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s) +if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i =i+ 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + math.floor(cp / 1024), 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + math.floor((hiS - 0xD000) / 64), 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + math.floor((loS - 0xD000) / 64), 0x80 + loS % 64)) + i =i+ 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +-- ------------------------------------------------------------------------------------------------ read +local function fail(s, msg) +if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s, n) +if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s) +if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p =s.p+ 1 + return v +end + +local function varuint(s) +local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p =s.p+ 1 + v =v+ (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul =mul* 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s) +if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return (v >= 32768 and((v - 65536 ))or(v +))end + +local function u32raw(s) +if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return (s.le and{v }or{(byteswap(v) +)})[1]end + +local function i32(s) +if s.net then + local n = varuint(s) + return (n % 2 == 0 and{(math.floor(n / 2 ))}or{(math.floor(-(n + 1) / 2 +))})[1] end + local v = u32raw(s) + return (v >= 0x80000000 and((v - TWO32 ))or(v +))end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s) +return i32(s) +end + +local function i64(s) +if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p =s.p+ 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo =lo+ x % TWO32 + hi = (hi + math.floor(x / TWO32)) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh =sh+ 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = math.floor(lo / 2 )+ (hi % 2) * 0x80000000 + hi = math.floor(hi / 2 +) if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s) +local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s) +local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s) +local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p =s.p+ n + return (s.java and{(fromModified(v) )}or{v +})[1]end + +local function tag(name, v) +return setmetatable({ type = name, value = v }, newTag) +end + +-- the smallest encoded size of one element, to bound list lengths before allocating +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload + +local function count(s, n, size) +if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s, id) +if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth =s.depth+ 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth =s.depth- 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p =s.p+ 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p =s.p+ n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, ((s.net and{MIN_NET }or{MIN})[1])[et]) then + return nil + end + s.depth =s.depth+ 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth =s.depth- 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, s.net and 1 or 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, s.net and 1 or 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p =s.p+ n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at +function Binary.read(b, pos, limit, opts) +local o= opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s= { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = o.nameless and"" or str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end +-- ------------------------------------------------------------------------------------------------ write + + + +local function wvaruint(w, v) + v =v% TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v =math.floor(v/ 128 +) end + w:u8(v) +end + +local function wi32(ws, v) + v =v% TWO32 -- two's complement + if ws.net then + local sv = (v >= 0x80000000 and((v - TWO32 ))or(v +)) wvaruint(ws.w, (sv >= 0 and((sv * 2 ))or((-sv * 2 - 1)))) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws, v) + v =v% 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws, hi, lo) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (lo >= 0x80000000 and 1 or 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = math.floor(zl / 128 )+ (zh % 128) * 0x2000000 + zh =math.floor(zh/ 128 +) end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws, s) +local v = (ws.java and{(toModified(s) )}or{s +})[1] if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v, lo, hi, what) +local n = (type(v) == "boolean" and{(v and 1 or 0) }or{v +})[1] if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload + +local function wlist(ws, v) +local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt ]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt , x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws, t, v) +local w = ws.w + local x = (Value.isTag(v) and{v.value }or{v +})[1] if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth =ws.depth+ 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in __iter(Types.keys(v)) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct ]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct , c) + if e then + return e + end + end + w:u8(0) + ws.depth =ws.depth- 1 + elseif t == "list" then + ws.depth =ws.depth+ 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth =ws.depth- 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo ) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = math.floor(buffer.len(x) / 8 +) wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +-- write(value, opts?) -> buffer | nil, message +function Binary.write(v, opts) +local o= opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws= { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t ]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t , v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary +end +__FILES["codecs/text/Nbt/Snbt"] = function() +local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict +-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the +-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] +-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted +-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex +-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing +-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's +-- compact form (or indented); floats print as the shortest text that reads back to the same value. +local Types = __include("Types") +local Value = __include("codecs/text/Nbt/Value") + +local Snbt = {} + + + + + + + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name, v) +return setmetatable({ type = name, value = v }, Value.TagMeta) +end +-- ------------------------------------------------------------------------------------------------ parse + + + +local function fail(p, msg) +if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e ) + 1 +end + +local function isUnquoted(c) +return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC= { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p) +local q = sub(p.s, p.i, p.i) + p.i =p.i+ 1 + local out = {} + while true do + local j = find(p.s, q == '"' and'["\\]' or"['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = c == "x" and 2 or(c == "u" and 4 or 8 +) local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = (tonumber(hex, 16) ) +if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +-- number text -> a value, or nil when it is not a number (then it is an unquoted string) +local INT_RANGE= { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t) +local sign, body = string.match(t, "^([+-]?)(.+)$") + body = (string.gsub(body , "_", "") ) +local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m , string.lower(sfx ) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + -- the magnitude as (hi, lo) + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = (c <= 57 and((c - 48 ))or((c >= 97 and((c - 87 ))or((c - 55 +))))) local x = lo * radix + d + local carry = math.floor(x / TWO32 +) lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (lo == 0 and 1 or 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v =v- (r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) +) elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v =v- (r[3] + 1 +) end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t) +local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(sfx == "f" and"float" or"double", (special == "-" and{(-math.huge )}or{math.huge})[1]) + elseif low == "nanf" or low == "nand" then + return tag(sfx == "f" and"float" or"double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m , "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant , "^[+-]?%d+%.?%d*$") or string.match(mant , "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant , ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs ) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue + +local function token(p) +local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j =j+ 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p) +ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p, kind) +local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = (t ~= "" and{(number(t) )}or{nil +})[1] local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x= (Value.isTag(v) and{(v ).value }or{v +})[1] if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i =p.i+ 1 + if c == "]" then + break + elseif c ~= "," then + p.i =p.i- 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i =p.i+ 1 + break + end + end + else + p.i =p.i+ 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in __iter(items) do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p) +ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth =p.depth+ 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i =p.i+ 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i =p.i+ 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i =p.i+ 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k ] == nil then + table.insert(keys, k) + end + o[k ] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i =p.i+ 1 + if d == "}" then + break + elseif d ~= "," then + p.i =p.i- 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i =p.i+ 1 + break + end + end + end + p.depth =p.depth- 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth =p.depth+ 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i =p.i+ 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e ) + 1 + local v = array(p, ARRAY[kind]) + p.depth =p.depth- 1 + return v + end + local items = {} + local lt= nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i =p.i+ 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i =p.i+ 1 + if d == "]" then + break + elseif d ~= "," then + p.i =p.i- 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i =p.i+ 1 + break + end + end + end + p.depth =p.depth- 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +-- parse(text, opts?) -> value | nil, message, position (1-based) +function Snbt.parse(s, opts) +local p= { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +-- ------------------------------------------------------------------------------------------------ print +local function shortest(v, single) +if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = single and 6 or 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = (tonumber(s) ) +if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s =s.. ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s, q) +local other = q == '"' and"'" or'"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c) +if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k, q) +if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + + + +local printValue + +local function scalar(v, q) +local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return v and"1b" or"0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return ((type(x) == "string" and{x }or{(string.format("%d", x))})[1]) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr, head, items, close) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, pr.indent and", " or",") .. close) + end +end + +local function sub1(pr, v) +local inner= { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr, v, depth) +if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = (table.create(buffer.len(v)) ) +for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in __iter(v.value) do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in __iter(Value.longs(v)) do + items[i] = ((type(x) == "string" and{x }or{(string.format("%d", x))})[1]) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items= {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x +end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in __iter(Types.keys(v)) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (pr.indent and": " or":") .. (x )) + end + seq(pr, "{", items, "}") + end + return nil +end + +-- print(value, opts?) -> text | nil, message +function Snbt.print(v, opts) +local o= opts or {} + local ind = o.indent + local pr= { + out = {}, + indent = (type(ind) == "number" and{(string.rep(" ", ind) )}or{(type(ind) == "string" and{ind }or{nil})[1]})[1], + q = o.quote == "'" and"'" or'"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v) +return Snbt.print(v) or "?" +end + +return Snbt +end +__FILES["codecs/text/Nbt/Value"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- Plain Luau values with typed numbers, so a decode / encode round trip is exact: +-- int -> number string -> string byteArray -> buffer +-- compound -> Types.object (key order kept) list -> array (element type in Value.listType) +-- byte / short / long / float / double / intArray / longArray -> a tag { type = "<name>", value = ... } with a +-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal +-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. +-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as +-- byte 1 / 0; a plain table with string keys as a compound. +local Types = __include("Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} +Value.IDS = {} +for id = 0, 12 do + Value.IDS[Value.NAMES[id] ] = id +end + + + +local TagMeta= {} +Value.TagMeta = TagMeta +-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) +Value.print = function(v) +return tostring(v.value) +end +TagMeta.__tostring = function(v) +return Value.print(v) +end +TagMeta.__eq = function(a, b) +if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes= (setmetatable({}, { __mode = "k" }) ) +-- ------------------------------------------------------------------------------------------------ 64-bit integers + +local TWO32 = 4294967296 + +-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the +-- two's complement int64) +function Value.fromHiLo(hi, lo) +local s = (hi >= 0x80000000 and((hi - TWO32 ))or(hi +)) if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (lo == 0 and 1 or 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = math.floor(hi / 10000 +) local x = (hi - qh * 10000) * TWO32 + lo + local ql = math.floor(x / 10000 +) local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format((hi > 0 or lo > 0 )and"%04d" or"%d", d)) + end + return (neg and"-" or"") .. table.concat(parts) +end + +-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text +function Value.toHiLo(v) +if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = math.floor(v / TWO32 +) local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = math.floor(x / TWO32 +) lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (lo == 0 and 1 or 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +local function tag(name, v) +return (setmetatable({ type = name, value = v }, TagMeta) ) +end +function Value.byte(n) +return tag("byte", n) +end +function Value.short(n) +return tag("short", n) +end +function Value.int(n) +return n +end +-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) +function Value.long(v) +if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo ) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +-- float(n) -> a float tag holding n rounded to single precision +function Value.float(n) +buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n) +return tag("double", n) +end +function Value.intArray(t) +return tag("intArray", t or {}) +end +-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) +function Value.longArray(t) +if type(t) == "buffer" then + return tag("longArray", t) + end + local list= (t or {}) +local b = buffer.create(#list * 8) + for i, x in __iter(list) do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +-- longs(longArray) -> { number | string }: the elements as long values +function Value.longs(a) +local b= a.value + local out = (table.create(math.floor(buffer.len(b) / 8)) ) +for i = 0, math.floor(buffer.len(b) / 8 )- 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) +function Value.list(name, items) +local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t, keys) +return Types.object(t, keys) +end +-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) +function Value.listType(t) +return listTypes[t] +end +function Value.setListType(t, name) + listTypes[t] = name +end +function Value.isTag(v) +return type(v) == "table" and getmetatable(v) == TagMeta +end + +-- typeOf(v) -> the tag name v writes as, or nil + why +function Value.typeOf(v) +local tv = type(v) + if tv == "number" then + return v % 1 == 0 and v >= -2147483648 and v <= 2147483647 and"int" or"double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) +function Value.number(v) +if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return v and 1 or 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value +end +__FILES["codecs/text/Text"] = function() +local __compat = __compat local buffer, utf8, __iter = __compat.buffer, __compat.utf8, __compat.__iter --!strict +--!optimize 2 +-- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +-- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. +local Text = {} + +-- utf8char(codepoint) -> its UTF-8 bytes (no validation: the parsers check ranges first; utf8.char would throw) +function Text.utf8char(c) +local char = string.char + if c < 0x80 then + return char(c) + elseif c < 0x800 then + return char(0xC0 + math.floor(c / 64), 0x80 + c % 64) + elseif c < 0x10000 then + return char(0xE0 + math.floor(c / 4096), 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) + end + return char(0xF0 + math.floor(c / 262144), 0x80 + (math.floor(c / 4096)) % 64, 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) +end + +-- CP1252 bytes 0x80..0x9F (undefined ones map to U+FFFD) +Text.CP1252 = { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +function Text.trim(s) +return ((string.match(s, "^%s*(.-)%s*$") )) +end + +-- utf16(buf, offset, length, bigEndian?) -> UTF-8 text of UTF-16 code units (surrogate pairs joined, lone surrogates +-- become U+FFFD; an odd last byte is ignored). Font names, 7z / PSD / Windows strings, XML in UTF-16. +function Text.utf16(b, o, n, bigEndian) +local out = {} + local k = 0 + local readu16 = buffer.readu16 + local function unit(at) +local v = readu16(b, at) + return (bigEndian and(((v % 256) * 256 + math.floor(v / 256 )))or(v +)) end + while k + 1 < n do + local c = unit(o + k) + k =k+ 2 + if c >= 0xD800 and c < 0xDC00 and k + 1 < n then + local lo = unit(o + k) + if lo >= 0xDC00 and lo < 0xE000 then + c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00) + k =k+ 2 + end + end + if c >= 0xD800 and c < 0xE000 then + c = 0xFFFD + end + table.insert(out, Text.utf8char(c)) + end + return table.concat(out) +end + +-- toUtf8(text, warnings?) -> text as UTF-8: strips a BOM; text that is not valid UTF-8 is read as Windows-1252 +function Text.toUtf8(text, warnings) +if string.sub(text, 1, 3) == "\239\187\191" then + text = string.sub(text, 4) + end + if utf8.len(text) then + return text + end + if warnings then + table.insert(warnings, "text is not UTF-8: read as Windows-1252") + end + local out = table.create(#text) + for i = 1, #text do + local b = string.byte(text, i) + if b < 0x80 then + out[i] = string.char(b) + else + out[i] = utf8.char((b < 0xA0 and{Text.CP1252[b] or 0xFFFD }or{b})[1]) + end + end + return table.concat(out) +end + +function Text.lines(text) +text = string.gsub(text, "\r\n?", "\n") + local out = {} + for line in __iter(string.gmatch(text .. "\n", "([^\n]*)\n")) do + table.insert(out, line) + end + return out +end + +return Text +end +__FILES["codecs/text/Url"] = function() +local __compat = __compat local type = __compat.type --!strict +--!optimize 2 +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +-- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI +-- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. +-- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its +-- init.luau. Never throws. +local Url = {} + +-- Splits a URI reference into its five components (RFC 3986 appendix B). + + + + + + + + + + +function Url.split(ref) +local scheme, rest = string.match(ref, "^([%a][%w+%.%-]*):(.*)$") + if not scheme then + rest = ref + end + local s = rest +local fragment, query, authority + local i = string.find(s, "#", 1, true) + if i then + fragment = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + i = string.find(s, "?", 1, true) + if i then + query = string.sub(s, i + 1) + s = string.sub(s, 1, i - 1) + end + if string.sub(s, 1, 2) == "//" then + local j = string.find(s, "/", 3, true) + if j then + authority = string.sub(s, 3, j - 1) + s = string.sub(s, j) + else + authority = string.sub(s, 3) + s = "" + end + end + return { scheme = scheme, authority = authority, path = s, query = query, fragment = fragment } +end + +-- Recomposes components (RFC 3986 section 5.3). +function Url.join(p) +local out = {} + if p.scheme then + table.insert(out, p.scheme .. ":") + end + if p.authority then + table.insert(out, "//" .. p.authority) + end + table.insert(out, p.path) + if p.query then + table.insert(out, "?" .. p.query) + end + if p.fragment then + table.insert(out, "#" .. p.fragment) + end + return table.concat(out) +end + +-- RFC 3986 section 5.2.4 +function Url.removeDotSegments(path) +local input = path + local output = {} + while input ~= "" do + if string.sub(input, 1, 3) == "../" then + input = string.sub(input, 4) + elseif string.sub(input, 1, 2) == "./" then + input = string.sub(input, 3) + elseif string.sub(input, 1, 3) == "/./" then + input = string.sub(input, 3) + elseif input == "/." then + input = "/" + elseif string.sub(input, 1, 4) == "/../" then + input = string.sub(input, 4) + table.remove(output) + elseif input == "/.." then + input = "/" + table.remove(output) + elseif input == "." or input == ".." then + input = "" + else + -- move the first segment (with its leading "/", up to the next "/") to the output + local j = string.find(input, "/", 2, true) + local seg = (j and{(string.sub(input, 1, j - 1) )}or{input +})[1] table.insert(output, seg) + input = string.sub(input, #seg + 1) + end + end + return table.concat(output) +end + +-- Resolves a reference against an absolute base URI (RFC 3986 section 5.2.2, strict). +function Url.resolve(ref, base) +local r, b = Url.split(ref), Url.split(base) + local t= { path = "" } + if r.scheme then + t.scheme, t.authority, t.path, t.query = r.scheme, r.authority, Url.removeDotSegments(r.path), r.query + else + if r.authority then + t.authority, t.path, t.query = r.authority, Url.removeDotSegments(r.path), r.query + else + if r.path == "" then + t.path = b.path + t.query = (r.query and{r.query }or{b.query +})[1] else + if string.sub(r.path, 1, 1) == "/" then + t.path = Url.removeDotSegments(r.path) + else + -- merge (5.2.3) + local merged + if b.authority and b.path == "" then + merged = "/" .. r.path + else + local k = string.match(b.path, "^.*()/") + merged = ((k and{(string.sub(b.path, 1, k) )}or{""})[1]) .. r.path + end + t.path = Url.removeDotSegments(merged) + end + t.query = r.query + end + t.authority = b.authority + end + t.scheme = b.scheme + end + t.fragment = r.fragment + return Url.join(t) +end + +-- Percent-encodes the bytes that may not appear in a URI (controls, space, non-ASCII, "<>\"^`{|}" and "\\"), +-- leaving existing %XX escapes and the reserved delimiters alone. +function Url.encodeUnsafe(s) +return (string.gsub(s, "[%z\1-\32\127-\255<>\"%^`{|}\\]", function(c) +return string.format("%%%02X", string.byte(c)) + end)) +end + +-- Is a location a local Windows path ("C:\x", "C:/x", "\\server\share", "\x")? +function Url.isWindowsPath(s) +return string.match(s, "^%a:[\\/]") ~= nil + or string.match(s, "^%a:$") ~= nil + or string.sub(s, 1, 2) == "\\\\" + or string.sub(s, 1, 1) == "\\" +end + +-- The scheme of an absolute URI (lower case), or nil. Windows drive letters are not schemes. +function Url.scheme(s) +if Url.isWindowsPath(s) then + return nil + end + local scheme = string.match(s, "^([%a][%w+%.%-]*):") + return (scheme and{(string.lower(scheme) )}or{nil +})[1]end + +-- locate(raw, base?, baseScheme?) -> { url, playable, reason? }: an entry location resolved against the playlist's +-- base (from Url.base). Windows paths stay as they are and are local; relative paths without a base, file: URLs and +-- schemes other than http(s) are not playable (reason says why). +function Url.locate(raw, base, baseScheme) +local loc = ((string.match(raw, "^%s*(.-)%s*$") )) + if Url.isWindowsPath(loc) then + return { url = loc, playable = false, reason = "local path" } + end + local scheme = Url.scheme(loc) + local url = loc + if not scheme and baseScheme == "windows" and base then + -- a playlist on a Windows disk: relative entries are paths next to it + local dir = string.match(base, "^(.*[\\/])") or "" + return { url = dir .. loc, playable = false, reason = "local path" } + end + if scheme then + if scheme == "http" or scheme == "https" then + url = Url.encodeUnsafe(Url.resolve(loc, loc)) + end + elseif base and baseScheme then + -- a relative reference: Windows separators become URL ones + url = Url.resolve(Url.encodeUnsafe((string.gsub(loc, "\\", "/"))), base) + scheme = baseScheme + else + return { url = loc, playable = false, reason = "relative path without a base URL" } + end + if scheme == "http" or scheme == "https" then + return { url = url, playable = true } + elseif scheme == "file" then + return { url = url, playable = false, reason = "local path" } + end + return { url = url, playable = false, reason = "scheme " .. tostring(scheme) } +end + +-- base(baseUrl?, warnings?) -> base, baseScheme: the base for Url.locate from the playlist's own URL or path ("windows" +-- for a Windows path); a non-absolute base is ignored (with a warning) +function Url.base(baseUrl, warnings) +if type(baseUrl) ~= "string" or baseUrl == "" then + return nil, nil + end + local s = Url.scheme(baseUrl) + if s and Url.split(baseUrl).authority ~= nil or s == "file" then + return Url.encodeUnsafe(baseUrl), s + elseif Url.isWindowsPath(baseUrl) then + return baseUrl, "windows" + end + if warnings then + table.insert(warnings, "base URL is not absolute: " .. baseUrl) + end + return nil, nil +end + +return Url +end +__FILES["codecs/text/Xml"] = function() +local __compat = __compat local buffer, typeof, type, __iter = __compat.buffer, __compat.typeof, __compat.type, __compat.__iter --!strict +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +-- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal +-- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces +-- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives +-- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. +-- +-- local Xml = require("rosetta.codecs.text.Xml") +-- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element +-- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end +-- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) +-- local s = Xml.encode(doc, { indent = 2 }) +-- local e = Xml.element("svg", { width = "10" }, { Xml.element("rect") }) -- build trees +-- +-- Nodes (Types.XmlNode): { name, attrs (a Types.object: attribute order kept), children = { node | string }, +-- parent }. Text children are strings. With opts.comments / opts.cdata / opts.pi, comments, CDATA sections and +-- processing instructions are kept as "#comment" / "#cdata" / "#pi" nodes (text = the content, target = the PI +-- target); otherwise CDATA merges into the text and the others are dropped. Never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Parse = __include("codecs/text/Xml/Parse") + +local Xml = {} + + + + + + + + + + + + + + +local find, gsub, sub, match = string.find, string.gsub, string.sub, string.match + +local function text(src) +if type(src) == "string" then + return src, nil + elseif type(src) == "buffer" then + return buffer.tostring(src), nil + end + return nil, Err.new(Err.ARG, "expected a string or a buffer, got " .. typeof(src)) +end + +local function errCode(msg, at, n) +if find(msg, "unterminated", 1, true) or find(msg, "truncated", 1, true) or find(msg, "unclosed", 1, true) or at >= n then + return Err.TRUNCATED + elseif find(msg, "over the limit", 1, true) or find(msg, "nested deeper", 1, true) then + return Err.LIMIT + elseif find(msg, "not supported", 1, true) or find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + end + return Err.CORRUPT +end + +-- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, +-- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) +function Xml.events(src, opts) +local s, terr = text(src) + local u, enc = nil, "" + if s then + u, enc = Parse.toUtf8(s) + end + if not u then + local e = terr or Err.new((find(enc, "unsupported", 1, true) and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], enc) + local done = false + return function() +if done then + return nil + end + done = true + return "error", e + end + end + local str= u + local nextEv = Parse.events(str, opts) + return function() +local ev, a, b, c = nextEv() + if ev == "error" then + return ev, Err.new(errCode(a, b, #str), a, b) + end + return ev, a, b, c + end +end + +-- decode(src, opts?) -> the "#document" node | nil, Err. doc.root = the root element; doc.declaration = { version, +-- encoding, standalone }?; doc.doctype = { raw, name, publicId, systemId, entities }?; doc.children = the root plus +-- any kept comments / PIs around it. +function Xml.decode(src, opts) +local o= opts or {} + local keepComments, keepCdata, keepPi = o.comments == true, o.cdata == true, o.pi == true + local parents = o.parents ~= false + local doc= { name = "#document", attrs = Types.object(), children = {}, parent = nil } + local cur= doc + local stack = { doc } + local depth = 1 + for ev, a, b, c in __iter(Xml.events(src, o)) do + if ev == "start" then + local node= { name = a, attrs = b, children = {}, parent = (parents and{cur }or{nil })[1]} + if c then + node.ns = c + end + table.insert(cur.children, node) + depth =depth+ 1 + stack[depth] = node + cur = node + if depth == 2 then + doc.root = node + end + elseif ev == "end" then + stack[depth] = nil + depth =depth- 1 + cur = stack[depth] + elseif ev == "text" or (ev == "cdata" and not keepCdata) then + local ch = cur.children + local last = #ch + if last > 0 and type(ch[last]) == "string" then + ch[last]=ch[last].. a + else + ch[last + 1] = a + end + elseif ev == "cdata" then + table.insert(cur.children, { name = "#cdata", attrs = Types.object(), children = {}, text = a, parent = (parents and{cur }or{nil })[1]}) + elseif ev == "comment" then + if keepComments then + table.insert(cur.children, { name = "#comment", attrs = Types.object(), children = {}, text = a, parent = (parents and{cur }or{nil })[1]}) + end + elseif ev == "pi" then + if keepPi then + table.insert(cur.children, { name = "#pi", attrs = Types.object(), children = {}, target = a, text = b, parent = (parents and{cur }or{nil })[1]}) + end + elseif ev == "decl" then + doc.declaration = a + elseif ev == "doctype" then + doc.doctype = { raw = a, name = b.name, publicId = b.publicId, systemId = b.systemId, entities = b.entities } + elseif ev == "error" then + return nil, a + end + end + return doc, nil +end + +-- ------------------------------------------------------------------------------------------------ tree helpers +-- element(name, attrs?, children?) -> a new element (attrs: a plain table (written sorted) or a Types.object; +-- children: nodes or strings; their parent is set) +function Xml.element(name, attrs, children) +local a = attrs or Types.object() + if not Types.isObject(a) then + local keys = {} + for k in next, a do + table.insert(keys, k) + end + table.sort(keys) + a = Types.object(a, keys) + end + local node= { name = name, attrs = a, children = children or {} } + for _, ch in __iter(node.children) do + if type(ch) == "table" then + ch.parent = node + end + end + return node +end + +-- document(root, declaration?) -> a "#document" node around root +function Xml.document(root, declaration) +local doc= { name = "#document", attrs = Types.object(), children = { root }, root = root, declaration = declaration } + root.parent = doc + return doc +end + +-- append(parent, child) -> child (a node or a string), parent link set +function Xml.append(parent, child) +table.insert(parent.children, child) + if type(child) == "table" then + child.parent = parent + end + return child +end + +-- setAttr(node, name, value): set (or with nil remove) an attribute, keeping the order +function Xml.setAttr(node, name, value) + Types.set(node.attrs, name, value) +end + +-- children(node, name?) -> the element children (with that qualified name, or local name when name has no prefix and +-- the child's does), in order +function Xml.children(node, name) +local out = {} + for _, ch in __iter(node.children) do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + table.insert(out, ch) + end + end + end + return out +end + +-- child(node, name?) -> the first matching element child, or nil +function Xml.child(node, name) +for _, ch in __iter(node.children) do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name, ":", 1, true) and match(ch.name, ":(.*)$") == name) then + return ch + end + end + end + return nil +end + +-- descendants(node, name?) -> every element below node (document order), optionally filtered as children() does +function Xml.descendants(node, name) +local out = {} + local function walk(n) + for _, ch in __iter(n.children) do + if type(ch) == "table" and string.byte(ch.name) ~= 35 then + if name == nil or ch.name == name or (not find(name , ":", 1, true) and match(ch.name, ":(.*)$") == name) then + table.insert(out, ch) + end + walk(ch) + end + end + end + walk(node) + return out +end + +-- text(node) -> all the character data below node, concatenated (CDATA included, comments / PIs not) +function Xml.text(node) +if type(node) == "string" then + return node + end + if node.name == "#cdata" then + return node.text or "" + end + local parts = {} + local function walk(n) + for _, ch in __iter(n.children) do + if type(ch) == "string" then + table.insert(parts, ch) + elseif ch.name == "#cdata" then + table.insert(parts, ch.text or "") + elseif string.byte(ch.name) ~= 35 then + walk(ch) + end + end + end + walk(node) + return table.concat(parts) +end + +-- prefix(name) / localName(name): the parts of a qualified name ("svg:rect" -> "svg", "rect"; "rect" -> "", "rect") +function Xml.prefix(name) +return match(name, "^([^:]*):") or "" +end +function Xml.localName(name) +return match(name, ":(.*)$") or name +end + +-- namespace(node, prefix?) -> the URI bound to prefix (default: the node's own prefix) at node, through its +-- ancestors' xmlns attributes (needs parent links) +function Xml.namespace(node, prefix) +return Parse.resolve(node, prefix or Xml.prefix(node.name)) +end + +-- clark(node, attrName?) -> "{uri}local" (ElementTree's notation) for the element, or for one of its attributes +-- (unprefixed attributes have no namespace) +function Xml.clark(node, attrName) +local name = attrName or node.name + local prefix = Xml.prefix(name) + if attrName and prefix == "" then + return name + end + local uri = Parse.resolve(node, prefix) + if uri then + return "{" .. uri .. "}" .. Xml.localName(name) + end + return name +end + +-- ------------------------------------------------------------------------------------------------ encode +local TEXT_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ["\r"] = " " } +local ATTR_ESC = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["\t"] = " ", ["\n"] = " ", ["\r"] = " " } + +-- escape(s) / escapeAttr(s): text / attribute-value escaping +function Xml.escape(s) +return (gsub(s, "[&<>\r]", TEXT_ESC)) +end +function Xml.escapeAttr(s) +return (gsub(s, '[&<>"\t\n\r]', ATTR_ESC)) +end + +local function badName(name) +return type(name) ~= "string" or not match(name, "^[%a_:\128-\255][%w_:%.%-\128-\255]*$") +end + +-- encode(node, opts?) -> string | nil, Err. node: a "#document" or any node (an element, a comment, ...) +function Xml.encode(node, opts) +local o= opts or {} + local ind= nil + if type(o.indent) == "number" then + ind = (o.indent > 0 and{(string.rep(" ", o.indent) )}or{nil +})[1] elseif type(o.indent) == "string" then + ind = o.indent + end + local selfClose = o.selfClose ~= false + local out= {} + local err= nil + local seen= {} + + local write +function write(n, depth) + if err then + return + end + if type(n) == "string" then + table.insert(out, Xml.escape(n)) + return + end + if type(n) ~= "table" or type(n.name) ~= "string" then + err = "a child is not a node or a string" + return + end + if seen[n] then + err = "a node appears twice (a cycle?)" + return + end + seen[n] = true + local name = n.name + if name == "#comment" then + local t = n.text or "" + if find(t, "--", 1, true) or sub(t, -1) == "-" then + err = "comment text contains '--'" + return + end + table.insert(out, "<!--" .. t .. "-->") + elseif name == "#cdata" then + table.insert(out, "<![CDATA[" .. gsub(n.text or "", "]]>", "]]]]><![CDATA[>") .. "]]>") + elseif name == "#pi" then + if badName(n.target) or find(n.text or "", "?>", 1, true) then + err = "bad processing instruction" + return + end + table.insert(out, "<?" .. n.target .. ((n.text and n.text ~= "" and((" " .. n.text ))or(""))) .. "?>") + elseif name == "#doctype" then + table.insert(out, "<!DOCTYPE" .. (n.text or "") .. ">") + elseif name == "#document" then + for i, ch in __iter(n.children) do + if i > 1 and ind then + table.insert(out, "\n") + end + write(ch, 0) + end + else + if badName(name) then + err = "bad element name " .. tostring(name) + return + end + table.insert(out, "<" .. name) + local attrs = n.attrs or {} + for _, k in __iter(Types.keys(attrs)) do + local v = attrs[k] + if badName(k) then + err = "bad attribute name " .. tostring(k) + return + end + if type(v) == "number" or type(v) == "boolean" then + v = tostring(v) + elseif type(v) ~= "string" then + err = "attribute " .. k .. " is not a string" + return + end + table.insert(out, " " .. k .. '="' .. Xml.escapeAttr(v) .. '"') + end + local ch = n.children or {} + if #ch == 0 then + table.insert(out, selfClose and"/>" or"></" .. name .. ">") + return + end + table.insert(out, ">") + local pretty = ind ~= nil + if pretty then + for _, c in __iter(ch) do + if type(c) == "string" or c.name == "#cdata" then + pretty = false + break + end + end + end + for _, c in __iter(ch) do + if pretty then + table.insert(out, "\n" .. string.rep(ind , depth + 1)) + end + write(c, depth + 1) + end + if pretty then + table.insert(out, "\n" .. string.rep(ind , depth)) + end + table.insert(out, "</" .. name .. ">") + end + end + + local decl = o.declaration + if decl == nil then + decl = node.name == "#document" + end + if decl then + local d= node.declaration or {} + table.insert(out, '<?xml version="' .. (d.version or "1.0") .. '" encoding="UTF-8"' .. ((d.standalone and((' standalone="' .. d.standalone .. '"' ))or(""))) .. "?>") + table.insert(out, "\n") + end + if node.name == "#document" and node.doctype then + local dt= node.doctype + local raw = dt.raw + if raw == nil then + raw = " " .. (dt.name or ((node.root and{node.root.name }or{"root"})[1])) + if dt.publicId then + raw =raw.. ' PUBLIC "' .. dt.publicId .. '" "' .. (dt.systemId or "") .. '"' + elseif dt.systemId then + raw =raw.. ' SYSTEM "' .. dt.systemId .. '"' + end + end + table.insert(out, "<!DOCTYPE" .. raw .. ">\n") + end + write(node, 0) + if err then + return nil, Err.new(Err.ARG, err) + end + if ind and node.name == "#document" then + table.insert(out, "\n") + end + return table.concat(out), nil +end + +return Xml +end +__FILES["codecs/text/Xml/Parse"] = function() +local __compat = __compat local utf8, __iter = __compat.utf8, __compat.__iter --!strict +--!native +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the +-- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, +-- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, +-- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: +-- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), +-- validation. Never throws: errors are events. +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Parse = {} + +local byte, sub, find, match, char, gsub, lower = string.byte, string.sub, string.find, string.match, string.char, string.gsub, string.lower + + + + + + + + + +local NAME = "^[%a_:\128-\255][%w_:%.%-\128-\255]*" +local PREDEF= { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'" } + +local utf8char = Text.utf8char +Parse.utf8char = utf8char + +local CP1252= { + [0x80] = 0x20AC, [0x82] = 0x201A, [0x83] = 0x0192, [0x84] = 0x201E, [0x85] = 0x2026, [0x86] = 0x2020, + [0x87] = 0x2021, [0x88] = 0x02C6, [0x89] = 0x2030, [0x8A] = 0x0160, [0x8B] = 0x2039, [0x8C] = 0x0152, + [0x8E] = 0x017D, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201C, [0x94] = 0x201D, [0x95] = 0x2022, + [0x96] = 0x2013, [0x97] = 0x2014, [0x98] = 0x02DC, [0x99] = 0x2122, [0x9A] = 0x0161, [0x9B] = 0x203A, + [0x9C] = 0x0153, [0x9E] = 0x017E, [0x9F] = 0x0178, +} + +local function utf16(s, start, le) +local out = table.create(math.floor(#s / 2)) + local n = 0 + local i = start + local len = #s + while i + 1 <= len do + local a, b = byte(s, i, i + 1) + local u = (le and((a + b * 256 ))or((a * 256 + b +))) i =i+ 2 + if u >= 0xD800 and u <= 0xDBFF then + if i + 1 > len then + return nil, "truncated UTF-16 surrogate pair" + end + local c, d = byte(s, i, i + 1) + local lo = (le and((c + d * 256 ))or((c * 256 + d +))) if lo < 0xDC00 or lo > 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + i =i+ 2 + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + elseif u >= 0xDC00 and u <= 0xDFFF then + return nil, "bad UTF-16 surrogate pair" + end + n =n+ 1 + out[n] = utf8char(u) + end + if i <= len then + return nil, "odd number of bytes in UTF-16 text" + end + return table.concat(out), nil +end + +-- toUtf8(s) -> UTF-8 text (BOM removed), the encoding name | nil, message +function Parse.toUtf8(s) +local b1, b2, b3 = byte(s, 1, 3) + if b1 == 0xEF and b2 == 0xBB and b3 == 0xBF then + return sub(s, 4), "utf-8" + elseif b1 == 0xFF and b2 == 0xFE then + local t, e = utf16(s, 3, true) + return t, e or "utf-16le" + elseif b1 == 0xFE and b2 == 0xFF then + local t, e = utf16(s, 3, false) + return t, e or "utf-16be" + elseif b1 == 0x3C and b2 == 0 then + local t, e = utf16(s, 1, true) + return t, e or "utf-16le" + elseif b1 == 0 and b2 == 0x3C then + local t, e = utf16(s, 1, false) + return t, e or "utf-16be" + end + local decl = match(s, "^<%?xml[^>]-%?>") + local enc = (decl and{(match(decl, "encoding%s*=%s*[\"']([%w%._%-]+)[\"']") )}or{nil +})[1] if enc then + local e = lower(enc) + if e == "utf-8" or e == "utf8" or e == "us-ascii" or e == "ascii" then + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, e + elseif e == "iso-8859-1" or e == "latin1" or e == "latin-1" or e == "iso8859-1" or e == "windows-1252" or e == "cp1252" then + local w = e == "windows-1252" or e == "cp1252" + return (gsub(s, "[\128-\255]", function(c) +local v = byte(c) + return utf8char((w and{CP1252[v] or v }or{v})[1]) + end)), e + elseif e == "utf-16" or e == "utf-16le" or e == "utf-16be" then + return s, "utf-8" -- declared UTF-16 but read as 8-bit text: trust the bytes + end + return nil, "unsupported encoding " .. enc + end + if find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8" + end + return s, "utf-8" +end + +-- the <?xml ...?> pseudo-attributes, strictly: version, then encoding?, then standalone?, each after whitespace +local function xmlDecl(data) +local p = 1 + local out= {} + for k, key in __iter({ "version", "encoding", "standalone" }) do + local ws = (match(data, "^[ \t\n]*()", p) ) +local q, v, e = match(data, "^" .. key .. "[ \t\n]*=[ \t\n]*([\"'])(.-)%1()", ws) + if q then + if k > 1 and ws == p then + return nil -- no whitespace before + end + if (key == "version" and not match(v, "^1%.%d+$")) + or (key == "encoding" and not match(v, "^%a[%w%._%-]*$")) + or (key == "standalone" and v ~= "yes" and v ~= "no") + then + return nil + end + out[key] = v + p = e + elseif key == "version" then + return nil + end + end + if match(data, "^[ \t\n]*()", p) ~= #data + 1 then + return nil + end + return out +end + +-- the events iterator: next() -> event, a, b, c +-- "decl", { version, encoding, standalone } the <?xml ...?> declaration +-- "doctype", raw, info raw = the text between "<!DOCTYPE" and ">"; info = { name, +-- publicId, systemId, entities } +-- "start", name, attrs (Types.object), ns ns: the element's namespace URI (opts.namespaces) or nil +-- "end", name +-- "text", s character data, entities decoded (whitespace-only dropped +-- unless opts.whitespace) +-- "cdata", s "comment", s "pi", target, data +-- "error", message, offset then the iterator ends +-- nil at the end of the document. +function Parse.events(s, opts) +local o= opts or {} + local keepWs = o.whitespace == true + local nsOn = o.namespaces == true + local maxExp = o.maxExpansion or 1e7 + local maxDepth = o.maxDepth or 10000 + local entities= {} + if o.entities then + for k, v in __iter(o.entities) do + entities[k] = v + end + end + local external= {} + local expanded = 0 + if find(s, "\r", 1, true) then + s = gsub(gsub(s, "\r\n", "\n"), "\r", "\n") + end + local n = #s + local i = 1 + local stack= {} + local nsStack= {} + local preserve= {} + local depth = 0 + local rootSeen = false + local rootDone = false + local dead = false + local pending= nil -- an "end" queued after a self-closing start + local errMsg= nil + local errAt = 0 + + local function fail(msg, at) +dead = true + return "error", msg, at - 1 + end + + -- decode entity / character references in raw text; nil on error (errMsg set) + local decode +function decode(raw, at, level) +if not find(raw, "&", 1, true) then + return raw + end + local parts = {} + local np = 0 + local p = 1 + while true do + local a = find(raw, "&", p, true) + if not a then + break + end + np =np+ 1 + parts[np] = sub(raw, p, a - 1) + local ref, e = match(raw, "^&([^;&%s<]*);()", a) + if not ref then + errMsg, errAt = "bad reference (no ';')", at + a - 1 + return nil + end + local rep +if byte(ref) == 35 then -- # + local cp = (byte(ref, 2) == 120 and{(tonumber(match(ref, "^#x(%x+)$") or "", 16) )}or{(tonumber(match(ref, "^#(%d+)$") or "") +)})[1] if not cp or cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) or cp == 0xFFFE or cp == 0xFFFF then + errMsg, errAt = "bad character reference &" .. ref .. ";", at + a - 1 + return nil + end + rep = utf8char(cp) + else + local pre = PREDEF[ref] + if pre then + rep = pre + else + local ent = entities[ref] + if not ent then + errMsg = (external[ref] and(("external entity &" .. ref .. "; not supported" ))or(("undefined entity &" .. ref .. ";" +))) errAt = at + a - 1 + return nil + end + if level > 40 then + errMsg, errAt = "entity references nested too deeply (recursive?)", at + a - 1 + return nil + end + local r = decode(ent, at + a - 1, level + 1) + if not r then + return nil + end + rep = r + end + end + expanded =expanded+ #rep + if expanded > maxExp then + errMsg, errAt = "entity expansion over the limit", at + a - 1 + return nil + end + np =np+ 1 + parts[np] = rep + p = e +end + np =np+ 1 + parts[np] = sub(raw, p) + return table.concat(parts) + end + + local function lookupNs(prefix) +for d = depth, 1, -1 do + local m = nsStack[d] + if m and m[prefix] ~= nil then + return m[prefix] + end + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil + end + + -- a quoted literal at p -> its content, the position after it | nil + local function literal(p) +local q = byte(s, p) + if q ~= 34 and q ~= 39 then + return nil, p + end + local e = find(s, q == 34 and'"' or"'", p + 1, true) + if not e then + return nil, p + end + return sub(s, p + 1, e - 1), e + 1 + end + -- an ExternalID (SYSTEM "sys" | PUBLIC "pub" "sys") at p -> publicId, systemId, next | nil + local function externalId(p) +local kw = sub(s, p, p + 5) + if kw == "SYSTEM" then + local q = (match(s, "^[ \t\n]+()", p + 6) ) +if not q then + return nil, nil, nil + end + local sys, e = literal(q) + if not sys then + return nil, nil, nil + end + return "", sys, e + elseif kw == "PUBLIC" then + local q = (match(s, "^[ \t\n]+()", p + 6) ) +if not q then + return nil, nil, nil + end + local pub, e = literal(q) + if not pub or find(pub, "[^ \r\n%w%-'()+,./:=?;!*#@$_%%]") then + return nil, nil, nil + end + local r = (match(s, "^[ \t\n]+()", e) ) +if not r then + return nil, nil, nil + end + local sys, e2 = literal(r) + if not sys then + return nil, nil, nil + end + return pub, sys, e2 + end + return nil, nil, nil + end + -- check an entity value's references and expand its character references (the rest expand when used) + local function entityValue(v) +if find(v, "%", 1, true) then + return nil -- parameter-entity references are not allowed in the internal subset's markup + end + local p = 1 + local parts = {} + while true do + local a = find(v, "&", p, true) + if not a then + table.insert(parts, sub(v, p)) + break + end + table.insert(parts, sub(v, p, a - 1)) + local hex = match(v, "^&#x(%x+);", a) + local dec = match(v, "^&#(%d+);", a) + if hex or dec then + local cp = (tonumber(hex or dec, hex and 16 or 10) ) +if cp > 0x10FFFF or (cp < 0x20 and cp ~= 9 and cp ~= 10 and cp ~= 13) or (cp >= 0xD800 and cp <= 0xDFFF) then + return nil + end + table.insert(parts, utf8char(cp)) + p = ((find(v, ";", a, true) )) + 1 + else + local name = match(v, "^&([%a_:\128-\255][%w_:%.%-\128-\255]*);", a) + if not name then + return nil + end + table.insert(parts, "&" .. name .. ";") + p = a + #name + 2 + end + end + return table.concat(parts) + end + -- the DOCTYPE at i (just past "<!DOCTYPE"): its raw text and info { name, publicId, systemId, entities }; records + -- the internal subset's general entities. nil, message on bad syntax. + local function doctype() +local start = i + local p = (match(s, "^[ \t\n]+()", i) ) +if not p then + return nil, "bad DOCTYPE" + end + local name = match(s, NAME, p) + if not name then + return nil, "bad DOCTYPE name" + end + local info= { name = name, entities = {} } + p =p+ #name + local q = (match(s, "^[ \t\n]*()", p) ) +if q > p and (sub(s, q, q + 5) == "SYSTEM" or sub(s, q, q + 5) == "PUBLIC") then + local pub, sys, e = externalId(q) + if not pub then + return nil, "bad DOCTYPE external id" + end + info.publicId = (pub ~= "" and{pub }or{nil +})[1] info.systemId = sys + q = (match(s, "^[ \t\n]*()", e) ) +end + if byte(s, q) == 91 then -- the internal subset + q =q+ 1 + while true do + q = (match(s, "^[ \t\n]*()", q) ) +local c = byte(s, q) + if c == 93 then + q =q+ 1 + break + elseif c == 37 then -- %name; + local pe = match(s, "^%%[%a_:\128-\255][%w_:%.%-\128-\255]*;()", q) + if not pe then + return nil, "bad parameter-entity reference" + end + q = pe +elseif sub(s, q, q + 3) == "<!--" then + local e = find(s, "--", q + 4, true) + if not e or byte(s, e + 2) ~= 62 then + return nil, e and"'--' inside a comment" or"unterminated comment in DOCTYPE" + end + q = e + 3 + elseif sub(s, q, q + 1) == "<?" then + local target = match(s, NAME, q + 2) + local e = find(s, "?>", q + 2, true) + if not target or not e or lower(target) == "xml" then + return nil, "bad processing instruction in DOCTYPE" + end + q = e + 2 + elseif sub(s, q, q + 7) == "<!ENTITY" then + local r = (match(s, "^[ \t\n]+()", q + 8) ) +if not r then + return nil, "bad ENTITY declaration" + end + local isPe = false + if byte(s, r) == 37 then + isPe = true + r = (match(s, "^[ \t\n]+()", r + 1) ) +if not r then + return nil, "bad ENTITY declaration" + end + end + local ename = match(s, NAME, r) + if not ename then + return nil, "bad ENTITY name" + end + r = (match(s, "^[ \t\n]+()", r + #ename) ) +if not r then + return nil, "bad ENTITY declaration" + end + local val, e = literal(r) + if val then + local v = entityValue(val) + if not v then + return nil, "bad ENTITY value" + end + if not isPe and entities[ename] == nil then + entities[ename] = v + info.entities[ename] = v + end + r = e + else + local pub, _, e2 = externalId(r) + if not pub then + return nil, "bad ENTITY declaration" + end + r = e2 +local nd = match(s, "^[ \t\n]+NDATA[ \t\n]+()", r) + if nd then + local nn = match(s, NAME, nd) + if not nn or isPe then + return nil, "bad NDATA" + end + r = nd + #nn + end + if not isPe then + external[ename] = true + end + end + r = (match(s, "^[ \t\n]*()", r) ) +if byte(s, r) ~= 62 then + return nil, "bad ENTITY declaration" + end + q = r + 1 + elseif sub(s, q, q + 8) == "<!ELEMENT" or sub(s, q, q + 8) == "<!ATTLIST" or sub(s, q, q + 9) == "<!NOTATION" then + local kw = (match(s, "^<!(%u+)", q) ) +local r = (match(s, "^[ \t\n]+()", q + 2 + #kw) ) +if not r or not match(s, NAME, r) then + return nil, "bad " .. kw .. " declaration" + end + -- skip to the closing '>' outside quotes + while true do + local c2 = byte(s, r) + if c2 == nil then + return nil, "unterminated DOCTYPE" + elseif c2 == 34 or c2 == 39 then + local e = find(s, c2 == 34 and'"' or"'", r + 1, true) + if not e then + return nil, "unterminated DOCTYPE" + end + r = e + 1 + elseif c2 == 62 then + break + elseif c2 == 60 then + return nil, "bad " .. kw .. " declaration" + else + r =r+ 1 + end + end + q = r + 1 + elseif c == nil then + return nil, "unterminated DOCTYPE" + else + return nil, "bad markup in the DOCTYPE" + end + end + q = (match(s, "^[ \t\n]*()", q) ) +end + if byte(s, q) ~= 62 then + return nil, q > n and"unterminated DOCTYPE" or"bad DOCTYPE" + end + i = q + 1 + return sub(s, start, q - 1), info + end + + return function() +if dead then + return nil + end + if pending then + local ev = pending + pending = nil + depth =depth- 1 + if depth == 0 then + rootDone = true + end + return "end", ev[1] + end + while true do +local __DARKLUA_CONTINUE_9=false repeat if i > n then + dead = true + if depth > 0 then + return "error", "unclosed element <" .. stack[depth] .. ">", n + end + if not rootSeen then + return "error", "no root element", n + end + return nil + end + local c = byte(s, i) + if c ~= 60 then -- text + local e = find(s, "<", i, true) or (n + 1) + local raw = sub(s, i, e - 1) + local start = i + i = e + local wsOnly = not find(raw, "[^ \t\n]") + if depth == 0 then + if not wsOnly then + return fail(rootDone and"text after the root element" or"text before the root element", start) + end + else + if find(raw, "]]>", 1, true) then + return fail("']]>' in text", start + ((find(raw, "]]>", 1, true) )) - 1) + end + local bad = find(raw, "[%z\1-\8\11\12\14-\31]") + if bad then + return fail("control character in text", start + bad - 1) + end + if not wsOnly or keepWs or preserve[depth] then + local t = decode(raw, start, 0) + if not t then + return fail(errMsg , errAt) + end + return "text", t + end + end +__DARKLUA_CONTINUE_9=true break + end + local c2 = byte(s, i + 1) + if c2 == 47 then -- </ + local name = match(s, NAME, i + 2) + if not name then + return fail("bad end tag", i) + end + local p = (match(s, "^[ \t\n]*()", i + 2 + #name) ) +if byte(s, p) ~= 62 then + return fail(p > n and"unterminated end tag" or"bad end tag", p) + end + if depth == 0 or stack[depth] ~= name then + return fail("mismatched end tag </" .. name .. ">" .. ((depth > 0 and((" (open: <" .. stack[depth] .. ">)" ))or(""))), i) + end + i = p + 1 + stack[depth] = nil + nsStack[depth] = nil + preserve[depth] = nil + depth =depth- 1 + if depth == 0 then + rootDone = true + end + return "end", name + elseif c2 == 33 then -- <! + if sub(s, i + 2, i + 3) == "--" then + local e = find(s, "--", i + 4, true) + if not e then + return fail("unterminated comment", i) + end + if byte(s, e + 2) ~= 62 then + return fail(e + 2 > n and"unterminated comment" or"'--' inside a comment", e) + end + local text = sub(s, i + 4, e - 1) + i = e + 3 + return "comment", text + elseif sub(s, i + 2, i + 8) == "[CDATA[" then + if depth == 0 then + return fail("CDATA outside the root element", i) + end + local e = find(s, "]]>", i + 9, true) + if not e then + return fail("unterminated CDATA section", i) + end + local text = sub(s, i + 9, e - 1) + i = e + 3 + return "cdata", text + elseif sub(s, i + 2, i + 8) == "DOCTYPE" then + if rootSeen then + return fail("DOCTYPE after the root element", i) + end + local at = i + i =i+ 9 + local raw, info = doctype() + if not raw then + return fail(info, at) + end + return "doctype", raw, info + end + return fail("bad markup declaration", i) + elseif c2 == 63 then -- <? + local target = match(s, NAME, i + 2) + if not target then + return fail("bad processing instruction", i) + end + local e = find(s, "?>", i + 2 + #target, true) + if not e then + return fail("unterminated processing instruction", i) + end + local data = sub(s, i + 2 + #target, e - 1) + if data ~= "" and not find(data, "^[ \t\n]") then + return fail("bad processing instruction", i) + end + data = (match(data, "^[ \t\n]*(.-)$") ) +local at = i + i = e + 2 + if lower(target) == "xml" then + if target ~= "xml" or at ~= 1 then + return fail("misplaced XML declaration", at) + end + local decl = xmlDecl(data) + if not decl then + return fail("bad XML declaration", at) + end + return "decl", decl + end + return "pi", target, data + end + -- a start tag + local name = match(s, NAME, i + 1) + if not name then + return fail(i + 1 > n and"truncated tag" or"bad tag name", i + 1) + end + if rootDone then + return fail("a second root element <" .. name .. ">", i) + end + local at = i + local p = i + 1 + #name + local attrs = Types.object() + local order = {} + local closed = false + local nsMap= nil + while true do + local q = (match(s, "^[ \t\n]*()", p) ) +local cc = byte(s, q) + if cc == 62 then + p = q + 1 + break + elseif cc == 47 then + if byte(s, q + 1) ~= 62 then + return fail("bad tag end", q) + end + p = q + 2 + closed = true + break + elseif cc == nil then + return fail("truncated tag", q) + end + if q == p then + return fail("missing whitespace between attributes", q) + end + local an = match(s, NAME, q) + if not an then + return fail("bad attribute name", q) + end + local r = (match(s, "^[ \t\n]*=[ \t\n]*()", q + #an) ) +if not r then + return fail("attribute " .. an .. " without a value", q) + end + local qc = byte(s, r) + if qc ~= 34 and qc ~= 39 then + return fail("unquoted attribute value", r) + end + local e = find(s, qc == 34 and'"' or"'", r + 1, true) + if not e then + return fail("unterminated attribute value", r) + end + local raw = sub(s, r + 1, e - 1) + if find(raw, "<", 1, true) then + return fail("'<' in an attribute value", r) + end + if find(raw, "[%z\1-\8\11\12\14-\31]") then + return fail("control character in an attribute value", r) + end + local v = decode(raw, r + 1, 0) + if not v then + return fail(errMsg , errAt) + end + if find(raw, "[\t\n]") then + -- attribute-value normalization: literal tab / newline become spaces (references stay) + v = (decode((gsub(raw, "[\t\n]", " ")), r + 1, 0) ) +end + if attrs[an] ~= nil then + return fail("duplicate attribute " .. an, q) + end + attrs[an] = v + table.insert(order, an) + if nsOn then + if an == "xmlns" or sub(an, 1, 6) == "xmlns:" then + local m= nsMap or {} + nsMap = m + m[an == "xmlns" and"" or sub(an, 7)] = v + end + end + p = e + 1 + end + Types.object(attrs, order) + i = p + depth =depth+ 1 + if depth > maxDepth then + return fail("nested deeper than " .. maxDepth, at) + end + stack[depth] = name + nsStack[depth] = nsMap +local sp = attrs["xml:space"] + preserve[depth] = sp == "preserve" and true or(sp == "default" and{false }or{(preserve[depth - 1] or false) +})[1] rootSeen = true + local uri= nil + if nsOn then + local prefix = match(name, "^([^:]*):") or "" + uri = lookupNs(prefix) + if uri == "" then + uri = nil + end + if prefix ~= "" and uri == nil then + return fail("undeclared namespace prefix " .. prefix, at) + end + end + if closed then + stack[depth] = nil + nsStack[depth] = nil + preserve[depth] = nil + pending = { name } -- depth goes down when the queued "end" is returned + end + return "start", name, attrs, uri +until true if not __DARKLUA_CONTINUE_9 then break end end + end +end + +-- lookup(nsMaps...) helper for the DOM: the namespace URI of prefix, walking an element's ancestors +function Parse.resolve(node, prefix) +local p = node + local key = prefix == "" and"xmlns" or"xmlns:" .. prefix + while p do + local a = p.attrs + if a and a[key] ~= nil then + local v = a[key] + return (v == "" and{nil }or{v +})[1] end + p = p.parent + end + if prefix == "xml" then + return "http://www.w3.org/XML/1998/namespace" + end + return nil +end + +return Parse +end +__FILES["codecs/video/Dsp"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. +-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added +-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never +-- throws (the caller keeps offsets in range). +-- +-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg +-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then +-- columns, with every sparse-input special case of the original kept, because several of them use merged constants +-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that +-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order +-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for +-- coefficients in the MPEG range), and the put / add clamping fused into the last pass. +-- +-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it +-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) +-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block +-- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+) +-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) +local Dsp = {} + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local rshift = bit32.rshift + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range +-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, plus a prediction of up to 255 +local COFF = 40000 +local CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end +Dsp.CLAMP = CLAMP +Dsp.COFF = COFF + +-- ------------------------------------------------------------------------------------------------ IDCT +function Dsp.idct(blk, dst, off, stride, add) + local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 + local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 + local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0 + -- pass 1: rows, scaled up by 2^PASS1_BITS + for r = 0, 224, 32 do + local d0 = readi32(blk, r) + local d1 = readi32(blk, r + 4) + local d2 = readi32(blk, r + 8) + local d3 = readi32(blk, r + 12) + local d4 = readi32(blk, r + 16) + local d5 = readi32(blk, r + 20) + local d6 = readi32(blk, r + 24) + local d7 = readi32(blk, r + 28) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + if d0 ~= 0 then + local v = d0 * 4 + writei32(blk, r, v) + writei32(blk, r + 4, v) + writei32(blk, r + 8, v) + writei32(blk, r + 12, v) + writei32(blk, r + 16, v) + writei32(blk, r + 20, v) + writei32(blk, r + 24, v) + writei32(blk, r + 28, v) + end + else + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z4 = d5 + d1 + z5 = (d7 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 = z2 + z3 + tmp3 =tmp3+ (z1 + z4 +) else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ z3 + tmp1 =tmp1+ z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 = z2 + z4 + tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 =tmp0+ z3 + tmp1 = z2 + z5 + tmp2 =tmp2+ z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 =tmp0+ z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 =tmp3+ z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 = z1 + z3 + tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 =tmp1+ z2 + tmp2 =tmp2+ z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 =tmp1+ z4 + tmp2 = z2 + z5 + tmp3 =tmp3+ z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 =tmp2+ z5 + tmp3 =tmp3+ z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, r, math.floor((tmp10 + tmp3 + 1024) / 2048)) + writei32(blk, r + 28, math.floor((tmp10 - tmp3 + 1024) / 2048)) + writei32(blk, r + 4, math.floor((tmp11 + tmp2 + 1024) / 2048)) + writei32(blk, r + 24, math.floor((tmp11 - tmp2 + 1024) / 2048)) + writei32(blk, r + 8, math.floor((tmp12 + tmp1 + 1024) / 2048)) + writei32(blk, r + 20, math.floor((tmp12 - tmp1 + 1024) / 2048)) + writei32(blk, r + 12, math.floor((tmp13 + tmp0 + 1024) / 2048)) + writei32(blk, r + 16, math.floor((tmp13 - tmp0 + 1024) / 2048)) + end + end + -- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3) + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 =tmp1+ (z2 + z4 +) tmp2 = z2 + z3 + tmp3 =tmp3+ (z1 + z4 +) else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ z3 + tmp1 =tmp1+ z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 =tmp0+ (z1 + z3 +) tmp1 = z2 + z4 + tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 =tmp0+ z3 + tmp1 = z2 + z5 + tmp2 =tmp2+ z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 =tmp0+ z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 =tmp3+ z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 =z3+ z5 + z4 =z4+ z5 + tmp0 = z1 + z3 + tmp1 =tmp1+ (z2 + z4 +) tmp2 =tmp2+ (z2 + z3 +) tmp3 =tmp3+ (z1 + z4 +) else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 =tmp1+ z2 + tmp2 =tmp2+ z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 =tmp1+ z4 + tmp2 = z2 + z5 + tmp3 =tmp3+ z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 =tmp2+ z5 + tmp3 =tmp3+ z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, c, math.floor((tmp10 + tmp3 + 131072) / 262144)) + writei32(blk, c + 224, math.floor((tmp10 - tmp3 + 131072) / 262144)) + writei32(blk, c + 32, math.floor((tmp11 + tmp2 + 131072) / 262144)) + writei32(blk, c + 192, math.floor((tmp11 - tmp2 + 131072) / 262144)) + writei32(blk, c + 64, math.floor((tmp12 + tmp1 + 131072) / 262144)) + writei32(blk, c + 160, math.floor((tmp12 - tmp1 + 131072) / 262144)) + writei32(blk, c + 96, math.floor((tmp13 + tmp0 + 131072) / 262144)) + writei32(blk, c + 128, math.floor((tmp13 - tmp0 + 131072) / 262144)) + end + -- put / add, clamped + for r = 0, 224, 32 do + local p0 = readi32(blk, r) + COFF + local p1 = readi32(blk, r + 4) + COFF + local p2 = readi32(blk, r + 8) + COFF + local p3 = readi32(blk, r + 12) + COFF + local p4 = readi32(blk, r + 16) + COFF + local p5 = readi32(blk, r + 20) + COFF + local p6 = readi32(blk, r + 24) + COFF + local p7 = readi32(blk, r + 28) + COFF + if add then + p0 =p0+ readu8(dst, off) + p1 =p1+ readu8(dst, off + 1) + p2 =p2+ readu8(dst, off + 2) + p3 =p3+ readu8(dst, off + 3) + p4 =p4+ readu8(dst, off + 4) + p5 =p5+ readu8(dst, off + 5) + p6 =p6+ readu8(dst, off + 6) + p7 =p7+ readu8(dst, off + 7) + end + writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216) + writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216) + off =off+ stride + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT +-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +function Dsp.fill(dst, off, stride, v, add) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off =off+ stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off =off+ stride + end + end +end + +-- ------------------------------------------------------------------------------------------------ motion +-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst +-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what +-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for +-- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits +-- each byte into its low 2 bits and high 6 bits so no lane overflows. +function Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) + for _ = 1, h do + for i = 0, w - 4, 4 do + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff =sOff+ sStride + dOff =dOff+ dStride + end +end + +-- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: +-- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst. +function Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) + if hx == 0 and hy == 0 then + Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) + return + end + local dx = (hx == 0 and{sStride }or{1 -- the second sample of a two-tap average +})[1] for _ = 1, h do + for i = 0, w - 4, 4 do + local p + if hx == 0 or hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + dx) + p = band(a, b) + rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x01010101 + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) + end + writeu32(dst, dOff + i, p) + end + sOff =sOff+ sStride + dOff =dOff+ dStride + end +end + +-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to +-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture +-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +Dsp.EDGE_STRIDE = 32 +Dsp.EDGE_SIZE = 32 * 34 + 4 +function Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) + for j = 0, h do + local sy = y + j + sy = sy < 0 and 0 or(sy >= ph and((ph - 1 ))or(sy +)) local row = base + sy * stride + local o = j * 32 + for i = 0, w do + local sx = x + i + sx = sx < 0 and 0 or(sx >= pw and((pw - 1 ))or(sx +)) writeu8(out, o + i, readu8(src, row + sx)) + end + end +end + +return Dsp +end +__FILES["codecs/video/H263"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. +-- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is +-- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal +-- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures, +-- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter +-- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP +-- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...). +-- +-- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1) +-- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned) +-- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601) +-- local img, err = dec:image(packetData) -- both at once +-- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ... +-- dec:reset() -- after a seek: wait for the next I picture +-- +-- Nothing here throws: bad arguments and bad data come back as nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local D = __include("codecs/video/H263/Decoder") + +local H263 = {} + +H263.PICTURE_I = 1 +H263.PICTURE_P = 2 + + + + + + + + + + + + + + + + + + + + + + + + +local Decoder = {} +Decoder.__index = Decoder + + + +function H263.new(opts) +local o= (type(opts) == "table" and{opts }or{{} +})[1] local flv = o.flv == true + local maxPixels = (type(o.maxPixels) == "number" and o.maxPixels > 0 and{o.maxPixels }or{nil +})[1] return setmetatable({ _core = D.new(flv, maxPixels), _flv = flv, _count = 0, stats = { pictures = 0, errors = 0 } }, Decoder) +end + +local function span(data, off, len) +local b +if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return nil, 0, 0 + end + local total = buffer.len(b) + local o = math.floor(tonumber(off) or 0) + if o < 0 or o > total then + return nil, 0, 0 + end + local n = math.floor(tonumber(len) or (total - o)) + if n < 0 or o + n > total then + return nil, 0, 0 + end + return b, o, n +end + +-- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged +-- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them). +function Decoder.decode(self, data, off, len) +local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string and a valid range") + end + local core = self._core + local s, msg = core.decode(b, o, n) + self.stats.pictures = core.state.pictures + self.stats.errors = core.state.errors + if not s then + return nil, Err.from(msg or "bad picture") + end + self._count =self._count+ 1 + return { + width = s.w, + height = s.h, + y = s.y, + cb = s.cb, + cr = s.cr, + stride = s.ls, + pictureType = s.ptype, + keyframe = s.ptype == 1, + disposable = s.disposable, + temporalReference = s.tr, + index = self._count, + flv = self._flv, + }, nil +end + +-- decode + frameImage +function Decoder.image(self, data, off, len) +local f, err = self:decode(data, off, len) + if not f then + return nil, err + end + return H263.frameImage(f), nil +end + +-- Forgets the reference picture (after a seek: P pictures fail until the next I picture). +function Decoder.reset(self) + self._core.reset() +end + +-- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x +-- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame +function H263.frameImage(frame) +if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, ls = frame.width, frame.height, frame.stride + if type(w) ~= "number" or type(h) ~= "number" or type(ls) ~= "number" or w < 1 or h < 1 or ls < w then + return nil + end + local cw, ch, cs = math.floor((w + 1) / 2), math.floor((h + 1) / 2), math.floor(ls / 2 +) if buffer.len(frame.y) < ls * h or buffer.len(frame.cb) < cs * ch or buffer.len(frame.cr) < cs * ch then + return nil + end + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * ls, w) + end + local o = w * h + for y = 0, ch - 1 do + buffer.copy(px, o + y * cw, frame.cb, y * cs, cw) + buffer.copy(px, o + cw * ch + y * cw, frame.cr, y * cs, cw) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { + format = frame.flv and"flv1" or"h263", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + disposable = frame.disposable, + } + return img +end + +-- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err: +-- the first picture header in the data, without decoding (containers use it for the track size) +function H263.header(data, off, len, flv) +local b, o, n = span(data, off, len) + if not b then + return nil, Err.new(Err.ARG, "header: expected a buffer or string and a valid range") + end + local h, msg = D.header(b, o, n, flv == true, nil) + if not h then + return nil, Err.from(msg or "bad picture header") + end + return h, nil +end + +return H263 +end +__FILES["codecs/video/H263/Decoder"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T +-- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). +-- +-- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats, +-- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers +-- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion +-- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the +-- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular +-- slices) and the extended escape of Annex T. Sorenson Spark +-- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit +-- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message): +-- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures, +-- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced +-- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape). +-- +-- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL| +-- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read +-- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int` +-- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors). +-- +-- local core = D.new(flv, maxPixels) +-- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding) +-- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned) +-- core.reset() -- forget the reference (after a seek) +local Tb = __include("codecs/video/H263/Tables") +local Dsp = __include("codecs/video/Dsp") + +local readu8 = buffer.readu8 +local readu32 = buffer.readu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local bfill = buffer.fill +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc +local mcNoRound = Dsp.mcNoRound +local edge = Dsp.edge + +local MCBPC_I = Tb.MCBPC_I +local MCBPC_P = Tb.MCBPC_P +local CBPY = Tb.CBPY +local MVD = Tb.MVD +local TCOEF = Tb.TCOEF +local ZIGZAG = Tb.ZIGZAG +local DQUANT = Tb.DQUANT +local STUFFING = Tb.STUFFING +local ESCAPE = Tb.ESCAPE + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2.5 KB, the end check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +-- the PLUSPTYPE options that persist while UFEP = 0 +-- ------------------------------------------------------------------------------------------------ header +-- the length of a slice's MBA field for a picture of n macroblocks (table K.2) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function D.mbaBits(n) +return n <= 48 and 6 or(n <= 99 and 7 or(n <= 396 and 9 or(n <= 1584 and 11 or(n <= 6336 and 13 or 14 +))))end + +-- n (<= 24) bits at bit position p of buf, zeros past endByte +local function bitsAt(buf, endByte, p, n) +local v = 0 + for k = p, p + n - 1 do + local byte = rshift(k, 3) + local b = (byte < endByte and{(readu8(buf, byte) )}or{0 +})[1] v = v * 2 + band(rshift(b, 7 - band(k, 7)), 1) + end + return v +end + +-- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: +-- 17 bits 0..01 and version 0 / 1), or -1 +local function findStart(buf, off, len, flv) +local mask = flv and 0xF8 or 0xFC + for i = off, off + len - 3 do + if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then + return i + end + end + return -1 +end + +-- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in +-- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them) +function D.header(buf, off, len, flv, opp) +if off < 0 or len < 0 or off + len > buffer.len(buf) then + return nil, "bad range" + end + local s = findStart(buf, off, len, flv) + if s < 0 then + return nil, "no picture start code" + end + local e = off + len + local p = s * 8 + local function bits(n) +local v = bitsAt(buf, e, p, n) + p =p+ n + return v + end + local h= { + flv = flv, + version = 0, + tr = 0, + width = 0, + height = 0, + ptype = 1, + disposable = false, + quant = 1, + umv = false, + umvPlus = false, + rounding = 0, + plus = false, + ss = false, + cpm = false, + deblock = false, + bitPos = 0, + } + if flv then + bits(17) + h.version = bits(5) + h.tr = bits(8) + local size = bits(3) + if size == 0 then + h.width, h.height = bits(8), bits(8) + elseif size == 1 then + h.width, h.height = bits(16), bits(16) + elseif size <= 6 then + local d = Tb.FLV_SIZES[size] + h.width, h.height = d[1], d[2] + else + return nil, "reserved picture size" + end + local t = bits(2) + if t == 3 then + return nil, "reserved picture type" + end + h.ptype = t == 0 and 1 or 2 + h.disposable = t == 2 + h.deblock = bits(1) == 1 + h.quant = bits(5) + else + bits(22) + h.tr = bits(8) + if bits(1) ~= 1 or bits(1) ~= 0 then + return nil, "bad PTYPE" + end + bits(3) -- split screen, document camera, freeze picture release + local format = bits(3) + if format >= 1 and format <= 5 then + local d = Tb.FORMATS[format] + h.width, h.height = d[1], d[2] + h.ptype = bits(1) + 1 + h.umv = bits(1) == 1 + local sac, ap, pb = bits(1), bits(1), bits(1) + if sac == 1 then + return nil, "unsupported: syntax-based arithmetic coding" + elseif ap == 1 then + return nil, "unsupported: advanced prediction mode" + elseif pb == 1 then + return nil, "unsupported: PB-frames" + end + h.quant = bits(5) + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + elseif format == 7 then + h.plus = true + local ufep = bits(3) + local o +if ufep == 1 then + local f = bits(3) + local pcf, umv = bits(1) == 1, bits(1) == 1 + local names= { "syntax-based arithmetic coding", "advanced prediction", "advanced intra coding", + "deblocking filter", "slice structure", "reference picture selection", "independent segment decoding", + "alternative inter VLC", "modified quantisation" } + local unsup= nil + local ss = false + for i = 1, 9 do + if bits(1) == 1 then + if i == 5 then + ss = true + elseif not unsup then + unsup = names[i] + end + end + end + bits(4) -- 1 000 + o = { format = f, customPcf = pcf, umv = umv, ss = ss, options = unsup, width = 0, height = 0 } + elseif ufep == 0 and opp then + o = opp + else + return nil, ufep == 0 and"PLUSPTYPE without the options (UFEP 0 first)" or"bad UFEP" + end + local t = bits(3) + if t ~= 0 and t ~= 1 then + return nil, "unsupported: " .. ({ "", "improved PB-frames", "B-pictures", "EI-pictures", "EP-pictures", "reserved", "reserved" })[t] .. " picture type" + end + h.ptype = t + 1 + local rpr, rru = bits(1), bits(1) + h.rounding = bits(1) + bits(3) -- 0 0 1 + if rpr == 1 then + return nil, "unsupported: reference picture resampling" + elseif rru == 1 then + return nil, "unsupported: reduced-resolution update" + end + local unsupported = o.options + if unsupported ~= nil then + return nil, "unsupported: " .. unsupported + end + h.cpm = bits(1) == 1 + if h.cpm then + bits(2) + end + if ufep == 1 then + if o.format == 6 then + local par = bits(4) + o.width = (bits(9) + 1) * 4 + bits(1) + o.height = bits(9) * 4 + h.aspect = par + if par == 15 then + h.aspectNum, h.aspectDen = bits(8), bits(8) + end + elseif o.format >= 1 and o.format <= 5 then + local d = Tb.FORMATS[o.format] + o.width, o.height = d[1], d[2] + else + return nil, "bad source format " .. o.format + end + if o.customPcf then + bits(8) -- clock conversion code, clock divisor + end + end + if o.customPcf then + bits(2) -- ETR + end + if ufep == 1 and o.umv then + if bits(1) == 0 then + bits(1) + end + end + if ufep == 1 and o.ss then + if bits(1) == 1 then + return nil, "unsupported: rectangular slices" + end + bits(1) -- arbitrary slice ordering (slices carry their address) + end + h.width, h.height = o.width, o.height + h.umvPlus = o.umv + h.ss = o.ss + h.opp = o + else + return nil, "bad source format " .. format + end + h.quant = (h.plus and{(bits(5) )}or{h.quant +})[1] end + -- PEI / PSPARE + local guard = 0 + while bits(1) == 1 do + bits(8) + guard =guard+ 1 + if guard > 256 then + return nil, "PSPARE without end" + end + end + if h.quant == 0 then + return nil, "QUANT 0" + end + if h.width < 1 or h.height < 1 then + return nil, "empty picture size" + end + if h.ss then + -- the first slice's SEPB1, MBA and SEPB2 + bits(1) + bits(D.mbaBits(math.floor((h.width + 15) / 16 )* (math.floor((h.height + 15) / 16)))) + bits(1) + end + if p > e * 8 then + return nil, "truncated picture header" + end + h.bitPos = p + return h, nil +end +-- ------------------------------------------------------------------------------------------------ decoder + + + + + + + + + + + + + + + +function D.new(flv, maxPixels) +local state = { + width = 0, + height = 0, + pictures = 0, + errors = 0, + header = nil , + opp = nil , + maxPixels = maxPixels or 4096 * 2304, + } + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local endBits = 0 + local pos = 0 + local err = false + -- picture + local W, H = 0, 0 + local mbW, mbH = 0, 0 + local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights + local stores= {} + local ref= nil + local curY, curCb, curCr = data, data, data + local refY, refCb, refCr = data, data, data + local quant = 1 + local escFlv = false -- Sorenson version 1 escapes + local longMv = false + local umvPlus = false + local mcf = mc + local mvX, mvY = {} , {} +local upX, upY = {} , {} +local blk = buffer.create(256) + local EDGE = buffer.create(Dsp.EDGE_SIZE) + + local function read(n) +local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + pos =pos+ n + return rshift(w, 32 - n) + end + + local function peek32() +local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + local function vlc(lut, k) +local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos =pos+ l + return band(e, 0xFFFF) + end + + local function alloc(w, h) + W, H = w, h + mbW, mbH = math.floor((w + 15) / 16), math.floor((h + 15) / 16 +) ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8 + stores = {} + for i = 1, 2 do + local y = buffer.create(ls * lh) + local cb = buffer.create(cs * chh) + local cr = buffer.create(cs * chh) + bfill(cb, 0, 128) + bfill(cr, 0, 128) + stores[i] = { y = y, cb = cb, cr = cr, ls = ls, w = w, h = h, ptype = 0, tr = 0, disposable = false } + end + mvX, mvY, upX, upY = table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0) + ref = nil + state.width, state.height = w, h + end + + -- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's + -- coefficients added to the prediction already in dst + local function block(intra, coded, dst, off, stride) +local i = 0 + local dcOnly = true + if intra then + local v = read(8) + if v == 255 then + v = 128 + end + writei32(blk, 0, v * 8) + i = 1 + end + if coded then + local q2 = quant * 2 + local qadd = (quant % 2 == 1 and{quant }or{(quant - 1 +)})[1] while true do + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(TCOEF, rshift(w, 20) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + local last, run, level + if v == ESCAPE then + -- the escape and the 25 (H.263) / 22 or 26 (Sorenson v1) bits after it, all inside w's next bits + if escFlv then + local is11 = band(rshift(w, 24), 1) + last = band(rshift(w, 23), 1) + run = band(rshift(w, 17), 63) + if is11 == 1 then + level = band(rshift(w, 6), 2047) + if level >= 1024 then + level =level- 2048 + end + pos =pos+ (7 + 1 + 7 + 11 +) else + level = band(rshift(w, 10), 127) + if level >= 64 then + level =level- 128 + end + pos =pos+ (7 + 1 + 7 + 7 +) end + else + last = band(rshift(w, 24), 1) + run = band(rshift(w, 18), 63) + level = band(rshift(w, 10), 255) + pos =pos+ (7 + 1 + 6 + 8 +) if level == 128 then + -- the extended escape (Annex T): 5 low bits, then 6 signed high bits + local x = read(11) + level = band(x, 31) + (rshift(x, 5) - (x >= 1024 and 64 or 0)) * 32 + elseif level > 128 then + level =level- 256 + end + end + if level == 0 then + err = true + return false + end + else + last = rshift(v, 10) + run = band(rshift(v, 4), 63) + level = band(v, 15) + if band(w, lshift(1, 31 - l)) ~= 0 then + level = -level + end + pos =pos+ (l + 1 +) end + i =i+ run + if i > 63 then + err = true + return false + end + local rec = (level > 0 and((level * q2 + qadd ))or((level * q2 - qadd +))) -- not the -2048..2047 saturation of H.263 6.2.1: ffmpeg does not saturate, and encoders write values + -- slightly past it (2055 = 68 * 30 + 15). +-2400 bounds the IDCT output to Dsp's clamp table. + if rec > 2400 then + rec = 2400 + elseif rec < -2400 then + rec = -2400 + end + local z = readu8(ZIGZAG, i) + if z ~= 0 then + dcOnly = false + end + writei32(blk, z * 4, rec) + i =i+ 1 + if last ~= 0 then + break + end + end + elseif not intra then + return true + end + if dcOnly then + local dc = readi32(blk, 0) + writei32(blk, 0, 0) + fillBlock(dst, off, stride, math.floor((dc + 4) / 8), not intra) + else + idct(blk, dst, off, stride, not intra) + bfill(blk, 0, 0, 256) + end + return true + end + + -- one motion vector component from its prediction (half samples) + local function motion(pred) +if umvPlus then + -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign + if read(1) == 1 then + return pred + end + local code = 2 + read(1) + local guard = 0 + while read(1) == 1 do + code = code * 2 + read(1) + guard =guard+ 1 + if guard > 14 then + err = true + return pred + end + end + local mag = math.floor(code / 2 +) return (code % 2 == 1 and((pred - mag ))or((pred + mag +))) end + local d = vlc(MVD, 12) + if d == 0 then + return pred + end + if read(1) == 1 then + d = -d + end + local v = pred + d + if longMv then + -- Annex D (baseline header): vectors up to +-31.5; the other value of a code pair only past +-16 + if pred < -31 and v < -63 then + v =v+ 64 + elseif pred > 32 and v > 63 then + v =v- 64 + end + return v + end + return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 + end + + -- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples + local function predict(col, row, mx, my) + local hx, hy = mx % 2, my % 2 + local sx, sy = col * 16 + math.floor((mx - hx) / 2), row * 16 + math.floor((my - hy) / 2 +) local dOff = row * 16 * ls + col * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > ls or sy + 16 + hy > lh then + edge(refY, ls, 0, sx, sy, 16, 16, ls, lh, EDGE) + mcf(EDGE, 32, 0, curY, ls, dOff, 16, 16, hx, hy, false) + else + mcf(refY, ls, sy * ls + sx, curY, ls, dOff, 16, 16, hx, hy, false) + end + -- chroma: the luma position halved, half-sample flags from the quarter positions rounded to halves + local cx, cy = math.floor(sx / 2), math.floor(sy / 2 +) local chx = (hx == 1 or (math.floor(mx / 2)) % 2 == 1 )and 1 or 0 + local chy = (hy == 1 or (math.floor(my / 2)) % 2 == 1 )and 1 or 0 + local cOff = row * 8 * cs + col * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > cs or cy + 8 + chy > chh then + edge(refCb, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCb, cs, cOff, 8, 8, chx, chy, false) + edge(refCr, cs, 0, cx, cy, 8, 8, cs, chh, EDGE) + mcf(EDGE, 32, 0, curCr, cs, cOff, 8, 8, chx, chy, false) + else + local so = cy * cs + cx + mcf(refCb, cs, so, curCb, cs, cOff, 8, 8, chx, chy, false) + mcf(refCr, cs, so, curCr, cs, cOff, 8, 8, chx, chy, false) + end + end + + -- a macroblock copied from the reference (not coded, or concealed); mid-grey without one + local function copyMb(col, row) + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if ref then + mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false) + mc(refCb, cs, co, curCb, cs, co, 8, 8, 0, 0, false) + mc(refCr, cs, co, curCr, cs, co, 8, 8, 0, 0, false) + else + fillBlock(curY, yo, ls, 128, false) + fillBlock(curY, yo + 8, ls, 128, false) + fillBlock(curY, yo + 8 * ls, ls, 128, false) + fillBlock(curY, yo + 8 * ls + 8, ls, 128, false) + fillBlock(curCb, co, cs, 128, false) + fillBlock(curCr, co, cs, 128, false) + end + end + + -- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of + -- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first + -- macroblock of a slice, whose left neighbour is outside). false on bad data. + local function macroblock(col, row, P, top, first) +if pos > endBits then + return false + end + if P and read(1) == 1 then + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return true + end + local lut = (P and{MCBPC_P }or{MCBPC_I +})[1] local m = vlc(lut, 9) + while m == STUFFING and not err do + if P and read(1) == 1 then -- stuffing is followed by a new COD in P-pictures + copyMb(col, row) + mvX[col + 1], mvY[col + 1] = 0, 0 + return pos <= endBits + end + if pos > endBits then + return false + end + m = vlc(lut, 9) + end + if err then + return false + end + local mtype, cbpc = math.floor(m / 4), m % 4 + if mtype == 2 then + err = true -- INTER4V needs advanced prediction (Annex F), which the header refused + return false + end + local intra = mtype >= 3 + local cbpy = vlc(CBPY, 6) + if err then + return false + end + if mtype == 1 or mtype == 4 then + quant = math.clamp(quant + DQUANT[read(2)], 1, 31) + end + local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 + if intra then + mvX[col + 1], mvY[col + 1] = 0, 0 + if not block(true, cbpy >= 8, curY, yo, ls) or not block(true, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(true, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(true, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(true, cbpc >= 2, curCb, co, cs) or not block(true, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + cbpy = 15 - cbpy + -- the vector prediction: the median of left, above and above right (outside or past the right edge: 0; the + -- first row of a picture / GOB: the left vector) + local ax = (col > 0 and not first and{mvX[col] }or{0 +})[1] local ay = (col > 0 and not first and{mvY[col] }or{0 +})[1] local px, py = ax, ay + if not top then + local bx, by = upX[col + 1], upY[col + 1] + local cx = (col + 1 < mbW and{upX[col + 2] }or{0 +})[1] local cy = (col + 1 < mbW and{upY[col + 2] }or{0 +})[1] px = math.max(math.min(ax, bx), math.min(math.max(ax, bx), cx)) + py = math.max(math.min(ay, by), math.min(math.max(ay, by), cy)) + end + local mx = motion(px) + local my = motion(py) + if umvPlus and mx - px == 1 and my - py == 1 then + pos =pos+ 1 -- start code emulation prevention bit + end + if err then + return false + end + mvX[col + 1], mvY[col + 1] = mx, my + predict(col, row, mx, my) + if not block(false, cbpy >= 8, curY, yo, ls) or not block(false, cbpy % 8 >= 4, curY, yo + 8, ls) + or not block(false, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(false, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls) + or not block(false, cbpc >= 2, curCb, co, cs) or not block(false, cbpc % 2 == 1, curCr, co, cs) then + return false + end + return pos <= endBits + end + + -- a GBSC / SSC (17 bits 0..01) next, after zero stuffing to a byte boundary or not: consumed, true + local function startCode() +local w = peek32() + if rshift(w, 15) ~= 1 then + local s = (8 - pos % 8) % 8 + if s == 0 or rshift(w, 32 - s) ~= 0 or rshift(lshift(w, s), 15) ~= 1 then + return false + end + pos =pos+ s + end + pos =pos+ 17 + return true + end + + -- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil + local function gobHeader(cpm) +if not startCode() then + return nil, nil + end + local gn = read(5) + if cpm then + read(2) + end + read(2) -- GFID + return gn, read(5) + end + + -- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil + local function sliceHeader(cpm, mbaBits, sepb2) +if not startCode() then + return nil, nil + end + read(1) -- SEPB1 + if cpm then + read(2) + end + local mba = read(mbaBits) + if sepb2 then + read(1) + end + local q = read(5) + read(3) -- SEPB3, GFID + return mba, q + end + + local function picture(hdr) +if hdr.width ~= W or hdr.height ~= H then + if hdr.width * hdr.height > state.maxPixels then + return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height + end + alloc(hdr.width, hdr.height) + end + local P = hdr.ptype == 2 + local r = ref + if P and not r then + return nil, "a P picture without a reference picture" + end + local cur = (stores[1] == r and{stores[2] }or{stores[1] +})[1] curY, curCb, curCr = cur.y, cur.cb, cur.cr + if r then + refY, refCb, refCr = r.y, r.cb, r.cr + end + quant = hdr.quant + escFlv = hdr.flv and hdr.version == 1 + longMv = hdr.umv + umvPlus = hdr.umvPlus + mcf = (hdr.rounding == 1 and{mcNoRound }or{mc +})[1] pos = hdr.bitPos + err = false + local gobRows = hdr.flv and 0 or(H <= 400 and 1 or(H <= 800 and 2 or 4 +)) local ss = hdr.ss + local total = mbW * mbH + local mbaBits = D.mbaBits(total) + local resync = 0 -- the first macroblock of the current GOB with a header / slice + local k = 0 + local failAt = -1 + mvX, upX = upX, mvX + mvY, upY = upY, mvY + while k < total do + local col, row = k % mbW, math.floor(k / mbW +) if k > 0 and (ss or (gobRows > 0 and col == 0 and row % gobRows == 0)) then + local at, q + if ss then + at, q = sliceHeader(hdr.cpm, mbaBits, total > 1584) + else + local gn, gq = gobHeader(hdr.cpm) + if gn then + at, q = gn == 0 and-1 or gn * gobRows * mbW, gq + end + end + if at and q then + if at < k or at >= total or q == 0 then + failAt = k + break + end + while k < at do -- macroblocks missing in between: copied + copyMb(k % mbW, math.floor(k / mbW)) + mvX[k % mbW + 1], mvY[k % mbW + 1] = 0, 0 + k =k+ 1 + if k % mbW == 0 then + mvX, upX = upX, mvX + mvY, upY = upY, mvY + end + end + col, row = k % mbW, math.floor(k / mbW +) resync, quant = k, q + end + end + -- above is outside for the slice's first mbW macroblocks (ffmpeg's first_slice_line: also the start of the + -- next row for a slice starting mid-row) + if not macroblock(col, row, P, k < resync + mbW, k == resync) then + failAt = k + break + end + k =k+ 1 + if k % mbW == 0 then + mvX, upX = upX, mvX + mvY, upY = upY, mvY + end + end + local msg= nil + if failAt >= 0 then + state.errors =state.errors+ 1 + msg = "bad macroblock data at macroblock " .. failAt + for k = failAt, mbW * mbH - 1 do + copyMb(k % mbW, math.floor(k / mbW)) + end + end + cur.ptype = hdr.ptype + cur.tr = hdr.tr + cur.disposable = hdr.disposable + if not hdr.disposable then + ref = cur + end + state.pictures =state.pictures+ 1 + return cur, msg + end + + local core = {} +core.state = state + + function core.decode(buf, off, len) +local hdr, herr = D.header(buf, off, len, flv, state.opp) + if not hdr then + state.errors =state.errors+ 1 + return nil, herr + end + state.header = hdr + if hdr.opp then + state.opp = hdr.opp + end + -- the data from the header on, with zero padding + local need = len + PAD + if buffer.len(data) < need then + data = buffer.create(need) + else + bfill(data, len, 0, PAD) + end + buffer.copy(data, 0, buf, off, len) + endBits = len * 8 + hdr.bitPos =hdr.bitPos- off * 8 + local s, msg = picture(hdr) + hdr.bitPos =hdr.bitPos+ off * 8 + return s, msg + end + + function core.reset() + ref = nil + end + + return core +end + +return D +end +__FILES["codecs/video/H263/Tables"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, +-- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of +-- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. +-- +-- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). +-- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, +-- 4 INTRA+Q), STUFFING for the stuffing code +-- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value) +-- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0) +-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code +local T = {} + +T.STUFFING = 255 +T.ESCAPE = 0xFFFF + +-- builds a K-bit flat table from { bits, value } pairs +local function flat(codes, k) +local lut = buffer.create(4 * 2 ^ k) + for _, c in __iter(codes) do + local bits= c[1] + local len = #bits + local code = (tonumber(bits, 2) ) +local shift = k - len + local first = code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, len * 65536 + c[2]) + end + end + return lut +end + +-- table 7: MCBPC for I-pictures (type 3 INTRA, 4 INTRA+Q; CBPC = Cb Cr) +T.MCBPC_I = flat({ + { "1", 3 * 4 + 0 }, + { "001", 3 * 4 + 1 }, + { "010", 3 * 4 + 2 }, + { "011", 3 * 4 + 3 }, + { "0001", 4 * 4 + 0 }, + { "000001", 4 * 4 + 1 }, + { "000010", 4 * 4 + 2 }, + { "000011", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 8: MCBPC for P-pictures +T.MCBPC_P = flat({ + { "1", 0 * 4 + 0 }, + { "0011", 0 * 4 + 1 }, + { "0010", 0 * 4 + 2 }, + { "000101", 0 * 4 + 3 }, + { "011", 1 * 4 + 0 }, + { "0000111", 1 * 4 + 1 }, + { "0000110", 1 * 4 + 2 }, + { "000000101", 1 * 4 + 3 }, + { "010", 2 * 4 + 0 }, + { "0000101", 2 * 4 + 1 }, + { "0000100", 2 * 4 + 2 }, + { "00000101", 2 * 4 + 3 }, + { "00011", 3 * 4 + 0 }, + { "00000100", 3 * 4 + 1 }, + { "00000011", 3 * 4 + 2 }, + { "0000011", 3 * 4 + 3 }, + { "000100", 4 * 4 + 0 }, + { "000000100", 4 * 4 + 1 }, + { "000000011", 4 * 4 + 2 }, + { "000000010", 4 * 4 + 3 }, + { "000000001", T.STUFFING }, +}, 9) + +-- table 13: CBPY (intra values 0..15) +do + local codes = { "0011", "00101", "00100", "1001", "00011", "0111", "000010", "1011", "00010", "000011", "0101", + "1010", "0100", "1000", "0110", "11" } + local list = {} + for i, c in __iter(codes) do + list[i] = { c, i - 1 } + end + T.CBPY = flat(list, 6) +end + +-- table 14: MVD magnitudes 0, 0.5, 1, ... 16 (in half samples 0..32); the sign bit is not part of these +do + local codes = { "1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", + "000001001", "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100", "0000001011", + "0000001010", "0000001001", "0000001000", "0000000111", "0000000110", "0000000101", "0000000100", "00000000111", + "00000000110", "00000000101", "00000000100", "00000000011", "00000000010", "000000000011", "000000000010" } + local list = {} + for i, c in __iter(codes) do + list[i] = { c, i - 1 } + end + T.MVD = flat(list, 12) +end + +-- table 16: TCOEF, per LAST and RUN the codes of levels 1, 2, ... (without the sign bit) +local TCOEF_LAST0= { + [0] = { "10", "1111", "010101", "0010111", "00011111", "000100101", "000100100", "0000100001", "0000100000", + "00000000111", "00000000110", "00000100000" }, + [1] = { "110", "010100", "00011110", "0000001111", "00000100001", "000001010000" }, + [2] = { "1110", "00011101", "0000001110", "000001010001" }, + [3] = { "01101", "000100011", "0000001101" }, + [4] = { "01100", "000100010", "000001010010" }, + [5] = { "01011", "0000001100", "000001010011" }, + [6] = { "010011", "0000001011", "000001010100" }, + [7] = { "010010", "0000001010" }, + [8] = { "010001", "0000001001" }, + [9] = { "010000", "0000001000" }, + [10] = { "0010110", "000001010101" }, + [11] = { "0010101" }, + [12] = { "0010100" }, + [13] = { "00011100" }, + [14] = { "00011011" }, + [15] = { "000100001" }, + [16] = { "000100000" }, + [17] = { "000011111" }, + [18] = { "000011110" }, + [19] = { "000011101" }, + [20] = { "000011100" }, + [21] = { "000011011" }, + [22] = { "000011010" }, + [23] = { "00000100010" }, + [24] = { "00000100011" }, + [25] = { "000001010110" }, + [26] = { "000001010111" }, +} +local TCOEF_LAST1= { + [0] = { "0111", "000011001", "00000000101" }, + [1] = { "001111", "00000000100" }, + [2] = { "001110" }, + [3] = { "001101" }, + [4] = { "001100" }, + [5] = { "0010011" }, + [6] = { "0010010" }, + [7] = { "0010001" }, + [8] = { "0010000" }, + [9] = { "00011010" }, + [10] = { "00011001" }, + [11] = { "00011000" }, + [12] = { "00010111" }, + [13] = { "00010110" }, + [14] = { "00010101" }, + [15] = { "00010100" }, + [16] = { "00010011" }, + [17] = { "000011000" }, + [18] = { "000010111" }, + [19] = { "000010110" }, + [20] = { "000010101" }, + [21] = { "000010100" }, + [22] = { "000010011" }, + [23] = { "000010010" }, + [24] = { "000010001" }, + [25] = { "0000000111" }, + [26] = { "0000000110" }, + [27] = { "0000000101" }, + [28] = { "0000000100" }, + [29] = { "00000100100" }, + [30] = { "00000100101" }, + [31] = { "00000100110" }, + [32] = { "00000100111" }, + [33] = { "000001011000" }, + [34] = { "000001011001" }, + [35] = { "000001011010" }, + [36] = { "000001011011" }, + [37] = { "000001011100" }, + [38] = { "000001011101" }, + [39] = { "000001011110" }, + [40] = { "000001011111" }, +} +do + local list = { { "0000011", T.ESCAPE } } + for last = 0, 1 do + local byRun = (last == 0 and{TCOEF_LAST0 }or{TCOEF_LAST1 +})[1] for run = 0, 40 do + local levels = byRun[run] + if levels then + for level, c in __iter(levels) do + table.insert(list, { c, last * 1024 + run * 16 + level }) + end + end + end + end + T.TCOEF = flat(list, 12) + T.TCOEF_COUNT = #list - 1 +end + +-- figure 14: the zigzag scan (scan index -> natural position) +T.ZIGZAG = buffer.create(64) +do + local zz = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, + 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, + 60, 61, 54, 47, 55, 62, 63 } + for i, v in __iter(zz) do + buffer.writeu8(T.ZIGZAG, i - 1, v) + end +end + +-- table 12: DQUANT (2 bits) -> the change of QUANT +T.DQUANT = { [0] = -1, -2, 1, 2 } + +-- source formats 1..5 (sub-QCIF, QCIF, CIF, 4CIF, 16CIF): width, height +T.FORMATS = { { 128, 96 }, { 176, 144 }, { 352, 288 }, { 704, 576 }, { 1408, 1152 } } + +-- Sorenson Spark picture sizes 2..6 +T.FLV_SIZES = { [2] = { 352, 288 }, [3] = { 176, 144 }, [4] = { 128, 96 }, [5] = { 320, 240 }, [6] = { 160, 120 } } + +return T +end +__FILES["codecs/video/H264"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the +-- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the +-- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the +-- reference decoder (checked against ffmpeg per frame). +-- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and +-- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion +-- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8 +-- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and +-- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline, +-- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their +-- macroblocks concealed (copied from the latest reference picture). +-- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8, +-- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers +-- (their NAL units are ignored). +-- +-- local H264 = require("rosetta.codecs.video.H264") +-- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) +-- for _, au in accessUnits do +-- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } +-- end +-- local rest = dec:flush() -- the frames still held for reordering +-- +-- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135 +-- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default +-- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and +-- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau). +-- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices +-- concealed (dec.errors counts them, dec.lastError says why). +local Err = __include("core/Err") +local Types = __include("Types") +local Bitstream = __include("codecs/video/H264/Bitstream") +local Decoder = __include("codecs/video/H264/Decoder") +local Params = __include("codecs/video/H264/Params") + +local H264 = {} + + + + + + + + + + + + + + + + + + +local DecoderMeta = {} +DecoderMeta.__index = DecoderMeta + + + +local function toBuffer(data) +if type(data) == "buffer" then + return data + elseif type(data) == "string" then + return buffer.fromstring(data) + end + return nil +end + +local function status(self) +local st = self.state + self.errors = st.errors + self.lastError = st.lastError + if st.fatal then + local m = st.fatal + if string.sub(m, 1, 7) == "limit: " then + return Err.new(Err.LIMIT, string.sub(m, 8)) + end + return Err.new(Err.CORRUPT, m) + end + if st.unsupported then + return Err.new(Err.UNSUPPORTED, st.unsupported) + end + return nil +end + +-- newDecoder(opts?) -> H264Decoder | nil, Err +function H264.newDecoder(opts) +local o = opts or {} + if type(o) ~= "table" then + return nil, Err.new(Err.ARG, "newDecoder: options must be a table") + end + local st = Decoder.new(o ) + local self = setmetatable({ state = st, lengthSize = o.lengthSize, errors = 0, lastError = nil }, DecoderMeta) + if o.avcC then + local ok, err = self:configure(o.avcC) + if not ok then + return nil, err + end + end + return self, nil +end + +-- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to +-- length-prefixed input +function DecoderMeta.configure(self, avcC) +local b = toBuffer(avcC) + if not b then + return nil, Err.new(Err.ARG, "configure: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + local m = err or "bad avcC" + if string.sub(m, 1, 11) == "truncated: " then + return nil, Err.new(Err.TRUNCATED, string.sub(m, 12)) + end + return nil, Err.new(Err.CORRUPT, m) + end + self.lengthSize = cfg.lengthSize + local nals = cfg.nals + for i = 1, #nals, 2 do + Decoder.nal(self.state, b, nals[i], nals[i + 1], nil) + end + local e = status(self) + if e and e.code ~= Err.CORRUPT then + return nil, e + end + return true, nil +end + +-- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units: +-- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit. +function DecoderMeta.decode(self, data, pts, off, len) +local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "decode: expected a buffer or string") + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + local l = math.clamp(len or (n - o), 0, n - o) + local st = self.state + local nals + if self.lengthSize then + local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize) + nals = all or partial + if not all then + st.errors =st.errors+ 1 + st.lastError = "NAL length past the end of the sample" + end + elseif Bitstream.isAnnexB(b, o, l) then + nals = Bitstream.splitAnnexB(b, o, l) + else + nals = { o, l } + end + for i = 1, #nals, 2 do + Decoder.nal(st, b, nals[i], nals[i + 1], pts) + if st.fatal or st.unsupported then + break + end + end + local frames = Decoder.take(st) + local e = status(self) + if e then + return nil, e + end + return frames, nil +end + +-- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering) +function DecoderMeta.flush(self) +Decoder.flush(self.state) + status(self) + return Decoder.take(self.state) +end + +-- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream +function H264.decodeAll(data, opts) +local dec, err = H264.newDecoder(opts) + if not dec then + return nil, err + end + local frames, e = dec:decode(data) + if not frames then + return nil, e + end + for _, f in __iter(dec:flush()) do + table.insert(frames, f) + end + return frames, nil +end + +-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err +function H264.parseAvcC(data) +local b = toBuffer(data) + if not b then + return nil, Err.new(Err.ARG, "parseAvcC: expected a buffer or string") + end + local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + return cfg, nil +end + +-- ------------------------------------------------------------------------------------------------ video layer +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"): +-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). +-- Pictures come out in display order with the packet timestamps sorted (display order); a track with +-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. +function H264.newVideoDecoder(track, opts) +local o= { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay, + yield = opts and opts.yield } + local function make() +local d, err = H264.newDecoder(o) + if d and track.config then + local ok, e = d:configure(track.config) + if not ok then + return nil, e + end + end + return d, err + end + local dec, err = make() + if not dec then + return nil, err + end + local queue= {} + local pool= {} + local outIndex= track.ptsInOutputOrder and 0 or nil + local self= {} + local function push(frames) + for _, f in __iter(frames) do + local pts = f.pts + if track.ptsInOutputOrder then + pts = outIndex or 0 + outIndex = pts + 1 + elseif #pool > 0 then + -- pictures leave in display order: they take the packet timestamps in increasing order (right for + -- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times) + pts = table.remove(pool, 1) + end + table.insert(queue, { f.image, pts, f.keyframe }) + end + end + function self.decode(_, packet) +if not dec then + return Err.new(Err.CORRUPT, "decoder not available") + end + if outIndex == nil and track.ptsInOutputOrder then + outIndex = packet.pts + end + if packet.pts ~= nil and not track.ptsInOutputOrder then + local i = #pool + while i > 0 and pool[i] > packet.pts do + i =i- 1 + end + table.insert(pool, i + 1, packet.pts) + end + local frames, e = (dec ):decode(packet.data, packet.pts) + if not frames then + return e + end + push(frames) + return nil + end + function self.receive(_) +local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil + end + function self.flush(_) + if dec then + push((dec ):flush()) + end + end + function self.reset(_) + dec = make() + table.clear(queue) + table.clear(pool) + if track.ptsInOutputOrder then + outIndex = nil + end + end + return self, nil +end + +-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units +-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0 +-- after a slice). keyframe: the unit holds an IDR slice. +function H264.accessUnits(data, off, len) +local b = toBuffer(data) + local out = {} + if not b then + return out + end + local n = buffer.len(b) + local o = math.clamp(off or 0, 0, n) + local l = math.clamp(len or (n - o), 0, n - o) + local nals = Bitstream.splitAnnexB(b, o, l) + local start, hasSlice, key = o, false, false + for i = 1, #nals, 2 do + local p, nl = nals[i], nals[i + 1] + local t = buffer.readu8(b, p) % 32 + local isSlice = t == 1 or t == 5 + local boundary = false + if hasSlice then + if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then + boundary = true + elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then + boundary = true + end + end + if boundary then + -- the unit ends where this NAL's start code begins + local s = p + while s > start and buffer.readu8(b, s - 1) ~= 1 do + s =s- 1 + end + s =s- 1 + while s > start and buffer.readu8(b, s - 1) == 0 do + s =s- 1 + end + table.insert(out, start) + table.insert(out, s - start) + table.insert(out, key) + start, hasSlice, key = s, false, false + end + if isSlice then + hasSlice = true + if t == 5 then + key = true + end + end + end + if hasSlice and o + l > start then + table.insert(out, start) + table.insert(out, o + l - start) + table.insert(out, key) + end + return out +end + +-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the +-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample +function H264.toAnnexB(config, sample) +local parts = {} + local lengthSize = 4 + if config then + local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config)) + if not cfg then + return nil, Err.new(Err.CORRUPT, err or "bad avcC") + end + lengthSize = cfg.lengthSize + for i = 1, #cfg.nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1])) + end + end + local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize) + if not nals then + return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample") + end + for i = 1, #nals, 2 do + table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1])) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil +function H264.info(data) +local b = toBuffer(data) + if not b then + return nil + end + local nals + if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then + local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b)) + nals = (cfg and{cfg.nals }or{{} +})[1] else + nals = Bitstream.splitAnnexB(b, 0, buffer.len(b)) + end + for i = 1, #nals, 2 do + if buffer.readu8(b, nals[i]) % 32 == 7 then + local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1)) + if sps then + local fps = nil + if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then + fps = sps.timeScale / (2 * sps.unitsInTick) + end + return { + width = sps.width, + height = sps.height, + profile = sps.profile, + level = sps.level, + chromaFormat = sps.chromaFormat, + bitDepth = sps.bitDepth, + interlaced = not sps.frameMbsOnly, + frameRate = fps, + maxRefFrames = sps.maxRefFrames, + numReorderFrames = sps.numReorderFrames, + } + end + end + end + return nil +end + +-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height +function H264.planes(img) +local cw, ch = math.floor((img.width + 1) / 2), math.floor((img.height + 1) / 2 +) local ny = img.width * img.height + return 0, ny, ny + cw * ch, cw, ch +end + +return H264 +end +__FILES["codecs/video/H264/Bitstream"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start +-- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) +-- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. +-- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every +-- read is range-checked), and callers check `r.pos > r.size` once per syntax structure. +local Bitstream = {} + +local readu8 = buffer.readu8 +local band, lshift = bit32.band, bit32.lshift + +-- ------------------------------------------------------------------------------------------------ framing +-- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes +-- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped. + + + + + + + + +function Bitstream.splitAnnexB(buf, off, len) +local out = {} + local e = off + len + local i = off + local start = -1 + while i + 2 < e do + local b2 = readu8(buf, i + 2) + if b2 > 1 then + i =i+ 3 + elseif readu8(buf, i + 1) ~= 0 then + i =i+ 2 + elseif b2 == 1 and readu8(buf, i) == 0 then + if start >= 0 then + local j = i + while j > start and readu8(buf, j - 1) == 0 do + j =j- 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + start = i + 3 + i =i+ 3 + else + i =i+ 1 + end + end + if start >= 0 then + local j = e + while j > start and readu8(buf, j - 1) == 0 do + j =j- 1 + end + if j > start then + table.insert(out, start) + table.insert(out, j - start) + end + end + return out +end + +-- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01) +function Bitstream.isAnnexB(buf, off, len) +if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then + local b2 = readu8(buf, off + 2) + if b2 == 1 then + return true + end + return b2 == 0 and len >= 4 and readu8(buf, off + 3) == 1 + end + return false +end + +-- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a +-- length runs past the end (the NALs before it are kept in the second result) +function Bitstream.splitLength(buf, off, len, size) +local out = {} + local e = off + len + local p = off + while p + size <= e do + local n = 0 + for k = 0, size - 1 do + n = n * 256 + readu8(buf, p + k) + end + p =p+ size + if n > e - p then + return nil, out + end + if n > 0 then + table.insert(out, p) + table.insert(out, n) + end + p =p+ n + end + return out, out +end + +-- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } | +-- nil, message +function Bitstream.parseAvcC(buf, off, len) +if len < 7 then + return nil, "truncated: avcC shorter than 7 bytes" + end + if readu8(buf, off) ~= 1 then + return nil, "avcC configurationVersion is not 1" + end + local cfg = { + profile = readu8(buf, off + 1), + compat = readu8(buf, off + 2), + level = readu8(buf, off + 3), + lengthSize = band(readu8(buf, off + 4), 3) + 1, + nals = {} , + } + local p = off + 5 + local e = off + len + for pass = 1, 2 do + if p >= e then + return nil, "truncated: avcC parameter set count" + end + local count = (pass == 1 and{(band(readu8(buf, p), 31) )}or{(readu8(buf, p) +)})[1] p =p+ 1 + for _ = 1, count do + if p + 2 > e then + return nil, "truncated: avcC parameter set length" + end + local n = readu8(buf, p) * 256 + readu8(buf, p + 1) + p =p+ 2 + if p + n > e then + return nil, "truncated: avcC parameter set" + end + table.insert(cfg.nals, p) + table.insert(cfg.nals, n) + p =p+ n + end + end + return cfg, nil +end + +-- ------------------------------------------------------------------------------------------------ rbsp +-- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip` +-- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed. +function Bitstream.reader(buf, off, len, skip) +local out = buffer.create(len + 8) + local o = 0 + local zeros = 0 + for i = off + skip, off + len - 1 do + local b = readu8(buf, i) + if zeros >= 2 and b == 3 then + zeros = 0 + else + buffer.writeu8(out, o, b) + o =o+ 1 + if b == 0 then + zeros =zeros+ 1 + else + zeros = 0 + end + end + end + -- the rbsp_stop_one_bit: the last set bit of the last non-zero byte + local stop = o * 8 + local j = o - 1 + while j >= 0 and readu8(out, j) == 0 do + j =j- 1 + end + if j >= 0 then + local b = readu8(out, j) + local k = 0 + while band(b, lshift(1, k)) == 0 do + k =k+ 1 + end + stop = j * 8 + 7 - k + end + return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } +end + +-- ------------------------------------------------------------------------------------------------ bits +-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). +local P2 = table.create(33, 1) -- P2[k + 1] = 2^k +for k = 0, 32 do + P2[k + 1] = 2 ^ k +end +Bitstream.P2 = P2 +local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0) +for x = 0, 255 do + local n, v = 0, x + while n < 8 and v < 128 do + v =v* 2 + n =n+ 1 + end + LZ8[x + 1] = n +end +Bitstream.LZ8 = LZ8 + +-- clz32(v) -> leading zero bits of a 32-bit value +local function clz32(v) +if v >= 16777216 then + return LZ8[math.floor(v / 16777216 )+ 1] + elseif v >= 65536 then + return 8 + LZ8[math.floor(v / 65536 )+ 1] + elseif v >= 256 then + return 16 + LZ8[math.floor(v / 256 )+ 1] + end + return 24 + LZ8[v + 1] +end +Bitstream.clz32 = clz32 + +-- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end +local function peekAt(b, n, pos) +local p = math.floor(pos / 8 +) if p + 5 > n then + return 0 + end + local s = pos - p * 8 + local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) + if s == 0 then + return w + end + return (w * P2[s + 1]) % 4294967296 + math.floor(readu8(b, p + 4) / P2[9 - s] +)end +Bitstream.peekAt = peekAt + +-- peek32(r) -> the next 32 bits (zeros past the end) +local function peek32(r) +return peekAt(r.buf, r.n, r.pos) +end +Bitstream.peek32 = peek32 + +-- u(r, n) -> n bits (n 1..32) as an unsigned number +function Bitstream.u(r, n) +local v = peekAt(r.buf, r.n, r.pos) + r.pos =r.pos+ n + return math.floor(v / P2[33 - n] +)end + +-- u1(r) -> one bit +function Bitstream.u1(r) +local pos = r.pos + r.pos = pos + 1 + local p = math.floor(pos / 8 +) if p >= r.n then + return 0 + end + return (math.floor(readu8(r.buf, p) / P2[8 - (pos - p * 8)])) % 2 +end + +-- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) +local function ue(r) +local v = peekAt(r.buf, r.n, r.pos) + if v == 0 then + r.pos =r.pos+ 32 + return 4294967296 + end + local lz = clz32(v) + if lz < 16 then + local n = 2 * lz + 1 + r.pos =r.pos+ n + return math.floor(v / P2[33 - n] )- 1 + end + r.pos =r.pos+ lz + v = peekAt(r.buf, r.n, r.pos) + r.pos =r.pos+ (lz + 1 +) return math.floor(v / P2[32 - lz] )- 1 +end +Bitstream.ue = ue + +-- se(r) -> se(v) +function Bitstream.se(r) +local k = ue(r) + if k % 2 == 1 then + return math.floor((k + 1) / 2 +) end + return -(math.floor(k / 2)) +end + +-- te(r, range) -> te(v) with the given range (max value) +function Bitstream.te(r, range) +if range == 1 then + return 1 - Bitstream.u1(r) + end + return ue(r) +end + +-- moreData(r) -> more_rbsp_data() +function Bitstream.moreData(r) +return r.pos < r.stop +end + +return Bitstream +end +__FILES["codecs/video/H264/Cabac"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the +-- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context +-- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. +-- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. +-- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one +-- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") + +local readu8 = buffer.readu8 +local min = math.min + +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT +local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y + +local Cabac = {} + +-- ------------------------------------------------------------------------------------------------ engine +local RANGE_LPS = Tables.RANGE_LPS +local TRANS = Tables.TRANS +local POW2 = table.create(40, 1) +for i = 0, 39 do + POW2[i + 1] = 2 ^ i +end +local NORM = table.create(512, 0) -- NORM[r + 1] = renormalisation shift of range r (r < 512) +for r = 1, 511 do + local s, v = 0, r + while v < 256 do + v =v* 2 + s =s+ 1 + end + NORM[r + 1] = s +end +-- state per context: pStateIdx * 2 + valMPS, at ST[ctxIdx + 1] +local ST = table.create(460, 0) +-- per packed state s (pStateIdx * 2 + valMPS) and LPS bit: the next state and the bin; rangeTabLPS by packed state +local NEXTS, BINS = table.create(256, 0), table.create(256, 0) +local LPSR = table.create(512, 0) +for st = 0, 127 do + local p, mps = math.floor(st / 2), st % 2 + NEXTS[st * 2 + 1] = TRANS[p * 2 + 2] * 2 + mps + BINS[st * 2 + 1] = mps + NEXTS[st * 2 + 2] = TRANS[p * 2 + 1] * 2 + ((p == 0 and((1 - mps ))or(mps))) + BINS[st * 2 + 2] = 1 - mps + for q = 0, 3 do + LPSR[st * 4 + q + 1] = RANGE_LPS[p * 4 + q + 1] + end +end + +-- the engine (one slice at a time) +local ebuf= buffer.create(1) +local epos, elimit = 0, 0 +local erange, elow, enb = 510, 0, 0 + +local function refill() + local b = 0 + if epos < elimit then + b = readu8(ebuf, epos) + end + epos =epos+ 1 + elow = elow * 256 + b + enb =enb+ 8 +end + +-- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) +-- (low < 2.5 * scaled always), the state step and the bin come from tables +local function decision(ctx) +local s = ST[ctx + 1] + local range = erange + local lps = LPSR[s * 4 + (math.floor(range / 64)) % 4 + 1] + local r = range - lps + local scaled = r * POW2[enb + 1] + local bit = min(1, math.floor(elow / scaled)) + elow =elow- bit * scaled + r =r+ bit * (lps - r) + local k = s * 2 + bit + 1 + ST[ctx + 1] = NEXTS[k] + local sh = NORM[r + 1] + erange = r * POW2[sh + 1] + enb =enb- sh + if enb < 8 then + refill() + end + return BINS[k] +end + +local function bypass() +enb =enb- 1 + local scaled = erange * POW2[enb + 1] + local bin = math.floor(elow / scaled +) elow =elow- bin * scaled + if enb < 8 then + refill() + end + return bin +end + +local function terminate() +local r = erange - 2 + local scaled = r * POW2[enb + 1] + if elow >= scaled then + erange = r + return 1 + end + if r < 256 then + r =r* 2 + enb =enb- 1 + if enb < 8 then + refill() + end + end + erange = r + return 0 +end + +-- start the engine at byte p of the rbsp +local function engineInit(b, p, limit) + ebuf, epos, elimit = b, p, limit + elow, enb = 0, -9 + refill() + refill() + refill() + erange = 510 +end + +-- the bit position the spec's decoder is at (after a terminate bin of 1) +local function bitPos() +return epos * 8 - enb +end + +local function initContexts(sliceQp, model) + local init = Tables.CABAC_INIT + local qp = math.clamp(sliceQp, 0, 51) + for ctx = 0, 459 do + local m = init[ctx * 8 + model * 2 + 1] + local n = init[ctx * 8 + model * 2 + 2] + local pre = math.clamp(math.floor((m * qp) / 16 )+ n, 1, 126) + if pre <= 63 then + ST[ctx + 1] = (63 - pre) * 2 + else + ST[ctx + 1] = (pre - 64) * 2 + 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ residual +local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 +local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 +local CAT_CBF = { 0, 4, 8, 12, 16 } +local CAT_SIG = { 0, 15, 29, 44, 47 } +local CAT_ABS = { 0, 10, 20, 30, 39 } +local MAXC = { 16, 15, 16, 4, 15, 64 } +local SIGPOS = table.create(64, 0) + +-- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. +-- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag +local SCAN = {} +do + local ac = table.create(15, 0) + for i = 1, 15 do + ac[i] = ZZ4[i + 1] + end + SCAN[1], SCAN[2], SCAN[3], SCAN[4], SCAN[5], SCAN[6] = ZZ4, ac, ZZ4, { 0, 1, 2, 3 }, ac, ZZ8 +end +local SIG3 = { 0, 1, 2 } + +local function block(cat, out, base, mul, div) +local maxc = MAXC[cat + 1] + local n = 0 + local last = false + -- significance map + if cat == 5 then + for i = 0, 62 do + if decision(402 + SIG8[i + 1]) == 1 then + n =n+ 1 + SIGPOS[n] = i + if decision(417 + LAST8[i + 1]) == 1 then + last = true + break + end + end + end + elseif cat == 3 then + local sb, lb = 105 + 44, 166 + 44 + for i = 0, 2 do + if decision(sb + SIG3[i + 1]) == 1 then + n =n+ 1 + SIGPOS[n] = i + if decision(lb + SIG3[i + 1]) == 1 then + last = true + break + end + end + end + else + local sb = 105 + CAT_SIG[cat + 1] + local lb = 166 + CAT_SIG[cat + 1] + for i = 0, maxc - 2 do + if decision(sb + i) == 1 then + n =n+ 1 + SIGPOS[n] = i + if decision(lb + i) == 1 then + last = true + break + end + end + end + end + if not last then + n =n+ 1 + SIGPOS[n] = maxc - 1 + end + -- levels, highest frequency first + local absBase = cat == 5 and 426 or 227 + CAT_ABS[cat + 1] + local gt1, eq1 = 0, 0 + local half = math.floor(div / 2 +) local catMax = cat == 3 and 3 or 4 + local scan = SCAN[cat + 1] + for k = n, 1, -1 do + local v + local inc = 0 + if gt1 == 0 then + inc = min(eq1 + 1, 4) + end + if decision(absBase + inc) == 0 then + v = 1 + eq1 =eq1+ 1 + else + local ctx = absBase + 5 + min(gt1, catMax) + local prefix = 1 + while prefix < 14 and decision(ctx) == 1 do + prefix =prefix+ 1 + end + v = prefix + 1 + if prefix == 14 then + -- Exp-Golomb (k = 0) suffix + local kk = 0 + while bypass() == 1 do + v =v+ POW2[kk + 1] + kk =kk+ 1 + if kk > 24 then + return -1 + end + end + while kk > 0 do + kk =kk- 1 + v =v+ bypass() * POW2[kk + 1] + end + end + gt1 =gt1+ 1 + end + if bypass() == 1 then + v = -v + end + local p = scan[SIGPOS[k] + 1] + if mul then + out[base + p + 1] = math.floor((v * mul[p + 1] + half) / div +) else + out[base + p + 1] = v + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ syntax elements +-- condition helpers on neighbouring macroblocks (addresses are 1-based here) +local function leftAddr(S, M) +return ((M.aL) and (M.addr) or (0)) +end +local function topAddr(S, M) +return ((M.aT) and (M.addr - S.mbW + 1) or (0)) +end + +local function mbSkipFlag(S, M) +local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_PSKIP and k[a] ~= K_BSKIP then + inc =inc+ 1 + end + if b > 0 and k[b] ~= K_PSKIP and k[b] ~= K_BSKIP then + inc =inc+ 1 + end + return decision((((S.type == 1) and (24) or (11))) + inc) +end + +-- intra mb_type (I slice: prefix false, offset 3; P / B suffix: offset 17 / 32) -> 0..25 +local function intraType(S, M, off) +local b0 + if off == 3 then + local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_I4 and k[a] ~= K_I8 then + inc =inc+ 1 + end + if b > 0 and k[b] ~= K_I4 and k[b] ~= K_I8 then + inc =inc+ 1 + end + b0 = decision(3 + inc) + else + b0 = decision(off) + end + if b0 == 0 then + return 0 + end + if terminate() == 1 then + return 25 + end + local luma, chroma, pred + if off == 3 then + luma = decision(6) + chroma = decision(7) + if chroma == 1 then + chroma =chroma+ decision(8) + end + pred = decision(9) * 2 + pred =pred+ decision(10) + else + luma = decision(off + 1) + chroma = decision(off + 2) + if chroma == 1 then + chroma =chroma+ decision(off + 2) + end + pred = decision(off + 3) * 2 + pred =pred+ decision(off + 3) + end + return 1 + pred + 4 * chroma + 12 * luma +end + +local function pMbType() -- 0..3 inter, 5+ intra (returned as -1: the caller decodes the suffix) + +if decision(14) == 1 then + return -1 + end + if decision(15) == 0 then + return ((decision(16) == 0) and (0) or (3)) + end + return ((decision(17) == 1) and (1) or (2)) +end + +local function bMbType(S, M) +local k = S.kind + local a, b = leftAddr(S, M), topAddr(S, M) + local inc = 0 + if a > 0 and k[a] ~= K_BSKIP and k[a] ~= K_BDIRECT then + inc =inc+ 1 + end + if b > 0 and k[b] ~= K_BSKIP and k[b] ~= K_BDIRECT then + inc =inc+ 1 + end + if decision(27 + inc) == 0 then + return 0 + end + if decision(30) == 0 then + return 1 + decision(32) + end + local bits = decision(31) * 8 + bits =bits+ decision(32) * 4 + bits =bits+ decision(32) * 2 + bits =bits+ decision(32) + if bits < 8 then + return bits + 3 + elseif bits == 13 then + return -1 -- intra + elseif bits == 14 then + return 11 + elseif bits == 15 then + return 22 + end + bits = bits * 2 + decision(32) + return bits - 4 +end + +local function pSubType() +if decision(21) == 1 then + return 0 + end + if decision(22) == 0 then + return 1 + end + return ((decision(23) == 1) and (2) or (3)) +end + +local function bSubType() +if decision(36) == 0 then + return 0 + end + if decision(37) == 0 then + return 1 + decision(39) + end + local t = 3 + if decision(38) == 1 then + if decision(39) == 1 then + return 11 + decision(39) + end + t =t+ 4 + end + t =t+ 2 * decision(39) + t =t+ decision(39) + return t +end + +-- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list +local function refIdx(S, M, rgt, x, y) +local g = M.g0 + y * S.w4 + x + local inc = 0 + if (x > 0 or M.aL) and rgt[g - 1] ~= 0 then + inc =inc+ 1 + end + if (y > 0 or M.aT) and rgt[g - S.w4] ~= 0 then + inc =inc+ 2 + end + if decision(54 + inc) == 0 then + return 0 + end + local v = 1 + local ctx = 58 + while decision(ctx) == 1 do + v =v+ 1 + ctx = 59 + if v > 32 then + return -1 + end + end + return v +end + +-- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) +local function mvd(S, M, grid, x, y, comp) +local g = M.g0 + y * S.w4 + x + local sum = 0 + if x > 0 or M.aL then + sum =sum+ grid[2 * (g - 1) - 1 + comp] + end + if y > 0 or M.aT then + sum =sum+ grid[2 * (g - S.w4) - 1 + comp] + end + local base = ((comp == 0) and (40) or (47)) + local inc = 0 + if sum > 32 then + inc = 2 + elseif sum >= 3 then + inc = 1 + end + if decision(base + inc) == 0 then + return 0 + end + local v = 1 + local ctx = base + 3 + while v < 9 and decision(ctx) == 1 do + v =v+ 1 + if ctx < base + 6 then + ctx =ctx+ 1 + end + end + if v >= 9 then + local k = 3 + while bypass() == 1 do + v =v+ POW2[k + 1] + k =k+ 1 + if k > 24 then + return 0 + end + end + while k > 0 do + k =k- 1 + v =v+ bypass() * POW2[k + 1] + end + end + if bypass() == 1 then + return -v + end + return v +end + +local function fillRegion(S, M, grid, x, y, w, h, v) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[g + i] = v + end + end +end + +local function fillMvd(S, M, grid, x, y, w, h, ax, ay) + local w4 = S.w4 + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = 0, w - 1 do + grid[2 * (g + i) - 1] = ax + grid[2 * (g + i)] = ay + end + end +end + +local function cbpCabac(S, M) +local cbpTab = S.cbpTab + local a, b = leftAddr(S, M), topAddr(S, M) + local luma = 0 + for b8 = 0, 3 do + local bx, by = b8 % 2, math.floor(b8 / 2 +) local condA, condB = 0, 0 + if bx == 1 then + if (math.floor(luma / POW2[b8 - 1 + 1])) % 2 == 0 then + condA = 1 + end + elseif a > 0 then + if (math.floor(cbpTab[a] / POW2[b8 + 1 + 1])) % 2 == 0 then + condA = 1 + end + end + if by == 1 then + if (math.floor(luma / POW2[b8 - 2 + 1])) % 2 == 0 then + condB = 1 + end + elseif b > 0 then + if (math.floor(cbpTab[b] / POW2[b8 + 2 + 1])) % 2 == 0 then + condB = 1 + end + end + if decision(73 + condA + 2 * condB) == 1 then + luma =luma+ POW2[b8 + 1] + end + end + local ca = ((a > 0) and (math.floor(cbpTab[a] / 16)) or (0)) + local cb = ((b > 0) and (math.floor(cbpTab[b] / 16)) or (0)) + local inc = (((ca ~= 0) and (1) or (0))) + (((cb ~= 0) and (2) or (0))) + local chroma = 0 + if decision(77 + inc) == 1 then + inc = (((ca == 2) and (1) or (0))) + (((cb == 2) and (2) or (0))) + chroma = 1 + decision(81 + inc) + end + return luma + 16 * chroma +end + +local function qpDelta(S) +local k = 0 + if decision(60 + (((S.lastQpd) and (1) or (0)))) == 1 then + k = 1 + local ctx = 62 + while decision(ctx) == 1 do + k =k+ 1 + ctx = 63 + if k > 104 then + return 999 + end + end + end + if k % 2 == 1 then + return math.floor((k + 1) / 2 +) end + return -(math.floor(k / 2)) +end + +local function chromaPredMode(S, M) +local a, b = leftAddr(S, M), topAddr(S, M) + local cpm, kind = S.cpmTab, S.kind + local inc = 0 + if a > 0 and kind[a] <= K_I16 and cpm[a] ~= 0 then + inc =inc+ 1 + end + if b > 0 and kind[b] <= K_I16 and cpm[b] ~= 0 then + inc =inc+ 1 + end + if decision(64 + inc) == 0 then + return 0 + end + if decision(67) == 0 then + return 1 + end + return 2 + decision(67) +end + +local function t8Flag(S, M) +local a, b = leftAddr(S, M), topAddr(S, M) + local t8 = S.t8Tab + local inc = 0 + if a > 0 and t8[a] == 1 then + inc =inc+ 1 + end + if b > 0 and t8[b] == 1 then + inc =inc+ 1 + end + return decision(399 + inc) +end + +-- coded_block_flag condition of a neighbour: v = the neighbour's flag when its block is available +local function cbf(cat, condA, condB) +return decision(85 + CAT_CBF[cat + 1] + condA + 2 * condB) +end + +-- luma 4x4 coded_block_flag neighbours of (bx, by) +local function lumaCond(S, M, bx, by, intra) +local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local ca, cb + if bx > 0 then + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) + elseif M.aL then + ca = ((nzc[g - 1] ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if by > 0 then + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) + elseif M.aT then + cb = ((nzc[g - S.w4] ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +local function chromaCond(S, M, tab, bx, by, intra) +local cw = S.cw4 + local g = M.c0 + by * cw + bx + local ca, cb + if bx > 0 or M.aL then + ca = ((tab[g - 1] ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if by > 0 or M.aT then + cb = ((tab[g - cw] ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +local function dcCond(S, M, bit, intra) +local dc = S.dcTab + local a, b = leftAddr(S, M), topAddr(S, M) + local ca, cb + if a > 0 then + ca = (((math.floor(dc[a] / bit)) % 2 ~= 0) and (1) or (0)) + else + ca = ((intra) and (1) or (0)) + end + if b > 0 then + cb = (((math.floor(dc[b] / bit)) % 2 ~= 0) and (1) or (0)) + else + cb = ((intra) and (1) or (0)) + end + return ca, cb +end + +-- ------------------------------------------------------------------------------------------------ residual +local function residuals(S, M) +local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + local dcBits = 0 + if kind == K_I16 then + local ca, cb = dcCond(S, M, 1, intra) + if cbf(0, ca, cb) == 1 then + local n = block(0, M.dcY, 0, nil, 1) + if n < 0 then + return false + end + M.hasDcY = true + dcBits =dcBits+ 1 + end + end + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local n = 0 + if (math.floor(cbp / POW2[i8 + 1])) % 2 ~= 0 then + n = block(5, M.c8, i8 * 64, mul8, 64) + if n < 0 then + return false + end + end + local f = ((n > 0) and (1) or (0)) + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = f, f, f, f + nz[by * 4 + bx + 1], nz[by * 4 + bx + 2], nz[by * 4 + bx + 5], nz[by * 4 + bx + 6] = n, n, n, n + end + else + local ac = kind == K_I16 + local cat = ((ac) and (1) or (2)) + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local n = 0 + if (math.floor(cbp / POW2[math.floor(i / 4 )+ 1])) % 2 ~= 0 then + local ca, cb = lumaCond(S, M, bx, by, intra) + if cbf(cat, ca, cb) == 1 then + n = block(cat, c4, blk * 16, mul4, 16) + if n < 0 then + return false + end + end + end + grid[g0 + by * w4 + bx] = ((n > 0) and (1) or (0)) + nz[blk + 1] = n + end + end + local chroma = math.floor(cbp / 16 +) local cw, c0 = S.cw4, M.c0 + local nzc = M.nzc + if chroma ~= 0 then + for plane = 0, 1 do + local bit = ((plane == 0) and (2) or (4)) + local ca, cb = dcCond(S, M, bit, intra) + if cbf(3, ca, cb) == 1 then + local n = block(3, M.dcC, plane * 4, nil, 1) + if n < 0 then + return false + end + M.hasDcC = true + dcBits =dcBits+ bit + end + end + end + local cc = M.cc + for plane = 0, 1 do + local tab = ((plane == 0) and (S.nzcCb) or (S.nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] + for blk = 0, 3 do + local bx, by = blk % 2, math.floor(blk / 2 +) local n = 0 + if chroma == 2 then + local ca, cb = chromaCond(S, M, tab, bx, by, intra) + if cbf(4, ca, cb) == 1 then + n = block(4, cc, (plane * 4 + blk) * 16, mulc, 16) + if n < 0 then + return false + end + end + end + tab[c0 + by * cw + bx] = ((n > 0) and (1) or (0)) + nzc[plane * 4 + blk + 1] = n + end + end + S.dcTab[M.addr + 1] = dcBits + return true +end + +local function setQp(S, M, delta) +if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + S.lastQpd = delta ~= 0 + return true +end + +local function clearCounts(M) + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +-- ------------------------------------------------------------------------------------------------ macroblock +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +local function intraMb(S, M, r, t) +local addr = M.addr + 1 + local w4, g0 = S.w4, M.g0 + fillRegion(S, M, S.rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, S.rgt1, 0, 0, 4, 4, 0) + fillMvd(S, M, S.mvd0, 0, 0, 4, 4, 0, 0) + fillMvd(S, M, S.mvd1, 0, 0, 4, 4, 0, 0) + clearCounts(M) + if t == 25 then + M.kind = K_PCM + -- pcm_alignment_zero_bit and the samples follow the terminate bin + local p = math.floor((bitPos() + 7) / 8 +) if p + 384 > elimit then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, ebuf, p, 384) + engineInit(ebuf, p + 384, elimit) + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + fillRegion(S, M, S.nzc, 0, 0, 4, 4, 16) + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.lastQpd = false + Mb.recon(S, M) + return true + end + if t == 0 then + M.kind = K_I4 + if S.t8mode and t8Flag(S, M) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem =rem+ decision(69) * 2 + rem =rem+ decision(69) * 4 + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if decision(68) == 0 then + local rem = decision(69) + rem =rem+ decision(69) * 2 + rem =rem+ decision(69) * 4 + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + M.cbp = cbpCabac(S, M) + else + M.kind = K_I16 + M.i16 = (t - 1) % 4 + M.cbp = (math.floor((t - 1) / 4)) % 3 * 16 + (((t >= 13) and (15) or (0))) + M.cpm = chromaPredMode(S, M) + S.cpmTab[addr] = M.cpm + end + S.cbpTab[addr] = M.cbp + S.kind[addr] = M.kind + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + S.t8Tab[addr] = M.t8 + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +local function interMb(S, M, r, t, isB) +clearCounts(M) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + local rgt0, rgt1, g0, g1 = S.rgt0, S.rgt1, S.mvd0, S.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + pf[i] = 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + local addr = M.addr + 1 + if isB and t == 0 then + M.kind = K_BDIRECT + M.part = 0 + noSmall = S.direct8x8 + fillRegion(S, M, rgt0, 0, 0, 4, 4, 0) + fillRegion(S, M, rgt1, 0, 0, 4, 4, 0) + fillMvd(S, M, g0, 0, 0, 4, 4, 0, 0) + fillMvd(S, M, g1, 0, 0, 4, 4, 0, 0) + elseif (not isB and t < 3) or (isB and t <= 21) then + M.kind = ((isB) and (K_B) or (K_P)) + if not isB then + M.part = t + pf[1], pf[2] = 1, 1 + elseif t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = ((t % 2 == 0) and (1) or (2)) + local k = math.floor((t - 4) / 2 )+ 1 + pf[1], pf[2] = BPAIR0[k], BPAIR1[k] + end + local part = M.part + local n = ((part == 0) and (1) or (2)) + for l = 0, 1 do + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + elseif part == 2 then + x, w = (p - 1) * 2, 2 + end + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end + local v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[p] = v + fillRegion(S, M, rgt, x, y, w, h, ((uses and v > 0) and (1) or (0))) + end + end + for l = 0, 1 do + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + if part == 1 then + y, h = (p - 1) * 2, 2 + elseif part == 2 then + x, w = (p - 1) * 2, 2 + end + local uses = pf[p] >= 2 + if l == 0 then + uses = pf[p] % 2 == 1 + end + local mx, my = 0, 0 + if uses then + mx = mvd(S, M, grid, x, y, 0) + my = mvd(S, M, grid, x, y, 1) + end + md[2 * p - 1], md[2 * p] = mx, my + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) + end + end + else + -- P_8x8 (3) / P_8x8ref0 (4) / B_8x8 (22) + M.kind = ((isB) and (K_B) or (K_P)) + M.part = 3 + for i = 1, 4 do + if isB then + local s = bSubType() + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + else + local s = pSubType() + pf[i] = 1 + sub[i] = s + if s > 0 then + noSmall = false + end + end + end + for l = 0, 1 do + local rgt = ((l == 0) and (rgt0) or (rgt1)) + local nr = ((l == 0) and (n0) or (n1)) + local refs = ((l == 0) and (ref0) or (ref1)) + for i = 1, 4 do + local x, y = ((i - 1) % 2) * 2, (math.floor((i - 1) / 2)) * 2 + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] + local v = 0 + if uses and nr > 1 then + v = refIdx(S, M, rgt, x, y) + if v < 0 or v >= nr then + return false, "ref_idx out of range" + end + end + refs[i] = v + fillRegion(S, M, rgt, x, y, 2, 2, ((uses and v > 0) and (1) or (0))) + end + end + for l = 0, 1 do + local grid = ((l == 0) and (g0) or (g1)) + local md = ((l == 0) and (mvd0) or (mvd1)) + for i = 1, 4 do + local x0, y0 = ((i - 1) % 2) * 2, (math.floor((i - 1) / 2)) * 2 + local uses = pf[i] >= 2 + if l == 0 then + uses = pf[i] % 2 == 1 + end + uses = uses and not dir[i] + if not uses then + fillMvd(S, M, grid, x0, y0, 2, 2, 0, 0) + else + local s = sub[i] + local w, h = SUB_W[s + 1], SUB_H[s + 1] + for k = 0, SUB_N[s + 1] - 1 do + local x, y = x0, y0 + if s == 1 then + y =y+ k + elseif s == 2 then + x =x+ k + elseif s == 3 then + x =x+ k % 2 + y =y+ math.floor(k / 2 +) end + local mx = mvd(S, M, grid, x, y, 0) + local my = mvd(S, M, grid, x, y, 1) + local p = (i - 1) * 4 + k + 1 + md[2 * p - 1], md[2 * p] = mx, my + fillMvd(S, M, grid, x, y, w, h, ((mx < 0) and (-mx) or (mx)), ((my < 0) and (-my) or (my))) + end + end + end + end + end + S.kind[addr] = M.kind + M.cbp = cbpCabac(S, M) + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = t8Flag(S, M) + end + S.t8Tab[addr] = M.t8 + if M.cbp > 0 then + if not setQp(S, M, qpDelta(S)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if not residuals(S, M) then + return false, "bad residual" + end + Mb.recon(S, M) + return true +end + +local function macroblock(S, M, r) +local st = S.type + if st == 2 then + return intraMb(S, M, r, intraType(S, M, 3)) + elseif st == 0 then + local t = pMbType() + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 17)) + end + return interMb(S, M, r, t, false) + end + local t = bMbType(S, M) + if t < 0 then + return intraMb(S, M, r, intraType(S, M, 32)) + end + return interMb(S, M, r, t, true) +end + +-- slice(S, M, r) -> true | false, message +function Cabac.slice(S, M, r) +local p = math.floor((r.pos + 7) / 8 +) local limit = math.floor(r.size / 8 +) if p >= limit then + return false, "truncated: slice data" + end + engineInit(r.buf, p, limit) + initContexts(S.qp, ((S.type == 2) and (0) or (S.cabacInit + 1))) + S.lastQpd = false + local addr = S.firstMb + local total = S.mbW * S.mbH + local st = S.type + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) + local hook = S.hook + local every = Mb.YIELD_MBS + while true do + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + if st ~= 2 and mbSkipFlag(S, M) == 1 then + Mb.skip(S, M, skipKind) + S.lastQpd = false + else + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + end + addr =addr+ 1 + if hook and addr % every == 0 then + pcall(hook) -- (may yield: the engine state lives in this module's locals, see Decoder Options.yield) + end + if epos > elimit + 8 then + return false, "truncated: slice data" + end + if terminate() == 1 then + break + end + end + return true +end + +return Cabac +end +__FILES["codecs/video/H264/Cavlc"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): +-- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and +-- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. +-- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. +-- Never throws: returns false, "message" on bad data. +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT +local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y + +local Cavlc = {} + +-- ------------------------------------------------------------------------------------------------ vlc tables +-- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or +-- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code +local function build(entries) +local l1 = table.create(256, 0) + local l2 = {} + local nsub = 0 + for _, e in __iter(entries) do + local code, len, val = e[1], e[2], e[3] + local packed = val * 32 + len + if len <= 8 then + local s = code * 2 ^ (8 - len) + for k = 0, 2 ^ (8 - len) - 1 do + l1[s + k + 1] = packed + end + else + local prefix = math.floor(code / 2 ^ (len - 8) +) local base = -l1[prefix + 1] + if base <= 0 then + base = nsub * 256 + 1 + nsub =nsub+ 1 + for k = 0, 255 do + l2[base + k] = 0 + end + l1[prefix + 1] = -base + end + local s = (code % 2 ^ (len - 8)) * 2 ^ (16 - len) + for k = 0, 2 ^ (16 - len) - 1 do + l2[base + s + k] = packed + end + end + end + return l1, l2 +end + +-- coeff_token: CT1[class + 1], CT2[class + 1]; value = TotalCoeff * 4 + TrailingOnes +local CT1, CT2 = {}, {} +for t = 0, 4 do + local src = (Tables )["COEFF_TOKEN_" .. t] + local entries = {} + for i = 1, #src, 4 do + table.insert(entries, { src[i], src[i + 1], src[i + 2] * 4 + src[i + 3] }) + end + CT1[t + 1], CT2[t + 1] = build(entries) +end + +-- total_zeros by tzVlcIndex (luma 1..15, chroma DC 1..3), run_before by min(zerosLeft, 7) +local function group(src, n) +local per = {} + for i = 1, n do + per[i] = {} + end + for i = 1, #src, 4 do + table.insert(per[src[i] ], { src[i + 1], src[i + 2], src[i + 3] }) + end + local a, b = {}, {} + for i = 1, n do + a[i], b[i] = build(per[i]) + end + return a, b +end +local TZ1, TZ2 = group(Tables.TOTAL_ZEROS, 15) +local TZC1, TZC2 = group(Tables.TOTAL_ZEROS_CDC, 3) +local RB1, RB2 = group(Tables.RUN_BEFORE, 7) + +-- scans: coefficient index (1-based) -> raster position (0-based) +local ZZ4 = Tables.ZIGZAG4 +local ZZAC = table.create(15, 0) +for i = 1, 15 do + ZZAC[i] = ZZ4[i + 1] +end +local ZZ8I = {} -- [i4 + 1][k + 1] = raster position in the 8x8 block of the k-th coefficient of interleaved list i4 +for i4 = 0, 3 do + local t = table.create(16, 0) + for k = 0, 15 do + t[k + 1] = Tables.ZIGZAG8[4 * k + i4 + 1] + end + ZZ8I[i4 + 1] = t +end +local IDENT = { 0, 1, 2, 3 } + +local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP + +-- ------------------------------------------------------------------------------------------------ residual +local LEVEL = table.create(16, 0) +local RUN = table.create(16, 0) + +local peek = Bitstream.peekAt +local clz32 = Bitstream.clz32 +local P2 = Bitstream.P2 + +-- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to +-- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels) +local function residual(r, nC, maxCoeff, out, base, scan, mul, div) +local b, n = r.buf, r.n + local pos = r.pos + local cls + if nC < 0 then + cls = 5 + elseif nC < 2 then + cls = 1 + elseif nC < 4 then + cls = 2 + elseif nC < 8 then + cls = 3 + else + cls = 4 + end + local v = math.floor(peek(b, n, pos) / 65536 +) local e = CT1[cls][math.floor(v / 256 )+ 1] + if e < 0 then + e = CT2[cls][-e + v % 256] + end + if e == 0 then + return -1 + end + pos =pos+ e % 32 + local tok = math.floor(e / 32 +) local tc = math.floor(tok / 4 +) local t1 = tok % 4 + if tc == 0 then + r.pos = pos + return 0 + end + if tc > maxCoeff then + return -1 + end + -- levels + local w = peek(b, n, pos) + for i = 0, t1 - 1 do + LEVEL[i + 1] = 1 - 2 * ((math.floor(w / P2[32 - i])) % 2) + end + pos =pos+ t1 + local suffixLength = ((tc > 10 and t1 < 3) and (1) or (0)) + for i = t1, tc - 1 do + w = peek(b, n, pos) + local prefix = w == 0 and 32 or clz32(w) + if prefix > 28 then + return -1 + end + pos =pos+ (prefix + 1 +) local size = suffixLength + if prefix == 14 and suffixLength == 0 then + size = 4 + elseif prefix >= 15 then + size = prefix - 3 + end + local levelCode = (((prefix < 15) and (prefix) or (15))) * 2 ^ suffixLength + if size > 0 then + levelCode =levelCode+ math.floor(peek(b, n, pos) / P2[33 - size] +) pos =pos+ size + end + if prefix >= 15 and suffixLength == 0 then + levelCode =levelCode+ 15 + end + if prefix >= 16 then + levelCode =levelCode+ (2 ^ (prefix - 3) - 4096 +) end + if i == t1 and t1 < 3 then + levelCode =levelCode+ 2 + end + local level + if levelCode % 2 == 0 then + level = math.floor((levelCode + 2) / 2 +) else + level = -(math.floor((levelCode + 1) / 2)) + end + LEVEL[i + 1] = level + if suffixLength == 0 then + suffixLength = 1 + end + local a = ((level < 0) and (-level) or (level)) + if a > 3 * 2 ^ (suffixLength - 1) and suffixLength < 6 then + suffixLength =suffixLength+ 1 + end + end + -- total_zeros + local zerosLeft = 0 + if tc < maxCoeff then + v = math.floor(peek(b, n, pos) / 65536 +) local l1, l2 + if maxCoeff == 4 then + l1, l2 = TZC1[tc], TZC2[tc] + else + l1, l2 = TZ1[tc], TZ2[tc] + end + e = l1[math.floor(v / 256 )+ 1] + if e < 0 then + e = l2[-e + v % 256] + end + if e == 0 then + return -1 + end + pos =pos+ e % 32 + zerosLeft = math.floor(e / 32 +) if zerosLeft + tc > maxCoeff then + return -1 + end + end + -- run_before + for i = 0, tc - 2 do + local run = 0 + if zerosLeft > 0 then + local t = ((zerosLeft > 7) and (7) or (zerosLeft)) + v = math.floor(peek(b, n, pos) / 65536 +) e = RB1[t][math.floor(v / 256 )+ 1] + if e < 0 then + e = RB2[t][-e + v % 256] + end + if e == 0 then + return -1 + end + pos =pos+ e % 32 + run = math.floor(e / 32 +) if run > zerosLeft then + return -1 + end + end + RUN[i + 1] = run + zerosLeft =zerosLeft- run + end + RUN[tc] = zerosLeft + r.pos = pos + -- place (highest frequency first) + local k = -1 + local half = math.floor(div / 2 +) for i = tc - 1, 0, -1 do + k =k+ (RUN[i + 1] + 1 +) local p = scan[k + 1] + if mul then + out[base + p + 1] = math.floor((LEVEL[i + 1] * mul[p + 1] + half) / div +) else + out[base + p + 1] = LEVEL[i + 1] + end + end + return tc +end +Cavlc.residual = residual + +-- ------------------------------------------------------------------------------------------------ macroblock +local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } +local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local SUB_N = { 1, 2, 2, 4 } +local BPAIR0 = { 1, 2, 1, 2, 1, 2, 3, 3, 3 } +local BPAIR1 = { 1, 2, 2, 1, 3, 3, 1, 2, 3 } + +local function refIdx(r, n) +if n <= 1 then + return 0 + end + local v + if n == 2 then + v = 1 - u1(r) + else + v = ue(r) + end + if v >= n then + return -1 + end + return v +end + +-- the residual of the parsed macroblock +local function residuals(S, M, r) +local kind = M.kind + local cbp = M.cbp + local intra = kind <= K_PCM + local dq = S.dq + local qp = M.qp + local w4, g0 = S.w4, M.g0 + local grid = S.nzc + local nz = M.nz + local c4 = M.c4 + if kind == K_I16 then + local tc = residual(r, Mb.nC(S, M, 0, 0), 16, M.dcY, 0, ZZ4, nil, 1) + if tc < 0 then + return false, "bad Intra16x16 DC residual" + end + M.hasDcY = tc > 0 + end + local mul4 = dq.d4[((intra) and (1) or (4))][qp + 1] + if M.t8 == 1 then + local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1] + local c8 = M.c8 + for i8 = 0, 3 do + local bx0, by0 = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local sum = 0 + for i4 = 0, 3 do + local bx, by = bx0 + i4 % 2, by0 + math.floor(i4 / 2 +) local tc = 0 + if (math.floor(cbp / P2[i8 + 1])) % 2 ~= 0 then + tc = residual(r, Mb.nC(S, M, bx, by), 16, c8, i8 * 64, ZZ8I[i4 + 1], mul8, 64) + if tc < 0 then + return false, "bad 8x8 luma residual" + end + end + grid[g0 + by * w4 + bx] = tc + sum =sum+ tc + end + nz[by0 * 4 + bx0 + 1] = sum + nz[by0 * 4 + bx0 + 2] = sum + nz[by0 * 4 + bx0 + 5] = sum + nz[by0 * 4 + bx0 + 6] = sum + end + else + local ac = kind == K_I16 + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local tc = 0 + if (math.floor(cbp / P2[math.floor(i / 4 )+ 1])) % 2 ~= 0 then + if ac then + tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16) + else + tc = residual(r, Mb.nC(S, M, bx, by), 16, c4, blk * 16, ZZ4, mul4, 16) + end + if tc < 0 then + return false, "bad luma residual" + end + end + grid[g0 + by * w4 + bx] = tc + nz[blk + 1] = tc + end + end + -- chroma + local chroma = math.floor(cbp / 16 +) local cw, c0 = S.cw4, M.c0 + local nzcCb, nzcCr = S.nzcCb, S.nzcCr + local nzc = M.nzc + if chroma ~= 0 then + local any = false + for plane = 0, 1 do + local tc = residual(r, -1, 4, M.dcC, plane * 4, IDENT, nil, 1) + if tc < 0 then + return false, "bad chroma DC residual" + end + if tc > 0 then + any = true + end + end + M.hasDcC = any + end + local cc = M.cc + for plane = 0, 1 do + local tab = ((plane == 0) and (nzcCb) or (nzcCr)) + local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1] + for blk = 0, 3 do + local bx, by = blk % 2, math.floor(blk / 2 +) local tc = 0 + if chroma == 2 then + tc = residual(r, Mb.nCc(S, M, tab, bx, by), 15, cc, (plane * 4 + blk) * 16, ZZAC, mulc, 16) + if tc < 0 then + return false, "bad chroma AC residual" + end + end + tab[c0 + by * cw + bx] = tc + nzc[plane * 4 + blk + 1] = tc + end + end + return true +end + +local function setQp(S, M, delta) +if delta < -26 or delta > 25 then + return false + end + local qp = (S.qp + delta + 52) % 52 + S.qp = qp + M.qp = qp + M.qpc = S.qpcOf[qp + 1] + M.qpc2 = S.qpc2Of[qp + 1] + return true +end + +local function clearLumaGrids(S, M, intra) + -- the CABAC-only grids stay zero for CAVLC; intra modes for non-NxN macroblocks are written by Mb.recon + local _ = intra + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end +end + +-- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) +local function intraMb(S, M, r, t) +local addr = M.addr + 1 + if t == 25 then + M.kind = K_PCM + r.pos = math.floor((r.pos + 7) / 8 )* 8 + local p = math.floor(r.pos / 8 +) if p + 384 > math.floor(r.size / 8 )then + return false, "truncated: I_PCM samples" + end + buffer.copy(M.pcm, 0, r.buf, p, 384) + r.pos =r.pos+ 3072 + M.qp = S.qp + M.qpc, M.qpc2 = 0, 0 + M.cbp = 0x2f + local w4, g0 = S.w4, M.g0 + for j = 0, 3 do + for i = 0, 3 do + S.nzc[g0 + j * w4 + i] = 16 + end + end + local cw, c0 = S.cw4, M.c0 + for j = 0, 1 do + for i = 0, 1 do + S.nzcCb[c0 + j * cw + i] = 16 + S.nzcCr[c0 + j * cw + i] = 16 + end + end + S.cbpTab[addr] = 0x2f + S.dcTab[addr] = 7 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + Mb.recon(S, M) + return true + end + clearLumaGrids(S, M, true) + if t == 0 then + M.kind = K_I4 + if S.t8mode and u1(r) == 1 then + M.kind = K_I8 + M.t8 = 1 + end + local ipm = M.ipm + local grid = S.ipm + local w4, g0 = S.w4, M.g0 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + local g = g0 + by * w4 + bx + grid[g], grid[g + 1], grid[g + w4], grid[g + w4 + 1] = mode, mode, mode, mode + end + else + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local pred = Mb.predMode(S, M, bx, by) + local mode = pred + if u1(r) == 0 then + local rem = u(r, 3) + mode = ((rem < pred) and (rem) or (rem + 1)) + end + ipm[by * 4 + bx + 1] = mode + grid[g0 + by * w4 + bx] = mode + end + end + M.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTRA_CBP[code + 1] + elseif t <= 24 then + M.kind = K_I16 + M.i16 = (t - 1) % 4 + M.cbp = (math.floor((t - 1) / 4)) % 3 * 16 + (((t >= 13) and (15) or (0))) + M.cpm = ue(r) + if M.cpm > 3 then + return false, "intra_chroma_pred_mode out of range" + end + else + return false, "mb_type out of range" + end + S.cpmTab[addr] = M.cpm + S.cbpTab[addr] = M.cbp + if M.cbp > 0 or M.kind == K_I16 then + if not setQp(S, M, Bitstream.se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +-- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types +local function interMb(S, M, r, t, isB) +clearLumaGrids(S, M, false) + local n0, n1 = S.n0, S.n1 + local pf, sub, dir, ref0, ref1, mvd0, mvd1 = M.pf, M.sub, M.dir, M.ref0, M.ref1, M.mvd0, M.mvd1 + for i = 1, 4 do + dir[i] = false + ref0[i], ref1[i] = 0, 0 + end + for i = 1, 32 do + mvd0[i], mvd1[i] = 0, 0 + end + local noSmall = true + if not isB then + M.kind = K_P + if t > 4 then + return false, "mb_type out of range" + end + M.part = ((t >= 3) and (3) or (t)) + pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1 + if M.part == 3 then + for i = 1, 4 do + local s = ue(r) + if s > 3 then + return false, "sub_mb_type out of range" + end + sub[i] = s + if s > 0 then + noSmall = false + end + end + for i = 1, 4 do + local v = ((t == 4) and (0) or (refIdx(r, n0))) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + for i = 0, 3 do + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + local n = ((M.part == 0) and (1) or (2)) + for p = 1, n do + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + for p = 1, n do + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + else + if t == 0 then + M.kind = K_BDIRECT + M.part = 0 + if not S.direct8x8 then + noSmall = false + end + elseif t <= 21 then + M.kind = K_B + if t <= 3 then + M.part = 0 + pf[1] = t + else + M.part = ((t % 2 == 0) and (1) or (2)) + local k = math.floor((t - 4) / 2 )+ 1 + pf[1], pf[2] = BPAIR0[k], BPAIR1[k] + end + local n = ((M.part == 0) and (1) or (2)) + for p = 1, n do + if pf[p] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[p] = v + end + end + for p = 1, n do + if pf[p] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[p] = v + end + end + for p = 1, n do + if pf[p] % 2 == 1 then + mvd0[2 * p - 1] = se(r) + mvd0[2 * p] = se(r) + end + end + for p = 1, n do + if pf[p] >= 2 then + mvd1[2 * p - 1] = se(r) + mvd1[2 * p] = se(r) + end + end + elseif t == 22 then + M.kind = K_B + M.part = 3 + for i = 1, 4 do + local s = ue(r) + if s > 12 then + return false, "sub_mb_type out of range" + end + pf[i] = SUBB_PF[s + 1] + sub[i] = SUBB_SHAPE[s + 1] + dir[i] = s == 0 + if s == 0 then + if not S.direct8x8 then + noSmall = false + end + elseif SUB_N[sub[i] + 1] > 1 then + noSmall = false + end + end + for i = 1, 4 do + if not dir[i] and pf[i] % 2 == 1 then + local v = refIdx(r, n0) + if v < 0 then + return false, "ref_idx_l0 out of range" + end + ref0[i] = v + end + end + for i = 1, 4 do + if not dir[i] and pf[i] >= 2 then + local v = refIdx(r, n1) + if v < 0 then + return false, "ref_idx_l1 out of range" + end + ref1[i] = v + end + end + for l = 0, 1 do + local mvd = ((l == 0) and (mvd0) or (mvd1)) + for i = 0, 3 do + local uses = pf[i + 1] >= 2 + if l == 0 then + uses = pf[i + 1] % 2 == 1 + end + if uses and not dir[i + 1] then + for k = 0, SUB_N[sub[i + 1] + 1] - 1 do + local p = i * 4 + k + 1 + mvd[2 * p - 1] = se(r) + mvd[2 * p] = se(r) + end + end + end + end + else + return false, "mb_type out of range" + end + end + local code = ue(r) + if code > 47 then + return false, "coded_block_pattern out of range" + end + M.cbp = INTER_CBP[code + 1] + M.t8 = 0 + if M.cbp % 16 ~= 0 and S.t8mode and noSmall then + M.t8 = u1(r) + end + local addr = M.addr + 1 + S.cbpTab[addr] = M.cbp + S.cpmTab[addr] = 0 + if M.cbp > 0 then + if not setQp(S, M, se(r)) then + return false, "mb_qp_delta out of range" + end + else + setQp(S, M, 0) + end + if r.pos > r.size then + return false, "truncated: macroblock" + end + local ok, err = residuals(S, M, r) + if not ok then + return false, err + end + Mb.recon(S, M) + return true +end + +-- macroblock(S, M, r) -> true | false, message +local function macroblock(S, M, r) +local t = ue(r) + local st = S.type + if st == 2 then + return intraMb(S, M, r, t) + elseif st == 0 then + if t >= 5 then + return intraMb(S, M, r, t - 5) + end + return interMb(S, M, r, t, false) + end + if t >= 23 then + return intraMb(S, M, r, t - 23) + end + return interMb(S, M, r, t, true) +end + +-- ------------------------------------------------------------------------------------------------ slice data +-- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data +function Cavlc.slice(S, M, r) +local addr = S.firstMb + local total = S.mbW * S.mbH + local st = S.type + local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) + local more = true + local hook = S.hook + local every = Mb.YIELD_MBS + repeat + if st ~= 2 then + local run = ue(r) + if run > total - addr then + return false, "mb_skip_run past the end of the picture" + end + for _ = 1, run do + Mb.start(S, M, addr) + Mb.skip(S, M, skipKind) + addr =addr+ 1 + end + if run > 0 then + more = Bitstream.moreData(r) + end + end + if more then + if addr >= total then + return false, "slice data past the end of the picture" + end + Mb.start(S, M, addr) + local ok, err = macroblock(S, M, r) + if not ok then + return false, err + end + addr =addr+ 1 + if hook and addr % every == 0 then + pcall(hook) + end + if r.pos > r.size then + return false, "truncated: slice data" + end + more = Bitstream.moreData(r) + end + until not more + return true +end + +return Cavlc +end +__FILES["codecs/video/H264/Deblock"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: +-- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 +-- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the +-- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its +-- slices are decoded (the result equals filtering each macroblock as it is decoded). +-- Never throws. +local Tables = __include("codecs/video/H264/Tables") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0 + +local Deblock = {} + +local BS = table.create(4, 0) + +local min, max = math.min, math.max +local function clip3(lo, hi, v) +return min(max(v, lo), hi) +end + +local abs = math.abs + +-- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1 +-- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four +-- strengths +local function luma(b, o, across, along, qp, aOff, bOff) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for seg = 0, 3 do + local bS = BS[seg + 1] + if bS > 0 then + local tc0 = TC0[(indexA + 12) * 4 + bS + 1] + for k = 0, 3 do + local q = o + (seg * 4 + k) * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + local p2 = readu8(b, q - 3 * across) + local q2 = readu8(b, q + 2 * across) + local ap = abs(p2 - p0) + local aq = abs(q2 - q0) + if bS < 4 then + local tc = tc0 + (((ap < beta) and (1) or (0))) + (((aq < beta) and (1) or (0))) + local delta = clip3(-tc, tc, math.floor(((q0 - p0) * 4 + (p1 - q1) + 4) / 8)) + writeu8(b, q - across, clip3(0, 255, p0 + delta)) + writeu8(b, q, clip3(0, 255, q0 - delta)) + if ap < beta then + writeu8(b, q - 2 * across, p1 + clip3(-tc0, tc0, math.floor((p2 + math.floor((p0 + q0 + 1) / 2 )- 2 * p1) / 2))) + end + if aq < beta then + writeu8(b, q + across, q1 + clip3(-tc0, tc0, math.floor((q2 + math.floor((p0 + q0 + 1) / 2 )- 2 * q1) / 2))) + end + else + local strong = abs(p0 - q0) < math.floor(alpha / 4 )+ 2 + if ap < beta and strong then + local p3 = readu8(b, q - 4 * across) + writeu8(b, q - across, math.floor((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) / 8)) + writeu8(b, q - 2 * across, math.floor((p2 + p1 + p0 + q0 + 2) / 4)) + writeu8(b, q - 3 * across, math.floor((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) / 8)) + else + writeu8(b, q - across, math.floor((2 * p1 + p0 + q1 + 2) / 4)) + end + if aq < beta and strong then + local q3 = readu8(b, q + 3 * across) + writeu8(b, q, math.floor((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) / 8)) + writeu8(b, q + across, math.floor((p0 + q0 + q1 + q2 + 2) / 4)) + writeu8(b, q + 2 * across, math.floor((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) / 8)) + else + writeu8(b, q, math.floor((2 * q1 + q0 + p1 + 2) / 4)) + end + end + end + end + end + end +end + +-- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) +local function chroma(b, o, across, along, qp, aOff, bOff) + local indexA = clip3(0, 51, qp + aOff) + local alpha = ALPHA[indexA + 13] + local beta = BETA[clip3(0, 51, qp + bOff) + 13] + if alpha == 0 or beta == 0 then + return + end + for i = 0, 7 do + local bS = BS[math.floor(i / 2 )+ 1] + if bS > 0 then + local q = o + i * along + local p0 = readu8(b, q - across) + local q0 = readu8(b, q) + local p1 = readu8(b, q - 2 * across) + local q1 = readu8(b, q + across) + if abs(p0 - q0) < alpha and abs(p1 - p0) < beta and abs(q1 - q0) < beta then + if bS < 4 then + local tc = TC0[(indexA + 12) * 4 + bS + 1] + 1 + local delta = clip3(-tc, tc, math.floor(((q0 - p0) * 4 + (p1 - q1) + 4) / 8)) + writeu8(b, q - across, clip3(0, 255, p0 + delta)) + writeu8(b, q, clip3(0, 255, q0 - delta)) + else + writeu8(b, q - across, math.floor((2 * p1 + p0 + q1 + 2) / 4)) + writeu8(b, q, math.floor((2 * q1 + q0 + p1 + 2) / 4)) + end + end + end + end +end + +-- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) +local function mvDiff(mvA, a, mvB, b) +return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 +end + +local function motionDiffers(pic, p, q) +local uid0, uid1, mv0, mv1 = pic.uid0, pic.uid1, pic.mv0, pic.mv1 + local pa, pb, qa, qb = uid0[p], uid1[p], uid0[q], uid1[q] + local np = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0))) + local nq = (((qa >= 0) and (1) or (0))) + (((qb >= 0) and (1) or (0))) + if np ~= nq then + return true + end + if np == 1 then + local pr, pm = pa, mv0 + if pa < 0 then + pr, pm = pb, mv1 + end + local qr, qm = qa, mv0 + if qa < 0 then + qr, qm = qb, mv1 + end + if pr ~= qr then + return true + end + return mvDiff(pm, p, qm, q) + elseif np == 0 then + return false + end + if not ((pa == qa and pb == qb) or (pa == qb and pb == qa)) then + return true + end + if pa ~= pb then + if pa == qa then + return mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q) + end + return mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q) + end + return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) +end + +-- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset } +function Deblock.picture(S, pic, params) + local mbW, mbH = S.mbW, S.mbH + local w4 = S.w4 + local kind, sliceTab, qpTab, qpcTab, qpc2Tab, t8Tab = S.kind, S.sliceTab, S.qpTab, S.qpcTab, S.qpc2Tab, S.t8Tab + local nzDb = S.nzDb + local ys, cs = pic.ys, pic.cs + local Y, U, V = pic.y, pic.u, pic.v + local hook = S.hook + for my = 0, mbH - 1 do + if hook and my > 0 then + pcall(hook) + end + for mx = 0, mbW - 1 do +local __DARKLUA_CONTINUE_5=false repeat local addr = my * mbW + mx + 1 + local sn = sliceTab[addr] + local prm = params[sn] + if sn == 0 or not prm or prm[1] == 1 then +__DARKLUA_CONTINUE_5=true break + end + local idc, aOff, bOff = prm[1], prm[2], prm[3] + local intraQ = kind[addr] <= 4 + local t8 = t8Tab[addr] == 1 + local qpQ, qpcQ, qpc2Q = qpTab[addr], qpcTab[addr], qpc2Tab[addr] + local g0 = my * 4 * w4 + mx * 4 + 1 + local lo = pic.yo + my * 16 * ys + mx * 16 + local co = pic.co + my * 8 * cs + mx * 8 + for dir = 0, 1 do + -- dir 0: vertical edges (left neighbour), dir 1: horizontal edges (top neighbour) + local nAddr = ((dir == 0) and (addr - 1) or (addr - mbW)) + local edgeOk = my > 0 + if dir == 0 then + edgeOk = mx > 0 + end + if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then + edgeOk = false + end + if edgeOk and sliceTab[nAddr] == 0 then + edgeOk = false + end + for e = 0, 3 do +local __DARKLUA_CONTINUE_7=false repeat if e == 0 and not edgeOk then +__DARKLUA_CONTINUE_7=true break + end + if t8 and (e == 1 or e == 3) then +__DARKLUA_CONTINUE_7=true break + end + -- strengths of the four segments + local intraP = intraQ + local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q + if e == 0 then + intraP = kind[nAddr] <= 4 + qpP, qpcP, qpc2P = qpTab[nAddr], qpcTab[nAddr], qpc2Tab[nAddr] + end + local any = false + for k = 0, 3 do + local qg, pg + if dir == 0 then + qg = g0 + k * w4 + e + pg = qg - 1 + else + qg = g0 + e * w4 + k + pg = qg - w4 + end + local bS + if intraP or intraQ then + bS = ((e == 0) and (4) or (3)) + elseif nzDb[qg] ~= 0 or nzDb[pg] ~= 0 then + bS = 2 + elseif motionDiffers(pic, pg, qg) then + bS = 1 + else + bS = 0 + end + BS[k + 1] = bS + if bS > 0 then + any = true + end + end + if not any then +__DARKLUA_CONTINUE_7=true break + end + local qpav = math.floor((qpP + qpQ + 1) / 2 +) if dir == 0 then + luma(Y, lo + e * 4, 1, ys, qpav, aOff, bOff) + else + luma(Y, lo + e * 4 * ys, ys, 1, qpav, aOff, bOff) + end + if e % 2 == 0 then + local qc = math.floor((qpcP + qpcQ + 1) / 2 +) local qc2 = math.floor((qpc2P + qpc2Q + 1) / 2 +) if dir == 0 then + chroma(U, co + e * 2, 1, cs, qc, aOff, bOff) + chroma(V, co + e * 2, 1, cs, qc2, aOff, bOff) + else + chroma(U, co + e * 2 * cs, cs, 1, qc, aOff, bOff) + chroma(V, co + e * 2 * cs, cs, 1, qc2, aOff, bOff) + end + end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + end +__DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end + end +end + +return Deblock +end +__FILES["codecs/video/H264/Decoder"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit +-- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), +-- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output +-- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, +-- deblocking and border extension. Written from the spec. +-- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). +local Bitstream = __include("codecs/video/H264/Bitstream") +local Params = __include("codecs/video/H264/Params") +local Slice = __include("codecs/video/H264/Slice") +local Tables = __include("codecs/video/H264/Tables") +local Mb = __include("codecs/video/H264/Mb") +local Cavlc = __include("codecs/video/H264/Cavlc") +local Cabac = __include("codecs/video/H264/Cabac") +local Deblock = __include("codecs/video/H264/Deblock") +local Inter = __include("codecs/video/H264/Inter") +local Types = __include("Types") + +local PAD, PADC = Inter.PAD, Inter.PADC +local CHROMA_QP = Tables.CHROMA_QP + +local Decoder = {} +Decoder.__index = Decoder + +-- new(opts) -> decoder state + + + + + + + + + + + +function Decoder.new(opts) +local o = opts or {} + return setmetatable({ + opts = o, + maxPixels = o.maxPixels or 2 ^ 22, + spsTab = {}, + ppsTab = {}, + dqCache = {}, + cur = nil, + curSh = nil, + S = nil, + M = Mb.new(), + refs = {}, -- reference pictures (short and long term) + waiting = {}, -- decoded pictures not output yet + out = {}, + uid = 0, + prevRefFrameNum = 0, + prevPocMsb = 0, + prevPocLsb = 0, + prevFrameNumOffset = 0, + prevFrameNum = 0, + maxLongTermIdx = -1, + pool = {}, + gray = nil, + frames = 0, -- pictures decoded + errors = 0, + lastError = nil, + fatal = nil, + seqW = 0, + seqH = 0, + }, Decoder) +end + +-- ------------------------------------------------------------------------------------------------ pictures +local function newPicture(self, sps) +local mbW, mbH = sps.mbWidth, sps.mbHeight + local pool = self.pool + for i = #pool, 1, -1 do + local p = pool[i] + if p.mbW == mbW and p.mbH == mbH then + table.remove(pool, i) + return p + end + end + local w, h = mbW * 16, mbH * 16 + local ys = w + 2 * PAD + local cs = math.floor(w / 2 )+ 2 * PADC + local n4 = mbW * mbH * 16 + return { + mbW = mbW, + mbH = mbH, + ys = ys, + cs = cs, + yo = PAD * ys + PAD, + co = PADC * cs + PADC, + y = buffer.create(ys * (h + 2 * PAD)), + u = buffer.create(cs * (math.floor(h / 2 )+ 2 * PADC)), + v = buffer.create(cs * (math.floor(h / 2 )+ 2 * PADC)), + mbIntra = table.create(mbW * mbH, true), + ref0 = table.create(n4, -1), + ref1 = table.create(n4, -1), + uid0 = table.create(n4, -1), + uid1 = table.create(n4, -1), + mv0 = table.create(n4 * 2, 0), + mv1 = table.create(n4 * 2, 0), + uid = 0, + poc = 0, + frameNum = 0, + long = false, + short = false, + longIdx = 0, + waiting = false, + pts = 0, + } +end + +local function release(self, p) + if not p.short and not p.long and not p.waiting and p ~= self.cur and p ~= self.gray then + for _, q in __iter(self.pool) do + if q == p then + return + end + end + table.insert(self.pool, p) + end +end + +local function grayPicture(self, sps) +local g = self.gray + if g and g.mbW == sps.mbWidth and g.mbH == sps.mbHeight then + return g + end + g = newPicture(self, sps) + buffer.fill(g.y, 0, 128) + buffer.fill(g.u, 0, 128) + buffer.fill(g.v, 0, 128) + self.uid =self.uid+ 1 + g.uid = self.uid + self.gray = g + return g +end + +-- ------------------------------------------------------------------------------------------------ output +local function emit(self, p) + p.waiting = false + local sps = p.sps + local W, H = sps.width, sps.height + local img = Types.Image.new(W, H, "yuv420p") + local px = img.pixels + local cx, cy = sps.cropX, sps.cropY + for y = 0, H - 1 do + buffer.copy(px, y * W, p.y, p.yo + (cy + y) * p.ys + cx, W) + end + local cw, ch = math.floor((W + 1) / 2), math.floor((H + 1) / 2 +) local ub, vb = W * H, W * H + cw * ch + for y = 0, ch - 1 do + buffer.copy(px, ub + y * cw, p.u, p.co + (math.floor(cy / 2 )+ y) * p.cs + math.floor(cx / 2), cw) + buffer.copy(px, vb + y * cw, p.v, p.co + (math.floor(cy / 2 )+ y) * p.cs + math.floor(cx / 2), cw) + end + img.meta.source = { format = "h264", bitDepth = 8, profile = sps.profile, level = sps.level, poc = p.poc, keyframe = p.idr } + if sps.sarW and sps.sarH then + img.meta.sar = { sps.sarW, sps.sarH } + end + img.meta.yuv = { range = sps.fullRange and"full" or"limited", matrix = sps.matrix == 1 and"bt709" or"bt601" } + table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr }) + release(self, p) +end + +local function bump(self, keep) + local w = self.waiting + while #w > keep do + local best = 1 + for i = 2, #w do + if w[i].poc < w[best].poc then + best = i + end + end + local p = table.remove(w, best) + emit(self, p) + end +end + +local function reorderDepth(self, sps) +if self.opts.lowDelay then + return 0 + end + if sps.numReorderFrames then + return sps.numReorderFrames + end + if sps.pocType == 2 then + return 0 + end + return sps.maxDecFrameBuffering or sps.maxDpbFrames +end + +-- ------------------------------------------------------------------------------------------------ reference lists +local function shortRefs(self) +local t = {} + for _, p in __iter(self.refs) do + if p.short then + table.insert(t, p) + end + end + return t +end + +local function longRefs(self) +local t = {} + for _, p in __iter(self.refs) do + if p.long then + table.insert(t, p) + end + end + table.sort(t, function(a, b) + return a.longIdx < b.longIdx + end) + return t +end + +local function picNums(self, sh) + local maxFrameNum = 2 ^ sh.sps.log2MaxFrameNum + for _, p in __iter(self.refs) do + if p.short then + p.picNum = (p.frameNum > sh.frameNum and((p.frameNum - maxFrameNum ))or(p.frameNum +)) end + end +end + +local function modify(self, list, ops, n, sh) +if #ops == 0 then + return true + end + local maxPicNum = 2 ^ sh.sps.log2MaxFrameNum + local curr = sh.frameNum + local pred = curr + local idx = 0 + for i = 1, #ops, 2 do + local idc, v = ops[i], ops[i + 1] + local pic = nil + if idc == 0 or idc == 1 then + local absDiff = v + 1 + if absDiff > maxPicNum then + return false + end + local noWrap + if idc == 0 then + noWrap = pred - absDiff + if noWrap < 0 then + noWrap =noWrap+ maxPicNum + end + else + noWrap = pred + absDiff + if noWrap >= maxPicNum then + noWrap =noWrap- maxPicNum + end + end + pred = noWrap + local picNum = (noWrap > curr and((noWrap - maxPicNum ))or(noWrap +)) for _, p in __iter(self.refs) do + if p.short and p.picNum == picNum then + pic = p + break + end + end + elseif idc == 2 then + for _, p in __iter(self.refs) do + if p.long and p.longIdx == v then + pic = p + break + end + end + else + return false + end + if not pic then + return false + end + if idx >= n then + return false + end + table.insert(list, idx + 1, pic) + local k = idx + 2 + while k <= #list do + if list[k] == pic then + table.remove(list, k) + else + k =k+ 1 + end + end + idx =idx+ 1 + end + return true +end + +-- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active) +local function buildLists(self, sh, cur) +picNums(self, sh) + local list0, list1 = {}, {} + local shorts = shortRefs(self) + local longs = longRefs(self) + if sh.type == Slice.P then + table.sort(shorts, function(a, b) + return a.picNum > b.picNum + end) + for _, p in __iter(shorts) do + table.insert(list0, p) + end + for _, p in __iter(longs) do + table.insert(list0, p) + end + else + local before, after = {}, {} + for _, p in __iter(shorts) do + if p.poc < cur.poc then + table.insert(before, p) + else + table.insert(after, p) + end + end + table.sort(before, function(a, b) + return a.poc > b.poc + end) + table.sort(after, function(a, b) + return a.poc < b.poc + end) + for _, p in __iter(before) do + table.insert(list0, p) + end + for _, p in __iter(after) do + table.insert(list0, p) + end + for _, p in __iter(after) do + table.insert(list1, p) + end + for _, p in __iter(before) do + table.insert(list1, p) + end + for _, p in __iter(longs) do + table.insert(list0, p) + table.insert(list1, p) + end + if #list1 > 1 and #list0 == #list1 then + local same = true + for i = 1, #list0 do + if list0[i] ~= list1[i] then + same = false + break + end + end + if same then + list1[1], list1[2] = list1[2], list1[1] + end + end + end + local n0, n1 = sh.numRefIdxL0, sh.numRefIdxL1 + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + local ok = modify(self, list0, sh.mod0 or {}, n0, sh) + if sh.type == Slice.B then + ok = modify(self, list1, sh.mod1 or {}, n1, sh) and ok + end + for i = #list0, n0 + 1, -1 do + list0[i] = nil + end + for i = #list1, n1 + 1, -1 do + list1[i] = nil + end + return list0, list1, ok +end + +-- ------------------------------------------------------------------------------------------------ marking +local function unmark(self, p) + p.short = false + p.long = false + for i, q in __iter(self.refs) do + if q == p then + table.remove(self.refs, i) + break + end + end + release(self, p) +end + +local function slidingWindow(self, sps, frameNum) + local maxRefs = math.max(sps.maxRefFrames, 1) + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + while #self.refs >= maxRefs do + local oldest, ow = nil, math.huge + for _, p in __iter(self.refs) do + if p.short then + local w = (p.frameNum > frameNum and((p.frameNum - maxFrameNum ))or(p.frameNum +)) if w < ow then + oldest, ow = p, w + end + end + end + if not oldest then + -- only long-term references left: drop the lowest index (bad stream) + oldest = self.refs[1] + end + unmark(self, oldest) + end +end + +local function addRef(self, p) + for _, q in __iter(self.refs) do + if q == p then + return + end + end + table.insert(self.refs, p) +end + +-- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present +local function mark(self, cur, sh) +local sps = sh.sps + if sh.idr then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + if sh.longTermReference then + cur.long = true + cur.longIdx = 0 + self.maxLongTermIdx = 0 + else + cur.short = true + self.maxLongTermIdx = -1 + end + addRef(self, cur) + return false + end + local mmco5 = false + local becameLong = false + if sh.adaptive and sh.mmco then + picNums(self, sh) + local ops = sh.mmco + for i = 1, #ops, 3 do + local op, a, b = ops[i], ops[i + 1], ops[i + 2] + if op == 1 then + local picNum = sh.frameNum - a + for _, p in __iter(self.refs) do + if p.short and p.picNum == picNum then + unmark(self, p) + break + end + end + elseif op == 2 then + for _, p in __iter(self.refs) do + if p.long and p.longIdx == a then + unmark(self, p) + break + end + end + elseif op == 3 then + local picNum = sh.frameNum - a + for _, p in __iter(self.refs) do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + for _, p in __iter(self.refs) do + if p.short and p.picNum == picNum then + p.short = false + p.long = true + p.longIdx = b + break + end + end + elseif op == 4 then + self.maxLongTermIdx = a - 1 + local drop = {} + for _, p in __iter(self.refs) do + if p.long and p.longIdx > self.maxLongTermIdx then + table.insert(drop, p) + end + end + for _, p in __iter(drop) do + unmark(self, p) + end + elseif op == 5 then + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.maxLongTermIdx = -1 + mmco5 = true + elseif op == 6 then + for _, p in __iter(self.refs) do + if p.long and p.longIdx == b then + unmark(self, p) + break + end + end + cur.long = true + cur.longIdx = b + becameLong = true + end + end + else + slidingWindow(self, sps, sh.frameNum) + end + if not becameLong then + cur.short = true + end + -- a bad stream may leave too many references + local maxRefs = math.max(sps.maxRefFrames, 1) + if #self.refs >= maxRefs and not becameLong then + slidingWindow(self, sps, sh.frameNum) + end + addRef(self, cur) + return mmco5 +end + +-- ------------------------------------------------------------------------------------------------ poc +local function computePoc(self, sh) +local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sps.pocType == 0 then + local prevMsb, prevLsb = self.prevPocMsb, self.prevPocLsb + if sh.idr then + prevMsb, prevLsb = 0, 0 + end + local maxLsb = 2 ^ sps.log2MaxPocLsb + local lsb = sh.pocLsb + local msb + if lsb < prevLsb and prevLsb - lsb >= maxLsb / 2 then + msb = prevMsb + maxLsb + elseif lsb > prevLsb and lsb - prevLsb > maxLsb / 2 then + msb = prevMsb - maxLsb + else + msb = prevMsb + end + local top = msb + lsb + local bottom = top + sh.deltaPocBottom + sh.pocMsb = msb + return math.min(top, bottom), top + end + local offset + if sh.idr then + offset = 0 + elseif self.prevFrameNum > sh.frameNum then + offset = self.prevFrameNumOffset + maxFrameNum + else + offset = self.prevFrameNumOffset + end + sh.frameNumOffset = offset + if sps.pocType == 1 then + local n = #sps.offsetsForRefFrame + local absFrameNum = (n ~= 0 and((offset + sh.frameNum ))or(0 +)) if sh.nalRefIdc == 0 and absFrameNum > 0 then + absFrameNum =absFrameNum- 1 + end + local expected = 0 + if absFrameNum > 0 then + local cycle = math.floor((absFrameNum - 1) / n +) local inCycle = (absFrameNum - 1) % n + expected = cycle * sps.expectedDeltaPerCycle + for i = 1, inCycle + 1 do + expected =expected+ sps.offsetsForRefFrame[i] + end + end + if sh.nalRefIdc == 0 then + expected =expected+ sps.offsetNonRef + end + local top = expected + sh.deltaPoc0 + local bottom = top + sps.offsetTopToBottom + sh.deltaPoc1 + return math.min(top, bottom), top + end + local t + if sh.idr then + t = 0 + elseif sh.nalRefIdc == 0 then + t = 2 * (offset + sh.frameNum) - 1 + else + t = 2 * (offset + sh.frameNum) + end + return t, t +end + +-- ------------------------------------------------------------------------------------------------ picture decode +local function setupGrids(self, sps) + local mbW, mbH = sps.mbWidth, sps.mbHeight + if self.S and self.S.mbW == mbW and self.S.mbH == mbH then + return + end + local S = Mb.grids(mbW, mbH) + S.mbW, S.mbH = mbW, mbH + S.w4 = mbW * 4 + S.cw4 = mbW * 2 + S.qpcOf = table.create(52, 0) + S.qpc2Of = table.create(52, 0) + self.S = S +end + +-- fill a frame_num gap with "non-existing" frames (8.2.5.2), concealed as copies of the latest reference +local function fillGap(self, sh) + local sps = sh.sps + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + local fn = (self.prevRefFrameNum + 1) % maxFrameNum + local guard = 0 + while fn ~= sh.frameNum and guard < 32 do + guard =guard+ 1 + local src = nil + for _, p in __iter(self.refs) do + if p.short and (src == nil or p.decodeOrder > src.decodeOrder) then + src = p + end + end + local p = newPicture(self, sps) + if src then + buffer.copy(p.y, 0, src.y) + buffer.copy(p.u, 0, src.u) + buffer.copy(p.v, 0, src.v) + else + local g = grayPicture(self, sps) + buffer.copy(p.y, 0, g.y) + buffer.copy(p.u, 0, g.u) + buffer.copy(p.v, 0, g.v) + end + for i = 1, #p.mbIntra do + p.mbIntra[i] = true + end + self.uid =self.uid+ 1 + p.uid = self.uid + p.frameNum = fn + p.poc = (src and{src.poc }or{0 +})[1] p.sps = sps + p.idr = false + p.decodeOrder = self.frames + p.long = false + slidingWindow(self, sps, fn) + p.short = true + addRef(self, p) + self.prevRefFrameNum = fn + self.prevFrameNum = fn + fn = (fn + 1) % maxFrameNum + end +end + +local function startPicture(self, sh, pts) + local sps = sh.sps + if sps.mbWidth ~= self.seqW or sps.mbHeight ~= self.seqH then + -- a new sequence size: output everything, drop the references + bump(self, 0) + while #self.refs > 0 do + unmark(self, self.refs[1]) + end + self.pool = {} + self.seqW, self.seqH = sps.mbWidth, sps.mbHeight + end + setupGrids(self, sps) + if not sh.idr then + local maxFrameNum = 2 ^ sps.log2MaxFrameNum + if sh.frameNum ~= self.prevRefFrameNum and sh.frameNum ~= (self.prevRefFrameNum + 1) % maxFrameNum then + fillGap(self, sh) + end + end + local p = newPicture(self, sps) + self.uid =self.uid+ 1 + p.uid = self.uid + p.sps = sps + p.frameNum = sh.frameNum + p.idr = sh.idr + p.refIdc = sh.nalRefIdc + p.short, p.long, p.waiting = false, false, false + p.poc, p.topPoc = computePoc(self, sh) + p.pts = pts or self.frames + p.decodeOrder = self.frames + self.frames =self.frames+ 1 + self.cur = p + self.curSh = sh + self.decoded = 0 + self.sliceNum = 0 + self.sliceParams = {} + local S = self.S + local st = S.sliceTab + for i = 1, #st do + st[i] = 0 + end + S.pic = p + S.hook = self.opts.yield +end + +local function conceal(self, p) + local S = self.S + local st = S.sliceTab + local src = nil + for _, q in __iter(self.refs) do + if q ~= p and (src == nil or q.decodeOrder > src.decodeOrder) then + src = q + end + end + local mbW = S.mbW + for addr = 1, #st do + if st[addr] == 0 then + local mx, my = (addr - 1) % mbW, math.floor((addr - 1) / mbW +) for y = 0, 15 do + local o = p.yo + (my * 16 + y) * p.ys + mx * 16 + if src then + buffer.copy(p.y, o, src.y, o, 16) + else + buffer.fill(p.y, o, 128, 16) + end + end + for y = 0, 7 do + local o = p.co + (my * 8 + y) * p.cs + mx * 8 + if src then + buffer.copy(p.u, o, src.u, o, 8) + buffer.copy(p.v, o, src.v, o, 8) + else + buffer.fill(p.u, o, 128, 8) + buffer.fill(p.v, o, 128, 8) + end + end + p.mbIntra[addr] = true + local g0 = my * 4 * S.w4 + mx * 4 + 1 + for j = 0, 3 do + for i = 0, 3 do + local g = g0 + j * S.w4 + i + p.ref0[g], p.ref1[g], p.uid0[g], p.uid1[g] = -1, -1, -1, -1 + end + end + S.kind[addr] = 0 + end + end +end + +local function finishPicture(self) + local p = self.cur + if not p then + return + end + local sh = self.curSh + local S = self.S + if self.decoded < S.mbW * S.mbH then + conceal(self, p) + end + local hook = self.opts.yield + if self.opts.deblock ~= false then + Deblock.picture(S, p, self.sliceParams) + end + if hook then + pcall(hook) + end + local w, h = S.mbW * 16, S.mbH * 16 + Inter.extend(p.y, p.yo, p.ys, w, h, PAD) + Inter.extend(p.u, p.co, p.cs, math.floor(w / 2), math.floor(h / 2), PADC) + Inter.extend(p.v, p.co, p.cs, math.floor(w / 2), math.floor(h / 2), PADC) + local mmco5 = false + if sh.nalRefIdc ~= 0 then + mmco5 = mark(self, p, sh) + end + if sh.idr or mmco5 then + bump(self, 0) + end + if mmco5 then + -- 8.2.1: after MMCO 5 the picture counts as frame_num 0 with its POC moved to 0 + local t = p.poc + p.topPoc =p.topPoc- t + p.poc = 0 + p.frameNum = 0 + end + -- POC / frame_num state for the next pictures + if sh.nalRefIdc ~= 0 then + if mmco5 then + self.prevPocMsb = 0 + self.prevPocLsb = p.topPoc + self.prevRefFrameNum = 0 + else + self.prevPocMsb = sh.pocMsb or 0 + self.prevPocLsb = sh.pocLsb + self.prevRefFrameNum = sh.frameNum + end + end + if mmco5 then + self.prevFrameNumOffset = 0 + self.prevFrameNum = 0 + else + self.prevFrameNumOffset = sh.frameNumOffset or 0 + self.prevFrameNum = sh.frameNum + end + self.cur = nil + self.curSh = nil + p.waiting = true + table.insert(self.waiting, p) + bump(self, reorderDepth(self, sh.sps)) + release(self, p) +end + +local function sameNewPicture(a, b) -- 7.4.1.2.4: true when slice header b starts a new primary picture after a + +if a.frameNum ~= b.frameNum or a.ppsId ~= b.ppsId or a.idr ~= b.idr then + return true + end + if (a.nalRefIdc == 0) ~= (b.nalRefIdc == 0) then + return true + end + local sps = b.sps + if sps.pocType == 0 and (a.pocLsb ~= b.pocLsb or a.deltaPocBottom ~= b.deltaPocBottom) then + return true + end + if sps.pocType == 1 and (a.deltaPoc0 ~= b.deltaPoc0 or a.deltaPoc1 ~= b.deltaPoc1) then + return true + end + if a.idr and b.idr and a.idrPicId ~= b.idrPicId then + return true + end + return false +end + +local function fail(self, msg) + self.errors =self.errors+ 1 + self.lastError = msg +end + +local function decodeSlice(self, sh, r) + local S = self.S + local cur = self.cur + local sps, pps = sh.sps, sh.pps + self.sliceNum =self.sliceNum+ 1 + S.slice = self.sliceNum + self.sliceParams[self.sliceNum] = { sh.deblock, sh.alphaOffset, sh.betaOffset } + S.type = sh.type + S.firstMb = sh.firstMb + if sh.firstMb >= S.mbW * S.mbH then + fail(self, "first_mb_in_slice out of range") + return + end + S.qp = sh.qp + for q = 0, 51 do + S.qpcOf[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset, 0, 51) + 1] + S.qpc2Of[q + 1] = CHROMA_QP[math.clamp(q + pps.chromaQpOffset2, 0, 51) + 1] + end + S.dq = Params.dequant(sps, pps, self.dqCache) + S.t8mode = pps.transform8x8 + S.constrainedIntra = pps.constrainedIntra + S.direct8x8 = sps.direct8x8 + S.directSpatial = sh.directSpatial + S.n0, S.n1 = sh.numRefIdxL0, sh.numRefIdxL1 + S.cabacInit = sh.cabacInit + local list0, list1 = {}, {} + if sh.type ~= Slice.I then + local ok + list0, list1, ok = buildLists(self, sh, cur) + if not ok then + fail(self, "bad ref_pic_list_modification") + end + if #list0 == 0 then + list0 = { grayPicture(self, sps) } + end + if sh.type == Slice.B and #list1 == 0 then + list1 = { list0[1] } + end + end + S.list0, S.list1 = list0, list1 + local uids0, uids1 = {}, {} + local uidToRef0 = {} + for i, p in __iter(list0) do + uids0[i] = p.uid + if uidToRef0[p.uid] == nil then + uidToRef0[p.uid] = i - 1 + end + end + for i, p in __iter(list1) do + uids1[i] = p.uid + end + S.uids0, S.uids1, S.uidToRef0 = uids0, uids1, uidToRef0 + S.weightMode = sh.weightMode + S.weights0, S.weights1 = sh.weights0 or {}, sh.weights1 or {} + S.lumaDenom, S.chromaDenom = sh.lumaDenom or 0, sh.chromaDenom or 0 + if sh.type == Slice.B then + local col = list1[1] + S.colPic = col + S.colShort = not col.long + local dsf = {} + for i, p in __iter(list0) do + local d = nil + if not p.long then + d = Mb.distScale(cur.poc, p.poc, col.poc) + end + dsf[i] = d or false + end + S.dsf = dsf + if sh.weightMode == 2 then + local imp = table.create(32 * 32, 32) + for i0, p0 in __iter(list0) do + for i1, p1 in __iter(list1) do + local w1 = 32 + if not p0.long and not p1.long and p1.poc ~= p0.poc then + local d = Mb.distScale(cur.poc, p0.poc, p1.poc) + if d and math.floor(d / 4 )>= -64 and math.floor(d / 4 )<= 128 then + w1 = math.floor(d / 4 +) end + end + imp[(i0 - 1) * 32 + i1] = w1 + end + end + S.implicit = imp + end + end + local before = 0 + local st = S.sliceTab + local ok, err + if pps.cabac then + ok, err = Cabac.slice(S, self.M, r) + else + ok, err = Cavlc.slice(S, self.M, r) + end + for i = 1, #st do + if st[i] ~= 0 then + before =before+ 1 + end + end + self.decoded = before + if not ok then + fail(self, err or "bad slice data") + end +end + +-- nal(self, buf, off, len, pts): one NAL unit (no start code) +function Decoder.nal(self, buf, off, len, pts) + if len < 1 then + return + end + local hdr = buffer.readu8(buf, off) + if hdr >= 128 then + fail(self, "forbidden_zero_bit set") + return + end + local refIdc = bit32.rshift(hdr, 5) + local t = bit32.band(hdr, 31) + if t == 7 then + local sps, err = Params.sps(Bitstream.reader(buf, off, len, 1)) + if not sps then + if err and string.sub(err, 1, 6) == "limit:" then + self.fatal = err + end + fail(self, err or "bad sps") + return + end + if sps.chromaFormat ~= 1 then + self.unsupported = "chroma format " .. ({ [0] = "4:0:0 (monochrome)", [2] = "4:2:2", [3] = "4:4:4" })[sps.chromaFormat] + elseif sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 then + self.unsupported = "bit depth " .. sps.bitDepth + elseif not sps.frameMbsOnly then + self.unsupported = "interlaced coding (PAFF / MBAFF)" + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture of " .. sps.mbWidth * 16 .. " x " .. sps.mbHeight * 16 .. " over maxPixels" + end + self.spsTab[sps.id] = sps + return + elseif t == 8 then + local pps, err = Params.pps(Bitstream.reader(buf, off, len, 1), self.spsTab) + if not pps then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad pps") + return + end + self.ppsTab[pps.id] = pps + return + elseif t == 1 or t == 5 then + local r = Bitstream.reader(buf, off, len, 1) + local sh, err = Slice.header(r, t, refIdc, self.spsTab, self.ppsTab) + if not sh then + if err and string.sub(err, 1, 12) == "unsupported:" then + self.unsupported = string.sub(err, 14) + end + fail(self, err or "bad slice header") + return + end + local sps = sh.sps + if sps.chromaFormat ~= 1 or sps.bitDepth ~= 8 or sps.bitDepthC ~= 8 or sps.bypass or not sps.frameMbsOnly then + self.unsupported = self.unsupported or "profile features (chroma format / bit depth / lossless)" + return + end + if sps.mbWidth * sps.mbHeight * 256 > self.maxPixels then + self.fatal = "limit: picture over maxPixels" + return + end + if sh.redundantPicCnt and sh.redundantPicCnt > 0 then + return + end + if self.cur and (sameNewPicture(self.curSh, sh) or (sh.firstMb == 0 and self.decoded > 0)) then + finishPicture(self) + end + if not self.cur then + if not sh.idr and #self.refs == 0 and self.frames == 0 and sh.type ~= Slice.I then + -- a stream starting without an intra picture: decode against gray + self.lastError = "stream starts with an inter picture" + end + startPicture(self, sh, pts) + end + decodeSlice(self, sh, r) + if self.decoded >= self.S.mbW * self.S.mbH then + finishPicture(self) + end + return + elseif t == 9 or t == 10 or t == 11 then + finishPicture(self) + return + elseif t >= 2 and t <= 4 then + self.unsupported = "data partitioning (Extended profile)" + return + end + -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored +end + +-- flush(self): finish the current picture and output every waiting picture +function Decoder.flush(self) + finishPicture(self) + bump(self, 0) +end + +-- take(self) -> the frames output since the last call +function Decoder.take(self) +local out = self.out + self.out = {} + return out +end + +return Decoder +end +__FILES["codecs/video/H264/Inter"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap +-- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample +-- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped +-- sample positions of 8.4.2.2.1. Written from the spec. +-- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions +-- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Inter = {} + +Inter.PAD = 32 +Inter.PADC = 16 + +local min, max = math.min, math.max +local function clip(v) +return min(max(v, 0), 255) +end + +-- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns +local B1 = table.create(24 * 17, 0) + +-- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each +-- sample once per row / column +local function lumaCopy(ref, s, base, w, h, P) + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + P[d + c] = readu8(ref, o + c) + end + end +end + +-- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1 +local function lumaH(ref, s, base, w, h, P, avg) + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w - 1 do + local a5 = readu8(ref, o + c + 3) + local v = min(max(math.floor((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) / 32), 0), 255) + if avg == 1 then + v = math.floor((v + a2 + 1) / 2 +) elseif avg == 2 then + v = math.floor((v + a3 + 1) / 2 +) end + P[d + c] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1 +local function lumaV(ref, s, base, w, h, P, avg) + for c = 0, w - 1 do + local o = base + c + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + local d = c + 1 + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local v = min(max(math.floor((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) / 32), 0), 255) + if avg == 1 then + v = math.floor((v + a2 + 1) / 2 +) elseif avg == 2 then + v = math.floor((v + a3 + 1) / 2 +) end + P[d + r * 16] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17 +local function horizontal1(ref, s, base, w, h) + for r = -2, h + 2 do + local o = base + r * s + local d = (r + 2) * 17 + 1 + local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2) + for c = 0, w do + local a5 = readu8(ref, o + c + 3) + B1[d + c] = a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row) +local function lumaJ(ref, s, base, w, h, P, with) + horizontal1(ref, s, base, w, h) + for c = 0, w - 1 do + local k = 2 * 17 + 1 + c + local a0, a1, a2, a3, a4 = B1[k - 34], B1[k - 17], B1[k], B1[k + 17], B1[k + 34] + for r = 0, h - 1 do + local a5 = B1[k + 51] + local v = min(max(math.floor((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 512) / 1024), 0), 255) + if with == 1 then + v = math.floor((v + min(max(math.floor((a2 + 16) / 32), 0), 255) + 1) / 2 +) elseif with == 2 then + v = math.floor((v + min(max(math.floor((a3 + 16) / 32), 0), 255) + 1) / 2 +) end + P[r * 16 + c + 1] = v + a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + k =k+ 17 + end + end +end + +-- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k) +local function lumaJV(ref, s, base, w, h, P, co) + lumaJ(ref, s, base, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local hv = min(max(math.floor((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) / 32), 0), 255) + local d = r * 16 + c + 1 + P[d] = math.floor((P[d] + hv + 1) / 2 +) a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m) +local function lumaDiag(ref, s, base, w, h, P, ro, co) + lumaH(ref, s, base + ro, w, h, P, 0) + for c = 0, w - 1 do + local o = base + c + co + local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s) + for r = 0, h - 1 do + local a5 = readu8(ref, o + (r + 3) * s) + local vb = min(max(math.floor((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) / 32), 0), 255) + local d = r * 16 + c + 1 + P[d] = math.floor((P[d] + vb + 1) / 2 +) a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5 + end + end +end + +-- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at +-- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples +function Inter.luma(ref, s, base, fx, fy, w, h, P) + if fy == 0 then + if fx == 0 then + lumaCopy(ref, s, base, w, h, P) + else + lumaH(ref, s, base, w, h, P, fx == 2 and 0 or(fx == 1 and 1 or 2)) + end + elseif fx == 0 then + lumaV(ref, s, base, w, h, P, fy == 2 and 0 or(fy == 1 and 1 or 2)) + elseif fx == 2 then + lumaJ(ref, s, base, w, h, P, fy == 2 and 0 or(fy == 1 and 1 or 2)) + elseif fy == 2 then + lumaJV(ref, s, base, w, h, P, fx == 3 and 1 or 0) + else + lumaDiag(ref, s, base, w, h, P, (fy == 3 and{s }or{0})[1], fx == 3 and 1 or 0) + end +end + +-- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction +function Inter.chroma(ref, s, base, fx, fy, w, h, P) + if fx == 0 and fy == 0 then + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + P[d + c] = readu8(ref, o + c) + end + end + return + end + local wa = (8 - fx) * (8 - fy) + local wb = fx * (8 - fy) + local wc = (8 - fx) * fy + local wd = fx * fy + for r = 0, h - 1 do + local o = base + r * s + local d = r * 16 + 1 + for c = 0, w - 1 do + local p = o + c + P[d + c] = math.floor((wa * readu8(ref, p) + wb * readu8(ref, p + 1) + wc * readu8(ref, p + s) + wd * readu8(ref, p + s + 1) + 32) / 64 +) end + end +end + +-- ------------------------------------------------------------------------------------------------ weighting +-- put(P, w, h, b, o, s): P into the picture +function Inter.put(P, w, h, b, o, s) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, P[d + c]) + end + end +end + +-- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 +function Inter.avg(P0, P1, w, h, b, o, s) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, math.floor((P0[d + c] + P1[d + c] + 1) / 2)) + end + end +end + +-- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) +function Inter.weight1(P, w, h, b, o, s, logWD, wt, off) + if logWD >= 1 then + local rnd = 2 ^ (logWD - 1) + local div = 2 ^ logWD + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip(math.floor((P[d + c] * wt + rnd) / div )+ off)) + end + end + else + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip(P[d + c] * wt + off)) + end + end + end +end + +-- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); +-- off = (o0 + o1 + 1) >> 1 +function Inter.weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off) + local rnd = 2 ^ logWD + local div = 2 ^ (logWD + 1) + for r = 0, h - 1 do + local d = r * 16 + 1 + local q = o + r * s + for c = 0, w - 1 do + writeu8(b, q + c, clip(math.floor((P0[d + c] * w0 + P1[d + c] * w1 + rnd) / div )+ off)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ borders +-- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border +function Inter.extend(b, o, s, w, h, pad) + for y = 0, h - 1 do + local r = o + y * s + buffer.fill(b, r - pad, readu8(b, r), pad) + buffer.fill(b, r + w, readu8(b, r + w - 1), pad) + end + local top = o - pad + local bottom = o + (h - 1) * s - pad + for y = 1, pad do + buffer.copy(b, top - y * s, b, top, w + 2 * pad) + buffer.copy(b, bottom + y * s, b, bottom, w + 2 * pad) + end +end + +return Inter +end +__FILES["codecs/video/H264/Intra"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the +-- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. +-- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). +-- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Intra = {} + +local E = table.create(40, 0) -- reference samples: p[-1, y] = E[N - y], p[-1, -1] = E[N + 1], p[x, -1] = E[N + 2 + x] +local F = table.create(40, 0) -- filtered 8x8 references, same layout + +local min, max = math.min, math.max +local function clip(v) +return min(max(v, 0), 255) +end + +-- predNxN: the directional modes 3..8 over the edge array R (N = 4 or 8) +local function directional(R, N, mode, b, o, s) + local c = N + 1 -- R[c] = p[-1, -1]; p[x, -1] = R[c + 1 + x]; p[-1, y] = R[c - 1 - y] + for y = 0, N - 1 do + local row = o + y * s + for x = 0, N - 1 do + local v + if mode == 3 then -- diagonal down left + if x == N - 1 and y == N - 1 then + v = math.floor((R[c + 2 * N - 1] + 3 * R[c + 2 * N] + 2) / 4 +) else + local i = c + 1 + x + y + v = math.floor((R[i] + 2 * R[i + 1] + R[i + 2] + 2) / 4 +) end + elseif mode == 4 then -- diagonal down right + if x > y then + local i = c + 1 + x - y + v = math.floor((R[i - 2] + 2 * R[i - 1] + R[i] + 2) / 4 +) elseif x < y then + local i = c - 1 - (y - x) + v = math.floor((R[i + 2] + 2 * R[i + 1] + R[i] + 2) / 4 +) else + v = math.floor((R[c + 1] + 2 * R[c] + R[c - 1] + 2) / 4 +) end + elseif mode == 5 then -- vertical right + local z = 2 * x - y + if z >= 0 and z % 2 == 0 then + local i = c + 1 + x - math.floor(y / 2 +) v = math.floor((R[i - 1] + R[i] + 1) / 2 +) elseif z > 0 then + local i = c + 1 + x - math.floor(y / 2 +) v = math.floor((R[i - 2] + 2 * R[i - 1] + R[i] + 2) / 4 +) elseif z == -1 then + v = math.floor((R[c - 1] + 2 * R[c] + R[c + 1] + 2) / 4 +) else + local i = c - 1 - (y - 2 * x - 1) -- p[-1, y - 2x - 1] + v = math.floor((R[i] + 2 * R[i + 1] + R[i + 2] + 2) / 4 +) end + elseif mode == 6 then -- horizontal down + local z = 2 * y - x + if z >= 0 and z % 2 == 0 then + local i = c - 1 - (y - math.floor(x / 2)) -- p[-1, y - (x >> 1)] + v = math.floor((R[i + 1] + R[i] + 1) / 2 +) elseif z > 0 then + local i = c - 1 - (y - math.floor(x / 2)) + v = math.floor((R[i + 2] + 2 * R[i + 1] + R[i] + 2) / 4 +) elseif z == -1 then + v = math.floor((R[c - 1] + 2 * R[c] + R[c + 1] + 2) / 4 +) else + local i = c + 1 + (x - 2 * y - 1) -- p[x - 2y - 1, -1] + v = math.floor((R[i] + 2 * R[i - 1] + R[i - 2] + 2) / 4 +) end + elseif mode == 7 then -- vertical left + local i = c + 1 + x + math.floor(y / 2 +) if y % 2 == 0 then + v = math.floor((R[i] + R[i + 1] + 1) / 2 +) else + v = math.floor((R[i] + 2 * R[i + 1] + R[i + 2] + 2) / 4 +) end + else -- horizontal up + local z = x + 2 * y + local i = c - 1 - (y + math.floor(x / 2)) -- p[-1, y + (x >> 1)] + if z > 2 * N - 3 then + v = R[c - N] + elseif z == 2 * N - 3 then + v = math.floor((R[c - N + 1] + 3 * R[c - N] + 2) / 4 +) elseif z % 2 == 0 then + v = math.floor((R[i] + R[i - 1] + 1) / 2 +) else + v = math.floor((R[i] + 2 * R[i - 1] + R[i - 2] + 2) / 4 +) end + end + writeu8(b, row + x, v) + end + end +end + +-- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples +-- repeat p[3, -1]. +function Intra.pred4x4(b, o, s, mode, left, top, topRight, topLeft) + if mode == 0 then + local t = o - s + local a0, a1, a2, a3 = readu8(b, t), readu8(b, t + 1), readu8(b, t + 2), readu8(b, t + 3) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, a0) + writeu8(b, r + 1, a1) + writeu8(b, r + 2, a2) + writeu8(b, r + 3, a3) + end + return + elseif mode == 1 then + for y = 0, 3 do + local r = o + y * s + local v = readu8(b, r - 1) + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + sum =sum+ (readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) +) n =n+ 1 + end + if left then + sum =sum+ (readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) +) n =n+ 1 + end + local v = 128 + if n == 2 then + v = math.floor((sum + 4) / 8 +) elseif n == 1 then + v = math.floor((sum + 2) / 4 +) end + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end + return + end + -- edges: E[1..4] = p[-1, 3..0], E[5] = p[-1, -1], E[6..13] = p[0..7, -1] + if left then + for y = 0, 3 do + E[4 - y] = readu8(b, o + y * s - 1) + end + end + if topLeft then + E[5] = readu8(b, o - s - 1) + end + if top then + local t = o - s + for x = 0, 3 do + E[6 + x] = readu8(b, t + x) + end + if topRight then + for x = 4, 7 do + E[6 + x] = readu8(b, t + x) + end + else + local v = E[9] + E[10], E[11], E[12], E[13] = v, v, v, v + end + end + directional(E, 4, mode, b, o, s) +end + +-- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter +function Intra.pred8x8(b, o, s, mode, left, top, topRight, topLeft) + -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] + if left then + for y = 0, 7 do + E[8 - y] = readu8(b, o + y * s - 1) + end + end + local tl = 0 + if topLeft then + tl = readu8(b, o - s - 1) + E[9] = tl + end + if top then + local t = o - s + for x = 0, 7 do + E[10 + x] = readu8(b, t + x) + end + if topRight then + for x = 8, 15 do + E[10 + x] = readu8(b, t + x) + end + else + local v = E[17] + for x = 8, 15 do + E[10 + x] = v + end + end + -- filtered top + if topLeft then + F[10] = math.floor((tl + 2 * E[10] + E[11] + 2) / 4 +) else + F[10] = math.floor((3 * E[10] + E[11] + 2) / 4 +) end + for x = 1, 14 do + F[10 + x] = math.floor((E[9 + x] + 2 * E[10 + x] + E[11 + x] + 2) / 4 +) end + F[25] = math.floor((E[24] + 3 * E[25] + 2) / 4 +) end + if topLeft then + if top and left then + F[9] = math.floor((E[10] + 2 * tl + E[8] + 2) / 4 +) elseif top then + F[9] = math.floor((3 * tl + E[10] + 2) / 4 +) elseif left then + F[9] = math.floor((3 * tl + E[8] + 2) / 4 +) else + F[9] = tl + end + end + if left then + if topLeft then + F[8] = math.floor((tl + 2 * E[8] + E[7] + 2) / 4 +) else + F[8] = math.floor((3 * E[8] + E[7] + 2) / 4 +) end + for y = 1, 6 do + F[8 - y] = math.floor((E[9 - y] + 2 * E[8 - y] + E[7 - y] + 2) / 4 +) end + F[1] = math.floor((E[2] + 3 * E[1] + 2) / 4 +) end + if mode == 0 then + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, F[10 + x]) + end + end + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + local v = F[8 - y] + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + for x = 0, 7 do + sum =sum+ F[10 + x] + end + n =n+ 1 + end + if left then + for y = 0, 7 do + sum =sum+ F[8 - y] + end + n =n+ 1 + end + local v = 128 + if n == 2 then + v = math.floor((sum + 8) / 16 +) elseif n == 1 then + v = math.floor((sum + 4) / 8 +) end + for y = 0, 7 do + local r = o + y * s + for x = 0, 7 do + writeu8(b, r + x, v) + end + end + else + directional(F, 8, mode, b, o, s) + end +end + +-- pred16x16(b, o, s, mode, left, top, topLeft) +function Intra.pred16x16(b, o, s, mode, left, top, topLeft) + if mode == 0 then + local t = o - s + for y = 0, 15 do + buffer.copy(b, o + y * s, b, t, 16) + end + elseif mode == 1 then + for y = 0, 15 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 16) + end + elseif mode == 2 then + local sum, n = 0, 0 + if top then + local t = o - s + for x = 0, 15 do + sum =sum+ readu8(b, t + x) + end + n =n+ 1 + end + if left then + for y = 0, 15 do + sum =sum+ readu8(b, o + y * s - 1) + end + n =n+ 1 + end + local v = 128 + if n == 2 then + v = math.floor((sum + 16) / 32 +) elseif n == 1 then + v = math.floor((sum + 8) / 16 +) end + for y = 0, 15 do + buffer.fill(b, o + y * s, v, 16) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 7 do + H =H+ (i + 1) * (readu8(b, t + 8 + i) - readu8(b, t + 6 - i)) + V =V+ (i + 1) * (readu8(b, o + (8 + i) * s - 1) - readu8(b, o + (6 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 15 * s - 1) + readu8(b, t + 15)) + local bb = math.floor((5 * H + 32) / 64 +) local cc = math.floor((5 * V + 32) / 64 +) for y = 0, 15 do + local r = o + y * s + local base = a + cc * (y - 7) + 16 - 7 * bb + for x = 0, 15 do + writeu8(b, r + x, clip(math.floor((base + bb * x) / 32))) + end + end + end +end + +local function fill4(b, o, s, v) + for y = 0, 3 do + local r = o + y * s + writeu8(b, r, v) + writeu8(b, r + 1, v) + writeu8(b, r + 2, v) + writeu8(b, r + 3, v) + end +end + +-- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane +function Intra.predChroma(b, o, s, mode, left, top, topLeft) + if mode == 0 then + local t = o - s + local st0, st1, sl0, sl1 = 0, 0, 0, 0 + if top then + st0 = readu8(b, t) + readu8(b, t + 1) + readu8(b, t + 2) + readu8(b, t + 3) + st1 = readu8(b, t + 4) + readu8(b, t + 5) + readu8(b, t + 6) + readu8(b, t + 7) + end + if left then + sl0 = readu8(b, o - 1) + readu8(b, o + s - 1) + readu8(b, o + 2 * s - 1) + readu8(b, o + 3 * s - 1) + sl1 = readu8(b, o + 4 * s - 1) + readu8(b, o + 5 * s - 1) + readu8(b, o + 6 * s - 1) + readu8(b, o + 7 * s - 1) + end + local v00, v10, v01, v11 = 128, 128, 128, 128 + if top and left then + v00 = math.floor((st0 + sl0 + 4) / 8 +) v11 = math.floor((st1 + sl1 + 4) / 8 +) v10 = math.floor((st1 + 2) / 4 +) v01 = math.floor((sl1 + 2) / 4 +) elseif left then + v00 = math.floor((sl0 + 2) / 4 +) v11 = math.floor((sl1 + 2) / 4 +) v10 = v00 + v01 = v11 + elseif top then + v00 = math.floor((st0 + 2) / 4 +) v11 = math.floor((st1 + 2) / 4 +) v10 = v11 + v01 = v00 + end + fill4(b, o, s, v00) + fill4(b, o + 4, s, v10) + fill4(b, o + 4 * s, s, v01) + fill4(b, o + 4 * s + 4, s, v11) + elseif mode == 1 then + for y = 0, 7 do + local r = o + y * s + buffer.fill(b, r, readu8(b, r - 1), 8) + end + elseif mode == 2 then + local t = o - s + for y = 0, 7 do + buffer.copy(b, o + y * s, b, t, 8) + end + else + local t = o - s + local H, V = 0, 0 + for i = 0, 3 do + H =H+ (i + 1) * (readu8(b, t + 4 + i) - readu8(b, t + 2 - i)) + V =V+ (i + 1) * (readu8(b, o + (4 + i) * s - 1) - readu8(b, o + (2 - i) * s - 1)) + end + local a = 16 * (readu8(b, o + 7 * s - 1) + readu8(b, t + 7)) + local bb = math.floor((34 * H + 32) / 64 +) local cc = math.floor((34 * V + 32) / 64 +) for y = 0, 7 do + local r = o + y * s + local base = a + cc * (y - 3) + 16 - 3 * bb + for x = 0, 7 do + writeu8(b, r + x, clip(math.floor((base + bb * x) / 32))) + end + end + end +end + +return Intra +end +__FILES["codecs/video/H264/Mb"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): +-- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction +-- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra +-- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout +-- (picture-wide arrays, one entry per 4x4 luma block, 1-based). +-- Never throws: every index is in range by construction; reference indices past the list use the first entry. +local Intra = __include("codecs/video/H264/Intra") +local Transform = __include("codecs/video/H264/Transform") +local Inter = __include("codecs/video/H264/Inter") + +local Mb = {} +Mb.YIELD_MBS = 16 -- macroblocks between calls of the cooperative yield hook (S.hook: Decoder Options.yield) + +-- macroblock kinds (S.kind per macroblock) +local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, 4, 5, 6, 7, 8, 9 +Mb.K_I4, Mb.K_I8, Mb.K_I16, Mb.K_PCM, Mb.K_P, Mb.K_PSKIP, Mb.K_B, Mb.K_BSKIP, Mb.K_BDIRECT = K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT + +local UNAVAIL = -2 +local min, max = math.min, math.max + +local add4, addDc4, add8 = Transform.add4, Transform.addDc4, Transform.add8 +local PAD, PADC = Inter.PAD, Inter.PADC + +-- raster 4x4 block (bx + 4 by) of the decoding-order block index 0..15 (6.4.3) +local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 } +local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } +Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y + +-- new() -> M, the per-macroblock scratch state +function Mb.new() +return { + addr = 0, + x = 0, + y = 0, + g0 = 1, -- grid index of the macroblock's 4x4 block (0, 0) + c0 = 1, -- chroma 4x4 grid index of its block (0, 0) + aL = false, + aT = false, + aTR = false, + aTL = false, + iL = false, -- intra sample availability (constrained_intra_pred aware) + iT = false, + iTR = false, + iTL = false, + kind = 0, + t8 = 0, + i16 = 0, + cpm = 0, + cbp = 0, + qp = 0, + qpd = 0, -- mb_qp_delta + part = 0, -- 0 16x16, 1 16x8, 2 8x16, 3 8x8 + pf = { 0, 0, 0, 0 }, -- prediction flags per partition: 1 L0, 2 L1, 3 Bi + sub = { 0, 0, 0, 0 }, -- sub-macroblock shape: 0 8x8, 1 8x4, 2 4x8, 3 4x4 + dir = { false, false, false, false }, -- B_Direct_8x8 sub-macroblocks + ref0 = { 0, 0, 0, 0 }, + ref1 = { 0, 0, 0, 0 }, + mvd0 = table.create(32, 0), + mvd1 = table.create(32, 0), + ipm = table.create(16, 2), -- intra 4x4 / 8x8 modes by raster block + c4 = table.create(256, 0), -- luma 4x4 coefficients (dequantised), raster block * 16 + raster position + c8 = table.create(256, 0), -- luma 8x8 coefficients, 8x8 block * 64 + raster position + cc = table.create(128, 0), -- chroma: (plane * 4 + block) * 16 + position + dcY = table.create(16, 0), + dcC = table.create(8, 0), + nz = table.create(16, 0), -- coefficients per luma 4x4 block (raster) + nzc = table.create(8, 0), -- coefficients per chroma AC block (plane * 4 + block) + hasDcY = false, + hasDcC = false, + done = table.create(16, false), + reg = table.create(64, 0), -- motion compensation regions: x, y, w, h (4x4 units) + nreg = 0, + P0 = table.create(256, 0), + P1 = table.create(256, 0), + pcm = buffer.create(384), + } +end + +-- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture) +function Mb.grids(mbW, mbH) +local n = mbW * mbH + local n4 = n * 16 + local nc = n * 4 + return { + sliceTab = table.create(n, 0), + kind = table.create(n, 0), + cbpTab = table.create(n, 0), + qpTab = table.create(n, 0), -- QPY for deblocking (0 for I_PCM) + qpcTab = table.create(n, 0), -- QPc (Cb) + qpc2Tab = table.create(n, 0), -- QPc (Cr) + t8Tab = table.create(n, 0), + cpmTab = table.create(n, 0), + dcTab = table.create(n, 0), -- CABAC coded_block_flag of the DC blocks: 1 luma, 2 Cb, 4 Cr + qpdTab = table.create(n, 0), -- mb_qp_delta ~= 0 + nzc = table.create(n4, 0), + nzcCb = table.create(nc, 0), + nzcCr = table.create(nc, 0), + nzDb = table.create(n4, 0), + ipm = table.create(n4, 2), + mvd0 = table.create(n4 * 2, 0), + mvd1 = table.create(n4 * 2, 0), + rgt0 = table.create(n4, 0), + rgt1 = table.create(n4, 0), + } +end + +-- ------------------------------------------------------------------------------------------------ neighbours +-- start(S, M, addr): position and neighbour availability of macroblock addr +function Mb.start(S, M, addr) + local mbW = S.mbW + local x, y = addr % mbW, math.floor(addr / mbW +) M.addr, M.x, M.y = addr, x, y + local w4 = S.w4 + M.g0 = y * 4 * w4 + x * 4 + 1 + M.c0 = y * 2 * S.cw4 + x * 2 + 1 + local st, sl = S.sliceTab, S.slice + local aL = x > 0 and st[addr] == sl -- addr is 0-based: st[addr] is macroblock addr - 1 + local aT = y > 0 and st[addr - mbW + 1] == sl + local aTR = y > 0 and x < mbW - 1 and st[addr - mbW + 2] == sl + local aTL = y > 0 and x > 0 and st[addr - mbW] == sl + M.aL, M.aT, M.aTR, M.aTL = aL, aT, aTR, aTL + if S.constrainedIntra then + local k = S.kind + M.iL = aL and k[addr] <= K_PCM + M.iT = aT and k[addr - mbW + 1] <= K_PCM + M.iTR = aTR and k[addr - mbW + 2] <= K_PCM + M.iTL = aTL and k[addr - mbW] <= K_PCM + else + M.iL, M.iT, M.iTR, M.iTL = aL, aT, aTR, aTL + end + local done = M.done + for i = 1, 16 do + done[i] = false + end + M.nreg = 0 + M.hasDcY, M.hasDcC = false, false + M.t8 = 0 + M.qpd = 0 +end + +-- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) +function Mb.nC(S, M, bx, by) +local g = M.g0 + by * S.w4 + bx + local nzc = S.nzc + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return math.floor((nzc[g - 1] + nzc[g - S.w4] + 1) / 2 +) elseif la then + return nzc[g - 1] + elseif ta then + return nzc[g - S.w4] + end + return 0 +end + +-- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab +function Mb.nCc(S, M, tab, bx, by) +local cw = S.cw4 + local g = M.c0 + by * cw + bx + local la = bx > 0 or M.aL + local ta = by > 0 or M.aT + if la and ta then + return math.floor((tab[g - 1] + tab[g - cw] + 1) / 2 +) elseif la then + return tab[g - 1] + elseif ta then + return tab[g - cw] + end + return 0 +end + +-- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) +function Mb.predMode(S, M, bx, by) +local la = bx > 0 or M.iL + local ta = by > 0 or M.iT + if not (la and ta) then + return 2 + end + local ipm = S.ipm + local g = M.g0 + by * S.w4 + bx + local a, b = ipm[g - 1], ipm[g - S.w4] + return ((a < b) and (a) or (b)) +end + +-- ------------------------------------------------------------------------------------------------ motion vectors +-- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the +-- macroblock (nx, ny in -1 .. 4) +local function neighbour(S, M, refs, mvs, nx, ny) +local ok + if ny < 0 then + if nx < 0 then + ok = M.aTL + elseif nx < 4 then + ok = M.aT + else + ok = M.aTR + end + elseif nx < 0 then + ok = M.aL + elseif nx >= 4 then + ok = false + else + ok = M.done[ny * 4 + nx + 1] + end + if not ok then + return UNAVAIL, 0, 0 + end + local g = M.g0 + ny * S.w4 + nx + local r = refs[g] + if r < 0 then + return -1, 0, 0 + end + return r, mvs[2 * g - 1], mvs[2 * g] +end + +local function median(a, b, c) +return max(min(a, b), min(max(a, b), c)) +end + +-- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference +-- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right +local function mvp(S, M, list, x, y, w, ref, shape) +local pic = S.pic + local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((list == 0) and (pic.mv0) or (pic.mv1)) + local rA, ax, ay = neighbour(S, M, refs, mvs, x - 1, y) + local rB, bx, by = neighbour(S, M, refs, mvs, x, y - 1) + local rC, cx, cy = neighbour(S, M, refs, mvs, x + w, y - 1) + if rC == UNAVAIL then + rC, cx, cy = neighbour(S, M, refs, mvs, x - 1, y - 1) + end + if shape == 1 then + if rB == ref then + return bx, by + end + elseif shape == 2 then + if rA == ref then + return ax, ay + end + elseif shape == 3 then + if rA == ref then + return ax, ay + end + elseif shape == 4 then + if rC == ref then + return cx, cy + end + end + if rB == UNAVAIL and rC == UNAVAIL and rA ~= UNAVAIL then + rB, bx, by = rA, ax, ay + rC, cx, cy = rA, ax, ay + end + local n = 0 + if rA == ref then + n =n+ 1 + end + if rB == ref then + n =n+ 2 + end + if rC == ref then + n =n+ 4 + end + if n == 1 then + return ax, ay + elseif n == 2 then + return bx, by + elseif n == 4 then + return cx, cy + end + return median(ax, bx, cx), median(ay, by, cy) +end +Mb.mvp = mvp + +-- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids +local function set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + local pic = S.pic + local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 + local u0 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1)) + local u1 = ((r1 >= 0) and (S.uids1[r1 + 1] or -1) or (-1)) + local w4 = S.w4 + local done = M.done + for j = y, y + h - 1 do + local g = M.g0 + j * w4 + x + for i = x, x + w - 1 do + ref0[g] = r0 + ref1[g] = r1 + mv0[2 * g - 1], mv0[2 * g] = m0x, m0y + mv1[2 * g - 1], mv1[2 * g] = m1x, m1y + uid0[g] = u0 + uid1[g] = u1 + done[j * 4 + i + 1] = true + g =g+ 1 + end + end + local k = M.nreg * 4 + local reg = M.reg + reg[k + 1], reg[k + 2], reg[k + 3], reg[k + 4] = x, y, w, h + M.nreg =M.nreg+ 1 +end + +-- clipping helpers +local function clip3(lo, hi, v) +return min(max(v, lo), hi) +end + +local function tdiv(a, b) +local q = a / b + if q >= 0 then + return math.floor(q) + end + return -math.floor(-q) +end + +-- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 +function Mb.distScale(cur, poc0, poc1) +local tb = clip3(-128, 127, cur - poc0) + local td = clip3(-128, 127, poc1 - poc0) + if td == 0 then + return nil + end + local tx = tdiv(16384 + math.abs(tdiv(td, 2)), td) + return clip3(-1024, 1023, math.floor((tb * tx + 32) / 64)) +end + +-- pskip(S, M): P_Skip motion (8.4.1.1) +local function pskip(S, M) + local mx, my = 0, 0 + if M.aL and M.aT then + local pic = S.pic + local rA, ax, ay = neighbour(S, M, pic.ref0, pic.mv0, -1, 0) + local rB, bx, by = neighbour(S, M, pic.ref0, pic.mv0, 0, -1) + if not ((rA == 0 and ax == 0 and ay == 0) or (rB == 0 and bx == 0 and by == 0)) then + mx, my = mvp(S, M, 0, 0, 0, 4, 0, 0) + end + end + set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) +end + +-- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) +local function colocated(S, M, bx, by) +local col = S.colPic + if S.direct8x8 then + bx = ((bx < 2) and (0) or (3)) + by = ((by < 2) and (0) or (3)) + end + if col.mbIntra[M.addr + 1] then + return -1, 0, 0, -1 + end + local g = M.g0 + by * S.w4 + bx + local r = col.ref0[g] + if r >= 0 then + return r, col.mv0[2 * g - 1], col.mv0[2 * g], col.uid0[g] + end + r = col.ref1[g] + if r >= 0 then + return r, col.mv1[2 * g - 1], col.mv1[2 * g], col.uid1[g] + end + return -1, 0, 0, -1 +end + +local function minPositive(a, b) +if a >= 0 and b >= 0 then + return ((a < b) and (a) or (b)) + end + return ((a > b) and (a) or (b)) +end + +-- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M +local function spatialRefs(S, M) + local pic = S.pic + local r0, r1 = -1, -1 + for l = 0, 1 do + local refs = ((l == 0) and (pic.ref0) or (pic.ref1)) + local mvs = ((l == 0) and (pic.mv0) or (pic.mv1)) + local rA = neighbour(S, M, refs, mvs, -1, 0) + local rB = neighbour(S, M, refs, mvs, 0, -1) + local rC = neighbour(S, M, refs, mvs, 4, -1) + if rC == UNAVAIL then + rC = neighbour(S, M, refs, mvs, -1, -1) + end + local r = minPositive(rA, minPositive(rB, rC)) + if r < -1 then + r = -1 + end + if l == 0 then + r0 = r + else + r1 = r + end + end + M.dZero = false + if r0 < 0 and r1 < 0 then + r0, r1 = 0, 0 + M.dZero = true + end + M.dr0, M.dr1 = r0, r1 + M.d0x, M.d0y, M.d1x, M.d1y = 0, 0, 0, 0 + if not M.dZero then + if r0 >= 0 then + M.d0x, M.d0y = mvp(S, M, 0, 0, 0, 4, r0, 0) + end + if r1 >= 0 then + M.d1x, M.d1y = mvp(S, M, 1, 0, 0, 4, r1, 0) + end + end + M.dReady = true +end + +-- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8) +local function direct8(S, M, i8) + local x0, y0 = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local step = ((S.direct8x8) and (2) or (1)) + if S.directSpatial then + if not M.dReady then + spatialRefs(S, M) + end + local r0, r1 = M.dr0, M.dr1 + local l1short = S.colShort + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local m0x, m0y, m1x, m1y = M.d0x, M.d0y, M.d1x, M.d1y + if not M.dZero and l1short then + local rc, cx, cy = colocated(S, M, x, y) + if rc == 0 and cx >= -1 and cx <= 1 and cy >= -1 and cy <= 1 then + if r0 == 0 then + m0x, m0y = 0, 0 + end + if r1 == 0 then + m1x, m1y = 0, 0 + end + end + end + set(S, M, x, y, step, step, r0, m0x, m0y, r1, m1x, m1y) + end + end + else + for y = y0, y0 + 1, step do + for x = x0, x0 + 1, step do + local rc, cx, cy, cu = colocated(S, M, x, y) + local r0 = 0 + if rc >= 0 then + r0 = S.uidToRef0[cu] or 0 + end + local m0x, m0y, m1x, m1y = cx, cy, 0, 0 + local dsf = S.dsf[r0 + 1] + if dsf then + m0x = math.floor((dsf * cx + 128) / 256 +) m0y = math.floor((dsf * cy + 128) / 256 +) m1x = m0x - cx + m1y = m0y - cy + end + set(S, M, x, y, step, step, r0, m0x, m0y, 0, m1x, m1y) + end + end + end +end + +-- partition geometry (4x4 units) of the sub-macroblock shapes +local SUB_N = { 1, 2, 2, 4 } +local SUB_W = { 2, 2, 1, 1 } +local SUB_H = { 2, 1, 2, 1 } + +-- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions +local function motion(S, M) + local kind = M.kind + M.dReady = false + if kind == K_PSKIP then + pskip(S, M) + return + end + if kind == K_BSKIP or kind == K_BDIRECT then + for i8 = 0, 3 do + direct8(S, M, i8) + end + return + end + local part = M.part + local mvd0, mvd1 = M.mvd0, M.mvd1 + if part < 3 then + local n = ((part == 0) and (1) or (2)) + for p = 1, n do + local x, y, w, h = 0, 0, 4, 4 + local shape = 0 + if part == 1 then + y, h = (p - 1) * 2, 2 + shape = p + elseif part == 2 then + x, w = (p - 1) * 2, 2 + shape = 2 + p + end + local pf = M.pf[p] + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[p] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, shape) + m0x =m0x+ mvd0[2 * p - 1] + m0y =m0y+ mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[p] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, shape) + m1x =m1x+ mvd1[2 * p - 1] + m1y =m1y+ mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + return + end + for i8 = 0, 3 do + if M.dir[i8 + 1] then + direct8(S, M, i8) + else + local x0, y0 = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local sub = M.sub[i8 + 1] + local pf = M.pf[i8 + 1] + local w, h = SUB_W[sub + 1], SUB_H[sub + 1] + for k = 0, SUB_N[sub + 1] - 1 do + local x, y = x0, y0 + if sub == 1 then + y =y+ k + elseif sub == 2 then + x =x+ k + elseif sub == 3 then + x =x+ k % 2 + y =y+ math.floor(k / 2 +) end + local p = i8 * 4 + k + 1 + local r0, r1 = -1, -1 + local m0x, m0y, m1x, m1y = 0, 0, 0, 0 + if pf % 2 == 1 then + r0 = M.ref0[i8 + 1] + m0x, m0y = mvp(S, M, 0, x, y, w, r0, 0) + m0x =m0x+ mvd0[2 * p - 1] + m0y =m0y+ mvd0[2 * p] + end + if pf >= 2 then + r1 = M.ref1[i8 + 1] + m1x, m1y = mvp(S, M, 1, x, y, w, r1, 0) + m1x =m1x+ mvd1[2 * p - 1] + m1y =m1y+ mvd1[2 * p] + end + set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y) + end + end + end +end +Mb.motion = motion + +-- ------------------------------------------------------------------------------------------------ motion compensation +-- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P +local function predLuma(S, ref, P, px, py, w, h, mvx, mvy) + local W, H = S.mbW * 16, S.mbH * 16 + local ix = px + math.floor(mvx / 4 +) local iy = py + math.floor(mvy / 4 +) ix = clip3(2 - PAD, W + PAD - w - 4, ix) + iy = clip3(2 - PAD, H + PAD - h - 4, iy) + local s = ref.ys + Inter.luma(ref.y, s, ref.yo + iy * s + ix, mvx % 4, mvy % 4, w, h, P) +end + +local function predChroma(S, ref, P, plane, px, py, w, h, mvx, mvy) + local W, H = S.mbW * 8, S.mbH * 8 + local ix = px + math.floor(mvx / 8 +) local iy = py + math.floor(mvy / 8 +) ix = clip3(-PADC, W + PADC - 1 - w, ix) + iy = clip3(-PADC, H + PADC - 1 - h, iy) + local s = ref.cs + Inter.chroma(plane, s, ref.co + iy * s + ix, mvx % 8, mvy % 8, w, h, P) +end + +local function refPic(list, r) +return list[r + 1] or list[1] +end + +-- mc(S, M): inter prediction of every region of the macroblock into the current picture +local function mc(S, M) + local pic = S.pic + local reg = M.reg + local P0, P1 = M.P0, M.P1 + local ys, cs = pic.ys, pic.cs + local wm = S.weightMode + local list0, list1 = S.list0, S.list1 + for k = 0, M.nreg - 1 do +local __DARKLUA_CONTINUE_13=false repeat local x, y, w, h = reg[k * 4 + 1], reg[k * 4 + 2], reg[k * 4 + 3], reg[k * 4 + 4] + local g = M.g0 + y * S.w4 + x + local r0, r1 = pic.ref0[g], pic.ref1[g] + local m0x, m0y, m1x, m1y = pic.mv0[2 * g - 1], pic.mv0[2 * g], pic.mv1[2 * g - 1], pic.mv1[2 * g] + local ref0 = ((r0 >= 0) and (refPic(list0, r0)) or (nil)) + local ref1 = ((r1 >= 0) and (refPic(list1, r1)) or (nil)) + if ref0 == nil and ref1 == nil then + ref0 = list0[1] or list1[1] + r0 = 0 + if ref0 == nil then +__DARKLUA_CONTINUE_13=true break + end + end + local px, py = M.x * 16 + x * 4, M.y * 16 + y * 4 + local lw, lh = w * 4, h * 4 + local lo = pic.yo + py * ys + px + local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 + local co = pic.co + cy * cs + cx + -- weights for this pair + local bi = ref0 ~= nil and ref1 ~= nil + local explicit = wm == 1 + local implicitW0, implicitW1 = 32, 32 + if wm == 2 then + if bi then + local iw = S.implicit[r0 * 32 + r1 + 1] + implicitW0, implicitW1 = 64 - iw, iw + else + explicit = false + end + end + local W0, W1 = S.weights0, S.weights1 + for plane = 0, 2 do + local dst, o, s, bw, bh = pic.y, lo, ys, lw, lh + if plane == 1 then + dst, o, s, bw, bh = pic.u, co, cs, cw, ch + elseif plane == 2 then + dst, o, s, bw, bh = pic.v, co, cs, cw, ch + end + if ref0 then + if plane == 0 then + predLuma(S, ref0, P0, px, py, lw, lh, m0x, m0y) + else + predChroma(S, ref0, P0, ((plane == 1) and (ref0.u) or (ref0.v)), cx, cy, cw, ch, m0x, m0y) + end + end + if ref1 then + if plane == 0 then + predLuma(S, ref1, P1, px, py, lw, lh, m1x, m1y) + else + predChroma(S, ref1, P1, ((plane == 1) and (ref1.u) or (ref1.v)), cx, cy, cw, ch, m1x, m1y) + end + end + if wm == 2 and bi then + Inter.weight2(P0, P1, bw, bh, dst, o, s, 5, implicitW0, implicitW1, 0) + elseif explicit then + local logWD = ((plane == 0) and (S.lumaDenom) or (S.chromaDenom)) + local wi = plane * 2 + 1 + if bi then + local b0, b1 = r0 * 8, r1 * 8 + Inter.weight2(P0, P1, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W1[b1 + wi] or 1, math.floor(((W0[b0 + wi + 1] or 0) + (W1[b1 + wi + 1] or 0) + 1) / 2)) + elseif ref0 then + local b0 = r0 * 8 + Inter.weight1(P0, bw, bh, dst, o, s, logWD, W0[b0 + wi] or 1, W0[b0 + wi + 1] or 0) + else + local b1 = r1 * 8 + Inter.weight1(P1, bw, bh, dst, o, s, logWD, W1[b1 + wi] or 1, W1[b1 + wi + 1] or 0) + end + elseif bi then + Inter.avg(P0, P1, bw, bh, dst, o, s) + elseif ref0 then + Inter.put(P0, bw, bh, dst, o, s) + else + Inter.put(P1, bw, bh, dst, o, s) + end + end +__DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end +end + +-- ------------------------------------------------------------------------------------------------ residual +local function lumaResidual(S, M) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local nz, c4, c8 = M.nz, M.c4, M.c8 + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, o + by * 4 * s + bx * 4, s) + end + end + return + end + for blk = 0, 15 do + if nz[blk + 1] > 0 then + local bx, by = blk % 4, math.floor(blk / 4 +) add4(c4, blk * 16, b, o + by * 4 * s + bx * 4, s) + end + end +end + +local function chromaResidual(S, M) + if not M.hasDcC and M.cbp < 32 then + return + end + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + local cc, nzc = M.cc, M.nzc + if M.hasDcC then + local dq = S.dq.d4 + local intra = M.kind <= K_PCM + Transform.chromaDc(M.dcC, 0, dq[((intra) and (2) or (5))][M.qpc + 1][1], cc, 0) + Transform.chromaDc(M.dcC, 4, dq[((intra) and (3) or (6))][M.qpc2 + 1][1], cc, 64) + end + for plane = 0, 1 do + local b = ((plane == 0) and (pic.u) or (pic.v)) + for blk = 0, 3 do + local base = (plane * 4 + blk) * 16 + local q = o + (math.floor(blk / 2)) * 4 * s + (blk % 2) * 4 + if nzc[plane * 4 + blk + 1] > 0 then + add4(cc, base, b, q, s) + elseif cc[base + 1] ~= 0 then + addDc4(cc[base + 1], b, q, s) + cc[base + 1] = 0 + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ intra +local function intraLuma(S, M) + local pic = S.pic + local b, s = pic.y, pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + local kind = M.kind + local ipm = M.ipm + if kind == K_I16 then + Intra.pred16x16(b, o, s, M.i16, M.iL, M.iT, M.iTL) + local c4, nz = M.c4, M.nz + if M.hasDcY then + Transform.lumaDc(M.dcY, S.dq.d4[1][M.qp + 1][1], c4) + end + for blk = 0, 15 do + local bx, by = blk % 4, math.floor(blk / 4 +) local q = o + by * 4 * s + bx * 4 + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + elseif c4[blk * 16 + 1] ~= 0 then + addDc4(c4[blk * 16 + 1], b, q, s) + c4[blk * 16 + 1] = 0 + end + end + elseif kind == K_I8 then + local nz, c8 = M.nz, M.c8 + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tr, tl + if i8 == 0 then + tr, tl = M.iT, M.iTL + elseif i8 == 1 then + tr, tl = M.iTR, M.iT + elseif i8 == 2 then + tr, tl = true, M.iL + else + tr, tl = false, true + end + local q = o + by * 4 * s + bx * 4 + Intra.pred8x8(b, q, s, ipm[by * 4 + bx + 1], left, top, tr, tl) + if nz[by * 4 + bx + 1] > 0 then + add8(c8, i8 * 64, b, q, s) + end + end + else + local nz, c4 = M.nz, M.c4 + for i = 0, 15 do + local bx, by = BLK_X[i + 1], BLK_Y[i + 1] + local blk = by * 4 + bx + local left = bx > 0 or M.iL + local top = by > 0 or M.iT + local tl + if bx > 0 and by > 0 then + tl = true + elseif bx > 0 then + tl = M.iT + elseif by > 0 then + tl = M.iL + else + tl = M.iTL + end + local tr + if by == 0 then + if bx < 3 then + tr = M.iT + else + tr = M.iTR + end + else + tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3))) + end + local q = o + by * 4 * s + bx * 4 + Intra.pred4x4(b, q, s, ipm[blk + 1], left, top, tr, tl) + if nz[blk + 1] > 0 then + add4(c4, blk * 16, b, q, s) + end + end + end +end + +local function intraChroma(S, M) + local pic = S.pic + local s = pic.cs + local o = pic.co + M.y * 8 * s + M.x * 8 + Intra.predChroma(pic.u, o, s, M.cpm, M.iL, M.iT, M.iTL) + Intra.predChroma(pic.v, o, s, M.cpm, M.iL, M.iT, M.iTL) +end + +local function pcm(S, M) + local pic = S.pic + local src = M.pcm + local s = pic.ys + local o = pic.yo + M.y * 16 * s + M.x * 16 + for y = 0, 15 do + buffer.copy(pic.y, o + y * s, src, y * 16, 16) + end + s = pic.cs + o = pic.co + M.y * 8 * s + M.x * 8 + for y = 0, 7 do + buffer.copy(pic.u, o + y * s, src, 256 + y * 8, 8) + buffer.copy(pic.v, o + y * s, src, 320 + y * 8, 8) + end +end + +-- ------------------------------------------------------------------------------------------------ macroblock +-- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need +function Mb.recon(S, M) + local kind = M.kind + local addr = M.addr + 1 + local pic = S.pic + local w4 = S.w4 + S.kind[addr] = kind + S.sliceTab[addr] = S.slice + S.t8Tab[addr] = M.t8 + S.qpTab[addr] = ((kind == K_PCM) and (0) or (M.qp)) + S.qpcTab[addr] = ((kind == K_PCM) and (S.qpcOf[1]) or (M.qpc)) + S.qpc2Tab[addr] = ((kind == K_PCM) and (S.qpc2Of[1]) or (M.qpc2)) + pic.mbIntra[addr] = kind <= K_PCM + local nzDb = S.nzDb + local g0 = M.g0 + if kind <= K_PCM then + -- intra: no motion + local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + ref0[g + i], ref1[g + i], uid0[g + i], uid1[g + i] = -1, -1, -1, -1 + end + end + if kind == K_PCM or kind == K_I16 then + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + end + if kind == K_PCM then + pcm(S, M) + return + end + intraLuma(S, M) + intraChroma(S, M) + chromaResidual(S, M) + return + end + local ipm = S.ipm + for j = 0, 3 do + local g = g0 + j * w4 + ipm[g], ipm[g + 1], ipm[g + 2], ipm[g + 3] = 2, 2, 2, 2 + end + motion(S, M) + mc(S, M) + local nz = M.nz + if M.t8 == 1 then + for i8 = 0, 3 do + local bx, by = (i8 % 2) * 2, (math.floor(i8 / 2)) * 2 + local v = ((nz[by * 4 + bx + 1] > 0) and (1) or (0)) + local g = g0 + by * w4 + bx + nzDb[g], nzDb[g + 1], nzDb[g + w4], nzDb[g + w4 + 1] = v, v, v, v + end + else + for blk = 0, 15 do + nzDb[g0 + (math.floor(blk / 4)) * w4 + blk % 4] = ((nz[blk + 1] > 0) and (1) or (0)) + end + end + if M.cbp % 16 ~= 0 then + lumaResidual(S, M) + end + chromaResidual(S, M) +end + +-- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual) +function Mb.skip(S, M, kind) + M.kind = kind + M.cbp = 0 + M.t8 = 0 + M.qp = S.qp + M.qpc = S.qpcOf[S.qp + 1] + M.qpc2 = S.qpc2Of[S.qp + 1] + local addr = M.addr + 1 + S.cbpTab[addr] = 0 + S.dcTab[addr] = 0 + S.cpmTab[addr] = 0 + S.qpdTab[addr] = 0 + local nz = M.nz + for i = 1, 16 do + nz[i] = 0 + end + local nzc = M.nzc + for i = 1, 8 do + nzc[i] = 0 + end + local w4, g0 = S.w4, M.g0 + local grid, mvd0, mvd1, rgt0, rgt1 = S.nzc, S.mvd0, S.mvd1, S.rgt0, S.rgt1 + for j = 0, 3 do + local g = g0 + j * w4 + for i = 0, 3 do + grid[g + i] = 0 + mvd0[2 * (g + i) - 1], mvd0[2 * (g + i)] = 0, 0 + mvd1[2 * (g + i) - 1], mvd1[2 * (g + i)] = 0, 0 + rgt0[g + i], rgt1[g + i] = 0, 0 + end + end + local cw, c0 = S.cw4, M.c0 + local cb, cr = S.nzcCb, S.nzcCr + cb[c0], cb[c0 + 1], cb[c0 + cw], cb[c0 + cw + 1] = 0, 0, 0, 0 + cr[c0], cr[c0 + 1], cr[c0 + cw], cr[c0 + cw + 1] = 0, 0, 0, 0 + M.hasDcC = false + Mb.recon(S, M) +end + +return Mb +end +__FILES["codecs/video/H264/Params"] = function() +--!strict +--!native +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with +-- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the +-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. +-- Never throws: parse functions return nil, "message". +local Bitstream = __include("codecs/video/H264/Bitstream") +local Tables = __include("codecs/video/H264/Tables") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Params = {} + +local HIGH_PROFILES = { [100] = true, [110] = true, [122] = true, [244] = true, [44] = true, [83] = true, [86] = true, [118] = true, [128] = true, [138] = true, [139] = true, [134] = true, [135] = true } + +-- MaxDpbMbs by level_idc (table A-1); level 9 is level 1b +local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 2376, [20] = 2376, [21] = 4752, [22] = 8100, [30] = 8100, [31] = 18000, [32] = 20480, [40] = 32768, [41] = 32768, [42] = 34816, [50] = 110400, [51] = 184320, [52] = 184320, [60] = 696320, [61] = 696320, [62] = 696320 } + +local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 + +-- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) +local function scalingList(r, size) +local list = table.create(size, 0) + local last, nxt = 8, 8 + local zz = (size == 16 and{ZIGZAG4 }or{ZIGZAG8 +})[1] for j = 0, size - 1 do + if nxt ~= 0 then + local d = se(r) + if d < -128 or d > 127 then + return nil + end + nxt = (last + d + 256) % 256 + if j == 0 and nxt == 0 then + return "default" + end + end + local v = (nxt == 0 and{last }or{nxt +})[1] list[zz[j + 1] + 1] = v + last = v + end + return list +end + +-- lists: 12 entries (false = not present, "default", or a raster list) +local function scalingMatrix(r, count) +local lists = table.create(12, false) + for i = 1, count do + if u1(r) == 1 then + local l = scalingList(r, i <= 6 and 16 or 64) + if l == nil then + return nil + end + lists[i] = l + end + end + return lists +end + +local function default(i) +local out = {} + if i <= 6 then + local base = i <= 3 and 0 or 16 + for k = 1, 16 do + out[k] = Tables.DEFAULT_4x4[base + k] + end + else + local base = (i - 7) % 2 == 0 and 0 or 64 + for k = 1, 64 do + out[k] = Tables.DEFAULT_8x8[base + k] + end + end + return out +end + +local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) + +-- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) +local function resolve(lists, fallback) +local out = {} + for i = 1, 12 do + local l = lists[i] + if l == "default" then + out[i] = default(i) + elseif l then + out[i] = l + elseif i == 1 or i == 4 or i == 7 or i == 8 then + out[i] = (fallback and{fallback[i] }or{(default(i) +)})[1] elseif i <= 6 then + out[i] = out[i - 1] + else + out[i] = out[i - 2] + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ vui +local function hrd(r) + local cnt = ue(r) + if cnt > 31 then + return false + end + u(r, 8) + for _ = 0, cnt do + ue(r) + ue(r) + u1(r) + end + u(r, 20) + return true +end + +local function vui(r, sps) + if u1(r) == 1 then + local idc = u(r, 8) + if idc == 255 then + sps.sarW = u(r, 16) + sps.sarH = u(r, 16) + end + sps.aspectIdc = idc + end + if u1(r) == 1 then + u1(r) + end + if u1(r) == 1 then + u(r, 3) + sps.fullRange = u1(r) == 1 + if u1(r) == 1 then + sps.colourPrimaries = u(r, 8) + sps.transfer = u(r, 8) + sps.matrix = u(r, 8) + end + end + if u1(r) == 1 then + ue(r) + ue(r) + end + if u1(r) == 1 then + sps.unitsInTick = u(r, 32) + sps.timeScale = u(r, 32) + sps.fixedRate = u1(r) == 1 + end + local nal = u1(r) == 1 + if nal and not hrd(r) then + return + end + local vcl = u1(r) == 1 + if vcl and not hrd(r) then + return + end + if nal or vcl then + u1(r) + end + u1(r) + if u1(r) == 1 then + u1(r) + ue(r) + ue(r) + ue(r) + ue(r) + local reorder = ue(r) + local dpb = ue(r) + if r.pos <= r.size and reorder <= 16 and dpb <= 16 then + sps.numReorderFrames = reorder + sps.maxDecFrameBuffering = dpb + end + end +end + +-- ------------------------------------------------------------------------------------------------ sps +-- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header. +function Params.sps(r) +local sps= {} + sps.profile = u(r, 8) + sps.constraints = u(r, 8) + sps.level = u(r, 8) + sps.id = ue(r) + if sps.id > 31 then + return nil, "seq_parameter_set_id out of range" + end + sps.chromaFormat = 1 + sps.bitDepth = 8 + sps.bitDepthC = 8 + sps.bypass = false + sps.scaling = nil + if HIGH_PROFILES[sps.profile] then + sps.chromaFormat = ue(r) + if sps.chromaFormat > 3 then + return nil, "chroma_format_idc out of range" + end + if sps.chromaFormat == 3 then + sps.separatePlanes = u1(r) == 1 + end + sps.bitDepth = ue(r) + 8 + sps.bitDepthC = ue(r) + 8 + if sps.bitDepth > 14 or sps.bitDepthC > 14 then + return nil, "bit depth out of range" + end + sps.bypass = u1(r) == 1 + if u1(r) == 1 then + local lists = scalingMatrix(r, sps.chromaFormat ~= 3 and 8 or 12) + if not lists then + return nil, "bad scaling list" + end + sps.scaling = resolve(lists, nil) + end + end + sps.log2MaxFrameNum = ue(r) + 4 + if sps.log2MaxFrameNum > 16 then + return nil, "log2_max_frame_num out of range" + end + sps.pocType = ue(r) + if sps.pocType == 0 then + sps.log2MaxPocLsb = ue(r) + 4 + if sps.log2MaxPocLsb > 16 then + return nil, "log2_max_pic_order_cnt_lsb out of range" + end + elseif sps.pocType == 1 then + sps.deltaPocAlwaysZero = u1(r) == 1 + sps.offsetNonRef = se(r) + sps.offsetTopToBottom = se(r) + local n = ue(r) + if n > 255 then + return nil, "num_ref_frames_in_pic_order_cnt_cycle out of range" + end + sps.offsetsForRefFrame = {} + local expected = 0 + for i = 1, n do + sps.offsetsForRefFrame[i] = se(r) + expected =expected+ sps.offsetsForRefFrame[i] + end + sps.expectedDeltaPerCycle = expected + elseif sps.pocType ~= 2 then + return nil, "pic_order_cnt_type out of range" + end + sps.maxRefFrames = ue(r) + if sps.maxRefFrames > 16 then + return nil, "max_num_ref_frames out of range" + end + sps.gapsAllowed = u1(r) == 1 + sps.mbWidth = ue(r) + 1 + sps.mbHeightMap = ue(r) + 1 + sps.frameMbsOnly = u1(r) == 1 + if not sps.frameMbsOnly then + sps.mbaff = u1(r) == 1 + end + sps.mbHeight = (sps.frameMbsOnly and{sps.mbHeightMap }or{(sps.mbHeightMap * 2 +)})[1] if sps.mbWidth > 1024 or sps.mbHeight > 1024 then + return nil, "limit: picture too large" + end + sps.direct8x8 = u1(r) == 1 + sps.cropLeft, sps.cropRight, sps.cropTop, sps.cropBottom = 0, 0, 0, 0 + if u1(r) == 1 then + sps.cropLeft = ue(r) + sps.cropRight = ue(r) + sps.cropTop = ue(r) + sps.cropBottom = ue(r) + end + if r.pos > r.size then + return nil, "truncated: sequence parameter set" + end + if u1(r) == 1 then + local save = r.pos + vui(r, sps) + if r.pos > r.size then + r.pos = save + end + end + -- derived sizes (4:2:0 crop units: 2 x 2; monochrome / 4:4:4 are rejected later) + local cux, cuy = 2, 2 * (sps.frameMbsOnly and 1 or 2) + if sps.chromaFormat == 0 or sps.chromaFormat == 3 then + cux, cuy = 1, (sps.frameMbsOnly and 1 or 2) + elseif sps.chromaFormat == 2 then + cux, cuy = 2, (sps.frameMbsOnly and 1 or 2) + end + local w, h = sps.mbWidth * 16, sps.mbHeight * 16 + sps.width = w - cux * (sps.cropLeft + sps.cropRight) + sps.height = h - cuy * (sps.cropTop + sps.cropBottom) + sps.cropX = cux * sps.cropLeft + sps.cropY = cuy * sps.cropTop + if sps.width <= 0 or sps.height <= 0 then + return nil, "cropping larger than the picture" + end + local maxMbs = MAX_DPB_MBS[sps.level] or 696320 + if sps.level == 11 and sps.constraints % 32 >= 16 and sps.profile ~= 100 then + maxMbs = 396 -- level 1b + end + sps.maxDpbFrames = math.clamp(math.floor(maxMbs / (sps.mbWidth * sps.mbHeight)), 1, 16) + return sps, nil +end + +-- ------------------------------------------------------------------------------------------------ pps +-- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count) +function Params.pps(r, spsTable) +local pps= {} + pps.id = ue(r) + if pps.id > 255 then + return nil, "pic_parameter_set_id out of range" + end + pps.spsId = ue(r) + local sps = spsTable[pps.spsId] + if not sps then + return nil, "pps refers to a missing sps" + end + pps.cabac = u1(r) == 1 + pps.bottomFieldPocPresent = u1(r) == 1 + pps.sliceGroups = ue(r) + 1 + if pps.sliceGroups > 1 then + return nil, "unsupported: slice groups (FMO)" + end + pps.numRefIdxL0 = ue(r) + 1 + pps.numRefIdxL1 = ue(r) + 1 + if pps.numRefIdxL0 > 32 or pps.numRefIdxL1 > 32 then + return nil, "num_ref_idx_default_active out of range" + end + pps.weightedPred = u1(r) == 1 + pps.weightedBipred = u(r, 2) + pps.initQp = 26 + se(r) + pps.initQs = 26 + se(r) + pps.chromaQpOffset = se(r) + if pps.initQp < 0 or pps.initQp > 51 or pps.chromaQpOffset < -12 or pps.chromaQpOffset > 12 then + return nil, "pic_init_qp / chroma_qp_index_offset out of range" + end + pps.deblockingControl = u1(r) == 1 + pps.constrainedIntra = u1(r) == 1 + pps.redundantPicCnt = u1(r) == 1 + pps.transform8x8 = false + pps.chromaQpOffset2 = pps.chromaQpOffset + pps.scalingLists = nil + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + if Bitstream.moreData(r) then + pps.transform8x8 = u1(r) == 1 + if u1(r) == 1 then + local n = 6 + ((pps.transform8x8 and{(sps.chromaFormat ~= 3 and 2 or 6) }or{0})[1]) + local lists = scalingMatrix(r, n) + if not lists then + return nil, "bad scaling list" + end + pps.scalingLists = lists + end + pps.chromaQpOffset2 = se(r) + if pps.chromaQpOffset2 < -12 or pps.chromaQpOffset2 > 12 then + return nil, "second_chroma_qp_index_offset out of range" + end + if r.pos > r.size then + return nil, "truncated: picture parameter set" + end + end + return pps, nil +end + +-- ------------------------------------------------------------------------------------------------ dequantisation +local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } +local V8 = { + { 20, 18, 32, 19, 25, 24 }, + { 22, 19, 35, 21, 28, 26 }, + { 26, 23, 42, 24, 33, 31 }, + { 28, 25, 45, 26, 35, 33 }, + { 32, 28, 51, 30, 40, 38 }, + { 36, 32, 58, 34, 46, 43 }, +} + +local function norm4(m, i, j) +local v = V4[m + 1] + if i % 2 == 0 and j % 2 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + end + return v[3] +end + +local function norm8(m, i, j) +local v = V8[m + 1] + if i % 4 == 0 and j % 4 == 0 then + return v[1] + elseif i % 2 == 1 and j % 2 == 1 then + return v[2] + elseif i % 4 == 2 and j % 4 == 2 then + return v[3] + elseif (i % 4 == 0 and j % 2 == 1) or (i % 2 == 1 and j % 4 == 0) then + return v[4] + elseif (i % 4 == 0 and j % 4 == 2) or (i % 4 == 2 and j % 4 == 0) then + return v[5] + end + return v[6] +end + +-- dequant tables: dq.d4[list][qp + 1] = 16 multipliers (raster), list 1..6 = Y/Cb/Cr intra, Y/Cb/Cr inter; +-- dq.d8[list][qp + 1] = 64 multipliers, list 1 = Y intra, 2 = Y inter. A 4x4 coefficient c dequantises to +-- (c * m + 8) >> 4, an 8x8 one to (c * m + 32) >> 6 (8.5.12.1 / 8.5.13.1 with LevelScale * 2^(qP / 6)). +local function build(lists) +local d4, d8 = {}, {} + for l = 1, 6 do + local w = lists[l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (math.floor(qp / 6)) + local t = table.create(16, 0) + for k = 0, 15 do + local i, j = k % 4, math.floor(k / 4 +) t[k + 1] = w[k + 1] * norm4(m, i, j) * sh + end + per[qp + 1] = t + end + d4[l] = per + end + for l = 1, 2 do + local w = lists[6 + l] + local per = {} + for qp = 0, 51 do + local m, sh = qp % 6, 2 ^ (math.floor(qp / 6)) + local t = table.create(64, 0) + for k = 0, 63 do + local i, j = k % 8, math.floor(k / 8 +) t[k + 1] = w[k + 1] * norm8(m, i, j) * sh + end + per[qp + 1] = t + end + d8[l] = per + end + return { d4 = d4, d8 = d8 } +end + +-- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content) +function Params.dequant(sps, pps, cache) +local lists +if pps.scalingLists then + lists = resolve(pps.scalingLists, sps.scaling) + elseif sps.scaling then + lists = sps.scaling + else + lists = {} + for i = 1, 12 do + lists[i] = (i <= 6 and{FLAT16 }or{FLAT64 +})[1] end + end + local parts = {} + for i = 1, 8 do + parts[i] = table.concat(lists[i], ",") + end + local key = table.concat(parts, ";") + local dq = cache[key] + if not dq then + dq = build(lists) + cache[key] = dq + end + return dq +end + +return Params +end +__FILES["codecs/video/H264/Slice"] = function() +local __compat = __compat local type = __compat.type --!strict +--!native +-- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and +-- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, +-- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". +-- Never throws: header() returns nil, "message". +local Bitstream = __include("codecs/video/H264/Bitstream") + +local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se + +local Slice = {} + +Slice.P, Slice.B, Slice.I, Slice.SP, Slice.SI = 0, 1, 2, 3, 4 + +local function modifications(r) +local ops = {} + if u1(r) == 1 then + for _ = 1, 100 do + local idc = ue(r) + if idc == 3 then + return ops + end + if idc > 5 then + return nil + end + table.insert(ops, idc) + table.insert(ops, ue(r)) + if r.pos > r.size then + return nil + end + end + return nil + end + return ops +end + +local function weights(r, n, lw, cw, chroma) -- per entry: lumaW, lumaO, cbW, cbO, crW, crO, lumaFlag, chromaFlag (8 numbers) + +local t = table.create(n * 8, 0) + for i = 0, n - 1 do + local b = i * 8 + t[b + 1], t[b + 2], t[b + 3], t[b + 4], t[b + 5], t[b + 6] = lw, 0, cw, 0, cw, 0 + if u1(r) == 1 then + t[b + 1] = se(r) + t[b + 2] = se(r) + t[b + 7] = 1 + if t[b + 1] < -128 or t[b + 1] > 127 or t[b + 2] < -128 or t[b + 2] > 127 then + return nil + end + end + if chroma and u1(r) == 1 then + for k = 0, 1 do + t[b + 3 + k * 2] = se(r) + t[b + 4 + k * 2] = se(r) + if t[b + 3 + k * 2] < -128 or t[b + 3 + k * 2] > 127 or t[b + 4 + k * 2] < -128 or t[b + 4 + k * 2] > 127 then + return nil + end + end + t[b + 8] = 1 + end + end + return t +end + +-- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message +function Slice.header(r, nalType, nalRefIdc, spsTable, ppsTable) +local sh= {} + sh.nalType = nalType + sh.nalRefIdc = nalRefIdc + sh.idr = nalType == 5 + sh.firstMb = ue(r) + local st = ue(r) + if st > 9 then + return nil, "slice_type out of range" + end + sh.type = st % 5 + if sh.type == Slice.SP or sh.type == Slice.SI then + return nil, "unsupported: SP / SI slices (Extended profile)" + end + sh.ppsId = ue(r) + local pps = ppsTable[sh.ppsId] + if not pps then + return nil, "slice refers to a missing pps" + end + local sps = spsTable[pps.spsId] + if not sps then + return nil, "slice refers to a missing sps" + end + sh.pps, sh.sps = pps, sps + if sps.separatePlanes then + return nil, "unsupported: separate colour planes" + end + sh.frameNum = u(r, sps.log2MaxFrameNum) + if not sps.frameMbsOnly then + if u1(r) == 1 then + return nil, "unsupported: field pictures (PAFF)" + end + if sps.mbaff then + return nil, "unsupported: MBAFF" + end + end + if sh.idr then + sh.idrPicId = ue(r) + end + sh.pocLsb, sh.deltaPocBottom, sh.deltaPoc0, sh.deltaPoc1 = 0, 0, 0, 0 + if sps.pocType == 0 then + sh.pocLsb = u(r, sps.log2MaxPocLsb) + if pps.bottomFieldPocPresent then + sh.deltaPocBottom = se(r) + end + elseif sps.pocType == 1 and not sps.deltaPocAlwaysZero then + sh.deltaPoc0 = se(r) + if pps.bottomFieldPocPresent then + sh.deltaPoc1 = se(r) + end + end + if pps.redundantPicCnt then + sh.redundantPicCnt = ue(r) + end + sh.numRefIdxL0, sh.numRefIdxL1 = 0, 0 + if sh.type == Slice.B then + sh.directSpatial = u1(r) == 1 + end + if sh.type ~= Slice.I then + sh.numRefIdxL0 = pps.numRefIdxL0 + sh.numRefIdxL1 = (sh.type == Slice.B and{pps.numRefIdxL1 }or{0 +})[1] if u1(r) == 1 then + sh.numRefIdxL0 = ue(r) + 1 + if sh.type == Slice.B then + sh.numRefIdxL1 = ue(r) + 1 + end + end + if sh.numRefIdxL0 > 32 or sh.numRefIdxL1 > 32 then + return nil, "num_ref_idx_active out of range" + end + local m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod0 = m + if sh.type == Slice.B then + m = modifications(r) + if not m then + return nil, "bad ref_pic_list_modification" + end + sh.mod1 = m + end + end + sh.weightMode = 0 -- 0 default, 1 explicit, 2 implicit + if (pps.weightedPred and sh.type == Slice.P) or (pps.weightedBipred == 1 and sh.type == Slice.B) then + sh.weightMode = 1 + sh.lumaDenom = ue(r) + if sh.lumaDenom > 7 then + return nil, "luma_log2_weight_denom out of range" + end + local chroma = sps.chromaFormat ~= 0 + sh.chromaDenom = 0 + if chroma then + sh.chromaDenom = ue(r) + if sh.chromaDenom > 7 then + return nil, "chroma_log2_weight_denom out of range" + end + end + local w = weights(r, sh.numRefIdxL0, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights0 = w + if sh.type == Slice.B then + w = weights(r, sh.numRefIdxL1, 2 ^ sh.lumaDenom, 2 ^ sh.chromaDenom, chroma) + if not w then + return nil, "bad pred_weight_table" + end + sh.weights1 = w + end + elseif pps.weightedBipred == 2 and sh.type == Slice.B then + sh.weightMode = 2 + end + if nalRefIdc ~= 0 then + if sh.idr then + sh.noOutputOfPriorPics = u1(r) == 1 + sh.longTermReference = u1(r) == 1 + else + sh.adaptive = u1(r) == 1 + if sh.adaptive then + local ops = {} + for _ = 1, 100 do + local op = ue(r) + if op == 0 then + break + end + if op > 6 then + return nil, "bad memory_management_control_operation" + end + local a, b = 0, 0 + if op == 1 or op == 3 then + a = ue(r) + 1 -- difference_of_pic_nums + end + if op == 2 then + a = ue(r) -- long_term_pic_num + end + if op == 3 or op == 6 then + b = ue(r) -- long_term_frame_idx + end + if op == 4 then + a = ue(r) -- max_long_term_frame_idx_plus1 + end + if r.pos > r.size then + return nil, "truncated: dec_ref_pic_marking" + end + table.insert(ops, op) + table.insert(ops, a) + table.insert(ops, b) + end + sh.mmco = ops + end + end + end + sh.cabacInit = 0 + if pps.cabac and sh.type ~= Slice.I then + sh.cabacInit = ue(r) + if sh.cabacInit > 2 then + return nil, "cabac_init_idc out of range" + end + end + sh.qp = pps.initQp + se(r) + if sh.qp < 0 or sh.qp > 51 then + return nil, "slice QP out of range" + end + sh.deblock = 0 + sh.alphaOffset, sh.betaOffset = 0, 0 + if pps.deblockingControl then + sh.deblock = ue(r) + if sh.deblock > 2 then + return nil, "disable_deblocking_filter_idc out of range" + end + if sh.deblock ~= 1 then + sh.alphaOffset = se(r) * 2 + sh.betaOffset = se(r) * 2 + if sh.alphaOffset < -12 or sh.alphaOffset > 12 or sh.betaOffset < -12 or sh.betaOffset > 12 then + return nil, "slice_alpha / beta_offset out of range" + end + end + end + if r.pos > r.size then + return nil, "truncated: slice header" + end + return sh, nil +end + +return Slice +end +__FILES["codecs/video/H264/Tables"] = function() +--!strict +--!native +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context +-- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the +-- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the +-- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, +-- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp, +-- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table. +local T = {} + +-- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, +-- TrailingOnes } quads. TOTAL_ZEROS / TOTAL_ZEROS_CDC / RUN_BEFORE: { tzVlcIndex | zerosLeft, code, len, value } quads. +-- CABAC_INIT: [ctxIdx * 8 + model * 2 + 1] = m, [... + 2] = n; model 0 = I slices, 1..3 = cabac_init_idc 0..2. +-- RANGE_LPS: [pStateIdx * 4 + qCodIRangeIdx + 1]. TRANS: [pStateIdx * 2 + 1] = transIdxLPS, [+ 2] = transIdxMPS. +-- DEFAULT_4x4 / DEFAULT_8x8: intra list then inter list, raster order. ZIGZAG4 / ZIGZAG8: scan index -> raster index. +-- SIG8 / LAST8: 8x8 significant / last ctxIdxInc by scan index (frame coded). ALPHA / BETA: [indexA + 13] (index +-- -12..63); TC0: [(indexA + 12) * 4 + bS + 1] (bS 0..3; bS 0 is unused). +T.COEFF_TOKEN_0 = { 1, 1, 0, 0, 5, 6, 1, 0, 1, 2, 1, 1, 7, 8, 2, 0, 4, 6, 2, 1, 1, 3, 2, 2, 7, 9, 3, 0, 6, 8, 3, 1, 5, 7, 3, 2, 3, 5, 3, 3, 7, 10, 4, 0, 6, 9, 4, 1, 5, 8, 4, 2, 3, 6, 4, 3, 7, 11, 5, 0, 6, 10, 5, 1, 5, 9, 5, 2, 4, 7, 5, 3, 15, 13, 6, 0, 6, 11, 6, 1, 5, 10, 6, 2, 4, 8, 6, 3, 11, 13, 7, 0, 14, 13, 7, 1, 5, 11, 7, 2, 4, 9, 7, 3, 8, 13, 8, 0, 10, 13, 8, 1, 13, 13, 8, 2, 4, 10, 8, 3, 15, 14, 9, 0, 14, 14, 9, 1, 9, 13, 9, 2, 4, 11, 9, 3, 11, 14, 10, 0, 10, 14, 10, 1, 13, 14, 10, 2, 12, 13, 10, 3, 15, 15, 11, 0, 14, 15, 11, 1, 9, 14, 11, 2, 12, 14, 11, 3, 11, 15, 12, 0, 10, 15, 12, 1, 13, 15, 12, 2, 8, 14, 12, 3, 15, 16, 13, 0, 1, 15, 13, 1, 9, 15, 13, 2, 12, 15, 13, 3, 11, 16, 14, 0, 14, 16, 14, 1, 13, 16, 14, 2, 8, 15, 14, 3, 7, 16, 15, 0, 10, 16, 15, 1, 9, 16, 15, 2, 12, 16, 15, 3, 4, 16, 16, 0, 6, 16, 16, 1, 5, 16, 16, 2, 8, 16, 16, 3 } +T.COEFF_TOKEN_1 = { 3, 2, 0, 0, 11, 6, 1, 0, 2, 2, 1, 1, 7, 6, 2, 0, 7, 5, 2, 1, 3, 3, 2, 2, 7, 7, 3, 0, 10, 6, 3, 1, 9, 6, 3, 2, 5, 4, 3, 3, 7, 8, 4, 0, 6, 6, 4, 1, 5, 6, 4, 2, 4, 4, 4, 3, 4, 8, 5, 0, 6, 7, 5, 1, 5, 7, 5, 2, 6, 5, 5, 3, 7, 9, 6, 0, 6, 8, 6, 1, 5, 8, 6, 2, 8, 6, 6, 3, 15, 11, 7, 0, 6, 9, 7, 1, 5, 9, 7, 2, 4, 6, 7, 3, 11, 11, 8, 0, 14, 11, 8, 1, 13, 11, 8, 2, 4, 7, 8, 3, 15, 12, 9, 0, 10, 11, 9, 1, 9, 11, 9, 2, 4, 9, 9, 3, 11, 12, 10, 0, 14, 12, 10, 1, 13, 12, 10, 2, 12, 11, 10, 3, 8, 12, 11, 0, 10, 12, 11, 1, 9, 12, 11, 2, 8, 11, 11, 3, 15, 13, 12, 0, 14, 13, 12, 1, 13, 13, 12, 2, 12, 12, 12, 3, 11, 13, 13, 0, 10, 13, 13, 1, 9, 13, 13, 2, 12, 13, 13, 3, 7, 13, 14, 0, 11, 14, 14, 1, 6, 13, 14, 2, 8, 13, 14, 3, 9, 14, 15, 0, 8, 14, 15, 1, 10, 14, 15, 2, 1, 13, 15, 3, 7, 14, 16, 0, 6, 14, 16, 1, 5, 14, 16, 2, 4, 14, 16, 3 } +T.COEFF_TOKEN_2 = { 15, 4, 0, 0, 15, 6, 1, 0, 14, 4, 1, 1, 11, 6, 2, 0, 15, 5, 2, 1, 13, 4, 2, 2, 8, 6, 3, 0, 12, 5, 3, 1, 14, 5, 3, 2, 12, 4, 3, 3, 15, 7, 4, 0, 10, 5, 4, 1, 11, 5, 4, 2, 11, 4, 4, 3, 11, 7, 5, 0, 8, 5, 5, 1, 9, 5, 5, 2, 10, 4, 5, 3, 9, 7, 6, 0, 14, 6, 6, 1, 13, 6, 6, 2, 9, 4, 6, 3, 8, 7, 7, 0, 10, 6, 7, 1, 9, 6, 7, 2, 8, 4, 7, 3, 15, 8, 8, 0, 14, 7, 8, 1, 13, 7, 8, 2, 13, 5, 8, 3, 11, 8, 9, 0, 14, 8, 9, 1, 10, 7, 9, 2, 12, 6, 9, 3, 15, 9, 10, 0, 10, 8, 10, 1, 13, 8, 10, 2, 12, 7, 10, 3, 11, 9, 11, 0, 14, 9, 11, 1, 9, 8, 11, 2, 12, 8, 11, 3, 8, 9, 12, 0, 10, 9, 12, 1, 13, 9, 12, 2, 8, 8, 12, 3, 13, 10, 13, 0, 7, 9, 13, 1, 9, 9, 13, 2, 12, 9, 13, 3, 9, 10, 14, 0, 12, 10, 14, 1, 11, 10, 14, 2, 10, 10, 14, 3, 5, 10, 15, 0, 8, 10, 15, 1, 7, 10, 15, 2, 6, 10, 15, 3, 1, 10, 16, 0, 4, 10, 16, 1, 3, 10, 16, 2, 2, 10, 16, 3 } +T.COEFF_TOKEN_3 = { 3, 6, 0, 0, 0, 6, 1, 0, 1, 6, 1, 1, 4, 6, 2, 0, 5, 6, 2, 1, 6, 6, 2, 2, 8, 6, 3, 0, 9, 6, 3, 1, 10, 6, 3, 2, 11, 6, 3, 3, 12, 6, 4, 0, 13, 6, 4, 1, 14, 6, 4, 2, 15, 6, 4, 3, 16, 6, 5, 0, 17, 6, 5, 1, 18, 6, 5, 2, 19, 6, 5, 3, 20, 6, 6, 0, 21, 6, 6, 1, 22, 6, 6, 2, 23, 6, 6, 3, 24, 6, 7, 0, 25, 6, 7, 1, 26, 6, 7, 2, 27, 6, 7, 3, 28, 6, 8, 0, 29, 6, 8, 1, 30, 6, 8, 2, 31, 6, 8, 3, 32, 6, 9, 0, 33, 6, 9, 1, 34, 6, 9, 2, 35, 6, 9, 3, 36, 6, 10, 0, 37, 6, 10, 1, 38, 6, 10, 2, 39, 6, 10, 3, 40, 6, 11, 0, 41, 6, 11, 1, 42, 6, 11, 2, 43, 6, 11, 3, 44, 6, 12, 0, 45, 6, 12, 1, 46, 6, 12, 2, 47, 6, 12, 3, 48, 6, 13, 0, 49, 6, 13, 1, 50, 6, 13, 2, 51, 6, 13, 3, 52, 6, 14, 0, 53, 6, 14, 1, 54, 6, 14, 2, 55, 6, 14, 3, 56, 6, 15, 0, 57, 6, 15, 1, 58, 6, 15, 2, 59, 6, 15, 3, 60, 6, 16, 0, 61, 6, 16, 1, 62, 6, 16, 2, 63, 6, 16, 3 } +T.COEFF_TOKEN_4 = { 1, 2, 0, 0, 7, 6, 1, 0, 1, 1, 1, 1, 4, 6, 2, 0, 6, 6, 2, 1, 1, 3, 2, 2, 3, 6, 3, 0, 3, 7, 3, 1, 2, 7, 3, 2, 5, 6, 3, 3, 2, 6, 4, 0, 3, 8, 4, 1, 2, 8, 4, 2, 0, 7, 4, 3 } +T.TOTAL_ZEROS = { 1, 1, 1, 0, 1, 3, 3, 1, 1, 2, 3, 2, 1, 3, 4, 3, 1, 2, 4, 4, 1, 3, 5, 5, 1, 2, 5, 6, 1, 3, 6, 7, 1, 2, 6, 8, 1, 3, 7, 9, 1, 2, 7, 10, 1, 3, 8, 11, 1, 2, 8, 12, 1, 3, 9, 13, 1, 2, 9, 14, 1, 1, 9, 15, 2, 7, 3, 0, 2, 6, 3, 1, 2, 5, 3, 2, 2, 4, 3, 3, 2, 3, 3, 4, 2, 5, 4, 5, 2, 4, 4, 6, 2, 3, 4, 7, 2, 2, 4, 8, 2, 3, 5, 9, 2, 2, 5, 10, 2, 3, 6, 11, 2, 2, 6, 12, 2, 1, 6, 13, 2, 0, 6, 14, 3, 5, 4, 0, 3, 7, 3, 1, 3, 6, 3, 2, 3, 5, 3, 3, 3, 4, 4, 4, 3, 3, 4, 5, 3, 4, 3, 6, 3, 3, 3, 7, 3, 2, 4, 8, 3, 3, 5, 9, 3, 2, 5, 10, 3, 1, 6, 11, 3, 1, 5, 12, 3, 0, 6, 13, 4, 3, 5, 0, 4, 7, 3, 1, 4, 5, 4, 2, 4, 4, 4, 3, 4, 6, 3, 4, 4, 5, 3, 5, 4, 4, 3, 6, 4, 3, 4, 7, 4, 3, 3, 8, 4, 2, 4, 9, 4, 2, 5, 10, 4, 1, 5, 11, 4, 0, 5, 12, 5, 5, 4, 0, 5, 4, 4, 1, 5, 3, 4, 2, 5, 7, 3, 3, 5, 6, 3, 4, 5, 5, 3, 5, 5, 4, 3, 6, 5, 3, 3, 7, 5, 2, 4, 8, 5, 1, 5, 9, 5, 1, 4, 10, 5, 0, 5, 11, 6, 1, 6, 0, 6, 1, 5, 1, 6, 7, 3, 2, 6, 6, 3, 3, 6, 5, 3, 4, 6, 4, 3, 5, 6, 3, 3, 6, 6, 2, 3, 7, 6, 1, 4, 8, 6, 1, 3, 9, 6, 0, 6, 10, 7, 1, 6, 0, 7, 1, 5, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 3, 2, 5, 7, 2, 3, 6, 7, 1, 4, 7, 7, 1, 3, 8, 7, 0, 6, 9, 8, 1, 6, 0, 8, 1, 4, 1, 8, 1, 5, 2, 8, 3, 3, 3, 8, 3, 2, 4, 8, 2, 2, 5, 8, 2, 3, 6, 8, 1, 3, 7, 8, 0, 6, 8, 9, 1, 6, 0, 9, 0, 6, 1, 9, 1, 4, 2, 9, 3, 2, 3, 9, 2, 2, 4, 9, 1, 3, 5, 9, 1, 2, 6, 9, 1, 5, 7, 10, 1, 5, 0, 10, 0, 5, 1, 10, 1, 3, 2, 10, 3, 2, 3, 10, 2, 2, 4, 10, 1, 2, 5, 10, 1, 4, 6, 11, 0, 4, 0, 11, 1, 4, 1, 11, 1, 3, 2, 11, 2, 3, 3, 11, 1, 1, 4, 11, 3, 3, 5, 12, 0, 4, 0, 12, 1, 4, 1, 12, 1, 2, 2, 12, 1, 1, 3, 12, 1, 3, 4, 13, 0, 3, 0, 13, 1, 3, 1, 13, 1, 1, 2, 13, 1, 2, 3, 14, 0, 2, 0, 14, 1, 2, 1, 14, 1, 1, 2, 15, 0, 1, 0, 15, 1, 1, 1 } +T.TOTAL_ZEROS_CDC = { 1, 1, 1, 0, 1, 1, 2, 1, 1, 1, 3, 2, 1, 0, 3, 3, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 1, 1, 0, 3, 0, 1, 1 } +T.RUN_BEFORE = { 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 0, 2, 1, 2, 1, 2, 0, 2, 2, 3, 3, 2, 0, 3, 2, 2, 1, 3, 1, 2, 2, 3, 0, 2, 3, 4, 3, 2, 0, 4, 2, 2, 1, 4, 1, 2, 2, 4, 1, 3, 3, 4, 0, 3, 4, 5, 3, 2, 0, 5, 2, 2, 1, 5, 3, 3, 2, 5, 2, 3, 3, 5, 1, 3, 4, 5, 0, 3, 5, 6, 3, 2, 0, 6, 0, 3, 1, 6, 1, 3, 2, 6, 3, 3, 3, 6, 2, 3, 4, 6, 5, 3, 5, 6, 4, 3, 6, 7, 7, 3, 0, 7, 6, 3, 1, 7, 5, 3, 2, 7, 4, 3, 3, 7, 3, 3, 4, 7, 2, 3, 5, 7, 1, 3, 6, 7, 1, 4, 7, 7, 1, 5, 8, 7, 1, 6, 9, 7, 1, 7, 10, 7, 1, 8, 11, 7, 1, 9, 12, 7, 1, 10, 13, 7, 1, 11, 14 } +T.CABAC_INIT = { 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, 20, -15, 20, -15, 20, -15, 20, -15, 2, 54, 2, 54, 2, 54, 2, 54, 3, 74, 3, 74, 3, 74, 3, 74, -28, 127, -28, 127, -28, 127, -28, 127, -23, 104, -23, 104, -23, 104, -23, 104, -6, 53, -6, 53, -6, 53, -6, 53, -1, 54, -1, 54, -1, 54, -1, 54, 7, 51, 7, 51, 7, 51, 7, 51, 0, 0, 23, 33, 22, 25, 29, 16, 0, 0, 23, 2, 34, 0, 25, 0, 0, 0, 21, 0, 16, 0, 14, 0, 0, 0, 1, 9, -2, 9, -10, 51, 0, 0, 0, 49, 4, 41, -3, 62, 0, 0, -37, 118, -29, 118, -27, 99, 0, 0, 5, 57, 2, 65, 26, 16, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, 12, 49, 9, 50, 6, 57, 0, 0, -4, 73, -3, 70, -17, 73, 0, 0, 17, 50, 10, 54, 14, 57, 0, 0, 18, 64, 26, 34, 20, 40, 0, 0, 9, 43, 19, 22, 20, 10, 0, 0, 29, 0, 40, 0, 29, 0, 0, 0, 26, 67, 57, 2, 54, 0, 0, 0, 16, 90, 41, 36, 37, 42, 0, 0, 9, 104, 26, 69, 12, 97, 0, 0, -46, 127, -45, 127, -32, 127, 0, 0, -20, 104, -15, 101, -22, 117, 0, 0, 1, 67, -4, 76, -2, 74, 0, 0, -13, 78, -6, 71, -4, 85, 0, 0, -11, 65, -13, 79, -24, 102, 0, 0, 1, 62, 5, 52, 5, 57, 0, 0, -6, 86, 6, 69, -6, 93, 0, 0, -17, 95, -13, 90, -14, 88, 0, 0, -6, 61, 0, 52, -6, 44, 0, 0, 9, 45, 8, 43, 4, 55, 0, 0, -3, 69, -2, 69, -11, 89, 0, 0, -6, 81, -5, 82, -15, 103, 0, 0, -11, 96, -10, 96, -21, 116, 0, 0, 6, 55, 2, 59, 19, 57, 0, 0, 7, 67, 2, 75, 20, 58, 0, 0, -5, 86, -3, 87, 4, 84, 0, 0, 2, 88, -3, 100, 6, 96, 0, 0, 0, 58, 1, 56, 1, 63, 0, 0, -3, 76, -3, 74, -5, 85, 0, 0, -10, 94, -6, 85, -13, 106, 0, 0, 5, 54, 0, 59, 5, 63, 0, 0, 4, 69, -3, 81, 6, 75, 0, 0, -3, 81, -7, 86, -3, 90, 0, 0, 0, 88, -5, 95, -1, 101, 0, 0, -7, 67, -1, 66, 3, 55, 0, 0, -5, 74, -1, 77, -4, 79, 0, 0, -4, 74, 1, 70, -2, 75, 0, 0, -5, 80, -2, 86, -12, 97, 0, 0, -7, 72, -5, 72, -7, 50, 0, 0, 1, 58, 0, 61, 1, 60, 0, 41, 0, 41, 0, 41, 0, 41, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, -9, 83, -9, 83, -9, 83, -9, 83, 4, 86, 4, 86, 4, 86, 4, 86, 0, 97, 0, 97, 0, 97, 0, 97, -7, 72, -7, 72, -7, 72, -7, 72, 13, 41, 13, 41, 13, 41, 13, 41, 3, 62, 3, 62, 3, 62, 3, 62, 0, 11, 0, 45, 13, 15, 7, 34, 1, 55, -4, 78, 7, 51, -9, 88, 0, 69, -3, 96, 2, 80, -20, 127, -17, 127, -27, 126, -39, 127, -36, 127, -13, 102, -28, 98, -18, 91, -17, 91, 0, 82, -25, 101, -17, 96, -14, 95, -7, 74, -23, 67, -26, 81, -25, 84, -21, 107, -28, 82, -35, 98, -25, 86, -27, 127, -20, 94, -24, 102, -12, 89, -31, 127, -16, 83, -23, 97, -17, 91, -24, 127, -22, 110, -27, 119, -31, 127, -18, 95, -21, 91, -24, 99, -14, 76, -27, 127, -18, 102, -21, 110, -18, 103, -21, 114, -13, 93, -18, 102, -13, 90, -30, 127, -29, 127, -36, 127, -37, 127, -17, 123, -7, 92, 0, 80, 11, 80, -12, 115, -5, 89, -5, 89, 5, 76, -16, 122, -7, 96, -7, 94, 2, 84, -11, 115, -13, 108, -4, 92, 5, 78, -12, 63, -3, 46, 0, 39, -6, 55, -2, 68, -1, 65, 0, 65, 4, 61, -15, 84, -1, 57, -15, 84, -14, 83, -13, 104, -9, 93, -35, 127, -37, 127, -3, 70, -3, 74, -2, 73, -5, 79, -8, 93, -9, 92, -12, 104, -11, 104, -10, 90, -8, 87, -9, 91, -11, 91, -30, 127, -23, 126, -31, 127, -30, 127, -1, 74, 5, 54, 3, 55, 0, 65, -6, 97, 6, 60, 7, 56, -2, 79, -7, 91, 6, 59, 7, 55, 0, 72, -20, 127, 6, 69, 8, 61, -4, 92, -4, 56, -1, 48, -3, 53, -6, 56, -5, 82, 0, 68, 0, 68, 3, 68, -7, 76, -4, 69, -7, 74, -8, 71, -22, 125, -8, 88, -9, 88, -13, 98, -7, 93, -2, 85, -13, 103, -4, 86, -11, 87, -6, 78, -13, 91, -12, 88, -3, 77, -1, 75, -9, 89, -5, 82, -5, 71, -7, 77, -14, 92, -3, 72, -4, 63, 2, 54, -8, 76, -4, 67, -4, 68, 5, 50, -12, 87, -8, 72, -12, 84, -3, 68, -23, 110, -16, 89, -7, 62, 1, 50, -24, 105, -9, 69, -7, 65, 6, 42, -10, 78, -1, 59, 8, 61, -4, 81, -20, 112, 5, 66, 5, 56, 1, 63, -17, 99, 4, 57, -2, 66, -4, 70, -78, 127, -4, 71, 1, 64, 0, 67, -70, 127, -2, 71, 0, 61, 2, 57, -50, 127, 2, 58, -2, 78, -2, 76, -46, 127, -1, 74, 1, 50, 11, 35, -4, 66, -4, 44, 7, 52, 4, 64, -5, 78, -1, 69, 10, 35, 1, 61, -4, 71, 0, 62, 0, 44, 11, 35, -8, 72, -7, 51, 11, 38, 18, 25, 2, 59, -4, 47, 1, 45, 12, 24, -1, 55, -6, 42, 0, 46, 13, 29, -7, 70, -3, 41, 5, 44, 13, 36, -6, 75, -6, 53, 31, 17, -10, 93, -8, 89, 8, 76, 1, 51, -7, 73, -34, 119, -9, 78, 7, 50, -2, 73, -3, 75, -11, 83, 28, 19, 13, 46, 32, 20, 9, 52, 16, 33, 9, 49, 30, 22, 0, 67, 14, 62, -7, 100, -44, 127, -5, 90, -13, 108, 9, 53, 0, 54, 1, 67, -15, 100, 2, 53, -5, 61, -15, 72, -13, 101, 5, 53, 0, 58, -5, 75, -13, 91, -2, 61, -1, 60, -8, 80, -12, 94, 0, 56, -3, 61, -21, 83, -10, 88, 0, 56, -8, 67, -21, 64, -16, 84, -13, 63, -25, 84, -13, 31, -10, 86, -5, 60, -14, 74, -25, 64, -7, 83, -1, 62, -5, 65, -29, 94, -13, 87, 4, 57, 5, 52, 9, 75, -19, 94, -6, 69, 2, 57, 17, 63, 1, 70, 4, 57, 0, 61, -8, 74, 0, 72, 14, 39, -9, 69, -5, 35, -5, 74, 4, 51, -11, 70, -2, 27, 18, 59, 13, 68, 18, 55, 13, 91, -8, 102, 3, 64, -4, 71, 3, 65, -15, 100, 1, 61, 0, 58, -7, 69, 0, 95, 9, 63, 7, 61, 8, 77, -4, 75, 7, 50, 9, 41, -10, 66, 2, 72, 16, 39, 18, 25, 3, 62, -11, 75, 5, 44, 9, 32, -3, 68, -3, 71, 4, 52, 5, 43, -20, 81, 15, 46, 11, 48, 9, 47, 0, 30, -13, 69, -5, 60, 0, 44, 1, 7, 0, 62, -1, 59, 0, 51, -3, 23, 0, 65, 0, 59, 2, 46, -21, 74, 21, 37, 22, 33, 19, 38, 16, 66, -15, 72, 5, 44, -4, 66, -23, 124, 9, 57, 14, 43, 15, 38, 17, 37, 16, 54, -1, 78, 12, 42, 44, -18, 0, 62, 0, 60, 9, 34, 50, -34, 12, 72, 9, 69, 0, 89, -22, 127, 24, 0, 11, 28, 4, 45, 4, 39, 15, 9, 2, 40, 10, 28, 0, 42, 8, 25, 3, 44, 10, 31, 7, 34, 13, 18, 0, 49, 33, -11, 11, 29, 15, 9, 0, 46, 52, -43, 8, 31, 13, 19, 2, 44, 18, 15, 6, 37, 10, 37, 2, 51, 28, 0, 7, 42, 12, 18, 0, 47, 35, -22, 3, 40, 6, 29, 4, 39, 38, -25, 8, 33, 20, 33, 2, 62, 34, 0, 13, 43, 15, 30, 6, 46, 39, -18, 13, 36, 4, 45, 0, 54, 32, -12, 4, 47, 1, 58, 3, 54, 102, -94, 3, 55, 0, 62, 2, 58, 0, 0, 2, 58, 7, 61, 4, 63, 56, -15, 6, 60, 12, 38, 6, 51, 33, -4, 8, 44, 11, 45, 6, 57, 29, 10, 11, 44, 15, 39, 7, 53, 37, -5, 14, 42, 11, 42, 6, 52, 51, -29, 7, 48, 13, 44, 6, 55, 39, -9, 4, 56, 16, 45, 11, 45, 52, -34, 4, 52, 12, 41, 14, 36, 69, -58, 13, 37, 10, 49, 8, 53, 67, -63, 9, 49, 30, 34, -1, 82, 44, -5, 19, 58, 18, 42, 7, 55, 32, 7, 10, 48, 10, 55, -3, 78, 55, -29, 12, 45, 17, 51, 15, 46, 32, 1, 0, 69, 17, 46, 22, 31, 0, 0, 20, 33, 0, 89, -1, 84, 27, 36, 8, 63, 26, -19, 25, 7, 33, -25, 35, -18, 22, -17, 30, -7, 34, -30, 33, -25, 26, -17, 28, 3, 36, -28, 28, -3, 30, -25, 28, 4, 38, -28, 24, 10, 28, -20, 32, 0, 38, -27, 27, 0, 33, -23, 34, -1, 34, -18, 34, -14, 37, -27, 30, 6, 35, -16, 52, -44, 33, -23, 30, 6, 34, -14, 39, -24, 40, -28, 32, 9, 32, -8, 19, 17, 38, -17, 31, 19, 37, -6, 31, 25, 33, -11, 26, 27, 35, 0, 36, 29, 40, -15, 26, 30, 30, 10, 24, 33, 41, -6, 37, 20, 28, 18, 34, 15, 38, 1, 28, 34, 26, 25, 30, 20, 41, 17, 17, 70, 29, 41, 22, 73, 30, -6, 1, 67, 0, 75, 20, 34, 27, 3, 5, 59, 2, 72, 19, 31, 26, 22, 9, 67, 8, 77, 27, 44, 37, -16, 16, 30, 14, 35, 19, 16, 35, -4, 18, 32, 18, 31, 15, 36, 38, -8, 18, 35, 17, 35, 15, 36, 38, -3, 22, 29, 21, 30, 21, 28, 37, 3, 24, 31, 17, 45, 25, 21, 38, 5, 23, 38, 20, 42, 30, 20, 42, 0, 18, 43, 18, 45, 31, 12, 35, 16, 20, 41, 27, 26, 27, 16, 39, 22, 11, 63, 16, 54, 24, 42, 14, 48, 9, 59, 7, 66, 0, 93, 27, 37, 9, 64, 16, 56, 14, 56, 21, 60, -1, 94, 11, 73, 15, 57, 12, 68, -2, 89, 10, 67, 26, 38, 2, 97, -9, 108, -10, 116, -24, 127, -3, 71, -6, 76, -23, 112, -24, 115, -6, 42, -2, 44, -15, 71, -22, 82, -5, 50, 0, 45, -7, 61, -9, 62, -3, 54, 0, 52, 0, 53, 0, 53, -2, 62, -3, 64, -5, 66, 0, 59, 0, 58, -2, 59, -11, 77, -14, 85, 1, 63, -4, 70, -9, 80, -13, 89, -2, 72, -4, 75, -9, 84, -13, 94, -1, 74, -8, 82, -10, 87, -11, 92, -9, 91, -17, 102, -34, 127, -29, 127, -5, 67, -9, 77, -21, 101, -21, 100, -5, 27, 3, 24, -3, 39, -14, 57, -3, 39, 0, 42, -5, 53, -12, 67, -2, 44, 0, 48, -7, 61, -11, 71, 0, 46, 0, 55, -11, 75, -10, 77, -16, 64, -6, 59, -15, 77, -21, 85, -8, 68, -7, 71, -17, 91, -16, 88, -10, 78, -12, 83, -25, 107, -23, 104, -6, 77, -11, 87, -25, 111, -15, 98, -10, 86, -30, 119, -28, 122, -37, 127, -12, 92, 1, 58, -11, 76, -10, 82, -15, 55, -3, 29, -10, 44, -8, 48, -10, 60, -1, 36, -10, 52, -8, 61, -6, 62, 1, 38, -10, 57, -8, 66, -4, 65, 2, 43, -9, 58, -7, 70, -12, 73, -6, 55, -16, 72, -14, 75, -8, 76, 0, 58, -7, 69, -10, 79, -7, 80, 0, 64, -4, 69, -9, 83, -9, 88, -3, 74, -5, 74, -12, 92, -17, 110, -10, 90, -9, 86, -18, 108, -11, 97, 0, 70, 2, 66, -4, 79, -20, 84, -4, 29, -9, 34, -22, 69, -11, 79, 5, 31, 1, 32, -16, 75, -6, 73, 7, 42, 11, 31, -2, 58, -4, 74, 1, 59, 5, 52, 1, 58, -13, 86, -2, 58, -2, 55, -13, 78, -13, 96, -3, 72, -2, 67, -9, 83, -11, 97, -3, 81, 0, 73, -4, 81, -19, 117, -11, 97, -8, 89, -13, 99, -8, 78, 0, 58, 3, 52, -13, 81, -5, 33, 8, 5, 7, 4, -6, 38, -4, 48, 10, 14, 10, 8, -13, 62, -2, 53, 14, 18, 17, 8, -6, 58, -3, 62, 13, 27, 16, 19, -2, 59, -13, 71, 2, 40, 3, 37, -16, 73, -10, 79, 0, 58, -1, 61, -10, 76, -12, 86, -3, 70, -5, 73, -13, 86, -13, 90, -6, 79, -1, 70, -9, 83, -14, 97, -8, 85, -4, 78, -10, 87, 0, 0, 0, 0, 0, 0, 0, 0, -6, 93, -13, 106, -21, 126, -22, 127, -6, 84, -16, 106, -23, 124, -25, 127, -8, 79, -10, 87, -20, 110, -25, 120, 0, 66, -21, 114, -26, 126, -27, 127, -1, 71, -18, 110, -25, 124, -19, 114, 0, 62, -14, 98, -17, 105, -23, 117, -2, 60, -22, 110, -27, 121, -25, 118, -2, 59, -21, 106, -27, 117, -26, 117, -5, 75, -18, 103, -17, 102, -24, 113, -3, 62, -21, 107, -26, 117, -28, 118, -4, 58, -23, 108, -27, 116, -31, 120, -9, 66, -26, 112, -33, 122, -37, 124, -1, 79, -10, 96, -10, 95, -10, 94, 0, 71, -12, 95, -14, 100, -15, 102, 3, 68, -5, 91, -8, 95, -10, 99, 10, 44, -9, 93, -17, 111, -13, 106, -7, 62, -22, 94, -28, 114, -50, 127, 15, 36, -5, 86, -6, 89, -5, 92, 14, 40, 9, 67, -2, 80, 17, 57, 16, 27, -4, 80, -4, 82, -5, 86, 12, 29, -10, 85, -9, 85, -13, 94, 1, 44, -1, 70, -8, 81, -12, 91, 20, 36, 7, 60, -1, 72, -2, 77, 18, 32, 9, 58, 5, 64, 0, 71, 5, 42, 5, 61, 1, 67, -1, 73, 1, 48, 12, 50, 9, 56, 4, 64, 10, 62, 15, 50, 0, 69, -7, 81, 17, 46, 18, 49, 1, 69, 5, 64, 9, 64, 17, 54, 7, 69, 15, 57, -12, 104, 10, 41, -7, 69, 1, 67, -11, 97, 7, 46, -6, 67, 0, 68, -16, 96, -1, 51, -16, 77, -10, 67, -7, 88, 7, 49, -2, 64, 1, 68, -8, 85, 8, 52, 2, 61, 0, 77, -7, 85, 9, 41, -6, 67, 2, 64, -9, 85, 6, 47, -3, 64, 0, 68, -13, 88, 2, 55, 2, 57, -5, 78, 4, 66, 13, 41, -3, 65, 7, 55, -3, 77, 10, 44, -3, 66, 5, 59, -3, 76, 6, 50, 0, 62, 2, 65, -6, 76, 5, 53, 9, 51, 14, 54, 10, 58, 13, 49, -1, 66, 15, 44, -1, 76, 4, 63, -2, 71, 5, 60, -1, 83, 6, 64, -2, 75, 2, 70, -7, 99, -2, 69, -1, 70, -2, 76, -14, 95, -2, 59, -9, 72, -18, 86, 2, 95, 6, 70, 14, 60, 12, 70, 0, 76, 10, 44, 16, 37, 5, 64, -5, 74, 9, 31, 0, 47, -12, 70, 0, 70, 12, 43, 18, 35, 11, 55, -11, 75, 3, 53, 11, 37, 5, 56, 1, 68, 14, 34, 12, 41, 0, 69, 0, 65, 10, 38, 10, 41, 2, 65, -14, 73, -3, 52, 2, 48, -6, 74, 3, 62, 13, 40, 12, 41, 5, 54, 4, 62, 17, 32, 13, 41, 7, 54, -1, 68, 7, 44, 0, 59, -6, 76, -13, 75, 7, 38, 3, 50, -11, 82, 11, 55, 13, 50, 19, 40, -2, 77, 5, 64, 10, 57, 3, 66, -2, 77, 12, 70, 26, 43, 18, 50, 25, 42, 15, 6, 14, 11, 19, -6, 17, -13, 6, 19, 11, 14, 18, -6, 16, -9, 7, 16, 9, 11, 14, 0, 17, -12, 12, 14, 18, 11, 26, -12, 27, -21, 18, 13, 21, 9, 31, -16, 37, -30, 13, 11, 23, -2, 33, -25, 41, -40, 13, 15, 32, -15, 33, -22, 42, -41, 15, 16, 32, -15, 37, -28, 48, -47, 12, 23, 34, -21, 39, -30, 39, -32, 13, 23, 39, -23, 42, -30, 46, -40, 15, 20, 42, -33, 47, -42, 52, -51, 14, 26, 41, -31, 45, -36, 46, -41, 14, 44, 46, -28, 49, -34, 52, -39, 17, 40, 38, -12, 41, -17, 43, -19, 17, 47, 21, 29, 32, 9, 32, 11, 24, 17, 45, -24, 69, -71, 61, -55, 21, 21, 53, -45, 63, -63, 56, -46, 25, 22, 48, -26, 66, -64, 62, -50, 31, 27, 65, -43, 77, -74, 81, -67, 22, 29, 43, -19, 54, -39, 45, -20, 19, 35, 39, -10, 52, -35, 35, -2, 14, 50, 30, 9, 41, -10, 28, 15, 10, 57, 18, 26, 36, 0, 34, 1, 7, 63, 20, 27, 40, -1, 39, 1, -2, 77, 0, 57, 30, 14, 30, 17, -4, 82, -14, 82, 28, 26, 20, 38, -3, 94, -5, 75, 23, 37, 18, 45, 9, 69, -19, 97, 12, 55, 15, 54, -12, 109, -35, 125, 11, 65, 0, 79, 36, -35, 27, 0, 37, -33, 36, -16, 36, -34, 28, 0, 39, -36, 37, -14, 32, -26, 31, -4, 40, -37, 37, -17, 37, -30, 27, 6, 38, -30, 32, 1, 44, -32, 34, 8, 46, -33, 34, 15, 34, -18, 30, 10, 42, -30, 29, 15, 34, -15, 24, 22, 40, -24, 24, 25, 40, -15, 33, 19, 49, -29, 34, 22, 33, -7, 22, 32, 38, -12, 31, 16, 35, -5, 26, 31, 40, -10, 35, 18, 33, 0, 21, 41, 38, -3, 31, 28, 38, 2, 26, 44, 46, -5, 33, 41, 33, 13, 23, 47, 31, 20, 36, 28, 23, 35, 16, 65, 29, 30, 27, 47, 13, 58, 14, 71, 25, 44, 21, 62, 29, -3, 8, 60, 12, 48, 18, 31, 26, 0, 6, 63, 11, 49, 19, 26, 22, 30, 17, 65, 26, 45, 36, 24, 31, -7, 21, 24, 22, 22, 24, 23, 35, -15, 23, 20, 23, 22, 27, 16, 34, -3, 26, 23, 27, 21, 24, 30, 34, 3, 27, 32, 33, 20, 31, 29, 36, -1, 28, 23, 26, 28, 22, 41, 34, 5, 28, 24, 30, 24, 22, 42, 32, 11, 23, 40, 27, 34, 16, 60, 35, 5, 24, 32, 18, 42, 15, 52, 34, 12, 28, 29, 25, 39, 14, 60, 39, 11, 23, 42, 18, 50, 3, 78, 30, 29, 19, 57, 12, 70, -16, 123, 34, 26, 22, 53, 21, 54, 21, 53, 29, 39, 22, 61, 14, 71, 22, 56, 19, 66, 11, 86, 11, 83, 25, 61, 31, 21, 12, 40, 25, 32, 21, 33, 31, 31, 11, 51, 21, 49, 19, 50, 25, 50, 14, 59, 21, 54, 17, 61, -17, 120, -4, 79, -5, 85, -3, 78, -20, 112, -7, 71, -6, 81, -8, 74, -18, 114, -5, 69, -10, 77, -9, 72, -11, 85, -9, 70, -7, 81, -10, 72, -15, 92, -8, 66, -17, 80, -18, 75, -14, 89, -10, 68, -18, 73, -12, 71, -26, 71, -19, 73, -4, 74, -11, 63, -15, 81, -12, 69, -10, 83, -5, 70, -14, 80, -16, 70, -9, 71, -17, 75, 0, 68, -15, 67, -9, 67, -14, 72, -14, 70, -20, 62, -1, 61, -16, 67, -24, 56, -19, 70, -8, 66, -8, 53, -23, 68, -16, 66, -14, 66, -14, 59, -24, 50, -22, 65, 0, 59, -9, 52, -11, 74, -20, 63, 2, 59, -11, 68, 23, -13, 9, -2, 17, -10, 9, -2, 26, -13, 26, -9, 32, -13, 30, -10, 40, -15, 33, -9, 42, -9, 31, -4, 49, -14, 39, -7, 49, -5, 33, -1, 44, 3, 41, -2, 53, 0, 33, 7, 45, 6, 45, 3, 64, 3, 31, 12, 44, 34, 49, 9, 68, 10, 37, 23, 33, 54, 45, 27, 66, 27, 31, 38, 19, 82, 36, 59, 47, 57, 20, 64, -3, 75, -6, 66, -5, 71, -9, 71, -1, 23, -7, 35, 0, 24, -7, 37, 1, 34, -7, 42, -1, 36, -8, 44, 1, 43, -8, 45, -2, 42, -11, 49, 0, 54, -5, 48, -2, 52, -10, 56, -2, 55, -12, 56, -9, 57, -12, 59, 0, 61, -6, 60, -6, 63, -8, 63, 1, 64, -5, 62, -4, 65, -9, 67, 0, 68, -8, 66, -4, 67, -6, 68, -9, 92, -8, 76, -7, 82, -10, 79, -14, 106, -5, 85, -3, 81, -3, 78, -13, 97, -6, 81, -3, 76, -8, 74, -15, 90, -10, 77, -7, 72, -9, 72, -12, 90, -7, 81, -6, 78, -10, 72, -18, 88, -17, 80, -12, 72, -18, 75, -10, 73, -18, 73, -14, 68, -12, 71, -9, 79, -4, 74, -3, 70, -11, 63, -14, 86, -10, 83, -6, 76, -5, 70, -10, 73, -9, 71, -5, 66, -17, 75, -10, 70, -9, 67, -5, 62, -14, 72, -10, 69, -1, 61, 0, 57, -16, 67, -5, 66, -8, 66, -4, 61, -8, 53, -9, 64, -14, 66, -9, 60, -14, 59, -5, 58, 0, 59, 1, 54, -9, 52, 2, 59, 2, 59, 2, 58, -11, 68, 21, -10, 21, -13, 17, -10, 9, -2, 24, -11, 33, -14, 32, -13, 30, -10, 28, -8, 39, -7, 42, -9, 31, -4, 28, -1, 46, -2, 49, -5, 33, -1, 29, 3, 51, 2, 53, 0, 33, 7, 29, 9, 60, 6, 64, 3, 31, 12, 35, 20, 61, 17, 68, 10, 37, 23, 29, 36, 55, 34, 66, 27, 31, 38, 14, 67, 42, 62, 47, 57, 20, 64 } +T.RANGE_LPS = { 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150, 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, 66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69, 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, 30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31, 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19, 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, 8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2 } +T.TRANS = { 0, 1, 0, 2, 1, 3, 2, 4, 2, 5, 4, 6, 4, 7, 5, 8, 6, 9, 7, 10, 8, 11, 9, 12, 9, 13, 11, 14, 11, 15, 12, 16, 13, 17, 13, 18, 15, 19, 15, 20, 16, 21, 16, 22, 18, 23, 18, 24, 19, 25, 19, 26, 21, 27, 21, 28, 22, 29, 22, 30, 23, 31, 24, 32, 24, 33, 25, 34, 26, 35, 26, 36, 27, 37, 27, 38, 28, 39, 29, 40, 29, 41, 30, 42, 30, 43, 30, 44, 31, 45, 32, 46, 32, 47, 33, 48, 33, 49, 33, 50, 34, 51, 34, 52, 35, 53, 35, 54, 35, 55, 36, 56, 36, 57, 36, 58, 37, 59, 37, 60, 37, 61, 38, 62, 38, 62, 63, 63 } +T.CHROMA_QP = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39 } +T.INTRA_CBP = { 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41 } +T.INTER_CBP = { 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41 } +T.DEFAULT_4x4 = { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42, 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 } +T.DEFAULT_8x8 = { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42, 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 } +T.ZIGZAG4 = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 } +T.ZIGZAG8 = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 } +T.SIG8 = { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14 } +T.LAST8 = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8 } +T.ALPHA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } +T.BETA = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 } +T.TC0 = { -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 2, 3, -1, 1, 2, 3, -1, 2, 2, 3, -1, 2, 2, 4, -1, 2, 3, 4, -1, 2, 3, 4, -1, 3, 3, 5, -1, 3, 4, 6, -1, 3, 4, 6, -1, 4, 5, 7, -1, 4, 5, 8, -1, 4, 6, 9, -1, 5, 7, 10, -1, 6, 8, 11, -1, 6, 8, 13, -1, 7, 10, 14, -1, 8, 11, 16, -1, 9, 12, 18, -1, 10, 13, 20, -1, 11, 15, 23, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25, -1, 13, 17, 25 } + +return T +end +__FILES["codecs/video/H264/Transform"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual +-- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard +-- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already +-- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. +-- Never throws. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Transform = {} + +local min, max = math.min, math.max +local function clip(v) +return min(max(v, 0), 255) +end + +-- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s) +function Transform.add4(c, base, b, o, s) + -- rows + for i = 0, 3 do + local k = base + i * 4 + local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] + local e = d0 + d2 + local f = d0 - d2 + local g = math.floor(d1 / 2 )- d3 + local h = d1 + math.floor(d3 / 2 +) c[k + 1] = e + h + c[k + 2] = f + g + c[k + 3] = f - g + c[k + 4] = e - h + end + -- columns + for j = 0, 3 do + local k = base + j + local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] + local e = d0 + d2 + local f = d0 - d2 + local g = math.floor(d1 / 2 )- d3 + local h = d1 + math.floor(d3 / 2 +) c[k + 1], c[k + 5], c[k + 9], c[k + 13] = 0, 0, 0, 0 + local p = o + j + writeu8(b, p, clip(readu8(b, p) + math.floor((e + h + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((f + g + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((f - g + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((e - h + 32) / 64))) + end +end + +-- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC +function Transform.addDc4(dc, b, o, s) + local v = math.floor((dc + 32) / 64 +) if v == 0 then + return + end + for y = 0, 3 do + local p = o + y * s + writeu8(b, p, clip(readu8(b, p) + v)) + writeu8(b, p + 1, clip(readu8(b, p + 1) + v)) + writeu8(b, p + 2, clip(readu8(b, p + 2) + v)) + writeu8(b, p + 3, clip(readu8(b, p + 3) + v)) + end +end + +local T8 = table.create(64, 0) + +-- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o] +function Transform.add8(c, base, b, o, s) + for pass = 0, 1 do + for i = 0, 7 do + -- pass 0: rows of c into T8; pass 1: columns of T8 + local d0, d1, d2, d3, d4, d5, d6, d7 + if pass == 0 then + local k = base + i * 8 + d0, d1, d2, d3, d4, d5, d6, d7 = c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] + c[k + 1], c[k + 2], c[k + 3], c[k + 4], c[k + 5], c[k + 6], c[k + 7], c[k + 8] = 0, 0, 0, 0, 0, 0, 0, 0 + else + d0, d1, d2, d3, d4, d5, d6, d7 = T8[i + 1], T8[i + 9], T8[i + 17], T8[i + 25], T8[i + 33], T8[i + 41], T8[i + 49], T8[i + 57] + end + local a0 = d0 + d4 + local a4 = d0 - d4 + local a2 = math.floor(d2 / 2 )- d6 + local a6 = d2 + math.floor(d6 / 2 +) local b0 = a0 + a6 + local b2 = a4 + a2 + local b4 = a4 - a2 + local b6 = a0 - a6 + local a1 = -d3 + d5 - d7 - math.floor(d7 / 2 +) local a3 = d1 + d7 - d3 - math.floor(d3 / 2 +) local a5 = -d1 + d7 + d5 + math.floor(d5 / 2 +) local a7 = d3 + d5 + d1 + math.floor(d1 / 2 +) local b1 = a1 + math.floor(a7 / 4 +) local b7 = a7 - math.floor(a1 / 4 +) local b3 = a3 + math.floor(a5 / 4 +) local b5 = math.floor(a3 / 4 )- a5 + if pass == 0 then + local k = i * 8 + T8[k + 1] = b0 + b7 + T8[k + 2] = b2 + b5 + T8[k + 3] = b4 + b3 + T8[k + 4] = b6 + b1 + T8[k + 5] = b6 - b1 + T8[k + 6] = b4 - b3 + T8[k + 7] = b2 - b5 + T8[k + 8] = b0 - b7 + else + local p = o + i + writeu8(b, p, clip(readu8(b, p) + math.floor((b0 + b7 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b2 + b5 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b4 + b3 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b6 + b1 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b6 - b1 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b4 - b3 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b2 - b5 + 32) / 64))) + p =p+ s + writeu8(b, p, clip(readu8(b, p) + math.floor((b0 - b7 + 32) / 64))) + end + end + end +end + +-- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the +-- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index) +function Transform.lumaDc(dc, m, c) + for i = 0, 3 do + local k = i * 4 + local d0, d1, d2, d3 = dc[k + 1], dc[k + 2], dc[k + 3], dc[k + 4] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[k + 1] = e + g + dc[k + 2] = e - g + dc[k + 3] = f - h + dc[k + 4] = f + h + end + for j = 0, 3 do + local d0, d1, d2, d3 = dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] + local e = d0 + d1 + local f = d0 - d1 + local g = d2 + d3 + local h = d2 - d3 + dc[j + 1], dc[j + 5], dc[j + 9], dc[j + 13] = 0, 0, 0, 0 + c[j * 16 + 1] = math.floor(((e + g) * m + 32) / 64 +) c[(4 + j) * 16 + 1] = math.floor(((e - g) * m + 32) / 64 +) c[(8 + j) * 16 + 1] = math.floor(((f - h) * m + 32) / 64 +) c[(12 + j) * 16 + 1] = math.floor(((f + h) * m + 32) / 64 +) end +end + +-- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1] +function Transform.chromaDc(dc, base, m, c, cbase) + local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] + dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 + local e = c0 + c1 + local f = c0 - c1 + local g = c2 + c3 + local h = c2 - c3 + c[cbase + 1] = math.floor(((e + g) * m) / 32 +) c[cbase + 17] = math.floor(((f + h) * m) / 32 +) c[cbase + 33] = math.floor(((e - g) * m) / 32 +) c[cbase + 49] = math.floor(((f - h) * m) / 32 +)end + +return Transform +end +__FILES["codecs/video/Legacy"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. +-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk +-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", +-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker +-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). +-- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's +-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns +-- a fresh copy. +-- +-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the +-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that +-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). +-- +-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } +-- +-- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +local Err = __include("core/Err") +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") +local Flic = __include("codecs/video/Legacy/Flic") +local Cinepak = __include("codecs/video/Legacy/Cinepak") +local Msvideo1 = __include("codecs/video/Legacy/Msvideo1") +local QtRle = __include("codecs/video/Legacy/QtRle") +local Smc = __include("codecs/video/Legacy/Smc") +local Smacker = __include("codecs/video/Legacy/Smacker") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } +-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? + + + + + + + + + + + +local function fail(msg) +return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic, packet) +local pal = (packet ).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS= { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = (depth > 32 and((depth - 32 ))or(depth +)) if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width , t.height , QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width , t.height , true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width ) < 4 or (t.height ) < 4 then + return nil, "smaller than one block" + end + local bits = t.bitsPerPixel == 8 and 8 or 16 + return { pic = Picture.new(t.width , t.height , bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width , t.height , pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, (msg and{(fail(msg) )}or{nil +})[1] end + return Picture.image(st.pic), nil + end, + }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width , t.height , true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width , t.height , t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err +function Legacy.newDecoder(id, track, opts) +local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= math.floor(w / 1 )or h ~= math.floor(h / 1 )then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + -- Video.simpleDecoder, without requiring the registry (which requires this module) + local queue= {} + local self = {} + function self.decode(_, packet) +local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_) +local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_) end + function self.reset(_) + table.clear(queue) + st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + end + return self , nil +end + +return Legacy +end +__FILES["codecs/video/Legacy/Cinepak"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 +-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description +-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 +-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame +-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are +-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra +-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak +-- decoder. Never throws: every read is range-checked against its chunk. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + + + + + + +function Cinepak.state() +return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +local function be16(d, o) +return readu8(d, o) * 256 + readu8(d, o + 1) +end +local function be24(d, o) +return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +local function be32(d, o) +return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +local function clip(v) +return v < 0 and 0 or(v > 255 and 255 or v +)end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +local function codebook(books, book, id, d, p, stop) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = six and 6 or 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask =math.floor(mask/ 2 +) if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p =p+ 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u =u- 256 + end + if v >= 128 then + v =v- 256 + end + local uh = (u < 0 and{(-(math.floor((-u) / 2)) )}or{(math.floor(u / 2 -- C division (towards zero) +))})[1] local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p =p+ size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +local function vectors(pic, books, v4, v1, id, d, p, + stop, x1, y1, x2, y2) +local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) +local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask =math.floor(mask/ 2 +) if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p =p+ 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask =math.floor(mask/ 2 +) if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p =p+ 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p =p+ 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = (r < 2 and{a }or{c})[1], (r < 2 and{b }or{e4 +})[1] writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p =p+ 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = (r < 2 and{e0 }or{e2})[1], (r < 2 and{e1 }or{e3 +})[1] local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = (r < 2 and{e0 }or{e2})[1], (r < 2 and{e1 }or{e3 +})[1] local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this +-- packet (an empty frame); false + message = an error +function Cinepak.decode(pic, d, st, newPalette) +local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < math.floor(size * 5 / 100 )then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + -- the coded area: the size rounded up to whole blocks (the picture's plane) + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p =p+ 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- the strip's chunks: codebooks, then one vector chunk + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q =q+ 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak +end +__FILES["codecs/video/Legacy/Flic"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is +-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's +-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit +-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK +-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX +-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); +-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet +-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. +-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +local Types = __include("Types") +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} +-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette +-- state(w, h, depth) -> State | nil, message + + + + + + + +function Flic.state(w, h, depth) +local bpp = depth == 8 and 1 or((depth == 15 or depth == 16 )and 2 or(depth == 24 and 3 or 0 +)) if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +local function s8(v) +return (v >= 128 and((v - 256 ))or(v +))end + +-- decode(st, data) -> true | false, message +function Flic.decode(st, d) +local pic = st.pic + local px = pic.idx +local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + local function u8() +local v = (p < n and{(readu8(d, p) )}or{0 +})[1] p =p+ 1 + return v + end + local function u16() +local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize =frameSize- 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p =p+ 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at =at+ u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + math.floor(r / 64), g + math.floor(g / 64), b + math.floor(b / 64 +) end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at =at+ 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do +local __DARKLUA_CONTINUE_4=false repeat if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp =lp- 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y =y+ -lp * stride +__DARKLUA_CONTINUE_4=true break + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y =y+ -lp * stride +__DARKLUA_CONTINUE_4=true break + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) +__DARKLUA_CONTINUE_4=true break + elseif lp >= 0x4000 then +__DARKLUA_CONTINUE_4=true break -- undefined opcode + end + lines =lines- 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q =q+ u8() * bpp + local run = s8(u8()) + if deep then + local cnt = (run < 0 and{(-run )}or{run +})[1] if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), (bpp == 3 and{(u8() )}or{0 +})[1] for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q =q+ bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p =p+ cnt * bpp + q =q+ cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q =q+ 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p =p+ run * 2 + q =q+ run * 2 + end + end + y =y+ stride +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q =q+ u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p =p+ run + q =q+ run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q =q- run + end + end + y =y+ stride + lines =lines- 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = (typ == 25 and{bpp }or{1 +})[1] local y = 0 + for _ = 1, h do + local q = y + p =p+ 1 -- the packet count (unused) + local left = (typ == 25 and{w }or{(w * bpp +)})[1] while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q =q+ run + else + local a, b, c = u8(), u8(), (bpp == 3 and{(u8() )}or{0 +})[1] for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q =q+ bpp + end + end + left =left- run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p =p+ cnt * unit + q =q+ cnt * unit + left =left- cnt + end + end + y =y+ stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = (deep and((row + (w % 2) * bpp ))or(((math.floor((w + 3) / 4)) * 4 +))) local ok = (deep and{(size - 6 <= (math.floor((w + 1) / 2)) * 2 * h * bpp )}or{(size - 6 == padded * h +)})[1] if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p =p+ padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize =frameSize- size + chunks =chunks- 1 + end + return true, nil +end + +-- image(st) -> a fresh rgba8 Image +function Flic.image(st) +local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx +local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = (st.depth == 15 and{(Picture.rgb555() )}or{(Picture.rgb565() +)})[1] local mask = st.depth == 15 and 32768 or 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic +end +__FILES["codecs/video/Legacy/Msvideo1"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit +-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows +-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour +-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour +-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. +-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 +-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +local function quadrant(x, y) +return (y >= 2 and 4 or 0) + (x >= 2 and 2 or 0) +end + +-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) +function Msvideo1.decode(pic, d, bits) +local n = buffer.len(d) + local bw, bh = math.floor(pic.w / 4), math.floor(pic.h / 4 +) if n < math.floor(bw * bh / 512 )then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = ((wide and{pic.rgba }or{pic.idx})[1]) +local lut = (wide and{(Picture.rgb555() )}or{nil +})[1] local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do +local __DARKLUA_CONTINUE_2=false repeat if skip ~= 0 then + skip =skip- 1 + total =total- 1 +__DARKLUA_CONTINUE_2=true break + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p =p+ 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + -- the block's bottom-left pixel; its rows go up + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p =p+ 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p =p+ 2 + end + end + else + eight = b >= 0x90 + local cnt = eight and 8 or 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p =p+ 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (band(flags, 1) == 1 and 1 or 2) + if eight then + k =k+ quadrant(x, y) + end + flags = math.floor(flags / 2 +) if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = (wide and{(readu32(lut , ((b * 256 + a) % 32768) * 4) )}or{a +})[1] for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total =total- 1 +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + end + return true, nil +end + +return Msvideo1 +end +__FILES["codecs/video/Legacy/Picture"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame +-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, +-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past +-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication +-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) + + + + + + + + + + +function Picture.new(w, h, palettised, padW, padH, palette) +local pw, ph = padW or 1, padH or 1 + local stride = (math.floor((w + pw - 1) / pw)) * pw + local rows = (math.floor((h + ph - 1) / ph)) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p= { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +-- image(p) -> a fresh rgba8 Image of the visible w x h +function Picture.image(p) +local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track +function Picture.setPalette(p, src) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555= nil +local lut565= nil + +-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries +function Picture.rgb555() +local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = math.floor(v / 1024), (math.floor(v / 32)) % 32, v % 32 + r, g, bl = r * 8 + math.floor(r / 4), g * 8 + math.floor(g / 4), bl * 8 + math.floor(bl / 4 +) writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries +function Picture.rgb565() +local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = math.floor(v / 2048), (math.floor(v / 32)) % 64, v % 32 + r, g, bl = r * 8 + math.floor(r / 4), g * 4 + math.floor(g / 16), bl * 8 + math.floor(bl / 4 +) writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +-- copy of a picture's plane (for decoders that read the previous picture while writing the next) +function Picture.clonePlane(p) +local src = (p.idx or p.rgba) +local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture +end +__FILES["codecs/video/Legacy/QtRle"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File +-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per +-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). +-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its +-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames +-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read +-- and write is range-checked (a damaged frame stops where the damage is). +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +local function s8(v) +return (v >= 128 and((v - 256 ))or(v +))end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +local function decode1(px, stride, limit, d, p, n, row, lines) + row =row- stride + local q = row + lines =lines+ 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p =p+ 2 + if code == 0 then + return + end + if skip >= 128 then + lines =lines- 1 + row =row+ stride + q = row + 16 * (skip - 128) + else + q =q+ 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p =p+ 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q =q+ 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q =q+ 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p =p+ 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q =q+ 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +local function decodeIdx(px, stride, limit, d, p, n, row, lines, bpp) + local group = math.floor(32 / bpp -- pixels per 4 bytes +) local per = math.floor(8 / bpp -- pixels per byte +) local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p =p+ 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p =p+ 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q =q+ group * (readu8(d, p) - 1) + p =p+ 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q =q+ 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q =q+ 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q =q+ group + end + end + p =p+ 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q =q+ bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q =q+ 1 + end + end + end + p =p+ bytes + end + end + row =row+ stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +local function decodeRgb(px, stride, limit, d, p, n, row, lines, depth) + local bpp = math.floor(depth / 8 +) local lut = (depth == 16 and{(Picture.rgb555() )}or{nil +})[1] for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p =p+ 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p =p+ 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q =q+ (readu8(d, p) - 1 +) p =p+ 1 + if q < 0 or q > limit then + return + end + else + local cnt = (code < 0 and{(-code )}or{code +})[1] local need = (code < 0 and{bpp }or{(bpp * cnt +)})[1] if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q =q+ 1 + if code > 0 then + p =p+ bpp + end + end + if code < 0 then + p =p+ bpp + end + end + end + row =row+ stride + end +end + +-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message +function QtRle.decode(pic, d, depth) +local n = buffer.len(d) + if n < 8 then + return true, nil -- no change + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p =p+ 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p =p+ 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = (depth > 32 and((depth - 32 ))or(depth +)) local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs +function QtRle.palettised(depth) +return depth <= 8 or depth > 32 +end +function QtRle.pad(depth) +local bits = (depth > 32 and((depth - 32 ))or(depth +)) return (bits <= 8 and{(math.floor(32 / math.max(1, bits) ))}or{1 +})[1]end + +return QtRle +end +__FILES["codecs/video/Legacy/Smacker"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads +-- 10 bits at a time through a lookup table into them. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 +-- a bit position over buf[0, nbits / 8) + + + +function Smacker.bits(buf, offset, length) +return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +local function bit(br) +local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +function Smacker.read(br, n) +local v, m = 0, 1 + for _ = 1, n do + v =v+ bit(br) * m + m =m* 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +local function walk(tree, br) +local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i =i+ (-e - 1 +) end + i =i+ 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +local function build(br, maxDepth, maxEntries, leaf, bigChecks) +local vals= {} + local n = 0 + local stack= {} + local state= {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n =n+ 1 + vals[n] = -1 + sp =sp+ 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n =n+ 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp =sp- 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +function Smacker.tree8(br) +local leaves = 0 + return build(br, MAX_DEPTH8, 511, function(_) +if leaves >= 256 then + return nil, "tree too big" + end + leaves =leaves+ 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) + + +local function bigTree(br, size) +if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi= {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, math.floor((size + 3) / 4), function(index) +local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits + + +function Smacker.trees(config) +local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out= {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present =present+ 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +local function lut(vals) +local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i =i+ (-e - 1 +) end + i =i+ 1 + len =len+ 1 + e = vals[i] + end + writeu32(t, pat * 4, i * 32 + len) + end + return t +end + +local function reset(t) + local vals, last = t.vals, t.last + vals[last[1] ], vals[last[2] ], vals[last[3] ] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +function Smacker.decode(pic, d, trees, v4) +local px = pic.idx +local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + for _, t in __iter({ mmap, mclr, full, typ }) do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree + local function code(t) +local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut , v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i =i+ (-e - 1 +) end + p =p+ 1 + i =i+ 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3] ] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + local function bit() +local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end + local bw, bh = math.floor(pic.w / 4), math.floor(pic.h / 4 +) local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ) + if ty < 0 then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (math.floor(blk / bw)) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk =blk+ 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (math.floor(blk / bw)) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, (band(map, 1) ~= 0 and{hi }or{lo})[1]) + writeu8(px, q + 1, (band(map, 2) ~= 0 and{hi }or{lo})[1]) + writeu8(px, q + 2, (band(map, 4) ~= 0 and{hi }or{lo})[1]) + writeu8(px, q + 3, (band(map, 8) ~= 0 and{hi }or{lo})[1]) + map = rshift(map, 4) + end + blk =blk+ 1 + end + else + local mode = 0 + if v4 then + if pos >= nbits then + return false, "truncated frame" + end + if bit() == 1 then + mode = 1 + elseif bit() == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (math.floor(blk / bw)) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then + return false, "truncated frame" + end + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full) + if a < 0 then + return false, "truncated frame" + end + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk =blk+ 1 + end + end + end + return true, nil +end + +return Smacker +end +__FILES["codecs/video/Legacy/Smc"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description +-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble +-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour +-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: +-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc +-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row +-- above). Never throws: reads past the data give zeros, the block count bounds every write. +local Picture = __include("codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) +function Smc.decode(pic, d, tables) +local px = pic.idx +local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = math.floor(pic.rows / 4 +) local total = (math.floor((pic.w + 3) / 4)) * (math.floor((pic.h + 3) / 4)) + if math.floor(total / 1024 )> n then + return false, "frame too small" + end + local blocksWide = math.floor((pic.w + 3) / 4 +) local p = 4 -- flags byte + 24-bit chunk size + -- block position: bx, by (blocks) + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + local function u8() +if p < n then + local v = readu8(d, p) + p =p+ 1 + return v + end + return 0 + end + local function advance() + bx =bx+ 1 + if bx >= blocksWide then + bx = 0 + by =by+ 1 + end + total =total- 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p =p+ 1 + local kind = rshift(op, 4) + local count +if kind < 8 then + count = (band(op, 0x10) ~= 0 and{(1 + u8() )}or{(1 + band(op, 15) +)})[1] else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = pair and 2 or 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = (pair and((count * 2 ))or(count +)) local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = (pair and k % 2 == 1 and{srcB }or{srcA +})[1] local sx, sy = (s % blocksWide) * 4, (math.floor(s / blocksWide)) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = kind <= 9 and 2 or(kind <= 11 and 4 or 8 +) local base = size == 2 and 0 or(size == 4 and 512 or 1536 +) local entry +if kind % 2 == 0 then + local i = (size == 2 and{pairI }or{(size == 4 and{quadI }or{octI +})[1]})[1] for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (math.floor(k / 4)) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (math.floor(k / 4)) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = (k < 8 and{fa }or{fb +})[1] local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (math.floor(k / 4)) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + -- 16-colour blocks + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (math.floor(k / 4)) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +-- tables() -> the colour group scratch (pairs, quads, octets) +function Smc.tables() +return buffer.create(512 + 1024 + 2048) +end + +return Smc +end +__FILES["codecs/video/Mpeg1"] = function() +--!strict +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder +-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / +-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +local Mpeg2 = __include("codecs/video/Mpeg2") + + + + + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). +-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / +-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes +-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from +-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this +-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); +-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. +-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- local dec = Mpeg2.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } +-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = __include("Types") +local Err = __include("core/Err") +local D = __include("codecs/video/Mpeg2/Decoder") + +local Mpeg2 = {} + +Mpeg2.PICTURE_I = 1 +Mpeg2.PICTURE_P = 2 +Mpeg2.PICTURE_B = 3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local Decoder = {} +Decoder.__index = Decoder + + + + + + + + + + + + + + + + + + +function Mpeg2.new(opts) +local o= (type(opts) == "table" and{opts }or{{} +})[1] local core = D.new(o.maxPixels) + if type(o.yield) == "function" then + core.setYield(o.yield) + end + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self, s) +local core = self._core + local pixels= nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px ) + pixels = px + end + self._count =self._count+ 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + chroma = s.chroma, + mpeg2 = s.mpeg2, + progressive = s.progressive, + fields = s.fields, + topFieldFirst = s.tff, + repeatFirstField = s.rff, + clamped = s.clamped, + concealed = s.concealed, + } +end + +local function sync(self) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self, s) +if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self, atEnd, tag) +local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self, data, offset, len) +local src +if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self, data, offset, len) +return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self) +return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self, data, offset, len, tag) +if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self) +local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Sets (or clears, nil) the cooperative yield hook (Options.yield). +function Decoder.setYield(self, hook) + self._core.setYield((type(hook) == "function" and{hook }or{nil})[1]) +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self) + self._core.reset() + self._held = nil +end + +-- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a +-- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes. +-- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in +-- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 .. +-- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows. +-- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many +-- rows as its luma; use frameImage(frame, true) for those.) +function Mpeg2.toRgba(y, cb, cr, codedWidth, width, height, out, row0, row1, outOffset, planeRow0, hook) +if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then + return false + end + local cw, w, h = tonumber(codedWidth), tonumber(width), tonumber(height) + if not cw or not w or not h or cw % 2 ~= 0 or w < 1 or h < 1 or w > cw or cw ~= math.floor(cw) or w ~= math.floor(w) or h ~= math.floor(h) then + return false + end + local r0 = math.floor(tonumber(row0) or 0) + r0 =r0- r0 % 2 + local r1 = math.floor(tonumber(row1) or h) + local pr = math.floor(tonumber(planeRow0) or 0) + local oo = math.floor(tonumber(outOffset) or 0) + if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then + return false + end + -- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band + local lumaRows = r1 - pr + local chromaRows = math.floor((r1 + 1) / 2 )- math.floor(pr / 2 +) if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (math.floor(cw / 2)) or buffer.len(cr) < chromaRows * (math.floor(cw / 2)) then + return false + end + if buffer.len(out) < oo + (r1 - r0) * w * 4 then + return false + end + -- rows relative to the planes' first row + D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, (type(hook) == "function" and{hook }or{nil})[1]) + return true +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma +-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for +-- a value that is not a Frame. +function Mpeg2.frameImage(frame, rgba) +if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local c422 = frame.chroma == 2 + local chw, ow, oh = math.floor(cw / 2), math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local crows = (c422 and{h }or{oh +})[1] if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + if c422 then + D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + end + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + if not c422 then + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + else + -- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field + -- (4k + j and 4k + j + 2), so the fields do not mix + local inter = not frame.progressive + for y = 0, oh - 1 do + local a, b + if inter then + local base = (math.floor(y / 2)) * 4 + y % 2 + a, b = base, base + 2 + else + a, b = 2 * y, 2 * y + 1 + end + if b >= h then + b = a + end + for x = 0, ow - 1 do + buffer.writeu8(px, o + y * ow + x, math.floor((buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) / 2)) + buffer.writeu8(px, o + ow * oh + y * ow + x, math.floor((buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) / 2)) + end + end + end + end + img.meta.source = { + format = frame.mpeg2 and"mpeg2" or"mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + chroma = c422 and"422" or"420", + interlaced = not frame.progressive, + topFieldFirst = frame.topFieldFirst, + range = (rgba and{nil }or{"limited"})[1], + } + return img +end + +-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder +-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in +-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of +-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). +function Mpeg2.newVideoDecoder(_track, opts) +local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue= {} + local function push(f) + local img = Mpeg2.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, (type(tag) == "table" and{tag[1] }or{nil})[1], f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_, packet) +local tag = { packet.pts } + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + while f do -- more pictures in the packet + push(f) + f = dec:decode(packet.data, 0, 0, tag) + end + return nil + end + function self.receive(_) +local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_) + for _ = 1, 8 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_) + dec:reset() + table.clear(queue) + end + return self , nil +end + +return Mpeg2 +end +__FILES["codecs/video/Mpeg2/Decoder"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). +-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame +-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion +-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; +-- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser +-- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: +-- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js +-- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion +-- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), +-- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid +-- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 +-- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are +-- clamped (ffmpeg skips the prediction): both only matter for corrupt data. +-- +-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. +-- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), +-- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +local V = __include("codecs/video/Mpeg2/Vlc") +local T = __include("codecs/video/Mpeg2/Tables") +local Dsp = __include("codecs/video/Dsp") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +-- scan index -> natural position (zigzag, alternate); default matrices in natural order +local ZZ = buffer.create(64) +local ALT = buffer.create(64) +local DEF_INTRA = buffer.create(64) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(ALT, i, T.ALTERNATE_SCAN[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[i]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[i]) +end +local NON_LINEAR = buffer.create(32) +for i = 0, 31 do + buffer.writeu8(NON_LINEAR, i, T.NON_LINEAR_QSCALE[i]) +end + +local COFF = 40000 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT, DCT_B15 = V.DCT_FIRST, V.DCT_NEXT, V.DCT_B15 +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +-- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases +-- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively +local RGB_CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. +-- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional) +-- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's +-- later banded conversion.) +local function toRgba(Y, Cb, Cr, cw, w, h, out, row0, row1, oo, hook) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local r0= row0 or 0 + local r1= row1 or h + local base= oo or 0 + local chw = math.floor(cw / 2 +) local w2 = math.floor(w / 2 -- whole pixel pairs per row +) local stride = w * 4 + local C = RGB_CLAMP + local n = 0 + for y = r0, r1 - 1, 2 do + local yo = y * cw + local co = (math.floor(y / 2)) * chw + local o = base + (y - r0) * stride + local two = y + 1 < r1 + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co =co+ 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + yo =yo+ 2 + o =o+ 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, two and 1 or 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, readu8(C, rshift(yv + rr, 8)) + readu8(C, rshift(yv + gg, 8)) * 256 + readu8(C, rshift(yv + bb, 8)) * 65536 + 0xFF000000) + end + end + n =n+ 2 + if hook and n >= 16 then + n = 0 + pcall(hook) + end + end +end +D.toRgba = toRgba + +-- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2 +local function toRgba422(Y, Cb, Cr, cw, w, h, out) + local chw = math.floor(cw / 2 +) for y = 0, h - 1 do + local o = y * w * 4 + for x = 0, w - 1 do + local c = y * chw + math.floor(x / 2 +) local cb, cr = readu8(Cb, c), readu8(Cr, c) + local yv = readu8(Y, y * cw + x) * 298 + local r = math.clamp(rshift(yv + cr * 409 + RBIAS, 8) - COFF, 0, 255) + local g = math.clamp(rshift(yv + GBIAS - cb * 100 - cr * 208, 8) - COFF, 0, 255) + local b = math.clamp(rshift(yv + cb * 516 + BBIAS, 8) - COFF, 0, 255) + writeu32(out, o + x * 4, r + g * 256 + b * 65536 + 0xFF000000) + end + end +end +D.toRgba422 = toRgba422 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function D.new(maxPixels) +local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + mpeg2 = false, + chroma = 1, + progressive = true, + profileLevel = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil , + refNew = nil , + } + + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + -- sequence + local hasSeq = false + local mpeg2 = false + local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 + local progSeq = true + local mbW, mbH = 0, 0 -- frame size in macroblocks + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local lumaH, chromaH = 0, 0 -- plane heights (coded) + local intraQ = buffer.create(64) -- natural order + local nonIntraQ = buffer.create(64) + local chromaIntraQ = buffer.create(64) + local chromaNonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + buffer.copy(chromaIntraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(chromaNonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores= {} + local bStore= nil + -- the sequence header's values, applied (and the stores allocated) once its extension has been seen + local seqW, seqH = 0, 0 + + -- picture + local ptype = 0 + local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] + local fullPelFw, fullPelBw = false, false + local dcPrec = 0 + local picStruct = 3 -- 1 top field, 2 bottom field, 3 frame + local fpfd = true -- frame_pred_frame_dct + local concealMv = false + local qScaleType = 0 + local intraVlc = false + local scan = ZZ + local tff, rff, progFrame = true, false, true + local fieldPic = false + local secondField = false + local parity = 0 -- the current field (0 top, 1 bottom) + local mbRows, mbSize = 0, 0 -- of the current picture (field pictures: half the frame's rows) + local lstride, lbase, cstride, cbase = 0, 0, 0, 0 -- plane addressing of the current picture + local cur= nil + local curY, curCb, curCr = data, data, data + local fwS= nil + local bwS= nil + local pending= nil -- a first field waiting for its second + local pendingStruct = 0 + local pendingFw= nil + local pendingBw= nil + + -- slice / macroblock + local qscale = 2 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local mbIntra = false + local motFw, motBw = false, false + local motionType = 1 -- 1 frame (field pictures: field 16x16), 2 field (frame pictures), 3 16x8, 4 dual prime + local dctType = 0 + -- vectors: MV[(d * 4 + k) * 2 + c + 1] (direction d, vector k: 0 / 1 the two fields or halves, 2 / 3 dual-prime + -- opposite-parity vectors; component c); PMV[(d * 2 + r) * 2 + c + 1]; FSEL[d * 2 + r + 1] + local MV = table.create(16, 0) + local PMV = table.create(8, 0) + local FSEL = table.create(4, 0) + local blk = buffer.create(256) + local yieldHook= nil + + local function peek32() +local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + local function read(n) +local v = rshift(peek32(), 32 - n) + pos =pos+ n + return v + end + + local function vlc(lut, k) +local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos =pos+ l + return band(e, 0xFFFF) - 32768 + end + + -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 + local function findStart(from, to) +local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i =i+ 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i =i+ 3 + else + i =i+ 1 + end + end + return -1 + end + + local function newStore() +local y = buffer.create(cw * lumaH) + local cb = buffer.create(chw * chromaH) + local cr = buffer.create(chw * chromaH) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { + y = y, + cb = cb, + cr = cr, + w = state.width, + h = state.height, + cw = cw, + chroma = chroma, + tref = 0, + ptype = 0, + tag = nil, + mpeg2 = mpeg2, + progressive = true, + fields = false, + tff = true, + rff = false, + clamped = 0, + concealed = {}, + } + end + + local function loadMatrix(q) + for i = 0, 63 do + local v = read(8) + writeu8(q, readu8(ZZ, i), v == 0 and 1 or v) + end + end + + -- the sequence (header + extension) takes effect: sizes and stores + local function applySequence() +local w, h = seqW, seqH + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + local mh = (mpeg2 and not progSeq and((2 * (math.floor((h + 31) / 32)) ))or((math.floor((h + 15) / 16 +)))) if w ~= state.width or h ~= state.height or mh ~= mbH or chroma ~= state.chroma or mpeg2 ~= state.mpeg2 then + state.width = w + state.height = h + state.chroma = chroma + state.mpeg2 = mpeg2 + mbW = math.floor((w + 15) / 16 +) mbH = mh + cw = mbW * 16 + chw = mbW * 8 + lumaH = mbH * 16 + chromaH = (chroma == 2 and{lumaH }or{(math.floor(lumaH / 2 +))})[1] state.codedWidth = cw + state.codedHeight = lumaH + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + pending = nil + state.sizeChanged = true + end + state.progressive = progSeq + hasSeq = true + return true + end + + -- sequence header at byte p (after the start code); false when invalid + local function sequenceHeader(p) +pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos =pos+ (1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag +) if read(1) == 1 then + loadMatrix(intraQ) + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + seqW, seqH = w, h + mpeg2 = false -- until a sequence extension follows + chroma = 1 + progSeq = true + return w > 0 and h > 0 + end + + local function sequenceExtension() + state.profileLevel = read(8) + progSeq = read(1) == 1 + local cf = read(2) + seqW =seqW+ lshift(read(2), 12) + seqH =seqH+ lshift(read(2), 12) + state.bitRate =state.bitRate+ lshift(read(12), 18) * 400 + pos =pos+ (1 + 8 + 1 -- marker, vbv_buffer_size_extension, low_delay +) local n = read(2) + local d = read(5) + state.frameRate = state.frameRate * (n + 1) / (d + 1) + mpeg2 = true + chroma = cf == 2 and 2 or 1 -- 4:4:4 (3) is not supported: decoded as 4:2:0 (wrong but safe) + if cf == 3 then + state.errors =state.errors+ 1 + end + end + + local function quantMatrixExtension() + if read(1) == 1 then + loadMatrix(intraQ) + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(chromaIntraQ) + end + if read(1) == 1 then + loadMatrix(chromaNonIntraQ) + end + end + + local function fcode(v) +return (v < 1 or v > 9 )and 1 or v + end + + local function pictureCodingExtension() + fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4)) + dcPrec = read(2) + picStruct = read(2) + tff = read(1) == 1 + fpfd = read(1) == 1 + concealMv = read(1) == 1 + qScaleType = read(1) + intraVlc = read(1) == 1 + scan = (read(1) == 1 and{ALT }or{ZZ +})[1] rff = read(1) == 1 + pos =pos+ 1 -- chroma_420_type + progFrame = read(1) == 1 + if picStruct == 0 then + picStruct = 3 + err = true + end + end + + -- an extension (00 00 01 B5) at byte p + local function extension(p) + pos = p * 8 + local id = read(4) + if id == 1 then + sequenceExtension() + elseif id == 3 then + quantMatrixExtension() + elseif id == 8 then + pictureCodingExtension() + end + end + + local function decodeMotion(f, pred) +local code = vlc(MOTION, MOTION_BITS) + local d = code + local rsize = f - 1 + if code ~= 0 and rsize > 0 then + local r = read(rsize) + d = lshift(math.abs(code) - 1, rsize) + r + 1 + if code < 0 then + d = -d + end + end + local range = lshift(16, rsize) + return (pred + d + range) % (2 * range) - range + end + + -- ------------------------------------------------------------------------------------------------ prediction + -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: + -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the + -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the + -- first prediction. + local EDGE = buffer.create(Dsp.EDGE_SIZE) + local function mcPart(rY, rCb, rCr, sp, dp, rowY, h, mvx, mvy, avg) + local stride, sb, db, ph = cw, 0, 0, lumaH + local cs, csb, cdb = chw, 0, 0 + if sp >= 0 then + stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, math.floor(lumaH / 2 +) cs, csb, cdb = 2 * chw, sp * chw, dp * chw + end + -- luma + local hx, hy = band(mvx, 1), band(mvy, 1) + local sx = mbCol * 16 + math.floor((mvx - hx) / 2 +) local sy = rowY + math.floor((mvy - hy) / 2 +) local dOff = db + rowY * stride + mbCol * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + h + hy > ph then + -- outside the reference (invalid in MPEG; ffmpeg's encoder writes such half-sample vectors at the right / + -- bottom edge): predicted from repeated edge samples, as the encoder meant (ffmpeg's decoder skips it) + Dsp.edge(rY, stride, sb, sx, sy, 16, h, cw, ph, EDGE) + mc(EDGE, 32, 0, curY, stride, dOff, 16, h, hx, hy, avg) + state.clamped =state.clamped+ 1; +cur .clamped =cur.clamped+ 1 + else + mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) + end + -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 + local mx = math.floor(mvx / 2 +) if mvx < 0 then + mx = -(math.floor((-mvx) / 2)) + end + local cx, cy, chh, cph, chx, chy + chx = band(mx, 1) + cx = mbCol * 8 + math.floor((mx - chx) / 2 +) if chroma == 1 then + local my = math.floor(mvy / 2 +) if mvy < 0 then + my = -(math.floor((-mvy) / 2)) + end + chy = band(my, 1) + cy = math.floor(rowY / 2 )+ math.floor((my - chy) / 2 +) chh, cph = math.floor(h / 2), math.floor(ph / 2 +) else + chy = band(mvy, 1) + cy = rowY + math.floor((mvy - chy) / 2 +) chh, cph = h, ph + end + local crow = rowY + if chroma == 1 then + crow = math.floor(rowY / 2 +) end + local cdOff = cdb + crow * cs + mbCol * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then + Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) + Dsp.edge(rCr, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCr, cs, cdOff, 8, chh, chx, chy, avg) + else + local so = csb + cy * cs + cx + mc(rCb, cs, so, curCb, cs, cdOff, 8, chh, chx, chy, avg) + mc(rCr, cs, so, curCr, cs, cdOff, 8, chh, chx, chy, avg) + end + end + + -- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the + -- opposite parity from its own first field + local function fieldRef(d, fs) +if d == 0 then + if secondField and ptype == 2 and fs ~= parity then + return cur +end + return (fwS or cur) +end + return (bwS or cur) +end + + -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock + local function predictDir(d, avg) + local o = d * 8 + if not fieldPic then + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r +local ry, rcb, rcr = ref.y, ref.cb, ref.cr + if motionType == 1 then + mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 2 then + mcPart(ry, rcb, rcr, FSEL[d * 2 + 1], 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, FSEL[d * 2 + 2], 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + else -- dual prime: each field from the same parity (MV 0 / 1), averaged with the opposite parity (MV 2 / 3) + mcPart(ry, rcb, rcr, 0, 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, 1, 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + mcPart(ry, rcb, rcr, 1, 0, mbRow * 8, 8, MV[o + 5], MV[o + 6], true) + mcPart(ry, rcb, rcr, 0, 1, mbRow * 8, 8, MV[o + 7], MV[o + 8], true) + end + return + end + if motionType == 1 then + local fs = FSEL[d * 2 + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 3 then + for k = 0, 1 do + local fs = FSEL[d * 2 + k + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16 + k * 8, 8, MV[o + k * 2 + 1], MV[o + k * 2 + 2], avg) + end + else -- dual prime: same parity, then the opposite one (the first field of this frame for a second field) + local r = (fwS or cur) +mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + local q = (secondField and{cur }or{r +})[1] mcPart(q.y, q.cb, q.cr, 1 - parity, parity, mbRow * 16, 16, MV[o + 5], MV[o + 6], true) + end + end + + -- the prediction of a non-intra macroblock from the current motion state + local function predictMb() + if ptype == 2 then + predictDir(0, false) + elseif motFw then + predictDir(0, false) + if motBw then + predictDir(1, true) + end + elseif motBw then + predictDir(1, false) + end + end + + local function resetPmv() + for i = 1, 8 do + PMV[i] = 0 + end + end + + -- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the + -- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction + local function skipMotion() + motionType = 1 + FSEL[1], FSEL[3] = parity, parity + if ptype == 2 then + resetPmv() + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = PMV[1], PMV[2] + MV[9], MV[10] = PMV[5], PMV[6] + end + end + + -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 + -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do + -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock + -- before the gap. + local covered = 0 + local gapFw, gapBw = false, false + local GAP = table.create(16, 0) + local gapType = 1 + local hasRef = false + local SAVE = table.create(16, 0) + local function conceal(from, to) + if from > to or not hasRef then + return + end + local sFw, sBw, sType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, SAVE) + local f1, f2, f3, f4 = FSEL[1], FSEL[2], FSEL[3], FSEL[4] + if ptype == 3 and mpeg2 then + -- both references, zero vectors (ffmpeg's error concealment of B macroblocks, without its deblocking) + motFw, motBw, motionType = true, true, 1 + MV[1], MV[2], MV[9], MV[10] = 0, 0, 0, 0 + elseif ptype == 3 then + motFw, motBw, motionType = gapFw, gapBw, gapType + table.move(GAP, 1, 16, 1, MV) + if not motFw and not motBw then + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + end + else + motionType = 1 + if not (ptype == 2 and gapFw) then + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = GAP[1], GAP[2] + end + end + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = parity, parity, parity, parity + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + local c = (cur ).concealed + for a = from, to do + mbRow = math.floor(a / mbW +) mbCol = a % mbW + predictMb() + if fieldPic then + c[mbRow * 2] = true + c[mbRow * 2 + 1] = true + else + c[mbRow] = true + end + end + ptype = pt + motFw, motBw, motionType = sFw, sBw, sType + table.move(SAVE, 1, 16, 1, MV) + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 + end + + -- ------------------------------------------------------------------------------------------------ blocks + -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. + -- False on a bitstream error. + local function decodeBlock(b) +local n = 0 + local q +local onlyDc = true + local luma = b < 4 + local parityOdd = 1 -- MPEG-2 mismatch control: 1 while the coefficient sum is even + if mbIntra then + local dc + local size + if luma then + size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + else + size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end + end + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc =dc+ diff + end + if err then + return false + end + local top = lshift(256, dcPrec) - 1 + if dc < 0 or dc > top then + dc = dc < 0 and 0 or top -- corrupt data: clamped, which also bounds the IDCT input + end + if luma then + dcY = dc + elseif b % 2 == 0 then + dcCb = dc + else + dcCr = dc + end + local v = lshift(dc, 3 - dcPrec) + writei32(blk, 0, v) + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end + n = 1 + else + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST + end + local intra = mbIntra + local qs = qscale + local m2 = mpeg2 + while true do + -- inline peek + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = nextLut + if v == EOB then + pos =pos+ l + break + end + local run, level, neg + if v == ESC then + pos =pos+ l + run = read(6) + if m2 then + -- a 12-bit signed level + level = read(12) + if level >= 2048 then + level =level- 4096 + end + else + -- an 8-bit level or 0x00 / 0x80 and 8 more bits + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level =level- 256 + end + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos =pos+ (l + 1 +) end + n =n+ run + if n > 63 then + err = true + return false + end + local zz = readu8(scan, n) + -- dequantise the magnitude (ffmpeg's arithmetic); MPEG-1 makes it odd toward zero + local m + if intra then + m = math.floor((level * qs * readu8(q, zz)) / 16 +) else + m = math.floor(((level * 2 + 1) * qs * readu8(q, zz)) / 32 +) end + if not m2 then + if m == 0 then + m = -1 + elseif band(m, 1) == 0 then + m =m- 1 + end + end + if neg then + m = -m + end + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end + -- saturate + if m > 2047 then + m = 2047 + elseif m < -2048 then + m = -2048 + end + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n =n+ 1 + end + if m2 and parityOdd == 1 then + -- mismatch control: toggle the last coefficient's lowest bit + local v = readi32(blk, 252) + writei32(blk, 252, (v % 2 ~= 0 and((v - 1 ))or((v + 1)))) + onlyDc = false + end + -- reconstruction + local dst, off, stride + if luma then + dst = curY + if fieldPic then + stride = lstride + off = lbase + (mbRow * 16 + (b >= 2 and 8 or 0)) * stride + mbCol * 16 + (b % 2 == 1 and 8 or 0) + elseif dctType == 1 then + stride = 2 * cw + off = (mbRow * 16 + (b >= 2 and 1 or 0)) * cw + mbCol * 16 + (b % 2 == 1 and 8 or 0) + else + stride = cw + off = (mbRow * 16 + (b >= 2 and 8 or 0)) * cw + mbCol * 16 + (b % 2 == 1 and 8 or 0) + end + else + dst = curCr + if b % 2 == 0 then + dst = curCb + end + local k = math.floor((b - 4) / 2 -- the vertical chroma block of a 4:2:2 macroblock +) if chroma == 1 then + stride = cstride + off = cbase + mbRow * 8 * stride + mbCol * 8 + elseif fieldPic then + stride = cstride + off = cbase + (mbRow * 16 + k * 8) * stride + mbCol * 8 + elseif dctType == 1 then + stride = 2 * chw + off = (mbRow * 16 + k) * chw + mbCol * 8 + else + stride = chw + off = (mbRow * 16 + k * 8) * chw + mbCol * 8 + end + end + if onlyDc then + fillBlock(dst, off, stride, math.floor((readi32(blk, 0) + 4) / 8), not intra) + writei32(blk, 0, 0) + else + idct(blk, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + -- ------------------------------------------------------------------------------------------------ macroblocks + local function getQscale(code) +if qScaleType == 1 then + return readu8(NON_LINEAR, code) + end + return code * 2 + end + + -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) + local function motionVectors(d) + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end + local o, p, f = d * 8, d * 4, d * 2 + if motionType == 1 and not fieldPic then + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + if (d == 0 and fullPelFw) or (d == 1 and fullPelBw) then + x =x* 2 + y =y* 2 + end + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 2 then + -- field prediction in a frame picture: vertical predictors in frame units + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, math.floor(PMV[p + r * 2 + 2] / 2)) + PMV[p + r * 2 + 1] = x + PMV[p + r * 2 + 2] = y * 2 + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + elseif motionType == 1 then + -- field picture, 16x16 + FSEL[f + 1] = read(1) + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 3 then + -- 16x8 (field pictures) + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2]) + PMV[p + r * 2 + 1], PMV[p + r * 2 + 2] = x, y + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + else + -- dual prime + local shift = fieldPic and 0 or 1 + local x = decodeMotion(fh, PMV[p + 1]) + local dmx = (read(1) == 1 and((1 - 2 * read(1) ))or(0 +)) local y = decodeMotion(fv, (shift == 1 and{(math.floor(PMV[p + 2] / 2 ))}or{PMV[p + 2]})[1]) + local dmy = (read(1) == 1 and((1 - 2 * read(1) ))or(0 +)) PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y * (shift + 1), y * (shift + 1) + MV[o + 1], MV[o + 2], MV[o + 3], MV[o + 4] = x, y, x, y + -- the opposite-parity vectors: scaled by the field distance, rounded away from zero + local xp, yp = x > 0 and 1 or 0, y > 0 and 1 or 0 + if not fieldPic then + local m = tff and 1 or 3 + MV[o + 5] = math.floor((x * m + xp) / 2 )+ dmx + MV[o + 6] = math.floor((y * m + yp) / 2 )+ dmy - 1 + m = 4 - m + MV[o + 7] = math.floor((x * m + xp) / 2 )+ dmx + MV[o + 8] = math.floor((y * m + yp) / 2 )+ dmy + 1 + else + MV[o + 5] = math.floor((x + xp) / 2 )+ dmx + MV[o + 6] = math.floor((y + yp) / 2 )+ dmy + (parity == 0 and-1 or 1) + end + end + end + + -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. + local function decodeMacroblock(first, endBits) +local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc =inc+ 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc =inc+ t + if first then + mbAddr =mbAddr+ inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + skipMotion() + for _ = 2, inc do + mbAddr =mbAddr+ 1 + mbRow = math.floor(mbAddr / mbW +) mbCol = mbAddr % mbW + predictMb() + end + end + mbAddr =mbAddr+ 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = math.floor(mbAddr / mbW +) mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + local pattern = band(mt, 2) ~= 0 + local fw = band(mt, 8) ~= 0 + local bw = band(mt, 4) ~= 0 + dctType = 0 + if mpeg2 then + if mbIntra or not (fw or bw) then + motionType = 1 + if not fieldPic and not fpfd and (mbIntra or pattern) then + dctType = read(1) + end + else + if not fieldPic and fpfd then + motionType = 1 + else + local mtc = read(2) + if fieldPic then + motionType = mtc == 1 and 1 or(mtc == 2 and 3 or 4 +) else + motionType = mtc == 1 and 2 or(mtc == 2 and 1 or 4 +) end + if mtc == 0 then + err = true + return false + end + if not fieldPic and pattern then + dctType = read(1) + end + end + end + else + motionType = 1 + end + if band(mt, 0x10) ~= 0 then + local code = read(5) + if code == 0 then + err = true + return false + end + qscale = getQscale(code) + end + if mbIntra then + if concealMv then + -- concealment vectors: parsed, kept as predictors + if fieldPic then + pos =pos+ 1 + end + local x = decodeMotion(fc00, PMV[1]) + local y = decodeMotion(fc01, PMV[2]) + PMV[1], PMV[3] = x, x + PMV[2], PMV[4] = y, y + pos =pos+ 1 -- marker + else + resetPmv() + end + else + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw = fw + motBw = bw + if fw then + motionVectors(0) + elseif ptype == 2 then + -- P without motion: a zero vector (field pictures: from the same parity) + resetPmv() + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + FSEL[1] = parity + end + if bw then + motionVectors(1) + end + if err then + return false + end + predictMb() + end + local nb = chroma == 2 and 8 or 6 + local cbp + if pattern then + cbp = vlc(CBP, CBP_BITS) + if nb == 8 then + cbp = cbp * 4 + read(2) + end + if err then + return false + end + else + cbp = (mbIntra and{(lshift(1, nb) - 1 )}or{0 +})[1] end + if cbp ~= 0 then + for b = 0, nb - 1 do + if band(cbp, lshift(1, nb - 1 - b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + local function decodeSlice(row, endByte) + if mpeg2 and lumaH > 2800 then + row =row+ lshift(read(3), 7) + end + if row > mbRows then + return + end + mbAddr = (row - 1) * mbW - 1 + resetPmv() + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw, motBw = false, false + local code = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos =pos+ 8 + end + if code == 0 then + return + end + qscale = getQscale(code) + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors =state.errors+ 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, GAP) + end + end + + -- ------------------------------------------------------------------------------------------------ pictures + -- the frame a picture completes becomes the newest reference (I / P) + local function finishFrame(s) + if s.ptype ~= 3 then + state.refOld = state.refNew + state.refNew = s + end + end + + -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice + -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + local function pictureHeader(p, stop) +pos = p * 8 + local tref = read(10) + ptype = read(3) + pos =pos+ 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped =state.skipped+ 1 -- D pictures and invalid types + return nil, 0 + end + fullPelFw, fullPelBw = false, false + if ptype >= 2 then + fullPelFw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped =state.skipped+ 1 + return nil, 0 + end + fc00, fc01 = c, c + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped =state.skipped+ 1 + return nil, 0 + end + fc10, fc11 = c, c + end + -- MPEG-1 semantics unless a picture coding extension follows + dcPrec, picStruct, fpfd, concealMv, qScaleType, intraVlc, scan = 0, 3, true, false, 0, false, ZZ + tff, rff, progFrame = true, false, true + err = false + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code == 0xB5 then + extension(at + 4) + elseif code ~= 0xB2 then + break + end + at = findStart(at + 4, stop) + end + if mpeg2 then + fullPelFw, fullPelBw = false, false + end + if err then + state.errors =state.errors+ 1 + err = false + end + return at, tref + end + + -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped + local function selectTarget(tref, tag) +fieldPic = picStruct ~= 3 + parity = picStruct == 2 and 1 or 0 + secondField = false + local target +if fieldPic and pending and pendingStruct ~= picStruct then + secondField = true + target = pending +fwS, bwS = pendingFw, pendingBw + if ptype == 3 and (fwS == nil or bwS == nil) then + state.skipped =state.skipped+ 1 + return false + end + else + if pending then + -- an unpaired field: its frame is done as it is + finishFrame(pending ) + pending = nil + end + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = (stores[1] == refNew and{stores[2] }or{stores[1] +})[1] fwS, bwS = refNew, nil + elseif ptype == 2 then + if refNew == nil and not fieldPic then + state.skipped =state.skipped+ 1 + return false + end + target = (stores[1] == refNew and{stores[2] }or{stores[1] +})[1] fwS, bwS = refNew, nil + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped =state.skipped+ 1 + return false + end + target = bStore +fwS, bwS = refOld, refNew + end + target.ptype = ptype + target.tref = tref + target.tag = tag + target.mpeg2 = mpeg2 + target.progressive = progFrame + target.fields = fieldPic + target.tff = (fieldPic and{(picStruct == 1 )}or{tff +})[1] target.rff = rff + target.clamped = 0 + target.concealed = {} + end + cur = target + return true + end + + -- plane addressing of the current picture + local function setAddressing() + local target = cur +curY, curCb, curCr = target.y, target.cb, target.cr + if fieldPic then + mbRows = math.floor(mbH / 2 +) lstride, lbase = 2 * cw, parity * cw + cstride, cbase = 2 * chw, parity * chw + else + mbRows = mbH + lstride, lbase = cw, 0 + cstride, cbase = chw, 0 + end + mbSize = mbW * mbRows + covered = 0 + hasRef = fwS ~= nil + gapFw, gapBw = false, false + mbIntra = false + end + + -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil + -- (skipped, or the first field of a frame). + local function decodePicture(p, stop, tag) +local first, tref = pictureHeader(p, stop) + if first == nil or not selectTarget(tref, tag) then + return nil + end + setAddressing() + -- slices + local at = first +while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local hook = yieldHook + if hook then + -- the hook may suspend this coroutine: the picture state is all upvalues of this core + pcall(hook) + end + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures =state.pictures+ 1 + local target = cur +if fieldPic and not secondField then + pending = target + pendingStruct = picStruct + pendingFw, pendingBw = fwS, bwS + return nil + end + pending = nil + finishFrame(target) + return target + end + + local core = {} +core.state = state + + function core.write(src, off, n) + if n <= 0 then + return + end + -- drop consumed bytes, keeping the scan state relative + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap =cap* 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen =dataLen+ n + buffer.fill(data, dataLen, 0, PAD) + end + + -- the sequence header unit at byte at (up to stop): the header, then its extensions + local function sequenceUnit(at, stop) + local ok = sequenceHeader(at + 4) + local s = findStart(at + 4, stop) + while s >= 0 do + if readu8(data, s + 3) == 0xB5 then + extension(s + 4) + end + s = findStart(s + 4, stop) + end + if not ok or not applySequence() then + state.errors =state.errors+ 1 + end + end + + function core.nextPicture(atEnd, tag) +while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + sequenceUnit(at, stop) + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped =state.skipped+ 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + function core.toRgba(s, out) + if s.chroma == 2 then + toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + else + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out, 0, s.h, 0, yieldHook) + end + end + + function core.setYield(hook) + yieldHook = hook + end + + function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + pending = nil + end + + return core +end + +return D +end +__FILES["codecs/video/Mpeg2/Tables"] = function() +--!strict +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from +-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the +-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. +local T = {} +T.PICTURE_RATE = { [0] = 0.0, + 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, +} +T.ZIG_ZAG = { [0] = 0, + 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, + 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} +T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8, + 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, + 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, + 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83, +} +T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, +} +T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0, + 0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0, + 0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99, + 102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135, + 138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1, + 144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1, + 186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0, + 0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0, + 0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0, + 0, 24, 0, 0, 23, 0, 0, 22, +} +T.MACROBLOCK_TYPE_INTRA = { [0] = 3, + 6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3, + 6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33, + 36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17, +} +T.MACROBLOCK_TYPE_B = { [0] = 3, + 6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36, + 33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0, + 0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26, +} +T.CODE_BLOCK_PATTERN = { [0] = 6, + 3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54, + 48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132, + 144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129, + 102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0, + 0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171, + 174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0, + 0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0, + 0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264, + 246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0, + 0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270, + 276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336, + 333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0, + 0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0, + 0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0, + 0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0, + 0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31, +} +T.MOTION = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36, + 33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51, + 57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108, + 105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0, + 0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156, + 141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0, + 0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0, + 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, + 0, -15, 0, 0, -11, 0, 0, -13, +} +T.DCT_COEFF = { [0] = 3, + 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, + 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, + 75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0, + 0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120, + 123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0, + 0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0, + 0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201, + 210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273, + 240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0, + 0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333, + 342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339, + 309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417, + 420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411, + 399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0, + 0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0, + 0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510, + 483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549, + 546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0, + 0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0, + 0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0, + 0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0, + 0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0, + 0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654, + 633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657, + 624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0, + 0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0, + 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, + 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, +} +-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size +T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } } +T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } } +-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows) +T.DCT_COEFF_B15 = { + 2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8, + 124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16, + 30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24, + 22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32, + 23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40, + 2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264, + 30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272, + 17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769, + 38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282, + 18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050, + 120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074, + 36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098, + 31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145, + 28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937, +} +-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code +T.NON_LINEAR_QSCALE = { [0] = 0, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112, +} +-- the alternate scan (Figure 7-3): scan index -> natural position +T.ALTERNATE_SCAN = { [0] = 0, + 8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58, + 35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46, + 54, 62, 39, 47, 55, 63, +} +return T +end +__FILES["codecs/video/Mpeg2/Vlc"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). +-- +-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds +-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level +-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, +-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the +-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / +-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); +-- the MPEG-2 tables are built from code lists. +local T = __include("codecs/video/Mpeg2/Tables") + +local V = {} + + + +local function leaves(tree) +local out= {} + local function walk(state, code, len) + if tree[state] == 0 and len > 0 then + table.insert(out, { code = code, len = len, value = tree[state + 2] }) + return + end + for bit = 0, 1 do + local nxt = tree[state + bit] + if nxt ~= nil and nxt > 0 then + walk(nxt, code * 2 + bit, len + 1) + end + end + end + walk(0, 0, 0) + return out +end + +local function flatLeaves(ls) +local k = 0 + for _, l in __iter(ls) do + k = math.max(k, l.len) + end + local lut = buffer.create(4 * 2 ^ k) + for _, l in __iter(ls) do + local shift = k - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768) + end + end + return lut, k +end + +local function flat(tree) +return flatLeaves(leaves(tree)) +end + +-- { { code, length } } indexed from 1 -> leaves with value = index - 1 +local function codeLeaves(codes) +local out= {} + for i, c in __iter(codes) do + table.insert(out, { code = c[1], len = c[2], value = i - 1 }) + end + return out +end + +V.SUB = 0x1000000 +V.ESC = 0xFFFF +V.EOB = 0xFFFE + +-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits +local function twoLevel(ls) +local subs= {} + local nsub = 0 + for _, l in __iter(ls) do + if l.len > 8 then + local prefix = math.floor(l.code / 2 ^ (l.len - 8) +) if subs[prefix] == nil then + nsub =nsub+ 1 + subs[prefix] = nsub + end + end + end + local lut = buffer.create(4 * 256 * (1 + nsub)) + for _, l in __iter(ls) do + if l.len <= 8 then + local shift = 8 - l.len + local first = l.code * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, i * 4, l.len * 65536 + l.value) + end + else + local prefix = math.floor(l.code / 2 ^ (l.len - 8) +) local s = subs[prefix] + buffer.writeu32(lut, prefix * 4, V.SUB + s) + local rest = l.code % 2 ^ (l.len - 8) + local shift = 16 - l.len + local first = rest * 2 ^ shift + for i = first, first + 2 ^ shift - 1 do + buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value) + end + end + end + return lut +end + +V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape +V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) +V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) +V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) +do + -- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma + -- pattern bits) + local ls = leaves(T.CODE_BLOCK_PATTERN) + table.insert(ls, { code = 1, len = 9, value = 0 }) + V.CBP, V.CBP_BITS = flatLeaves(ls) +end +V.MOTION, V.MOTION_BITS = flat(T.MOTION) +V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA)) +V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA)) + +do + local ls = leaves(T.DCT_COEFF) + V.DCT_FIRST = twoLevel(ls) + local nextLs= {} + for _, l in __iter(ls) do + if l.len == 1 and l.code == 1 then + table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10" + table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11" + else + table.insert(nextLs, l) + end + end + V.DCT_NEXT = twoLevel(nextLs) +end + +do + local ls= { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } } + local b = T.DCT_COEFF_B15 + for i = 1, #b, 3 do + table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] }) + end + V.DCT_B15 = twoLevel(ls) +end + +return V +end +__FILES["codecs/video/Theora"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska +-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau +-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). +-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV +-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, +-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); +-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). +-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). +-- +-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate +-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err +-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region +-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down +-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position +-- +-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +local Err = __include("core/Err") +local Types = __include("Types") +local VorbisComment = __include("codecs/audio/VorbisComment") +local Header = __include("codecs/video/Theora/Header") +local Decoder = __include("codecs/video/Theora/Decoder") + +local Theora = {} + + + + + + + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil +function Theora.isHeader(b, off, len) +local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) +function Theora.splitConfig(c) +local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size =size+ b + p =p+ 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p =p+ lens[k] + end + return out +end + +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h) +local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from((ok and{err }or{(tostring(info))})[1]) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h) +local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from((ok and{err }or{(tostring(vendor))})[1]) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + +-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) +function Theora.granuleFrame(info, g) +if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = math.floor(g / shift +) local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f =f- 1 + end + return f +end + +-- ------------------------------------------------------------------------------------------------ decoder +local Dec = {} +Dec.__index = Dec + +-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config + + + + + + + + + + + + + + + + + + +function Theora.new(headers, opts) +local list= nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from((ok3 and{serr }or{(tostring(setup))})[1]) + end + local st = Decoder.new(info, setup) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = (info.aspectNum > 0 and info.aspectDen > 0 and((info.aspectNum / info.aspectDen ))or(1)), + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). +function Dec.decode(self, data, off, len) +local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames =self.frames+ 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) +function Dec.reset(self) + local st = self._st + st.shown = st.prev +end + +local function window(self) +local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, +-- chroma height +function Dec.planes(self) +local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = math.floor(x0 / 2 ^ hd), math.floor(y0 / 2 ^ vd +) local cw, ch = math.floor((w + hd) / 2 ^ hd), math.floor((h + vd) / 2 ^ vd +) cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) +function Dec.image(self) +local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +-- ------------------------------------------------------------------------------------------------ registry +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config +-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat +function Theora.newVideoDecoder(track, opts) +if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config , { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec +local pending= {} + local self= {} + function self.decode(_, packet) +local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_) +local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_) end + function self.reset(_) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora +end +__FILES["codecs/video/Theora/Decoder"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A +-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, +-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: +-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode +-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel +-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; +-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), +-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for +-- unrestricted motion vectors, golden / previous reference frames; +-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. +-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, +-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), +-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- +-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled +-- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +local Header = __include("codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n =n+ 1 + end + MODE_VLC[w + 1] = n * 8 + ((n < 7 and((n + 1 ))or(7))) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + local function put(code, len, v) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = tok == 9 and 1 or(tok == 10 and-1 or(tok == 11 and 2 or-2 +)) elseif tok < 17 then + v = (eb == 1 and{(-(tok - 10) )}or{(tok - 10 +)})[1] elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = tok == 17 and 7 or(tok == 18 and 9 or(tok == 19 and 13 or(tok == 20 and 21 or(tok == 21 and 37 or 69 +)))) v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = eb == 1 and-1 or 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = eb >= 4 and-1 or 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = eb >= 8 and-1 or 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (math.floor(eb / 2)) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +-- new(info, setup) -> State + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function D.new(info, setup) +local pf = info.pixelFormat + local hdec = pf % 2 == 0 and 1 or 0 + local vdec = pf < 2 and 1 or 0 + local fw, fh = info.frameWidth, info.frameHeight + local st= { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(128), + tmp = buffer.create(128), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = (pli > 0 and{hdec }or{0})[1], (pli > 0 and{vdec }or{0 +})[1] local w, h = math.floor(fw / 2 ^ hd), math.floor(fh / 2 ^ vd +) local px, py = math.floor(16 / 2 ^ hd), math.floor(16 / 2 ^ vd +) st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = math.floor(w / 8), math.floor(h / 8 +) st.foff[pli + 1] = nfr + nfr =nfr+ (math.floor(w / 8)) * (math.floor(h / 8)) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr= {} + local sbQuadValid= {} + local sbPlane= {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = q == 3 and 2 or 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi =sbi+ 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (math.floor(mby / 2)) * nhc + math.floor(mbx / 2 +) elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + math.floor(mbx / 2 +) end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi =sbi+ 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = pf == 0 and{ 0, 1, 2, 3, 4, 8 } or(pf == 2 and{ 0, 1, 2, 3, 4, 6, 8, 10 } or{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } +) st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +local function idct8(x0, x1, x2, x3, x4, x5, x6, x7) +local t0 = math.floor((C4 * (x0 + x4)) / 65536 +) local t1 = math.floor((C4 * (x0 - x4)) / 65536 +) local t2 = math.floor((C6 * x2) / 65536 )- math.floor((C2 * x6) / 65536 +) local t3 = math.floor((C2 * x2) / 65536 )+ math.floor((C6 * x6) / 65536 +) local t4 = math.floor((C7 * x1) / 65536 )- math.floor((C1 * x7) / 65536 +) local t5 = math.floor((C3 * x5) / 65536 )- math.floor((C5 * x3) / 65536 +) local t6 = math.floor((C5 * x5) / 65536 )+ math.floor((C3 * x3) / 65536 +) local t7 = math.floor((C1 * x1) / 65536 )+ math.floor((C7 * x7) / 65536 +) local r = t4 + t5 + t5 = math.floor((C4 * (t4 - t5)) / 65536 +) t4 = r + r = t7 + t6 + t6 = math.floor((C4 * (t7 - t6)) / 65536 +) t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +local function idctRows(blk, tmp) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = math.floor((C4 * x0) / 65536 +) writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +local function idctAdd(tmp, dst, pos, stride) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y0 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y1 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y2 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y3 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y4 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y5 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y6 + 8) / 16 )+ COFF)) + p =p+ stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + math.floor((y7 + 8) / 16 )+ COFF)) + end +end + +local function wrap16(v) +return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +local function mvSplit(d, q) +local div = q and 4 or 2 + local a = (d < 0 and{(-(math.floor((-d) / div)) )}or{(math.floor(d / div +))})[1] local frac = d - a * div + local b = frac > 0 and 1 or(frac < 0 and-1 or 0 +) return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added +local function reconFrag(st, fi, qis, dstPlanes) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = mode == INTRA and 0 or 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + local fv = 0 + if last == 0 then + fv = wrap16(math.floor((dc * dcq + 15) / 32)) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idctRows(blk, st.tmp) + end + -- the prediction + if ri == SELF then + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[(ri == GOLD and{st.gold }or{st.prev})[1] ][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u= readu32(ref, a) + local v= readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2= readu32(ref, a + 4) + local v2= readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) + end + else + for y = 0, 7 do + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) + end + end + end + -- the residual + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then + for y = 0, 7 do + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ loop filter +local function filterH(b, p, stride, bv) + p =p- 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[math.floor((p0 - p3 + 3 * (p2 - p1) + 4) / 8 )+ 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p =p+ stride + end +end + +local function filterV(b, p, stride, bv) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[math.floor((p0 - p3 + 3 * (p2 - p1) + 4) / 8 )+ 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +local function loopFilter(st, planes, flimit) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = (i > 0 and((2 * flimit - a ))or((a - 2 * flimit +))) end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +local function borders(st, planes) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +local function dcPredict(st) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred +if fy == 0 then + pred = (r == 0 and{pl0 }or{(r == 1 and{pl1 }or{pl2 +})[1]})[1] else + local m = (lref == r and 1 or 0) + (ulref == r and 2 or 0) + (uref == r and 4 or 0) + (urref == r and 8 or 0) + if m == 0 then + pred = (r == 0 and{pl0 }or{(r == 1 and{pl1 }or{pl2 +})[1]})[1] elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = (s < 0 and{(-(math.floor((-s) / 2)) )}or{(math.floor(s / 2 +))})[1] elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = (s < 0 and{(-(math.floor((-s) / 128)) )}or{(math.floor(s / 128 +))})[1] elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = (s < 0 and{(-(math.floor((-s) / 2)) )}or{(math.floor(s / 2 +))})[1] elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = (s < 0 and{(-(math.floor((-s) / 16)) )}or{(math.floor(s / 16 +))})[1] else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = (s < 0 and{(-(math.floor((-s) / 32)) )}or{(math.floor(s / 32 +))})[1] if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ frame decode +-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in +-- st.refs[st.shown]. +function D.decode(st, data, off, len) +if len <= 0 then + return "dup", nil + end + -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + local function bits(n) +if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) + pos =pos+ n + return w + end + local huff = st.huff + local function sbRun() +if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + local function blockRun() +if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n =n+ 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total =total+ n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial =npartial+ flag + sbi =sbi+ 1 + run =run- 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi =sbi+ 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run =run- 1 + full[sbi + 1] = flag == 1 + end + sbi =sbi+ 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run =run- 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n =n+ 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total =total+ n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet +if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx +if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos =pos- (7 - e % 8 +) idx = math.floor(e / 8 +) end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + local function mv() +if clc then + local v = bits(6) + return (v % 2 == 1 and{(-(math.floor(v / 2)) )}or{(math.floor(v / 2 +))})[1] end + local e = MV_VLC[bits(8) + 1] + pos =pos- (8 - e % 16 +) return math.floor(e / 16 )- 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = math.floor((sx + 2 - (sx < 0 and 1 or 0)) / 4 +) cy[1] = math.floor((sy + 2 - (sy < 0 and 1 or 0)) / 4 +) elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = math.floor((sx + 1 - (sx < 0 and 1 or 0)) / 2 +) cy[1] = math.floor((sy + 1 - (sy < 0 and 1 or 0)) / 2 +) sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = math.floor((sx + 1 - (sx < 0 and 1 or 0)) / 2 +) cy[3] = math.floor((sy + 1 - (sy < 0 and 1 or 0)) / 2 +) else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n =n+ 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k] ] = flag + nqi1 =nqi1+ flag + k =k+ 1 + run =run- 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k] ] == 0 do + k =k+ 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run =run- 1 + qii[fi]=qii[fi]+ flag + end + k =k+ 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy= bits(4) + local hc= bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp= zzi == 0 and 0 or(zzi < 6 and 16 or(zzi < 15 and 32 or(zzi < 28 and 48 or 64 +))) for pli = 1, 3 do + local sel= (pli == 1 and{hy }or{hc +})[1] local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs =eobs- 1 + t = 64 + else + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos =pos+ rshift(e, 6) + tok = band(e, 63) + break + end + pos =pos+ nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos =pos+ ex + end + if tok < 7 then + local run +if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = eb == 0 and 2 ^ 31 or eb + end + eobs = run - 1 + t = 64 + else + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w =w+ 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + dcPredict(st) + + -- reconstruction into a free reference buffer + local self = 1 + while self == st.gold or self == st.prev do + self =self+ 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes =st.keyframes+ 1 + else + st.prev = self + end + st.shown = self + return intra and"key" or"inter", nil +end + +-- ------------------------------------------------------------------------------------------------ output +-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose +-- top-left corner is (x0, y0) counted from the top of the plane +function D.plane(st, pli, x0, y0, w, h) +local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 +-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +function D.downsample(src, cw, ch, hdec, dst, off, ow, oh) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, math.floor((readu8(src, a + c) + readu8(src, b + c) + 1) / 2)) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, math.floor((readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) / 4)) + end + end + end +end + +return D +end +__FILES["codecs/video/Theora/Header"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / +-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis +-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the +-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman +-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; +-- the table layout here is simpler). Never throws: bad headers return nil, message. +local Bits = __include("core/Bits") + +local H = {} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi + + + + + + + + + + + + + + + + + + + + + + + + + + + + +H.ZIGZAG = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} + +local function ilog(v) +local n = 0 + while v > 0 do + n =n+ 1 + v = math.floor(v / 2 +) end + return n +end + +-- ------------------------------------------------------------------------------------------------ identification +-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +function H.info(b, off, len) +if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info= { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ comment +-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +function H.comment(b, off, len) +if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str() +if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p =p+ 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p =p+ n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p =p+ 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list= {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- ------------------------------------------------------------------------------------------------ Huffman trees +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br) -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + +local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len =len+ 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves =nleaves+ 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + -- insert the leaf + local n = 1 + for d = 1, len do + local k = (math.floor(code / 2 ^ (32 - d))) % 2 + local kids = (k == 0 and{kid0 }or{kid1 +})[1] local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (math.floor(code / cb)) % 2 == 1 do + code =code- cb + cb =cb* 2 + len =len- 1 + end + if len <= 0 then + break + end + code =code+ cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out, kid0, kid1, tok) +local heights= {} + local function height(n) +local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = (kid0[n] ~= 0 and{(height(kid0[n]) )}or{0 +})[1] local c = (kid1[n] ~= 0 and{(height(kid1[n]) )}or{0 +})[1] h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n) +local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = bit32.extract(i, nb - 1 - d, 1) + local nx = (bit == 0 and{kid0[cur] }or{kid1[cur] +})[1] d =d+ 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +-- ------------------------------------------------------------------------------------------------ setup +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +function H.setup(b, off, len) +if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms= {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges= {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = math.floor(i / 3), i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi =qi+ s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in __iter(idx) do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = (qri == #r.sizes and((qi + 1 ))or((qi + r.sizes[qri + 1] +))) while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (math.floor(dcScale[qi + 1] * base[1] / 100)) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (math.floor(acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] / 100)) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi =qi+ 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = math.floor((2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) / (2 * sz) +) end + end + end + end + end + -- the 80 Huffman trees + local huff= {} + local roots= {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H +end +__FILES["codecs/video/Video"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. +-- +-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them +-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a +-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc / +-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs +-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). +-- +-- local Video = require("rosetta.codecs.video.Video") +-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" +-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) +-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) +-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP) +-- +-- Never throws: bad data / missing codecs come back as nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Video = {} + +-- ------------------------------------------------------------------------------------------------ simple decoders +-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no +-- picture to show, such as a hidden VP8 altref frame) + + + + + + + + + + +function Video.simpleDecoder(decodeOne, resetFn) +local queue= {} + local self = {} + function self.decode(_, packet) +local ok, img, err = pcall(decodeOne, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_) +local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_) end + function self.reset(_) + table.clear(queue) + if resetFn then + resetFn() + end + end + return self +end + +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged +-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / +-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) +local function rawPlanar(data, pf, bits, w, h) +local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local bps = bits > 8 and 2 or 1 + local shift = 2 ^ (bits - 8) + local function sample(o) +if bps == 1 then + return buffer.readu8(data, o) + end + return math.min(255, math.floor(buffer.readu16(data, o) / shift)) + end + for i = 0, w * h - 1 do + buffer.writeu8(px, i, sample(i * bps)) + end + local scw, sch = w, h -- source chroma plane size + if pf == "yuv420p" then + scw, sch = cw, ch + elseif pf == "yuv422p" then + scw, sch = cw, h + end + local uo, vo = w * h * bps, (w * h + scw * sch) * bps + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local i = cy * cw + cx + local u, v + if pf == "gray" then + u, v = 128, 128 + elseif pf == "yuv420p" then + u, v = sample(uo + i * bps), (sample(vo + i * bps) ) +elseif pf == "yuv422p" then + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + u = math.floor((sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) / 2 +) v = math.floor((sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) / 2 +) else + local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps + u = math.floor((sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) / 4 +) v = math.floor((sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) / 4 +) end + buffer.writeu8(px, w * h + i, u) + buffer.writeu8(px, w * h + cw * ch + i, v) + end + end + return img +end + +local PLANAR_SIZE= { + yuv420p = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yv12 = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yuv422p = function(w, h, cw, _ch) + return w * h + 2 * cw * h + end, + yuv444p = function(w, h) + return w * h * 3 + end, + yuva444p = function(w, h) + return w * h * 4 + end, + gray = function(w, h) + return w * h + end, +} + +local function rawDecoder(track, _opts) +local w, h = track.width or 0, track.height or 0 + if w <= 0 or h <= 0 or w * h > 2 ^ 26 then + return nil, Err.new(Err.CORRUPT, "raw video without a valid size") + end + local pf = track.pixelFormat or "yuv420p" + local bits = track.bitDepth or 8 + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local flip = track.flip == true + local planar = PLANAR_SIZE[pf] + return Video.simpleDecoder(function(data) +local n = buffer.len(data) + if planar then + local need = planar(w, h, cw, ch) * (bits > 8 and 2 or 1) + if n < need then + return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") + end + if pf == "yuv420p" and bits == 8 then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, need) + return img, nil + elseif pf == "yv12" then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, w * h) + buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) + buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) + return img, nil + end + return rawPlanar(data, pf, bits, w, h), nil + end + local bpp = (pf == "bgra" or pf == "rgba" )and 4 or 3 + local stride= track.stride or w * bpp + if n < stride * (h - 1) + w * bpp then + return nil, Err.new(Err.TRUNCATED, "raw frame too short") + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local bgr = pf == "bgr24" or pf == "bgra" + for y = 0, h - 1 do + local s = ((flip and((h - 1 - y ))or(y))) * stride + local o = y * w * 4 + for x = 0, w - 1 do + local p = s + x * bpp + local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2) + if bgr then + a, c = c, a + end + buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000) + end + end + return img, nil + end), nil +end + +local function vp8Decoder(_track, opts) +local Vp8 = __include("codecs/image/Vp8") + local dec = Vp8.newDecoder() + local o = { maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data) +local img, err = dec:decodeFrame(data, 0, buffer.len(data), o) + if not img then + return nil, err + end + local src = img.meta.source + if type(src) == "table" and src.show == false then + return nil, nil + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + return img, nil + end, function() + if dec.reset then + dec:reset() + else + dec = Vp8.newDecoder() + end + end), nil +end + +-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout +-- allows, else rgba8 +local function mjpegDecoder(_track, opts) +local Jpeg = __include("codecs/image/Jpeg") + local o= { yuv = true, maxPixels = opts and opts.maxPixels } + return Video.simpleDecoder(function(data) +local img, err = Jpeg.decode(data, 0, buffer.len(data), o) + if img and img.format == "yuv420p" then + img.meta.yuv = { range = "full", matrix = "bt601" } + end + return img, err + end), nil +end + +-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first +local function mjpegEncode(img, opts) +local Jpeg = __include("codecs/image/Jpeg") + local src = img + if img.format == "yuv420p" then + local range = Yuv.info(img) + if range ~= "full" then + src = Yuv.toFullRange(img) + end + end + return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) +end + +-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display +local function mpeg2Decoder(track, opts) +local Mpeg2 = __include("codecs/video/Mpeg2") + return Mpeg2.newVideoDecoder(track, opts) +end + +-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); +-- pictures in display order with the pts of their packet +local function h264Decoder(track, opts) +local H264 = __include("codecs/video/H264") + return H264.newVideoDecoder(track, opts) +end + +-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering +local function h263Decoder(track, opts) +local H263 = __include("codecs/video/H263") + local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) + return Video.simpleDecoder(function(data) +return dec:image(data) + end, function() + dec:reset() + end), nil +end + +-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv +-- builds the same); one picture per packet, empty packets repeat the previous one +local function theoraDecoder(track, opts) +local Theora = __include("codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + +-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) +local function legacyDecoder(id) +return function(track, opts) +return __include("codecs/video/Legacy").newDecoder(id, track, opts) + end +end + +-- ------------------------------------------------------------------------------------------------ registry +-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. +local BUILTIN= { + { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, + { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder }, + { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder }, + { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, + { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, + { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, + { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, + { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, + { id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder }, + { id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder }, + { id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } }, + { id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } }, + { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, + { id = "flashsv2", name = "Flash Screen Video 2" }, + { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, +} + +local byId= {} +local byFourcc= {} +local byMatroska= {} + +-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it +function Video.register(entry) +if type(entry) ~= "table" or type(entry.id) ~= "string" then + return false, Err.new(Err.ARG, "register: needs an entry with an id") + end + local old = byId[entry.id] + if old and entry.new == nil then + entry.new = old.new + end + byId[entry.id] = entry + for _, f in __iter(entry.fourcc or {}) do + byFourcc[f] = entry.id + end + for _, m in __iter(entry.matroska or {}) do + byMatroska[m] = entry.id + end + return true, nil +end +for _, e in __iter(BUILTIN) do + Video.register(e) +end + +-- the registry (read only by convention): id -> Entry +Video.codecs = byId + +-- fromFourcc(fourcc) -> codec id | nil +function Video.fromFourcc(fcc) +return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] +end + +-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...) +function Video.fromMatroska(id) +return byMatroska[id] +end + +-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil +function Video.entry(id) +return byId[id] +end + +-- canDecode(codecId) -> boolean +function Video.canDecode(id) +local e = byId[id] + return e ~= nil and e.new ~= nil +end + +-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered) +function Video.decoder(track, opts) +local e = byId[track.codec] + if not e or not e.new then + return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec)) + end + local ok, dec, err = pcall(e.new , track, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec)) + end + return dec, err +end + +-- ------------------------------------------------------------------------------------------------ VideoDecoder +local function toRGBA(_self, f) +local img = (type(f) == "table" and f.image and{f.image }or{f +})[1] local out = Yuv.imageToRgba(img) + return out or img +end + +-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through +-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and +-- the demuxer (remuxing) and audio work. + + + + + + + + + + + + + + +function Video.open(demuxer, opts) +local o= opts or {} + local track= nil + if o.track then + for _, t in __iter(demuxer.tracks) do + if t.id == o.track then + track = t + end + end + if not track then + return nil, Err.new(Err.ARG, "no track " .. tostring(o.track)) + end + else + track = demuxer:track("video") + end + local codec= nil + local codecErr= nil + if track then + codec, codecErr = Video.decoder(track, o) + else + codecErr = Err.new(Err.UNSUPPORTED, "no video track") + end + local v= { + kind = "video", + format = demuxer.format, + codec = (track and{track.codec }or{"none"})[1], + width = (track and{track.width or 0 }or{0})[1], + height = (track and{track.height or 0 }or{0})[1], + frameRate = (track and{track.frameRate or 0 }or{0})[1], + frames = (track and{track.frames or 0 }or{0})[1], + duration = (track and track.duration and track.duration > 0 and{track.duration }or{demuxer.duration})[1], + track = track, + demuxer = demuxer, + meta = demuxer.meta or {}, + decodeError = codecErr, + toRGBA = toRGBA, + } + if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then + v.frames = math.floor(v.duration * v.frameRate + 0.5) + end + -- audio + if o.audio ~= false then + local at = demuxer:track("audio") + if at then + if o.openAudio then + local ok, dec, err = pcall(o.openAudio, demuxer, at) + if ok and dec then + v.audio = dec + else + v.audioError = (ok and{err }or{(Err.new(Err.CORRUPT, "audio: " .. tostring(dec)) +)})[1] end + else + v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)") + end + end + end + local index, flushed, skipUntil = 0, false, -math.huge + local tid = (track and{track.id }or{(-1 +)})[1] local scale= (track and track.timescale and track.timescale > 0 and{track.timescale }or{1000 +})[1] local start = demuxer.startTime or 0 + v.startTime = start + local defaultDur = (v.frameRate > 0 and((1 / v.frameRate ))or(0 +)) local lastPts = nil +function v.nextFrame(self) +if not codec then + return nil, codecErr + end + local dec = codec +while true do + local img, pts, key = dec:receive() + if img then + local t = (pts or 0) / scale - start + if t + 1e-9 >= skipUntil then + if index < 0 then + -- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); + -- without a frame rate, counted from the seek) + index = (v.frameRate > 0 and{(math.max(0, math.floor(t * v.frameRate + 0.5)) )}or{0 +})[1] end + index =index+ 1 + local d = defaultDur + if lastPts and t > (lastPts ) and defaultDur == 0 then + d = t - (lastPts ) + end + lastPts = t + local maxSide = o.maxSide + if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then + local hook= o.yield + if hook then + pcall(hook) + end + local s = maxSide / math.max(img.width, img.height) + img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5))) + end + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil + end + else + local p = demuxer:read(tid) + if p == nil then + if flushed then + return nil, nil + end + flushed = true + dec:flush() + else + local err = dec:decode(p) + if err then + return nil, err + end + end + end + end + end + function v.seek(self, seconds) + demuxer:seek(seconds + start) + if codec then + codec:reset() + end + flushed = false + skipUntil = seconds + lastPts = nil + index = -1 -- recomputed from the first frame's time + if self.audio then + pcall(self.audio.seek, self.audio, seconds) + end + end + function v.reset(self) + self:seek(0) + skipUntil = -math.huge + index = 0 + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ frames-backed +-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after +-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded. +function Video.fromFrames(images, delays, opts) +if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then + return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") + end + local w, h = images[1].width, images[1].height + local pts= {} + local durs= {} + local t = 0 + for i, img in __iter(images) do + if type(img) ~= "table" or img.width ~= w or img.height ~= h then + return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image") + end + local d = (type(delays) == "table" and{delays[i] or 0.1 }or{(delays or 0.1) +})[1] if type(d) ~= "number" or d ~= d or d < 0 then + d = 0.1 + end + pts[i] = t + durs[i] = d + t =t+ d + end + local n = #images + local o = opts or {} + local v= { + kind = "video", + format = o.format or "frames", + codec = "frames", + width = w, + height = h, + frameRate = (t > 0 and((n / t ))or(10)), + frames = n, + duration = t, + loops = o.loops, + meta = o.meta or {}, + toRGBA = toRGBA, + images = images, + } + local i = 0 + function v.nextFrame(self) +i =i+ 1 + if i > n then + i = n + return nil, nil + end + local img = images[i] + if o.rgba then + img = Yuv.imageToRgba(img) or img + end + return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil + end + function v.seek(self, seconds) + local k = 0 + for j = 1, n do + if pts[j] <= seconds + 1e-9 then + k = j - 1 + end + end + i = k + end + function v.reset(self) + i = 0 + end + return v, nil +end + +return Video +end +__FILES["codecs/video/Video/Source"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either +-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, +-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw +-- yuv420p frames, PCM audio from the audio Decoder). New in rosetta. +-- +-- local streams, err = Source.streams(value, opts, { +-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any) +-- audio = { copy = { opus = true, vorbis = true }, pcm = true }, +-- }) +-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config, +-- -- track, packets = { { pts, duration (seconds), keyframe, data } } } +local Err = __include("core/Err") +local Types = __include("Types") +local Yuv = __include("codecs/image/Yuv") + +local Source = {} + + + + + + + + + + + + + + + + + + + + + +local function allows(set, codec) +return set ~= nil and (set[codec] == true or set["*"] == true) +end + +-- the packets of a source track, times in seconds +local function copyPackets(dmx, track) +local out = {} + local scale = (track.timescale and track.timescale > 0 and{track.timescale }or{1 +})[1] local n = dmx:count(track.id) + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data }) + end + end + return out +end + +local function trackStream(track, packets) +return { + kind = track.kind , + codec = track.codec, + copied = true, + width = track.width, + height = track.height, + frameRate = track.frameRate, + sampleRate = track.sampleRate, + channels = track.channels, + bitsPerSample = track.bitsPerSample, + config = track.config, + track = track, + packets = packets, + } +end + +-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo": +-- yuv420p planes) +local function encodeFrames(v, codec, opts) +local encode= nil + if codec ~= "rawvideo" then + local Video = __include("codecs/video/Video") + local e = Video.entry(codec) + encode = e and e.encode + if not encode then + return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder") + end + end + if type(v.reset) == "function" then + v:reset() + end + local packets= {} + local w, h = v.width, v.height + local maxFrames = opts.maxFrames or math.huge + while #packets < maxFrames do + local f, err = v:nextFrame() + if not f then + if err then + return nil, err + end + break + end + local img= f.image + if (w == 0 or h == 0) and #packets == 0 then + w, h = img.width, img.height + end + if img.width ~= w or img.height ~= h then + return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")") + end + local data +if codec == "rawvideo" then + local y = (img.format == "yuv420p" and{img }or{(Yuv.imageFromRgba(img, "limited", "bt601") +)})[1] if not y then + return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format) + end + data = y.pixels + else + local e2 + data, e2 = (encode )(img, opts) + if not data then + return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode") + end + end + table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data }) + end + if #packets == 0 then + return nil, Err.new(Err.ARG, "no frames to write") + end + local fr = v.frameRate + if not fr or fr <= 0 then + local d = packets[1].duration + fr = (d > 0 and((1 / d ))or(25 +)) end + return { + kind = "video", + codec = codec, + copied = false, + width = w, + height = h, + frameRate = fr, + packets = packets, + } , nil +end + +-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096) +local function pcmFrom(dec, opts) +local ch, rate = dec.channels, dec.sampleRate + if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then + return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate") + end + pcall(dec.seek, dec, 0) + local chunk = opts.audioChunk or 4096 + local packets= {} + local pos = 0 + local tmp= nil + while true do + local ok, out, n = pcall(dec.read, dec, chunk, tmp) + if not ok or not out or not n or n <= 0 then + break + end + tmp = out + local data = buffer.create(n * ch * 2) + for i = 0, n * ch - 1 do + local s = buffer.readf32(out, i * 4) + local v = math.floor(s * 32768 + 0.5) + if v > 32767 then + v = 32767 + elseif v < -32768 then + v = -32768 + elseif v ~= v then + v = 0 + end + buffer.writei16(data, i * 2, v) + end + table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data }) + pos =pos+ n + end + return { + kind = "audio", + codec = "pcm_s16le", + copied = false, + sampleRate = rate, + channels = ch, + bitsPerSample = 16, + packets = packets, + } , nil +end + +-- streams(value, opts, want) -> { Stream } | nil, Err +function Source.streams(value, opts, want) +local o = opts or {} + if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then + return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer") + end + local dmx = (value.kind == "demuxer" and{value }or{value.demuxer +})[1] local out= {} + -- video + local vt= (value.kind == "video" and{value.track }or{(dmx and dmx:track("video")) +})[1] local wv = want.video + if wv and o.video ~= false then + if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then + table.insert(out, trackStream(vt, copyPackets(dmx, vt))) + elseif value.kind == "video" and wv.encode then + local s, err = encodeFrames(value, wv.encode, o) + if not s then + return nil, err + end + table.insert(out, s) + elseif vt then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (wv.encode and"" or" (this container cannot take it and it cannot be re-encoded)")) + end + end + -- audio + local wa = want.audio + if wa and o.audio ~= false then + local at= dmx and dmx:track("audio") + if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then + table.insert(out, trackStream(at, copyPackets(dmx, at))) + elseif wa.pcm and value.kind == "video" and value.audio then + local s, err = pcmFrom(value.audio, o) + if not s then + return nil, err + end + if #s.packets > 0 then + table.insert(out, s) + end + elseif at and o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container") + end + end + if #out == 0 then + return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)") + end + return out, nil +end + +-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +function Source.rational(fps) +if fps ~= fps or fps <= 0 then + return 25, 1 + end + if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then + return math.floor(fps + 0.5), 1 + end + local ntsc = fps * 1001 / 1000 + if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then + return math.floor(ntsc + 0.5) * 1000, 1001 + end + return math.floor(fps * 1000 + 0.5), 1000 +end + +-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the +-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet +-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) +function Source.constantRate(s, maxFps) +local fd = math.huge + for _, p in __iter(s.packets) do + if p.duration and p.duration > 0 and p.duration < fd then + fd = p.duration + end + end + if fd == math.huge then + fd = (s.frameRate and s.frameRate > 0 and((1 / s.frameRate ))or(0.04 +)) end + fd = math.max(fd, 1 / (maxFps or 100)) + local num, den = Source.rational(1 / fd) + local step = den / num + local out= {} + local slots = 0 + local t0 = (s.packets[1] and{s.packets[1].pts }or{0 +})[1] for _, p in __iter(s.packets) do + local stop = p.pts - t0 + ((p.duration and p.duration > 0 and{p.duration }or{step})[1]) + local n = math.max(1, math.floor(stop / step + 0.5) - slots) + for _ = 1, n do + table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data }) + slots =slots+ 1 + end + end + return num, den, out +end + +-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its +-- own order +function Source.interleave(streams) +local order = {} + local pos = table.create(#streams, 1) + while true do + local best, bt = 0, math.huge + for si, s in __iter(streams) do + local p = s.packets[pos[si] ] + if p then + local t = p.dts or p.pts + if best == 0 or t < bt then + best, bt = si, t + end + end + end + if best == 0 then + break + end + table.insert(order, { best, streams[best].packets[pos[best] ] }) + pos[best]=pos[best]+ 1 + end + return order +end + +return Source +end +__FILES["containers/Archive"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data +-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder +-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be +-- encoded by any writable archive format through its list() / read(). +-- +-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err +-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 }) +-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end }) +-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write() +-- +-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them +-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. +local Err = __include("core/Err") +local Types = __include("Types") +local Tar = __include("containers/Tar") + +local Archive = {} +-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source + + + + + + + + + + + + + + +local Methods = {} +Methods.__index = Methods + +-- the public fields of an entry (no data / loader) +local function public(e) +local out= {} + for k, v in __iter(e) do + if k ~= "data" and k ~= "load" then + out[k] = v + end + end + return out +end + +function Methods.list(self) +local out = (table.create(#self._entries) ) +for i, e in __iter(self._entries) do + out[i] = public(e) + end + return out +end + +-- read(name) -> buffer | nil, Err (directories read as an empty buffer) +function Methods.read(self, name) +local e= self._byName[name] + if not e then + return nil, Err.new(Err.ARG, "no entry named " .. tostring(name)) + end + if e.data then + return e.data, nil + end + if e.load then + local ok, b, err = pcall(e.load) + if not ok then + return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b)) + end + if not b then + return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed") + end + return b, nil + end + return buffer.create(0), nil +end + +-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name +function Methods.add(self, name, data, opts) + local b= (type(data) == "string" and{(buffer.fromstring(data) )}or{(type(data) == "buffer" and{data }or{(buffer.create(0) +)})[1]})[1] local o = opts or {} + local e= { + name = name, + size = buffer.len(b), + dir = o.dir == true, + mtime = o.mtime, + mode = o.mode, + data = b, + } + Archive.put(self, e) +end + +-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api) +function Methods.write(self, opts) +local enc= self._encode + if not enc then + return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only") + end + return enc(self, opts) +end + +-- new(format, encode?) -> an empty Archive +function Archive.new(format, encode) +return setmetatable({ + kind = "archive", + format = format, + meta = {}, + _entries = {} , + _byName = {} , + _encode = encode, + }, Methods) +end + +-- put(archive, entry): append (or replace by name) an entry +function Archive.put(a, e) + local old = a._byName[e.name] + if old then + local i = table.find(a._entries, old) + if i then + a._entries[i] = e + end + else + table.insert(a._entries, e) + end + a._byName[e.name] = e +end + +-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another +-- format's): what encoders iterate. nil when the value is not an archive. +function Archive.entries(value) +if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then + return nil + end + local ok, list = pcall(value.list, value) + if not ok or type(list) ~= "table" then + return nil + end + local out = {} + for _, e in __iter(list) do + if type(e) == "table" and type(e.name) == "string" then + table.insert(out, { + entry = e, + read = function() +local rok, b, err = pcall(value.read, value, e.name) + if not rok then + return nil, Err.new(Err.CORRUPT, tostring(b)) + end + return b, err + end, + }) + end + end + return out +end + +-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) +function Archive.slice(buf, at, n) +return function() +local out = buffer.create(n) + buffer.copy(out, 0, buf, at, n) + return out, nil + end +end + +-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read +-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) +function Archive.collect(value) +local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out= {} + for _, it in __iter(items) do + local b= buffer.create(0) + if not it.entry.dir then + local d, err = it.read() + if not d then + return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed") + end + b = d + end + table.insert(out, { entry = it.entry, data = b }) + end + return out, nil +end + +-- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value, +-- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take. +function Archive.files(value, name) +if type(value) == "buffer" or type(value) == "string" then + local b = (type(value) == "string" and{(buffer.fromstring(value) )}or{value +})[1] return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + local out = {} + for _, it in __iter(items) do + if not it.entry.dir then + local b, err = it.read() + if not b then + return nil, err + end + table.insert(out, { name = it.entry.name, data = b, entry = it.entry }) + end + end + return out, nil +end + +-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or +-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err +function Archive.streamData(value) +if type(value) == "buffer" then + return value, nil + elseif type(value) == "string" then + return buffer.fromstring(value), nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + if #items == 1 and not items[1].entry.dir then + return items[1].read() + end + local list = {} + for _, it in __iter(items) do + local e= it.entry + local data= nil + if not e.dir and (e.type == nil or e.type == "0") then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local typ = (type(e.type) == "string" and #e.type == 1 and{e.type }or{nil +})[1] table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode }) + end + return Tar.write(list) +end + +-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store +-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date +function Archive.fromDos(stamp) +local time, date = stamp % 65536, math.floor(stamp / 65536 +) local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) + if date == 0 or m < 1 or m > 12 or d < 1 then + return nil + end + local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 + return Types.Date.daysFromCivil(y, m, d) * 86400 + secs +end + +-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31) +function Archive.toDos(t) +if type(t) ~= "number" or t ~= t or t < 315532800 then + return 0x210000 -- 1980-01-01 00:00 + end + local s = math.floor(t) + local days = math.floor(s / 86400 +) local rem = s - days * 86400 + local y, m, d = Types.Date.civilFromDays(days) + if y > 2107 then + y, m, d, rem = 2107, 12, 31, 86398 + end + return ((y - 1980) * 512 + m * 32 + d) * 65536 + (math.floor(rem / 3600)) * 2048 + ((math.floor(rem / 60)) % 60) * 32 + math.floor((rem % 60) / 2 +)end + +-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension +-- (".tgz" -> ".tar"), else "data" +function Archive.streamName(opts, exts) +local name = (type(opts) == "table" and type(opts.name) == "string" and{opts.name }or{nil +})[1] if not name then + return "data" + end + local base = string.match(name, "([^/\\]+)$") or name + local stem, ext = string.match(base, "^(.+)%.([%w]+)$") + if stem and ext then + local e = string.lower(ext) + if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then + return stem .. ".tar" + end + if table.find(exts, e) then + return stem + end + end + return base +end + +return Archive +end +__FILES["containers/AudioWrap"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/AudioWrap: an audio track of a video container (a Types.Demuxer track and its packets) as a standalone +-- stream that an audio format reads, so the api can open it with the audio formats (a format never requires another +-- format). New in rosetta. +-- PCM (pcm_u8 / s16 / s24 / s32 le and be, f32 / f64, alaw, mulaw) -> WAV (big-endian samples byte-swapped); +-- an AVI audio track with its WAVEFORMATEX (track.waveFormat: IMA / MS ADPCM, ...) -> WAV with that fmt chunk; +-- adpcm_swf (Flash ADPCM, FLV SoundFormat 1) -> decoded through codecs/audio/Adpcm into a float WAV; +-- mp3 / mp2 / mp1 -> the frames back to back (format "mp3"); +-- flac -> "fLaC" + the metadata blocks (CodecPrivate / dfLa) + the frames; +-- opus -> Ogg Opus (OpusHead from the config or made up, OpusTags, packets with granules from their TOC durations); +-- vorbis -> Ogg Vorbis (the three headers from Matroska's Xiph-laced CodecPrivate or MP4's esds-less layout); +-- aac -> ADTS (from the AudioSpecificConfig) for audio/aac; +-- ac3 -> the syncframes back to back (format "ac3"; E-AC-3 tracks stay UNSUPPORTED). +-- +-- local buf, format, err = AudioWrap.wrap(demuxer, track) -- then F.open(buf, { format = format }) +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mux = __include("containers/Ogg/Mux") +local Adpcm = __include("codecs/audio/Adpcm") + +local AudioWrap = {} + + + + + + +local function allPackets(dmx, track) +local out= {} + local n = (dmx.count and{(dmx:count(track.id) )}or{0 +})[1] if n > 0 and dmx.get then + for k = 1, n do + local p = dmx:get(track.id, k) + if p then + table.insert(out, p) + end + end + end + return out +end + +local function concat(packets, prefix) +local total = (prefix and{(buffer.len(prefix) )}or{0 +})[1] for _, p in __iter(packets) do + total =total+ buffer.len(p.data) + end + local out = buffer.create(total) + local o = 0 + if prefix then + buffer.copy(out, 0, prefix) + o = buffer.len(prefix) + end + for _, p in __iter(packets) do + buffer.copy(out, o, p.data) + o =o+ buffer.len(p.data) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ WAV +local PCM= { -- tag, bits, bytes swapped (big-endian source) + pcm_u8 = { 1, 8, 0 }, + pcm_s8 = { 1, 8, 0 }, + pcm_s16le = { 1, 16, 0 }, + pcm_s24le = { 1, 24, 0 }, + pcm_s32le = { 1, 32, 0 }, + pcm_s16be = { 1, 16, 1 }, + pcm_s24be = { 1, 24, 1 }, + pcm_s32be = { 1, 32, 1 }, + pcm_f32le = { 3, 32, 0 }, + pcm_f64le = { 3, 64, 0 }, + pcm_f32be = { 3, 32, 1 }, + pcm_f64be = { 3, 64, 1 }, + pcm_alaw = { 6, 8, 0 }, + pcm_mulaw = { 7, 8, 0 }, +} + +local function wav(fmt, data) +local w = Bytes.writer(buffer.len(data) + buffer.len(fmt) + 64) + local fl = buffer.len(fmt) + local dl = buffer.len(data) + w:string("RIFF") + w:u32le(4 + 8 + fl + (fl % 2) + 8 + dl + (dl % 2)) + w:string("WAVE") + w:string("fmt ") + w:u32le(fl) + w:bytes(fmt) + if fl % 2 == 1 then + w:u8(0) + end + w:string("data") + w:u32le(dl) + w:bytes(data) + if dl % 2 == 1 then + w:u8(0) + end + return w:finish() +end + +local function pcmWav(track, packets) +local spec = PCM[track.codec] + local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "PCM track without channels / sample rate") + end + local bits = spec[2] + local data = concat(packets) + if spec[3] == 1 then + local bps = math.floor(bits / 8 +) for i = 0, buffer.len(data) - bps, bps do + for k = 0, math.floor(bps / 2 )- 1 do + local a, b = buffer.readu8(data, i + k), buffer.readu8(data, i + bps - 1 - k) + buffer.writeu8(data, i + k, b) + buffer.writeu8(data, i + bps - 1 - k, a) + end + end + end + if track.codec == "pcm_s8" then + for i = 0, buffer.len(data) - 1 do + buffer.writeu8(data, i, (buffer.readu8(data, i) + 128) % 256) + end + end + local f = Bytes.writer(16) + local align = math.floor(ch * bits / 8 +) f:u16le(spec[1]) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * align) + f:u16le(align) + f:u16le(bits) + return wav(f:finish(), data), nil +end + +-- Flash ADPCM packets decode on their own (each starts with its code size and block headers): f32 samples in a WAV +local function swfWav(track, packets) +local ch = track.channels or 1 + local rate = math.floor((track.sampleRate or 0) + 0.5) + if ch < 1 or ch > 2 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "Flash ADPCM track without channels / sample rate") + end + local frames = 0 + for _, pk in __iter(packets) do + frames =frames+ Adpcm.swfFrames(pk.data, 0, buffer.len(pk.data), ch) + end + local data = buffer.create(frames * ch * 4) + local d = 0 + for _, pk in __iter(packets) do + d =d+ Adpcm.swf(pk.data, 0, buffer.len(pk.data), ch, data, d) * ch + end + local f = Bytes.writer(16) + f:u16le(3) + f:u16le(ch) + f:u32le(rate) + f:u32le(rate * ch * 4) + f:u16le(ch * 4) + f:u16le(32) + return wav(f:finish(), data), nil +end + +-- ------------------------------------------------------------------------------------------------ Ogg +-- the number of 48 kHz samples in an Opus packet (RFC 6716 section 3.1) +local function opusSamples(b) +local n = buffer.len(b) + if n < 1 then + return 0 + end + local toc = buffer.readu8(b, 0) + local config = math.floor(toc / 8 +) local fs +if config < 12 then + fs = ({ 480, 960, 1920, 2880 })[config % 4 + 1] + elseif config < 16 then + fs = config % 2 == 0 and 480 or 960 + else + fs = ({ 120, 240, 480, 960 })[config % 4 + 1] + end + local c = toc % 4 + local frames = c == 0 and 1 or(c == 3 and{((n >= 2 and{(buffer.readu8(b, 1) % 64 )}or{0})[1]) }or{2 +})[1] return fs * frames +end + +local function opusHead(track) +local c = track.config + if c and buffer.len(c) >= 19 and buffer.readstring(c, 0, 8) == "OpusHead" then + return c + end + local w = Bytes.writer(19) + w:string("OpusHead") + w:u8(1) + w:u8(math.clamp(track.channels or 2, 1, 2)) + w:u16le(math.floor((track.codecDelay or 0) * 48000 + 0.5)) + w:u32le(math.floor(track.sampleRate or 48000)) + w:u16le(0) + w:u8(0) + return w:finish() +end + +local function opusTags() +local w = Bytes.writer(32) + w:string("OpusTags") + local vendor = "rosetta" + w:u32le(#vendor) + w:string(vendor) + w:u32le(0) + return w:finish() +end + +local function ogg(headers, packets, granuleOf) +local mux = Mux.new({ pageSize = 4096 }) + local s = mux:stream(1) + for i, h in __iter(headers) do + s:packet(h, 0, { flush = i == 1 or i == #headers }) + end + for i, p in __iter(packets) do + s:packet(p.data, granuleOf(p, i), { eos = i == #packets }) + end + return mux:finish() +end + +-- Matroska's Vorbis CodecPrivate: Xiph-laced headers (count - 1, sizes, data) +local function xiphHeaders(c) +local n = buffer.len(c) + if n < 3 then + return nil + end + local count = buffer.readu8(c, 0) + 1 + local p = 1 + local sizes = {} + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + p =p+ 1 + s =s+ b + if b ~= 255 then + break + end + end + sizes[k] = s + total =total+ s + end + sizes[count] = n - p - total + if sizes[count] < 0 then + return nil + end + local out = {} + for k = 1, count do + local b = buffer.create(sizes[k]) + buffer.copy(b, 0, c, p, sizes[k]) + p =p+ sizes[k] + out[k] = b + end + return out +end + +-- Vorbis packet sizes: the block sizes from the identification header and each mode's block flag from the end of the +-- setup header (read backwards from its framing bit: mode entries are 41 bits whose window / transform types are 0, +-- preceded by the 6-bit mode count), so the Ogg granules are exact: a packet yields (previous + current block) / 4 +-- samples (the first one as if its previous block had its own size, as ffmpeg times it). +local function bit(b, k) +return bit32.extract(buffer.readu8(b, math.floor(k / 8)), k % 8, 1) +end +local function bits(b, k, n) +local v = 0 + for i = n - 1, 0, -1 do + v = v * 2 + bit(b, k + i) + end + return v +end + +local function vorbisModes(id, setup) +if buffer.len(id) < 30 or buffer.len(setup) < 8 then + return nil, nil + end + local bs = buffer.readu8(id, 28) + local sizes = { 2 ^ (bs % 16), 2 ^ (math.floor(bs / 16)) } + -- the framing bit: the highest set bit of the last non-zero byte + local last = buffer.len(setup) - 1 + while last > 0 and buffer.readu8(setup, last) == 0 do + last =last- 1 + end + local v = buffer.readu8(setup, last) + local hb = 7 + while hb > 0 and bit32.extract(v, hb, 1) == 0 do + hb =hb- 1 + end + local f = last * 8 + hb + local flags= {} + local pos = f + while #flags < 64 and pos - 41 >= 7 * 8 do + local s0 = pos - 41 + if bits(setup, s0 + 1, 16) ~= 0 or bits(setup, s0 + 17, 16) ~= 0 then + break + end + table.insert(flags, 1, bit(setup, s0) == 1) + pos = s0 + end + -- the largest count whose 6-bit field matches + for n = #flags, 1, -1 do + local start = f - 41 * n + if start - 6 >= 0 and bits(setup, start - 6, 6) == n - 1 then + local out = {} + for i = #flags - n + 1, #flags do + table.insert(out, flags[i]) + end + return sizes, out + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ ADTS +local function adts(track, packets) +local c = track.config + local profile, rateIndex, chanConfig + if c and buffer.len(c) >= 2 then + local b0, b1 = buffer.readu8(c, 0), buffer.readu8(c, 1) + profile = math.floor(b0 / 8 -- audio object type +) rateIndex = (b0 % 8) * 2 + math.floor(b1 / 128 +) chanConfig = (math.floor(b1 / 8)) % 16 + else + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + profile = 2 + rateIndex = 4 + for i, r in __iter(rates) do + if r == math.floor((track.sampleRate or 44100) + 0.5) then + rateIndex = i - 1 + end + end + chanConfig = track.channels or 2 + end + if profile < 1 or profile > 4 or rateIndex > 12 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. tostring(profile) .. " in ADTS") + end + local w = Bytes.writer(64) + for _, p in __iter(packets) do + local len = buffer.len(p.data) + 7 + w:u8(0xFF) + w:u8(0xF1) + w:u8((profile - 1) * 64 + rateIndex * 4 + math.floor(chanConfig / 4)) + w:u8((chanConfig % 4) * 64 + (math.floor(len / 2048)) % 4) + w:u8((math.floor(len / 8)) % 256) + w:u8((len % 8) * 32 + 0x1F) + w:u8(0xFC) + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ trim +-- trim(decoder, frames, length?) -> an audio Decoder that drops the first `frames` sample frames (a container's +-- codec delay: Matroska CodecDelay, an MP4 edit's media time for MP2 / MP3 / AAC, which ffmpeg drops too; Opus +-- handles its pre-skip itself) and, with length, ends after that many frames (an MP4 edit's length: end padding) +function AudioWrap.trim(dec, skip, length) +if skip <= 0 and length == nil then + return dec + end + skip = math.max(0, skip) + local rate = dec.sampleRate + local w= setmetatable({}, { __index = dec }) + w.frames = math.max(0, (dec.frames or 0) - skip) + if length then + w.frames = ((dec.frames or 0) > 0 and{(math.min(w.frames, length) )}or{length +})[1] end + w.duration = w.frames / rate + local cap = length or math.huge + local delivered = 0 + local function drop() + local left = skip + while left > 0 do + local _, n = dec:read(math.min(left, 4096)) + if not n or n <= 0 then + break + end + left =left- n + end + end + local started = false + function w.read(_, n, out) +if not started then + started = true + drop() + end + local want = math.min(n, cap - delivered) + if want <= 0 then + return out or buffer.create(0), 0 + end + local b, got = dec:read(want, out) + delivered =delivered+ got + return b, got + end + function w.seek(_, seconds) + started = true + if seconds <= 0 then + dec:seek(0) + drop() + delivered = 0 + else + dec:seek(seconds + skip / rate) + delivered = math.floor(seconds * rate + 0.5) + end + end + function w.position(_) +return math.max(0, dec:position() - skip / rate) + end + return w +end + +-- ------------------------------------------------------------------------------------------------ wrap +-- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err +function AudioWrap.wrap(dmx, track) +if type(track) ~= "table" or track.kind ~= "audio" then + return nil, nil, Err.new(Err.ARG, "not an audio track") + end + if track.unsupported then + return nil, nil, Err.new(Err.UNSUPPORTED, track.unsupported) + end + local codec = track.codec + local packets = allPackets(dmx, track) + if #packets == 0 then + return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") + end + if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then + return wav(track.waveFormat, concat(packets)), "wav", nil + end + if codec == "adpcm_swf" then + local b, err = swfWav(track, packets) + return b, b and"wav" or nil, err + end + if PCM[codec] then + local b, err = pcmWav(track, packets) + return b, b and"wav" or nil, err + end + if codec == "mp3" or codec == "mp2" or codec == "mp1" then + return concat(packets), "mp3", nil + end + if codec == "ac3" then + return concat(packets), "ac3", nil + end + if codec == "flac" then + local c = track.config + local prefix= nil + if c and buffer.len(c) >= 4 and buffer.readstring(c, 0, 4) == "fLaC" then + prefix = c + elseif c and buffer.len(c) >= 34 then + -- metadata blocks without the marker (MP4 dfLa payload after version / flags) + local start = buffer.len(c) >= 38 and buffer.readu8(c, 0) == 0 and buffer.readu8(c, 4) % 128 == 0 and 4 or 0 + local b = buffer.create(4 + buffer.len(c) - start) + buffer.writestring(b, 0, "fLaC") + buffer.copy(b, 4, c, start) + prefix = b + else + return nil, nil, Err.new(Err.CORRUPT, "FLAC track without its STREAMINFO") + end + return concat(packets, prefix), "flac", nil + end + if codec == "opus" then + local head = opusHead(track) + local pre = buffer.readu16(head, 10) + local g = pre + local out = ogg({ head, opusTags() }, packets, function(p) +g =g+ opusSamples(p.data) + local d = (p ).discardPadding + if type(d) == "number" and d > 0 then + return g - math.floor(d * 48000 + 0.5) -- the end trimming (WebM DiscardPadding) + end + return g + end) + return out, "opus", nil + end + if codec == "vorbis" then + local c = track.config + local headers = c and xiphHeaders(c) + if not headers or #headers ~= 3 then + return nil, nil, Err.new(Err.CORRUPT, "Vorbis track without its three headers") + end + local sizes, modes = vorbisModes(headers[1], headers[3]) + local granule, prev = 0, nil +local rate = track.sampleRate or 44100 + local scale = track.timescale + local out = ogg(headers, packets, function(p) +if not sizes or not modes then + return math.floor((p.pts + (p.duration or 0)) / scale * rate + 0.5) -- from the container's times + end + local d = p.data + if buffer.len(d) == 0 or buffer.readu8(d, 0) % 2 ~= 0 then + return granule + end + local mb = 0 + while 2 ^ mb < #(modes ) do + mb =mb+ 1 + end + local m = (mb > 0 and buffer.len(d) * 8 > mb and{(bits(d, 1, mb) )}or{0 +})[1] local cur = sizes[(modes )[m + 1] and 2 or 1] + if prev then + granule =granule+ math.floor((prev + cur) / 4 +) end + prev = cur + return granule + end) + return out, "vorbis", nil + end + if codec == "aac" then + if track.adts then + return concat(packets), "aac", nil -- already ADTS (MPEG-TS) + end + local b, err = adts(track, packets) + return b, b and"aac" or nil, err + end + return nil, nil, Err.new(Err.UNSUPPORTED, "no audio format for codec " .. tostring(codec)) +end + +return AudioWrap +end +__FILES["containers/Avi"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in rosetta. +-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk +-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets +-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). +-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. +-- +-- local avi, err = Avi.read(buf, base, limit) +-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf +-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute +-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) +-- +-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Avi = {} + + + + + + + + + + + + + + + + + + + + + + + + + + +local function u32(b, o) +return readu32(b, o) +end + +-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not +-- entered); returns where it stopped +local function walk(b, p, limit, fn) +while p + 8 <= limit do + local id = readstring(b, p, 4) + local size = u32(b, p + 4) + local data = p + 8 + local ltype= nil + if (id == "LIST" or id == "RIFF") and data + 4 <= limit then + ltype = readstring(b, data, 4) + end + if data + size > limit then + size = limit - data + end + if fn(id, data, size, ltype) == false then + return p + end + p = data + size + (size % 2) + end + return p +end + +local function streamNumber(id) +local a, b = string.byte(id, 1, 2) + if not a or not b then + return nil + end + local function hex(c) +if c >= 48 and c <= 57 then + return c - 48 + elseif c >= 65 and c <= 70 then + return c - 55 + elseif c >= 97 and c <= 102 then + return c - 87 + end + return nil + end + local h, l = hex(a), hex(b) + if h and l then + return h * 16 + l + end + return nil +end +Avi.streamNumber = streamNumber + +local function parseStrl(b, data, size, index) +local s= { + index = index, + type = "", + handler = "", + flags = 0, + scale = 1, + rate = 1, + start = 0, + length = 0, + suggestedBufferSize = 0, + sampleSize = 0, + frame = { 0, 0, 0, 0 }, + strf = buffer.create(0), + chunks = {}, + } + local indx= nil + walk(b, data + 4, data + size, function(id, d, n) +if id == "strh" and n >= 48 then + s.type = readstring(b, d, 4) + s.handler = readstring(b, d + 4, 4) + s.flags = u32(b, d + 8) + s.scale = u32(b, d + 20) + s.rate = u32(b, d + 24) + s.start = u32(b, d + 28) + s.length = u32(b, d + 32) + s.suggestedBufferSize = u32(b, d + 36) + s.sampleSize = u32(b, d + 44) + if n >= 56 then + s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) } + end + elseif id == "strf" then + local f = buffer.create(n) + buffer.copy(f, 0, b, d, n) + s.strf = f + elseif id == "strn" then + local str = readstring(b, d, n) + s.name = string.match(str, "^[^%z]*") + elseif id == "indx" and n >= 24 then + indx = { d, n } + end + return nil + end) + ;(s )._indx = indx + return s +end + +-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s +local function readIndex(b, d, n, s, limit, depth) +if n < 24 or depth > 2 then + return false + end + local longsPerEntry = readu16(b, d) + local subType = readu8(b, d + 2) + local indexType = readu8(b, d + 3) + local entries = u32(b, d + 4) + if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration } + if longsPerEntry ~= 4 then + return false + end + local p = d + 24 + for _ = 1, entries do + if p + 16 > d + n then + break + end + local off = u32(b, p) + u32(b, p + 4) * 4294967296 + local size = u32(b, p + 8) + p =p+ 16 + if off > 0 and off + 8 <= limit then + local sz = math.min(u32(b, off + 4), limit - off - 8) + readIndex(b, off + 8, (size > 0 and{(math.min(sz, size) )}or{sz})[1], s, limit, depth + 1) + end + end + return #s.chunks > 0 + elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs) + if n < 24 then + return false + end + local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296 + local per = subType == 1 and 12 or 8 -- AVI_INDEX_2FIELD + local p = d + 24 + for _ = 1, entries do + if p + per > d + n then + break + end + local off = u32(b, p) + local size = u32(b, p + 4) + p =p+ per + local key = size < 0x80000000 + size =size% 0x80000000 + local at = base + off + if at >= 0 and at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = key }) + end + end + return true + end + return false +end + +-- read(buf, base, limit) -> File | nil, Err +function Avi.read(b, base, limit) +if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then + return nil, Err.new(Err.CORRUPT, "not an AVI file", base) + end + local file= { + avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 }, + streams = {}, + odml = nil, + info = {}, + index = "scan", + } + local movis= {} -- { data offset of the 'movi' fourcc, end } + local idx1= nil + local hdrl = false + -- every RIFF piece (AVI, then AVIX for OpenDML files) + walk(b, base, limit, function(id, d, n, ltype) +if id ~= "RIFF" then + return nil + end + walk(b, d + 4, d + n, function(cid, cd, cn, cltype) +if cid == "LIST" and cltype == "hdrl" and not hdrl then + hdrl = true + local si = 0 + walk(b, cd + 4, cd + cn, function(hid, hd, hn, hltype) +if hid == "avih" and hn >= 40 then + file.avih = { + microSecPerFrame = u32(b, hd), + flags = u32(b, hd + 12), + totalFrames = u32(b, hd + 16), + streams = u32(b, hd + 24), + width = u32(b, hd + 32), + height = u32(b, hd + 36), + } + elseif hid == "LIST" and hltype == "strl" then + table.insert(file.streams, parseStrl(b, hd, hn, si)) + si =si+ 1 + elseif hid == "LIST" and hltype == "odml" then + walk(b, hd + 4, hd + hn, function(oid, od, on) +if oid == "dmlh" and on >= 4 then + file.odml = { totalFrames = u32(b, od) } + end + return nil + end) + end + return nil + end) + elseif cid == "LIST" and cltype == "movi" then + table.insert(movis, { cd, cd + cn }) + elseif cid == "LIST" and cltype == "INFO" then + walk(b, cd + 4, cd + cn, function(iid, idd, inn) +file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or "" + return nil + end) + elseif cid == "idx1" and not idx1 then + idx1 = { cd, cn } + end + return nil + end) + return nil + end) + if not hdrl then + return nil, Err.new(Err.CORRUPT, "no hdrl list") + end + if #file.streams == 0 then + return nil, Err.new(Err.CORRUPT, "no streams") + end + -- 1. OpenDML indexes + local odml = true + for _, s in __iter(file.streams) do + local ix = (s )._indx + if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then + odml = false + end + end + if odml then + file.index = "odml" + else + for _, s in __iter(file.streams) do + table.clear(s.chunks) + end + -- 2. idx1 + local ok = false + if idx1 and movis[1] then + local d, n = idx1[1], idx1[2] + local count = math.floor(n / 16 +) local moviBase = movis[1][1] -- the 'movi' fourcc + -- relative or absolute offsets: check the first entry that points at a chunk id + local rel = true + if count > 0 then + local off = u32(b, d + 8) + local ckid = readstring(b, d, 4) + local relAt, absAt = moviBase + off, base + off + if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then + rel = true + elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then + rel = false + end + end + for k = 0, count - 1 do + local e = d + k * 16 + local ckid = readstring(b, e, 4) + local flags = u32(b, e + 4) + local off = u32(b, e + 8) + local size = u32(b, e + 12) + local sn = streamNumber(ckid) + local s = sn and file.streams[sn + 1] + if s and string.sub(ckid, 3, 4) ~= "pc" then + local at = ((rel and{moviBase }or{base})[1]) + off + 8 + if at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 }) + ok = true + end + end + end + end + if ok then + file.index = "idx1" + else + for _, s in __iter(file.streams) do + table.clear(s.chunks) + end + -- 3. scan the movi lists + local function scan(d0, e0) + walk(b, d0, e0, function(id, d, n, ltype) +if id == "LIST" and ltype == "rec " then + scan(d + 4, d + n) + return nil + end + local sn = streamNumber(id) + local s = sn and file.streams[sn + 1] + if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then + table.insert(s.chunks, { offset = d, size = n, key = true }) + end + return nil + end) + end + for _, m in __iter(movis) do + scan(m[1] + 4, m[2]) + end + file.index = "scan" + end + end + for _, s in __iter(file.streams) do + (s )._indx = nil + end + return file, nil +end +-- ------------------------------------------------------------------------------------------------ writing +-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order + + + + + + + + + + + + + + + + + + + + + + +function Avi.write(opts, chunks) +local ns = #opts.streams + local lengths = table.create(ns, 0) + local maxChunk = table.create(ns, 0) + local bytes = table.create(ns, 0) + local total = 0 + for _, c in __iter(chunks) do + local si, data = c[1], c[2] + local n = buffer.len(data) + local s = opts.streams[si] + if s.sampleSize > 0 then + lengths[si]=lengths[si]+ math.floor(n / s.sampleSize +) else + lengths[si]=lengths[si]+ 1 + end + bytes[si]=bytes[si]+ n + if n > maxChunk[si] then + maxChunk[si] = n + end + total =total+ (n + 8 + (n % 2) +) end + local frames = 0 + for si, s in __iter(opts.streams) do + if s.type == "vids" and frames == 0 then + frames = lengths[si] + end + end + local w = Bytes.writer(total + 4096 + #chunks * 16) + w:string("RIFF") + local riffSize = w:tell() + w:u32le(0) + w:string("AVI ") + -- hdrl + w:string("LIST") + local hdrlSize = w:tell() + w:u32le(0) + w:string("hdrl") + w:string("avih") + w:u32le(56) + local duration = (opts.microSecPerFrame > 0 and((frames * opts.microSecPerFrame / 1e6 ))or(1 +)) local maxBytes = 0 + for si = 1, ns do + maxBytes =maxBytes+ bytes[si] + end + w:u32le(math.floor(opts.microSecPerFrame + 0.5)) + w:u32le((duration > 0 and{(math.floor(maxBytes / duration) )}or{0})[1]) + w:u32le(0) -- padding granularity + w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED + w:u32le(frames) + w:u32le(0) -- initial frames + w:u32le(ns) + local suggested = 0 + for si = 1, ns do + suggested = math.max(suggested, maxChunk[si] + 8) + end + w:u32le(suggested) + w:u32le(opts.width) + w:u32le(opts.height) + for _ = 1, 4 do + w:u32le(0) + end + for si, s in __iter(opts.streams) do + w:string("LIST") + local strlSize = w:tell() + w:u32le(0) + w:string("strl") + w:string("strh") + w:u32le(56) + w:string(s.type) + w:string(s.handler) + w:u32le(0) -- flags + w:u16le(0) -- priority + w:u16le(0) -- language + w:u32le(0) -- initial frames + w:u32le(s.scale) + w:u32le(s.rate) + w:u32le(0) -- start + w:u32le(lengths[si]) + w:u32le(maxChunk[si]) + w:u32le((s.quality and{s.quality }or{0xFFFFFFFF})[1]) + w:u32le(s.sampleSize) + w:u16le(0) + w:u16le(0) + w:u16le(s.width or 0) + w:u16le(s.height or 0) + w:string("strf") + w:u32le(buffer.len(s.strf)) + w:bytes(s.strf) + if buffer.len(s.strf) % 2 == 1 then + w:u8(0) + end + if s.name then + local nm = s.name .. "\0" + w:string("strn") + w:u32le(#nm) + w:string(nm) + if #nm % 2 == 1 then + w:u8(0) + end + end + w:setU32le(strlSize, w:tell() - strlSize - 4) + end + -- OpenDML extended header (total frames) + w:string("LIST") + w:u32le(16) + w:string("odml") + w:string("dmlh") + w:u32le(4) + w:u32le(frames) + w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) + -- INFO + local sw = (opts.software or "rosetta") .. "\0" + if #sw % 2 == 1 then + sw =sw.. "\0" + end + w:string("LIST") + w:u32le(4 + 8 + #sw) + w:string("INFO") + w:string("ISFT") + w:u32le(#sw) + w:string(sw) + -- movi + w:string("LIST") + local moviSize = w:tell() + w:u32le(0) + local moviBase = w:tell() + w:string("movi") + local index = (table.create(#chunks) ) +for _, c in __iter(chunks) do + local si, data, key = c[1], c[2], c[3] + local s = opts.streams[si] + local id = string.format("%02d", si - 1) .. (s.ckid or (s.type == "vids" and"dc" or"wb")) + local at = w:tell() + local n = buffer.len(data) + w:string(id) + w:u32le(n) + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + table.insert(index, { id, key and 0x10 or 0, at - moviBase, n }) + end + w:setU32le(moviSize, w:tell() - moviSize - 4) + -- idx1 + w:string("idx1") + w:u32le(#index * 16) + for _, e in __iter(index) do + w:string(e[1]) + w:u32le(e[2]) + w:u32le(e[3]) + w:u32le(e[4]) + end + w:setU32le(riffSize, w:tell() - 8) + return w:finish() +end +-- ------------------------------------------------------------------------------------------------ BITMAPINFO +-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | +-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; +-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. + + + + + + + + + + +function Avi.bitmapInfo(f) +local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info= { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, math.floor((n - 40) / 4)) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at =at- 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + +return Avi +end +__FILES["containers/Chunks"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional +-- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a +-- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing +-- the loop. New in rosetta (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). +-- +-- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf) +-- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG +-- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end +-- local c = Chunks.find(list, "SSND") +-- +-- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in +-- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). +-- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one +-- byte earlier). layout.resize(id, declared) can replace a declared size (RF64's ds64). Never throws. +local Chunks = {} + + + + + + + + + + + + + + + + + + + + + + + + +Chunks.RIFF = (table.freeze({ pad = 2, lenientPad = true }) ) +Chunks.RIFX = (table.freeze({ pad = 2, lenientPad = true, bigEndian = true }) ) +Chunks.IFF = (table.freeze({ pad = 2, bigEndian = true }) ) +Chunks.PNG = (table.freeze({ sizeFirst = true, bigEndian = true, trailer = 4 }) ) +Chunks.CAF = (table.freeze({ bigEndian = true, sizeBytes = 8 }) ) + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring + +local function printable4(b, p, limit) +if p + 4 > limit then + return false + end + for i = 0, 3 do + local c = readu8(b, p + i) + if c < 32 or c > 126 then + return false + end + end + return true +end +Chunks.printable4 = printable4 + +local function u32(b, o, be) +local v = readu32(b, o) + return (be and{(bit32.byteswap(v) )}or{v +})[1]end + +-- walk(b, p, limit, layout?) -> { Chunk } of [p, limit) +function Chunks.walk(b, p, limit, layout) +local L= layout or Chunks.RIFF + local be = L.bigEndian == true + local sizeBytes = L.sizeBytes or 4 + local head = 4 + sizeBytes + local trailer = L.trailer or 0 + local pad = L.pad or 1 + local openEnded = L.openEnded + local resize = L.resize + local maxChunks = L.maxChunks or 100000 + local list= {} + limit = math.min(limit, buffer.len(b)) + while p + head <= limit and #list < maxChunks do + local idAt = (L.sizeFirst and((p + sizeBytes ))or(p +)) local sizeAt = (L.sizeFirst and{p }or{(p + 4 +)})[1] local id = readstring(b, idAt, 4) + local declared + if sizeBytes == 8 then + local hi, lo = u32(b, sizeAt, be), u32(b, sizeAt + 4, be) + if not be then + hi, lo = lo, hi + end + declared = hi * 4294967296 + lo + else + declared = u32(b, sizeAt, be) + end + local size = declared + if resize then + size = resize(id, declared) or declared + end + local body = p + head + local avail = limit - body + local c= { + id = id, + start = p, + offset = body, + size = size, + declared = declared, + avail = math.min(size, avail), + truncated = false, + streamed = false, + } + table.insert(list, c) + if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then + c.streamed = size == 0 or size == 0xFFFFFFFF + c.truncated = not c.streamed + c.size, c.avail = avail, avail + break + end + if size + trailer > avail then + c.truncated = true -- (the body or its trailer runs past the end) + break + end + local rem = size % pad + local nextPos = body + size + trailer + ((rem > 0 and((pad - rem ))or(0))) + if L.lenientPad and rem > 0 and not printable4(b, nextPos, limit) and printable4(b, body + size + trailer, limit) then + nextPos = body + size + trailer + end + p = nextPos + end + return list +end + +-- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index +function Chunks.find(list, id, from) +for i = from or 1, #list do + if list[i].id == id then + return list[i], i + end + end + return nil, nil +end + +return Chunks +end +__FILES["containers/Cpio"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment), +-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the +-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the +-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar +-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks +-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as +-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The +-- archive formats (archive/cpio, archive/rpm's payload) build on it. +-- +-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err +-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" }) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Cpio = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + +local S_IFMT = 0xF000 +local TYPES= { + [0x8000] = "0", + [0x4000] = "5", + [0xA000] = "2", + [0x2000] = "3", + [0x6000] = "4", + [0x1000] = "6", + [0xC000] = "s", +} +local MODES= {} +for m, t in __iter(TYPES) do + MODES[t] = m +end +Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits +Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter + +local TRAILER = "TRAILER!!!" + +-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset +function Cpio.format(b, o) +local n = buffer.len(b) + if o + 6 <= n then + local m = buffer.readstring(b, o, 6) + if m == "070701" then + return "newc" + elseif m == "070702" then + return "crc" + elseif m == "070707" then + return "odc" + end + end + if o + 2 <= n then + local v = buffer.readu16(b, o) + if v == 0x71C7 then + return "bin" + elseif v == 0xC771 then + return "binbe" + end + end + return nil +end + +-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits +local function num(b, o, n, base) +local s = buffer.readstring(b, o, n) + if base == 16 then + if not string.find(s, "^%x+$") then + return nil + end + elseif not string.find(s, "^[0-7]+$") then + return nil + end + return tonumber(s, base) +end + +-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32) +function Cpio.checksum(b, o, n) +local s = 0 + local i = o + local e = o + n + while i + 4 <= e do + local v = buffer.readu32(b, i) + s =s+ (bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24) +) i =i+ 4 + end + while i < e do + s =s+ buffer.readu8(b, i) + i =i+ 1 + end + return s % 4294967296 +end + +-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err +local function header(b, p, e, fmt) +local h= {} + local nameAt + if fmt == "newc" or fmt == "crc" then + if p + 110 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local f = {} +for i = 1, 13 do + local v = num(b, p + 6 + (i - 1) * 8, 8, 16) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8) + end + f[i] = v + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7] + h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13] + nameAt = p + 110 + elseif fmt == "odc" then + if p + 76 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 } + local f = {} +local q = p + 6 + for i, w in __iter(widths) do + local v = num(b, q, w, 8) + if not v then + return nil, Err.new(Err.CORRUPT, "bad header field", q) + end + f[i] = v + q =q+ w + end + h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10] + h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255) + h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255) + nameAt = p + 76 + else + if p + 26 > e then + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + local be = fmt == "binbe" + local function u16(i) +local v = buffer.readu16(b, p + i * 2) + return (be and{(bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) )}or{v +})[1] end + local dev, rdev = u16(1), u16(7) + h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6) + h.mtime = u16(8) * 65536 + u16(9) + h.namesize = u16(10) + h.size = u16(11) * 65536 + u16(12) + h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255) + h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255) + nameAt = p + 26 + end + if h.namesize < 1 or nameAt + h.namesize > e then + return nil, Err.new((h.namesize < 1 and{Err.CORRUPT }or{Err.TRUNCATED})[1], "bad name size", nameAt) + end + h.nameAt = nameAt + return h, nil +end + +-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err +function Cpio.read(b, offset, length, opts) +local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local verify = not (opts and opts.verify == false) + local fmt = Cpio.format(b, o) + if not fmt or o >= e then + return nil, Err.new(Err.CORRUPT, "not a cpio archive", o) + end + local align = (fmt == "newc" or fmt == "crc" )and 4 or(fmt == "odc" and 1 or 2 +) local out= {} + local groups= {} + local p = o + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p) + end + if Cpio.format(b, p) ~= fmt then + return nil, Err.new(Err.CORRUPT, "bad header magic", p) + end + local h, herr = header(b, p, e, fmt) + if not h then + return nil, herr + end + local name = buffer.readstring(b, h.nameAt, h.namesize) + local z = string.find(name, "\0", 1, true) + if z then + name = string.sub(name, 1, z - 1) + end + local data = h.nameAt + h.namesize + data = o + math.floor((data - o + align - 1) / align )* align + if name == TRAILER then + break + end + if data + h.size > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data) + end + local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0" + local entry= { + name = name, + size = h.size, + mode = h.mode, + type = typ, + dir = typ == "5", + uid = h.uid, + gid = h.gid, + nlink = h.nlink, + mtime = h.mtime, + ino = h.ino, + devmajor = h.devmajor, + devminor = h.devminor, + rdevmajor = h.rdevmajor, + rdevminor = h.rdevminor, + link = (typ == "2" and{(buffer.readstring(b, data, h.size) )}or{nil})[1], + hardlink = nil, + offset = data, + check = (fmt == "crc" and{h.check }or{nil})[1], + } + if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then + return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data) + end + if typ == "0" and h.nlink > 1 then + local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino + local g = groups[key] + if not g then + g = {} + groups[key] = g + else + entry.hardlink = g[1].name + end + table.insert(g, entry) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + p = data + h.size + p = o + math.floor((p - o + align - 1) / align )* align + end + -- hard links: the links stored without data read the group's data (newc / crc keep it on the last link) + for _, g in __iter(groups) do + local holder= nil + for _, x in __iter(g) do + if x.size > 0 then + holder = x + end + end + if holder then + for _, x in __iter(g) do + if x.size == 0 then + x.size, x.offset = holder.size, holder.offset + end + end + end + end + return out, { format = fmt } +end +-- ------------------------------------------------------------------------------------------------ writing + + + + + + + + + + + + + + + + + + + + + + + +local function hex8(v) +if v < 0 or v % 1 ~= 0 or v >= 4294967296 then + return nil + end + return string.format("%08X", v) +end + +local function oct(v, w) +if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then + return nil + end + local s = string.format("%o", v) + return string.rep("0", w - #s) .. s +end + +-- write(entries, opts?) -> buffer | nil, Err +function Cpio.write(entries, opts) +local fmt = (opts and opts.format) or "newc" + if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then + return nil, Err.new(Err.ARG, "format must be newc, crc or odc") + end + local block = (opts and opts.block) or 512 + if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then + return nil, Err.new(Err.ARG, "block must be a positive integer") + end + -- newc / crc: a hard link group's data goes on its last link only + local last= {} + local prepared= table.create(#entries) + for i, e in __iter(entries) do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local typ = e.type or (e.dir and"5" or"0") + local tbits = MODES[typ] + if not tbits then + return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ)) + end + local mode = e.mode or (typ == "5" and 0x1ED or(typ == "2" and 0x1FF or 0x1A4)) + if bit32.band(mode, S_IFMT) == 0 then + mode = bit32.bor(mode, tbits) + end + local data = e.data + if typ == "2" and not data then + data = buffer.fromstring(e.link or "") + elseif typ ~= "0" and typ ~= "2" then + data = nil + end + local nlink = e.nlink or (typ == "5" and 2 or 1) + local ino = e.ino or i + local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ } + prepared[i] = p + if typ == "0" and nlink > 1 then + last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i + end + end + local w = Bytes.writer(1024) + local function put(name, p, data) +local e = p.e + local namesize = #name + 1 + local size = buffer.len(data) + if fmt == "odc" then + local dev = (e.devmajor or 0) * 256 + (e.devminor or 0) + local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0) + local fields = { + oct(dev, 6), + oct(p.ino, 6), + oct(p.mode, 6), + oct(e.uid or 0, 6), + oct(e.gid or 0, 6), + oct(p.nlink, 6), + oct(rdev, 6), + oct(math.floor(e.mtime or 0), 11), + oct(namesize, 6), + oct(size, 11), + } + for k = 1, 10 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header") + end + end + w:string("070707" .. table.concat(fields )) + w:string(name) + w:u8(0) + w:bytes(data) + else + local check = (fmt == "crc" and p.typ == "0" and{(Cpio.checksum(data, 0, size) )}or{0 +})[1] local fields = { + hex8(p.ino), + hex8(p.mode), + hex8(e.uid or 0), + hex8(e.gid or 0), + hex8(p.nlink), + hex8(math.floor(e.mtime or 0)), + hex8(size), + hex8(e.devmajor or 0), + hex8(e.devminor or 0), + hex8(e.rdevmajor or 0), + hex8(e.rdevminor or 0), + hex8(namesize), + hex8(check), + } + for k = 1, 13 do + if not fields[k] then + return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header") + end + end + w:string((fmt == "crc" and"070702" or"070701") .. table.concat(fields )) + w:string(name) + w:u8(0) + w:fill(0, (4 - (110 + namesize) % 4) % 4) + w:bytes(data) + w:fill(0, (4 - size % 4) % 4) + end + return nil + end + for i, p in __iter(prepared) do + local data = p.data + if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then + local e = p.e + if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then + data = buffer.create(0) + end + end + local err = put(p.e.name, p, data) + if err then + return nil, err + end + end + local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0)) + if err then + return nil, err + end + w:fill(0, (block - w.pos % block) % block) + return w:finish(), nil +end + +return Cpio +end +__FILES["containers/Demux"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4). +-- New in rosetta. A container parses its file once into an index of packets (track, pts, dts, duration, +-- keyframe, and the bytes as an offset + length into the source buffer or a buffer of their own); this module gives +-- that index the Demuxer interface: per-track cursors (a video decoder and an audio decoder read the same file +-- independently), a file-order cursor, keyframe seeking, packet copies on demand. +-- +-- local d = Demux.new("mkv", tracks, src, meta) +-- d:add(trackId, pts, dts, duration, keyframe, offset, length) -- in file order +-- d:addData(trackId, pts, dts, duration, keyframe, buffer) -- bytes that are not one range of src +-- d:finish() -- durations, per-track indexes +-- for p in d:packets(1) do ... end; d:read(); d:seek(12.5); d:count(1); d:get(1, i) +local Types = __include("Types") + +local Demux = {} +local D = {} +D.__index = D + +-- new(format, tracks, src, meta?) -> an empty index + + + + + + + + + + + + + + + + + + + + + + + + + + +function Demux.new(format, tracks, src, meta) +return setmetatable({ + kind = "demuxer" , + format = format, + tracks = tracks, + duration = 0, + startTime = 0, + meta = meta or {}, + src = src, + n = 0, + tr = {}, + pts = {}, + dts = {}, + dur = {}, + key = {}, + off = {}, + len = {}, + data = {}, + extra = {}, + byTrack = {}, + cur = {}, + gcur = 1, + }, D) +end + +-- add(track, pts, dts?, duration?, keyframe, offset, length): a packet whose bytes are src[offset, offset + length) +function D.add(self, track, pts, dts, duration, keyframe, offset, length) + local i = self.n + 1 + self.n = i + self.tr[i] = track + self.pts[i] = pts + self.dts[i] = dts or pts + self.dur[i] = duration or 0 + self.key[i] = keyframe + self.off[i] = offset + self.len[i] = length +end + +-- addData(track, pts, dts?, duration?, keyframe, data): a packet with its own bytes +function D.addData(self, track, pts, dts, duration, keyframe, data) + self:add(track, pts, dts, duration, keyframe, -1, buffer.len(data)) + self.data[self.n] = data +end + +-- setExtra(key, value): a field for the last packet added (Packet[key] = value: discardPadding, ...) +function D.setExtra(self, key, value) + local e = self.extra[self.n] + if not e then + e = {} + self.extra[self.n] = e + end + e[key] = value +end + +-- finish(): builds the per-track indexes, fills missing packet durations from the next packet's pts (or the track's +-- frame rate), and the track / file durations (seconds) where the container gave none +function D.finish(self) + local byTrack= {} + for _, t in __iter(self.tracks) do + byTrack[t.id] = {} + end + for i = 1, self.n do + local list = byTrack[self.tr[i] ] + if list then + table.insert(list, i) + end + end + self.byTrack = byTrack + local total = self.duration + local start = math.huge + for _, t in __iter(self.tracks) do + local list = byTrack[t.id] + local scale = (t.timescale and t.timescale > 0 and{t.timescale }or{1 +})[1] t.timescale = scale + local frameTicks = (t.frameRate and t.frameRate > 0 and((scale / t.frameRate ))or(0 +)) -- durations from the next packet in presentation order + if #list > 0 then + local order = table.clone(list) + table.sort(order, function(a, b) +return self.pts[a] < self.pts[b] + end) + for k = 1, #order do + local i = order[k] + if self.dur[i] <= 0 then + local nx = order[k + 1] + if nx and self.pts[nx] > self.pts[i] then + self.dur[i] = self.pts[nx] - self.pts[i] + elseif frameTicks > 0 then + self.dur[i] = frameTicks + elseif k > 1 then + self.dur[i] = self.dur[order[k - 1] ] + end + end + end + local first, last = order[1], order[#order] + if t.kind == "video" or t.kind == "audio" then + start = math.min(start, self.pts[first] / scale) + end + local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale + if not t.duration or t.duration <= 0 then + t.duration = d + end + t.frames = t.frames or #list + end + if t.duration and t.duration > total then + total = t.duration + end + self.cur[t.id] = 1 + end + self.duration = total + -- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count + -- frame times from it + self.startTime = (start ~= math.huge and start > 0 and{start }or{0 +})[1]end + +-- the Packet for index entry i (a copy of its bytes) +function D._packet(self, i) +local data = self.data[i] + if not data then + local o, l = self.off[i], self.len[i] + local src = self.src + local n = buffer.len(src) + if o < 0 or o > n then + o, l = n, 0 + elseif o + l > n then + l = n - o + end + data = buffer.create(l) + buffer.copy(data, 0, src, o, l) + end + local p= { + track = self.tr[i], + pts = self.pts[i], + dts = self.dts[i], + duration = self.dur[i], + keyframe = self.key[i], + data = data , + } + local e = self.extra[i] + if e then + for k, v in __iter(e) do + p[k] = v + end + end + return p +end + +-- read(track?) -> the next Packet of the track (or of any track, in file order) | nil at the end +function D.read(self, track) +if track == nil then + local i = self.gcur + if i > self.n then + return nil + end + self.gcur = i + 1 + return self:_packet(i) + end + local list = self.byTrack[track] + if not list then + return nil + end + local c = self.cur[track] or 1 + local i = list[c] + if not i then + return nil + end + self.cur[track] = c + 1 + return self:_packet(i) +end + +-- packets(track?) -> an iterator of Packets from the current position (advancing it) +function D.packets(self, track) +return function() +return self:read(track) + end +end + +-- count(track) -> number of packets; get(track, k) -> the k-th packet (1-based) without moving cursors +function D.count(self, track) +local list = self.byTrack[track] + return (list and((#list ))or(0 +))end +function D.get(self, track, k) +local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil + end + return self:_packet(i) +end + +-- info(track, k) -> pts, dts, duration, keyframe, length of the k-th packet (no copy) +function D.info(self, track, k) +local list = self.byTrack[track] + local i = list and list[k] + if not i then + return nil, nil, nil, nil, nil + end + return self.pts[i], self.dts[i], self.dur[i], self.key[i], self.len[i] +end + +-- rewind(track?): a track's cursor (or every cursor) back to the start +function D.rewind(self, track) + if track then + self.cur[track] = 1 + return + end + for id in __iter(self.cur) do + self.cur[id] = 1 + end + self.gcur = 1 +end + +-- seek(seconds): each track to its last keyframe at or before the time (the file-order cursor to the earliest) +function D.seek(self, seconds) + local g = self.n + 1 + for _, t in __iter(self.tracks) do + local list = self.byTrack[t.id] + if list and #list > 0 then + local target = seconds * t.timescale + local best = 1 + for k = 1, #list do + local i = list[k] + if self.key[i] and self.pts[i] <= target + 1e-6 then + best = k + end + end + self.cur[t.id] = best + if list[best] < g then + g = list[best] + end + end + end + self.gcur = g > self.n and 1 or g +end + +-- track(kind) -> the first default track of the kind, else the first of the kind +function D.track(self, kind) +local first = nil + for _, t in __iter(self.tracks) do + if t.kind == kind then + if t.default then + return t + end + first = first or t + end + end + return first +end + +return Demux +end +__FILES["containers/Ebml"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- containers/Ebml: EBML (RFC 8794), the binary structure under Matroska and WebM. New in rosetta. +-- Reading: element headers (IDs keep their length marker bits, as the specs write them: 0x1A45DFA3; sizes drop it; +-- an all-ones size is "unknown"), children iteration, and the value types (unsigned / signed integers, floats, +-- strings, binary). Writing: a byte builder with nested master elements whose 8-byte sizes are patched on close, and +-- minimal-length value elements. +-- +-- local id, size, data = Ebml.header(buf, pos, limit) -- size = -1: unknown; nil when malformed / truncated +-- for id, off, size in Ebml.children(buf, off, limit) do ... end +-- local w = Ebml.writer(); local m = w:open(0x18538067); w:uint(0xD7, 1); w:close(m); local out = w:finish() +-- +-- Never throws: malformed input gives nil (readers) or stops iteration. +local Bytes = __include("core/Bytes") + +local readu8 = buffer.readu8 + +local Ebml = {} + +Ebml.UNKNOWN = -1 + +-- vint(buf, pos, limit) -> value (marker removed), length | nil. All-ones values (unknown sizes) return -1. +function Ebml.vint(buf, pos, limit) +if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + if b == 0 then + return nil, nil + end + local len = 1 + local mask = 0x80 + while bit32.band(b, mask) == 0 do + len =len+ 1 + mask = math.floor(mask / 2 +) end + if pos + len > limit then + return nil, nil + end + local v = bit32.band(b, mask - 1) + local allOnes = v == mask - 1 + for i = 1, len - 1 do + local c = readu8(buf, pos + i) + v = v * 256 + c + if c ~= 255 then + allOnes = false + end + end + if allOnes then + return -1, len + end + return v, len +end + +-- svint(buf, pos, limit) -> a signed vint (EBML lacing deltas) | nil +function Ebml.svint(buf, pos, limit) +local v, len = Ebml.vint(buf, pos, limit) + if v == nil or len == nil then + return nil, nil + end + if v == -1 then + return nil, nil + end + return v - (2 ^ (7 * len - 1) - 1), len +end + +-- id(buf, pos, limit) -> the element ID with its marker bits, length | nil (IDs are 1..4 bytes) +function Ebml.id(buf, pos, limit) +if pos >= limit then + return nil, nil + end + local b = readu8(buf, pos) + local len = b >= 0x80 and 1 or(b >= 0x40 and 2 or(b >= 0x20 and 3 or(b >= 0x10 and 4 or 0 +))) if len == 0 or pos + len > limit then + return nil, nil + end + local v = b + for i = 1, len - 1 do + v = v * 256 + readu8(buf, pos + i) + end + return v, len +end + +-- header(buf, pos, limit) -> id, size (-1 = unknown), data offset | nil +function Ebml.header(buf, pos, limit) +local id, il = Ebml.id(buf, pos, limit) + if not id or not il then + return nil, nil, nil + end + local size, sl = Ebml.vint(buf, pos + il, limit) + if not size or not sl then + return nil, nil, nil + end + return id, size, pos + il + sl +end + +-- children(buf, off, limit) -> iterator of id, data offset, size (an unknown size runs to limit; a size past the +-- limit is clipped; a malformed header ends the iteration) +function Ebml.children(buf, off, limit) +local pos = off + return function() +if pos >= limit then + return nil, 0, 0 + end + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + pos = limit + return nil, 0, 0 + end + if size < 0 or data + size > limit then + size = limit - data + end + pos = data + size + return id, data, size + end +end + +-- uint(buf, off, len) / int / float / string: element values (0 / "" for empty elements) +function Ebml.uint(buf, off, len) +local v = 0 + for i = 0, math.min(len, 8) - 1 do + v = v * 256 + readu8(buf, off + i) + end + return v +end +function Ebml.int(buf, off, len) +if len <= 0 then + return 0 + end + local v = Ebml.uint(buf, off, len) + local n = math.min(len, 8) + if readu8(buf, off) >= 0x80 then + v =v- 2 ^ (8 * n) + end + return v +end +function Ebml.float(buf, off, len) +local r = Bytes.reader(buf, off, len) + if len == 4 then + return r:f32be() + elseif len == 8 then + return r:f64be() + end + return 0 +end +function Ebml.string(buf, off, len) +local s = buffer.readstring(buf, off, len) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, 1, z - 1) + end + return s +end +function Ebml.binary(buf, off, len) +local b = buffer.create(len) + buffer.copy(b, 0, buf, off, len) + return b +end + +-- ------------------------------------------------------------------------------------------------ writing +local W = {} +W.__index = W + +-- writer(capacity?) -> an EBML byte builder + + +function Ebml.writer(capacity) +return setmetatable({ w = Bytes.writer(capacity or 65536) }, W) +end + +-- idBytes(id) -> the ID's bytes as written +local function writeId(w, id) + if id >= 0x1000000 then + w:u32be(id) + elseif id >= 0x10000 then + w:u24be(id) + elseif id >= 0x100 then + w:u16be(id) + else + w:u8(id) + end +end + +-- size as a minimal vint (n bytes: force a length) +local function writeSize(w, size, n) + local len = n or 1 + if not n then + while size >= 2 ^ (7 * len) - 1 do + len =len+ 1 + end + end + local v = size + 2 ^ (7 * len) -- the marker bit + local bytes = table.create(len, 0) + for i = len, 1, -1 do + bytes[i] = v % 256 + v = math.floor(v / 256 +) end + for i = 1, len do + w:u8(bytes[i]) + end +end +Ebml.writeSize = writeSize + +-- vintBytes(v, n?) -> the vint encoding of v as a string (lacing, block track numbers) +function Ebml.vintString(v, n) +local w = Bytes.writer(8) + writeSize(w, v, n) + return buffer.readstring(w:finish(), 0, w:tell()) +end + +function W.tell(self) +return self.w:tell() +end + +-- open(id) -> a handle for close(): writes the ID and an 8-byte size placeholder +function W.open(self, id) +writeId(self.w, id) + local at = self.w:tell() + for _ = 1, 8 do + self.w:u8(0) + end + return at +end + +-- close(handle): patches the size of the element opened at handle +function W.close(self, at) + local w = self.w + local v = w:tell() - at - 8 + w:setU8(at, 0x01) + for i = 7, 1, -1 do + w:setU8(at + i, v % 256) + v = math.floor(v / 256 +) end +end + +-- unknownSize(id): a master element with an unknown size (live streams) +function W.openUnknown(self, id) + writeId(self.w, id) + self.w:u8(0x01) + for _ = 1, 7 do + self.w:u8(0xFF) + end +end + +function W.uint(self, id, v) + local n = 1 + while v >= 2 ^ (8 * n) and n < 8 do + n =n+ 1 + end + writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + local x = v + for i = n, 1, -1 do + bytes[i] = x % 256 + x = math.floor(x / 256 +) end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.int(self, id, v) + local n = 1 + while (v < -(2 ^ (8 * n - 1)) or v >= 2 ^ (8 * n - 1)) and n < 8 do + n =n+ 1 + end + local u = (v < 0 and((v + 2 ^ (8 * n) ))or(v +)) writeId(self.w, id) + writeSize(self.w, n) + local bytes = table.create(n, 0) + for i = n, 1, -1 do + bytes[i] = u % 256 + u = math.floor(u / 256 +) end + for i = 1, n do + self.w:u8(bytes[i]) + end +end + +function W.float(self, id, v) + writeId(self.w, id) + writeSize(self.w, 8) + self.w:f64be(v) +end + +function W.string(self, id, s) + writeId(self.w, id) + writeSize(self.w, #s) + self.w:string(s) +end + +-- binary(id, buf, off?, len?) +function W.binary(self, id, b, off, len) + local o = off or 0 + local n = len or (buffer.len(b) - o) + writeId(self.w, id) + writeSize(self.w, n) + self.w:bytes(b, o, n) +end + +-- raw bytes (a pre-built element, block headers) +function W.raw(self, s) + self.w:string(s) +end +function W.rawBuffer(self, b, off, len) + local o = off or 0 + self.w:bytes(b, o, len or (buffer.len(b) - o)) +end +-- element header for a binary element whose payload follows in pieces: id + size +function W.header(self, id, size) + writeId(self.w, id) + writeSize(self.w, size) +end + +-- void(n): an EBML Void element of exactly n bytes (n >= 2), for reserved space +function W.void(self, n) + self.w:u8(0xEC) + if n - 2 < 127 then + writeSize(self.w, n - 2, 1) + for _ = 1, n - 2 do + self.w:u8(0) + end + else + writeSize(self.w, n - 9, 8) + for _ = 1, n - 9 do + self.w:u8(0) + end + end +end + +function W.finish(self) +return self.w:finish() +end + +return Ebml +end +__FILES["containers/Fat"] = function() +local __compat = __compat local buffer, bit32, utf8, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.__iter --!strict +-- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories +-- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names, +-- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images +-- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from +-- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout. +-- +-- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message +-- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/") +-- local data, err = Fat.read(vol, entry) -- buffer | nil, message +-- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image +-- +-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by +-- the cluster count (loops are errors). +local Archive = __include("containers/Archive") + +local Fat = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +-- ------------------------------------------------------------------------------------------------ open + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function bpbAt(b, o, len) +if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + local jump = readu8(b, o) + local bps = readu16(b, o + 11) + local spc = readu8(b, o + 13) + if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then + return nil, "no FAT boot sector" + end + if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then + return nil, "bad sectors per cluster" + end + local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17) + local total = readu16(b, o + 19) + if total == 0 then + total = readu32(b, o + 32) + end + local fatSectors = readu16(b, o + 22) + local fat32 = fatSectors == 0 + if fat32 then + fatSectors = readu32(b, o + 36) + end + if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then + return nil, "bad BPB" + end + local rootSectors = math.ceil(rootEntries * 32 / bps) + local dataSector = reserved + nfats * fatSectors + rootSectors + if dataSector >= total then + return nil, "bad BPB: no data area" + end + local clusters = math.floor((total - dataSector) / spc +) local bits = clusters < 4085 and 12 or(clusters < 65525 and 16 or 32 +) if fat32 and bits ~= 32 then + bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count + end + if total * bps > len then + -- images cut short at the last used sector are common: allow, reads past the end fail + total = math.floor(len / bps +) end + local labelAt = bits == 32 and 71 or 43 + local sig = readu8(b, o + (bits == 32 and 66 or 38)) + local label= (sig == 0x29 and{(string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) }or{nil +})[1] if label == "NO NAME" or label == "" then + label = nil + end + return { + b = b, + base = o, + limit = o + len, + bps = bps, + spc = spc, + fatOffset = reserved * bps, + fatSize = fatSectors * bps, + rootOffset = (reserved + nfats * fatSectors) * bps, + rootEntries = rootEntries, + rootCluster = (bits == 32 and{(readu32(b, o + 44) )}or{0})[1], + dataOffset = dataSector * bps, + clusters = clusters, + bits = bits, + label = label, + oem = buffer.readstring(b, o + 3, 8), + media = readu8(b, o + 21), + }, nil +end + + + +local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true } + +function Fat.open(b, off, len, opts) +local o= opts or {} + off = math.max(0, off) + len = math.min(len, buffer.len(b) - off) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + if not o.partition then + local v = bpbAt(b, off, len) + if v then + return v, nil + end + end + -- an MBR: 0x55AA and four partition entries + if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then + return nil, "no FAT boot sector and no partition table" + end + for i = 1, 4 do + local e = off + 446 + (i - 1) * 16 + local ptype = readu8(b, e + 4) + local lba, count = readu32(b, e + 8), readu32(b, e + 12) + if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then + if lba * 512 >= len then + return nil, "truncated: partition " .. i .. " starts past the end" + end + local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512)) + if v then + v.partition = i + end + return v, err + end + end + return nil, (o.partition and(("no partition " .. o.partition ))or("no FAT partition" +))end + +-- ------------------------------------------------------------------------------------------------ chains +local function nextCluster(v, c) +local f = v.base + v.fatOffset + if v.bits == 12 then + local p = f + c + math.floor(c / 2 +) if p + 1 >= v.limit then + return 0xFFFFFFF + end + local w = readu16(v.b, p) + local n = (c % 2 == 0 and{(bit32.band(w, 0xFFF) )}or{(bit32.rshift(w, 4) +)})[1] return n >= 0xFF8 and 0xFFFFFFF or(n == 0xFF7 and 0xFFFFFF7 or n +) elseif v.bits == 16 then + local p = f + c * 2 + if p + 2 > v.limit then + return 0xFFFFFFF + end + local n = readu16(v.b, p) + return n >= 0xFFF8 and 0xFFFFFFF or(n == 0xFFF7 and 0xFFFFFF7 or n +) end + local p = f + c * 4 + if p + 4 > v.limit then + return 0xFFFFFFF + end + return bit32.band(readu32(v.b, p), 0x0FFFFFFF) +end + +-- the clusters of a chain (nil, message when it leaves the volume or loops) +local function chainOf(v, first, maxClusters) +local out = {} + local c = first + while c >= 2 and c < 0xFFFFFF7 do + if c >= v.clusters + 2 then + return nil, "cluster " .. c .. " outside the volume" + end + table.insert(out, c) + if #out > maxClusters then + return nil, "cluster chain loops" + end + c = nextCluster(v, c) + end + if c == 0xFFFFFF7 then + return nil, "bad cluster in a chain" + end + return out, nil +end + +local function clusterOffset(v, c) +return v.base + v.dataOffset + (c - 2) * v.spc * v.bps +end + +-- the bytes of a chain, up to size bytes (nil = the whole chain) +local function readChain(v, first, size) +local csize = v.spc * v.bps + local maxClusters = (size and((math.ceil(size / csize) + 1 ))or(v.clusters +)) local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1)) + if not list then + return nil, err + end + local total = (size and{size }or{(#list * csize +)})[1] if #list * csize < total then + return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)" + end + local out = buffer.create(total) + local o = 0 + for _, c in __iter(list) do + local n = math.min(csize, total - o) + if n <= 0 then + break + end + local at = clusterOffset(v, c) + if at + n > v.limit then + return nil, "truncated: cluster " .. c .. " past the end of the image" + end + buffer.copy(out, o, v.b, at, n) + o =o+ n + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ directories +local function latin1(s) +if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +local function shortChecksum(raw) +local sum = 0 + for i = 1, 11 do + sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256 + end + return sum +end + +local function ucs2(b, o, n, out) + for k = 0, n - 1 do + table.insert(out, readu16(b, o + k * 2)) + end +end + +-- the entries of one directory's bytes +local function parseDir(d, prefix, out) +local lfn= {} + local lfnSum, lfnCount = -1, 0 + local subdirs = {} + for p = 0, buffer.len(d) - 32, 32 do + local first = readu8(d, p) + if first == 0 then + break + end + local attr = readu8(d, p + 11) + if first == 0xE5 then + lfn, lfnSum, lfnCount = {}, -1, 0 + elseif attr == 0x0F then + local seq = bit32.band(first, 0x3F) + if bit32.band(first, 0x40) ~= 0 then + lfn, lfnCount = {}, seq + lfnSum = readu8(d, p + 13) + end + if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then + local chars = {} + ucs2(d, p + 1, 5, chars) + ucs2(d, p + 14, 6, chars) + ucs2(d, p + 28, 2, chars) + lfn[seq] = chars + end + else + local raw = buffer.readstring(d, p, 11) + if first == 0x05 then + raw = "\229" .. string.sub(raw, 2) + end + local long= nil + if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then + local cps = {} + local complete = true + for s = 1, lfnCount do + if not lfn[s] then + complete = false + break + end + for _, c in __iter(lfn[s]) do + if c == 0 or c == 0xFFFF then + break + end + table.insert(cps, c) + end + end + if complete then + local parts = table.create(#cps) + for i, c in __iter(cps) do + parts[i] = utf8.char(c >= 0xD800 and c < 0xE000 and 0xFFFD or c) + end + long = table.concat(parts) + end + end + lfn, lfnSum, lfnCount = {}, -1, 0 + local nt = readu8(d, p + 12) + local base = string.gsub(string.sub(raw, 1, 8), " +$", "") + local ext = string.gsub(string.sub(raw, 9, 11), " +$", "") + if bit32.band(nt, 0x08) ~= 0 then + base = string.lower(base) + end + if bit32.band(nt, 0x10) ~= 0 then + ext = string.lower(ext) + end + local short = latin1((ext ~= "" and((base .. "." .. ext ))or(base))) + local isDir = bit32.band(attr, 0x10) ~= 0 + local isLabel = bit32.band(attr, 0x08) ~= 0 + if not isLabel and short ~= "." and short ~= ".." then + local name = prefix .. (long or short) + local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536 + local e= { + name = (isDir and((name .. "/" ))or(name)), + dir = isDir, + size = isDir and 0 or readu32(d, p + 28), + mtime = Archive.fromDos(readu16(d, p + 24) * 65536 + readu16(d, p + 22)), + cluster = cluster, + attr = attr, + shortName = short, + } + table.insert(out, e) + if isDir then + table.insert(subdirs, e) + end + end + end + end + return subdirs +end + +-- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents) +function Fat.list(v, maxEntries) +local out= {} + local limit = maxEntries or 65536 + local root, err +if v.bits == 32 then + root, err = readChain(v, v.rootCluster, nil) + else + local n = v.rootEntries * 32 + if v.base + v.rootOffset + n > v.limit then + return nil, "truncated: root directory past the end" + end + root = buffer.create(n) + buffer.copy(root , 0, v.b, v.base + v.rootOffset, n) + end + if not root then + return nil, err + end + local seen= {} + local function walk(d, prefix, depth) +if depth > 64 then + return "directories nested too deep" + end + local start = #out + local subdirs = parseDir(d, prefix, out) + if #out > limit then + return "limit: more than maxEntries entries" + end + local _ = start + for _, s in __iter(subdirs) do + if s.cluster >= 2 then + if seen[s.cluster] then + return "directory loop at cluster " .. s.cluster + end + seen[s.cluster] = true + local sd, serr = readChain(v, s.cluster, nil) + if not sd then + return s.name .. ": " .. tostring(serr) + end + local werr = walk(sd, s.name, depth + 1) + if werr then + return werr + end + end + end + return nil + end + local werr = walk(root , "", 0) + if werr then + return nil, werr + end + return out, nil +end + +-- read(vol, entry) -> the file's bytes +function Fat.read(v, e) +if e.dir or e.size == 0 then + return buffer.create(0), nil + end + if e.cluster < 2 then + return nil, "file without clusters" + end + return readChain(v, e.cluster, e.size) +end +-- ------------------------------------------------------------------------------------------------ write + + + + + + + + +local GEOMETRY = { + [360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 }, + [720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 }, + [1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 }, + [1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 }, + [2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 }, +} + +local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$" + +local function toDos(t) +local v = Archive.toDos(t) + return math.floor(v / 65536), v % 65536 +end + +-- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed + + +local function shortName(name, used) +local base, ext = string.match(name, "^(.*)%.([^%.]*)$") + if not base or base == "" then + base, ext = name, "" + end + local b, e = base , ext -- a plain 8.3 name, all upper or all lower case per part: no long name needed + +if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then + local bu, eu = string.upper(b), string.upper(e) + local nt = 0 + local ok = true + if b ~= bu then + if b == string.lower(b) then + nt = bit32.bor(nt, 0x08) + else + ok = false + end + end + if e ~= eu then + if e == string.lower(e) then + nt = bit32.bor(nt, 0x10) + else + ok = false + end + end + local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu) + if ok and not used[raw] then + used[raw] = true + return raw, nt, false + end + end + local function clean(s) +s = string.upper((string.gsub(s, "[%s%.]", ""))) + return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_")) + end + local cb, ce = clean(b), string.sub(clean(e), 1, 3) + if cb == "" then + cb = "_" + end + for n = 1, 999999 do + local tail = "~" .. n + local raw = string.sub(cb, 1, 8 - #tail) .. tail + raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce) + if not used[raw] then + used[raw] = true + return raw, 0, true + end + end + return " ___", 0, true +end + +-- the directory entries (32 bytes each) of a node's children +local function dirEntries(n, parentCluster, isRoot, label) +local w = {} + local function entry(raw, attr, nt, cluster, size, mtime) + local e = buffer.create(32) + buffer.writestring(e, 0, raw) + buffer.writeu8(e, 11, attr) + buffer.writeu8(e, 12, nt) + local date, time = toDos(mtime) + buffer.writeu16(e, 14, time) + buffer.writeu16(e, 16, date) + buffer.writeu16(e, 18, date) + buffer.writeu16(e, 22, time) + buffer.writeu16(e, 24, date) + buffer.writeu16(e, 26, cluster) + buffer.writeu32(e, 28, size) + table.insert(w, e) + end + if isRoot and label then + local l = string.sub(string.upper(label), 1, 11) + entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime) + end + if not isRoot then + entry(". ", 0x10, 0, n.cluster, 0, n.mtime) + entry(".. ", 0x10, 0, parentCluster, 0, n.mtime) + end + local used= {} + for _, c in __iter(n.children) do + local raw, nt, needLong = shortName(c.name, used) + if needLong then + local cps = {} + if utf8.len(c.name) then + for _, cp in __iter(utf8.codes(c.name)) do + table.insert(cps, cp > 0xFFFF and 0x5F or cp) + end + else + for i = 1, #c.name do + table.insert(cps, (string.byte(c.name, i))) + end + end + local count = math.ceil(#cps / 13) + local sum = shortChecksum(raw) + for s = count, 1, -1 do + local e = buffer.create(32) + buffer.writeu8(e, 0, (s == count and{(bit32.bor(s, 0x40) )}or{s})[1]) + buffer.writeu8(e, 11, 0x0F) + buffer.writeu8(e, 13, sum) + local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 } + for k = 1, 13 do + local i = (s - 1) * 13 + k + local v = (i <= #cps and{cps[i] }or{i == #cps + 1 and 0 or 0xFFFF +})[1] buffer.writeu16(e, slots[k], v) + end + table.insert(w, e) + end + end + entry(raw, c.dir and 0x10 or 0x20, nt, c.cluster, c.dir and 0 or buffer.len(c.data or buffer.create(0)), c.mtime) + end + local out = buffer.create(#w * 32) + for i, e in __iter(w) do + buffer.copy(out, (i - 1) * 32, e) + end + return out +end + +-- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths) +function Fat.write(files, opts) +local o= opts or {} + local g = GEOMETRY[o.size or 1440] + if not g then + return nil, "size must be 360, 720, 1200, 1440 or 2880" + end + local bps = 512 + local root= { name = "", dir = true, children = {}, byName = {}, cluster = 0 } + local function node(path, isDir) +local cur = root + local parts = string.split(path, "/") + for i, p in __iter(parts) do + if p ~= "" and p ~= "." then + if p == ".." then + return nil, "'..' in a path" + end + local last = i == #parts or (i == #parts - 1 and parts[#parts] == "") + local child= cur.byName[string.lower(p)] + if not child then + local nc= { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 } + cur.byName[string.lower(p)] = nc + table.insert(cur.children, nc) + child = nc + elseif not child.dir and (not last or isDir) then + return nil, p .. " is both a file and a directory" + end + cur = child +end + end + return cur, nil + end + for _, f in __iter(files) do + local n, err = node(f.name, f.dir == true) + if not n then + return nil, err + end + if n ~= root then + n.mtime = f.mtime + if not n.dir then + n.data = f.data or buffer.create(0) + end + end + end + local csize = g.spc * bps + local dataSector = 1 + 2 * g.fat + math.floor(g.root * 32 / bps +) local clusters = math.floor((g.sectors - dataSector) / g.spc +) local img = buffer.create(g.sectors * bps) + local fat = buffer.create(g.fat * bps) + local nextFree = 2 + local function setFat(c, v) + local p = c + math.floor(c / 2 +) local w = buffer.readu16(fat, p) + if c % 2 == 0 then + w = bit32.bor(bit32.band(w, 0xF000), v) + else + w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4)) + end + buffer.writeu16(fat, p, w) + end + local function alloc(bytes) +local n = math.max(1, math.ceil(bytes / csize)) + if nextFree + n - 1 > clusters + 1 then + return nil + end + local first = nextFree + for k = 0, n - 1 do + setFat(first + k, k == n - 1 and 0xFFF or first + k + 1) + end + nextFree =nextFree+ n + return first + end + -- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first + local function place(n) +for _, c in __iter(n.children) do + if c.dir then + local size = buffer.len(dirEntries(c, 0, false, nil)) + local cl = alloc(size) + if not cl then + return "disk full" + end + c.cluster = cl + local err = place(c) + if err then + return err + end + elseif c.data and buffer.len(c.data) > 0 then + local cl = alloc(buffer.len(c.data)) + if not cl then + return "disk full" + end + c.cluster = cl + local at = (dataSector + (cl - 2) * g.spc) * bps + buffer.copy(img, at, c.data) + end + end + return nil + end + local perr = place(root) + if perr then + return nil, "limit: " .. perr + end + local function writeDirs(n, parent) +for _, c in __iter(n.children) do + if c.dir then + local d = dirEntries(c, parent, false, nil) + buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d) + local err = writeDirs(c, c.cluster) + if err then + return err + end + end + end + return nil + end + writeDirs(root, 0) + local rootDir = dirEntries(root, 0, true, o.label) + if buffer.len(rootDir) > g.root * 32 then + return nil, "limit: too many entries in the root directory" + end + buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir) + setFat(0, 0xF00 + g.media) + setFat(1, 0xFFF) + buffer.copy(img, bps, fat) + buffer.copy(img, (1 + g.fat) * bps, fat) + -- boot sector + buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") + buffer.writeu16(img, 11, bps) + buffer.writeu8(img, 13, g.spc) + buffer.writeu16(img, 14, 1) + buffer.writeu8(img, 16, 2) + buffer.writeu16(img, 17, g.root) + buffer.writeu16(img, 19, g.sectors) + buffer.writeu8(img, 21, g.media) + buffer.writeu16(img, 22, g.fat) + buffer.writeu16(img, 24, g.spt) + buffer.writeu16(img, 26, g.heads) + buffer.writeu8(img, 36, 0) + buffer.writeu8(img, 38, 0x29) + buffer.writeu32(img, 39, o.serial or 0x12345678) + local label = string.upper(string.sub(o.label or "NO NAME", 1, 11)) + buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ") + buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code) + buffer.writeu8(img, 510, 0x55) + buffer.writeu8(img, 511, 0xAA) + return img, nil +end + +return Fat +end +__FILES["containers/Iso9660"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary, +-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross +-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is +-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names +-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the +-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE +-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock +-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog +-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet +-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns +-- the stored bytes), UDF, writing. +-- +-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err +-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents) +local Err = __include("core/Err") +local Types = __include("Types") +local Text = __include("codecs/text/Text") + +local Iso9660 = {} + + + + + + + + + + + + + + + + + + + + + + + + +local SECTOR = 2048 +local S_TYPES= { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" } + +-- ------------------------------------------------------------------------------------------------ fields +local function u16(b, o) +return buffer.readu16(b, o) +end +local function u32(b, o) +return buffer.readu32(b, o) +end +local function str(b, o, n) +return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", "")) +end + +-- a 7-byte directory record date -> unix seconds +local function recDate(b, o) +local y = buffer.readu8(b, o) + local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2) + if m < 1 or m > 12 or d < 1 or d > 31 then + return nil + end + local off = buffer.readi8(b, o + 6) + return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 }) +end + +-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds +local function longDate(b, o) +local s = buffer.readstring(b, o, 16) + local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$") + if not y or tonumber(y) == 0 then + return nil + end + local off = buffer.readi8(b, o + 16) + return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 }) +end +-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge +-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } } + + + +local function suspEntries(b, base, limit, o, e, bs, budget) +local out = {} + while o + 4 <= e do + local sig = buffer.readstring(b, o, 2) + local len = buffer.readu8(b, o + 2) + if len < 4 or o + len > e then + break + end + if sig == "ST" then + break + elseif sig == "CE" and len >= 28 then + local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20) + local at = base + blk * bs + off + budget[1]=budget[1]- 1 + if budget[1] < 0 or at < base or at + n > limit or n > 65536 then + break + end + -- the rest of this area first, then the continuation (it holds what did not fit) + local rest = suspEntries(b, base, limit, o + len, e, bs, budget) + for _, x in __iter(rest) do + table.insert(out, x) + end + local cont = suspEntries(b, base, limit, at, at + n, bs, budget) + for _, x in __iter(cont) do + table.insert(out, x) + end + return out + end + table.insert(out, { sig, o, len }) + o =o+ len + end + return out +end + +-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs } +local function rockRidge(b, base, limit, o, e, bs) +local rr= {} + local name= nil + local slParts= nil + local slRoot = false + local slCont = false + for _, x in __iter(suspEntries(b, base, limit, o, e, bs, { 32 })) do + local sig, at, len = x[1], x[2], x[3] + if sig == "NM" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + if bit32.band(flags, 6) == 0 then + name = name or {} + table.insert(name , buffer.readstring(b, at + 5, len - 5)) + end + elseif sig == "PX" and len >= 36 then + rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28) + elseif sig == "PN" and len >= 20 then + rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12) + elseif sig == "TF" and len >= 5 then + local flags = buffer.readu8(b, at + 4) + local w = bit32.band(flags, 0x80) ~= 0 and 17 or 7 + local q = at + 5 + for bit = 0, 6 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + if q + w > at + len then + break + end + if bit == 1 then + rr.mtime = (w == 17 and{(longDate(b, q) )}or{(recDate(b, q) +)})[1] end + q =q+ w + end + end + elseif sig == "SL" and len >= 5 then + slParts = slParts or {} + local parts = slParts +local q = at + 5 + while q + 2 <= at + len do + local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1) + if q + 2 + cl > at + len then + break + end + local piece = bit32.band(cf, 2) ~= 0 and"." or(bit32.band(cf, 4) ~= 0 and".." or buffer.readstring(b, q + 2, cl) +) if bit32.band(cf, 8) ~= 0 then + slRoot = #parts == 0 + piece = "" + end + if slCont and #parts > 0 then +do local __DARKLUA_VAR=#parts parts[__DARKLUA_VAR]=parts[__DARKLUA_VAR].. piece +end elseif bit32.band(cf, 8) == 0 or #parts > 0 then + table.insert(parts, piece) + end + slCont = bit32.band(cf, 1) ~= 0 + q =q+ (2 + cl +) end + elseif sig == "CL" and len >= 12 then + rr.child = u32(b, at + 4) + elseif sig == "RE" then + rr.relocated = true + elseif sig == "ZF" then + rr.zisofs = true + end + end + if name then + rr.name = table.concat(name) + end + if slParts then + rr.link = (slRoot and"/" or"") .. table.concat(slParts, "/") + end + return rr +end +-- ------------------------------------------------------------------------------------------------ directories +-- the records of a directory extent (without "." and "..") | nil, Err + + + + + + + + + + + + + +local function records(b, base, limit, at, size, bs, joliet, rrSkip) +if at + size > limit then + return nil, Err.new(Err.TRUNCATED, "directory past the end", at) + end + local out= {} + local p = at + local e = at + size + while p < e do +local __DARKLUA_CONTINUE_7=false repeat local len = buffer.readu8(b, p) + if len == 0 then + p = at + (math.floor((p - at) / SECTOR )+ 1) * SECTOR -- the rest of the sector is padding +__DARKLUA_CONTINUE_7=true break + end + if len < 34 or p + len > e then + return nil, Err.new(Err.CORRUPT, "bad directory record", p) + end + local nl = buffer.readu8(b, p + 32) + if 33 + nl > len then + return nil, Err.new(Err.CORRUPT, "bad name length", p + 32) + end + local raw = buffer.readstring(b, p + 33, nl) + if raw ~= "\0" and raw ~= "\1" then + local flags = buffer.readu8(b, p + 25) + local name + if joliet then + name = Text.utf16(b, p + 33, nl, true) + else + name = raw + end + name = string.gsub(name, ";%d*$", "") + if not joliet and bit32.band(flags, 2) == 0 then + name = string.gsub(name, "%.$", "") + end + local r= { + name = name, + dir = bit32.band(flags, 2) ~= 0, + lba = u32(b, p + 2), + size = u32(b, p + 10), + ear = buffer.readu8(b, p + 1), + flags = flags, + interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0, + mtime = recDate(b, p + 18), + rr = nil, + } + if rrSkip then + local su = p + 33 + nl + (nl % 2 == 0 and 1 or 0) + rrSkip + r.rr = rockRidge(b, base, limit, su, p + len, bs) + end + table.insert(out, r) + end + p =p+ len +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + return out, nil +end + +-- the root record of a volume descriptor at vd -> lba, size +local function root(b, vd) +return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10) +end + +-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length +local function rockRidgeSkip(b, base, limit, lba, bs) +local p = base + lba * bs + if p + 34 > limit then + return nil + end + local len = buffer.readu8(b, p) + local nl = buffer.readu8(b, p + 32) + local su = p + 33 + nl + (nl % 2 == 0 and 1 or 0) + if len < 34 or su + 7 > p + len or p + len > limit then + return nil + end + if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then + return buffer.readu8(b, su + 6) + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ El Torito +local function boot(b, base, limit, vd, bs) +if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then + return nil + end + local cat = u32(b, vd + 0x47) + local p = base + cat * bs + local info= { catalog = cat } + if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then + return info + end + local sum = 0 + for i = 0, 30, 2 do + sum =sum+ u16(b, p + i) + end + info.valid = sum % 65536 == 0 + info.platform = buffer.readu8(b, p + 1) + info.id = str(b, p + 4, 24) + local d = p + 32 + info.bootable = buffer.readu8(b, d) == 0x88 + info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk + info.loadSegment = u16(b, d + 2) + info.systemType = buffer.readu8(b, d + 4) + info.sectors = u16(b, d + 6) -- 512-byte virtual sectors + info.lba = u32(b, d + 8) + return info +end + +-- ------------------------------------------------------------------------------------------------ read +-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err +function Iso9660.read(b, offset, length, opts) +local base = offset or 0 + local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base))) + local o= opts or {} + local maxEntries = o.maxEntries or 1e6 + local pvd= nil + local svd= nil + local jolietLevel= nil + local bootInfo = nil + local p = base + 16 * SECTOR + for _ = 1, 64 do + if p + SECTOR > limit then + return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p) + end + if buffer.readstring(b, p + 1, 5) ~= "CD001" then + return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p) + end + local t = buffer.readu8(b, p) + if t == 255 then + break + elseif t == 1 and not pvd then + pvd = p + elseif t == 2 then + local esc = buffer.readstring(b, p + 88, 3) + if esc == "%/@" or esc == "%/C" or esc == "%/E" then + svd = p + jolietLevel = esc == "%/@" and 1 or(esc == "%/C" and 2 or 3 +) end + elseif t == 0 then + bootInfo = bootInfo or { vd = p } + end + p =p+ SECTOR + end + if not pvd then + return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR) + end + local pv = pvd +local bs = u16(b, pv + 128) + if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then + return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128) + end + local info= { + blockSize = bs, + blocks = u32(b, pv + 80), + systemId = str(b, pv + 8, 32), + volumeId = str(b, pv + 40, 32), + volumeSet = str(b, pv + 190, 128), + publisher = str(b, pv + 318, 128), + preparer = str(b, pv + 446, 128), + application = str(b, pv + 574, 128), + created = longDate(b, pv + 813), + modified = longDate(b, pv + 830), + joliet = jolietLevel, + } + if bootInfo then + info.boot = boot(b, base, limit, bootInfo.vd, bs) + end + local rlba, rsize = root(b, pv) + local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs) + info.rockRidge = rrSkip ~= nil + local tree = o.prefer or (rrSkip and"rockridge" or(svd and"joliet" or"iso9660")) + if tree == "joliet" and not svd then + tree = "iso9660" + elseif tree == "rockridge" and not rrSkip then + tree = "iso9660" + end + info.tree = tree + local joliet = tree == "joliet" + local useRR = (tree == "rockridge" and{rrSkip }or{nil +})[1] if joliet then + rlba, rsize = root(b, svd ) + end + if tree == "joliet" then + info.volumeId = (string.gsub(Text.utf16(b, (svd ) + 40, 32, true), "[ %z]+$", "")) + end + local out= {} + local visited= {} + local stack = { { lba = rlba, size = rsize, path = "" } } + local relocatedDirs= {} + while #stack > 0 do +local __DARKLUA_CONTINUE_10=false repeat local d = (table.remove(stack) ) +if visited[d.lba] then +__DARKLUA_CONTINUE_10=true break + end + visited[d.lba] = true + local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR) + if not list then + return nil, err + end + local i = 1 + local subdirs = {} + while i <= #list do +local __DARKLUA_CONTINUE_11=false repeat local r = list[i] + -- multi-extent: this record and the following ones of the same name + local extents= { { at = base + (r.lba + r.ear) * bs, size = r.size } } + local total = r.size + local last = r + while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do + i =i+ 1 + last = list[i] + table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size }) + total =total+ last.size + end + i =i+ 1 + if bit32.band(r.flags, 4) ~= 0 then +__DARKLUA_CONTINUE_11=true break -- an associated file (resource fork) + end + local rr= r.rr + if rr and rr.relocated then +__DARKLUA_CONTINUE_11=true break -- shown where its CL placeholder is + end + local name = (rr and rr.name and{rr.name }or{r.name +})[1] local path = d.path .. name + local isDir = r.dir + local lba, size= r.lba, r.size + if rr and rr.child then + -- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's + isDir = true + lba = rr.child + local q = base + lba * bs + size = (q + 14 <= limit and{(u32(b, q + 10) )}or{0 +})[1] end + local typ = isDir and"5" or"0" + if rr and rr.mode then + typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ + end + local e= { + name = path, + dir = isDir, + size = (isDir or typ ~= "0" )and 0 or total, + extents = (isDir or typ ~= "0" )and{} or extents, + mtime = (rr and rr.mtime and{rr.mtime }or{r.mtime})[1], + type = typ, + mode = (rr and rr.mode and{(bit32.band(rr.mode, 0xFFF) )}or{nil})[1], + uid = rr and rr.uid, + gid = rr and rr.gid, + nlink = rr and rr.nlink, + link = (rr and typ == "2" and{rr.link }or{nil})[1], + rdev = rr and rr.rdev, + hidden = bit32.band(r.flags, 1) ~= 0 and true or nil, + interleaved = r.interleave and true or nil, + zisofs = rr and rr.zisofs and true or nil, + } + table.insert(out, e) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + if isDir then + table.insert(subdirs, { lba = lba, size = size, path = path .. "/" }) + end +__DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end + for k = #subdirs, 1, -1 do + table.insert(stack, subdirs[k]) + end + if useRR then + for _, r in __iter(list) do + if r.rr and r.rr.relocated then + relocatedDirs[d.path] = true + end + end + end +__DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end + -- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it + if useRR then + for dirPath in __iter(relocatedDirs) do + local name = string.sub(dirPath, 1, -2) + local holds = false + for _, e in __iter(out) do + if string.sub(e.name, 1, #dirPath) == dirPath then + holds = true + break + end + end + if not holds then + for k, e in __iter(out) do + if e.name == name then + table.remove(out, k) + break + end + end + end + end + end + -- archive order: depth-first walk order is kept; directories sorted as the image stores them + return out, info +end + +-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err +function Iso9660.extract(b, e, limit) +if e.interleaved then + return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name) + end + local lim = limit or buffer.len(b) + local out = buffer.create(e.size) + local q = 0 + for _, x in __iter(e.extents) do + if x.at < 0 or x.at + x.size > lim then + return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at) + end + buffer.copy(out, q, b, x.at, x.size) + q =q+ x.size + end + return out, nil +end + +-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16 +function Iso9660.valid(b, offset) +local p = (offset or 0) + 16 * SECTOR + return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001" +end + +return Iso9660 +end +__FILES["containers/IsoBmff"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) +-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, +-- mov, heif, avif build on it. Written from the specifications; no third-party code. +-- +-- local IsoBmff = require("rosetta.containers.IsoBmff") +-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) +-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) +-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) +-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs +-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes +-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) +-- +-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit +-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', +-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), +-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local Demux = __include("containers/IsoBmff/Demux") +local Meta = __include("containers/IsoBmff/Meta") +local Mux = __include("containers/IsoBmff/Mux") + +local IsoBmff = {} +IsoBmff.Box = Box +IsoBmff.Demux = Demux +IsoBmff.Meta = Meta + + + + + + + + + +local TOP= { + ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true, + styp = true, sidx = true, meta = true, uuid = true, PICT = true, +} + +-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, +-- nil when it is not an ISO BMFF file +function IsoBmff.sniff(r) +local head = r:peek(12) + if #head < 8 then + return nil + end + local typ = string.sub(head, 5, 8) + if typ == "ftyp" then + return (#head >= 12 and{(string.sub(head, 9, 12) )}or{"" +})[1] end + if TOP[typ] then + local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4) + if size == 1 or size == 0 or size >= 8 then + return "" + end + end + return nil +end + +-- parse(r, opts?) -> Movie | nil, Err +function IsoBmff.parse(r, opts) +return Demux.parse(r, opts) +end + +-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) +function IsoBmff.tags(r, movie) +local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") + return Meta.tags(r.buf, ilst) +end + +-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) +function IsoBmff.items(r, movie) +local meta = Box.path(movie.boxes, "meta") + if not meta then + return nil, Err.new(Err.CORRUPT, "no top-level meta box") + end + return Meta.items(r.buf, meta) +end + +-- itemData(r, items, id) -> buffer | nil, Err +function IsoBmff.itemData(r, items, id) +return Meta.itemData(r.buf, r.base, r.limit, items, id) +end + +-- sample(r, track, i) -> a copy of sample i (1-based) +function IsoBmff.sample(r, t, i) +if i < 1 or i > t.sampleCount then + return nil + end + local n = t.sizes[i] + local out = buffer.create(n) + buffer.copy(out, 0, r.buf, t.offsets[i], n) + return out +end + +-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / +-- dts / duration in their track's timescale ticks and a copy of the sample bytes. +function IsoBmff.demux(r, opts) +local movie, err = Demux.parse(r, opts) + if not movie then + return nil, err + end + local cursor= {} + local byId= {} + for _, t in __iter(movie.tracks) do + cursor[t.id] = 1 + byId[t.id] = t + end + local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie } + local function packet(t, i) +local dts = t.dts[i] + local cts = t.cts + return { + track = t.id, + dts = dts, + pts = dts + ((cts and{cts[i] or 0 }or{0})[1]), + duration = t.durations[i], + keyframe = t.sync == nil or (t.sync )[i] == true, + data = IsoBmff.sample(r, t, i), + index = i, + } + end + function dmx.packets(_self, trackId) +return function() +if trackId then + local t = byId[trackId] + if not t then + return nil + end + local i = cursor[trackId] + if i > t.sampleCount then + return nil + end + cursor[trackId] = i + 1 + return packet(t, i) + end + -- all tracks in file order + local best= nil + local bestOff = math.huge + for _, t in __iter(movie.tracks) do + local i = cursor[t.id] + if i <= t.sampleCount and t.offsets[i] < bestOff then + best, bestOff = t, t.offsets[i] + end + end + if not best then + return nil + end + local i = cursor[best.id] + cursor[best.id] = i + 1 + return packet(best, i) + end + end + -- seek(seconds): every track to its last sync sample at or before the time + function dmx.seek(_self, seconds) + for _, t in __iter(movie.tracks) do + local target = seconds * t.timescale + local lo, hi = 1, t.sampleCount + local found = 1 + while lo <= hi do + local mid = math.floor((lo + hi) / 2 +) if t.dts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if t.sync then + while found > 1 and not (t.sync )[found] do + found =found- 1 + end + end + cursor[t.id] = found + end + end + return dmx, nil +end + +-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) +function IsoBmff.mux(spec) +return Mux.mux(spec) +end + +return IsoBmff +end +__FILES["containers/IsoBmff/Box"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit +-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container +-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...). +-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws. +local Err = __include("core/Err") + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring +local byteswap = bit32.byteswap + +local Box = {} + +-- plain container boxes: their payload is a list of boxes + + + + + + + + + + + +local CONTAINERS = { + moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true, + mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true, + schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true, + strk = true, strd = true, grpl = true, meco = true, mere = true, +} +-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes +local FULL_CONTAINERS= { meta = 0, iref = 0, dref = 4 } +Box.CONTAINERS = CONTAINERS + +local function be32(b, o) +return byteswap(readu32(b, o)) +end +Box.be32 = be32 + +-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes +local function isIlstItem(parentType) +return parentType == "ilst" +end + +-- header(buf, p, limit) -> Box (without children) | nil, Err +function Box.header(b, p, limit) +if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) + end + local size = be32(b, p) + local typ = readstring(b, p + 4, 4) + local data = p + 8 + if size == 1 then + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p) + end + size = be32(b, p + 8) * 4294967296 + be32(b, p + 12) + data = p + 16 + elseif size == 0 then + size = limit - p + end + local uuid= nil + if typ == "uuid" then + if data + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p) + end + uuid = readstring(b, data, 16) + data =data+ 16 + end + if size < data - p then + return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p) + end + local stop = p + size + local truncated= nil + if stop > limit then + stop = limit + truncated = true + end + return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil +end + +-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A +-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. +function Box.list(b, p, limit, parentType, depth) +local d = depth or 0 + local out= {} + local firstErr= nil + if d > 32 then + return out, Err.new(Err.CORRUPT, "boxes nested too deep", p) + end + while p + 8 <= limit do + local box, err = Box.header(b, p, limit) + if not box then + firstErr = firstErr or err + break + end + if box.truncated then + firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p) + end + local t = box.type + local kids= nil + local kerr= nil + if CONTAINERS[t] or isIlstItem(parentType) then + kids, kerr = Box.list(b, box.data, box.stop, t, d + 1) + elseif FULL_CONTAINERS[t] then + local q = box.data + 4 + FULL_CONTAINERS[t] + -- QuickTime writes udta/meta as a plain container: its first child box follows directly + if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then + q = box.data + end + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + elseif t == "iinf" then + if box.data + 4 <= box.stop then + local v = readu8(b, box.data) + local q = box.data + 4 + (v == 0 and 2 or 4) + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + end + end + box.children = kids + if kerr then + firstErr = firstErr or kerr + end + table.insert(out, box) + if box.stop <= p then + break + end + p = box.stop + end + return out, firstErr +end + +-- child(box, type) -> the first child of that type +function Box.child(box, typ) +if not box or not box.children then + return nil + end + for _, c in __iter(box.children) do + if c.type == typ then + return c + end + end + return nil +end + +-- children(box, type) -> every child of that type +function Box.childrenOf(box, typ) +local out = {} + if box and box.children then + for _, c in __iter(box.children) do + if c.type == typ then + table.insert(out, c) + end + end + end + return out +end + +-- path(boxes or box, "moov/trak/mdia") -> the first box along the path +function Box.path(root, path) +local cur= root + for part in __iter(string.gmatch(path, "[^/]+")) do + if cur == nil then + return nil + end + local list = ((cur.children ~= nil or cur.type ~= nil )and{cur.children }or{cur +})[1] local found = nil + if list then + for _, c in __iter(list) do + if c.type == part then + found = c + break + end + end + end + cur = found + end + return cur +end + +-- version / flags of a full box +function Box.fullHeader(b, box) +if box.data + 4 > box.stop then + return -1, 0 + end + local v = be32(b, box.data) + return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF) +end + +return Box +end +__FILES["containers/IsoBmff/Demux"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): +-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration +-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / +-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). +-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the +-- reader's buffer. Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") +local QtPalette = __include("containers/IsoBmff/QtPalette") + +local readstring = buffer.readstring + +local function readu16be(b, o) +return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + +local Demux = {} +-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the +-- sample tables and the ISO facts + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local HANDLER_KIND= { + soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle", + sbtl = "subtitle", clcp = "subtitle", +} +local CODEC= { + mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3", + lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm", + ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb", + avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9", + mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1", + ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text", +} +-- esds objectTypeIndication -> codec +local OTI= { + [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1", + [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3", + [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis", +} +-- the box holding each video / audio codec's configuration +local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" } +local FULL_CONFIG= { vpcC = true, dfLa = true, alac = true } + +local function payload(b, box, skip) +local o = box.data + (skip or 0) + local n = math.max(0, box.stop - o) + local out = buffer.create(n) + if n > 0 then + buffer.copy(out, 0, b, o, n) + end + return out +end + +local function reader(b, box) +return Bytes.reader(b, box.data, box.stop - box.data) +end + +-- expandable descriptor length (ISO 14496-1 8.3.3) +local function descLen(r) +local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n +end + +-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate +function Demux.esds(b, box) +local r = reader(b, box) + r:skip(4) -- version / flags + if r:u8() ~= 3 then + return nil, nil, nil + end + descLen(r) + r:skip(2) -- ES_ID + local flags = r:u8() + if bit32.band(flags, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(flags, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(flags, 0x20) ~= 0 then + r:skip(2) + end + if r:u8() ~= 4 then + return nil, nil, nil + end + local dlen = descLen(r) + local dstart = r.pos + local oti = r:u8() + r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate + local avg = r:u32be() + local dsi= nil + if r.pos < dstart + dlen and r:u8() == 5 then + local n = descLen(r) + if n > 0 and r:need(n) then + dsi = r:bytes(n) + end + end + if r.err then + return oti, nil, nil + end + return oti, dsi, avg +end + +-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t +local function sampleEntry(b, e, handler, t) + local r = reader(b, e) + r:skip(6) + r:skip(2) -- data reference index + local typ = e.type + t.entry = typ + t.codec = CODEC[typ] or typ + local kind = t.kind + local childStart + if kind == "audio" then + local version = r:u16be() + r:skip(2 + 4) -- revision, vendor + local channels = r:u16be() + local bits = r:u16be() + r:skip(4) -- compression id, packet size + local rate = r:u32be() / 65536 + if version == 1 then + r:skip(16) + elseif version == 2 then + r:skip(4) + rate = r:f64be() + channels = r:u32be() + r:skip(4) + bits = r:u32be() + local lpcmFlags = r:u32be() + r:skip(8) + if typ == "lpcm" then + t.pcm = { + bits = bits, + float = bit32.band(lpcmFlags, 1) ~= 0, + little = bit32.band(lpcmFlags, 2) == 0, + } + end + end + t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits + if not t.pcm and t.codec == "pcm" then + local B= { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 } + t.pcm = { + bits = B[typ] or bits, + float = typ == "fl32" or typ == "fl64", + little = typ == "sowt", + } + end + childStart = r.pos + elseif kind == "video" then + r:skip(16) + t.width = r:u16be() + t.height = r:u16be() + r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) + childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, typ == "cvid" and"cinepak" or typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end + else + childStart = r.pos + end + if r.err then + t.entryBoxes = {} + return + end + local kids = Box.list(b, childStart, e.stop, typ) + t.entryBoxes = kids + -- QuickTime puts the codec boxes inside 'wave' + local all = table.clone(kids) + local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } , "wave") + if wave and wave.children then + for _, c in __iter(wave.children) do + table.insert(all, c) + end + end + local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } +local esds = Box.child(holder, "esds") + if esds then + local oti, dsi, avg = Demux.esds(b, esds) + t.objectType = oti + if oti and OTI[oti] then + t.codec = OTI[oti] + end + t.config = dsi + if avg and avg > 0 then + t.bitrate = avg + end + end + if typ == "alac" then + local a = Box.child(holder, "alac") + if a then + t.config = payload(b, a, 4) + end + end + for _, name in __iter(CONFIG_BOX) do + local c = Box.child(holder, name) + if c then + t.config = payload(b, c, FULL_CONFIG[name] and 4 or 0) + break + end + end +end + +-- media handler / header / sample tables of one trak -> Track | nil, Err +local function track(b, trak, movieTimescale, trex, o) +local tkhd = Box.child(trak, "tkhd") + local mdia = Box.child(trak, "mdia") + if not tkhd or not mdia then + return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start) + end + local t= { + id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0, + entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {}, + } + do + local r = reader(b, tkhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.id = r:u32be() + r:skip(4 + 8) + else + r:skip(8) + t.id = r:u32be() + r:skip(4 + 4) + end + r:skip(8 + 2 + 2 + 2 + 2 + 36) + local w, h = r:u32be() / 65536, r:u32be() / 65536 + if r.err then + return nil, r.err + end + if w > 0 and h > 0 then + t.width, t.height = math.floor(w), math.floor(h) + end + end + local mdhd = Box.child(mdia, "mdhd") + if mdhd then + local r = reader(b, mdhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.timescale = r:u32be() + t.mediaDuration = r:u64be() + else + r:skip(8) + t.timescale = r:u32be() + t.mediaDuration = r:u32be() + end + local lang = r:u16be() + if not r.err and lang ~= 0 and lang ~= 0x7FFF then + t.language = string.char( + 96 + bit32.band(bit32.rshift(lang, 10), 31), + 96 + bit32.band(bit32.rshift(lang, 5), 31), + 96 + bit32.band(lang, 31) + ) + end + if t.timescale == 0 then + t.timescale = 1 + end + end + local hdlr = Box.child(mdia, "hdlr") + if hdlr and hdlr.data + 12 <= hdlr.stop then + t.handler = readstring(b, hdlr.data + 8, 4) + end + t.kind = HANDLER_KIND[t.handler] or "data" + local stbl = Box.path(mdia, "minf/stbl") + if not stbl then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) + end + -- sample descriptions + local stsd = Box.child(stbl, "stsd") + if stsd and stsd.data + 8 <= stsd.stop then + local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") + if entries[1] then + sampleEntry(b, entries[1], t.handler, t) + end + t.sampleEntries = entries + end + -- edit list + local elst = Box.path(trak, "edts/elst") + if elst then + local r = reader(b, elst) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n <= math.floor((elst.stop - elst.data) / 12 )then + local edits= {} + for _ = 1, n do + local dur, mt +if v == 1 then + dur, mt = r:u64be(), (r:i64be() ) +else + dur, mt = r:u32be(), (r:i32be() ) +end + local rate = r:i32be() / 65536 + if r.err then + break + end + table.insert(edits, { duration = dur, mediaTime = mt, rate = rate }) + end + t.edits = edits + local play = 0 + local started = false + for _, ed in __iter(edits) do + if ed.mediaTime == -1 then + if not started then + t.delay =t.delay+ ed.duration + end + else + if not started then + t.skip = ed.mediaTime + started = true + end + play =play+ ed.duration * t.timescale / math.max(1, movieTimescale) + end + end + if started and play > 0 then + t.playDuration = math.floor(play + 0.5) + end + end + end + -- sample sizes + local maxSamples = o.maxSamples or 2 ^ 25 + local sizes = t.sizes + local count = 0 + local stsz = Box.child(stbl, "stsz") + local stz2 = Box.child(stbl, "stz2") + if stsz then + local r = reader(b, stsz) + r:skip(4) + local fixed = r:u32be() + count = r:u32be() + if r.err then + return nil, r.err + end + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start) + end + if fixed ~= 0 then + for i = 1, count do + sizes[i] = fixed + end + else + if count * 4 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start) + end + for i = 1, count do + sizes[i] = r:u32be() + end + end + elseif stz2 then + local r = reader(b, stz2) + r:skip(4 + 3) + local fieldSize = r:u8() + count = r:u32be() + if r.err then + return nil, r.err + end + if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then + return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start) + end + if count * fieldSize / 8 > r:remaining() + 1 then + return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start) + end + for i = 1, count do + if fieldSize == 16 then + sizes[i] = r:u16be() + elseif fieldSize == 8 then + sizes[i] = r:u8() + else + local byte = r:peekU8() + if i % 2 == 1 then + sizes[i] = bit32.rshift(math.max(byte, 0), 4) + else + sizes[i] = bit32.band(math.max(byte, 0), 15) + r:skip(1) + end + end + end + end + -- decode times + local dts, durs = t.dts, t.durations + local stts = Box.child(stbl, "stts") + if stts and count > 0 then + local r = reader(b, stts) + r:skip(4) + local n = r:u32be() + if n * 8 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start) + end + local i, time = 1, 0 + for _ = 1, n do + local c, d = r:u32be(), r:u32be() + for _ = 1, c do + if i > count then + break + end + dts[i], durs[i] = time, d + time =time+ d + i =i+ 1 + end + end + -- fewer stts entries than samples: repeat the last duration + local last = (i > 1 and{durs[i - 1] }or{0 +})[1] while i <= count do + dts[i], durs[i] = time, last + time =time+ last + i =i+ 1 + end + else + for i = 1, count do + dts[i], durs[i] = 0, 0 + end + end + -- composition offsets + local ctts = Box.child(stbl, "ctts") + if ctts and count > 0 then + local r = reader(b, ctts) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n * 8 <= r:remaining() then + local cts = table.create(count, 0) + local i = 1 + for _ = 1, n do + local c = r:u32be() + local off = (v == 1 and{(r:i32be() )}or{(r:u32be() +)})[1] if v == 0 and off >= 2147483648 then + off =off- 4294967296 -- writers put negative offsets in version 0 too + end + for _ = 1, c do + if i > count then + break + end + cts[i] = off + i =i+ 1 + end + end + t.cts = cts + end + end + -- sync samples + local stss = Box.child(stbl, "stss") + if stss then + local r = reader(b, stss) + r:skip(4) + local n = r:u32be() + if n * 4 <= r:remaining() then + local sync = {} + for _ = 1, n do + sync[r:u32be()] = true + end + t.sync = sync + end + end + -- chunk offsets + sample-to-chunk -> sample offsets + local stco = Box.child(stbl, "stco") + local co64 = Box.child(stbl, "co64") + local chunks= {} + if stco or co64 then + local box = (stco or co64) +local r = reader(b, box) + r:skip(4) + local n = r:u32be() + local w = co64 and 8 or 4 + if n * w > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start) + end + for i = 1, n do + chunks[i] = (co64 and{(r:u64be() )}or{(r:u32be() +)})[1] end + end + local stsc = Box.child(stbl, "stsc") + local offsets = t.offsets + if count > 0 then + if not stsc or #chunks == 0 then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start) + end + local r = reader(b, stsc) + r:skip(4) + local n = r:u32be() + if n * 12 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) + end + local first, per, desc= {}, {}, {} + for k = 1, n do + first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() + end + local sdi= nil + if n > 0 then + for k = 1, n do + if desc[k] ~= desc[1] then + sdi = table.create(count, 1) + end + end + end + local i = 1 + local base = 0 -- added by the caller (the file's offset in the buffer) + for k = 1, n do + local c0 = first[k] + local c1 = (k < n and((first[k + 1] - 1 ))or((#chunks +))) if c0 < 1 then + return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start) + end + for c = c0, math.min(c1, #chunks) do + local off = chunks[c] + base + for _ = 1, per[k] do + if i > count then + break + end + offsets[i] = off + if sdi then + sdi[i] = desc[k] + end + off =off+ sizes[i] + i =i+ 1 + end + if i > count then + break + end + end + if i > count then + break + end + end + if i <= count then + return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start) + end + t.sampleDescription = sdi + end + t.sampleCount = count + -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024 + -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio. + if t.kind == "audio" and count > 1 and not t.cts and not t.sync then + local fixed = sizes[1] + local uniform = fixed > 0 + for i = 1, count do + if sizes[i] ~= fixed or durs[i] ~= 1 then + uniform = false + break + end + end + if uniform then + local no, ns, nd, nu = {}, {}, {}, {} + local i = 1 + while i <= count do + local k = 1 + while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do + k =k+ 1 + end + table.insert(no, offsets[i]) + table.insert(ns, k * fixed) + table.insert(nd, dts[i]) + table.insert(nu, k) + i =i+ k + end + t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu + t.sampleCount = #no + t.frameSize = fixed + t.sampleDescription = nil + end + end + -- fragment defaults + t.trex = trex[t.id] + return t, nil +end + +-- the movie fragments (moof) after the moov: appends their samples to the tracks +local function fragments(b, fileBase, top, byId, o) +local maxSamples = o.maxSamples or 2 ^ 25 + for _, moof in __iter(top) do +local __DARKLUA_CONTINUE_25=false repeat if moof.type ~= "moof" then +__DARKLUA_CONTINUE_25=true break + end + local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end) + local prevEnd = moofStart + for _, traf in __iter(Box.childrenOf(moof, "traf")) do +local __DARKLUA_CONTINUE_26=false repeat local tfhd = Box.child(traf, "tfhd") + if not tfhd then +__DARKLUA_CONTINUE_26=true break + end + local r = reader(b, tfhd) + r:skip(1) + local flags = r:u24be() + local id = r:u32be() + local t = byId[id] + if r.err or not t then +__DARKLUA_CONTINUE_26=true break + end + local trex = t.trex or {} + local base + if bit32.band(flags, 0x1) ~= 0 then + base = r:u64be() + elseif bit32.band(flags, 0x20000) ~= 0 then + base = moofStart + else + base = prevEnd + end + if bit32.band(flags, 0x2) ~= 0 then + r:skip(4) + end + local defDur = (bit32.band(flags, 0x8) ~= 0 and{(r:u32be() )}or{(trex.duration or 0) +})[1] local defSize = (bit32.band(flags, 0x10) ~= 0 and{(r:u32be() )}or{(trex.size or 0) +})[1] local defFlags = (bit32.band(flags, 0x20) ~= 0 and{(r:u32be() )}or{(trex.flags or 0) +})[1] if r.err then + return r.err + end + local n0 = t.sampleCount + local time = (n0 > 0 and((t.dts[n0] + t.durations[n0] ))or(0 +)) local tfdt = Box.child(traf, "tfdt") + if tfdt then + local q = reader(b, tfdt) + local v = q:u8() + q:skip(3) + local bt = (v == 1 and{(q:u64be() )}or{(q:u32be() +)})[1] if not q.err then + time = bt + end + end + local dataPos = base + for _, trun in __iter(Box.childrenOf(traf, "trun")) do + local q = reader(b, trun) + local v = q:u8() + local tf = q:u24be() + local n = q:u32be() + if q.err then + return q.err + end + if t.sampleCount + n > maxSamples then + return Err.new(Err.LIMIT, "too many fragment samples", trun.start) + end + if bit32.band(tf, 0x1) ~= 0 then + dataPos = base + q:i32be() + end + local firstFlags = (bit32.band(tf, 0x4) ~= 0 and{(q:u32be() )}or{nil +})[1] local per = 0 + for _, bit in __iter({ 0x100, 0x200, 0x400, 0x800 }) do + if bit32.band(tf, bit) ~= 0 then + per =per+ 4 + end + end + if n * per > q:remaining() then + return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start) + end + for k = 1, n do + local dur = (bit32.band(tf, 0x100) ~= 0 and{(q:u32be() )}or{defDur +})[1] local size = (bit32.band(tf, 0x200) ~= 0 and{(q:u32be() )}or{defSize +})[1] local sf = (bit32.band(tf, 0x400) ~= 0 and{(q:u32be() )}or{((k == 1 and firstFlags and{firstFlags }or{defFlags})[1]) +})[1] local cto = 0 + if bit32.band(tf, 0x800) ~= 0 then + cto = (v == 1 and{(q:i32be() )}or{(q:u32be() +)})[1] end + local i = t.sampleCount + 1 + t.sampleCount = i + t.offsets[i] = dataPos + t.sizes[i] = size + t.dts[i] = time + t.durations[i] = dur + if cto ~= 0 or t.cts then + if not t.cts then + t.cts = table.create(i - 1, 0) + end + (t.cts )[i] = cto + end + -- sample_is_non_sync_sample (bit 16) + local nonSync = bit32.band(sf, 0x10000) ~= 0 + if nonSync then + if not t.sync then + local s = {} + for j = 1, i - 1 do + s[j] = true + end + t.sync = s + end + elseif t.sync then + (t.sync )[i] = true + end + time =time+ dur + dataPos =dataPos+ size + end + prevEnd = dataPos + end +__DARKLUA_CONTINUE_26=true until true if not __DARKLUA_CONTINUE_26 then break end end +__DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break end end + return nil +end + +-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) + + + + + + + + + + + + +function Demux.parse(r, opts) +local o= opts or {} + local b = r.buf + local top, terr = Box.list(b, r.base, r.limit) + if #top == 0 then + return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base) + end + local m= { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false } + local ftyp = Box.child({ children = top } , "ftyp") + if ftyp and ftyp.data + 8 <= ftyp.stop then + m.brand = readstring(b, ftyp.data, 4) + m.minor = Box.be32(b, ftyp.data + 4) + local p = ftyp.data + 8 + while p + 4 <= ftyp.stop do + table.insert(m.compatible, readstring(b, p, 4)) + p =p+ 4 + end + end + local moov = Box.child({ children = top } , "moov") + m.moov = moov + if not moov then + return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks + end + local mvhd = Box.child(moov, "mvhd") + local movieDuration = 0 + if mvhd then + local q = reader(b, mvhd) + local v = q:u8() + q:skip(3) + if v == 1 then + q:skip(16) + m.timescale = q:u32be() + movieDuration = q:u64be() + else + q:skip(8) + m.timescale = q:u32be() + movieDuration = q:u32be() + end + if q.err or m.timescale == 0 then + m.timescale = 1000 + end + end + local trex = {} + local mvex = Box.child(moov, "mvex") + if mvex then + m.fragmented = true + for _, x in __iter(Box.childrenOf(mvex, "trex")) do + local q = reader(b, x) + q:skip(4) + local id = q:u32be() + q:skip(4) + local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() } + if not q.err then + trex[id] = d + end + end + end + local byId = {} + for _, trak in __iter(Box.childrenOf(moov, "trak")) do + local t, err = track(b, trak, m.timescale, trex, o) + if not t then + return nil, err + end + table.insert(m.tracks, t) + byId[t.id] = t + end + if m.fragmented then + local ferr = fragments(b, r.base, top, byId, o) + if ferr then + return nil, ferr + end + end + -- durations; drop samples outside the buffer (a truncated file) but keep what is there + for _, t in __iter(m.tracks) do + local n = t.sampleCount + local ticks = t.mediaDuration + if n > 0 then + ticks = math.max(ticks, t.dts[n] + t.durations[n]) + end + t.mediaDuration = ticks + t.duration = ticks / t.timescale + for i = 1, n do + local off = t.offsets[i] + if off < 0 or off + t.sizes[i] > r.limit - r.base then + t.sampleCount = i - 1 + t.truncated = true + break + end + end + -- the tables hold file offsets; make them buffer offsets + local base = r.base + if base ~= 0 then + local offs = t.offsets + for i = 1, t.sampleCount do + offs[i]=offs[i]+ base + end + end + end + m.duration = movieDuration / m.timescale + if m.duration == 0 then + for _, t in __iter(m.tracks) do + m.duration = math.max(m.duration, t.duration) + end + end + return m, nil +end + +return Demux +end +__FILES["containers/IsoBmff/Meta"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc +-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC +-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn / +-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer. +-- Never throws. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Box = __include("containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Meta = {} + +local function reader(b, box) +return Bytes.reader(b, box.data, box.stop - box.data) +end + +local function uint(r, size) +if size == 0 then + return 0 + elseif size == 4 then + return r:u32be() + elseif size == 8 then + return r:u64be() + elseif size == 2 then + return r:u16be() + elseif size == 1 then + return r:u8() + end + r:fail(Err.CORRUPT, "bad iloc field size " .. size) + return 0 +end +-- ------------------------------------------------------------------------------------------------ HEIF items + + + + + + + + + + + + + + + + + + + + + + + +local function property(b, box) +local p= { type = box.type, box = box } + local r = reader(b, box) + local t = box.type + if t == "ispe" then + r:skip(4) + p.width, p.height = r:u32be(), r:u32be() + elseif t == "pixi" then + r:skip(4) + local n = r:u8() + local bits = {} + for i = 1, math.min(n, 16) do + bits[i] = r:u8() + end + p.bits = bits + elseif t == "colr" then + local ct = r:string(4) + p.colourType = ct + if ct == "nclx" then + p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be() + p.fullRange = bit32.band(r:u8(), 0x80) ~= 0 + elseif ct == "rICC" or ct == "prof" then + p.icc = r:bytes(r:remaining()) + end + elseif t == "irot" then + p.angle = bit32.band(r:u8(), 3) * 90 + elseif t == "imir" then + p.axis = bit32.band(r:u8(), 1) + elseif t == "clap" then + local function frac() +local n, d = r:i32be(), r:u32be() + return d == 0 and 0 or n / d + end + p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac() + elseif t == "auxC" then + r:skip(4) + p.auxType = r:cstring() + else + local n = box.stop - box.data + local cfg = buffer.create(math.max(0, n)) + if n > 0 then + buffer.copy(cfg, 0, b, box.data, n) + end + p.config = cfg + end + return p +end + +-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) +function Meta.items(b, meta) +local out= { items = {}, order = {}, properties = {} } + local pitm = Box.child(meta, "pitm") + if pitm then + local r = reader(b, pitm) + local v = r:u8() + r:skip(3) + out.primary = (v == 0 and{(r:u16be() )}or{(r:u32be() +)})[1] end + local iinf = Box.child(meta, "iinf") + if iinf then + for _, infe in __iter(Box.childrenOf(iinf, "infe")) do + local r = reader(b, infe) + local v = r:u8() + local flags = r:u24be() + local it= { + id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0, + extents = {}, properties = {}, essential = {}, refs = {}, + } + if v >= 2 then + it.id = (v == 2 and{(r:u16be() )}or{(r:u32be() +)})[1] r:skip(2) + it.type = r:string(4) + it.name = r:cstring() + if it.type == "mime" and r:remaining() > 0 then + it.contentType = r:cstring() + end + else + it.id = r:u16be() + r:skip(2) + it.name = r:cstring() + it.contentType = r:cstring() + it.type = "mime" + end + if r.err and it.id == 0 then + return nil, r.err + end + out.items[it.id] = it + table.insert(out.order, it.id) + end + end + local iloc = Box.child(meta, "iloc") + if iloc then + local r = reader(b, iloc) + local v = r:u8() + r:skip(3) + local a, c = r:u8(), r:u8() + local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4) + local idxSize = (v >= 1 and{(bit32.band(c, 15) )}or{0 +})[1] local n = (v < 2 and{(r:u16be() )}or{(r:u32be() +)})[1] if r.err then + return nil, r.err + end + for _ = 1, n do + local id = (v < 2 and{(r:u16be() )}or{(r:u32be() +)})[1] local method = 0 + if v >= 1 then + method = bit32.band(r:u16be(), 15) + end + r:skip(2) -- data reference index + local base = uint(r, baseSize) + local ne = r:u16be() + if r.err then + return nil, r.err + end + if ne * (offSize + lenSize + idxSize) > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start) + end + local extents = {} + for k = 1, ne do + if idxSize > 0 then + uint(r, idxSize) + end + extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) } + end + if r.err then + return nil, r.err + end + local it = out.items[id] + if not it then + it = { + id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, + properties = {}, essential = {}, refs = {}, + } +out.items[id] = it + table.insert(out.order, id) + end + it.construction, it.baseOffset, it.extents = method, base, extents + end + end + local iref = Box.child(meta, "iref") + if iref then + local v = Box.fullHeader(b, iref) + for _, ref in __iter((iref.children or {})) do + local r = reader(b, ref) + local from = (v == 0 and{(r:u16be() )}or{(r:u32be() +)})[1] local n = r:u16be() + local to = {} + for k = 1, n do + to[k] = (v == 0 and{(r:u16be() )}or{(r:u32be() +)})[1] end + local it = out.items[from] + if it and not r.err then + it.refs[ref.type] = to + end + end + end + local ipco = Box.path(meta, "iprp/ipco") + if ipco and ipco.children then + for i, pb in __iter(ipco.children) do + out.properties[i] = property(b, pb) + end + end + local ipma = Box.path(meta, "iprp/ipma") + if ipma then + local r = reader(b, ipma) + local v = r:u8() + local flags = r:u24be() + local n = r:u32be() + for _ = 1, n do + if r.err then + break + end + local id = (v < 1 and{(r:u16be() )}or{(r:u32be() +)})[1] local na = r:u8() + local it = out.items[id] + for _ = 1, na do + local idx, ess + if bit32.band(flags, 1) ~= 0 then + local x = r:u16be() + idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000 + else + local x = r:u8() + idx, ess = bit32.band(x, 0x7F), x >= 0x80 + end + local p = out.properties[idx] + if it and p and not r.err then + table.insert(it.properties, p) + if ess then + it.essential[#it.properties] = true + end + end + end + end + end + out.idat = Box.child(meta, "idat") + return out, nil +end + +-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit +-- bound the file in the buffer +function Meta.itemData(b, base, limit, items, id) +local it = items.items[id] + if not it then + return nil, Err.new(Err.CORRUPT, "no item " .. id) + end + local origin, stop + if it.construction == 0 then + origin, stop = base, limit + elseif it.construction == 1 then + local idat = items.idat + if not idat then + return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat") + end + origin, stop = idat.data, idat.stop + else + return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction) + end + local total = 0 + for _, e in __iter(it.extents) do + local len = e.length + if len == 0 then -- the whole rest of the file + len = stop - origin - e.offset + end + if e.offset < 0 or len < 0 or origin + e.offset + len > stop then + return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end") + end + total =total+ len + end + if total > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big") + end + local out = buffer.create(total) + local p = 0 + for _, e in __iter(it.extents) do + local len = (e.length == 0 and((stop - origin - e.offset ))or(e.length +)) buffer.copy(out, p, b, origin + e.offset, len) + p =p+ len + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ iTunes tags +-- ilst item -> standard tag name +local TAG= { + ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", + ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder", + ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription", + sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort", + tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate", + ["\169pub"] = "publisher", ["\169xyz"] = "location", +} +local TAG_ATOM= {} +for atom, name in __iter(TAG) do + TAG_ATOM[name] = atom +end +Meta.TAG = TAG +Meta.TAG_ATOM = TAG_ATOM +-- freeform (----) names: tags keys are lower case; these keep their usual spelling when written back +local FREEFORM= { itunsmpb = "iTunSMPB", itunnorm = "iTunNORM", itunes_cddb_ids = "iTunes_CDDB_IDs" } + +-- the ID3v1 genres gnre indexes (1-based in gnre) +local GENRES = { + "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", + "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", + "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", + "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", + "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", + "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", + "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", + "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", + "Musical", "Rock & Roll", "Hard Rock", +} + +-- tags(buf, ilst) -> Tags, { Picture } + + +function Meta.tags(b, ilst) +local tags= {} + local pics= {} + if not ilst or not ilst.children then + return tags, pics + end + for _, item in __iter(ilst.children) do + local typ = item.type + local freeName= nil + if typ == "----" then + local nm = Box.child(item, "name") + if nm and nm.data + 4 <= nm.stop then + freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4) + end + end + for _, d in __iter(Box.childrenOf(item, "data")) do +local __DARKLUA_CONTINUE_14=false repeat if d.data + 8 > d.stop then +__DARKLUA_CONTINUE_14=true break + end + local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF) + local p, n = d.data + 8, d.stop - d.data - 8 + if typ == "trkn" or typ == "disk" then + if n >= 6 then + local num = Box.be32(b, p) % 65536 + local total = Box.be32(b, p + 2) % 65536 + local key = typ == "trkn" and"track" or"disc" + if num > 0 then + tags[key] = tostring(num) + end + if total > 0 then + tags[key .. "total"] = tostring(total) + end + end + elseif typ == "gnre" then + if n >= 2 then + local g = GENRES[Box.be32(b, p - 2) % 65536] + if g and not tags.genre then + tags.genre = g + end + end + elseif typ == "tmpo" then + if n >= 2 then + tags.bpm = tostring(Box.be32(b, p - 2) % 65536) + end + elseif typ == "cpil" or typ == "pgap" then + if n >= 1 then + tags[typ == "cpil" and"compilation" or"gapless"] = tostring(buffer.readu8(b, p)) + end + elseif typ == "covr" then + local mime = kind == 14 and"image/png" or(kind == 27 and"image/bmp" or"image/jpeg" +) local data = buffer.create(n) + buffer.copy(data, 0, b, p, n) + table.insert(pics, { mime = mime, data = data }) + elseif kind == 1 or kind == 0 then + local s = readstring(b, p, n) + local key = (freeName and{(string.lower(freeName) )}or{TAG[typ] or string.lower(typ) +})[1] if typ == "\169gen" or not tags[key] then + tags[key] = s + end + end +__DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break end end + end + return tags, pics +end + +-- ------------------------------------------------------------------------------------------------ ilst writer +local function box(w, typ, body) + local start = w:tell() + w:u32be(0) + w:string(typ) + body(w) + w:setU32be(start, w:tell() - start) +end +Meta.box = box + +local function dataBox(w, kind, value) + box(w, "data", function() + w:u32be(kind) + w:u32be(0) + if type(value) == "string" then + w:string(value) + else + w:bytes(value) + end + end) +end + +local function num(s) +local v = tonumber(s or "") + if not v then + return 0 + end + return math.clamp(math.floor(v), 0, 65535) +end + +-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' +-- freeform com.apple.iTunes items) and cover pictures +function Meta.writeIlst(w, tags, pictures) + box(w, "ilst", function() + local keys = {} + for k in __iter(tags) do + table.insert(keys, k) + end + table.sort(keys) + local done= {} + for _, k in __iter(keys) do +local __DARKLUA_CONTINUE_16=false repeat local v = tags[k] + if type(v) ~= "string" or done[k] then +__DARKLUA_CONTINUE_16=true break + end + if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then + local base = (k == "track" or k == "tracktotal" )and"track" or"disc" + if done[base] then +__DARKLUA_CONTINUE_16=true break + end + done[base] = true + local atom = base == "track" and"trkn" or"disk" + local n, total = num(tags[base]), num(tags[base .. "total"]) + box(w, atom, function() + box(w, "data", function() + w:u32be(0) + w:u32be(0) + w:u16be(0) + w:u16be(n) + w:u16be(total) + if atom == "trkn" then + w:u16be(0) + end + end) + end) + elseif k == "bpm" then + box(w, "tmpo", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u16be(num(v)) + end) + end) + elseif k == "compilation" or k == "gapless" then + box(w, k == "compilation" and"cpil" or"pgap", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u8(num(v) ~= 0 and 1 or 0) + end) + end) + elseif TAG_ATOM[k] then + box(w, TAG_ATOM[k], function() + dataBox(w, 1, v) + end) + else + box(w, "----", function() + box(w, "mean", function() + w:u32be(0) + w:string("com.apple.iTunes") + end) + box(w, "name", function() + w:u32be(0) + w:string(FREEFORM[k] or k) + end) + dataBox(w, 1, v) + end) + end + done[k] = true +__DARKLUA_CONTINUE_16=true until true if not __DARKLUA_CONTINUE_16 then break end end + if pictures and #pictures > 0 then + box(w, "covr", function() + for _, p in __iter(pictures) do + dataBox(w, p.mime == "image/png" and 14 or(p.mime == "image/bmp" and 27 or 13), p.data) + end + end) + end + end) +end + +-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +function Meta.writeUdta(w, tags, pictures) + box(w, "udta", function() + box(w, "meta", function() + w:u32be(0) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string("mdir") + w:string("appl") + w:u32be(0) + w:u32be(0) + w:u8(0) + end) + Meta.writeIlst(w, tags, pictures) + end) + end) +end + +return Meta +end +__FILES["containers/IsoBmff/Mux"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak +-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks +-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample +-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + +-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Meta = __include("containers/IsoBmff/Meta") + +local Mux = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local DEFAULT_CONFIG_BOX= { + mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC", + hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3", +} +local FULL_BOX= { alac = true, dfLa = true, vpcC = true } +local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" } + +local box = Meta.box + +local function lang(s) +local l = s or "und" + if #l ~= 3 then + l = "und" + end + local v = 0 + for i = 1, 3 do + v = v * 32 + bit32.band(string.byte(l, i) - 96, 31) + end + return v +end + +local function descriptor(w, tag, body) + local inner = Bytes.writer(64) + body(inner) + local n = inner:tell() + w:u8(tag) + -- 4-byte expandable length (the common iTunes / ffmpeg form) + w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127)) + w:u8(bit32.band(n, 127)) + w:bytes(inner.buf, 0, n) +end + +local function esds(w, t) + box(w, "esds", function() + w:u32be(0) + descriptor(w, 3, function(d) + d:u16be(0) -- ES_ID + d:u8(0) + descriptor(d, 4, function(c) + c:u8(t.objectType or 0x40) + c:u8(t.kind == "video" and 0x11 or 0x15) -- streamType << 2 | upStream 0 | reserved 1 + c:u24be(0) + c:u32be(t.bitrate or 0) + c:u32be(t.bitrate or 0) + if t.config and buffer.len(t.config) > 0 then -- (MJPEG / MP3 have no decoder-specific info) + descriptor(c, 5, function(s) + s:bytes(t.config ) + end) + end + end) + descriptor(d, 6, function(s) + s:u8(2) + end) + end) + end) +end + +local function sampleEntry(w, t) + box(w, t.entry, function() + w:fill(0, 6) + w:u16be(1) -- data reference index + if t.kind == "audio" then + w:u16be(0) -- version + w:u16be(0) + w:u32be(0) + w:u16be(t.channels or 2) + w:u16be(t.bitsPerSample or 16) + w:u16be(0) + w:u16be(0) + local sr = t.sampleRate or t.timescale + w:u32be((sr < 65536 and((sr * 65536 ))or(0))) + elseif t.kind == "video" then + w:fill(0, 16) + w:u16be(t.width or 0) + w:u16be(t.height or 0) + w:u32be(0x00480000) + w:u32be(0x00480000) + w:u32be(0) + w:u16be(1) -- frame count + w:fill(0, 32) -- compressor name + w:u16be(0x18) + w:i16be(-1) + end + local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry] + if t.config and cb then + if cb == "esds" then + esds(w, t) + else + box(w, cb, function() + if FULL_BOX[cb] then + w:u32be(0) + end + w:bytes(t.config ) + end) + end + end + for _, x in __iter(t.boxes or {}) do + box(w, x.type, function() + w:bytes(x.data) + end) + end + end) +end + +-- runs of equal values: { { count, value } } + + +local function runs(n, value) +local out = {} + for i = 1, n do + local v = value(i) + local last = out[#out] + if last and last[2] == v then + last[1]=last[1]+ 1 + else + table.insert(out, { 1, v }) + end + end + return out +end + + + + + + + + + + + +local function moov(w, spec, prep, co64) + local mts = spec.timescale or 1000 + local function toMovie(p, ticks) +return math.floor(ticks * mts / p.t.timescale + 0.5) + end + local movieDur = 0 + for _, p in __iter(prep) do + local play = p.t.playDuration or (p.total - (p.t.skip or 0)) + movieDur = math.max(movieDur, toMovie(p, play)) + end + box(w, "moov", function() + box(w, "mvhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(mts) + w:u32be(movieDur) + w:u32be(0x00010000) + w:u16be(0x0100) + w:fill(0, 10) + for _, v in __iter({ 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 }) do + w:u32be(v) + end + w:fill(0, 24) + w:u32be(#prep + 1) + end) + for id, p in __iter(prep) do + local t = p.t + local play = t.playDuration or (p.total - (t.skip or 0)) + box(w, "trak", function() + box(w, "tkhd", function() + w:u32be(3) -- enabled, in movie + w:u32be(0) + w:u32be(0) + w:u32be(id) + w:u32be(0) + w:u32be(toMovie(p, play)) + w:fill(0, 8) + w:u16be(0) + w:u16be(0) + w:u16be(t.kind == "audio" and 0x0100 or 0) + w:u16be(0) + for _, v in __iter({ 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 }) do + w:u32be(v) + end + w:u32be((t.width or 0) * 65536) + w:u32be((t.height or 0) * 65536) + end) + if t.skip or t.playDuration then + box(w, "edts", function() + box(w, "elst", function() + w:u32be(0) + w:u32be(1) + w:u32be(toMovie(p, play)) + w:u32be(t.skip or 0) + w:u32be(0x00010000) + end) + end) + end + box(w, "mdia", function() + box(w, "mdhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(t.timescale) + w:u32be(p.total) + w:u16be(lang(t.language)) + w:u16be(0) + end) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string(HANDLER[t.kind] or "meta") + w:fill(0, 12) + w:cstring(t.name or (t.kind == "audio" and"SoundHandler" or(t.kind == "video" and"VideoHandler" or"DataHandler"))) + end) + box(w, "minf", function() + if t.kind == "audio" then + box(w, "smhd", function() + w:u32be(0) + w:u32be(0) + end) + elseif t.kind == "video" then + box(w, "vmhd", function() + w:u32be(1) + w:fill(0, 8) + end) + else + box(w, "nmhd", function() + w:u32be(0) + end) + end + box(w, "dinf", function() + box(w, "dref", function() + w:u32be(0) + w:u32be(1) + box(w, "url ", function() + w:u32be(1) -- self-contained + end) + end) + end) + box(w, "stbl", function() + box(w, "stsd", function() + w:u32be(0) + w:u32be(1) + sampleEntry(w, t) + end) + local stts = runs(p.n, p.dur) + box(w, "stts", function() + w:u32be(0) + w:u32be(#stts) + for _, r in __iter(stts) do + w:u32be(r[1]) + w:u32be(r[2]) + end + end) + local cts = t.cts + if cts then + local cr = runs(p.n, function(i) + return cts[i] or 0 + end) + box(w, "ctts", function() + w:u32be(0x01000000) -- version 1: signed offsets + w:u32be(#cr) + for _, r in __iter(cr) do + w:u32be(r[1]) + w:i32be(r[2]) + end + end) + end + local sync = t.sync + if sync then + local list = {} + for i = 1, p.n do + if sync[i] then + table.insert(list, i) + end + end + box(w, "stss", function() + w:u32be(0) + w:u32be(#list) + for _, i in __iter(list) do + w:u32be(i) + end + end) + end + local stsc = runs(#p.chunks, function(i) + return p.chunks[i].count + end) + box(w, "stsc", function() + w:u32be(0) + w:u32be(#stsc) + local c = 1 + for _, r in __iter(stsc) do + w:u32be(c) + w:u32be(r[2]) + w:u32be(1) + c =c+ r[1] + end + end) + box(w, "stsz", function() + w:u32be(0) + local fixed = p.sizes[1] or 0 + for i = 2, p.n do + if p.sizes[i] ~= fixed then + fixed = -1 + break + end + end + if fixed >= 0 and p.n > 0 then + w:u32be(fixed) + w:u32be(p.n) + else + w:u32be(0) + w:u32be(p.n) + for i = 1, p.n do + w:u32be(p.sizes[i]) + end + end + end) + box(w, co64 and"co64" or"stco", function() + w:u32be(0) + w:u32be(#p.chunks) + for _, c in __iter(p.chunks) do + if co64 then + w:u64be(c.offset) + else + w:u32be(c.offset) + end + end + end) + end) + end) + end) + end) + end + if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then + Meta.writeUdta(w, spec.tags or {}, spec.pictures) + end + end) +end + +-- mux(spec) -> buffer | nil, Err +function Mux.mux(spec) +if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then + return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") + end + local prep= {} + local all= {} + for k, t in __iter(spec.tracks) do + if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale") + end + if not HANDLER[t.kind] then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind)) + end + local n, sizes, sample + if t.samples then + local list = t.samples + n = #list + sizes = table.create(n, 0) + for i = 1, n do + if type(list[i]) ~= "buffer" then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer") + end + sizes[i] = buffer.len(list[i]) + end + sample = function(i) +return list[i], 0 + end + elseif t.data and t.sizes then + n = #t.sizes + sizes = t.sizes + local starts = table.create(n, 0) + local o = 0 + for i = 1, n do + starts[i] = o + o =o+ sizes[i] + end + if o > buffer.len(t.data) then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data") + end + local data = t.data + sample = function(i) +return data, starts[i] + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes") + end + local durs = t.durations + local dur + if type(durs) == "number" then + dur = function(_) +return durs + end + elseif type(durs) == "table" then + dur = function(i) +return durs[i] or 0 + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations") + end + local total = 0 + local chunks= {} + local per = (spec.chunkDuration or 1) * t.timescale + local cur= nil + for i = 1, n do + if not cur or total - cur.time >= per then + cur = { track = k, first = i, count = 0, time = total, offset = 0 } + table.insert(chunks, cur ) + table.insert(all, cur ) + end +cur .count =cur.count+ 1 + total =total+ dur(i) + end + prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample } + end + -- interleave the chunks by time + table.sort(all, function(a, b) +local ta = a.time / prep[a.track].t.timescale + local tb = b.time / prep[b.track].t.timescale + if ta ~= tb then + return ta < tb + end + if a.track ~= b.track then + return a.track < b.track + end + return a.first < b.first + end) + local mdatSize = 0 + for _, c in __iter(all) do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + mdatSize =mdatSize+ p.sizes[i] + end + end + local co64 = mdatSize > 4294967295 - 2 ^ 24 + -- ftyp + local w = Bytes.writer(mdatSize + 4096) + box(w, "ftyp", function() + w:string(spec.brand or "isom") + w:u32be(spec.minor or 0x200) + for _, c in __iter(spec.compatible or { spec.brand or "isom", "iso2", "mp41" }) do + w:string(string.sub(c .. " ", 1, 4)) + end + end) + -- moov twice: the first pass measures it, the second has the real chunk offsets + local probe = Bytes.writer(4096) + moov(probe, spec, prep, co64) + local mdatHeader = mdatSize + 8 > 4294967295 and 16 or 8 + local o = w:tell() + probe:tell() + mdatHeader + for _, c in __iter(all) do + c.offset = o + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + o =o+ p.sizes[i] + end + end + moov(w, spec, prep, co64) + if mdatHeader == 16 then + w:u32be(1) + w:string("mdat") + w:u64be(mdatSize + 16) + else + w:u32be(mdatSize + 8) + w:string("mdat") + end + for _, c in __iter(all) do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + local b, off = p.sample(i) + w:bytes(b, off, p.sizes[i]) + end + end + return w:finish(), nil +end + +return Mux +end +__FILES["containers/IsoBmff/QtPalette"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- +-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) +-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil +-- +-- Never throws. +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b, o) +return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b, o) +return readu16(b, o) * 65536 + readu16(b, o + 2) +end + +local QtPalette = {} + +local function rgb(r, g, b) +return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL= { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits) +local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in __iter(small) do + writeu32(pal, (i - 1) * 4, rgb(math.floor(c / 65536), (math.floor(c / 256)) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i =i+ 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in __iter(RAMP) do + local r = ((ch == 0 or ch == 3 )and{v }or{0 +})[1] local g = ((ch == 1 or ch == 3 )and{v }or{0 +})[1] local b = ((ch == 2 or ch == 3 )and{v }or{0 +})[1] writeu32(pal, i * 4, rgb(r, g, b)) + i =i+ 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size +-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +function QtPalette.read(b, start, stop, codec) +if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (math.floor(raw / 32)) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = math.floor(256 / (count - 1) +) local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette +end +__FILES["containers/MacFile"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by +-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"): +-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with +-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix +-- seconds) and comment. Writers pair them back with collect(). +-- +-- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" }) +-- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string +-- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes +-- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped) +-- New code. Never throws. +local Err = __include("core/Err") +local Archive = __include("containers/Archive") + +local MacFile = {} + + + + + + + + + + + + + +local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01 + +function MacFile.fromMac(s) +return (s == 0 and{nil }or{(s - MAC_EPOCH +)})[1]end + +function MacFile.toMac(unix) +if type(unix) ~= "number" or unix ~= unix then + return 0 + end + return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF) +end + +-- Mac OS Roman bytes 0x80..0xFF +local ROMAN = { + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, + 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, + 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, + 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, + 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4, + 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7, +} +local FROM_UNICODE= {} +for i, u in __iter(ROMAN) do + FROM_UNICODE[u] = 127 + i +end + +-- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through) +function MacFile.name(s) +if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + local c = string.byte(s, i) + out[i] = (c < 128 and{(string.char(c) )}or{(utf8.char(ROMAN[c - 127]) +)})[1] end + return table.concat(out) +end + +-- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes) +function MacFile.roman(s) +if not string.find(s, "[\128-\255]") or not utf8.len(s) then + return s + end + local out = {} + for _, c in __iter(utf8.codes(s)) do + table.insert(out, (c < 128 and{(string.char(c) )}or{(string.char(FROM_UNICODE[c] or 63))})[1]) + end + return table.concat(out) +end + +local function four(s) +if type(s) ~= "string" then + return "\0\0\0\0" + end + return string.sub(s .. "\0\0\0\0", 1, 4) +end + +-- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and +-- there is a resource fork) and, when non-empty, the resource fork entry +function MacFile.put(a, f, noData) + local common = { + macType = f.type, + macCreator = f.creator, + finderFlags = f.flags, + created = f.created, + mtime = f.modified, + comment = f.comment, + dir = false, + } + local e= table.clone(common) + e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data" + if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then + Archive.put(a, e) + end + if buffer.len(f.rsrc) > 0 then + local r= table.clone(common) + r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource" + Archive.put(a, r) + end +end + +-- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a +-- buffer or a string (one data fork named name, default "data") +function MacFile.collect(value, name) +local files, err = Archive.files(value, name) + if not files then + return nil, err + end + local out= {} + local byName= {} + local function get(n, e) +local f = byName[n] + if not f then + f = { + name = n, + data = buffer.create(0), + rsrc = buffer.create(0), + type = four(e.macType), + creator = four(e.macCreator), + flags = (type(e.finderFlags) == "number" and{(bit32.band(e.finderFlags, 0xFFFF) )}or{0})[1], + created = (type(e.created) == "number" and{e.created }or{nil})[1], + modified = (type(e.mtime) == "number" and{e.mtime }or{nil})[1], + comment = (type(e.comment) == "string" and{e.comment }or{nil})[1], + } + byName[n] = f + table.insert(out, f) + end + return f +end + -- data forks first, so a resource fork finds its file whatever the order + for _, it in __iter(files) do + if it.entry.fork ~= "resource" then + get(it.name, it.entry).data = it.data + end + end + for _, it in __iter(files) do + if it.entry.fork == "resource" then + local base = string.match(it.name, "^(.*)%.rsrc$") or it.name + get(base, it.entry).rsrc = it.data + end + end + return out, nil +end + +return MacFile +end +__FILES["containers/MpegEs"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- containers/MpegEs: helpers over MPEG video elementary streams for the MPEG-TS / PS demuxers. New in rosetta. +-- Start-code scanning, MPEG-1 / MPEG-2 video access units (a picture with the sequence / GOP headers before it, +-- picture type and temporal reference, the sequence's frame rate and size, MPEG-2 detection by its sequence +-- extension) and H.264 Annex B keyframes (an IDR slice, or a recovery-point SEI). Interpreted; never throws. +local readu8 = buffer.readu8 + +local MpegEs = {} + +-- next start code (00 00 01 xx) at or after p, before limit: position of the 00 00 01 | nil +function MpegEs.findStart(b, p, limit) +local i = p + while i + 3 <= limit do + local c = readu8(b, i + 2) + if c > 1 then + i =i+ 3 + elseif c == 1 then + if readu8(b, i) == 0 and readu8(b, i + 1) == 0 then + return i + end + i =i+ 3 + else -- c == 0: the start code may begin at i + 1 or i + 2 + i =i+ 1 + end + end + return nil +end + +local FRAME_RATES = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 } + +-- info(b, off, limit) -> the first sequence header's facts | nil + + + + + + + + + + + + +function MpegEs.info(b, off, limit) +local p = MpegEs.findStart(b, off, limit) + local info= nil + local count = 0 + while p and count < 64 do + count =count+ 1 + local code = (p + 3 < limit and{(readu8(b, p + 3) )}or{(-1 +)})[1] if code == 0xB3 and p + 11 < limit and not info then + local w = readu8(b, p + 4) * 16 + math.floor(readu8(b, p + 5) / 16 +) local h = (readu8(b, p + 5) % 16) * 256 + readu8(b, p + 6) + local fr = readu8(b, p + 7) % 16 + info = { width = w, height = h, frameRate = FRAME_RATES[fr] or 0, mpeg2 = false } + elseif code == 0xB5 and info then + info.mpeg2 = true + return info + elseif code == 0x00 and info then + return info + end + p = MpegEs.findStart(b, p + 4, limit) + end + return info +end + +-- pictureType(b, off, limit) -> the type (1 I, 2 P, 3 B) and temporal reference of the first picture header | 0 +function MpegEs.pictureType(b, off, limit) +local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 32 do + count =count+ 1 + if p + 5 < limit and readu8(b, p + 3) == 0x00 then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + return (math.floor(x / 8)) % 8, math.floor(x / 64 +) end + p = MpegEs.findStart(b, p + 4, limit) + end + return 0, 0 +end + +-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture +-- coding extension (3 = frame when there is none: MPEG-1) +function MpegEs.pictureStructure(b, p, limit) +local q = MpegEs.findStart(b, p + 4, limit) + local count = 0 + while q and count < 8 do + count =count+ 1 + local code = (q + 6 < limit and{(readu8(b, q + 3) )}or{(-1 +)})[1] if code == 0xB5 then + if math.floor(readu8(b, q + 4) / 16 )== 8 then + local st = readu8(b, q + 6) % 4 + return st == 0 and 3 or st + end + elseif code ~= 0xB2 then + break + end + q = MpegEs.findStart(b, q + 4, limit) + end + return 3 +end + +-- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its +-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures +-- is one unit (fields = 2) +function MpegEs.pictures(b, off, limit) +local out= {} + local unitStart= nil + local seq, gop = false, false + local cur= nil + local p = MpegEs.findStart(b, off, limit) + while p do + local code = (p + 3 < limit and{(readu8(b, p + 3) )}or{(-1 +)})[1] local st = (code == 0x00 and{(MpegEs.pictureStructure(b, p, limit) )}or{3 +})[1] if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then + -- the second field of the current frame: same unit + cur.fields = 2 + elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + -- a sequence / GOP header or a picture after a picture closes it + if cur and (code ~= 0xB7) then + cur.size = p - cur.offset + table.insert(out, cur) + cur = nil + end + if code == 0xB3 then + unitStart = unitStart or p + seq = true + elseif code == 0xB8 then + unitStart = unitStart or p + gop = true + elseif code == 0x00 then + local t, tr = 0, 0 + if p + 5 < limit then + local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) + t, tr = (math.floor(x / 8)) % 8, math.floor(x / 64 +) end + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } +unitStart, seq, gop = nil, false, false + elseif code == 0xB7 and cur then + cur.size = p + 4 - cur.offset + table.insert(out, cur) + cur = nil + end + end + p = MpegEs.findStart(b, p + 4, limit) + end + if cur then + cur.size = limit - cur.offset + table.insert(out, cur) + end + return out +end + +-- h264Key(b, off, limit) -> an Annex B access unit holds an IDR slice (NAL type 5) +function MpegEs.h264Key(b, off, limit) +local p = MpegEs.findStart(b, off, limit) + local count = 0 + while p and count < 64 do + count =count+ 1 + if p + 3 < limit then + local t = readu8(b, p + 3) % 32 + if t == 5 then + return true + elseif t == 1 then + return false + end + end + p = MpegEs.findStart(b, p + 3, limit) + end + return false +end + +return MpegEs +end +__FILES["containers/MpegPs"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- containers/MpegPs: the MPEG program stream (ISO/IEC 11172-1 system streams and ISO/IEC 13818-1 program streams: +-- .mpg / .mpeg / .vob). New in rosetta. Pack headers (MPEG-1 and MPEG-2 layouts), system headers, the program +-- stream map (stream types), padding, and PES packets of the video (0xE0..0xEF), audio (0xC0..0xDF) and private +-- stream 1 (0xBD: AC-3 / DTS / LPCM / subpicture sub-streams) ids with their PTS / DTS (both PES header layouts, +-- 33-bit timestamps unwrapped). Data between packs that is not a start code is skipped (resync). +-- +-- local ps, err = MpegPs.read(buf, base, limit) +-- ps.streams[id] = { id, kind, codec, streamType, pes = { { pts?, dts?, offset, size } } } (id: stream_id, or +-- 0xBD00 + sub-stream id for private stream 1); ps.order = the ids in order of appearance +-- +-- Never throws: malformed packets are skipped and counted in ps.errors. +local Err = __include("core/Err") +local MpegEs = __include("containers/MpegEs") + +local readu8 = buffer.readu8 + +local MpegPs = {} + + + + + +local WRAP = 8589934592 -- 2^33 + +-- PSM stream_type -> kind, codec +local TYPES= { + [0x01] = { "video", "mpeg1" }, + [0x02] = { "video", "mpeg2" }, + [0x03] = { "audio", "mp2" }, + [0x04] = { "audio", "mp2" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, +} + +local function ts(b, p) +local a = readu8(b, p) + local v = (math.floor(a / 2)) % 8 + v = v * 32768 + math.floor((readu8(b, p + 1) * 256 + readu8(b, p + 2)) / 2 +) v = v * 32768 + math.floor((readu8(b, p + 3) * 256 + readu8(b, p + 4)) / 2 +) return v +end + +-- read(buf, base, limit) -> File | nil, Err +function MpegPs.read(b, base, limit) +local file= { streams = {}, order = {}, mpeg2 = false, errors = 0 } + local types= {} + local last= {} + local wrap= {} + local packs = 0 + local p = MpegEs.findStart(b, base, limit) + local function unwrap(id, v) +local off = wrap[id] or 0 + local prev = last[id] + local t = v + off + if prev and t < prev - WRAP / 2 then + off =off+ WRAP + wrap[id] = off + t = v + off + end + last[id] = t + return t + end + while p do + if p + 4 > limit then + break + end + local code = readu8(b, p + 3) + local nextP = p + 4 + if code == 0xBA then + packs =packs+ 1 + if p + 5 > limit then + break + end + local m = readu8(b, p + 4) + if math.floor(m / 64 )== 1 then -- MPEG-2 pack: 14 bytes + stuffing + file.mpeg2 = true + if p + 14 > limit then + break + end + nextP = p + 14 + readu8(b, p + 13) % 8 + else + nextP = p + 12 + end + elseif code == 0xB9 then + nextP = p + 4 + elseif code >= 0xBB then + if p + 6 > limit then + break + end + local len = readu8(b, p + 4) * 256 + readu8(b, p + 5) + local stop = p + 6 + len + if stop > limit then + stop = limit + end + nextP = stop + if code == 0xBC and len >= 10 then -- program stream map + local infoLen = readu8(b, p + 8) * 256 + readu8(b, p + 9) + local q = p + 10 + infoLen + if q + 2 <= stop then + local mapLen = readu8(b, q) * 256 + readu8(b, q + 1) + q =q+ 2 + local e = math.min(stop, q + mapLen) + while q + 4 <= e do + local st, sid = readu8(b, q), readu8(b, q + 1) + local il = readu8(b, q + 2) * 256 + readu8(b, q + 3) + types[sid] = st + q =q+ (4 + il +) end + end + elseif code == 0xBD or (code >= 0xC0 and code <= 0xEF) then + -- a PES packet + local q = p + 6 + local pts, dts= nil, nil + local ok = true + if q < stop and math.floor(readu8(b, q) / 64 )== 2 then -- MPEG-2 PES header + if q + 3 > stop then + ok = false + else + local flags = readu8(b, q + 1) + local hlen = readu8(b, q + 2) + local h = q + 3 + if flags >= 0x80 and h + 5 <= stop then + pts = ts(b, h) + if math.floor(flags / 64 )== 3 and h + 10 <= stop then + dts = ts(b, h + 5) + end + end + q = h + hlen + end + else -- MPEG-1 packet header + local n = 0 + while q < stop and readu8(b, q) == 0xFF and n < 16 do + q =q+ 1 + n =n+ 1 + end + if q < stop and math.floor(readu8(b, q) / 64 )== 1 then + q =q+ 2 + end + if q < stop then + local c = math.floor(readu8(b, q) / 16 +) if c == 2 and q + 5 <= stop then + pts = ts(b, q) + q =q+ 5 + elseif c == 3 and q + 10 <= stop then + pts = ts(b, q) + dts = ts(b, q + 5) + q =q+ 10 + elseif readu8(b, q) == 0x0F then + q =q+ 1 + else + ok = false + end + end + end + if ok and q <= stop then + local id = code + local kind, codec = "other", "unknown" + if code == 0xBD then + if q >= stop then + ok = false + else + local sub = readu8(b, q) + id = 0xBD00 + sub + if sub >= 0x80 and sub <= 0x87 then + kind, codec = "audio", "ac3" + q =q+ 4 + elseif sub >= 0x88 and sub <= 0x8F then + kind, codec = "audio", "dts" + q =q+ 4 + elseif sub >= 0xA0 and sub <= 0xA7 then + kind, codec = "audio", "pcm_dvd" + q =q+ 7 + elseif sub >= 0x20 and sub <= 0x3F then + kind, codec = "subtitle", "dvdsub" + q =q+ 1 + else + q =q+ 1 + end + end + elseif code >= 0xE0 then + kind, codec = "video", "mpeg1" + else + kind, codec = "audio", "mp2" + end + local st = types[code] + if st and TYPES[st] then + kind, codec = TYPES[st][1], TYPES[st][2] + end + if ok and q <= stop then + local s = file.streams[id] + if not s then + s = { id = id, kind = kind, codec = codec, streamType = st, pes = {} } +file.streams[id] = s + table.insert(file.order, id) + end + table.insert(s.pes, { + pts = (pts and{(unwrap(id, pts) )}or{nil})[1], + dts = (dts and{(unwrap(id + 0x10000, dts) )}or{nil})[1], + offset = q, + size = stop - q, + }) + end + end + if not ok then + file.errors =file.errors+ 1 + end + end + else + -- a start code that is not a system one (stray ES data between packets): resync + file.errors =file.errors+ 1 + end + p = MpegEs.findStart(b, nextP, limit) + end + if packs == 0 and #file.order == 0 then + return nil, Err.new(Err.CORRUPT, "no MPEG pack or PES packet", base) + end + return file, nil +end + +return MpegPs +end +__FILES["containers/MpegTs"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +-- containers/MpegTs: an MPEG transport stream demuxer (ISO/IEC 13818-1). Absorbed from mpegts-luau 6e16197 (same +-- author; no third-party code). Changed: this header, and the unit queue keeps an explicit tail (pull() used #q on a +-- table with holes at its front, which LuaJIT's border rule makes lose units). 188-byte packets with resync, PAT / PMT sections +-- (assembled across packets, CRC-checked), adaptation fields (PCR, discontinuity, random access), continuity +-- counter checks (gaps are flagged on the unit, duplicates dropped), PES reassembly with 33-bit PTS / DTS. +-- +-- local units = MpegTs.demux(buf) -- whole segment: { video = {...}, audio = {...}, streams, ... } +-- local d = MpegTs.new(); d:push(chunk); local u = d:pull() ... d:flush() -- streamed +-- +-- Native code must never throw (an error unwinding through native code crashes Roblox Studio), so every read is +-- bounds-checked by construction and bad input is skipped and counted in `stats`, never raised. +local Crc32 = __include("core/Crc32") + +local MpegTs = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local TS_SIZE = 188 +local SYNC = 0x47 +local MAX_SECTION = 4096 + 188 +local WRAP = 8589934592 -- 2^33 + +local readu8 = buffer.readu8 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift + +local CODECS= { + [0x01] = { "video", "mpeg1video" }, + [0x02] = { "video", "mpeg2video" }, + [0x03] = { "audio", "mpegaudio" }, + [0x04] = { "audio", "mpegaudio" }, + [0x0F] = { "audio", "aac" }, + [0x10] = { "video", "mpeg4" }, + [0x11] = { "audio", "aac_latm" }, + [0x1B] = { "video", "h264" }, + [0x24] = { "video", "hevc" }, + [0x81] = { "audio", "ac3" }, + [0x87] = { "audio", "eac3" }, +} + +-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0 +local function crc32(b, off, n) +return Crc32.msb(b, off, n, 0xFFFFFFFF) +end +MpegTs.crc32 = crc32 + +local function u16(b, p) +return readu8(b, p) * 256 + readu8(b, p + 1) +end + +-- 33-bit timestamp from the 5-byte PES encoding at p +local function readTs(b, p) +local b0 = readu8(b, p) + local hi = band(rshift(b0, 1), 7) * 1073741824 -- bits 32..30 + local mid = bor(lshift(readu8(b, p + 1), 7), rshift(readu8(b, p + 2), 1)) -- bits 29..15 + local lo = bor(lshift(readu8(b, p + 3), 7), rshift(readu8(b, p + 4), 1)) -- bits 14..0 + return hi + mid * 32768 + lo +end + +local Demuxer = {} +Demuxer.__index = Demuxer + + + + + + + + + + + + + + + + + + + +function MpegTs.new() +local self = setmetatable({ + _pend = buffer.create(64 * 1024), + _pendLen = 0, + _pmtPids = {}, + _streams = {}, + _pes = {}, + _sections = {}, + _cc = {}, + _queue = {}, + _qhead = 1, + _qtail = 0, + streams = {}, + stats = { + packets = 0, + syncLosses = 0, + skippedBytes = 0, + teiErrors = 0, + ccErrors = 0, + duplicates = 0, + crcErrors = 0, + pesErrors = 0, + scrambled = 0, + pcr = nil, + } , + }, Demuxer) + return self +end + +-- PSI --------------------------------------------------------------------------------------------------------- + +local function addStream(self, pid, streamType, program, language) + local info = CODECS[streamType] + local s = self._streams[pid] + if s == nil then + s = { + pid = pid, + streamType = streamType, + kind = (info and{info[1] }or{"other"})[1], + codec = (info and{info[2] }or{"unknown"})[1], + program = program, + language = language, + } + self._streams[pid] = s + table.insert(self.streams, s) + else + s.streamType = streamType + s.kind = (info and{info[1] }or{"other" +})[1] s.codec = (info and{info[2] }or{"unknown" +})[1] s.program = program + s.language = language + end +end + +local function parseSection(self, pid, b, n) + -- n >= 3 bytes: table_id, section_length (n = 3 + section_length) + if n < 12 then + return + end + if band(readu8(b, 1), 0x80) == 0 then + return -- no section_syntax_indicator: not a PAT / PMT + end + if crc32(b, 0, n) ~= 0 then +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.crcErrors =__DARKLUA_VAR.crcErrors+ 1 +end return + end + if band(readu8(b, 5), 1) == 0 then + return -- current_next_indicator = 0: a future table + end + local tid = readu8(b, 0) + local stop = n - 4 + if tid == 0x00 and pid == 0 then + local p = 8 + while p + 4 <= stop do + local prog = u16(b, p) + local pmt = band(u16(b, p + 2), 0x1FFF) + if prog ~= 0 then + self._pmtPids[pmt] = prog + end + p =p+ 4 + end + elseif tid == 0x02 and self._pmtPids[pid] ~= nil then + local program = u16(b, 3) + local p = 12 + band(u16(b, 10), 0x0FFF) + while p + 5 <= stop do + local st = readu8(b, p) + local epid = band(u16(b, p + 1), 0x1FFF) + local esl = band(u16(b, p + 3), 0x0FFF) + local d = p + 5 + local dend = math.min(d + esl, stop) + local language= nil + while d + 2 <= dend do + local tag, len = readu8(b, d), readu8(b, d + 1) + if tag == 0x0A and len >= 3 and d + 5 <= dend then + language = buffer.readstring(b, d + 2, 3) + end + d =d+ (2 + len +) end + addStream(self, epid, st, program, language) + p =p+ (5 + esl +) end + end +end + +local function sectionBytes(self, pid, s, src, from, to) + local n = to - from + if n <= 0 then + return + end + if s.len + n > MAX_SECTION then + s.active = false + s.len = 0 + return + end + buffer.copy(s.buf, s.len, src, from, n) + s.len =s.len+ n + -- every complete section in the buffer + while s.active and s.len >= 3 do + if readu8(s.buf, 0) == 0xFF then + s.active = false -- stuffing: no more sections until the next unit start + s.len = 0 + return + end + local need = 3 + band(u16(s.buf, 1), 0x0FFF) + if s.len < need then + return + end + parseSection(self, pid, s.buf, need) + local rest = s.len - need + if rest > 0 then + buffer.copy(s.buf, 0, s.buf, need, rest) + end + s.len = rest + end +end + +local function sectionPayload(self, pid, pusi, b, pos, stop) + local s = self._sections[pid] + if s == nil then + s = { buf = buffer.create(MAX_SECTION), len = 0, active = false } + self._sections[pid] = s + end + if pusi then + if pos >= stop then + return + end + local ptr = readu8(b, pos) + pos =pos+ 1 + local tail = math.min(pos + ptr, stop) + if s.active then + sectionBytes(self, pid, s, b, pos, tail) -- the end of the previous section + end + s.active = true + s.len = 0 + pos = tail + elseif not s.active then + return + end + sectionBytes(self, pid, s, b, pos, stop) +end + +-- PES --------------------------------------------------------------------------------------------------------- + +local function completePes(self, pid, st) + st.active = false + local b, len = st.buf, st.len + if len < 6 or readu8(b, 0) ~= 0 or readu8(b, 1) ~= 0 or readu8(b, 2) ~= 1 then +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.pesErrors =__DARKLUA_VAR.pesErrors+ 1 +end return + end + local sid = readu8(b, 3) + local stop = (st.expected > 0 and{(math.min(st.expected, len) )}or{len +})[1] local start = 6 + local pts, dts= nil, nil + if not (sid == 0xBC or sid == 0xBE or sid == 0xBF or sid == 0xF0 or sid == 0xF1 or sid == 0xF2 or sid == 0xF8 or sid == 0xFF) then + if stop < 9 then +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.pesErrors =__DARKLUA_VAR.pesErrors+ 1 +end return + end + if band(readu8(b, 6), 0xC0) == 0x80 then + -- MPEG-2 PES header + local flags = readu8(b, 7) + local hl = readu8(b, 8) + start = 9 + hl + if band(flags, 0x80) ~= 0 and hl >= 5 and 14 <= stop then + pts = readTs(b, 9) + if band(flags, 0x40) ~= 0 and hl >= 10 and 19 <= stop then + dts = readTs(b, 14) + end + end + else + -- MPEG-1 (ISO 11172-1) packet header: stuffing, STD buffer, PTS / DTS + local p = 6 + local k = 0 + while p < stop and readu8(b, p) == 0xFF and k < 16 do + p =p+ 1 + k =k+ 1 + end + if p < stop and band(readu8(b, p), 0xC0) == 0x40 then + p =p+ 2 + end + if p < stop then + local c = band(readu8(b, p), 0xF0) + if c == 0x20 and p + 5 <= stop then + pts = readTs(b, p) + p =p+ 5 + elseif c == 0x30 and p + 10 <= stop then + pts = readTs(b, p) + dts = readTs(b, p + 5) + p =p+ 10 + else + p =p+ 1 + end + end + start = p + end + end + if start > stop then +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.pesErrors =__DARKLUA_VAR.pesErrors+ 1 +end return + end + -- unwrap the 33-bit clock (per PID) + if pts ~= nil then + pts =pts+ st.wrapOffset + if st.lastPts >= 0 then + if pts < st.lastPts - WRAP / 2 then + st.wrapOffset =st.wrapOffset+ WRAP + pts =pts+ WRAP + elseif pts > st.lastPts + WRAP / 2 and st.wrapOffset >= WRAP then + st.wrapOffset =st.wrapOffset- WRAP + pts =pts- WRAP + end + end + st.lastPts = pts + if dts ~= nil then + dts =dts+ st.wrapOffset + if dts > pts + WRAP / 2 then + dts =dts- WRAP + elseif dts < pts - WRAP / 2 then + dts =dts+ WRAP + end + else + dts = pts + end + end + local n = stop - start + local data = buffer.create(n) + if n > 0 then + buffer.copy(data, 0, b, start, n) + end + local s = self._streams[pid] + local kind, codec, streamType + if s then + kind, codec, streamType = s.kind, s.codec, s.streamType + elseif sid >= 0xE0 and sid <= 0xEF then + kind, codec, streamType = "video", "unknown", 0 + elseif sid >= 0xC0 and sid <= 0xDF then + kind, codec, streamType = "audio", "mpegaudio", 0 + else + kind, codec, streamType = "other", "unknown", 0 + end + local unit= { + pid = pid, + kind = kind, + codec = codec, + streamType = streamType, + streamId = sid, + pts = (pts and((pts / 90000 ))or(nil)), + dts = (dts and((dts / 90000 ))or(nil)), + pts90 = pts, + dts90 = dts, + data = data, + ccError = st.ccError, + randomAccess = st.randomAccess, + discontinuity = st.discontinuity, + } + local tail = self._qtail + 1 + self._qtail = tail + self._queue[tail] = unit +end + +local function pesPayload( + self, + pid, + pusi, + b, + pos, + stop, + ccError, + randomAccess, + discontinuity +) + local st = self._pes[pid] + -- a unit starts with a PES start code; anything else on a PID outside the PMT (SDT, EIT ...) is ignored + local startCode = pusi + and stop - pos >= 3 + and readu8(b, pos) == 0 + and readu8(b, pos + 1) == 0 + and readu8(b, pos + 2) == 1 + if st == nil then + if not startCode then + return + end + st = { + buf = buffer.create(16 * 1024), + len = 0, + active = false, + expected = 0, + hdrChecked = false, + ccError = false, + randomAccess = false, + discontinuity = false, + lastPts = -1, + wrapOffset = 0, + } + self._pes[pid] = st + end + if ccError and st.active then + st.ccError = true -- packets of the unit in progress were lost + end + if pusi then + if st.active then + completePes(self, pid, st) + end + if not startCode then + if self._streams[pid] ~= nil then +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.pesErrors =__DARKLUA_VAR.pesErrors+ 1 +end end + return + end + st.active = true + st.len = 0 + st.expected = 0 + st.hdrChecked = false + st.ccError = false + st.randomAccess = randomAccess + st.discontinuity = discontinuity + elseif not st.active then + return + end + local n = stop - pos + if n <= 0 then + return + end + if st.len + n > buffer.len(st.buf) then + local cap = buffer.len(st.buf) * 2 + while cap < st.len + n do + cap =cap* 2 + end + if cap > 64 * 1024 * 1024 then + st.active = false -- runaway unit (no unit start for 64 MB): drop it + st.len = 0 +do local __DARKLUA_VAR= self.stats __DARKLUA_VAR.pesErrors =__DARKLUA_VAR.pesErrors+ 1 +end return + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, st.buf, 0, st.len) + st.buf = nb + end + buffer.copy(st.buf, st.len, b, pos, n) + st.len =st.len+ n + if not st.hdrChecked and st.len >= 6 then + st.hdrChecked = true + local plen = u16(st.buf, 4) + if plen > 0 then + st.expected = 6 + plen + end + end + if st.expected > 0 and st.len >= st.expected then + completePes(self, pid, st) + end +end + +-- packets ----------------------------------------------------------------------------------------------------- + +local function packet(self, b, pk) + local stats = self.stats + stats.packets =stats.packets+ 1 + local b1 = readu8(b, pk + 1) + if band(b1, 0x80) ~= 0 then + stats.teiErrors =stats.teiErrors+ 1 + return + end + local pusi = band(b1, 0x40) ~= 0 + local pid = band(b1, 0x1F) * 256 + readu8(b, pk + 2) + if pid == 0x1FFF then + return + end + local b3 = readu8(b, pk + 3) + if band(b3, 0xC0) ~= 0 then + stats.scrambled =stats.scrambled+ 1 + return + end + local afc = band(rshift(b3, 4), 3) + local cc = band(b3, 15) + if afc == 0 then + return + end + local pos = pk + 4 + local stop = pk + TS_SIZE + local discontinuity, randomAccess = false, false + if afc >= 2 then + local afl = readu8(b, pos) + pos =pos+ 1 + if afl > 183 then + return + end + if afl > 0 then + local flags = readu8(b, pos) + discontinuity = band(flags, 0x80) ~= 0 + randomAccess = band(flags, 0x40) ~= 0 + if band(flags, 0x10) ~= 0 and afl >= 7 then + local base = readu8(b, pos + 1) * 33554432 + + readu8(b, pos + 2) * 131072 + + readu8(b, pos + 3) * 512 + + readu8(b, pos + 4) * 2 + + rshift(readu8(b, pos + 5), 7) + local ext = band(readu8(b, pos + 5), 1) * 256 + readu8(b, pos + 6) + stats.pcr = base / 90000 + ext / 27000000 + end + end + pos =pos+ afl + if afc == 2 then + if discontinuity then + self._cc[pid] = nil + end + return -- adaptation field only: the counter does not advance + end + end + -- continuity counter + local ccError = false + local last = self._cc[pid] + if last ~= nil and not discontinuity then + if cc == last then + stats.duplicates =stats.duplicates+ 1 + return + elseif cc ~= band(last + 1, 15) then + ccError = true + stats.ccErrors =stats.ccErrors+ 1 + end + end + self._cc[pid] = cc + if pid == 0 or self._pmtPids[pid] ~= nil then + sectionPayload(self, pid, pusi, b, pos, stop) + elseif pid >= 0x10 then + pesPayload(self, pid, pusi, b, pos, stop, ccError, randomAccess, discontinuity) + end +end + +-- Appends bytes (a buffer, or a string) and demuxes every whole packet in them. Completed units queue up for +-- pull(). Returns false for a bad argument. +function Demuxer.push(self, data, offset, len) +local src +if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local off = math.max(0, math.floor(offset or 0)) + local total = buffer.len(src) + if off > total then + return false + end + local n = math.min(math.floor(len or (total - off)), total - off) + if n < 0 then + return false + end + -- append to the pending bytes + local need = self._pendLen + n + if need > buffer.len(self._pend) then + local cap = buffer.len(self._pend) + while cap < need do + cap =cap* 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, self._pend, 0, self._pendLen) + self._pend = nb + end + if n > 0 then + buffer.copy(self._pend, self._pendLen, src, off, n) + end + self._pendLen = need + local b, avail = self._pend, self._pendLen + local p = 0 + while p + TS_SIZE <= avail do + if readu8(b, p) ~= SYNC then +do local __DARKLUA_VAR= -- resync: the next 0x47 that is followed by another one 188 bytes later (or by the end of the data) + self.stats __DARKLUA_VAR.syncLosses =__DARKLUA_VAR.syncLosses+ 1 +end local q = p + 1 + local found = -1 + local waitAt = -1 + while q < avail do + if readu8(b, q) == SYNC then + if q + TS_SIZE < avail then + if readu8(b, q + TS_SIZE) == SYNC then + found = q + break + end + elseif q + TS_SIZE == avail then + found = q + break + else + waitAt = q -- not enough bytes to confirm: wait for more + break + end + end + q =q+ 1 + end + if found >= 0 then +do local __DARKLUA_VAR0= self.stats __DARKLUA_VAR0.skippedBytes =__DARKLUA_VAR0.skippedBytes+ (found - p +)end p = found + elseif waitAt >= 0 then +do local __DARKLUA_VAR0= self.stats __DARKLUA_VAR0.skippedBytes =__DARKLUA_VAR0.skippedBytes+ (waitAt - p +)end p = waitAt + break + else +do local __DARKLUA_VAR0= self.stats __DARKLUA_VAR0.skippedBytes =__DARKLUA_VAR0.skippedBytes+ (avail - p +)end p = avail + break + end + else + packet(self, b, p) + p =p+ TS_SIZE + end + end + local rest = avail - p + if rest > 0 and p > 0 then + buffer.copy(b, 0, b, p, rest) + end + self._pendLen = rest + return true +end + +-- The next completed unit (any PID), or nil. +function Demuxer.pull(self) +local q = self._queue + local h = self._qhead + local u = q[h] + if u == nil then + return nil + end + q[h] = nil +h =h+ 1 + if h > self._qtail then + table.clear(q) + h = 1 + self._qtail = 0 + end + self._qhead = h + return u +end + +-- Ends every unit in progress (call at the end of the data: a video PES with no length only ends at the next +-- unit start). Units still queue up for pull(). +function Demuxer.flush(self) + local pids = {} + for pid, st in __iter(self._pes) do + if st.active then + table.insert(pids, pid) + end + end + table.sort(pids) + for _, pid in __iter(pids) do + completePes(self, pid, self._pes[pid]) + end + self._pendLen = 0 +end + +-- Forgets buffered bytes, units in progress and continuity state, but keeps the PAT / PMT (for a seek). +function Demuxer.reset(self) + self._pendLen = 0 + for _, st in __iter(self._pes) do + st.active = false + st.len = 0 + st.lastPts = -1 + st.wrapOffset = 0 + end + for _, s in __iter(self._sections) do + s.active = false + s.len = 0 + end + table.clear(self._cc) + table.clear(self._queue) + self._qhead = 1 + self._qtail = 0 +end + +-- Streams by kind: the first video / audio PID in PMT order (or in unit order without a PMT). +function Demuxer.streamFor(self, kind) +for _, s in __iter(self.streams) do + if s.kind == kind then + return s + end + end + return nil +end + +-- Demuxes a whole buffer (one segment). Video and audio are the units of one PID each: opts.videoPid / +-- opts.audioPid, else the first video / audio stream of the PMT, else the first PID whose units look like video / +-- audio (PES stream_id). Never throws; a bad argument gives empty lists. + + +function MpegTs.demux(data, opts) +local d = MpegTs.new() + d:push(data) + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + local videoPid = opts and opts.videoPid + local audioPid = opts and opts.audioPid + if videoPid == nil then + local s = d:streamFor("video") + videoPid = (s and{s.pid }or{nil +})[1] end + if audioPid == nil then + local s = d:streamFor("audio") + audioPid = (s and{s.pid }or{nil +})[1] end + for _, u in __iter(units) do + if videoPid == nil and u.kind == "video" then + videoPid = u.pid + end + if audioPid == nil and u.kind == "audio" then + audioPid = u.pid + end + end + local video, audio = {}, {} + for _, u in __iter(units) do + if u.pid == videoPid then + table.insert(video, u) + elseif u.pid == audioPid then + table.insert(audio, u) + end + end + return { + video = video, + audio = audio, + streams = d.streams, + units = units, + videoPid = videoPid, + audioPid = audioPid, + stats = d.stats, + } +end + +-- Concatenates the data of a list of units (e.g. a segment's audio access units, for Mp3.open). +function MpegTs.concat(units) +local n = 0 + for _, u in __iter(units) do + n =n+ buffer.len(u.data) + end + local out = buffer.create(n) + local p = 0 + for _, u in __iter(units) do + local l = buffer.len(u.data) + buffer.copy(out, p, u.data, 0, l) + p =p+ l + end + return out +end + +return MpegTs +end +__FILES["containers/Ogg"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- containers/Ogg: the Ogg container (RFC 3533): a demuxer and a muxer (page writer). Absorbed from ogg-luau be9f604 +-- (same author, no third-party code; the demuxer), the muxer is new. Used by audio/opus, audio/flac (Ogg FLAC) and +-- the Vorbis decoder / encoders. Pages are CRC-checked and resynced on the capture +-- pattern; packets are reassembled across pages (lacing values, continued packets) per logical stream (serial); +-- seeking bisects byte offsets to the page that holds a granule position. No Roblox APIs; nothing throws (bad +-- input gives nil, err). +-- +-- local demux, err = Ogg.open(buf) +-- for _, s in demux:streams() do print(s.serial, s.codec, s.lastGranule) end +-- local r = demux:reader(serial) -- or demux:packets(serial) as a for-iterator +-- local p = r:nextPacket() -- { data, offset, size, granule, eos, bos, ... } / nil +-- local start = r:seekGranule(48000) -- next packet starts at granule `start` (<= target) +-- +-- local mux = Ogg.muxer() -- the page writer (Containers/Ogg/Mux) +-- local s = mux:stream(serial?) -- one logical stream +-- s:packet(idHeader, 0, { flush = true }) -- headers on their own pages +-- s:packet(audio, granuleAfterThisPacket) -- pages fill up to opts.pageSize (default 4096) bytes +-- local file = mux:finish() -- every stream ends with an eos page +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") +local Mux = __include("containers/Ogg/Mux") + +local readu8 = buffer.readu8 + + +local Ogg = {} +Ogg.Page = Page +Ogg.Mux = Mux +Ogg.muxer = Mux.new + +-- Reader: the packet cursor of one logical stream + + + + + + + + + + + + + + + + + + + + +local Reader = {} +Reader.__index = Reader + +local function newReader(d, serial, start) +return setmetatable({ + demux = d, + buf = d.buf, + serial = serial, + start = start, -- the bos page offset + pagePos = start, -- where to look for the next page + page = nil , + seg = 0, -- next segment index on the page + dataPos = 0, -- byte offset of the next segment's data + lastComplete = -1, -- index of the last segment ending a packet on this page + firstPacketOnPage = true, + parts = {} , -- pending partial packet: offset, len pairs + partLen = 0, + lastSeq = -1, + gap = false, + ended = false, + total = 0, + }, Reader) +end + +-- Load the next page of this serial; false at the end of the data +function Reader._nextPage(self) +local b, d = self.buf, self.demux + while true do + local p = Page.find(b, self.pagePos, nil, d.verify) + if not p then + return false + end + self.pagePos = p.offset + p.size + if p.serial == self.serial then + if self.lastSeq >= 0 and p.sequence ~= (self.lastSeq + 1) % 4294967296 then + -- a page is missing: drop the partial packet + self.parts, self.partLen = {}, 0 + self.gap = true + end + self.lastSeq = p.sequence + self.page = p + self.seg = 0 + self.dataPos = p.offset + p.headerSize + self.firstPacketOnPage = true + local lc = -1 + local base = p.offset + 27 + for i = 0, p.nsegs - 1 do + if readu8(b, base + i) < 255 then + lc = i + end + end + self.lastComplete = lc + if p.continued then + if self.partLen == 0 and #self.parts == 0 then + -- the start of this packet is not ours (after a seek or a loss): skip its tail + local s = 0 + while s < p.nsegs do + local l = readu8(b, base + s) + self.dataPos =self.dataPos+ l + s =s+ 1 + if l < 255 then + break + end + end + self.seg = s + self.firstPacketOnPage = false + end + elseif #self.parts > 0 then + -- a fresh packet while one was pending: the pending one is lost + self.parts, self.partLen = {}, 0 + self.gap = true + end + return true + end + end +end + +-- The next packet, or nil at the end of the stream +function Reader.nextPacket(self) +if self.ended then + return nil + end + local b = self.buf + while true do + local p = self.page + if p and self.seg < p.nsegs then + local base = p.offset + 27 + local start = self.dataPos + local len = 0 + local s = self.seg + local complete = false + while s < p.nsegs do + local l = readu8(b, base + s) + s =s+ 1 + len =len+ l + if l < 255 then + complete = true + break + end + end + self.seg = s + self.dataPos = start + len + if complete then + local data, off, size = b, start, len + local parts = self.parts + if #parts > 0 then + size = self.partLen + len + data = buffer.create(size) + off = 0 + local o = 0 + for i = 1, #parts, 2 do + buffer.copy(data, o, b, parts[i], parts[i + 1]) + o =o+ parts[i + 1] + end + buffer.copy(data, o, b, start, len) + self.parts, self.partLen = {}, 0 + end + local last = (s - 1) == self.lastComplete + local pkt = { + data = data, + offset = off, + size = size, + granule = (last and{p.granule }or{(-1)})[1], + pageGranule = p.granule, + bos = p.bos and self.firstPacketOnPage, + eos = p.eos and last, + pageOffset = p.offset, + gap = self.gap, + } + self.firstPacketOnPage = false + self.gap = false + self.total =self.total+ 1 + if pkt.eos then + self.ended = true + end + return pkt + else + -- the packet continues on a later page + table.insert(self.parts, start) + table.insert(self.parts, len) + self.partLen =self.partLen+ len + end + else + if p and p.eos then + self.ended = true + return nil + end + if not self:_nextPage() then + self.ended = true + return nil + end + end + end +end + +-- Back to the start of the stream (the identification packet comes next) +function Reader.rewind(self) + self.pagePos = self.start + self.page = nil + self.seg = 0 + self.parts, self.partLen = {}, 0 + self.lastSeq = -1 + self.gap = false + self.ended = false +end + +-- Position on page p: the packets finishing on p are skipped; the next packet is the one that starts after them +function Reader._at(self, p) + self:rewind() + self.pagePos = p.offset + self:_nextPage() -- loads p (it is a valid page of this serial) + local b = self.buf + local base = p.offset + 27 + local dp = p.offset + p.headerSize + for i = 0, self.lastComplete do + dp =dp+ readu8(b, base + i) + end + self.seg = self.lastComplete + 1 + self.dataPos = dp + self.parts, self.partLen = {}, 0 + self.firstPacketOnPage = false + self.gap = false + self.ended = false +end + +-- Seek so that the next packet is the first one that starts at or before granule g: positions after the last +-- page whose granule is <= g (found by bisection over byte offsets, then a short linear scan). Returns the +-- granule at the start of that next packet, or nil, err. A g before every granule rewinds to the stream start +-- (headers included) and returns -1. A g past the end leaves the reader at the end (nextPacket gives nil). +function Reader.seekGranule(self, g) +local b, d = self.buf, self.demux + local serial = self.serial + local verify = d.verify + local function nextOf(pos, limit) +while true do + local p = Page.find(b, pos, limit, verify) + if not p then + return nil + end + if p.serial == serial and p.granule ~= -1 then + return p + end + pos = p.offset + p.size + end + end + local lo, hi = self.start, buffer.len(b) + local best= nil + while hi - lo > 65536 do + local mid = math.floor((lo + hi) / 2 +) local p = nextOf(mid, hi) + if p and p.granule <= g then + best = p + lo = p.offset + else + hi = mid + end + end + local pos = lo + while true do + local p = nextOf(pos) + if not p or p.granule > g then + break + end + best = p + pos = p.offset + p.size + end + if not best then + self:rewind() + return -1, nil + end + self:_at(best) + return best.granule, nil +end + +-- Demux +local Demux = {} +Demux.__index = Demux + +-- open(src, opts?) -> Demux | nil, Err. src: a buffer (the whole file) or a core/Bytes Reader (its range is copied +-- when it is not the whole buffer). opts.verify = false skips CRC checks (faster on trusted data); opts.scanAll = +-- true lists every bos page in the file (chained streams), not just the first group +function Ogg.open(src, opts) +local buf +if type(src) == "buffer" then + buf = src + elseif type(src) == "table" and type(src.buf) == "buffer" and type(src.base) == "number" and type(src.limit) == "number" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + buf = src.buf + else + local n = math.max(0, src.limit - src.base) + buf = buffer.create(n) + buffer.copy(buf, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer or a Reader") + end + local verify = not (opts and opts.verify == false) + local first = Page.find(buf, 0, nil, verify) + if not first then + return nil, Err.new(Err.CORRUPT, "no Ogg page found") + end + local d = setmetatable({ + buf = buf, + size = buffer.len(buf), + verify = verify, + _streams = {} , + _bySerial = {} , + _readers = {} , + _lastDone = false, + }, Demux) + -- the bos pages (at the start of the file, and later ones for chains if scanAll) + local pos = first.offset + local scanAll = opts and opts.scanAll + while true do + local p = Page.find(buf, pos, nil, verify) + if not p then + break + end + if p.bos and not d._bySerial[p.serial] then + local st = { + serial = p.serial, + codec = "unknown", + firstPacket = buffer.create(0), + bosOffset = p.offset, + lastGranule = -1, + } + table.insert(d._streams, st) + d._bySerial[p.serial] = st + local r = newReader(d, p.serial, p.offset) + local pk = r:nextPacket() + if pk then + local c = buffer.create(pk.size) + buffer.copy(c, 0, pk.data, pk.offset, pk.size) + st.firstPacket = c + st.codec = Page.codec(c, 0, pk.size) + end + elseif not p.bos and not scanAll then + break + end + pos = p.offset + p.size + end + if #d._streams == 0 then + return nil, Err.new(Err.CORRUPT, "no beginning-of-stream page") + end + return d, nil +end + +-- Scan backwards from the end for each stream's last granule +function Demux._scanLast(self) + if self._lastDone then + return + end + self._lastDone = true + local b = self.buf + local need = #self._streams + local pos = self.size - 27 + while need > 0 do + local p = Page.findBack(b, pos, 0, self.verify) + if not p then + break + end + local st = self._bySerial[p.serial] + if st and st.lastGranule == -1 and p.granule ~= -1 then + st.lastGranule = p.granule + need =need- 1 + end + pos = p.offset - 1 + end +end + +-- Every logical stream: { serial, codec, firstPacket, bosOffset, lastGranule } +function Demux.streams(self) +self:_scanLast() + return self._streams +end + +function Demux.stream(self, serial) +self:_scanLast() + return self._bySerial[serial] +end + +-- The serial of the first stream of a codec, or nil +function Demux.find(self, codec) +for _, s in __iter(self._streams) do + if s.codec == codec then + return s.serial + end + end + return nil +end + +-- The packet cursor of a stream (one per serial, shared by nextPacket / seekGranule below), or nil, Err +function Demux.reader(self, serial) +local r = self._readers[serial] + if r then + return r, nil + end + local st = self._bySerial[serial] + if not st then + return nil, Err.new(Err.ARG, "unknown serial " .. tostring(serial)) + end + r = newReader(self, serial, st.bosOffset) + self._readers[serial] = r + return r, nil +end + +function Demux.nextPacket(self, serial) +local r = self:reader(serial) + return (r and{(r:nextPacket() )}or{nil +})[1]end + +function Demux.seekGranule(self, serial, g) +local r, err = self:reader(serial) + if not r then + return nil, err + end + return r:seekGranule(g) +end + +function Demux.rewind(self, serial) + local r = self:reader(serial) + if r then + r:rewind() + end +end + +-- for p in demux:packets(serial) do ... end (continues from the stream's current position) +function Demux.packets(self, serial) +local r = self:reader(serial) + return function() + return (r and{(r:nextPacket() )}or{nil +})[1] end +end + +-- Copy a packet's bytes into a fresh buffer of its own +function Ogg.copy(p) +local c = buffer.create(p.size) + buffer.copy(c, 0, p.data, p.offset, p.size) + return c +end + +return Ogg +end +__FILES["containers/Ogg/Mux"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!native +--!optimize 2 +-- containers/Ogg/Mux: the Ogg page writer (RFC 3533), for Ogg Opus / Vorbis / FLAC output. New in rosetta. +-- Packets are laced into pages per logical stream; a page is closed when it reaches opts.pageSize bytes of data (or +-- 255 lacing values), when a packet asks for flush, and at the end (eos). The page granule is the granule of the last +-- packet that finishes on it (-1 when none does). Pages go to the output in the order they close, so the bos pages +-- of a multiplexed file come first when every stream's first packet is written (with flush) before any other. +-- +-- local mux = Mux.new({ pageSize = 4096 }) +-- local s = mux:stream(0x1234) -- serial (default: 1, 2, ...) +-- s:packet(head, 0, { flush = true }) -- OpusHead / FLAC mapping header: alone on the bos page +-- s:packet(tags, 0, { flush = true }) +-- s:packet(audio, granule) -- granule after this packet (samples, at the codec's rate) +-- local out = mux:finish() -- closes every stream with an eos page +-- +-- Never throws: a bad argument returns false, Err. +local Err = __include("core/Err") +local Page = __include("containers/Ogg/Page") + +local CRC = Page.CRC_TABLE +local readu8, writeu8, writeu32, writei32 = buffer.readu8, buffer.writeu8, buffer.writeu32, buffer.writei32 +local bxor, lshift, rshift = bit32.bxor, bit32.lshift, bit32.rshift + +local Mux = {} +Mux.__index = Mux +local Stream = {} +Stream.__index = Stream + +-- new(opts?) -> Mux + + + + + + + + +function Mux.new(opts) +local size = opts and opts.pageSize or 4096 + if type(size) ~= "number" or size < 1 then + size = 4096 + end + return setmetatable({ + pageSize = math.min(size, 255 * 255), + chunks = {} , + total = 0, + streams = {} , + nextSerial = 1, + }, Mux) +end + +-- stream(serial?) -> Stream (serials must be unique in the file) +function Mux.stream(self, serial) +local sr = serial or self.nextSerial + self.nextSerial = math.max(self.nextSerial, sr + 1) + local s = setmetatable({ + mux = self, + serial = sr % 4294967296, + seq = 0, + lacing = {} , + parts = {} , -- buffer, offset, length triples of the page data + dataLen = 0, + granule = -1, + continued = false, -- the page being built starts with the tail of a packet + first = true, + ended = false, + lastGranule = -1, + }, Stream) + table.insert(self.streams, s) + return s +end + +-- the CRC of a page (the crc field written as zero) +local function crc(b, n) +local c = 0 + for i = 0, n - 1 do + c = bxor(lshift(c, 8), CRC[bxor(rshift(c, 24), readu8(b, i)) + 1]) + end + return c +end + +-- close the page being built (also when empty, for eos) +function Stream._flush(self, eos) + local nseg = #self.lacing + local n = 27 + nseg + self.dataLen + local b = buffer.create(n) + buffer.writestring(b, 0, "OggS") + local flags = (self.continued and 1 or 0) + (self.first and 2 or 0) + (eos and 4 or 0) + writeu8(b, 5, flags) + local g = self.granule + if g < 0 then + writeu32(b, 6, 0xFFFFFFFF) + writei32(b, 10, -1) + else + writeu32(b, 6, g % 4294967296) + writeu32(b, 10, (math.floor(g / 4294967296)) % 4294967296) + end + writeu32(b, 14, self.serial) + writeu32(b, 18, self.seq % 4294967296) + writeu8(b, 26, nseg) + for i = 1, nseg do + writeu8(b, 26 + i, self.lacing[i]) + end + local o = 27 + nseg + local parts = self.parts + for i = 1, #parts, 3 do + buffer.copy(b, o, parts[i], parts[i + 1], parts[i + 2]) + o =o+ parts[i + 2] + end + writeu32(b, 22, crc(b, n)) + local m = self.mux + table.insert(m.chunks, b) + m.total =m.total+ n + self.seq =self.seq+ 1 + self.first = false + self.lacing, self.parts, self.dataLen, self.granule = {}, {}, 0, -1 + self.continued = false + if eos then + self.ended = true + end +end + +-- packet(data, granule, opts?) -> true | false, Err. data: buffer or string; granule: the position after this packet +-- (-1: unknown, not recommended); offset / length select a range of data. +function Stream.packet(self, data, granule, opts, offset, length) +if self.ended then + return false, Err.new(Err.ARG, "packet after the end of stream " .. self.serial) + end + local b +if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + else + return false, Err.new(Err.ARG, "packet: data must be a buffer or a string") + end + if type(granule) ~= "number" then + return false, Err.new(Err.ARG, "packet: granule must be a number") + end + local off = offset or 0 + local len = length or (buffer.len(b) - off) + if off < 0 or len < 0 or off + len > buffer.len(b) then + return false, Err.new(Err.ARG, "packet: range outside the buffer") + end + local pageSize = self.mux.pageSize + local left = len + local pos = off + -- lacing: 255-byte segments then one < 255 (0 when the size is a multiple of 255) + while true do + if #self.lacing == 255 or (self.dataLen >= pageSize and #self.lacing > 0) then + self:_flush(false) + self.continued = pos > off -- the next page starts inside this packet + end + local seg = math.min(left, 255) + table.insert(self.lacing, seg) + if seg > 0 then + table.insert(self.parts, b) + table.insert(self.parts, pos) + table.insert(self.parts, seg) + end + self.dataLen =self.dataLen+ seg + pos =pos+ seg + left =left- seg + if seg < 255 then + break + end + end + if granule >= 0 then -- -1 (unknown) keeps the granule of an earlier packet finishing on this page + self.granule = granule + self.lastGranule = granule + end + local eos = opts and opts.eos or false + if eos then + self:_flush(true) + elseif (opts and opts.flush) or self.dataLen >= pageSize or #self.lacing == 255 then + self:_flush(false) + end + return true, nil +end + +-- flush(): close the current page now (if it holds anything) +function Stream.flush(self) + if not self.ended and #self.lacing > 0 then + self:_flush(false) + end +end + +-- finish() -> the file: closes every stream with an eos page (an empty one when its last page was already written) +function Mux.finish(self) +for _, s in __iter(self.streams) do + if not s.ended then + if #s.lacing == 0 then + s.granule = s.lastGranule + end + s:_flush(true) + end + end + local out = buffer.create(self.total) + local o = 0 + for _, c in __iter(self.chunks) do + buffer.copy(out, o, c, 0, buffer.len(c)) + o =o+ buffer.len(c) + end + return out +end + +return Mux +end +__FILES["containers/Ogg/Page"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- containers/Ogg/Page: Ogg pages (RFC 3533). Absorbed from ogg-luau be9f604 (same author, no third-party code): the CRC-32 (poly 0x04C11DB7, MSB first, init 0, the CRC field read as zero), header +-- parsing with bounds checks, and the capture-pattern resync (find the next valid page at or after a byte offset, +-- forwards or backwards). Nothing here throws: invalid or truncated data gives nil. +-- +-- A page header (27 bytes + segment table): +-- 0 "OggS" | 4 version (0) | 5 flags (1 continued, 2 bos, 4 eos) | 6 granule (i64 LE) | 14 serial (u32) +-- 18 sequence (u32) | 22 crc (u32) | 26 segment count | 27 lacing values | data +local Crc32 = __include("core/Crc32") +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 +local band, bxor, lshift, rshift = bit32.band, bit32.bxor, bit32.lshift, bit32.rshift + +local Page = {} + +-- CRC table, MSB-first (core/Crc32) + + + + + + + + + + + + + + +local CRC = Crc32.MSB_TABLE +Page.CRC_TABLE = CRC + +-- CRC of bytes [from, to) (caller guarantees bounds), continuing from crc +local function crcRange(b, from, to, crc) +for i = from, to - 1 do + crc = bxor(lshift(crc, 8), CRC[bxor(rshift(crc, 24), readu8(b, i)) + 1]) + end + return crc +end + +-- CRC-32 of a byte range, the Ogg way (the crc field is not zeroed: use for arbitrary data) +function Page.crc32(b, offset, len) +local o = offset or 0 + local n = len or (buffer.len(b) - o) + if o < 0 or n < 0 or o + n > buffer.len(b) then + return 0 + end + return crcRange(b, o, o + n, 0) +end + +-- Parse the page at pos. Returns Info, or nil + reason ("short" if the buffer ends inside the page, "magic", +-- "version", "crc"). verify = false skips the CRC check. +function Page.parse(b, pos, verify) +local size = buffer.len(b) + if pos < 0 or pos + 27 > size then + return nil, "short" + end + if readu32(b, pos) ~= 0x5367674F then -- "OggS" + return nil, "magic" + end + if readu8(b, pos + 4) ~= 0 then + return nil, "version" + end + local nsegs = readu8(b, pos + 26) + local hsize = 27 + nsegs + if pos + hsize > size then + return nil, "short" + end + local dlen = 0 + for i = pos + 27, pos + hsize - 1 do + dlen =dlen+ readu8(b, i) + end + local total = hsize + dlen + if pos + total > size then + return nil, "short" + end + if verify ~= false then + local c = crcRange(b, pos, pos + 22, 0) + for _ = 1, 4 do + c = bxor(lshift(c, 8), CRC[rshift(c, 24) + 1]) + end + c = crcRange(b, pos + 26, pos + total, c) + if c ~= readu32(b, pos + 22) then + return nil, "crc" + end + end + local flags = readu8(b, pos + 5) + return { + offset = pos, + size = total, + headerSize = hsize, + nsegs = nsegs, + flags = flags, + continued = band(flags, 1) ~= 0, + bos = band(flags, 2) ~= 0, + eos = band(flags, 4) ~= 0, + granule = readi32(b, pos + 10) * 4294967296 + readu32(b, pos + 6), + serial = readu32(b, pos + 14), + sequence = readu32(b, pos + 18), + }, nil +end + +-- The first valid page starting at an offset in [pos, limit) (limit defaults to the buffer end). Resyncs on the +-- capture pattern: bytes that are not a valid page (garbage, a bad CRC, a truncated page) are skipped. +function Page.find(b, pos, limit, verify) +local size = buffer.len(b) + local lim = math.min(limit or size, size - 27 + 1) + if pos < 0 then + pos = 0 + end + while pos < lim do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos =pos+ 1 + end + return nil +end + +-- The last valid page starting at an offset in [floor, pos] (searching backwards). +function Page.findBack(b, pos, floor, verify) +local size = buffer.len(b) + local lo = math.max(floor or 0, 0) + if pos > size - 27 then + pos = size - 27 + end + while pos >= lo do + if readu8(b, pos) == 0x4F and readu32(b, pos) == 0x5367674F then + local p = Page.parse(b, pos, verify) + if p then + return p + end + end + pos =pos- 1 + end + return nil +end + +-- The identification of a codec from a stream's first packet (the bos page's packet) +function Page.codec(b, off, len) +local function is(s, at) +if at + #s > len then + return false + end + for i = 1, #s do + if readu8(b, off + at + i - 1) ~= string.byte(s, i) then + return false + end + end + return true + end + if is("OpusHead", 0) then + return "opus" + elseif len >= 5 and readu8(b, off) == 0x7F and is("FLAC", 1) then + return "flac" + elseif len >= 7 and readu8(b, off) == 1 and is("vorbis", 1) then + return "vorbis" + elseif len >= 7 and readu8(b, off) == 0x80 and is("theora", 1) then + return "theora" + elseif is("Speex ", 0) then + return "speex" + elseif is("fishead", 0) then + return "skeleton" + elseif is("fLaC", 0) then + return "flac-old" -- pre-1.1.1 Ogg FLAC mapping + end + return "unknown" +end + +return Page +end +__FILES["containers/Riff"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently +-- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from +-- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. +-- +-- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer +-- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false +-- for _, c in f.chunks do print(c.id, c.offset, c.size, c.avail) end -- offsets are absolute in f.buf +-- local c = Riff.find(f, "fmt ") +-- local subs = Riff.list(f, c) -- the sub-chunks of a LIST body (after its type) +-- +-- local w = Riff.writer("WAVE", { rf64 = "auto" }) -- or bigEndian = true (RIFX) +-- w:chunk("fmt ", fmtBody) w:chunk("data", samples) w:list("INFO", { { "INAM", "title" } }) +-- local file = w:finish() -- RF64 + ds64 when a size passes 4 GiB +-- local parts = w:finish({ parts = true }) -- { buffer }: no copy, for files over 1 GiB +-- +-- Lenient reading (what real files need): an odd-sized chunk without its pad byte is detected; a chunk declared past +-- the end keeps what is there (avail < size, truncated = true) and ends the walk; for the ids in opts.openEnded a +-- size of 0 or 0xFFFFFFFF means "up to the end of the file" (streamed writers) and ends the walk; RF64 sizes of +-- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Riff = {} + +-- ------------------------------------------------------------------------------------------------ read + + + + + + + + + + + + + + + + + + + + + + + + + + +local function u32(b, o, be) +local v = readu32(b, o) + return (be and{(bit32.byteswap(v) )}or{v +})[1]end + +-- sniff(r) -> the form type ("WAVE", ...) when r starts with a RIFF / RIFX / RF64 / BW64 header, else nil +function Riff.sniff(r) +local magic = r:peek(4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil + end + local form = r:peek(4, 8) + return (#form == 4 and{form }or{nil +})[1]end + +-- walk(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2, +-- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64) +local function walk(b, p, limit, be, opts, ds64) +local layout= { + bigEndian = be, + pad = 2, + lenientPad = true, + openEnded = opts and opts.openEnded, + maxChunks = opts and opts.maxChunks, + resize = ds64 +and function(id, declared) +if declared ~= 0xFFFFFFFF then + return nil + end + return (id == "data" and{ds64.dataSize }or{ds64.table[id] +})[1] end +or nil, + } + return (Chunks.walk(b, p, limit, layout) ) +end + +-- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. +function Riff.read(src, opts) +local r = (type(src) == "buffer" and{(Bytes.reader(src) )}or{src +})[1] if type(r) ~= "table" or type(r.buf) ~= "buffer" then + return nil, Err.new(Err.ARG, "read: expected a buffer or a Reader") + end + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "file too short for a RIFF header", base) + end + local magic = readstring(b, base, 4) + if magic ~= "RIFF" and magic ~= "RIFX" and magic ~= "RF64" and magic ~= "BW64" then + return nil, Err.new(Err.CORRUPT, "not a RIFF / RIFX / RF64 file", base) + end + local be = magic == "RIFX" + local f= { + container = magic == "BW64" and"RF64" or magic, + form = readstring(b, base + 8, 4), + bigEndian = be, + buf = b, + base = base, + limit = limit, + size = u32(b, base + 4, be), + chunks = {}, + ds64 = nil, + } + -- RF64: the ds64 chunk comes first + if f.container == "RF64" and base + 20 <= limit and readstring(b, base + 12, 4) == "ds64" then + local sz = readu32(b, base + 16) + local o = base + 20 + if sz >= 24 and o + 24 <= limit then + local d = { + riffSize = readu32(b, o) + readu32(b, o + 4) * 4294967296, + dataSize = readu32(b, o + 8) + readu32(b, o + 12) * 4294967296, + sampleCount = readu32(b, o + 16) + readu32(b, o + 20) * 4294967296, + table = {} , + } + if sz >= 28 and o + 28 <= limit then + local n = readu32(b, o + 24) + local q = o + 28 + for _ = 1, math.min(n, 1000) do + if q + 12 > limit or q + 12 > o + sz then + break + end + d.table[readstring(b, q, 4)] = readu32(b, q + 4) + readu32(b, q + 8) * 4294967296 + q =q+ 12 + end + end + f.ds64 = d + if f.size == 0xFFFFFFFF then + f.size = d.riffSize + end + end + end + f.chunks = walk(b, base + 12, limit, be, opts, f.ds64) + return f, nil +end + +-- find(file, id, from?) -> the first chunk with that id (after index from), and its index +function Riff.find(f, id, from) +for i = (from or 0) + 1, #f.chunks do + if f.chunks[i].id == id then + return f.chunks[i], i + end + end + return nil, nil +end + +-- listType(file, chunk) -> the 4-byte type of a LIST / RIFF chunk ("INFO", "movi", ...) or nil +function Riff.listType(f, c) +if c.avail < 4 then + return nil + end + return readstring(f.buf, c.offset, 4) +end + +-- list(file, chunk, opts?) -> the sub-chunks of a LIST body (after its 4-byte type) +function Riff.list(f, c, opts) +if c.avail < 4 then + return {} + end + return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) +end + +-- body(file, chunk) -> a Reader over the chunk's available body +function Riff.body(f, c) +return Bytes.reader(f.buf, c.offset, c.avail) +end + +-- u16 / u32 in the file's byte order (for chunk bodies) +function Riff.u16(f, o) +if f.bigEndian then + return readu8(f.buf, o) * 256 + readu8(f.buf, o + 1) + end + return readu16(f.buf, o) +end +function Riff.u32(f, o) +return u32(f.buf, o, f.bigEndian) +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +-- writer(form, opts?) -> Writer: collects chunks; finish() lays out the file + + + + + + + +function Riff.writer(form, opts) +return setmetatable({ + form = string.sub(form .. " ", 1, 4), + be = opts and opts.bigEndian or false, + rf64 = (opts and opts.rf64 ~= nil and{opts.rf64 }or{"auto"})[1], + sampleCount = opts and opts.sampleCount or 0, + threshold = opts and opts.rf64Threshold or 0xFFFFFFFF, + chunks = {} , + }, Writer) +end + +-- chunk(id, body, offset?, length?): body is a buffer or a string (a range of a buffer with offset / length), or a +-- list of buffers written one after the other (a data chunk bigger than one buffer) +function Writer.chunk(self, id, body, offset, length) + local parts = {} + local n = 0 + if type(body) == "table" then + for _, b in __iter(body) do + table.insert(parts, { b, 0, buffer.len(b) }) + n =n+ buffer.len(b) + end + else + local b= (type(body) == "string" and{(buffer.fromstring(body) )}or{body +})[1] local o = offset or 0 + n = length or (buffer.len(b) - o) + parts[1] = { b, o, n } + end + table.insert(self.chunks, { id = string.sub(id .. " ", 1, 4), parts = parts, length = n }) +end + +-- list(type, items): a LIST chunk of { id, string-or-buffer } sub-chunks (strings get a NUL terminator, INFO style) +function Writer.list(self, listType, items) + local w = Bytes.writer() + w:string(string.sub(listType .. " ", 1, 4)) + for _, it in __iter(items) do + local v = it[2] + local data= (type(v) == "string" and{(buffer.fromstring(v .. "\0") )}or{v +})[1] local n = buffer.len(data) + w:string(string.sub(it[1] .. " ", 1, 4)) + if self.be then + w:u32be(n) + else + w:u32le(n) + end + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + end + self:chunk("LIST", w:finish()) +end + +-- finish(opts?) -> buffer | nil, Err; with opts.parts: { buffer } (the header pieces and the chunk bodies, not copied) +function Writer.finish(self, opts) +local total = 4 -- the form type + local big = false + local dataSize = 0 + for _, c in __iter(self.chunks) do + total =total+ (8 + c.length + c.length % 2 +) if c.length > 0xFFFFFFFE then + big = true + end + if c.id == "data" then + dataSize = c.length + end + end + local rf64 = self.rf64 == true or (self.rf64 == "auto" and (big or total > self.threshold)) + if not rf64 and (big or total > 0xFFFFFFFF) then + return nil, Err.new(Err.LIMIT, "over 4 GiB without RF64") + end + if rf64 and self.be then + return nil, Err.new(Err.ARG, "RF64 is little-endian only") + end + if rf64 then + total =total+ 36 -- ds64 + end + local asParts = opts and opts.parts + if not asParts and total + 8 > 0x40000000 then + return nil, Err.new(Err.LIMIT, "the file would not fit in a buffer (1 GiB): use finish({ parts = true })") + end + local out= {} + local w = Bytes.writer(asParts and 256 or total + 8) + local function size32(v) + if self.be then + w:u32be(v) + else + w:u32le(v) + end + end + if rf64 then + w:string("RF64") + w:u32le(0xFFFFFFFF) + w:string(self.form) + w:string("ds64") + w:u32le(28) + w:u64le(total) + w:u64le(dataSize) + w:u64le(self.sampleCount) + w:u32le(0) -- no table: only data may be over 4 GiB + else + w:string(self.be and"RIFX" or"RIFF") + size32(total) + w:string(self.form) + end + for _, c in __iter(self.chunks) do + w:string(c.id) + if rf64 and (c.id == "data" or c.length > 0xFFFFFFFE) then + w:u32le(0xFFFFFFFF) + else + size32(c.length) + end + for _, p in __iter(c.parts) do + if asParts then + table.insert(out, w:finish()) + w = Bytes.writer(64) + if p[2] == 0 and p[3] == buffer.len(p[1]) then + table.insert(out, p[1]) + else + local cp = buffer.create(p[3]) + buffer.copy(cp, 0, p[1], p[2], p[3]) + table.insert(out, cp) + end + else + w:bytes(p[1], p[2], p[3]) + end + end + if c.length % 2 == 1 then + w:u8(0) + end + end + if asParts then + if w:tell() > 0 then + table.insert(out, w:finish()) + end + return out, nil + end + return w:finish(), nil +end + +return Riff +end +__FILES["containers/Tar"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles +-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, +-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, +-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar +-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, +-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX +-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- +-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). +-- +-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } +-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) +-- +-- Never throws: bad data returns nil, Err. +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local Tar = {} + + + + + + + + + + + + + + + + + +local BLOCK = 512 + +local function zeros(b, o) +for i = 0, BLOCK - 1, 4 do + if buffer.readu32(b, o + i) ~= 0 then + return false + end + end + return true +end + +-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte) +local function number(b, o, n) +local first = buffer.readu8(b, o) + if first >= 0x80 then + local v = first - (first >= 0xC0 and 0x100 or 0x80) -- 0xFF.. = negative + for i = 1, n - 1 do + v = v * 256 + buffer.readu8(b, o + i) + end + return v + end + local s = buffer.readstring(b, o, n) + s = string.match(s, "^[ %z]*([0-7]*)") or "" + if s == "" then + return 0 + end + return tonumber(s, 8) +end + +local function str(b, o, n) +local s = buffer.readstring(b, o, n) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1]end + +local function checksum(b, o) +local u, s = 0, 0 + for i = 0, BLOCK - 1 do + local v = i >= 148 and i < 156 and 32 or buffer.readu8(b, o + i) + u =u+ v + s =s+ (v >= 128 and((v - 256 ))or(v +)) end + return u, s +end + +-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum +function Tar.valid(b, o) +if o + BLOCK > buffer.len(b) or zeros(b, o) then + return false + end + local want = number(b, o + 148, 8) + local u, s = checksum(b, o) + return want == u or want == s +end + +-- pax records "len key=value\n" -> { key = value } +local function pax(b, o, n, into) +local s = buffer.readstring(b, o, n) + local p = 1 + while p <= #s do + if string.byte(s, p) == 0 then + break + end + local len = string.match(s, "^(%d+) ", p) + if not len then + return false + end + local l = (tonumber(len) ) +if l < #len + 3 or p + l - 1 > #s then + return false + end + local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline + local eq = string.find(rec, "=", 1, true) + if not eq then + return false + end + into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1) + p =p+ l + end + return true +end + +-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err + + +function Tar.read(b, offset, length, opts) +local o = offset or 0 + local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o))) + local maxEntries = (opts and opts.maxEntries) or 1e6 + local out= {} + local global= {} + local nextPax= nil + local longName= nil + local longLink= nil + local p = o + while true do +local __DARKLUA_CONTINUE_5=false repeat if p + BLOCK > e then + if p == e then + break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning) + end + return nil, Err.new(Err.TRUNCATED, "header past the end", p) + end + if zeros(b, p) then + break -- end of archive (one or two zero blocks; what follows is padding) + end + local want = number(b, p + 148, 8) + local u, s = checksum(b, p) + if want ~= u and want ~= s then + return nil, Err.new((#out == 0 and{Err.CORRUPT }or{Err.CHECKSUM})[1], "bad header checksum", p + 148) + end + local typ = buffer.readstring(b, p + 156, 1) + if typ == "\0" then + typ = "0" + end + local size = number(b, p + 124, 12) + if not size or size < 0 then + return nil, Err.new(Err.CORRUPT, "bad size field", p + 124) + end + local data = p + BLOCK + local nextHeader = data + math.floor((size + BLOCK - 1) / BLOCK )* BLOCK + local ustar = buffer.readstring(b, p + 257, 5) == "ustar" + -- meta records: pax / GNU long names + if typ == "x" or typ == "g" or typ == "L" or typ == "K" then + if data + size > e then + return nil, Err.new(Err.TRUNCATED, "extended header past the end", data) + end + if typ == "x" or typ == "g" then + local into = (typ == "g" and{global }or{(nextPax or {}) +})[1] if not pax(b, data, size, into) then + return nil, Err.new(Err.CORRUPT, "bad pax record", data) + end + if typ == "x" then + nextPax = into + end + elseif typ == "L" then + longName = str(b, data, size) + else + longLink = str(b, data, size) + end + p = nextHeader +__DARKLUA_CONTINUE_5=true break + end + local name = str(b, p, 100) + if ustar then + local prefix = str(b, p + 345, 155) + if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times) + name = prefix .. "/" .. name + end + end + local entry= { + name = name, + size = size, + type = typ, + dir = typ == "5", + mode = number(b, p + 100, 8) or 0, + uid = number(b, p + 108, 8) or 0, + gid = number(b, p + 116, 8) or 0, + mtime = number(b, p + 136, 12) or 0, + link = ((typ == "1" or typ == "2" )and{(str(b, p + 157, 100) )}or{nil})[1], + uname = (ustar and{(str(b, p + 265, 32) )}or{nil})[1], + gname = (ustar and{(str(b, p + 297, 32) )}or{nil})[1], + offset = data, + pax = nil, + } + if longName then + entry.name = longName + end + if longLink then + entry.link = longLink + end + local px = nextPax + for _, rec in __iter({ global, px }) do + if rec then + if rec.path then + entry.name = rec.path + end + if rec.linkpath then + entry.link = rec.linkpath + end + if rec.size then + local sz = tonumber(rec.size) + if not sz or sz < 0 or sz % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad pax size", p) + end + entry.size = sz + end + if rec.mtime then + entry.mtime = tonumber(rec.mtime) or entry.mtime + end + if rec.uid then + entry.uid = tonumber(rec.uid) or entry.uid + end + if rec.gid then + entry.gid = tonumber(rec.gid) or entry.gid + end + if rec.uname then + entry.uname = rec.uname + end + if rec.gname then + entry.gname = rec.gname + end + end + end + if px then + entry.pax = px + end + if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then + entry.dir = true + end + -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir) + local dataSize = (typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" )and 0 or entry.size + if typ == "5" or typ == "1" or typ == "2" then + entry.size = 0 + end + nextHeader = data + math.floor((dataSize + BLOCK - 1) / BLOCK )* BLOCK + if typ ~= "5" and data + dataSize > e then + return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data) + end + table.insert(out, entry) + if #out > maxEntries then + return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") + end + nextPax, longName, longLink = nil, nil, nil + p = nextHeader +__DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end + return out, nil +end +-- ------------------------------------------------------------------------------------------------ writing + + + + + + + + + + + + + + + + +local function octal(w, o, n, v) -- n - 1 octal digits and a NUL; false when it does not fit + +local s = string.format("%o", v) + if v < 0 or v % 1 ~= 0 or #s > n - 1 then + return false + end + buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s) + buffer.writeu8(w, o + n - 1, 0) + return true +end + +local function field(w, o, n, s) + buffer.writestring(w, o, string.sub(s, 1, n)) +end + +local function ascii(s) +return not string.find(s, "[\128-\255]") +end + +local function paxRecord(key, value) +local body = " " .. key .. "=" .. value .. "\n" + local n = #body + 1 + while #tostring(n) + #body ~= n do + n = #tostring(n) + #body + end + return tostring(n) .. body +end + +-- one header block (the checksum filled in) +local function header(name, typ, size, e, prefix, link, gnu) +local h = buffer.create(BLOCK) + field(h, 0, 100, name) + local mode = e.mode or (typ == "5" and 0x1ED or 0x1A4) + octal(h, 100, 8, mode % 0x200000) + octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF)) + octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF)) + octal(h, 124, 12, size) + octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1)) + field(h, 148, 8, " ") + field(h, 156, 1, typ) + field(h, 157, 100, link) + field(h, 257, 8, gnu and"ustar \0" or"ustar\00000") + field(h, 265, 32, e.uname or "") + field(h, 297, 32, e.gname or "") + field(h, 345, 155, prefix) + local u = checksum(h, 0) + field(h, 148, 8, string.format("%06o", u) .. "\0 ") + return h +end + +-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil +local function split(path) +if #path <= 100 then + return "", path + end + for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile + if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then + return string.sub(path, 1, i - 1), string.sub(path, i + 1) + end + end + return nil, nil +end + +-- write(entries, opts?) -> buffer | nil, Err +function Tar.write(entries, opts) +local fmt = (opts and opts.format) or "pax" + local w = Bytes.writer(BLOCK * (2 * #entries + 2)) + for i, e in __iter(entries) do + if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name") + end + local data = e.data or buffer.create(0) + local typ = e.type or (e.dir and"5" or"0") + local name= e.name + if typ == "5" and string.sub(name, -1) ~= "/" then + name =name.. "/" + end + local size = ((typ == "0" or typ == "7" )and{(buffer.len(data) )}or{0 +})[1] local link = e.link or "" + -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole + local prefix, short + if fmt == "ustar" then + prefix, short = split(name) + elseif #name <= 100 then + prefix, short = "", name + end + local paxRecs= {} + -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII + local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name)) + local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link)) + if needName or needLink then + if fmt == "ustar" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar") + elseif fmt == "gnu" then + if needName then + local ln = buffer.fromstring(name .. "\0") + w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } , "", "", true)) + w:bytes(ln) + w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK) + end + if needLink then + local ll = buffer.fromstring(link .. "\0") + w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } , "", "", true)) + w:bytes(ll) + w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK) + end + else + if needName then + table.insert(paxRecs, paxRecord("path", name)) + end + if needLink then + table.insert(paxRecs, paxRecord("linkpath", link)) + end + end + end + if size >= 8 ^ 11 then + if fmt ~= "pax" then + return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax") + end + table.insert(paxRecs, paxRecord("size", tostring(size))) + end + local mt = e.mtime or 0 + if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then + table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", ""))) + end + if #paxRecs > 0 then + local body = buffer.fromstring(table.concat(paxRecs)) + w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } , "", "", false)) + w:bytes(body) + w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK) + end + if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then + -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile) + local stand = (fmt == "gnu" and{name }or{(string.gsub(name, "[\192-\255][\128-\191]*", "?") +)})[1] prefix, short = "", string.sub(stand, 1, 100) + end + w:bytes(header(short , typ, size >= 8 ^ 11 and 0 or size, e, prefix , string.sub(link, 1, 100), fmt == "gnu")) + if size > 0 then + w:bytes(data) + w:fill(0, (BLOCK - size % BLOCK) % BLOCK) + end + end + w:fill(0, BLOCK * 2) + return w:finish(), nil +end + +return Tar +end +__FILES["containers/Zip"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +--!optimize 2 +-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from +-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an +-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor +-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, +-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly +-- (codecs/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/Deflate compress, stored +-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. +-- +-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader +-- for _, e in zip:list() do print(e.name, e.size) end +-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked +-- +-- local w = Zip.writer() +-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds +-- local file = w:finish({ comment = "..." }) +-- +-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native +-- code it reaches (Deflate, Crc32) does not throw either. +local Err = __include("core/Err") +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +-- ------------------------------------------------------------------------------------------------ read + + + + + + + + + + + + + + + + + + + + + + + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b, o) +return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b, o, sig) +return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name) +name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name) +return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name) +local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) +function Zip.isZip(buf) +local b = (type(buf) == "string" and{(buffer.fromstring(string.sub(buf, 1, 4)) )}or{buf +})[1] return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b) +local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b) +local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries = (table.create(math.min(count, 65536)) ) +local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r =r+ 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r =r+ 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r =r+ 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q =q+ (4 + sz +) end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in __iter(entries) do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a +-- part of a bigger buffer) +function Zip.open(src) +local b +if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +-- every entry (directories included), in central directory order +function Archive.list(self) +return self.entries +end + +-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename +-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and +-- macOS "__MACOSX/" / "._" files never match by basename. +function Archive.find(self, name) +local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b, e, dataStart) +local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, (type(err) == "table" and{err.message }or{(tostring(err) +)})[1] end + return out +end + +-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers +-- get the local extra length wrong) +function Zip._starts(b, e) +local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +-- read(entry | name, verify = true) -> buffer | nil, Err +function Archive.read(self, entry, verify) +local e= (type(entry) == "string" and{(self:find(entry) )}or{entry })[1] +if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr= nil + local code = Err.CORRUPT + for _, s in __iter(starts) do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new((firstErr and string.find(firstErr, "CRC", 1, true) and{Err.CHECKSUM }or{code})[1], e.name .. ": " .. tostring(firstErr)) +end + +-- readString(entry | name, verify?) -> string | nil, Err +function Archive.readString(self, entry, verify) +local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +-- writer() -> Writer + + + + + + + + + + + + + +function Zip.writer() +return setmetatable({ files = {} }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local civil = Types.Date.civilFromDays +local function daysFrom(y, m, d) +y = (m <= 2 and((y - 1 ))or(y +)) local era = math.floor(((y >= 0 and{y }or{(y - 399)})[1]) / 400 +) local yoe = y - era * 400 + local mp = (m > 2 and((m - 3 ))or((m + 9 +))) local doy = math.floor((153 * mp + 2) / 5 )+ d - 1 + local doe = yoe * 365 + math.floor(yoe / 4 )- math.floor(yoe / 100 )+ doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t) +if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = math.floor(s / 86400 +) local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (math.floor(rem / 3600)) * 2048 + ((math.floor(rem / 60)) % 60) * 32 + math.floor((rem % 60) / 2 +) return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time, date) +local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s) +return string.find(s, "[\128-\255]") == nil +end + +-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) +function Writer.add(self, name, data, opts) +if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b +if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o= opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = (n > 0 and{(Crc32.of(b) )}or{0})[1], + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = (o.utf8 ~= nil and{o.utf8 }or{(not isAscii(name))})[1], + attributes = o.attributes or (isDir and 0x41ED0010 or 0x81A40000), + }) + return true, nil +end + +-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err +function Writer.addRaw(self, e, archive, newName) +local b = archive.buf + local start= nil + for _, s in __iter(Zip._starts(b, e)) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (e.isDir and 0x41ED0010 or 0x81A40000), + }) + return true, nil +end + +-- finish(opts?) -> the archive | nil, Err +function Writer.finish(self, opts) +local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in __iter(self.files) do + total =total+ (30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment +) end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in __iter(self.files) do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = f.utf8 and 0x800 or 0 + w:u32le(SIG_LOCAL) + w:u16le(big and 45 or 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(big and 0xFFFFFFFF or f.dataLength) + w:u32le(big and 0xFFFFFFFF or f.size) + w:u16le(#f.name) + w:u16le(big and 20 or 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in __iter(self.files) do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (bigSize and 16 or 0) + (bigOff and 8 or 0) + local version = (bigSize or bigOff )and 45 or 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(f.utf8 and 0x800 or 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(bigSize and 0xFFFFFFFF or f.dataLength) + w:u32le(bigSize and 0xFFFFFFFF or f.size) + w:u16le(#f.name) + w:u16le((extra > 0 and((extra + 4 ))or(0))) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(bigOff and 0xFFFFFFFF or off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(z64 and 0xFFFF or count) + w:u16le(z64 and 0xFFFF or count) + w:u32le(z64 and 0xFFFFFFFF or cdSize) + w:u32le(z64 and 0xFFFFFFFF or cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip +end +__FILES["core/Adler32"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- core/Adler32: Adler-32 (RFC 1950, the zlib checksum). Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Adler32.of(buf, offset?, length?, adler?) -> u32 (starts at 1; pass a previous result to continue it) +-- Adler32.string(s, adler?) -> u32 +local readu8 = buffer.readu8 + +-- Adler-32 of buf[off, off + len), continuing adler (default 1) +local function adler32(buf, off, len, adler) +local a0 = adler or 1 + local a, b = a0 % 65536, math.floor(a0 / 65536 +) local i, e = off, off + len + while i < e do + -- 5552 is zlib's NMAX: the largest n with 255 n (n + 1) / 2 + (n + 1) (BASE - 1) < 2^32. Doubles hold far + -- more, but keeping the sums small keeps them exact and cheap. + local stop = math.min(e, i + 5552) + while i < stop do + a =a+ readu8(buf, i) + b =b+ a + i =i+ 1 + end + a =a% 65521 + b =b% 65521 + end + return b * 65536 + a +end + +-- clamp (offset, length) to the buffer +local function range(buf, offset, length) +local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Adler32 = {} + +function Adler32.of(buf, offset, length, adler) +local o, l = range(buf, offset, length) + return adler32(buf, o, l, adler) +end + +function Adler32.string(s, adler) +return adler32(buffer.fromstring(s), 0, #s, adler) +end + +Adler32.raw = adler32 + +return Adler32 +end +__FILES["core/Base64"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +-- core/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, and data: URIs. +-- Used by tiled map data, glTF / SVG / CSS data: URIs, plist <data>, YAML !!binary, FBX, the Brotli static tables. +-- decode skips whitespace, accepts missing padding and both alphabets; any other character, data after padding or a +-- lone last character is an error. Never throws. +-- +-- local s = Base64.encode(buf) -- buffer | string -> string ("" for empty input) +-- local s2 = Base64.encode(buf, { url = true, pad = false, wrap = 76 }, offset, length) +-- local b, err = Base64.decode(s) -- string | buffer -> buffer | nil, "message" +-- local b2, mime = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, msg +-- local uri = Base64.dataUri(buf, "image/png") +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 __iter({ 9, 10, 11, 12, 13, 32 }) do + buffer.writeu8(DEC, c, 64) +end +buffer.writeu8(DEC, string.byte("="), 65) + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- encode(data, opts?, offset?, length?) -> base64 text of data[offset, offset + length) +function Base64.encode(data, opts, offset, length) +local buf= (type(data) == "string" and{(buffer.fromstring(data) )}or{data +})[1] local total = buffer.len(buf) + local o = math.clamp(offset or 0, 0, total) + local n = math.clamp(length or (total - o), 0, total - o) + local enc = (opts and opts.url and{ENC_URL }or{ENC +})[1] local pad = not (opts and opts.pad == false) + local wrap = (opts and opts.wrap and opts.wrap >= 4 and{(math.floor(opts.wrap / 4 ))}or{0 -- groups per line +})[1] local full = math.floor(n / 3 +) local rest = n - full * 3 + local textLen = full * 4 + (rest == 0 and 0 or(pad and 4 or rest + 1)) + local groups = full + (rest > 0 and 1 or 0) + local breaks = (wrap > 0 and groups > 0 and{(math.floor((groups - 1) / wrap ))}or{0 +})[1] local out = buffer.create(textLen + breaks) + local p = 0 + local col = 0 + for i = 0, full - 1 do + if wrap > 0 then + if col == wrap then + writeu8(out, p, 10) + p =p+ 1 + col = 0 + end + col =col+ 1 + end + 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, math.floor(v / 262144))) + writeu8(out, p + 1, readu8(enc, (math.floor(v / 4096)) % 64)) + writeu8(out, p + 2, readu8(enc, (math.floor(v / 64)) % 64)) + writeu8(out, p + 3, readu8(enc, v % 64)) + p =p+ 4 + end + if rest > 0 then + if wrap > 0 and col == wrap then + writeu8(out, p, 10) + p =p+ 1 + end + local q = o + full * 3 + local v = readu8(buf, q) * 65536 + ((rest == 2 and{(readu8(buf, q + 1) * 256 )}or{0})[1]) + writeu8(out, p, readu8(enc, math.floor(v / 262144))) + writeu8(out, p + 1, readu8(enc, (math.floor(v / 4096)) % 64)) + if rest == 2 then + writeu8(out, p + 2, readu8(enc, (math.floor(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) +local src= (type(s) == "string" and{(buffer.fromstring(s) )}or{s +})[1] local n = buffer.len(src) + local out = buffer.create((math.floor(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 =bits+ 6 + if bits >= 8 then + bits =bits- 8 + local scale = 2 ^ bits + local byte = math.floor(acc / scale +) writeu8(out, p, byte % 256) + p =p+ 1 + acc =acc- byte * scale + 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) +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) +return string.char((tonumber(h, 16) )) + end) + return buffer.fromstring(decoded), mime +end + +-- dataUri(buf, mime?) -> "data:<mime>;base64,..." +function Base64.dataUri(buf, mime) +return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) +end + +return Base64 +end +__FILES["core/Bits"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- core/Bits: bit readers and writers, LSB-first (DEFLATE, GIF LZW, VP8L, ...) and MSB-first (JPEG entropy data +-- without the 0xFF00 unstuffing, MPEG, H.264, FLAC, ...). Up to 32 bits per read / write. +-- +-- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. +-- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see +-- codecs/compress/Deflate/Inflate) and uses these for headers. +-- +-- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). +-- +-- local br = Bits.lsbReader(buf, offset?, length?) -- or Bits.msbReader +-- local v = br:read(5); if br.err then return nil, br.err end +-- local bw = Bits.msbWriter(); bw:write(0b101, 3); local out = bw:finish() +-- local w = { buf = buffer.create(n), pos = 0, acc = 0, cnt = 0 }; Bits.msbPut(w, v, nbits) -- encoders' fast path +-- (a plain record the caller sizes / grows itself: MP3, MP2 and FLAC frames) +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +local readu8, blen = buffer.readu8, buffer.len +local floor = math.floor + +-- 2^n for n = 0..32 +local POW = table.create(33, 0) +for i = 0, 32 do + POW[i + 1] = 2 ^ i +end + +local Bits = {} +Bits.POW = POW +-- ------------------------------------------------------------------------------------------------ readers + + + + + + + + + + + + + + + + +local function overrun(self) + if not self.err then + self.err = Err.new(Err.TRUNCATED, "bit stream ends early", self.limit) + end +end + +-- LSB-first: the first bit of the stream is bit 0 of the first byte; a field's first bit is its least significant +local Lsb = {} +Lsb.__index = Lsb + +local function lsbFill(self, n) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc =acc+ readu8(self.buf, pos) * POW[cnt + 1] + pos =pos+ 1 + else + overrun(self) + end + cnt =cnt+ 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +function Lsb.read(self, n) +if n > 24 then + local lo = Lsb.read(self, 16) + return lo + Lsb.read(self, n - 16) * 65536 + end + if self.cnt < n then + lsbFill(self, n) + end + local m = POW[n + 1] + local v = self.acc % m + self.acc = (self.acc - v) / m + self.cnt =self.cnt- n + return v +end +function Lsb.peek(self, n) +if self.cnt < n then + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do -- no error for peeking past the end: the bits are zeros + if pos < self.limit then + acc =acc+ readu8(self.buf, pos) * POW[cnt + 1] + pos =pos+ 1 + end + cnt =cnt+ 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return acc % POW[n + 1] + end + return self.acc % POW[n + 1] +end +function Lsb.skip(self, n) + while n > 24 do + Lsb.read(self, 24) + n =n- 24 + end + Lsb.read(self, n) +end +-- align(): drop the bits up to the next byte boundary +function Lsb.align(self) + local k = self.cnt % 8 + if k > 0 then + Lsb.read(self, k) + end +end +-- bytePos(): the offset of the first byte not yet (even partly) consumed +function Lsb.bytePos(self) +return self.pos - floor(self.cnt / 8) +end +function Lsb.bitsLeft(self) +return (self.limit - self.pos) * 8 + self.cnt +end + +-- MSB-first: the first bit of the stream is bit 7 of the first byte; a field's first bit is its most significant +local Msb = {} +Msb.__index = Msb + +local function msbFill(self, n) + local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos =pos+ 1 + else + acc =acc* 256 + overrun(self) + end + cnt =cnt+ 8 + end + self.acc, self.cnt, self.pos = acc, cnt, pos +end + +function Msb.read(self, n) +if n > 24 then + local hi = Msb.read(self, n - 16) + return hi * 65536 + Msb.read(self, 16) + end + if self.cnt < n then + msbFill(self, n) + end + local sh = POW[self.cnt - n + 1] + local v = floor(self.acc / sh) + self.acc =self.acc- v * sh + self.cnt =self.cnt- n + return v +end +function Msb.peek(self, n) +local acc, cnt, pos = self.acc, self.cnt, self.pos + while cnt < n do + if pos < self.limit then + acc = acc * 256 + readu8(self.buf, pos) + pos =pos+ 1 + else + acc =acc* 256 + end + cnt =cnt+ 8 + end + -- keep the loaded bytes only when they are all real (zero padding past the end is not data) + if (pos - self.pos) * 8 == cnt - self.cnt then + self.acc, self.cnt, self.pos = acc, cnt, pos + end + return floor(acc / POW[cnt - n + 1]) +end +function Msb.skip(self, n) + while n > 24 do + Msb.read(self, 24) + n =n- 24 + end + Msb.read(self, n) +end +function Msb.align(self) + local k = self.cnt % 8 + if k > 0 then + Msb.read(self, k) + end +end +Msb.bytePos = Lsb.bytePos +Msb.bitsLeft = Lsb.bitsLeft + +local function reader(meta, buf, offset, length) +local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return (setmetatable({ buf = buf, pos = o, limit = o + l, acc = 0, cnt = 0, err = nil }, meta) ) +end + +-- lsbReader(buf, offset?, length?) / msbReader(buf, offset?, length?) -> BitReader +function Bits.lsbReader(buf, offset, length) +return reader(Lsb, buf, offset, length) +end +function Bits.msbReader(buf, offset, length) +return reader(Msb, buf, offset, length) +end +-- ------------------------------------------------------------------------------------------------ writers + + + + + + + + + + +local LsbW = {} +LsbW.__index = LsbW +function LsbW.write(self, v, n) + if n > 24 then + local lo = v % 65536 + LsbW.write(self, lo, 16) + LsbW.write(self, (v - lo) / 65536, n - 16) + return + end + local acc = self.acc + (v % POW[n + 1]) * POW[self.cnt + 1] + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local byte = acc % 256 + out:u8(byte) + acc = (acc - byte) / 256 + cnt =cnt- 8 + end + self.acc, self.cnt = acc, cnt +end +-- align(): pad with zero bits to a byte boundary +function LsbW.align(self) + if self.cnt > 0 then + self.out:u8(self.acc) + self.acc, self.cnt = 0, 0 + end +end +function LsbW.finish(self) +LsbW.align(self) + return self.out:finish() +end + +local MsbW = {} +MsbW.__index = MsbW +function MsbW.write(self, v, n) + if n > 24 then + local lo = v % 65536 + MsbW.write(self, (v - lo) / 65536, n - 16) + MsbW.write(self, lo, 16) + return + end + local acc = self.acc * POW[n + 1] + (v % POW[n + 1]) + local cnt = self.cnt + n + local out = self.out + while cnt >= 8 do + local sh = POW[cnt - 8 + 1] + local byte = floor(acc / sh) + out:u8(byte) + acc =acc- byte * sh + cnt =cnt- 8 + end + self.acc, self.cnt = acc, cnt +end +function MsbW.align(self) + if self.cnt > 0 then + self.out:u8(self.acc * POW[8 - self.cnt + 1]) + self.acc, self.cnt = 0, 0 + end +end +function MsbW.finish(self) +MsbW.align(self) + return self.out:finish() +end +-- msbPut(w, v, n): append the low n bits (n <= 32) of the non-negative integer v to the record w = { buf, pos, acc, +-- cnt }, MSB first. No growth: the caller keeps buf large enough (whole bytes go to buf[pos]; acc holds cnt < 8 bits). + + +function Bits.msbPut(w, v, n) + 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 =cnt- 8 + local m = POW[cnt + 1] + local byte = floor(acc / m) + buffer.writeu8(b, p, byte) + p =p+ 1 + acc =acc- byte * m + end + w.acc, w.cnt, w.pos = acc, cnt, p +end + +-- lsbWriter(capacity?) / msbWriter(capacity?) -> BitWriter +function Bits.lsbWriter(capacity) +return (setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, LsbW) ) +end +function Bits.msbWriter(capacity) +return (setmetatable({ out = Bytes.writer(capacity), acc = 0, cnt = 0 }, MsbW) ) +end + +return Bits +end +__FILES["core/Bytes"] = function() +local __compat = __compat local buffer, bit32, typeof, type = __compat.buffer, __compat.bit32, __compat.typeof, __compat.type --!strict +--!native +-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a +-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers. +-- +-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor +-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads: +-- +-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length) +-- local magic, w, h = r:string(4), r:u32be(), r:u32be() +-- if r.err then return nil, r.err end +-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end +-- +-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity) +-- w:string("abcd"); w:u32be(width); local out = w:finish() +-- +-- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking +local Err = __include("core/Err") + +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring +local writeu8, writeu16, writeu32, writef32, writef64, writestring = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32, buffer.writef64, buffer.writestring +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len +local byteswap = bit32.byteswap + +local TWO32 = 4294967296 +local scratch = bcreate(8) -- reinterpret casts for big-endian floats + +local Bytes = {} + +-- ------------------------------------------------------------------------------------------------ Reader +local Reader = {} +Reader.__index = Reader + +-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer + + + + + + + + + + + +function Bytes.reader(buf, offset, length) +local n = blen(buf) + local o = math.clamp(offset or 0, 0, n) + local l = math.clamp(length or (n - o), 0, n - o) + return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil }, Reader) +end + +-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)` +function Reader.fail(self, code, message) +if not self.err then + self.err = Err.new(code, message, self.pos) + end + return nil, self.err +end + +-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end +function Reader.need(self, n) +if self.pos + n <= self.limit and n >= 0 then + return true + end + if not self.err then + self.err = Err.new(Err.TRUNCATED, string.format("need %d bytes, %d left", n, self.limit - self.pos), self.pos) + end + self.pos = self.limit + return false +end + +function Reader.tell(self) +return self.pos - self.base +end +function Reader.size(self) +return self.limit - self.base +end +function Reader.remaining(self) +return self.limit - self.pos +end +function Reader.eof(self) +return self.pos >= self.limit +end + +-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED +function Reader.seek(self, offset) +if offset < 0 or self.base + offset > self.limit then + self.pos = self.limit + if not self.err then + self.err = Err.new(Err.TRUNCATED, "seek to " .. offset .. " past the end", self.base + offset) + end + return false + end + self.pos = self.base + offset + return true +end + +function Reader.skip(self, n) +if self:need(n) then + self.pos =self.pos+ n + return true + end + return false +end + +-- align(n): skip to the next multiple of n (relative to the reader's start) +function Reader.align(self, n) +local r = (self.pos - self.base) % n + if r == 0 then + return true + end + return self:skip(n - r) +end + +-- integers +function Reader.u8(self) +local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readu8(self.buf, p) +end +function Reader.i8(self) +local p = self.pos + if p + 1 > self.limit then + self:need(1) + return 0 + end + self.pos = p + 1 + return readi8(self.buf, p) +end +function Reader.u16le(self) +local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu16(self.buf, p) +end +function Reader.u16be(self) +local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readu8(self.buf, p) * 256 + readu8(self.buf, p + 1) +end +function Reader.i16le(self) +local p = self.pos + if p + 2 > self.limit then + self:need(2) + return 0 + end + self.pos = p + 2 + return readi16(self.buf, p) +end +function Reader.i16be(self) +local v = self:u16be() + return (v >= 32768 and((v - 65536 ))or(v +))end +function Reader.u24le(self) +local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu16(self.buf, p) + readu8(self.buf, p + 2) * 65536 +end +function Reader.u24be(self) +local p = self.pos + if p + 3 > self.limit then + self:need(3) + return 0 + end + self.pos = p + 3 + return readu8(self.buf, p) * 65536 + readu8(self.buf, p + 1) * 256 + readu8(self.buf, p + 2) +end +function Reader.u32le(self) +local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readu32(self.buf, p) +end +function Reader.u32be(self) +local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return byteswap(readu32(self.buf, p)) +end +function Reader.i32le(self) +local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readi32(self.buf, p) +end +function Reader.i32be(self) +local v = self:u32be() + return (v >= 2147483648 and((v - TWO32 ))or(v +))end +-- 64-bit integers as doubles (exact below 2^53) +function Reader.u64le(self) +local lo = self:u32le() + return lo + self:u32le() * TWO32 +end +function Reader.u64be(self) +local hi = self:u32be() + return hi * TWO32 + self:u32be() +end +function Reader.i64le(self) +local lo = self:u32le() + return lo + self:i32le() * TWO32 +end +function Reader.i64be(self) +local hi = self:i32be() + return hi * TWO32 + self:u32be() +end + +-- floats +local function half(h) +local s = h >= 32768 and-1 or 1 + local e = bit32.band(bit32.rshift(h, 10), 31) + local m = bit32.band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return (m == 0 and((s * math.huge ))or((0 / 0 +))) end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end +Bytes.half = half + +function Reader.f16le(self) +return half(self:u16le()) +end +function Reader.f16be(self) +return half(self:u16be()) +end +function Reader.f32le(self) +local p = self.pos + if p + 4 > self.limit then + self:need(4) + return 0 + end + self.pos = p + 4 + return readf32(self.buf, p) +end +function Reader.f32be(self) +local v = self:u32be() + writeu32(scratch, 0, v) + return readf32(scratch, 0) +end +function Reader.f64le(self) +local p = self.pos + if p + 8 > self.limit then + self:need(8) + return 0 + end + self.pos = p + 8 + return readf64(self.buf, p) +end +function Reader.f64be(self) +local hi = self:u32be() + local lo = self:u32be() + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end + +-- strings +function Reader.string(self, n) +local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return "" + end + self.pos = p + n + return readstring(self.buf, p, n) +end + +-- fixed(n): an n-byte field, cut at the first NUL +function Reader.fixed(self, n) +local s = self:string(n) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1]end + +-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED +function Reader.cstring(self, max) +local p = self.pos + local e = (max and{(math.min(self.limit, p + max) )}or{self.limit +})[1] local q = p + local buf = self.buf + while q < e and readu8(buf, q) ~= 0 do + q =q+ 1 + end + if q >= e then + self.pos = e + self:need(1) + return readstring(buf, p, e - p) + end + self.pos = q + 1 + return readstring(buf, p, q - p) +end + +-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error +function Reader.match(self, s) +local p, n = self.pos, #s + if p + n > self.limit or readstring(self.buf, p, n) ~= s then + return false + end + self.pos = p + n + return true +end + +-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error +function Reader.peek(self, n, at) +local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return "" + end + return readstring(self.buf, p, math.min(n, self.limit - p)) +end + +-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end +function Reader.peekU8(self, at) +local p = self.pos + (at or 0) + if p < self.base or p >= self.limit then + return -1 + end + return readu8(self.buf, p) +end + +-- bytes(n) -> a new buffer with a copy of the next n bytes +function Reader.bytes(self, n) +local p = self.pos + if n < 0 or p + n > self.limit then + self:need(n) + return bcreate(0) + end + local b = bcreate(n) + bcopy(b, 0, self.buf, p, n) + self.pos = p + n + return b +end + +-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is +-- left, and the parent records TRUNCATED. +function Reader.slice(self, n) +local p = self.pos + local l = math.max(0, math.min(n, self.limit - p)) + if l < n then + self:need(n) + else + self.pos = p + n + end + return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil }, Reader) +end + +-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without +-- moving the cursor +function Reader.sub(self, offset, length) +local o = math.clamp(self.base + offset, self.base, self.limit) + local l = math.clamp(length or (self.limit - o), 0, self.limit - o) + return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil }, Reader) +end + +-- ------------------------------------------------------------------------------------------------ Writer +local Writer = {} +Writer.__index = Writer + +-- writer(capacity?) -> Writer + + + + + + + + +function Bytes.writer(capacity) +return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer) +end + +-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf) +function Writer.reserve(self, n) +local p = self.pos + local cap = blen(self.buf) + if p + n > cap then + local nb = bcreate(math.max(cap * 2, p + n)) + bcopy(nb, 0, self.buf, 0, p) + self.buf = nb + end + return p +end + +function Writer.tell(self) +return self.pos +end + +function Writer.u8(self, v) + local p = self:reserve(1) + writeu8(self.buf, p, v) + self.pos = p + 1 +end +function Writer.u16le(self, v) + local p = self:reserve(2) + writeu16(self.buf, p, v) + self.pos = p + 2 +end +function Writer.u16be(self, v) + local p = self:reserve(2) + writeu8(self.buf, p, bit32.rshift(v, 8)) + writeu8(self.buf, p + 1, v) + self.pos = p + 2 +end +function Writer.u24le(self, v) + local p = self:reserve(3) + writeu16(self.buf, p, v) + writeu8(self.buf, p + 2, bit32.rshift(v, 16)) + self.pos = p + 3 +end +function Writer.u24be(self, v) + local p = self:reserve(3) + writeu8(self.buf, p, bit32.rshift(v, 16)) + writeu8(self.buf, p + 1, bit32.rshift(v, 8)) + writeu8(self.buf, p + 2, v) + self.pos = p + 3 +end +function Writer.u32le(self, v) + local p = self:reserve(4) + writeu32(self.buf, p, v) + self.pos = p + 4 +end +function Writer.u32be(self, v) + local p = self:reserve(4) + writeu32(self.buf, p, byteswap(v % TWO32)) + self.pos = p + 4 +end +Writer.i8 = Writer.u8 +Writer.i16le = Writer.u16le +Writer.i16be = Writer.u16be +Writer.i32le = Writer.u32le +Writer.i32be = Writer.u32be +function Writer.u64le(self, v) + self:u32le(v % TWO32) + self:u32le(math.floor(v / TWO32) % TWO32) +end +function Writer.u64be(self, v) + self:u32be(math.floor(v / TWO32) % TWO32) + self:u32be(v % TWO32) +end +Writer.i64le = Writer.u64le +Writer.i64be = Writer.u64be +function Writer.f32le(self, v) + local p = self:reserve(4) + writef32(self.buf, p, v) + self.pos = p + 4 +end +function Writer.f32be(self, v) + writef32(scratch, 0, v) + self:u32be(readu32(scratch, 0)) +end +function Writer.f64le(self, v) + local p = self:reserve(8) + writef64(self.buf, p, v) + self.pos = p + 8 +end +function Writer.f64be(self, v) + writef64(scratch, 0, v) + self:u32be(readu32(scratch, 4)) + self:u32be(readu32(scratch, 0)) +end + +function Writer.string(self, s) + local n = #s + local p = self:reserve(n) + writestring(self.buf, p, s) + self.pos = p + n +end +-- cstring(s): s and a NUL +function Writer.cstring(self, s) + self:string(s) + self:u8(0) +end +-- bytes(b, offset?, length?): copy a buffer range +function Writer.bytes(self, b, offset, length) + local o = offset or 0 + local n = length or (blen(b) - o) + local p = self:reserve(n) + bcopy(self.buf, p, b, o, n) + self.pos = p + n +end +function Writer.fill(self, v, n) + local p = self:reserve(n) + bfill(self.buf, p, v, n) + self.pos = p + n +end + +-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos +function Writer.setU32le(self, at, v) + writeu32(self.buf, at, v) +end +function Writer.setU32be(self, at, v) + writeu32(self.buf, at, byteswap(v % TWO32)) +end +function Writer.setU16le(self, at, v) + writeu16(self.buf, at, v) +end +function Writer.setU8(self, at, v) + writeu8(self.buf, at, v) +end + +-- finish() -> a buffer of exactly the written bytes (the writer can keep going) +function Writer.finish(self) +local b = bcreate(self.pos) + bcopy(b, 0, self.buf, 0, self.pos) + return b +end + +Bytes.Reader = Reader +Bytes.Writer = Writer + +-- ------------------------------------------------------------------------------------------------ arguments +-- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else +function Bytes.toBuffer(v) +if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1]end + +-- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string, +-- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end) +function Bytes.span(what, input, offset, length) +local b = Bytes.toBuffer(input) + if not b then + return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(input)) + end + local n = buffer.len(b) + local o = offset or 0 + local l = length or (n - ((type(o) == "number" and{o }or{0})[1])) + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 or type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) + end + if o + l > n then + l = n - o + end + return b, o, l, nil +end + +return Bytes +end +__FILES["core/Crc16"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code. +-- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0, +-- MacBinary II / III headers) +-- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC) +-- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer. +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift +local readu8 = buffer.readu8 + +local MSB = table.create(256, 0) +local ARC = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 8) + for _ = 1, 8 do + c = (band(c, 0x8000) ~= 0 and{(bxor(band(lshift(c, 1), 0xFFFF), 0x1021) )}or{(band(lshift(c, 1), 0xFFFF) +)})[1] end + MSB[n + 1] = c + local r = n + for _ = 1, 8 do + r = (band(r, 1) ~= 0 and{(bxor(rshift(r, 1), 0xA001) )}or{(rshift(r, 1) +)})[1] end + ARC[n + 1] = r +end + +local Crc16 = {} + +local function clamp(buf, off, len) +local n = buffer.len(buf) + local o = math.clamp(math.floor(off), 0, n) + return o, math.clamp(math.floor(len), 0, n - o) +end + +function Crc16.ccitt(buf, off, len, crc) +local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1]) + end + return c +end + +function Crc16.arc(buf, off, len, crc) +local o, l = clamp(buf, off, len) + local c = crc or 0 + for i = o, o + l - 1 do + c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1]) + end + return c +end + +return Crc16 +end +__FILES["core/Crc32"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- core/Crc32: CRC-32 (IEEE 802.3, the zlib / gzip / zip / PNG polynomial 0xEDB88320, reflected), slice-by-8. +-- Absorbed from deflate-luau src/Deflate/Checksum.luau (same author; +-- no third-party code). Never throws: the range is clamped. +-- +-- Crc32.of(buf, offset?, length?, crc?) -> u32 (pass a previous result as crc to continue it) +-- Crc32.string(s, crc?) -> u32 +-- Crc32.msb(buf, offset, length, init?) -> u32 the MSB-first (unreflected) 0x04C11DB7 CRC, raw register: no +-- inversions (Ogg: init 0; MPEG-2 sections / bzip2: 0xFFFFFFFF) +-- Crc32.MSB_TABLE its 1-based byte table, for codecs that inline it (bzip2) +local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T0, T1, T2, T3 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +local T4, T5, T6, T7 = table.create(256, 0), table.create(256, 0), table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local c = n + for _ = 1, 8 do + if band(c, 1) ~= 0 then + c = bxor(0xEDB88320, rshift(c, 1)) + else + c = rshift(c, 1) + end + end + T0[n + 1] = c +end +for n = 0, 255 do + local c = T0[n + 1] + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T1[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T2[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T3[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T4[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T5[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T6[n + 1] = c + c = bxor(T0[band(c, 255) + 1], rshift(c, 8)) + T7[n + 1] = c +end + +-- CRC-32 of buf[off, off + len), continuing crc (default 0 = a new CRC). Values are finished CRCs (the inversion +-- happens inside), so crc(b, crc(a)) == the CRC of a .. b. +local function crc32(buf, off, len, crc) +local c = bxor(crc or 0, 0xFFFFFFFF) + local i, e = off, off + len + local e8 = e - 8 + while i <= e8 do + c = bxor(c, readu32(buf, i)) + local d = readu32(buf, i + 4) + c = bxor( + T7[band(c, 255) + 1], + T6[band(rshift(c, 8), 255) + 1], + T5[band(rshift(c, 16), 255) + 1], + T4[rshift(c, 24) + 1], + T3[band(d, 255) + 1], + T2[band(rshift(d, 8), 255) + 1], + T1[band(rshift(d, 16), 255) + 1], + T0[rshift(d, 24) + 1] + ) + i =i+ 8 + end + local e4 = e - 4 + while i <= e4 do + c = bxor(c, readu32(buf, i)) + c = bxor(T3[band(c, 255) + 1], T2[band(rshift(c, 8), 255) + 1], T1[band(rshift(c, 16), 255) + 1], T0[rshift(c, 24) + 1]) + i =i+ 4 + end + while i < e do + c = bxor(T0[band(bxor(c, readu8(buf, i)), 255) + 1], rshift(c, 8)) + i =i+ 1 + end + return bxor(c, 0xFFFFFFFF) +end + +-- clamp (offset, length) to the buffer +local function range(buf, offset, length) +local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + return o, math.clamp(length or (n - o), 0, n - o) +end + +local Crc32 = {} + +function Crc32.of(buf, offset, length, crc) +local o, l = range(buf, offset, length) + return crc32(buf, o, l, crc) +end + +function Crc32.string(s, crc) +return crc32(buffer.fromstring(s), 0, #s, crc) +end + +-- raw(buf, off, len, crc?): no clamping, for callers that already checked the range (hot paths) +Crc32.raw = crc32 + +-- the MSB-first CRC-32 (polynomial 0x04C11DB7, not reflected): Ogg pages, MPEG-2 PSI sections, bzip2 blocks +local MSB = table.create(256, 0) +for n = 0, 255 do + local c = lshift(n, 24) + for _ = 1, 8 do + c = (band(c, 0x80000000) ~= 0 and{(bxor(lshift(c, 1), 0x04C11DB7) )}or{(lshift(c, 1) +)})[1] end + MSB[n + 1] = c +end +Crc32.MSB_TABLE = MSB + +-- msb(buf, off, len, init?) -> the register after buf[off, off + len) (no inversions; the caller checked the range) +function Crc32.msb(buf, off, len, init) +local c = init or 0 + for i = off, off + len - 1 do + c = bxor(lshift(c, 8), MSB[bxor(rshift(c, 24), readu8(buf, i)) + 1]) + end + return c +end + +return Crc32 +end +__FILES["core/Err"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data). +-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7". +-- Never throws: --!native modules may require it. +-- +-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos) +-- if err.code == Err.UNSUPPORTED then ... end +local Err = {} + +-- codes +Err.TRUNCATED = "TRUNCATED" -- the data ends early +Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field) +Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch +Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder +Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name +Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...) +Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option) +Err.IO = "IO" -- reading or writing a file failed, or the host has no file system + + + + + + + + +local Meta = {} +Meta.__tostring = function(e) +local s = (e.format and((e.format .. ": " .. e.code ))or(e.code +)) if e.offset then + s =s.. string.format(" at 0x%x", e.offset) + end + return s .. ": " .. e.message +end + +-- new(code, message, offset?) -> Err +function Err.new(code, message, offset) +return (setmetatable({ code = code, message = message, offset = offset, format = nil }, Meta) ) +end + +-- the kinds a private submodule may report: Err codes in either case ("truncated", "CORRUPT", ...) +local KIND= {} +for _, c in __iter({ "TRUNCATED", "CORRUPT", "CHECKSUM", "UNSUPPORTED", "LIMIT", "ARG", "IO", "UNKNOWN_FORMAT" }) do + KIND[c] = c + KIND[string.lower(c)] = c +end + +-- from(message, offset?, kind?) -> Err: the error plumbing between a private submodule (which returns +-- nil / false, "message"[, kind]) and the contract. kind names the code ("truncated", "LIMIT", ...); without it the +-- message decides: a "<code>: ..." prefix ("limit: ...", "unsupported: ...") names the code and is dropped; +-- "...truncated..." / "...past the end" / "...runs past..." -> TRUNCATED; "unsupported..." -> UNSUPPORTED; +-- "checksum..." -> CHECKSUM; anything else CORRUPT. An Err passes +-- through unchanged. +function Err.from(message, offset, kind) +if Err.is(message) then + return message + end + local msg = message == nil and"failed" or tostring(message) + local code= kind and KIND[kind] + if not code then + local head, rest = string.match(msg, "^(%a+):%s*(.*)$") + if head and KIND[head] then + code, msg = KIND[head], rest +elseif string.find(msg, "truncated", 1, true) or string.find(msg, "past the end", 1, true) or string.find(msg, "runs past", 1, true) then + code = Err.TRUNCATED + elseif string.find(msg, "^unsupported") then + code = Err.UNSUPPORTED + elseif string.find(msg, "^checksum") then + code = Err.CHECKSUM + else + code = Err.CORRUPT + end + end + return Err.new(code , msg, offset) +end + +-- is(v) -> true when v is an Err +function Err.is(v) +return type(v) == "table" and getmetatable(v) == Meta +end + +-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to +-- tag errors with the format name. +function Err.wrap(e, format) +if not Err.is(e) then + e = Err.new(Err.CORRUPT, tostring(e)) + end + if e.format == nil then + e.format = format + end + return e +end + +return table.freeze(Err) +end +__FILES["core/Input"] = function() +local __compat = __compat local buffer, typeof, type = __compat.buffer, __compat.typeof, __compat.type --!strict +-- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files +-- through the host adapter the API passes in (core never requires host itself). +-- +-- local buf, err, name = Input.resolve(src, opts, host) +-- +-- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path +-- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). +-- name: the path (for the extension fallback) or opts.name. Never throws. +local Err = __include("core/Err") + +local Input = {} + +-- looksLikePath(s) -> true for short strings without NUL / newline bytes + + + + + + +function Input.looksLikePath(s) +return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") +end + +-- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err +function Input.resolve(src, opts, host) +local o = opts or {} + local t = type(src) + if t == "buffer" then + return src, nil, o.name + elseif t == "string" then + local isPath = false + if o.path == true then + isPath = true + elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then + isPath = host.exists(src) + end + if isPath then + if not host then + return nil, Err.new(Err.IO, "no host to read " .. src), nil + end + local b, err = host.readFile(src) + if not b then + return nil, err, nil + end + return b, nil, src + end + return buffer.fromstring(src), nil, o.name + end + return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil +end + +-- extension(name) -> the lower-case extension without the dot ("png"), or nil +function Input.extension(name) +if not name then + return nil + end + local ext = string.match(name, "%.([%w_]+)$") + return (ext and{(string.lower(ext) )}or{nil +})[1]end + +-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive +-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) +function Input.sibling(opts, uri) +if type(opts) ~= "table" then + return nil + end + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, got = pcall(opts.resolve, uri) + v = (ok and{got }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1]end + +return Input +end +__FILES["core/Md5"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- core/Md5: MD5 (RFC 1321), incremental. Written from the RFC. Used by the FLAC encoder (STREAMINFO's MD5 of the PCM); +-- not for security. +-- +-- local h = Md5.new() +-- h:update(buf, offset?, length?) -- any number of times +-- local digest = h:digest() -- 16-byte string (the state is finished; make a new one to hash again) +-- Md5.hex(digest) / Md5.of(buf) -> hex string +-- Never throws (ranges are clamped to the buffer). +local Md5 = {} + +local band, bor, bxor, bnot, lrotate = bit32.band, bit32.bor, bit32.bxor, bit32.bnot, bit32.lrotate +local readu32, writeu32, writeu8 = buffer.readu32, buffer.writeu32, buffer.writeu8 + +local K = table.create(64, 0) +for i = 0, 63 do + K[i + 1] = math.floor(math.abs(math.sin(i + 1)) * 4294967296) % 4294967296 +end +local S = { + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +} +local G = table.create(64, 0) +for i = 0, 63 do + if i < 16 then + G[i + 1] = i + elseif i < 32 then + G[i + 1] = (5 * i + 1) % 16 + elseif i < 48 then + G[i + 1] = (3 * i + 5) % 16 + else + G[i + 1] = (7 * i) % 16 + end +end + + + + + + + + + + + + + +local M = table.create(16, 0) + +local function compress(st, blk, o) + for i = 0, 15 do + M[i + 1] = readu32(blk, o + i * 4) + end + local a, b, c, d = st.a, st.b, st.c, st.d + for i = 0, 63 do + local f + if i < 16 then + f = bor(band(b, c), band(bnot(b), d)) + elseif i < 32 then + f = bor(band(d, b), band(bnot(d), c)) + elseif i < 48 then + f = bxor(b, c, d) + else + f = bxor(c, bor(b, bnot(d))) + end + local tmp = d + d = c + c = b + b = (b + lrotate((a + f + K[i + 1] + M[G[i + 1] + 1]) % 4294967296, S[i + 1])) % 4294967296 + a = tmp + end + st.a = (st.a + a) % 4294967296 + st.b = (st.b + b) % 4294967296 + st.c = (st.c + c) % 4294967296 + st.d = (st.d + d) % 4294967296 +end + +local function update(self, buf, offset, length) + local n = buffer.len(buf) + local o = math.clamp(offset or 0, 0, n) + local len = math.clamp(length or (n - o), 0, n - o) + self.total =self.total+ len + local blk = self.block + if self.fill > 0 then + local take = math.min(64 - self.fill, len) + buffer.copy(blk, self.fill, buf, o, take) + self.fill =self.fill+ take + o =o+ take + len =len- take + if self.fill == 64 then + compress(self, blk, 0) + self.fill = 0 + end + end + while len >= 64 do + compress(self, buf, o) + o =o+ 64 + len =len- 64 + end + if len > 0 then + buffer.copy(blk, 0, buf, o, len) + self.fill = len + end +end + +local function digest(self) +local bits = self.total * 8 + local blk = self.block + local f = self.fill + writeu8(blk, f, 0x80) + f =f+ 1 + if f > 56 then + buffer.fill(blk, f, 0, 64 - f) + compress(self, blk, 0) + f = 0 + end + buffer.fill(blk, f, 0, 56 - f) + writeu32(blk, 56, bits % 4294967296) + writeu32(blk, 60, math.floor(bits / 4294967296) % 4294967296) + compress(self, blk, 0) + self.fill = 0 + local out = buffer.create(16) + writeu32(out, 0, self.a) + writeu32(out, 4, self.b) + writeu32(out, 8, self.c) + writeu32(out, 12, self.d) + return buffer.tostring(out) +end + +function Md5.new() +return { + a = 0x67452301, + b = 0xEFCDAB89, + c = 0x98BADCFE, + d = 0x10325476, + block = buffer.create(64), + fill = 0, + total = 0, + update = update, + digest = digest, + } +end + +-- hex(digest) -> 32 lower-case hex digits +function Md5.hex(d) +local out = table.create(#d) + for i = 1, #d do + out[i] = string.format("%02x", string.byte(d, i)) + end + return table.concat(out) +end + +-- of(buf, offset?, length?) -> hex digest +function Md5.of(buf, offset, length) +local h = Md5.new() + h:update(buf, offset, length) + return Md5.hex(h:digest()) +end + +return Md5 +end +__FILES["core/Sniff"] = function() +--!strict +-- core/Sniff: helpers for the formats' sniff functions (which return 0..1 from the first bytes, never consuming and +-- never throwing): magic comparison and the start of a text file without its UTF-8 byte order mark. +-- +-- function Qoi.sniff(r) return Sniff.magic(r, "qoif") end -- 1 or 0 +-- function Gz.sniff(r) return Sniff.magic(r, "\31\139\8", 0, 0.9) end -- a custom score +-- local head = Sniff.text(r, 64) -- the first 64 bytes, BOM dropped +-- local head = Sniff.text(r, 512, true) -- ... and leading whitespace too +-- local text = Sniff.dropBom(whole) -- decoders: the BOM off a whole file +local Sniff = {} + +-- magic(r, s, at?, score?) -> score (default 1) when the bytes at offset at (default 0) are s, else 0 + + +function Sniff.magic(r, s, at, score) +return (r:peek(#s, at) == s and{score or 1 }or{0 +})[1]end + +-- dropBom(s) -> s without a leading UTF-8 byte order mark (for decoders reading a whole text file) +function Sniff.dropBom(s) +return (string.sub(s, 1, 3) == "\239\187\191" and{(string.sub(s, 4) )}or{s +})[1]end + +-- text(r, n, trim?) -> up to n bytes from the start without a UTF-8 BOM (and leading whitespace when trim) +function Sniff.text(r, n, trim) +local s = r:peek(n) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + if trim then + s = (string.match(s, "^%s*(.*)$") ) +end + return s +end + +return Sniff +end +__FILES["data/cbor"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / +-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, +-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), +-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences +-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, +-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/cbor/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Cbor = { + name = "cbor", + category = "data", + extensions = { "cbor" }, + mime = { "application/cbor", "application/cbor-seq" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true, tags = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function Cbor.sniff(r) +return r:peek(3) == "\217\217\247" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function codeOf(e) +if string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) then + return Err.TRUNCATED + elseif string.find(e, "nested deeper", 1, true) then + return Err.LIMIT + end + return Err.CORRUPT +end + +function Cbor.decode(r, opts) +local o= opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.new(codeOf(e), e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the item (opts.all reads a sequence)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Cbor.encode(value, opts) +local w = Bytes.writer() + if opts and opts.selfDescribe then + w:string("\217\217\247") + end + local items = { value } + if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of items") + end + items = value + end + for _, v in __iter(items) do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.isTagged = Codec.isTagged +Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.isSimple = Codec.isSimple +Cbor.undefined = Codec.undefined + +return Cbor +end +__FILES["data/cbor/Codec"] = function() +local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict +--!native +-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, +-- message, offset. +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- ------------------------------------------------------------------------------------------------ value types +local TaggedMeta = { __tostring = function(t) +return "cbor.tag(" .. t.tag .. ")" +end } +local SimpleMeta = { __tostring = function(s) +return "cbor.simple(" .. s.value .. ")" +end } +-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret +function Codec.tagged(tag, value) +return (setmetatable({ tag = tag, value = value }, TaggedMeta) ) +end +function Codec.isTagged(v) +return type(v) == "table" and getmetatable(v) == TaggedMeta +end +-- simple(n) -> an unassigned simple value (0..19, 32..255) +function Codec.simple(n) +return (setmetatable({ value = n }, SimpleMeta) ) +end +function Codec.isSimple(v) +return type(v) == "table" and getmetatable(v) == SimpleMeta +end +Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() + return "undefined" +end })) + +-- decimal text of a big-endian unsigned byte string (any length) +local function bigText(s) +local limbs = {} -- base 1e7, little-endian + for i = 1, #s do + local carry = string.byte(s, i) + for k = 1, #limbs do + local v = limbs[k] * 256 + carry + limbs[k] = v % 10000000 + carry = math.floor(v / 10000000 +) end + while carry > 0 do + table.insert(limbs, carry % 10000000) + carry =math.floor(carry/ 10000000 +) end + end + if #limbs == 0 then + return "0" + end + local out = { string.format("%d", limbs[#limbs]) } + for k = #limbs - 1, 1, -1 do + table.insert(out, string.format("%07d", limbs[k])) + end + return table.concat(out) +end +-- text + 1 for a decimal string +local function incText(s) +local digits= (table.create(#s) ) +for i = 1, #s do + digits[i] = string.byte(s, i) - 48 + end + local i = #digits + while i >= 1 do + if digits[i] < 9 then + digits[i]=digits[i]+ 1 + break + end + digits[i] = 0 + i =i- 1 + end + local out= (table.create(#digits) ) +for k, d in __iter(digits) do + out[k] = string.char(48 + d) + end + return (i == 0 and"1" or"") .. table.concat(out) +end + + + + + + + + + + + +local BREAK = {} -- the 0xFF stop code, inside indefinite items + +-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +local function arg(st, ai) +local r = st.r + if ai < 24 then + return ai, nil, nil + elseif ai == 24 then + return r:u8(), nil, nil + elseif ai == 25 then + return r:u16be(), nil, nil + elseif ai == 26 then + return r:u32be(), nil, nil + elseif ai == 27 then + local hi, lo = r:u32be(), r:u32be() + if st.big and hi >= 0x200000 then + return hi * TWO32 + lo, bigText(string.char(math.floor(hi / 16777216), (math.floor(hi / 65536)) % 256, (math.floor(hi / 256)) % 256, hi % 256, math.floor(lo / 16777216), (math.floor(lo / 65536)) % 256, (math.floor(lo / 256)) % 256, lo % 256)), nil + end + return hi * TWO32 + lo, nil, nil + elseif ai == 31 then + return nil, nil, nil + end + return nil, nil, "reserved additional information " .. ai +end + +local item + +local function chunks(st, major, depth) +local parts = {} + while true do + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + if ib == 0xFF then + return table.concat(parts), nil + end + if math.floor(ib / 32 )~= major then + return nil, "bad chunk in an indefinite string" + end + local n, _, e = arg(st, ib % 32) + if e or n == nil then + return nil, e or "nested indefinite string" + end + if r.err or not r:need(n) then + return nil, "truncated string" + end + table.insert(parts, r:string(n)) + end +end + +local half = Bytes.half + +local function tag(st, t, v) +if t == 0 and st.dates then + if type(v) ~= "string" then + return nil, "tag 0 needs a text string" + end + local d = Types.Date.parse(v) + if not d or not d.offset then + return nil, "tag 0: bad date-time " .. v + end + return d, nil + elseif t == 1 and st.dates then + if type(v) ~= "number" or v ~= v or v == math.huge or v == -math.huge then + return nil, "tag 1 needs a number" + end + return Types.Date.fromUnix(v), nil + elseif t == 2 or t == 3 then + if type(v) ~= "string" then + return nil, "bignum tag needs a byte string" + end + local s = v +local n = 0 + for i = 1, #s do + n = n * 256 + string.byte(s, i) + end + if n >= 9007199254740992 then + -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + local text = bigText(s) + if t == 3 then + text = incText(text) + end + if st.big then + return (t == 2 and{text }or{("-" .. text)})[1], nil + end + local x = (tonumber(text) ) +return (t == 2 and{x }or{(-x)})[1], nil + end + return (t == 2 and{n }or{(-1 - n)})[1], nil + elseif t == 55799 then + return v, nil + end + return Codec.tagged(t, v), nil +end + +function item(st, depth) +if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local ib = r:u8() + if r.err then + return nil, "truncated" + end + local major, ai = math.floor(ib / 32), ib % 32 + if major == 7 then + if ai < 20 then + return Codec.simple(ai), nil + elseif ai == 20 then + return false, nil + elseif ai == 21 then + return true, nil + elseif ai == 22 then + return st.null, nil + elseif ai == 23 then + return st.undef, nil + elseif ai == 24 then + local n = r:u8() + if r.err then + return nil, "truncated" + end + if n < 32 then + return nil, "bad two-byte simple value" + end + return Codec.simple(n), nil + elseif ai == 25 then + local h = r:u16be() + return (r.err and{nil }or{(half(h))})[1], r.err and"truncated" or nil + elseif ai == 26 then + local f = r:f32be() + return (r.err and{nil }or{f})[1], r.err and"truncated" or nil + elseif ai == 27 then + local f = r:f64be() + return (r.err and{nil }or{f})[1], r.err and"truncated" or nil + elseif ai == 31 then + return BREAK, nil + end + return nil, "reserved simple value" + end + local n, text, e = arg(st, ai) + if e then + return nil, e + end + if r.err then + return nil, "truncated" + end + if major == 0 then + if n == nil then + return nil, "indefinite integer" + end + return text or n, nil + elseif major == 1 then + if n == nil then + return nil, "indefinite integer" + end + if text then + return "-" .. incText(text), nil + end + return -1 - n, nil + elseif major == 2 or major == 3 then + local s +if n == nil then + local c, ce = chunks(st, major, depth) + if not c then + return nil, ce + end + s = c + else + if not r:need(n) then + return nil, "truncated string" + end + s = r:string(n) + end + if major == 2 then + return buffer.fromstring(s), nil + end + if string.find(s, "[\128-\255]") and not utf8.len(s) then + return nil, "invalid UTF-8 in a text string" + end + return s, nil + elseif major == 4 then + if n == nil then + local t = {} + while true do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return t, nil + end + table.insert(t, v) + end + end + if (n ) > r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n ) + for k = 1, n do + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + t[k] = v + end + return t, nil + elseif major == 5 then + if n ~= nil and n * 2 > r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order = {} + local k = 0 + while n == nil or k < n do + k =k+ 1 + local key, ke = item(st, depth + 1) + if ke then + return nil, ke + end + if key == BREAK then + if n == nil then + break + end + return nil, "unexpected break" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + if key ~= key then + return nil, "NaN map key" + end + if t[key] == nil then + table.insert(order, key) + end + t[key] = v + end + return Types.object(t, order), nil + else -- 6: tag + if n == nil then + return nil, "indefinite tag" + end + local v, ve = item(st, depth + 1) + if ve then + return nil, ve + end + if v == BREAK then + return nil, "unexpected break" + end + -- bignum content arrives as a buffer: hand the tag its bytes + if (n == 2 or n == 3) and type(v) == "buffer" then + return tag(st, n, buffer.tostring(v)) + end + return tag(st, n, v) + end +end + +-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) +function Codec.decode(r, opts) +local o= opts or {} + local st= { + r = r, + big = o.bigInts == "string", + null = (o.null ~= nil and{o.null }or{Types.null})[1], + undef = (o.undefined ~= nil and{o.undefined }or{Codec.undefined})[1], + maxDepth = o.maxDepth or 512, + dates = o.dates ~= false, + } + local v, e = item(st, 0) + if e then + return nil, e, r.pos - r.base + end + if v == BREAK then + return nil, "unexpected break", r.pos - r.base - 1 + end + return v, nil +end +-- ------------------------------------------------------------------------------------------------ encode + + + + + + + + + + + +local function head(w, major, n) + local m = major * 32 + if n < 24 then + w:u8(m + n) + elseif n < 256 then + w:u8(m + 24) + w:u8(n) + elseif n < 65536 then + w:u8(m + 25) + w:u16be(n) + elseif n < TWO32 then + w:u8(m + 26) + w:u32be(n) + elseif n >= 18446744073709551616 then -- -1 - (-2^64) rounds up to 2^64: the exact argument is 2^64 - 1 + w:u8(m + 27) + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + else + w:u8(m + 27) + w:u64be(n) + end +end + +-- the half-float bits of x when x is exactly representable, else nil +local function toHalf(x) +if x ~= x then + return 0x7E00 + end + local sign = (x < 0 or (x == 0 and 1 / x < 0) )and 0x8000 or 0 + local a = math.abs(x) + if a == math.huge then + return sign + 0x7C00 + end + if a == 0 then + return sign + end + local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local exp = e - 1 + 15 + if exp >= 31 then + return nil + end + if exp <= 0 then -- subnormal: a = mant * 2^-24 + local mant = a / 2 ^ -24 + if mant ~= math.floor(mant) or mant >= 1024 then + return nil + end + return sign + mant + end + local frac = (m * 2 - 1) * 1024 + if frac ~= math.floor(frac) then + return nil + end + return sign + exp * 1024 + frac +end +Codec.toHalf = toHalf + +local keyLess = Types.keyLess + +local isArray = Types.isArray + +local scratch = buffer.create(8) + +local function enc(st, v, depth) +local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xF6) + elseif v == Codec.undefined then + w:u8(0xF7) + elseif tv == "boolean" then + w:u8(v and 0xF5 or 0xF4) + elseif tv == "number" then + if v == math.floor(v) and v >= -18446744073709551616 and v < 18446744073709551616 and not (v == 0 and 1 / v < 0) then + if v >= 0 then + head(w, 0, v) + else + head(w, 1, -1 - v) + end + else + local h = (st.compact and{(toHalf(v) )}or{nil +})[1] if h then + w:u8(0xF9) + w:u16be(h) + else + buffer.writef32(scratch, 0, v) + if st.compact and (buffer.readf32(scratch, 0) == v or v ~= v) then + w:u8(0xFA) + w:f32be(v) + else + w:u8(0xFB) + w:f64be(v) + end + end + end + elseif tv == "string" then + head(w, 3, #v) + w:string(v) + elseif tv == "buffer" then + head(w, 2, buffer.len(v)) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isTagged(v) then + if type(v.tag) ~= "number" or v.tag < 0 or v.tag ~= math.floor(v.tag) then + st.err = "bad tag number" + return false + end + head(w, 6, v.tag) + return enc(st, v.value, depth + 1) + elseif Codec.isSimple(v) then + local n = v.value + if n < 20 then + w:u8(0xE0 + n) + elseif n >= 32 and n < 256 then + w:u8(0xF8) + w:u8(n) + else + st.err = "bad simple value " .. tostring(n) + return false + end + elseif Types.Date.is(v) then + if st.epoch then + w:u8(0xC1) + return enc(st, Types.Date.toUnix(v), depth + 1) + end + w:u8(0xC0) + local s = tostring(v) + head(w, 3, #s) + w:string(s) + elseif isArray(v, st.emptyMap) then + local n = #v + head(w, 4, n) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys +if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + head(w, 5, #keys) + for _, k in __iter(keys) do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +function Codec.encode(v, opts) +local o= opts or {} + local st= { + w = Bytes.writer(256), + compact = o.compactFloats == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + epoch = o.dates == "epoch", + maxDepth = o.maxDepth or 512, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/csv"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any +-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded +-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column +-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only +-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters +-- other than the doubled quote, multi-byte delimiters. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Csv = { + name = "csv", + category = "data", + extensions = { "csv", "tsv" }, + mime = { "text/csv", "text/tab-separated-values" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, header = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + +local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub + +local function patEscape(c) +return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0")) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Csv.sniff(r) +local head = r:peek(1024) + if find(head, "%z") then + return 0 + end + local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)") + if not l1 or l1 == "" then + return 0 + end + for _, d in __iter({ ",", "\t", ";" }) do + local _, c1 = gsub(l1, d, "") + local _, c2 = gsub(l2 , d, "") + if c1 > 0 and c1 == c2 then + return 0.15 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function guess(s, q) +local line = string.match(s, "^[^\r\n]*") or "" + line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "") + local best, bestN = ",", 0 + for _, d in __iter({ ",", ";", "\t", "|" }) do + local _, n = gsub(line, patEscape(d), "") + if n > bestN then + best, bestN = d, n + end + end + return best +end + +-- rows(s, opts) -> { { string } } | nil, Err +function Csv.parse(s, opts) +local o= opts or {} + local q = o.quote or '"' + local d = o.delimiter or "," + if d == "auto" then + d = guess(s, q) + end + if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)") + end + local qb, db = byte(q), byte(d) + local stop = "[" .. patEscape(d) .. "\r\n]" + local maxRows = o.maxRows or math.huge + local rows= {} + local row= {} + local n = #s + local i = 1 + local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + while true do + local c = byte(s, i) + local field +if c == qb then + local k = i + 1 + local parts = {} + while true do + local j = find(s, q, k, true) + if not j then + return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1) + end + if byte(s, j + 1) == qb then + table.insert(parts, sub(s, k, j)) + k = j + 2 + else + table.insert(parts, sub(s, k, j - 1)) + i = j + 1 + break + end + end + -- text after the closing quote up to the delimiter is kept (Python's lenient reading) + local e = find(s, stop, i) or (n + 1) + if e > i then + table.insert(parts, sub(s, i, e - 1)) + end + i = e + field = table.concat(parts) + rowEmpty = false + else + local e = find(s, stop, i) or (n + 1) + field = sub(s, i, e - 1) + if e > i then + rowEmpty = false + end + i = e + end + table.insert(row, field) + c = byte(s, i) + if c == db then + rowEmpty = false + i =i+ 1 + else + -- end of the row: CRLF / LF / CR / end of data + if c == 13 and byte(s, i + 1) == 10 then + i =i+ 2 + elseif c ~= nil then + i =i+ 1 + end + if not rowEmpty then + table.insert(rows, row) + if #rows > maxRows then + return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows") + end + end + row = {} + rowEmpty = true + if i > n then + break + end + end + end + return rows, nil +end + +local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$" +local function convert(v) +if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then + local x = tonumber(v) + if x then + return x + end + end + return v +end + +function Csv.decode(r, opts) +local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + s = Sniff.dropBom(s) + local rows, err = Csv.parse(s, opts) + if not rows then + return nil, err + end + local o= opts or {} + if o.numbers then + for _, row in __iter(rows) do + for k, v in __iter(row) do + row[k] = convert(v) + end + end + end + if not o.header then + return rows, nil + end + local names = rows[1] or {} + local out = table.create(math.max(#rows - 1, 0)) + for k = 2, #rows do + local row = rows[k] + local obj = Types.object() + for c, name in __iter(names) do + if row[c] ~= nil then + Types.set(obj, tostring(name), row[c]) + end + end + out[k - 1] = obj + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v) +local tv = type(v) + if tv == "string" then + return v, nil + elseif tv == "number" then + local s = Json.number(v) + if not s then + return v ~= v and"nan" or(v > 0 and"inf" or"-inf"), nil + end + return s, nil + elseif tv == "boolean" then + return v and"true" or"false", nil + elseif v == nil or v == Types.null then + return "", nil + elseif tv == "table" and Types.Date.is(v) then + return tostring(v), nil + end + return nil, "cannot write a " .. tv .. " as a field" +end + +local function isArray(t) +if type(t) ~= "table" or Types.isObject(t) then + return false + end + local n = #t + return n > 0 or next(t) == nil +end + +function Csv.encode(rows, opts) +local o= opts or {} + local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n" + if #d ~= 1 or #q ~= 1 or d == q then + return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes") + end + if type(rows) ~= "table" then + return nil, Err.new(Err.ARG, "expected an array of rows") + end + local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]" + local qq = q .. q + local out= {} + local function writeRow(fields, count) +local parts = table.create(count) + for k = 1, count do + local s, e = text(fields[k]) + if not s then + return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e)) + end + if o.quoteAll or find(s, special) or (count == 1 and s == "") then + s = q .. gsub(s, patEscape(q), qq) .. q + end + parts[k] = s + end + table.insert(out, table.concat(parts, d) .. nl) + return nil + end + local keyed = rows[1] ~= nil and not isArray(rows[1]) + if keyed then + local cols = o.columns + if not cols then + local seen, list = {}, {} + for _, row in __iter(rows) do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be tables") + end + for _, k in __iter(Types.keys(row)) do + if not seen[k] then + seen[k] = true + table.insert(list, k) + end + end + end + cols = list + end + local cl = cols +if o.header ~= false then + local e = writeRow(cl, #cl) + if e then + return nil, e + end + end + for _, row in __iter(rows) do + local fields = table.create(#cl) + for k, name in __iter(cl) do + fields[k] = row[name] + end + local e = writeRow(fields, #cl) + if e then + return nil, e + end + end + else + for _, row in __iter(rows) do + if type(row) ~= "table" then + return nil, Err.new(Err.ARG, "rows must be arrays of fields") + end + local e = writeRow(row, #row) + if e then + return nil, e + end + end + end + return buffer.fromstring(table.concat(out)), nil +end + +return Csv +end +__FILES["data/ini"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. +-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, +-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at +-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a +-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level +-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested +-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local Ini = { + name = "ini", + category = "data", + extensions = { "ini", "cfg", "conf", "inf", "desktop" }, + mime = { "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function Ini.sniff(r) +local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + local first = string.match(head, "^[%s]*([^\r\n]*)") + while first and string.match(first, "^[;#]") do + head = string.match(head, "^[^\n]*\n(.*)$") or "" + first = string.match(head, "^[%s]*([^\r\n]*)") + end + if first and string.match(first, "^%[[^%]]+%]%s*$") then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local BOOLS= { ["true"] = true, ["false"] = false, yes = true, no = false, on = true, off = false } + +local function typed(v) +if type(v) ~= "string" then + return v + end + local b = BOOLS[string.lower(v)] + if b ~= nil then + return b + end + if string.match(v, "^[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*$") or string.match(v, "^[%-%+]?%.%d+$") or string.match(v, "^0x%x+$") then + local n = tonumber(v) + if n then + return n + end + end + return v +end + +function Ini.decode(r, opts) +local o= opts or {} + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + s = Sniff.dropBom(s) + local root = Types.object() + local cur = root + local lastKey= nil + local lastIndent = 0 + local lastTable= nil + local seenKeys= {} + local pos = 1 + local lineStart = 0 + for line in __iter(string.gmatch(s .. "\n", "([^\n]*)\n")) do + lineStart = pos - 1 + pos =pos+ (#line + 1 +) line = string.gsub(line, "\r$", "") + local indent = #((string.match(line, "^[ \t]*") )) + local trimmed = (string.match(line, "^%s*(.-)%s*$") ) +if trimmed == "" then + lastKey = nil + elseif string.match(trimmed, "^[;#]") then + -- a comment line (configparser: also when indented); it does not end a continuation + elseif lastKey and indent > lastIndent then + -- continuation of the previous value + local v = trimmed + if o.inlineComments then + v = string.match(v, "^(.-)%s+[;#]") or v + end + local prev = lastTable[lastKey] + lastTable[lastKey] = ((type(prev) == "string" and{prev }or{""})[1]) .. "\n" .. v + elseif string.sub(trimmed, 1, 1) == "[" and string.find(trimmed, "]", 2, true) then + local name = (string.match(trimmed, "^%[(.*)%]") ) +local existing = root[name] + if existing ~= nil and type(existing) ~= "table" then + return nil, Err.new(Err.CORRUPT, "section [" .. name .. "] has the name of a top-level key", lineStart) + end + if existing and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate section [" .. name .. "]", lineStart) + end + if not existing then + existing = Types.object() + Types.set(root, name, existing) + end + cur = existing + lastKey = nil + else + local key, value = string.match(trimmed, "^(.-)%s*[=:]%s*(.*)$") + if not key then + if not o.allowNoValue then + return nil, Err.new(Err.CORRUPT, "line without '=' or ':': " .. string.sub(trimmed, 1, 40), lineStart) + end + key, value = trimmed, true +end + if key == "" then + return nil, Err.new(Err.CORRUPT, "empty key", lineStart) + end + if o.inlineComments and type(value) == "string" then + value = string.match(value, "^(.-)%s+[;#]") or (string.match(value, "^[;#]") and"" or value) + end + local seen = seenKeys[cur] + if not seen then + seen = {} + seenKeys[cur] = seen + end + if seen[key ] and o.strict then + return nil, Err.new(Err.CORRUPT, "duplicate key " .. (key ), lineStart) + end + seen[key ] = true + if cur == root and type(root[key]) == "table" then + return nil, Err.new(Err.CORRUPT, "top-level key " .. (key ) .. " has the name of a section", lineStart) + end + Types.set(cur, key, value) + lastKey, lastIndent, lastTable = key, indent, cur + end + end + if o.types then + for _, k in __iter(Types.keys(root)) do + local v = root[k] + if type(v) == "table" then + for _, k2 in __iter(Types.keys(v)) do + v[k2] = typed(v[k2]) + end + else + root[k] = typed(v) + end + end + end + return root, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function text(v) +local tv = type(v) + if tv == "string" then + return (string.gsub(v, "\n", "\n\t")) + elseif tv == "number" then + return Json.number(v) or tostring(v) + elseif tv == "boolean" then + return v and"true" or"false" + elseif v == Types.null then + return "" + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +function Ini.encode(value, opts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "expected a table of sections") + end + local delim = (opts and opts.delimiter) or " = " + local out= {} + local err= nil + local function keyOk(k) +if type(k) ~= "string" and type(k) ~= "number" then + err = "keys must be strings" + return false + end + local ks = tostring(k) + if ks == "" or string.find(ks, "[=:\r\n]") or string.match(ks, "^[%s;#%[]") or string.match(ks, "%s$") then + err = "key " .. string.format("%q", ks) .. " cannot be written" + return false + end + return true + end + local function pairsOf(t, prefix, depth) +if depth > 32 then + err = "sections nested too deeply (a cycle?)" + return false + end + local subs = {} + local lines = {} + for _, k in __iter(Types.keys(t)) do + local v = t[k] + if type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then + table.insert(subs, k) + else + if not keyOk(k) then + return false + end + local s = text(v) + if not s then + err = "cannot write a " .. type(v) .. " value" + return false + end + table.insert(lines, tostring(k) .. delim .. s .. "\n") + end + end + if prefix ~= "" then + table.insert(out, "[" .. prefix .. "]\n") + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + elseif #lines > 0 then + table.move(lines, 1, #lines, #out + 1, out) + table.insert(out, "\n") + end + for _, k in __iter(subs) do + local name = tostring(k) + if string.find(name, "[\r\n%]]") then + err = "section name " .. string.format("%q", name) .. " cannot be written" + return false + end + if not pairsOf(t[k], (prefix == "" and{name }or{(prefix .. "." .. name)})[1], depth + 1) then + return false + end + end + return true + end + if not pairsOf(value, "", 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(table.concat(out)), nil +end + +return Ini +end +__FILES["data/json"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). +-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or +-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Json = __include("codecs/text/Json") + +-- ------------------------------------------------------------------------------------------------ contract +local JsonFormat = { + name = "json", + category = "data", + extensions = { "json", "jsonl", "ndjson", "geojson" }, + mime = { "application/json", "application/x-ndjson" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" }, + caps = { decode = true, encode = true, ordered = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + +function JsonFormat.sniff(r) +local head = Sniff.text(r, 64) + local first = string.match(head, "^[ \t\r\n]*(.)") + if first == "{" then + local nxt = string.match(head, "^[^{]*{[ \t\r\n]*(.)") + return (nxt == nil or nxt == '"' or nxt == "}" )and 0.6 or 0.1 + elseif first == "[" then + -- past any nested '[': a JSON value must start (TOML / INI "[section]" and "[[table]]" do not) + local nxt = string.match(head, "^[ \t\r\n]*[%[ \t\r\n]*(.)") + if nxt == nil or string.find('{"-0123456789tfn]', nxt, 1, true) then + return 0.3 + end + return 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function JsonFormat.decode(r, opts) +local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if opts and opts.lines then + local out = {} + for _, v, err in __iter(Json.lines(s, opts)) do + if err then + return nil, err + end + table.insert(out, v) + end + return out, nil + end + return Json.decode(s, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function JsonFormat.encode(value, opts) +if opts and opts.lines then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "lines: expected an array of values") + end + local o = (table.clone(opts) ) +o.indent = nil + local parts = {} + for i, v in __iter(value) do + local s, err = Json.encode(v, o) + if not s then + return nil, err + end + parts[i] = s .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + local s, err = Json.encode(value, opts) + if not s then + return nil, err + end + if opts and opts.indent then + s =s.. "\n" + end + return buffer.fromstring(s), nil +end + +return JsonFormat +end +__FILES["data/msgpack"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the +-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as +-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a +-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for +-- non-integers unless opts.float32). Not supported: nothing in the spec. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Codec = __include("data/msgpack/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Msgpack = { + name = "msgpack", + category = "data", + extensions = { "msgpack", "mpk" }, + mime = { "application/msgpack", "application/x-msgpack" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, binary = true, ordered = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + +function Msgpack.sniff(_r) +return 0 -- no magic: by extension or opts.format only +end + +-- ------------------------------------------------------------------------------------------------ decode +function Msgpack.decode(r, opts) +local o= opts or {} + if o.all then + local out = {} + while not r:eof() do + local v, e, at = Codec.decode(r, o) + if e then + return nil, Err.from(e, at) + end + table.insert(out, v) + end + return out, nil + end + local v, e, at = Codec.decode(r, o) + if e then + local code = ((string.find(e, "truncated", 1, true) or string.find(e, "past the end", 1, true) )and{Err.TRUNCATED +}or{(string.find(e, "nested deeper", 1, true) and{Err.LIMIT +}or{Err.CORRUPT +})[1]})[1] return nil, Err.new(code, e, at) + end + if not r:eof() then + return nil, Err.new(Err.CORRUPT, "trailing data after the value (opts.all reads a stream)", r.pos - r.base) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Msgpack.encode(value, opts) +if opts and opts.all then + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "all: expected an array of values") + end + local w = Bytes.writer() + for _, v in __iter(value) do + local b, e = Codec.encode(v, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + w:bytes(b) + end + return w:finish(), nil + end + local b, e = Codec.encode(value, opts) + if not b then + return nil, Err.new(Err.ARG, e or "cannot encode") + end + return b, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) +Msgpack.ext = Codec.ext +Msgpack.isExt = Codec.isExt + +return Msgpack +end +__FILES["data/msgpack/Codec"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with +-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Codec = {} + +local TWO32 = 4294967296 + +-- an extension value: { type = -128..127, data = buffer } +local ExtMeta = { __tostring = function(e) +return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" +end } +function Codec.ext(t, data) +return (setmetatable({ type = t, data = data }, ExtMeta) ) +end +function Codec.isExt(v) +return type(v) == "table" and getmetatable(v) == ExtMeta +end + +-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact +local function u64text(hi, lo) +if hi == 0 then + return string.format("%d", lo) + end + local digits = {} + -- long division by 10 on four 16-bit limbs + local l = { math.floor(hi / 65536), hi % 65536, math.floor(lo / 65536), lo % 65536 } + while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + l[k] + l[k] = math.floor(cur / 10 +) rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + return table.concat(digits) +end +Codec.u64text = u64text + + + + + + + + + + + +local function int64(st, signed) +local r = st.r + local hi, lo = r:u32be(), r:u32be() + if signed and hi >= 0x80000000 then + -- negative: two's complement + local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo + if nlo == TWO32 then + nlo = 0 + nhi =nhi+ 1 + end + if st.big and nhi >= 0x200000 then + return "-" .. u64text(nhi, nlo) + end + return -(nhi * TWO32 + nlo) + end + if st.big and hi >= 0x200000 then + return u64text(hi, lo) + end + return hi * TWO32 + lo +end + +local value + +local function ext(st, n) +local r = st.r + local t = r:i8() + if r.err or not r:need(n) then + return nil, "truncated ext" + end + if t == -1 and st.ts then + local secs, ns = 0, 0 + if n == 4 then + secs = r:u32be() + elseif n == 8 then + local hi, lo = r:u32be(), r:u32be() + ns = math.floor(hi / 4 +) secs = (hi % 4) * TWO32 + lo + elseif n == 12 then + ns = r:u32be() + secs = r:i64be() + else + return nil, "bad timestamp length" + end + if ns > 999999999 then + return nil, "bad timestamp nanoseconds" + end + local d= Types.Date.fromUnix(secs) + d.nanosecond = ns + return d, nil + end + return Codec.ext(t, r:bytes(n)), nil +end + +local function array(st, n, depth) +if n > st.r:remaining() then + return nil, "array count past the end" + end + local t = table.create(n) + for k = 1, n do + local v, e = value(st, depth + 1) + if e then + return nil, e + end + t[k] = v + end + return t, nil +end + +local function map(st, n, depth) +if n * 2 > st.r:remaining() then + return nil, "map count past the end" + end + local t = {} + local order= (st.ordered and{(table.create(n) )}or{nil +})[1] for _ = 1, n do + local k, e = value(st, depth + 1) + if e then + return nil, e + end + local v, e2 = value(st, depth + 1) + if e2 then + return nil, e2 + end + if k ~= k then + return nil, "NaN map key" + end + if order and t[k] == nil then + table.insert(order, k) + end + t[k] = v + end + return Types.object(t, order or {}), nil +end + +function value(st, depth) +if depth > st.maxDepth then + return nil, "nested deeper than " .. st.maxDepth + end + local r = st.r + local b = r:u8() + if r.err then + return nil, "truncated" + end + if b < 0x80 then + return b, nil + elseif b >= 0xE0 then + return b - 256, nil + elseif b < 0x90 then + return map(st, b - 0x80, depth) + elseif b < 0xA0 then + return array(st, b - 0x90, depth) + elseif b < 0xC0 then + local n = b - 0xA0 + if not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xC0 then + return st.null, nil + elseif b == 0xC2 then + return false, nil + elseif b == 0xC3 then + return true, nil + elseif b == 0xC4 or b == 0xC5 or b == 0xC6 then + local n = (b == 0xC4 and{(r:u8() )}or{(b == 0xC5 and{(r:u16be() )}or{(r:u32be() +)})[1]})[1] if r.err or not r:need(n) then + return nil, "truncated bin" + end + return r:bytes(n), nil + elseif b == 0xC7 or b == 0xC8 or b == 0xC9 then + local n = (b == 0xC7 and{(r:u8() )}or{(b == 0xC8 and{(r:u16be() )}or{(r:u32be() +)})[1]})[1] if r.err then + return nil, "truncated ext" + end + return ext(st, n) + elseif b == 0xCA then + local v = r:f32be() + return (r.err and{nil }or{v})[1], r.err and"truncated" or nil + elseif b == 0xCB then + local v = r:f64be() + return (r.err and{nil }or{v})[1], r.err and"truncated" or nil + elseif b >= 0xCC and b <= 0xD3 then + local v +if b == 0xCC then + v = r:u8() + elseif b == 0xCD then + v = r:u16be() + elseif b == 0xCE then + v = r:u32be() + elseif b == 0xCF then + v = int64(st, false) + elseif b == 0xD0 then + v = r:i8() + elseif b == 0xD1 then + v = r:i16be() + elseif b == 0xD2 then + v = r:i32be() + else + v = int64(st, true) + end + if r.err then + return nil, "truncated" + end + return v, nil + elseif b >= 0xD4 and b <= 0xD8 then + return ext(st, 2 ^ (b - 0xD4)) + elseif b >= 0xD9 and b <= 0xDB then + local n = (b == 0xD9 and{(r:u8() )}or{(b == 0xDA and{(r:u16be() )}or{(r:u32be() +)})[1]})[1] if r.err or not r:need(n) then + return nil, "truncated string" + end + return r:string(n), nil + elseif b == 0xDC or b == 0xDD then + local n = (b == 0xDC and{(r:u16be() )}or{(r:u32be() +)})[1] if r.err then + return nil, "truncated" + end + return array(st, n, depth) + elseif b == 0xDE or b == 0xDF then + local n = (b == 0xDE and{(r:u16be() )}or{(r:u32be() +)})[1] if r.err then + return nil, "truncated" + end + return map(st, n, depth) + end + return nil, string.format("reserved type byte 0x%02x", b) +end + +-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) +function Codec.decode(r, opts) +local o= opts or {} + local st= { + r = r, + big = o.bigInts == "string", + null = (o.null ~= nil and{o.null }or{Types.null})[1], + maxDepth = o.maxDepth or 512, + ts = o.timestamps ~= false, + ordered = o.ordered ~= false, + } + local v, e = value(st, 0) + if e then + return nil, e, r.pos - r.base + end + return v, nil +end +-- ------------------------------------------------------------------------------------------------ encode + + + + + + + + + + + +local function writeInt(w, v) + if v >= 0 then + if v < 128 then + w:u8(v) + elseif v < 256 then + w:u8(0xCC) + w:u8(v) + elseif v < 65536 then + w:u8(0xCD) + w:u16be(v) + elseif v < TWO32 then + w:u8(0xCE) + w:u32be(v) + else + w:u8(0xCF) + w:u64be(v) + end + else + if v >= -32 then + w:u8(v + 256) + elseif v >= -128 then + w:u8(0xD0) + w:u8(v + 256) + elseif v >= -32768 then + w:u8(0xD1) + w:u16be(v + 65536) + elseif v >= -2147483648 then + w:u8(0xD2) + w:u32be(v + TWO32) + else + w:u8(0xD3) + local hi = math.floor(v / TWO32) + local lo = v - hi * TWO32 + w:u32be(hi + TWO32) + w:u32be(lo) + end + end +end + +local function lenHeader(w, n, fix, fixMax, b8, b16, b32) + if fix and n <= fixMax then + w:u8(fix + n) + elseif b8 and n < 256 then + w:u8(b8) + w:u8(n) + elseif n < 65536 then + w:u8(b16) + w:u16be(n) + else + w:u8(b32) + w:u32be(n) + end +end + +local keyLess = Types.keyLess + +local isArray = Types.isArray +Codec.isArray = isArray + +local function enc(st, v, depth) +local w = st.w + local tv = type(v) + if v == nil or v == Types.null then + w:u8(0xC0) + elseif tv == "boolean" then + w:u8(v and 0xC3 or 0xC2) + elseif tv == "number" then + if v == math.floor(v) and v >= -9223372036854775808 and v < 18446744073709551616 then + writeInt(w, v) + elseif st.f32 then + w:u8(0xCA) + w:f32be(v) + else + w:u8(0xCB) + w:f64be(v) + end + elseif tv == "string" then + if st.bin then + lenHeader(w, #v, nil, 0, 0xC4, 0xC5, 0xC6) + else + lenHeader(w, #v, 0xA0, 31, 0xD9, 0xDA, 0xDB) + end + w:string(v) + elseif tv == "buffer" then + lenHeader(w, buffer.len(v), nil, 0, 0xC4, 0xC5, 0xC6) + w:bytes(v) + elseif tv == "table" then + if depth >= st.maxDepth then + st.err = "nested deeper than " .. st.maxDepth .. " (a cycle?)" + return false + end + if Codec.isExt(v) then + local n = buffer.len(v.data) + if n == 1 or n == 2 or n == 4 or n == 8 or n == 16 then + w:u8(({ [1] = 0xD4, [2] = 0xD5, [4] = 0xD6, [8] = 0xD7, [16] = 0xD8 })[n]) + else + lenHeader(w, n, nil, 0, 0xC7, 0xC8, 0xC9) + end + w:u8(v.type % 256) + w:bytes(v.data) + elseif Types.Date.is(v) then + local t = Types.Date.toUnix(v) + local secs = math.floor(t) + local ns = (v ).nanosecond or 0 + if ns == 0 and secs >= 0 and secs < TWO32 then + w:u8(0xD6) + w:u8(0xFF) + w:u32be(secs) + elseif secs >= 0 and secs < 2 ^ 34 then + w:u8(0xD7) + w:u8(0xFF) + w:u32be(ns * 4 + math.floor(secs / TWO32)) + w:u32be(secs % TWO32) + else + w:u8(0xC7) + w:u8(12) + w:u8(0xFF) + w:u32be(ns) + local hi = math.floor(secs / TWO32) + w:u32be(hi % TWO32) + w:u32be(secs - hi * TWO32) + end + elseif isArray(v, st.emptyMap) then + local n = #v + lenHeader(w, n, 0x90, 15, nil, 0xDC, 0xDD) + for k = 1, n do + if not enc(st, v[k], depth + 1) then + return false + end + end + else + local keys +if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + lenHeader(w, #keys, 0x80, 15, nil, 0xDE, 0xDF) + for _, k in __iter(keys) do + if not enc(st, k, depth + 1) or not enc(st, v[k], depth + 1) then + return false + end + end + end + else + st.err = "cannot encode a " .. tv + return false + end + return true +end + +-- encode(v, opts) -> buffer | nil, message +function Codec.encode(v, opts) +local o= opts or {} + local st= { + w = Bytes.writer(256), + f32 = o.float32 == true, + sort = o.sortKeys ~= false, + emptyMap = o.emptyTable == "map", + maxDepth = o.maxDepth or 512, + bin = o.stringsAsBin == true, + err = nil, + } + if not enc(st, v, 0) then + return nil, st.err + end + return st.w:finish(), nil +end + +return Codec +end +__FILES["data/nbt"] = function() +--!strict +-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and +-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and +-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / +-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression +-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. +-- Not supported: nothing in the format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + +function NbtFormat.sniff(r) +local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return p.firstType and 1 or 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return p.firstType and p.firstName and 0.6 or 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r, opts) +local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value, opts) +if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.Nbt = Nbt + +return NbtFormat +end +__FILES["data/plist"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is +-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> +-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> +-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past +-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as <integer>. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Binary = __include("data/plist/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Plist = { + name = "plist", + category = "data", + extensions = { "plist" }, + mime = { "application/x-plist", "application/x-bplist" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" }, + caps = { decode = true, encode = true, binary = "read", ordered = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function Plist.sniff(r) +local head = r:peek(256) + if string.sub(head, 1, 6) == "bplist" then + return 1 + end + if string.find(head, "<!DOCTYPE plist", 1, true) or string.find(head, "<plist", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function xmlValue(node, opts, depth) +if depth > ((opts and opts.maxDepth) or 512) then + return nil, "nested too deeply" + end + local name = node.name + if name == "dict" then + local out = Types.object() + local kids = Xml.children(node) + local i = 1 + while i <= #kids do + local k = kids[i] + if k.name ~= "key" then + return nil, "dict: expected <key>, got <" .. k.name .. ">" + end + local v = kids[i + 1] + if not v then + return nil, "dict: <key> without a value" + end + local val, e = xmlValue(v, opts, depth + 1) + if e then + return nil, e + end + Types.set(out, Xml.text(k), val) + i =i+ 2 + end + return out, nil + elseif name == "array" then + local out = {} + for _, ch in __iter(Xml.children(node)) do + local val, e = xmlValue(ch, opts, depth + 1) + if e then + return nil, e + end + table.insert(out, val) + end + return out, nil + elseif name == "string" then + return Xml.text(node), nil + elseif name == "integer" then + local t = (string.match(Xml.text(node), "^%s*(.-)%s*$") ) +local neg, hex = string.match(t, "^([%-%+]?)0[xX](%x+)$") + local n +if hex then + n = tonumber(hex, 16) + if n and neg == "-" then + n = -n + end + elseif string.match(t, "^[%-%+]?%d+$") then + n = tonumber(t) + if n and math.abs(n) >= 2 ^ 53 and opts and opts.bigInts == "string" then + return (string.gsub(t, "^%+", "")), nil + end + end + if not n then + return nil, "bad integer " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "real" then + local t = string.lower((string.match(Xml.text(node), "^%s*(.-)%s*$") )) + local n = tonumber(t) + if not n then + if t == "nan" or t == "+nan" or t == "-nan" then + n = 0 / 0 + elseif t == "inf" or t == "+inf" or t == "infinity" or t == "+infinity" then + n = math.huge + elseif t == "-inf" or t == "-infinity" then + n = -math.huge + end + end + if not n then + return nil, "bad real " .. string.sub(t, 1, 30) + end + return n, nil + elseif name == "true" then + return true, nil + elseif name == "false" then + return false, nil + elseif name == "date" then + local d = Types.Date.parse((string.match(Xml.text(node), "^%s*(.-)%s*$"))) + if not d then + return nil, "bad date" + end + return d, nil + elseif name == "data" then + local b, e = Base64.decode(Xml.text(node)) + if not b then + return nil, e + end + return b, nil + end + return nil, "unknown element <" .. tostring(name) .. ">" +end + +function Plist.decode(r, opts) +local len = r.limit - r.base + if len >= 8 and buffer.readstring(r.buf, r.base, 6) == "bplist" then + local v, e = Binary.decode(r.buf, r.base, len, opts) + if e then + return nil, Err.from(e) + end + return v, nil + end + local doc, err = Xml.decode(buffer.readstring(r.buf, r.base, len), { whitespace = true }) + if not doc then + return nil, err + end + local root = (doc ).root + if root.name == "plist" then + local kids = Xml.children(root) + if #kids ~= 1 then + return nil, Err.new(Err.CORRUPT, "<plist> must hold exactly one value") + end + root = kids[1] + end + local v, e = xmlValue(root, opts, 0) + if e then + return nil, Err.new(Err.CORRUPT, e) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local HEADER = '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n' + +local function esc(s) +if string.find(s, "[%z\1-\8\11\12\14-\31]") then + return nil, "strings cannot contain control characters" + end + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + return (string.gsub(s, "[&<>]", { ["&"] = "&", ["<"] = "<", [">"] = ">" })), nil +end + +local function keyLess(a, b) +return a < b +end + +function Plist.encode(value, opts) +local sort = not (opts and opts.sortKeys == false) + local out= { HEADER } + local err= nil + local function line(level, s) + table.insert(out, string.rep("\t", level) .. s .. "\n") + end + local write +function write(v, level, depth) +if depth > 512 then + err = "nested deeper than 512 (a cycle?)" + return false + end + local tv = type(v) + if tv == "string" then + local s, e = esc(v) + if not s then + err = e + return false + end + line(level, "<string>" .. s .. "</string>") + elseif tv == "boolean" then + line(level, v and"<true/>" or"<false/>") + elseif tv == "number" then + if v == math.floor(v) and math.abs(v) < 2 ^ 63 then + line(level, "<integer>" .. string.format("%d", v) .. "</integer>") + else + local s = Json.number(v) + if not s then + s = v ~= v and"nan" or(v > 0 and"inf" or"-inf" +) end + line(level, "<real>" .. s .. "</real>") + end + elseif tv == "buffer" then + line(level, "<data>") + local maxLine = math.max(16, 76 - 8 * level) + for l in __iter(string.gmatch(Base64.encode(v, { wrap = math.floor(maxLine / 4 )* 4 }), "[^\n]+")) do + line(level, l) + end + line(level, "</data>") + elseif tv == "table" and Types.Date.is(v) then + local d = Types.Date.fromUnix(math.floor(Types.Date.toUnix(v))) + line(level, string.format("<date>%04d-%02d-%02dT%02d:%02d:%02dZ</date>", d.year , d.month , d.day , d.hour , d.minute , d.second )) + elseif tv == "table" and Binary.isUid(v) then + err = "UIDs can only be written to binary plists" + return false + elseif tv == "table" and v ~= Types.null then + local n = #v + local isArray = false + if not Types.isObject(v) then + local c = 0 + for _ in next, v do + c =c+ 1 + end + isArray = c == n + end + if isArray then + if n == 0 then + line(level, "<array/>") + return true + end + line(level, "<array>") + for k = 1, n do + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "</array>") + else + local keys +if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + end + for _, k in __iter(keys) do + if type(k) ~= "string" then + err = "dict keys must be strings" + return false + end + end + if sort and not Types.isObject(v) then + table.sort(keys, keyLess) + end + if #keys == 0 then + line(level, "<dict/>") + return true + end + line(level, "<dict>") + for _, k in __iter(keys) do + local ks, e = esc(k) + if not ks then + err = e + return false + end + line(level + 1, "<key>" .. ks .. "</key>") + if not write(v[k], level + 1, depth + 1) then + return false + end + end + line(level, "</dict>") + end + else + err = "cannot write " .. (v == Types.null and"null" or"a " .. tv) .. " in a plist" + return false + end + return true + end + if not write(value, 0, 0) then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + table.insert(out, "</plist>\n") + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.isUid = Binary.isUid + +return Plist +end +__FILES["data/plist/Binary"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +--!native +-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in +-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte +-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, +-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles +-- are errors. Never throws: errors return nil, message. +local Types = __include("Types") + +local Binary = {} + +local readu8 = buffer.readu8 +local TWO32 = 4294967296 +local EPOCH_2001 = 978307200 + +local UidMeta = { __tostring = function(u) +return "UID(" .. u.uid .. ")" +end } +function Binary.uid(n) +return (setmetatable({ uid = n }, UidMeta) ) +end +function Binary.isUid(v) +return type(v) == "table" and getmetatable(v) == UidMeta +end + +local function be(b, o, n) +local v = 0 + for k = 0, n - 1 do + v = v * 256 + readu8(b, o + k) + end + return v +end + +local function utf8char(c) +if c < 0x80 then + return string.char(c) + elseif c < 0x800 then + return string.char(0xC0 + math.floor(c / 64), 0x80 + c % 64) + elseif c < 0x10000 then + return string.char(0xE0 + math.floor(c / 4096), 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) + end + return string.char(0xF0 + math.floor(c / 262144), 0x80 + (math.floor(c / 4096)) % 64, 0x80 + (math.floor(c / 64)) % 64, 0x80 + c % 64) +end + +-- decode(buf, base, len, opts) -> value | nil, message + + +function Binary.decode(b, base, len, opts) +if len < 40 then + return nil, "truncated: shorter than header + trailer" + end + local t = base + len - 32 + local offSize, refSize = readu8(b, t + 6), readu8(b, t + 7) + local numObjects = be(b, t + 8, 8) + local top = be(b, t + 16, 8) + local tableOff = be(b, t + 24, 8) + if offSize < 1 or offSize > 8 or refSize < 1 or refSize > 8 then + return nil, "bad trailer sizes" + end + if numObjects < 1 or top >= numObjects or tableOff < 8 or tableOff + numObjects * offSize > len - 32 then + return nil, "bad trailer" + end + local maxDepth = (opts and opts.maxDepth) or 512 + local cache= {} + local busy= {} + + local object + -- a length nibble: 0..14, or 15 = an int object follows + +local function count(o, nib) +if nib < 15 then + return nib, o + 1 + end + if o + 2 > len - 32 then + return nil, 0 + end + local m = readu8(b, base + o + 1) + if math.floor(m / 16 )~= 1 then + return nil, 0 + end + local w = 2 ^ (m % 16) + if w > 8 or o + 2 + w > len - 32 then + return nil, 0 + end + return be(b, base + o + 2, w), o + 2 + w + end + + local function ref(at) +return be(b, base + at, refSize) + end + + function object(idx, depth) +local cached = cache[idx] + if cached ~= nil then + return cached, nil + end + if busy[idx] then + return nil, "object references form a cycle" + end + if depth > maxDepth then + return nil, "nested deeper than " .. maxDepth + end + if idx >= numObjects then + return nil, "object reference out of range" + end + local o = be(b, base + tableOff + idx * offSize, offSize) + if o < 8 or o >= len - 32 then + return nil, "object offset out of range" + end + local marker = readu8(b, base + o) + local hi, nib = math.floor(marker / 16), marker % 16 + local v +if marker == 0x00 then + v = Types.null + elseif marker == 0x08 then + v = false + elseif marker == 0x09 then + v = true + elseif hi == 1 then + local w = 2 ^ nib + if w > 16 or o + 1 + w > len - 32 then + return nil, "bad integer" + end + if w == 16 then + o =o+ 8 + w = 8 + end + if w == 8 then + local h, l = be(b, base + o + 1, 4), be(b, base + o + 5, 4) + if h >= 0x80000000 and nib == 3 then + v = (h - TWO32) * TWO32 + l + elseif opts and opts.bigInts == "string" and h >= 0x200000 then + -- exact decimal text of h * 2^32 + l + local digits = {} + local limbs = { math.floor(h / 65536), h % 65536, math.floor(l / 65536), l % 65536 } + while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do + local rem = 0 + for k = 1, 4 do + local cur = rem * 65536 + limbs[k] + limbs[k] = math.floor(cur / 10 +) rem = cur % 10 + end + table.insert(digits, 1, string.char(48 + rem)) + end + v = table.concat(digits) + else + v = h * TWO32 + l + end + else + v = be(b, base + o + 1, w) + end + elseif hi == 2 then + if nib == 2 and o + 5 <= len - 32 then + local s = buffer.create(4) + for k = 0, 3 do + buffer.writeu8(s, k, readu8(b, base + o + 4 - k)) + end + v = buffer.readf32(s, 0) + elseif nib == 3 and o + 9 <= len - 32 then + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + v = buffer.readf64(s, 0) + else + return nil, "bad real" + end + elseif marker == 0x33 then + if o + 9 > len - 32 then + return nil, "truncated date" + end + local s = buffer.create(8) + for k = 0, 7 do + buffer.writeu8(s, k, readu8(b, base + o + 8 - k)) + end + local secs = buffer.readf64(s, 0) + if secs ~= secs or math.abs(secs) > 1e14 then + return nil, "bad date" + end + v = Types.Date.fromUnix(secs + EPOCH_2001) + elseif hi == 4 or hi == 5 or hi == 6 or hi == 7 then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local bytes = (hi == 6 and((n * 2 ))or(n +)) if p + bytes > len - 32 then + return nil, "string / data past the end" + end + if hi == 4 then + local d = buffer.create(bytes) + buffer.copy(d, 0, b, base + p, bytes) + v = d + elseif hi == 6 then + local parts = table.create(n) + local k = 0 + while k < n do + local u = be(b, base + p + k * 2, 2) + k =k+ 1 + if u >= 0xD800 and u <= 0xDBFF and k < n then + local lo = be(b, base + p + k * 2, 2) + if lo >= 0xDC00 and lo <= 0xDFFF then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + k =k+ 1 + end + end + table.insert(parts, utf8char(u)) + end + v = table.concat(parts) + else + v = buffer.readstring(b, base + p, bytes) + end + elseif hi == 8 then + if o + 2 + nib > len - 32 then + return nil, "bad UID" + end + v = Binary.uid(be(b, base + o + 1, nib + 1)) + elseif hi == 0xA or hi == 0xC or hi == 0xD then + local n, p = count(o, nib) + if not n then + return nil, "bad length" + end + local refs = (hi == 0xD and((n * 2 ))or(n +)) if p + refs * refSize > len - 32 then + return nil, "collection past the end" + end + busy[idx] = true + if hi == 0xD then + local t2 = {} + local order = table.create(n) + for k = 0, n - 1 do + local key, ke = object(ref(p + k * refSize), depth + 1) + if ke then + return nil, ke + end + if type(key) ~= "string" then + return nil, "dict key is not a string" + end + local val, ve = object(ref(p + (n + k) * refSize), depth + 1) + if ve then + return nil, ve + end + if t2[key] == nil then + table.insert(order, key) + end + t2[key] = val + end + v = Types.object(t2, order) + else + local arr = table.create(n) + for k = 0, n - 1 do + local item, ie = object(ref(p + k * refSize), depth + 1) + if ie then + return nil, ie + end + arr[k + 1] = item + end + v = arr + end + busy[idx] = nil + else + return nil, string.format("unknown object marker 0x%02x", marker) + end + cache[idx] = v + return v, nil + end + + return object(top, 0) +end + +return Binary +end +__FILES["data/snbt"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over +-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt +-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Nbt = __include("codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function SnbtFormat.sniff(r) -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + +local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r, opts) +local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value, opts) +if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat +end +__FILES["data/toml"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, +-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range +-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules +-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / +-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to +-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral +-- values are written as integers). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Decode = __include("data/toml/Decode") +local Encode = __include("data/toml/Encode") + +-- ------------------------------------------------------------------------------------------------ contract +local Toml = { + name = "toml", + category = "data", + extensions = { "toml" }, + mime = { "application/toml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, dates = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, +-- so this stays low and the extension decides + + + +function Toml.sniff(r) +local head = r:peek(512) + if string.find(head, "%z") then + return 0 + end + for line in __iter(string.gmatch(head, "[^\n]+")) do + local l = (string.match(line, "^[ \t]*(.-)[ \t\r]*$") ) +if l ~= "" and string.sub(l, 1, 1) ~= "#" then + if string.match(l, "^%[%[?[%w_%-%.\"' ]+%]%]?$") or string.match(l, "^[%w_%-%.\"']+[ \t]*=[ \t]*[\"'%[{%dtf%+%-in]") then + return 0.2 + end + return 0 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Toml.decode(r, opts) +local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + local v, msg, at = Decode.decode(s, opts) + if v == nil then + local m = tostring(msg) + local code = (string.find(m, "unterminated", 1, true) and{Err.TRUNCATED }or{Err.CORRUPT +})[1] return nil, Err.new(code, m, at) + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Toml.encode(value, opts) +local s, msg = Encode.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Toml +end +__FILES["data/toml/Decode"] = function() +local __compat = __compat local utf8, __iter = __compat.utf8, __compat.__iter --!strict +-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with +-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control +-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and +-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +local Text = __include("codecs/text/Text") +local Types = __include("Types") + +local Decode = {} + +local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char + + + + + +local utf8char = Text.utf8char + +local ESC= { [98] = "\b", [116] = "\t", [110] = "\n", [102] = "\f", [114] = "\r", [34] = '"', [92] = "\\" } + +-- digits with single underscores between them +local function digitsOk(d, class) +return d ~= "" and not find(d, "__", 1, true) and byte(d, 1) ~= 95 and byte(d, #d) ~= 95 and find(d, "^[" .. class .. "_]+$") ~= nil +end + +function Decode.decode(s, opts) +local bigStrings = opts ~= nil and opts.bigInts == "string" + local errMsg= "" + local errAt = 0 + local function fail(msg, at) +errMsg, errAt = msg, at - 1 + return nil + end + + -- input checks: BOM, UTF-8, control characters, bare CR + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + do + local bad = find(s, "[%z\1-\8\11\12\14-\31\127]") + if bad then + return nil, "control character", bad - 1 + end + local cr = find(s, "\r[^\n]") or ((byte(s, #s) == 13 and((#s ))or(nil))) + if cr then + return nil, "carriage return without a line feed", cr - 1 + end + if find(s, "[\128-\255]") then + if not utf8.len(s) then + return nil, "invalid UTF-8", 0 + end + local sur = find(s, "\237[\160-\191]") + if sur then + return nil, "invalid UTF-8 (surrogate)", sur - 1 + end + end + if find(s, "\r", 1, true) then + s = gsub(s, "\r\n", "\n") + end + end + local n = #s + + -- table bookkeeping: kind = "explicit" | "implicit" | "dotted" | "inline"; section = where dotted tables were made + local kinds= {} + local sections= {} + local aot= {} -- arrays of tables ([[x]]); other arrays are static + local arrays= {} + local section = 0 + local building= nil -- tables created inside the inline table being parsed (frozen when it closes) + + local function newTable(kind) +local t = Types.object({}, {}) + kinds[t] = kind + if building then + table.insert(building, t) + end + return t + end + + local function ws(i) +return (match(s, "^[ \t]*()", i) ) +end + -- whitespace, newlines and comments (inside arrays) + local function wsnl(i) +while true do + i = (match(s, "^[ \t\n]*()", i) ) +if byte(s, i) == 35 then + i = find(s, "\n", i, true) or (n + 1) + else + return i + end + end + end + + local function escape(p, parts) +local e = byte(s, p + 1) + local simple = (e and{ESC[e] }or{nil +})[1] if simple then + table.insert(parts, simple) + return p + 2 + elseif e == 117 or e == 85 then + local len = e == 117 and 4 or 8 + local h = match(s, "^" .. string.rep("%x", len), p + 2) + if not h then + return fail("bad unicode escape", p) + end + local cp = (tonumber(h, 16) ) +if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + return fail("unicode escape is not a scalar value", p) + end + table.insert(parts, utf8char(cp)) + return p + 2 + len + end + return fail("bad escape", p) + end + + -- strings: value, next | nil + local function basic(i) +local parts = {} + local j = i + 1 + while true do + local p = find(s, '["\\\n]', j) + if not p or byte(s, p) == 10 then + return fail("unterminated string", p or n + 1), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + return table.concat(parts), p + 1 + end + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + local function multiBasic(i) +local j = i + 3 + if byte(s, j) == 10 then + j =j+ 1 + end + local parts = {} + while true do + local p = find(s, '["\\]', j) + if not p then + return fail("unterminated multi-line string", i), 0 + end + table.insert(parts, sub(s, j, p - 1)) + if byte(s, p) == 34 then + if sub(s, p, p + 2) == '"""' then + local q = p + 3 + local extra = 0 + while byte(s, q) == 34 and extra < 2 do + extra =extra+ 1 + q =q+ 1 + end + if byte(s, q) == 34 then + return fail("too many quotes", q), 0 + end + table.insert(parts, string.rep('"', extra)) + return table.concat(parts), q + end + table.insert(parts, '"') + j = p + 1 + else + local k = match(s, "^\\[ \t]*\n[ \t\n]*()", p) + if k then + j = k +else + local nj = escape(p, parts) + if not nj then + return nil, 0 + end + j = nj + end + end + end + end + local function literal(i) +local e = find(s, "['\n]", i + 1) + if not e or byte(s, e) == 10 then + return fail("unterminated literal string", e or n + 1), 0 + end + return sub(s, i + 1, e - 1), e + 1 + end + local function multiLiteral(i) +local j = i + 3 + if byte(s, j) == 10 then + j =j+ 1 + end + local e = find(s, "'''", j, true) + if not e then + return fail("unterminated multi-line literal string", i), 0 + end + local q = e + 3 + local extra = 0 + while byte(s, q) == 39 and extra < 2 do + extra =extra+ 1 + q =q+ 1 + end + if byte(s, q) == 39 then + return fail("too many quotes", q), 0 + end + return sub(s, j, e - 1) .. string.rep("'", extra), q + end + + -- a (dotted) key: { parts }, next | nil + local function key(i) +local keys= {} + while true do + i = ws(i) + local c = byte(s, i) + local k +if c == 34 then + if sub(s, i, i + 2) == '"""' then + return fail("multi-line string as a key", i), 0 + end + k, i = basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return fail("multi-line string as a key", i), 0 + end + k, i = literal(i) + else + k = match(s, "^[%w_%-]+", i) + if k then + i =i+ #k + else + return fail("expected a key", i), 0 + end + end + if k == nil then + return nil, 0 + end + table.insert(keys, k ) + i = ws(i) + if byte(s, i) == 46 then + i =i+ 1 + else + return keys, i + end + end + end + + -- numbers and datetimes + local function number(i) +local tok = match(s, "^[%+%-]?[%w_%.]+", i) + if not tok then + return fail("expected a value", i), 0 + end + local last = byte(tok, #tok) + if (last == 101 or last == 69) and not find(tok, "^[%+%-]?0[xob]") then + local ext = match(s, "^[%+%-][%w_]*", i + #tok) + if ext then + tok =tok.. ext + end + end + local nexti = i + #tok + local sign, body = match(tok, "^([%+%-]?)(.*)$") + if body == "inf" or body == "nan" then + return (body == "nan" and 0 / 0 or(sign == "-" and{(-math.huge )}or{math.huge})[1]), nexti + end + local prefix = sub(body , 1, 2) + if prefix == "0x" or prefix == "0o" or prefix == "0b" then + if sign ~= "" then + return fail("sign on a non-decimal integer", i), 0 + end + local d = sub(body , 3) + local class = prefix == "0x" and"%x" or(prefix == "0o" and"0-7" or"01" +) if not digitsOk(d, class) then + return fail("bad integer", i), 0 + end + d = gsub(gsub(d, "_", ""), "^0+", "") + local over = (prefix == "0x" and{#d > 16 or (#d == 16 and ((tonumber(sub(d, 1, 1), 16) )) >= 8) +}or{(prefix == "0o" and{(#d > 21 +)}or{(#d > 63 +)})[1]})[1] if over then + return fail("integer out of 64-bit range", i), 0 + end + if d == "" then + return 0, nexti + end + local v = (tonumber(d, prefix == "0x" and 16 or(prefix == "0o" and 8 or 2)) ) +if bigStrings and v >= 9007199254740992 then + return prefix .. d, nexti + end + return v, nexti + end + local ip, rest = match(body , "^([%d_]+)(.*)$") + if not ip or not digitsOk(ip, "%d") then + return fail("bad number", i), 0 + end + local digits = gsub(ip, "_", "") + if #digits > 1 and byte(digits, 1) == 48 then + return fail("leading zero", i), 0 + end + if rest == "" then + local limit = sign == "-" and"9223372036854775808" or"9223372036854775807" + if #digits > 19 or (#digits == 19 and digits > limit) then + return fail("integer out of 64-bit range", i), 0 + end + local v = (tonumber(digits) ) +if bigStrings and v >= 9007199254740992 then + return (sign == "-" and"-" or"") .. digits, nexti + end + return (sign == "-" and{(-v )}or{v})[1], nexti + end + local text= (sign ) .. digits + local frac, r2 = match(rest , "^%.([%d_]*)(.*)$") + if frac then + if not digitsOk(frac, "%d") then + return fail("bad fraction", i), 0 + end + text =text.. "." .. gsub(frac, "_", "") + rest = r2 + end + if rest ~= "" then + local es, ed = match(rest , "^[eE]([%+%-]?)([%d_]*)$") + if not es or not digitsOk(ed , "%d") then + return fail("bad float", i), 0 + end + text =text.. "e" .. es .. gsub(ed , "_", "") + end + local v = tonumber(text) + if v == nil then + return fail("bad float", i), 0 + end + return v, nexti + end + + local function datetime(i) +local j = i + if match(s, "^%d%d%d%d%-%d%d%-%d%d", i) then + j = i + 10 + local c = byte(s, j) + if (c == 84 or c == 116 or c == 32) and match(s, "^%d%d:", j + 1) then + j =j+ 1 + elseif c == 84 or c == 116 then + return fail("bad datetime", i), 0 + else + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad date", i), 0 + end + return d, j + end + end + local t = match(s, "^%d%d:%d%d:%d%d", j) + if not t then + return fail("bad time (seconds are required)", j), 0 + end + j =j+ 8 + local frac = match(s, "^%.%d+", j) + if frac then + j =j+ #frac + elseif byte(s, j) == 46 then + return fail("bad fraction", j), 0 + end + if j - i > 19 or match(s, "^%d%d%d%d%-", i) then + local off = match(s, "^[Zz]", j) or match(s, "^[%+%-]%d%d:%d%d", j) + if off then + j =j+ #off + end + end + local d = Types.Date.parse(sub(s, i, j - 1)) + if not d then + return fail("bad datetime", i), 0 + end + return d, j + end + + local value +local assign + +local function array(i) +local arr = {} + arrays[arr] = true + i =i+ 1 + while true do + i = wsnl(i) + local c = byte(s, i) + if c == 93 then + return arr, i + 1 + elseif c == nil then + return fail("unterminated array", i), 0 + end + local v, ni = value(i) + if v == nil then + return nil, 0 + end + table.insert(arr, v) + i = wsnl(ni) + c = byte(s, i) + if c == 44 then + i =i+ 1 + elseif c == 93 then + return arr, i + 1 + else + return fail(c == nil and"unterminated array" or"expected ',' or ']'", i), 0 + end + end + end + + local function inline(i) +local outer = building + local mine = {} + building = mine + local t = newTable("inline") + section =section+ 1 + local sid = section + i = ws(i + 1) + if byte(s, i) == 125 then + building = outer + return t, i + 1 + end + while true do + local keys, ni = key(i) + if not keys then + return nil, 0 + end + i = ws(ni) + if byte(s, i) ~= 61 then + return fail("expected '='", i), 0 + end + local v, vi = value(ws(i + 1)) + if v == nil then + return nil, 0 + end + if not assign(t, keys, v, sid, i) then + return nil, 0 + end + i = ws(vi) + local c = byte(s, i) + if c == 44 then + i = ws(i + 1) + if byte(s, i) == 125 then + return fail("trailing comma in an inline table", i), 0 + end + elseif c == 125 then + break + else + return fail(c == 10 and"newline in an inline table" or"expected ',' or '}'", i), 0 + end + end + for _, x in __iter(mine) do + kinds[x] = "inline" + end + building = outer + if outer then + for _, x in __iter(mine) do + table.insert(outer, x) + end + end + return t, i + 1 + end + + function value(i) +local c = byte(s, i) + if c == 34 then + if sub(s, i, i + 2) == '"""' then + return multiBasic(i) + end + return basic(i) + elseif c == 39 then + if sub(s, i, i + 2) == "'''" then + return multiLiteral(i) + end + return literal(i) + elseif c == 116 then + if match(s, "^true", i) and not match(s, "^[%w_%-]", i + 4) then + return true, i + 4 + end + elseif c == 102 then + if match(s, "^false", i) and not match(s, "^[%w_%-]", i + 5) then + return false, i + 5 + end + elseif c == 91 then + return array(i) + elseif c == 123 then + return inline(i) + elseif c and ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 105 or c == 110) then + if match(s, "^%d%d%d%d%-", i) or match(s, "^%d%d:", i) then + return datetime(i) + end + return number(i) + end + return fail((c == nil or c == 10 )and"expected a value" or"bad value", i), 0 + end + + function assign(tbl, keys, v, sid, at) +local t = tbl + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("dotted") + sections[nt] = sid + Types.set(t, k, nt) + t = nt + elseif kinds[x] == "implicit" or (kinds[x] == "dotted" and sections[x] == sid) then + t = x + else + fail("cannot add to " .. k .. " with a dotted key (already defined)", at) + return false + end + end + local k = keys[#keys] + if t[k] ~= nil then + fail("duplicate key " .. k, at) + return false + end + Types.set(t, k, v) + return true + end + + -- after a key / value or a header: spaces, an optional comment, then a newline or the end + local function eol(i) +i = ws(i) + local c = byte(s, i) + if c == 35 then + return find(s, "\n", i, true) or (n + 1) + elseif c == 10 or c == nil then + return i + end + return fail("expected the end of the line", i) + end + + local root = newTable("explicit") + local cur = root + local i = 1 + while true do + i = ws(i) + local c = byte(s, i) + if c == nil then + break + elseif c == 10 then + i =i+ 1 + elseif c == 35 then + i = find(s, "\n", i, true) or (n + 1) + elseif c == 91 then + local at = i + local isAot = byte(s, i + 1) == 91 + local keys, ni = key(i + (isAot and 2 or 1)) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if isAot then + if sub(s, ni, ni + 1) ~= "]]" then + return nil, "expected ']]'", ni - 1 + end + ni =ni+ 2 + else + if byte(s, ni) ~= 93 then + return nil, "expected ']'", ni - 1 + end + ni =ni+ 1 + end + -- walk to the parent + local t = root + for j = 1, #keys - 1 do + local k = keys[j] + local x = t[k] + if x == nil then + local nt = newTable("implicit") + Types.set(t, k, nt) + t = nt + elseif kinds[x] and kinds[x] ~= "inline" then + t = x + elseif aot[x] then + t = x[#x] + else + return nil, "cannot define a table under " .. k .. " (already defined)", at - 1 + end + end + local k = keys[#keys] + local x = t[k] + if isAot then + local arr = x + if arr == nil then + arr = {} + aot[arr] = true + Types.set(t, k, arr) + elseif not aot[arr] then + return nil, "cannot define an array of tables " .. k .. " (already defined)", at - 1 + end + local nt = newTable("explicit") + table.insert(arr, nt) + cur = nt + else + if x == nil then + local nt = newTable("explicit") + Types.set(t, k, nt) + cur = nt + elseif kinds[x] == "implicit" then + kinds[x] = "explicit" + cur = x + else + return nil, "table " .. k .. " defined twice", at - 1 + end + end + section =section+ 1 + local e = eol(ni) + if not e then + return nil, errMsg, errAt + end + i = e + else + local at = i + local keys, ni = key(i) + if not keys then + return nil, errMsg, errAt + end + ni = ws(ni) + if byte(s, ni) ~= 61 then + return nil, "expected '='", ni - 1 + end + local v, vi = value(ws(ni + 1)) + if v == nil then + return nil, errMsg, errAt + end + if not assign(cur, keys, v, section, at) then + return nil, errMsg, errAt + end + local e = eol(vi) + if not e then + return nil, errMsg, errAt + end + i = e + end + end + return root, nil, nil +end + +return Decode +end +__FILES["data/toml/Encode"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables +-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as +-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date +-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, +-- message. +local Types = __include("Types") +local Json = __include("codecs/text/Json") + +local Encode = {} + +local format, gsub, find = string.format, string.gsub, string.find + + + + + + +local ESC= { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } +for c = 0, 31 do + local ch = string.char(c) + if not ESC[ch] then + ESC[ch] = format("\\u%04X", c) + end +end + +local function quote(str) +return '"' .. gsub(str, '[%z\1-\31"\\\127]', ESC) .. '"' +end +Encode.quote = quote + +local function keyText(k) +if find(k, "^[%w_%-]+$") then + return k + end + return quote(k) +end + +-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays +local function isMap(t) +if Types.isObject(t) then + return true + end + local n = #t + if n == 0 then + return next(t) ~= nil + end + local count = 0 + for _ in next, t do + count =count+ 1 + end + return count ~= n +end + +local function isDate(v) +return Types.Date.is(v) +end + +-- an array of tables: non-empty, every element a map +local function isAot(v) +if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then + return false + end + for _, x in __iter(v) do + if type(x) ~= "table" or isDate(x) or not isMap(x) then + return false + end + end + return true +end + +local function keysOf(t) +local keys = Types.keys(t) + for _, k in __iter(keys) do + if type(k) ~= "string" then + return nil, "table key of type " .. type(k) + end + end + return keys , nil +end + + + +local inlineValue + +local function scalar(st, v) +local tv = type(v) + if v == Types.null then + st.err = "TOML has no null" + return nil + elseif tv == "string" then + return quote(v) + elseif tv == "boolean" then + return v and"true" or"false" + elseif tv == "number" then + if v ~= v then + return "nan" + elseif v == math.huge then + return "inf" + elseif v == -math.huge then + return "-inf" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 63 then + return format("%d", v) + end + local t = (Json.number(v) ) +if not find(t, "[%.eEn]") then + t =t.. ".0" + end + return t + elseif tv == "table" and isDate(v) then + return tostring(v) + elseif tv == "table" then + return inlineValue(st, v) + end + st.err = "cannot encode a " .. tv + return nil +end + +function inlineValue(st, v) +if st.seen[v] then + st.err = "a table contains itself" + return nil + end + st.seen[v] = true + local parts = {} + if isMap(v) then + local keys, kerr = keysOf(v) + if not keys then + st.err = kerr + return nil + end + for _, k in __iter(keys) do + local s = scalar(st, v[k]) + if not s then + return nil + end + table.insert(parts, keyText(k) .. " = " .. s) + end + st.seen[v] = nil + return #parts == 0 and"{}" or"{ " .. table.concat(parts, ", ") .. " }" + end + for i = 1, #v do + local s = scalar(st, v[i]) + if not s then + return nil + end + parts[i] = s + end + st.seen[v] = nil + return "[" .. table.concat(parts, ", ") .. "]" +end + +local function section(st, t, path, out, inlineAll, ind, depth) +if st.seen[t] then + st.err = "a table contains itself" + return false + end + st.seen[t] = true + local keys, kerr = keysOf(t) + if not keys then + st.err = kerr + return false + end + local pad = string.rep(ind, depth) + local subs = {} + for _, k in __iter(keys) do + local v = t[k] + if not inlineAll and type(v) == "table" and not isDate(v) and (isMap(v) or isAot(v)) then + table.insert(subs, k) + else + local s = scalar(st, v) + if not s then + return false + end + table.insert(out, pad .. keyText(k) .. " = " .. s .. "\n") + end + end + for _, k in __iter(subs) do + local v = t[k] + local p = (path == "" and"" or path .. ".") .. keyText(k) + if isMap(v) then + table.insert(out, (#out > 0 and"\n" or"") .. pad .. "[" .. p .. "]\n") + if not section(st, v, p, out, inlineAll, ind, depth + 1) then + return false + end + else + for _, el in __iter(v) do + table.insert(out, (#out > 0 and"\n" or"") .. pad .. "[[" .. p .. "]]\n") + if not section(st, el, p, out, inlineAll, ind, depth + 1) then + return false + end + end + end + end + st.seen[t] = nil + return true +end + +-- encode(t, opts) -> text | nil, message +function Encode.encode(t, opts) +if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then + return nil, "the top level must be a table with string keys" + end + local o= opts or {} + local ind = (type(o.indent) == "number" and{(string.rep(" ", o.indent) )}or{(type(o.indent) == "string" and{o.indent }or{"" +})[1]})[1] local st= { seen = {}, err = nil } + local out = {} + if not section(st, t, "", out, o.inline == true, ind, 0) then + return nil, st.err + end + return table.concat(out), nil +end + +return Encode +end +__FILES["data/xml"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: +-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not +-- supported: external entities / DTDs, validation. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local XmlFormat = { + name = "xml", + category = "data", + extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" }, + mime = { "application/xml", "text/xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" }, + caps = { decode = true, encode = true, namespaces = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + +function XmlFormat.sniff(r) +local head = Sniff.text(r, 64) + if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then + return 0.5 + end + if string.match(head, "^[ \t\r\n]*<[%a!]") then + return 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function XmlFormat.decode(r, opts) +return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function XmlFormat.encode(node, opts) +if type(node) ~= "table" or type(node.name) ~= "string" then + return nil, Err.new(Err.ARG, "expected an XmlNode") + end + local s, err = Xml.encode(node, opts) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return XmlFormat +end +__FILES["data/yaml"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / +-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as +-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null +-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. +-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). +-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; +-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("data/yaml/Parse") +local Emit = __include("data/yaml/Emit") + +-- ------------------------------------------------------------------------------------------------ contract +local Yaml = { + name = "yaml", + category = "data", + extensions = { "yaml", "yml" }, + mime = { "application/yaml", "application/x-yaml", "text/yaml" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" }, + caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + +function Yaml.sniff(r) +local head = r:peek(256) + if string.find(head, "%z") then + return 0 + end + if string.match(head, "^%%YAML ") then + return 0.9 + end + if string.match(head, "^%-%-%-[ \r\n]") then + return 0.5 + end + local line = string.match(head, "^[ \t\r\n]*([^\r\n]*)") + if line and (string.match(line, "^[%w_%-\"']+[%w_%- \"']*:[ ]") or string.match(line, "^[%w_%-]+:$") or string.match(line, "^%- ")) then + return 0.2 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err +function Yaml.decode(r, opts) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local docs, code, msg, at = Parse.run(text, opts) + if not docs then + return nil, Err.new(code, msg, at) + end + if opts and opts.all then + return docs, nil + end + local first = docs[1] + if first == nil then + return (opts and opts.null ~= nil and{opts.null }or{Types.null})[1], nil + end + return first, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) +function Yaml.encode(value, opts) +local s, err = Emit.encode(value, opts) + if not s then + return nil, Err.new(Err.ARG, err or "cannot encode") + end + return buffer.fromstring(s), nil +end + +return Yaml +end +__FILES["data/yaml/Emit"] = function() +local __compat = __compat local utf8, type, __iter = __compat.utf8, __compat.type, __compat.__iter --!strict +-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when +-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars +-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as +-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad +-- values (cycles, functions, collection keys) return nil, message. +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Parse = __include("data/yaml/Parse") + +local Emit = {} + + + + + + + + + +local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub + +local YAML11 = { + y = true, Y = true, yes = true, Yes = true, YES = true, n = true, N = true, no = true, No = true, NO = true, + on = true, On = true, ON = true, off = true, Off = true, OFF = true, +} + +local function number(x) +if x ~= x then + return ".nan" + elseif x == math.huge then + return ".inf" + elseif x == -math.huge then + return "-.inf" + elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then + if x == 0 and 1 / x < 0 then + return "-0.0" + end + return format("%d", x) + end + for _, f in __iter({ "%.15g", "%.16g", "%.17g" }) do + local t = format(f, x) + if tonumber(t) == x then + if not find(t, "[%.eEn]") then + t =t.. ".0" + end + return t + end + end + return format("%.17g", x) +end + +local DQ= { + ["\\"] = "\\\\", + ['"'] = '\\"', + ["\n"] = "\\n", + ["\t"] = "\\t", + ["\r"] = "\\r", + ["\0"] = "\\0", + ["\27"] = "\\e", +} +local function dquote(s) +s = gsub(s, '[%z\1-\31\127\\"]', function(c) +return DQ[c] or format("\\x%02x", byte(c)) + end) + -- the Unicode line / paragraph separators and NEL would be folded as line breaks: escape them + s = gsub(s, "\226\128\168", "\\L") + s = gsub(s, "\226\128\169", "\\P") + s = gsub(s, "\194\133", "\\N") + return '"' .. s .. '"' +end + +local function plainOk(s) +if s == "" or YAML11[s] then + return false + end + if Parse.resolve(s, Types.null) ~= s then + return false + end + if find(s, "^[%s]") or find(s, "[%s]$") then + return false + end + if find(s, "^[%-%?:,%[%]{}#&%*!|>'\"%%@`]") or find(s, "^%.%.%.") then + return false + end + if find(s, ": ", 1, true) or find(s, " #", 1, true) or find(s, ":$") or find(s, "[%z\1-\31\127]") then + return false + end + if find(s, "\226\128\168") or find(s, "\226\128\169") or find(s, "\194\133") or find(s, "\239\187\191") then + return false + end + -- not invalid UTF-8 (the reader treats the text as bytes, but other tools will not) + if find(s, "[\128-\255]") and not utf8.len(s) then + return false + end + return true +end + +-- a string as a scalar on a line at indentation ind (for block scalars) +local function str(s, ind, key) +if plainOk(s) then + return s + end + if not key and find(s, "\n", 1, true) and not find(s, "[%z\1-\9\11-\31\127]") and not find(s, "[ ]\n") and not find(s, " $") + and not find(s, "^[ \n]") and not find(s, "\226\128[\168\169]") and not find(s, "\194\133") and (not find(s, "[\128-\255]") or utf8.len(s)) + then + local trailing = #((string.match(s, "\n*$") )) + local body = string.sub(s, 1, #s - trailing) + local chomp = trailing == 0 and"-" or(trailing == 1 and"" or"+" +) local lines = string.split(body, "\n") + local out = { "|" .. chomp } + for _, l in __iter(lines) do + table.insert(out, l == "" and"" or ind .. l) + end + for _ = 2, trailing do + table.insert(out, "") + end + return table.concat(out, "\n") + end + return dquote(s) +end + +local isArray = Types.isArray + +local keyLess = Types.keyLess + +-- count references to tables (anchors for those seen twice); false on a cycle + + +local function count(st, v, onStack) +if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then + return true + end + if onStack[v] then + st.err = "a cycle (YAML aliases cannot point at their own ancestors here)" + return false + end + local r = st.refs[v] + st.refs[v] = (r or 0) + 1 + if r then + return true + end + onStack[v] = true + for k, x in next, v do + if not count(st, k, onStack) or not count(st, x, onStack) then + return false + end + end + onStack[v] = nil + return true +end + +-- scalar text for a non-collection value, or nil +local function scalar(st, v, ind, key) +local tv = type(v) + if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then + return "null" + elseif tv == "boolean" then + return v and"true" or"false" + elseif tv == "number" then + return number(v) + elseif tv == "string" then + return str(v, ind, key) + elseif tv == "buffer" then + return "!!binary " .. Base64.encode(v) + elseif tv == "table" and Types.Date.is(v) then + return tostring(v) + end + return nil +end + +local write +-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) + +function write(st, v, depth) +local ind = string.rep(" ", st.step * (depth + 1)) + local s = scalar(st, v, ind, false) + if s then + return " " .. s + end + if type(v) ~= "table" then + st.err = "cannot write a " .. type(v) + return nil + end + local prefix = "" + if st.refs[v] and st.refs[v] > 1 then + local a = st.anchors[v] + if a then + return " *" .. a + end + st.nextId =st.nextId+ 1 + a = "id" .. format("%03d", st.nextId) + st.anchors[v] = a + prefix = " &" .. a + end + local pad = string.rep(" ", st.step * depth) + if isArray(v) and not Types.isObject(v) then + if #v == 0 then + return prefix .. " []" + end + local parts = {} + for _, x in __iter(v) do + local t = write(st, x, depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. "-" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") + end + local keys + if Types.isObject(v) then + keys = Types.keys(v) + else + keys = {} + for k in next, v do + table.insert(keys, k) + end + if st.sort then + table.sort(keys, keyLess) + end + end + if #keys == 0 then + return prefix .. " {}" + end + local parts = {} + for _, k in __iter(keys) do + local ks = scalar(st, k, "", true) + if not ks or (type(k) == "table" and not Types.Date.is(k) and k ~= Types.null) then + st.err = "mapping keys must be scalars" + return nil + end + local t = write(st, v[k], depth + 1) + if not t then + return nil + end + table.insert(parts, pad .. ks .. ":" .. t) + end + return prefix .. "\n" .. table.concat(parts, "\n") +end + +local function document(st, v) +local t = write(st, v, 0) + if not t then + return nil + end + -- the top level: drop the separator write() put before the first line + if string.sub(t, 1, 1) == "\n" then + return string.sub(t, 2) + end + local body = string.sub(t, 2) + if string.sub(body, 1, 1) == "&" then + -- "&id001\n- a": an anchored top-level collection + return body + end + return body +end + +-- encode(v, opts) -> text | nil, message +function Emit.encode(v, opts) +local o= opts or {} + local st= { + out = {}, + step = math.clamp(math.floor(o.indent or 2), 1, 10), + sort = o.sortKeys ~= false, + null = o.null, + refs = {}, + anchors = {}, + nextId = 0, + err = nil, + } + local docs = (o.all and{v }or{{ v } +})[1] if type(docs) ~= "table" then + return nil, "all: expected an array of documents" + end + local parts = {} + for i, d in __iter(docs) do + st.refs, st.anchors = {}, {} + if not count(st, d, {}) then + return nil, st.err + end + local t = document(st, d) + if not t then + return nil, st.err + end + local start = i > 1 or o.explicitStart + if start then + -- a scalar / [] / {} can share the "---" line; a collection starts on the next one + local block = type(d) == "table" and d ~= Types.null and not Types.Date.is(d) and next(d) ~= nil + local sep = block and not string.find(t, "^&") and"---\n" or"--- " + table.insert(parts, sep .. t .. "\n") + else + table.insert(parts, t .. "\n") + end + end + return table.concat(parts), nil +end + +return Emit +end +__FILES["data/yaml/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): +-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with +-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared +-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless +-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core +-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a +-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +local Text = __include("codecs/text/Text") +local Types = __include("Types") +local Base64 = __include("core/Base64") + +local Parse = {} + +local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char + + + + + + + + + + + + + + + + + + + + + + + +local CORE = "tag:yaml.org,2002:" + +local function raise(code, msg, p) + error({ yamlErr = true, code = code, msg = msg, at = p - 1 }, 0) +end +local function corrupt(msg, p) + raise("CORRUPT", msg, p) +end + +-- ------------------------------------------------------------------------------------------------ helpers +local function col(s, p) +local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q =q- 1 + end + return p - q +end + +local function isWsEnd(c) +return c == nil or c == 32 or c == 9 or c == 10 +end + +local function docMarker(s, p) +if p ~= 1 and byte(s, p - 1) ~= 10 then + return false + end + local m = sub(s, p, p + 2) + return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) +end + +-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) +local function skip(s, p) +local n = #s + while p <= n do + local c = byte(s, p) + if c == 32 or c == 9 or c == 10 then + p =p+ 1 + elseif c == 35 and (p == 1 or isWsEnd(byte(s, p - 1))) then + local e = find(s, "\n", p, true) + if not e then + return n + 1 + end + p = e + 1 + else + return p + end + end + return p +end + +-- the number of leading spaces on p's line, and whether a tab comes before p on it +local function lineIndent(s, p) +local q = p + while q > 1 and byte(s, q - 1) ~= 10 do + q =q- 1 + end + local sp = ((match(s, "^ *()", q) )) - q + return sp, find(sub(s, q, p - 1), "\t", 1, true) ~= nil +end + +-- block content at p on a new line must not be indented with tabs: a tab before p is an error when the spaces before +-- it do not already indent the line past ind (siblings: pass ind = their column - 1... any tab is an error) +local function noTabs(s, p, ind) + local sp, tab = lineIndent(s, p) + if tab and (ind == nil or sp <= ind) then + error({ yamlErr = true, code = "CORRUPT", msg = "tab in indentation", at = p - 1 }, 0) + end +end + +-- skip spaces / tabs on the line +local function skipLine(s, p) +return (match(s, "^[ \t]*()", p) ) +end + +-- after a node on its line: only spaces and a comment may follow before the line break +local function endOfLine(s, p) +local q = skipLine(s, p) + local c = byte(s, q) + return c == nil or c == 10 or (c == 35 and q > p) +end + +local utf8char = Text.utf8char + +-- ------------------------------------------------------------------------------------------------ resolution +-- the core schema: a plain scalar's value +function Parse.resolve(t, nullv) +if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then + return nullv + end + local c = byte(t) + if c == 116 or c == 84 or c == 102 or c == 70 then + if t == "true" or t == "True" or t == "TRUE" then + return true + elseif t == "false" or t == "False" or t == "FALSE" then + return false + end + return t + end + if not ((c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46) then + return t + end + if match(t, "^[-+]?%d+$") then + return tonumber((c == 43 and{(sub(t, 2) )}or{t})[1]) + end + local o = match(t, "^0o([0-7]+)$") + if o then + return tonumber(o, 8) + end + local x = match(t, "^0x(%x+)$") + if x then + return tonumber(x, 16) + end + if match(t, "^[-+]?%d+%.?%d*$") or match(t, "^[-+]?%.%d+$") or match(t, "^[-+]?%d+%.?%d*[eE][-+]?%d+$") or match(t, "^[-+]?%.%d+[eE][-+]?%d+$") then + local v = tonumber((c == 43 and{(sub(t, 2) )}or{t})[1]) + if v then + return v + end + end + local inf = match(t, "^([-+]?)%.[iI][nN][fF]$") + if inf and (t == inf .. ".inf" or t == inf .. ".Inf" or t == inf .. ".INF") then + return (inf == "-" and{(-math.huge )}or{math.huge +})[1] end + if t == ".nan" or t == ".NaN" or t == ".NAN" then + return 0 / 0 + end + return t +end + +local function base64(t) +return (Base64.decode(t)) +end + +-- a scalar's value given its tag (nil = untagged, "!" = non-specific) +local function scalarValue(st, raw, plain, tag, p) +if tag == nil then + return (plain and{(Parse.resolve(raw, st.null) )}or{raw +})[1] end + if tag == "!" or tag == CORE .. "str" then + return raw + end + if sub(tag, 1, #CORE) == CORE then + local kind = sub(tag, #CORE + 1) + local v = Parse.resolve(raw, st.null) + if kind == "null" then + if v ~= st.null then + corrupt("bad !!null " .. raw, p) + end + return v + elseif kind == "bool" then + if type(v) ~= "boolean" then + corrupt("bad !!bool " .. raw, p) + end + return v + elseif kind == "int" then + if type(v) ~= "number" or not (match(raw, "^[-+]?%d+$") or match(raw, "^0[ox]")) then + corrupt("bad !!int " .. raw, p) + end + return v + elseif kind == "float" then + if type(v) ~= "number" then + corrupt("bad !!float " .. raw, p) + end + return v + elseif kind == "binary" then + local b = base64(raw) + if not b then + corrupt("bad !!binary data", p) + end + return b + elseif kind == "timestamp" then + local d = Types.Date.parse(raw) + if not d then + corrupt("bad !!timestamp " .. raw, p) + end + return d + elseif kind == "map" or kind == "seq" then + corrupt("!!" .. kind .. " on a scalar", p) + end + end + if st.ignoreTags then + return (plain and{(Parse.resolve(raw, st.null) )}or{raw +})[1] end + raise("UNSUPPORTED", "tag " .. tag, p) + return nil +end + +local function collectionTag(st, tag, kind, p) + if tag == nil or tag == "!" or tag == CORE .. kind then + return + end + if sub(tag, 1, #CORE) == CORE then + local k = sub(tag, #CORE + 1) + if k == "map" or k == "seq" or k == "str" or k == "int" or k == "float" or k == "bool" or k == "null" or k == "binary" then + corrupt("!!" .. k .. " on a " .. kind, p) + end + end + if not st.ignoreTags then + raise("UNSUPPORTED", "tag " .. tag, p) + end +end + +-- expansion size of a value (nodes), memoized +local function size(st, v) +if type(v) ~= "table" or v == st.null then + return 1 + end + local m = st.sizes[v] + if m then + return m + end + local total = 1 + for k, x in next, v do + total =total+ (size(st, k) + size(st, x) +) end + st.sizes[v] = total + return total +end +-- ------------------------------------------------------------------------------------------------ properties +-- anchors / tags at p -> props?, the position after them (and the spaces after them) + + + +local function properties(st, p) +local s = st.s + local props= nil + while true do + local c = byte(s, p) + if c == 38 then -- & + local name = match(s, "^&([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad anchor", p) + end + local pr= props or { at = p } + props = pr + if pr.anchor then + corrupt("two anchors on one node", p) + end + pr.anchor = name + p = skipLine(s, p + 1 + #(name )) + elseif c == 33 then -- ! + local pr= props or { at = p } + props = pr + if pr.tag then + corrupt("two tags on one node", p) + end + local tag +if byte(s, p + 1) == 60 then -- !<verbatim> + local v = match(s, "^!<([^>%s]+)>", p) + if not v then + corrupt("bad verbatim tag", p) + end + tag = v +p =p+ (#tag + 3 +) else + local handle, suffix = match(s, "^(![%w%-]*!)([^%s,%[%]{}]*)", p) + if handle then + local prefix = st.handles[handle] + if not prefix then + corrupt("undefined tag handle " .. handle, p) + end + if suffix == "" then + corrupt("empty tag", p) + end + tag = prefix .. string.gsub(suffix , "%%(%x%x)", function(h) +return char((tonumber(h, 16) )) + end) + else + local sfx = (match(s, "^!([^%s,%[%]{}]*)", p) ) +if sfx == "" then + tag = "!" + else + tag = st.handles["!"] .. sfx + end + end + p =p+ #((match(s, "^![^%s,%[%]{}]*", p) )) + end + pr.tag = tag + if not isWsEnd(byte(s, p)) and byte(s, p) ~= 44 and byte(s, p) ~= 93 and byte(s, p) ~= 125 then + corrupt("bad tag", p) + end + p = skipLine(s, p) + else + return props, p + end + end +end + +local function finish(st, props, v) +if props and props.anchor then + st.anchors[props.anchor] = v + end + return v +end + +local function alias(st, p) +local s = st.s + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + corrupt("bad alias", p) + end + local v = st.anchors[name ] + if v == nil then + corrupt("undefined alias *" .. (name ), p) + end + st.aliasNodes =st.aliasNodes+ size(st, v) + if st.aliasNodes > st.maxAlias then + raise("LIMIT", "alias expansion over " .. st.maxAlias .. " nodes", p) + end + return v, p + 1 + #(name ) +end + +-- ------------------------------------------------------------------------------------------------ scalars +-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. +-- Lines holding only spaces / tabs count as empty. +local function fold(s, p) +local empties = 0 + local q = p + 1 + while true do + local r = skipLine(s, q) + if byte(s, r) == 10 then + empties =empties+ 1 + q = r + 1 + else + return (empties == 0 and" " or string.rep("\n", empties)), q + end + end +end + +local ESC= { + [48] = "\0", + [97] = "\a", + [98] = "\b", + [116] = "\t", + [9] = "\t", + [110] = "\n", + [118] = "\v", + [102] = "\f", + [114] = "\r", + [101] = "\27", + [32] = " ", + [34] = '"', + [47] = "/", + [92] = "\\", + [78] = "\194\133", + [95] = "\194\160", + [76] = "\226\128\168", + [80] = "\226\128\169", +} + +-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote +local function quoted(st, p, ind) +local s = st.s + local dq = byte(s, p) == 34 + local parts= {} + local i = p + 1 + local stop = dq and'[\\"\n]' or"['\n]" + while true do + local j = find(s, stop, i) + if not j then + raise("TRUNCATED", "unterminated quoted scalar", p) + end + local jj = j +local seg = sub(s, i, jj - 1) + local c = byte(s, jj) + if c == 10 then + table.insert(parts, (string.gsub(seg, "[ \t]+$", ""))) + local f, q = fold(s, jj) + if docMarker(s, q) then + corrupt("document marker inside a quoted scalar", q) + end + if ind >= 0 and ((match(s, "^ *()", q) )) - q <= ind then + corrupt("a quoted scalar's continuation line is not indented", q) + end + table.insert(parts, f) + i = skipLine(s, q) + elseif dq and c == 92 then + table.insert(parts, seg) + local e = byte(s, jj + 1) + if e == 10 then -- escaped line break: joined without a space + local r = jj + 2 + while true do + local q = skipLine(s, r) + if byte(s, q) == 10 then + table.insert(parts, "\n") + r = q + 1 + else + i = q + break + end + end + elseif e == 120 or e == 117 or e == 85 then + local len = e == 120 and 2 or(e == 117 and 4 or 8 +) local h = sub(s, jj + 2, jj + 1 + len) + if #h ~= len or not match(h, "^%x+$") then + corrupt("bad escape", jj) + end + local cp = (tonumber(h, 16) ) +if cp > 0x10FFFF then + corrupt("bad escape", jj) + end + table.insert(parts, utf8char(cp)) + i = jj + 2 + len + else + local r = (e and{ESC[e] }or{nil +})[1] if not r then + corrupt("bad escape", jj) + end + table.insert(parts, r ) + i = jj + 2 + end + elseif not dq and byte(s, jj + 1) == 39 then + table.insert(parts, seg .. "'") + i = jj + 2 + else + table.insert(parts, seg) + return table.concat(parts), jj + 1 + end + end +end + +-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind +-- (block context); flow: the flow-context rules (stops at , [ ] { }). +local function plain(st, p, ind, flow) +local s = st.s + local parts= {} + local i = p + local lastEnd = p + while true do + -- one line's worth + local j = i + local stopAt = nil + while true do + local c = byte(s, j) + if c == nil or c == 10 then + break + elseif c == 58 then -- : + local d = byte(s, j + 1) + if isWsEnd(d) or (flow and (d == 44 or d == 91 or d == 93 or d == 123 or d == 125)) then + stopAt = j + break + end + elseif c == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + stopAt = j + break + elseif flow and (c == 44 or c == 91 or c == 93 or c == 123 or c == 125) then + stopAt = j + break + end + j =j+ 1 + end + local seg = string.gsub(sub(s, i, j - 1), "[ \t]+$", "") + table.insert(parts, seg) + lastEnd = i + #seg + if stopAt or byte(s, j) == nil then + return table.concat(parts), lastEnd + end + -- a continuation line? + local f, q = fold(s, j) + local r = skipLine(s, q) + local c = byte(s, r) + if c == nil or docMarker(s, q) or c == 35 or (not flow and ((match(s, "^ *()", q) )) - q <= ind) then + return table.concat(parts), lastEnd + end + if flow and (c == 44 or c == 93 or c == 125 or (c == 58 and isWsEnd(byte(s, r + 1)))) then + return table.concat(parts), lastEnd + end + table.insert(parts, f) + i = r + end +end + +-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it +local function blockScalar(st, p, ind) +local s = st.s + local folded = byte(s, p) == 62 + local q = p + 1 + local explicit= nil + local chomp = "clip" + for _ = 1, 2 do + local c = byte(s, q) + if c and c >= 49 and c <= 57 and not explicit then + explicit = c - 48 + q =q+ 1 + elseif (c == 43 or c == 45) and chomp == "clip" then + chomp = c == 43 and"keep" or"strip" + q =q+ 1 + end + end + if not endOfLine(s, q) then + corrupt("bad block scalar header", q) + end + local nl = find(s, "\n", q, true) + local lines= {} + local trailing = 0 -- empty lines after the last content line + if not nl then + return "", #s + 1 + end + local ls = (nl ) + 1 + local indent +if explicit then + indent = math.max(ind + explicit, 0) -- n + the indicator (n = -1 at the top level) + else + -- auto-detect: the first non-empty line; leading empty lines may not be longer + local maxEmpty = 0 + local r = ls + indent = -1 + while true do + local sp = ((match(s, "^ *()", r) )) - r + local c = byte(s, r + sp) + if c == 10 then + maxEmpty = math.max(maxEmpty, sp) + r = r + sp + 1 + elseif c == nil then + maxEmpty = math.max(maxEmpty, sp) + indent = math.max(maxEmpty, ind + 1) + break + else + if docMarker(s, r) then + indent = math.max(maxEmpty, ind + 1) + break + end + indent = sp + if sp < maxEmpty then + corrupt("leading empty lines indented more than the block scalar", r) + end + break + end + end + if indent <= ind then + indent = ind + 1 + end + end + -- the lines + local r = ls + local pendingEmpty = 0 + local endPos = ls + while r <= #s do + if docMarker(s, r) then + break + end + local sp = ((match(s, "^ *()", r) )) - r + local e = find(s, "\n", r, true) or (#s + 1) + if sp >= indent then + local text = sub(s, r + indent, e - 1) + for _ = 1, pendingEmpty do + table.insert(lines, "") + end + pendingEmpty = 0 + table.insert(lines, text) + elseif r + sp == e then + pendingEmpty =pendingEmpty+ 1 + else + if byte(s, r + sp) == 9 then + corrupt("tab in block scalar indentation", r + sp) + end + break + end + r = e + 1 + endPos = math.min(r, #s + 1) + end + trailing = pendingEmpty + local body +if #lines == 0 then + body = "" + elseif not folded then + body = table.concat(lines, "\n") + else + local out= {} + local prevMore = false + local empties = 0 + local first = true + for _, l in __iter(lines) do + if l == "" then + empties =empties+ 1 + else + local more = byte(l) == 32 or byte(l) == 9 + if first then + table.insert(out, string.rep("\n", empties)) + elseif empties == 0 then + table.insert(out, (more or prevMore )and"\n" or" ") + else + table.insert(out, string.rep("\n", ((more or prevMore )and((empties + 1 ))or(empties)))) + end + table.insert(out, l) + first = false + prevMore = more + empties = 0 + end + end + trailing =trailing+ empties -- empty lines after the last content line (or all of them) + body = table.concat(out) + end + if not folded then + -- literal: trailing "" lines inside `lines` are content-indented empty lines; count them as trailing + local k = #lines + while k > 0 and lines[k] == "" do + k =k- 1 + trailing =trailing+ 1 + end + body = table.concat(lines, "\n", 1, k) + if k == 0 then + body = "" + end + lines = table.move(lines, 1, k, 1, {}) + end + local hasContent = false + for _, l in __iter(lines) do + if l ~= "" then + hasContent = true + break + end + end + if chomp == "strip" then + return body, endPos + elseif chomp == "clip" then + return ((hasContent and((body .. "\n" ))or(""))), endPos + end + return ((hasContent and((body .. "\n" ))or(""))) .. string.rep("\n", trailing), endPos +end + +-- ------------------------------------------------------------------------------------------------ flow +local parseFlow + +local function enter(st, p) + st.depth =st.depth+ 1 + if st.depth > st.maxDepth then + raise("LIMIT", "nested deeper than " .. st.maxDepth, p) + end +end + +-- a flow node at p (after skip) -> value, next, wasEmpty +local function flowNode(st, p, ind) +local s = st.s + local props, q = properties(st, p) + if props then + q = skip(s, q) + end + local c = byte(s, q) + local v +if c == 42 then -- * + if props then + corrupt("properties on an alias", q) + end + return alias(st, q) + elseif c == 91 or c == 123 then + v, q = parseFlow(st, q, ind) + collectionTag(st, props and props.tag, c == 91 and"seq" or"map", q) + return finish(st, props, v), q, false + elseif c == 34 or c == 39 then + local t, r = quoted(st, q, ind) + return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false + elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then + -- an empty node + return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), ((props and{q }or{p})[1]), true + elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then + corrupt("unexpected character in a flow collection", q) + elseif (c == 45 or c == 63 or c == 58) and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125) then + if c == 63 then + raise("UNSUPPORTED", "explicit keys (?) in flow collections", q) + end + corrupt("unexpected '" .. char(c ) .. "' in a flow collection", q) + end + local t, r = plain(st, q, ind, true) + return finish(st, props, scalarValue(st, t, true, props and props.tag, q)), r, false +end + +local function checkKey(st, k, p) +if type(k) == "table" and k ~= st.null and not Types.Date.is(k) then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + if k ~= k then + corrupt("NaN as a mapping key", p) + end + return k +end + +function parseFlow(st, p, ind) +local s = st.s + enter(st, p) + local isMap = byte(s, p) == 123 + local close = isMap and 125 or 93 + local t= {} + local order= {} + local count = 0 + local q = p + 1 + local function flowSkip(from) +local r = skip(s, from) + if ind >= 0 and r <= #s and find(sub(s, from, r), "\n", 1, true) and (lineIndent(s, r)) <= ind then + corrupt("a flow collection's line is not indented", r) + end + return r + end + while true do + q = flowSkip(q) + local c = byte(s, q) + if c == nil then + raise("TRUNCATED", "unterminated flow collection", p) + end + if docMarker(s, q) then + corrupt("document marker inside a flow collection", q) + end + if c == close then + q =q+ 1 + break + end + local explicitKey = false + if c == 63 and isWsEnd(byte(s, q + 1)) then + explicitKey = true + q = flowSkip(q + 1) + end + local startLine = q + local k, r, empty = flowNode(st, q, ind) + r = flowSkip(r) + local hasColon = false + if byte(s, r) == 58 then + local d = byte(s, r + 1) + local jsonLike = byte(s, q) == 34 or byte(s, q) == 39 or byte(s, q) == 91 or byte(s, q) == 123 + if isWsEnd(d) or d == 44 or d == 93 or d == 125 or jsonLike then + hasColon = true + -- an implicit key must sit on one line + if not isMap and not explicitKey and find(sub(s, startLine, r), "\n", 1, true) then + corrupt("multi-line implicit key", startLine) + end + r =r+ 1 + end + end + if isMap then + local v= st.null + if hasColon then + local r2 = flowSkip(r) + local cc = byte(s, r2) + if cc ~= 44 and cc ~= 125 then + v, r = flowNode(st, r2, ind) + end + end + if empty and not hasColon and not explicitKey then + corrupt("expected a mapping entry", q) + end + k = checkKey(st, k, q) + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + else + local item = k + if hasColon or explicitKey then + local v= st.null + local r2 = (hasColon and{(flowSkip(r) )}or{r +})[1] local cc = byte(s, r2) + if hasColon and cc ~= 44 and cc ~= 93 then + v, r = flowNode(st, r2, ind) + end + k = checkKey(st, k, q) + item = Types.object({ [k] = v }, { k }) + elseif empty then + corrupt("empty sequence entry", q) + end + count =count+ 1 + t[count] = item + end + r = flowSkip(r) + local cc = byte(s, r) + if cc == 44 then + q = r + 1 + elseif cc == close then + q = r + 1 + break + elseif cc == nil then + raise("TRUNCATED", "unterminated flow collection", p) + else + corrupt(isMap and"expected ',' or '}'" or"expected ',' or ']'", r) + end + end + st.depth =st.depth- 1 + if isMap then + return Types.object(t, order), q + end + return t, q +end + +-- ------------------------------------------------------------------------------------------------ block +local blockNode +-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' + +local function implicitKey(st, p) +local s = st.s + local c = byte(s, p) + if c == 34 or c == 39 then + local ok, t, q = pcall(quoted, st, p, -1) + if not ok then + return nil, nil + end + if find(sub(s, p, q - 1), "\n", 1, true) then + return nil, nil + end + local r = skipLine(s, q) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return t, r + 1 + end + return nil, nil + elseif c == 42 then + local name = match(s, "^%*([^%s,%[%]{}]+)", p) + if not name then + return nil, nil + end + local r = skipLine(s, p + 1 + #name) + if byte(s, r) == 58 and isWsEnd(byte(s, r + 1)) then + return true, r + 1 + end + return nil, nil + elseif c == 91 or c == 123 then + -- a flow collection used as a key? + local e = find(s, "\n", p, true) or #s + 1 + local line = sub(s, p, e - 1) + if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then + local ok, _, q = pcall(parseFlow, st, p, -1) + if ok and byte(s, skipLine(s, q)) == 58 then + raise("UNSUPPORTED", "collections as mapping keys", p) + end + end + return nil, nil + end + if c == nil or c == 10 or c == 35 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 then + return nil, nil + end + if (c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, p + 1)) then + return nil, nil + end + local j = p + while true do + local d = byte(s, j) + if d == nil or d == 10 then + return nil, nil + elseif d == 58 and isWsEnd(byte(s, j + 1)) then + break + elseif d == 35 and (byte(s, j - 1) == 32 or byte(s, j - 1) == 9) then + return nil, nil + end + j =j+ 1 + end + local t = string.gsub(sub(s, p, j - 1), "[ \t]+$", "") + return t, j + 1 +end + +local function readKey(st, p, props) +local s = st.s + local c = byte(s, p) + local tag = props and props.tag + local k +local q +if c == 42 then + if props then + corrupt("properties on an alias", p) + end + k, q = alias(st, p) + q = skipLine(s, q) + q =q+ 1 -- the ':' + elseif c == 34 or c == 39 then + local t, r = quoted(st, p, -1) + if find(sub(s, p, r - 1), "\n", 1, true) then + corrupt("multi-line implicit key", p) + end + k = scalarValue(st, t, false, tag, p) + q = skipLine(s, r) + 1 + else + local t, after = implicitKey(st, p) + if t == nil then + corrupt("expected a mapping key", p) + end + k = scalarValue(st, t, true, tag, p) + q = after +end + k = finish(st, props, k) + return checkKey(st, k, p), q +end + +-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null +local function nextLineNode(st, ind, p, seqAt, mapParent) +local s = st.s + local r = skip(s, p) + if r <= #s and not docMarker(s, r) then + local c = col(s, r) + if c > ind or (seqAt and c == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1))) then + noTabs(s, r, ind) + return blockNode(st, ind, r, false, mapParent) + end + end + return st.null, p +end + +-- the value after a ':' (at p, just past it) of a mapping at column mc +local function mapValue(st, mc, p, explicit) +local s = st.s + local r = skipLine(s, p) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p) then + return nextLineNode(st, mc, r, true, true) + end + return blockNode(st, mc, r, not explicit, true) +end + +local function blockMap(st, mc, p, firstProps) +local s = st.s + enter(st, p) + local t= {} + local order= {} + local q = p + local first = true + while true do + local props= nil + if first and firstProps then + props = firstProps + else + props, p = properties(st, p) + end + first = false + local c = byte(s, p) + local k +local v +if ((c == 63 and not props) or c == 58) and isWsEnd(byte(s, p + 1)) then + -- "? key" (explicit) and ": value" (an empty key) + k = st.null + q = p + if c == 63 then + local r = skipLine(s, p + 1) + local cc = byte(s, r) + if cc == nil or cc == 10 or (cc == 35 and r > p + 1) then + k, q = nextLineNode(st, mc, r, true, false) + else + k, q = blockNode(st, mc, r, false, false) + end + k = checkKey(st, k, p) + local r3 = skip(s, q) + if r3 <= #s and not docMarker(s, r3) and col(s, r3) == mc and byte(s, r3) == 58 and isWsEnd(byte(s, r3 + 1)) then + v, q = mapValue(st, mc, r3 + 1, true) + else + v = st.null + end + else + k = finish(st, props, scalarValue(st, "", true, props and props.tag, p)) + v, q = mapValue(st, mc, p + 1, true) + end + else + local after + k, after = readKey(st, p, props) + v, q = mapValue(st, mc, after, false) + end + if t[k] == nil then + table.insert(order, k) + end + t[k] = v + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc3 = col(s, r3) + if cc3 == mc then + noTabs(s, r3) + if byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + corrupt("a sequence entry where a mapping key is expected", r3) + end + p = r3 + elseif cc3 < mc then + break + else + corrupt("bad indentation of a mapping entry", r3) + end + end + st.depth =st.depth- 1 + return Types.object(t, order), q +end + +local function blockSeq(st, sc, p) +local s = st.s + enter(st, p) + local t= {} + local q = p + while true do + local r = skipLine(s, p + 1) + local c = byte(s, r) + local v +if c == nil or c == 10 or (c == 35 and r > p + 1) then + v, q = nextLineNode(st, sc, r, false, false) + else + if find(sub(s, p + 1, r - 1), "\t", 1, true) and (((c == 45 or c == 63 or c == 58) and isWsEnd(byte(s, r + 1))) or implicitKey(st, r) ~= nil) then + corrupt("tab before a compact collection", r) + end + v, q = blockNode(st, sc, r, false, false) + end + table.insert(t, v) + local r3 = skip(s, q) + if r3 > #s or docMarker(s, r3) then + break + end + local cc = col(s, r3) + if cc == sc and byte(s, r3) == 45 and isWsEnd(byte(s, r3 + 1)) then + noTabs(s, r3) + p = r3 + elseif cc <= sc then + break + else + corrupt("bad indentation of a sequence entry", r3) + end + end + st.depth =st.depth- 1 + return t, q +end + +-- the node at q after its properties (props may be nil); start = where the properties began +local function afterProps(st, ind, start, q, props, inline, mapParent) +local s = st.s + local tag = props and props.tag + local c = byte(s, q) + if c == 42 then + if props then + corrupt("properties on an alias", q) + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + return blockMap(st, col(s, q), q, nil) + end + local v, e = alias(st, q) + if not endOfLine(s, e) then + corrupt("unexpected text after an alias", e) + end + return v, e + end + if c == 45 and isWsEnd(byte(s, q + 1)) then + if inline or props then + corrupt("a sequence cannot start here", q) + end + return blockSeq(st, col(s, q), q) + elseif (c == 63 or c == 58) and isWsEnd(byte(s, q + 1)) then + if inline or (props and c == 63) then + corrupt("a mapping cannot start here", q) + end + return blockMap(st, col(s, start), q, props) + elseif c == 124 or c == 62 then + local text, e = blockScalar(st, q, ind) + return finish(st, props, scalarValue(st, text, false, tag, q)), e + elseif c == 91 or c == 123 then + implicitKey(st, q) -- raises UNSUPPORTED for a flow collection used as a key + local v, e = parseFlow(st, q, ind) + collectionTag(st, tag, c == 91 and"seq" or"map", q) + if not endOfLine(s, e) then + corrupt("unexpected text after a flow collection", e) + end + return finish(st, props, v), e + end + if implicitKey(st, q) ~= nil then + if inline then + corrupt("a mapping cannot start on its key's line", q) + end + -- properties on the key's line belong to the first key + return blockMap(st, col(s, start), q, props) + end + if c == 34 or c == 39 then + local text, e = quoted(st, q, ind) + if not endOfLine(s, e) then + corrupt("unexpected text after a quoted scalar", e) + end + return finish(st, props, scalarValue(st, text, false, tag, q)), e + end + if c == 35 or c == 37 or c == 64 or c == 96 or c == 44 or c == 93 or c == 125 or c == 38 or c == 33 then + corrupt("unexpected character '" .. char(c ) .. "'", q) + end + local text, e = plain(st, q, ind, false) + if not endOfLine(s, e) then + corrupt("unexpected ':' (mapping values are not allowed here)", e) + end + return finish(st, props, scalarValue(st, text, true, tag, q)), e +end + +-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the +-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's +-- indentation may follow properties that end their line. +function blockNode(st, ind, p, inline, mapParent) +local s = st.s + local props, q = properties(st, p) + if not props then + return afterProps(st, ind, p, q, nil, inline, mapParent) + end + -- properties ending their line apply to the node on the next lines; more properties there merge in, unless + -- they start a mapping key + local c = byte(s, q) + if not (c == nil or c == 10 or (c == 35 and q > p)) then + return afterProps(st, ind, p, q, props, inline, mapParent) + end + while true do +local __DARKLUA_CONTINUE_22=false repeat local r = skip(s, q) + if r > #s or docMarker(s, r) then + break + end + local cr = col(s, r) + if not (cr > ind or (mapParent and cr == ind and byte(s, r) == 45 and isWsEnd(byte(s, r + 1)))) then + break + end + noTabs(s, r, ind) + local cc = byte(s, r) + if cc == 38 or cc == 33 then + local p2, q2 = properties(st, r) + local c2 = byte(s, q2) + if c2 == nil or c2 == 10 or (c2 == 35 and q2 > r) then + local pr = props +if (p2 ).anchor then + if pr.anchor then + corrupt("two anchors on one node", r) + end + pr.anchor = (p2 ).anchor + end + if (p2 ).tag then + if pr.tag then + corrupt("two tags on one node", r) + end + pr.tag = (p2 ).tag + end + q = q2 +__DARKLUA_CONTINUE_22=true break + end + if implicitKey(st, q2) ~= nil then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, (props ).tag, "map", r) + return finish(st, props, v), e + end + -- properties then a scalar on the next line: merge + local pr = props +if (p2 ).anchor and pr.anchor or (p2 ).tag and pr.tag then + corrupt("two anchors or tags on one node", r) + end + pr.anchor = pr.anchor or (p2 ).anchor + pr.tag = pr.tag or (p2 ).tag + return afterProps(st, ind, r, q2, pr, false, mapParent) + end + local tag = (props ).tag + if cc == 45 and isWsEnd(byte(s, r + 1)) then + local v, e = blockSeq(st, cr, r) + collectionTag(st, tag, "seq", r) + return finish(st, props, v), e + elseif ((cc == 63 or cc == 58) and isWsEnd(byte(s, r + 1))) or (cc ~= 91 and cc ~= 123 and implicitKey(st, r) ~= nil) then + local v, e = blockMap(st, cr, r, nil) + collectionTag(st, tag, "map", r) + return finish(st, props, v), e + elseif cc == 42 then + corrupt("properties on an alias", r) + end + return afterProps(st, ind, r, r, props, false, mapParent) +until true if not __DARKLUA_CONTINUE_22 then break end end + return finish(st, props, scalarValue(st, "", true, (props ).tag, q)), q +end + +-- ------------------------------------------------------------------------------------------------ stream +local function stream(st) +local s = st.s + local n = #s + local docs = {} + local p = 1 + local needEnd = false -- a bare document after a document must follow "..." or "---" + while true do +local __DARKLUA_CONTINUE_23=false repeat p = skip(s, p) + if p > n then + break + end + local sawDirective = false + st.handles = { ["!"] = "!", ["!!"] = CORE } + local yamlSeen = false + while byte(s, p) == 37 and col(s, p) == 0 do -- % + if needEnd then + corrupt("a directive needs '...' after the previous document", p) + end + local e = find(s, "\n", p, true) or n + 1 + local line = string.gsub(sub(s, p, e - 1), "%s+#.*$", "") + local name = match(line, "^%%(%S+)") + if name == "YAML" then + if yamlSeen then + corrupt("two %YAML directives", p) + end + yamlSeen = true + local v = match(line, "^%%YAML[ \t]+(%d+%.%d+)[ \t]*$") + if not v then + corrupt("bad %YAML directive", p) + end + elseif name == "TAG" then + local h, prefix = match(line, "^%%TAG[ \t]+(![%w%-]*!?)[ \t]+(%S+)[ \t]*$") + if not h then + corrupt("bad %TAG directive", p) + end + st.handles[h ] = prefix +end + sawDirective = true + p = skip(s, e) + end + local explicit = false + if docMarker(s, p) and sub(s, p, p + 2) == "---" then + explicit = true + p =p+ 3 + elseif sawDirective then + corrupt("directives without '---'", p) + elseif docMarker(s, p) then -- "..." + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p =p+ 3 + needEnd = false +__DARKLUA_CONTINUE_23=true break + elseif needEnd then + corrupt("a second document needs '---'", p) + end + st.anchors = {} + local q = skip(s, p) + local value +if q > n or docMarker(s, q) then + value = st.null + p = q + else + if explicit and not find(sub(s, p, q), "\n", 1, true) then + -- content on the "---" line + local ok, _, q2 = pcall(properties, st, q) + local c = byte(s, q2) + if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then + corrupt("a block mapping cannot start on the '---' line", q) + end + end + value, p = blockNode(st, -1, q, false, false) + local r = skip(s, p) + if r <= n and not docMarker(s, r) then + corrupt("unexpected content after the document", r) + end + p = r + end + table.insert(docs, value) + needEnd = true + if p <= n and docMarker(s, p) and sub(s, p, p + 2) == "..." then + if not endOfLine(s, p + 3) then + corrupt("text after '...'", p + 3) + end + p =p+ 3 + needEnd = false + elseif p <= n and docMarker(s, p) then + needEnd = false + end +__DARKLUA_CONTINUE_23=true until true if not __DARKLUA_CONTINUE_23 then break end end + return docs +end + +-- run(text, opts) -> docs | nil, code, message, offset +function Parse.run(text, opts) +local o= opts or {} + local s = text + if sub(s, 1, 3) == "\239\187\191" then + s = sub(s, 4) + end + if find(s, "\r", 1, true) then + s = string.gsub(string.gsub(s, "\r\n", "\n"), "\r", "\n") + end + local st= { + s = s, + n = #s, + anchors = {}, + handles = {}, + depth = 0, + maxDepth = o.maxDepth or 500, + aliasNodes = 0, + maxAlias = o.maxAliasNodes or 1e6, + sizes = (setmetatable({}, { __mode = "k" }) ), + ignoreTags = o.tags == "ignore", + null = (o.null ~= nil and{o.null }or{Types.null})[1], + } + local ok, res = pcall(stream, st) + if ok then + return res, nil, nil, nil + end + if type(res) == "table" and res.yamlErr then + return nil, res.code, res.msg, res.at + end + local msg = tostring(res) + if string.find(msg, "stack overflow", 1, true) then + return nil, "LIMIT", "nested too deeply", 0 + end + return nil, "CORRUPT", "internal error: " .. msg, 0 +end + +return Parse +end +__FILES["font/bdf"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in +-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), +-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to +-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for +-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and +-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font +-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. +-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Bdf = { + name = "bdf", + category = "font", + extensions = { "bdf" }, + mime = { "application/x-font-bdf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + +function Bdf.sniff(r) +local head = r:peek(32) + return string.match(head, "^STARTFONT%s+2%.%d") and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function unquote(v) +local s = string.match(v, '^"(.*)"%s*$') + if s then + return (string.gsub(s, '""', '"')) + end + return tonumber(v) or v +end + +local function hexRow(line, w, row, rowOff) + local n = math.min(math.floor(#line / 2), math.ceil(w / 8)) + for i = 0, n - 1 do + local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0 + buffer.writeu8(row, rowOff + i, v) + end +end + +function Bdf.decode(r, opts) +local o= opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split(text, "\n") + local props= {} + local fontName, size = "", 0 + local fbb = { 0, 0, 0, 0 } + local fontDw = 0 + local glyphs= {} + local encodings= {} + local i = 1 + local n = #lines + local function line() +local l = string.gsub(lines[i] or "", "\r$", "") + i =i+ 1 + return l + end + local first = line() + if not string.match(first, "^STARTFONT%s") then + return nil, Err.new(Err.CORRUPT, "no STARTFONT") + end + local ended = false + while i <= n do + local l = line() + local key, rest = string.match(l, "^(%S+)%s*(.*)$") + if key == "FONT" then + fontName = rest +elseif key == "SIZE" then + size = tonumber(string.match(rest , "^(%S+)")) or 0 + elseif key == "FONTBOUNDINGBOX" then + local a, b, c, d = string.match(rest , "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif key == "DWIDTH" then + fontDw = tonumber(string.match(rest , "^(%-?%d+)")) or 0 + elseif key == "STARTPROPERTIES" then + while i <= n do + local pl = line() + if string.match(pl, "^ENDPROPERTIES") then + break + end + local pk, pv = string.match(pl, "^(%S+)%s*(.*)$") + if pk then + props[pk ] = unquote(pv ) + end + end + elseif key == "STARTCHAR" then + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local name = rest +local enc = -1 + local dw = fontDw + local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] } + local px= nil + while i <= n do + local cl = line() + local ck, cr = string.match(cl, "^(%S+)%s*(.*)$") + if ck == "ENCODING" then + local e1, e2 = string.match(cr , "^(%-?%d+)%s*(%-?%d*)") + enc = tonumber(e1) or -1 + if enc == -1 and e2 and e2 ~= "" then + enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings) + end + elseif ck == "DWIDTH" then + dw = tonumber(string.match(cr , "^(%-?%d+)")) or dw + elseif ck == "BBX" then + local a, b, c, d = string.match(cr , "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)") + bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 } + elseif ck == "BITMAP" then + local w, h = bbx[1], bbx[2] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name) + end + local stride = math.ceil(w / 8) + local rows = buffer.create(stride * h) + for y = 0, h - 1 do + local rl = string.gsub(lines[i] or "", "%s", "") + if string.match(rl, "^ENDCHAR") then + break + end + i =i+ 1 + hexRow(rl, w, rows, y * stride) + end + px = Bitmap.unpack(rows, 0, w, h, stride) + elseif ck == "ENDCHAR" then + break + end + end + local gl= { + name = name, + codepoint = nil, + width = bbx[1], + height = bbx[2], + left = bbx[3], + top = bbx[4] + bbx[2], + advance = dw, + pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])), + } + table.insert(glyphs, gl) + table.insert(encodings, enc) + elseif key == "ENDFONT" then + ended = true + break + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no ENDFONT") + end + local registry = (type(props.CHARSET_REGISTRY) == "string" and{(string.upper(props.CHARSET_REGISTRY) )}or{nil +})[1] local cset = ((type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" )and{(tostring(props.CHARSET_ENCODING) )}or{nil +})[1] local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local default= nil + for k, gl in __iter(glyphs) do + local enc = encodings[k] + if unicode and enc >= 0 then + gl.codepoint = enc + end + if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then + default = k - 1 + end + end + local pixelSize = (type(props.PIXEL_SIZE) == "number" and{props.PIXEL_SIZE }or{((fbb[2] > 0 and{fbb[2] }or{size})[1]) +})[1] local strike= { + size = pixelSize, + ascent = (type(props.FONT_ASCENT) == "number" and{props.FONT_ASCENT }or{(fbb[2] + fbb[4])})[1], + descent = (type(props.FONT_DESCENT) == "number" and{props.FONT_DESCENT }or{(-fbb[4])})[1], + glyphs = glyphs, + default = default, + } + local slant = props.SLANT + local weight = props.WEIGHT_NAME + local style = ((type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" and{weight }or{""})[1]) + if slant == "I" or slant == "O" then + style = ((style ~= "" and((style .. " " ))or(""))) .. "Italic" + end + local info = { + family = (type(props.FAMILY_NAME) == "string" and{props.FAMILY_NAME }or{fontName})[1], + style = (style ~= "" and{style }or{"Regular"})[1], + fullName = fontName, + } + local font = Bitmap.font(strike, info, { + properties = props, + encodings = encodings, + unicode = unicode, + fontName = fontName, + boundingBox = fbb, + source = { format = "bdf", charset = (registry and((registry .. "-" .. tostring(cset) ))or(nil ))}, + }) + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function quote(s) +return '"' .. string.gsub(s, '"', '""') .. '"' +end + +function Bdf.encode(font, opts) +local o= opts or {} + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local info = (type(font.info) == "table" and{font.info }or{{} +})[1] local family = string.gsub(tostring(info.family or "rosetta"), "[%-\n\r\"]", " ") + local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil + local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil + local px = strike.size + -- the font bounding box + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, g in __iter(strike.glyphs) do + if g.width > 0 and g.height > 0 then + x0 = math.min(x0, g.left) + x1 = math.max(x1, g.left + g.width) + y0 = math.min(y0, g.top - g.height) + y1 = math.max(y1, g.top) + end + end + if x0 == math.huge then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + local name = o.name + or string.format("-rosetta-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, bold and"bold" or"medium", italic and"i" or"r", px, px * 10, (x1 - x0) * 10) + local out = { + "STARTFONT 2.1", + "FONT " .. name, + string.format("SIZE %d 75 75", px), + string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), + } + -- the default glyph: the strike's default, else glyph 0 + local defaultIndex = (strike.default or 0) + 1 + local props= { + { "FAMILY_NAME", quote(family) }, + { "WEIGHT_NAME", quote(bold and"Bold" or"Medium") }, + { "SLANT", quote(italic and"I" or"R") }, + { "PIXEL_SIZE", px }, + { "POINT_SIZE", px * 10 }, + { "RESOLUTION_X", 75 }, + { "RESOLUTION_Y", 75 }, + { "CHARSET_REGISTRY", quote("ISO10646") }, + { "CHARSET_ENCODING", quote("1") }, + { "FONT_ASCENT", strike.ascent }, + { "FONT_DESCENT", strike.descent }, + } + local dg = strike.glyphs[defaultIndex] + if dg and dg.codepoint then + table.insert(props, { "DEFAULT_CHAR", dg.codepoint }) + end + table.insert(out, "STARTPROPERTIES " .. #props) + for _, p in __iter(props) do + table.insert(out, p[1] .. " " .. tostring(p[2])) + end + table.insert(out, "ENDPROPERTIES") + table.insert(out, "CHARS " .. #strike.glyphs) + for k, g in __iter(strike.glyphs) do + local gname = g.name or ((g.codepoint and{(string.format("uni%04X", g.codepoint) )}or{("glyph" .. (k - 1))})[1]) + table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_")) + table.insert(out, "ENCODING " .. ((g.codepoint and{(tostring(g.codepoint) )}or{"-1"})[1])) + table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5))) + table.insert(out, string.format("DWIDTH %d 0", g.advance)) + table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height)) + table.insert(out, "BITMAP") + local stride = math.ceil(g.width / 8) + local rows = Bitmap.pack(g.pixels, g.width, g.height, stride) + for y = 0, g.height - 1 do + local hex = table.create(stride) + for x = 0, stride - 1 do + hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x)) + end + table.insert(out, table.concat(hex)) + end + table.insert(out, "ENDCHAR") + end + table.insert(out, "ENDFONT") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Bdf +end +__FILES["font/bmfont"] = function() +local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict +-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and +-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize +-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are +-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the +-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / +-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. +-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("font/bmfont/Parse") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmfont = { + name = "bmfont", + category = "font", + extensions = { "fnt" }, + mime = { "application/x-bmfont" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + + + + + +function Bmfont.sniff(r) +local head = r:peek(64) + if string.sub(head, 1, 4) == "BMF\3" then + return 1 + end + if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then + return 0.9 + end + if string.find(head, "<font>", 1, true) or (string.find(head, "<?xml", 1, true) and string.find(r:peek(512), "<font>", 1, true)) then + return string.find(r:peek(512), "<info", 1, true) and 0.9 or 0.3 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the Font value +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self, cp) +return self._index[cp] or 0 +end +function Face.advance(self, g) +local c = self._chars[g] + return (c and{c.xadvance }or{0 +})[1]end +function Face.kern(self, a, b) +local ca, cb = self._chars[a], self._chars[b] + if not ca or not cb then + return 0 + end + return self._kern[ca.id * 2097152 + cb.id] or 0 +end +function Face.outline(_self, _g) +return nil -- bitmap font +end + +-- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil +function Face.loadPages(self, loader) +local load = loader or self.meta.pageLoader + if type(load) ~= "function" then + return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))") + end + local pages = {} + for i, file in __iter(self.meta.pageFiles) do + local ok, img, err = pcall(load, file, i - 1) + if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, (Err.is(err) and{err }or{(Err.new(Err.IO, "page " .. file .. ": " .. tostring((ok and{err }or{img})[1])) +)})[1] end + pages[i] = img + end + self.pages = pages + return true, nil +end + +local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 + +-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; +-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. +function Face.rasterize(self, g, px) +local c = self._chars[g] + if not c then + return nil + end + if not self.pages and self.meta.pageLoader then + self:loadPages() + end + local page = self.pages and self.pages[c.page + 1] + local img = Types.Image.new(c.width, c.height, "alpha8") + img.meta.left = c.xoffset + img.meta.top = (self.meta.base or 0) - c.yoffset + img.meta.advance = c.xadvance + img.meta.glyph = g + img.meta.scale = (type(px) == "number" and self.unitsPerEm > 0 and((px / self.unitsPerEm ))or(1 +)) if not page then + return nil + end + local pw, ph = page.width, page.height + local bpp = Types.Image.bpp(page.format) or 4 + local ch = (page.format == "rgba8" and{CHANNEL[c.chnl] or 3 }or{0 +})[1] if page.format == "graya8" then + ch = 1 + end + for y = 0, c.height - 1 do + local sy = c.y + y + for x = 0, c.width - 1 do + local sx = c.x + x + if sx >= 0 and sy >= 0 and sx < pw and sy < ph then + buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1))) + end + end + end + return img +end + +-- the Font value of a description +local function face(d, variant) +local f= setmetatable({ + kind = "font", + info = { + family = d.info.face, + style = (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 and"Bold Italic" or((d.info.bold or 0) ~= 0 and"Bold" or((d.info.italic or 0) ~= 0 and"Italic" or"Regular")), + fullName = d.info.face, + }, + unitsPerEm = math.abs(d.info.size or 0), + ascent = d.common.base or 0, + descent = (d.common.base or 0) - (d.common.lineHeight or 0), + lineGap = 0, + numGlyphs = #d.chars + 1, + pages = nil, + meta = { + bmfont = d, + variant = variant, + pageFiles = d.pages, + lineHeight = d.common.lineHeight, + base = d.common.base, + source = { format = "bmfont", variant = variant }, + }, + _chars = {}, + _index = {}, + _kern = {}, + }, Face) + for i, c in __iter(d.chars) do + f._chars[i] = c + if f._index[c.id] == nil then + f._index[c.id] = i + end + end + for _, k in __iter(d.kernings) do + f._kern[k[1] * 2097152 + k[2] ] = k[3] + end + return f +end + +function Bmfont.decode(r, opts) +local d, err, variant + if r:peek(3) == "BMF" then + d, err = Parse.binary(r:sub(0)) + variant = "binary" + else + local s = r:peek(r:size()) + if string.find(string.sub(s, 1, 512), "<font", 1, true) then + d, err = Parse.xml(s) + variant = "xml" + else + d, err = Parse.text(s) + variant = "text" + end + end + if not d then + return nil, Err.from(err or "bad descriptor", r.base) + end + local f = face(d, variant) + if opts and type(opts.pages) == "table" then + f.pages = opts.pages + end + if opts and type(opts.loadPage) == "function" then + f.meta.pageLoader = opts.loadPage + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validDesc(d) +if type(d) ~= "table" or type(d.info) ~= "table" or type(d.common) ~= "table" or type(d.pages) ~= "table" or type(d.chars) ~= "table" or type(d.kernings) ~= "table" then + return false + end + for _, c in __iter(d.chars) do + for _, k in __iter({ "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }) do + local v = c[k] + if type(v) ~= "number" or v % 1 ~= 0 then + return false + end + end + if c.id < 0 or c.x < 0 or c.y < 0 or c.width < 0 or c.height < 0 or c.page < 0 or c.page > 255 or c.chnl < 0 or c.chnl > 255 then + return false + end + end + for _, k in __iter(d.kernings) do + if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then + return false + end + end + for _, p in __iter(d.pages) do + if type(p) ~= "string" then + return false + end + end + return true +end + +function Bmfont.encode(font, opts) +if type(font) ~= "table" or font.kind ~= "font" then + return nil, Err.new(Err.ARG, "expected a Font") + end + local d = type(font.meta) == "table" and font.meta.bmfont or nil + local pages = font.pages + if d == nil then + -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" + local file = opts and opts.file + if file == nil and opts and type(opts.name) == "string" then + file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") + if file == "" then + file = nil + end + end + local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) + if not baked then + return nil, err + end + d = baked.meta.bmfont + pages = baked.pages + end + if not validDesc(d) then + return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") + end + -- the page images into opts.files, under the names the descriptor gives them + local files = opts and opts.files + local encodeImage = opts and opts.encodeImage + if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then + for i, name in __iter(d.pages) do + local img = pages[i] + if type(img) == "table" and type(name) == "string" and name ~= "" then + local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") + local bytes, eerr = encodeImage(img, ext) + if not bytes then + return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) + end + files[name] = bytes + end + end + end + local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" + if variant == "text" then + return buffer.fromstring(Parse.writeText(d)), nil + elseif variant == "xml" then + return buffer.fromstring(Parse.writeXml(d)), nil + elseif variant == "binary" then + return Parse.writeBinary(d), nil + end + return nil, Err.new(Err.ARG, "variant must be text, xml or binary") +end + +-- ------------------------------------------------------------------------------------------------ extras +local function codepoints(chars) +local out = {} + if type(chars) == "string" then + for _, c in __iter(utf8.codes(chars)) do + table.insert(out, c) + end + elseif type(chars) == "table" then + for _, c in __iter(chars) do + if type(c) == "number" then + table.insert(out, c) + end + end + else + for c = 32, 126 do + table.insert(out, c) + end + end + return out +end + +-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are +-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are +-- kept (rounded to pixels). +function Bmfont.bake(font, opts) +if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then + return nil, Err.new(Err.ARG, "bake: expected an outline Font") + end + local o= opts or {} + local px = (type(o.px) == "number" and o.px > 0 and o.px <= 1024 and{o.px }or{32 +})[1] local pad = (type(o.padding) == "number" and o.padding >= 0 and{(math.floor(o.padding) )}or{1 +})[1] local scale = px / font.unitsPerEm + local glyphs= {} + local area = 0 + local seen = {} + for _, cp in __iter(codepoints(o.chars)) do + local g = (font ):glyphIndex(cp) + if (g ~= 0 or cp == 0) and not seen[cp] then + seen[cp] = true + local img= (font ):rasterize(g, px) + if img then + table.insert(glyphs, { cp = cp, g = g, img = img }) + area =area+ (img.width + pad) * (img.height + pad) + end + end + end + local size +if type(o.pageSize) == "number" then + size = o.pageSize + else + size = 64 + while size * size < area * 1.3 and size < 4096 do + size =size* 2 + end + end + local order = table.clone(glyphs) + table.sort(order, function(a, b) +if a.img.height ~= b.img.height then + return a.img.height > b.img.height + end + return a.cp < b.cp + end) + local ascent = math.ceil(font.ascent * scale) + local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale) + local prefix = o.file or "font" + local d= { + info = { + face = font.info and font.info.family or "font", + size = px, + bold = 0, + italic = 0, + charset = "", + unicode = 1, + stretchH = 100, + smooth = 1, + aa = 1, + padding = { 0, 0, 0, 0 }, + spacing = { pad, pad }, + outline = 0, + }, + common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 }, + pages = {}, + chars = {}, + kernings = {}, + } + local pages= {} + local page= nil + local x, y, rowH = pad, pad, 0 + local placed= {} + for _, gl in __iter(order) do + local w, h = gl.img.width, gl.img.height + if w + 2 * pad > size or h + 2 * pad > size then + return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page") + end + if x + w + pad > size then + x, y, rowH = pad, y + rowH + pad, 0 + end + if not page or y + h + pad > size then + page = Types.Image.new(size, size) + table.insert(pages, page ) + table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1)) + x, y, rowH = pad, pad, 0 + end + local pg = page +for yy = 0, h - 1 do + for xx = 0, w - 1 do + local a = buffer.readu8(gl.img.pixels, yy * w + xx) + buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216) + end + end + local c= { + id = gl.cp, + x = x, + y = y, + width = w, + height = h, + xoffset = gl.img.meta.left, + yoffset = ascent - gl.img.meta.top, + xadvance = math.floor(gl.img.meta.advance + 0.5), + page = #pages - 1, + chnl = 15, + } + placed[gl.cp] = c + x =x+ (w + pad +) rowH = math.max(rowH, h) + end + for _, gl in __iter(glyphs) do + table.insert(d.chars, placed[gl.cp]) + end + d.common.pages = #pages + if type(font.kern) == "function" then + for _, a in __iter(glyphs) do + for _, b in __iter(glyphs) do + local k = font:kern(a.g, b.g) + if k ~= 0 then + local v = math.floor(k * scale + 0.5) + if v ~= 0 then + table.insert(d.kernings, { a.cp, b.cp, v }) + end + end + end + end + end + local f = face(d, "text") + f.pages = pages + return f, nil +end + +return Bmfont +end +__FILES["font/bmfont/Parse"] = function() +local __compat = __compat local bit32, utf8, __iter = __compat.bit32, __compat.utf8, __compat.__iter --!strict +-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one +-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation +-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the +-- descriptor has no nesting that matters, no text content). +-- +-- Never throws on bad input: parse functions return nil, message. +local Bytes = __include("core/Bytes") + +local Parse = {} + + + + + + + + + + + + + + + + + + + + + +local LIMIT = 1000000 -- chars / kernings + +local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } +local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } +local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } + +local function list(s, n) +local out = table.create(n, 0) + if s then + local i = 1 + for v in __iter(string.gmatch(s, "-?%d+")) do + if i > n then + break + end + out[i] = tonumber(v) or 0 + i =i+ 1 + end + end + return out +end + +local function new() +return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } +end + +-- one tag's attributes (already split into key -> string) into the description +local function apply(d, tag, a) +if tag == "info" then + d.info.face = a.face or "" + d.info.charset = a.charset or "" + for _, k in __iter(INFO_NUM) do + d.info[k] = tonumber(a[k]) or 0 + end + d.info.padding = list(a.padding, 4) + d.info.spacing = list(a.spacing, 2) + elseif tag == "common" then + for _, k in __iter(COMMON_NUM) do + d.common[k] = tonumber(a[k]) or 0 + end + elseif tag == "page" then + local id = tonumber(a.id) + if not id or id < 0 or id > 4096 or id % 1 ~= 0 then + return "bad page id" + end + d.pages[id + 1] = a.file or "" + elseif tag == "char" then + if #d.chars >= LIMIT then + return "too many chars" + end + local c= {} + for _, k in __iter(CHAR_NUM) do + c[k] = tonumber(a[k]) or 0 + end + table.insert(d.chars, c) + elseif tag == "kerning" then + if #d.kernings >= LIMIT then + return "too many kerning pairs" + end + table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 }) + end + return nil +end + +local function fill(d) + for i = 1, #d.pages do + d.pages[i] = d.pages[i] or "" + end +end + +-- ------------------------------------------------------------------------------------------------ text +function Parse.text(s) +local d = new() + for line in __iter(string.gmatch(s, "[^\r\n]+")) do + local tag, rest = string.match(line, "^%s*(%a+)(.*)$") + if tag then + local a= {} + -- key=value, key="quoted value" + local i = 1 + while i <= #(rest ) do + local k, q, e = string.match(rest , '^%s*([%w_]+)="([^"]*)"()', i) + if k then + a[k] = q + i = e + else + local k2, v2, e2 = string.match(rest , "^%s*([%w_]+)=(%S*)()", i) + if not k2 then + break + end + a[k2] = v2 + i = e2 + end + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + end + if not d.common.lineHeight then + return nil, "no common line" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ XML +local ENTITIES= { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" } +local function unescape(s) +return ( + string.gsub(s, "&(#?x?%w+);", function(e) +if ENTITIES[e] then + return ENTITIES[e] + end + local n = (string.sub(e, 1, 2) == "#x" and{(tonumber(string.sub(e, 3), 16) )}or{(string.sub(e, 1, 1) == "#" and{(tonumber(string.sub(e, 2)) )}or{nil +})[1]})[1] if n and n >= 0 and n <= 0x10FFFF then + return utf8.char(n) + end + return nil + end) + ) +end + +function Parse.xml(s) +local d = new() + local seenFont = false + for tag, attrs in __iter(string.gmatch(s, "<(%a+)([^>]*)>")) do + if tag == "font" then + seenFont = true + end + local a= {} + for k, q, v in __iter(string.gmatch(attrs , "([%w_]+)%s*=%s*([\"'])(.-)%2")) do + a[k] = unescape(v ) + local _ = q + end + local err = apply(d, tag, a) + if err then + return nil, err + end + end + if not seenFont or not d.common.lineHeight then + return nil, "not a BMFont XML descriptor" + end + fill(d) + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ binary +function Parse.binary(r) +if not r:match("BMF") then + return nil, "bad signature" + end + local version = r:u8() + if version ~= 3 then + return nil, "unsupported binary version " .. version + end + local d = new() + while not r:eof() do + local kind = r:u8() + local size = r:u32le() + if r.err then + return nil, "truncated block header" + end + local b = r:slice(size) + if r.err then + return nil, "block past the end" + end + if kind == 1 then + d.info.size = b:i16le() + local bits = b:u8() + d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0 + d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0 + d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0 + d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0 + d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0 + d.info.charsetId = b:u8() + d.info.charset = "" + d.info.stretchH = b:u16le() + d.info.aa = b:u8() + d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() } + d.info.spacing = { b:u8(), b:u8() } + d.info.outline = b:u8() + d.info.face = b:cstring() + elseif kind == 2 then + d.common.lineHeight = b:u16le() + d.common.base = b:u16le() + d.common.scaleW = b:u16le() + d.common.scaleH = b:u16le() + d.common.pages = b:u16le() + d.common.packed = bit32.band(b:u8(), 1) ~= 0 and 1 or 0 + d.common.alphaChnl = b:u8() + d.common.redChnl = b:u8() + d.common.greenChnl = b:u8() + d.common.blueChnl = b:u8() + elseif kind == 3 then + while not b:eof() and #d.pages < 4096 do + table.insert(d.pages, b:cstring()) + end + elseif kind == 4 then + local n = math.floor(size / 20 +) if n > LIMIT then + return nil, "too many chars" + end + for _ = 1, n do + table.insert(d.chars, { + id = b:u32le(), + x = b:u16le(), + y = b:u16le(), + width = b:u16le(), + height = b:u16le(), + xoffset = b:i16le(), + yoffset = b:i16le(), + xadvance = b:i16le(), + page = b:u8(), + chnl = b:u8(), + }) + end + elseif kind == 5 then + local n = math.floor(size / 10 +) if n > LIMIT then + return nil, "too many kerning pairs" + end + for _ = 1, n do + table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() }) + end + end + if b.err then + return nil, "truncated block " .. kind + end + end + if not d.common.lineHeight then + return nil, "no common block" + end + return d, nil +end + +-- ------------------------------------------------------------------------------------------------ writers +local function num(v) +return string.format("%d", math.floor(tonumber(v) or 0)) +end + +local function textLines(d, quote) +local i, c = d.info, d.common + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + local lines= { + { + "info", + { + { "face", quote(i.face or "") }, + { "size", num(i.size) }, + { "bold", num(i.bold) }, + { "italic", num(i.italic) }, + { "charset", quote(i.charset or "") }, + { "unicode", num(i.unicode) }, + { "stretchH", num(i.stretchH or 100) }, + { "smooth", num(i.smooth) }, + { "aa", num(i.aa) }, + { "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") }, + { "spacing", num(sp[1]) .. "," .. num(sp[2]) }, + { "outline", num(i.outline) }, + }, + }, + } + local cf = {} + for _, k in __iter(COMMON_NUM) do + table.insert(cf, { k, num(c[k]) }) + end + table.insert(lines, { "common", cf }) + return lines +end + +function Parse.writeText(d) +local out = {} + local function q(s) +return '"' .. string.gsub(s, '"', "") .. '"' + end + for _, l in __iter(textLines(d, q)) do + local parts = { l[1] } + for _, kv in __iter(l[2]) do + table.insert(parts, kv[1] .. "=" .. kv[2]) + end + table.insert(out, table.concat(parts, " ")) + end + for id, file in __iter(d.pages) do + table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', "")))) + end + table.insert(out, "chars count=" .. #d.chars) + for _, c in __iter(d.chars) do + local parts = { "char" } + for _, k in __iter(CHAR_NUM) do + table.insert(parts, k .. "=" .. num((c )[k])) + end + table.insert(out, table.concat(parts, " ")) + end + if #d.kernings > 0 then + table.insert(out, "kernings count=" .. #d.kernings) + for _, k in __iter(d.kernings) do + table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3]))) + end + end + return table.concat(out, "\n") .. "\n" +end + +local function esc(s) +return (string.gsub(s, '[&<>"]', { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """ })) +end + +function Parse.writeXml(d) +local out = { '<?xml version="1.0"?>', "<font>" } + for _, l in __iter(textLines(d, function(s) +return s + end)) do + local parts = { " <" .. l[1] } + for _, kv in __iter(l[2]) do + table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " <pages>") + for id, file in __iter(d.pages) do + table.insert(out, string.format(' <page id="%d" file="%s"/>', id - 1, esc(file))) + end + table.insert(out, " </pages>") + table.insert(out, string.format(' <chars count="%d">', #d.chars)) + for _, c in __iter(d.chars) do + local parts = { " <char" } + for _, k in __iter(CHAR_NUM) do + table.insert(parts, k .. '="' .. num((c )[k]) .. '"') + end + table.insert(out, table.concat(parts, " ") .. "/>") + end + table.insert(out, " </chars>") + if #d.kernings > 0 then + table.insert(out, string.format(' <kernings count="%d">', #d.kernings)) + for _, k in __iter(d.kernings) do + table.insert(out, string.format(' <kerning first="%s" second="%s" amount="%s"/>', num(k[1]), num(k[2]), num(k[3]))) + end + table.insert(out, " </kernings>") + end + table.insert(out, "</font>") + return table.concat(out, "\n") .. "\n" +end + +function Parse.writeBinary(d) +local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10) + w:string("BMF") + w:u8(3) + local i, c = d.info, d.common + local face = i.face or "" + w:u8(1) + w:u32le(14 + #face + 1) + w:u16le((tonumber(i.size) or 0) % 65536) + local bits = 0 + if (tonumber(i.smooth) or 0) ~= 0 then + bits =bits+ 0x80 + end + if (tonumber(i.unicode) or 0) ~= 0 then + bits =bits+ 0x40 + end + if (tonumber(i.italic) or 0) ~= 0 then + bits =bits+ 0x20 + end + if (tonumber(i.bold) or 0) ~= 0 then + bits =bits+ 0x10 + end + if (tonumber(i.fixedHeight) or 0) ~= 0 then + bits =bits+ 0x08 + end + w:u8(bits) + w:u8(tonumber(i.charsetId) or 0) + w:u16le(tonumber(i.stretchH) or 100) + w:u8(tonumber(i.aa) or 1) + local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 } + for k = 1, 4 do + w:u8(pad[k] or 0) + end + w:u8(sp[1] or 0) + w:u8(sp[2] or 0) + w:u8(tonumber(i.outline) or 0) + w:cstring(face) + w:u8(2) + w:u32le(15) + for _, k in __iter({ "lineHeight", "base", "scaleW", "scaleH", "pages" }) do + w:u16le((tonumber(c[k]) or 0) % 65536) + end + w:u8((tonumber(c.packed) or 0) ~= 0 and 1 or 0) + for _, k in __iter({ "alphaChnl", "redChnl", "greenChnl", "blueChnl" }) do + w:u8(tonumber(c[k]) or 0) + end + if #d.pages > 0 then + local len = 0 + for _, p in __iter(d.pages) do + len =len+ (#p + 1 +) end + w:u8(3) + w:u32le(len) + for _, p in __iter(d.pages) do + w:cstring(p) + end + end + w:u8(4) + w:u32le(#d.chars * 20) + for _, ch in __iter(d.chars) do + w:u32le(ch.id) + w:u16le(ch.x) + w:u16le(ch.y) + w:u16le(ch.width) + w:u16le(ch.height) + w:u16le(ch.xoffset % 65536) + w:u16le(ch.yoffset % 65536) + w:u16le(ch.xadvance % 65536) + w:u8(ch.page) + w:u8(ch.chnl) + end + if #d.kernings > 0 then + w:u8(5) + w:u32le(#d.kernings * 10) + for _, k in __iter(d.kernings) do + w:u32le(k[1]) + w:u32le(k[2]) + w:u16le(k[3] % 65536) + end + end + return w:finish() +end + +return Parse +end +__FILES["font/eot"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, +-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and +-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot +-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, +-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C +-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Eot = { + name = "eot", + category = "font", + extensions = { "eot" }, + mime = { "application/vnd.ms-fontobject" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" }, + caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local MAGIC = 0x504C +local COMPRESSED, XOR = 0x4, 0x10000000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Eot.sniff(r) +local h = r:peek(36) + if #h < 36 then + return 0 + end + local ver = string.sub(h, 9, 12) + local magic = string.byte(h, 35) + string.byte(h, 36) * 256 + if magic == MAGIC and (ver == "\0\0\1\0" or ver == "\1\0\2\0" or ver == "\2\0\2\0") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Eot.decode(r, opts) +local eotSize, dataSize, version, flags = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local panose = r:string(10) + local charset, italic = r:u8(), r:u8() + local weight = r:u32le() + local fsType, magic = r:u16le(), r:u16le() + local ranges = { r:u32le(), r:u32le(), r:u32le(), r:u32le() } + local codepages = { r:u32le(), r:u32le() } + local checksum = r:u32le() + r:skip(16) + if r.err then + return nil, r.err + end + if magic ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad magic number") + end + if version ~= 0x00010000 and version ~= 0x00020001 and version ~= 0x00020002 then + return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%08x", version)) + end + local function name() +r:skip(2) + local n = r:u16le() + local s = r:bytes(n) + return Text.utf16(s, 0, buffer.len(s)) + end + local eot= { + version = version, + flags = flags, + panose = panose, + charset = charset, + italic = italic ~= 0, + weight = weight, + fsType = fsType, + unicodeRange = ranges, + codePageRange = codepages, + checkSumAdjustment = checksum, + eotSize = eotSize, + } + eot.familyName, eot.styleName, eot.versionName, eot.fullName = name(), name(), name(), name() + if version >= 0x00020001 then + eot.rootString = name() + end + if version == 0x00020002 then + eot.rootStringChecksum = r:u32le() + eot.eudcCodePage = r:u32le() + r:skip(2) + r:skip(r:u16le()) -- signature + eot.eudcFlags = r:u32le() + r:skip(r:u32le()) -- EUDC font data + end + if r.err then + return nil, r.err + end + if bit32.band(flags, COMPRESSED) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "MicroType Express compressed font data") + end + local data = r:bytes(dataSize) + if r.err then + return nil, r.err + end + if bit32.band(flags, XOR) ~= 0 then + for i = 0, dataSize - 1 do + buffer.writeu8(data, i, bit32.bxor(buffer.readu8(data, i), 0x50)) + end + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + font.meta.eot = eot + font.meta.fontData = data + font.meta.source = { format = "eot", version = version, outlines = font.meta.outlines } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf16(s) +local out = {} + if utf8.len(s) then + for _, c in __iter(utf8.codes(s)) do + if c >= 0x10000 then + c =c- 0x10000 + local hi, lo = 0xD800 + bit32.rshift(c, 10), 0xDC00 + bit32.band(c, 0x3FF) + table.insert(out, string.char(hi % 256, math.floor(hi / 256), lo % 256, math.floor(lo / 256))) + else + table.insert(out, string.char(c % 256, math.floor(c / 256))) + end + end + end + return table.concat(out) +end + +function Eot.encode(value, opts) +local o= opts or {} + local data +if type(value) == "buffer" then + data = value + elseif type(value) == "string" then + data = buffer.fromstring(value) + elseif type(value) == "table" and type(value.meta) == "table" and type(value.meta.fontData) == "buffer" then + data = value.meta.fontData + else + return nil, Err.new(Err.ARG, "expected TrueType bytes (or a Font read from an EOT)") + end + local font, ferr = TrueType.font(data) + if not font then + return nil, ferr + end + local tables= TrueType.tables(data, 0, 0, buffer.len(data)) or {} + local function tab(tagName) +local t= tables[tagName] + return (t and{(Bytes.reader(data, t[1], t[2]) )}or{nil +})[1] end + -- OS/2: PANOSE, weight, fsType, ranges, selection; head: checkSumAdjustment + local panose, weight, fsType, italic, charset = string.rep("\0", 10), 400, 0, 0, 1 + local ranges, codepages = { 0, 0, 0, 0 }, { 0, 0 } + local os2 = tab("OS/2") + if os2 then + os2:seek(4) + weight = os2:u16be() + os2:seek(8) + fsType = os2:u16be() + os2:seek(32) + panose = os2:string(10) + ranges = { os2:u32be(), os2:u32be(), os2:u32be(), os2:u32be() } + os2:seek(62) + local sel = os2:u16be() + italic = bit32.band(sel, 1) ~= 0 and 1 or 0 + os2:seek(78) + codepages = { os2:u32be(), os2:u32be() } + if os2.err then + codepages = { 0, 0 } + end + end + local head = tab("head") + local checksum = 0 + if head then + head:seek(8) + checksum = head:u32be() + end + local info = font.info or {} + local names = { info.family or "", info.style or "", info.version or "", info.fullName or "" } + local w = Bytes.writer(buffer.len(data) + 512) + w:u32le(0) -- EOTSize, patched + w:u32le(buffer.len(data)) + w:u32le(0x00020001) + w:u32le((o.xor and{XOR }or{0})[1]) + w:string(panose) + w:u8(charset) + w:u8(italic) + w:u32le(weight) + w:u16le(fsType) + w:u16le(MAGIC) + for _, v in __iter(ranges) do + w:u32le(v) + end + for _, v in __iter(codepages) do + w:u32le(v) + end + w:u32le(checksum) + w:string(string.rep("\0", 16)) + for _, s in __iter(names) do + local u = utf16(tostring(s)) + w:u16le(0) + w:u16le(#u) + w:string(u) + end + local root = utf16(o.rootString or "") + w:u16le(0) + w:u16le(#root) + w:string(root) + local start = w:tell() + w:bytes(data) + local out = w:finish() + if o.xor then + for i = start, start + buffer.len(data) - 1 do + buffer.writeu8(out, i, bit32.bxor(buffer.readu8(out, i), 0x50)) + end + end + buffer.writeu32(out, 0, buffer.len(out)) + return out, nil +end + +return Eot +end +__FILES["font/fon"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the +-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE +-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first +-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI +-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). +-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- Not supported: vector FNT (Err.UNSUPPORTED), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Fon = { + name = "fon", + category = "font", + extensions = { "fon", "fnt" }, + mime = { "application/x-font-fnt" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + +local function isFnt(h) +if #h < 4 then + return false + end + local ver = string.byte(h, 1) + string.byte(h, 2) * 256 + return ver == 0x200 or ver == 0x300 +end + +function Fon.sniff(r) +local h = r:peek(64) + if string.sub(h, 1, 2) == "MZ" and #h >= 64 then + local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536 + local sig = r:peek(2, lfanew) + return sig == "NE" and 0.6 or(sig == "PE" and 0.2 or 0 +) end + if isFnt(h) and #h >= 6 then + local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216 + return size == r:size() and 0.9 or(size <= r:size() and size > 118 and 0.3 or 0 +) end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one FNT resource -> Font +local function fnt(r) +local version = r:u16le() + local total = r:u32le() + local copyright = string.match(r:string(60), "^[^%z]*") or "" + local ftype = r:u16le() + local points, vres, hres = r:u16le(), r:u16le(), r:u16le() + local ascent = r:u16le() + r:skip(4) -- internal / external leading + local italic = r:u8() + r:skip(2) + local weight = r:u16le() + local charset = r:u8() + local pixWidth, pixHeight = r:u16le(), r:u16le() + r:skip(5) -- pitch and family, average / max width + local first, last, default = r:u8(), r:u8(), r:u8() + r:skip(1 + 2 + 4) + local faceAt = r:u32le() + if r.err then + return nil, r.err + end + if version ~= 0x200 and version ~= 0x300 then + return nil, Err.new(Err.CORRUPT, "not a FNT resource") + end + if bit32.band(ftype, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "vector fonts") + end + if last < first or pixHeight == 0 or pixHeight > 1024 then + return nil, Err.new(Err.CORRUPT, "bad character range or height") + end + r:seek(version == 0x300 and 148 or 118) + local glyphs= {} + for c = first, last do + local w = r:u16le() + local off = (version == 0x300 and{(r:u32le() )}or{(r:u16le() +)})[1] if r.err then + return nil, r.err + end + if w > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph width") + end + -- column-major: byte column k holds pixels 8k .. 8k + 7 of every row + local h = pixHeight + local px = buffer.create(w * h) + local cols = math.ceil(w / 8) + local base = r.base + off + local limit = r.base + r:size() + for k = 0, cols - 1 do + for y = 0, h - 1 do + local p = base + k * h + y + if p >= 0 and p < limit then + local byte = buffer.readu8(r.buf, p) + for b = 0, 7 do + local x = k * 8 + b + if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then + buffer.writeu8(px, y * w + x, 255) + end + end + end + end + end + local cp= nil + if charset == 0 then + cp = (c >= 0x80 and c < 0xA0 and{Text.CP1252[c] }or{c +})[1] elseif c < 0x80 then + cp = c + end + table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px }) + end + local face = "" + if faceAt > 0 and faceAt < r:size() then + face = r:sub(faceAt):cstring(256) + end + local dflt = default + first + local strike= { + size = pixHeight, + ascent = ascent, + descent = pixHeight - ascent, + glyphs = glyphs, + default = (dflt >= first and dflt <= last and((dflt - first ))or(nil)), + } + local style = (weight >= 600 and"Bold" or"") .. (italic ~= 0 and" Italic" or"") + style = string.gsub(style, "^ ", "") + return Bitmap.font(strike, { family = face, style = (style ~= "" and{style }or{"Regular"})[1], fullName = face }, { + copyright = copyright, + points = points, + resolution = { hres, vres }, + charset = charset, + weight = weight, + pixWidth = pixWidth, + firstChar = first, + source = { format = "fon", version = version == 0x300 and 3 or 2, size = total }, + }), nil +end + +-- the RT_FONT resources of an NE executable: { { offset, length } } +local function neFonts(r, ne) +local rt = r:sub(ne + 0x24, 2):u16le() + local t = r:sub(ne + rt) + local shift = t:u16le() + if shift > 16 then + return nil, "bad resource alignment" + end + local out = {} + for _ = 1, 64 do + local typeId = t:u16le() + if typeId == 0 or t.err then + break + end + local count = t:u16le() + t:skip(4) + for _ = 1, count do + local off, len = t:u16le(), t:u16le() + t:skip(8) + if typeId == 0x8008 then + table.insert(out, { off * 2 ^ shift, len * 2 ^ shift }) + end + end + end + if t.err then + return nil, "truncated resource table" + end + return out, nil +end + +-- the RT_FONT (8) resources of a PE executable: { { offset, length } } +local function peFonts(r, pe) +local h = r:sub(pe + 4, 20) + h:skip(2) + local nsec = h:u16le() + h:skip(12) + local optSize = h:u16le() + local opt = r:sub(pe + 24, optSize) + local magic = opt:u16le() + local ddAt = magic == 0x20B and 112 or 96 + opt:seek(ddAt + 2 * 8) + local rsrcRva = opt:u32le() + if opt.err or rsrcRva == 0 then + return {}, nil + end + -- the section holding the resources + local secs = r:sub(pe + 24 + optSize, nsec * 40) + local base, rva0 = -1, 0 + for _ = 1, nsec do + secs:skip(8) + local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le() + secs:skip(16) + if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then + base, rva0 = rawAt + (rsrcRva - va), va - rawAt + end + end + if base < 0 then + return nil, "no resource section" + end + local out = {} + local function dir(at, depth, isFont) + if depth > 3 then + return + end + local d = r:sub(base + at, 16) + d:skip(12) + local named, ids = d:u16le(), d:u16le() + local e = r:sub(base + at + 16, (named + ids) * 8) + for _ = 1, math.min(named + ids, 512) do +local __DARKLUA_CONTINUE_8=false repeat local id, target = e:u32le(), e:u32le() + if e.err then + return + end + if depth == 0 and id ~= 8 then +__DARKLUA_CONTINUE_8=true break + end + if bit32.band(target, 0x80000000) ~= 0 then + dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0) + elseif isFont then + local leaf = r:sub(base + target, 8) + local dataRva, size = leaf:u32le(), leaf:u32le() + table.insert(out, { dataRva - rva0, size }) + end +__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end + end + dir(0, 0, false) + return out, nil +end + +function Fon.decode(r, opts) +local o= opts or {} + local list +if r:peek(2) == "MZ" then + local lfanew = r:sub(0x3C, 4):u32le() + local sig = r:peek(2, lfanew) + local l, err + if sig == "NE" then + l, err = neFonts(r, lfanew) + elseif sig == "PE" then + l, err = peFonts(r, lfanew) + else + return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header") + end + if not l then + return nil, Err.from(err) + end + list = l + else + if r:size() < 118 then + return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header") + end + list = { { 0, r:size() } } + end + local fonts= {} + local firstErr= nil + for _, res in __iter(list) do + if res[1] + 118 <= r:size() then + local f, err = fnt(r:sub(res[1], res[2])) + if f then + table.insert(fonts, f) + else + firstErr = firstErr or err + end + end + end + if #fonts == 0 then + return nil, firstErr or Err.new(Err.CORRUPT, "no font resources") + end + local pick = fonts[1] + if type(o.size) == "number" then + for _, f in __iter(fonts) do + if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then + pick = f + end + end + end + pick.meta.strikes = fonts + return pick, nil +end + +return Fon +end +__FILES["font/hershey"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph +-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", +-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths +-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster +-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of +-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i +-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph +-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: +-- writing, the Hershey "occidental" index files (.hmp), filled rendering. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") + +-- ------------------------------------------------------------------------------------------------ contract +local Hershey = { + name = "hershey", + category = "font", + extensions = { "jhf" }, + mime = { "application/x-hershey-font" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" }, + caps = { decode = true, encode = false, strokes = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards) + +-- ------------------------------------------------------------------------------------------------ sniff +-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R") +local function header(line) +if #line < 10 then + return nil, nil + end + local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", ""))) + local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", ""))) + if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then + return nil, nil + end + return id, n +end + +function Hershey.sniff(r) +local head = r:peek(256) + local line = string.match(head, "^([^\r\n]*)") + local id, n = header(line or "") + if not id or not n then + return 0 + end + local body = string.sub(line , 9) + if string.find(body, "[^ -~]") then + return 0 + end + return (#body == math.min(2 * n, 64) or #body == 2 * n )and 0.7 or 0.3 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self, cp) +return self._index[cp] or 0 +end + +function Face.advance(self, g) +local gl = self._glyphs[g + 1] + return (gl and((gl.right - gl.left ))or(0 +))end + +function Face.kern(_self, _a, _b) +return 0 +end + +function Face.outline(self, g) +local gl = self._glyphs[g + 1] + if not gl then + return nil + end + local out = table.create(#gl.cmds) + for i, c in __iter(gl.cmds) do + out[i] = table.clone(c) + end + return out +end + +-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) +function Face.rasterize(self, g, px) +local gl = self._glyphs[g + 1] + if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local s = px / self.unitsPerEm + local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" }) + local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left = m.x + img.meta.top = -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = (gl.right - gl.left) * s + img.meta.glyph = g + return img +end + +function Hershey.decode(r, opts) +local o= opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines = string.split((string.gsub(text, "\r", "")), "\n") + local glyphs= {} + local i = 1 + while i <= #lines do +local __DARKLUA_CONTINUE_2=false repeat local line = lines[i] + i =i+ 1 + if string.match(line, "^%s*$") then +__DARKLUA_CONTINUE_2=true break + end + local id, n = header(line) + if not id or not n then + return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1)) + end + local data = string.sub(line, 9) + while #data < 2 * n and i <= #lines do + data =data.. lines[i] + i =i+ 1 + end + if #data < 2 * n then + return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count") + end + if #glyphs >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + local left = string.byte(data, 1) - 82 + local right = string.byte(data, 2) - 82 + local cmds= {} + local pen = false + for k = 1, n - 1 do + local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2) + if a == 32 and b == 82 then + pen = false + else + local x, y = a - 82 - left, BASELINE - (b - 82) + local cmd= { op = pen and"lineTo" or"moveTo" } + cmd[1], cmd[2] = x, y + table.insert(cmds, cmd) + pen = true + end + end + table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds }) +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + if #glyphs == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + local index= {} + local byId = o.map == "id" + for k, g in __iter(glyphs) do + local cp = (byId and{g.id }or{(31 + k +)})[1] if index[cp] == nil then + index[cp] = k - 1 + end + end + local font = setmetatable({ + kind = "font", + info = { family = "Hershey", style = "Regular" }, + unitsPerEm = 32, + ascent = 21, + descent = -7, + lineGap = 4, + numGlyphs = #glyphs, + meta = { + strokes = true, + strokeWidth = o.strokeWidth or 2, + ids = table.create(#glyphs, 0), + source = { format = "hershey", map = byId and"id" or"ascii" }, + }, + _glyphs = glyphs, + _index = index, + }, Face) + for k, g in __iter(glyphs) do + font.meta.ids[k] = g.id + end + return font, nil +end + +return Hershey +end +__FILES["font/pcf"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the +-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), +-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad +-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. +-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets +-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver +-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcf = { + name = "pcf", + category = "font", + extensions = { "pcf" }, + mime = { "application/x-font-pcf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = false, bitmap = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + +local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8 +local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256 +local COMPRESSED = 0x100 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcf.sniff(r) +return r:peek(4) == "\1fcp" and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +-- a reader positioned after a table's format word, with the integer readers for its byte order + + +local function open(r, t) +if not t or t.offset + 4 > r:size() then + return nil + end + local s = r:sub(t.offset, t.size) + local format = s:u32le() + return { r = s, format = format, big = bit32.band(format, 4) ~= 0 } +end + +local function u32(t) +return (t.big and{(t.r:u32be() )}or{(t.r:u32le() +)})[1]end +local function i32(t) +return (t.big and{(t.r:i32be() )}or{(t.r:i32le() +)})[1]end +local function i16(t) +return (t.big and{(t.r:i16be() )}or{(t.r:i16le() +)})[1]end +local function u16(t) +return (t.big and{(t.r:u16be() )}or{(t.r:u16le() +)})[1]end + +local REV = buffer.create(256) +for i = 0, 255 do + local v, rv = i, 0 + for _ = 1, 8 do + rv = rv * 2 + v % 2 + v =math.floor(v/ 2 +) end + buffer.writeu8(REV, i, rv) +end + +function Pcf.decode(r, opts) +local o= opts or {} + local maxGlyphs = o.maxGlyphs or 1114112 + if r:string(4) ~= "\1fcp" then + return nil, Err.new((r.err and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a PCF file") + end + local count = r:u32le() + if count > 64 then + return nil, Err.new(Err.CORRUPT, "too many tables") + end + local tables= {} + for _ = 1, count do + local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le() + tables[ty] = { format = format, size = size, offset = offset } + end + if r.err then + return nil, r.err + end + -- properties + local props= {} + local pt = open(r, tables[PROPERTIES]) + if pt then + local n = i32(pt) + if n < 0 or n > 4096 then + return nil, Err.new(Err.CORRUPT, "bad property count") + end + local raw = {} + for k = 1, n do + raw[k] = { i32(pt), pt.r:u8(), i32(pt) } + end + if n % 4 ~= 0 then + pt.r:skip(4 - n % 4) + end + local strSize = i32(pt) + local strAt = pt.r:tell() + local function str(off) +if off < 0 or off >= strSize then + return "" + end + local s = pt.r:sub(strAt + off, strSize - off) + return s:cstring() + end + for _, p in __iter(raw) do + props[str(p[1])] = (p[2] ~= 0 and{(str(p[3]) )}or{p[3] +})[1] end + if pt.r.err then + return nil, Err.new(Err.TRUNCATED, "properties table") + end + end + -- accelerators: ascent / descent + local ascent, descent= nil, nil + local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) + if at then + at.r:skip(8) + ascent, descent = i32(at), i32(at) + end + -- metrics + local mt = open(r, tables[METRICS]) + if not mt then + return nil, Err.new(Err.CORRUPT, "no METRICS table") + end + local metrics = {} + local compressed = bit32.band(mt.format, COMPRESSED) ~= 0 + local nm = (compressed and{(u16(mt) )}or{(u32(mt) +)})[1] if nm > maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + for k = 1, nm do + if compressed then + local b = mt.r + metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 } + else + metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) } + mt.r:skip(2) + end + end + if mt.r.err then + return nil, Err.new(Err.TRUNCATED, "metrics table") + end + -- bitmaps + local bt = open(r, tables[BITMAPS]) + if not bt then + return nil, Err.new(Err.CORRUPT, "no BITMAPS table") + end + local nb = u32(bt) + if nb ~= nm then + return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count") + end + local offsets = table.create(nb, 0) + for k = 1, nb do + offsets[k] = u32(bt) + end + local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) } + local padIndex = bit32.band(bt.format, 3) + local pad = bit32.lshift(1, padIndex) + local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3)) + local msbBit = bit32.band(bt.format, 8) ~= 0 + local dataAt = bt.r:tell() + local dataSize = sizes[padIndex + 1] + if bt.r.err or dataAt + dataSize > bt.r:size() then + return nil, Err.new(Err.TRUNCATED, "bitmaps table") + end + -- the bitmap data normalised to MSB-first bits and bytes + local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize) + if not msbBit then + for k = 0, dataSize - 1 do + buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k))) + end + end + if bt.big ~= msbBit and unit > 1 then + for k = 0, dataSize - unit, unit do + for j = 0, math.floor(unit / 2 )- 1 do + local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j) + buffer.writeu8(bits, k + j, y) + buffer.writeu8(bits, k + unit - 1 - j, x) + end + end + end + local glyphs= {} + for k = 1, nm do + local m = metrics[k] + local w, h = m[2] - m[1], m[4] + m[5] + if w < 0 or h < 0 or w > 4096 or h > 4096 then + return nil, Err.new(Err.CORRUPT, "bad glyph metrics") + end + local stride = math.ceil(w / (pad * 8)) * pad + local px = Bitmap.unpack(bits, offsets[k], w, h, stride) + glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } + end + -- encodings + local encodings= {} + local default= nil + local et = open(r, tables[BDF_ENCODINGS]) + if et then + local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et) + if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then + return nil, Err.new(Err.CORRUPT, "bad encoding ranges") + end + for b1 = min1, max1 do + for b2 = min2, max2 do + local g = u16(et) + if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then + encodings[g + 1] = b1 * 256 + b2 + end + end + end + if et.r.err then + return nil, Err.new(Err.TRUNCATED, "encodings table") + end + local dcols = max2 - min2 + 1 + local d1, d2 = math.floor(def / 256), def % 256 + if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then + local slot = (d1 - min1) * dcols + (d2 - min2) + local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2) + local g = (et.big and{(dr:u16be() )}or{(dr:u16le() +)})[1] if g ~= 0xFFFF and g < nm then + default = g + end + end + end + -- glyph names + local nt = open(r, tables[GLYPH_NAMES]) + if nt then + local n = u32(nt) + if n == nm then + local offs = table.create(n, 0) + for k = 1, n do + offs[k] = u32(nt) + end + local strSize = u32(nt) + local strAt = nt.r:tell() + for k = 1, n do + if offs[k] < strSize then + glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring() + end + end + end + end + local registry = (type(props.CHARSET_REGISTRY) == "string" and{(string.upper(props.CHARSET_REGISTRY) )}or{nil +})[1] local cset = (props.CHARSET_ENCODING ~= nil and{(tostring(props.CHARSET_ENCODING) )}or{nil +})[1] local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1") + local encList = table.create(nm, -1) + for k = 1, nm do + local enc = encodings[k] + encList[k] = enc or -1 + if unicode and enc then + glyphs[k].codepoint = enc + end + end + local pixelSize = (type(props.PIXEL_SIZE) == "number" and{props.PIXEL_SIZE }or{((ascent or 0) + (descent or 0) +)})[1] local strike= { + size = pixelSize, + ascent = (type(props.FONT_ASCENT) == "number" and{props.FONT_ASCENT }or{ascent or 0})[1], + descent = (type(props.FONT_DESCENT) == "number" and{props.FONT_DESCENT }or{descent or 0})[1], + glyphs = glyphs, + default = default, + } + local weight = props.WEIGHT_NAME + local style = (type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" and{weight }or{"" +})[1] if props.SLANT == "I" or props.SLANT == "O" then + style = ((style ~= "" and((style .. " " ))or(""))) .. "Italic" + end + return Bitmap.font(strike, { + family = (type(props.FAMILY_NAME) == "string" and{props.FAMILY_NAME }or{nil})[1], + style = (style ~= "" and{style }or{"Regular"})[1], + fullName = (type(props.FONT) == "string" and{props.FONT }or{nil})[1], + }, { + properties = props, + encodings = encList, + unicode = unicode, + source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = (registry and((registry .. "-" .. tostring(cset) ))or(nil ))}, + }), nil +end + +return Pcf +end +__FILES["font/psf"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 +-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and +-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry +-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map +-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell +-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: +-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through +-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps +-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd +-- project's psf documentation (Andries Brouwer). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bitmap = __include("codecs/font/Bitmap") + +-- ------------------------------------------------------------------------------------------------ contract +local Psf = { + name = "psf", + category = "font", + extensions = { "psf", "psfu" }, + mime = { "application/x-font-linux-psf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" }, + caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function Psf.sniff(r) +local h = r:peek(4) + if h == "\114\181\74\134" then + return 1 + end + if string.sub(h, 1, 2) == "\54\4" and #h >= 4 and string.byte(h, 3) <= 7 and string.byte(h, 4) > 0 then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Psf.decode(r, opts) +local o= opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local version, count, width, height, stride, glyphAt, hasTable + if r:peek(4) == "\114\181\74\134" then + r:skip(4) + local ver, hsize, flags = r:u32le(), r:u32le(), r:u32le() + count = r:u32le() + local charsize = r:u32le() + height, width = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PSF 2 version " .. ver) + end + stride = math.ceil(width / 8) + if width < 1 or height < 1 or width > 4096 or height > 4096 or charsize ~= stride * height then + return nil, Err.new(Err.CORRUPT, "bad glyph size") + end + version, glyphAt, hasTable = 2, hsize, bit32.band(flags, 1) ~= 0 + elseif r:peek(2) == "\54\4" then + r:skip(2) + local mode, charsize = r:u8(), r:u8() + if r.err then + return nil, r.err + end + version, width, height, stride = 1, 8, charsize, 1 + count = bit32.band(mode, 1) ~= 0 and 512 or 256 + glyphAt, hasTable = 4, bit32.band(mode, 6) ~= 0 + if height < 1 then + return nil, Err.new(Err.CORRUPT, "zero glyph height") + end + else + return nil, Err.new(Err.CORRUPT, "not a PSF font") + end + if count < 1 or count > maxGlyphs then + return nil, Err.new(Err.LIMIT, "glyph count " .. count .. " over maxGlyphs") + end + local size = stride * height + if glyphAt + count * size > r:size() then + return nil, Err.new(Err.TRUNCATED, "glyph data past the end") + end + local glyphs= {} + for i = 0, count - 1 do + glyphs[i + 1] = { + width = width, + height = height, + left = 0, + top = height, + advance = width, + pixels = Bitmap.unpack(r.buf, r.base + glyphAt + i * size, width, height, stride), + } + end + local map= {} + local sequences = {} + local unicodeTable= {} -- per glyph: code points and { sequence } tables, in file order + if hasTable then + local t = r:sub(glyphAt + count * size) + for i = 0, count - 1 do + local inSeq = false + local seq= {} + local entry= {} + unicodeTable[i + 1] = entry + local function endSeq() + if #seq > 0 then + table.insert(sequences, { glyph = i, codepoints = seq }) + table.insert(entry, seq) + end + seq = {} + end + while true do +local __DARKLUA_CONTINUE_3=false repeat if t:eof() then + break + end + local cp + if version == 1 then + cp = t:u16le() + if cp == 0xFFFF then + break + elseif cp == 0xFFFE then + endSeq() + inSeq = true +__DARKLUA_CONTINUE_3=true break + end + else + local b = t:u8() + if b == 0xFF then + break + elseif b == 0xFE then + endSeq() + inSeq = true +__DARKLUA_CONTINUE_3=true break + end + -- UTF-8 + local n = b < 0x80 and 0 or(b >= 0xF0 and 3 or(b >= 0xE0 and 2 or(b >= 0xC0 and 1 or-1 +))) if n < 0 then + return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") + end + cp = (n == 0 and{b }or{(n == 1 and{(bit32.band(b, 0x1F) )}or{(n == 2 and{(bit32.band(b, 0x0F) )}or{(bit32.band(b, 0x07) +)})[1]})[1]})[1] for _ = 1, n do + cp = cp * 64 + bit32.band(t:u8(), 0x3F) + end + end + if inSeq then + table.insert(seq, cp) +__DARKLUA_CONTINUE_3=true break + end + table.insert(entry, cp) + if map[cp] == nil then + map[cp] = i + if glyphs[i + 1].codepoint == nil then + glyphs[i + 1].codepoint = cp + end + end +__DARKLUA_CONTINUE_3=true until true if not __DARKLUA_CONTINUE_3 then break end end + endSeq() + end + if t.err then + return nil, Err.new(Err.TRUNCATED, "Unicode table") + end + else + for i = 0, count - 1 do + glyphs[i + 1].codepoint = i + end + end + local strike= { size = height, ascent = height, descent = 0, glyphs = glyphs, map = map, default = 0 } + local defaultGlyph = map[0xFFFD] or map[0x3F] + if defaultGlyph then + strike.default = defaultGlyph + end + return Bitmap.font(strike, {}, { + unicode = hasTable, + sequences = sequences, + unicodeTable = (hasTable and{unicodeTable }or{nil})[1], + width = width, + height = height, + source = { format = "psf", version = version, glyphs = count }, + }), nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function utf8Bytes(cp) +return utf8.char(cp) +end + +function Psf.encode(font, opts) +local o= opts or {} + local version = o.version or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars }) + if not strike then + return nil, err + end + local glyphs = strike.glyphs + local n = #glyphs + if n == 0 then + return nil, Err.new(Err.ARG, "no glyphs") + end + -- the cell + local width = 0 + for _, g in __iter(glyphs) do + width = math.max(width, g.advance, g.left + g.width) + end + local height = math.max(1, strike.ascent + strike.descent) + if version == 1 then + if width > 8 then + return nil, Err.new(Err.ARG, "PSF 1 glyphs are 8 pixels wide (this font needs " .. width .. ")") + end + if n > 512 then + return nil, Err.new(Err.ARG, "PSF 1 holds 256 or 512 glyphs (this font has " .. n .. ")") + end + width = 8 + end + width = math.max(width, 1) + local count = (version == 1 and{(n > 256 and 512 or 256) }or{n +})[1] local stride = math.ceil(width / 8) + local size = stride * height + local cells = buffer.create(count * size) + for i, g in __iter(glyphs) do + local cell = buffer.create(width * height) + local x0, y0 = g.left, strike.ascent - g.top + for y = 0, g.height - 1 do + for x = 0, g.width - 1 do + local cx, cy = x0 + x, y0 + y + if cx >= 0 and cy >= 0 and cx < width and cy < height and buffer.readu8(g.pixels, y * g.width + x) >= 128 then + buffer.writeu8(cell, cy * width + cx, 255) + end + end + end + buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) + end + -- the Unicode table: each glyph's code point and the extra mappings onto it + local cps= {} + for i = 1, count do + cps[i] = {} + end + local seen= {} + for i, g in __iter(glyphs) do + if g.codepoint and not seen[g.codepoint] then + seen[g.codepoint] = true + table.insert(cps[i], g.codepoint) + end + end + if strike.map then + local extra= {} + for cp, gi in __iter(strike.map) do + if not seen[cp] and gi >= 0 and gi < count then + table.insert(extra, { cp, gi }) + end + end + table.sort(extra, function(a, b) +return a[1] < b[1] + end) + for _, e in __iter(extra) do + seen[e[1] ] = true + table.insert(cps[e[2] + 1], e[1]) + end + end + local meta = (type(font.meta) == "table" and{font.meta }or{{} +})[1] local srcTable = (font.bitmap == strike and type(meta.unicodeTable) == "table" and #meta.unicodeTable == n and{meta.unicodeTable }or{nil +})[1] local withTable = (o.unicode ~= nil and{o.unicode }or{(meta.unicode ~= false +)})[1] local w = Bytes.writer(count * size + 64) + if version == 2 then + w:string("\114\181\74\134") + w:u32le(0) + w:u32le(32) + w:u32le(withTable and 1 or 0) + w:u32le(count) + w:u32le(size) + w:u32le(height) + w:u32le(width) + else + w:string("\54\4") + w:u8((count == 512 and 1 or 0) + (withTable and 2 or 0)) + w:u8(height) + end + w:bytes(cells) + if withTable then + local function put(cp) + if version == 2 then + w:string(utf8Bytes(cp)) + elseif cp < 0xFFFE then + w:u16le(cp) + end + end + for i = 1, count do + -- a PSF read earlier writes its table back as it was (code points on several glyphs, sequences) + local list = (srcTable and srcTable[i] and{srcTable[i] }or{cps[i] +})[1] for _, x in __iter(list) do + if type(x) == "number" then + put(x) + end + end + for _, x in __iter(list) do + if type(x) == "table" then + if version == 2 then + w:u8(0xFE) + else + w:u16le(0xFFFE) + end + for _, cp in __iter(x) do + put(cp) + end + end + end + if version == 2 then + w:u8(0xFF) + else + w:u16le(0xFFFF) + end + end + end + return w:finish(), nil +end + +return Psf +end +__FILES["font/ttf"] = function() +--!strict +-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the +-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. +-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Ttf = { + name = "ttf", + category = "font", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function Ttf.sniff(r) +local m = r:peek(4) + if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ttf.decode(r, opts) +local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) + if not font then + return nil, err + end + font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- count(r) -> the number of fonts in the file (1 unless a collection) +function Ttf.count(r) +return TrueType.count(r.buf, r.base) +end + +return Ttf +end +__FILES["font/type1"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the +-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, +-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, +-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring +-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph +-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through +-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple +-- Master and CID-keyed (Type 9 / 11) fonts, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local GlyphNames = __include("codecs/font/GlyphNames") +local Charstring = __include("font/type1/Charstring") + +-- ------------------------------------------------------------------------------------------------ contract +local Type1 = { + name = "type1", + category = "font", + extensions = { "pfb", "pfa", "t1" }, + mime = { "application/x-font-type1" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" }, + caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + +function Type1.sniff(r) +local h = r:peek(64) + if string.sub(h, 1, 2) == "\128\1" then + h = string.sub(h, 7) + end + if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA +local function sections(r) +local b = r.buf + local n = r:size() + if r:peek(2) == "\128\1" then + local clear, bin = {}, Bytes.writer() + local p = 0 + while p + 2 <= n do + local h = r:sub(p, 6) + local m, ty, len = h:u8(), h:u8(), h:u32le() + if m ~= 128 then + return nil, nil, "bad PFB segment marker" + end + if ty == 3 then + break + end + if h.err or p + 6 + len > n then + return nil, nil, "truncated PFB segment" + end + if ty == 1 then + if #clear == 0 or bin:tell() == 0 then + table.insert(clear, buffer.readstring(b, r.base + p + 6, len)) + end + elseif ty == 2 then + bin:bytes(r:sub(p + 6, len):bytes(len)) + else + return nil, nil, "bad PFB segment type " .. ty + end + p =p+ (6 + len +) end + return table.concat(clear), bin:finish(), nil + end + local text = buffer.readstring(b, r.base, n) + local e = string.find(text, "eexec", 1, true) + if not e then + return nil, nil, "no eexec section" + end + local clear = string.sub(text, 1, e + 4) + -- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex) + local rest = string.sub(text, e + 5) + local hexPart = string.match(rest, "^%s*([%x%s]+)") + if hexPart and #hexPart > 8 then + local digits = string.gsub(hexPart, "%s", "") + local out = buffer.create(math.floor(#digits / 2)) + for i = 0, math.floor(#digits / 2 )- 1 do + buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0) + end + return clear, out, nil + end + local s = string.match(rest, "^[\r\n]*(.*)$") or rest + return clear, buffer.fromstring(s), nil +end + +local function decrypt(src, off, n, key, skip) +local r = key + local out = buffer.create(math.max(0, n - skip)) + for i = 0, n - 1 do + local c = buffer.readu8(src, off + i) + local p = bit32.bxor(c, bit32.rshift(r, 8)) + r = ((c + r) * 52845 + 22719) % 65536 + if i >= skip then + buffer.writeu8(out, i - skip, p) + end + end + return out +end + +-- binary strings of the private dictionary: "<len> RD <bytes>" / "<len> -| <bytes>" +local function binaryAt(priv, p, len) +if p < 0 or len < 0 or p + len > buffer.len(priv) then + return nil + end + local out = buffer.create(len) + buffer.copy(out, 0, priv, p, len) + return out +end + +local function psString(clear, key) +return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)") +end + +local Face = {} +Face.__index = Face + +function Face.glyphIndex(self, cp) +return self._cmap[cp] or 0 +end + +function Face.advance(self, g) +local res = self:_run(g) + return (res and{res.advance }or{0 +})[1]end + +function Face.kern(_self, _a, _b) +return 0 +end + +function Face._run(self, g) +local cached = self._cache[g] + if cached ~= nil then + return (cached == false and{nil }or{cached +})[1] end + local cs = self._charstrings[g + 1] + if not cs then + return nil + end + local res = Charstring.run(cs, self._ctx) + self._cache[g] = res or false + return res +end + +function Face.outline(self, g) +local res = self:_run(g) + if not res then + return nil + end + local out = table.create(#res.cmds) + for i, c in __iter(res.cmds) do + out[i] = table.clone(c) + end + return out +end + +function Face.rasterize(self, g, px) +if type(px) ~= "number" or not (px > 0) or px > 4096 then + return nil + end + local res = self:_run(g) + if not res then + return nil + end + local s = px / self.unitsPerEm + local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 }) + local img + if m then + img = Types.Image.new(m.width, m.height, "alpha8") + buffer.copy(img.pixels, 0, m.coverage) + img.meta.left, img.meta.top = m.x, -m.y + else + img = Types.Image.new(0, 0, "alpha8") + img.meta.left, img.meta.top = 0, 0 + end + img.meta.advance = res.advance * s + img.meta.glyph = g + return img +end + +function Type1.decode(r, opts) +local o= opts or {} + local maxGlyphs = o.maxGlyphs or 65536 + local clear, enc, serr = sections(r) + if not clear or not enc then + return nil, Err.from(serr) + end + if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then + return nil, Err.new(Err.CORRUPT, "no eexec section") + end + if buffer.len(enc) < 4 then + return nil, Err.new(Err.TRUNCATED, "eexec section too short") + end + local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) + local ptext = buffer.tostring(priv) + local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 + -- Subrs + local subrs= {} + local function charstring(p, len) +local raw = binaryAt(priv, p, len) + if not raw then + return nil + end + if lenIV < 0 then + return raw + end + return decrypt(raw, 0, len, 4330, lenIV) + end + local sAt = string.find(ptext, "/Subrs", 1, true) + local csAt = string.find(ptext, "/CharStrings", 1, true) + if not csAt then + return nil, Err.new(Err.CORRUPT, "no CharStrings") + end + if sAt and sAt < csAt then + local p = sAt + while true do + local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p) + if not s or s > csAt then + break + end + local e = e0 +local i, n = (tonumber(idx) ), (tonumber(len) ) +if i > 65535 then + return nil, Err.new(Err.LIMIT, "too many subroutines") + end + local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end") + end + subrs[i + 1] = cs + p = e + n + end + end + -- CharStrings + local names= {} + local charstrings= {} + local byName= {} + local p = csAt + 12 + while true do + local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p) + if not s then + break + end + local e = e0 -- stop at the end of the dictionary + +if string.find(string.sub(ptext, p, s), "%send%s") then + break + end + local n = (tonumber(len) ) +local cs = charstring(e, n) + if not cs then + return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end") + end + if #names >= maxGlyphs then + return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs") + end + table.insert(names, name ) + table.insert(charstrings, cs) + if byName[name ] == nil then + byName[name ] = #names - 1 + end + p = e + n + end + if #names == 0 then + return nil, Err.new(Err.CORRUPT, "no glyphs") + end + -- .notdef first: glyph 0 + local nd = byName[".notdef"] + if nd and nd ~= 0 then + names[1], names[nd + 1] = names[nd + 1], names[1] + charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] + byName[names[1] ], byName[names[nd + 1] ] = 0, nd + end + -- the encoding + local encoding= {} + if string.find(clear, "/Encoding%s+StandardEncoding") then + for code, gname in __iter(GlyphNames.STANDARD) do + encoding[code] = gname + end + else + for code, gname in __iter(string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put")) do + encoding[(tonumber(code) )] = gname + end + end + local cmap= {} + for _, gname in __iter(encoding) do + local g = byName[gname] + local cp = GlyphNames.unicode(gname) + if g and cp and cmap[cp] == nil then + cmap[cp] = g + end + end + for k, gname in __iter(names) do + local cp = GlyphNames.unicode(gname) + if cp and cmap[cp] == nil then + cmap[cp] = k - 1 + end + end + -- font matrix / bbox + local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") + local scale = 0.001 + if fm then + local a = tonumber(string.match(fm, "^%s*(%S+)")) + if a and a > 0 then + scale = a + end + end + local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]") + local bbox = { 0, 0, 0, 0 } + if bb then + local k = 1 + for v in __iter(string.gmatch(bb, "%S+")) do + bbox[k] = tonumber(v) or 0 + k =k+ 1 + end + end + local upm = math.floor(1 / scale + 0.5) + local font = setmetatable({ + kind = "font", + info = { + family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"), + style = psString(clear, "Weight") or "Regular", + fullName = psString(clear, "FullName"), + postscriptName = string.match(clear, "/FontName%s*/(%S+)"), + }, + unitsPerEm = upm, + ascent = bbox[4], + descent = bbox[2], + lineGap = 0, + numGlyphs = #names, + meta = { + glyphNames = names, + encoding = encoding, + bbox = bbox, + italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"), + lenIV = lenIV, + source = { format = "type1", variant = r:peek(2) == "\128\1" and"pfb" or"pfa" }, + }, + _cmap = cmap, + _charstrings = charstrings, + _cache = {}, + }, Face) + font._ctx = { + subrs = subrs, + seac = function(code) +local gname = GlyphNames.STANDARD[code] + local g = (gname and{byName[gname] }or{nil +})[1] if not g then + return nil + end + local res = Charstring.run(charstrings[g + 1], { subrs = subrs }) + return res + end, + } + return font, nil +end + +return Type1 +end +__FILES["font/type1/Charstring"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted +-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side +-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, +-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; +-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, +-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the +-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +local Charstring = {} +-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result + + + + +local readu8 = buffer.readu8 + +function Charstring.run(cs, ctx) +local cmds= {} + local stack= {} + local sp = 0 + local ps= {} -- the PostScript stack callothersubr / pop use + local x, y = 0, 0 + local advance, sbx = 0, 0 + local open = false + local flex = false + local flexPts= {} + local budget = 200000 + local finished = false + + local function push(v) + if sp < 48 then + sp =sp+ 1 + stack[sp] = v + end + end + local function arg(i) +return stack[i] or 0 + end + local function close() + if open then + table.insert(cmds, { op = "close" }) + open = false + end + end + local function moveTo(dx, dy) + x =x+ dx + y =y+ dy + if flex then + table.insert(flexPts, x) + table.insert(flexPts, y) + return + end + close() + local c= { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function ensureOpen() + if not open then + -- a drawing operator without a moveto starts at the current point + local c= { op = "moveTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + open = true + end + end + local function lineTo(dx, dy) + ensureOpen() + x =x+ dx + y =y+ dy + local c= { op = "lineTo" } + c[1], c[2] = x, y + table.insert(cmds, c) + end + local function curveTo(a, b, c, d, e, f) + ensureOpen() + local x1, y1 = x + a, y + b + local x2, y2 = x1 + c, y1 + d + x, y = x2 + e, y2 + f + local cmd= { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y + table.insert(cmds, cmd) + end + + local function exec(b, depth) +if depth > 10 then + return "subroutines nested too deep" + end + local n = buffer.len(b) + local p = 0 + while p < n do +local __DARKLUA_CONTINUE_1=false repeat budget =budget- 1 + if budget <= 0 then + return "operation budget exceeded" + end + local v = readu8(b, p) + p =p+ 1 + if v >= 32 then + if v <= 246 then + push(v - 139) + elseif v <= 250 then + if p >= n then + return "truncated number" + end + push((v - 247) * 256 + readu8(b, p) + 108) + p =p+ 1 + elseif v <= 254 then + if p >= n then + return "truncated number" + end + push(-(v - 251) * 256 - readu8(b, p) - 108) + p =p+ 1 + else + if p + 4 > n then + return "truncated number" + end + local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3) + push((u >= 0x80000000 and((u - 0x100000000 ))or(u))) + p =p+ 4 + end +__DARKLUA_CONTINUE_1=true break + end + local op = v + if op == 12 then + if p >= n then + return "truncated escape" + end + op = 1200 + readu8(b, p) + p =p+ 1 + end + if op == 13 then -- hsbw + sbx, advance = arg(1), arg(2) + x, y = sbx, 0 + sp = 0 + elseif op == 1207 then -- sbw + sbx, advance = arg(1), arg(3) + x, y = arg(1), arg(2) + sp = 0 + elseif op == 21 then + moveTo(arg(1), arg(2)) + sp = 0 + elseif op == 22 then + moveTo(arg(1), 0) + sp = 0 + elseif op == 4 then + moveTo(0, arg(1)) + sp = 0 + elseif op == 5 then + lineTo(arg(1), arg(2)) + sp = 0 + elseif op == 6 then + lineTo(arg(1), 0) + sp = 0 + elseif op == 7 then + lineTo(0, arg(1)) + sp = 0 + elseif op == 8 then + curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6)) + sp = 0 + elseif op == 30 then -- vhcurveto + curveTo(0, arg(1), arg(2), arg(3), arg(4), 0) + sp = 0 + elseif op == 31 then -- hvcurveto + curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4)) + sp = 0 + elseif op == 9 then + close() + sp = 0 + elseif op == 10 then -- callsubr + local idx = arg(sp) + sp = math.max(0, sp - 1) + local sub = ctx.subrs[idx + 1] + if not sub then + return "call of a missing subroutine " .. idx + end + local err = exec(sub, depth + 1) + if err or finished then + return err + end + elseif op == 11 then -- return + return nil + elseif op == 14 then -- endchar + close() + finished = true + return nil + elseif op == 1212 then -- div + if sp >= 2 then + local d = stack[sp] + stack[sp - 1] = (d ~= 0 and((stack[sp - 1] / d ))or(0 +)) sp =sp- 1 + end + elseif op == 1216 then -- callothersubr: args... n othersubr# + local num = arg(sp) + local count = arg(sp - 1) + sp = math.max(0, sp - 2) + count = math.clamp(count, 0, sp) + local args = {} + for i = 1, count do + args[i] = stack[sp - count + i] + end + sp =sp- count + if num == 1 then + flex = true + table.clear(flexPts) + elseif num == 2 then + -- a flex point: the rmoveto before it already recorded the point + elseif num == 0 and flex then + flex = false + -- flexPts: the reference point, then 6 control / end points + local f = flexPts + if #f >= 14 then + -- restore the current point to before the flex sequence's moves + local function curve(i) + ensureOpen() + local cmd= { op = "cubicTo" } + cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5] + table.insert(cmds, cmd) + end + curve(3) + curve(9) + x, y = f[13], f[14] + end + table.clear(ps) + table.insert(ps, args[3] or y) + table.insert(ps, args[2] or x) + elseif num == 3 then + table.clear(ps) + table.insert(ps, 3) + else + table.clear(ps) + for i = #args, 1, -1 do + table.insert(ps, args[i]) + end + end + elseif op == 1217 then -- pop + push(table.remove(ps) or 0) + elseif op == 1233 then -- setcurrentpoint + x, y = arg(1), arg(2) + sp = 0 + elseif op == 1206 then -- seac: asb adx ady bchar achar + local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5) + sp = 0 + local seac = ctx.seac + if not seac then + return "seac without base glyphs" + end + local base = seac(bchar) + local accent = seac(achar) + if not base or not accent then + return "seac of a missing glyph" + end + close() + for _, c in __iter(base.cmds) do + table.insert(cmds, c) + end + local ox, oy = adx - asb, ady + for _, c in __iter(accent.cmds) do + local t= { op = c.op } + for i = 1, #c, 2 do + t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy + end + table.insert(cmds, t) + end + finished = true + return nil + elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then + sp = 0 -- hints + else + sp = 0 -- unknown operators clear the stack + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + return nil + end + + local err = exec(cs, 0) + if err then + return nil, err + end + close() + return { cmds = cmds, advance = advance, sbx = sbx }, nil +end + +return Charstring +end +__FILES["font/woff"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding +-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended +-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Deflate = __include("codecs/compress/Deflate") +local TrueType = __include("codecs/font/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff = { + name = "woff", + category = "font", + extensions = { "woff" }, + mime = { "font/woff" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function Woff.sniff(r) +return r:peek(4) == "wOFF" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err +function Woff.sfnt(r, opts) +local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local base = r.base + if not r:match("wOFF") then + return nil, Err.new(Err.CORRUPT, "bad signature", base), nil + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local total = r:u32be() + r:skip(4) + local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be() + r:skip(8) + if r.err then + return nil, r.err, nil + end + if flavor == "ttcf" then + return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4), nil + end + if length > r:size() then + return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8), nil + end + if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then + return nil, Err.new((total > maxBytes and{Err.LIMIT }or{Err.CORRUPT})[1], "bad table count or sfnt size", base + 12), nil + end + local dir = {} + for i = 1, numTables do + local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() } + dir[i] = e + end + if r.err then + return nil, r.err, nil + end + local out = buffer.create(total) + local w = Bytes.writer(12) + w:string(flavor) + w:u16be(numTables) + local es, sel = 1, 0 + while es * 2 <= numTables do + es =es* 2 + sel =sel+ 1 + end + w:u16be(es * 16) + w:u16be(sel) + w:u16be(numTables * 16 - es * 16) + buffer.copy(out, 0, w.buf, 0, 12) + local p = 12 + 16 * numTables + for i, e in __iter(dir) do + if e.offset + e.comp > r:size() or e.comp > e.orig then + return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20), nil + end + if p + e.orig > total then + return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16), nil + end + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, e.tag) + buffer.writeu32(out, d + 4, bit32.byteswap(e.sum)) + buffer.writeu32(out, d + 8, bit32.byteswap(p)) + buffer.writeu32(out, d + 12, bit32.byteswap(e.orig)) + if e.comp < e.orig then + local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig) + if not t then + return nil, Err.new((err ).code, "table " .. e.tag .. ": " .. (err ).message, base + e.offset), nil + end + buffer.copy(out, p, t, 0, e.orig) + else + buffer.copy(out, p, r.buf, base + e.offset, e.orig) + end + p =p+ e.orig + p = math.floor((p + 3) / 4 )* 4 + if p > total then + p = total + end + end + local xml = nil + if metaLength > 0 and metaOffset + metaLength <= r:size() then + local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig) + if m then + xml = buffer.tostring(m) + end + end + return out, nil, xml +end + +function Woff.decode(r, opts) +local sfnt, err, xml = Woff.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.woffMetadata = xml + font.meta.source = { format = "woff", outlines = font.meta.outlines } + return font, nil +end + +return Woff +end +__FILES["font/woff2"] = function() +--!strict +-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx +-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF +-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local TrueType = __include("codecs/font/TrueType") +local Rebuild = __include("font/woff2/Rebuild") + +-- ------------------------------------------------------------------------------------------------ contract +local Woff2 = { + name = "woff2", + category = "font", + extensions = { "woff2" }, + mime = { "font/woff2" }, + deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } }, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function Woff2.sniff(r) +return r:peek(4) == "wOF2" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err +function Woff2.sfnt(r, opts) +local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 + local at = r.base + local out, msg, code = Rebuild.sfnt(r, maxBytes) + if not out then + return nil, Err.from(msg or "rebuild failed", at, code or "corrupt") + end + return out, nil +end + +function Woff2.decode(r, opts) +local sfnt, err = Woff2.sfnt(r, opts) + if not sfnt then + return nil, err + end + local font, ferr = TrueType.font(sfnt) + if not font then + return nil, ferr + end + font.meta.source = { format = "woff2", outlines = font.meta.outlines } + return font, nil +end + +return Woff2 +end +__FILES["font/woff2/Rebuild"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table +-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, +-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx +-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). +-- +-- Never throws: malformed data returns nil, message. +local Bytes = __include("core/Bytes") +local Brotli = __include("codecs/compress/Brotli") + +local Rebuild = {} + +local readu8 = buffer.readu8 +local band, rshift = bit32.band, bit32.rshift + +local KNOWN = { + "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", + "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", + "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", + "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", + "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill", +} + +-- UIntBase128 from r +local function base128(r) +local v = 0 + for i = 1, 5 do + local b = r:u8() + if r.err or (i == 1 and b == 0x80) then + return nil + end + if v >= 2 ^ 25 then + return nil + end + v = v * 128 + band(b, 0x7F) + if b < 0x80 then + return v + end + end + return nil +end +-- a cursor over a stream inside the decompressed block + + +local function stream(b, p, n) +return { buf = b, p = p, e = p + n, bad = false } +end +local function su8(s) +if s.p >= s.e then + s.bad = true + return 0 + end + local v = readu8(s.buf, s.p) + s.p =s.p+ 1 + return v +end +local function su16(s) +return su8(s) * 256 + su8(s) +end +local function si16(s) +local v = su16(s) + return (v >= 32768 and((v - 65536 ))or(v +))end +local function s255(s) +local c = su8(s) + if c == 253 then + return su16(s) + elseif c == 255 then + return su8(s) + 253 + elseif c == 254 then + return su8(s) + 506 + end + return c +end + +local function withSign(flag, v) +return (band(flag, 1) ~= 0 and{v }or{(-v +)})[1]end + +-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat +local function glyf(b, p, n, maxBytes) +local h = stream(b, p, n) + su16(h) -- reserved + local option = su16(h) + local numGlyphs = su16(h) + local indexFormat = su16(h) + local sizes = {} + for i = 1, 7 do + sizes[i] = su16(h) * 65536 + su16(h) + end + if h.bad then + return nil, "truncated glyf transform header" + end + local at = h.p + local streams= {} + for i = 1, 7 do + if at + sizes[i] > p + n then + return nil, "glyf transform stream past the end" + end + streams[i] = stream(b, at, sizes[i]) + at =at+ sizes[i] + end + local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7] + local overlap= nil + if band(option, 1) ~= 0 then + overlap = stream(b, at, math.floor((numGlyphs + 7) / 8)) + if at + math.floor((numGlyphs + 7) / 8 )> p + n then + return nil, "overlap bitmap past the end" + end + end + -- the bbox bitmap leads the bbox stream + local bitmapLen = 4 * (math.floor((numGlyphs + 31) / 32)) + if bitmapLen > sizes[6] then + return nil, "bbox bitmap past the end" + end + local bboxBits = bboxS.p + bboxS.p =bboxS.p+ bitmapLen + local function hasBox(g) +return band(readu8(b, bboxBits + math.floor(g / 8)), rshift(0x80, g % 8)) ~= 0 + end + local w = Bytes.writer(n * 2) + local loca = table.create(numGlyphs + 1, 0) + local xMins = table.create(numGlyphs, 0) + for g = 0, numGlyphs - 1 do + loca[g + 1] = w.pos + local nc = si16(nContour) + if nContour.bad then + return nil, "nContour stream truncated" + end + if nc == 0 then + if hasBox(g) then + return nil, "empty glyph with a bounding box" + end + elseif nc > 0 then + -- simple glyph + local ends = table.create(nc, 0) + local total = 0 + for c = 1, nc do + total =total+ s255(nPoints) + ends[c] = total - 1 + end + if nPoints.bad or total > 65535 then + return nil, "bad point counts" + end + local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false) + local x, y = 0, 0 + for k = 1, total do + local fl = su8(flagS) + on[k] = rshift(fl, 7) == 0 + fl = band(fl, 0x7F) + local dx, dy + if fl < 10 then + dx = 0 + dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS)) + elseif fl < 20 then + dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS)) + dy = 0 + elseif fl < 84 then + local b0 = fl - 20 + local b1 = su8(glyphS) + dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4)) + dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F)) + elseif fl < 120 then + local b0 = fl - 84 + dx = withSign(fl, 1 + (math.floor(b0 / 12)) * 256 + su8(glyphS)) + dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS)) + elseif fl < 124 then + local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 16 + rshift(b2, 4)) + dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3) + else + local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS) + dx = withSign(fl, b1 * 256 + b2) + dy = withSign(rshift(fl, 1), b3 * 256 + b4) + end + x =x+ dx + y =y+ dy + xs[k], ys[k] = x, y + end + local ilen = s255(glyphS) + if flagS.bad or glyphS.bad then + return nil, "flag / glyph stream truncated" + end + local x0, y0, x1, y1 + if hasBox(g) then + x0 = si16(bboxS) + y0 = si16(bboxS) + x1 = si16(bboxS) + y1 = si16(bboxS) + else + x0, y0, x1, y1 = 32767, 32767, -32768, -32768 + for k = 1, total do + x0 = math.min(x0, xs[k]) + y0 = math.min(y0, ys[k]) + x1 = math.max(x1, xs[k]) + y1 = math.max(y1, ys[k]) + end + if total == 0 then + x0, y0, x1, y1 = 0, 0, 0, 0 + end + end + xMins[g + 1] = x0 + w:u16be(nc % 65536) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + for c = 1, nc do + w:u16be(ends[c]) + end + w:u16be(ilen) + if instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:bytes(b, instrS.p, ilen) + instrS.p =instrS.p+ ilen + local ov = overlap ~= nil and band(readu8(b, (overlap ).p + math.floor(g / 8)), rshift(0x80, g % 8)) ~= 0 + -- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them + local fls = table.create(total, 0) + for k = 1, total do + local fl = on[k] and 1 or 0 + if k == 1 and ov then + fl =fl+ 0x40 + end + local dx = xs[k] - ((k > 1 and{xs[k - 1] }or{0})[1]) + local dy = ys[k] - ((k > 1 and{ys[k - 1] }or{0})[1]) + if dx == 0 then + fl =fl+ 0x10 + elseif dx > -256 and dx < 256 then + fl =fl+ (dx > 0 and 0x12 or 0x02 +) end + if dy == 0 then + fl =fl+ 0x20 + elseif dy > -256 and dy < 256 then + fl =fl+ (dy > 0 and 0x24 or 0x04 +) end + fls[k] = fl + end + local k = 1 + while k <= total do + local fl = fls[k] + local run = 0 + while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do + run =run+ 1 + end + if run > 1 then + w:u8(fl + 8) + w:u8(run) + k =k+ (run + 1 +) else + w:u8(fl) + k =k+ 1 + end + end + for pass = 0, 1 do + local cs = (pass == 0 and{xs }or{ys +})[1] local short, same = pass == 0 and 0x02 or 0x04, pass == 0 and 0x10 or 0x20 + local prev = 0 + for q = 1, total do + local d = cs[q] - prev + prev = cs[q] + local fl = fls[q] + if band(fl, short) ~= 0 then + w:u8(math.abs(d)) + elseif band(fl, same) == 0 then + w:u16be(d % 65536) + end + end + end + elseif nc == -1 then + if not hasBox(g) then + return nil, "composite glyph without a bounding box" + end + local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS) + xMins[g + 1] = x0 + w:u16be(0xFFFF) + w:u16be(x0 % 65536) + w:u16be(y0 % 65536) + w:u16be(x1 % 65536) + w:u16be(y1 % 65536) + -- copy the component records: their length follows from the flags + local start = compS.p + local instr = false + while true do + local fl = su16(compS) + su16(compS) -- glyph index + local len = band(fl, 1) ~= 0 and 4 or 2 + if band(fl, 8) ~= 0 then + len =len+ 2 + elseif band(fl, 0x40) ~= 0 then + len =len+ 4 + elseif band(fl, 0x80) ~= 0 then + len =len+ 8 + end + compS.p =compS.p+ len + if band(fl, 0x100) ~= 0 then + instr = true + end + if compS.bad or compS.p > compS.e then + return nil, "composite stream truncated" + end + if band(fl, 0x20) == 0 then + break + end + end + w:bytes(b, start, compS.p - start) + if instr then + local ilen = s255(glyphS) + if glyphS.bad or instrS.p + ilen > instrS.e then + return nil, "instruction stream truncated" + end + w:u16be(ilen) + w:bytes(b, instrS.p, ilen) + instrS.p =instrS.p+ ilen + end + else + return nil, "bad contour count " .. nc + end + if bboxS.bad then + return nil, "bbox stream truncated" + end + -- 4-byte alignment + while w.pos % 4 ~= 0 do + w:u8(0) + end + if w.pos > maxBytes then + return nil, "limit" + end + end + loca[numGlyphs + 1] = w.pos + if indexFormat == 0 and w.pos > 0x1FFFE then + indexFormat = 1 -- (head.indexToLocFormat is patched to match) + end + return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil +end + +-- hmtx transform (version 1): advances + the side bearings that were not dropped +local function hmtx(b, p, n, numGlyphs, numH, xMins) +local s = stream(b, p, n) + local flags = su8(s) + local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2) + local adv = table.create(numH, 0) + for i = 1, numH do + adv[i] = su16(s) + end + local lsb = table.create(numGlyphs, 0) + for i = 1, numH do + lsb[i] = (band(flags, 1) == 0 and{(si16(s) )}or{(xMins[i] or 0) +})[1] end + for i = numH + 1, numGlyphs do + lsb[i] = (band(flags, 2) == 0 and{(si16(s) )}or{(xMins[i] or 0) +})[1] end + if s.bad then + return nil, "hmtx transform truncated" + end + for i = 1, numH do + out:u16be(adv[i]) + out:u16be(lsb[i] % 65536) + end + for i = numH + 1, numGlyphs do + out:u16be(lsb[i] % 65536) + end + return out:finish(), nil +end + +-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") +function Rebuild.sfnt(r, maxBytes) +if not r:match("wOF2") then + return nil, "bad signature", "corrupt" + end + local flavor = r:string(4) + local length = r:u32be() + local numTables = r:u16be() + r:skip(2) + local totalSfnt = r:u32be() + local totalComp = r:u32be() + r:skip(24) + if r.err then + return nil, "truncated header", "truncated" + end + if flavor == "ttcf" then + return nil, "font collections in WOFF2", "unsupported" + end + if length > r:size() then + return nil, "file shorter than its header says", "truncated" + end + if numTables == 0 or numTables > 1024 then + return nil, "bad table count", "corrupt" + end + local dir = {} + local streamTotal = 0 + for i = 1, numTables do + local flags = r:u8() + local tag = KNOWN[band(flags, 63) + 1] + if band(flags, 63) == 63 then + tag = r:string(4) + end + local version = rshift(flags, 6) + local orig = base128(r) + if not tag or not orig then + return nil, "bad table directory entry " .. i, r.err and"truncated" or"corrupt" + end + local transformed = ((tag == "glyf" or tag == "loca" )and{(version == 0 )}or{(version ~= 0 +)})[1] local tlen = orig + if transformed then + local t = base128(r) + if not t then + return nil, "bad transformLength", "corrupt" + end + tlen = t + end + if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then + return nil, "bad glyf / loca transform version", "corrupt" + end + if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then + return nil, "unknown transform of " .. tag, "unsupported" + end + dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal } + streamTotal =streamTotal+ tlen + if streamTotal > maxBytes or orig > maxBytes then + return nil, "limit", "limit" + end + end + local compAt = r.pos + if compAt + totalComp > r.limit then + return nil, "compressed data past the end", "truncated" + end + local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) }) + if not data then + local e = berr +return nil, "brotli: " .. tostring(e.message), e.code == "LIMIT" and"limit" or"corrupt" + end + if buffer.len(data) < streamTotal then + return nil, "decompressed stream shorter than the tables", "corrupt" + end + -- the tables, glyf / loca / hmtx rebuilt + local byTag= {} + for _, e in __iter(dir) do + byTag[e.tag] = e + end + local tables= {} + local g = byTag.glyf + local xMins= {} + local locaLong= nil + if g and g.transformed then + if not byTag.loca then + return nil, "glyf without loca", "corrupt" + end + local res, gerr = glyf(data, g.at, g.len, maxBytes) + if not res then + return nil, "glyf: " .. tostring(gerr), gerr == "limit" and"limit" or"corrupt" + end + tables.glyf = res.glyf + xMins = res.xMins + local short = res.indexFormat == 0 + local lw = Bytes.writer((res.numGlyphs + 1) * 4) + for _, o in __iter(res.loca) do + if short then + lw:u16be(math.floor(o / 2)) + else + lw:u32be(o) + end + end + tables.loca = lw:finish() + locaLong = not short + end + for _, e in __iter(dir) do + if e.tag == "glyf" or e.tag == "loca" then + if not e.transformed then + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + elseif e.tag == "hmtx" and e.transformed then + -- needs numGlyphs (maxp) and numberOfHMetrics (hhea) + local mp, hh = byTag.maxp, byTag.hhea + if not mp or not hh or mp.len < 6 or hh.len < 36 then + return nil, "hmtx transform without maxp / hhea", "corrupt" + end + local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5) + local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35) + if numH < 1 or numH > numGlyphs then + return nil, "bad numberOfHMetrics", "corrupt" + end + local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins) + if not t then + return nil, herr, "corrupt" + end + tables.hmtx = t + else + local t = buffer.create(e.len) + buffer.copy(t, 0, data, e.at, e.len) + tables[e.tag] = t + end + end + -- head.indexToLocFormat must agree with the rebuilt loca + if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then + buffer.writeu8(tables.head, 50, 0) + buffer.writeu8(tables.head, 51, locaLong and 1 or 0) + end + -- the sfnt: directory sorted by tag, tables 4-byte aligned + local tags = {} + for t in __iter(tables) do + table.insert(tags, t) + end + table.sort(tags) + local n = #tags + local size = 12 + 16 * n + for _, t in __iter(tags) do + size =size+ math.floor((buffer.len(tables[t]) + 3) / 4 )* 4 + end + if size > maxBytes then + return nil, "limit", "limit" + end + local out = buffer.create(size) + buffer.writestring(out, 0, flavor) + local es, sel = 1, 0 + while es * 2 <= n do + es =es* 2 + sel =sel+ 1 + end + local function be16(o, v) + buffer.writeu8(out, o, rshift(v, 8)) + buffer.writeu8(out, o + 1, band(v, 255)) + end + local function be32(o, v) + buffer.writeu32(out, o, bit32.byteswap(v)) + end + be16(4, n) + be16(6, es * 16) + be16(8, sel) + be16(10, n * 16 - es * 16) + local p = 12 + 16 * n + for i, t in __iter(tags) do + local tb = tables[t] + local d = 12 + (i - 1) * 16 + buffer.writestring(out, d, t) + be32(d + 4, 0) -- checksums are not recomputed + be32(d + 8, p) + be32(d + 12, buffer.len(tb)) + buffer.copy(out, p, tb) + p =p+ math.floor((buffer.len(tb) + 3) / 4 )* 4 + end + local _ = totalSfnt + return out, nil, nil +end + +return Rebuild +end +__FILES["host"] = function() +local __compat = __compat local typeof, type = __compat.typeof, __compat.type --!strict +-- host: the runtime adapter, detected once at load time. Roblox (no file system; toEditableImage), LÖVE +-- (love.filesystem + io; toImageData / toSoundData), plain LuaJIT (io), the Luau CLI (no file system). +-- +-- local host = require("rosetta.host") +-- print(host.name) -- "roblox" | "love" | "luajit" | "luau" +-- local buf, err = host.readFile("a.png") -- every host has readFile / writeFile / exists (failing with Err.IO +-- -- where there is no file system) +local Err = __include("core/Err") + + + + + + + + + + +local G = _G +local name +if typeof(game) == "Instance" then + name = "roblox" +elseif G.love ~= nil and type(G.love) == "table" and G.love.filesystem ~= nil then + name = "love" +elseif G.jit ~= nil or G.io ~= nil then + name = "luajit" +else + name = "luau" +end + +local host +if name == "roblox" then + host = (__include("host/Roblox") ) +elseif name == "love" then + host = (__include("host/Love") ) +elseif name == "luajit" then + host = (__include("host/LuaJIT") ) +else + host = (__include("host/Luau") ) +end +-- LuaJIT (plain or LÖVE): the big decoders (Opus CELT, H.264, ...) outgrow the default 1000 traces / 8 MB of machine +-- code and fall back to the interpreter (CELT runs about 2.5x faster with these limits). Raising the limits only +-- allows more traces; set _G.ROSETTA_NO_JIT_TUNE = true before requiring the library to leave them alone. +if G.jit ~= nil and type(G.jit.opt) == "table" and not G.ROSETTA_NO_JIT_TUNE then + pcall(G.jit.opt.start, "maxtrace=8000", "maxmcode=65536") +end + +local _ = Err +return host +end +__FILES["host/Love"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- host/Love: LÖVE 11+. Files through love.filesystem (the game folder and the save directory), falling back to io for +-- paths outside them; converts the standard types to LÖVE objects: +-- host.toImageData(img) -> love ImageData (rgba8) +-- host.fromImageData(imageData) -> Image (rgba8) +-- host.toSoundData(audio) -> love SoundData (an Audio, or a Decoder decoded to the end; 16-bit) +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "love" +Host.hasFiles = true + +local function love() +return (_G ).love +end +local function io() +return (_G ).io +end +-- the FFI, when the build runs on LuaJIT (always, under LÖVE); called through _G so the build leaves it alone +local function ffi() +local req = (_G ).require + local ok, m = pcall(req, "ffi") + return (ok and{m }or{nil +})[1]end + +function Host.readFile(path) +local fs = love().filesystem + if fs.getInfo(path, "file") then + local s, msg = fs.read(path) + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path .. ": " .. tostring(msg)) + end + return buffer.fromstring(s), nil + end + local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + return buffer.fromstring(s), nil +end + +-- writeFile: relative paths go to the save directory (love.filesystem.write), absolute ones through io +function Host.writeFile(path, data) +local s = buffer.tostring(data) + if string.sub(path, 1, 1) ~= "/" and not string.find(path, "^%a:[/\\]") then + local ok, msg = love().filesystem.write(path, s) + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(msg)) + end + return true, nil + end + local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + f:write(s) + f:close() + return true, nil +end + +function Host.exists(path) +if love().filesystem.getInfo(path, "file") then + return true + end + local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +-- toImageData(img) -> ImageData | nil, Err +function Host.toImageData(img) +if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toImageData: needs rgba8 pixels, got " .. tostring(img.format)) + end + local n = img.width * img.height * 4 + local F= ffi() + local B= buffer +if F and B.toffi then + local id = love().image.newImageData(img.width, img.height, "rgba8") + F.copy(id:getFFIPointer(), B.toffi(img.pixels), n) + return id + end + local bytes = love().data.newByteData(buffer.readstring(img.pixels, 0, n)) + return love().image.newImageData(img.width, img.height, "rgba8", bytes) +end + +-- fromImageData(imageData) -> Image (rgba8 copy) +function Host.fromImageData(id) +local w, h = id:getDimensions() + local img = Types.Image.new(w, h, "rgba8") + local F= ffi() + local B= buffer +if F and B.toffi and id:getFormat() == "rgba8" then + F.copy(B.toffi(img.pixels), id:getFFIPointer(), w * h * 4) + return img + end + local s = id:getString() + buffer.writestring(img.pixels, 0, s, math.min(#s, w * h * 4)) + return img +end + +-- toSoundData(audio) -> SoundData (16-bit). audio: an Audio, or a Decoder (decoded to the end). +function Host.toSoundData(a) +local samples, frames, channels, rate = a.samples, a.frames, a.channels, a.sampleRate + if samples == nil then + -- a Decoder: read everything + local parts, total = {}, 0 + while true do + local out, n = a:read(65536) + if n == 0 then + break + end + local copy = buffer.create(n * channels * 4) + buffer.copy(copy, 0, out, 0, n * channels * 4) + table.insert(parts, copy) + total =total+ n + end + samples = buffer.create(total * channels * 4) + local o = 0 + for _, p in __iter(parts) do + buffer.copy(samples, o, p) + o =o+ buffer.len(p) + end + frames = total + end + local sd = love().sound.newSoundData(math.max(frames, 1), rate, 16, channels) + local count = frames * channels + local F= ffi() + if F then + local p = F.cast("int16_t*", sd:getFFIPointer()) + for i = 0, count - 1 do + local v = math.clamp(buffer.readf32(samples, i * 4), -1, 1) + p[i] = math.floor(v * 32767 + 0.5) + end + else + for i = 0, count - 1 do + sd:setSample(i, math.clamp(buffer.readf32(samples, i * 4), -1, 1)) + end + end + return sd +end + +return Host +end +__FILES["host/LuaJIT"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- host/LuaJIT: plain LuaJIT (or any Lua with io): files through io.open. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luajit" +Host.hasFiles = true + +local function io() +return (_G ).io +end + +function Host.readFile(path) +local f, msg = io().open(path, "rb") + if not f then + return nil, Err.new(Err.IO, "cannot open " .. path .. ": " .. tostring(msg)) + end + local s = f:read("*a") + f:close() + if type(s) ~= "string" then + return nil, Err.new(Err.IO, "cannot read " .. path) + end + return buffer.fromstring(s), nil +end + +function Host.writeFile(path, data) +local f, msg = io().open(path, "wb") + if not f then + return false, Err.new(Err.IO, "cannot create " .. path .. ": " .. tostring(msg)) + end + local ok, werr = f:write(buffer.tostring(data)) + f:close() + if not ok then + return false, Err.new(Err.IO, "cannot write " .. path .. ": " .. tostring(werr)) + end + return true, nil +end + +function Host.exists(path) +local f = io().open(path, "rb") + if f then + f:close() + return true + end + return false +end + +return Host +end +__FILES["host/Luau"] = function() +--!strict +-- host/Luau: the Luau CLI (and any embedding without io): no file system. Sources are buffers or strings. +local Err = __include("core/Err") + +local Host = {} +Host.name = "luau" +Host.hasFiles = false + +function Host.readFile(path) +return nil, Err.new(Err.IO, "no file system on this host (luau): pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path, _data) +return false, Err.new(Err.IO, "no file system on this host (luau): cannot write " .. path) +end + +function Host.exists(_path) +return false +end + +return Host +end +__FILES["host/Roblox"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- host/Roblox: no file system (sources are buffers or strings, e.g. from HttpService or an asset); converts the +-- standard types to engine objects: +-- host.toEditableImage(img) -> EditableImage (rgba8; other formats are converted by the caller first) +-- host.meshPages(prim, opts?) -> { MeshPage } a triangle Primitive split into pages that fit one EditableMesh +-- host.pageData(prim, page, opts?) -> PageData a page's vertices as flat arrays (scaled, centred, sRGB colours) +-- host.toEditableMesh(prim, page?, opts?) -> EditableMesh, centre one page as an EditableMesh +-- meshPages / pageData are pure (no engine calls: tests/host/roblox.luau runs them on every runtime). +local Err = __include("core/Err") +local Types = __include("Types") + +local Host = {} +Host.name = "roblox" +Host.hasFiles = false + +function Host.readFile(path) +return nil, Err.new(Err.IO, "Roblox has no file system: pass a buffer or a string, not the path " .. path) +end + +function Host.writeFile(path, _data) +return false, Err.new(Err.IO, "Roblox has no file system: cannot write " .. path .. " (use F.save(value) for a buffer)") +end + +function Host.exists(_path) +return false +end + +-- toEditableImage(img) -> EditableImage | nil, Err. img.format must be "rgba8". +function Host.toEditableImage(img) +if img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "toEditableImage: needs rgba8 pixels, got " .. tostring(img.format)) + end + local AssetService = (game ):GetService("AssetService") + local size = Vector2.new(img.width, img.height) + local ok, ei = pcall(function() + return AssetService:CreateEditableImage({ Size = size }) + end) + if not ok or not ei then + return nil, Err.new(Err.IO, "CreateEditableImage failed: " .. tostring(ei)) + end + ei:WritePixelsBuffer(Vector2.zero, size, img.pixels) + return ei +end +-- ---------------------------------------------------------------------------------------------------------- meshes +-- A triangle Primitive (F.ops.mesh.merge gives one in world space) becomes EditableMeshes page by page. One +-- EditableMesh holds at most ~20k triangles and 60k vertices (measured in Studio: surfacenet-luau MeshOut), and a client +-- has only 8 growable ones at a time: build a page, turn it into what you keep (a MeshPart, a FixedSize copy through +-- AssetService:CreateEditableMeshAsync), destroy it, then build the next. +-- +-- local prims = F.ops.mesh.merge(scene, { byMaterial = true }) +-- for _, prim in prims do +-- for _, page in assert(F.host.meshPages(prim)) do +-- local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs +-- local part = AssetService:CreateMeshPartAsync(Content.fromObject(em)) +-- part.Position = Vector3.new(centre[1], centre[2], centre[3]) +-- end +-- end +-- +-- Axes: Roblox is right-handed, y up, like glTF: z-up sources (STL, VOX, CAD) go through F.ops.mesh.setUp(scene, "y") +-- before merging. Winding: counter-clockwise front faces, as glTF. UVs keep the glTF top-left origin (opts.flipV +-- turns them over). Colours: COLOR_0 is linear (glTF); EditableMesh colours are sRGB, so they are converted. +-- the index of each corner (0-based vertex numbers) or nil, Err + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function cornerReader(prim) +local idx = prim.indices + if not idx then + return function(i) +return i + end + end + local get = Types.Scene.reader(idx) + if not get then + return nil + end + return function(i) +return (get )(i, 0) + end +end + +local function checkPrim(prim) +if type(prim) ~= "table" or type(prim.attributes) ~= "table" or type(prim.attributes.POSITION) ~= "table" then + return 0, Err.new(Err.ARG, "expected a Primitive with POSITION") + end + if (prim.mode or "triangles") ~= "triangles" then + return 0, Err.new(Err.ARG, "needs a triangle primitive (F.ops.mesh.merge or triangulate first), got " .. tostring(prim.mode)) + end + local n = (prim.indices and{prim.indices.count }or{prim.attributes.POSITION.count +})[1] return math.floor(n / 3), nil +end + +-- meshPages(prim, opts?) -> { MeshPage } | nil, Err: consecutive triangle runs, each within maxTriangles (back faces +-- counted when doubleSided) and maxVertices. +function Host.meshPages(prim, opts) +local tris, err = checkPrim(prim) + if err then + return nil, err + end + local o= opts or {} + local per = o.doubleSided and 2 or 1 + local maxT = math.max(1, math.floor((o.maxTriangles or 20000) / per)) + local maxV = math.max(3, o.maxVertices or 60000) + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + local corner = cornerReader(prim) + if not getP or not corner then + return nil, Err.new(Err.ARG, "unsupported accessor type") + end + local nv = pos.count + local pages= {} + local t = 0 + while t < tris do + local map= {} + local verts= {} + local first = t + local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local cs= {} + while t < tris and t - first < maxT do + local a, b, c = corner(t * 3), corner(t * 3 + 1), corner(t * 3 + 2) + if a >= nv or b >= nv or c >= nv or a < 0 or b < 0 or c < 0 then + return nil, Err.new(Err.ARG, string.format("triangle %d: vertex index out of range", t)) + end + local fresh = (map[a] and 0 or 1) + ((map[b] or b == a )and 0 or 1) + ((map[c] or c == a or c == b )and 0 or 1) + if #verts + fresh > maxV and t > first then + break + end + for _, v in __iter({ a, b, c }) do + local l = map[v] + if not l then + l = #verts + verts[l + 1] = v + map[v] = l + for k = 1, 3 do + local x = (getP )(v, k - 1) + if x < lo[k] then + lo[k] = x + end + if x > hi[k] then + hi[k] = x + end + end + end + cs[#cs + 1] = l + end + t =t+ 1 + end + local corners = buffer.create(#cs * 4) + for i, l in __iter(cs) do + buffer.writeu32(corners, (i - 1) * 4, l) + end + pages[#pages + 1] = { first = first, count = t - first, vertices = verts, corners = corners, min = lo, max = hi } + end + return pages, nil +end + +local function toSrgb(c) +c = math.clamp(c, 0, 1) + return (c <= 0.0031308 and((c * 12.92 ))or((1.055 * c ^ (1 / 2.4) - 0.055 +)))end + +-- pageData(prim, page, opts?) -> PageData | nil, Err: the page's vertex attributes as flat number arrays, ready for +-- engine calls (positions relative to the origin and scaled, unit normals, uvs, sRGB colours). +function Host.pageData(prim, page, opts) +local _, err = checkPrim(prim) + if err then + return nil, err + end + if type(page) ~= "table" or type(page.vertices) ~= "table" or type(page.corners) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a MeshPage from meshPages") + end + local o= opts or {} + local sc = o.scale or 1 + local sx, sy, sz + if type(sc) == "table" then + sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1 + else + sx, sy, sz = sc, sc, sc + end + local origin = o.origin + or { (page.min[1] + page.max[1]) / 2, (page.min[2] + page.max[2]) / 2, (page.min[3] + page.max[3]) / 2 } + local attrs = prim.attributes + local getP = Types.Scene.reader(attrs.POSITION) + local getN = (o.normals ~= false and attrs.NORMAL and{(Types.Scene.reader(attrs.NORMAL) )}or{nil +})[1] local uvAcc = (o.uvs ~= false and{attrs["TEXCOORD_" .. tostring(o.texCoord or 0)] }or{nil +})[1] local getT = (uvAcc and{(Types.Scene.reader(uvAcc) )}or{nil +})[1] local colAcc = (o.colors ~= false and{attrs.COLOR_0 }or{nil +})[1] local getC = (colAcc and{(Types.Scene.reader(colAcc) )}or{nil +})[1] if not getP then + return nil, Err.new(Err.ARG, "unsupported POSITION accessor type") + end + local n = #page.vertices + local positions = table.create(n * 3, 0) + local normals = (getN and{(table.create(n * 3, 0) )}or{nil +})[1] local uvs = (getT and{(table.create(n * 2, 0) )}or{nil +})[1] local colors = (getC and{(table.create(n * 4, 1) )}or{nil +})[1] local ox, oy, oz = origin[1], origin[2], origin[3] + local flip = o.flipV == true + local alpha = colAcc and colAcc.components >= 4 + for i, v in __iter(page.vertices) do + local j = (i - 1) * 3 + positions[j + 1] = ((getP )(v, 0) - ox) * sx + positions[j + 2] = ((getP )(v, 1) - oy) * sy + positions[j + 3] = ((getP )(v, 2) - oz) * sz + if normals then + -- normals of a scaled mesh scale by the inverse + local x, y, z = (getN )(v, 0) / sx, (getN )(v, 1) / sy, (getN )(v, 2) / sz + local len = math.sqrt(x * x + y * y + z * z) + if len > 0 then + x, y, z = x / len, y / len, z / len + else + x, y, z = 0, 1, 0 + end + normals[j + 1], normals[j + 2], normals[j + 3] = x, y, z + end + if uvs then + local u, w = (getT )(v, 0), (getT )(v, 1) + uvs[(i - 1) * 2 + 1] = u + uvs[(i - 1) * 2 + 2] = (flip and((1 - w ))or(w +)) end + if colors then + local k = (i - 1) * 4 + colors[k + 1] = toSrgb((getC )(v, 0)) + colors[k + 2] = toSrgb((getC )(v, 1)) + colors[k + 3] = toSrgb((getC )(v, 2)) + colors[k + 4] = (alpha and{(math.clamp((getC )(v, 3), 0, 1) )}or{1 +})[1] end + end + return { + vertexCount = n, + triangleCount = page.count, + positions = positions, + normals = normals, + uvs = uvs, + colors = colors, + corners = page.corners, + centre = { ox * sx, oy * sy, oz * sz }, + }, nil +end + +-- toEditableMesh(prim, page?, opts?) -> EditableMesh, centre { x, y, z } | nil, Err. Without a page the whole +-- primitive must fit one (else Err.LIMIT: use meshPages). Positions are relative to the centre (place the MeshPart +-- there). Engine errors (no free EditableMesh, limits) come back as Err.IO; a mesh this call created is destroyed then. +function Host.toEditableMesh(prim, page, opts) +local o= opts or {} + local pg = page + if not pg then + local pages, err = Host.meshPages(prim, o) + if not pages then + return nil, err + end + if #pages ~= 1 then + return nil, Err.new(Err.LIMIT, string.format("toEditableMesh: %d pages: split with meshPages", #pages)) + end + pg = pages[1] + end + local data, err = Host.pageData(prim, pg , o) + if not data then + return nil, err + end + local d = data +local em = o.editableMesh + local own = em == nil + if own then + local AssetService = (game ):GetService("AssetService") + local ok, made = pcall(function() + return AssetService:CreateEditableMesh() + end) + if not ok or not made then + return nil, Err.new(Err.IO, "CreateEditableMesh failed (a client has 8 growable EditableMeshes): " .. tostring(made)) + end + em = made + end + local ok, perr = pcall(function() + local P, N, U, C = d.positions, d.normals, d.uvs, d.colors + local vids = table.create(d.vertexCount, 0) + local nids = (N and{(table.create(d.vertexCount, 0) )}or{nil +})[1] local bids = (N and o.doubleSided and{(table.create(d.vertexCount, 0) )}or{nil +})[1] local uids = (U and{(table.create(d.vertexCount, 0) )}or{nil +})[1] local cids = (C and{(table.create(d.vertexCount, 0) )}or{nil +})[1] local palette= {} + for i = 1, d.vertexCount do + local j = (i - 1) * 3 + vids[i] = em:AddVertex(Vector3.new(P[j + 1], P[j + 2], P[j + 3])) + if N and nids then + local n = Vector3.new(N[j + 1], N[j + 2], N[j + 3]) + nids[i] = em:AddNormal(n) + if bids then + bids[i] = em:AddNormal(-n) + end + end + if U and uids then + uids[i] = em:AddUV(Vector2.new(U[(i - 1) * 2 + 1], U[(i - 1) * 2 + 2])) + end + if C and cids then + local k = (i - 1) * 4 + local r, g, b, a = C[k + 1], C[k + 2], C[k + 3], C[k + 4] + -- equal colours share one id (voxel palettes, flat-coloured models) + local key = string.format("%d,%d,%d,%d", math.floor(r * 255 + 0.5), math.floor(g * 255 + 0.5), math.floor(b * 255 + 0.5), math.floor(a * 255 + 0.5)) + local id = palette[key] + if not id then + id = em:AddColor(Color3.new(r, g, b), a) + palette[key] = id + end + cids[i] = id + end + end + local corners = d.corners + local every = o.yieldEvery or 2000 + local yield = o.yield + for t = 0, d.triangleCount - 1 do + local a = buffer.readu32(corners, t * 12) + 1 + local b = buffer.readu32(corners, t * 12 + 4) + 1 + local c = buffer.readu32(corners, t * 12 + 8) + 1 + local f = em:AddTriangle(vids[a], vids[b], vids[c]) + if nids then + em:SetFaceNormals(f, { nids[a], nids[b], nids[c] }) + end + if uids then + em:SetFaceUVs(f, { uids[a], uids[b], uids[c] }) + end + if cids then + em:SetFaceColors(f, { cids[a], cids[b], cids[c] }) + end + if o.doubleSided then + local g = em:AddTriangle(vids[a], vids[c], vids[b]) + if bids then + em:SetFaceNormals(g, { bids[a], bids[c], bids[b] }) + end + if uids then + em:SetFaceUVs(g, { uids[a], uids[c], uids[b] }) + end + if cids then + em:SetFaceColors(g, { cids[a], cids[c], cids[b] }) + end + end + if yield and (t + 1) % every == 0 then + yield() + end + end + end) + if not ok then + if own then + pcall(function() + em:Destroy() + end) + end + return nil, Err.new(Err.IO, "EditableMesh: " .. tostring(perr)) + end + return em, d.centre +end + +return Host +end +__FILES["image/ani"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; +-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, +-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) +-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames +-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors +-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a +-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Riff = __include("containers/Riff") + +-- ------------------------------------------------------------------------------------------------ contract +local Ani = { + name = "ani", + category = "image", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + +function Ani.sniff(r) +return r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ani.decode(r, opts) +local f, ferr = Riff.read(r) + if not f then + return nil, ferr + end + if f.form ~= "ACON" then + return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8) + end + local anih = Riff.find(f, "anih") + if not anih or anih.avail < 36 then + return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12) + end + local a = anih.offset + local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8) + local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32) + local maxFrames = opts and opts.maxFrames or 10000 + if nSteps == 0 then + nSteps = nFrames + end + if nFrames > maxFrames or nSteps > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames", a + 4) + end + if bit32.band(flags, 1) == 0 then + return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32) + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") + end + -- the icon chunks + local icons= {} + for _, c in __iter(f.chunks) do + if c.id == "LIST" and Riff.listType(f, c) == "fram" then + for _, ic in __iter(Riff.list(f, c)) do + if ic.id == "icon" then + local sub = buffer.create(ic.avail) + buffer.copy(sub, 0, f.buf, ic.offset, ic.avail) + local ok, im, ierr = pcall(decodeImage, sub) + if not ok or not im then + return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring((ok and{ierr }or{im})[1]), ic.offset) + end + table.insert(icons, im ) + end + end + end + end + if #icons == 0 then + return nil, Err.new(Err.TRUNCATED, "no icon frames") + end + local rate = Riff.find(f, "rate") + local seq = Riff.find(f, "seq ") + local frames= {} + for s = 0, nSteps - 1 do + local idx = s + if seq and seq.avail >= (s + 1) * 4 then + idx = Riff.u32(f, seq.offset + s * 4) + end + local im = icons[idx + 1] + if not im then + if s >= #icons and not seq then + break -- fewer icons than steps: keep what is there + end + return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) + end + local jiffies = dispRate + if rate and rate.avail >= (s + 1) * 4 then + jiffies = Riff.u32(f, rate.offset + s * 4) + end + table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } ) + end + local first = frames[1].image + local img = Types.Image.new(0, 0, first.format) + img.width, img.height, img.pixels = first.width, first.height, first.pixels + img.frames = frames + img.loops = 0 + img.meta.hotspot = first.meta.hotspot + local text= {} + for _, c in __iter(f.chunks) do + if c.id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, it in __iter(Riff.list(f, c)) do + local key = it.id == "INAM" and"title" or(it.id == "IART" and"author" or nil +) if key then + text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", "")) + end + end + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ani.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook") + end + local frames= (type(img.frames) == "table" and #img.frames > 0 and{img.frames }or{{ { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } } +})[1] local w = Riff.writer("ACON") + local jiffies= {} + local same = true + for i, fr in __iter(frames) do + jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5)) + same = same and jiffies[i] == jiffies[1] + end + local head = Bytes.writer(36) + head:u32le(36) + head:u32le(#frames) + head:u32le(#frames) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(jiffies[1]) + head:u32le(1) + w:chunk("anih", head:finish()) + if not same then + local rw = Bytes.writer(#frames * 4) + for _, j in __iter(jiffies) do + rw:u32le(j) + end + w:chunk("rate", rw:finish()) + end + local items = {} + for i, fr in __iter(frames) do + local im = fr.image + local ok, data, err = pcall(encodeImage, im, "ico") + if not ok or not data then + return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring((ok and{err }or{data})[1])) + end + table.insert(items, { "icon", data }) + end + w:list("fram", items) + return w:finish() +end + +return Ani +end +__FILES["image/blp"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written +-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken. +-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8: +-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual +-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back); +-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque); +-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha +-- type 0 / 1 / 7), uncompressed BGRA. +-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain). +-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Jpeg = __include("codecs/image/Jpeg") +local Bcn = __include("codecs/image/Bcn") + +-- ------------------------------------------------------------------------------------------------ contract +local Blp = { + name = "blp", + category = "image", + extensions = { "blp" }, + mime = { "image/x-blp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg", "codecs/image/Bcn" }, + caps = { decode = true, encode = true, alpha = true, variants = { "blp1", "blp2" }, compressions = { "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Blp.sniff(r) +local m = r:peek(4) + return (m == "BLP1" or m == "BLP2" )and 1 or(m == "BLP0" and 0.8 or 0 +)end + +-- ------------------------------------------------------------------------------------------------ decode +-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha +local function swap(v, a) +local b, g, r = v % 256, (math.floor(v / 256)) % 256, (math.floor(v / 65536)) % 256 + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- alpha of pixel i from a packed plane at p of depth bits +local function alphaAt(b, p, depth, i) +if depth == 8 then + return readu8(b, p + i) + elseif depth == 4 then + local v = readu8(b, p + math.floor(i / 2)) + local n = (i % 2 == 0 and((v % 16 ))or((math.floor(v / 16 +)))) return n * 17 + elseif depth == 1 then + local v = readu8(b, p + math.floor(i / 8)) + return bit32.band(v, bit32.lshift(1, i % 8)) ~= 0 and 255 or 0 + end + return 255 +end + +function Blp.decode(r, opts) +local size = r.limit - r.base + local b, base = r.buf, r.base + local magic = r:peek(4) + if magic == "BLP0" then + return nil, Err.new(Err.UNSUPPORTED, "BLP0 (mips in external files)", 0) + end + if magic ~= "BLP1" and magic ~= "BLP2" then + return nil, Err.new((size < 4 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "bad magic", 0) + end + local v2 = magic == "BLP2" + local headerSize = v2 and 20 + 128 + 1024 or 28 + 128 + if size < headerSize then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local kind = readu32(b, base + 4) -- BLP1: 0 = JPEG, 1 = palette; BLP2: 1 (0 = JPEG) + local compression = (v2 and{(readu8(b, base + 8) )}or{kind == 0 and 0 or 1 +})[1] local alphaDepth = (v2 and{(readu8(b, base + 9) )}or{(readu32(b, base + 8) +)})[1] local alphaType = (v2 and{(readu8(b, base + 10) )}or{0 +})[1] local w, h = readu32(b, base + 12), readu32(b, base + 16) + local mipsAt = v2 and 20 or 28 + if w == 0 or h == 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. " x " .. h, 12) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local offs, lens= {}, {} + local mips = 0 + for i = 0, 15 do + offs[i + 1] = readu32(b, base + mipsAt + i * 4) + lens[i + 1] = readu32(b, base + mipsAt + 64 + i * 4) + if offs[i + 1] ~= 0 and lens[i + 1] ~= 0 then + mips =mips+ 1 + end + end + local at, len = offs[1], lens[1] + if at + len > size or len == 0 then + return nil, Err.new(Err.TRUNCATED, "mip 0 past the end", mipsAt) + end + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local src = base + at + local name +if (not v2 and kind == 0) or (v2 and kind == 0) then + if v2 then + return nil, Err.new(Err.UNSUPPORTED, "BLP2 JPEG") + end + -- the JPEG header shared by the mips, then the mip's own data + if size < headerSize + 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG header size", headerSize) + end + local hs = readu32(b, base + headerSize) + if hs > 0x10000 or headerSize + 4 + hs > size then + return nil, Err.new(Err.CORRUPT, "bad JPEG header size", headerSize) + end + local jpg = buffer.create(hs + len) + buffer.copy(jpg, 0, b, base + headerSize + 4, hs) + buffer.copy(jpg, hs, b, src, len) + local info = Jpeg.info(jpg) + local four = info ~= nil and (info ).components == 4 + local dec, err = Jpeg.decode(jpg, 0, nil, { raw = four, maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local dw, dh = math.min(dec.width, w), math.min(dec.height, h) + for y = 0, dh - 1 do + for x = 0, dw - 1 do + local v = readu32(dec.pixels, (y * dec.width + x) * 4) + local a = (four and alphaDepth > 0 and{(math.floor(v / 16777216 ))}or{255 +})[1] writeu32(px, (y * w + x) * 4, swap(v, a)) + end + end + name = "jpeg" + elseif compression == 1 then + local palAt = base + (v2 and 148 or headerSize) + local dataAt = src + if not v2 then + -- BLP1: the palette follows the header; the mip offsets point past it + if headerSize + 1024 > size then + return nil, Err.new(Err.TRUNCATED, "palette", headerSize) + end + end + local depth = (v2 and{alphaDepth }or{(alphaDepth >= 8 and 8 or 0) +})[1] local need = n + ((depth == 8 and{n }or{(depth == 4 and{(math.floor((n + 1) / 2 ))}or{(depth == 1 and{(math.floor((n + 7) / 8 ))}or{0})[1]})[1]})[1]) + if at + need > size then + return nil, Err.new(Err.TRUNCATED, "palette mip past the end", at) + end + for i = 0, n - 1 do + local e = readu32(b, palAt + readu8(b, dataAt + i) * 4) + writeu32(px, i * 4, swap(e, (depth > 0 and{(alphaAt(b, dataAt + n, depth, i) )}or{255})[1])) + end + name = "palette" + elseif compression == 2 then + local kindName = alphaType == 7 and"bc3" or(alphaType == 1 and"bc2" or"bc1" +) local want= Bcn.size(kindName, w, h) or 0 + if len < want then + return nil, Err.new(Err.TRUNCATED, "DXT mip shorter than " .. want .. " bytes", mipsAt + 64) + end + local dec, err = Bcn.decode(kindName, b, src, w, h) + if not dec then + return nil, Err.from(err) + end + buffer.copy(px, 0, dec, 0, n * 4) + if kindName == "bc1" and alphaDepth == 0 then + for i = 0, n - 1 do + writeu8(px, i * 4 + 3, 255) + end + end + name = ({ bc1 = "dxt1", bc2 = "dxt3", bc3 = "dxt5" } )[kindName] + elseif compression == 3 then + if len < n * 4 then + return nil, Err.new(Err.TRUNCATED, "BGRA mip too short", mipsAt + 64) + end + for i = 0, n - 1 do + local v = readu32(b, src + i * 4) + writeu32(px, i * 4, swap(v, math.floor(v / 16777216))) + end + name = "bgra" + else + return nil, Err.new(Err.UNSUPPORTED, "compression " .. tostring(compression)) + end + img.meta.source = { format = "blp", version = v2 and 2 or 1, compression = name, alphaDepth = alphaDepth, alphaType = alphaType, mips = mips } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat) +local function halve(px, w, h) +local nw, nh = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) + local out = buffer.create(nw * nh * 4) + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s =s+ readu8(px, (sy * w + sx) * 4 + c) + end + end + writeu8(out, (y * nw + x) * 4 + c, math.floor((s + 2) / 4)) + end + end + end + return out, nw, nh +end + +function Blp.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "bad size") + end + local levels= { img.pixels } + local sizes= { { w, h } } + if opts and opts.mips then + local p, cw, ch = img.pixels, w, h + while (cw > 1 or ch > 1) and #levels < 16 do + p, cw, ch = halve(p, cw, ch) + table.insert(levels, p) + table.insert(sizes, { cw, ch }) + end + end + local out = Bytes.writer(1172 + w * h * 6) + out:string("BLP2") + out:u32le(1) + out:u8(3) -- uncompressed BGRA + out:u8(8) -- alpha depth + out:u8(8) -- alpha type + out:u8(#levels > 1 and 1 or 0) + out:u32le(w) + out:u32le(h) + local at = 1172 + for i = 1, 16 do + local l = levels[i] + out:u32le((l and{at }or{0})[1]) + if l then + at =at+ buffer.len(l) + end + end + for i = 1, 16 do + local l = levels[i] + out:u32le((l and{(buffer.len(l) )}or{0})[1]) + end + out:fill(0, 1024) + for _, l in __iter(levels) do + local p = out:reserve(buffer.len(l)) + local o = out.buf + for i = 0, math.floor(buffer.len(l) / 4 )- 1 do + local v = readu32(l, i * 4) + writeu32(o, p + i * 4, swap(v, math.floor(v / 16777216))) + end + out.pos = p + buffer.len(l) + end + return out:finish(), nil +end + +return Blp +end +__FILES["image/bmp"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +--!optimize 2 +-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a +-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3 +-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or +-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap), +-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the +-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit +-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max). +-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance +-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with +-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output. +-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Bmp = { + name = "bmp", + category = "image", + extensions = { "bmp", "dib" }, + mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" }, + 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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + +local MAX_PIXELS = 2 ^ 26 +local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "png", "alphabitfields" } + +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz + +-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer) +local function whole(r) +if r.base == 0 and r.limit == buffer.len(r.buf) then + return r.buf + end + local n = r.limit - r.base + local b = buffer.create(n) + buffer.copy(b, 0, r.buf, r.base, n) + return b +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Bmp.sniff(r) +if r:peek(2) ~= "BM" then + return 0 + end + -- a known header size: a strong match; "BM" alone is weak + local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256 + if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err +local function parseHeader(buf) +local n = buffer.len(buf) + if n < 18 then + return nil, Err.new(Err.TRUNCATED, "file too short") + end + if readu8(buf, 0) ~= 0x42 or readu8(buf, 1) ~= 0x4D then + return nil, Err.new(Err.CORRUPT, "not a BMP file (no BM signature)") + end + local hs = readu32(buf, 14) + if hs < 12 or 14 + hs > n then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + local info= { + width = 0, + height = 0, + bitsPerPixel = 0, + compression = 0, + topDown = false, + headerSize = hs, + os2 = false, + } + if hs == 12 then + info.width = readu16(buf, 18) + info.height = readu16(buf, 20) + info.bitsPerPixel = readu16(buf, 24) + info.os2 = true + else + if hs < 16 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. hs) + end + info.width = readi32(buf, 18) + local h = readi32(buf, 22) + info.bitsPerPixel = readu16(buf, 28) + if hs >= 20 then + info.compression = readu32(buf, 30) + end + if h < 0 then + info.topDown = true + h = -h + end + info.height = h + -- OS/2 2.x headers: 16 / 64 bytes, or any size that is not a Windows one + info.os2 = not (hs == 40 or hs == 52 or hs == 56 or hs == 108 or hs == 124) + end + return info +end + +-- info(r) -> Info | nil, Err: the header without decoding the pixels +function Bmp.info(r) +return parseHeader(whole(r)) +end + +-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate +-- the top bits instead, which can differ by 1). m = 0 -> { empty }. +local function scaleTable(m, empty) +local t = buffer.create(m + 1) + if m == 0 then + buffer.writeu8(t, 0, empty) + else + for v = 0, m do + buffer.writeu8(t, v, math.floor((v * 255) / m)) + end + end + return t +end + +-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16) +local function channel(mask, empty) +if mask == 0 then + return 0, 0, scaleTable(0, empty) + end + local sh = countrz(mask) + local m = rshift(mask, sh) + -- holes in the mask: use the lowest contiguous run of bits + local bits = 0 + while bits < 32 and band(m, lshift(1, bits)) ~= 0 do + bits =bits+ 1 + end + if bits > 16 then + sh =sh+ (bits - 16 +) bits = 16 + end + m = lshift(1, bits) - 1 + return sh, m, scaleTable(m, empty) +end + +-- decode(r, opts?) -> rgba8 Image | nil, Err +function Bmp.decode(r, opts) +local buf = whole(r) + local info, herr = parseHeader(buf) + if not info then + return nil, herr + end + local n = buffer.len(buf) + local hs, w, h, bpp, comp = info.headerSize, info.width, info.height, info.bitsPerPixel, info.compression + if w <= 0 or h <= 0 then + return nil, Err.new(Err.CORRUPT, "bad size " .. w .. "x" .. h) + end + local maxPixels = (opts and opts.maxPixels) or MAX_PIXELS + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "image too large (" .. w .. "x" .. h .. ")") + end + if info.os2 and hs ~= 12 and (comp == 3 or comp == 4) then + return nil, Err.new(Err.UNSUPPORTED, "OS/2 Huffman / RLE24 compression is not supported") + end + if comp == 4 or comp == 5 then + return nil, Err.new(Err.UNSUPPORTED, "embedded " .. (comp == 4 and"JPEG" or"PNG") .. " is not supported") + end + if comp > 6 then + return nil, Err.new(Err.CORRUPT, "unknown compression " .. comp) + end + local valid = (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 or bpp == 16 or bpp == 24 or bpp == 32) + if not valid then + return nil, Err.new(Err.CORRUPT, "unsupported bit depth " .. bpp) + end + if (comp == 1 and bpp ~= 8) or (comp == 2 and bpp ~= 4) then + return nil, Err.new(Err.CORRUPT, "RLE compression " .. comp .. " with " .. bpp .. " bpp") + end + if (comp == 3 or comp == 6) and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + return nil, Err.new(Err.CORRUPT, "BITFIELDS with " .. bpp .. " bpp") + end + + -- masks: in the v2+ header, or right after a 40-byte header + local palStart = 14 + hs + local rm, gm, bm, am= 0, 0, 0, 0 + local hasMasks = false + if comp == 3 or comp == 6 then + hasMasks = true + if hs >= 52 then + rm = readu32(buf, 54) + gm = readu32(buf, 58) + bm = readu32(buf, 62) + if hs >= 56 then + am = readu32(buf, 66) + end + else + local count = comp == 6 and 4 or 3 + if palStart + count * 4 > n then + return nil, Err.new(Err.TRUNCATED, "truncated bit masks") + end + rm = readu32(buf, palStart) + gm = readu32(buf, palStart + 4) + bm = readu32(buf, palStart + 8) + if comp == 6 then + am = readu32(buf, palStart + 12) + end + palStart =palStart+ count * 4 + end + if comp == 3 and hs < 56 then + am = 0 + end + if rm == 0 and gm == 0 and bm == 0 then + hasMasks = false -- all-zero masks: use the defaults + end + end + + -- palette + local entrySize = hs == 12 and 3 or 4 + local declared = (hs >= 36 and{(readu32(buf, 46) )}or{0 +})[1] local palCount = 0 + if bpp <= 8 then + palCount = ((declared == 0 or declared > lshift(1, bpp) )and{(lshift(1, bpp) )}or{declared +})[1] end + local off = readu32(buf, 10) + local pixelEnd = palStart + palCount * entrySize + if off < palStart or off >= n then + -- bad bfOffBits: the pixels start after the palette as declared + off = math.min(pixelEnd, n) + elseif bpp <= 8 and off < pixelEnd then + -- palette shorter than declared: it ends where the pixels start + palCount = math.floor((off - palStart) / entrySize +) end + palCount = math.max(0, math.min(palCount, math.floor((n - palStart) / entrySize))) + local pal = buffer.create(256 * 4) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + for i = 0, palCount - 1 do + local p = palStart + i * entrySize + local bb, gg, rr = readu8(buf, p), readu8(buf, p + 1), readu8(buf, p + 2) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + + local img = Types.Image.new(w, h, "rgba8") + local pixels = img.pixels + img.meta.source = { + format = "bmp", + bitDepth = bpp, + compression = COMPRESSION_NAMES[comp], + topDown = info.topDown, + headerSize = hs, + paletteSize = palCount, + os2 = info.os2, + } + if bpp <= 8 and palCount > 0 then + local palette= {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), 255 } + end + img.meta.palette = palette + end + if hs >= 40 then + local xp, yp = readi32(buf, 38), readi32(buf, 42) + if xp > 0 and yp > 0 then + img.meta.dpi = { x = xp * 0.0254, y = yp * 0.0254 } + end + end + + if comp == 1 or comp == 2 then + Pixels.rle(buf, off, n, comp == 2, pixels, w, h, info.topDown, pal) + return img, nil + end + + -- uncompressed: make sure every row is readable (a truncated file reads as zeros) + local stride = (math.floor((w * bpp + 31) / 32)) * 4 + local need = stride * h + local src, base = buf, off + if off + need > n then + src = buffer.create(need) + buffer.copy(src, 0, buf, off, n - off) + base = 0 + end + + if bpp <= 8 then + Pixels.indexed(src, base, stride, bpp, pixels, w, h, info.topDown, pal) + elseif bpp == 24 and not hasMasks then + Pixels.bgr24(src, base, stride, pixels, w, h, info.topDown) + elseif bpp == 32 and (not hasMasks or (rm == 0xFF0000 and gm == 0xFF00 and bm == 0xFF and (am == 0xFF000000 or am == 0))) then + local aor = Pixels.bgra32(src, base, stride, pixels, w, h, info.topDown) + if aor == 0 or (hasMasks and am == 0) then + Pixels.opaque(pixels, w * h) + end + else + if not hasMasks then + if bpp == 16 then + rm, gm, bm, am = 0x7C00, 0x3E0, 0x1F, 0 + else + rm, gm, bm, am = 0xFF0000, 0xFF00, 0xFF, 0 + end + end + local shr, mr, tr = channel(rm, 0) + local shg, mg, tg = channel(gm, 0) + local shb, mb, tb = channel(bm, 0) + local sha, ma, ta = channel(am, 255) + local aor = + Pixels.masked(src, base, stride, bpp, pixels, w, h, info.topDown, shr, mr, tr, shg, mg, tg, shb, mb, tb, sha, ma, ta) + if ma ~= 0 and aor == 0 then + Pixels.opaque(pixels, w * h) + end + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(img, opts?) -> buffer | nil, Err +function Bmp.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 0x7FFFFFFF or h > 0x7FFFFFFF then + return nil, Err.new(Err.ARG, "encode: bad image size") + end + if buffer.len(img.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "encode: the pixel buffer is smaller than width * height * 4") + end + local want = opts and opts.bitDepth or "auto" + if want ~= "auto" and want ~= 8 and want ~= 24 and want ~= 32 then + return nil, Err.new(Err.ARG, "encode: bitDepth must be 8, 24, 32 or auto") + end + local headerKind = opts and opts.header or "v4" + if headerKind ~= "v4" and headerKind ~= "info" then + return nil, Err.new(Err.ARG, "encode: header must be v4 or info") + end + local colours, alpha = Pixels.colours(img.pixels, w * h, 256) + local bpp +if want == "auto" then + bpp = alpha and 32 or(#colours <= 256 and 8 or 24 +) else + bpp = want +if bpp == 8 and #colours > 256 then + return nil, Err.new(Err.ARG, "encode: more than 256 colours for 8 bpp") + end + end + local v4 = bpp == 32 and headerKind == "v4" + local hs = v4 and 108 or 40 + local stride = (math.floor((w * bpp + 31) / 32)) * 4 + local palCount = (bpp == 8 and((#colours ))or(0 +)) local off = 14 + hs + palCount * 4 + local imageSize = stride * h + if off + imageSize > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "encode: the file would be over 1 GiB") + end + local out = buffer.create(off + imageSize) + local o = Bytes.writer(off) + o:string("BM") + o:u32le(off + imageSize) + o:u32le(0) + o:u32le(off) + o:u32le(hs) + o:i32le(w) + o:i32le(h) + o:u16le(1) + o:u16le(bpp) + o:u32le(v4 and 3 or 0) -- BI_BITFIELDS / BI_RGB + o:u32le(imageSize) + local dpi = img.meta and img.meta.dpi + local xp, yp= 3780, 3780 -- 96 dpi, as Pillow + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + xp = math.floor((dpi.x ) * 39.3701 + 0.5) + yp = math.floor((dpi.y ) * 39.3701 + 0.5) + end + o:i32le(xp) + o:i32le(yp) + o:u32le(palCount) + o:u32le(palCount) + if v4 then + o:u32le(0x00FF0000) + o:u32le(0x0000FF00) + o:u32le(0x000000FF) + o:u32le(0xFF000000) + o:string("BGRs") -- LCS_sRGB (stored little-endian: 'sRGB') + o:fill(0, 36 + 12) -- endpoints, gamma + end + local idx= {} + for i, c in __iter(colours) do + if i > palCount then + break + end + idx[c] = i - 1 + o:u8(band(rshift(c, 16), 255)) + o:u8(band(rshift(c, 8), 255)) + o:u8(band(c, 255)) + o:u8(0) + end + buffer.copy(out, 0, o.buf, 0, off) + if bpp == 8 then + Pixels.encode8(img.pixels, w, h, out, off, stride, idx) + elseif bpp == 24 then + Pixels.encode24(img.pixels, w, h, out, off, stride) + else + Pixels.encode32(img.pixels, w, h, out, off) + end + return out, nil +end + +return Bmp +end +__FILES["image/dds"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new +-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / +-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the +-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the +-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six +-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there +-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / +-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by +-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. +-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 +-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the +-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), +-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Dds = { + name = "dds", + category = "image", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants +-- DXGI_FORMAT -> texture format name, sRGB + + + + + + + + + + + + + + + + +local DXGI= { + [1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i", + [5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i", + [9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i", + [15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i", + [23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f", + [27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i", + [33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i", + [39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i", + [48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i", + [53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i", + [60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8", + [67] = "rgb9e5", [68] = "rgbg", [69] = "grgb", + [70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3", + [79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s", + [85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8", + [94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7", + [100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4", +} +local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true } +-- legacy FourCC codes (strings and D3DFMT numbers) +local FOURCC= { + DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3", + ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s", + YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb", +} +local D3DFMT= { + [36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f", + [114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s", +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } +local MAGIC = "DDS " + +local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000 +local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000 +local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000 +local MISC_CUBE = 0x4 + +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Dds.sniff(r) +return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6)) +end +-- ------------------------------------------------------------------------------------------------ decode + + + + + + + + + + + + + + + + + + + +local function u32(b, o) +return buffer.readu32(b, o) +end + +-- info(r) -> Info | nil, Err (the headers only) +function Dds.info(r) +local b, o, n = r.buf, r.base, r.limit - r.base + if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new((n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a DDS file", o) + end + if u32(b, o + 4) ~= 124 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4) + end + local flags = u32(b, o + 8) + local h, w = u32(b, o + 12), u32(b, o + 16) + local depth = u32(b, o + 24) + local mips = u32(b, o + 28) + local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84) + local bitCount = u32(b, o + 88) + local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104) + local caps2 = u32(b, o + 112) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12) + end + if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then + mips = 1 -- a count without the flag or the caps bit: some writers leave garbage + end + mips = math.max(1, mips) + local maxMips = 1 + do + local m = math.max(w, h, depth) + while m > 1 do + m =math.floor(m/ 2 +) maxMips =maxMips+ 1 + end + end + if mips > maxMips then + return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28) + end + local info= { + width = w, + height = h, + depth = 1, + mips = mips, + format = "", + layout = "2d", + layers = 1, + faces = {}, + srgb = false, + dataOffset = 128, + } + local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1 + if band(pfFlags, DDPF_FOURCC) ~= 0 then + local fourcc = buffer.readstring(b, o + 84, 4) + if fourcc == "DX10" then + if n < 148 then + return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128) + end + local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144) + info.dxgi = dxgi + info.dataOffset = 148 + local name = DXGI[dxgi] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128) + end + info.format = name + info.srgb = SRGB[dxgi] == true + info.alphaMode = band(misc2, 7) + info.premultiplied = band(misc2, 7) == 2 + info.layers = math.max(1, arr) + if info.layers > 4096 then + return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140) + end + if dim == 4 then + volume = true + elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132) + else + volume = false + end + if band(misc, MISC_CUBE) ~= 0 then + info.layout = "cube" + info.faces = table.clone(FACES) + elseif info.layers > 1 then + info.layout = "array" + end + else + info.fourcc = fourcc + local name = FOURCC[fourcc] or D3DFMT[fourccNum] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84) + end + info.format = name + info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4" + end + elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then + local bytes = math.floor(bitCount / 8 +) if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then + return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88) + end + local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0 + local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0 + local a = (band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 and{am }or{0 +})[1] local d + if alphaOnly then + d = Texel.masked(bytes, 0, 0, 0, (am ~= 0 and{am }or{0xFF})[1]) + elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then + d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC + else + d = Texel.masked(bytes, rm, lum and 0 or gm, lum and 0 or bm, a, lum) + end + if not d then + return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) + end + -- the common masks map onto named texel formats (fast paths, sane names) + local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) + local named = ({ + ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", + ["32:ff0000:ff00:ff:ff000000:false"] = "bgra8", + ["32:ff0000:ff00:ff:0:false"] = "bgrx8", + ["32:ff:ff00:ff0000:0:false"] = "rgbx8", + ["24:ff0000:ff00:ff:0:false"] = "bgr8", + ["24:ff:ff00:ff0000:0:false"] = "rgb8", + ["8:ff:0:0:0:true"] = "l8", + ["16:ffff:0:0:0:true"] = "l16", + } )[key] + info.format = named or "masked" + info.masked = d + else + return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80) + end + if volume then + info.layout = "volume" + info.depth = math.max(1, depth) + if info.depth > 2048 then + return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24) + end + elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then + info.layout = "cube" + for i, f in __iter(FACES) do + if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then + table.insert(info.faces, f) + end + end + if #info.faces == 0 then + info.faces = table.clone(FACES) + end + end + return info, nil +end + +-- the bytes of one surface of format f +local function surfaceSize(info, w, h) +if info.format == "masked" then + return (info.masked ).bytes * w * h + end + return (Texture.size(info.format, w, h) ) +end + +function Dds.decode(r, opts) +local info, ierr = Dds.info(r) + if not info then + return nil, ierr + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base = r.buf, r.base + local p = base + info.dataOffset + local limit = r.limit + local count = (info.layout == "cube" and((#info.faces * info.layers ))or(info.layers +)) local list= {} + local pixels = 0 + local stop = false + for layer = 0, count - 1 do + local w, h, d = info.width, info.height, info.depth + for level = 0, info.mips - 1 do + local size = surfaceSize(info, w, h) + for slice = 0, d - 1 do + local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0) + if want then + if p + size > limit then + if level > 0 or layer > 0 or slice > 0 then + stop = true -- a cut mip chain / later surface: keep what decoded + break + end + return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p) + end + pixels =pixels+ w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local px, pf + if info.format == "masked" then + px, pf = Texel.decode(info.masked , b, p, w, h, native) + else + px, pf = Texture.decode(info.format, b, p, w, h, native) + end + if not px then + return nil, Err.from(pf, p) + end + local face = (info.layout == "cube" and((layer % #info.faces ))or(0 +)) table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) }) + end + p =p+ size + end + if stop then + break + end + w, h, d = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)), math.max(1, math.floor(d / 2)) + end + if stop then + break + end + end + local img = Texture.assemble(list, info.layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset) + end + if info.layout == "cube" then + img.meta.faces = info.faces + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.source = { + format = "dds", + pixelFormat = info.format, + dxgi = info.dxgi, + fourcc = info.fourcc, + mips = info.mips, + layers = info.layers, + depth = info.depth, + premultiplied = info.premultiplied, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BYTES_PF= { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } +local DX10_OUT= { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } + +-- the surface bytes of one image in format f +local function surface(img, f, opts) +local w, h, px = img.width, img.height, img.pixels + if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then + local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil) + if not blocks then + return nil, Err.new(Err.ARG, tostring(err)) + end + return blocks, nil + elseif f == "bgra8" then + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16)) + end + return out, nil + elseif f == "rgba16f" then + return Texture.toHalf(px, w * h), nil + end + local out = buffer.create(w * h * (BYTES_PF[f] )) + buffer.copy(out, 0, px, 0, buffer.len(out)) + return out, nil +end + +local function writeHeader(out, w, h, f, mips, dx10, layers, cube) + local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" + out:string(MAGIC) + out:u32le(124) + local flags = 0x1007 + ((mips > 1 and{DDSD_MIPMAPCOUNT }or{0})[1]) + (blockFmt and 0x80000 or 0x8) + out:u32le(flags) + out:u32le(h) + out:u32le(w) + out:u32le((blockFmt and{(Texture.size(f, w, h) )}or{(w * (BYTES_PF[f] ))})[1]) + out:u32le(0) + out:u32le((mips > 1 and{mips }or{0})[1]) + out:fill(0, 44) + -- DDS_PIXELFORMAT + out:u32le(32) + if dx10 then + out:u32le(DDPF_FOURCC) + out:string("DX10") + out:fill(0, 20) + elseif blockFmt then + out:u32le(DDPF_FOURCC) + out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } )[f]) + out:fill(0, 20) + else + out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS) + out:u32le(0) + out:u32le(32) + if f == "bgra8" then + out:u32le(0xFF0000) + out:u32le(0xFF00) + out:u32le(0xFF) + else + out:u32le(0xFF) + out:u32le(0xFF00) + out:u32le(0xFF0000) + end + out:u32le(0xFF000000) + end + out:u32le(0x1000 + (mips > 1 and 0x400008 or 0) + (cube and 0x8 or 0)) + out:u32le(cube and 0xFE00 or 0) + out:fill(0, 12) + if dx10 then + out:u32le(DX10_OUT[f]) + out:u32le(3) + out:u32le((cube and{MISC_CUBE }or{0})[1]) + out:u32le((cube and{(math.floor(layers / 6 ))}or{layers})[1]) + out:u32le(0) + end +end + +function Dds.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f= (opts and opts.pixelFormat) or (pf == "rgba8" and"rgba8" or(pf == "rgba16" and"rgba16" or"rgba32f")) + if not DX10_OUT[f] then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = f == "rgba16" and"rgba16" or((f == "rgba16f" or f == "rgba32f" )and"rgbaf32" or"rgba8" +) if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + -- surfaces: the frames (array / cube faces) or the image + local images= { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in __iter(img.frames) do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = (opts and opts.cube ~= nil and{opts.cube }or{(img.meta and img.meta.layout == "cube") +})[1] if cube and #images % 6 ~= 0 then + return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer") + end + local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6)) + local mips = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m =math.floor(m/ 2 +) mips =mips+ 1 + end + end + local out = Bytes.writer(img.width * img.height * 4 * #images + 200) + writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true) + for _, im in __iter(images) do + local level = im + for m = 1, mips do + local data, err = surface(level, f, opts) + if not data then + return nil, err + end + out:bytes(data) + if m < mips then + level = Texture.halve(level) + end + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Dds.DXGI = DXGI + +return Dds +end +__FILES["image/exr"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ +-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and +-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts +-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), +-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any +-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image +-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. +-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear +-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) +-- for colour, round(clamp(a, 0, 1) * 255) for alpha. +-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only +-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / +-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Half = __include("codecs/image/Half") +local Codec = __include("image/exr/Codec") +local Piz = __include("image/exr/Piz") + +-- ------------------------------------------------------------------------------------------------ contract +local Exr = { + name = "exr", + category = "image", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +local MAGIC = "\118\47\49\1" +local COMPRESSION= { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" } +local LINES= { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 } +local GAMMA = 1 / 2.2 + +local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Exr.sniff(r) +return Sniff.magic(r, MAGIC) +end +-- ------------------------------------------------------------------------------------------------ decode + + + + + + + + + + + + + + + + +local function cstr(b, p, limit, max) +local q = p + while q < limit and q - p <= max do + if readu8(b, q) == 0 then + return readstring(b, p, q - p), q + 1 + end + q =q+ 1 + end + return nil, q +end + +local function f32(b, o) +return readf32(b, o) +end + +-- one attribute value of a known type +local function value(b, p, size, typ) +if typ == "chlist" then + local list= {} + local q, stop = p, p + size + while q < stop and readu8(b, q) ~= 0 do + local name, nq = cstr(b, q, stop, 255) + if not name or nq + 16 > stop then + return nil + end + table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) }) + q = nq + 16 + end + return list + elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then + return (size >= 1 and{(readu8(b, p) )}or{nil +})[1] elseif typ == "box2i" then + return size >= 16 and{ readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } or nil + elseif typ == "box2f" then + return size >= 16 and{ f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } or nil + elseif typ == "v2i" then + return size >= 8 and{ readi32(b, p), readi32(b, p + 4) } or nil + elseif typ == "v2f" then + return size >= 8 and{ f32(b, p), f32(b, p + 4) } or nil + elseif typ == "v3f" then + return size >= 12 and{ f32(b, p), f32(b, p + 4), f32(b, p + 8) } or nil + elseif typ == "float" then + return (size >= 4 and{(f32(b, p) )}or{nil +})[1] elseif typ == "double" then + return (size >= 8 and{(buffer.readf64(b, p) )}or{nil +})[1] elseif typ == "int" then + return (size >= 4 and{(readi32(b, p) )}or{nil +})[1] elseif typ == "string" then + return readstring(b, p, size) + elseif typ == "tiledesc" then + if size < 9 then + return nil + end + local m = readu8(b, p + 8) + return { readu32(b, p), readu32(b, p + 4), m % 16, math.floor(m / 16 )} + elseif typ == "chromaticities" then + if size < 32 then + return nil + end + local t = {} + for i = 0, 7 do + t[i + 1] = f32(b, p + i * 4) + end + return t + end + local raw = buffer.create(size) + buffer.copy(raw, 0, b, p, size) + return raw +end + +-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err +local function header(b, p, limit) +local attrs= {} + local types= {} + while true do + if p >= limit then + return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p) + end + if readu8(b, p) == 0 then + attrs._types = types + return attrs, p + 1, nil + end + local name, q = cstr(b, p, limit, 255) + if not name then + return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p) + end + local typ, q2 = cstr(b, q, limit, 255) + if not typ then + return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q) + end + if q2 + 4 > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2) + end + local size = readi32(b, q2) + if size < 0 or q2 + 4 + size > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2) + end + attrs[name] = value(b, q2 + 4, size, typ) + types[name] = typ + p = q2 + 4 + size + end +end + +-- level sizes of a tiled part +local function levelSize(n, l, roundUp) +local d = 2 ^ l + return math.max(1, (roundUp and{(math.ceil(n / d) )}or{(math.floor(n / d))})[1]) +end +local function levelCount(w, h, mode, roundUp) +local function count(n) +local c = 1 + while levelSize(n, c - 1, roundUp) > 1 do + c =c+ 1 + end + return c + end + if mode == 0 then + return 1, 1 + elseif mode == 1 then + local c = count(math.max(w, h)) + return c, c + end + return count(w), count(h) +end + +-- chunk count of a part (single-part files: computed) +local function chunkCount(pt) +local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 + if not pt.tiled then + return math.floor((h + LINES[pt.compression] - 1) / LINES[pt.compression] +) end + local t = pt.tiles +local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1 + local lx, ly = levelCount(w, h, mode, roundUp) + local n = 0 + if mode == 2 then + for y = 0, ly - 1 do + for x = 0, lx - 1 do + n =n+ math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty) + end + end + else + for l = 0, lx - 1 do + n =n+ math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty) + end + end + return n +end + + + +local function parse(r) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base) + end + local ver = readu32(b, base + 4) + if ver % 256 ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4) + end + local flags = math.floor(ver / 256 +) local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0 + local info= { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 } + local p = base + 8 + repeat + local attrs, q, herr = header(b, p, limit) + if not attrs then + return nil, herr + end + p = q + local chans = attrs.channels + local box = attrs.dataWindow + if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then + return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p) + end + local typ = attrs.type + local pt= { + attrs = attrs, + channels = chans, + compression = attrs.compression, + box = box, + display = attrs.displayWindow or box, + tiled = (typ and{(typ == "tiledimage" or typ == "deeptile") }or{tiledFlag})[1], + tiles = attrs.tiles, + name = attrs.name, + type = typ, + chunks = 0, + offsets = {}, + } + if pt.tiled and type(pt.tiles) ~= "table" then + return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p) + end + if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad data window", p) + end + if pt.tiled and ((pt.tiles )[1] < 1 or (pt.tiles )[2] < 1) then + return nil, Err.new(Err.CORRUPT, "bad tile size", p) + end + for _, c in __iter(chans) do + if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then + return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p) + end + end + table.insert(info.parts, pt) + if #info.parts > 4096 then + return nil, Err.new(Err.LIMIT, "too many parts", p) + end + until not multi or (p < limit and readu8(b, p) == 0) + if multi then + p =p+ 1 + end + -- offset tables + for _, pt in __iter(info.parts) do + local n = (type(pt.attrs.chunkCount) == "number" and{pt.attrs.chunkCount }or{((LINES[pt.compression] and{(chunkCount(pt) )}or{0})[1]) +})[1] if n < 0 or n > 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad chunk count", p) + end + pt.chunks = n + if p + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p) + end + for i = 0, n - 1 do + pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296 + end + p =p+ n * 8 + end + info.dataStart = p - base + return info, nil +end + +-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err +function Exr.info(r) +return parse(r) +end + +-- bytes of a sample kind +local SIZE = { [0] = 4, 2, 4 } + +-- number of multiples of s in [a, b] +local function samples(a, b, s) +return math.floor(b / s )- math.floor((a - 1) / s +)end + + + +local function newPlane(pw, ph) +local px = buffer.create(pw * ph * 16) + for i = 0, pw * ph - 1 do + buffer.writef32(px, i * 16 + 12, 1) + end + return px +end +-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) +local function block(part, target, data, dp, y0, y1, x0, bw, plane, pw, ph, ox, oy) +local p = dp + for y = y0, y1 do + for i, c in __iter(part.channels) do + if y % c.ys == 0 then + local nx = (c.xs == 1 and{bw }or{(samples(x0, x0 + bw - 1, c.xs) +)})[1] local sz = SIZE[c.kind] + if p + nx * sz > buffer.len(data) then + return Err.new(Err.CORRUPT, "block too short") + end + local k = target[i] + if k ~= nil then + local row = y - oy + if c.xs == 1 and c.ys == 1 and k < 4 then + Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16) + else + local tmp = buffer.create(nx * 4) + Codec.samples(data, p, nx, c.kind, tmp, 0, 4) + local first = math.floor((x0 + c.xs - 1) / c.xs )* c.xs + for s = 0, nx - 1 do + local v = buffer.readf32(tmp, s * 4) + local sx = first + s * c.xs + for yy = row, math.min(row + c.ys - 1, ph - 1) do + for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do + local o = (yy * pw + xx) * 16 + if k == 4 then + buffer.writef32(plane, o, v) + buffer.writef32(plane, o + 4, v) + buffer.writef32(plane, o + 8, v) + else + buffer.writef32(plane, o + k * 4, v) + end + end + end + end + end + end + p =p+ nx * sz + end + end + end + return nil +end + +-- the raw bytes of a block (uncompressed size raw) +local function unpack(b, comp, part, p, size, raw, y0, y1, x0, bw) +if size == raw or comp == 0 then + if size < raw then + return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p) + end + return b, p, nil + end + local out, err + if comp == 1 then + out, err = Codec.rle(b, p, size, raw) + elseif comp == 2 or comp == 3 then + out, err = Codec.unzip(b, p, size, raw) + else + local chans= {} + for i, c in __iter(part.channels) do + chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = math.floor(SIZE[c.kind] / 2), ys = c.ys } + end + out, err = Piz.decode(b, p, size, chans, y0, y1, raw) + end + if not out then + return nil, 0, Err.from(err, p) + end + return out, 0, nil +end + +local function rawSize(part, y0, y1, x0, bw) +local n = 0 + for y = y0, y1 do + for _, c in __iter(part.channels) do + if y % c.ys == 0 then + n =n+ samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind] + end + end + end + return n +end + +function Exr.decode(r, opts) +local info, perr = parse(r) + if not info then + return nil, perr + end + local b, base, limit = r.buf, r.base, r.limit + local want = opts and opts.part or 1 + local pt= nil + local partIndex = 0 + for i, p in __iter(info.parts) do + if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then + pt, partIndex = p, i + end + end + if not pt then + return nil, Err.new(Err.ARG, "no part " .. tostring(want)) + end + local part = pt +if info.deep or (part.type and string.find(part.type, "deep")) then + return nil, Err.new(Err.UNSUPPORTED, "deep data") + end + local comp= part.compression + if comp > 4 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp))) + end + local box = part.box + local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4] + local w, h = xMax - xMin + 1, yMax - yMin + 1 + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel -> output component + local prefix = (opts and opts.layer and((opts.layer .. "." ))or("" +)) local target= {} + local hasRgb = false + for i, c in __iter(part.channels) do + local n = c.name + if string.sub(n, 1, #prefix) == prefix then + local s = string.sub(n, #prefix + 1) + local k = (s == "R" or s == "r" )and 0 or((s == "G" or s == "g" )and 1 or((s == "B" or s == "b" )and 2 or((s == "A" or s == "a" )and 3 or nil +))) if k then + target[i] = k + hasRgb = hasRgb or k < 3 + end + end + end + if not hasRgb then + for i, c in __iter(part.channels) do + if c.name == prefix .. "Y" then + target[i] = 4 + end + end + end + local multi = info.multipart + -- offsets: single-part tables with holes are rebuilt from the chunk sequence + local offsets = part.offsets + local bad = false + for _, o in __iter(offsets) do + if o < info.dataStart or base + o + 8 > limit then + bad = true + break + end + end + if bad then + -- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part) + offsets = {} + local p = base + info.dataStart + local total = 0 + for _, q in __iter(info.parts) do + total =total+ q.chunks + end + for _ = 1, total do + local pi = 1 + local at = p + if multi then + if p + 4 > limit then + break + end + pi = readi32(b, p) + 1 + p =p+ 4 + end + local q = info.parts[pi] + if not q then + break + end + local head = q.tiled and 20 or 8 + if p + head > limit then + break + end + local size = readi32(b, p + head - 4) + if size < 0 then + break + end + if pi == partIndex then + table.insert(offsets, at - base) + end + p =p+ (head + size +) end + end + + local planes= { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local tiles = part.tiles + local roundUp = tiles ~= nil and tiles[4] == 1 + local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 + + local lpb = LINES[comp] + for ci, off in __iter(offsets) do + local p = base + off + if multi then + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk past the end", p) + end + if readi32(b, p) ~= partIndex - 1 then + return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p) + end + p =p+ 4 + end + if part.tiled then + if p + 20 > limit then + return nil, Err.new(Err.TRUNCATED, "tile header past the end", p) + end + local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16) + p =p+ 20 + local t = tiles +local level = lx == 0 and ly == 0 and 0 or(wantMips and lx == ly and{lx }or{(-1 +)})[1] if level >= 0 then + local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp) + local x0, y0 = tx * t[1], ty * t[2] + if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then + return nil, Err.new(Err.CORRUPT, "tile outside the image", p) + end + if size < 0 or p + size > limit then + return nil, Err.new(Err.TRUNCATED, "tile data past the end", p) + end + local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0) + local plane = planes[level] + if not plane then + plane = newPlane(lw, lh) + planes[level] = plane + end + -- tile coordinates are relative to the level's data window origin + local ax, ay = xMin + x0, yMin + y0 + local raw = rawSize(part, ay, ay + bh - 1, ax, bw) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin) + if berr then + return nil, berr + end + end + else + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p) + end + local y, size = readi32(b, p), readi32(b, p + 4) + p =p+ 8 + if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8) + end + if size < 0 or p + size > limit then + if ci > 1 then + break -- a cut file: keep the lines that decoded (meta.truncated) + end + return nil, Err.new(Err.TRUNCATED, "block data past the end", p) + end + local y1 = math.min(y + lpb - 1, yMax) + local raw = rawSize(part, y, y1, xMin, w) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin) + if berr then + return nil, berr + end + end + end + + local native = opts and opts.native + local function finish(px, pw, ph) +if native then + local img = Types.Image.new(0, 0, "rgbaf32") + img.width, img.height, img.pixels = pw, ph, px + return img + end + local img = Types.Image.new(pw, ph, "rgba8") + local o = img.pixels + for i = 0, pw * ph - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + v = (v ~= v or v <= 0 )and 0 or(v >= 1 and 1 or v +) buffer.writeu8(o, i * 4 + c, math.floor(((c < 3 and((v ^ GAMMA ))or(v))) * 255 + 0.5)) + end + end + return img + end + local img = finish(planes[0], w, h) + if wantMips then + local mips = {} + local l = 1 + while planes[l] do + mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp)) + l =l+ 1 + end + if #mips > 0 then + img.meta.mipmaps = mips + end + end + local names, parts = {}, {} + for i, c in __iter(part.channels) do + names[i] = c.name + end + for i, p in __iter(info.parts) do + parts[i] = { name = p.name or "", type = p.type or (p.tiled and"tiledimage" or"scanlineimage") } + end + img.meta.colorSpace = "linear" + img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h } + local dw = part.display + img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 } + local attrs = {} + for k, v in __iter(part.attrs) do + if k ~= "_types" and (type(v) == "string" or type(v) == "number") then + attrs[k] = v + end + end + img.meta.attributes = attrs + local kinds = {} + for i, c in __iter(part.channels) do + kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind] + end + img.meta.source = { + format = "exr", + compression = COMPRESSION[comp], + channels = names, + pixelTypes = kinds, + part = partIndex, + parts = parts, + tiled = part.tiled, + lineOrder = part.attrs.lineOrder, + bitDepth = kinds[1] == "half" and 16 or 32, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function attr(w, name, typ, data) + w:cstring(name) + w:cstring(typ) + w:u32le(buffer.len(data)) + w:bytes(data) +end + +function Exr.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad image size") + end + local compName = opts and opts.compression or "zip" + local comp = compName == "none" and 0 or(compName == "zips" and 2 or(compName == "zip" and 3 or nil +)) if not comp then + return nil, Err.new(Err.ARG, "compression must be none, zips or zip") + end + local ptype = opts and opts.pixelType or "half" + if ptype ~= "half" and ptype ~= "float" then + return nil, Err.new(Err.ARG, "pixelType must be half or float") + end + local level = opts and opts.level or 6 + -- the float values + local n = w * h + local fl = buffer.create(n * 16) + if img.format == "rgbaf32" then + buffer.copy(fl, 0, img.pixels, 0, n * 16) + else + for i = 0, n * 4 - 1 do + local v = buffer.readu8(img.pixels, i) / 255 + buffer.writef32(fl, i * 4, (i % 4 < 3 and((v ^ 2.2 ))or(v))) + end + end + local alpha = opts and opts.alpha + if alpha == nil then + alpha = false + for i = 0, n - 1 do + if buffer.readf32(fl, i * 16 + 12) ~= 1 then + alpha = true + break + end + end + end + local chans = alpha and{ { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } or{ { "B", 2 }, { "G", 1 }, { "R", 0 } } + local kind = ptype == "half" and 1 or 2 + local sz = kind == 1 and 2 or 4 + local lpb = LINES[comp] + local nblocks = math.floor((h + lpb - 1) / lpb +) -- header + local hw = Bytes.writer(512) + hw:string(MAGIC) + hw:u32le(2) + local cl = Bytes.writer() + for _, c in __iter(chans) do + cl:cstring(c[1]) + cl:u32le(kind) + cl:u8(0) + cl:fill(0, 3) + cl:u32le(1) + cl:u32le(1) + end + cl:u8(0) + attr(hw, "channels", "chlist", cl:finish()) + attr(hw, "compression", "compression", buffer.fromstring(string.char(comp))) + local bw = Bytes.writer(16) + bw:u32le(0) + bw:u32le(0) + bw:u32le(w - 1) + bw:u32le(h - 1) + local boxb = bw:finish() + attr(hw, "dataWindow", "box2i", boxb) + attr(hw, "displayWindow", "box2i", boxb) + attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0")) + local fw = Bytes.writer(4) + fw:f32le(1) + attr(hw, "pixelAspectRatio", "float", fw:finish()) + attr(hw, "screenWindowCenter", "v2f", buffer.create(8)) + attr(hw, "screenWindowWidth", "float", fw:finish()) + hw:u8(0) + local tableAt = hw:tell() + hw:fill(0, nblocks * 8) + local from = Half.fromFloat + for bi = 0, nblocks - 1 do + local y0 = bi * lpb + local y1 = math.min(y0 + lpb - 1, h - 1) + local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz) + local o = 0 + for y = y0, y1 do + for _, c in __iter(chans) do + local k = c[2] + for x = 0, w - 1 do + local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4) + if kind == 1 then + buffer.writeu16(raw, o, from(v)) + else + buffer.writef32(raw, o, v) + end + o =o+ sz + end + end + end + local data = raw + if comp ~= 0 then + local z = Codec.zip(raw, level) + if buffer.len(z) < buffer.len(raw) then + data = z + end + end + local at = hw:tell() + hw:setU32le(tableAt + bi * 8, at) + hw:u32le(y0) + hw:u32le(buffer.len(data)) + hw:bytes(data) + end + return hw:finish(), nil +end + +return Exr +end +__FILES["image/exr/Codec"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- +-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), +-- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +local Deflate = __include("codecs/compress/Deflate") +local Half = __include("codecs/image/Half") + +local Codec = {} + +local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 +local HALF = Half.TABLE + +-- undoes the predictor and the interleave of t (n bytes) -> a new buffer +local function reconstruct(t, n) +local prev = (n > 0 and{(readu8(t, 0) )}or{0 +})[1] for i = 1, n - 1 do + prev = (prev + readu8(t, i) - 128) % 256 + writeu8(t, i, prev) + end + local out = buffer.create(n) + local half = math.floor((n + 1) / 2 +) for i = 0, half - 1 do + writeu8(out, i * 2, readu8(t, i)) + end + for i = 0, n - half - 1 do + writeu8(out, i * 2 + 1, readu8(t, half + i)) + end + return out +end + +-- rle(src, p, n, outSize) -> the raw block | nil, message +function Codec.rle(src, p, n, outSize) +local t = buffer.create(outSize) + local o, stop = 0, p + n + while p < stop do + local c = readi8(src, p) + p =p+ 1 + if c < 0 then + local cnt = -c + if p + cnt > stop or o + cnt > outSize then + return nil, "bad RLE run" + end + buffer.copy(t, o, src, p, cnt) + p =p+ cnt + o =o+ cnt + else + if p >= stop or o + c + 1 > outSize then + return nil, "bad RLE run" + end + buffer.fill(t, o, readu8(src, p), c + 1) + p =p+ 1 + o =o+ (c + 1 +) end + end + if o ~= outSize then + return nil, "RLE data too short" + end + return reconstruct(t, outSize), nil +end + +-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) +function Codec.unzip(src, p, n, outSize) +local t, err = Deflate.zlib(src, p, n, outSize) + if not t then + return nil, tostring(err) + end + if buffer.len(t) ~= outSize then + return nil, "zlib block has the wrong size" + end + return reconstruct(t, outSize), nil +end + +-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) +function Codec.zip(raw, level) +local n = buffer.len(raw) + local t = buffer.create(n) + local half = math.floor((n + 1) / 2 +) for i = 0, n - 1 do + local v = readu8(raw, i) + if i % 2 == 0 then + writeu8(t, math.floor(i / 2), v) + else + writeu8(t, half + math.floor(i / 2), v) + end + end + local prev = (n > 0 and{(readu8(t, 0) )}or{0 +})[1] for i = 1, n - 1 do + local v = readu8(t, i) + writeu8(t, i, (v - prev + 384) % 256) + prev = v + end + return (Deflate.zlibCompress(t, { level = level }) ) +end + +-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into +-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them +function Codec.samples(src, p, count, kind, dst, d, step) +if kind == 1 then + for i = 0, count - 1 do + writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)]) + end + return p + count * 2 + elseif kind == 2 then + for i = 0, count - 1 do + writef32(dst, d + i * step, readf32(src, p + i * 4)) + end + else + for i = 0, count - 1 do + writef32(dst, d + i * step, readu32(src, p + i * 4)) + end + end + return p + count * 4 +end + +return Codec +end +__FILES["image/exr/Piz"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor +-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman +-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit +-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +local Piz = {} + +local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift + +local USHORT_RANGE, BITMAP_SIZE = 65536, 8192 +local HUF_ENCSIZE = 65537 +local DECBITS = 14 +local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 + +-- ------------------------------------------------------------------------------------------------ Huffman +-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) +local function unpackTable(src, p, limit, im, iM, len) +local c, lc = 0, 0 + local function bits(n) +while lc < n do + if p >= limit then + return nil + end + c = c * 256 + readu8(src, p) + p =p+ 1 + lc =lc+ 8 + end + lc =lc- n + local v = math.floor(c / 2 ^ lc +) c =c- v * 2 ^ lc + return v + end + local i = im + while i <= iM do + local l = bits(6) + if not l then + return nil + end + if l == LONG_ZEROCODE_RUN then + local z = bits(8) + if not z then + return nil + end + z =z+ SHORTEST_LONG_RUN + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i =i+ z + elseif l >= SHORT_ZEROCODE_RUN then + local z = l - SHORT_ZEROCODE_RUN + 2 + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i =i+ z + else + len[i + 1] = l + i =i+ 1 + end + end + return p +end + +-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message +local function huffman(src, p, n, out, nRaw) +if n == 0 then + return (nRaw == 0 and{nil }or{"empty Huffman data" +})[1] end + if n < 20 then + return "truncated Huffman header" + end + local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12) + if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then + return "bad Huffman symbol range" + end + local limit = p + n + local len = table.create(HUF_ENCSIZE, 0) + local q = unpackTable(src, p + 20, limit, im, iM, len) + if not q then + return "bad Huffman table" + end + if q + math.floor((nBits + 7) / 8 )> limit then + return "truncated Huffman data" + end + -- canonical codes (OpenEXR's order: longest codes get the smallest values) + local count = table.create(59, 0) + for s = im, iM do + local l = len[s + 1] + if l > 58 then + return "bad Huffman code length" + end +do local __DARKLUA_VAR=l + 1 count[__DARKLUA_VAR]=count[__DARKLUA_VAR]+ 1 +end end + local start = table.create(59, 0) + local c = 0 + for l = 58, 1, -1 do + local nc = math.floor((c + count[l + 1]) / 2 +) start[l + 1] = c + c = nc + end + local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid + local long= {} + local maxLong = 0 + for s = im, iM do + local l = len[s + 1] + if l > 0 then + local code = start[l + 1] + start[l + 1] = code + 1 + if l <= DECBITS then + local base = code * 2 ^ (DECBITS - l) + local v = (s + 1) * 64 + l + for k = base, base + 2 ^ (DECBITS - l) - 1 do + if k < lshift(1, DECBITS) then + buffer.writeu32(fast, k * 4, v) + end + end + else + if l > 52 then + return "unsupported: Huffman code longer than 52 bits" + end + local t = long[l] + if not t then + t = {} + long[l] = t + end + t[code] = s + maxLong = math.max(maxLong, l) + end + end + end + -- decode MSB-first from a zero-padded copy + local nbytes = math.floor((nBits + 7) / 8 +) local data = buffer.create(nbytes + 8) + buffer.copy(data, 0, src, q, nbytes) + local bp = 0 + local o = 0 + local rlc = iM + local mask = lshift(1, DECBITS) - 1 + while bp < nBits do + local byte = rshift(bp, 3) + local w = bit32.byteswap(readu32(data, byte)) + local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask) + local e = readu32(fast, peek * 4) + local sym, l= 0, 0 + if e ~= 0 then + sym = math.floor(e / 64 )- 1 + l = band(e, 63) + else + -- a long code: bit by bit from length 15 + sym = -1 + local code = 0 + for k = 0, maxLong - 1 do + local bitAt = bp + k + code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1) + if k + 1 > DECBITS then + local t = long[k + 1] + local found= (t and{t[code] }or{nil +})[1] if found then + sym = found + l = k + 1 + break + end + end + end + if sym < 0 then + return "invalid Huffman code" + end + end + bp =bp+ l + if bp > nBits then + return "Huffman code past the end of the data" + end + if sym == rlc then + if bp + 8 > nBits then + return "truncated run length" + end + local b2 = bit32.byteswap(readu32(data, rshift(bp, 3))) + local cs = band(rshift(b2, 24 - band(bp, 7)), 255) + bp =bp+ 8 + if o + cs > nRaw then + return "too much Huffman data" + end + if o == 0 then + return "run length at the start" + end + local s = readu16(out, (o - 1) * 2) + for _ = 1, cs do + writeu16(out, o * 2, s) + o =o+ 1 + end + else + if o >= nRaw then + return "too much Huffman data" + end + writeu16(out, o * 2, sym) + o =o+ 1 + end + end + if o ~= nRaw then + return "not enough Huffman data" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ wavelet +-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) +local function wav2Decode(t, base, nx, ox, ny, oy, mx) + local w14 = mx < 16384 + local n = math.min(nx, ny) + local p = 1 + while p <= n do + p =p* 2 + end + p =math.floor(p/ 2 +) local p2 = p + p =math.floor(p/ 2 +) local function dec(l, h) +if w14 then + local ls = (l >= 32768 and((l - 65536 ))or(l +)) local hs = (h >= 32768 and((h - 65536 ))or(h +)) local ai = ls + hs % 2 + math.floor(hs / 2 +) return ai % 65536, (ai - hs) % 65536 + end + local bb = (l - rshift(h, 1)) % 65536 + return (h + bb - 32768) % 65536, bb + end + while p >= 1 do + local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2 + local py = base + local ey = base + oy * (ny - p2) + while py <= ey do + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local p10 = px + oy1 + local p11 = p10 + ox1 + local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2)) + local a, b = dec(i00, i01) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + local c, d = dec(i10, i11) + writeu16(t, p10 * 2, c) + writeu16(t, p11 * 2, d) + px =px+ ox2 + end + if band(nx, p) ~= 0 then + local p10 = px + oy1 + local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p10 * 2, b) + end + py =py+ oy2 + end + if band(ny, p) ~= 0 then + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + px =px+ ox2 + end + end + p2 = p + p =math.floor(p/ 2 +) end +end +-- ------------------------------------------------------------------------------------------------ decode +-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. +-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and +-- ySampling. + + + +function Piz.decode(src, p, n, chans, minY, maxY, outSize) +local total = 0 + for _, c in __iter(chans) do + total =total+ c.nx * c.ny * c.size + end + if total * 2 ~= outSize then + return nil, "PIZ block size mismatch" + end + local out = buffer.create(outSize) + if total == 0 then + return out, nil + end + local limit = p + n + if p + 4 > limit then + return nil, "truncated PIZ header" + end + local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2) + p =p+ 4 + if maxNZ >= BITMAP_SIZE then + return nil, "bad PIZ bitmap range" + end + local bitmap = buffer.create(BITMAP_SIZE) + if minNZ <= maxNZ then + local cnt = maxNZ - minNZ + 1 + if p + cnt > limit then + return nil, "truncated PIZ bitmap" + end + buffer.copy(bitmap, minNZ, src, p, cnt) + p =p+ cnt + end + -- reverse LUT + local lut = buffer.create(USHORT_RANGE * 2) + local k = 0 + for i = 0, USHORT_RANGE - 1 do + if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then + writeu16(lut, k * 2, i) + k =k+ 1 + end + end + local maxValue = k - 1 + if p + 4 > limit then + return nil, "truncated PIZ length" + end + local length = readu32(src, p) + p =p+ 4 + if length > limit - p then + return nil, "truncated PIZ data" + end + local tmp = buffer.create(total * 2) + local herr = huffman(src, p, length, tmp, total) + if herr then + return nil, herr + end + local starts = table.create(#chans, 0) + local at = 0 + for i, c in __iter(chans) do + starts[i] = at + for j = 0, c.size - 1 do + wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue) + end + at =at+ c.nx * c.ny * c.size + end + for i = 0, total - 1 do + writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) + end + -- planes -> scanlines + local o = 0 + local cursor = table.clone(starts) + for y = minY, maxY do + for i, c in __iter(chans) do + if y % c.ys == 0 then + local cnt = c.nx * c.size + buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2) + cursor[i]=cursor[i]+ cnt + o =o+ cnt * 2 + end + end + end + return out, nil +end + +return Piz +end +__FILES["image/gif"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image +-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames +-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / +-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames +-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize +-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with +-- alpha < 128 as the transparent index. +-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" +-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over). +-- +-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every +-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the +-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as +-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Lzw = __include("codecs/compress/Lzw") +local Quantize = __include("codecs/image/Quantize") +local Types = __include("Types") +local Decode = __include("image/gif/Decode") + +-- ------------------------------------------------------------------------------------------------ contract +local Gif = { + name = "gif", + category = "image", + extensions = { "gif" }, + mime = { "image/gif" }, + 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 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +local readu8 = buffer.readu8 +local DISPOSE = { [0] = "none", [1] = "none", [2] = "background", [3] = "previous" } +local DISPOSE_CODE= { none = 1, background = 2, previous = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Gif.sniff(r) +local s = r:peek(6) + return (s == "GIF89a" or s == "GIF87a" )and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list +local function colorTable(b, p, n) +local t = buffer.create(1024) + local list= (table.create(n) ) +for i = 0, 255 do + buffer.writeu32(t, i * 4, 0xFF000000) + end + for i = 0, n - 1 do + local q = p + i * 3 + local r, g, bl = readu8(b, q), readu8(b, q + 1), readu8(b, q + 2) + buffer.writeu32(t, i * 4, r + g * 256 + bl * 65536 + 0xFF000000) + list[i + 1] = { r, g, bl, 255 } + end + return t, list +end + +function Gif.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxTotal = opts and opts.maxTotalPixels or 2 ^ 28 + local maxFrames = opts and opts.maxFrames or math.huge + local sig = r:string(6) + local cw, ch = r:u16le(), r:u16le() + local flags, bg, aspect = r:u8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + if sig ~= "GIF89a" and sig ~= "GIF87a" then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + if cw == 0 or ch == 0 then + return nil, Err.new(Err.CORRUPT, "zero canvas size", r.base + 6) + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", cw, ch, maxPixels)) + end + local b = r.buf + local gct= nil + local gpal= nil + if bit32.band(flags, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(flags, 7) + 1) + if not r:need(n * 3) then + return nil, r.err + end + gct, gpal = colorTable(b, r.pos, n) + r.pos =r.pos+ n * 3 + end + local img = Types.Image.new(cw, ch, "rgba8") + local frames= {} + local comments= {} + local loops= nil + local total = 0 + -- the pending Graphic Control Extension + local delay, dispose, trans = 0, 0, -1 + local truncated = false + local interlacedAny = false + local localTables = 0 + local minCode = 8 + local limit = r.limit + -- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end) + local function subBlocks() +local p = r.pos + local n = 0 + while true do + if p >= limit then + return nil, p + end + local len = readu8(b, p) + if len == 0 then + break + end + if p + 1 + len > limit then + -- keep what is there: a truncated last block + n =n+ (limit - p - 1 +) p = limit + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < limit do + local l = math.min(readu8(b, q), limit - q - 1) + buffer.copy(out, o, b, q + 1, l) + o =o+ l + q =q+ (1 + l +) end + return out, -1 + end + n =n+ len + p =p+ (1 + len +) end + local out = buffer.create(n) + local q, o = r.pos, 0 + while q < p do + local l = readu8(b, q) + buffer.copy(out, o, b, q + 1, l) + o =o+ l + q =q+ (1 + l +) end + return out, p + 1 + end + local function skipBlocks() +local p = r.pos + while p < limit do + local len = readu8(b, p) + if len == 0 then + r.pos = p + 1 + return true + end + p =p+ (1 + len +) end + r.pos = limit + return false + end + while true do + if r.pos >= limit then + truncated = true + break + end + local intro = r:u8() + if intro == 0x3B then + break + elseif intro == 0x21 then + local label = r:u8() + if r.err then + truncated = true + break + end + local p = r.pos + if label == 0xF9 and p + 6 <= limit and readu8(b, p) >= 4 then + local f = readu8(b, p + 1) + dispose = bit32.band(bit32.rshift(f, 2), 7) + delay = readu8(b, p + 2) + readu8(b, p + 3) * 256 + trans = (bit32.band(f, 1) ~= 0 and{(readu8(b, p + 4) )}or{(-1 +)})[1] elseif label == 0xFF and p + 15 <= limit and readu8(b, p) == 11 then + local id = buffer.readstring(b, p + 1, 11) + if (id == "NETSCAPE2.0" or id == "ANIMEXTS1.0") and readu8(b, p + 12) >= 3 and readu8(b, p + 13) == 1 then + local rep = readu8(b, p + 14) + readu8(b, p + 15) * 256 + loops = rep == 0 and 0 or rep + 1 -- the stored value repeats: plays = value + 1 + end + elseif label == 0xFE then + local data = subBlocks() + if data then + table.insert(comments, buffer.tostring(data)) + end + end + if not skipBlocks() then + truncated = true + break + end + elseif intro == 0x2C then + local fx, fy, fw, fh = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local f = r:u8() + if r.err then + truncated = true + break + end + if fw * fh > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("a %d x %d frame is over the %d pixel limit", fw, fh, maxPixels), r.pos) + end + total =total+ fw * fh + if total > maxTotal then + return nil, Err.new(Err.LIMIT, string.format("the frames add up to over %d pixels", maxTotal), r.pos) + end + local pal = gct + if bit32.band(f, 0x80) ~= 0 then + local n = bit32.lshift(1, bit32.band(f, 7) + 1) + if not r:need(n * 3) then + truncated = true + break + end + pal = colorTable(b, r.pos, n) + r.pos =r.pos+ n * 3 + localTables =localTables+ 1 + end + local interlaced = bit32.band(f, 0x40) ~= 0 + interlacedAny = interlacedAny or interlaced + local mc = r:u8() + if r.err then + truncated = true + break + end + if mc < 1 or mc > 11 then + return nil, Err.new(Err.CORRUPT, "bad LZW minimum code size " .. mc, r.pos - 1) + end + minCode = mc + local data, nextPos = subBlocks() + if not data then + truncated = true + break + end + local n = fw * fh + local idx = buffer.create(n) + local got, lerr = Lzw.decode(data, 0, buffer.len(data), idx, 0, n, "gif", mc) + if got < n or nextPos < 0 then + truncated = true -- the missing pixels stay index 0, as most decoders show them + end + local _ = lerr -- a corrupt code ends the frame early (kept: what was decoded is shown) + local t = buffer.create(1024) + if pal then + buffer.copy(t, 0, pal) + else + -- no colour table at all: a grey ramp (what the spec leaves to the decoder) + for i = 0, 255 do + buffer.writeu32(t, i * 4, i + i * 256 + i * 65536 + 0xFF000000) + end + end + if trans >= 0 then + buffer.writeu32(t, trans * 4, 0) + end + local fimg = Types.Image.new(fw, fh, "rgba8") + Decode.toRgba(idx, fw, fh, interlaced, t, fimg.pixels) + if #frames == 0 then + Decode.draw(img.pixels, cw, ch, fimg.pixels, fx, fy, fw, fh) + end + table.insert(frames, { + image = fimg, + delay = delay / 100, + x = fx, + y = fy, + dispose = DISPOSE[dispose] or "none", + blend = trans >= 0 and"over" or"source", + } ) + delay, dispose, trans = 0, 0, -1 + if nextPos < 0 then + break + end + r.pos = nextPos + if #frames >= maxFrames then + break + end + else + -- junk between blocks: stop here, keeping what was read + if #frames == 0 then + return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1) + end + truncated = true + break + end + end + if #frames == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", r.pos) + end + if #frames > 1 then + img.frames = frames + img.loops = loops or 1 + else + img.loops = loops or 0 + end + img.meta.palette = gpal + img.meta.background = bg + if #comments > 0 then + img.meta.text = { comment = table.concat(comments, "\n") } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "gif", + version = string.sub(sig, 4), + bitDepth = minCode, + colorType = "palette", + frames = #frames, + interlaced = interlacedAny, + localPalettes = localTables, + aspect = aspect, + loopExtension = loops ~= nil, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function validImage(i) +return type(i) == "table" and i.format == "rgba8" and type(i.pixels) == "buffer" and type(i.width) == "number" and type(i.height) == "number" and i.width >= 1 and i.height >= 1 and i.width <= 65535 and i.height <= 65535 and i.width % 1 == 0 and i.height % 1 == 0 and buffer.len(i.pixels) >= i.width * i.height * 4 +end + +local function hasTransparency(px, n) +for i = 0, n - 1 do + if readu8(px, i * 4 + 3) < 128 then + return true + end + end + return false +end + +-- palette list -> padded table bytes (power of two entries, >= 2) and its size code +local function writeTable(w, pal) +local bits = 1 + while bit32.lshift(1, bits) < #pal do + bits =bits+ 1 + end + for i = 1, bit32.lshift(1, bits) do + local c = pal[i] + if c then + w:u8(c[1]) + w:u8(c[2]) + w:u8(c[3]) + else + w:fill(0, 3) + end + end + return bits +end + +local function tableBits(n) +local bits = 1 + while bit32.lshift(1, bits) < n do + bits =bits+ 1 + end + return bits +end + +function Gif.encode(img, opts) +if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image of 1..65535 x 1..65535 pixels") + end + local maxColors = opts and opts.maxColors or 256 + if type(maxColors) ~= "number" or maxColors < 2 or maxColors > 256 then + return nil, Err.new(Err.ARG, "maxColors must be 2..256") + end + maxColors = math.floor(maxColors) + local method = opts and opts.method or "mediancut" + if method ~= "mediancut" and method ~= "octree" then + return nil, Err.new(Err.ARG, "method must be mediancut or octree") + end + local dither = opts and opts.dither or false + -- the frames to write: { image, x, y, delay, dispose } + local list= {} + if type(img.frames) == "table" and #(img.frames ) > 0 then + for i, f in __iter(img.frames) do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x + f.image.width > 65535 or y + f.image.height > 65535 then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad position") + end + table.insert(list, f) + end + else + list[1] = { image = img, x = 0, y = 0, delay = 0, dispose = "none", blend = "source" } + end + local animated = #list > 1 + local loops = opts and opts.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then + return nil, Err.new(Err.ARG, "loops must be 0..65536") + end + -- palettes + local shared = (opts and opts.globalPalette) or not animated + local qopts= { method = method, dither = dither } + local globalPal= nil + local globalTrans = false + if shared then + -- every frame's pixels together + local npx = 0 + for _, f in __iter(list) do + npx =npx+ f.image.width * f.image.height + end + local all = buffer.create(npx * 4) + local o = 0 + for _, f in __iter(list) do + local n = f.image.width * f.image.height * 4 + buffer.copy(all, o, f.image.pixels, 0, n) + o =o+ n + end + globalTrans = hasTransparency(all, npx) + local pal = Quantize.palette(all, npx, 1, (globalTrans and((maxColors - 1 ))or(maxColors)), qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if globalTrans then + table.insert(pal, { 0, 0, 0, 0 }) + end + globalPal = pal + end + local w = Bytes.writer(img.width * img.height + 1024) + w:string("GIF89a") + w:u16le(img.width) + w:u16le(img.height) + if globalPal then + w:u8(0x80 + 0x70 + (tableBits(#globalPal) - 1)) + w:u8(0) + w:u8(0) + writeTable(w, globalPal) + else + w:u8(0x70) + w:u8(0) + w:u8(0) + end + if animated and loops ~= 1 then + w:u8(0x21) + w:u8(0xFF) + w:u8(11) + w:string("NETSCAPE2.0") + w:u8(3) + w:u8(1) + w:u16le(loops == 0 and 0 or loops - 1) + w:u8(0) + end + local text = img.meta and img.meta.text + local comment = text and (text.comment or text.Comment) + if type(comment) == "string" and #comment > 0 then + w:u8(0x21) + w:u8(0xFE) + for i = 1, #comment, 255 do + local part = string.sub(comment, i, i + 254) + w:u8(#part) + w:string(part) + end + w:u8(0) + end + for _, f in __iter(list) do + local fi = f.image + local fw, fh = fi.width, fi.height + local n = fw * fh + local pal +local tidx= nil + if globalPal then + pal = globalPal + if globalTrans then + tidx = #pal - 1 + end + else + local tr = hasTransparency(fi.pixels, n) + pal = Quantize.palette(fi.pixels, fw, fh, (tr and((maxColors - 1 ))or(maxColors)), qopts) + if #pal == 0 then + pal = { { 0, 0, 0, 255 } } + end + if tr then + table.insert(pal, { 0, 0, 0, 0 }) + tidx = #pal - 1 + end + end + local idx = Quantize.map(fi.pixels, fw, fh, pal, { dither = dither, transparentIndex = tidx }) + -- the Graphic Control Extension: always for animations, else only for transparency + if animated or tidx then + local d = DISPOSE_CODE[f.dispose or "none"] or 1 + w:u8(0x21) + w:u8(0xF9) + w:u8(4) + w:u8(d * 4 + (tidx and 1 or 0)) + w:u16le(math.clamp(math.floor((f.delay or 0) * 100 + 0.5), 0, 65535)) + w:u8(tidx or 0) + w:u8(0) + end + w:u8(0x2C) + w:u16le(f.x or 0) + w:u16le(f.y or 0) + w:u16le(fw) + w:u16le(fh) + local bits + if globalPal then + w:u8(0) + bits = tableBits(#globalPal) + else + bits = tableBits(#pal) + w:u8(0x80 + bits - 1) + writeTable(w, pal) + end + local mc = math.max(2, bits) + w:u8(mc) + local codes = Lzw.encode(idx, 0, n, "gif", mc) + local cl = buffer.len(codes) + local p = 0 + while p < cl do + local l = math.min(255, cl - p) + w:u8(l) + w:bytes(codes, p, l) + p =p+ l + end + w:u8(0) + end + w:u8(0x3B) + return w:finish(), nil +end + +return Gif +end +__FILES["image/gif/Decode"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to +-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every +-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4. +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Decode = {} + +-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from +-- 2, every 2nd from 1) +local function interlacedRow(fh) +local map = table.create(fh, 0) + local r = 0 + for _, pass in __iter({ { 0, 8 }, { 4, 8 }, { 2, 4 }, { 1, 2 } }) do + local y = pass[1] + while y < fh do + map[y + 1] = r + r =r+ 1 + y =y+ pass[2] + end + end + return map +end + +-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the +-- transparent one already alpha 0) +function Decode.toRgba(indexes, fw, fh, interlaced, palette, out) + local rows = (interlaced and{(interlacedRow(fh) )}or{nil +})[1] for y = 0, fh - 1 do + local src = ((rows and{rows[y + 1] }or{y})[1]) * fw + local dst = y * fw * 4 + for x = 0, fw - 1 do + writeu32(out, dst + x * 4, readu32(palette, readu8(indexes, src + x) * 4)) + end + end +end + +-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped) +function Decode.draw(canvas, cw, ch, frame, fx, fy, fw, fh) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + for y = y0, y1 - 1 do + local s = ((y - fy) * fw - fx) * 4 + local d = y * cw * 4 + for x = x0, x1 - 1 do + local v = readu32(frame, s + x * 4) + if v >= 0x01000000 then + writeu32(canvas, d + x * 4, v) + end + end + end +end + +-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background) +function Decode.clear(canvas, cw, ch, fx, fy, fw, fh) + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh) + if x1 <= x0 then + return + end + for y = y0, y1 - 1 do + buffer.fill(canvas, (y * cw + x0) * 4, 0, (x1 - x0) * 4) + end +end + +return Decode +end +__FILES["image/hdr"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions. +-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of +-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution +-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines. +-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion: +-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a +-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767). +-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/hdr/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Hdr = { + name = "hdr", + category = "image", + extensions = { "hdr", "pic", "rgbe" }, + mime = { "image/vnd.radiance", "image/x-hdr" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = false, float = true, depths = { 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local GAMMA = 1 / 2.2 + +-- ------------------------------------------------------------------------------------------------ sniff +function Hdr.sniff(r) +local s = r:peek(10) + if s == "#?RADIANCE" then + return 1 + end + if string.sub(s, 1, 6) == "#?RGBE" then + return 1 + end + if string.sub(s, 1, 2) == "#?" and string.match(s, "^#%?%u") then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hdr.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, limit = r.buf, r.limit + local p = r.base + -- header lines up to the first empty one + local function line() +local s = p + while p < limit and buffer.readu8(b, p) ~= 10 do + p =p+ 1 + end + if p >= limit then + return nil + end + local l = buffer.readstring(b, s, p - s) + p =p+ 1 + return l + end + local first = line() + if not first or string.sub(first, 1, 2) ~= "#?" then + return nil, Err.new(Err.CORRUPT, "not a Radiance file (no #? line)", r.base) + end + local exposure = 1 + local format = nil + local text= {} + while true do + local l = line() + if l == nil then + return nil, Err.new(Err.TRUNCATED, "header ends early", p) + end + l = string.gsub(l, "\r$", "") + if l == "" then + break + end + local k, v = string.match(l, "^%s*([%w_%-]+)%s*=%s*(.-)%s*$") + if k == "FORMAT" then + format = v + elseif k == "EXPOSURE" then + local e = tonumber(v) + if e and e > 0 then + exposure =exposure* e + end + elseif k then + text[k] = v +end + end + if format and format ~= "32-bit_rle_rgbe" then + return nil, Err.new(Err.UNSUPPORTED, "FORMAT=" .. format) + end + local res = line() + if not res then + return nil, Err.new(Err.TRUNCATED, "no resolution line", p) + end + local s1, a1, n1, s2, a2, n2 = string.match(res, "^%s*([%+%-])([XY])%s+(%d+)%s+([%+%-])([XY])%s+(%d+)%s*$") + if not s1 or a1 == a2 or #(n1 ) > 9 or #(n2 ) > 9 then + return nil, Err.new(Err.CORRUPT, "bad resolution line", p) + end + local outer, inner = (tonumber(n1) ), (tonumber(n2) ) +local w, h = (a1 == "Y" and{inner }or{outer})[1], (a1 == "Y" and{outer }or{inner +})[1] if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "zero size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgbaf32") + local px = img.pixels + local row = buffer.create(inner * 4) + local truncated = false + for i = 0, outer - 1 do + local np, err = Codec.readLine(b, p, limit, inner, row) + if not np then + if err == "truncated" then + truncated = true + break + end + return nil, Err.new(Err.CORRUPT, tostring(err), p) + end + p = np + -- where scanline i, pixel j lands: Y decreasing ("-Y") = top first, X increasing ("+X") = left first + local base, step + if a1 == "Y" then + local y = (s1 == "-" and{i }or{(h - 1 - i +)})[1] if s2 == "+" then + base, step = y * w * 16, 16 + else + base, step = (y * w + w - 1) * 16, -16 + end + else + local x = (s1 == "+" and{i }or{(w - 1 - i +)})[1] if s2 == "-" then + base, step = x * 16, w * 16 + else + base, step = ((h - 1) * w + x) * 16, -w * 16 + end + end + Codec.toFloat(row, inner, px, base, step) + end + if not (opts and opts.native) then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + for c = 0, 2 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(o.pixels, i * 4 + c, math.floor(math.clamp(v, 0, 1) ^ GAMMA * 255 + 0.5)) + end + buffer.writeu8(o.pixels, i * 4 + 3, 255) + end + o.meta = img.meta + img = o + end + img.meta.exposure = exposure + img.meta.colorSpace = "linear" + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "hdr", bitDepth = 32, colorType = "rgbe", program = string.sub(first, 3), orientation = string.format("%s%s %s%s", s1, a1 , s2 , a2 ) } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Hdr.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + local bpp = img.format == "rgbaf32" and 16 or 4 + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o= opts or {} + local px = img.pixels + if bpp == 4 then + -- rgba8 through the inverse of the decoder's display curve + local lut = table.create(256, 0) + for v = 0, 255 do + lut[v + 1] = (v / 255) ^ 2.2 + end + px = buffer.create(w * h * 16) + for i = 0, w * h - 1 do + for c = 0, 2 do + buffer.writef32(px, i * 16 + c * 4, lut[buffer.readu8(img.pixels, i * 4 + c) + 1]) + end + buffer.writef32(px, i * 16 + 12, 1) + end + end + local exposure = o.exposure or (img.meta and img.meta.exposure) + local head = "#?RADIANCE\n# written by rosetta\nFORMAT=32-bit_rle_rgbe\n" + if type(exposure) == "number" and exposure > 0 and exposure ~= 1 then + head =head.. string.format("EXPOSURE=%.9g\n", exposure) + end + head =head.. string.format("\n-Y %d +X %d\n", h, w) + local rle = o.rle ~= false and w >= 8 and w <= 32767 + local out = buffer.create(#head + h * (w * 5 + 8)) + buffer.writestring(out, 0, head) + local op = #head + local row = buffer.create(w * 4) + for y = 0, h - 1 do + Codec.fromFloat(px, y, w, row) + if rle then + op = Codec.writeLine(row, w, out, op) + else + buffer.copy(out, op, row, 0, w * 4) + for x = 0, w - 1 do + -- 1, 1, 1 would read as an old-style run marker + if buffer.readu8(out, op + x * 4) == 1 and buffer.readu8(out, op + x * 4 + 1) == 1 and buffer.readu8(out, op + x * 4 + 2) == 1 then + buffer.writeu8(out, op + x * 4 + 2, 0) + end + end + op =op+ w * 4 + end + end + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Hdr +end +__FILES["image/hdr/Codec"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes +-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE +-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then +-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and +-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked. +local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32 +local frexp = math.frexp + +local Codec = {} + +-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes) +function Codec.readLine(b, p, limit, w, row) +if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then + if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then + return nil, "scanline width mismatch" + end + p =p+ 4 + for c = 0, 3 do + local x = 0 + while x < w do + if p >= limit then + return nil, "truncated" + end + local n = readu8(b, p) + p =p+ 1 + if n > 128 then + n =n- 128 + if x + n > w or p >= limit then + return nil, p >= limit and"truncated" or"bad run" + end + local v = readu8(b, p) + p =p+ 1 + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, v) + end + else + if n == 0 or x + n > w then + return nil, "bad count" + end + if p + n > limit then + return nil, "truncated" + end + for i = x, x + n - 1 do + writeu8(row, i * 4 + c, readu8(b, p)) + p =p+ 1 + end + end + x =x+ n + end + end + return p, nil + end + -- flat pixels, with old-style runs + local x = 0 + local shift = 0 + while x < w do + if p + 4 > limit then + return nil, "truncated" + end + local r, g, bl, e = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + p =p+ 4 + if r == 1 and g == 1 and bl == 1 then + if x == 0 then + return nil, "run at the start of a scanline" + end + local n = e * 2 ^ shift + if x + n > w then + return nil, "bad run" + end + local q = (x - 1) * 4 + local pr, pg, pb, pe = readu8(row, q), readu8(row, q + 1), readu8(row, q + 2), readu8(row, q + 3) + for i = x, x + n - 1 do + writeu8(row, i * 4, pr) + writeu8(row, i * 4 + 1, pg) + writeu8(row, i * 4 + 2, pb) + writeu8(row, i * 4 + 3, pe) + end + x =x+ n + shift =shift+ 8 + if shift > 24 then + return nil, "bad run" + end + else + writeu8(row, x * 4, r) + writeu8(row, x * 4 + 1, g) + writeu8(row, x * 4 + 2, bl) + writeu8(row, x * 4 + 3, e) + x =x+ 1 + shift = 0 + end + end + return p, nil +end + +-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step +function Codec.toFloat(row, n, out, base, step) + for i = 0, n - 1 do + local q = i * 4 + local e = readu8(row, q + 3) + local o = base + i * step + if e == 0 then + writef32(out, o, 0) + writef32(out, o + 4, 0) + writef32(out, o + 8, 0) + else + local f = 2 ^ (e - 136) + writef32(out, o, readu8(row, q) * f) + writef32(out, o + 4, readu8(row, q + 1) * f) + writef32(out, o + 8, readu8(row, q + 2) * f) + end + writef32(out, o + 12, 1) + end +end + +-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe) +function Codec.fromFloat(px, y, w, row) + for x = 0, w - 1 do + local q = (y * w + x) * 16 + local r, g, b = readf32(px, q), readf32(px, q + 4), readf32(px, q + 8) + if r ~= r or r < 0 then + r = 0 + end + if g ~= g or g < 0 then + g = 0 + end + if b ~= b or b < 0 then + b = 0 + end + local v = math.max(r, g, b) + local o = x * 4 + if v < 1e-32 or v == math.huge then + if v == math.huge then + -- clamp infinities to the largest RGBE value + writeu8(row, o, r == math.huge and 255 or 0) + writeu8(row, o + 1, g == math.huge and 255 or 0) + writeu8(row, o + 2, b == math.huge and 255 or 0) + writeu8(row, o + 3, 255) + else + writeu8(row, o, 0) + writeu8(row, o + 1, 0) + writeu8(row, o + 2, 0) + writeu8(row, o + 3, 0) + end + else + local m, e = frexp(v) + if e > 127 then + writeu8(row, o, 255) + writeu8(row, o + 1, 255) + writeu8(row, o + 2, 255) + writeu8(row, o + 3, 255) + else + local s = m * 256 / v + writeu8(row, o, math.min(255, math.floor(r * s))) + writeu8(row, o + 1, math.min(255, math.floor(g * s))) + writeu8(row, o + 2, math.min(255, math.floor(b * s))) + writeu8(row, o + 3, e + 128) + end + end + end +end + +-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8 +function Codec.writeLine(row, w, out, o) +writeu8(out, o, 2) + writeu8(out, o + 1, 2) + writeu8(out, o + 2, math.floor(w / 256)) + writeu8(out, o + 3, w % 256) + o =o+ 4 + for c = 0, 3 do + local cur = 0 + while cur < w do + -- find the next run of at least 4 + local begRun = cur + local runCount = 0 + local oldRun = 0 + while runCount < 4 and begRun < w do + begRun =begRun+ runCount + oldRun = runCount + runCount = 1 + if begRun < w then + local v = readu8(row, begRun * 4 + c) + while begRun + runCount < w and runCount < 127 and readu8(row, (begRun + runCount) * 4 + c) == v do + runCount =runCount+ 1 + end + end + end + -- a short run just before the long one + if oldRun > 1 and oldRun == begRun - cur then + writeu8(out, o, 128 + oldRun) + writeu8(out, o + 1, readu8(row, cur * 4 + c)) + o =o+ 2 + cur = begRun + end + -- raw bytes up to the run + while cur < begRun do + local n = math.min(begRun - cur, 128) + writeu8(out, o, n) + o =o+ 1 + for i = cur, cur + n - 1 do + writeu8(out, o, readu8(row, i * 4 + c)) + o =o+ 1 + end + cur =cur+ n + end + if runCount >= 4 then + writeu8(out, o, 128 + runCount) + writeu8(out, o + 1, readu8(row, begRun * 4 + c)) + o =o+ 2 + cur =cur+ runCount + end + end + end + return o +end + +return Codec +end +__FILES["image/icns"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: +-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha +-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any +-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), +-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists +-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns +-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage +-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / +-- 48 / 128 with masks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") + +-- ------------------------------------------------------------------------------------------------ contract +local Icns = { + name = "icns", + category = "image", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local RGB= { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } } +local MASKS= { s8mk = true, l8mk = true, h8mk = true, t8mk = true } +local ARGB= { ic04 = 16, ic05 = 32 } +local MONO= { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } } +local PNG_TYPES= { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" } +local LEGACY= { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } } +local LAYOUT= { + bigEndian = true, + resize = function(_id, declared) +return math.max(0, declared - 8) + end, +} + +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Icns.sniff(r) +return Sniff.magic(r, "icns") +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) +local function unrle(b, p, stop, out, channels, count) +for _, ch in __iter(channels) do + local i = 0 + while i < count do + if p >= stop then + return false + end + local c = readu8(b, p) + p =p+ 1 + if c >= 128 then + local n = c - 125 + if p >= stop then + return false + end + local v = readu8(b, p) + p =p+ 1 + for _ = 1, math.min(n, count - i) do + buffer.writeu8(out, i * 4 + ch, v) + i =i+ 1 + end + else + local n = c + 1 + if p + n > stop then + return false + end + for k = 0, math.min(n, count - i) - 1 do + buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k)) + end + i =i+ math.min(n, count - i) + p =p+ n + end + end + end + return true +end + +local function isPng(b, p, n) +return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n" +end +local function isJp2(b, p, n) +return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81") +end + +function Icns.decode(r, opts) +local b, o, limit = r.buf, r.base, r.limit + if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then + return nil, Err.new(Err.CORRUPT, "not an icns file", o) + end + local total = bit32.byteswap(buffer.readu32(b, o + 4)) + local stop = math.min(limit, o + math.max(total, 8)) + local list = Chunks.walk(b, o + 8, stop, LAYOUT) + local decodeImage = opts and opts.decodeImage + local maxPixels = opts and opts.maxPixels or 2 ^ 22 + local masks= {} + for _, c in __iter(list) do + if MASKS[c.id] then + masks[c.id] = c + end + end + local frames= {} + local skipped= {} + local function add(im, typ, extra) + local src= { format = "icns", type = typ } + if extra then + for k, v in __iter(extra) do + src[k] = v + end + end + im.meta.source = src +table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } ) + end + for _, c in __iter(list) do + local id, p, n = c.id, c.offset, c.avail + if c.truncated then + table.insert(skipped, id .. " (truncated)") + elseif RGB[id] then + local size = RGB[id][1] + local im = Types.Image.new(size, size, "rgba8") + local px = im.pixels + local q = (id == "it32" and((p + 4 ))or(p +)) local count = size * size + local ok + if n == count * 3 then + for i = 0, count - 1 do + for k = 0, 2 do + buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i)) + end + end + ok = true + else + ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count) + end + local m = masks[RGB[id][2] ] + for i = 0, count - 1 do + buffer.writeu8(px, i * 4 + 3, (m and m.avail >= count and{(readu8(b, m.offset + i) )}or{255})[1]) + end + if ok then + add(im, id, { bitDepth = 24, mask = m ~= nil }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then + local size = ARGB[id] + local im = Types.Image.new(size, size, "rgba8") + if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then + add(im, id, { bitDepth = 32 }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif MONO[id] then + local w, h = MONO[id][1], MONO[id][2] + local bytes = math.floor(w * h / 8 +) if n >= bytes * 2 then + local im = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + buffer.writeu32(im.pixels, i * 4, (bit == 1 and 0 or 0xFFFFFF) + mbit * 0xFF000000) + end + add(im, id, { bitDepth = 1 }) + end + elseif isPng(b, p, n) then + if decodeImage then + local sub = buffer.create(n) + buffer.copy(sub, 0, b, p, n) + local okc, im, ierr = pcall(decodeImage, sub) + if okc and im then + if im.width * im.height <= maxPixels then + add(im , id, { png = true }) + else + table.insert(skipped, id .. " (over maxPixels)") + end + else + table.insert(skipped, id .. " (PNG: " .. tostring((okc and{ierr }or{im})[1]) .. ")") + end + else + table.insert(skipped, id .. " (PNG: no decodeImage hook)") + end + elseif isJp2(b, p, n) then + table.insert(skipped, id .. " (JPEG 2000)") + elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then + table.insert(skipped, id) + end + end + if #frames == 0 then + if #skipped > 0 then + return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")") + end + return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8) + end + local main = frames[1].image + for _, f in __iter(frames) do + if f.image.width * f.image.height > main.width * main.height then + main = f.image + end + end + local img = Types.Image.new(0, 0, "rgba8") + img.width, img.height, img.pixels = main.width, main.height, main.pixels + if #frames > 1 then + img.frames = frames + end + if #skipped > 0 then + img.meta.skipped = skipped + end + img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the icns RLE of one channel (count bytes, step 4 from ch) into w +local function rle(w, px, ch, count) + local i = 0 + while i < count do + local v = readu8(px, i * 4 + ch) + local run = 1 + while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do + run =run+ 1 + end + if run >= 3 then + w:u8(run + 125) + w:u8(v) + i =i+ run + else + local lit = 0 + while i + lit < count and lit < 128 do + local a = readu8(px, (i + lit) * 4 + ch) + if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then + break + end + lit =lit+ 1 + end + lit = math.max(lit, 1) + w:u8(lit - 1) + for k = 0, lit - 1 do + w:u8(readu8(px, (i + k) * 4 + ch)) + end + i =i+ lit + end + end +end + +function Icns.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local images= {} + local seen= {} + local function take(im) +if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then + return Err.new(Err.ARG, "icons are square rgba8 images") + end + if not seen[im.width] then + seen[im.width] = true + table.insert(images, im) + end + return nil + end + local e = take(img) + if e then + return nil, e + end + if type(img.frames) == "table" then + for _, f in __iter(img.frames) do + local fe = take(f.image) + if fe then + return nil, fe + end + end + end + table.sort(images, function(a, c) +return a.width < c.width + end) + local encodeImage = opts and opts.encodeImage + local legacy = (opts and opts.legacy) or encodeImage == nil + local body = Bytes.writer() + local function chunk(id, data) + body:string(id) + body:u32be(buffer.len(data) + 8) + body:bytes(data) + end + for _, im in __iter(images) do + local s = im.width + if legacy and LEGACY[s] then + local types = LEGACY[s] + local w = Bytes.writer() + if s == 128 then + w:u32be(0) + end + for ch = 0, 2 do + rle(w, im.pixels, ch, s * s) + end + chunk(types[1], w:finish()) + local m = buffer.create(s * s) + for i = 0, s * s - 1 do + buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3)) + end + chunk(types[2], m) + elseif encodeImage and PNG_TYPES[s] then + local ok, png, perr = pcall(encodeImage, im, "png") + if not ok or not png then + return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring((ok and{perr }or{png})[1])) + end + chunk(PNG_TYPES[s], png ) + else + return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, encodeImage and"" or" without an encodeImage hook (16 / 32 / 48 / 128 only)")) + end + end + local data = body:finish() + local out = Bytes.writer(buffer.len(data) + 8) + out:string("icns") + out:u32be(buffer.len(data) + 8) + out:bytes(data) + return out:finish(), nil +end + +return Icns +end +__FILES["image/ico"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every +-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or +-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are +-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest); +-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png +-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as +-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it +-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot. +-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS +-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Dib = __include("image/ico/Dib") + +-- ------------------------------------------------------------------------------------------------ contract +local Ico = { + name = "ico", + category = "image", + extensions = { "ico", "cur" }, + mime = { "image/vnd.microsoft.icon", "image/x-icon" }, + 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 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local PNG_SIG = "\137PNG\r\n\26\n" +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Ico.sniff(r) +if r:remaining() < 22 then + return 0 + end + local b, o = r.buf, r.pos + local typ = buffer.readu16(b, o + 2) + local count = buffer.readu16(b, o + 4) + if buffer.readu16(b, o) ~= 0 or (typ ~= 1 and typ ~= 2) or count == 0 then + return 0 + end + -- the first entry: reserved byte 0, a size and offset inside the file + local size, off = buffer.readu32(b, o + 14), buffer.readu32(b, o + 18) + if readu8(b, o + 9) ~= 0 or size == 0 or off < 6 + count * 16 then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function le16(b, p) +return buffer.readu16(b, p) +end +local function le32(b, p) +return buffer.readu32(b, p) +end + +function Ico.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local decodeImage = opts and opts.decodeImage + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 6 then + return nil, Err.new(Err.TRUNCATED, "short header", base) + end + local typ, count = le16(b, base + 2), le16(b, base + 4) + if le16(b, base) ~= 0 or (typ ~= 1 and typ ~= 2) then + return nil, Err.new(Err.CORRUPT, "not an ICO / CUR file", base) + end + if count == 0 then + return nil, Err.new(Err.CORRUPT, "no images", base) + end + if base + 6 + count * 16 > limit then + return nil, Err.new(Err.TRUNCATED, "directory runs past the end", base) + end + local frames= {} + local best= nil + local bestScore = -1 + local skipped, lastErr = 0, nil +for i = 0, count - 1 do + local d = base + 6 + i * 16 + local dw, dh = readu8(b, d), readu8(b, d + 1) + dw = dw == 0 and 256 or dw + dh = dh == 0 and 256 or dh + local f1, f2 = le16(b, d + 4), le16(b, d + 6) + local size, off = le32(b, d + 8), le32(b, d + 12) + local p, e = base + off, base + off + size + local img= nil + local depth = 0 + local isPng = false + if off < 6 or p >= limit then + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " lies past the end", d) + else + e = math.min(e, limit) + if e - p >= 8 and buffer.readstring(b, p, 8) == PNG_SIG then + isPng = true + depth = 32 + if decodeImage then + local sub = buffer.create(e - p) + buffer.copy(sub, 0, b, p, e - p) + local ok, pimg, perr = pcall(decodeImage, sub) + if ok and pimg and pimg.format == "rgba8" then + img = pimg + else + lastErr = (ok and perr and{perr }or{(Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad PNG") +)})[1] end + else + lastErr = Err.new(Err.UNSUPPORTED, "PNG entries need opts.decodeImage (F.load passes it)") + end + elseif e - p >= 40 then + local hs = le32(b, p) + local bw = buffer.readi32(b, p + 4) + local bh = buffer.readi32(b, p + 8) + local bpp = le16(b, p + 14) + local clrUsed = le32(b, p + 32) + local w = (bw > 0 and{bw }or{dw +})[1] local h = (bh ~= 0 and{(math.floor(math.abs(bh) / 2 ))}or{dh +})[1] if hs < 12 or hs > e - p or w < 1 or h < 1 or w > 4096 or h > 4096 then + lastErr = Err.new(Err.CORRUPT, "entry " .. (i + 1) .. ": bad bitmap header", p) + elseif bpp ~= 1 and bpp ~= 4 and bpp ~= 8 and bpp ~= 16 and bpp ~= 24 and bpp ~= 32 then + lastErr = Err.new(Err.UNSUPPORTED, "entry " .. (i + 1) .. ": " .. bpp .. "-bit bitmap", p) + elseif w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + else + depth = bpp + local q = p + hs + local palN = 0 + local pal = buffer.create(4) + if bpp <= 8 then + palN = (clrUsed > 0 and clrUsed < 2 ^ bpp and{clrUsed }or{(2 ^ bpp +)})[1] if q + palN * 4 > e then + palN = 0 + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": colour table runs past the entry", q) + else + pal = buffer.create(palN * 4) + for k = 0, palN - 1 do + local c = q + k * 4 + buffer.writeu32(pal, k * 4, readu8(b, c + 2) + readu8(b, c + 1) * 256 + readu8(b, c) * 65536 + 0xFF000000) + end + q =q+ palN * 4 + end + end + if bpp > 8 or palN > 0 then + if bpp == 16 and le32(b, p + 16) == 3 then + q =q+ 12 -- BI_BITFIELDS masks (assumed 5-5-5) + end + local out = Types.Image.new(w, h, "rgba8") + local ok, msg = Dib.decode(b, q, e, w, h, bpp, pal, palN, out.pixels) + if ok then + img = out + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. ": " .. tostring(msg), q) + end + end + end + else + lastErr = Err.new(Err.TRUNCATED, "entry " .. (i + 1) .. " is too short", p) + end + end + if img then + local im = img +im.meta.source = { format = "ico", bitDepth = depth, png = isPng, colorCount = readu8(b, d + 2) } + if typ == 2 then + im.meta.hotspot = { x = f1, y = f2 } + end + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } ) + local score = im.width * im.height * 64 + depth + if score > bestScore then + best, bestScore = im, score + end + else + skipped =skipped+ 1 + end + end + if not best then + return nil, lastErr or Err.new(Err.CORRUPT, "no decodable entry") + end + local main = best +local img = Types.Image.new(main.width, main.height, "rgba8") + buffer.copy(img.pixels, 0, main.pixels) + if #frames > 1 then + img.frames = frames + end + img.meta.source = { format = "ico", type = typ == 2 and"cur" or"ico", bitDepth = main.meta.source and main.meta.source.bitDepth, entries = count, skipped = skipped, png = main.meta.source and main.meta.source.png } + img.meta.hotspot = main.meta.hotspot + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ico.encode(img, opts) +if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o= opts or {} + local list= {} + if type(img.frames) == "table" and #img.frames > 0 then + for _, f in __iter(img.frames) do + table.insert(list, f.image) + end + else + list[1] = img + end + local cursor = o.cursor + if cursor == nil then + cursor = type(img.meta) == "table" and img.meta.hotspot ~= nil + end + local blobs= {} + for i, im in __iter(list) do + if type(im) ~= "table" or im.format ~= "rgba8" or type(im.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "entry " .. i .. ": needs an rgba8 Image") + end + local w, h = im.width, im.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 256 or h > 256 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(im.pixels) < w * h * 4 then + return nil, Err.new(Err.ARG, "entry " .. i .. ": icons are 1..256 pixels per side") + end + local png = nil + if o.encodeImage and (o.png or w == 256 or h == 256) then + local ok, res, err = pcall(o.encodeImage, im, "png") + if not ok or not res then + return nil, (ok and err and{err }or{(Err.new(Err.ARG, "entry " .. i .. ": PNG encode failed") +)})[1] end + png = res + elseif o.png then + return nil, Err.new(Err.ARG, "opts.png needs opts.encodeImage (F.save passes it)") + end + if png then + blobs[i] = png + else + local maskStride = (math.floor((w + 31) / 32)) * 4 + local n = 40 + w * h * 4 + maskStride * h + local d = buffer.create(n) + buffer.writeu32(d, 0, 40) + buffer.writei32(d, 4, w) + buffer.writei32(d, 8, h * 2) + buffer.writeu16(d, 12, 1) + buffer.writeu16(d, 14, 32) + buffer.writeu32(d, 20, w * h * 4 + maskStride * h) + Dib.encode(im.pixels, w, h, d, 40) + blobs[i] = d + end + end + local total = 6 + #list * 16 + for _, bl in __iter(blobs) do + total =total+ buffer.len(bl) + end + local out = buffer.create(total) + buffer.writeu16(out, 2, cursor and 2 or 1) + buffer.writeu16(out, 4, #list) + local off = 6 + #list * 16 + for i, im in __iter(list) do + local d = 6 + (i - 1) * 16 + buffer.writeu8(out, d, im.width % 256) + buffer.writeu8(out, d + 1, im.height % 256) + if cursor then + local hs = (type(im.meta) == "table" and im.meta.hotspot) or (img.meta and img.meta.hotspot) or { x = 0, y = 0 } + buffer.writeu16(out, d + 4, math.clamp(math.floor(tonumber(hs.x) or 0), 0, 65535)) + buffer.writeu16(out, d + 6, math.clamp(math.floor(tonumber(hs.y) or 0), 0, 65535)) + else + buffer.writeu16(out, d + 4, 1) + buffer.writeu16(out, d + 6, 32) + end + buffer.writeu32(out, d + 8, buffer.len(blobs[i])) + buffer.writeu32(out, d + 12, off) + buffer.copy(out, off, blobs[i]) + off =off+ buffer.len(blobs[i]) + end + return out, nil +end + +return Ico +end +__FILES["image/ico/Dib"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from +-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit +-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha +-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are +-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +local Pixels = __include("codecs/image/Pixels") + +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 + +local Dib = {} + +-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out +function Dib.decode(b, p, e, w, h, bpp, pal, palN, out) +local stride = (math.floor((w * bpp + 31) / 32)) * 4 + local maskStride = (math.floor((w + 31) / 32)) * 4 + if p + stride * h > e then + return false, "colour bitmap runs past the entry" + end + local hasMask = p + stride * h + maskStride * h <= e + local anyAlpha = false + if bpp == 32 then + anyAlpha = Pixels.bgra32(b, p, stride, out, w, h, false) ~= 0 + elseif bpp == 24 then + Pixels.bgr24(b, p, stride, out, w, h, false) + elseif bpp == 16 then + Pixels.rgb555(b, p, stride, out, w, h, false) + else + -- palette indexes past palN read as opaque black + local full = buffer.create(1024) + for i = 0, 255 do + writeu32(full, i * 4, (i < palN and{(readu32(pal, i * 4) )}or{0xFF000000})[1]) + end + Pixels.indexed(b, p, stride, bpp, out, w, h, false, full) + end + if bpp == 32 and anyAlpha then + return true, nil + end + if hasMask then + local mp = p + stride * h + for y = 0, h - 1 do + local row = mp + (h - 1 - y) * maskStride + for x = 0, w - 1 do + local o = (y * w + x) * 4 + local px = readu32(out, o) % 16777216 + if (math.floor(readu8(b, row + math.floor(x / 8)) / 2 ^ (7 - x % 8))) % 2 == 1 then + writeu32(out, o, px) -- transparent + else + writeu32(out, o, px + 0xFF000000) + end + end + end + elseif bpp == 32 then + -- no alpha and no mask: opaque + for i = 0, w * h - 1 do + writeu32(out, i * 4, readu32(out, i * 4) % 16777216 + 0xFF000000) + end + end + return true, nil +end + +-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1). +-- out needs room for w * h * 4 + maskStride * h bytes. +function Dib.encode(px, w, h, out, o) +for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 4 + buffer.writeu8(out, o, readu8(px, q + 2)) + buffer.writeu8(out, o + 1, readu8(px, q + 1)) + buffer.writeu8(out, o + 2, readu8(px, q)) + buffer.writeu8(out, o + 3, readu8(px, q + 3)) + o =o+ 4 + end + end + local maskStride = (math.floor((w + 31) / 32)) * 4 + for y = h - 1, 0, -1 do + local acc, nb, written = 0, 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (readu8(px, (y * w + x) * 4 + 3) == 0 and 1 or 0) + nb =nb+ 1 + if nb == 8 then + buffer.writeu8(out, o + written, acc) + written =written+ 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + buffer.writeu8(out, o + written, acc * 2 ^ (8 - nb)) + written =written+ 1 + end + buffer.fill(out, o + written, 0, maskStride - written) + o =o+ maskStride + end + return o +end + +return Dib +end +__FILES["image/ilbm"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks +-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a +-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), +-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or +-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH +-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else +-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer +-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local PackBits = __include("codecs/compress/PackBits") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Ilbm = { + name = "ilbm", + category = "image", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types + + + + + + + + + +local readu8, readu16 = buffer.readu8, buffer.readu16 +local function be16(b, o) +return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ilbm.sniff(r) +if r:peek(4) ~= "FORM" then + return 0 + end + local t = r:peek(4, 8) + return (t == "ILBM" or t == "PBM " )and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ilbm.decode(r, opts) +local b, o, limit = r.buf, r.base, r.limit + if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o) + end + local form = buffer.readstring(b, o + 8, 4) + if form ~= "ILBM" and form ~= "PBM " then + return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8) + end + local chunky = form == "PBM " + local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF) + local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY") + if not bmhd or bmhd.avail < 20 then + return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12) + end + if not body then + return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12) + end + local q = bmhd.offset + local w, h = be16(b, q), be16(b, q + 2) + local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10) + local trans = be16(b, q + 12) + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "bad size", q) + end + if comp > 1 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10) + end + if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then + return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local camg = 0 + local c = Chunks.find(list, "CAMG") + if c and c.avail >= 4 then + camg = bit32.byteswap(buffer.readu32(b, c.offset)) + end + local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) + local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham + -- palette + local pal = buffer.create(1024) + local ncol = 0 + if cmap then + ncol = math.min(256, math.floor(cmap.avail / 3)) + local low = true + for i = 0, ncol * 3 - 1 do + low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0 + end + local adjust = low and opts and opts.adjustColors + for i = 0, ncol - 1 do + local function ch(k) +local v = readu8(b, cmap.offset + i * 3 + k) + return (adjust and{(v + bit32.rshift(v, 4) )}or{v +})[1] end + buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000) + end + end + if ncol == 0 and planes <= 8 then + local n = bit32.lshift(1, planes) + for i = 0, n - 1 do + local g = math.floor((i * 255) / math.max(1, n - 1) +) buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000) + end + ncol = n + end + if ehb then + for i = 0, 31 do + local v = buffer.readu32(pal, i * 4) + local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255) + buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) + end + end + -- the body, decompressed + local rowBytes = (chunky and((w + w % 2 ))or(((math.floor((w + 15) / 16)) * 2 +))) local total = (chunky and((rowBytes * h ))or((rowBytes * (planes + (masking == 1 and 1 or 0)) * h +))) local raw = buffer.create(total) + local truncated + if comp == 1 then + local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total) + truncated = written < total + else + local n = math.min(total, body.avail) + buffer.copy(raw, 0, b, body.offset, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if chunky then + Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal) + if masking == 2 then + for i = 0, w * h - 1 do + local y, x = math.floor(i / w), i % w + if readu8(raw, y * rowBytes + x) == trans then + buffer.writeu32(px, i * 4, 0) + end + end + end + else + local stride = rowBytes * (planes + (masking == 1 and 1 or 0)) + local deep = planes >= 24 + local bits = planes - 2 + for y = 0, h - 1 do + local row = y * stride + local pr, pg, pb= 0, 0, 0 + if ham then + local v = buffer.readu32(pal, 0) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + end + for x = 0, w - 1 do + local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7) + local idx = 0 + for k = 0, planes - 1 do + idx =idx+ bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k + end + local out +if deep then + local a = (planes == 32 and{(bit32.rshift(idx, 24) % 256 )}or{255 +})[1] out = bit32.band(idx, 0xFFFFFF) + a * 16777216 + elseif ham then + local ctl = bit32.rshift(idx, bits) + local val = bit32.band(idx, bit32.lshift(1, bits) - 1) + local v8 = (bits == 4 and{(val * 17 )}or{(val * 4 + bit32.rshift(val, 4) +)})[1] if ctl == 0 then + local v = buffer.readu32(pal, val * 4) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + elseif ctl == 1 then + pb = v8 + elseif ctl == 2 then + pr = v8 + else + pg = v8 + end + out = pr + pg * 256 + pb * 65536 + 0xFF000000 + else + out = buffer.readu32(pal, bit32.band(idx, 255) * 4) + if masking == 2 and idx == trans then + out = 0 + end + end + if masking == 1 then + local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1) + if m == 0 then + out = 0 + end + end + buffer.writeu32(px, (y * w + x) * 4, out) + end + end + end + if ncol > 0 and planes <= 8 and not ham then + local plist= {} + for i = 0, (ehb and 64 or ncol) - 1 do + local v = buffer.readu32(pal, i * 4) + plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = plist + end + local text= {} + for _, ch in __iter(list) do + if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then + local s = buffer.readstring(b, ch.offset, ch.avail) + local key = string.gsub(ch.id, "[^%w]", "") + text[string.lower(key)] = (string.gsub(s, "%z+$", "")) + end + end + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ilbm.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 + local planes = usePal and 1 or(alpha and 32 or 24 +) if usePal then + while bit32.lshift(1, planes) < #cols do + planes =planes+ 1 + end + end + local compress = not (opts and opts.compress == false) + local index= {} + for i, cv in __iter(cols) do + index[cv] = i - 1 + end + local rowBytes = (math.floor((w + 15) / 16)) * 2 + local body = Bytes.writer(rowBytes * planes * h) + local row = buffer.create(rowBytes) + for y = 0, h - 1 do + for k = 0, planes - 1 do + buffer.fill(row, 0, 0, rowBytes) + for x = 0, w - 1 do + local v = buffer.readu32(px, (y * w + x) * 4) + local idx = (usePal and{(index[bit32.band(v, 0xFFFFFF)] or 0) }or{v +})[1] if bit32.band(bit32.rshift(idx, k), 1) == 1 then + local at = bit32.rshift(x, 3) + buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7)))) + end + end + if compress then + body:bytes(PackBits.encode(row, 0, rowBytes)) + else + body:bytes(row) + end + end + end + local bodyData = body:finish() + local out = Bytes.writer(buffer.len(bodyData) + 900) + out:string("FORM") + out:u32be(0) + out:string("ILBM") + out:string("BMHD") + out:u32be(20) + out:u16be(w) + out:u16be(h) + out:u16be(0) + out:u16be(0) + out:u8(planes) + out:u8(0) + out:u8(compress and 1 or 0) + out:u8(0) + out:u16be(0) + out:u8(1) + out:u8(1) + out:u16be(w) + out:u16be(h) + if usePal then + local n = bit32.lshift(1, planes) + out:string("CMAP") + out:u32be(n * 3) + for i = 1, n do + local cv = cols[i] or 0 + out:u8(bit32.band(cv, 255)) + out:u8(bit32.band(bit32.rshift(cv, 8), 255)) + out:u8(bit32.rshift(cv, 16)) + end + if (n * 3) % 2 == 1 then + out:u8(0) + end + end + out:string("BODY") + out:u32be(buffer.len(bodyData)) + out:bytes(bodyData) + if buffer.len(bodyData) % 2 == 1 then + out:u8(0) + end + local res = out:finish() + buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8)) + return res, nil +end + +return Ilbm +end +__FILES["image/jpeg"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG +-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical +-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the +-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi +-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images +-- (coded 4:2:0 from the planes as they are). +-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit +-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt +-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's +-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt +-- scans decode as far as they go (meta.truncated = true). +-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or +-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta; +-- byte-identical to cjpeg for the same settings. +-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit +-- or CMYK encoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("codecs/image/Jpeg") + +-- ------------------------------------------------------------------------------------------------ contract +local Jpeg = { + name = "jpeg", + category = "image", + extensions = { "jpg", "jpeg", "jpe", "jfif" }, + mime = { "image/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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + + + +function Jpeg.sniff(r) +local s = r:peek(3) + return s == "\255\216\255" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- info(r) -> Info | nil, Err (reads the headers up to the frame header) +function Jpeg.info(r) +return Codec.info(r.buf, r.base, r.limit - r.base) +end + +function Jpeg.decode(r, opts) +if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o = opts or {} -- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF) + +return Codec.decode(r.buf, r.base, r.limit - r.base, { + scale = o.scale, + orient = o.orient, + native = o.native, + maxPixels = o.maxPixels, + fields = false, + }) +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the APP1 / APP2 / COM segments and the JFIF density from img.meta +local function metaSegments(meta) +local segments = {} + if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then + local d = buffer.create(buffer.len(meta.exif) + 6) + buffer.writestring(d, 0, "Exif\0\0") + buffer.copy(d, 6, meta.exif) + table.insert(segments, { marker = 0xE1, data = d }) + end + if type(meta.icc) == "buffer" then + local icc = meta.icc +local n = buffer.len(icc) + local chunk = 65519 + local count = math.max(1, math.ceil(n / chunk)) + if count <= 255 then + for i = 1, count do + local a = (i - 1) * chunk + local l = math.min(chunk, n - a) + local d = buffer.create(l + 14) + buffer.writestring(d, 0, "ICC_PROFILE\0") + buffer.writeu8(d, 12, i) + buffer.writeu8(d, 13, count) + buffer.copy(d, 14, icc, a, l) + table.insert(segments, { marker = 0xE2, data = d }) + end + end + end + local text = meta.text + if type(text) == "table" and type(text.comment) == "string" and #text.comment <= 65533 then + table.insert(segments, { marker = 0xFE, data = buffer.fromstring(text.comment) }) + end + local density = nil + if type(meta.dpi) == "table" and type(meta.dpi.x) == "number" and type(meta.dpi.y) == "number" then + density = { unit = 1, x = math.clamp(math.floor(meta.dpi.x + 0.5), 1, 65535), y = math.clamp(math.floor(meta.dpi.y + 0.5), 1, 65535) } + end + return segments, density +end + +function Jpeg.encode(img, opts) +if type(img) ~= "table" then + return nil, Err.new(Err.ARG, "needs an Image") + end + if opts ~= nil and type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "options must be a table") + end + local o= opts or {} + local segments, density = {}, nil + if o.meta ~= false then + segments, density = metaSegments(img.meta or {}) + elseif type(img.meta) == "table" then + local _ + _, density = metaSegments({ dpi = img.meta.dpi }) + end + return Codec.encode(img, { + quality = o.quality, + subsampling = o.subsampling, + progressive = o.progressive, + optimize = o.optimize, + gray = o.gray, + restart = o.restart, + jfif = o.jfif, + density = density, + segments = segments, + }) +end + +return Jpeg +end +__FILES["image/ktx"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL +-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the +-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every +-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip +-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are +-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is +-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. +-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 +-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, +-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and +-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Texel = __include("codecs/image/Texel") +local Texture = __include("codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Ktx = { + name = "ktx", + category = "image", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + +local ID1 = "\171KTX 11\187\r\n\26\n" +local ID2 = "\171KTX 20\187\r\n\26\n" + +-- VkFormat -> texture format name +local VK= { + [2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1", + [9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8", + [16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8", + [23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8", + [30] = "bgr8", [36] = "bgr8", + [37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8", + [44] = "bgra8", [50] = "bgra8", + [58] = "bgr10a2", [64] = "rgb10a2", + [70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f", + [77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f", + [84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f", + [91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f", + [98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f", + [104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f", + [122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f", + [131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3", + [139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7", + [147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba", + [153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s", +} +local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true } +local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black +-- OpenGL compressed internal formats +local GL_COMPRESSED= { + [0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3", + [0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3", + [0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s", + [0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h", + [0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1", + [0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s", +} +local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true } +local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true } +-- glFormat -> channel order; glType -> bit size, Texel suffix +local GL_ORDER= { + [0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra", + [0x1909] = "l", [0x190A] = "la", [0x1906] = "a", + [0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats +} +local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true } +local GL_PACKED= { + [0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5", +} +local GL_TYPES= { + [0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" }, + [0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" }, +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } + +local readu32, readstring = buffer.readu32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Ktx.sniff(r) +return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1)) +end +-- ------------------------------------------------------------------------------------------------ decode + + + + + + + + + + + + + + + + + + + + + + + +local function u64(b, o) +return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4 +local function keyValues(b, p, stop, be) +local kv= {} + while p + 4 <= stop do + local n = readu32(b, p) + if be then + n = bit32.byteswap(n) + end + p =p+ 4 + if n > stop - p then + break + end + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + if z then + local v = string.sub(s, z + 1) + if string.sub(v, -1) == "\0" then + v = string.sub(v, 1, -2) + end + kv[string.sub(s, 1, z - 1)] = v + end + p =p+ (n + (3 - (n + 3) % 4) +) end + return kv +end + +local function info1(r) +local b, o, n = r.buf, r.base, r.limit - r.base + if n < 64 then + return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o) + end + local e = readu32(b, o + 12) + local be = e == 0x01020304 + if not be and e ~= 0x04030201 then + return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12) + end + local function f(i) +local v = readu32(b, o + 16 + i * 4) + return (be and{(bit32.byteswap(v) )}or{v +})[1] end + local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3) + local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16) + end + if 64 + kvBytes > n then + return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64) + end + local info= { + version = 1, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, arr), + faces = faces, + levels = math.max(1, levels), + srgb = GL_SRGB[internal] == true, + opaque = GL_OPAQUE[internal] == true, + glInternalFormat = internal, + keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be), + bigEndian = be, + typeSize = typeSize, + dataOffset = 64 + kvBytes, + } + if glType == 0 then + info.format = GL_COMPRESSED[internal] + if not info.format then + info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal) + end + else + local name = GL_PACKED[glType] + if not name then + local order = GL_ORDER[glFormat] + local int = GL_INTEGER[glFormat] == true + -- glType -> component bits, Texel suffix (normalized / integer) + local t = GL_TYPES[glType] + local size= t and t[1] + local suffix= (t and{((int and{t[3] }or{t[2]})[1]) }or{"" +})[1] if order and size then + name = order .. tostring(size) .. suffix + end + end + if name and Texel.FORMATS[name] then + info.format = name + else + info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType) + end + end + return info, nil +end + +local function info2(r) +local b, o, n = r.buf, r.base, r.limit - r.base + if n < 80 then + return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o) + end + local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16) + local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28) + local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20) + end + local nl = math.max(1, levels) + if 80 + nl * 24 > n then + return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80) + end + local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60) + local info= { + version = 2, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, layers), + faces = faces, + levels = nl, + srgb = VK_SRGB[vk] == true, + opaque = VK_OPAQUE[vk] == true, + vkFormat = vk, + supercompression = scheme, + keyValue = (kvLen > 0 and kvOff + kvLen <= n and{(keyValues(b, o + kvOff, o + kvOff + kvLen, false) )}or{{}})[1], + typeSize = typeSize, + dataOffset = 0, + levelIndex = {}, + } + for i = 0, nl - 1 do + local q = o + 80 + i * 24 + table.insert(info.levelIndex , { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) }) + end + -- the colour model of the DFD tells Basis Universal apart + local model = -1 + if dfdLen >= 16 and dfdOff + dfdLen <= n then + model = buffer.readu8(b, o + dfdOff + 12) + if buffer.readu8(b, o + dfdOff + 14) == 2 then + info.srgb = true + end + end + if scheme == 1 or model == 163 then + info.unsupported = "Basis Universal ETC1S / BasisLZ" + elseif model == 166 then + info.unsupported = "Basis Universal UASTC" + elseif scheme > 3 then + info.unsupported = "supercompression scheme " .. scheme + elseif vk == 0 then + info.unsupported = "VK_FORMAT_UNDEFINED" + else + info.format = VK[vk] + if not info.format then + info.unsupported = "VkFormat " .. vk .. ((vk >= 157 and vk <= 184 or vk >= 1000066000 )and" (ASTC)" or"") + end + end + return info, nil +end + +-- info(r) -> Info | nil, Err (the headers only) +function Ktx.info(r) +local id = r:peek(12) + if id == ID2 then + return info2(r) + elseif id == ID1 then + return info1(r) + end + return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) +end + +-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image +local function swapped(b, p, n, size) +local out = buffer.create(n) + buffer.copy(out, 0, b, p, n) + for i = 0, n - size, size do + if size == 2 then + buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16)) + else + buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i))) + end + end + return out +end + +-- flips the rows of a decoded surface (KTXorientation T=u) +local function flip(img) + local row = img.width * (Types.BPP[img.format] or 4) + local px = img.pixels + local tmp = buffer.create(row) + for y = 0, math.floor(img.height / 2 )- 1 do + local a, z = y * row, (img.height - 1 - y) * row + buffer.copy(tmp, 0, px, a, row) + buffer.copy(px, a, px, z, row) + buffer.copy(px, z, tmp, 0, row) + end +end + +function Ktx.decode(r, opts) +local info, ierr = Ktx.info(r) + if not info then + return nil, ierr + end + local fmt = info.format + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format") + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base, limit = r.buf, r.base, r.limit + local bw, bh, bbytes = Texture.block(fmt) + local blockFmt = bw == 4 + local orient = info.keyValue.KTXorientation or "" + local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u") + local list= {} + local pixels = 0 + local count = info.layers * info.faces + local p = base + info.dataOffset + local w, h, d = info.width, info.height, info.depth + for level = 0, info.levels - 1 do + local want = level == 0 or wantMips + -- the level's data: buf, offset, the image stride and row pitch + local lb, lp = b, 0 + local rowPitch= nil + local imgSize = (Texture.size(fmt, w, h) ) +local stride = imgSize + if info.version == 1 then + if p + 4 > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "missing level 0", p) + end + break + end + local declared = readu32(b, p) + if info.bigEndian then + declared = bit32.byteswap(declared) + end + p =p+ 4 + if not blockFmt then + local tight = (bbytes ) * w + rowPitch = tight + (3 - (tight + 3) % 4) + imgSize = (rowPitch ) * h + end + stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding + local total = stride * count * d + if declared < imgSize * (info.faces == 6 and info.layers == 1 and 1 or count * d) and level == 0 then + return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4) + end + if p + total > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p) + end + break + end + lp = p + p =p+ total + p =p+ (3 - (total + 3) % 4 +) if info.bigEndian and info.typeSize > 1 and want then + lb, lp = swapped(b, lp, total, info.typeSize), 0 + end + else + local li = (info.levelIndex )[level + 1] + local off, len = base + li.offset, li.length + if off + len > limit or li.offset < 80 then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off) + end + break + end + local expect = imgSize * count * d + if want then + local scheme = info.supercompression + if scheme == 2 or scheme == 3 then + if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24) + end + local out, zerr + if scheme == 2 then + out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed }) + else + out, zerr = Deflate.zlib(b, off, len, li.uncompressed) + end + if not out then + return nil, Err.wrap(zerr) + end + lb, lp = out, 0 + else + lb, lp = b, off + end + if lp + expect > buffer.len(lb) then + return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off) + end + end + end + if want then + for layer = 0, count - 1 do + for slice = 0, d - 1 do +local __DARKLUA_CONTINUE_7=false repeat if level == 0 and not wantAll and (layer > 0 or slice > 0) then +__DARKLUA_CONTINUE_7=true break + end + if level > 0 and (layer > 0 or slice > 0) then +__DARKLUA_CONTINUE_7=true break + end + pixels =pixels+ w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local at = lp + (layer * d + slice) * stride + local px, pf + if rowPitch then + px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch) + else + px, pf = Texture.decode(fmt, lb, at, w, h, native) + end + if not px then + return nil, Err.from(pf, at) + end + local im = Texture.image(px, pf, w, h) + if info.opaque then + for i = 0, w * h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + end + if up then + flip(im) + end + table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im }) +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + end + end + w, h, d = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)), math.max(1, math.floor(d / 2)) + end + local layout = info.depth > 1 and"volume" or(info.faces == 6 and"cube" or(info.layers > 1 and"array" or"2d" +)) local img = Texture.assemble(list, layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no image data") + end + if info.faces == 6 then + img.meta.faces = table.clone(FACES) + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.keyValue = info.keyValue + img.meta.source = { + format = "ktx", + version = info.version, + pixelFormat = fmt, + vkFormat = info.vkFormat, + glInternalFormat = info.glInternalFormat, + supercompression = info.supercompression, + mips = info.levels, + layers = info.layers, + depth = info.depth, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- format -> VkFormat, bytes per texel, component bytes, kind +local OUT= { + rgba8 = { 37, 4, 1 }, + rgba16 = { 91, 8, 2 }, + rgba16f = { 97, 8, 2 }, + rgba32f = { 109, 16, 4 }, +} + +-- the DFD: one basic descriptor block with four samples (R G B A) +local function dfd(f, srgb) +local spec = OUT[f] + local texel, comp = spec[2], spec[3] + local float = f == "rgba16f" or f == "rgba32f" + local w = Bytes.writer(92) + local blockSize = 24 + 16 * 4 + w:u32le(4 + blockSize) + w:u32le(0) -- vendor 0, descriptor type 0 + w:u32le(2 + blockSize * 65536) -- version 2, block size + w:u8(1) -- colour model RGBSDA + w:u8(1) -- primaries BT.709 + w:u8(srgb and 2 or 1) -- transfer: sRGB / linear + w:u8(0) -- straight alpha + w:u32le(0) -- texel block 1 x 1 x 1 x 1 + w:u32le(texel) -- bytesPlane0 + w:u32le(0) + for c = 0, 3 do + local channel = c == 3 and 15 or c + local qual = (float and 0xC0 or 0) + (srgb and c == 3 and 0x10 or 0) + w:u16le(c * comp * 8) + w:u8(comp * 8 - 1) + w:u8(channel + qual) + w:u32le(0) -- sample position + if float then + w:u32le(0xBF800000) + w:u32le(0x3F800000) + else + w:u32le(0) + w:u32le(comp == 1 and 255 or 65535) + end + end + return w:finish() +end + +function Ktx.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f= (opts and opts.pixelFormat) or (pf == "rgbaf32" and"rgba32f" or pf) + local spec = OUT[f] + if not spec then + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) + end + local needs = (f == "rgba16f" or f == "rgba32f" )and"rgbaf32" or f + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) + end + local srgb = f == "rgba8" and ((opts and opts.srgb ~= nil and{opts.srgb }or{(img.meta and img.meta.colorSpace == "srgb")})[1]) + local images= { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in __iter(img.frames) do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = (opts and opts.cube ~= nil and{opts.cube }or{(img.meta and img.meta.layout == "cube") +})[1] if cube and (#images % 6 ~= 0 or img.width ~= img.height) then + return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer") + end + local faces = cube and 6 or 1 + local layers = math.floor(#images / faces +) local levels = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m =math.floor(m/ 2 +) levels =levels+ 1 + end + end + local zl = opts and opts.zlib + if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then + return nil, Err.new(Err.ARG, "zlib level must be 1..9") + end + -- level data: the images of every layer / face per level + local levelData= {} + local raw= {} + local cur = table.clone(images) + for lv = 1, levels do + local w = Bytes.writer() + for i, im in __iter(cur) do + local data = (f == "rgba16f" and{(Texture.toHalf(im.pixels, im.width * im.height) )}or{im.pixels +})[1] w:bytes(data, 0, im.width * im.height * spec[2]) + if lv < levels then + cur[i] = Texture.halve(im) + end + end + local lb = w:finish() + raw[lv] = buffer.len(lb) + if zl then + lb = (Deflate.zlibCompress(lb, { level = zl }) ) +end + levelData[lv] = lb + end + -- key / value data + local kvw = Bytes.writer() + local pairs_= { { "KTXwriter", "rosetta" } } + if opts and opts.keyValue then + for k, v in __iter(opts.keyValue) do + if k ~= "KTXwriter" then + table.insert(pairs_, { k, v }) + end + end + end + table.sort(pairs_, function(a, c) +return a[1] < c[1] + end) + for _, kv in __iter(pairs_) do + local n = #kv[1] + 1 + #kv[2] + 1 + kvw:u32le(n) + kvw:string(kv[1]) + kvw:u8(0) + kvw:string(kv[2]) + kvw:u8(0) + kvw:fill(0, 3 - (n + 3) % 4) + end + local kvd = kvw:finish() + local d = dfd(f, srgb == true) + local dfdOff = 80 + levels * 24 + local kvOff = dfdOff + buffer.len(d) + local dataStart = kvOff + buffer.len(kvd) + local align = zl and 1 or((spec[2] % 4 == 0 and{spec[2] }or{4})[1]) + -- smallest level first + local offsets= {} + local p = dataStart + for lv = levels, 1, -1 do + p =p+ (align - p % align) % align + offsets[lv] = p + p =p+ buffer.len(levelData[lv]) + end + local out = Bytes.writer(p) + out:string(ID2) + out:u32le(f == "rgba8" and srgb and 43 or spec[1]) + out:u32le(spec[3]) + out:u32le(img.width) + out:u32le(img.height) + out:u32le(0) + out:u32le((layers > 1 and{layers }or{0})[1]) + out:u32le(faces) + out:u32le(levels) + out:u32le(zl and 3 or 0) + out:u32le(dfdOff) + out:u32le(buffer.len(d)) + out:u32le(kvOff) + out:u32le(buffer.len(kvd)) + out:u64le(0) + out:u64le(0) + for lv = 1, levels do + out:u64le(offsets[lv]) + out:u64le(buffer.len(levelData[lv])) + out:u64le(raw[lv]) + end + out:bytes(d) + out:bytes(kvd) + for lv = levels, 1, -1 do + out:fill(0, offsets[lv] - out:tell()) + out:bytes(levelData[lv]) + end + return out:finish(), nil +end + +return Ktx +end +__FILES["image/pcx"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit +-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the +-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross +-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as +-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcx = { + name = "pcx", + category = "image", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types + + + + + + + + +local readu8, readu16 = buffer.readu8, buffer.readu16 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcx.sniff(r) +if r:size() < 128 then + return 0 + end + local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3) + if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then + return 0 + end + return (bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 )and 0.8 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pcx.decode(r, opts) +local b, o, limit = r.buf, r.base, r.limit + if limit - o < 128 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if readu8(b, o) ~= 10 then + return nil, Err.new(Err.CORRUPT, "not a PCX file", o) + end + local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) + local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10) + local planes, bpl = readu8(b, o + 65), readu16(b, o + 66) + local w, h = x1 - x0 + 1, y1 - y0 + 1 + if x1 < x0 or y1 < y0 then + return nil, Err.new(Err.CORRUPT, "bad window", o + 4) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local kind + if bpp == 8 and planes == 1 then + kind = "pal8" + elseif bpp == 8 and (planes == 3 or planes == 4) then + kind = "rgb" + elseif bpp == 1 and planes >= 1 and planes <= 4 then + kind = "planar" + elseif (bpp == 2 or bpp == 4) and planes == 1 then + kind = "packed" + else + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3) + end + if bpl * 8 < w * bpp then + return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66) + end + -- the scan lines (planes after each other per line), RLE across lines + local total = bpl * planes * h + local raw = buffer.create(total) + local p, q = o + 128, 0 + local truncated = false + if enc == 1 then + while q < total do + if p >= limit then + truncated = true + break + end + local c = readu8(b, p) + p =p+ 1 + if c >= 0xC0 then + if p >= limit then + truncated = true + break + end + local n = math.min(c - 0xC0, total - q) + buffer.fill(raw, q, readu8(b, p), n) + p =p+ 1 + q =q+ n + else + buffer.writeu8(raw, q, c) + q =q+ 1 + end + end + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + p =p+ n + truncated = n < total + end + -- palettes + local pal = buffer.create(1024) + local function setPal(i, rr, gg, bb) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + if kind == "pal8" then + local at = limit - 769 + if at >= p and readu8(b, at) == 12 then + for i = 0, 255 do + setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3)) + end + else + for i = 0, 255 do + setPal(i, i, i, i) + end + end + elseif kind == "planar" and planes == 1 then + setPal(0, 0, 0, 0) + setPal(1, 255, 255, 255) + else + for i = 0, 15 do + setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3)) + end + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if kind == "pal8" or kind == "packed" then + Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal) + elseif kind == "planar" then + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local idx = 0 + for pl = 0, planes - 1 do + local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3)) + idx =idx+ bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl) + end + buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4)) + end + end + else + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local d = (y * w + x) * 4 + buffer.writeu8(px, d, readu8(raw, row + x)) + buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x)) + buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x)) + buffer.writeu8(px, d + 3, (planes == 4 and{(readu8(raw, row + 3 * bpl + x) )}or{255})[1]) + end + end + end + if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then + local list= {} + for i = 0, (kind == "pal8" and 256 or bit32.lshift(1, bpp * planes)) - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + local hd, vd = readu16(b, o + 12), readu16(b, o + 14) + if hd > 0 and vd > 0 then + img.meta.dpi = { x = hd, y = vd } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- RLE of one plane row into w +local function rleRow(out, src, p, n) + local i = 0 + while i < n do + local v = readu8(src, p + i) + local run = 1 + while i + run < n and run < 63 and readu8(src, p + i + run) == v do + run =run+ 1 + end + if run > 1 or v >= 0xC0 then + out:u8(0xC0 + run) + end + out:u8(v) + i =i+ run + end +end + +function Pcx.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false) + local planes = usePal and 1 or(alpha and 4 or 3 +) local bpl = w + w % 2 + local out = Bytes.writer(128 + w * h * planes + 800) + out:u8(10) + out:u8(5) + out:u8(1) + out:u8(8) + out:u16le(0) + out:u16le(0) + out:u16le(w - 1) + out:u16le(h - 1) + local dpi = img.meta and img.meta.dpi + out:u16le((dpi and{(math.floor(dpi.x + 0.5) )}or{72})[1]) + out:u16le((dpi and{(math.floor(dpi.y + 0.5) )}or{72})[1]) + out:fill(0, 48) + out:u8(0) + out:u8(planes) + out:u16le(bpl) + out:u16le(1) + out:fill(0, 58) + local row = buffer.create(bpl) + local index= {} + for i, c in __iter(cols) do + index[c] = i - 1 + end + for y = 0, h - 1 do + for pl = 0, planes - 1 do + for x = 0, w - 1 do + local s = (y * w + x) * 4 + local v + if usePal then + v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0 + else + v = readu8(px, s + pl) + end + buffer.writeu8(row, x, v) + end + rleRow(out, row, 0, bpl) + end + end + if usePal then + out:u8(12) + for i = 0, 255 do + local c = cols[i + 1] or 0 + out:u8(bit32.band(c, 255)) + out:u8(bit32.band(bit32.rshift(c, 8), 255)) + out:u8(bit32.rshift(c, 16)) + end + end + return out:finish(), nil +end + +return Pcx +end +__FILES["image/png"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder. +-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16), +-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha +-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte). +-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose / +-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not +-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode +-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked. +-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are +-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Crc32 = __include("core/Crc32") +local Deflate = __include("codecs/compress/Deflate") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Decode = __include("image/png/Decode") +local Encode = __include("image/png/Encode") +local Apng = __include("image/png/Apng") + +-- ------------------------------------------------------------------------------------------------ contract +local Png = { + name = "png", + category = "image", + extensions = { "png", "apng" }, + mime = { "image/png", "image/apng" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local SIGNATURE = "\137PNG\r\n\26\n" +local VALID = { + [0] = { [1] = true, [2] = true, [4] = true, [8] = true, [16] = true }, + [2] = { [8] = true, [16] = true }, + [3] = { [1] = true, [2] = true, [4] = true, [8] = true }, + [4] = { [8] = true, [16] = true }, + [6] = { [8] = true, [16] = true }, +} +local COLOR_NAMES = { [0] = "gray", [2] = "rgb", [3] = "palette", [4] = "graya", [6] = "rgba" } + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b, o) +return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Png.sniff(r) +return r:peek(8) == SIGNATURE and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- the IHDR at r's start: Header | nil, Err + + + +local function header(r) +local b, o, n = r.buf, r.base, r.limit - r.base + if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", o) + end + if n < 33 or buffer.readstring(b, o + 12, 4) ~= "IHDR" or be32(b, o + 8) ~= 13 then + return nil, Err.new(Err.CORRUPT, "missing IHDR", o + 8) + end + local h = { + width = be32(b, o + 16), + height = be32(b, o + 20), + bitDepth = readu8(b, o + 24), + colorType = readu8(b, o + 25), + interlace = readu8(b, o + 28), + } + if h.width == 0 or h.height == 0 or h.width >= 2 ^ 31 or h.height >= 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad image size", o + 16) + end + local depths = VALID[h.colorType] + if not depths then + return nil, Err.new(Err.CORRUPT, "bad colour type " .. h.colorType, o + 25) + end + if not depths[h.bitDepth] then + return nil, Err.new(Err.CORRUPT, string.format("bad bit depth %d for colour type %d", h.bitDepth, h.colorType), o + 24) + end + if readu8(b, o + 26) ~= 0 or readu8(b, o + 27) ~= 0 or h.interlace > 1 then + return nil, Err.new(Err.UNSUPPORTED, "unknown compression, filter or interlace method", o + 26) + end + return h, nil +end + +-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header) +function Png.info(r) +return header(r) +end + + + + + + + + + + + + + +local DISPOSE= { [0] = "none", [1] = "background", [2] = "previous" } + +-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split +-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h) +local function pixels(b, chunks, total, w, ht, depth, ct, interlace, pal, tr, out) -- the inflated size: every (pass) row has a filter byte + +local channels = Decode.CHANNELS[ct] + local expected = 0 + if interlace == 0 then + expected = ht * (Decode.rowBytes(w, channels, depth) + 1) + else + for _, pass in __iter(Decode.PASSES) do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = (w > x0 and{(math.floor((w - x0 + dx - 1) / dx ))}or{0 +})[1] local ph = (ht > y0 and{(math.floor((ht - y0 + dy - 1) / dy ))}or{0 +})[1] if pw > 0 and ph > 0 then + expected =expected+ ph * (Decode.rowBytes(pw, channels, depth) + 1) + end + end + end + local z +if #chunks == 1 then + z = b + else + z = buffer.create(total) + local w0 = 0 + for _, c in __iter(chunks) do + buffer.copy(z, w0, b, c[1], c[2]) + w0 =w0+ c[2] + end + end + local zo = (#chunks == 1 and{chunks[1][1] }or{0 +})[1] local raw, zerr = Deflate.zlib(z, zo, total, expected) + if not raw then + -- some encoders leave extra bytes after the rows: inflate without the exact size, keep the rows + local loose = Deflate.zlib(z, zo, total) + if not loose or buffer.len(loose) < expected then + return zerr or Err.new(Err.CORRUPT, "bad image data") + end + raw = loose + end + local ok, derr = Decode.run(raw , w, ht, depth, ct, interlace, pal, tr, out) + if not ok then + return Err.new(Err.CORRUPT, tostring(derr)) + end + return nil +end + +function Png.decode(r, opts) +local checkCrc = opts and opts.checkCrc or false + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h, herr = header(r) + if not h then + return nil, herr + end + local w, ht, depth, ct = h.width, h.height, h.bitDepth, h.colorType + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b, n = r.buf, r.limit + -- chunks + local pal = buffer.create(1024) + for i = 0, 255 do + buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black + end + local palCount = 0 + local tr = -1 + local idat= {} + local idatLen = 0 + local text= {} + local iccCompressed= nil + -- APNG: acTL, then fcTL (+ IDAT for frame 1 when it is the default image) / fdAT, one sequence counter + local plays= nil + local fctls= {} + local seq = 0 + local idatInAnim = false + local animPixels = 0 + local p = r.base + 8 + local first = true + for _, c in __iter(Chunks.walk(b, p, n, Chunks.PNG)) do + local len, typ, d = c.size, c.id, c.offset + p = c.start + if c.truncated then + if p + 12 > n then + break -- not even a whole chunk header + CRC left (a cut tail) + end + return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p) + end + if checkCrc then + local want = be32(b, d + len) + if Crc32.raw(b, p + 4, len + 4) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC mismatch in chunk " .. typ, d + len) + end + end + if first and typ ~= "IHDR" then + return nil, Err.new(Err.CORRUPT, "IHDR is not the first chunk", p) + end + first = false + if typ == "PLTE" then + if len % 3 ~= 0 or len > 768 or len == 0 then + return nil, Err.new(Err.CORRUPT, "bad PLTE length", p) + end + palCount = math.floor(len / 3 +) for i = 0, palCount - 1 do + local q = d + i * 3 + buffer.writeu32(pal, i * 4, readu8(b, q) + readu8(b, q + 1) * 256 + readu8(b, q + 2) * 65536 + 0xFF000000) + end + elseif typ == "tRNS" then + if ct == 3 then + for i = 0, math.min(len, 256) - 1 do + buffer.writeu8(pal, i * 4 + 3, readu8(b, d + i)) + end + elseif ct == 0 and len >= 2 then + tr = readu8(b, d) * 256 + readu8(b, d + 1) + elseif ct == 2 and len >= 6 then + local function u16(q) +return readu8(b, d + q) * 256 + readu8(b, d + q + 1) + end + tr = u16(0) * 4294967296 + u16(2) * 65536 + u16(4) + end + elseif typ == "IDAT" then + table.insert(idat, { d, len }) + idatLen =idatLen+ len + if #fctls == 1 and #idat == 1 then + idatInAnim = true + end + elseif typ == "tEXt" then + local s = buffer.readstring(b, d, len) + local z = string.find(s, "\0", 1, true) + if z then + text[string.sub(s, 1, z - 1)] = string.sub(s, z + 1) + end + elseif typ == "iCCP" then + local cb = buffer.create(len) + buffer.copy(cb, 0, b, d, len) + iccCompressed = cb + elseif typ == "acTL" then + if len >= 8 and plays == nil and #idat == 0 then + plays = be32(b, d + 4) + end + elseif typ == "fcTL" and plays ~= nil then + if len < 26 then + return nil, Err.new(Err.CORRUPT, "short fcTL", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fcTL sequence %d, expected %d", be32(b, d), seq), p) + end + seq =seq+ 1 + local f= { + width = be32(b, d + 4), + height = be32(b, d + 8), + x = be32(b, d + 12), + y = be32(b, d + 16), + num = readu8(b, d + 20) * 256 + readu8(b, d + 21), + den = readu8(b, d + 22) * 256 + readu8(b, d + 23), + dispose = readu8(b, d + 24), + blend = readu8(b, d + 25), + chunks = {}, + len = 0, + } + if f.width == 0 or f.height == 0 or f.x + f.width > w or f.y + f.height > ht then + return nil, Err.new(Err.CORRUPT, "fcTL frame outside the image", p) + end + if f.dispose > 2 or f.blend > 1 then + return nil, Err.new(Err.CORRUPT, "bad fcTL dispose / blend op", p) + end + if #idat == 0 and (f.width ~= w or f.height ~= ht or f.x ~= 0 or f.y ~= 0) then + return nil, Err.new(Err.CORRUPT, "the fcTL before IDAT must cover the image", p) + end + animPixels =animPixels+ f.width * f.height + if animPixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("the animation frames are over the %d pixel limit", maxPixels)) + end + table.insert(fctls, f) + elseif typ == "fdAT" and plays ~= nil then + if len < 4 then + return nil, Err.new(Err.CORRUPT, "short fdAT", p) + end + if be32(b, d) ~= seq then + return nil, Err.new(Err.CORRUPT, string.format("fdAT sequence %d, expected %d", be32(b, d), seq), p) + end + seq =seq+ 1 + local f = fctls[#fctls] + if not f or (#fctls == 1 and idatInAnim) then + return nil, Err.new(Err.CORRUPT, "fdAT without its fcTL", p) + end + table.insert(f.chunks, { d + 4, len - 4 }) + f.len =f.len+ (len - 4 +) elseif typ == "IEND" then + break -- a missing IEND is tolerated (truncated tail after the data) + elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then + return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p) + end + end + if #idat == 0 then + return nil, Err.new(Err.TRUNCATED, "no image data", p) + end + if ct == 3 and palCount == 0 then + return nil, Err.new(Err.CORRUPT, "palette image without PLTE") + end + local img = Types.Image.new(w, ht, "rgba8") + local ierr = pixels(b, idat, idatLen, w, ht, h.bitDepth, ct, h.interlace, pal, tr, img.pixels) + if ierr then + return nil, ierr + end + if plays ~= nil and #fctls > 0 then + local last = fctls[#fctls] + if #fctls > 1 and #last.chunks == 0 then + fctls[#fctls] = nil -- a truncated file: the last frame never got its data + end + local frames= {} + for i, f in __iter(fctls) do + local fimg +if i == 1 and idatInAnim then + fimg = Types.Image.new(w, ht, "rgba8") + buffer.copy(fimg.pixels, 0, img.pixels) + else + if #f.chunks == 0 then + return nil, Err.new(Err.CORRUPT, "APNG frame " .. i .. " has no data") + end + fimg = Types.Image.new(f.width, f.height, "rgba8") + local ferr = pixels(b, f.chunks, f.len, f.width, f.height, h.bitDepth, ct, h.interlace, pal, tr, fimg.pixels) + if ferr then + ferr.message = "frame " .. i .. ": " .. ferr.message + return nil, ferr + end + end + frames[i] = { + image = fimg, + delay = f.num / (f.den == 0 and 100 or f.den), + x = f.x, + y = f.y, + dispose = DISPOSE[f.dispose] , + blend = f.blend == 1 and"over" or"source" , + } + end + img.frames = frames + img.loops = plays + img.meta.apngDefaultHidden = not idatInAnim + end + if ct == 3 then + local palette= {} + for i = 0, palCount - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if next(text) then + img.meta.text = text + end + img.meta.iccCompressed = iccCompressed + img.meta.source = { format = "png", bitDepth = depth, colorType = COLOR_NAMES[ct], interlace = h.interlace } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 } +local DISPOSE_CODES= { none = 0, background = 1, previous = 2 } +local BLEND_CODES= { source = 0, over = 1 } + +-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds +local function delayFraction(delay) +for den = 1, 1000 do + local num = math.floor(delay * den + 0.5) + if num > 65535 then + break + end + if math.abs(num / den - delay) < 1e-9 then + return num, den + end + end + if delay * 1000 <= 65535 then + return math.floor(delay * 1000 + 0.5), 1000 + elseif delay * 100 <= 65535 then + return math.floor(delay * 100 + 0.5), 100 + end + return math.min(65535, math.floor(delay + 0.5)), 1 +end + +local function validImage(im) +return type(im) == "table" + and im.format == "rgba8" + and type(im.pixels) == "buffer" + and type(im.width) == "number" + and type(im.height) == "number" + and im.width >= 1 + and im.height >= 1 + and im.width % 1 == 0 + and im.height % 1 == 0 + and buffer.len(im.pixels) >= im.width * im.height * 4 +end + +-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list +local function animationFrames(img, opts) +local frames = img.frames + local mode = (opts and{opts.apng }or{nil +})[1] if mode == false then + return nil, nil + end + if frames ~= nil and type(frames) ~= "table" then + return nil, Err.new(Err.ARG, "frames must be a list") + end + if frames == nil or #frames == 0 then + if mode then + return { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } }, nil + end + return nil, nil + end + for i, f in __iter(frames) do + local label = "png encode: frame " .. i + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, label .. ": needs an rgba8 image") + end + local x, y = f.x or 0, f.y or 0 + if type(x) ~= "number" or type(y) ~= "number" or x < 0 or y < 0 or x % 1 ~= 0 or y % 1 ~= 0 or x + f.image.width > img.width or y + f.image.height > img.height then + return nil, Err.new(Err.ARG, label .. ": rectangle outside the image") + end + if f.delay ~= nil and (type(f.delay) ~= "number" or not (f.delay >= 0)) then + return nil, Err.new(Err.ARG, label .. ": bad delay") + end + if f.dispose ~= nil and DISPOSE_CODES[f.dispose] == nil then + return nil, Err.new(Err.ARG, label .. ": bad dispose " .. tostring(f.dispose)) + end + if f.blend ~= nil and BLEND_CODES[f.blend] == nil then + return nil, Err.new(Err.ARG, label .. ": bad blend " .. tostring(f.blend)) + end + end + return frames, nil +end + +function Png.encode(img, opts) +if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + local level = opts and opts.level or 6 + if type(level) ~= "number" or level < 0 or level > 9 then + return nil, Err.new(Err.ARG, "level must be 0..9") + end + local frames, ferr = animationFrames(img, opts) + if ferr then + return nil, ferr + end + local loops = img.loops or 0 + if frames and (type(loops) ~= "number" or loops < 0 or loops > 4294967295 or loops % 1 ~= 0) then + return nil, Err.new(Err.ARG, "loops must be an integer 0..2^32-1") + end + local want = opts and opts.colorType or "auto" + local ctName= want + if want == "auto" then + -- the smallest colour type that holds the image and every frame + local alpha, color = false, false + local function scan(im) + local c = Encode.pickColorType(im.pixels, im.width, im.height) + alpha = alpha or c == "rgba" or c == "graya" + color = color or c == "rgba" or c == "rgb" + end + scan(img) + if frames then + for _, f in __iter(frames) do + scan(f.image) + end + end + ctName = (color and{(alpha and"rgba" or"rgb") }or{(alpha and"graya" or"gray") +})[1] end + local ct = CT_CODES[ctName] + if ct == nil then + return nil, Err.new(Err.ARG, "unknown colorType " .. tostring(want)) + end + local function zdata(im) +return (Deflate.zlibCompress(Encode.filter(im.pixels, im.width, im.height, ct), { level = level }) ) +end + + local out = Bytes.writer(w * h + 128) + local function chunk(typ, data, prefix) + local len = ((data and{(buffer.len(data) )}or{0})[1]) + (prefix and 4 or 0) + out:u32be(len) + local start = out:tell() + out:string(typ) + if prefix then + out:u32be(prefix) + end + if data then + out:bytes(data) + end + out:u32be(Crc32.raw(out.buf, start, len + 4)) + end + out:string(SIGNATURE) + local ihdr = Bytes.writer(13) + ihdr:u32be(w) + ihdr:u32be(h) + ihdr:u8(8) + ihdr:u8(ct) + ihdr:u8(0) + ihdr:u8(0) + ihdr:u8(0) + chunk("IHDR", ihdr:finish()) + if frames then + local actl = Bytes.writer(8) + actl:u32be(#frames) + actl:u32be(loops) + chunk("acTL", actl:finish()) + end + if img.meta and img.meta.text then + for k, v in __iter(img.meta.text) do + local t = Bytes.writer() + t:string(k) + t:u8(0) + t:string(v) + chunk("tEXt", t:finish()) + end + end + if not frames then + chunk("IDAT", zdata(img)) + chunk("IEND", nil) + return out:finish(), nil + end + -- frame 1 is the default image when it covers the canvas with the same pixels; otherwise the default image is + -- written first, outside the animation + local f1 = frames[1] + local f1i = f1.image + local inAnim = f1i == img + or ((f1.x or 0) == 0 and (f1.y or 0) == 0 and f1i.width == w and f1i.height == h and buffer.len(f1i.pixels) >= w * h * 4 and buffer.readstring(f1i.pixels, 0, w * h * 4) == buffer.readstring(img.pixels, 0, w * h * 4)) + local seq = 0 + if not inAnim then + chunk("IDAT", zdata(img)) + end + for i, f in __iter(frames) do + local fi = f.image + local num, den = delayFraction(f.delay or 0) + local fc = Bytes.writer(26) + fc:u32be(seq) + fc:u32be(fi.width) + fc:u32be(fi.height) + fc:u32be(f.x or 0) + fc:u32be(f.y or 0) + fc:u16be(num) + fc:u16be(den) + fc:u8(DISPOSE_CODES[f.dispose or "none"]) + fc:u8(BLEND_CODES[f.blend or "source"]) + chunk("fcTL", fc:finish()) + seq =seq+ 1 + if i == 1 and inAnim then + chunk("IDAT", zdata(img)) + else + chunk("fdAT", zdata(fi), seq) + seq =seq+ 1 + end + end + chunk("IEND", nil) + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a +-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }. +function Png.composite(img) +if not validImage(img) then + return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image") + end + local frames, ferr = animationFrames(img, { apng = true }) + if not frames then + return nil, ferr + end + local w, h = img.width, img.height + local list = {} + for i, f in __iter(frames) do + list[i] = { image = f.image, x = f.x or 0, y = f.y or 0, dispose = f.dispose or "none", blend = f.blend or "source" } + end + local out = {} + for i, b in __iter(Apng.composite(w, h, list)) do + local im = Types.Image.new(w, h, "rgba8") + im.pixels = b + out[i] = im + end + return out, nil +end + +return Png +end +__FILES["image/png/Apng"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source / +-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the +-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle. +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Apng = {} + +local function div255(x) +return math.floor((x + 128) * 257 / 65536 +)end + +-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas +local function blend(canvas, cw, src, fw, fh, fx, fy, over) + for y = 0, fh - 1 do + local so = y * fw * 4 + local co = ((fy + y) * cw + fx) * 4 + if not over then + bcopy(canvas, co, src, so, fw * 4) + else + for x = 0, fw - 1 do + local s, c = so + x * 4, co + x * 4 + local fa = readu8(src, s + 3) + if fa == 255 then + writeu32(canvas, c, readu32(src, s)) + elseif fa ~= 0 then + local ba = readu8(canvas, c + 3) + local oa = fa + div255((255 - fa) * ba) + if ba == 255 then + for k = 0, 2 do + writeu8(canvas, c + k, div255(fa * readu8(src, s + k) + (255 - fa) * readu8(canvas, c + k))) + end + else + local den = 255 * oa + for k = 0, 2 do + writeu8(canvas, c + k, math.floor((255 * fa * readu8(src, s + k) + (255 - fa) * ba * readu8(canvas, c + k)) / den)) + end + end + writeu8(canvas, c + 3, oa) + end + end + end + end +end + +-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend }) +function Apng.composite(w, h, frames) +local canvas = bcreate(w * h * 4) + local saved = bcreate(w * h * 4) + local out= {} + for i, f in __iter(frames) do + local fi = f.image + local fw, fh = fi.width, fi.height + local dispose, over = f.dispose, f.blend == "over" + if i == 1 then + over = false -- the canvas starts transparent black: source and over differ only in hidden colour + if dispose == "previous" then + dispose = "background" + end + end + if dispose == "previous" then + bcopy(saved, 0, canvas, 0) + end + blend(canvas, w, fi.pixels, fw, fh, f.x, f.y, over) + local snap = bcreate(w * h * 4) + bcopy(snap, 0, canvas, 0) + out[i] = snap + if dispose == "background" then + for y = 0, fh - 1 do + bfill(canvas, ((f.y + y) * w + f.x) * 4, 0, fw * 4) + end + elseif dispose == "previous" then + bcopy(canvas, 0, saved, 0) + end + end + return out +end + +return Apng +end +__FILES["image/png/Decode"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +--!optimize 2 +-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the +-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes. +-- Absorbed from png-luau src/Png/Decode.luau (same author). +-- +-- The caller (init) has validated the header and checked that the data holds at least the expected number of +-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws. +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bcopy = buffer.copy + +local Decode = {} + +-- Adam7: x0, y0, dx, dy per pass +local PASSES = { + { 0, 0, 8, 8 }, + { 4, 0, 8, 8 }, + { 0, 4, 4, 8 }, + { 2, 0, 4, 4 }, + { 0, 2, 2, 4 }, + { 1, 0, 2, 2 }, + { 0, 1, 1, 2 }, +} +Decode.PASSES = PASSES + +local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 } +Decode.CHANNELS = CHANNELS + +-- bytes per row (without the filter byte) for a pass width +function Decode.rowBytes(pw, channels, depth) +return math.floor((pw * channels * depth + 7) / 8 +)end + +-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per +-- complete pixel (at least 1). Returns true, or false + the bad filter type. +local function unfilter(raw, p, ph, rb, bpp) +local stride = rb + 1 + for r = 0, ph - 1 do + local f = readu8(raw, p) + local cur = p + 1 + if f == 0 then + -- none + elseif f == 1 then + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + elseif f == 2 then + if r > 0 then + local i = cur + local e4 = cur + rb - 4 + while i <= e4 do + -- four bytes at once: add without carries between the byte lanes + local x, y = readu32(raw, i), readu32(raw, i - stride) + local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F) + writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080))) + i =i+ 4 + end + while i < cur + rb do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + i =i+ 1 + end + end + elseif f == 3 then + if r > 0 then + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - stride), 1)) + end + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp) + readu8(raw, i - stride), 1)) + end + else + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + rshift(readu8(raw, i - bpp), 1)) + end + end + elseif f == 4 then + if r > 0 then + -- the first pixel: a = c = 0, so Paeth picks b + for i = cur, cur + bpp - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - stride)) + end + for i = cur + bpp, cur + rb - 1 do + local a = readu8(raw, i - bpp) + local b = readu8(raw, i - stride) + local c = readu8(raw, i - stride - bpp) + local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + local v + if pa <= pb and pa <= pc then + v = a + elseif pb <= pc then + v = b + else + v = c + end + writeu8(raw, i, readu8(raw, i) + v) + end + else + -- no previous row: Paeth is sub + for i = cur + bpp, cur + rb - 1 do + writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp)) + end + end + else + return false, f + end + p =p+ stride + end + return true, 0 +end + +-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes. +-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none), +-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth. +local function convert(raw, ro, pw, out, oo, ostep, ct, depth, pal, tr) + if ct == 6 then + if depth == 8 then + if ostep == 4 then + bcopy(out, oo, raw, ro, pw * 4) + else + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(raw, ro + x * 4)) + end + end + else + for x = 0, pw - 1 do + local s = ro + x * 8 + local o = oo + x * ostep + writeu8(out, o, readu8(raw, s)) + writeu8(out, o + 1, readu8(raw, s + 2)) + writeu8(out, o + 2, readu8(raw, s + 4)) + writeu8(out, o + 3, readu8(raw, s + 6)) + end + end + elseif ct == 2 then + if depth == 8 then + for x = 0, pw - 1 do + local s = ro + x * 3 + local r, g, b = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, r + g * 256 + b * 65536 + a * 16777216) + end + else + for x = 0, pw - 1 do + local s = ro + x * 6 + local r = readu8(raw, s) * 256 + readu8(raw, s + 1) + local g = readu8(raw, s + 2) * 256 + readu8(raw, s + 3) + local b = readu8(raw, s + 4) * 256 + readu8(raw, s + 5) + local a = 255 + if tr >= 0 and r * 4294967296 + g * 65536 + b == tr then + a = 0 + end + writeu32(out, oo + x * ostep, rshift(r, 8) + band(g, 0xFF00) + lshift(rshift(b, 8), 16) + a * 16777216) + end + end + elseif ct == 3 then + if depth == 8 then + for x = 0, pw - 1 do + writeu32(out, oo + x * ostep, readu32(pal, readu8(raw, ro + x) * 4)) + end + else + local per = math.floor(8 / depth +) local mask = lshift(1, depth) - 1 + for x = 0, pw - 1 do + local byte = readu8(raw, ro + math.floor(x / per)) + local idx = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + writeu32(out, oo + x * ostep, readu32(pal, idx * 4)) + end + end + elseif ct == 0 then + if depth == 8 then + for x = 0, pw - 1 do + local v = readu8(raw, ro + x) + local a = v == tr and 0 or 255 + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + elseif depth == 16 then + for x = 0, pw - 1 do + local hi = readu8(raw, ro + x * 2) + local v = hi * 256 + readu8(raw, ro + x * 2 + 1) + local a = v == tr and 0 or 255 + writeu32(out, oo + x * ostep, hi * 0x10101 + a * 16777216) + end + else + local per = math.floor(8 / depth +) local mask = lshift(1, depth) - 1 + local scale = math.floor(255 / mask +) for x = 0, pw - 1 do + local byte = readu8(raw, ro + math.floor(x / per)) + local v = band(rshift(byte, 8 - depth - (x % per) * depth), mask) + local a = v == tr and 0 or 255 + writeu32(out, oo + x * ostep, v * scale * 0x10101 + a * 16777216) + end + end + else -- ct == 4: grey + alpha + if depth == 8 then + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 2), readu8(raw, ro + x * 2 + 1) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + else + for x = 0, pw - 1 do + local v, a = readu8(raw, ro + x * 4), readu8(raw, ro + x * 4 + 2) + writeu32(out, oo + x * ostep, v * 0x10101 + a * 16777216) + end + end + end +end + +-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8). +-- Returns true, or false + message. +function Decode.run(raw, w, h, depth, ct, interlace, pal, tr, out) +local channels = CHANNELS[ct] + local bpp = math.max(1, math.floor((channels * depth) / 8)) + local p = 0 + if interlace == 0 then + local rb = Decode.rowBytes(w, channels, depth) + local ok, f = unfilter(raw, 0, h, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for y = 0, h - 1 do + convert(raw, y * (rb + 1) + 1, w, out, y * w * 4, 4, ct, depth, pal, tr) + end + return true, nil + end + for _, pass in __iter(PASSES) do + local x0, y0, dx, dy = pass[1], pass[2], pass[3], pass[4] + local pw = (w > x0 and{(math.floor((w - x0 + dx - 1) / dx ))}or{0 +})[1] local ph = (h > y0 and{(math.floor((h - y0 + dy - 1) / dy ))}or{0 +})[1] if pw > 0 and ph > 0 then + local rb = Decode.rowBytes(pw, channels, depth) + local ok, f = unfilter(raw, p, ph, rb, bpp) + if not ok then + return false, "bad filter type " .. f + end + for r = 0, ph - 1 do + local y = y0 + r * dy + convert(raw, p + r * (rb + 1) + 1, pw, out, (y * w + x0) * 4, dx * 4, ct, depth, pal, tr) + end + p =p+ ph * (rb + 1) + end + end + return true, nil +end + +return Decode +end +__FILES["image/png/Encode"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and +-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute +-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image. +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy = buffer.create, buffer.copy + +local Encode = {} + +local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 } + +-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray" +function Encode.pickColorType(px, w, h) +local opaque, gray = true, true + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b, a = readu8(px, o), readu8(px, o + 1), readu8(px, o + 2), readu8(px, o + 3) + if a ~= 255 then + opaque = false + end + if r ~= g or g ~= b then + gray = false + end + if not opaque and not gray then + return "rgba" + end + end + if gray then + return opaque and"gray" or"graya" + end + return "rgb" +end + +-- convert rgba8 to the colour type's packed rows (no filter bytes) +local function pack(px, w, h, ct) +local ch = CHANNELS[ct] + if ch == 4 then + return px + end + local out = bcreate(w * h * ch) + local n = w * h + if ct == 2 then + for i = 0, n - 1 do + bcopy(out, i * 3, px, i * 4, 3) + end + elseif ct == 0 then + for i = 0, n - 1 do + writeu8(out, i, readu8(px, i * 4)) + end + else -- graya + for i = 0, n - 1 do + writeu8(out, i * 2, readu8(px, i * 4)) + writeu8(out, i * 2 + 1, readu8(px, i * 4 + 3)) + end + end + return out +end + +local function paeth(a, b, c) +local pa = math.abs(b - c) + local pb = math.abs(a - c) + local pc = math.abs(a + b - c - c) + if pa <= pb and pa <= pc then + return a + elseif pb <= pc then + return b + end + return c +end + +-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first); +-- the arithmetic is inlined: this runs for every byte +local function costs(src, s, rb, bpp, first) +local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0 + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = (i >= bpp and{(readu8(src, s + i - bpp) )}or{0 +})[1] local b, c = 0, 0 + if not first then + b = readu8(src, p + i) + if i >= bpp then + c = readu8(src, p + i - bpp) + end + end + local d = (x < 128 and{x }or{(256 - x +)})[1] c0 =c0+ d + d = (x - a) % 256 + c1 =c1+ (d < 128 and{d }or{(256 - d +)})[1] d = (x - b) % 256 + c2 =c2+ (d < 128 and{d }or{(256 - d +)})[1] d = (x - math.floor((a + b) / 2)) % 256 + c3 =c3+ (d < 128 and{d }or{(256 - d +)})[1] local pa, pb, pc = math.abs(b - c), math.abs(a - c), math.abs(a + b - c - c) + local pr = (pa <= pb and pa <= pc and{a }or{(pb <= pc and{b }or{c +})[1]})[1] d = (x - pr) % 256 + c4 =c4+ (d < 128 and{d }or{(256 - d +)})[1] end + return c0, c1, c2, c3, c4 +end + +-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f) +local function apply(src, s, rb, bpp, first, f, out, o) + writeu8(out, o, f) + o =o+ 1 + if f == 0 or (f == 2 and first) then + bcopy(out, o, src, s, rb) + return + end + local p = s - rb + for i = 0, rb - 1 do + local x = readu8(src, s + i) + local a = (i >= bpp and{(readu8(src, s + i - bpp) )}or{0 +})[1] local pred + if f == 1 then + pred = a + elseif f == 2 then + pred = readu8(src, p + i) + elseif f == 3 then + pred = math.floor((a + (first and 0 or readu8(src, p + i))) / 2 +) elseif first then + pred = a + else + local c = (i >= bpp and{(readu8(src, p + i - bpp) )}or{0 +})[1] pred = paeth(a, readu8(src, p + i), c) + end + writeu8(out, o + i, x - pred) + end +end + +-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of +-- |signed residuals| (the libpng heuristic) +function Encode.filter(px, w, h, ct) +local ch = CHANNELS[ct] + local src = pack(px, w, h, ct) + local rb = w * ch + local out = bcreate(h * (rb + 1)) + for y = 0, h - 1 do + local s = y * rb + local first = y == 0 + local c0, c1, c2, c3, c4 = costs(src, s, rb, ch, first) + local best, bc = 0, c0 + if c1 < bc then + best, bc = 1, c1 + end + if c2 < bc then + best, bc = 2, c2 + end + if c3 < bc then + best, bc = 3, c3 + end + if c4 < bc then + best = 4 + end + apply(src, s, rb, ch, first, best, out, y * (rb + 1)) + end + return out +end + +return Encode +end +__FILES["image/pnm"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5), +-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any +-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows). +-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout +-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is +-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel +-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image. +-- Not supported: multi-image streams (the first image is read), PAM depths above 4. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/pnm/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Pnm = { + name = "pnm", + category = "image", + extensions = { "pnm", "pbm", "pgm", "ppm", "pam", "pfm" }, + mime = { "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-portable-arbitrarymap", "image/x-portable-floatmap" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 1, 8, 16, 32 }, float = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + +local FMT_CODE= { rgba8 = 0, rgb8 = 1, gray8 = 2, graya8 = 3, rgba16 = 4, gray16 = 5, rgbaf32 = 6 } +local BPP= { rgba8 = 4, rgb8 = 3, gray8 = 1, graya8 = 2, rgba16 = 8, gray16 = 2, rgbaf32 = 16 } +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pnm.sniff(r) +if r:remaining() < 3 then + return 0 + end + local a, b, c = r:peekU8(0), r:peekU8(1), r:peekU8(2) + if a ~= 80 then -- 'P' + return 0 + end + local ws = c == 32 or (c >= 9 and c <= 13) + if b >= 49 and b <= 55 and ws then -- P1..P7 + return 0.9 + end + if (b == 70 or b == 102) and ws then -- PF / Pf + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function isSpace(c) +return c == 32 or (c >= 9 and c <= 13) +end + +-- the next header token from p: token, position after it (nil at the end) +local function token(b, p, limit) +while p < limit do + local c = readu8(b, p) + if c == 35 then + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p =p+ 1 + end + elseif isSpace(c) then + p =p+ 1 + else + break + end + end + local s = p + while p < limit and not isSpace(readu8(b, p)) and readu8(b, p) ~= 35 do + p =p+ 1 + end + if p == s then + return nil, p + end + return buffer.readstring(b, s, p - s), p +end + +local function int(s) +if s == nil or not string.match(s, "^%d+$") or #s > 9 then + return nil + end + return tonumber(s) +end + +function Pnm.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local native = opts and opts.native or false + local b, limit = r.buf, r.limit + if r.limit - r.base < 3 or readu8(b, r.base) ~= 80 then + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local kind = string.char(readu8(b, r.base + 1)) + local p = r.base + 2 + local w, h, maxval, ch, mode +local bits = false -- PBM: 1 = black + local bw = false -- PAM BLACKANDWHITE: 1 = white + local tupl= nil + local scale= nil + if kind == "1" or kind == "2" or kind == "3" or kind == "4" or kind == "5" or kind == "6" or kind == "F" or kind == "f" then + local t1, t2, t3 + t1, p = token(b, p, limit) + t2, p = token(b, p, limit) + w, h = int(t1), int(t2) + if kind == "1" or kind == "4" then + maxval = 1 + elseif kind == "F" or kind == "f" then + t3, p = token(b, p, limit) + scale = (t3 and{(tonumber(t3) )}or{nil +})[1] if scale == nil or scale == 0 then + return nil, Err.new(Err.CORRUPT, "bad PFM scale", p) + end + maxval = 1 + else + t3, p = token(b, p, limit) + maxval = int(t3) + end + if w == nil or h == nil or maxval == nil then + return nil, (p >= limit and{(Err.new(Err.TRUNCATED, "header ends early", p) )}or{(Err.new(Err.CORRUPT, "bad header", p) +)})[1] end + if kind ~= "1" and kind ~= "2" and kind ~= "3" then + p =p+ 1 -- exactly one whitespace byte before binary data + end + ch = (kind == "3" or kind == "6" or kind == "F" )and 3 or 1 + bits = kind == "1" or kind == "4" + mode = kind == "1" and 4 or((kind == "2" or kind == "3" )and 3 or(kind == "4" and 0 or((maxval ) > 255 and 2 or 1 +))) elseif kind == "7" then + local depth +while true do + local key + key, p = token(b, p, limit) + if key == nil then + return nil, Err.new(Err.TRUNCATED, "PAM header ends early", p) + end + if key == "ENDHDR" then + break + end + local v + v, p = token(b, p, limit) + if key == "WIDTH" then + w = int(v) + elseif key == "HEIGHT" then + h = int(v) + elseif key == "DEPTH" then + depth = int(v) + elseif key == "MAXVAL" then + maxval = int(v) + elseif key == "TUPLTYPE" then + tupl = v + -- the rest of the line belongs to the value + while p < limit and readu8(b, p) ~= 10 do + p =p+ 1 + end + end + end + -- ENDHDR ends with a newline + while p < limit and readu8(b, p) ~= 10 do + p =p+ 1 + end + p =p+ 1 + if w == nil or h == nil or depth == nil or maxval == nil then + return nil, Err.new(Err.CORRUPT, "PAM header misses WIDTH / HEIGHT / DEPTH / MAXVAL", p) + end + if (depth ) < 1 or (depth ) > 4 then + return nil, Err.new(Err.UNSUPPORTED, "PAM depth " .. (depth )) + end + ch = depth +bw = tupl ~= nil and string.sub(tupl , 1, 13) == "BLACKANDWHITE" + mode = (maxval ) > 255 and 2 or 1 + else + return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base) + end + local w, h, maxval = w , h , maxval +if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval)) + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local n = w * h + local img +local colorType = ch == 1 and"gray" or(ch == 2 and"graya" or(ch == 3 and"rgb" or"rgba" +)) if scale then + local f = Types.Image.new(w, h, "rgbaf32") + local ok, e = Codec.readFloats(b, p, limit, w, h, ch, (scale ) < 0, f.pixels) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + img = f + if not native then + local o = Types.Image.new(w, h, "rgba8") + for i = 0, n * 4 - 1 do + local v = buffer.readf32(f.pixels, i * 4) + buffer.writeu8(o.pixels, i, v ~= v and 0 or math.floor(math.clamp(v, 0, 1) * 255 + 0.5)) + end + img = o + end + img.meta.source = { format = "pnm", type = ch == 3 and"pfm" or"pfm-gray", bitDepth = 32, colorType = colorType, scale = math.abs(scale ), byteOrder = (scale ) < 0 and"little" or"big" } + return img, nil + end + local samples = buffer.create(n * ch * 2) + local ok, e + if mode == 0 then + ok, e = Codec.readBits(b, p, limit, w, h, samples) + else + ok, e = Codec.readSamples(b, p, limit, n * ch, mode, samples) + end + if not ok then + return nil, Err.new((e == "truncated" and{Err.TRUNCATED }or{Err.CORRUPT})[1], tostring(e)) + end + local fmt= "rgba8" + if native then + local wide = maxval > 255 + if bits or bw or ch == 1 then + fmt = wide and"gray16" or"gray8" + elseif ch == 2 then + fmt = wide and"rgba16" or"graya8" + elseif ch == 3 then + fmt = wide and"rgba16" or"rgb8" + else + fmt = wide and"rgba16" or"rgba8" + end + end + img = Types.Image.new(w, h, fmt ) + Codec.pack(samples, n, ch, maxval, bits, FMT_CODE[fmt], img.pixels) + local typ = kind == "7" and"pam" or(bits and"pbm" or(ch == 1 and"pgm" or"ppm" +)) img.meta.source = { + format = "pnm", + type = typ, + ascii = mode == 3 or mode == 4, + bitDepth = (bits or bw )and 1 or(maxval > 255 and 16 or 8), + maxval = maxval, + colorType = (bits or bw )and"bilevel" or colorType, + tupltype = tupl, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local SUBTYPES = { pbm = true, pgm = true, ppm = true, pam = true, pfm = true } + +function Pnm.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local fc = FMT_CODE[img.format] + if fc == nil then + return nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h= img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * BPP[img.format] then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local o= opts or {} + local n = w * h + local isGray = img.format == "gray8" or img.format == "gray16" or img.format == "graya8" + local hasAlpha = img.format == "graya8" or img.format == "rgba16" or img.format == "rgba8" or img.format == "rgbaf32" + if hasAlpha and img.format ~= "graya8" then + -- an alpha channel that is fully opaque does not count + local opaque = true + for i = 0, n - 1 do + local a + if img.format == "rgba8" then + a = buffer.readu8(img.pixels, i * 4 + 3) == 255 + elseif img.format == "rgba16" then + a = buffer.readu16(img.pixels, i * 8 + 6) == 65535 + else + a = buffer.readf32(img.pixels, i * 16 + 12) == 1 + end + if not a then + opaque = false + break + end + end + hasAlpha = not opaque + end + local sub = (type(o.format) == "string" and{(string.lower(o.format) )}or{nil +})[1] if not (sub and SUBTYPES[sub]) then + if img.format == "rgbaf32" and not hasAlpha then + sub = "pfm" + elseif hasAlpha then + sub = "pam" + elseif isGray then + sub = "pgm" + else + sub = "ppm" + end + end + local ascii = o.ascii == true + local wideSrc = img.format == "gray16" or img.format == "rgba16" or img.format == "rgbaf32" + local maxval= o.maxval or (wideSrc and 65535 or 255) + if type(maxval) ~= "number" or maxval < 1 or maxval > 65535 or maxval % 1 ~= 0 then + return nil, Err.new(Err.ARG, "maxval must be 1..65535") + end + local out +local op = 0 + local function header(s, extra) + out = buffer.create(#s + extra) + buffer.writestring(out, 0, s) + op = #s + end + if sub == "pfm" then + local ch = isGray and 1 or 3 + local src = img + if img.format ~= "rgbaf32" then + local s = Codec.extract(img.pixels, fc, n, 4, true) + src = Types.Image.new(w, h, "rgbaf32") + for i = 0, n * 4 - 1 do + buffer.writef32(src.pixels, i * 4, buffer.readu16(s, i * 2) / 65535) + end + end + header(string.format("%s\n%d %d\n-1.0\n", ch == 3 and"PF" or"Pf", w, h), n * ch * 4) + op = Codec.writeFloats(src.pixels, w, h, ch, out, op) + return out, nil + end + local ch = (sub == "pbm" or sub == "pgm" )and 1 or(sub == "ppm" and 3 or(isGray and{(hasAlpha and 2 or 1) }or{(hasAlpha and 4 or 3) +})[1]) if sub == "pbm" then + local thr = o.threshold or 128 + local s = Codec.extract(img.pixels, fc, n, 1, false) + if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("P1\n%d %d\n", w, h) + for y = 0, h - 1 do + local row = table.create(w) + for x = 0, w - 1 do + row[x + 1] = buffer.readu16(s, (y * w + x) * 2) < thr and"1" or"0" + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("P4\n%d %d\n", w, h), (math.floor((w + 7) / 8)) * h) + op = Codec.writeBits(s, w, h, thr, out, op) + return out, nil + end + local wide = maxval > 255 + local s = Codec.extract(img.pixels, fc, n, ch, wide) + if maxval ~= 255 and maxval ~= 65535 then + local top = wide and 65535 or 255 + for i = 0, n * ch - 1 do + buffer.writeu16(s, i * 2, math.floor((buffer.readu16(s, i * 2) * maxval + math.floor(top / 2)) / top)) + end + end + local magic + if sub == "pam" then + local tt = ch == 1 and"GRAYSCALE" or(ch == 2 and"GRAYSCALE_ALPHA" or(ch == 3 and"RGB" or"RGB_ALPHA" +)) header(string.format("P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", w, h, ch, maxval, tt), n * ch * (wide and 2 or 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil + end + magic = (sub == "pgm" and{(ascii and"P2" or"P5") }or{(ascii and"P3" or"P6") +})[1] if ascii then + local parts = table.create(h + 1) + parts[1] = string.format("%s\n%d %d\n%d\n", magic, w, h, maxval) + local rowLen = w * ch + for y = 0, h - 1 do + local row = table.create(rowLen) + for i = 0, rowLen - 1 do + row[i + 1] = tostring(buffer.readu16(s, (y * rowLen + i) * 2)) + end + parts[y + 2] = table.concat(row, " ") .. "\n" + end + return buffer.fromstring(table.concat(parts)), nil + end + header(string.format("%s\n%d %d\n%d\n", magic, w, h, maxval), n * ch * (wide and 2 or 1)) + op = Codec.writeSamples(s, n * ch, wide, out, op) + return out, nil +end + +return Pnm +end +__FILES["image/pnm/Codec"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm, +-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM +-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling. +-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked. +local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16 +local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32 +local byteswap = bit32.byteswap + +local Codec = {} + +-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each). +-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits) +function Codec.readSamples(b, p, limit, count, mode, out) +if mode == 1 then + if p + count > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i)) + end + return true, nil + elseif mode == 2 then + if p + count * 2 > limit then + return false, "truncated" + end + for i = 0, count - 1 do + writeu16(out, i * 2, readu8(b, p + i * 2) * 256 + readu8(b, p + i * 2 + 1)) + end + return true, nil + end + local i = 0 + while i < count do + -- skip whitespace and comments + while p < limit do + local c = readu8(b, p) + if c == 35 then -- '#' + while p < limit and readu8(b, p) ~= 10 and readu8(b, p) ~= 13 do + p =p+ 1 + end + elseif c == 32 or (c >= 9 and c <= 13) then + p =p+ 1 + else + break + end + end + if p >= limit then + return false, "truncated" + end + local c = readu8(b, p) + if c < 48 or c > 57 then + return false, "bad ASCII sample" + end + if mode == 4 then + writeu16(out, i * 2, c - 48) + p =p+ 1 + else + local v = 0 + while p < limit do + local d = readu8(b, p) + if d < 48 or d > 57 then + break + end + v = math.min(v * 10 + d - 48, 65535) + p =p+ 1 + end + writeu16(out, i * 2, v) + end + i =i+ 1 + end + return true, nil +end + +-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values +function Codec.readBits(b, p, limit, w, h, out) +local rowBytes = math.floor((w + 7) / 8 +) if p + rowBytes * h > limit then + return false, "truncated" + end + for y = 0, h - 1 do + local r = p + y * rowBytes + for x = 0, w - 1 do + local byte = readu8(b, r + math.floor(x / 8)) + writeu16(out, (y * w + x) * 2, (math.floor(byte / 2 ^ (7 - x % 8))) % 2) + end + end + return true, nil +end + +-- format codes for pack / extract +Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6 + +-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for +-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval)) +function Codec.pack(s, n, ch, maxval, invert, fmt, dst) + local wide = fmt == 4 or fmt == 5 + local top = wide and 65535 or 255 + local half = math.floor(maxval / 2 +) local function get(i) +local v = math.min(readu16(s, i * 2), maxval) + if invert then + v = maxval - v + end + if maxval == top then + return v + end + return math.floor((v * top + half) / maxval +) end + for i = 0, n - 1 do + local q = i * ch + local r, g, b, a + if ch == 1 then + r = get(q) + g, b, a = r, r, top + elseif ch == 2 then + r = get(q) + g, b, a = r, r, get(q + 1) + elseif ch == 3 then + r, g, b, a = get(q), get(q + 1), get(q + 2), top + else + r, g, b, a = get(q), get(q + 1), get(q + 2), get(q + 3) + end + if fmt == 0 then + writeu32(dst, i * 4, r + g * 256 + b * 65536 + (a ) * 16777216) + elseif fmt == 1 then + writeu8(dst, i * 3, r) + writeu8(dst, i * 3 + 1, g) + writeu8(dst, i * 3 + 2, b) + elseif fmt == 2 then + writeu8(dst, i, r) + elseif fmt == 3 then + writeu8(dst, i * 2, r) + writeu8(dst, i * 2 + 1, a ) + elseif fmt == 4 then + writeu16(dst, i * 8, r) + writeu16(dst, i * 8 + 2, g) + writeu16(dst, i * 8 + 4, b) + writeu16(dst, i * 8 + 6, a ) + elseif fmt == 5 then + writeu16(dst, i * 2, r) + end + end +end + +-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst +function Codec.readFloats(b, p, limit, w, h, ch, le, dst) +if p + w * h * ch * 4 > limit then + return false, "truncated" + end + local tmp = buffer.create(4) + for y = 0, h - 1 do + local row = p + (h - 1 - y) * w * ch * 4 + for x = 0, w - 1 do + local o = (y * w + x) * 16 + for c = 0, ch - 1 do + local v + if le then + v = readf32(b, row + (x * ch + c) * 4) + else + writeu32(tmp, 0, byteswap(readu32(b, row + (x * ch + c) * 4))) + v = readf32(tmp, 0) + end + writef32(dst, o + c * 4, v) + end + if ch == 1 then + local v = readf32(dst, o) + writef32(dst, o + 4, v) + writef32(dst, o + 8, v) + end + writef32(dst, o + 12, 1) + end + end + return true, nil +end + +local function f(v) +if v ~= v then + return 0 + end + return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5) +end + +-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for +-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide +function Codec.extract(px, fmt, n, ch, wide) +local out = buffer.create(n * ch * 2) + local srcWide = fmt == 4 or fmt == 5 + local isGray = fmt == 2 or fmt == 3 or fmt == 5 + for i = 0, n - 1 do + local r, g, b, a + if fmt == 0 then + r, g, b, a = readu8(px, i * 4), readu8(px, i * 4 + 1), readu8(px, i * 4 + 2), readu8(px, i * 4 + 3) + elseif fmt == 1 then + r, g, b, a = readu8(px, i * 3), readu8(px, i * 3 + 1), readu8(px, i * 3 + 2), 255 + elseif fmt == 2 then + r = readu8(px, i) + g, b, a = r, r, 255 + elseif fmt == 3 then + r, a = readu8(px, i * 2), readu8(px, i * 2 + 1) + g, b = r, r + elseif fmt == 4 then + r, g, b, a = readu16(px, i * 8), readu16(px, i * 8 + 2), readu16(px, i * 8 + 4), readu16(px, i * 8 + 6) + elseif fmt == 5 then + r = readu16(px, i * 2) + g, b, a = r, r, 65535 + else + r, g, b, a = f(readf32(px, i * 16)), f(readf32(px, i * 16 + 4)), f(readf32(px, i * 16 + 8)), f(readf32(px, i * 16 + 12)) + end + local w16 = srcWide or fmt == 6 + local gray = r + if ch <= 2 and not isGray then + gray = math.floor((r * 299 + g * 587 + b * 114) / 1000 +) end + local vals = ch == 1 and 1 or(ch == 2 and 2 or ch +) for c = 0, vals - 1 do + local v + if ch <= 2 then + v = (c == 0 and{gray }or{a })[1] +else + v = (c == 0 and{r }or{(c == 1 and{g }or{(c == 2 and{b }or{a })[1]})[1]})[1] +end + if wide and not w16 then + v =v* 257 + elseif w16 and not wide then + v = math.floor((v * 255 + 32767) / 65535 +) end + writeu16(out, (i * ch + c) * 2, v) + end + end + return out +end + +-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian) +function Codec.writeSamples(s, count, wide, out, o) +if wide then + for i = 0, count - 1 do + local v = readu16(s, i * 2) + writeu8(out, o, math.floor(v / 256)) + writeu8(out, o + 1, v % 256) + o =o+ 2 + end + else + for i = 0, count - 1 do + writeu8(out, o, readu16(s, i * 2)) + o =o+ 1 + end + end + return o +end + +-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1) +function Codec.writeBits(s, w, h, threshold, out, o) +for y = 0, h - 1 do + local acc, nb = 0, 0 + for x = 0, w - 1 do + acc = acc * 2 + (readu16(s, (y * w + x) * 2) < threshold and 1 or 0) + nb =nb+ 1 + if nb == 8 then + writeu8(out, o, acc) + o =o+ 1 + acc, nb = 0, 0 + end + end + if nb > 0 then + writeu8(out, o, acc * 2 ^ (8 - nb)) + o =o+ 1 + end + end + return o +end + +-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM +-- rows, bottom-to-top +function Codec.writeFloats(px, w, h, ch, out, o) +for y = h - 1, 0, -1 do + for x = 0, w - 1 do + local q = (y * w + x) * 16 + for c = 0, ch - 1 do + writef32(out, o, readf32(px, q + c * 4)) + o =o+ 4 + end + end + end + return o +end + +return Codec +end +__FILES["image/qoi"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec. +-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files); +-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag. +-- Not supported: nothing in the spec is left out. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/qoi/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Qoi = { + name = "qoi", + category = "image", + extensions = { "qoi" }, + mime = { "image/qoi", "image/x-qoi" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function Qoi.sniff(r) +return r:peek(4) == "qoif" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Qoi.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local magic = r:string(4) + local w, h = r:u32be(), r:u32be() + local channels, cs = r:u8(), r:u8() + if r.err then + return nil, r.err + end + if magic ~= "qoif" then + return nil, Err.new(Err.CORRUPT, "bad magic", r.base) + end + if w == 0 or h == 0 or (channels ~= 3 and channels ~= 4) or cs > 1 then + return nil, Err.new(Err.CORRUPT, "bad header", r.base + 4) + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local img = Types.Image.new(w, h, "rgba8") + local ok, e = Codec.decode(r.buf, r.pos, r.limit, img.pixels, w * h) + if not ok then + return nil, Err.new(Err.TRUNCATED, tostring(e)) + end + if opts and opts.native and channels == 3 then + local rgb = Types.Image.new(w, h, "rgb8") + local src, dst = img.pixels, rgb.pixels + for i = 0, w * h - 1 do + buffer.writeu16(dst, i * 3, buffer.readu16(src, i * 4)) + buffer.writeu8(dst, i * 3 + 2, buffer.readu8(src, i * 4 + 2)) + end + img = rgb + end + img.meta.source = { format = "qoi", bitDepth = 8, colorType = channels == 4 and"rgba" or"rgb", channels = channels, colorSpace = cs == 1 and"linear" or"srgb" } + if cs == 1 then + img.meta.colorSpace = "linear" + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Qoi.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgba8" and img.format ~= "rgb8") then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgb8 Image") + end + local w, h = img.width, img.height + local bpp = img.format == "rgba8" and 4 or 3 + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * bpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local channels = opts and opts.channels + if channels == nil then + channels = 3 + if bpp == 4 then + local px = img.pixels + for i = 0, w * h - 1 do + if buffer.readu8(px, i * 4 + 3) ~= 255 then + channels = 4 + break + end + end + end + elseif channels ~= 3 and channels ~= 4 then + return nil, Err.new(Err.ARG, "channels must be 3 or 4") + end + local linear = opts and opts.linear + if linear == nil then + local src = img.meta and img.meta.source + linear = (type(src) == "table" and src.colorSpace == "linear") or (img.meta and img.meta.colorSpace == "linear") or false + end + local n = w * h + local out = buffer.create(14 + n * (bpp + 1) + 8) + buffer.writestring(out, 0, "qoif") + buffer.writeu32(out, 4, bit32.byteswap(w)) + buffer.writeu32(out, 8, bit32.byteswap(h)) + buffer.writeu8(out, 12, channels ) + buffer.writeu8(out, 13, linear and 1 or 0) + local o = Codec.encode(img.pixels, n, bpp, out, 14) + buffer.writestring(out, o, "\0\0\0\0\0\0\0\1") + o =o+ 8 + local res = buffer.create(o) + buffer.copy(res, 0, out, 0, o) + return res, nil +end + +return Qoi +end +__FILES["image/qoi/Codec"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org). +-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read +-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full. +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +local index = buffer.create(256) + +-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out) +function Codec.decode(b, p, limit, out, n) +buffer.fill(index, 0, 0, 256) + local r, g, bl, a = 0, 0, 0, 255 + local o = 0 + local stop = n * 4 + while o < stop do + if p >= limit then + return false, "truncated" + end + local op = readu8(b, p) + p =p+ 1 + if op == 0xFE then + if p + 3 > limit then + return false, "truncated" + end + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) + p =p+ 3 + elseif op == 0xFF then + if p + 4 > limit then + return false, "truncated" + end + r = readu8(b, p) + g = readu8(b, p + 1) + bl = readu8(b, p + 2) + a = readu8(b, p + 3) + p =p+ 4 + else + local tag = math.floor(op / 64 +) if tag == 0 then + local q = op * 4 + r = readu8(index, q) + g = readu8(index, q + 1) + bl = readu8(index, q + 2) + a = readu8(index, q + 3) + elseif tag == 1 then + r = (r + (math.floor(op / 16)) % 4 - 2) % 256 + g = (g + (math.floor(op / 4)) % 4 - 2) % 256 + bl = (bl + op % 4 - 2) % 256 + elseif tag == 2 then + if p >= limit then + return false, "truncated" + end + local d2 = readu8(b, p) + p =p+ 1 + local dg = op % 64 - 32 + g = (g + dg) % 256 + r = (r + dg + math.floor(d2 / 16 )- 8) % 256 + bl = (bl + dg + d2 % 16 - 8) % 256 + else + local run = op % 64 -- 1..62 more copies of the previous pixel (63 / 64 are RGB / RGBA) + local v = r + g * 256 + bl * 65536 + a * 16777216 + local e = math.min(o + run * 4, stop - 4) + while o < e do + writeu32(out, o, v) + o =o+ 4 + end + end + end + writeu32(out, o, r + g * 256 + bl * 65536 + a * 16777216) + o =o+ 4 + local h = ((r * 3 + g * 5 + bl * 7 + a * 11) % 64) * 4 + writeu8(index, h, r) + writeu8(index, h + 1, g) + writeu8(index, h + 2, bl) + writeu8(index, h + 3, a) + end + return true, nil +end + +-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes +function Codec.encode(px, n, bpp, out, o) +buffer.fill(index, 0, 0, 256) + local pr, pg, pb, pa = 0, 0, 0, 255 + local run = 0 + local hasA = bpp == 4 + for i = 0, n - 1 do + local q = i * bpp + local r, g, b = readu8(px, q), readu8(px, q + 1), readu8(px, q + 2) + local a = (hasA and{(readu8(px, q + 3) )}or{255 +})[1] if r == pr and g == pg and b == pb and a == pa then + run =run+ 1 + if run == 62 or i == n - 1 then + writeu8(out, o, 0xC0 + run - 1) + o =o+ 1 + run = 0 + end + else + if run > 0 then + writeu8(out, o, 0xC0 + run - 1) + o =o+ 1 + run = 0 + end + local h = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + local hq = h * 4 + if readu8(index, hq) == r and readu8(index, hq + 1) == g and readu8(index, hq + 2) == b and readu8(index, hq + 3) == a then + writeu8(out, o, h) + o =o+ 1 + else + writeu8(index, hq, r) + writeu8(index, hq + 1, g) + writeu8(index, hq + 2, b) + writeu8(index, hq + 3, a) + if a == pa then + local dr = (r - pr + 128) % 256 - 128 + local dg = (g - pg + 128) % 256 - 128 + local db = (b - pb + 128) % 256 - 128 + local dgr, dgb = dr - dg, db - dg + if dr >= -2 and dr <= 1 and dg >= -2 and dg <= 1 and db >= -2 and db <= 1 then + writeu8(out, o, 0x40 + (dr + 2) * 16 + (dg + 2) * 4 + db + 2) + o =o+ 1 + elseif dg >= -32 and dg <= 31 and dgr >= -8 and dgr <= 7 and dgb >= -8 and dgb <= 7 then + writeu8(out, o, 0x80 + dg + 32) + writeu8(out, o + 1, (dgr + 8) * 16 + dgb + 8) + o =o+ 2 + else + writeu8(out, o, 0xFE) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + o =o+ 4 + end + else + writeu8(out, o, 0xFF) + writeu8(out, o + 1, r) + writeu8(out, o + 2, g) + writeu8(out, o + 3, b) + writeu8(out, o + 4, a) + o =o+ 5 + end + end + pr, pg, pb, pa = r, g, b, a + end + end + return o +end + +return Codec +end +__FILES["image/sgi"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" +-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) +-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 +-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is +-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / +-- colour-map files (colormap field 1..3: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Sgi = { + name = "sgi", + category = "image", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, +} +-- ------------------------------------------------------------------------------------------------ types + + + + + + + + + + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local function be16(b, o) +return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end +local function be32(b, o) +return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sgi.sniff(r) +if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then + return 0 + end + local st, bpc = r:peekU8(2), r:peekU8(3) + return st <= 1 and (bpc == 1 or bpc == 2) and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sgi.decode(r, opts) +local b, o, limit = r.buf, r.base, r.limit + if limit - o < 512 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if be16(b, o) ~= 474 then + return nil, Err.new(Err.CORRUPT, "not an SGI image", o) + end + local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4) + local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10) + if dim == 1 then + h, z = 1, 1 + elseif dim == 2 then + z = 1 + end + if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then + return nil, Err.new(Err.CORRUPT, "bad header", o + 2) + end + if z > 4 then + return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10) + end + local cmap = be32(b, o + 104) + if cmap ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel planes as 16-bit samples (8-bit values scaled * 257) + local plane = buffer.create(w * h * z * 2) + local truncated = false + local function put(c, row, x, v) + buffer.writeu16(plane, ((c * h + row) * w + x) * 2, (bpc == 1 and((v * 257 ))or(v))) + end + if rle == 0 then + local need = w * h * z * bpc + local p = o + 512 + local avail = math.min(need, limit - p) + truncated = avail < need + for i = 0, math.floor(avail / bpc )- 1 do + local v = (bpc == 1 and{(readu8(b, p + i) )}or{(be16(b, p + i * 2) +)})[1] buffer.writeu16(plane, i * 2, (bpc == 1 and((v * 257 ))or(v))) + end + else + local n = h * z + if o + 512 + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512) + end + for c = 0, z - 1 do + for row = 0, h - 1 do + local i = c * h + row + local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4) + local p = o + start + local stop = math.min(limit, p + len) + local x = 0 + while x < w and p + bpc <= stop do + local cnt = (bpc == 1 and{(readu8(b, p) )}or{(be16(b, p) +)})[1] p =p+ bpc + local count = bit32.band(cnt, 0x7F) + if count == 0 then + break + end + if bit32.band(cnt, 0x80) ~= 0 then + for _ = 1, count do + if x >= w or p + bpc > stop then + break + end + put(c, row, x, (bpc == 1 and{(readu8(b, p) )}or{(be16(b, p))})[1]) + p =p+ bpc + x =x+ 1 + end + else + if p + bpc > stop then + break + end + local v = (bpc == 1 and{(readu8(b, p) )}or{(be16(b, p) +)})[1] p =p+ bpc + for _ = 1, count do + if x >= w then + break + end + put(c, row, x, v) + x =x+ 1 + end + end + end + if x < w then + truncated = true + end + end + end + end + local wide = opts and opts.native and bpc == 2 + local img = Types.Image.new(w, h, wide and"rgba16" or"rgba8") + local px = img.pixels + for y = 0, h - 1 do + local row = h - 1 - y + for x = 0, w - 1 do + local function s(c) +return buffer.readu16(plane, ((c * h + row) * w + x) * 2) + end + local rr= s(0) + local gg= (z >= 3 and{(s(1) )}or{rr +})[1] local bb= (z >= 3 and{(s(2) )}or{rr +})[1] local aa= (z == 2 and{(s(1) )}or{(z == 4 and{(s(3) )}or{65535 +})[1]})[1] local d = (y * w + x) + if wide then + buffer.writeu16(px, d * 8, rr) + buffer.writeu16(px, d * 8 + 2, gg) + buffer.writeu16(px, d * 8 + 4, bb) + buffer.writeu16(px, d * 8 + 6, aa) + else + buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216) + end + end + end + local name = buffer.readstring(b, o + 24, 80) + local zpos = string.find(name, "\0", 1, true) + name = (zpos and{(string.sub(name, 1, zpos - 1) )}or{name +})[1] if name ~= "" then + img.meta.text = { name = name } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sgi.encode(img, opts) +if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local wide = img.format == "rgba16" + local bpc = wide and 2 or 1 + local px = img.pixels + local function sample(x, y, c) +local i = (y * w + x) * 4 + c + return (wide and{(buffer.readu16(px, i * 2) )}or{(readu8(px, i) +)})[1] end + local z = 3 + for i = 0, w * h - 1 do + if ((wide and{(buffer.readu16(px, i * 8 + 6) < 65535 )}or{(readu8(px, i * 4 + 3) < 255)})[1]) then + z = 4 + break + end + end + local rle = not (opts and opts.rle == false) + local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8) + out:u16be(474) + out:u8(rle and 1 or 0) + out:u8(bpc) + out:u16be(3) + out:u16be(w) + out:u16be(h) + out:u16be(z) + out:u32be(0) + out:u32be(wide and 65535 or 255) + out:u32be(0) + local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or "" + name = string.sub(name, 1, 79) + out:string(name) + out:fill(0, 80 - #name) + out:u32be(0) + out:fill(0, 404) + local function put(v) + if wide then + out:u16be(v) + else + out:u8(v) + end + end + if not rle then + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + for x = 0, w - 1 do + put(sample(x, y, c)) + end + end + end + return out:finish(), nil + end + local tables = out:tell() + out:fill(0, h * z * 8) + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + local start = out:tell() + local x = 0 + while x < w do + -- a run of equal samples (>= 3) or literals up to the next run + local v = sample(x, y, c) + local run = 1 + while x + run < w and run < 127 and sample(x + run, y, c) == v do + run =run+ 1 + end + if run >= 3 then + put(run) + put(v) + x =x+ run + else + local lit = 0 + while x + lit < w and lit < 127 do + local a = sample(x + lit, y, c) + if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then + break + end + lit =lit+ 1 + end + lit = math.max(lit, 1) + put(0x80 + lit) + for k = 0, lit - 1 do + put(sample(x + k, y, c)) + end + x =x+ lit + end + end + put(0) + local i = c * h + row + out:setU32be(tables + i * 4, start) + out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start) + end + end + return out:finish(), nil +end + +return Sgi +end +__FILES["image/sunras"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour +-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, +-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in +-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the +-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), +-- raw colour maps (RMT_RAW is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Sunras = { + name = "sunras", + category = "image", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types + + + + + + + + +local MAGIC = "\89\166\106\149" +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b, o) +return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sunras.sniff(r) +return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sunras.decode(r, opts) +local b, o, limit = r.buf, r.base, r.limit + if limit - o < 32 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a Sun raster", o) + end + local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, "bad size", o + 4) + end + if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12) + end + if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then + return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local p = o + 32 + if p + maplen > limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local pal = buffer.create(1024) + local ncol = 0 + if maptype == 1 and maplen > 0 then + ncol = math.min(256, math.floor(maplen / 3)) + for i = 0, ncol - 1 do + buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000) + end + elseif depth == 1 then + buffer.writeu32(pal, 0, 0xFFFFFFFF) + buffer.writeu32(pal, 4, 0xFF000000) + else + for i = 0, 255 do + buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000) + end + end + p =p+ maplen + local stride = (math.floor((w * depth + 15) / 16)) * 2 + local total = stride * h + local raw = buffer.create(total + 4) + local truncated = false + if typ == 2 then + local q = 0 + while q < total and p < limit do + local c = readu8(b, p) + p =p+ 1 + if c ~= 0x80 then + buffer.writeu8(raw, q, c) + q =q+ 1 + else + if p >= limit then + break + end + local n = readu8(b, p) + p =p+ 1 + if n == 0 then + buffer.writeu8(raw, q, 0x80) + q =q+ 1 + else + if p >= limit then + break + end + local cnt = math.min(n + 1, total - q) + buffer.fill(raw, q, readu8(b, p), cnt) + p =p+ 1 + q =q+ cnt + end + end + end + truncated = q < total + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if depth <= 8 then + Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal) + else + local rgb = typ == 3 + local bytes = math.floor(depth / 8 +) local alpha = false + if bytes == 4 then + for y = 0, h - 1 do + for x = 0, w - 1 do + if readu8(raw, y * stride + x * 4) ~= 0 then + alpha = true + end + end + end + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local s = y * stride + x * bytes + local a = 255 + if bytes == 4 then + a = (alpha and{(readu8(raw, s) )}or{255 +})[1] s =s+ 1 + end + local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local rr, bb = (rgb and{c0 }or{c2})[1], (rgb and{c2 }or{c0 +})[1] buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216) + end + end + end + if ncol > 0 then + local list= {} + for i = 0, ncol - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sunras.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local px = img.pixels + local alpha = false + for i = 0, w * h - 1 do + if readu8(px, i * 4 + 3) < 255 then + alpha = true + break + end + end + local depth = alpha and 32 or 24 + local bytes = math.floor(depth / 8 +) local stride = (math.floor((w * depth + 15) / 16)) * 2 + local raw = buffer.create(stride * h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local s, d = (y * w + x) * 4, y * stride + x * bytes + if alpha then + buffer.writeu8(raw, d, readu8(px, s + 3)) + d =d+ 1 + end + buffer.writeu8(raw, d, readu8(px, s + 2)) + buffer.writeu8(raw, d + 1, readu8(px, s + 1)) + buffer.writeu8(raw, d + 2, readu8(px, s)) + end + end + local rle = not (opts and opts.rle == false) + local body = raw + if rle then + local wr = Bytes.writer(stride * h) + local i, n = 0, stride * h + while i < n do + local v = readu8(raw, i) + local run = 1 + while i + run < n and run < 256 and readu8(raw, i + run) == v do + run =run+ 1 + end + if run >= 3 or v == 0x80 then + if run == 1 then + wr:u8(0x80) + wr:u8(0) + else + wr:u8(0x80) + wr:u8(run - 1) + wr:u8(v) + end + else + for _ = 1, run do + wr:u8(v) + end + end + i =i+ run + end + body = wr:finish() + end + local out = Bytes.writer(32 + buffer.len(body)) + out:string(MAGIC) + out:u32be(w) + out:u32be(h) + out:u32be(depth) + out:u32be(buffer.len(body)) + out:u32be(rle and 2 or 1) + out:u32be(0) + out:u32be(0) + out:bytes(body) + return out:finish(), nil +end + +return Sunras +end +__FILES["image/tga"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3) +-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 / +-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left, +-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit: +-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data +-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit. +-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left +-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage +-- stamp, ...), which are ignored. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Codec = __include("image/tga/Codec") + +-- ------------------------------------------------------------------------------------------------ contract +local Tga = { + name = "tga", + category = "image", + extensions = { "tga", "icb", "vda", "vst", "tpic" }, + mime = { "image/x-tga", "image/x-targa" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8, 15, 16, 24, 32 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + +local TYPES = { [1] = true, [2] = true, [3] = true, [9] = true, [10] = true, [11] = true } +local FOOTER = "TRUEVISION-XFILE.\0" +local readu8 = buffer.readu8 +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + +local function header(r) +if r.limit - r.base < 18 then + return nil + end + local b, o = r.buf, r.base + local function u16(q) +return readu8(b, o + q) + readu8(b, o + q + 1) * 256 + end + local h= { + idLen = readu8(b, o), + cmapType = readu8(b, o + 1), + imageType = readu8(b, o + 2), + cmapFirst = u16(3), + cmapLen = u16(5), + cmapBits = readu8(b, o + 7), + width = u16(12), + height = u16(14), + depth = readu8(b, o + 16), + desc = readu8(b, o + 17), + } + return h +end + +-- plausible(h) -> nil | why not +local function implausible(h) +local t = h.imageType + if not TYPES[t] then + return "image type " .. t + end + if h.cmapType > 1 then + return "colour map type " .. h.cmapType + end + local mapped = t == 1 or t == 9 + if mapped and (h.cmapType ~= 1 or (h.depth ~= 8 and h.depth ~= 16)) then + return "colour-mapped image without a colour map" + end + if h.cmapType == 1 and h.cmapLen > 0 and h.cmapBits ~= 15 and h.cmapBits ~= 16 and h.cmapBits ~= 24 and h.cmapBits ~= 32 then + return "colour map entry size " .. h.cmapBits + end + if (t == 2 or t == 10) and h.depth ~= 15 and h.depth ~= 16 and h.depth ~= 24 and h.depth ~= 32 then + return "pixel depth " .. h.depth + end + if (t == 3 or t == 11) and h.depth ~= 8 and h.depth ~= 16 then + return "grey pixel depth " .. h.depth + end + if h.width == 0 or h.height == 0 then + return "zero size" + end + if h.desc >= 64 then + return "interleaving / reserved descriptor bits" + end + return nil +end + +function Tga.sniff(r) +local h = header(r) + if not h or implausible(h) then + return 0 + end + local n = r.limit - r.base + if n >= 44 and buffer.readstring(r.buf, r.limit - 18, 18) == FOOTER then + return 0.9 + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Tga.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local h = header(r) + if not h then + return nil, Err.new(Err.TRUNCATED, "short header", r.base) + end + local why = implausible(h) + if why then + return nil, Err.new((h.imageType == 0 and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], why, r.base) + end + local w, ht = h.width, h.height + if w * ht > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels)) + end + local b = r.buf + local p = r.base + 18 + local id = (h.idLen > 0 and p + h.idLen <= r.limit and{(buffer.readstring(b, p, h.idLen) )}or{nil +})[1] p =p+ h.idLen + -- colour map + local pal = buffer.create(4) + local palN = 0 + if h.cmapType == 1 and h.cmapLen > 0 then + local eb = math.floor((h.cmapBits + 7) / 8 +) if p + h.cmapLen * eb > r.limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local first = h.cmapFirst + palN = first + h.cmapLen + pal = buffer.create(palN * 4) + buffer.fill(pal, 0, 0, palN * 4) + local kind = h.cmapBits == 24 and 3 or(h.cmapBits == 32 and 4 or 2 +) for i = 0, h.cmapLen - 1 do + buffer.writeu32(pal, (first + i) * 4, Codec.pixel(b, p + i * eb, kind, false, pal, 0)) + end + for i = 0, first - 1 do + buffer.writeu32(pal, i * 4, 0xFF000000) + end + p =p+ h.cmapLen * eb + end + local t = h.imageType + local alphaBits = h.desc % 16 + local kind + if t == 1 or t == 9 then + kind = h.depth == 8 and 5 or 6 + elseif t == 3 or t == 11 then + kind = h.depth == 8 and 0 or 1 + else + kind = h.depth == 24 and 3 or(h.depth == 32 and 4 or 2 +) end + local bpp = math.floor((h.depth + 7) / 8 +) local bottomUp = (math.floor(h.desc / 32)) % 2 == 0 + local rtl = (math.floor(h.desc / 16)) % 2 == 1 + local img = Types.Image.new(w, ht, "rgba8") + local _, truncated = Codec.decode(b, p, r.limit, w, ht, bpp, kind, h.depth == 16 and alphaBits >= 1, t >= 9, bottomUp, rtl, pal, palN, img.pixels) + local native = opts and opts.native + if native and kind == 0 then + local g = Types.Image.new(w, ht, "gray8") + for i = 0, w * ht - 1 do + buffer.writeu8(g.pixels, i, readu8(img.pixels, i * 4)) + end + img = g + elseif native and kind == 3 then + local c = Types.Image.new(w, ht, "rgb8") + for i = 0, w * ht - 1 do + buffer.writeu16(c.pixels, i * 3, buffer.readu16(img.pixels, i * 4)) + buffer.writeu8(c.pixels, i * 3 + 2, readu8(img.pixels, i * 4 + 2)) + end + img = c + end + if palN > 0 then + local palette = {} + for i = 0, palN - 1 do + palette[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + img.meta.palette = palette + end + if id then + img.meta.text = { id = id } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { + format = "tga", + bitDepth = h.depth, + colorType = kind >= 5 and"palette" or(kind <= 1 and{(kind == 1 and"graya" or"gray") }or{(kind == 3 and"rgb" or"rgba")})[1], + rle = t >= 9, + origin = (bottomUp and"bottom" or"top") .. "-" .. (rtl and"right" or"left"), + alphaBits = alphaBits, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tga.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local srcBpp = img.format == "rgba8" and 4 or(img.format == "rgb8" and 3 or(img.format == "gray8" and 1 or nil +)) if not srcBpp then + return nil, Err.new(Err.ARG, "needs an rgba8, rgb8 or gray8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w > 65535 or h > 65535 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(img.pixels) < w * h * srcBpp then + return nil, Err.new(Err.ARG, "bad image size or pixel buffer (1..65535 per side)") + end + local o= opts or {} + local origin = o.origin or "bottom-left" + if origin ~= "bottom-left" and origin ~= "top-left" then + return nil, Err.new(Err.ARG, "origin must be \"bottom-left\" or \"top-left\"") + end + local outBpp = srcBpp + if srcBpp == 4 then + local alpha = o.alpha + if alpha == nil then + alpha = false + for i = 0, w * h - 1 do + if readu8(img.pixels, i * 4 + 3) ~= 255 then + alpha = true + break + end + end + end + outBpp = alpha and 4 or 3 + end + local id = o.id or (img.meta and img.meta.text and img.meta.text.id) or "" + if type(id) ~= "string" then + id = "" + end + id = string.sub(id, 1, 255) + local rle = o.rle == true + local out = buffer.create(18 + #id + w * h * (outBpp + 1) + 26) + buffer.writeu8(out, 0, #id) + buffer.writeu8(out, 2, (outBpp == 1 and 3 or 2) + (rle and 8 or 0)) + buffer.writeu16(out, 12, w) + buffer.writeu16(out, 14, h) + buffer.writeu8(out, 16, outBpp * 8) + buffer.writeu8(out, 17, (outBpp == 4 and 8 or 0) + (origin == "top-left" and 32 or 0)) + buffer.writestring(out, 18, id) + local op = Codec.encode(img.pixels, w, h, srcBpp, outBpp, rle, origin == "top-left", out, 18 + #id) + -- TGA 2.0 footer: no extension / developer areas + buffer.writeu32(out, op, 0) + buffer.writeu32(out, op + 4, 0) + buffer.writestring(out, op + 8, FOOTER) + op =op+ 26 + local res = buffer.create(op) + buffer.copy(res, 0, out, 0, op) + return res, nil +end + +return Tga +end +__FILES["image/tga/Codec"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0 +-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented +-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes. +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 + +local Codec = {} + +-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, +-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them) +local function pixel(b, p, kind, alpha1, pal, palN) +if kind == 0 then + return readu8(b, p) * 0x10101 + 0xFF000000 + elseif kind == 1 then + return readu8(b, p) * 0x10101 + readu8(b, p + 1) * 0x1000000 + elseif kind == 2 then + local v = readu16(b, p) + local r, g, bl = (math.floor(v / 1024)) % 32, (math.floor(v / 32)) % 32, v % 32 + local a = alpha1 and v < 32768 and 0 or 255 + return math.floor((r * 255 + 15) / 31 )+ (math.floor((g * 255 + 15) / 31)) * 256 + (math.floor((bl * 255 + 15) / 31)) * 65536 + a * 16777216 -- round(v * 255 / 31), as ImageMagick + elseif kind == 3 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + 0xFF000000 + elseif kind == 4 then + return readu8(b, p + 2) + readu8(b, p + 1) * 256 + readu8(b, p) * 65536 + readu8(b, p + 3) * 16777216 + end + local i = (kind == 5 and{(readu8(b, p) )}or{(readu16(b, p) +)})[1] if i >= palN then + return 0xFF000000 + end + return readu32(pal, i * 4) +end +Codec.pixel = pixel + +-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated? +function Codec.decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) +local n = w * h + local i = 0 + local function put(v) + local row, col = math.floor(i / w), i % w + if bottomUp then + row = h - 1 - row + end + if rtl then + col = w - 1 - col + end + writeu32(out, (row * w + col) * 4, v) + i =i+ 1 + end + if not rle then + local avail = math.min(n, math.floor((limit - p) / bpp)) + for _ = 1, avail do + put(pixel(b, p, kind, alpha1, pal, palN)) + p =p+ bpp + end + return i, avail < n + end + while i < n do + if p >= limit then + return i, true + end + local hd = readu8(b, p) + p =p+ 1 + local count = hd % 128 + 1 + if hd >= 128 then + if p + bpp > limit then + return i, true + end + local v = pixel(b, p, kind, alpha1, pal, palN) + p =p+ bpp + for _ = 1, math.min(count, n - i) do + put(v) + end + else + for _ = 1, math.min(count, n - i) do + if p + bpp > limit then + return i, true + end + put(pixel(b, p, kind, alpha1, pal, palN)) + p =p+ bpp + end + end + end + return i, false +end + +-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1); +-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row. +-- out needs room for w * h * (outBpp + 1) bytes. +function Codec.encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) +local function get(q) +if srcBpp == 1 then + return readu8(px, q) + elseif srcBpp == 3 then + return readu8(px, q) + readu8(px, q + 1) * 256 + readu8(px, q + 2) * 65536 + 0xFF000000 + end + return readu32(px, q) + end + local function emit(v) + if outBpp == 1 then + writeu8(out, o, v % 256) + else + writeu8(out, o, (math.floor(v / 65536)) % 256) + writeu8(out, o + 1, (math.floor(v / 256)) % 256) + writeu8(out, o + 2, v % 256) + if outBpp == 4 then + writeu8(out, o + 3, math.floor(v / 16777216)) + end + end + o =o+ outBpp + end + for y = 0, h - 1 do + local row = (topDown and{y }or{(h - 1 - y +)})[1] local base = row * w * srcBpp + if not rle then + for x = 0, w - 1 do + emit(get(base + x * srcBpp)) + end + else + local x = 0 + while x < w do + local v = get(base + x * srcBpp) + local run = 1 + while x + run < w and run < 128 and get(base + (x + run) * srcBpp) == v do + run =run+ 1 + end + if run >= 2 then + writeu8(out, o, 127 + run) + o =o+ 1 + emit(v) + x =x+ run + else + -- a raw packet up to the next run of 2 or more + local s = x + local cnt = 0 + while x < w and cnt < 128 do + local c = get(base + x * srcBpp) + if x + 1 < w and get(base + (x + 1) * srcBpp) == c then + break + end + cnt =cnt+ 1 + x =x+ 1 + end + writeu8(out, o, cnt - 1) + o =o+ 1 + for k = s, s + cnt - 1 do + emit(get(base + k * srcBpp)) + end + end + end + end + end + return o +end + +return Codec +end +__FILES["image/tiff"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. +-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / +-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's +-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), +-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, +-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as +-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard +-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32). +-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none / +-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames. +-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Lzw = __include("codecs/compress/Lzw") +local Pixels = __include("image/tiff/Pixels") +local PackBits = __include("codecs/compress/PackBits") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiff = { + name = "tiff", + category = "image", + extensions = { "tif", "tiff" }, + mime = { "image/tiff" }, + 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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +local TYPE_SIZE = { [1] = 1, [2] = 1, [3] = 2, [4] = 4, [5] = 8, [6] = 1, [7] = 1, [8] = 2, [9] = 4, [10] = 8, [11] = 4, [12] = 8, [13] = 4, [16] = 8, [17] = 8, [18] = 8 } +local COMPRESSION = { [1] = "none", [5] = "lzw", [8] = "deflate", [32946] = "deflate", [32773] = "packbits", [7] = "jpeg" } +local PHOTOMETRIC = { [0] = "miniswhite", [1] = "minisblack", [2] = "rgb", [3] = "palette", [5] = "cmyk", [6] = "ycbcr" } +local TWO32 = 4294967296 + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Tiff.sniff(r) +local s = r:peek(4) + if s == "II*\0" or s == "MM\0*" or s == "II+\0" or s == "MM\0+" then + return 1 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + + +local function u16(c, at) +if at < c.base or at + 2 > c.limit then + return 0 + end + return (c.le and{(readu16(c.b, at) )}or{(readu8(c.b, at) * 256 + readu8(c.b, at + 1) +)})[1]end +local function u32(c, at) +if at < c.base or at + 4 > c.limit then + return 0 + end + local v = readu32(c.b, at) + return (c.le and{v }or{(bit32.byteswap(v) +)})[1]end +local function u64(c, at) +local lo, hi = u32(c, at), u32(c, at + 4) + if not c.le then + lo, hi = hi, lo + end + return hi * TWO32 + lo +end +local function off(c, at) +return (c.big and{(u64(c, at) )}or{(u32(c, at) +)})[1]end + +-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many +local function values(c, e, max) +if not e then + return nil + end + local size = TYPE_SIZE[e.typ] + if not size or e.count > (max or 1e7) or e.at < c.base or e.at + e.count * size > c.limit then + return nil + end + local out = table.create(e.count, 0) + local b = c.b + for i = 0, e.count - 1 do + local p = e.at + i * size + local t = e.typ + local v + if t == 1 or t == 2 or t == 7 then + v = readu8(b, p) + elseif t == 6 then + v = buffer.readi8(b, p) + elseif t == 3 then + v = u16(c, p) + elseif t == 8 then + v = u16(c, p) + if v >= 32768 then + v =v- 65536 + end + elseif t == 4 or t == 13 then + v = u32(c, p) + elseif t == 9 then + v = u32(c, p) + if v >= 2147483648 then + v =v- TWO32 + end + elseif t == 5 or t == 10 then + local n, d = u32(c, p), u32(c, p + 4) + if t == 10 then + if n >= 2147483648 then + n =n- TWO32 + end + if d >= 2147483648 then + d =d- TWO32 + end + end + v = (d ~= 0 and((n / d ))or(0 +)) elseif t == 11 then + v = Pixels.f32(u32(c, p)) + elseif t == 12 then + local lo, hi = u32(c, p), u32(c, p + 4) + if not c.le then + lo, hi = hi, lo + end + v = Pixels.f64(lo, hi) + else + v = u64(c, p) + end + out[i + 1] = v + end + return out +end + +local function one(c, e, default) +local v = values(c, e, 64) + return (v and v[1] and{v[1] }or{default +})[1]end + +-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err +local function readIfd(c, p) +local esize = c.big and 20 or 12 + local hsize = c.big and 8 or 2 + if p < c.base or p + hsize > c.limit then + return nil, 0, Err.new(Err.TRUNCATED, "IFD past the end", p) + end + local n = (c.big and{(u64(c, p) )}or{(u16(c, p) +)})[1] if n == 0 or p + hsize + n * esize > c.limit then + return nil, 0, Err.new((n == 0 and{Err.CORRUPT }or{Err.TRUNCATED})[1], "bad IFD entry count " .. n, p) + end + local entries= {} + for i = 0, n - 1 do + local q = p + hsize + i * esize + local tag, typ = u16(c, q), u16(c, q + 2) + local count = (c.big and{(u64(c, q + 4) )}or{(u32(c, q + 4) +)})[1] local vat = q + (c.big and 12 or 8) + local size = TYPE_SIZE[typ] + if size then + local at = vat + if count * size > (c.big and 8 or 4) then + at = c.base + off(c, vat) + end + entries[tag] = { tag = tag, typ = typ, count = count, at = at } + end + end + local nq = p + hsize + n * esize + local nextOff = 0 + if nq + (c.big and 8 or 4) <= c.limit then + nextOff = off(c, nq) + end + return entries, (nextOff > 0 and((c.base + nextOff ))or(0)), nil +end + +local function bytesOf(c, e, max) +if not e or e.at < c.base then + return nil + end + local size = TYPE_SIZE[e.typ] or 1 + local n = e.count * size + if n > max or e.at + n > c.limit then + return nil + end + local x = buffer.create(n) + buffer.copy(x, 0, c.b, e.at, n) + return x +end + +-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err +local function inflateChunk(c, comp, p, len, out, o, size, rev) +if p < c.base or len < 0 or p + len > c.limit then + -- a chunk past the end: keep what exists (truncated files) + len = math.max(0, math.min(len, c.limit - p)) + if p < c.base or p >= c.limit then + return 0, nil + end + end + local src, sp = c.b, p + if rev then + src = buffer.create(len) + buffer.copy(src, 0, c.b, p, len) + Pixels.reverseBits(src, 0, len) + sp = 0 + end + if comp == 1 then + local n = math.min(len, size) + buffer.copy(out, o, src, sp, n) + return n, nil + elseif comp == 5 then + local n = Lzw.decode(src, sp, len, out, o, size, "tiff") + return n, nil + elseif comp == 8 or comp == 32946 then + local raw = Deflate.zlib(src, sp, len, size) + if not raw then + raw = Deflate.zlib(src, sp, len) or Deflate.inflate(src, sp, len) + end + if not raw then + return nil, Err.new(Err.CORRUPT, "bad deflate data", p) + end + local n = math.min(buffer.len(raw ), size) + buffer.copy(out, o, raw , 0, n) + return n, nil + elseif comp == 32773 then + return (PackBits.decode(src, sp, sp + len, out, o, size)), nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp) +end + + + +local function decodePage(c, t, opts) +local w, h = one(c, t[256], 0), one(c, t[257], 0) + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local spp = one(c, t[277], 1) + local bpsList = values(c, t[258], 64) or { 1 } + local bps = bpsList[1] or 1 + for i = 2, math.min(#bpsList, spp) do + if bpsList[i] ~= bps then + return nil, Err.new(Err.UNSUPPORTED, "different bit depths per sample") + end + end + local comp = one(c, t[259], 1) + local photo = one(c, t[262], spp >= 3 and 2 or 1) + local planar = one(c, t[284], 1) + local predictor = one(c, t[317], 1) + local sfmt = one(c, t[339], 1) + local fill = one(c, t[266], 1) + if spp < 1 or spp > 16 or bps < 1 or bps > 64 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%d samples of %d bits", spp, bps)) + end + if sfmt == 3 and bps ~= 16 and bps ~= 32 and bps ~= 64 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit floats") + end + if sfmt ~= 3 and bps > 32 then + return nil, Err.new(Err.UNSUPPORTED, bps .. "-bit integers") + end + if not COMPRESSION[comp] then + local names = { [2] = "CCITT RLE", [3] = "CCITT fax 3", [4] = "CCITT fax 4", [6] = "old-style JPEG", [34712] = "JPEG 2000", [34925] = "LZMA", [50000] = "Zstandard", [50001] = "WebP" } + return nil, Err.new(Err.UNSUPPORTED, (names[comp] or "compression") .. " (" .. comp .. ")") + end + if not PHOTOMETRIC[photo] then + return nil, Err.new(Err.UNSUPPORTED, "photometric interpretation " .. photo) + end + local cc = (photo == 2 or photo == 6 )and 3 or(photo == 5 and 4 or 1 +) if spp < cc then + return nil, Err.new(Err.CORRUPT, string.format("%d samples for photometric %d", spp, photo)) + end + if photo == 5 and one(c, t[332], 1) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "separated image that is not CMYK") + end + local extra = values(c, t[338], 16) or {} + local alpha, assoc = -1, false + if spp > cc then + local kind = extra[1] or 0 + alpha = cc + assoc = kind == 1 + end + local chunky = planar ~= 2 or spp == 1 + local tiled = t[322] ~= nil + local cw = (tiled and{(one(c, t[322], 0) )}or{w +})[1] local ch = (tiled and{(one(c, t[323], 0) )}or{(math.min(one(c, t[278], h), h) +)})[1] if cw < 1 or ch < 1 or cw > 65536 or (tiled and ch > 65536) then + return nil, Err.new(Err.CORRUPT, "bad tile / strip size") + end + if ch > h and not tiled then + ch = h + end + local pspp = (chunky and{spp }or{1 -- samples per pixel in one plane +})[1] local nplanes = chunky and 1 or spp + local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane + local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row + if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "decoded data over 1 GB") + end + local across = (tiled and{(math.ceil(w / cw) )}or{1 +})[1] local down = math.ceil(h / ch) + local perPlane = across * down + local offs = values(c, (tiled and{t[324] }or{t[273]})[1], 2 ^ 24) + local lens = values(c, (tiled and{t[325] }or{t[279]})[1], 2 ^ 24) + if not offs or #offs < perPlane * nplanes then + return nil, Err.new(Err.CORRUPT, "missing or short strip / tile offsets") + end + local planes= (table.create(nplanes) ) +for i = 1, nplanes do + planes[i] = buffer.create(rb * h + 8) + end + local tmp = buffer.create(crb * ch + 8) + local ftmp = buffer.create(math.max(rb, crb) + 8) + local le = c.le + local bytesPer = math.floor(bps / 8 +) local hook = opts and opts.decodeImage + local jpegTables = (comp == 7 and{(bytesOf(c, t[347], 1 * 2 ^ 20) )}or{nil +})[1] local jpegPixels= nil + if comp == 7 then + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "JPEG-compressed TIFF needs opts.decodeImage (F.load supplies it)") + end + jpegPixels = buffer.create(w * h * 4) + end + for pl = 0, nplanes - 1 do + for ty = 0, down - 1 do + for tx = 0, across - 1 do +local __DARKLUA_CONTINUE_7=false repeat local idx = pl * perPlane + ty * across + tx + local p = c.base + offs[idx + 1] + local len = (lens and lens[idx + 1] and{lens[idx + 1] }or{(c.limit - p +)})[1] local rows = (tiled and{ch }or{(math.min(ch, h - ty * ch) +)})[1] local size = rows * crb + if comp == 7 then + -- JPEGTables (SOI .. EOI) + the chunk (SOI .. EOI): one stream without the inner EOI / SOI + if p < c.base or p + len > c.limit or len < 4 then + return nil, Err.new(Err.TRUNCATED, "JPEG chunk past the end", p) + end + local tl = (jpegTables and buffer.len(jpegTables) >= 4 and((buffer.len(jpegTables) - 2 ))or(0 +)) local s = buffer.create(tl + len - (tl > 0 and 2 or 0)) + if tl > 0 then + buffer.copy(s, 0, jpegTables , 0, tl) + buffer.copy(s, tl, c.b, p + 2, len - 2) + else + buffer.copy(s, 0, c.b, p, len) + end + local ok, img, herr = pcall(hook , s) + if not ok or type(img) ~= "table" or img.format ~= "rgba8" then + return nil, (ok and herr and{herr }or{(Err.new(Err.CORRUPT, "embedded JPEG: " .. tostring((ok and{herr }or{img})[1])) +)})[1] end + local x0, y0 = tx * cw, ty * ch + local cwid = math.min(cw, w - x0, img.width) + for yy = 0, math.min(rows, h - y0, img.height) - 1 do + buffer.copy(jpegPixels , ((y0 + yy) * w + x0) * 4, img.pixels, yy * img.width * 4, cwid * 4) + end +__DARKLUA_CONTINUE_7=true break + end + buffer.fill(tmp, 0, 0, size) + local _, derr = inflateChunk(c, comp, p, len, tmp, 0, size, fill == 2) + if derr then + return nil, derr + end + if predictor == 2 then + Pixels.unpredict2(tmp, 0, rows, crb, pspp, bps, le) + elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then + Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp) + end + -- into the plane + local plane = planes[pl + 1] + local x0b = math.floor(tx * cw * pspp * bps / 8) + local cols = math.min(cw, w - tx * cw) + local nb = math.min(math.ceil(cols * pspp * bps / 8), rb - x0b) + for yy = 0, rows - 1 do + local y = ty * ch + yy + if y >= h then + break + end + buffer.copy(plane, y * rb + x0b, tmp, yy * crb, nb) + end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + end + end + local floatOut = sfmt == 3 + if predictor == 3 and floatOut then + le = true -- fpAcc leaves the samples little endian + end + local colorType = PHOTOMETRIC[photo] + -- the output layout + local kind = "rgba8" + if opts and opts.native and comp ~= 7 then + if photo == 3 or photo == 5 then + kind = "rgba8" + elseif floatOut then + kind = "rgbaf32" + elseif cc == 1 then + if alpha >= 0 then + kind = bps <= 8 and"graya8" or"rgba16" + else + kind = bps <= 8 and"gray8" or"gray16" + end + else + if alpha >= 0 then + kind = bps <= 8 and"rgba8" or"rgba16" + else + kind = bps <= 8 and"rgb8" or"rgba16" + end + end + end + local img = Types.Image.new(w, h, kind ) + if comp == 7 then + img.pixels = jpegPixels +else + if photo == 6 then + return nil, Err.new(Err.UNSUPPORTED, "uncompressed YCbCr") + end + local cmap = nil + if photo == 3 then + local n = 3 * 2 ^ math.min(bps, 16) + local cv = values(c, t[320], n) + if not cv or #cv < n then + return nil, Err.new(Err.CORRUPT, "palette image without a full ColorMap") + end + cmap = buffer.create(n * 2) + for i = 1, n do + buffer.writeu16(cmap, (i - 1) * 2, math.clamp(cv[i], 0, 65535)) + end + end + Pixels.convert({ + planes = planes, + rb = rb, + chunky = chunky, + w = w, + h = h, + spp = spp, + bps = bps, + sfmt = sfmt, + le = le, + photo = photo, + alpha = alpha, + assoc = assoc, + cmap = cmap, + kind = kind, + out = img.pixels, + }) + end + local xr, yr = one(c, t[282], 0), one(c, t[283], 0) + if xr > 0 and yr > 0 then + local unit = one(c, t[296], 2) + local k = unit == 3 and 2.54 or 1 + if unit ~= 1 then + img.meta.dpi = { x = xr * k, y = yr * k } + end + end + img.meta.icc = bytesOf(c, t[34675], 2 ^ 26) + local function ascii(tag) +local v = bytesOf(c, t[tag], 65536) + if not v then + return nil + end + local s = buffer.tostring(v) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1] end + local text = {} + for tag, key in __iter({ [270] = "description", [305] = "software", [306] = "datetime", [315] = "artist", [33432] = "copyright" }) do + local s = ascii(tag) + if s and s ~= "" then + text[key] = s + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { + format = "tiff", + bitDepth = bps, + colorType = colorType, + photometric = photo, + samples = spp, + sampleFormat = sfmt == 3 and"float" or(sfmt == 2 and"int" or"uint"), + compression = COMPRESSION[comp], + predictor = predictor, + planar = planar, + tiled = tiled, + alpha = (alpha >= 0 and{(assoc and"associated" or"unassociated") }or{nil})[1], + bigtiff = c.big, + byteOrder = c.le and"II" or"MM", + } + return img, nil +end + +-- pages(r) -> the IFD tables of every page (and the context) | nil, Err +local function pages(r, maxPages) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 then + return nil, nil, Err.new(Err.TRUNCATED, "short header") + end + local bo = buffer.readstring(b, base, 2) + if bo ~= "II" and bo ~= "MM" then + return nil, nil, Err.new(Err.CORRUPT, "bad byte order mark") + end + local c= { b = b, base = base, limit = limit, le = bo == "II", big = false } + local magic = u16(c, base + 2) + local first + if magic == 42 then + first = u32(c, base + 4) + elseif magic == 43 then + if limit - base < 16 or u16(c, base + 4) ~= 8 then + return nil, nil, Err.new(Err.CORRUPT, "bad BigTIFF header") + end + c.big = true + first = u64(c, base + 8) + else + return nil, nil, Err.new(Err.CORRUPT, "bad magic " .. magic) + end + local list = {} + local seen = {} + local p = base + first + while p > 0 and #list < maxPages do + if seen[p] then + break -- an IFD loop + end + seen[p] = true + local t, nextP, err = readIfd(c, p) + if not t then + if #list == 0 then + return nil, nil, err + end + break + end + table.insert(list, t) + p = nextP + end + return list, c, nil +end + +-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err +function Tiff.info(r) +local list, c, err = pages(r, 1024) + if not list or not c then + return nil, err + end + local t = list[1] + return { + pages = #list, + width = one(c, t[256], 0), + height = one(c, t[257], 0), + bitDepth = one(c, t[258], 1), + samples = one(c, t[277], 1), + compression = COMPRESSION[one(c, t[259], 1)] or tostring(one(c, t[259], 1)), + photometric = PHOTOMETRIC[one(c, t[262], 1)], + bigtiff = c.big, + }, + nil +end + +function Tiff.decode(r, opts) +local maxPages = opts and opts.maxPages or 1024 + local list, c, err = pages(r, (opts and opts.page and{(math.max(1, opts.page) )}or{maxPages})[1]) + if not list or not c then + return nil, err + end + if opts and opts.page then + local t = list[opts.page] + if not t then + return nil, Err.new(Err.ARG, "no page " .. tostring(opts.page)) + end + local img, perr = decodePage(c, t, opts) + if img then + (img.meta.source ).pages = #list + end + return img, perr + end + local first= nil + local frames = {} + for i, t in __iter(list) do +local __DARKLUA_CONTINUE_13=false repeat -- reduced-resolution subfiles (thumbnails) after page 1 are skipped + local sub = one(c, t[254], 0) + if i > 1 and bit32.band(sub, 1) ~= 0 then +__DARKLUA_CONTINUE_13=true break + end + local img, perr = decodePage(c, t, opts) + if not img then + if i == 1 then + return nil, perr + end +__DARKLUA_CONTINUE_13=true break + end + if not first then + first = img + end + table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }) +__DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end + local img = first ; +(img.meta.source ).pages = #frames + if #frames > 1 then + img.frames = frames +end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- layout per pixel format: samples, bits, sample format, photometric, extra samples +local LAYOUT = { + gray8 = { 1, 8, 1, 1 }, + graya8 = { 2, 8, 1, 1 }, + gray16 = { 1, 16, 1, 1 }, + rgb8 = { 3, 8, 1, 2 }, + rgba8 = { 4, 8, 1, 2 }, + rgba16 = { 4, 16, 1, 2 }, + rgbaf32 = { 4, 32, 3, 2 }, +} +local COMP_CODES = { none = 1, deflate = 8, lzw = 5, packbits = 32773 } + + + +local function encodePage(img, o, comp) +local L = LAYOUT[img.format] + if not L then + return nil, nil, Err.new(Err.ARG, "unsupported pixel format " .. tostring(img.format)) + end + local w, h = img.width, img.height + local spp, bps, sfmt, photo = L[1], L[2], L[3], L[4] + local rb = math.floor(w * spp * bps / 8 +) if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or w > 2 ^ 31 or buffer.len(img.pixels) < rb * h then + return nil, nil, Err.new(Err.ARG, "bad image size or pixel buffer") + end + local rps = o.rowsPerStrip or math.max(1, math.floor(65536 / rb)) + if type(rps) ~= "number" or rps < 1 then + return nil, nil, Err.new(Err.ARG, "rowsPerStrip must be >= 1") + end + rps = math.min(math.floor(rps), h) + local predictor = 1 + if (comp == 8 or comp == 5) and o.predictor ~= false then + predictor = sfmt == 3 and 3 or 2 + end + local strips = {} + local tmp = buffer.create(rb + 8) + for y0 = 0, h - 1, rps do + local rows = math.min(rps, h - y0) + local raw = buffer.create(rows * rb) + buffer.copy(raw, 0, img.pixels, y0 * rb, rows * rb) + if predictor == 2 then + Pixels.predict2(raw, 0, rows, rb, spp, bps) + elseif predictor == 3 then + Pixels.predict3(raw, 0, rows, rb, 4, spp, tmp) + end + local out + if comp == 1 then + out = raw + elseif comp == 8 then + out = (Deflate.zlibCompress(raw, { level = o.level or 6 }) ) +elseif comp == 5 then + out = Lzw.encode(raw, 0, rows * rb, "tiff") + else + local parts, total = {}, 0 + for r = 0, rows - 1 do + local p = PackBits.encode(raw, r * rb, rb) + table.insert(parts, p) + total =total+ buffer.len(p) + end + out = buffer.create(total) + local q = 0 + for _, p in __iter(parts) do + buffer.copy(out, q, p) + q =q+ buffer.len(p) + end + end + table.insert(strips, out) + end + local bpsv = table.create(spp, bps) + local tags= { + { tag = 254, typ = 4, vals = { 0 } }, + { tag = 256, typ = 4, vals = { w } }, + { tag = 257, typ = 4, vals = { h } }, + { tag = 258, typ = 3, vals = bpsv }, + { tag = 259, typ = 3, vals = { comp } }, + { tag = 262, typ = 3, vals = { photo } }, + { tag = 273, typ = 4, vals = table.create(#strips, 0) }, -- patched + { tag = 277, typ = 3, vals = { spp } }, + { tag = 278, typ = 4, vals = { rps } }, + { tag = 279, typ = 4, vals = table.create(#strips, 0) }, + { tag = 284, typ = 3, vals = { 1 } }, + } + for i, s in __iter(strips) do + (tags[10].vals )[i] = buffer.len(s) + end + local dpi = img.meta and img.meta.dpi + if type(dpi) == "table" and type(dpi.x) == "number" and type(dpi.y) == "number" and dpi.x > 0 and dpi.y > 0 then + table.insert(tags, { tag = 282, typ = 5, vals = { dpi.x } }) + table.insert(tags, { tag = 283, typ = 5, vals = { dpi.y } }) + table.insert(tags, { tag = 296, typ = 3, vals = { 2 } }) + end + if predictor > 1 then + table.insert(tags, { tag = 317, typ = 3, vals = { predictor } }) + end + if spp == 2 or spp == 4 then + table.insert(tags, { tag = 338, typ = 3, vals = { 2 } }) + end + if sfmt ~= 1 then + table.insert(tags, { tag = 339, typ = 3, vals = table.create(spp, sfmt) }) + end + local icc = img.meta and img.meta.icc + if type(icc) == "buffer" then + table.insert(tags, { tag = 34675, typ = 7, data = icc }) + end + local text = img.meta and img.meta.text + if type(text) == "table" then + for key, tag in __iter({ description = 270, software = 305, datetime = 306, artist = 315, copyright = 33432 }) do + if type(text[key]) == "string" then + table.insert(tags, { tag = tag, typ = 2, data = buffer.fromstring(text[key] .. "\0") }) + end + end + end + table.sort(tags, function(a, b) +return a.tag < b.tag + end) + return tags, strips, nil +end + +function Tiff.encode(img, opts) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local o= opts or {} + local comp = COMP_CODES[o.compression or "deflate"] + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, deflate, lzw or packbits") + end + local list = { img } + if type(img.frames) == "table" and #img.frames > 1 then + list = {} + for _, f in __iter(img.frames) do + if type(f) ~= "table" or type(f.image) ~= "table" then + return nil, Err.new(Err.ARG, "bad frame") + end + table.insert(list, f.image) + end + end + local w = Bytes.writer(1024) + w:string("II") + w:u16le(42) + w:u32le(0) -- first IFD, patched + local prevNext = 4 + for _, page in __iter(list) do + local tags, strips, err = encodePage(page, o, comp) + if not tags or not strips then + return nil, err + end + -- strip data first + local soffs = {} + for i, s in __iter(strips) do + if w:tell() % 2 == 1 then + w:u8(0) + end + soffs[i] = w:tell() + w:bytes(s) + end + for _, tg in __iter(tags) do + if tg.tag == 273 then + tg.vals = soffs + end + end + -- out-of-line values + local valOff= {} + for i, tg in __iter(tags) do + local size = TYPE_SIZE[tg.typ] + local n = (tg.data and{(buffer.len(tg.data ) )}or{(#(tg.vals ) * size +)})[1] if n > 4 then + if w:tell() % 2 == 1 then + w:u8(0) + end + valOff[i] = w:tell() + if tg.data then + w:bytes(tg.data ) + else + for _, v in __iter(tg.vals) do + if tg.typ == 3 then + w:u16le(v) + elseif tg.typ == 4 then + w:u32le(v) + elseif tg.typ == 5 then + w:u32le(math.floor(v * 10000 + 0.5)) + w:u32le(10000) + end + end + end + end + end + if w:tell() % 2 == 1 then + w:u8(0) + end + local ifd = w:tell() + w:setU32le(prevNext, ifd) + w:u16le(#tags) + for i, tg in __iter(tags) do + local count = (tg.data and{(buffer.len(tg.data ) )}or{(#(tg.vals ) +)})[1] w:u16le(tg.tag) + w:u16le(tg.typ) + w:u32le(count) + if valOff[i] then + w:u32le(valOff[i]) + else + local start = w:tell() + if tg.data then + w:bytes(tg.data ) + else + for _, v in __iter(tg.vals) do + if tg.typ == 3 then + w:u16le(v) + else + w:u32le(v) + end + end + end + w:fill(0, 4 - (w:tell() - start)) + end + end + prevNext = w:tell() + w:u32le(0) + end + return w:finish(), nil +end + +return Tiff +end +__FILES["image/tiff/Pixels"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and +-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's +-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout. +-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack. +local Bytes = __include("core/Bytes") +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64 +local band, bor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.rshift, bit32.lshift, bit32.byteswap +local floor = math.floor + +local Pixels = {} + +local scratch = buffer.create(8) + +-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an +-- arbitrary payload, which its NaN-tagged values misread as a table / userdata) +local function f32(bits) +if band(bits, 0x7F800000) == 0x7F800000 then + if band(bits, 0x7FFFFF) ~= 0 then + return 0 / 0 + end + return (bits >= 0x80000000 and{(-math.huge )}or{math.huge +})[1] end + writeu32(scratch, 0, bits) + return readf32(scratch, 0) +end +local function f64(lo, hi) +if band(hi, 0x7FF00000) == 0x7FF00000 then + if band(hi, 0xFFFFF) ~= 0 or lo ~= 0 then + return 0 / 0 + end + return (hi >= 0x80000000 and{(-math.huge )}or{math.huge +})[1] end + writeu32(scratch, 0, lo) + writeu32(scratch, 4, hi) + return readf64(scratch, 0) +end +Pixels.f32 = f32 +Pixels.f64 = f64 + +-- ------------------------------------------------------------------------------------------------ fill order +local REV = buffer.create(256) +for i = 0, 255 do + local r = 0 + for k = 0, 7 do + if band(i, lshift(1, k)) ~= 0 then + r = bor(r, lshift(1, 7 - k)) + end + end + writeu8(REV, i, r) +end +function Pixels.reverseBits(b, off, len) + for i = off, off + len - 1 do + writeu8(b, i, readu8(REV, readu8(b, i))) + end +end + +-- ------------------------------------------------------------------------------------------------ predictors +-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched) +function Pixels.unpredict2(b, off, rows, rb, stride, bps, le) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + elseif bps == 16 then + local n = math.floor(rb / 2 +) for k = stride, n - 1 do + local i = base + k * 2 + local j = i - stride * 2 + if le then + writeu16(b, i, band(readu16(b, i) + readu16(b, j), 0xFFFF)) + else + local v = readu8(b, i) * 256 + readu8(b, i + 1) + readu8(b, j) * 256 + readu8(b, j + 1) + writeu8(b, i, band(rshift(v, 8), 255)) + writeu8(b, i + 1, band(v, 255)) + end + end + elseif bps == 32 then + local n = math.floor(rb / 4 +) for k = stride, n - 1 do + local i = base + k * 4 + local j = i - stride * 4 + if le then + writeu32(b, i, (readu32(b, i) + readu32(b, j)) % 4294967296) + else + writeu32(b, i, byteswap((byteswap(readu32(b, i)) + byteswap(readu32(b, j))) % 4294967296)) + end + end + end + end +end + +-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit) +function Pixels.predict2(b, off, rows, rb, stride, bps) + for r = 0, rows - 1 do + local base = off + r * rb + if bps == 8 then + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + elseif bps == 16 then + for k = math.floor(rb / 2 )- 1, stride, -1 do + local i = base + k * 2 + writeu16(b, i, band(readu16(b, i) - readu16(b, i - stride * 2), 0xFFFF)) + end + end + end +end + +-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little +-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes. +function Pixels.unpredict3(b, off, rows, rb, bytes, stride, tmp) + local wc = math.floor(rb / bytes +) for r = 0, rows - 1 do + local base = off + r * rb + for i = base + stride, base + rb - 1 do + writeu8(b, i, band(readu8(b, i) + readu8(b, i - stride), 255)) + end + buffer.copy(tmp, 0, b, base, rb) + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(b, base + c * bytes + k, readu8(tmp, (bytes - k - 1) * wc + c)) + end + end + end +end + +-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff) +function Pixels.predict3(b, off, rows, rb, bytes, stride, tmp) + local wc = math.floor(rb / bytes +) for r = 0, rows - 1 do + local base = off + r * rb + for c = 0, wc - 1 do + for k = 0, bytes - 1 do + writeu8(tmp, (bytes - k - 1) * wc + c, readu8(b, base + c * bytes + k)) + end + end + buffer.copy(b, base, tmp, 0, rb) + for i = base + rb - 1, base + stride, -1 do + writeu8(b, i, band(readu8(b, i) - readu8(b, i - stride), 255)) + end + end +end + +-- ------------------------------------------------------------------------------------------------ samples +local half = Bytes.half + +-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them + + + + + + + + + + + + + + + + + + +local function fast(P) +if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then + return false + end + local b, rb, w, h, spp, alpha, kind, out = P.planes[1], P.rb, P.w, P.h, P.spp, P.alpha, P.kind, P.out + local o = 0 + if P.photo == 2 and spp >= 3 and (kind == "rgba8" or kind == "rgb8") then + local four = kind == "rgba8" + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + writeu8(out, o, readu8(b, p)) + writeu8(out, o + 1, readu8(b, p + 1)) + writeu8(out, o + 2, readu8(b, p + 2)) + if four then + writeu8(out, o + 3, (alpha >= 0 and{(readu8(b, p + alpha) )}or{255})[1]) + o =o+ 4 + else + o =o+ 3 + end + p =p+ spp + end + end + return true + elseif (P.photo == 1 or P.photo == 0) and (kind == "rgba8" or kind == "gray8" or kind == "graya8") then + local inv = P.photo == 0 and 255 or 0 + for y = 0, h - 1 do + local p = y * rb + for _ = 0, w - 1 do + local v = math.abs(inv - readu8(b, p)) + if kind == "gray8" then + writeu8(out, o, v) + o =o+ 1 + elseif kind == "graya8" then + writeu8(out, o, v) + writeu8(out, o + 1, (alpha >= 0 and{(readu8(b, p + alpha) )}or{255})[1]) + o =o+ 2 + else + writeu32(out, o, v * 0x10101 + ((alpha >= 0 and{(readu8(b, p + alpha) )}or{255})[1]) * 0x1000000) + o =o+ 4 + end + p =p+ spp + end + end + return true + end + return false +end + +-- convert(P): every pixel into P.out in P.kind's layout +function Pixels.convert(P) + if fast(P) then + return + end + local planes, rb, chunky, w, h, spp, bps, sfmt, le = P.planes, P.rb, P.chunky, P.w, P.h, P.spp, P.bps, P.sfmt, P.le + local photo, alpha, assoc, cmap, kind, out = P.photo, P.alpha, P.assoc, P.cmap, P.kind, P.out + local maxv = 2 ^ math.min(bps, 32) - 1 + local float = sfmt == 3 + local signed = sfmt == 2 + local cmapN = 2 ^ math.min(bps, 16) + -- raw sample s of pixel x in the row starting at byte ro of its plane + local function raw(s, x, row) +local b, i + if chunky then + b, i = planes[1], x * spp + s + else + b, i = planes[s + 1], x + end + local ro = row * rb + if bps == 8 then + local v = readu8(b, ro + i) + return (signed and(((v + 128) % 256 ))or(v +)) elseif bps == 16 then + local p = ro + i * 2 + local v = (le and{(readu16(b, p) )}or{(readu8(b, p) * 256 + readu8(b, p + 1) +)})[1] if float then + return half(v) + end + return (signed and(((v + 32768) % 65536 ))or(v +)) elseif bps == 32 then + local p = ro + i * 4 + if float then + return f32((le and{(readu32(b, p) )}or{(byteswap(readu32(b, p)))})[1]) + end + local v = (le and{(readu32(b, p) )}or{(byteswap(readu32(b, p)) +)})[1] return (signed and(((v + 2147483648) % 4294967296 ))or(v +)) elseif bps == 64 then + local p = ro + i * 8 + if le then + return f64(readu32(b, p), readu32(b, p + 4)) + end + return f64(byteswap(readu32(b, p + 4)), byteswap(readu32(b, p))) + else + -- any other depth (1..31): MSB-first bit fields + local bit = i * bps + local v = 0 + local need = bps + local p = ro + rshift(bit, 3) + local sh = band(bit, 7) + local cur = band(readu8(b, p), rshift(255, sh)) + local avail = 8 - sh + while need > 0 do + if need >= avail then + v = v * 2 ^ avail + cur + need =need- avail + p =p+ 1 + cur = (need > 0 and{(readu8(b, p) )}or{0 +})[1] avail = 8 + else + v = v * 2 ^ need + rshift(cur, avail - need) + need = 0 + end + end + return v + end + end + -- normalised 0..1 (floats as stored) + local function norm(s, x, row) +local v = raw(s, x, row) + if float then + return v + end + return v / maxv + end + local o = 0 + local is8 = kind == "rgba8" or kind == "rgb8" or kind == "gray8" or kind == "graya8" + local is16 = kind == "rgba16" or kind == "gray16" + local nch = (kind == "rgba8" or kind == "rgba16" or kind == "rgbaf32" )and 4 or(kind == "rgb8" and 3 or(kind == "graya8" and 2 or 1 +)) for y = 0, h - 1 do + for x = 0, w - 1 do + local r, g, bl, a + if photo == 3 then + local idx = raw(0, x, y) + if cmap and idx < cmapN then + r = readu16(cmap, idx * 2) / 65535 + g = readu16(cmap, (cmapN + idx) * 2) / 65535 + bl = readu16(cmap, (2 * cmapN + idx) * 2) / 65535 + else + r, g, bl = 0, 0, 0 + end + elseif photo == 2 then + r = norm(0, x, y) + g = norm(1, x, y) + bl = norm(2, x, y) + elseif photo == 5 then + local c, m, ye, k = norm(0, x, y), norm(1, x, y), norm(2, x, y), norm(3, x, y) + r, g, bl = (1 - c) * (1 - k), (1 - m) * (1 - k), (1 - ye) * (1 - k) + else + local v = norm(0, x, y) + if photo == 0 then + v = 1 - v + end + r, g, bl = v, v, v + end + if alpha >= 0 then + a = norm(alpha, x, y) + if assoc then + if a > 0 then + r = math.min(r / a, 1) + g = math.min(g / a, 1) + bl = math.min(bl / a, 1) + else + r, g, bl = 0, 0, 0 + end + end + else + a = 1 + end + if is8 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + local R = floor(math.clamp(r, 0, 1) * 255 + 0.5) + if nch == 1 then + writeu8(out, o, R) + elseif nch == 2 then + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + else + writeu8(out, o, R) + writeu8(out, o + 1, floor(math.clamp(g, 0, 1) * 255 + 0.5)) + writeu8(out, o + 2, floor(math.clamp(bl, 0, 1) * 255 + 0.5)) + if nch == 4 then + writeu8(out, o + 3, floor(math.clamp(a, 0, 1) * 255 + 0.5)) + end + end + o =o+ nch + elseif is16 then + if r ~= r then + r = 0 + end + if g ~= g then + g = 0 + end + if bl ~= bl then + bl = 0 + end + if a ~= a then + a = 0 + end + writeu16(out, o, floor(math.clamp(r, 0, 1) * 65535 + 0.5)) + if nch == 4 then + writeu16(out, o + 2, floor(math.clamp(g, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 4, floor(math.clamp(bl, 0, 1) * 65535 + 0.5)) + writeu16(out, o + 6, floor(math.clamp(a, 0, 1) * 65535 + 0.5)) + end + o =o+ nch * 2 + else + writef32(out, o, r) + writef32(out, o + 4, g) + writef32(out, o + 8, bl) + writef32(out, o + 12, a) + o =o+ 16 + end + end + end +end + +return Pixels +end +__FILES["image/tim"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation +-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken. +-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit +-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000 +-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when +-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }. +-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image +-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque +-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Tim = { + name = "tim", + category = "image", + extensions = { "tim" }, + mime = { "image/x-tim" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 4, 8, 16, 24 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + +local readu8, readu16, writeu32, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu32, buffer.writeu16, buffer.readu32 +local BPP = { [0] = 4, [1] = 8, [2] = 16, [3] = 24 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Tim.sniff(r) +if r:remaining() < 20 or r:peek(4) ~= "\16\0\0\0" then + return 0 + end + local flags = r:peekU8(4) + if flags > 0x0F or (flags % 8) > 3 or r:peek(3, 5) ~= "\0\0\0" then + return 0 + end + return 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function colour(c) +if c == 0 then + return 0 + end + local r, g, b = c % 32, (math.floor(c / 32)) % 32, (math.floor(c / 1024)) % 32 + r, g, b = r * 8 + math.floor(r / 4), g * 8 + math.floor(g / 4), b * 8 + math.floor(b / 4 +) return 0xFF000000 + b * 65536 + g * 256 + r +end + +function Tim.decode(r, opts) +local magic, flags = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if magic ~= 0x10 then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local pmode = flags % 8 + local bpp = BPP[pmode] + if not bpp then + return nil, Err.new(Err.UNSUPPORTED, "pmode " .. pmode .. " (mixed / unknown)", 4) + end + local stp = false + local pal= nil + local clutInfo= nil + if bit32.band(flags, 8) ~= 0 then + local start = r:tell() + local bnum, cx, cy, cw, ch = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + if bnum < 12 or cw * ch * 2 > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad CLUT block", start) + end + if not r:need(cw * ch * 2) then + return nil, r.err + end + local row = math.clamp(math.floor(opts and opts.clut or 0), 0, math.max(ch - 1, 0)) + pal = buffer.create(256 * 4) + local p = r.pos + row * cw * 2 + for i = 0, math.min(cw, 256) - 1 do + local c = readu16(r.buf, p + i * 2) + if c >= 0x8000 then + stp = true + end + writeu32(pal , i * 4, c == 0x8000 and 0xFF000000 or colour(c % 0x8000)) + end + clutInfo = { x = cx, y = cy, colours = cw, count = ch, row = row } + r:seek(start + bnum) + if r.err then + return nil, r.err + end + elseif bpp <= 8 then + return nil, Err.new(Err.CORRUPT, "indexed image without a CLUT", 4) + end + local start = r:tell() + local bnum, ix, iy, iw, ih = r:u32le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + if r.err then + return nil, r.err + end + local w = (bpp == 4 and((iw * 4 ))or((bpp == 8 and((iw * 2 ))or((bpp == 16 and{iw }or{(math.floor((iw * 2) / 3 +))})[1])))) local stride = iw * 2 + if w * ih > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + if bnum < 12 or stride * ih > bnum - 12 then + return nil, Err.new(Err.CORRUPT, "bad image block", start) + end + if not r:need(stride * ih) then + return nil, r.err + end + local img = Types.Image.new(w, ih) + local px, src, at = img.pixels, r.buf, r.pos + for y = 0, ih - 1 do + local row = at + y * stride + local d = y * w * 4 + if bpp == 4 then + for x = 0, w - 1 do + local v = readu8(src, row + math.floor(x / 2)) + local i = (x % 2 == 0 and((v % 16 ))or((math.floor(v / 16 +)))) writeu32(px, d + x * 4, readu32(pal , i * 4)) + end + elseif bpp == 8 then + for x = 0, w - 1 do + writeu32(px, d + x * 4, readu32(pal , readu8(src, row + x) * 4)) + end + elseif bpp == 16 then + for x = 0, w - 1 do + local c = readu16(src, row + x * 2) + if c >= 0x8000 then + stp = true + end + writeu32(px, d + x * 4, c == 0x8000 and 0xFF000000 or colour(c % 0x8000)) + end + else + for x = 0, w - 1 do + local o = row + x * 3 + writeu32(px, d + x * 4, 0xFF000000 + readu8(src, o + 2) * 65536 + readu8(src, o + 1) * 256 + readu8(src, o)) + end + end + end + img.meta.source = { format = "tim", bpp = bpp, x = ix, y = iy, clut = clutInfo, stp = stp or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- rgba8 pixel -> PSX colour +local function psx(v) +local r, g, b, a = v % 256, (math.floor(v / 256)) % 256, (math.floor(v / 65536)) % 256, math.floor(v / 16777216 +) if a < 128 then + return 0 + end + local c = (math.floor(b / 8)) * 1024 + (math.floor(g / 8)) * 32 + math.floor(r / 8 +) return c == 0 and 0x8000 or c +end + +function Tim.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local w, h = img.width, img.height + local bpp = opts and opts.bpp or 16 + local per = ({ [4] = 4, [8] = 2, [16] = 1, [24] = 2 / 3 } )[bpp] + if not per then + return nil, Err.new(Err.ARG, "bpp must be 4, 8, 16 or 24") + end + local iw = (bpp == 24 and{(math.floor((w * 3 + 1) / 2 ))}or{(math.ceil(w / per) +)})[1] if iw > 0xFFFF or h > 0xFFFF then + return nil, Err.new(Err.ARG, "image too wide for TIM") + end + local px = img.pixels + local out = Bytes.writer(64 + iw * 2 * h) + out:u32le(0x10) + local colours= {} + local index= {} + if bpp <= 8 then + for i = 0, w * h - 1 do + local c = psx(readu32(px, i * 4)) + if not index[c] then + table.insert(colours, c) + index[c] = #colours - 1 + if #colours > (bpp == 4 and 16 or 256) then + return nil, Err.new(Err.ARG, "more than " .. (bpp == 4 and 16 or 256) .. " colours for a " .. bpp .. "-bit TIM") + end + end + end + local n = bpp == 4 and 16 or 256 + out:u32le(8 + (bpp == 4 and 0 or 1)) + out:u32le(12 + n * 2) + out:u16le(opts and opts.clutX or 0) + out:u16le(opts and opts.clutY or 480) + out:u16le(n) + out:u16le(1) + for i = 1, n do + out:u16le(colours[i] or 0) + end + else + out:u32le(bpp == 16 and 2 or 3) + end + out:u32le(12 + iw * 2 * h) + out:u16le(opts and opts.x or 0) + out:u16le(opts and opts.y or 0) + out:u16le(iw) + out:u16le(h) + local at = out:reserve(iw * 2 * h) + local b = out.buf + buffer.fill(b, at, 0, iw * 2 * h) + for y = 0, h - 1 do + local row = at + y * iw * 2 + for x = 0, w - 1 do + local v = readu32(px, (y * w + x) * 4) + if bpp == 4 then + local i = index[psx(v)] + local o = row + math.floor(x / 2 +) buffer.writeu8(b, o, buffer.readu8(b, o) + ((x % 2 == 0 and{i }or{(i * 16)})[1])) + elseif bpp == 8 then + buffer.writeu8(b, row + x, index[psx(v)]) + elseif bpp == 16 then + writeu16(b, row + x * 2, psx(v)) + else + buffer.writeu8(b, row + x * 3, v % 256) + buffer.writeu8(b, row + x * 3 + 1, (math.floor(v / 256)) % 256) + buffer.writeu8(b, row + x * 3 + 2, (math.floor(v / 65536)) % 256) + end + end + end + out.pos = at + iw * 2 * h + return out:finish(), nil +end + +return Tim +end +__FILES["image/vtf"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer +-- Community "VTF (Valve Texture Format)" page; no code taken. +-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail +-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image +-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to +-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure +-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888, +-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through +-- codecs/image/Texel), DXT1 (+ one-bit alpha), +-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips, +-- texel, reflectivity, bumpScale }. +-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Bcn = __include("codecs/image/Bcn") +local Texel = __include("codecs/image/Texel") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtf = { + name = "vtf", + category = "image", + extensions = { "vtf" }, + mime = { "image/x-vtf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Bcn", "codecs/image/Texel" }, + caps = { decode = true, encode = false, alpha = true, animation = true, versions = { "7.0", "7.1", "7.2", "7.3", "7.4", "7.5" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local M = Texel.masked +-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind +local FORMATS= { + [0] = "rgba8", -- RGBA8888 + [1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888 + [2] = "rgb8", -- RGB888 + [3] = "bgr8", -- BGR888 + [4] = "r5g6b5", -- RGB565: red in the low bits (as VTFLib / srctools read it) + [5] = "l8", -- I8 + [6] = "la8", -- IA88 + [8] = "a8", -- A8 + [9] = { texel = "rgb8", bluescreen = true }, -- RGB888_BLUESCREEN + [10] = { texel = "bgr8", bluescreen = true }, -- BGR888_BLUESCREEN + [11] = M(4, 0xFF000000, 0x000000FF, 0x0000FF00, 0x00FF0000), -- ARGB8888: VTFLib's layout (G, B, A, R in memory) + [12] = "bgra8", -- BGRA8888 + [13] = "bc1", -- DXT1 + [14] = "bc2", -- DXT3 + [15] = "bc3", -- DXT5 + [16] = "bgrx8", -- BGRX8888 + [17] = "b5g6r5", -- BGR565: blue in the low bits + [18] = "b5g5r5x1", -- BGRX5551 + [19] = "b4g4r4a4", -- BGRA4444 + [20] = "bc1a", -- DXT1_ONEBITALPHA + [21] = "b5g5r5a1", -- BGRA5551 + [22] = "rg8", -- UV88 + [23] = "rgba8", -- UVWQ8888 + [24] = "rgba16f", -- RGBA16161616F + [25] = "rgba16", -- RGBA16161616 + [26] = "rgba8", -- UVLX8888 + [27] = "r32f", -- R32F + [28] = "rgb32f", -- RGB323232F + [29] = "rgba32f", -- RGBA32323232F + [34] = "bc5", -- ATI2N (Alien Swarm and later) + [35] = "bc4", -- ATI1N (Alien Swarm and later) + [37] = "bc5", -- ATI2N (Source 2013) + [38] = "bc4", -- ATI1N (Source 2013) +} +local BCN= { bc1 = true, bc1a = true, bc2 = true, bc3 = true, bc4 = true, bc5 = true } +local NAMES= { [0] = "RGBA8888", "ABGR8888", "RGB888", "BGR888", "RGB565", "I8", "IA88", "P8", "A8", "RGB888_BLUESCREEN", + "BGR888_BLUESCREEN", "ARGB8888", "BGRA8888", "DXT1", "DXT3", "DXT5", "BGRX8888", "BGR565", "BGRX5551", "BGRA4444", + "DXT1_ONEBITALPHA", "BGRA5551", "UV88", "UVWQ8888", "RGBA16161616F", "RGBA16161616", "UVLX8888", "R32F", "RGB323232F", + "RGBA32323232F", "NV_DST16", "NV_DST24", "NV_INTZ", "NV_RAWZ", "ATI2N", "ATI1N", "NV_NULL", "ATI2N", "ATI1N" } +local ENVMAP = 0x4000 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtf.sniff(r) +return r:peek(4) == "VTF\0" and r:peekU8(4) == 7 and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- bytes of one w x h image in format f +local function imageSize(f, w, h) +if type(f) == "string" and BCN[f] then + return Bcn.size(f == "bc1a" and"bc1" or f, w, h) or 0 + end + return Texel.size((type(f) == "table" and f.texel and{f.texel }or{f})[1], w, h) or 0 +end + +function Vtf.decode(r, opts) +local size = r.limit - r.base + local b, base = r.buf, r.base + if size < 64 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if buffer.readstring(b, base, 4) ~= "VTF\0" then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local major, minor = buffer.readu32(b, base + 4), buffer.readu32(b, base + 8) + if major ~= 7 or minor > 5 then + return nil, Err.new(Err.UNSUPPORTED, "VTF version " .. major .. "." .. minor, 4) + end + local headerSize = buffer.readu32(b, base + 12) + local w, h = buffer.readu16(b, base + 16), buffer.readu16(b, base + 18) + local flags = buffer.readu32(b, base + 20) + local frames, firstFrame = buffer.readu16(b, base + 24), buffer.readu16(b, base + 26) + local refl = { buffer.readf32(b, base + 32), buffer.readf32(b, base + 36), buffer.readf32(b, base + 40) } + local bump = buffer.readf32(b, base + 48) + local fmtId = buffer.readi32(b, base + 52) + local mips = buffer.readu8(b, base + 56) + local lowFmt = buffer.readi32(b, base + 57) + local lowW, lowH = buffer.readu8(b, base + 61), buffer.readu8(b, base + 62) + local depth = (minor >= 2 and size >= 65 and{(math.max(1, buffer.readu16(b, base + 63)) )}or{1 +})[1] if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "zero size", 16) + end + if w * h > (opts and opts.maxPixels or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "image too big") + end + local f= FORMATS[fmtId] + if not f then + return nil, Err.new(Err.UNSUPPORTED, "texel format " .. (NAMES[fmtId] or tostring(fmtId)), 52) + end + frames = math.max(1, frames) + mips = math.max(1, mips) + local faces = 1 + if bit32.band(flags, ENVMAP) ~= 0 then + faces = minor < 5 and firstFrame ~= 0xFFFF and 7 or 6 + end + -- where the high-resolution data starts + local dataAt= nil + if minor >= 3 then + if size < 80 then + return nil, Err.new(Err.TRUNCATED, "resource directory", 68) + end + local nres = buffer.readu32(b, base + 68) + if nres > 32 or 80 + nres * 8 > size then + return nil, Err.new(Err.CORRUPT, "bad resource count", 68) + end + for i = 0, nres - 1 do + local o = base + 80 + i * 8 + if buffer.readu8(b, o) == 0x30 and buffer.readu8(b, o + 1) == 0 and buffer.readu8(b, o + 2) == 0 then + dataAt = buffer.readu32(b, o + 4) + end + end + if not dataAt then + return nil, Err.new(Err.CORRUPT, "no high-resolution image resource", 80) + end + else + local lf = FORMATS[lowFmt] + local lowSize = (lowFmt >= 0 and lowW > 0 and lowH > 0 and lf and{(imageSize(lf, lowW, lowH) )}or{0 +})[1] dataAt = headerSize + lowSize + end + -- the chain: mips smallest first; per mip: frames, faces, slices + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1) + local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1) + local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1) + local off = dataAt +for m = mips - 1, mip + 1, -1 do + local mw, mh, md = math.max(1, math.floor(w / 2 ^ m)), math.max(1, math.floor(h / 2 ^ m)), math.max(1, math.floor(depth / 2 ^ m)) + off =off+ imageSize(f, mw, mh) * md * faces * frames + end + local mw, mh, md = math.max(1, math.floor(w / 2 ^ mip)), math.max(1, math.floor(h / 2 ^ mip)), math.max(1, math.floor(depth / 2 ^ mip)) + local one = imageSize(f, mw, mh) + local function image(frame) +local at = off + ((frame * faces + face) * md + math.min(slice, md - 1)) * one + if at + one > size or at < 0 then + return nil, Err.new(Err.TRUNCATED, "image data past the end", at) + end + local img = Types.Image.new(mw, mh) + if type(f) == "string" and BCN[f] then + local kind = f == "bc1a" and"bc1" or f + local px, e = Bcn.decode(kind, b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if f == "bc1" then + -- plain DXT1 carries no alpha: the transparent colour of 3-colour blocks reads as opaque black + for i = 0, mw * mh - 1 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + end + else + local blue = type(f) == "table" and f.bluescreen == true + local px, e = Texel.decode((blue and{f.texel }or{f})[1], b, base + at, mw, mh) + if not px then + return nil, Err.from(e) + end + buffer.copy(img.pixels, 0, px, 0, mw * mh * 4) + if blue then + -- pure blue is the transparent key + for i = 0, mw * mh - 1 do + if buffer.readu32(img.pixels, i * 4) == 0xFFFF0000 then + buffer.writeu32(img.pixels, i * 4, 0) + end + end + end + end + return img, nil + end + local img, err = image(0) + if not img then + return nil, err + end + if frames > 1 and not (opts and opts.frames == false) then + local delay = opts and opts.delay or 0.1 + local list= { { image = img, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } } + for fr = 1, frames - 1 do + local fi, ferr = image(fr) + if not fi then + return nil, ferr + end + table.insert(list, { image = fi, delay = delay, x = 0, y = 0, dispose = "none", blend = "source" } ) + end + img.frames = list + img.loops = 0 + end + img.meta.source = { + format = "vtf", + version = major .. "." .. minor, + flags = flags, + frames = frames, + faces = faces, + depth = depth, + mips = mips, + texel = NAMES[fmtId], + reflectivity = refl, + bumpScale = bump, + } + return img, nil +end + +return Vtf +end +__FILES["image/webp"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 +-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the +-- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. +-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw +-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the +-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or +-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif +-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and +-- metadata). +-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does), +-- alpha dithering / premultiplied output. +-- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s +-- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1). +-- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vp8 = __include("codecs/image/Vp8") +local Vp8L = __include("codecs/image/Vp8L") +local Riff = __include("containers/Riff") +local Alpha = __include("image/webp/Alpha") +local Anim = __include("image/webp/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local Webp = { + name = "webp", + category = "image", + extensions = { "webp" }, + mime = { "image/webp" }, + 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 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + +local DEFAULT_MAX_PIXELS = 2 ^ 26 +local FLAG_ANIM, FLAG_XMP, FLAG_EXIF, FLAG_ALPHA, FLAG_ICC = 0x02, 0x04, 0x08, 0x10, 0x20 + +local readu8 = buffer.readu8 + +local function u24(buf, p) +return readu8(buf, p) + readu8(buf, p + 1) * 256 + readu8(buf, p + 2) * 65536 +end + +local function corrupt(msg, offset) +return nil, Err.new(Err.CORRUPT, msg, offset) +end + +-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT) +local function fromMessage(msg, offset) +if Err.is(msg) then + return msg + end + local m = tostring(msg) + for _, k in __iter({ { "truncated: ", Err.TRUNCATED }, { "limit: ", Err.LIMIT }, { "unsupported: ", Err.UNSUPPORTED } }) do + if string.sub(m, 1, #k[1]) == k[1] then + return Err.new(k[2], string.sub(m, #k[1] + 1), offset) + end + end + return Err.new(Err.CORRUPT, m, offset) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Webp.sniff(r) +if r:peek(4) == "RIFF" and r:peek(4, 8) == "WEBP" then + return 1 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +local function convert(list) +local out= {} + for _, c in __iter(list) do + if c.truncated then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. c.id .. "' runs past the end", c.offset) + end + table.insert(out, { id = c.id, off = c.offset, size = c.size }) + end + return out, nil +end + +-- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size +-- must fit the data (TRUNCATED) and bytes after it are ignored. +local function readChunks(r) +local buf, base, limit = r.buf, r.base, r.limit + if limit - base < 12 then + return nil, Err.new(Err.TRUNCATED, "RIFF header", base) + end + if buffer.readstring(buf, base, 4) ~= "RIFF" or buffer.readstring(buf, base + 8, 4) ~= "WEBP" then + return nil, Err.new(Err.CORRUPT, "not a RIFF WEBP file", base) + end + local size = buffer.readu32(buf, base + 4) + if size < 12 then + return nil, Err.new(Err.CORRUPT, "RIFF size too small", base + 4) + end + if 8 + size > limit - base then + return nil, Err.new(Err.TRUNCATED, "the RIFF size runs past the end of the data", base + 4) + end + local f, err = Riff.read(Bytes.reader(buf, base, 8 + size)) + if not f then + return nil, err + end + local list, cerr = convert(f.chunks) + if not list then + return nil, cerr + end + return list, f +end + +-- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) +local function subChunks(f, c) +local n = c.size - 12 + return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) +end + +-- the image chunks of a still image or an ANMF frame: the first ALPH (if any) and the first VP8 / VP8L chunk + + +local function findImage(chunks, from) +local alph= nil + for i = from, #chunks do + local c = chunks[i] + if c.id == "ALPH" and not alph then + alph = c + elseif c.id == "VP8 " or c.id == "VP8L" then + return c, alph + elseif c.id == "ANMF" then + break + end + end + return nil, nil +end + +local function decodeBitstream(buf, c, alph, opts, allowNative) +local maxPixels = opts.maxPixels or DEFAULT_MAX_PIXELS + if c.id == "VP8L" then + local rgba, w, h, alphaHint = Vp8L.decode(buf, c.off, c.size, maxPixels) + if not rgba then + return nil, w + end + return { rgba = rgba, w = w, h = h , hasAlpha = alphaHint == true, source = { codec = "vp8l", lossless = true } }, nil + end + local y, u, v, w, h = Vp8.decodePlanes(buf, c.off, c.size, { maxPixels = maxPixels }) + if not y then + return nil, u + end + local fw, fh = w , h +local source= { codec = "vp8", lossless = false } + if allowNative and opts.native and not alph then + local img = Types.Image.new(fw, fh, "yuv420p") + local ny, nc = fw * fh, buffer.len(v ) + buffer.copy(img.pixels, 0, y, 0, ny) + buffer.copy(img.pixels, ny, u, 0, nc) + buffer.copy(img.pixels, ny + nc, v , 0, nc) + return { yuv = img, w = fw, h = fh, hasAlpha = false, source = source }, nil + end + local rgba = Vp8.yuvToRgba(y, u, v , fw, fh, opts.upsampling ~= "nearest") + if alph then + local a, info = Alpha.decode(buf, alph.off, alph.size, fw, fh) + if not a then + return nil, fromMessage(info, alph.off) + end + Vp8.setAlpha(rgba, a, fw * fh) + source.alpha = info + end + return { rgba = rgba, w = fw, h = fh, hasAlpha = alph ~= nil, source = source }, nil +end + +local function collectMeta(buf, chunks, meta) + for _, c in __iter(chunks) do + local key = c.id == "ICCP" and"icc" or(c.id == "EXIF" and"exif" or(c.id == "XMP " and"xmp" or nil +)) if key and meta[key] == nil then + local b = buffer.create(c.size) + buffer.copy(b, 0, buf, c.off, c.size) + meta[key] = b + end + end +end + +function Webp.decode(r, opts) +local o= opts or {} + local maxPixels = o.maxPixels or DEFAULT_MAX_PIXELS + local buf = r.buf + local chunks, file = readChunks(r) + if not chunks then + return nil, file + end + local first = chunks[1] + if not first then + return corrupt("no chunks", r.base + 12) + end + if first.id == "VP8 " or first.id == "VP8L" then + local bs, err = decodeBitstream(buf, first, nil, o, true) + if not bs then + return nil, err + end + local img = bs.yuv or Types.Image.new(bs.w, bs.h, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = false + img.meta.source = bs.source + return img, nil + end + if first.id ~= "VP8X" then + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X", first.off - 8) + end + if first.size < 10 then + return nil, Err.new(Err.TRUNCATED, "VP8X chunk too small", first.off) + end + local flags = readu8(buf, first.off) + local cw = u24(buf, first.off + 4) + 1 + local ch = u24(buf, first.off + 7) + 1 + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d canvas is over the %d pixel limit", cw, ch, maxPixels)) + end + local meta= {} + collectMeta(buf, chunks, meta) + + if bit32.band(flags, FLAG_ANIM) == 0 then + local c, alph = findImage(chunks, 2) + if not c then + return corrupt("no VP8 / VP8L image chunk") + end + local bs, err = decodeBitstream(buf, c, (c.id == "VP8 " and{alph }or{nil})[1], o, true) + if not bs then + return nil, err + end + if bs.w ~= cw or bs.h ~= ch then + return corrupt(string.format("image %d x %d does not match the %d x %d canvas", bs.w, bs.h, cw, ch), c.off) + end + local img = bs.yuv or Types.Image.new(cw, ch, "rgba8") + if bs.rgba then + img.pixels = bs.rgba + end + for k, v in __iter(meta) do + img.meta[k] = v + end + bs.source.format = "webp" + bs.source.bitDepth = 8 + bs.source.extended = true + bs.source.flags = flags + img.meta.source = bs.source + return img, nil + end + + -- animation: ANIM then ANMF frames + local bg, loops = 0, 0 + local haveAnim = false + local frames= {} + local sources= {} + local delays= {} + local wantAll = o.frames ~= false + for i = 2, #chunks do + local c = chunks[i] + if c.id == "ANIM" then + if c.size < 6 then + return nil, Err.new(Err.TRUNCATED, "ANIM chunk too small", c.off) + end + bg = buffer.readu32(buf, c.off) + loops = buffer.readu16(buf, c.off + 4) + haveAnim = true + elseif c.id == "ANMF" then + if not haveAnim then + return corrupt("ANMF before ANIM", c.off) + end + if c.size < 16 then + return nil, Err.new(Err.TRUNCATED, "ANMF chunk too small", c.off) + end + local fx = u24(buf, c.off) * 2 + local fy = u24(buf, c.off + 3) * 2 + local fw = u24(buf, c.off + 6) + 1 + local fh = u24(buf, c.off + 9) + 1 + local dur = u24(buf, c.off + 12) + local fl = readu8(buf, c.off + 15) + if fx + fw > cw or fy + fh > ch then + return corrupt("frame " .. (#frames + 1) .. " lies outside the canvas", c.off) + end + local sub, serr = subChunks(file, c) + if not sub then + return nil, serr + end + local img, alph = findImage(sub, 1) + if not img then + return corrupt("frame " .. (#frames + 1) .. " has no image data", c.off) + end + local bs, err = decodeBitstream(buf, img, (img.id == "VP8 " and{alph }or{nil})[1], o, false) + if not bs then + return nil, err + end + if bs.w ~= fw or bs.h ~= fh then + return corrupt(string.format("frame %d: image %d x %d does not match its ANMF size %d x %d", #frames + 1, bs.w, bs.h, fw, fh), c.off) + end + table.insert(frames, { + rgba = bs.rgba , + x = fx, + y = fy, + w = fw, + h = fh, + blend = bit32.band(fl, 2) == 0, + disposeBg = bit32.band(fl, 1) == 1, + hasAlpha = bs.hasAlpha, + }) + bs.source.hasAlpha = bs.hasAlpha + table.insert(sources, bs.source) + table.insert(delays, dur) + if not wantAll then + break + end + end + end + if #frames == 0 then + return corrupt("animation without frames") + end + local canvases = Anim.coalesce(cw, ch, frames) + local img = Types.Image.new(cw, ch, "rgba8") + img.pixels = canvases[1] + img.loops = loops + for k, v in __iter(meta) do + img.meta[k] = v + end + img.meta.background = { bit32.band(bit32.rshift(bg, 16), 255), bit32.band(bit32.rshift(bg, 8), 255), bit32.band(bg, 255), bit32.rshift(bg, 24) } + img.meta.source = { format = "webp", bitDepth = 8, extended = true, flags = flags, animated = true, codec = sources[1].codec, lossless = sources[1].lossless } + if wantAll then + local list= {} + for i, f in __iter(frames) do + local fi +if o.coalesce then + fi = Types.Image.new(cw, ch, "rgba8") + fi.pixels = canvases[i] + else + fi = Types.Image.new(f.w, f.h, "rgba8") + fi.pixels = f.rgba + end + fi.meta.source = sources[i] + fi.meta.duration = delays[i] + list[i] = { + image = fi, + delay = delays[i] / 1000, + x = o.coalesce and 0 or f.x, + y = o.coalesce and 0 or f.y, + dispose = not o.coalesce and f.disposeBg and"background" or"none", + blend = not o.coalesce and f.blend and"over" or"source", + } + end + img.frames = list + end + return img, nil +end + +-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err +function Webp.info(r) +local chunks, cerr = readChunks(r) + if not chunks then + return nil, cerr + end + local first = chunks[1] + if not first then + return corrupt("no chunks") + end + local buf = r.buf + if first.id == "VP8X" and first.size >= 10 then + local flags = readu8(buf, first.off) + local n = 0 + for _, c in __iter(chunks) do + if c.id == "ANMF" then + n =n+ 1 + end + end + return { + width = u24(buf, first.off + 4) + 1, + height = u24(buf, first.off + 7) + 1, + animated = bit32.band(flags, FLAG_ANIM) ~= 0, + alpha = bit32.band(flags, FLAG_ALPHA) ~= 0, + frames = (n > 0 and{n }or{1})[1], + }, nil + elseif first.id == "VP8L" then + local i, err = Vp8L.info(buf, first.off, first.size) + if not i then + return nil, err + end + return { width = i.width, height = i.height, animated = false, alpha = i.alpha, lossless = true, frames = 1 }, nil + elseif first.id == "VP8 " then + local h, err = Vp8.info(buf, first.off, first.size) + if not h then + return nil, err + end + return { width = h.width, height = h.height, animated = false, alpha = false, lossless = false, frames = 1 }, nil + end + return corrupt("the first chunk is '" .. first.id .. "', not VP8, VP8L or VP8X") +end + +-- ------------------------------------------------------------------------------------------------ encode +local function hasAlpha(px, n) +for i = 0, n - 1 do + if readu8(px, i * 4 + 3) ~= 255 then + return true + end + end + return false +end + +local function validImage(img) +return type(img) == "table" and img.format == "rgba8" and type(img.pixels) == "buffer" and type(img.width) == "number" and type(img.height) == "number" and img.width >= 1 and img.height >= 1 and img.width <= 16384 and img.height <= 16384 and img.width % 1 == 0 and img.height % 1 == 0 and buffer.len(img.pixels) >= img.width * img.height * 4 +end + +local function vp8x(flags, w, h) +local b = Bytes.writer(10) + b:u8(flags) + b:u24le(0) + b:u24le(w - 1) + b:u24le(h - 1) + return b:finish() +end + +local function metaChunk(meta, key) +local v = meta and meta[key] + if type(v) == "buffer" and buffer.len(v) > 0 then + return v + elseif type(v) == "string" and #v > 0 then + return buffer.fromstring(v) + end + return nil +end + +function Webp.encode(img, opts) +local o= opts or {} + if o.lossless == false then + return nil, Err.new(Err.UNSUPPORTED, "lossy WebP encoding is not supported (use lossless)") + end + if not validImage(img) then + return nil, Err.new(Err.ARG, "needs an rgba8 Image (1..16384 pixels a side)") + end + local effort = o.effort or 5 + if type(effort) ~= "number" or effort < 0 or effort > 9 then + return nil, Err.new(Err.ARG, "effort must be 0..9") + end + local vopts= { effort = effort, exact = o.exact } + local w, h = img.width, img.height + local icc, exif, xmp = metaChunk(img.meta, "icc"), metaChunk(img.meta, "exif"), metaChunk(img.meta, "xmp") + local frames = img.frames + local body = Riff.writer("WEBP", { rf64 = false }) + + if not frames or #frames == 0 then + local bits, err = Vp8L.encode(img.pixels, w, h, vopts) + if not bits then + return nil, err + end + if icc or exif or xmp then + local flags = ((icc and{FLAG_ICC }or{0})[1]) + ((exif and{FLAG_EXIF }or{0})[1]) + ((xmp and{FLAG_XMP }or{0})[1]) + if hasAlpha(img.pixels, w * h) then + flags =flags+ FLAG_ALPHA + end + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + body:chunk("VP8L", bits) + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + else + body:chunk("VP8L", bits) + end + return body:finish() + end + + -- animation: frames as they are when WebP can store them (even offsets, dispose none / background), else every + -- frame flattened to a full canvas + local list= {} + local direct = true + for i, f in __iter(frames) do + if type(f) ~= "table" or not validImage(f.image) then + return nil, Err.new(Err.ARG, "frame " .. i .. ": needs an rgba8 image") + end + local fx, fy = f.x or 0, f.y or 0 + local fw, fh = f.image.width, f.image.height + if type(fx) ~= "number" or type(fy) ~= "number" or fx < 0 or fy < 0 or fx % 1 ~= 0 or fy % 1 ~= 0 or fx + fw > w or fy + fh > h then + return nil, Err.new(Err.ARG, "frame " .. i .. ": rectangle outside the canvas") + end + local dispose = f.dispose or "none" + if dispose ~= "none" and dispose ~= "background" and dispose ~= "previous" then + return nil, Err.new(Err.ARG, "frame " .. i .. ": bad dispose " .. tostring(dispose)) + end + if dispose == "previous" or fx % 2 == 1 or fy % 2 == 1 then + direct = false + end + table.insert(list, { + rgba = f.image.pixels, + x = fx, + y = fy, + w = fw, + h = fh, + blend = f.blend == "over", + disposeBg = dispose == "background", + disposePrev = dispose == "previous", + hasAlpha = true, + }) + end + if not direct then + local canvases = Anim.composite(w, h, list) + for i, c in __iter(canvases) do + list[i] = { rgba = c, x = 0, y = 0, w = w, h = h, blend = false, disposeBg = false, hasAlpha = true } + end + end + local anyAlpha = false + for _, f in __iter(list) do + if hasAlpha(f.rgba, f.w * f.h) then + anyAlpha = true + break + end + end + local flags = FLAG_ANIM + ((anyAlpha and{FLAG_ALPHA }or{0})[1]) + ((icc and{FLAG_ICC }or{0})[1]) + ((exif and{FLAG_EXIF }or{0})[1]) + ((xmp and{FLAG_XMP }or{0})[1]) + body:chunk("VP8X", vp8x(flags, w, h)) + if icc then + body:chunk("ICCP", icc) + end + local loops = o.loops or img.loops or 0 + if type(loops) ~= "number" or loops < 0 or loops > 65535 then + return nil, Err.new(Err.ARG, "loops must be 0..65535") + end + local bgc = o.background or (img.meta and img.meta.background) or { 0, 0, 0, 0 } + if type(bgc) ~= "table" then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a }") + end + for k = 1, 4 do + local v = bgc[k] + if v ~= nil and (type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0) then + return nil, Err.new(Err.ARG, "background must be { r, g, b, a } with 0..255 integers") + end + end + local anim = buffer.create(6) + -- the background colour is stored as B, G, R, A + buffer.writeu8(anim, 0, bgc[3] or 0) + buffer.writeu8(anim, 1, bgc[2] or 0) + buffer.writeu8(anim, 2, bgc[1] or 0) + buffer.writeu8(anim, 3, bgc[4] or 0) + buffer.writeu16(anim, 4, loops) + body:chunk("ANIM", anim) + for i, f in __iter(list) do + local bits, err = Vp8L.encode(f.rgba, f.w, f.h, vopts) + if not bits then + return nil, err + end + local delay = frames[i].delay + local ms = (type(delay) == "number" and delay == delay and{(math.clamp(math.floor(delay * 1000 + 0.5), 0, 0xffffff) )}or{100 +})[1] local hdr = Bytes.writer(16 + buffer.len(bits) + 9) + hdr:u24le(math.floor(f.x / 2)) + hdr:u24le(math.floor(f.y / 2)) + hdr:u24le(f.w - 1) + hdr:u24le(f.h - 1) + hdr:u24le(ms) + hdr:u8((f.blend and 0 or 2) + (f.disposeBg and 1 or 0)) + local nb = buffer.len(bits) + hdr:string("VP8L") + hdr:u32le(nb) + hdr:bytes(bits) + if nb % 2 == 1 then + hdr:u8(0) + end + body:chunk("ANMF", hdr.buf, 0, hdr:tell()) + end + if exif then + body:chunk("EXIF", exif) + end + if xmp then + body:chunk("XMP ", xmp) + end + return body:finish() +end + +-- ------------------------------------------------------------------------------------------------ extras +-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way +-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas) +function Webp.coalesce(img) +if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then + return nil + end + local list= {} + for _, f in __iter(img.frames) do + if type(f) ~= "table" or not validImage(f.image) or type(f.x) ~= "number" or type(f.y) ~= "number" or f.x < 0 or f.y < 0 or f.x % 1 ~= 0 or f.y % 1 ~= 0 or f.x + f.image.width > img.width or f.y + f.image.height > img.height then + return nil + end + table.insert(list, { + rgba = f.image.pixels, + x = f.x, + y = f.y, + w = f.image.width, + h = f.image.height, + blend = f.blend == "over", + disposeBg = f.dispose == "background", + hasAlpha = not (f.image.meta.source and f.image.meta.source.hasAlpha == false), + }) + end + return Anim.coalesce(img.width, img.height, list) +end + +return Webp +end +__FILES["image/webp/Alpha"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), +-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / +-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. +local Vp8L = __include("codecs/image/Vp8L") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Alpha = {} + +local function unfilter(a, w, h, filter) + if filter == 0 then + return + end + for y = 0, h - 1 do + local row = y * w + local prev = row - w + if y == 0 or filter == 1 then + -- horizontal (also the first row of the other filters): the left pixel, the first one from above + local pred = y == 0 and 0 or readu8(a, prev) + for i = row, row + w - 1 do + pred = (pred + readu8(a, i)) % 256 + writeu8(a, i, pred) + end + elseif filter == 2 then + for i = 0, w - 1 do + writeu8(a, row + i, (readu8(a, prev + i) + readu8(a, row + i)) % 256) + end + else + local top = readu8(a, prev) + local topLeft, left = top, top + for i = 0, w - 1 do + top = readu8(a, prev + i) + local g = left + top - topLeft + g = g < 0 and 0 or(g > 255 and 255 or g +) left = (readu8(a, row + i) + g) % 256 + topLeft = top + writeu8(a, row + i, left) + end + end + end +end + +-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message +function Alpha.decode(buf, off, len, w, h) +if len <= 1 then + return nil, "truncated: ALPH chunk" + end + local hb = readu8(buf, off) + local method = hb % 4 + local filter = (math.floor(hb / 4)) % 4 + local pre = (math.floor(hb / 16)) % 4 + if method > 1 or pre > 1 or hb >= 64 then + return nil, "bad ALPH header" + end + local a +if method == 0 then + if len - 1 < w * h then + return nil, "truncated: raw alpha" + end + a = buffer.create(w * h) + buffer.copy(a, 0, buf, off + 1, w * h) + else + local d, err = Vp8L.decodeAlpha(buf, off + 1, len - 1, w, h) + if not d then + local e = err +return nil, (e.code == "TRUNCATED" and(("truncated: alpha " .. e.message ))or(("alpha: " .. e.message +))) end + a = d + end + unfilter(a, w, h, filter) + return a, { method = method, filter = filter, preprocessing = pre } +end + +return Alpha +end +__FILES["image/webp/Anim"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +--!native +-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c, +-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour +-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha +-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the +-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws. +local band, rshift = bit32.band, bit32.rshift +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill + +local Anim = {} + +-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult) + + + + + + + + + + + + +local function blendPixel(src, dst) +local sa = rshift(src, 24) + if sa == 0 then + return dst + end + local da = rshift(dst, 24) + local dfa = rshift(da * (256 - sa), 8) + local ba = sa + dfa + local scale = math.floor(16777216 / ba +) local r = math.floor(((band(src, 255) * sa + band(dst, 255) * dfa) * scale) / 16777216 +) local g = math.floor(((band(rshift(src, 8), 255) * sa + band(rshift(dst, 8), 255) * dfa) * scale) / 16777216 +) local b = math.floor(((band(rshift(src, 16), 255) * sa + band(rshift(dst, 16), 255) * dfa) * scale) / 16777216 +) return r + g * 256 + b * 65536 + ba * 16777216 +end +Anim.blendPixel = blendPixel + +-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets) +local function blendRow(cur, prev, o, n) + for i = o, o + n - 1 do + local s = readu32(cur, i * 4) + if s < 0xff000000 then + writeu32(cur, i * 4, blendPixel(s, readu32(prev, i * 4))) + end + end +end + +-- draw(canvas, cw, f): copy the frame rectangle into the canvas +local function draw(canvas, cw, f) + for j = 0, f.h - 1 do + bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4) + end +end + +local function clearRect(canvas, cw, x, y, w, h) + for j = 0, h - 1 do + bfill(canvas, ((y + j) * cw + x) * 4, 0, w * 4) + end +end + +-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them +function Anim.coalesce(cw, ch, frames) +local size = cw * ch * 4 + local out= {} + local disposed = bcreate(size) + local prev= nil + local prevKey = false + for n, f in __iter(frames) do + local full = f.w == cw and f.h == ch + local key + if n == 1 then + key = true + elseif (not f.hasAlpha or not f.blend) and full then + key = true + else + local p = prev +key = p.disposeBg and ((p.w == cw and p.h == ch) or prevKey) + end + local cur = bcreate(size) + if not key then + bcopy(cur, 0, disposed, 0, size) + end + draw(cur, cw, f) + if n > 1 and f.blend and not key then + local p = prev +if not p.disposeBg then + for j = 0, f.h - 1 do + blendRow(cur, disposed, (f.y + j) * cw + f.x, f.w) + end + else + -- the previous rectangle was cleared: blending with transparent there is a no-op for libwebp + local pmx, pmy = p.x + p.w, p.y + p.h + local smx = f.x + f.w + for j = 0, f.h - 1 do + local cy = f.y + j + if cy < p.y or cy >= pmy or f.x >= pmx or smx <= p.x then + blendRow(cur, disposed, cy * cw + f.x, f.w) + else + if f.x < p.x then + blendRow(cur, disposed, cy * cw + f.x, p.x - f.x) + end + if smx > pmx then + blendRow(cur, disposed, cy * cw + pmx, smx - pmx) + end + end + end + end + end + table.insert(out, cur) + prev = f + prevKey = key + bcopy(disposed, 0, cur, 0, size) + if f.disposeBg then + clearRect(disposed, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or +-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle; +-- previous: restore) +function Anim.composite(cw, ch, frames) +local size = cw * ch * 4 + local canvas = bcreate(size) + local out= {} + for _, f in __iter(frames) do + local saved= nil + if f.disposePrev then + saved = bcreate(size) + bcopy(saved , 0, canvas, 0, size) + end + if f.blend then + for j = 0, f.h - 1 do + local co = (f.y + j) * cw + f.x + for i = 0, f.w - 1 do + local s = readu32(f.rgba, (j * f.w + i) * 4) + local d = readu32(canvas, (co + i) * 4) + writeu32(canvas, (co + i) * 4, ((s >= 0xff000000 or d < 0x01000000 )and{s }or{(blendPixel(s, d))})[1]) + end + end + else + draw(canvas, cw, f) + end + local shown = bcreate(size) + bcopy(shown, 0, canvas, 0, size) + table.insert(out, shown) + if saved then + canvas = saved + elseif f.disposeBg then + clearRect(canvas, cw, f.x, f.y, f.w, f.h) + end + end + return out +end + +return Anim +end +__FILES["image/xbm"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height +-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, +-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below +-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Xbm = { + name = "xbm", + category = "image", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function Xbm.sniff(r) +local s = Sniff.text(r, 256, true) + if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xbm.decode(r, opts) +local n = r.limit - r.base + if n > 2 ^ 26 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local s = buffer.readstring(r.buf, r.base, n) + local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)")) + local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)")) + if not w or not h or w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "missing width / height defines") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local brace = string.find(s, "{", 1, true) + if not brace then + return nil, Err.new(Err.CORRUPT, "missing bits array") + end + local decl = string.sub(s, 1, brace) + local short = string.find(decl, "short", 1, true) ~= nil + local unit = short and 16 or 8 + local per = math.floor((w + unit - 1) / unit +) local want = per * h + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local clear = opts and opts.transparent and 0x00FFFFFF or 0xFFFFFFFF + local got = 0 + local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ") + for tok in __iter(string.gmatch(body, "[%w]+")) do + if got >= want then + break + end + local v + if string.match(tok, "^0[xX]%x+$") then + v = tonumber(string.sub(tok, 3), 16) + elseif string.match(tok, "^0%d+$") then + v = tonumber(tok, 8) + elseif string.match(tok, "^%d+$") then + v = tonumber(tok) + end + if v then + local y, cx = math.floor(got / per), (got % per) * unit + for k = 0, unit - 1 do + local x = cx + k + if x < w then + buffer.writeu32(px, (y * w + x) * 4, bit32.band(bit32.rshift(v, k), 1) == 1 and 0xFF000000 or clear) + end + end + got =got+ 1 + end + end + if got < want then + for i = got * unit, want * unit - 1 do + local y, x = math.floor(i / (per * unit)), i % (per * unit) + if x < w then + buffer.writeu32(px, (y * w + x) * 4, clear) + end + end + img.meta.truncated = true + end + local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)")) + local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)")) + if hx and hy then + img.meta.hotspot = { x = hx, y = hy } + end + local name = string.match(s, "#define%s+([%w_]-)_?width%s") + img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xbm.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local th = opts and opts.threshold or 128 + local px = img.pixels + local parts = { + string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h), + } + local hs= img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y)) + end + table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name)) + local per = math.floor((w + 7) / 8 +) local bytes = {} + for y = 0, h - 1 do + for bx = 0, per - 1 do + local v = 0 + for k = 0, 7 do + local x = bx * 8 + k + if x < w then + local o = (y * w + x) * 4 + local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2) + if lum < th and buffer.readu8(px, o + 3) >= 128 then + v =v+ bit32.lshift(1, k) + end + end + end + table.insert(bytes, string.format("0x%02x", v)) + end + end + for i = 1, #bytes, 12 do + table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (i + 11 < #bytes and",\n" or" };\n")) + end + return buffer.fromstring(table.concat(parts)), nil +end + +return Xbm +end +__FILES["image/xpm"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: +-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / +-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour +-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in +-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, +-- the fewest chars per pixel; opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Names = __include("image/xpm/Names") + +-- ------------------------------------------------------------------------------------------------ contract +local Xpm = { + name = "xpm", + category = "image", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- the characters of pixel codes (printable ASCII without '"' and '\') + + + + + + + + +local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|" + +-- ------------------------------------------------------------------------------------------------ sniff +function Xpm.sniff(r) +local s = Sniff.text(r, 64, true) + if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colour value -> rgba8 u32, or nil for an unknown name +local function colour(v) +local l = string.lower(v) + if l == "none" or l == "transparent" then + return 0 + end + if string.sub(v, 1, 1) == "#" then + local hex = string.sub(v, 2) + local n = #hex + if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then + return nil + end + local k = math.floor(n / 3 +) local mx = 16 ^ k - 1 + local c = 0 + for i = 0, 2 do + local x = (tonumber(string.sub(hex, i * k + 1, i * k + k), 16) ) +c =c+ math.floor(x * 255 / mx + 0.5) * 256 ^ i + end + return c + 0xFF000000 + end + local rgb = Names.lookup(l) + return (rgb and((rgb + 0xFF000000 ))or(nil +))end + +-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) +local function strings(s) +local out = {} + if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then + local first = true + for line in __iter(string.gmatch(s, "[^\n]+")) do + if first then + first = false + else + table.insert(out, (string.gsub(line, "\r$", ""))) + end + end + return out + end + local i, n = 1, #s + while i <= n do + local c = string.sub(s, i, i) + if c == "/" and string.sub(s, i + 1, i + 1) == "*" then + local e = string.find(s, "*/", i + 2, true) + i = (e and((e + 2 ))or((n + 1 +))) elseif c == '"' then + local parts = {} + local j = i + 1 + while j <= n do + local d = string.sub(s, j, j) + if d == "\\" then + table.insert(parts, string.sub(s, j + 1, j + 1)) + j =j+ 2 + elseif d == '"' then + break + else + local e = string.find(s, '["\\]', j) + local stop = (e or n + 1) - 1 + table.insert(parts, string.sub(s, j, stop)) + j = stop + 1 + end + end + table.insert(out, table.concat(parts)) + i = j + 1 + else + i =i+ 1 + end + end + return out +end + +local KEYS = { c = true, m = true, g4 = true, g = true, s = true } + +function Xpm.decode(r, opts) +local n = r.limit - r.base + if n > 2 ^ 27 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local list = strings(buffer.readstring(r.buf, r.base, n)) + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XPM strings") + end + local vals= {} + for tok in __iter(string.gmatch(list[1], "%S+")) do + table.insert(vals, tonumber(tok) or -1) + end + local w, h, nc, cpp= vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1 + if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad values line") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels or nc > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + if #list < 1 + nc then + return nil, Err.new(Err.TRUNCATED, "colour table runs past the end") + end + local map= {} + local unknown= {} + local palette= {} + for i = 1, nc do + local line = list[1 + i] + local code = string.sub(line, 1, cpp) + local rest = string.sub(line, cpp + 1) + local found= {} + local key= nil + local acc = {} + for tok in __iter(string.gmatch(rest, "%S+")) do + if KEYS[tok] and (key == nil or #acc > 0) then + if key then + found[key] = table.concat(acc, " ") + end + key, acc = tok, {} + else + table.insert(acc, tok) + end + end + if key then + found[key] = table.concat(acc, " ") + end + local v = found.c or found.g or found.g4 or found.m + local c = (v and{(colour(v) )}or{nil +})[1] if v and not c then + c = colour((string.gsub(v, " ", ""))) + end + local cv= c or 0xFF000000 + if not c then + table.insert(unknown, v or "") + end + c = cv + map[code] = cv + palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) } + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local truncated = false + for y = 0, h - 1 do + local row = list[2 + nc + y] + if not row then + truncated = true + break + end + for x = 0, w - 1 do + local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)] + buffer.writeu32(px, (y * w + x) * 4, c or 0) + end + end + if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then + img.meta.hotspot = { x = vals[5], y = vals[6] } + end + if #unknown > 0 then + img.meta.unknownColours = unknown + end + if truncated then + img.meta.truncated = true + end + img.meta.palette = palette + img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xpm.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name + end + local px = img.pixels + local index= {} + local order= {} + local keys = table.create(w * h, 0) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + local k = v < 0x80000000 and-1 or bit32.band(v, 0xFFFFFF) + if not index[k] then + table.insert(order, k) + index[k] = #order + end + keys[i + 1] = index[k] + end + local nchars = #CODE_CHARS + local cpp = 1 + while nchars ^ cpp < #order do + cpp =cpp+ 1 + end + local codes= {} + for i = 1, #order do + local v, s = i - 1, "" + for _ = 1, cpp do + local d = v % nchars + s =s.. string.sub(CODE_CHARS, d + 1, d + 1) + v =math.floor(v/ nchars +) end + codes[i] = s + end + local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) } + local hs= img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y)) + else + table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp)) + end + for i, k in __iter(order) do + local col = k < 0 and"None" or string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16)) + table.insert(parts, string.format('"%s c %s",\n', codes[i], col)) + end + for y = 0, h - 1 do + local row = table.create(w, "") + for x = 0, w - 1 do + row[x + 1] = codes[keys[y * w + x + 1] ] + end + table.insert(parts, '"' .. table.concat(row) .. '"' .. (y < h - 1 and",\n" or"\n")) + end + table.insert(parts, "};\n") + return buffer.fromstring(table.concat(parts)), nil +end + +return Xpm +end +__FILES["image/xpm/Names"] = function() +local __compat = __compat local bit32 = __compat.bit32 --!strict +-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's +-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. +-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +local Names = {} + +local HEX= { + aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF, + beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF, + blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00, + chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C, + cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9, + darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F, + darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F, + darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1, + darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF, + gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE, + green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4, + indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA, + lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080, + lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90, + lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA, + lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0, + lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060, + mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB, + mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC, + mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5, + navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23, + orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98, + paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F, + pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000, + rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460, + seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB, + slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F, + steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0, + violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, +} + +-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) +function Names.lookup(name) +local v = HEX[name] + if v then + return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536 + end + local n = string.match(name, "^gr[ae]y(%d+)$") + if n then + local k = (tonumber(n) ) +if k <= 100 then + local g = math.floor(k * 255 / 100 + 0.49) + return g * 0x10101 + end + end + return nil +end + +return Names +end +__FILES["layered/aseprite"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- layered/aseprite: Aseprite .ase / .aseprite sprites (aseprite docs/ase-file-specs.md, v1.3). Supports: RGBA, +-- grayscale and indexed sprites (to rgba8; the transparent index is clear except on background layers); every +-- frame (duration -> delay); layers (normal and group, child levels -> a tree; visibility, blend mode, opacity, +-- flags, UUIDs skipped; a group of normal blend at full opacity is "passThrough"); cels (raw, zlib-compressed, linked: a linked cel shares the Image of the frame it points to +-- and records `link`), cel opacity (-> the leaf's fillOpacity), z-index; the palette (new 0x2019 chunk and the old +-- 0x0004 / 0x0011 ones; entry names), tags (meta.tags, frames 1-based), user data text / colour on layers, cels and +-- tags, the pixel ratio and grid. A Layered value: layers = frame 1's tree, frames[i] = { layers = frame i's tree, +-- delay }. +-- Encode: RGBA (or grayscale / indexed when opts.depth or meta.colorDepth asks and the pixels fit), one layer chunk +-- per node of frame 1's tree, zlib cels, linked cels where a frame reuses an earlier frame's Image at the same place, +-- palette, tags. +-- Not supported: tilemap layers / tilesets (skipped: meta.skipped counts them), slices, external files, colour +-- profiles (sRGB assumed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") + +-- ------------------------------------------------------------------------------------------------ contract +local Aseprite = { + name = "aseprite", + category = "layered", + extensions = { "aseprite", "ase" }, + mime = { "image/x-aseprite" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local BLENDS = { [0] = "normal", "multiply", "screen", "overlay", "darken", "lighten", "colorDodge", "colorBurn", "hardLight", "softLight", "difference", "exclusion", "hue", "saturation", "color", "luminosity", "linearDodge", "subtract", "divide" } +local BLEND_IDS= {} +for k, v in __iter(BLENDS) do + BLEND_IDS[v] = k +end +BLEND_IDS.add = 16 +BLEND_IDS.passThrough = 0 +local DIRECTIONS = { [0] = "forward", "reverse", "pingpong", "pingpongReverse" } +local DIRECTION_IDS = { forward = 0, reverse = 1, pingpong = 2, pingpongReverse = 3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Aseprite.sniff(r) +if r:peekU8(4) == 0xE0 and r:peekU8(5) == 0xA5 then + local d = r:peekU8(12) + if (d == 32 or d == 16 or d == 8) and r:peekU8(13) == 0 then + return 1 + end + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r) +return r:string(r:u16le()) +end + +-- cel pixels (depth bytes per pixel) -> rgba8 +local function toRGBA(src, so, n, depth, palette, transparent, background) +local out = buffer.create(n * 4) + if depth == 32 then + buffer.copy(out, 0, src, so, n * 4) + elseif depth == 16 then + for i = 0, n - 1 do + local v, a = buffer.readu8(src, so + i * 2), buffer.readu8(src, so + i * 2 + 1) + buffer.writeu32(out, i * 4, v + v * 256 + v * 65536 + a * 16777216) + end + else + for i = 0, n - 1 do + local k = buffer.readu8(src, so + i) + local c = buffer.readu32(palette, k * 4) + if k == transparent and not background then + c = 0 + end + buffer.writeu32(out, i * 4, c) + end + end + return out +end + + + +function Aseprite.decode(r, opts) +local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local maxFrames = opts and opts.maxFrames or 65535 + if r:size() < 128 then + return nil, Err.new(Err.TRUNCATED, "header needs 128 bytes", r.pos) + end + r:skip(4) + if r:u16le() ~= 0xA5E0 then + return nil, Err.new(Err.CORRUPT, "bad magic", r.pos - 2) + end + local nframes, w, h, depth = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local hflags = r:u32le() + r:skip(2 + 8) + local transparent = r:u8() + r:skip(3) + local ncolors = r:u16le() + local pw, ph = r:u8(), r:u8() + local gx, gy, gw, gh = r:i16le(), r:i16le(), r:u16le(), r:u16le() + r:seek(128) + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.CORRUPT, "bad colour depth " .. depth) + end + if w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "bad size") + end + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the pixel limit", w, h)) + end + if nframes > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames") + end + local bpp = math.floor(depth / 8 +) local palette = buffer.create(1024) + local palList= {} + local palNames= {} + local infos= {} + local tags= {} + local frames= {} + local skipped = 0 + local lastUser= nil -- the object the next user data chunk belongs to + local tagUser = 0 -- tags waiting for their user data chunks + for fi = 1, nframes do + local fstart = r.pos + local fbytes = r:u32le() + local fmagic = r:u16le() + local oldChunks = r:u16le() + local duration = r:u16le() + r:skip(2) + local newChunks = r:u32le() + if r.err then + return nil, r.err + end + if fmagic ~= 0xF1FA then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": bad magic", fstart + 4) + end + if fbytes < 16 or fstart + fbytes > r.limit then + return nil, Err.new(Err.TRUNCATED, "frame " .. fi .. " runs past the end", fstart) + end + local nchunks = (newChunks ~= 0 and{newChunks }or{oldChunks +})[1] local frame = { cels = {}, delay = duration / 1000 } + frames[fi] = frame + local fr = Bytes.reader(r.buf, r.pos, fstart + fbytes - r.pos) + for _ = 1, nchunks do + if fr:remaining() < 6 then + break + end + local cstart = fr.pos + local csize = fr:u32le() + local ctype = fr:u16le() + if csize < 6 or cstart + csize > fr.limit then + return nil, Err.new(Err.CORRUPT, string.format("frame %d: chunk 0x%04x size %d", fi, ctype, csize), cstart) + end + local c = Bytes.reader(fr.buf, cstart + 6, csize - 6) + fr.pos = cstart + csize + if ctype == 0x2004 then + local info= { flags = c:u16le(), type = c:u16le(), level = c:u16le(), name = "", blend = 0, opacity = 255 } + c:skip(4) + info.blend = c:u16le() + info.opacity = c:u8() + c:skip(3) + info.name = str(c) + if c.err then + return nil, c.err + end + if info.type == 2 then + skipped =skipped+ 1 + end + table.insert(infos, info) + lastUser = info + elseif ctype == 0x2005 then + local li = c:u16le() + local x, y = c:i16le(), c:i16le() + local op = c:u8() + local ctyp = c:u16le() + local z = c:i16le() + c:skip(5) + if c.err then + return nil, c.err + end + local cel= { x = x, y = y, opacity = op, z = z } + if ctyp == 0 or ctyp == 2 then + local cw, ch = c:u16le(), c:u16le() + if c.err then + return nil, c.err + end + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "cel over the pixel limit") + end + local n = cw * ch + local raw, ro +if ctyp == 0 then + if not c:need(n * bpp) then + return nil, c.err + end + raw, ro = c.buf, c.pos + else + local z2, zerr = Deflate.zlib(c.buf, c.pos, c.limit - c.pos, n * bpp) + if not z2 then + -- some writers leave padding after the stream: inflate without the exact size + local loose = Deflate.zlib(c.buf, c.pos, c.limit - c.pos) + if not loose or buffer.len(loose) < n * bpp then + return nil, Err.new(Err.CORRUPT, "frame " .. fi .. ": cel data: " .. tostring(zerr and zerr.message), c.pos) + end + z2 = loose + end + raw, ro = z2 , 0 + end + cel.w, cel.h, cel.raw, cel.ro = cw, ch, raw, ro + elseif ctyp == 1 then + cel.link = c:u16le() + 1 + else + cel.skip = true -- tilemap cel + end + frame.cels[li + 1] = cel + lastUser = cel + elseif ctype == 0x2018 then + local n = c:u16le() + c:skip(8) + tagUser = 0 + for _ = 1, n do + local from, to = c:u16le(), c:u16le() + local dir = c:u8() + local rep = c:u16le() + c:skip(6) + local cr, cg, cb = c:u8(), c:u8(), c:u8() + c:skip(1) + local name = str(c) + if c.err then + return nil, c.err + end + table.insert(tags, { name = name, from = from + 1, to = to + 1, direction = DIRECTIONS[dir] or "forward", ["repeat"] = rep, color = { cr, cg, cb } }) + tagUser =tagUser+ 1 + end + lastUser = nil + elseif ctype == 0x2019 then + local size = c:u32le() + local first, last = c:u32le(), c:u32le() + c:skip(8) + if first > last or last > 255 or size > 256 then + return nil, Err.new(Err.CORRUPT, "bad palette range", cstart) + end + for k = first, last do + local f = c:u16le() + local cr, cg, cb, ca = c:u8(), c:u8(), c:u8(), c:u8() + if bit32.band(f, 1) ~= 0 then + palNames[k + 1] = str(c) + end + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + ca * 16777216) + palList[k + 1] = { cr, cg, cb, ca } + end + for k = #palList + 1, size do + palList[k] = { 0, 0, 0, 255 } + end + if c.err then + return nil, c.err + end + elseif (ctype == 0x0004 or ctype == 0x0011) and #palList == 0 then + -- old palettes (used when there is no 0x2019 chunk): packets of (skip, count) entries of RGB + local packets = c:u16le() + local k = 0 + for _ = 1, packets do + k =k+ c:u8() + local n = c:u8() + if n == 0 then + n = 256 + end + for _ = 1, n do + local cr, cg, cb = c:u8(), c:u8(), c:u8() + if ctype == 0x0011 then + cr, cg, cb = math.floor(cr * 255 / 63), math.floor(cg * 255 / 63), math.floor(cb * 255 / 63 +) end + if k < 256 then + buffer.writeu32(palette, k * 4, cr + cg * 256 + cb * 65536 + 0xFF000000) + end + k =k+ 1 + end + end + if c.err then + return nil, c.err + end + for i = 0, math.min(k, 256) - 1 do + local v = buffer.readu32(palette, i * 4) + palList[i + 1] = { v % 256, math.floor(v / 256 )% 256, math.floor(v / 65536 )% 256, 255 } + end + palList = table.move(palList, 1, math.min(k, 256), 1, {}) + elseif ctype == 0x2020 then + local f = c:u32le() + local ud= {} + if bit32.band(f, 1) ~= 0 then + ud.text = str(c) + end + if bit32.band(f, 2) ~= 0 then + ud.color = { c:u8(), c:u8(), c:u8(), c:u8() } + end + if not c.err then + if tagUser > 0 then + -- after a tags chunk, user data chunks follow for each tag in order + local t = tags[#tags - tagUser + 1] + if t then + t.userData = ud + end + tagUser =tagUser- 1 + elseif lastUser then + lastUser.userData = ud + end + end + end + -- others (colour profile, slices, tilesets, external files, cel extras, masks, paths) are skipped + end + r.pos = fstart + fbytes + end + local _ = ncolors + -- the layer tree of one frame + local function build(fi) +local root= {} + local stack= { root } -- stack[level + 1] = the children list at that level + for li, info in __iter(infos) do + local level = math.min(info.level, #stack - 1) + local list = stack[level + 1] + local l= { + name = info.name, + x = 0, + y = 0, + opacity = ((bit32.band(hflags, 1) ~= 0 or info.type ~= 0 )and((info.opacity / 255 ))or(1)), + blend = BLENDS[info.blend] or "normal", + visible = bit32.band(info.flags, 1) ~= 0, + flags = info.flags, + } + if info.userData then + l.userData = info.userData + end + if info.type == 1 then + l.image = Types.Image.new(0, 0) + l.children = {} + -- Aseprite renders a group straight onto the backdrop unless it has its own blend mode / opacity (then + -- into a buffer of its own): pass-through vs isolated + if bit32.band(hflags, 2) == 0 or (info.blend == 0 and info.opacity == 255) then + l.blend = "passThrough" + l.opacity = 1 + end + table.insert(list, l) + -- deeper layers go into this group + for k = #stack, level + 2, -1 do + stack[k] = nil + end + stack[level + 2] = l.children + else + for k = #stack, level + 2, -1 do + stack[k] = nil + end + l.image = Types.Image.new(0, 0) + if info.type == 2 then + l.tilemap = true + end + local cel = frames[fi].cels[li] + local guard = 0 + while cel and cel.link and guard < 8 do -- follow links (one hop in valid files) + l.link = cel.link + local target = frames[cel.link] + cel = (target and{target.cels[li] }or{nil +})[1] guard =guard+ 1 + end + if cel and cel.image then + l.image = cel.image + l.x, l.y = cel.x, cel.y + if cel.opacity < 255 then + l.fillOpacity = cel.opacity / 255 + end + if cel.z ~= 0 then + l.zIndex = cel.z + end + if cel.userData then + l.celUserData = cel.userData + end + end + table.insert(list, l) + end + end + return root + end + -- cel images (shared by linked cels) + for _, f in __iter(frames) do + for li, cel in pairs(f.cels) do -- sparse: pairs, not ipairs-style iteration + if cel.raw then + local info = infos[li] + local img = Types.Image.new(cel.w, cel.h) + img.pixels = toRGBA(cel.raw, cel.ro, cel.w * cel.h, depth, palette, transparent, info ~= nil and bit32.band(info.flags, 8) ~= 0) + cel.image = img + cel.raw = nil + end + end + end + local layered = Types.Layered.new(w, h) + local list = {} + for fi = 1, nframes do + list[fi] = { layers = build(fi), delay = frames[fi].delay } + end + if nframes > 0 then + layered.layers = list[1].layers + end + layered.frames = list + if #palList > 0 then + layered.meta.palette = palList + if next(palNames) then + layered.meta.paletteNames = palNames + end + end + layered.meta.tags = tags + layered.meta.colorDepth = depth + layered.meta.transparentIndex = transparent + layered.meta.pixelRatio = { pw == 0 and 1 or pw, ph == 0 and 1 or ph } + layered.meta.grid = { gx, gy, gw, gh } + if skipped > 0 then + layered.meta.skipped = skipped + end + layered.meta.source = { format = "aseprite", bitDepth = depth, colorType = depth == 32 and"rgba" or(depth == 16 and"graya" or"indexed" )} + return layered, nil +end +-- ------------------------------------------------------------------------------------------------ encode + + + +local function isImage(v) +return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and v.width < 65536 and v.height < 65536 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +-- the nodes of a tree in file order (a group, then its children one level deeper) +local function nodes(layers, level, out) +for _, l in __iter(layers) do + if type(l) ~= "table" or level > 64 then + return false + end + table.insert(out, { layer = l, level = level }) + if type(l.children) == "table" then + if not nodes(l.children, level + 1, out) then + return false + end + end + end + return true +end + +local function writeStr(w, s) + local n = math.min(#s, 65535) + w:u16le(n) + w:string(string.sub(s, 1, n)) +end + +function Aseprite.encode(layered, opts) +if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 65535 or H > 65535 then + return nil, Err.new(Err.ARG, "bad sprite size") + end + local meta= (type(layered.meta) == "table" and{layered.meta }or{{} +})[1] local level = opts and opts.level or 6 + -- frames: the layered frames, or one frame of the layers + local frameList= (type(layered.frames) == "table" and #layered.frames > 0 and{layered.frames }or{{ { layers = layered.layers, delay = 0.1 } } +})[1] local struct= {} + if not nodes(frameList[1].layers, 0, struct) then + return nil, Err.new(Err.ARG, "bad layer tree") + end + if #struct > 65535 or #frameList > 65535 then + return nil, Err.new(Err.ARG, "too many layers / frames") + end + local perFrame= {} + for fi, f in __iter(frameList) do + if type(f) ~= "table" or type(f.layers) ~= "table" then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": no layers") + end + local ns= {} + if not nodes(f.layers, 0, ns) or #ns ~= #struct then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + for k, n in __iter(ns) do + if (type(n.layer.children) == "table") ~= (type(struct[k].layer.children) == "table") then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": its layer tree differs from frame 1's") + end + if type(n.layer.children) ~= "table" and not isImage(n.layer.image) then + return nil, Err.new(Err.ARG, "frame " .. fi .. ": layer " .. tostring(n.layer.name) .. " needs an rgba8 image") + end + end + perFrame[fi] = ns + end + -- the colour depth: requested, or the source's when every pixel fits + local depth = opts and opts.depth or meta.colorDepth or 32 + local explicit = opts ~= nil and opts.depth ~= nil + if depth ~= 32 and depth ~= 16 and depth ~= 8 then + return nil, Err.new(Err.ARG, "depth must be 32, 16 or 8") + end + local palette= (type(meta.palette) == "table" and{meta.palette }or{{} +})[1] local transparent = (type(meta.transparentIndex) == "number" and{meta.transparentIndex }or{0 +})[1] local index= {} + for k = #palette, 1, -1 do + local c = palette[k] + if type(c) == "table" then + index[(c[1] or 0) + (c[2] or 0) * 256 + (c[3] or 0) * 65536 + (c[4] or 255) * 16777216] = k - 1 + end + end + if depth ~= 32 then + local fits = depth ~= 8 or #palette > 0 + for _, ns in __iter(perFrame) do + for _, n in __iter(ns) do + local img = n.layer.image + if fits and type(n.layer.children) ~= "table" then + local px = img.pixels + for i = 0, img.width * img.height - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + local r, g, b = v % 256, math.floor(v / 256 )% 256, math.floor(v / 65536 )% 256 + if r ~= g or g ~= b then + fits = false + break + end + elseif math.floor(v / 16777216 )~= 0 and index[v] == nil then + fits = false + break + end + end + end + end + end + if not fits then + if explicit then + return nil, Err.new(Err.ARG, "the pixels do not fit depth " .. depth .. (depth == 8 and" with meta.palette" or"")) + end + depth = 32 + end + end + local bpp = math.floor(depth / 8 +) local function pixels(n) +local img = n.layer.image + local count = img.width * img.height + if depth == 32 then + return img.pixels + end + local out = buffer.create(count * bpp) + local px = img.pixels + for i = 0, count - 1 do + local v = buffer.readu32(px, i * 4) + if depth == 16 then + buffer.writeu8(out, i * 2, v % 256) + buffer.writeu8(out, i * 2 + 1, math.floor(v / 16777216)) + else + local k = (math.floor(v / 16777216 )== 0 and bit32.band(tonumber(n.layer.flags) or 0, 8) == 0 and{transparent }or{index[v] or transparent +})[1] buffer.writeu8(out, i, k) + end + end + return out + end + + local out = Bytes.writer(65536) + -- header (file size patched at the end) + out:u32le(0) + out:u16le(0xA5E0) + out:u16le(#frameList) + out:u16le(W) + out:u16le(H) + out:u16le(depth) + out:u32le(3) -- layer opacity and group opacity / blend valid + out:u16le(100) + out:u32le(0) + out:u32le(0) + out:u8((depth == 8 and{transparent }or{0})[1]) + out:fill(0, 3) + out:u16le((#palette > 0 and #palette < 256 and((#palette ))or(0))) + local ratio = (type(meta.pixelRatio) == "table" and{meta.pixelRatio }or{{ 1, 1 } +})[1] out:u8(math.clamp(tonumber(ratio[1]) or 1, 0, 255)) + out:u8(math.clamp(tonumber(ratio[2]) or 1, 0, 255)) + local grid = (type(meta.grid) == "table" and{meta.grid }or{{ 0, 0, 16, 16 } +})[1] out:i16le(tonumber(grid[1]) or 0) + out:i16le(tonumber(grid[2]) or 0) + out:u16le(math.clamp(tonumber(grid[3]) or 16, 0, 65535)) + out:u16le(math.clamp(tonumber(grid[4]) or 16, 0, 65535)) + out:fill(0, 84) + + local function chunk(fw, ctype, body) + local b = body:finish() + fw:u32le(buffer.len(b) + 6) + fw:u16le(ctype) + fw:bytes(b) + end + local function userData(fw, ud) +if type(ud) ~= "table" then + return 0 + end + local c = Bytes.writer(64) + local f = (type(ud.text) == "string" and 1 or 0) + (type(ud.color) == "table" and 2 or 0) + c:u32le(f) + if type(ud.text) == "string" then + writeStr(c, ud.text) + end + if type(ud.color) == "table" then + for k = 1, 4 do + c:u8(math.clamp(tonumber(ud.color[k]) or 0, 0, 255)) + end + end + chunk(fw, 0x2020, c) + return 1 + end + -- where each (layer, frame) cel's image was first written: linked cels + local firstAt= {} + for fi, f in __iter(frameList) do + local fw = Bytes.writer(4096) + local count = 0 + if fi == 1 then + -- colour profile: sRGB + local cp = Bytes.writer(16) + cp:u16le(1) + cp:u16le(0) + cp:u32le(0) + cp:fill(0, 8) + chunk(fw, 0x2007, cp) + count =count+ 1 + if #palette > 0 then + local p = Bytes.writer(#palette * 6 + 20) + local n = math.min(#palette, 256) + p:u32le(n) + p:u32le(0) + p:u32le(n - 1) + p:fill(0, 8) + local names = (type(meta.paletteNames) == "table" and{meta.paletteNames }or{{} +})[1] for k = 1, n do + local c = palette[k] + local nm = names[k] + p:u16le(type(nm) == "string" and 1 or 0) + p:u8(c[1] or 0) + p:u8(c[2] or 0) + p:u8(c[3] or 0) + p:u8(c[4] or 255) + if type(nm) == "string" then + writeStr(p, nm) + end + end + chunk(fw, 0x2019, p) + count =count+ 1 + end + for _, n in __iter(struct) do + local l = n.layer + local c = Bytes.writer(64) + local isGroup = type(l.children) == "table" + local flags = tonumber(l.flags) or 3 + flags = bit32.band(flags, bit32.bnot(1)) + (l.visible == false and 0 or 1) + c:u16le(flags) + c:u16le(isGroup and 1 or 0) + c:u16le(n.level) + c:u16le(0) + c:u16le(0) + c:u16le(BLEND_IDS[l.blend] or 0) + c:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + c:fill(0, 3) + writeStr(c, tostring(l.name or "Layer")) + chunk(fw, 0x2004, c) + count =count+ 1 + count =count+ userData(fw, l.userData) + end + local tags = (type(meta.tags) == "table" and{meta.tags }or{{} +})[1] if #tags > 0 then + local c = Bytes.writer(64) + c:u16le(#tags) + c:fill(0, 8) + for _, t in __iter(tags) do + c:u16le(math.clamp((tonumber(t.from) or 1) - 1, 0, 65535)) + c:u16le(math.clamp((tonumber(t.to) or 1) - 1, 0, 65535)) + c:u8(DIRECTION_IDS[t.direction] or 0) + c:u16le(math.clamp(tonumber(t["repeat"]) or 0, 0, 65535)) + c:fill(0, 6) + local col = (type(t.color) == "table" and{t.color }or{{ 0, 0, 0 } +})[1] c:u8(col[1] or 0) + c:u8(col[2] or 0) + c:u8(col[3] or 0) + c:u8(0) + writeStr(c, tostring(t.name or "Tag")) + end + chunk(fw, 0x2018, c) + count =count+ 1 + for _, t in __iter(tags) do + if type(t.userData) == "table" then + count =count+ userData(fw, t.userData) + else + local e = Bytes.writer(4) + e:u32le(0) + chunk(fw, 0x2020, e) + count =count+ 1 + end + end + end + end + for li, n in __iter(perFrame[fi]) do +local __DARKLUA_CONTINUE_33=false repeat local l = n.layer + if type(l.children) == "table" or l.image.width == 0 or l.image.height == 0 then +__DARKLUA_CONTINUE_33=true break + end + local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local fill = math.clamp(math.floor((tonumber(l.fillOpacity) or 1) * 255 + 0.5), 0, 255) + local c = Bytes.writer(256) + c:u16le(li - 1) + c:i16le(x) + c:i16le(y) + c:u8(fill) + local seen = firstAt[li] and firstAt[li][l.image] + if seen and seen.x == x and seen.y == y and seen.fill == fill then + c:u16le(1) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(seen.frame - 1) + else + c:u16le(2) + c:i16le(tonumber(l.zIndex) or 0) + c:fill(0, 5) + c:u16le(l.image.width) + c:u16le(l.image.height) + local z = Deflate.zlibCompress(pixels(n), { level = level }) + if not z then + return nil, Err.new(Err.ARG, "cel compression failed") + end + c:bytes(z) + firstAt[li] = firstAt[li] or {} + firstAt[li][l.image] = { frame = fi, x = x, y = y, fill = fill } + end + chunk(fw, 0x2005, c) + count =count+ 1 + count =count+ userData(fw, l.celUserData) +__DARKLUA_CONTINUE_33=true until true if not __DARKLUA_CONTINUE_33 then break end end + local body = fw:finish() + out:u32le(buffer.len(body) + 16) + out:u16le(0xF1FA) + out:u16le(math.min(count, 0xFFFF)) + out:u16le(math.clamp(math.floor((tonumber(f.delay) or 0.1) * 1000 + 0.5), 0, 65535)) + out:u16le(0) + out:u32le(count) + out:bytes(body) + end + out:setU32le(0, out:tell()) + return out:finish(), nil +end + +return Aseprite +end +__FILES["layered/ora"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with +-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. +-- Decode: the stack tree (nested <stack> = groups: isolation="auto" is passThrough; <layer> name / src / x / y / +-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), +-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: +-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) +-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to +-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the <text> / <filter> / +-- <selection> elements (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Xml = __include("codecs/text/Xml") +local Blend = __include("codecs/image/Blend") + +-- ------------------------------------------------------------------------------------------------ contract +local Ora = { + name = "ora", + category = "layered", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + +local MIME = "image/openraster" +local OPS= { + ["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay", + ["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn", + ["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference", + ["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color", + ["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge", +} +local BACK= {} +for k, v in __iter(OPS) do + BACK[v] = k +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ora.sniff(r) -- a zip whose first (stored) entry is "mimetype" holding image/openraster + +if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(v, default) +local n = tonumber(v) + return (n and n == n and{n }or{default +})[1]end + +function Ora.decode(r, opts) +local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local mt = zip:readString("mimetype") + if mt and string.gsub(mt, "%s+$", "") ~= MIME then + return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME) + end + local stackText, serr = zip:readString("stack.xml") + if not stackText then + return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml") + end + local doc, xerr = Xml.decode(stackText) + if not doc then + return nil, xerr + end + local root = doc.root + if not root or root.name ~= "image" then + return nil, Err.new(Err.CORRUPT, "stack.xml has no <image> root") + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook") + end + local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0) + if W < 1 or H < 1 or W > 65536 or H > 65536 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxLayers = opts and opts.maxLayers or 10000 + local count = 0 + local function png(path) +local data, derr = zip:read(path) + if not data then + return nil, derr or Err.new(Err.CORRUPT, "missing " .. path) + end + local ok, img, ierr = pcall(decodeImage, data) + if not ok or not img then + return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring((ok and{ierr }or{img})[1])) + end + return img, nil + end + -- a <stack>'s children, top first in the file -> bottom to top + local function stack(node, ox, oy) +local out= {} + for _, ch in __iter(node.children) do +local __DARKLUA_CONTINUE_2=false repeat if type(ch) ~= "table" then +__DARKLUA_CONTINUE_2=true break + end + local a = ch.attrs or {} + local visible = a.visibility ~= "hidden" + local op = a["composite-op"] or "svg:src-over" + local blend = OPS[op] or op + local x, y = ox + num(a.x, 0), oy + num(a.y, 0) + count =count+ 1 + if count > maxLayers then + return nil, Err.new(Err.LIMIT, "too many layers") + end + if ch.name == "layer" then + local src = a.src + if type(src) ~= "string" then +__DARKLUA_CONTINUE_2=true break + end + if string.lower(string.sub(src, -4)) ~= ".png" then + return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src) + end + local img, perr = png(src) + if not img then + return nil, perr + end + local layer = Types.Layered.layer(a.name or src, img , x, y) + layer.opacity = math.clamp(num(a.opacity, 1), 0, 1) + layer.visible = visible + layer.blend = blend + table.insert(out, 1, layer) + elseif ch.name == "stack" then + local kids, kerr = stack(ch, x, y) + if not kids then + return nil, kerr + end + local g = Types.Layered.group(a.name or "group", kids ) + g.opacity = math.clamp(num(a.opacity, 1), 0, 1) + g.visible = visible + g.blend = (a.isolation == "isolate" and{(blend == "normal" and"normal" or blend) }or{"passThrough" +})[1] table.insert(out, 1, g) + end +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + return out, nil + end + local top = Xml.child(root, "stack") + if not top then + return nil, Err.new(Err.CORRUPT, "stack.xml has no <stack>") + end + local layers, lerr = stack(top, 0, 0) + if not layers then + return nil, lerr + end + local doc2 = Types.Layered.new(W, H) + doc2.layers = layers +if not (opts and opts.composite == false) and zip:find("mergedimage.png") then + doc2.meta.composite = png("mergedimage.png") + end + local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres) + if xr and yr then + doc2.meta.dpi = { x = xr, y = yr } + end + doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count } + return doc2, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- nearest-neighbour downscale to fit max x max +local function thumbnail(img, max) +local w, h = img.width, img.height + local s = math.min(1, max / math.max(w, h)) + local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s)) + local t = Types.Image.new(tw, th, "rgba8") + for y = 0, th - 1 do + local sy = math.min(h - 1, math.floor(y / s)) + for x = 0, tw - 1 do + local sx = math.min(w - 1, math.floor(x / s)) + buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4)) + end + end + return t +end + +function Ora.encode(doc, opts) +if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then + return nil, Err.new(Err.ARG, "needs a Layered document") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook") + end + local W, H = doc.width, doc.height + local zw = Zip.writer() + zw:add("mimetype", MIME, { method = "store" }) + local files= {} + local n = 0 + local function png(img, label) +if type(img) ~= "table" or img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images") + end + local ok, data, err = pcall(encodeImage, img, "png") + if not ok or not data then + return nil, Err.new(Err.ARG, label .. ": " .. tostring((ok and{err }or{data})[1])) + end + return data, nil + end + -- layers bottom to top -> xml children top first + local function stack(layers) +local kids = {} + for i = #layers, 1, -1 do + local l = layers[i] + local attrs= { + name = l.name or "", + opacity = string.format("%.6g", l.opacity or 1), + visibility = l.visible == false and"hidden" or"visible", + } + if l.children then + attrs.isolation = l.blend == "passThrough" and"auto" or"isolate" + if l.blend ~= "passThrough" then + attrs["composite-op"] = BACK[l.blend] or l.blend + end + local sub, serr = stack(l.children) + if not sub then + return nil, serr + end + table.insert(kids, Xml.element("stack", attrs, sub)) + else + n =n+ 1 + local path = string.format("data/layer%03d.png", n) + local data, perr = png(l.image, "layer " .. tostring(l.name)) + if not data then + return nil, perr + end + table.insert(files, { path, data }) + attrs.src = path + attrs.x = tostring(math.floor(l.x or 0)) + attrs.y = tostring(math.floor(l.y or 0)) + attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over" + table.insert(kids, Xml.element("layer", attrs)) + end + end + return kids, nil + end + local kids, kerr = stack(doc.layers) + if not kids then + return nil, kerr + end + local rootAttrs= { version = "0.0.6", w = tostring(W), h = tostring(H) } + local dpi = doc.meta and doc.meta.dpi + if dpi then + rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y) + end + local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids ) })), { indent = 1 }) + zw:add("stack.xml", xml ) + for _, f in __iter(files) do + zw:add(f[1], f[2], { method = "store" }) + end + local merged = opts and opts.composite + if not merged then + local m = Types.Image.new(W, H, "rgba8") + Blend.flatten(doc.layers, m.pixels, W, H, false) + merged = m + end + local mdata, merr = png(merged , "mergedimage") + if not mdata then + return nil, merr + end + zw:add("mergedimage.png", mdata, { method = "store" }) + if not (opts and opts.thumbnail == false) then + local tdata, terr = png(thumbnail(merged , 256), "thumbnail") + if not tdata then + return nil, terr + end + zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" }) + end + return zw:finish() +end + +return Ora +end +__FILES["layered/psd"] = function() +local __compat = __compat local buffer, bit32, utf8, type, __iter = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type, __compat.__iter --!strict +-- layered/psd: Adobe Photoshop PSD and PSB (Adobe Photoshop File Formats Specification, 2016). Supports: decode of +-- bitmap, greyscale, indexed, RGB, CMYK, Lab, duotone and multichannel documents at 1 / 8 / 16 / 32 bits; layers +-- (raw, PackBits RLE, ZIP and ZIP-with-prediction channels; 16 / 32-bit layers in Lr16 / Lr32), their blend mode, +-- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / +-- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image +-- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. +-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend +-- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, +-- clipping, opacity / fill, hidden flags and Unicode names. +-- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer +-- effects, vector masks, colour management, 16 / 32-bit or non-RGB output. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Text = __include("codecs/text/Text") +local Blend = __include("codecs/image/Blend") +local Channels = __include("layered/psd/Channels") + +-- ------------------------------------------------------------------------------------------------ contract +local Psd = { + name = "psd", + category = "layered", + extensions = { "psd", "psb" }, + mime = { "image/vnd.adobe.photoshop" }, + 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 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local BLEND_KEYS= { + norm = "normal", + diss = "dissolve", + dark = "darken", + ["mul "] = "multiply", + idiv = "colorBurn", + lbrn = "linearBurn", + dkCl = "darkerColor", + lite = "lighten", + scrn = "screen", + ["div "] = "colorDodge", + lddg = "linearDodge", + lgCl = "lighterColor", + over = "overlay", + sLit = "softLight", + hLit = "hardLight", + vLit = "vividLight", + lLit = "linearLight", + pLit = "pinLight", + hMix = "hardMix", + diff = "difference", + smud = "exclusion", + fsub = "subtract", + fdiv = "divide", + ["hue "] = "hue", + ["sat "] = "saturation", + colr = "color", + ["lum "] = "luminosity", + pass = "passThrough", +} +local BLEND_NAMES= {} +for k, v in __iter(BLEND_KEYS) do + BLEND_NAMES[v] = k +end +BLEND_NAMES.add = "lddg" + +-- colour channels per mode (the rest are alpha / spot channels) +local COLOR_CHANNELS = { [0] = 1, [1] = 1, [2] = 1, [3] = 3, [4] = 4, [7] = 1, [8] = 1, [9] = 3 } +local MODE_NAMES = { [0] = "bitmap", [1] = "gray", [2] = "indexed", [3] = "rgb", [4] = "cmyk", [7] = "multichannel", [8] = "duotone", [9] = "lab" } +-- additional layer info keys with 8-byte lengths in PSB +local LONG_KEYS = { LMsk = true, Lr16 = true, Lr32 = true, Layr = true, Mt16 = true, Mt32 = true, Mtrn = true, Alph = true, FMsk = true, lnk2 = true, FEid = true, FXid = true, PxSD = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Psd.sniff(r) +local h = r:peek(6) + if string.sub(h, 1, 4) == "8BPS" and (string.sub(h, 5, 6) == "\0\1" or string.sub(h, 5, 6) == "\0\2") then + return 1 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +local function len(r, psb) +return (psb and{(r:u64be() )}or{(r:u32be() +)})[1]end + +local function utf16be(s) +return (string.gsub(Text.utf16(buffer.fromstring(s), 0, #s, true), "%z", "")) +end + +-- the layer records + channel data at r (a Reader over the layer info, after its length): flat records | nil, Err +local function layerRecords(r, c) +local count = r:i16be() + local absAlpha = count < 0 + count = math.abs(count) + if r.err then + return nil, absAlpha, r.err + end + if count > c.maxLayers then + return nil, absAlpha, Err.new(Err.LIMIT, "over " .. c.maxLayers .. " layers") + end + local recs = {} + for li = 1, count do + local top, left, bottom, right = r:i32be(), r:i32be(), r:i32be(), r:i32be() + local nch = r:u16be() + if r.err then + return nil, absAlpha, r.err + end + if nch > 56 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": " .. nch .. " channels", r.pos) + end + local chans = {} + for k = 1, nch do + chans[k] = { id = r:i16be(), size = len(r, c.psb) } + end + if r:string(4) ~= "8BIM" and not r.err then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad blend mode signature", r.pos - 4) + end + local key = r:string(4) + local opacity, clipping, flags = r:u8(), r:u8(), r:u8() + r:skip(1) + local extraLen = r:u32be() + if r.err then + return nil, absAlpha, r.err + end + local ex = r:slice(extraLen) + local rec= { + top = top, + left = left, + bottom = bottom, + right = right, + chans = chans, + blend = BLEND_KEYS[key] or "normal", + blendKey = key, + opacity = opacity / 255, + clip = clipping ~= 0, + hidden = bit32.band(flags, 2) ~= 0, + flags = flags, + } + -- mask data + local ml = ex:u32be() + if ml > 0 then + local mr = ex:slice(ml) + if ml >= 18 then + rec.mask = { top = mr:i32be(), left = mr:i32be(), bottom = mr:i32be(), right = mr:i32be(), default = mr:u8(), flags = mr:u8() } + end + end + -- blending ranges + ex:skip(ex:u32be()) + -- name: Pascal string padded to 4 + local nl = ex:u8() + rec.name = ex:string(nl) + ex:skip((4 - (nl + 1) % 4) % 4) + -- additional layer info + while ex:remaining() >= 12 do + local sig = ex:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = ex:string(4) + local l = (c.psb and LONG_KEYS[k] and{(ex:u64be() )}or{(ex:u32be() +)})[1] if ex.err then + break + end + local d = ex:slice(l) + if k == "luni" then + local n = d:u32be() + local s = d:string(math.min(n * 2, d:remaining())) + rec.name = utf16be(s) + elseif k == "lsct" or k == "lsdk" then + rec.section = d:u32be() + if d:remaining() >= 8 and d:string(4) == "8BIM" then + rec.sectionBlend = d:string(4) + end + elseif k == "iOpa" then + rec.fill = d:u8() / 255 + elseif k == "lyid" then + rec.id = d:u32be() + end + end + if r.err then + return nil, absAlpha, r.err + end + recs[li] = rec + end + -- channel image data + local b = r.buf + for li, rec in __iter(recs) do + local w, h = rec.right - rec.left, rec.bottom - rec.top + if w < 0 or h < 0 or w > 300000 or h > 300000 then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. ": bad bounds", r.pos) + end + if w * h > c.maxPixels then + return nil, absAlpha, Err.new(Err.LIMIT, string.format("layer %d: %d x %d is over the pixel limit", li, w, h)) + end + local planes= {} + for _, ch in __iter(rec.chans) do +local __DARKLUA_CONTINUE_6=false repeat local p = r.pos + if ch.size < 0 or p + ch.size > r.limit then + return nil, absAlpha, Err.new(Err.TRUNCATED, "layer " .. li .. ": channel data past the end", p) + end + r.pos = p + ch.size + local cw, chh = w, h + if ch.id == -2 or ch.id == -3 then + local m = rec.mask + if not m then +__DARKLUA_CONTINUE_6=true break + end + cw, chh = m.right - m.left, m.bottom - m.top + if cw < 0 or chh < 0 or cw * chh > c.maxPixels then +__DARKLUA_CONTINUE_6=true break + end + end + if ch.size < 2 then +__DARKLUA_CONTINUE_6=true break -- an empty channel + end + local plane, perr = Channels.channel(b, p, p + ch.size, cw, chh, c.depth, c.psb) + if not plane then + return nil, absAlpha, Err.new(Err.CORRUPT, "layer " .. li .. " channel " .. ch.id .. ": " .. tostring(perr), p) + end + if c.depth == 32 then + Channels.swap32(plane) + end + if ch.id == -1 then + planes.alpha = plane + elseif ch.id == -2 then + rec.maskPlane = Channels.gray8(plane, cw, chh, c.depth) + elseif ch.id >= 0 and ch.id < 56 then + planes[ch.id + 1] = plane + end +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end + local img = Types.Image.new(w, h) + if w > 0 and h > 0 then + img.pixels = Channels.toRGBA(planes, w, h, c.depth, c.mode, nil) + end + rec.image = img + end + return recs, absAlpha, nil +end + +-- records (bottom to top) -> a layer tree +local function tree(recs) +local root= {} + local stack= {} + local cur = root + local function layerOf(rec) +local l= { + name = rec.name, + image = rec.image, + x = rec.left, + y = rec.top, + opacity = rec.opacity, + blend = rec.blend, + visible = not rec.hidden, + } + if rec.clip then + l.clip = true + end + if rec.fill and rec.fill < 1 then + l.fillOpacity = rec.fill + end + if rec.id then + l.id = rec.id + end + if rec.mask and rec.maskPlane then + local m = rec.mask + local mi = Types.Image.new(m.right - m.left, m.bottom - m.top, "gray8") + mi.pixels = rec.maskPlane + l.mask = { image = mi, x = m.left, y = m.top, default = m.default, disabled = bit32.band(m.flags, 2) ~= 0 } + end + return l + end + for _, rec in __iter(recs) do + local s = rec.section + if s == 3 then + table.insert(stack, cur) + cur = {} + elseif s == 1 or s == 2 then + local g = layerOf(rec) + g.image = Types.Image.new(0, 0) + g.children = cur + if rec.sectionBlend and BLEND_KEYS[rec.sectionBlend] then + g.blend = BLEND_KEYS[rec.sectionBlend] + end + ;(g ).collapsed = s == 2 + cur = table.remove(stack) or root + table.insert(cur, g) + else + table.insert(cur, layerOf(rec)) + end + end + -- unbalanced dividers: splice the open groups' layers back in + while #stack > 0 do + local parent = (table.remove(stack) ) +for _, l in __iter(cur) do + table.insert(parent, l) + end + cur = parent + end + return cur +end + +function Psd.decode(r, opts) +local o= opts or {} + local c= { psb = false, depth = 8, mode = 3, maxPixels = o.maxPixels or 2 ^ 26, maxLayers = o.maxLayers or 10000 } + if Psd.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a PSD (bad signature)", r.pos) + end + r:skip(4) + local version = r:u16be() + r:skip(6) + local nch, h, w, depth, mode = r:u16be(), r:u32be(), r:u32be(), r:u16be(), r:u16be() + if r.err then + return nil, r.err + end + c.psb, c.depth, c.mode = version == 2, depth, mode + if nch < 1 or nch > 56 then + return nil, Err.new(Err.CORRUPT, "bad channel count " .. nch) + end + local maxSide = c.psb and 300000 or 30000 + if w < 1 or h < 1 or w > maxSide or h > maxSide then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h)) + end + if not (depth == 1 or depth == 8 or depth == 16 or depth == 32) then + return nil, Err.new(Err.CORRUPT, "bad depth " .. depth) + end + if COLOR_CHANNELS[mode] == nil then + return nil, Err.new(Err.CORRUPT, "bad colour mode " .. mode) + end + if (mode == 0) ~= (depth == 1) then + return nil, Err.new(Err.UNSUPPORTED, "1-bit data outside bitmap mode") + end + if w * h > c.maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, c.maxPixels)) + end + local layered = Types.Layered.new(w, h) + -- colour mode data + local cm = r:slice(r:u32be()) + local palette= nil + if mode == 2 and cm:size() >= 768 then + palette = cm:bytes(768) + local pal = {} + for i = 0, 255 do + pal[i + 1] = { buffer.readu8(palette , i), buffer.readu8(palette , 256 + i), buffer.readu8(palette , 512 + i), 255 } + end + layered.meta.palette = pal + end + -- image resources + local rr = r:slice(r:u32be()) + if r.err then + return nil, r.err + end + local resources = {} + while rr:remaining() >= 12 and rr:string(4) == "8BIM" do + local id = rr:u16be() + local nl = rr:u8() + local name = rr:string(nl) + rr:skip((nl + 1) % 2) + local size = rr:u32be() + if rr.err or size > rr:remaining() then + break + end + local data = rr:bytes(size) + rr:skip(size % 2) + table.insert(resources, { id = id, name = name, data = data }) + if id == 0x040F then + layered.meta.icc = data + end + end + layered.meta.resources = resources + -- layer and mask information + local lm = r:slice(len(r, c.psb)) + if r.err then + return nil, r.err + end + local recs= nil + local absAlpha = false + if o.layers ~= false and lm:size() > 0 then + local liLen = len(lm, c.psb) + local li = lm:slice(liLen) + if lm.err then + return nil, lm.err + end + if liLen > 0 then + local list, aa, lerr = layerRecords(li, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + -- global layer mask info, then additional info (16 / 32-bit layers live in Lr16 / Lr32) + lm:skip(lm:u32be()) + while not lm.err and lm:remaining() >= 12 do + local sig = lm:string(4) + if sig ~= "8BIM" and sig ~= "8B64" then + break + end + local k = lm:string(4) + local l = (c.psb and LONG_KEYS[k] and{(lm:u64be() )}or{(lm:u32be() +)})[1] if lm.err then + break + end + local d = lm:slice(l) + if (k == "Lr16" or k == "Lr32" or k == "Layr") and recs == nil then + local list, aa, lerr = layerRecords(d, c) + if not list then + return nil, lerr + end + recs, absAlpha = list, aa + end + lm:align(4) + end + end + if recs then + layered.layers = tree(recs) + end + -- the merged image + local comp = r:u16be() + if r.err then + return nil, r.err + end + local cc = COLOR_CHANNELS[mode] + if mode == 7 then + cc = math.min(nch, 3) + end + local useAlpha = nch > cc and (absAlpha or recs == nil) and mode ~= 7 + local nread = math.min(nch, cc + (useAlpha and 1 or 0)) + local rb = Channels.rowBytes(w, depth) + local planes= {} + local b = r.buf + if comp == 0 then + for k = 1, nread do + local p = r.pos + (k - 1) * rb * h + if p + rb * h > r.limit then + return nil, Err.new(Err.TRUNCATED, "merged image past the end", p) + end + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, b, p, rb * h) + planes[k] = plane + end + elseif comp == 1 then + local counts, q = Channels.rleCounts(b, r.pos, r.limit, h * nch, c.psb) + if not counts then + return nil, Err.new(Err.TRUNCATED, "merged image row counts past the end", r.pos) + end + local p= q + for k = 1, nread do + local plane = buffer.create(rb * h) + local np, perr = Channels.rle(b, p, r.limit, counts, (k - 1) * h + 1, h, rb, plane, 0) + if not np then + return nil, Err.new(Err.CORRUPT, "merged image: " .. tostring(perr), p) + end + p = np + planes[k] = plane + end + elseif comp == 2 or comp == 3 then + -- one zlib stream per channel would be Channels.channel; Photoshop writes all channels in one stream + local all = Channels.channel(b, r.pos - 2, r.limit, w, h * nread, depth, c.psb) + if not all then + return nil, Err.new(Err.CORRUPT, "merged image: bad ZIP data", r.pos) + end + for k = 1, nread do + local plane = buffer.create(rb * h) + buffer.copy(plane, 0, all, (k - 1) * rb * h, rb * h) + planes[k] = plane + end + else + return nil, Err.new(Err.CORRUPT, "bad merged image compression " .. comp) + end + if useAlpha then + planes.alpha = planes[cc + 1] + planes[cc + 1] = nil +end + if depth == 32 then + for _, p in __iter(planes) do + Channels.swap32(p) + end + end + local composite = Types.Image.new(w, h) + composite.pixels = Channels.toRGBA(planes, w, h, depth, mode, palette) + if planes.alpha then + Channels.unmatte(composite.pixels, w * h) + end + composite.meta.source = { format = "psd", bitDepth = depth, colorType = MODE_NAMES[mode] } + layered.meta.composite = composite + layered.meta.source = { format = "psd", version = version, bitDepth = depth, colorMode = MODE_NAMES[mode], channels = nch, psb = c.psb } + return layered, nil +end +-- ------------------------------------------------------------------------------------------------ encode + + + +local function isImage(v) +return type(v) == "table" and v.format == "rgba8" and type(v.pixels) == "buffer" and type(v.width) == "number" and type(v.height) == "number" and v.width >= 0 and v.height >= 0 and buffer.len(v.pixels) >= v.width * v.height * 4 +end + +local function pascal(name) +local s = string.gsub(name, "[\128-\255]", "?") + s = string.sub(s, 1, 255) + local pad = (4 - (#s + 1) % 4) % 4 + return string.char(#s) .. s .. string.rep("\0", pad) +end + +local function block(w, key, data) + w:string("8BIM") + w:string(key) + local pad = (4 - #data % 4) % 4 -- additional info is padded to 4 + w:u32be(#data + pad) + w:string(data) + w:fill(0, pad) +end + +local function u32s(v) +return string.char(math.floor(v / 16777216 )% 256, math.floor(v / 65536 )% 256, math.floor(v / 256 )% 256, v % 256) +end + +local function luni(name) +local out = {} + local n = 0 + for _, cp in __iter(utf8.codes(name)) do + if cp >= 0x10000 then + local v = cp - 0x10000 + local hi, lo = 0xD800 + math.floor(v / 1024), 0xDC00 + v % 1024 + table.insert(out, string.char(math.floor(hi / 256), hi % 256, math.floor(lo / 256), lo % 256)) + n =n+ 2 + else + table.insert(out, string.char(math.floor(cp / 256), cp % 256)) + n =n+ 1 + end + end + return u32s(n) .. table.concat(out) +end + +function Psd.encode(layered, opts) +if type(layered) ~= "table" or type(layered.layers) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" then + return nil, Err.new(Err.ARG, "needs a Layered value") + end + local W, H = math.floor(layered.width), math.floor(layered.height) + if W < 1 or H < 1 or W > 300000 or H > 300000 then + return nil, Err.new(Err.ARG, "bad document size") + end + local psb = W > 30000 or H > 30000 + -- the records, bottom to top + local recs= {} + local bad= nil + local function walk(list, depth) + for _, l in __iter(list) do + if type(l) ~= "table" then + bad = "a layer is not a table" + return + end + if type(l.children) == "table" then + if depth > 64 then + bad = "groups nested too deep" + return + end + table.insert(recs, { layer = l, section = 3, name = "</Layer group>" }) + walk(l.children, depth + 1) + table.insert(recs, { layer = l, section = l.collapsed and 2 or 1, name = tostring(l.name or "Group") }) + else + if not isImage(l.image) then + bad = "layer " .. tostring(l.name) .. ": needs an rgba8 image" + return + end + table.insert(recs, { layer = l, name = tostring(l.name or "Layer") }) + end + end + end + walk(layered.layers, 0) + if bad then + return nil, Err.new(Err.ARG, bad ) + end + if #recs > 32767 then + return nil, Err.new(Err.ARG, "too many layers") + end + local function lenW(w, v) + if psb then + w:u64be(v) + else + w:u32be(v) + end + end + -- layer records and channel data + local info = Bytes.writer(4096) + local data = Bytes.writer(65536) + info:i16be(-#recs) -- negative: the merged image's first alpha channel is its transparency + for _, rec in __iter(recs) do + local l = rec.layer + local img = (rec.section and{nil }or{l.image +})[1] local x, y = math.floor(tonumber(l.x) or 0), math.floor(tonumber(l.y) or 0) + local w, h = (img and{img.width }or{0})[1], (img and{img.height }or{0 +})[1] if rec.section then + x, y = 0, 0 + end + info:i32be(y) + info:i32be(x) + info:i32be(y + h) + info:i32be(x + w) + local chans= {} + if img and w > 0 and h > 0 then + local pr, pg, pb, pa = Channels.planes8(img.pixels, w, h) + chans = { + { id = -1, data = Channels.rleChannel(pa, w, h, psb) }, + { id = 0, data = Channels.rleChannel(pr, w, h, psb) }, + { id = 1, data = Channels.rleChannel(pg, w, h, psb) }, + { id = 2, data = Channels.rleChannel(pb, w, h, psb) }, + } + else + chans = { { id = -1, data = buffer.create(0) }, { id = 0, data = buffer.create(0) }, { id = 1, data = buffer.create(0) }, { id = 2, data = buffer.create(0) } } + end + -- the mask + local m = (rec.section == nil and type(l.mask) == "table" and type(l.mask.image) == "table" and type(l.mask.image.pixels) == "buffer" and{l.mask }or{nil +})[1] local mw, mh = 0, 0 + if m then + local mi = m.image + mw, mh = mi.width, mi.height + local plane = mi.pixels + if mi.format == "rgba8" then + plane = (Channels.planes8(mi.pixels, mw, mh)) + elseif mi.format ~= "gray8" and mi.format ~= "alpha8" then + return nil, Err.new(Err.ARG, "mask images are gray8 / alpha8 / rgba8") + end + if buffer.len(plane) < mw * mh then + return nil, Err.new(Err.ARG, "bad mask image") + end + table.insert(chans, { id = -2, data = Channels.rleChannel(plane, mw, mh, psb) }) + end + info:u16be(#chans) + for _, ch in __iter(chans) do + info:i16be(ch.id) + lenW(info, buffer.len(ch.data) + 2) + data:u16be(buffer.len(ch.data) > 0 and 1 or 0) + data:bytes(ch.data) + end + info:string("8BIM") + local blend = (type(l.blend) == "string" and{l.blend }or{"normal" +})[1] local key = BLEND_NAMES[blend] or "norm" + if rec.section and rec.section ~= 3 then + key = blend == "passThrough" and"pass" or key + end + info:string(key) + info:u8(math.clamp(math.floor((tonumber(l.opacity) or 1) * 255 + 0.5), 0, 255)) + info:u8(l.clip and rec.section == nil and 1 or 0) + local flags = 8 -- bit 3: bit 4 is meaningful + if l.visible == false and rec.section ~= 3 then + flags =flags+ 2 + end + if rec.section then + flags =flags+ 16 -- pixel data irrelevant to the appearance + end + info:u8(flags) + info:u8(0) + local ex = Bytes.writer(256) + if m then + ex:u32be(20) + local mx, my = math.floor(tonumber(m.x) or 0), math.floor(tonumber(m.y) or 0) + ex:i32be(my) + ex:i32be(mx) + ex:i32be(my + mh) + ex:i32be(mx + mw) + ex:u8(math.clamp(math.floor(tonumber(m.default) or 0), 0, 255)) + ex:u8(m.disabled and 2 or 0) + ex:u16be(0) + else + ex:u32be(0) + end + ex:u32be(0) -- blending ranges + ex:string(pascal(rec.name)) + block(ex, "luni", luni(rec.name)) + if rec.section then + block(ex, "lsct", u32s(rec.section) .. ((rec.section ~= 3 and(("8BIM" .. key ))or("")))) + end + local fill = tonumber(l.fillOpacity) + if fill and fill < 1 and rec.section == nil then + block(ex, "iOpa", string.char(math.clamp(math.floor(fill * 255 + 0.5), 0, 255)) .. "\0\0\0") + end + local exb = ex:finish() + info:u32be(buffer.len(exb)) + info:bytes(exb) + end + info:bytes(data:finish()) + if info:tell() % 2 == 1 then + info:u8(0) + end + local infoB = info:finish() + -- the merged image + local comp= opts and opts.composite + if comp ~= nil and (not isImage(comp) or comp.width ~= W or comp.height ~= H) then + return nil, Err.new(Err.ARG, "opts.composite must be a " .. W .. " x " .. H .. " rgba8 Image") + end + local merged +if comp then + merged = comp.pixels + else + merged = buffer.create(W * H * 4) + Blend.flatten(layered.layers, merged, W, H, false) + end + local out = Bytes.writer(buffer.len(infoB) + W * H * 4 + 1024) + out:string("8BPS") + out:u16be(psb and 2 or 1) + out:fill(0, 6) + out:u16be(4) + out:u32be(H) + out:u32be(W) + out:u16be(8) + out:u16be(3) + out:u32be(0) -- colour mode data + out:u32be(0) -- image resources + local lmLen = (psb and 8 or 4) + buffer.len(infoB) + 4 + lenW(out, lmLen) + lenW(out, buffer.len(infoB)) + out:bytes(infoB) + out:u32be(0) -- global layer mask info + -- merged: RLE, all row counts first + out:u16be(1) + local pr, pg, pb, pa = Channels.planes8(Channels.matte(merged, W * H), W, H) + local cs = psb and 4 or 2 + local parts = {} + for k, plane in __iter({ pr, pg, pb, pa }) do + local ch = Channels.rleChannel(plane, W, H, psb) + parts[k] = ch + out:bytes(ch, 0, H * cs) + end + for k = 1, 4 do + out:bytes(parts[k], H * cs) + end + return out:finish(), nil +end + +return Psd +end +__FILES["layered/psd/Channels"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- layered/psd/Channels: PSD / PSB channel data. Decodes one channel (raw, PackBits RLE, ZIP, ZIP with prediction) to a +-- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the +-- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". +-- Never throws: every read is range-checked first; failures return nil, "message". +local Deflate = __include("codecs/compress/Deflate") +local PackBits = __include("codecs/compress/PackBits") + +local Channels = {} + +local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32 +local readf32, writef32, bcreate, bcopy, blen, bfill = buffer.readf32, buffer.writef32, buffer.create, buffer.copy, buffer.len, buffer.fill +local floor, min, max = math.floor, math.min, math.max +local byteswap = bit32.byteswap + +-- rowBytes(w, depth) -> bytes per row of one channel +function Channels.rowBytes(w, depth) +if depth == 1 then + return math.floor((w + 7) / 8 +) end + return w * (math.floor(depth / 8)) +end + +-- rleCounts(src, p, limit, rows, psb) -> { counts }, offset after them | nil +function Channels.rleCounts(src, p, limit, rows, psb) +local size = psb and 4 or 2 + if rows < 0 or p + rows * size > limit then + return nil, p + end + local counts= (table.create(rows) ) +for i = 1, rows do + if psb then + counts[i] = byteswap(readu32(src, p)) + else + counts[i] = readu8(src, p) * 256 + readu8(src, p + 1) + end + p =p+ size + end + return counts, p +end + +-- rle(src, p, limit, counts, first, rows, rowBytes, dst, d) -> offset after the rows | nil, message +function Channels.rle(src, p, limit, counts, first, rows, rowBytes, dst, d) +for i = 0, rows - 1 do + local c = counts[first + i] or 0 + if p + c > limit then + return nil, "RLE row past the end" + end + local _, _, clean = PackBits.decode(src, p, p + c, dst, d + i * rowBytes, rowBytes) + if not clean then + -- a short or overlong row: keep what decoded, zero the rest (Photoshop is lenient too) + return nil, "bad RLE row" + end + p =p+ c + end + return p, nil +end + +-- unpredict(plane, w, h, depth): undo ZIP-with-prediction deltas in place +local function unpredict(plane, w, h, depth) + if depth == 8 then + for y = 0, h - 1 do + local o = y * w + local acc = readu8(plane, o) + for x = 1, w - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + end + elseif depth == 16 then + for y = 0, h - 1 do + local o = y * w * 2 + local acc = readu8(plane, o) * 256 + readu8(plane, o + 1) + for x = 1, w - 1 do + local q = o + x * 2 + acc = (acc + readu8(plane, q) * 256 + readu8(plane, q + 1)) % 65536 + writeu8(plane, q, math.floor(acc / 256)) + writeu8(plane, q + 1, acc % 256) + end + end + elseif depth == 32 then + -- byte deltas over the row, then the row is 4 byte planes (all high bytes first) + local rb = w * 4 + local tmp = bcreate(rb) + for y = 0, h - 1 do + local o = y * rb + local acc = readu8(plane, o) + for x = 1, rb - 1 do + acc = (acc + readu8(plane, o + x)) % 256 + writeu8(plane, o + x, acc) + end + for x = 0, w - 1 do + writeu8(tmp, x * 4, readu8(plane, o + x)) + writeu8(tmp, x * 4 + 1, readu8(plane, o + w + x)) + writeu8(tmp, x * 4 + 2, readu8(plane, o + 2 * w + x)) + writeu8(tmp, x * 4 + 3, readu8(plane, o + 3 * w + x)) + end + bcopy(plane, o, tmp, 0, rb) + end + end +end + +-- channel(src, p, limit, w, h, depth, psb) -> plane (h rows of rowBytes) | nil, message. src[p, limit) holds the +-- 2-byte compression code and the data of one layer channel. +function Channels.channel(src, p, limit, w, h, depth, psb) +local rb = Channels.rowBytes(w, depth) + local plane = bcreate(rb * h) + if w == 0 or h == 0 then + return plane, nil + end + if p + 2 > limit then + return nil, "channel data past the end" + end + local comp = readu8(src, p) * 256 + readu8(src, p + 1) + p =p+ 2 + if comp == 0 then + if p + rb * h > limit then + return nil, "raw channel data past the end" + end + bcopy(plane, 0, src, p, rb * h) + elseif comp == 1 then + local counts, q = Channels.rleCounts(src, p, limit, h, psb) + if not counts then + return nil, "RLE row counts past the end" + end + local ok, err = Channels.rle(src, q, limit, counts, 1, h, rb, plane, 0) + if not ok then + return nil, err + end + elseif comp == 2 or comp == 3 then + local out, err = Deflate.zlib(src, p, limit - p, rb * h) + if not out then + return nil, "ZIP channel: " .. tostring(err) + end + plane = out + if comp == 3 then + unpredict(plane, w, h, depth) + end + else + return nil, "unknown channel compression " .. comp + end + return plane, nil +end + +-- sample8(plane, i, depth) -> sample i as 0..255 +local function sample8(plane, i, depth) +if depth == 8 then + return readu8(plane, i) + elseif depth == 16 then + return floor((readu8(plane, i * 2) * 256 + readu8(plane, i * 2 + 1)) / 257 + 0.5) + elseif depth == 32 then + local f = readf32(plane, i * 4) -- the plane holds big-endian floats: swapped by the caller + if f ~= f then + return 0 + end + return floor(max(0, min(1, f)) * 255 + 0.5) + end + -- 1-bit (rows are padded, so this is only right for whole-byte widths; toRGBA reads bitmaps itself): 1 = black + return math.floor(readu8(plane, math.floor(i / 8)) / 2 ^ (7 - i % 8) )% 2 == 1 and 0 or 255 +end + +-- swap32(plane): big-endian f32 samples to native order, in place +function Channels.swap32(plane) + for i = 0, math.floor(blen(plane) / 4 )- 1 do + writeu32(plane, i * 4, byteswap(readu32(plane, i * 4))) + end +end + +-- lab(L, a, b) 0..255 each (PSD Lab) -> sRGB r, g, b 0..255 (D50 -> D65 approximated by D65 white) +local function srgb(c) +c = (c <= 0.0031308 and((12.92 * c ))or((1.055 * c ^ (1 / 2.4) - 0.055 +))) return floor(max(0, min(1, c)) * 255 + 0.5) +end +local function lab(l8, a8, b8) +local L = l8 * 100 / 255 + local a, b = a8 - 128, b8 - 128 + local fy = (L + 16) / 116 + local fx = fy + a / 500 + local fz = fy - b / 200 + local function f(t) +return (t > 6 / 29 and((t * t * t ))or((3 * (6 / 29) ^ 2 * (t - 4 / 29) +))) end + local X, Y, Z = 0.95047 * f(fx), f(fy), 1.08883 * f(fz) + local r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z + local g = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z + local bl = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z + return srgb(r), srgb(g), srgb(bl) +end + +-- toRGBA(planes, w, h, depth, mode, palette?, dst?) -> rgba8 buffer. planes: { [1..k] = colour planes, alpha = plane? } +-- mode: PSD colour mode (0 bitmap, 1 grey, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab) +function Channels.toRGBA(planes, w, h, depth, mode, palette) +local n = w * h + local out = bcreate(n * 4) + local c1, c2, c3, c4 = planes[1], planes[2], planes[3], planes[4] + local alpha = planes.alpha + local bitmapW = math.floor((w + 7) / 8 +) if depth == 8 and (mode == 3 or mode == 1) and c1 and blen(c1) >= n then + -- the common case, without a call per sample + local g8 = (mode == 3 and c2 and blen(c2) >= n and{c2 }or{c1 +})[1] local b8 = (mode == 3 and c3 and blen(c3) >= n and{c3 }or{c1 +})[1] local a8 = (alpha and blen(alpha) >= n and{alpha }or{nil +})[1] for i = 0, n - 1 do + local a = (a8 and{(readu8(a8, i) )}or{255 +})[1] writeu32(out, i * 4, readu8(c1, i) + readu8(g8, i) * 256 + readu8(b8, i) * 65536 + a * 16777216) + end + return out + end + for i = 0, n - 1 do + local r, g, b = 0, 0, 0 + if mode == 3 then + r = (c1 and{(sample8(c1, i, depth) )}or{0 +})[1] g = (c2 and{(sample8(c2, i, depth) )}or{r +})[1] b = (c3 and{(sample8(c3, i, depth) )}or{r +})[1] elseif mode == 4 then + local cc = (c1 and{(sample8(c1, i, depth) )}or{255 +})[1] local mm = (c2 and{(sample8(c2, i, depth) )}or{255 +})[1] local yy = (c3 and{(sample8(c3, i, depth) )}or{255 +})[1] local kk = (c4 and{(sample8(c4, i, depth) )}or{255 +})[1] r = floor(cc * kk / 255 + 0.5) + g = floor(mm * kk / 255 + 0.5) + b = floor(yy * kk / 255 + 0.5) + elseif mode == 2 then + local k = (c1 and{(readu8(c1, i) )}or{0 +})[1] if palette and blen(palette) >= 768 then + r = readu8(palette, k) + g = readu8(palette, 256 + k) + b = readu8(palette, 512 + k) + else + r, g, b = k, k, k + end + elseif mode == 0 then + local y, x = math.floor(i / w), i % w + local bit = (c1 and{(math.floor(readu8(c1, y * bitmapW + math.floor(x / 8)) / 2 ^ (7 - x % 8) )% 2 )}or{0 +})[1] r = bit == 1 and 0 or 255 + g, b = r, r + elseif mode == 9 then + local L = (c1 and{(sample8(c1, i, depth) )}or{0 +})[1] local A = (c2 and{(sample8(c2, i, depth) )}or{128 +})[1] local B = (c3 and{(sample8(c3, i, depth) )}or{128 +})[1] r, g, b = lab(L, A, B) + else -- grey, duotone, multichannel: the first channel as grey + r = (c1 and{(sample8(c1, i, depth) )}or{0 +})[1] g, b = r, r + end + local a = (alpha and{(sample8(alpha, i, depth) )}or{255 +})[1] writeu32(out, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end + return out +end + +-- gray8(plane, w, h, depth) -> 1 byte per pixel +function Channels.gray8(plane, w, h, depth) +local n = w * h + local out = bcreate(n) + for i = 0, n - 1 do + writeu8(out, i, sample8(plane, i, depth)) + end + return out +end + +-- unmatte(rgba, n): Photoshop stores a transparent merged image matted with white (C * a + 255 * (1 - a)): undo it +function Channels.unmatte(rgba, n) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(rgba, o + 3) + if a == 0 then + writeu32(rgba, o, 0) + elseif a < 255 then + local f = a / 255 + for k = 0, 2 do + local v = (readu8(rgba, o + k) - 255 * (1 - f)) / f + writeu8(rgba, o + k, floor(max(0, min(255, v)) + 1e-6)) + end + end + end +end + +-- matte(rgba, n) -> a copy matted with white (the writer's merged image) +function Channels.matte(rgba, n) +local out = bcreate(n * 4) + bcopy(out, 0, rgba, 0, n * 4) + for i = 0, n - 1 do + local o = i * 4 + local a = readu8(out, o + 3) + if a < 255 then + local f = a / 255 + for k = 0, 2 do + writeu8(out, o + k, floor(readu8(out, o + k) * f + 255 * (1 - f) + 0.5)) + end + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ writer helpers +-- packRow(src, o, n, out, d) -> bytes written: PackBits of src[o, o + n) into out at d (out needs n + n // 128 + 1) +function Channels.packRow(src, o, n, out, d) +local start = d + local i = 0 + while i < n do + -- a run of at least 3 equal bytes? + local v = readu8(src, o + i) + local run = 1 + while i + run < n and run < 128 and readu8(src, o + i + run) == v do + run =run+ 1 + end + if run >= 3 then + writeu8(out, d, 257 - run) + writeu8(out, d + 1, v) + d =d+ 2 + i =i+ run + else + -- literals up to the next run of 3 + local j = i + while j < n and j - i < 128 do + if j + 2 < n and readu8(src, o + j) == readu8(src, o + j + 1) and readu8(src, o + j) == readu8(src, o + j + 2) then + break + end + j =j+ 1 + end + local c = j - i + writeu8(out, d, c - 1) + bcopy(out, d + 1, src, o + i, c) + d =d+ (c + 1 +) i = j + end + end + return d - start +end + +-- planes8(rgba, w, h) -> r, g, b, a planes (1 byte per pixel each) +function Channels.planes8(rgba, w, h) +local n = w * h + local r, g, b, a = bcreate(n), bcreate(n), bcreate(n), bcreate(n) + if blen(rgba) < n * 4 then + return r, g, b, a + end + for i = 0, n - 1 do + local v = readu32(rgba, i * 4) + writeu8(r, i, v % 256) + writeu8(g, i, math.floor(v / 256 )% 256) + writeu8(b, i, math.floor(v / 65536 )% 256) + writeu8(a, i, math.floor(v / 16777216)) + end + return r, g, b, a +end + +-- rleChannel(plane, w, h, psb) -> the RLE data of one channel (counts, then rows), without the compression code +function Channels.rleChannel(plane, w, h, psb) +local cs = psb and 4 or 2 + local out = bcreate(h * cs + h * (w + math.floor(w / 128 )+ 2)) + local d = h * cs + for y = 0, h - 1 do + local n = Channels.packRow(plane, y * w, w, out, d) + if psb then + writeu32(out, y * 4, byteswap(n)) + else + writeu16(out, y * 2, math.floor(byteswap(n) / 65536)) + end + d =d+ n + end + local res = bcreate(d) + bcopy(res, 0, out, 0, d) + return res +end + +return Channels +end +__FILES["model/3ds"] = function() +local __compat = __compat local type = __compat.type --!strict +-- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the +-- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference +-- for transforms and conventions; no code ported) and lib3ds (layouts only). +-- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, +-- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and +-- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials +-- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, +-- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as +-- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / +-- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the +-- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), +-- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, +-- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / +-- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from +-- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects +-- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not +-- applied), the keyframer frame range. +-- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first +-- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural +-- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on +-- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") +local Write = __include("model/3ds/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeDs = { + name = "3ds", + category = "model", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + +function ThreeDs.sniff(r) +local h = r:peek(8) + if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then + return 0 + end + local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8) + local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216 + local child = c1 + c2 * 256 + if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then + return 0 + end + return size == r.limit - r.pos and 0.95 or 0.7 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeDs.decode(r, opts) +local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) + if not raw then + return nil, Err.from(msg, at) + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene = pcall(Build.scene, raw, opts ) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeDs.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts ) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return ThreeDs +end +__FILES["model/3ds/Build"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world +-- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * +-- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix +-- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key +-- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's +-- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position +-- are averaged; group 0 is flat). Times are frame / fps. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Read = __include("model/3ds/Read") + +local Build = {} + +local S = Types.Scene +local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32 +local band = bit32.band +local sqrt, abs = math.sqrt, math.abs + +-- ------------------------------------------------------------------------------------------------ math +-- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 + + +local function meshMatrix(m) +if not m then + return Mat4.identity() + end + return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 } +end +Build.meshMatrix = meshMatrix + +local function det3(m) +return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) +end +Build.det3 = det3 + +-- q(a) * q(b) +local function qmul(a, b) +local ax, ay, az, aw = a[1], a[2], a[3], a[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end +Build.qmul = qmul + +-- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +local function keyQuat(angle, x, y, z) +if x == 0 and y == 0 and z == 0 then + return { 0, 0, 0, 1 } + end + return Mat4.axisAngle(x, y, z, -math.deg(angle)) +end + +local function normalize(x, y, z) +local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0, 0 + end + return x / l, y / l, z / l, l +end + +-- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +function Build.lookAt(p, t, roll) +local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) + if l == 0 then + fx, fy, fz = 0, 1, 0 + end + local ux, uy, uz = 0, 0, 1 + if abs(fz) > 0.999999 then + ux, uy, uz = 0, 1, 0 + end + -- right = forward x up, up = right x forward + local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) + ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx + local a = math.rad(roll) + local c, s = math.cos(a), math.sin(a) + local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz + local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz + return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +-- ------------------------------------------------------------------------------------------------ accessors +local function floats(values, comps) +local a = S.accessor(nil, "f32", comps, math.floor(#values / comps)) + for i = 1, (math.floor(#values / comps)) * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME= { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" } + +local function materials(raw, scene) +local byName= {} + local texByFile= {} + local function texture(m) +local file = m.file + if not file or file == "" then + return nil + end + local ti = texByFile[file] + if not ti then + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + local tiling = m.tiling or 0 + local wrap= band(tiling, 0x10) ~= 0 and"clamp" or(band(tiling, 0x2) ~= 0 and"mirror" or"repeat" +) local tex= { name = file, uri = file, mime = MIME[ext] , sampler = { wrapS = wrap, wrapT = wrap } } + table.insert(scene.textures, tex) + ti = #scene.textures + texByFile[file] = ti + end + local ref= { texture = ti } + local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0 + if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then + ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) } + end + return ref + end + for i, m in __iter(raw.materials) do + local mat = S.material(m.name) + local d = m.diffuse or { 0.5, 0.5, 0.5 } + local transparency = math.clamp(m.transparency or 0, 0, 1) + mat.baseColor = { d[1], d[2], d[3], 1 - transparency } + mat.metallic = 0 + mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1) + local si = m.selfIllum or 0 + if si > 0 then + mat.emissive = { d[1] * si, d[2] * si, d[3] * si } + end + mat.alphaMode = transparency > 0 and"blend" or"opaque" + mat.doubleSided = m.twoSided + local maps= {} + for kind, mp in __iter(m.maps) do + local ref = texture(mp) + maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture } + if kind == "diffuse" then + mat.baseColorTexture = ref + elseif kind == "selfIllum" and ref then + mat.emissiveTexture = ref + if si <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + mat.extras = { + ["3ds"] = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess, + shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum, + shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps, + }, + } + table.insert(scene.materials, mat) + local key = string.lower(m.name) + if byName[key] == nil then + byName[key] = i + end + end + return byName +end + +-- ------------------------------------------------------------------------------------------------ meshes +-- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved +-- by xf (world -> the node's local space) +local function mesh(name, m, xf, matByName, opts) +local nv, nf = m.nv, m.nf + local pos, faces = m.positions, m.faces + -- local positions + local lp = table.create(nv * 3, 0) + for v = 0, nv - 1 do + local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) + lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z + end + -- faces with valid corners, their materials + local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) + local valid = table.create(nf, false) + for f = 0, nf - 1 do + local a, b, c = readu16(faces , f * 8), readu16(faces , f * 8 + 2), readu16(faces , f * 8 + 4) + fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c + valid[f + 1] = a < nv and b < nv and c < nv + end + local fmat = table.create(nf, 0) + for _, fm in __iter(m.faceMats) do + local mi = matByName[string.lower(fm.name)] or 0 + for _, f in __iter(fm.faces) do + if f < nf then + fmat[f + 1] = mi + end + end + end + local smooth = m.smoothing + local doNormals = opts.normals ~= false + -- face normals (area weighted) and the faces around each distinct position + local fn = table.create(nf * 3, 0) + local around= {} + local group = table.create(nv, 0) + if doNormals then + local keyToGroup= {} + for v = 0, nv - 1 do + local k = buffer.readstring(pos, v * 12, 12) + local g = keyToGroup[k] + if not g then + g = v + keyToGroup[k] = g + end + group[v + 1] = g + end + for f = 1, nf do + if valid[f] then + local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3 + local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3] + local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3] + fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in __iter({ fa[f], fb[f], fc[f] }) do + local g = group[v + 1] + local list = around[g] + if not list then + list = {} + around[g] = list + end + if list[#list] ~= f then + table.insert(list, f) + end + end + end + end + end + local function sgOf(f) +return (smooth and{(readu32(smooth, (f - 1) * 4) )}or{1 +})[1] end + local function cornerNormal(f, v, sg) +local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] + if sg ~= 0 then + local sx, sy, sz = 0, 0, 0 + for _, g in __iter(around[group[v + 1] ]) do + if band(sgOf(g), sg) ~= 0 then + sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3] + end + end + local nx, ny, nz, l = normalize(sx, sy, sz) + if l > 0 then + return nx, ny, nz + end + end + local nx, ny, nz = normalize(x, y, z) + return nx, ny, nz + end + -- primitives in the order their material first appears + local order= {} + local byMat= {} + for f = 1, nf do + if valid[f] then + local mi = fmat[f] + if not byMat[mi] then + byMat[mi] = {} + table.insert(order, mi) + end + table.insert(byMat[mi], f) + end + end + local uvs, nuv = m.uvs, m.nuv + local flipV = opts.flipV ~= false + local out= { name = name, primitives = {} } + for _, mi in __iter(order) do + local list = byMat[mi] + local remap= {} + local P, N, U= {}, {}, {} + local idx = table.create(#list * 3, 0) + local sgs = table.create(#list, 0) + local count = 0 + for i, f in __iter(list) do + local sg = sgOf(f) + sgs[i] = sg + for k, v in __iter({ fa[f], fb[f], fc[f] }) do + local key = (not doNormals and{v }or{(sg ~= 0 and((v * 4294967296 + sg ))or((-(f * 65536 + v + 1) +)))})[1] local o= remap[key] or -1 + if o < 0 then + o = count + count =count+ 1 + remap[key] = o + P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] + if doNormals then + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg) + end + if uvs then + local u, w= 0, 0 + if v < nuv then + u = readf32(uvs, v * 8) + w = readf32(uvs, v * 8 + 4) + end + U[o * 2 + 1] = u + U[o * 2 + 2] = (flipV and((1 - w ))or(w +)) end + end + idx[(i - 1) * 3 + k] = o + end + end + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in __iter(idx) do + writeu32(ind.data, (i - 1) * 4, v) + end + local prim= { + attributes = { POSITION = floats(P, 3) }, + indices = ind, + mode = "triangles", + material = (mi > 0 and{mi }or{nil})[1], + extras = { ["3ds"] = { smoothing = sgs } }, + } + if doNormals then + prim.attributes.NORMAL = floats(N, 3) + end + if uvs then + prim.attributes.TEXCOORD_0 = floats(U, 2) + end + table.insert(out.primitives, prim) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ tracks +-- the value of a track at a frame (linear between keys, clamped at the ends) +local function evalTrack(t, frame, default) +if not t or #t.frames == 0 then + return default + end + local fr, vals, n = t.frames, t.values, t.size + local function at(k) +local r = table.create(n, 0) + for c = 1, n do + r[c] = vals[(k - 1) * n + c] + end + return r + end + if frame <= fr[1] then + return at(1) + end + for k = 1, #fr - 1 do + local f0, f1 = fr[k], fr[k + 1] + if frame <= f1 then + local u = (f1 > f0 and(((frame - f0) / (f1 - f0) ))or(1 +)) local a, b = at(k), at(k + 1) + for c = 1, n do + a[c]=a[c]+ (b[c] - a[c]) * u + end + return a + end + end + return at(#fr) +end + +local function first(t, default) +return evalTrack(t, -math.huge, default) +end + +local function scaleKey(v) +return { v[1] == 0 and 1 or v[1], v[2] == 0 and 1 or v[2], v[3] == 0 and 1 or v[3] } +end + +-- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys +local function rotations(t) +local frames, quats = {}, {} + local acc= nil + for k = 1, #t.frames do + local o = (k - 1) * 4 + local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4] + if acc == nil then + acc = keyQuat(angle, x, y, z) + else + local prev = acc +local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64) + local f0 = frames[#frames] + for s = 1, steps - 1 do + table.insert(frames, f0 + (t.frames[k] - f0) * s / steps) + table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z))) + end + acc = qmul(prev, keyQuat(angle, x, y, z)) + end + local q = acc +local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if n > 0 then + q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n } + end + acc = q + table.insert(frames, t.frames[k]) + table.insert(quats, q) + end + return frames, quats +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(raw, opts) +local o= opts or {} + local fps = o.fps or 30 + local scene = S.new() + local matByName = materials(raw, scene) + -- objects by name + local objByName= {} + for _, obj in __iter(raw.objects) do + if objByName[obj.name] == nil then + objByName[obj.name] = obj + end + local low = string.lower(obj.name) + if objByName[low] == nil then + objByName[low] = obj + end + end + local function findObj(name) +return objByName[name] or objByName[string.lower(name)] + end + local meshCache= {} + local function meshOf(obj, pivot, placed) +local m = obj.mesh + if not m or m.nf == 0 or not m.faces then + return nil + end + local pv = pivot or { 0, 0, 0 } + local key = obj.name .. ((placed and{(string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) )}or{"|free"})[1]) + if meshCache[key] then + return meshCache[key] + end + local M = meshMatrix(m.matrix) + local inv = Mat4.inverse(M) or Mat4.identity() + local xf = inv + if placed then + if det3(M) < 0 then + xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf) + end + xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf) + end + local me = mesh(obj.name, m, xf, matByName, o) + if #me.primitives == 0 then + return nil + end + table.insert(scene.meshes, me) + meshCache[key] = #scene.meshes + return #scene.meshes + end + local camIndex= {} + local function cameraOf(obj) +if camIndex[obj] then + return camIndex[obj] + end + local c = obj.camera +local hfov = (c.lens > 1e-3 and((2400 / c.lens ))or(45 +)) hfov = math.clamp(hfov, 0.01, 179) + local aspect = 4 / 3 + local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect) + local near = (c.near and c.near > 0 and{c.near }or{0.1 +})[1] local far = (c.far and c.far > near and{c.far }or{nil +})[1] local cam= { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + table.insert(scene.cameras, cam) + camIndex[obj] = #scene.cameras + return #scene.cameras + end + local lightIndex= {} + local function lightOf(obj) +if lightIndex[obj] then + return lightIndex[obj] + end + local l = obj.light +local L= { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier } + if l.spot then + L.type = "spot" + local hot = math.clamp(l.spot.hotspot, 0, 179.9) + local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9) + L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2 + end + if l.attenuate and l.outer and l.outer > 0 then + L.range = l.outer + end + table.insert(scene.lights, L) + lightIndex[obj] = #scene.lights + return #scene.lights + end + + local kf = raw.keyframer + local kfNodes = (kf and{kf.nodes }or{{} +})[1] -- targets of cameras / spotlights by name + local targets= {} + for _, n in __iter(kfNodes) do + if n.kind == "target" or n.kind == "lightTarget" then + targets[n.name] = targets[n.name] or n + end + end + local placedObj= {} + local sceneOf= {} -- kf id -> scene node + local channels= {} + local function channel(node, path, times, values, comps) + for i = 1, #times do + times[i]=times[i]/ fps + end + local ch= { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" } + table.insert(channels, ch) + end + local function addNode(n, parent) +table.insert(scene.nodes, n) + local i = #scene.nodes + if parent then + table.insert(scene.nodes[parent].children, i) + else + table.insert(scene.roots, i) + end + return i + end + + for k, kn in __iter(kfNodes) do +local __DARKLUA_CONTINUE_25=false repeat local kind = kn.kind + if kind == "target" or kind == "lightTarget" or kind == "ambient" then +__DARKLUA_CONTINUE_25=true break + end + local id = kn.id or (k - 1) + local parent = (kn.parent >= 0 and{sceneOf[kn.parent] }or{nil +})[1] local obj = findObj(kn.name) + local tr = kn.tracks + local name = (kn.instance and kn.instance ~= "" and{kn.instance }or{kn.name +})[1] local node= { name = name, children = {} } + local x3ds= { kind = kind, object = kn.name, id = id, pivot = kn.pivot } + node.extras = { ["3ds"] = x3ds } + local animated = false + if kind == "object" then + if obj and obj.mesh then + node.mesh = meshOf(obj, kn.pivot, true) + placedObj[obj] = true + x3ds.hidden = obj.hidden or nil + end + node.translation = first(tr.pos, { 0, 0, 0 }) + node.rotation = (tr.rot and #tr.rot.frames > 0 and{((select(2, rotations(tr.rot)) ))[1] }or{{ 0, 0, 0, 1 } +})[1] node.scale = scaleKey(first(tr.scl, { 1, 1, 1 })) + local ni = addNode(node, parent) + sceneOf[id] = ni + if tr.pos and #tr.pos.frames > 1 then + channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3) + end + if tr.rot and #tr.rot.frames > 1 then + local frames, quats = rotations(tr.rot) + local vals = {} + for _, q in __iter(quats) do + table.move(q, 1, 4, #vals + 1, vals) + end + channel(ni, "rotation", frames, vals, 4) + end + if tr.scl and #tr.scl.frames > 1 then + local vals = {} + for i = 1, #tr.scl.frames do + local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] }) + table.move(v, 1, 3, #vals + 1, vals) + end + channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) + end + else + -- cameras and lights: position, target, roll + local isCam = kind == "camera" + local cam = (obj and isCam and{obj.camera }or{nil +})[1] local lit = (obj and not isCam and{obj.light }or{nil +})[1] local tgt = targets[kn.name] + local basePos = (cam and{cam.pos }or{(lit and{lit.pos }or{{ 0, 0, 0 } +})[1]})[1] local baseTgt = (cam and{cam.target }or{(lit and lit.spot and{lit.spot.target }or{nil +})[1]})[1] local aims = isCam or kind == "spot" or baseTgt ~= nil + local function pose(frame) +local p = evalTrack(tr.pos, frame, basePos) + if not aims then + return p, nil + end + local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] }) + local roll = evalTrack(tr.roll, frame, { (cam and{cam.roll }or{0 })[1]})[1] + return p, Build.lookAt(p, t, roll) + end + local p0, r0 = pose(-math.huge) + node.translation, node.rotation = p0, r0 + if cam then + node.camera = cameraOf(obj ) + placedObj[obj ] = true + x3ds.lens, x3ds.roll = cam.lens, cam.roll + elseif lit then + node.light = lightOf(obj ) + placedObj[obj ] = true + x3ds.off = lit.off or nil + end + local ni = addNode(node, parent) + sceneOf[id] = ni + -- every key time of the position, roll and target tracks + local set= {} + local times= {} + for _, t in __iter({ tr.pos, tr.roll, (aims and tgt and{tgt.tracks.pos }or{nil })[1]}) do + if t and #t.frames > 1 then + animated = true + end + for _, f in __iter(((t and{t.frames }or{{}})[1])) do + if not set[f] then + set[f] = true + table.insert(times, f) + end + end + end + if animated then + table.sort(times) + local tv, rv = {}, {} + for _, f in __iter(times) do + local p, r = pose(f) + table.move(p, 1, 3, #tv + 1, tv) + if r then + table.move(r, 1, 4, #rv + 1, rv) + end + end + channel(ni, "translation", table.clone(times), tv, 3) + if aims then + channel(ni, "rotation", times, rv, 4) + end + end + end +__DARKLUA_CONTINUE_25=true until true if not __DARKLUA_CONTINUE_25 then break end end + -- objects the keyframer does not place (or files without one): at their own matrix / position + for _, obj in __iter(raw.objects) do +local __DARKLUA_CONTINUE_31=false repeat if placedObj[obj] then +__DARKLUA_CONTINUE_31=true break + end + local node= { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } } + if obj.mesh then + local mi = meshOf(obj, nil, false) + if not mi then +__DARKLUA_CONTINUE_31=true break + end + node.mesh = mi + if obj.mesh.matrix then + node.matrix = meshMatrix(obj.mesh.matrix) + end + elseif obj.camera then + local c = obj.camera + node.camera = cameraOf(obj) + node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll) + elseif obj.light then + local l = obj.light + node.light = lightOf(obj) + node.translation = l.pos + if l.spot then + node.rotation = Build.lookAt(l.pos, l.spot.target, 0) + end + else +__DARKLUA_CONTINUE_31=true break + end + addNode(node, nil) +__DARKLUA_CONTINUE_31=true until true if not __DARKLUA_CONTINUE_31 then break end end + if #channels > 0 then + table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels }) + end + scene.meta.up = "z" + scene.meta.source = { + format = "3ds", + version = raw.version, + meshVersion = raw.meshVersion, + masterScale = raw.masterScale, + ambient = raw.ambient, + keyframer = kf ~= nil, + frames = kf and kf.first and{ kf.first, kf.last } or nil, + fps = fps, + } + return scene +end + +return Build +end +__FILES["model/3ds/Read"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read +-- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their +-- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes +-- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). +-- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is +-- clipped to the parent. Never throws on bad data: returns nil, message, offset. +local Read = {} + +local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ chunk ids +local C = { + MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100, + RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031, + AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130, + UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620, + ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700, + CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010, + MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, + MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084, + MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351, + MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C, + KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011, + NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022, + TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028, +} +Read.C = C + +-- material map chunks -> their name in Raw materials +Read.MAPS = { + [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", + [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", +} +-- keyframer node chunks -> kind +local NODE_KINDS = { + [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", + [0xB006] = "lightTarget", [0xB007] = "spot", +} +-- track chunks -> (field, values per key) +local TRACKS= { + [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, + [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, +} +-- ------------------------------------------------------------------------------------------------ types + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +-- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error +-- ------------------------------------------------------------------------------------------------ helpers + + +local function each(ctx, p, stop, fn) +local b = ctx.b + while p + 6 <= stop do + local id, size = readu16(b, p), readu32(b, p + 2) + if size < 6 then + return nil, nil -- padding or garbage after the last chunk + end + local e = p + size + if e > ctx.limit then + return string.format("chunk 0x%04x runs past the end of the data", id), p + end + local err, at = fn(id, p + 6, math.min(e, stop)) + if err then + return err, at + end + p = e + end + return nil, nil +end + +-- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil +local function cstring(b, p, stop) +for q = p, stop - 1 do + if readu8(b, q) == 0 then + return buffer.readstring(b, p, q - p), q + 1 + end + end + return nil, stop +end + +local function vec3(b, p) +return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } +end + +-- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +local function color(ctx, p, stop) +local b = ctx.b + local main, lin= nil, nil + each(ctx, p, stop, function(id, q, e) +if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then + local c = vec3(b, q) + if id == C.RGBF then + main = main or c + else + lin = lin or c + end + elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then + local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 } + if id == C.RGBB then + main = main or c + else + lin = lin or c + end + end + return nil, nil + end) + return main or lin +end + +-- a percentage chunk list -> a fraction 0..1 +local function percent(ctx, p, stop) +local b = ctx.b + local v= nil + each(ctx, p, stop, function(id, q, e) +if v == nil and id == C.PERCENTW and e - q >= 2 then + v = readu16(b, q) / 100 + elseif v == nil and id == C.PERCENTF and e - q >= 4 then + v = readf32(b, q) / 100 + end + return nil, nil + end) + return v +end + +-- ------------------------------------------------------------------------------------------------ materials +local function map(ctx, p, stop) +local b = ctx.b + local m= {} + m.strength = percent(ctx, p, stop) + each(ctx, p, stop, function(id, q, e) +local n = e - q + if id == C.MAP_FILE then + m.file = cstring(b, q, e) + elseif id == C.MAP_TILING and n >= 2 then + m.tiling = readu16(b, q) + elseif n >= 4 then + local v = readf32(b, q) + if id == C.MAP_USCALE then + m.uscale = v + elseif id == C.MAP_VSCALE then + m.vscale = v + elseif id == C.MAP_UOFFSET then + m.uoffset = v + elseif id == C.MAP_VOFFSET then + m.voffset = v + elseif id == C.MAP_ANGLE then + m.angle = v + end + end + return nil, nil + end) + return m +end + +local function material(ctx, p, stop) + local b = ctx.b + local m= { name = "", twoSided = false, wire = false, maps = {} } + each(ctx, p, stop, function(id, q, e) +if id == C.MAT_NAME then + m.name = cstring(b, q, e) or "" + elseif id == C.MAT_AMBIENT then + m.ambient = color(ctx, q, e) + elseif id == C.MAT_DIFFUSE then + m.diffuse = color(ctx, q, e) + elseif id == C.MAT_SPECULAR then + m.specular = color(ctx, q, e) + elseif id == C.MAT_SHININESS then + m.shininess = percent(ctx, q, e) + elseif id == C.MAT_SHIN_STRENGTH then + m.shinStrength = percent(ctx, q, e) + elseif id == C.MAT_TRANSPARENCY then + m.transparency = percent(ctx, q, e) + elseif id == C.MAT_SELF_ILPCT then + m.selfIllum = percent(ctx, q, e) + elseif id == C.MAT_TWO_SIDE then + m.twoSided = true + elseif id == C.MAT_WIRE then + m.wire = true + elseif id == C.MAT_SHADING and e - q >= 2 then + m.shading = readu16(b, q) + elseif Read.MAPS[id] then + m.maps[Read.MAPS[id] ] = map(ctx, q, e) + end + return nil, nil + end) + table.insert(ctx.raw.materials, m) +end + +-- ------------------------------------------------------------------------------------------------ objects +local function faceList(ctx, mesh, p, stop) +local b = ctx.b + if stop - p < 2 then + return "truncated face list", p + end + local nf = readu16(b, p) + if p + 2 + nf * 8 > stop then + return "face list runs past its chunk", p + end + local faces = buffer.create(nf * 8) + buffer.copy(faces, 0, b, p + 2, nf * 8) + mesh.nf, mesh.faces = nf, faces + return each(ctx, p + 2 + nf * 8, stop, function(id, q, e) +if id == C.FACE_MAT then + local name, r = cstring(b, q, e) + if not name or r + 2 > e then + return "bad face material list", q + end + local n = readu16(b, r) + if r + 2 + n * 2 > e then + return "face material list runs past its chunk", q + end + local list= {} + for i = 0, n - 1 do + list[i + 1] = readu16(b, r + 2 + i * 2) + end + table.insert(mesh.faceMats, { name = name, faces = list }) + elseif id == C.SMOOTH then + local n = math.min(nf, math.floor((e - q) / 4)) + local s = buffer.create(nf * 4) + buffer.copy(s, 0, b, q, n * 4) + mesh.smoothing = s + end + return nil, nil + end) +end + +local function trimesh(ctx, p, stop) +local b = ctx.b + local mesh= { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} } + local err, at = each(ctx, p, stop, function(id, q, e) +if id == C.VERTICES or id == C.UVS then + if e - q < 2 then + return "truncated vertex list", q + end + local n = readu16(b, q) + local size = id == C.VERTICES and 12 or 8 + if q + 2 + n * size > e then + return "vertex list runs past its chunk", q + end + local data = buffer.create(n * size) + buffer.copy(data, 0, b, q + 2, n * size) + if id == C.VERTICES then +do local __DARKLUA_VAR= ctx.raw __DARKLUA_VAR.vertices =__DARKLUA_VAR.vertices+ n +end if ctx.raw.vertices > ctx.maxVertices then + return "limit: more than " .. ctx.maxVertices .. " vertices", q + end + mesh.nv, mesh.positions = n, data + else + mesh.nuv, mesh.uvs = n, data + end + elseif id == C.FACES then + return faceList(ctx, mesh, q, e) + elseif id == C.MATRIX and e - q >= 48 then + local m= {} + for i = 0, 11 do + m[i + 1] = readf32(b, q + i * 4) + end + mesh.matrix = m + end + return nil, nil + end) + if err then + return nil, err, at + end + return mesh, nil, nil +end + +local function camera(ctx, p, stop) +local b = ctx.b + if stop - p < 32 then + return nil + end + local cam= { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) } + each(ctx, p + 32, stop, function(id, q, e) +if id == C.CAM_RANGES and e - q >= 8 then + cam.near, cam.far = readf32(b, q), readf32(b, q + 4) + end + return nil, nil + end) + return cam +end + +local function light(ctx, p, stop) +local b = ctx.b + if stop - p < 12 then + return nil + end + local l= { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false } + l.color = color(ctx, p + 12, stop) or l.color + each(ctx, p + 12, stop, function(id, q, e) +local n = e - q + if id == C.SPOT and n >= 20 then + l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) } + elseif id == C.LIGHT_OFF then + l.off = true + elseif id == C.ATTENUATE then + l.attenuate = true + elseif id == C.MULTIPLIER and n >= 4 then + l.multiplier = readf32(b, q) + elseif id == C.INNER_RANGE and n >= 4 then + l.inner = readf32(b, q) + elseif id == C.OUTER_RANGE and n >= 4 then + l.outer = readf32(b, q) + end + return nil, nil + end) + return l +end + +local function object(ctx, p, stop) +local b = ctx.b + local name, q = cstring(b, p, stop) + if not name then + return "object without a name", p + end + local obj= { name = name, hidden = false } + local err, at = each(ctx, q, stop, function(id, r, e) +if id == C.TRIMESH then + local mesh, merr, mat = trimesh(ctx, r, e) + if not mesh then + return merr, mat + end + obj.mesh = mesh + elseif id == C.CAMERA then + obj.camera = camera(ctx, r, e) + elseif id == C.LIGHT then + obj.light = light(ctx, r, e) + elseif id == C.OBJ_HIDDEN then + obj.hidden = true + end + return nil, nil + end) + if err then + return err, at + end + table.insert(ctx.raw.objects, obj) + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ keyframer +-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of +-- tension / continuity / bias / ease to / ease from), then the values +local function track(b, p, stop, size) +if stop - p < 14 then + return nil + end + local flags, n = readu16(b, p), readu32(b, p + 10) + local t= { frames = {}, values = {}, size = size, flags = flags } + p =p+ 14 + for _ = 1, n do + if p + 6 > stop then + break + end + local frame, spline = readu32(b, p), readu16(b, p + 4) + p =p+ 6 + for bit = 0, 4 do + if band(spline, bit32.lshift(1, bit)) ~= 0 then + p =p+ 4 + end + end + if p + size * 4 > stop then + break + end + table.insert(t.frames, frame) + for k = 0, size - 1 do + table.insert(t.values, readf32(b, p + k * 4)) + end + p =p+ size * 4 + end + return t +end + +local function node(ctx, kind, p, stop, list) + local b = ctx.b + local n= { kind = kind, name = "", parent = -1, flags = 0, tracks = {} } + each(ctx, p, stop, function(id, q, e) +if id == C.NODE_ID and e - q >= 2 then + n.id = readu16(b, q) + elseif id == C.NODE_HDR then + local name, r = cstring(b, q, e) + n.name = name or "" + if r + 6 <= e then + n.flags = readu16(b, r) + n.parent = readi16(b, r + 4) + end + elseif id == C.NODE_INSTANCE then + n.instance = cstring(b, q, e) + elseif id == C.NODE_PIVOT and e - q >= 12 then + n.pivot = vec3(b, q) + elseif TRACKS[id] then + local spec = TRACKS[id] + n.tracks[spec[1] ] = track(b, q, e, spec[2]) + end + return nil, nil + end) + table.insert(list, n) +end + +local function keyframer(ctx, p, stop) + local b = ctx.b + local kf = { nodes = {} , name = nil , length = nil , first = nil , last = nil } + each(ctx, p, stop, function(id, q, e) +if id == C.KF_HDR and e - q >= 2 then + local name, r = cstring(b, q + 2, e) + kf.name = name + if r + 4 <= e then + kf.length = readu32(b, r) + end + elseif id == C.KF_FRAMES and e - q >= 8 then + kf.first, kf.last = readu32(b, q), readu32(b, q + 4) + elseif NODE_KINDS[id] then + node(ctx, NODE_KINDS[id], q, e, kf.nodes) + end + return nil, nil + end) + ctx.raw.keyframer = kf +end + +-- ------------------------------------------------------------------------------------------------ parse +local function editor(ctx, p, stop) +local b = ctx.b + return each(ctx, p, stop, function(id, q, e) +if id == C.MATERIAL then + material(ctx, q, e) + elseif id == C.OBJECT then + return object(ctx, q, e) + elseif id == C.MESH_VERSION and e - q >= 4 then + ctx.raw.meshVersion = readu32(b, q) + elseif id == C.MASTER_SCALE and e - q >= 4 then + ctx.raw.masterScale = readf32(b, q) + elseif id == C.AMBIENT_LIGHT then + ctx.raw.ambient = color(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) -- some writers nest it here + end + return nil, nil + end) +end + +-- parse(b, base, limit, opts) -> Raw | nil, message, offset +function Read.parse(b, base, limit, opts) +if limit - base < 6 or readu16(b, base) ~= C.MAIN then + return nil, "not a 3DS file (no 0x4D4D main chunk)", base + end + local raw= { materials = {}, objects = {}, vertices = 0 } + local ctx= { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw } + local size = readu32(b, base + 2) + if size < 6 then + return nil, "bad main chunk size", base + end + -- a main chunk declared longer than the data: truncated + if base + size > limit then + return nil, "truncated: the main chunk runs past the end of the data", base + end + local err, at = each(ctx, base + 6, base + size, function(id, q, e) +if id == C.VERSION and e - q >= 4 then + raw.version = readu32(b, q) + elseif id == C.EDITOR then + return editor(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) + end + return nil, nil + end) + if err then + return nil, err, at + end + return raw, nil, nil +end + +return Read +end +__FILES["model/3ds/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world +-- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's +-- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 +-- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with +-- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and +-- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in +-- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key +-- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. +-- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Sampler = __include("codecs/model/Sampler") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Read = __include("model/3ds/Read") +local Build = __include("model/3ds/Build") + +local Write = {} + +local C = Read.C +local S = Types.Scene +local writeu32 = buffer.writeu32 +local sqrt, abs = math.sqrt, math.abs +-- ------------------------------------------------------------------------------------------------ chunks + + + + +local function open(w, id) +local at = w.pos + w:u16le(id) + w:u32le(0) + return at +end +local function close(w, at) + writeu32(w.buf, at + 2, w.pos - at) +end +local function leaf(w, id, fn) + local at = open(w, id) + fn() + close(w, at) +end +local function name(s, fallback) +local n = string.gsub(s or "", "%z", "") + if n == "" then + n = fallback + end + return string.sub(n, 1, 63) +end + +local function colorChunk(w, id, c) + leaf(w, id, function() + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(c[k] or 0) + end + end) + leaf(w, C.RGBB, function() + for k = 1, 3 do + w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255)) + end + end) + end) +end +local function percentChunk(w, id, v) + leaf(w, id, function() + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100)) + end) + leaf(w, C.PERCENTF, function() + w:f32le(v * 100) + end) + end) +end + +-- ------------------------------------------------------------------------------------------------ math +local function world(scene) +local W= {} + local parent= {} + local order= {} + local function visit(i, p, pm, depth) + local n = scene.nodes[i] + if type(n) ~= "table" or W[i] or depth > 256 then + return + end + W[i] = S.mul(pm, S.nodeMatrix(n)) + parent[i] = p or 0 + table.insert(order, i) + for _, c in __iter(n.children or {}) do + visit(c, i, W[i], depth + 1) + end + end + for _, r in __iter(scene.roots) do + visit(r, nil, S.IDENTITY, 0) + end + return W, parent, order +end + +local function col(m, c) +return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3] +end +local function unit(x, y, z) +local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0 + end + return x / l, y / l, z / l +end + +-- a quaternion -> the 3DS (clockwise angle, axis) +local function axisAngle(q) +local x, y, z, w = q[1], q[2], q[3], q[4] + local n = sqrt(x * x + y * y + z * z + w * w) + if n < 1e-30 then + return 0, 0, 0, 0 + end + x, y, z, w = x / n, y / n, z / n, w / n + local s = sqrt(x * x + y * y + z * z) + if s < 1e-12 then + return 0, 0, 0, 0 + end + local angle = 2 * math.atan2(s, w) + return -angle, x / s, y / s, z / s +end + +local function conj(q) +return { -q[1], -q[2], -q[3], q[4] } +end + +-- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) +local function sample(ch, t) +local f = Sampler.channel(ch) + if not f then + return ch.path == "rotation" and{ 0, 0, 0, 1 } or{ 0, 0, 0 } + end + return f(t) +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" } + +local function textureFiles(scene, opts) +local files = opts.files + local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture" + local out= {} + for i, tex in __iter(scene.textures) do + local file = tex.uri + if not file or file == "" or string.sub(file, 1, 5) == "data:" then + file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + if tex.data and type(files) == "table" then + files[file] = tex.data + end + end + out[i] = file + end + return out +end + +local MAP_IDS= {} +for id, kind in __iter(Read.MAPS) do + MAP_IDS[kind] = id +end +local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" } + +local function writeMaterial(w, m, mname, files) + local x = (m.extras and m.extras["3ds"] or {}) +local bc = m.baseColor or { 1, 1, 1, 1 } + local diffuse = { bc[1], bc[2], bc[3] } + local shininess = math.clamp(1 - (m.roughness or 1), 0, 1) + local transparency = math.clamp(1 - (bc[4] or 1), 0, 1) + local e = m.emissive or { 0, 0, 0 } + local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1) + local at = open(w, C.MATERIAL) + leaf(w, C.MAT_NAME, function() + w:cstring(mname) + end) + colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse) + colorChunk(w, C.MAT_DIFFUSE, diffuse) + colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 }) + percentChunk(w, C.MAT_SHININESS, shininess) + percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5) + percentChunk(w, C.MAT_TRANSPARENCY, transparency) + percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum) + leaf(w, C.MAT_SHADING, function() + w:u16le(x.shading or 3) + end) + if m.doubleSided then + leaf(w, C.MAT_TWO_SIDE, function() end) + end + if x.wire then + leaf(w, C.MAT_WIRE, function() end) + end + -- maps: the PBR texture refs first, then the other kinds model/3ds read + local maps= {} + local function fromRef(ref, saved) +if not ref or not files[ref.texture] then + return nil + end + local s = saved or {} + local tf = ref.transform + return { + file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling, + uscale = (tf and tf.scale and{tf.scale[1] }or{s.uscale})[1], vscale = (tf and tf.scale and{tf.scale[2] }or{s.vscale})[1], + uoffset = (tf and tf.offset and{tf.offset[1] }or{s.uoffset})[1], voffset = (tf and tf.offset and{tf.offset[2] }or{s.voffset})[1], + angle = (tf and tf.rotation and{(math.deg(tf.rotation) )}or{s.angle})[1], + } + end + local saved = (x.maps or {}) +maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) + maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum) + for kind, s in __iter(saved) do + if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then + maps[kind] = fromRef(s.texture and{ texture = s.texture } or nil, s) + end + end + for _, kind in __iter(MAP_ORDER) do + local mp = maps[kind] + if mp then + local mat = open(w, MAP_IDS[kind]) + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100)) + end) + leaf(w, C.MAP_FILE, function() + w:cstring(name(mp.file, "texture")) + end) + if mp.tiling then + leaf(w, C.MAP_TILING, function() + w:u16le(mp.tiling) + end) + end + for _, f in __iter({ { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } }) do + local v = f[2] + if type(v) == "number" then + leaf(w, f[1], function() + w:f32le(v) + end) + end + end + close(w, mat) + end + end + close(w, at) +end +-- ------------------------------------------------------------------------------------------------ meshes +-- the mesh as 3DS parts (local space), or nil, message + + + +local function parts(mesh, base, opts) +local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n) +return n == "TEXCOORD_0" or n == "NORMAL" + end, { triangulate = true }) + if not merged then + return nil, err + end + local P = merged.attrs.POSITION.values + local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values + local T = merged.attrs.TEXCOORD_0 + local tv, tc = (T and{T.values }or{nil})[1], (T and{T.components }or{0 +})[1] local flipV = opts.flipV ~= false + local corners = merged.corners + -- per face: material, smoothing group + local nf = math.floor(#corners / 3 +) local fmat, fsg = table.create(nf, 0), table.create(nf, 1) + for _, part in __iter(merged.parts) do + local prim= part.prim + local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing + local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles" + for f = part.firstFace + 1, part.firstFace + part.faceCount do + fmat[f] = (type(prim.material) == "number" and{prim.material }or{0 +})[1] if savedOk then + fsg[f] = saved[f - part.firstFace] + elseif N then + -- flat when every corner normal is the face normal + local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] + local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } + local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } + local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]) + local flat = true + for _, v in __iter({ a, b, c }) do + local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3]) + if vx * nx + vy * ny + vz * nz < 0.9998 then + flat = false + end + end + fsg[f] = flat and 0 or 1 + end + end + end + local out= {} + local cur= nil + local remap= {} + local count = 0 + for f = 1, nf do + local fresh = 0 + for k = 1, 3 do + if not remap[corners[f * 3 - 3 + k] ] then + fresh =fresh+ 1 + end + end + if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then + cur = { name = (#out == 0 and{base }or{(string.sub(base, 1, 56) .. "." .. #out)})[1], positions = {}, uvs = tv and{} or nil, faces = {}, smooth = {}, mats = {} } + table.insert(out, cur ) + remap, count = {}, 0 + end + local p = cur +for k = 1, 3 do + local v = corners[f * 3 - 3 + k] + local o = remap[v] + if not o then + o = count + count =count+ 1 + remap[v] = o + table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions) + if tv and p.uvs then + local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0 + table.insert(p.uvs, u) + table.insert(p.uvs, (flipV and((1 - vv ))or(vv))) + end + end + table.insert(p.faces, o) + end + table.insert(p.smooth, fsg[f]) + local mi = fmat[f] + if mi > 0 then + p.mats[mi] = p.mats[mi] or {} + table.insert(p.mats[mi], #p.smooth - 1) + end + end + return out, nil +end + +local function writeMesh(w, part, M, matNames) + local at = open(w, C.OBJECT) + w:cstring(part.name) + local tm = open(w, C.TRIMESH) + local nv = math.floor(#part.positions / 3 +) leaf(w, C.VERTICES, function() + w:u16le(nv) + local p = part.positions + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3]) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + if part.uvs then + local uvs = part.uvs + leaf(w, C.UVS, function() + w:u16le(nv) + for i = 1, nv * 2 do + w:f32le(uvs[i] or 0) + end + end) + end + leaf(w, C.MATRIX, function() + for _, c in __iter({ 0, 1, 2, 3 }) do + local x, y, z = col(M, c) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + local fl = open(w, C.FACES) + local nf = #part.smooth + w:u16le(nf) + for f = 0, nf - 1 do + w:u16le(part.faces[f * 3 + 1]) + w:u16le(part.faces[f * 3 + 2]) + w:u16le(part.faces[f * 3 + 3]) + w:u16le(7) -- edges AB, BC, CA visible + end + local mats= {} + for mi in __iter(part.mats) do + table.insert(mats, mi) + end + table.sort(mats) + for _, mi in __iter(mats) do + local list = part.mats[mi] + leaf(w, C.FACE_MAT, function() + w:cstring(matNames[mi]) + w:u16le(#list) + for _, f in __iter(list) do + w:u16le(f) + end + end) + end + leaf(w, C.SMOOTH, function() + for _, s in __iter(part.smooth) do + w:u32le(s) + end + end) + close(w, fl) + close(w, tm) + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ cameras / lights +-- the eye, target and roll of a node's world matrix (looking down -Z, Y up) +local function aim(m, dist) +local p = { m[13], m[14], m[15] } + local fx, fy, fz = unit(-m[9], -m[10], -m[11]) + if fx == 0 and fy == 0 and fz == 0 then + fx, fy, fz = 0, 0, -1 + end + local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } + -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis + local q0 = Build.lookAt(p, t, 0) + local m0 = Mat4.fromQuat(q0) + local ux, uy, uz = unit(m[5], m[6], m[7]) + local cu = ux * m0[5] + uy * m0[6] + uz * m0[7] + local cr = ux * m0[1] + uy * m0[2] + uz * m0[3] + return p, t, math.deg(math.atan2(-cr, cu)) +end + +local function writeCamera(w, cname, cam, m, dist) + local p, t, roll = aim(m, dist) + local aspect = cam.aspect or 4 / 3 + local yfov = (cam.type == "perspective" and cam.yfov and{cam.yfov }or{(math.rad(45) +)})[1] local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect)) + local at = open(w, C.OBJECT) + w:cstring(cname) + local c = open(w, C.CAMERA) + for _, v in __iter({ p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) }) do + w:f32le(v) + end + leaf(w, C.CAM_RANGES, function() + w:f32le(cam.znear or 0) + w:f32le(cam.zfar or 1000) + end) + close(w, c) + close(w, at) +end + +local function writeLight(w, lname, l, m, dist) + local p, t = aim(m, dist) + local at = open(w, C.OBJECT) + w:cstring(lname) + local c = open(w, C.LIGHT) + for k = 13, 15 do + w:f32le(m[k]) + end + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(l.color and l.color[k] or 1) + end + end) + if l.type ~= "point" then + local inner = (l.type == "spot" and{(l.innerCone or 0) }or{(math.rad(45) +)})[1] local outer = (l.type == "spot" and{(l.outerCone or math.pi / 4) }or{(math.rad(45) +)})[1] leaf(w, C.SPOT, function() + for k = 1, 3 do + w:f32le(t[k]) + end + w:f32le(math.deg(inner * 2)) + w:f32le(math.deg(math.max(outer, inner) * 2)) + end) + end + if l.range and l.range > 0 then + leaf(w, C.ATTENUATE, function() end) + leaf(w, C.OUTER_RANGE, function() + w:f32le(l.range ) + end) + end + leaf(w, C.MULTIPLIER, function() + w:f32le(l.intensity or 1) + end) + close(w, c) + close(w, at) + return p +end + +-- ------------------------------------------------------------------------------------------------ keyframer +local function writeTrack(w, id, frames, values, size) + leaf(w, id, function() + w:u16le(0) + w:u32le(0) + w:u32le(0) + w:u32le(#frames) + for k, f in __iter(frames) do + w:u32le(f) + w:u16le(0) + for c = 1, size do + w:f32le(values[(k - 1) * size + c]) + end + end + end) +end + +-- frames (rounded, strictly increasing) and the indices of the channel keys they keep + + + + + +local function frameKeys(ch, fps) +local IN = (S.reader(ch.input) ) +local frames, keep = {}, {} + for k = 0, ch.input.count - 1 do + local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5)) + if #frames == 0 or f > frames[#frames] then + table.insert(frames, f) + table.insert(keep, k) + end + end + return frames, keep +end + +local function channelValues(ch, keep, comps) +local OUT = (S.reader(ch.output) ) +local cubic = ch.interpolation == "CUBICSPLINE" + local out = {} + for _, k in __iter(keep) do + local e = (cubic and((k * 3 + 1 ))or(k +)) local v = table.create(comps, 0) + for c = 1, comps do + v[c] = OUT(e, c - 1) + end + table.insert(out, v) + end + return out +end + +local function rotTrack(quats) +local vals = {} + local prev= nil + for _, q in __iter(quats) do + local d = q + if prev then + d = Build.qmul(conj(prev), q) + if d[4] < 0 then + d = { -d[1], -d[2], -d[3], -d[4] } + end + end + local a, x, y, z = axisAngle(d) + table.insert(vals, a) + table.insert(vals, x) + table.insert(vals, y) + table.insert(vals, z) + prev = q + end + return vals +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene, opts) +local o= opts or {} + local fps = o.fps or 30 + local W, parentOf, order = world(scene) + local w = Bytes.writer(65536) + local main = open(w, C.MAIN) + leaf(w, C.VERSION, function() + w:u32le(3) + end) + local ed = open(w, C.EDITOR) + leaf(w, C.MESH_VERSION, function() + w:u32le(3) + end) + -- materials (unique names) + local files = textureFiles(scene, o) + local matNames= {} + local used= {} + local function unique(base) +local n, k = base, 1 + while used[string.lower(n)] do + k =k+ 1 + n = string.sub(base, 1, 56) .. "_" .. k + end + used[string.lower(n)] = true + return n + end + for i, m in __iter(scene.materials) do + matNames[i] = unique(name(m.name, "Material" .. i)) + writeMaterial(w, m, matNames[i], files) + end + leaf(w, C.MASTER_SCALE, function() + w:f32le(1) + end) + -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) + used = {} + local firstNode= {} + for _, i in __iter(order) do + local mi = scene.nodes[i].mesh + if mi and scene.meshes[mi] and not firstNode[mi] then + firstNode[mi] = i + end + end + local meshParts= {} + local meshM= {} + for mi, mesh in __iter(scene.meshes) do +local __DARKLUA_CONTINUE_37=false repeat local ni = firstNode[mi] + if ni == nil and #scene.nodes > 0 then +__DARKLUA_CONTINUE_37=true break + end + local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o) + if not list then + return nil, err + end + local M = (ni and{W[ni] }or{S.IDENTITY +})[1] if not Mat4.inverse(M) then + M = S.IDENTITY + end + meshParts[mi], meshM[mi] = list, M + for _, part in __iter(list) do + used[string.lower(part.name)] = true + writeMesh(w, part, M, matNames) + end +__DARKLUA_CONTINUE_37=true until true if not __DARKLUA_CONTINUE_37 then break end end + -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors + local KW= {} + for _, i in __iter(order) do + local n = scene.nodes[i] + local m = W[i] + if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then + m = S.mul(m, Mat4.scaling(-1, 1, 1)) + end + KW[i] = m + end + local kfs= {} + local kfOf= {} + local anim = scene.animations[1] + local byNode= {} + if anim then + for _, ch in __iter(anim.channels) do + if ch.path ~= "weights" then + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + end + local lastFrame = 0 + local function single(v) +return table.clone(v) + end + for _, i in __iter(order) do +local __DARKLUA_CONTINUE_41=false repeat local n = scene.nodes[i] + local p = parentOf[i] + local pk = (p ~= 0 and{kfOf[p] }or{nil +})[1] local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) + local dist = 100 + local function placeCamLight(kind, objName, tgtChunk) + local pos, tgt, roll = aim(W[i], dist) + local kn= { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } + table.insert(kfs, kn) + local idx = #kfs + -- animated root cameras / lights: position, target and roll at the key times + local chs= (p == 0 and{byNode[i] }or{nil +})[1] local targetFrames, targetVals = { 0 }, tgt + if chs and (chs.translation or chs.rotation) then + local fr= {} + local frames= {} + local list= {} + table.insert(list, chs.translation) + table.insert(list, chs.rotation) + for _, ch in __iter(list) do + for _, f in __iter((frameKeys(ch, fps))) do + if not fr[f] then + fr[f] = true + table.insert(frames, f) + end + end + end + table.sort(frames) + local pv, tv, rv = {}, {}, {} + for _, f in __iter(frames) do + local t = f / fps + local ct, cr = chs.translation, chs.rotation + local tr = (ct and{(sample(ct, t) )}or{{ W[i][13], W[i][14], W[i][15] } +})[1] local rq = (cr and{(sample(cr, t) )}or{(n.rotation or { 0, 0, 0, 1 }) +})[1] local sc = n.scale or { 1, 1, 1 } + local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist) + table.move(ps, 1, 3, #pv + 1, pv) + table.move(ts, 1, 3, #tv + 1, tv) + table.insert(rv, rs) + lastFrame = math.max(lastFrame, f) + end + kn.frames.pos, kn.values.pos = frames, pv + kn.frames.roll, kn.values.roll = frames, rv + targetFrames, targetVals = frames, tv + end + if tgtChunk then + table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } }) + end + if kind ~= 0xB003 then + kn.frames.roll, kn.values.roll = nil , nil +end + return idx + end + local function camLight(onlyThis) +if not camOrLight then + return nil + end + local idx= nil + if n.camera and scene.cameras[n.camera] then + local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera)) + writeCamera(w, cname, scene.cameras[n.camera], W[i], dist) + idx = placeCamLight(0xB003, cname, 0xB004) + end + if n.light and scene.lights[n.light] then + local l = scene.lights[n.light] + local lname = unique(name(l.name or n.name, "Light" .. n.light)) + writeLight(w, lname, l, W[i], dist) + local k = placeCamLight(l.type == "point" and 0xB005 or 0xB007, lname, (l.type == "point" and{nil }or{0xB006})[1]) + idx = idx or k + end + if onlyThis and idx then + kfOf[i] = idx + -- the node's frame in the keyframer: the camera / light pose + local kn = kfs[idx] + local pos = kn.values.pos + local m= W[i] + if kn.chunk == 0xB005 then + KW[i] = Mat4.translation(pos[1], pos[2], pos[3]) + else + local _, tgt, roll = aim(m, dist) + KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, (kn.chunk == 0xB003 and{roll }or{0})[1]), nil) + end + end + return idx + end + if n.mesh == nil and camOrLight then + camLight(true) +__DARKLUA_CONTINUE_41=true break + end + -- an object node (or a dummy) with the node's transform relative to its keyframer parent + local pkw = (p ~= 0 and kfOf[p] and{KW[p] }or{S.IDENTITY +})[1] local inv = Mat4.inverse(pkw) or Mat4.identity() + local L = S.mul(inv, KW[i]) + local t, r, s = Mat4.decompose(L) + local plist = (n.mesh and{meshParts[n.mesh] }or{nil +})[1] local objName = (plist and{plist[1].name }or{"$$$DUMMY" +})[1] local instance = (plist and n.name and n.name ~= objName and{(name(n.name, objName) )}or{(not plist and{(name(n.name, "Dummy" .. i) )}or{nil +})[1]})[1] local kn= { chunk = 0xB002, name = objName, instance = instance, parent = (pk and((pk - 1 ))or((-1))), frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } + -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) + local chs = byNode[i] + if chs then + local own = S.nodeMatrix(n) + local same = true + for k = 1, 16 do + if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then + same = false + end + end + if same then + for path, field in __iter({ translation = "pos", rotation = "rot", scale = "scl" }) do + local ch = chs[path] + if ch then + local frames, keep = frameKeys(ch, fps) + local vals = channelValues(ch, keep, path == "rotation" and 4 or 3) + lastFrame = math.max(lastFrame, frames[#frames] or 0) + kn.frames[field] = frames + if path == "rotation" then + kn.values[field] = rotTrack(vals) + else + local flat = {} + for _, v in __iter(vals) do + table.move(v, 1, 3, #flat + 1, flat) + end + kn.values[field] = flat + end + end + end + end + end + table.insert(kfs, kn) + kfOf[i] = #kfs + for k = 2, (plist and((#plist ))or(0 ))do + local extra = table.clone(kn) + extra.name, extra.instance = (plist )[k].name, nil + table.insert(kfs, extra) + end + camLight(false) +__DARKLUA_CONTINUE_41=true until true if not __DARKLUA_CONTINUE_41 then break end end + close(w, ed) + -- the keyframer + local kf = open(w, C.KEYFRAMER) + leaf(w, C.KF_HDR, function() + w:u16le(5) + w:cstring("MAXSCENE") + w:u32le(math.max(lastFrame, 100)) + end) + leaf(w, C.KF_FRAMES, function() + w:u32le(0) + w:u32le(math.max(lastFrame, 100)) + end) + for id, kn in __iter(kfs) do + local nc = open(w, kn.chunk) + leaf(w, C.NODE_ID, function() + w:u16le(id - 1) + end) + leaf(w, C.NODE_HDR, function() + w:cstring(kn.name) + w:u16le(0x4000) + w:u16le(0) + w:u16le((kn.parent >= 0 and{kn.parent }or{0xFFFF})[1]) + end) + if kn.instance then + leaf(w, C.NODE_INSTANCE, function() + w:cstring(kn.instance ) + end) + end + if kn.chunk == 0xB002 then + leaf(w, C.NODE_PIVOT, function() + w:f32le(0) + w:f32le(0) + w:f32le(0) + end) + end + for _, tr in __iter({ { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } }) do + local field = tr[1] +local frames = kn.frames[field] + if frames then + writeTrack(w, tr[2] , frames, kn.values[field], tr[3] ) + end + end + close(w, nc) + end + close(w, kf) + close(w, main) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/3mf"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, +-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts +-- (codecs/text/Xml). +-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from +-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices +-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata +-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours +-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to +-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it +-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first +-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices +-- are split where a vertex's corners carry different colours / texture coordinates. +-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a +-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, +-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). +-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are +-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Read = __include("model/3mf/Read") +local Write = __include("model/3mf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeMf = { + name = "3mf", + category = "model", + extensions = { "3mf" }, + mime = { "model/3mf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + +function ThreeMf.sniff(r) +if r:peek(4) ~= "PK\3\4" then + return 0 + end + -- the central directory sits at the end: look for the model part's name there, then at the start + local n = r:size() + local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) + if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then + return 0.95 + end + local head = r:peek(256) + if string.find(head, "3D/", 1, true) then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeMf.decode(r, opts) +local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local ok, scene, err = pcall(Read.scene, zip, opts or {}) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")") + end + return scene, err +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeMf.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then + return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit)) + end + local ok, out, err = pcall(Write.build, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")") + end + return out, err +end + +return ThreeMf +end +__FILES["model/3mf/Read"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first +-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), +-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension +-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, +-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. +-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and +-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Read = {} + +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +Read.UNITS = UNITS +local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" } +local MAX_DEPTH = 64 + +local localName = Xml.localName + +-- an attribute by local name (namespaced attributes such as p:path) +local function attr(node, name) +local a = node.attrs + local v = a[name] + if v ~= nil then + return v + end + for k, x in next, a do + if type(k) == "string" and localName(k) == name then + return x + end + end + return nil +end + +local function int(s) +local n = (s and{(tonumber(s) )}or{nil +})[1] if n and n == math.floor(n) and n >= 0 then + return n + end + return nil +end + +-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +local function hexColor(s) +if type(s) ~= "string" then + return nil + end + local h = string.match(s, "^%s*#(%x+)%s*$") + if not h or (#h ~= 6 and #h ~= 8) then + return nil + end + local function c(i) +return ((tonumber(string.sub(h , i, i + 1), 16) )) / 255 + end + return { c(1), c(3), c(5), (#h == 8 and{(c(7) )}or{1 })[1]} +end +Read.hexColor = hexColor + +function Read.toLinear(c) +if c <= 0.04045 then + return c / 12.92 + end + return ((c + 0.055) / 1.055) ^ 2.4 +end +local toLinear = Read.toLinear + +-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +local function transform(s) +if not s then + return nil, true + end + local v = {} + for w in __iter(string.gmatch(s, "%S+")) do + local n = tonumber(w) + if not n or n ~= n or n == math.huge or n == -math.huge then + return nil, false + end + table.insert(v, n) + end + if #v ~= 12 then + return nil, false + end + local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 } + for i = 1, 16 do + if m[i] ~= Types.Scene.IDENTITY[i] then + return m, true + end + end + return nil, true +end + +local function normPath(p) +p = string.gsub(p, "\\", "/") + p = string.gsub(p, "^/+", "") + return p +end +-- one model part parsed into its resources and build + + + +local function parseModel(text, path, opts) +local doc, err = Xml.decode(text, { parents = false }) + if not doc then + return nil, err + end + local root = (doc ).root + if not root or localName(root.name) ~= "model" then + return nil, Err.new(Err.CORRUPT, path .. ": the root element is not <model>") + end + local maxV = opts.maxVertices or 2 ^ 25 + local model= { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") } + local resources= nil + local build= nil + for _, ch in __iter(Xml.children(root)) do + local ln = localName(ch.name) + if ln == "metadata" then + local n = attr(ch, "name") + if n then + model.metadata[n] = Xml.text(ch) + end + elseif ln == "resources" then + resources = ch + elseif ln == "build" then + build = ch + end + end + local total = 0 + if resources then + for _, r in __iter(Xml.children(resources)) do +local __DARKLUA_CONTINUE_5=false repeat local ln = localName(r.name) + local id = int(attr(r, "id")) + if id == nil then +__DARKLUA_CONTINUE_5=true break + end + if ln == "object" then + local o= { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") } + local mesh = Xml.child(r, "mesh") + local comps = Xml.child(r, "components") + if mesh then + local verts = Xml.child(mesh, "vertices") + local tris = Xml.child(mesh, "triangles") + local vl = (verts and{(Xml.children(verts, "vertex") )}or{{} +})[1] local tl = (tris and{(Xml.children(tris, "triangle") )}or{{} +})[1] total =total+ (#vl + #tl * 3 +) if total > maxV then + return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners") + end + local nv = #vl + local pos = table.create(nv * 3, 0) + for i, v in __iter(vl) do + local a = v.attrs + local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z) + if not x or not y or not z then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i) + end + pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z + end + local nt = #tl + local tv = table.create(nt * 3, 0) + local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none) + for i, tri in __iter(tl) do + local a = tri.attrs + local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3) + if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index") + end + tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3 + local b = i * 4 - 4 + local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3) + tp[b + 1] = pid or -1 + tp[b + 2] = p1 or -1 + tp[b + 3] = p2 or p1 or -1 + tp[b + 4] = p3 or p1 or -1 + end + o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt + end + if comps then + o.components = {} + for _, c in __iter(Xml.children(comps, "component")) do + local oid = int(attr(c, "objectid")) + local m, ok = transform(attr(c, "transform")) + if oid and ok then + table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") }) + end + end + end + model.res[id] = o + elseif ln == "basematerials" then + local items = {} + for _, b in __iter(Xml.children(r, "base")) do + table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") }) + end + model.res[id] = { kind = "base", id = id, items = items } + elseif ln == "colorgroup" then + local items = {} + for _, c in __iter(Xml.children(r, "color")) do + table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 }) + end + model.res[id] = { kind = "color", id = id, items = items } + elseif ln == "texture2d" then + model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") } + elseif ln == "texture2dgroup" then + local uvs = {} + for _, c in __iter(Xml.children(r, "tex2coord")) do + table.insert(uvs, tonumber(attr(c, "u")) or 0) + table.insert(uvs, tonumber(attr(c, "v")) or 0) + end + model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = math.floor(#uvs / 2 )} + elseif ln == "compositematerials" then + local mats = {} + for w in __iter(string.gmatch(attr(r, "matindices") or "", "%S+")) do + table.insert(mats, tonumber(w) or 0) + end + local items = {} + for _, c in __iter(Xml.children(r, "composite")) do + local vals = {} + for w in __iter(string.gmatch(attr(c, "values") or "", "%S+")) do + table.insert(vals, tonumber(w) or 0) + end + table.insert(items, vals) + end + model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items } + elseif ln == "multiproperties" then + local pids = {} + for w in __iter(string.gmatch(attr(r, "pids") or "", "%S+")) do + table.insert(pids, tonumber(w) or -1) + end + local items = {} + for _, c in __iter(Xml.children(r, "multi")) do + local ix = {} + for w in __iter(string.gmatch(attr(c, "pindices") or "", "%S+")) do + table.insert(ix, tonumber(w) or 0) + end + table.insert(items, ix) + end + model.res[id] = { kind = "multi", id = id, pids = pids, items = items } + end +__DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end + end + if build then + for _, it in __iter(Xml.children(build, "item")) do + local oid = int(attr(it, "objectid")) + local m, ok = transform(attr(it, "transform")) + if oid and ok then + table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") }) + end + end + end + return model, nil +end + +-- the root model part's path +local function rootPath(zip) +local rels = zip:readString("_rels/.rels") + if rels then + local doc = Xml.decode(rels, { parents = false }) + if doc then + for _, rel in __iter(Xml.descendants((doc ).root or doc, "Relationship")) do + local t, target = attr(rel, "Type"), attr(rel, "Target") + if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then + return normPath(target) + end + end + end + end + for _, e in __iter(zip:list()) do + if not e.isDir and string.find(string.lower(e.name), "%.model$") then + return e.name + end + end + return nil +end + +function Read.scene(zip, opts) +local rootP = rootPath(zip) + if not rootP then + return nil, Err.new(Err.CORRUPT, "no 3D model part in the package") + end + local models= {} + local function getModel(path) +local p = normPath(path) + local m = models[p] + if m then + return m, nil + end + local text, err = zip:readString(p) + if not text then + return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p) + end + if string.sub(text, 1, 5) == "%3McF" then + return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped") + end + local mm, perr = parseModel(text, p, opts) + if not mm then + return nil, perr + end + models[p] = mm + return mm, nil + end + local root, rerr = getModel(rootP) + if not root then + return nil, rerr + end + + local scene = Types.Scene.new() + local unitName = root.unit or "millimeter" + scene.meta.up = "z" + scene.meta.unit = UNITS[unitName] or 1e-3 + scene.meta.metadata = root.metadata + scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } + + -- textures and materials (shared across model parts by part path + resource id) + local texCache= {} + local function texture(model, id) +local key = model.path .. "#" .. id + if texCache[key] then + return texCache[key] + end + local r = model.res[id] + if not r or r.kind ~= "texture" or type(r.path) ~= "string" then + return nil + end + local data = zip:read(normPath(r.path)) + local tex= { + name = r.path, + data = data, + mime = r.contenttype, + uri = r.path, + sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = ((r.filter == "nearest" or r.filter == "linear" )and{r.filter }or{nil })[1]}, + extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } }, + } + table.insert(scene.textures, tex) + texCache[key] = #scene.textures + return #scene.textures + end + local matCache= {} + local function addMaterial(key, make) +local i = matCache[key] + if i then + return i + end + table.insert(scene.materials, make()) + matCache[key] = #scene.materials + return #scene.materials + end + local function colorMaterial(name, c, extras) +local m = Types.Scene.material(name) + m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] } + m.metallic = 0 + m.roughness = 1 + if c[4] < 1 then + m.alphaMode = "blend" + end + m.extras = { ["3mf"] = extras } + return m + end + + -- property of one corner -> (group key, material index?, kind, resource, index) + local function resolve(model, pid, p, depth) +local r = model.res[pid] + if not r or p < 0 then + return "none", nil, "none", nil, 0 + end + local k = r.kind + if k == "base" then + local item = r.items[p + 1] + if not item then + return "none", nil, "none", nil, 0 + end + local key = "b" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex }) + end), "base", r, p + elseif k == "color" then + return "c" .. model.path .. "#" .. pid, nil, "color", r, p + elseif k == "texgroup" then + local ti = r.texid and texture(model, r.texid) + local mat= nil + if ti then + local mk = "t" .. model.path .. "#" .. (r.texid ) + mat = addMaterial(mk, function() + local m = Types.Scene.material("texture " .. tostring(r.texid)) + m.metallic = 0 + m.roughness = 1 + m.baseColorTexture = { texture = ti } + m.extras = { ["3mf"] = { texture = r.texid } } + return m + end) + end + return "t" .. model.path .. "#" .. pid, mat, "tex", r, p + elseif k == "composite" then + local item = r.items[p + 1] + local base = r.matid and model.res[r.matid] + if not item or not base or base.kind ~= "base" then + return "none", nil, "none", nil, 0 + end + local key = "x" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + local c, sum = { 0, 0, 0, 0 }, 0 + for j, w in __iter(item) do + local b = base.items[(r.matindices[j] or 0) + 1] + if b then + for q = 1, 4 do + c[q]=c[q]+ b.color[q] * w + end + sum =sum+ w + end + end + if sum > 0 then + for q = 1, 4 do + c[q]=c[q]/ sum + end + else + c = { 1, 1, 1, 1 } + end + return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p }) + end), "base", r, p + elseif k == "multi" and (depth or 0) < 1 then + local item = r.items[p + 1] + local first = r.pids[1] + if item and first then + return resolve(model, first, item[1] or 0, 1) + end + end + return "none", nil, "none", nil, 0 + end + + -- one Scene mesh per (part, object) with a mesh + local meshCache= {} + local function buildMesh(model, o) +local key = model.path .. "#" .. o.id + local cached = meshCache[key] + if cached ~= nil then + return (cached > 0 and{cached }or{nil +})[1] end + local groups= {} + local order= {} + local pos, tv, tp = o.positions, o.tv, o.tp + for t = 0, o.nt - 1 do + local pid = tp[t * 4 + 1] + local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] } + if pid < 0 then + pid = o.pid or -1 + if ps[1] < 0 then + local d = o.pindex or (pid >= 0 and 0 or-1) + ps = { d, d, d } + end + end + local gkey, mat, kind, res, _ = resolve(model, pid, ps[1]) + local g = groups[gkey] + if not g then + g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 } + groups[gkey] = g + table.insert(order, g) + end + for c = 1, 3 do + local v = tv[t * 3 + c] + local vk = v + local pc = 0 + if kind == "color" or kind == "tex" then + pc = ps[c] + local cnt = (kind == "color" and((#res.items ))or(res.count +)) if pc < 0 or pc >= cnt then + pc = ps[1] + end + if pc < 0 or pc >= cnt then + pc = 0 + end + vk = v * (cnt + 1) + pc + end + local ni = g.vmap[vk] + if not ni then + ni = g.n + g.n =g.n+ 1 + g.vmap[vk] = ni + table.insert(g.pos, pos[v * 3 + 1]) + table.insert(g.pos, pos[v * 3 + 2]) + table.insert(g.pos, pos[v * 3 + 3]) + if kind == "color" then + local col = res.items[pc + 1] or { 1, 1, 1, 1 } + table.insert(g.attr, toLinear(col[1])) + table.insert(g.attr, toLinear(col[2])) + table.insert(g.attr, toLinear(col[3])) + table.insert(g.attr, col[4]) + elseif kind == "tex" then + table.insert(g.attr, res.uvs[pc * 2 + 1] or 0) + table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0)) + end + end + table.insert(g.idx, ni) + end + end + local mesh= { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } } + for _, g in __iter(order) do + local n = g.n + local pa = Types.Scene.accessor(nil, "f32", 3, n) + for i, x in __iter(g.pos) do + buffer.writef32(pa.data, (i - 1) * 4, x) + end + local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx) + for i, x in __iter(g.idx) do + buffer.writeu32(ia.data, (i - 1) * 4, x) + end + local prim= { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material } + if g.kind == "color" then + local ca = Types.Scene.accessor(nil, "f32", 4, n) + for i, x in __iter(g.attr) do + buffer.writef32(ca.data, (i - 1) * 4, x) + end + prim.attributes.COLOR_0 = ca + prim.extras = { ["3mf"] = { colorgroup = g.res.id } } + elseif g.kind == "tex" then + local ua = Types.Scene.accessor(nil, "f32", 2, n) + for i, x in __iter(g.attr) do + buffer.writef32(ua.data, (i - 1) * 4, x) + end + prim.attributes.TEXCOORD_0 = ua + prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } } + end + table.insert(mesh.primitives, prim) + end + if #mesh.primitives == 0 then + meshCache[key] = 0 + return nil + end + table.insert(scene.meshes, mesh) + meshCache[key] = #scene.meshes + return #scene.meshes + end + + -- nodes: one per object instance (build items and components) + local nodeCount = 0 + local maxNodes = opts.maxNodes or 2 ^ 20 + local instantiate +function instantiate(model, oid, matrix, depth, extra) +if depth > MAX_DEPTH then + return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)") + end + nodeCount =nodeCount+ 1 + if nodeCount > maxNodes then + return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances") + end + local o = model.res[oid] + if not o or o.kind ~= "object" then + return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path) + end + local node= { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } } + table.insert(scene.nodes, node) + local index = #scene.nodes + if o.positions then + node.mesh = buildMesh(model, o) + end + if o.components then + for _, c in __iter(o.components) do + local m= model + if c.path then + local mm, err = getModel(c.path) + if not mm then + return nil, err + end + m = mm + end + local child, err = instantiate(m , c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path }) + if not child then + return nil, err + end + table.insert(node.children, child) + end + end + return index, nil + end + for _, it in __iter(root.items) do + local m= root + if it.path then + local mm, err = getModel(it.path) + if not mm then + return nil, err + end + m = mm + end + local idx, err = instantiate(m , it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true }) + if not idx then + return nil, err + end + table.insert(scene.roots, idx) + end + return scene, nil +end + +function Read.open(r) +return Zip.open(r) +end + +return Read +end +__FILES["model/3mf/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, +-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the +-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), +-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has +-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). +-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") + +local Write = {} + +local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture" +local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" } +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" } + +local fmt = string.format +local esc = Xml.escapeAttr + +local function num(x) +if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 1e15 then + return fmt("%d", x) + end + return fmt("%.9g", x) +end + +local function toSrgb(c) +c = math.clamp(c, 0, 1) + if c <= 0.0031308 then + return c * 12.92 + end + return 1.055 * c ^ (1 / 2.4) - 0.055 +end + +local function hex(r, g, b, a) +local function q(x) +return math.clamp(math.floor(x * 255 + 0.5), 0, 255) + end + return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) +end + +-- the triangle corner list of a primitive (0-based vertex indices) or nil +local function triangles(prim) +local pos = prim.attributes and prim.attributes.POSITION + if type(pos) ~= "table" then + return nil + end + local n = pos.count + local ix= {} + if prim.indices then + local get = Types.Scene.reader(prim.indices) + if not get then + return nil + end + for i = 0, prim.indices.count - 1 do + ix[i + 1] = get(i, 0) + end + else + for i = 1, n do + ix[i] = i - 1 + end + end + for _, v in __iter(ix) do + if v ~= v or v < 0 or v >= n then + return nil + end + end + local mode = prim.mode or "triangles" + local out= {} + local function tri(a, b, c) + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + if mode == "triangles" then + for i = 1, #ix - 2, 3 do + tri(ix[i], ix[i + 1], ix[i + 2]) + end + elseif mode == "triangle_strip" then + for i = 1, #ix - 2 do + if i % 2 == 1 then + tri(ix[i], ix[i + 1], ix[i + 2]) + else + tri(ix[i + 1], ix[i], ix[i + 2]) + end + end + elseif mode == "triangle_fan" then + for i = 2, #ix - 1 do + tri(ix[1], ix[i], ix[i + 1]) + end + elseif mode == "polygons" and prim.faces then + local get = Types.Scene.reader(prim.faces) + if not get then + return nil + end + local at = 1 + for f = 0, prim.faces.count - 1 do + local k = get(f, 0) + if at + k - 1 > #ix then + break + end + for j = 1, k - 2 do + tri(ix[at], ix[at + j], ix[at + j + 1]) + end + at =at+ k + end + else + return nil + end + return out +end + +function Write.build(scene, opts) +local o = opts or {} + local nextId = 0 + local function id() +nextId =nextId+ 1 + return nextId + end + local res= {} -- resource XML chunks, in definition order + local files= {} + + -- unit + local unitName, scale= "millimeter", 1 + local mu= scene.meta and scene.meta.unit + if type(o.unit) == "string" and UNITS[o.unit] then + unitName = o.unit + if type(mu) == "number" and mu > 0 then + scale = mu / UNITS[o.unit] + end + elseif type(mu) == "number" and mu > 0 then + local found = false + for _, u in __iter(UNIT_ORDER) do + if math.abs(UNITS[u] - mu) <= 1e-9 * mu then + unitName, found = u, true + break + end + end + if not found then + scale = mu / 1e-3 + end + end + + -- base materials: one group with every Scene material + local baseId= nil + local nmat = #scene.materials + local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local needDefault = false + if nmat > 0 then + baseId = id() + end + + -- textures used as base colour textures + local texRes= {} + local function textureId(ti) +if texRes[ti] ~= nil then + return (texRes[ti] > 0 and{texRes[ti] }or{nil +})[1] end + local tex = scene.textures[ti] + local ext = tex and TEX_EXT[tex.mime or ""] + if not tex or type(tex.data) ~= "buffer" or not ext then + texRes[ti] = 0 + return nil + end + local rid = id() + local name = fmt("3D/Textures/texture_%d.%s", ti, ext ) + table.insert(files, { name = name, data = tex.data , mime = tex.mime }) + local s = tex.sampler + local function tile(w) +return w == "clamp" and"clamp" or(w == "mirror" and"mirror" or"wrap" +) end + local filter = (s and (s.filter == "nearest" or s.filter == "linear") and{s.filter }or{"auto" +})[1] table.insert(res, fmt('\t\t<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\n', rid, esc(name), tex.mime , tile(s and s.wrapS), tile(s and s.wrapT), filter)) + texRes[ti] = rid + return rid + end + + -- objects + local objectOf= {} + local objChunks= {} + for mi, mesh in __iter(scene.meshes) do +local __DARKLUA_CONTINUE_10=false repeat local verts= {} + local tris= {} + local base = 0 + local objPid, objP= nil, nil + local anyNone = false + local triList= {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + for _, prim in __iter(mesh.primitives) do +local __DARKLUA_CONTINUE_11=false repeat local corners = triangles(prim) + if not corners or #corners == 0 then +__DARKLUA_CONTINUE_11=true break + end + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + if not getP then +__DARKLUA_CONTINUE_11=true break + end + local n = pos.count + for v = 0, n - 1 do + table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num((pos.components >= 2 and{(getP(v, 1) )}or{0})[1]), num((pos.components >= 3 and{(getP(v, 2) )}or{0})[1]))) + end + -- properties: texture group, colour group, base material, none + local pid, kind = -1, "none" + local mat = prim.material and scene.materials[prim.material] + local uv = prim.attributes.TEXCOORD_0 + local col = prim.attributes.COLOR_0 + local tref = mat and mat.baseColorTexture + local tid = (tref and uv and (tref.texCoord or 0) == 0 and{(textureId(tref.texture) )}or{nil +})[1] if tid and uv then + local get = Types.Scene.reader(uv) + if get then + pid, kind = id(), "tex" + local parts = { fmt('\t\t<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) } + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1)))) + end + table.insert(parts, "\t\t</m:texture2dgroup>\n") + table.insert(res, table.concat(parts)) + end + end + if kind == "none" and col then + local get = Types.Scene.reader(col) + if get then + pid, kind = id(), "color" + local parts = { fmt('\t\t<m:colorgroup id="%d">\n', pid) } + local four = col.components >= 4 + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t<m:color color="%s" />\n', hex(get(v, 0), get(v, 1), get(v, 2), (four and{(get(v, 3) )}or{1})[1]))) + end + table.insert(parts, "\t\t</m:colorgroup>\n") + table.insert(res, table.concat(parts)) + end + end + local pindex = -1 + if kind == "none" and baseId and prim.material and scene.materials[prim.material] then + pid, kind, pindex = baseId , "base", prim.material - 1 + end + for i = 1, #corners, 3 do + local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base + if kind == "tex" or kind == "color" then + table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] }) + elseif kind == "base" then + table.insert(triList, { a, b, c, pid, pindex, pindex, pindex }) + else + table.insert(triList, { a, b, c, -1, -1, -1, -1 }) + anyNone = true + end + if objPid == nil and kind ~= "none" then + objPid, objP = pid, (kind == "base" and{pindex }or{corners[i] +})[1] end + end + base =base+ n +__DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end + if #triList == 0 then +__DARKLUA_CONTINUE_10=true break + end + if objPid and anyNone then + needDefault = true + if not baseId then + baseId = id() + end + end + for _, t in __iter(triList) do + if t[4] < 0 and objPid then + t[4], t[5], t[6], t[7] = baseId , defaultBase, defaultBase, defaultBase + end + if t[4] < 0 then + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" />\n', t[1], t[2], t[3])) + elseif t[5] == t[6] and t[6] == t[7] then + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5])) + else + table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7])) + end + end + local oid = id() + objectOf[mi] = oid + local head = fmt('\t\t<object id="%d" type="model"', oid) + if mesh.name then + head =head.. fmt(' name="%s"', esc(mesh.name)) + end + if objPid then + head =head.. fmt(' pid="%d" pindex="%d"', objPid, objP ) + end + table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\n" })) + table.insert(res, objChunks[#objChunks]) +__DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end + + -- the base material group goes first (its id was taken first) + if baseId then + local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) } + for _, m in __iter(scene.materials) do + local c = m.baseColor or { 1, 1, 1, 1 } + table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1))) + end + if needDefault then + table.insert(parts, '\t\t\t<base name="default" displaycolor="#FFFFFFFF" />\n') + end + table.insert(parts, "\t\t</basematerials>\n") + table.insert(res, 1, table.concat(parts)) + end + + -- build items: every node with a mesh, at its world matrix + local items= {} + local seen= {} + for _, pl in __iter(Types.Scene.flatten(scene)) do +local __DARKLUA_CONTINUE_18=false repeat if seen[pl.node] then +__DARKLUA_CONTINUE_18=true break + end + seen[pl.node] = true + local oid = objectOf[pl.mesh] + if not oid then +__DARKLUA_CONTINUE_18=true break + end + local m = pl.matrix + local s = scale + local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s } + local ident = s == 1 + for i, v in __iter({ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 }) do + if tr[i] ~= v then + ident = false + end + end + if ident then + table.insert(items, fmt('\t\t<item objectid="%d" />\n', oid)) + else + local ns = table.create(12, "") + for i = 1, 12 do + ns[i] = num(tr[i]) + end + table.insert(items, fmt('\t\t<item objectid="%d" transform="%s" />\n', oid, table.concat(ns, " "))) + end +__DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end + + -- metadata + local meta= {} + local md = scene.meta and scene.meta.metadata + if type(md) == "table" then + local keys= {} + for k, v in __iter(md) do + if type(k) == "string" and (type(v) == "string" or type(v) == "number") then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in __iter(keys) do + table.insert(meta, fmt('\t<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k])))) + end + end + + local model = table.concat({ + '<?xml version="1.0" encoding="UTF-8"?>\n', + '<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n', + table.concat(meta), + "\t<resources>\n", + table.concat(res), + "\t</resources>\n\t<build>\n", + table.concat(items), + "\t</build>\n</model>\n", + }) + + local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n', + '\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n', + '\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\n' } + local exts= {} + for _, f in __iter(files) do + local e = (string.match(f.name, "%.(%w+)$") ) +if not exts[e] then + exts[e] = true + table.insert(types, fmt('\t<Default Extension="%s" ContentType="%s" />\n', e, f.mime)) + end + end + table.insert(types, "</Types>\n") + local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' + .. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL) + .. "</Relationships>\n" + + local w = Zip.writer() + local level = o.level or 6 + local method = level == 0 and"store" or"deflate" + local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method }) + if ok then + ok, err = w:add("_rels/.rels", rels, { level = level, method = method }) + end + if ok then + ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method }) + end + if ok and #files > 0 then + local mr = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' } + for i, f in __iter(files) do + table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE)) + end + table.insert(mr, "</Relationships>\n") + ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method }) + for _, f in __iter(files) do + if ok then + ok, err = w:add(f.name, f.data, { method = "store" }) + end + end + end + if not ok then + return nil, err or Err.new(Err.ARG, "zip writer failed") + end + return w:finish() +end + +return Write +end +__FILES["model/b3d"] = function() +--!strict +-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description +-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. +-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, +-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> +-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is +-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree +-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / +-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the +-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights +-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the +-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, +-- default 60) -> one animation of LINEAR channels at frame / fps seconds. +-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding +-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their +-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. +-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the +-- extras; texture coordinate sets of 3 / 4 components keep their first two. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/b3d/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local B3d = { + name = "b3d", + category = "model", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function B3d.sniff(r) +if r:peek(4) == "BB3D" then + return r:peek(4, 8) ~= "" and 1 or 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function B3d.decode(r, opts) +if r:peek(4) ~= "BB3D" then + return nil, Err.new(Err.CORRUPT, "no BB3D chunk") + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +return B3d +end +__FILES["model/b3d/Read"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are +-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes +-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + + + + + + + + +local LAYOUT= { maxChunks = 1000000 } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated +-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored + + + + + + +local function vec(r) +local x, y, z = r:f32le(), r:f32le(), r:f32le() + return { x, y, -z } +end +local function quat(r) +local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le() + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 or l ~= l then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, -z / l, w / l } +end + +local function fetcher(opts) +local files = opts and opts.files + local resolve = opts and opts.resolve + return function(uri) +local v= (type(files) == "table" and{files[uri] }or{nil +})[1] if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = (ok and{res }or{nil +})[1] end + return (type(v) == "string" and{(buffer.fromstring(v) )}or{(type(v) == "buffer" and{v }or{nil +})[1]})[1] end +end + +-- scene(r, opts) -> Scene | nil, message, kind +function Read.scene(src, opts) +local buf = src.buf + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxDepth = opts and opts.maxDepth or 256 + local fetch = fetcher(opts) + local top = Chunks.walk(buf, src.base, src.limit, LAYOUT) + local head = top[1] + if not head or head.id ~= "BB3D" then + return nil, "not a BB3D file", nil + end + if head.truncated then + return nil, "truncated", "truncated" + end + local hr = Bytes.reader(buf, head.offset, head.size) + local version = hr:i32le() + if hr.err then + return nil, "truncated", "truncated" + end + + local scene = Types.Scene.new() + local texs= {} + local brushes= {} + local materialOf= {} -- brush index (0-based) -> material + local meshes= {} + local bones= {} + local nodeKeys= {} + local anim= nil + local lastMesh= nil + local totalVertices = 0 + local failure, failKind= nil, nil + + local function fail(msg, kind) + if not failure then + failure, failKind = msg, kind + end + end + local function body(c) +if c.truncated then + fail("truncated " .. c.id .. " chunk", "truncated") + end + return Bytes.reader(buf, c.offset, c.avail) + end + + local function readTexs(r) + while r.pos < r.limit and not r.err do + local file = r:cstring() + local t= { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 } + if r.err then + return fail("truncated TEXS entry", "truncated") + end + local tex= { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] } + local data = fetch(file) + if not data then + local base = string.match(file, "([^/\\]+)$") + if base and base ~= file then + data = fetch(base) + end + end + tex.data = data + if bit32.band(t.flags, 48) ~= 0 then + tex.sampler = { wrapS = bit32.band(t.flags, 16) ~= 0 and"clamp" or"repeat", wrapT = bit32.band(t.flags, 32) ~= 0 and"clamp" or"repeat" } + end + tex.extras = { b3d = { flags = t.flags, blend = t.blend } } + table.insert(scene.textures, tex) + t.index = #scene.textures + table.insert(texs, t) + end + end + + local function readBrus(r) + local n = r:i32le() + if r.err or n < 0 or n > 8 then + return fail("bad BRUS texture count") + end + while r.pos < r.limit and not r.err do + local b= { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} } + for i = 1, n do + b.textures[i] = r:i32le() + end + if r.err then + return fail("truncated BRUS entry", "truncated") + end + table.insert(brushes, b) + end + end + + -- the material of brush id (0-based) | nil for -1 / out of range + local function material(id) +if id < 0 or id >= #brushes then + return nil + end + local have = materialOf[id] + if have then + return have + end + local b = brushes[id + 1] + local m = Types.Scene.material(b.name ~= "" and b.name or nil) + local c = b.color + local function clamp01(v) +return v ~= v and 1 or math.clamp(v, 0, 1) + end + m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) } + m.metallic = 0 + m.roughness = 1 - 0.8 * clamp01(b.shininess) + m.doubleSided = bit32.band(b.fx, 16) ~= 0 + if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then + m.alphaMode = "blend" + end + if bit32.band(b.fx, 1) ~= 0 then + m.extensions = { KHR_materials_unlit = {} } + end + local extraTex= {} + for i, tid in __iter(b.textures) do + local t = texs[tid + 1] + if tid >= 0 and t then + if not m.baseColorTexture then + local ref= { texture = t.index, texCoord = bit32.band(t.flags, 65536) ~= 0 and 1 or nil } + local o, s, rot = t.offset, t.scale, t.rotation + if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot } + end + m.baseColorTexture = ref + if bit32.band(t.flags, 4) ~= 0 then + m.alphaMode = "mask" + elseif bit32.band(t.flags, 2) ~= 0 then + m.alphaMode = "blend" + end + else + extraTex[i] = t.index + end + end + end + m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = (next(extraTex) and{extraTex }or{nil })[1]} } + table.insert(scene.materials, m) + materialOf[id] = #scene.materials + return #scene.materials + end + + local function readMesh(r, nodeIndex) +local master = r:i32le() + if r.err then + fail("truncated MESH", "truncated") + return nil + end + local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT) + local attrs= nil + local count = 0 + local mesh= { primitives = {} } + local rec= { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} } + for _, c in __iter(list) do + local cr = body(c) + if c.id == "VRTS" and not attrs then + local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le() + if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then + fail("bad VRTS header") + return nil + end + local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0 + local stride = 12 + (hasN and 12 or 0) + (hasC and 16 or 0) + sets * size * 4 + local n = math.floor((cr.limit - cr.pos) / stride +) totalVertices =totalVertices+ n + if totalVertices > maxVertices then + fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit") + return nil + end + local pos = buffer.create(n * 12) + local nrm = (hasN and{(buffer.create(n * 12) )}or{nil +})[1] local col = (hasC and{(buffer.create(n * 16) )}or{nil +})[1] local uvs= {} + for s = 1, sets do + uvs[s] = buffer.create(n * 8) + end + local readf32, writef32 = buffer.readf32, buffer.writef32 + local p = cr.pos + for i = 0, n - 1 do + writef32(pos, i * 12, readf32(buf, p)) + writef32(pos, i * 12 + 4, readf32(buf, p + 4)) + writef32(pos, i * 12 + 8, -readf32(buf, p + 8)) + p =p+ 12 + if nrm then + writef32(nrm, i * 12, readf32(buf, p)) + writef32(nrm, i * 12 + 4, readf32(buf, p + 4)) + writef32(nrm, i * 12 + 8, -readf32(buf, p + 8)) + p =p+ 12 + end + if col then + for k = 0, 3 do + writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4)) + end + p =p+ 16 + end + for s = 1, sets do + if size >= 1 then + writef32(uvs[s], i * 8, readf32(buf, p)) + end + if size >= 2 then + writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4)) + end + p =p+ size * 4 + end + end + local a= { POSITION = Types.Scene.accessor(pos, "f32", 3, n) } + if nrm then + a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n) + end + if col then + a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n) + end + if size > 0 then + for s = 1, sets do + a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n) + end + end + attrs, count = a, n + mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } } + elseif c.id == "TRIS" then + local brush = cr:i32le() + if cr.err then + fail("truncated TRIS", "truncated") + return nil + end + if not attrs then + fail("TRIS before VRTS") + return nil + end + local nt = math.floor((cr.limit - cr.pos) / 12 +) local idx = buffer.create(nt * 12) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + local p = cr.pos + for i = 0, nt - 1 do + local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8) + if a >= count or b >= count or cc >= count then + fail(string.format("triangle %d: vertex index out of range", i)) + return nil + end + -- mirrored z: reverse the winding to keep the faces front-facing + writeu32(idx, i * 12, a) + writeu32(idx, i * 12 + 4, cc) + writeu32(idx, i * 12 + 8, b) + p =p+ 12 + end + local prim= { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" } + prim.material = material((brush == -1 and{master }or{brush})[1]) + table.insert(mesh.primitives, prim) + end + end + if not attrs then + return nil -- a mesh without vertices: the node stays a pivot + end + if #mesh.primitives == 0 then + table.insert(mesh.primitives, { attributes = attrs, mode = "points" }) + end + table.insert(scene.meshes, mesh) + rec.mesh, rec.count = #scene.meshes, count + table.insert(meshes, rec) + lastMesh = rec + return #scene.meshes + end + + local function readBone(r, nodeIndex) + local b= { node = nodeIndex, target = lastMesh, list = {} } + table.insert(bones, b) + local list = b.list + while r.pos + 8 <= r.limit do + local v, w = r:i32le(), r:f32le() + table.insert(list, v) + table.insert(list, w) + end + end + + local function readKeys(r, nodeIndex) + local flags = r:i32le() + local per = 4 + (bit32.band(flags, 1) ~= 0 and 12 or 0) + (bit32.band(flags, 2) ~= 0 and 12 or 0) + (bit32.band(flags, 4) ~= 0 and 16 or 0) + local k = nodeKeys[nodeIndex] + if not k then + k = { t = {}, s = {}, r = {} } + nodeKeys[nodeIndex] = k + end + while not r.err and r.pos + per <= r.limit do + local frame = r:i32le() + if bit32.band(flags, 1) ~= 0 then + k.t[frame] = vec(r) + end + if bit32.band(flags, 2) ~= 0 then + local x, y, z = r:f32le(), r:f32le(), r:f32le() + k.s[frame] = { x, y, z } + end + if bit32.band(flags, 4) ~= 0 then + k.r[frame] = quat(r) + end + end + end + + local function readNode(c, depth) +if depth > maxDepth then + fail("limit: nodes nested deeper than " .. maxDepth, "limit") + return nil + end + local r = body(c) + local name = r:cstring() + local t = vec(r) + local sx, sy, sz = r:f32le(), r:f32le(), r:f32le() + local q = quat(r) + if r.err then + fail("truncated NODE", "truncated") + return nil + end + local node= { name = name, children = {} } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then + node.rotation = q + end + if sx ~= 1 or sy ~= 1 or sz ~= 1 then + node.scale = { sx, sy, sz } + end + table.insert(scene.nodes, node) + local index = #scene.nodes + for _, sub in __iter(Chunks.walk(buf, r.pos, r.limit, LAYOUT)) do + if failure then + break + end + local id = sub.id + if id == "NODE" then + local child = readNode(sub, depth + 1) + if child then + table.insert(node.children, child) + end + elseif id == "MESH" and not node.mesh then + node.mesh = readMesh(body(sub), index) + elseif id == "BONE" then + readBone(body(sub), index) + elseif id == "KEYS" then + readKeys(body(sub), index) + elseif id == "ANIM" then + local ar = body(sub) + local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le() + if not ar.err and not anim then + anim = { flags = flags, frames = frames, fps = (fps > 0 and fps < 1e6 and{fps }or{60 })[1]} + end + end + end + return index + end + + for _, c in __iter(Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT)) do + if failure then + break + end + if c.id == "TEXS" then + readTexs(body(c)) + elseif c.id == "BRUS" then + readBrus(body(c)) + elseif c.id == "NODE" then + local n = readNode(c, 1) + if n then + table.insert(scene.roots, n) + end + end + end + if failure then + return nil, failure, failKind + end + if #scene.nodes == 0 then + return nil, "no NODE chunk", nil + end + + -- ------------------------------------------------------------------------------------------ skins + local parent= {} + for i, n in __iter(scene.nodes) do + for _, ch in __iter(n.children) do + parent[ch] = i + end + end + local worldCache= {} + local function world(i) +local w = worldCache[i] + if not w then + local n = scene.nodes[i] + local l = Mat4.compose(n.translation, n.rotation, n.scale) + w = (parent[i] and{(Mat4.mul(world(parent[i]), l) )}or{l +})[1] worldCache[i] = w + end + return w + end + local bonesOf= {} + for _, b in __iter(bones) do + local m = b.target + if m then + local l = bonesOf[m] or {} + bonesOf[m] = l + table.insert(l, b) + end + end + for _, rec in __iter(meshes) do + local list = bonesOf[rec] + if list then + local nv = rec.count + local inf= {} + local joints= {} + for j, b in __iter(list) do + joints[j] = b.node + local l = b.list + for k = 1, #l, 2 do + local v, w = l[k], l[k + 1] + if v >= 0 and v < nv and w > 0 and w == w then + local e = inf[v + 1] + if not e then + e = {} + inf[v + 1] = e + end + table.insert(e, j - 1) + table.insert(e, w) + end + end + end + local self= nil -- the mesh node as a joint, for vertices no bone moves + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for v = 0, nv - 1 do + local e = inf[v + 1] + if not e then + if not self then + table.insert(joints, rec.node) + self = #joints - 1 + end + buffer.writeu16(jb, v * 8, self ) + buffer.writef32(wb, v * 16, 1) + else + -- the 4 strongest, normalised + local order = {} + for k = 1, #e, 2 do + table.insert(order, k) + end + table.sort(order, function(a, b) +return e[a + 1] > e[b + 1] + end) + local sum = 0 + for k = 1, math.min(4, #order) do + sum =sum+ e[order[k] + 1] + end + for k = 1, math.min(4, #order) do + buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k] ]) + buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum) + end + end + end + local meshWorld = world(rec.node) + local ibm = buffer.create(#joints * 64) + for j, ni in __iter(joints) do + local inv = Mat4.inverse(world(ni)) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local ia = Types.Scene.accessor(ibm, "f32", 16, #joints) + ia.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia }) + scene.nodes[rec.node].skin = #scene.skins + local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv) + for _, prim in __iter(scene.meshes[rec.mesh].primitives) do + prim.attributes.JOINTS_0 = J + prim.attributes.WEIGHTS_0 = W + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + local fps = (anim and{anim.fps }or{60 +})[1] local channels= {} + for ni = 1, #scene.nodes do + local k = nodeKeys[ni] + if k then + for _, path in __iter({ "translation", "rotation", "scale" }) do + local map = (path == "translation" and{k.t }or{(path == "rotation" and{k.r }or{k.s +})[1]})[1] local frames = {} + for f in __iter(map) do + table.insert(frames, f) + end + if #frames > 0 then + table.sort(frames) + local nc = path == "rotation" and 4 or 3 + local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4) + for i, f in __iter(frames) do + buffer.writef32(input, (i - 1) * 4, f / fps) + local v = map[f] + for c = 1, nc do + buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c]) + end + end + table.insert(channels, { + node = ni, + path = path , + input = Types.Scene.accessor(input, "f32", 1, #frames), + output = Types.Scene.accessor(output, "f32", nc, #frames), + interpolation = "LINEAR" , + }) + end + end + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "b3d", channels = channels }) + end + + scene.meta.up = "y" + scene.meta.source = { + format = "b3d", + version = version, + brushes = #brushes, + frames = (anim and{anim.frames }or{nil})[1], + fps = (anim and{anim.fps }or{nil})[1], + handedness = "left", -- converted: z mirrored, winding reversed + } + return scene, nil, nil +end + +return Read +end +__FILES["model/bsp"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38) +-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a +-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III +-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as +-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not +-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey. +-- Quake II .wal sizes come from opts.resolve("textures/<name>.wal") / opts.files. Units are map units, z up. +-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Brush = __include("model/bsp/Brush") +local Quake3 = __include("model/bsp/Quake3") + +-- ------------------------------------------------------------------------------------------------ contract +local Bsp = { + name = "bsp", + category = "model", + extensions = { "bsp" }, + mime = { "model/x-bsp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + +local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" } +local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves", + "leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" } +local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes", + "brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Bsp.sniff(r) +if r:remaining() < 64 then + return 0 + end + local m = r:peek(4) + local v = buffer.readi32(r.buf, r.pos + (m == "IBSP" and 4 or 0)) + if m == "IBSP" then + return (v == 38 or v == 46 or v == 47 )and 1 or 0.3 + end + if v == 29 or v == 30 then + -- no magic: check that the lump directory fits the file + local size = r:remaining() + for i = 0, 14 do + local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8) + if o < 0 or n < 0 or o + n > size then + return 0 + end + end + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the entities text -> { { key = value } } +local function entities(text) +local out= {} + for block in __iter(string.gmatch(text, "%b{}")) do + local e= {} + for k, v in __iter(string.gmatch(block, '"([^"]*)"%s*"([^"]*)"')) do + e[k] = v + end + table.insert(out, e) + end + return out +end + +function Bsp.decode(r, opts) +local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local b, base = r.buf, r.base + local m = r:peek(4) + local version = buffer.readi32(b, base + (m == "IBSP" and 4 or 0)) + local names, dir, variant +if m == "IBSP" and version == 38 then + names, dir, variant = Q2_LUMPS, 8, "q2" + elseif m == "IBSP" and (version == 46 or version == 47) then + names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m ~= "IBSP" and (version == 29 or version == 30) then + names, dir, variant = Q1_LUMPS, 4, version == 30 and"hl" or"q1" + elseif m == "VBSP" then + return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0) + else + return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0) + end + if dir + #names * 8 > size then + return nil, Err.new(Err.TRUNCATED, "lump directory", dir) + end + local lumps= {} + for i, name in __iter(names) do + local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4) + if o < 0 or n < 0 or o + n > size then + return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8) + end + lumps[name] = { at = o, size = n } + end + local scene, msg +if variant == "q3" then + scene, msg = Quake3.decode(b, base, lumps, opts ) + else + local pal = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{(Input.sibling(opts, "gfx/palette.lmp") +)})[1] if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Brush.decode(b, base, lumps, variant, { + palette = pal, + wal = function(name) +return Input.sibling(opts, "textures/" .. name .. ".wal") + end, + maxPixels = opts and opts.maxPixels, + maxVertices = opts and opts.maxVertices, + }) + end + if not scene then + return nil, Err.from(msg) + end + local e = lumps.entities + local text = buffer.readstring(b, base + e.at, e.size) + text = (string.match(text, "^[^%z]*") ) +scene.meta.entities = entities(text) + scene.meta.source = { + format = "bsp", + variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } )[variant], + version = version, + entities = text, + palette = (variant == "q1" and{(opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) }or{nil})[1], + } + return scene, nil +end + +return Bsp +end +__FILES["model/bsp/Brush"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex +-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture +-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the +-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake / +-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the +-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from +-- opts.resolve("textures/<name>.wal") when available, else texture coordinates stay in texels: extras.bsp.texels). +-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken. +-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") + +local Brush = {} + +local Scene = Types.Scene +local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + + + + + + + + + + + +local function cstr(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +-- miptex lump (Quake / Half-Life) -> textures +local function miptex(b, base, l, hl, pal, maxPixels) +local out= {} + if l.size < 4 then + return out, nil + end + local at = base + l.at + local n = readi32(b, at) + if n < 0 or n > 65536 or 4 + n * 4 > l.size then + return nil, "bad miptex lump" + end + local gpal = (pal and{(Pixels.palette(pal, 0, 256) )}or{nil +})[1] for i = 0, n - 1 do + local o = readi32(b, at + 4 + i * 4) + if o < 0 or o + 40 > l.size then + out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } + else + local m = at + o + local name = cstr(b, m, 16) + local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) + local t= { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } + if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then + local px = m + off0 + local need = w * h + local palAt = m + readu32(b, m + 36) + (math.floor(w / 8)) * (math.floor(h / 8)) + 2 + if o + off0 + need <= l.size then + local p = gpal + if hl then + p = (palAt - at + 768 <= l.size and{(Pixels.palette(b, palAt, 256) )}or{nil +})[1] end + local img = Types.Image.new(w, h) + if p then + Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) + else + for k = 0, need - 1 do + writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) + end + end + img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + t.image = img + end + end + out[i + 1] = t + end + end + return out, nil +end + +-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message +-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes, +-- models, miptex (q1 / hl) +function Brush.decode(b, base, lumps, variant, opts) +local q2 = variant == "q2" + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models + local nV, nE, nSE, nF = math.floor(V.size / 12), math.floor(E.size / 4), math.floor(SE.size / 4), math.floor(Fc.size / 20 +) local tiSize = q2 and 76 or 40 + local nTI, nP = math.floor(TI.size / tiSize), math.floor(P.size / 20 +) local mSize = q2 and 48 or 64 + local nM = math.floor(M.size / mSize +) if nF > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many faces" + end + -- textures + local texs= {} + local texOf= {} -- texinfo -> texture index (1-based) + if q2 then + local byName= {} + for i = 0, nTI - 1 do + local name = cstr(b, base + TI.at + i * 76 + 40, 32) + local ti = byName[name] + if not ti then + local w, h, texels = 1, 1, true + local wal = opts and opts.wal and opts.wal(name) + if wal and buffer.len(wal) >= 40 then + w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false + end + table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels }) + ti = #texs + byName[name] = ti + end + texOf[i + 1] = ti + end + else + local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels) + if not list then + return nil, err + end + texs = list + for i = 0, nTI - 1 do + local mt = readi32(b, base + TI.at + i * 40 + 32) + texOf[i + 1] = (mt >= 0 and mt < #texs and((mt + 1 ))or(0 +)) end + end + -- faces of each model + local scene = Scene.new() + scene.meta.up = "z" + local faceModel= {} + local models= {} + for m = 0, nM - 1 do + local o = base + M.at + m * mSize + local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) } + local fo = q2 and 40 or 56 + local first, count = readi32(b, o + fo), readi32(b, o + fo + 4) + table.insert(models, { first = first, count = count, origin = origin }) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + if #models == 0 then + table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } }) + for f = 1, nF do + faceModel[f] = 1 + end + end + local batches= {} + local orders= {} + local skipped = 0 + for f = 0, nF - 1 do +local __DARKLUA_CONTINUE_8=false repeat local fo = base + Fc.at + f * 20 + local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local model = faceModel[f + 1] + if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + skipped =skipped+ 1 +__DARKLUA_CONTINUE_8=true break + end + -- the polygon + local poly= {} + local ok = true + for k = 0, numEdges - 1 do + local se = readi32(b, base + SE.at + (firstEdge + k) * 4) + local e = math.abs(se) + if e >= nE then + ok = false + break + end + local v = (se >= 0 and{(readu16(b, base + E.at + e * 4) )}or{(readu16(b, base + E.at + e * 4 + 2) +)})[1] if v >= nV then + ok = false + break + end + local vo = base + V.at + v * 12 + table.insert(poly, readf32(b, vo)) + table.insert(poly, readf32(b, vo + 4)) + table.insert(poly, readf32(b, vo + 8)) + end + if not ok then + skipped =skipped+ 1 +__DARKLUA_CONTINUE_8=true break + end + local po = base + P.at + plane * 20 + local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) + if side ~= 0 then + nx, ny, nz = -nx, -ny, -nz + end + -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored) + local n = math.floor(#poly / 3 +) local ax, ay, az = 0, 0, 0 + for k = 0, n - 1 do + local j = (k + 1) % n + local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3] + ax =ax+ (y1 - y2) * (z1 + z2) + ay =ay+ (z1 - z2) * (x1 + x2) + az =az+ (x1 - x2) * (y1 + y2) + end + local order= {} + if ax * nx + ay * ny + az * nz >= 0 then + for k = 0, n - 1 do + order[k + 1] = k + end + else + order[1] = 0 + for k = 1, n - 1 do + order[k + 1] = n - k + end + end + local tio = base + TI.at + texinfo * tiSize + local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) + local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local ti = texOf[texinfo + 1] or 0 + local tex = texs[ti] + local w, h = (tex and{tex.width }or{1})[1], (tex and{tex.height }or{1 +})[1] local bm = batches[model] or {} + batches[model] = bm + local bt = bm[ti] + if not bt then + bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bm[ti] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, ti) + end + local batch= bt + for k = 2, n - 1 do + for _, c in __iter({ order[1], order[k], order[k + 1] }) do + local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3] + local pp, nn, uu = batch.pos, batch.nrm, batch.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz + uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w + uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + end + end +__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end + -- textures, materials + for i, t in __iter(texs) do + local tex= { name = t.name, image = t.image, uri = (t.image and{nil }or{((q2 and(("textures/" .. t.name .. ".wal" ))or(t.name))) })[1]} + table.insert(scene.textures, tex) + local mat = Scene.material(t.name) + mat.metallic = 0 + local extras= { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } } + mat.extras = extras + mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } } +table.insert(scene.materials, mat) + end + -- meshes and nodes + local root= { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + for m, mdl in __iter(models) do + local list = orders[m] + if list then + local mesh= { name = m == 1 and"world" or"*" .. (m - 1), primitives = {} } + for _, ti in __iter(list) do + local bt = batches[m][ti] + local nv = math.floor(#bt.pos / 3 +) local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, bt.pos[k]) + writef32(nb, (k - 1) * 4, bt.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, bt.uv[k]) + end + for k = 0, nv - 1 do + writeu32(ib, k * 4, k) + end + table.insert(mesh.primitives, { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" , + material = (ti > 0 and{ti }or{nil})[1], + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.skippedFaces = skipped + return scene, nil +end + +return Brush +end +__FILES["model/bsp/Quake3"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a +-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches +-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap +-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1 +-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as +-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped. +-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken. +local Types = __include("Types") + +local Quake3 = {} + +local Scene = Types.Scene +local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8 +local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8 + + + + + + +local function cstr(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +-- decode(b, base, lumps, opts) -> Scene | nil, message +function Quake3.decode(b, base, lumps, opts) +local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps + local nT, nM, nV, nMV, nF, nLM = math.floor(T.size / 72), math.floor(M.size / 40), math.floor(VX.size / 44), math.floor(MV.size / 4), math.floor(F.size / 104), math.floor(LM.size / 49152 +) local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16) + local maxV = opts and opts.maxVertices or 2 ^ 24 + -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids + local extra= {} + local function vertex(i) +local o = base + VX.at + i * 44 + local v = table.create(14, 0) + for k = 0, 9 do + v[k + 1] = readf32(b, o + k * 4) + end + for k = 0, 3 do + v[11 + k] = readu8(b, o + 40 + k) + end + return v + end + local function addExtra(v) +for k = 1, 14 do + table.insert(extra, v[k]) + end + return -(math.floor(#extra / 14)) + end + local faceModel= {} + for m = 0, nM - 1 do + local o = base + M.at + m * 40 + local first, count = readi32(b, o + 24), readi32(b, o + 28) + if first >= 0 and count >= 0 and first + count <= nF then + for f = first, first + count - 1 do + faceModel[f + 1] = faceModel[f + 1] or (m + 1) + end + end + end + local batches= {} + local orders= {} + local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 } + local total = 0 + for f = 0, nF - 1 do + local o = base + F.at + f * 104 + local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28) + local model = faceModel[f + 1] or 1 + local tris= {} + if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then + for k = 0, nmv - 3, 3 do + local ok = true + local tri = {} + for c = 0, 2 do + local idx = readi32(b, base + MV.at + (mv + k + c) * 4) + if idx < 0 or idx >= n then + ok = false + end + tri[c + 1] = first + idx + end + if ok then + table.insert(tris, tri[3]) + table.insert(tris, tri[2]) + table.insert(tris, tri[1]) + end + end +do local __DARKLUA_VAR=kind == 1 and"polygons" or"meshes" counts[__DARKLUA_VAR]=counts[__DARKLUA_VAR]+ 1 +end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then + local w, h = readi32(b, o + 96), readi32(b, o + 100) + if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + counts.patches =counts.patches+ 1 + local L = level + for py = 0, math.floor((h - 1) / 2 )- 1 do + for px = 0, math.floor((w - 1) / 2 )- 1 do + -- the 3x3 control points of this sub-patch + local ctrl= {} + for j = 0, 2 do + for i = 0, 2 do + ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) + end + end + local grid= {} + for gy = 0, L do + local tv = gy / L + for gx = 0, L do + local tu = gx / L + local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } + local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } + local v = table.create(14, 0) + for j = 0, 2 do + for i = 0, 2 do + local wgt = bu[i + 1] * bv[j + 1] + local cp = ctrl[j * 3 + i + 1] + for k = 1, 14 do + v[k]=v[k]+ cp[k] * wgt + end + end + end + local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) + if l > 0 then + v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l + end + grid[gy * (L + 1) + gx + 1] = addExtra(v) + end + end + for gy = 0, L - 1 do + for gx = 0, L - 1 do + local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] + local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] + -- counter-clockwise for Quake's clockwise-front control grids + for _, v in __iter({ a, d, c2, c2, d, e }) do + table.insert(tris, v) + end + end + end + end + end + else + counts.skipped =counts.skipped+ 1 + end + elseif kind == 4 then + counts.billboards =counts.billboards+ 1 + else + counts.skipped =counts.skipped+ 1 + end + total =total+ #tris + if total > maxV then + return nil, "limit: too many vertices" + end + if #tris > 0 then + local key = shader .. ":" .. lm + local bm = batches[model] or {} + batches[model] = bm + local bt = bm[key] + if not bt then + bt = { shader = shader, lightmap = lm, verts = {} } + bm[key] = bt + local ol = orders[model] or {} + orders[model] = ol + table.insert(ol, key) + end + for _, v in __iter(tris) do + table.insert(bt.verts, v) + end + end + end + local scene = Scene.new() + scene.meta.up = "z" + -- shaders, lightmaps + for i = 0, nT - 1 do + local name = cstr(b, base + T.at + i * 72, 64) + table.insert(scene.textures, { name = name, uri = name }) + end + local lmTex= {} + for i = 0, nLM - 1 do + local img = Types.Image.new(128, 128) + local o = base + LM.at + i * 49152 + for k = 0, 128 * 128 - 1 do + writeu8(img.pixels, k * 4, readu8(b, o + k * 3)) + writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1)) + writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2)) + writeu8(img.pixels, k * 4 + 3, 255) + end + img.meta.source = { format = "bsp", lightmap = i } + table.insert(scene.textures, { name = "lightmap " .. i, image = img }) + lmTex[i] = #scene.textures + end + local matOf= {} + local root= { name = "bsp", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local modelCount = math.max(nM, 1) + for m = 1, modelCount do + local list = orders[m] + if list then + local mesh= { name = m == 1 and"world" or"*" .. (m - 1), primitives = {} } + for _, key in __iter(list) do + local bt = batches[m][key] + local nv = #bt.verts + local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4) + for k, id in __iter(bt.verts) do + local v +if id >= 0 then + v = vertex(id) + else + local e = (-id - 1) * 14 + v = (table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) ) +end + local o = (k - 1) + writef32(pb, o * 12, v[1]) + writef32(pb, o * 12 + 4, v[2]) + writef32(pb, o * 12 + 8, v[3]) + writef32(ub, o * 8, v[4]) + writef32(ub, o * 8 + 4, v[5]) + writef32(lb, o * 8, v[6]) + writef32(lb, o * 8 + 4, v[7]) + writef32(nb, o * 12, v[8]) + writef32(nb, o * 12 + 4, v[9]) + writef32(nb, o * 12 + 8, v[10]) + for c = 0, 3 do + writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255)) + end + writeu32(ib, o * 4, o) + end + local mi = matOf[key] + if not mi then + local name = (bt.shader >= 0 and bt.shader < nT and{scene.textures[bt.shader + 1].name }or{"noshader" +})[1] local mat = Scene.material(name) + mat.metallic = 0 + if bt.shader >= 0 and bt.shader < nT then + mat.baseColorTexture = { texture = bt.shader + 1 } + end + local lt = lmTex[bt.lightmap] + mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = lt and 1 or nil } } + table.insert(scene.materials, mat) + mi = #scene.materials + matOf[key] = mi + end + table.insert(mesh.primitives, { + attributes = { + POSITION = Scene.accessor(pb, "f32", 3, nv), + NORMAL = Scene.accessor(nb, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv), + TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv), + COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv), + }, + indices = Scene.accessor(ib, "u32", 1, nv), + mode = "triangles" , + material = mi, + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } }) + table.insert(root.children, #scene.nodes) + end + end + scene.meta.faces = counts + return scene, nil +end + +return Quake3 +end +__FILES["model/dae"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its +-- manifest.xml and the images). New code. +-- Reads: geometry (<mesh> triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input +-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), +-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / +-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> +-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), +-- kept encoded (opts.resolve / opts.files, embedded hex <data>, data: URIs), the instanced visual scene (matrix / +-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances +-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under +-- <skeleton> or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph +-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; +-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as +-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE +-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, +-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" +-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left +-- origin (opts.flipV = false keeps Collada's). +-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. +-- Not supported: <spline> / <brep> geometry, polygon holes (<ph>: the outer loop only), Bezier / Hermite curves +-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than +-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Zip = __include("containers/Zip") +local Read = __include("model/dae/Read") +local Write = __include("model/dae/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Dae = { + name = "dae", + category = "model", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + +function Dae.sniff(r) +local head = r:peek(2048) + if string.sub(head, 1, 4) == "PK\3\4" then + local nlen = string.byte(head, 27) or 0 + local name = string.lower(string.sub(head, 31, 30 + nlen)) + if string.find(name, "%.dae$") or name == "manifest.xml" then + return 0.95 + end + return 0 + end + -- UTF-16 files: drop the zero bytes + if string.find(string.sub(head, 1, 4), "\0", 1, true) then + head = string.gsub(head, "%z", "") + end + if string.find(head, "<COLLADA", 1, true) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts, zip) +return function(uri) +local v= nil + if zip then + local d = zip:read(uri) + if d then + return d + end + end + if not opts then + return nil + end + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1] end +end + +-- the main .dae of a .zae: manifest.xml's <dae_root>, else the first .dae entry +local function zae(r) +local zip, err = Zip.open(r) + if not zip then + return nil, nil, err + end + local main= nil + local manifest = zip:readString("manifest.xml") + if manifest then + local d = Xml.decode(manifest) + local rootEl = d and d.root and Xml.child(d.root , "dae_root") + if rootEl then + main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") + main = main and string.gsub(main, "^%./", "") + end + end + if not main or not zip:find(main) then + main = nil + for _, e in __iter(zip:list()) do + if string.find(string.lower(e.name), "%.dae$") then + main = e.name + break + end + end + end + if not main then + return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae") + end + local text, rerr = zip:readString(main) + if not text then + return nil, nil, rerr + end + return zip, text, nil +end + +function Dae.decode(r, opts) +local text +local zip= nil + if r:peek(4) == "PK\3\4" then + local z, t, err = zae(r) + if not z then + return nil, err + end + zip, text = z, t +else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local scene, err = Read.scene(doc, fetcher(opts, zip), opts) + if not scene then + return nil, err + end + if zip and scene.meta.source then + scene.meta.source.zae = true + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Dae.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "zae" then + -- a zip: manifest.xml, the .dae and its images + local files = {} + local o = table.clone(opts) + o.files = files + o.name = "model.dae" + local text = Write.build(scene, o) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + local w = Zip.writer() + w:add("manifest.xml", '<?xml version="1.0" encoding="utf-8"?>\n<dae_root>./model.dae</dae_root>\n') + w:add("model.dae", text) + local names = {} + for name in __iter(files) do + table.insert(names, name) + end + table.sort(names) + for _, name in __iter(names) do + w:add(name, files[name], { method = "store" }) + end + return w:finish() + end + local text = Write.build(scene, opts) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + return buffer.fromstring(text), nil +end + +return Dae +end +__FILES["model/dae/Math"] = function() +--!strict +-- model/dae/Math: the Collada-specific transform elements (<lookat>, <skew>); everything else (matrices, +-- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +local Mat4 = __include("codecs/model/Mat4") + +local DaeMath = {} + +local sqrt, rad = math.sqrt, math.rad + +local function cross(a, b) +return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function norm(a) +local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + if l < 1e-20 then + return { 0, 0, 0 } + end + return { a[1] / l, a[2] / l, a[3] / l } +end + +-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +function DaeMath.lookat(v) +local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 + local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) + local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z)) + local y = cross(z, x) + return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } +end + +-- skew(angle, rotation axis, translation axis) (RenderMan's skew) +function DaeMath.skew(v) +local a = rad(v[1] or 0) + local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) + local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) + local s = math.tan(a) + local m = Mat4.identity() + -- M = I + s * t * r^T (column-major: m[col*4 + row]) + for row = 0, 2 do + for col = 0, 2 do +do local __DARKLUA_VAR=col * 4 + row + 1 m[__DARKLUA_VAR]=m[__DARKLUA_VAR]+ s * t[row + 1] * r[col + 1] +end end + end + return m +end + +return DaeMath +end +__FILES["model/dae/Read"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / +-- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile +-- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, +-- images (kept encoded through the fetch callback, or embedded hex <data>), the visual scene's node tree (matrix / +-- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin +-- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as +-- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform +-- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS +-- channels; one animation per animation clip, else one for the file). +local Err = __include("core/Err") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local M = __include("model/dae/Math") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + + + +local Scene = Types.Scene +local find, sub, gmatch, match, lower, upper = string.find, string.sub, string.gmatch, string.match, string.lower, string.upper +local children, child, text = Xml.children, Xml.child, Xml.text + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" } +local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" } +local PARAM_SIZE= { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } +local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 } + +-- ------------------------------------------------------------------------------------------------ helpers +local function numbers(s, limit) +local out = {} + local n = 0 + for w in __iter(gmatch(s, "[^%s]+")) do + n =n+ 1 + if n > limit then + return nil, "array over the limit" + end + local v = tonumber(w) + if v == nil and find(w, ",", 1, true) and not find(w, ".", 1, true) then + v = tonumber((string.gsub(w, ",", "."))) -- decimal commas (some 3ds Max exporters) + end + if v == nil then + local lw = lower(w) + v = (lw == "nan" or lw == "-nan" or lw == "1.#qnan" or lw == "-1.#ind" )and 0 or((lw == "inf" or lw == "1.#inf" )and{math.huge }or{((lw == "-inf" or lw == "-1.#inf" )and{(-math.huge )}or{lw == "true" and 1 or(lw == "false" and 0 or 0 +)})[1]})[1] end + out[n] = v +end + return out, nil +end +local function words(s) +local out = {} + for w in __iter(gmatch(s, "[^%s]+")) do + table.insert(out, w) + end + return out +end +local function attr(node, name) +local v = node and node.attrs and node.attrs[name] + return (type(v) == "string" and{v }or{nil +})[1]end +local function urlId(url) +if not url then + return nil + end + return match(url, "^#(.*)$") or url +end +local function lname(node) +return Xml.localName(node.name) +end +local function numText(node, default) +if not node then + return default + end + return tonumber(match(text(node), "[^%s]+") or "") or default +end +local function color(node) +local c = node and child(node, "color") + if not c then + return nil + end + local v = numbers(text(c), 16) or {} + return { v[1] or 0, v[2] or 0, v[3] or 0, v[4] or 1 } +end + + + + + + + + + + + + + + + + + + + + + + + + + +local function skip(C, what) + C.skipped[what] = (C.skipped[what] or 0) + 1 +end + +-- ------------------------------------------------------------------------------------------------ sources +-- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) +local function readSource(C, el) +local cached = C.sources[el] + if cached ~= nil then + return cached or nil + end + C.sources[el] = false + local arrEl= nil + local strings = false + for _, ch in __iter(children(el)) do + local n = lname(ch) + if n == "float_array" or n == "int_array" or n == "bool_array" then + arrEl = ch + elseif n == "Name_array" or n == "IDREF_array" or n == "SIDREF_array" or n == "token_array" then + arrEl, strings = ch, true + end + end + local values= {} + if arrEl then + if strings then + values = words(text(arrEl)) + else + local v, e = numbers(text(arrEl), C.limit) + if not v then + C.err = e + return nil + end + values = v + end + end + local tc = child(el, "technique_common") + local acc = tc and child(tc, "accessor") + local out +if not acc then + out = { data = values, comps = 1, count = #values } + else + local count = tonumber(attr(acc, "count") or "") or 0 + local stride = tonumber(attr(acc, "stride") or "") or 1 + local offset = tonumber(attr(acc, "offset") or "") or 0 + local picks = {} + local pos = 0 + local anyNamed = false + for _, p in __iter(children(acc, "param")) do + if attr(p, "name") then + anyNamed = true + end + end + for _, p in __iter(children(acc, "param")) do + local w = PARAM_SIZE[attr(p, "type") or ""] or 1 + if attr(p, "name") or not anyNamed then + for k = 0, w - 1 do + table.insert(picks, pos + k) + end + end + pos =pos+ w + end + if #picks == 0 then + for k = 0, stride - 1 do + table.insert(picks, k) + end + end + if stride < 1 or count < 0 or count * stride > C.limit * 16 then + C.err = "bad accessor" + return nil + end + count = math.min(count, math.max(0, math.floor((#values - offset) / math.max(stride, 1)))) + local comps = #picks + local data = table.create(count * comps) + local n = 0 + for i = 0, count - 1 do + local base = offset + i * stride + 1 + for _, k in __iter(picks) do + n =n+ 1 + data[n] = values[base + k] or 0 + end + end + out = { data = data, comps = comps, count = count } + end + C.sources[el] = out + return out +end + +local function sourceById(C, url) +local id = urlId(url) + local el = id and C.ids[id] + if not el or lname(el) ~= "source" then + return nil + end + return readSource(C, el) +end + +-- ------------------------------------------------------------------------------------------------ images, materials +local function fetchImage(C, ref) +local uri = ref + uri = string.gsub(uri, "^file:///(%a:)", "%1") + uri = string.gsub(uri, "^file://", "") + local data = C.fetch(uri) + if not data then + local decoded = string.gsub(uri, "%%(%x%x)", function(h) +return string.char((tonumber(h, 16) )) + end) + data = C.fetch(decoded) + if not data then + local base = match(decoded, "([^/\\]+)$") + if base and base ~= decoded then + data = C.fetch(base) + end + end + end + return data, uri +end + +local function image(C, id) +local cached = C.images[id] + if cached ~= nil then + return cached or nil + end + C.images[id] = false + local el = C.ids[id] + if not el or lname(el) ~= "image" then + return nil + end + local img= { name = attr(el, "name") or id } + local init = child(el, "init_from") + local hex= child(el, "data") + if init then + local ref = child(init, "ref") + local s = match(text(ref or init), "^%s*(.-)%s*$") or "" + if s ~= "" then + if sub(s, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(s) + if d then + img.data, img.mime = d, mime + end + else + local d, uri = fetchImage(C, s) + img.data, img.uri = d, uri + local ext = match(uri, "%.([%w]+)$") + img.mime = ext and MIME[lower(ext)] + end + end + hex = hex or child(init, "hex") + end + if hex and not img.data then + local h = string.gsub(text(hex), "%s+", "") + if #h % 2 == 0 and not find(h, "[^%x]") then + local b = buffer.create(math.floor(#h / 2)) + for i = 0, math.floor(#h / 2 )- 1 do + buffer.writeu8(b, i, (tonumber(sub(h, i * 2 + 1, i * 2 + 2), 16) )) + end + img.data = b + local fmt = attr(hex, "format") or attr(el, "format") + img.mime = fmt and MIME[lower(fmt)] + end + end + if img.data and not img.mime then + local b = img.data + if buffer.len(b) >= 4 then + local m4 = buffer.readstring(b, 0, 4) + img.mime = m4 == "\137PNG" and"image/png" or(sub(m4, 1, 3) == "\255\216\255" and"image/jpeg" or nil +) end + end + C.images[id] = img + return img +end + +-- the effect's newparams by sid (this level and the profile's) +local function newparams(effect, profile, technique) +local out = {} + for _, scope in __iter({ effect, profile, technique }) do + if scope then + for _, np in __iter(children(scope, "newparam")) do + local sid = attr(np, "sid") + if sid then + out[sid] = np + end + end + end + end + return out +end + +-- texture(effect params, sampler sid) -> scene texture index +local function texture(C, params, samplerSid) +local np = params[samplerSid] + local imageId= nil + local sampler= nil + if np then + local s2d = child(np, "sampler2D") or child(np, "samplerCUBE") or child(np, "sampler3D") + if s2d then + sampler = s2d + local inst = child(s2d, "instance_image") + if inst then + imageId = urlId(attr(inst, "url")) + else + local src = child(s2d, "source") + local surfNp = src and params[match(text(src), "^%s*(.-)%s*$") or ""] + local surf = surfNp and child(surfNp, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + local surf = child(np, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + -- many exporters reference the image id directly + imageId = samplerSid + end + if not imageId then + return nil + end + local key = imageId .. "|" .. samplerSid + local cached = C.textures[key] + if cached then + return cached + end + local img = image(C, imageId) + if not img then + return nil + end + local tex= { name = img.name, data = img.data, mime = img.mime, uri = img.uri } + if sampler then + local ws, wt = child(sampler, "wrap_s"), child(sampler, "wrap_t") + local mag = child(sampler, "magfilter") + local smp= {} + if ws then + smp.wrapS = WRAP[upper(match(text(ws), "[%w_]+") or "")] +end + if wt then + smp.wrapT = WRAP[upper(match(text(wt), "[%w_]+") or "")] +end + if mag then + local f = upper(match(text(mag), "[%w_]+") or "") + smp.filter = f == "NEAREST" and"nearest" or(f == "LINEAR" and"linear" or nil +) end + if next(smp ) then + tex.sampler = smp + end + end + table.insert(C.scene.textures, tex) + local idx = #C.scene.textures + C.textures[key] = idx + return idx +end + +-- one colour-or-texture parameter of a common technique +local function param(C, params, el, uvsets) +if not el then + return nil, nil + end + local c = color(el) + local f = child(el, "float") + local tx = child(el, "texture") + local ref= nil + if tx then + local ti = texture(C, params, attr(tx, "texture") or "") + if ti then + ref = { texture = ti } + local set = uvsets[attr(tx, "texcoord") or ""] + if set and set > 0 then + ref.texCoord = set + end + end + end + if c then + return c, ref + elseif f then + return numText(f, 0), ref + end + local pr = child(el, "param") + if pr then + local np = params[attr(pr, "ref") or ""] + local v = np and (child(np, "float4") or child(np, "float3") or child(np, "float")) + if v then + local nums = numbers(text(v), 16) or {} + if #nums == 1 then + return nums[1], ref + end + return { nums[1] or 0, nums[2] or 0, nums[3] or 0, nums[4] or 1 }, ref + end + end + return nil, ref +end + +local function material(C, id, uvsets) +local cached = C.materials[id] + if cached then + return cached + end + local el = C.ids[id] + if not el or lname(el) ~= "material" then + return nil + end + local mat = Scene.material(attr(el, "name") or id) + mat.metallic = 0 + local inst = child(el, "instance_effect") + local effect = inst and C.ids[urlId(attr(inst, "url")) or ""] + local phong= {} + if effect and lname(effect) == "effect" then + local profile = child(effect, "profile_COMMON") + local tech = profile and child(profile, "technique") + local shader= nil + if tech then + for _, ch in __iter(children(tech)) do + local n = lname(ch) + if n == "phong" or n == "blinn" or n == "lambert" or n == "constant" then + shader = ch + phong.model = n + break + end + end + end + local params = newparams(effect, profile, tech) + if shader then + local diffuse, dtex = param(C, params, child(shader, "diffuse"), uvsets) + local emission, etex = param(C, params, child(shader, "emission"), uvsets) + local ambient, atex = param(C, params, child(shader, "ambient"), uvsets) + local specular, stex = param(C, params, child(shader, "specular"), uvsets) + local shininess = param(C, params, child(shader, "shininess"), uvsets) + local reflective = param(C, params, child(shader, "reflective"), uvsets) + local reflectivity = param(C, params, child(shader, "reflectivity"), uvsets) + local transparentEl = child(shader, "transparent") + local transparent, ttex = param(C, params, transparentEl, uvsets) + local transparency = param(C, params, child(shader, "transparency"), uvsets) + local ior = param(C, params, child(shader, "index_of_refraction"), uvsets) + phong.diffuse, phong.diffuseTexture = diffuse, dtex + phong.emission, phong.emissionTexture = emission, etex + phong.ambient, phong.ambientTexture = ambient, atex + phong.specular, phong.specularTexture = specular, stex + phong.shininess, phong.reflective, phong.reflectivity = shininess, reflective, reflectivity + phong.transparent, phong.transparentTexture, phong.transparency = transparent, ttex, transparency + phong.indexOfRefraction = ior + if type(diffuse) == "table" then + mat.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 } -- its alpha is not opacity (exporters write 0) + end + if phong.model == "constant" and type(emission) == "table" then + mat.baseColor = { emission[1], emission[2], emission[3], 1 } + mat.extensions = { KHR_materials_unlit = {} } + end + if dtex then + mat.baseColorTexture = dtex + if type(diffuse) ~= "table" then + mat.baseColor = { 1, 1, 1, 1 } + end + end + if type(emission) == "table" and phong.model ~= "constant" then + mat.emissive = { emission[1], emission[2], emission[3] } + end + if etex then + mat.emissiveTexture = etex + mat.emissive = { 1, 1, 1 } + end + if type(shininess) == "number" then + mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + end + -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then + local mode = attr(transparentEl, "opaque") or "A_ONE" + local tv = (type(transparency) == "number" and{transparency }or{1 +})[1] local tc= (type(transparent) == "table" and{transparent }or{{ 1, 1, 1, 1 } +})[1] local a +if mode == "RGB_ZERO" then + a = 1 - tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + elseif mode == "A_ZERO" then + a = 1 - tv * tc[4] + elseif mode == "RGB_ONE" then + a = tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + else + a = tv * tc[4] + end + a = math.clamp(a, 0, 1) + if a < 0.999 and a > 0.001 then + mat.baseColor[4] = a + mat.alphaMode = "blend" + end + phong.opacity = a + end + if ttex then + mat.alphaMode = "blend" + end + end + -- FCOLLADA / MAX3D / OpenCOLLADA extras: bump maps and double sidedness + for _, scope in __iter({ tech, profile, effect }) do + if scope then + for _, ex in __iter(children(scope, "extra")) do + for _, tq in __iter(children(ex, "technique")) do + local bump = child(tq, "bump") + if bump and not mat.normalTexture then + local _, btex = param(C, params, bump, uvsets) + if btex then + mat.normalTexture = btex + end + end + local ds = child(tq, "double_sided") + if ds and numText(ds, 0) ~= 0 then + mat.doubleSided = true + end + end + end + end + end + end + mat.extras = { phong = phong } + table.insert(C.scene.materials, mat) + local idx = #C.scene.materials + C.materials[id] = idx + return idx +end +-- ------------------------------------------------------------------------------------------------ geometry +-- the inputs of a primitive element (VERTEX expanded into the <vertices> inputs) + + + +local function inputs(C, prim, verticesEl) +local out= {} + local stride = 0 + for _, inp in __iter(children(prim, "input")) do + local sem = upper(attr(inp, "semantic") or "") + local offset = tonumber(attr(inp, "offset") or "") or 0 + local set = tonumber(attr(inp, "set") or "") or 0 + if offset + 1 > stride then + stride = offset + 1 + end + if sem == "VERTEX" then + local vel = C.ids[urlId(attr(inp, "source")) or ""] or verticesEl + if vel and lname(vel) == "vertices" then + for _, vin in __iter(children(vel, "input")) do + local vs = upper(attr(vin, "semantic") or "") + local src = sourceById(C, attr(vin, "source")) + if src then + table.insert(out, { semantic = vs, source = src, offset = offset, set = tonumber(attr(vin, "set") or "") or set }) + end + end + end + else + local src = sourceById(C, attr(inp, "source")) + if src then + table.insert(out, { semantic = sem, source = src, offset = offset, set = set }) + end + end + end + return out, math.max(stride, 1) +end + +-- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode +local function corners(C, prim, kind, stride) +local p= {} + local faces= {} + local starts= {} + local function addP(el) +local v, e = numbers(text(el), C.limit) + if not v then + C.err = e + return 0, 0 + end + local base = #p + table.move(v, 1, #v, base + 1, p) + return math.floor(base / stride), math.floor(#v / stride +) end + if kind == "triangles" or kind == "lines" then + local per = kind == "triangles" and 3 or 2 + local pe = child(prim, "p") + if pe then + local _, n = addP(pe) + local count = math.min(tonumber(attr(prim, "count") or "") or math.floor(n / per), math.floor(n / per)) + for f = 0, count - 1 do + table.insert(faces, per) + for k = 0, per - 1 do + table.insert(starts, f * per + k) + end + end + end + return p, faces, starts, kind + elseif kind == "polylist" then + local pe = child(prim, "p") + local vc = child(prim, "vcount") + if pe and vc then + local _, n = addP(pe) + local counts = numbers(text(vc), C.limit) or {} + local at = 0 + for _, c in __iter(counts) do + c = math.floor(c) + if c < 0 or at + c > n then + break + end + table.insert(faces, c) + for k = 0, c - 1 do + table.insert(starts, at + k) + end + at =at+ c + end + end + return p, faces, starts, "polygons" + elseif kind == "polygons" then + local list = children(prim, "p") + for _, ph in __iter(children(prim, "ph")) do + local outer = child(ph, "p") + if outer then + table.insert(list, outer) + end + skip(C, "polygon holes") + end + for _, pe in __iter(list) do + local first, n = addP(pe) + if n > 0 then + table.insert(faces, n) + for k = 0, n - 1 do + table.insert(starts, first + k) + end + end + end + return p, faces, starts, "polygons" + elseif kind == "linestrips" then + for _, pe in __iter(children(prim, "p")) do + local first, n = addP(pe) + for k = 0, n - 2 do + table.insert(faces, 2) + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + end + end + return p, faces, starts, "lines" + elseif kind == "tristrips" or kind == "trifans" then + for _, pe in __iter(children(prim, "p")) do + local first, n = addP(pe) + for k = 0, n - 3 do + table.insert(faces, 3) + if kind == "trifans" then + table.insert(starts, first) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + elseif k % 2 == 0 then + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + else + table.insert(starts, first + k + 1) + table.insert(starts, first + k) + table.insert(starts, first + k + 2) + end + end + end + return p, faces, starts, "triangles" + end + return nil, nil, nil, kind +end + +local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true } + +-- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) + + +local function buildPrim(C, prim, verticesEl, kind) +local ins, stride = inputs(C, prim, verticesEl) + local p, faces, starts, mode = corners(C, prim, kind, stride) + if C.err or not p or not faces or not starts then + return nil + end + local posIn= nil + for _, i in __iter(ins) do + if i.semantic == "POSITION" then + posIn = i + break + end + end + if not posIn then + skip(C, "primitives without positions") + return nil + end + -- attribute names + local named= {} + local texSets= {} + local texInputs= {} + local colorN, normalSeen = 0, false + for _, i in __iter(ins) do + if i.semantic == "TEXCOORD" then + table.insert(texInputs, i) + end + end + table.sort(texInputs, function(a, b) +if a.set ~= b.set then + return a.set < b.set + end + return a.offset < b.offset + end) + for k, i in __iter(texInputs) do + texSets[k] = i.set + table.insert(named, { input = i, name = "TEXCOORD_" .. (k - 1), comps = 2 }) + end + for _, i in __iter(ins) do + local s = i.semantic + local comps = math.min(i.source.comps, 4) + if s == "POSITION" then + if i == posIn then + table.insert(named, { input = i, name = "POSITION", comps = 3 }) + end + elseif s == "NORMAL" then + table.insert(named, { input = i, name = (normalSeen and(("_NORMAL" .. i.set ))or("NORMAL")), comps = 3 }) + normalSeen = true + elseif s == "COLOR" then + table.insert(named, { input = i, name = "COLOR_" .. colorN, comps = comps >= 4 and 4 or 3 }) + colorN =colorN+ 1 + elseif s ~= "TEXCOORD" then + table.insert(named, { input = i, name = "_" .. s .. ((i.set ~= 0 and{(tostring(i.set) )}or{""})[1]), comps = math.max(comps, 1) }) + end + end + -- de-index + local np = #p + local keyOf= {} + local tuples= {} -- the first p index of each output vertex's tuple + local corner = (table.create(#starts) ) +local count = 0 + for ci, s in __iter(starts) do + local base = s * stride + if base + stride > np then + C.err = "index list too short" + return nil + end + local key +if stride == 1 then + key = p[base + 1] + else + key = table.concat(p, ",", base + 1, base + stride) + end + local v = keyOf[key] + if not v then + v = count + count =count+ 1 + keyOf[key] = v + tuples[count] = base + end + corner[ci] = v + end + C.vertices =C.vertices+ count + if C.vertices > C.limit then + C.err = "over the vertex limit" + return nil + end + local attributes= {} + local posIndex = table.create(count, 0) + for _, a in __iter(named) do + local src = a.input.source + local comps, scomps = a.comps, src.comps + local data, n = src.data, src.count + local buf = buffer.create(count * comps * 4) + local off = a.input.offset + 1 + local isTex = sub(a.name, 1, 9) == "TEXCOORD_" + local isPos = a.name == "POSITION" + for v = 0, count - 1 do + local idx = p[tuples[v + 1] + off] + if idx == nil or idx < 0 or idx >= n or idx ~= math.floor(idx / 1 )then + C.err = "index out of range" + return nil + end + if isPos then + posIndex[v + 1] = idx + end + local at = idx * scomps + for k = 1, comps do + local x = (k <= scomps and{data[at + k] }or{(k == 4 and 1 or 0) +})[1] if type(x) ~= "number" then + x = 0 + end + if isTex and k == 2 and C.flipV then + x = 1 - x + end + buffer.writef32(buf, (v * comps + k - 1) * 4, x) + end + end + attributes[a.name] = Scene.accessor(buf, "f32", comps, count) + end + local nc = #corner + local out= { attributes = attributes, mode = "triangles" } + if mode == "polygons" then + local allTri = true + for _, f in __iter(faces) do + if f ~= 3 then + allTri = false + break + end + end + if allTri then + mode = "triangles" + elseif C.triangulate then + -- fan triangulation + local tri= {} + local at = 0 + for _, f in __iter(faces) do + for k = 1, f - 2 do + table.insert(tri, corner[at + 1]) + table.insert(tri, corner[at + k + 1]) + table.insert(tri, corner[at + k + 2]) + end + at =at+ f + end + corner, nc, mode = tri, #tri, "triangles" + else + local fb = buffer.create(#faces * 4) + for i, f in __iter(faces) do + buffer.writeu32(fb, (i - 1) * 4, f) + end + out.faces = Scene.accessor(fb, "u32", 1, #faces) + end + end + out.mode = mode +local ib = buffer.create(nc * 4) + for i = 1, nc do + buffer.writeu32(ib, (i - 1) * 4, corner[i]) + end + out.indices = Scene.accessor(ib, "u32", 1, nc) + return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } +end + +-- geometry(el) -> the built primitives (cached per geometry element) +local function geometry(C, el) +local cached = C.posIndex[el] + if cached then + return cached +end + local mesh = child(el, "mesh") or child(el, "convex_mesh") + if not mesh then + if child(el, "spline") or child(el, "brep") then + skip(C, "spline / brep geometry") + end + return nil + end + local verticesEl = child(mesh, "vertices") + local out= {} + for _, ch in __iter(children(mesh)) do + local n = lname(ch) + if PRIMS[n] then + local b = buildPrim(C, ch, verticesEl, n) + if C.err then + return nil + end + if b then + table.insert(out, b) + end + end + end + C.posIndex[el] = out +return out +end + +-- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set +local function bindings(node) +local syms= {} + local sets= {} + local bm = node and child(node, "bind_material") + local tc = bm and child(bm, "technique_common") + if tc then + for _, im in __iter(children(tc, "instance_material")) do + local sym, target = attr(im, "symbol"), urlId(attr(im, "target")) + if sym and target then + syms[sym] = target + local s = {} + for _, bvi in __iter(children(im, "bind_vertex_input")) do + local sem = attr(bvi, "semantic") + if sem then + s[sem] = tonumber(attr(bvi, "input_set") or "") or 0 + end + end + sets[sym] = s + end + end + end + return syms, sets +end + +local function copyAccessor(a) +local b = buffer.create(buffer.len(a.data)) + buffer.copy(b, 0, a.data) + return Scene.accessor(b, a.type, a.components, a.count) +end + +-- mesh(geometry element, instance element, skin?) -> scene mesh index +local function meshFor(C, geomEl, inst, key, bindShape) +local syms, sets = bindings(inst) + local parts = { key } + for s, t in __iter(syms) do + table.insert(parts, s .. "=" .. t) + end + table.sort(parts) + local k = table.concat(parts, ";") + local built = geometry(C, geomEl) + if not built or #built == 0 then + return nil, nil + end + local cached = C.meshes[k] + if cached then + return cached, built + end + local mesh= { name = attr(geomEl, "name") or attr(geomEl, "id"), primitives = {} } + for _, b in __iter(built) do + local prim = b.prim + if bindShape then + -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) + local attrs = table.clone(prim.attributes) + local pos = copyAccessor(attrs.POSITION) + for v = 0, pos.count - 1 do + local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) + x, y, z = Mat4.point(bindShape, x, y, z) + buffer.writef32(pos.data, v * 12, x) + buffer.writef32(pos.data, v * 12 + 4, y) + buffer.writef32(pos.data, v * 12 + 8, z) + end + attrs.POSITION = pos + if attrs.NORMAL then + local nm = Mat4.normalMatrix(bindShape) + local nrm = copyAccessor(attrs.NORMAL) + for v = 0, nrm.count - 1 do + local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8) + x, y, z = nm[1] * x + nm[5] * y + nm[9] * z, nm[2] * x + nm[6] * y + nm[10] * z, nm[3] * x + nm[7] * y + nm[11] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + buffer.writef32(nrm.data, v * 12, x) + buffer.writef32(nrm.data, v * 12 + 4, y) + buffer.writef32(nrm.data, v * 12 + 8, z) + end + attrs.NORMAL = nrm + end + prim = table.clone(prim) + prim.attributes = attrs + else + prim = table.clone(prim) + end + local sym = b.symbol + local target = sym and (syms[sym] or ((C.ids[sym] and lname(C.ids[sym]) == "material" and{sym }or{nil})[1])) + if not target then + -- no (or an unbound) symbol and a single binding: that one (MakeHuman leaves out the symbol) + local only, n = nil, 0 + for s2 in __iter(syms) do + only, n = s2, n + 1 + end + if n == 1 then + sym = only + target = syms[only ] + end + end + if target then + -- texcoord semantic -> TEXCOORD_n index among this primitive's sets + local uv= {} + for sem, set in __iter((sym and sets[sym]) or {}) do + uv[sem] = (table.find(b.texSets, set) or 1) - 1 + end + prim.material = material(C, target, uv) + end + table.insert(mesh.primitives, prim) + end + table.insert(C.scene.meshes, mesh) + local idx = #C.scene.meshes + C.meshes[k] = idx + return idx, built +end + +-- morph controller -> mesh with targets (deltas) +local function morphMesh(C, ctrl, morph, inst) +local base = C.ids[urlId(attr(morph, "source")) or ""] + if not base or lname(base) ~= "geometry" then + return nil + end + local idx, built = meshFor(C, base, inst, "morph:" .. (attr(ctrl, "id") or ""), nil) + if not idx or not built then + return nil + end + local mesh = C.scene.meshes[idx] + if mesh.weights then + return idx + end + local relative = upper(attr(morph, "method") or "NORMALIZED") == "RELATIVE" + local targetsEl = child(morph, "targets") + local targetIds= {} + local weights= {} + if targetsEl then + for _, inp in __iter(children(targetsEl, "input")) do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if src and sem == "MORPH_TARGET" then + for _, v in __iter(src.data) do + table.insert(targetIds, tostring(v)) + end + elseif src and sem == "MORPH_WEIGHT" then + for _, v in __iter(src.data) do + table.insert(weights, (type(v) == "number" and{v }or{0})[1]) + end + end + end + end + local tbuilt= {} + for _, tid in __iter(targetIds) do + local g = C.ids[tid] + local tb = g and lname(g) == "geometry" and geometry(C, g) + if not tb or #tb ~= #built then + skip(C, "morph targets with another topology") + return idx + end + table.insert(tbuilt, tb) + end + for pi, prim in __iter(mesh.primitives) do + local targets = {} + for ti, tb in __iter(tbuilt) do + local tp = tb[pi].prim + local t= {} + for _, name in __iter({ "POSITION", "NORMAL" }) do + local a, b = prim.attributes[name], tp.attributes[name] + if a and b and a.count == b.count then + local d = buffer.create(a.count * 12) + for i = 0, a.count * 3 - 1 do + local bv = buffer.readf32(b.data, i * 4) + buffer.writef32(d, i * 4, (relative and{bv }or{(bv - buffer.readf32(a.data, i * 4))})[1]) + end + t[name] = Scene.accessor(d, "f32", 3, a.count) + end + end + targets[ti] = t + end + prim.targets = targets + end + mesh.weights = weights + return idx +end + +-- ------------------------------------------------------------------------------------------------ cameras, lights +local function camera(C, el) +local optics = child(el, "optics") + local tc = optics and child(optics, "technique_common") + if not tc then + return nil + end + local cam +local persp, ortho = child(tc, "perspective"), child(tc, "orthographic") + if persp then + local xfov, yfov = child(persp, "xfov"), child(persp, "yfov") + local aspect = child(persp, "aspect_ratio") + local ar = (aspect and{(numText(aspect, 1) )}or{nil +})[1] local yf +if yfov then + yf = math.rad(numText(yfov, 45)) + elseif xfov and ar then + yf = 2 * math.atan(math.tan(math.rad(numText(xfov, 45)) / 2) / ar) + else + yf = math.rad(numText(xfov, 45)) + end + if xfov and yfov and not ar then + local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2) + ar = (ty > 0 and((tx / ty ))or(nil +)) end + cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective" , yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } +elseif ortho then + local xm, ym = child(ortho, "xmag"), child(ortho, "ymag") + local ar = numText(child(ortho, "aspect_ratio"), 1) + local x = (xm and{(numText(xm, 1) )}or{(numText(ym, 1) * ar +)})[1] local y = (ym and{(numText(ym, 1) )}or{(numText(xm, 1) / ar +)})[1] cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic" , xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } +else + return nil + end + table.insert(C.scene.cameras, cam) + return #C.scene.cameras +end + +-- light(el) -> light index, or nil and the ambient colour +local function light(C, el) +local tc = child(el, "technique_common") + if not tc then + return nil, nil + end + local amb = child(tc, "ambient") + if amb then + return nil, color(amb) or { 1, 1, 1, 1 } + end + local kinds= { directional = "directional", point = "point", spot = "spot" } + for k, t in __iter(kinds) do + local l = child(tc, k) + if l then + local c = color(l) or { 1, 1, 1 } + local lt= { name = attr(el, "name") or attr(el, "id"), type = t , color = { c[1], c[2], c[3] }, intensity = 1 } + if t == "spot" then + local fa = numText(child(l, "falloff_angle"), 180) + lt.outerCone = math.clamp(math.rad(fa) / 2, 0, math.pi / 2) + lt.innerCone = 0 + end + table.insert(C.scene.lights, lt) + local idx = #C.scene.lights + if t ~= "directional" then + lt.extras = { + dae = { + constantAttenuation = numText(child(l, "constant_attenuation"), 1), + linearAttenuation = numText(child(l, "linear_attenuation"), 0), + quadraticAttenuation = numText(child(l, "quadratic_attenuation"), 0), + falloffExponent = (t == "spot" and{(numText(child(l, "falloff_exponent"), 0) )}or{nil})[1], + }, + } +end + return idx, nil + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ nodes +local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } + +-- the matrix of one transform element's values +local function xfMatrix(kind, v) +if kind == "matrix" then + return Mat4.fromRows(v) + elseif kind == "translate" then + return Mat4.translation(v[1] or 0, v[2] or 0, v[3] or 0) + elseif kind == "rotate" then + return Mat4.fromQuat(Mat4.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) + elseif kind == "scale" then + return Mat4.scaling(v[1] or 1, v[2] or 1, v[3] or 1) + elseif kind == "lookat" then + return M.lookat(v) + elseif kind == "skew" then + return M.skew(v) + end + return Mat4.identity() +end + +local function compose(xf) +local m = Mat4.identity() + for _, x in __iter(xf) do + m = Mat4.mul(m, xfMatrix(x.kind, x.values)) + end + return m +end + +local function setTransform(node, m) + local t, r, s = Mat4.decomposeStrict(m) + node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil + if t and r and s then + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if math.abs(r[4]) < 1 - 1e-9 then + node.rotation = r + end + if math.abs(s[1] - 1) > 1e-7 or math.abs(s[2] - 1) > 1e-7 or math.abs(s[3] - 1) > 1e-7 then + node.scale = s + end + else + for i = 1, 16 do + if math.abs(m[i] - Mat4.identity()[i]) > 0 then + node.matrix = m + break + end + end + end +end + +local visitNode + +local function addChild(C, parent, node) +table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + table.insert(parent.children, idx) + return idx +end + +-- the instances of a node: the first of each kind on the node itself, the rest on child nodes +local function instances(C, el, node, idx) + local function slot(kind, name) +local n= node + if n[kind] == nil then + return node, idx + end + local extra= { name = name, children = {} } + return extra, addChild(C, node, extra) + end + for _, ch in __iter(children(el)) do + local n = lname(ch) + if n == "instance_geometry" then + local g = C.ids[urlId(attr(ch, "url")) or ""] + if g and lname(g) == "geometry" then + local mi = meshFor(C, g, ch, "geom:" .. (attr(g, "id") or ""), nil) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(g, "name")) + target.mesh = mi + end + end + elseif n == "instance_controller" then + local ctrl = C.ids[urlId(attr(ch, "url")) or ""] + local skinEl = ctrl and child(ctrl, "skin") + local morph = ctrl and child(ctrl, "morph") + if skinEl then + -- the skin's source may be a morph controller + local src = C.ids[urlId(attr(skinEl, "source")) or ""] + local morphEl = src and lname(src) == "controller" and child(src, "morph") + if morphEl then + src = C.ids[urlId(attr(morphEl, "source")) or ""] + skip(C, "skins over morph controllers (morph dropped)") + end + if src and lname(src) == "geometry" then + local bsm = child(skinEl, "bind_shape_matrix") + local bind = (bsm and{(Mat4.fromRows(numbers(text(bsm), 16) or {}) )}or{nil +})[1] local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind) + if C.err then + return + end + if mi and built then + local target, ti = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + local roots = {} + for _, sk in __iter(children(ch, "skeleton")) do + table.insert(roots, urlId(match(text(sk), "^%s*(.-)%s*$"))) + end + table.insert(C.pendingSkins, { node = ti, ctrl = ctrl, skin = skinEl, mesh = mi, built = built, roots = roots, bind = bind }) + end + end + elseif morph then + local mi = morphMesh(C, ctrl, morph, ch) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + target.weights = C.scene.meshes[mi].weights + end + end + elseif n == "instance_camera" then + local cel = C.ids[urlId(attr(ch, "url")) or ""] + local ci = cel and lname(cel) == "camera" and camera(C, cel) + if ci then + local target = slot("camera", C.scene.cameras[ci].name) + target.camera = ci + end + elseif n == "instance_light" then + local lel = C.ids[urlId(attr(ch, "url")) or ""] + if lel and lname(lel) == "light" then + local li, ambient = light(C, lel) + if li then + local target = slot("light", C.scene.lights[li].name) + target.light = li + elseif ambient then + local ex= node.extras or {} + ex.dae = ex.dae or {} + ex.dae.ambientLight = ambient + node.extras = ex + end + end + elseif n == "instance_node" then + local target = C.ids[urlId(attr(ch, "url")) or ""] + if target and lname(target) == "node" then + local ci = visitNode(C, target) + if ci then + table.insert(node.children, ci) + end + end + end + end +end + +visitNode = function(C, el) +if C.depth > 256 or #C.scene.nodes > C.limit then + C.err = "node tree too deep or too large (instance_node cycle?)" + return nil + end + C.depth =C.depth+ 1 + local xf = {} + for _, ch in __iter(children(el)) do + local n = lname(ch) + local want = XFORMS[n] + if want then + local v = numbers(text(ch), 64) or {} + table.insert(xf, { kind = n, sid = attr(ch, "sid"), values = v }) + end + end + local node= { name = attr(el, "name") or attr(el, "id"), children = {} } + setTransform(node, compose(xf)) + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + local id = attr(el, "id") + C.info[idx] = { xf = xf, sid = attr(el, "sid"), id = id, joint = upper(attr(el, "type") or "") == "JOINT" } + if id then + C.nodeOf[id] = C.nodeOf[id] or {} + table.insert(C.nodeOf[id], idx) + end + if upper(attr(el, "type") or "") == "JOINT" then + node.extras = { dae = { joint = true, sid = attr(el, "sid") } } +end + instances(C, el, node, idx) + for _, ch in __iter(children(el, "node")) do + if C.err then + break + end + local ci = visitNode(C, ch) + if ci then + table.insert(node.children, ci) + end + end + C.depth =C.depth- 1 + return idx +end + +-- ------------------------------------------------------------------------------------------------ skins +-- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +local function findJoint(C, name, roots, byId) +local nodes = C.scene.nodes + local function search(i, depth) +if depth > 300 then + return nil + end + local inf = C.info[i] + if inf and (inf.sid == name or (byId and inf.id == name)) then + return i + end + for _, c in __iter(nodes[i].children) do + local r = search(c, depth + 1) + if r then + return r + end + end + return nil + end + for _, r in __iter(roots) do + local f = search(r, 0) + if f then + return f + end + end + for i in __iter(nodes) do + local inf = C.info[i] + if inf and (inf.sid == name or inf.id == name) then + return i + end + end + for i, n in __iter(nodes) do + if n.name == name then + return i + end + end + return nil +end + +local function resolveSkins(C) + local cache= {} + for _, ps in __iter(C.pendingSkins) do +local __DARKLUA_CONTINUE_71=false repeat local skinEl = ps.skin + local jointsEl = child(skinEl, "joints") + local names= {} + local byId = false + local ibm= nil + if jointsEl then + for _, inp in __iter(children(jointsEl, "input")) do + local sem = upper(attr(inp, "semantic") or "") + local srcEl = C.ids[urlId(attr(inp, "source")) or ""] + local src = srcEl and lname(srcEl) == "source" and readSource(C, srcEl) + if src and sem == "JOINT" then + for _, v in __iter(src.data) do + table.insert(names, tostring(v)) + end + byId = child(srcEl, "IDREF_array") ~= nil + elseif src and sem == "INV_BIND_MATRIX" then + ibm = src + end + end + end + local roots= {} + for _, r in __iter(ps.roots) do + for _, ni in __iter(C.nodeOf[r] or {}) do + table.insert(roots, ni) + end + end + local jointNodes= {} + local ok = #names > 0 + for i, nm in __iter(names) do + local j = findJoint(C, nm, roots, byId) + if not j then + ok = false + break + end + jointNodes[i] = j + end + if not ok then + skip(C, "skins with unresolved joints") +__DARKLUA_CONTINUE_71=true break + end + local key = (attr(ps.ctrl, "id") or "") .. "|" .. table.concat(jointNodes, ",") + local si = cache[key] + if not si then + local skin= { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } + if ps.bind then + local sk= skin + sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + end + if ibm and ibm.comps == 16 and ibm.count >= #names then + local b = buffer.create(#names * 64) + for i = 0, #names - 1 do + local cm = Mat4.fromRows(ibm.data, i * 16 + 1) + for k = 1, 16 do + buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) + end + end + local acc = Scene.accessor(b, "f32", 16, #names) + acc.matrix = true + skin.inverseBindMatrices = acc + end + if roots[1] then + skin.skeleton = roots[1] + end + table.insert(C.scene.skins, skin) + si = #C.scene.skins + cache[key] = si + end + C.scene.nodes[ps.node].skin = si + -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) + local mesh = C.scene.meshes[ps.mesh] + if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then +__DARKLUA_CONTINUE_71=true break + end + local vw = child(skinEl, "vertex_weights") + if not vw then +__DARKLUA_CONTINUE_71=true break + end + local jOff, wOff, wSrc = 0, 1, nil + local stride = 1 + for _, inp in __iter(children(vw, "input")) do + local sem = upper(attr(inp, "semantic") or "") + local off = tonumber(attr(inp, "offset") or "") or 0 + stride = math.max(stride, off + 1) + if sem == "JOINT" then + jOff = off + elseif sem == "WEIGHT" then + wOff = off + wSrc = sourceById(C, attr(inp, "source")) + end + end + local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} + local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} + local wdata = wSrc and wSrc.data or {} + local per= {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local at = 0 + for pi, c in __iter(vcount) do + local list = {} + for _ = 1, math.floor(c) do + local j, w = v[at + jOff + 1], v[at + wOff + 1] + at =at+ stride + local wv = (w and{wdata[w + 1] }or{nil +})[1] if j and j >= 0 and j < #names and type(wv) == "number" and wv > 0 then + table.insert(list, { j, wv }) + end + end + table.sort(list, function(a, b) +return a[2] > b[2] + end) + local total = 0 + for k = 1, math.min(4, #list) do + total =total+ list[k][2] + end + local e = {} + for k = 1, math.min(4, #list) do + e[k * 2 - 1], e[k * 2] = list[k][1], list[k][2] / total + end + per[pi] = e + end + for pi, prim in __iter(mesh.primitives) do + local posIndex = ps.built[pi] and ps.built[pi].posIndex + local n = prim.attributes.POSITION.count + if posIndex and #posIndex == n then + local jt = #names < 256 and"u8" or"u16" + local js = jt == "u8" and 1 or 2 + local jb = buffer.create(n * 4 * js) + local wb = buffer.create(n * 16) + for vi = 0, n - 1 do + local e = per[posIndex[vi + 1] + 1] + for k = 0, 3 do + local j, w = 0, 0 + if e and e[k * 2 + 1] then + j, w = e[k * 2 + 1], e[k * 2 + 2] + end + if js == 1 then + buffer.writeu8(jb, vi * 4 + k, j) + else + buffer.writeu16(jb, (vi * 4 + k) * 2, j) + end + buffer.writef32(wb, (vi * 4 + k) * 4, w) + end + end + prim.attributes.JOINTS_0 = Scene.accessor(jb, jt, 4, n) + prim.attributes.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n) + end + end +__DARKLUA_CONTINUE_71=true until true if not __DARKLUA_CONTINUE_71 then break end end +end +-- ------------------------------------------------------------------------------------------------ animations + + + +local function sample(c, t) +local inp, out, st = c.input, c.output, c.stride + local n = #inp + local function at(i) +local r = (table.create(st) ) +for k = 1, st do + r[k] = out[(i - 1) * st + k] or 0 + end + return r + end + if n == 0 then + return {} + end + if t <= inp[1] then + return at(1) + end + if t >= inp[n] then + return at(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = math.floor((lo + hi) / 2 +) if inp[mid] <= t then + lo = mid + else + hi = mid + end + end + local a, b = at(lo), at(hi) + if c.interp[lo] == "STEP" then + return a + end + local span = inp[hi] - inp[lo] + local f = (span > 0 and(((t - inp[lo]) / span ))or(0 +)) for k = 1, st do + a[k]=a[k]+ (b[k] - a[k]) * f + end + return a +end + +-- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +local function target(C, s) -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + +local id, sids = match(s, "^([^/]*)/(.*)$") + if not id then + return nil, nil, nil + end + local spath, rest = match(sids , "^([^%.%(]*)(.*)$") + if not spath then + return nil, nil, nil + end + local parts = string.split(id .. "/" .. spath, "/") + local nodes = C.nodeOf[parts[1] ] + if not nodes or #parts < 2 then + return nil, nil, nil + end + local sid = parts[#parts] + local info = C.info[nodes[1] ] + local xf= nil + for _, x in __iter(info.xf) do + if x.sid == sid then + xf = x + break + end + end + if not xf then + return nil, nil, nil + end + local member= nil + if rest and rest ~= "" then + local m1 = match(rest, "^%.(.+)$") + if m1 then + member = MEMBER[upper(m1)] + if not member then + return nil, nil, nil + end + else + local i, j = match(rest, "^%((%d+)%)%((%d+)%)$") + if i then + member = (tonumber(i) )* 4 + (tonumber(j) )+ 1 + else + local k = match(rest, "^%((%d+)%)$") + if not k then + return nil, nil, nil + end + member = (tonumber(k) )+ 1 + end + end + end + return nodes, xf, member +end + +-- the channels of one <animation> (recursively) -> curves grouped by node +local function collect(C, anim, byNode, order, depth) + if depth > 64 then + return + end + for _, ch in __iter(children(anim, "channel")) do + local smp = C.ids[urlId(attr(ch, "source")) or ""] + local nodes, xf, member = target(C, attr(ch, "target") or "") + if smp and lname(smp) == "sampler" and nodes and xf then + local input, output, interp= nil, nil, nil + for _, inp in __iter(children(smp, "input")) do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if sem == "INPUT" then + input = src + elseif sem == "OUTPUT" then + output = src + elseif sem == "INTERPOLATION" then + interp = src + end + end + if input and output and input.count > 0 then + local stride = member and 1 or#xf.values + local ins = {} + for i = 1, input.count do + local x = input.data[(i - 1) * input.comps + 1] + ins[i] = (type(x) == "number" and{x }or{0 +})[1] end + local outs = output.data + if #outs >= input.count * stride then + local ip = {} + if interp then + for i = 1, input.count do + ip[i] = upper(tostring(interp.data[i] or "LINEAR")) + end + end + local curve= { input = ins, output = outs, stride = stride, interp = ip, member = member, xf = xf } + for _, ni in __iter(nodes) do + if not byNode[ni] then + byNode[ni] = {} + table.insert(order, ni) + end + table.insert(byNode[ni], curve) + end + end + end + elseif not (nodes and xf) then + skip(C, "animation channels on other targets") + end + end + for _, sub2 in __iter(children(anim, "animation")) do + collect(C, sub2, byNode, order, depth + 1) + end +end + +local function bake(C, name, byNode, order) +local channels= {} + for _, ni in __iter(order) do + local curves = byNode[ni] + local info = C.info[ni] + -- the union of the key times, plus subdivisions of rotations over 90 degrees + local set= {} + local times= {} + local function add(t) + if not set[t] then + set[t] = true + table.insert(times, t) + end + end + for _, c in __iter(curves) do + for i, t in __iter(c.input) do + add(t) + if i > 1 and c.xf.kind == "rotate" and (c.member == 4 or c.member == nil) then + local k = c.member and 1 or 4 + local a, b = c.output[(i - 2) * c.stride + k] or 0, c.output[(i - 1) * c.stride + k] or 0 + local steps = math.min(math.ceil(math.abs(b - a) / 90), 64) + for s = 1, steps - 1 do + add(c.input[i - 1] + (t - c.input[i - 1]) * s / steps) + end + end + end + if #times > C.limit then + return nil + end + end + table.sort(times) + local n = #times + local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) + local prev= nil + for i, t in __iter(times) do + -- this time's values of each animated element + local xf = {} + for k, x in __iter(info.xf) do + xf[k] = { kind = x.kind, values = table.clone(x.values) } + end + for _, c in __iter(curves) do + local v = sample(c, t) + local k = table.find(info.xf, c.xf) + if k then + local vals = xf[k].values + if c.member then + vals[c.member] = v[1] or 0 + else + for j = 1, #v do + vals[j] = v[j] + end + end + end + end + local tr, ro, sc = Mat4.decomposeStrict(compose(xf)) + tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 } + if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then + ro = { -ro[1], -ro[2], -ro[3], -ro[4] } + end + prev = ro + for k = 1, 3 do + buffer.writef32(tb, ((i - 1) * 3 + k - 1) * 4, tr[k]) + buffer.writef32(sb, ((i - 1) * 3 + k - 1) * 4, sc[k]) + end + for k = 1, 4 do + buffer.writef32(rb, ((i - 1) * 4 + k - 1) * 4, ro[k]) + end + end + local ib = buffer.create(n * 4) + for i, t in __iter(times) do + buffer.writef32(ib, (i - 1) * 4, t) + end + local input = Scene.accessor(ib, "f32", 1, n) + table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } ) + table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } ) + table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } ) + -- the node is now TRS-driven + local node = C.scene.nodes[ni] + if node.matrix then + setTransform(node, node.matrix) + end + end + if #channels == 0 then + return nil + end + return { name = name, channels = channels } +end + +local function animations(C, root) + local libs = children(root, "library_animations") + if #libs == 0 then + return + end + local clipsLib = child(root, "library_animation_clips") + local clips = clipsLib and children(clipsLib, "animation_clip") or {} + if #clips > 0 then + for _, clip in __iter(clips) do + local byNode, order = {}, {} + for _, ia in __iter(children(clip, "instance_animation")) do + local a = C.ids[urlId(attr(ia, "url")) or ""] + if a and lname(a) == "animation" then + collect(C, a, byNode, order, 0) + end + end + local anim = bake(C, attr(clip, "name") or attr(clip, "id"), byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end + end + return + end + local byNode, order = {}, {} + local name= nil + local count = 0 + for _, lib in __iter(libs) do + for _, a in __iter(children(lib, "animation")) do + collect(C, a, byNode, order, 0) + count =count+ 1 + name = name or attr(a, "name") or attr(a, "id") + end + end + local anim = bake(C, (count == 1 and{name }or{nil})[1], byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(doc, fetch, opts) +local root = doc and doc.root + if not root or lname(root) ~= "COLLADA" then + return nil, Err.new(Err.CORRUPT, "no <COLLADA> root element") + end + local scene = Scene.new() + local C= { + doc = doc, + ids = {}, + fetch = fetch, + scene = scene, + limit = opts and opts.maxVertices or 2 ^ 25, + vertices = 0, + flipV = not (opts and opts.flipV == false), + triangulate = not (opts and opts.triangulate == false), + sources = {}, + materials = {}, + textures = {}, + images = {}, + meshes = {}, + skins = {}, + posIndex = {}, + nodeOf = {}, + info = {}, + pendingSkins = {}, + skipped = {}, + err = nil, + depth = 0, + } + for _, el in __iter(Xml.descendants(root)) do + local id = el.attrs.id + -- duplicate ids: the first one, unless it is empty (some exporters write <light id="x"/> before the real one) + if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then + C.ids[id] = el + end + end + -- asset: up axis, unit + local asset = child(root, "asset") + local up = asset and child(asset, "up_axis") + local upAxis = (up and{(upper(match(text(up), "[%w_]+") or "Y_UP") )}or{"Y_UP" +})[1] scene.meta.up = upAxis == "Z_UP" and"z" or(upAxis == "X_UP" and"x" or"y" ) +local unit = asset and child(asset, "unit") + local meter = unit and attr(unit, "meter") + scene.meta.unit = (meter and{tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 }or{1 +})[1] -- the instanced visual scene (else the first one) + local vsId= nil + local sceneEl = child(root, "scene") + local ivs = sceneEl and child(sceneEl, "instance_visual_scene") + if ivs then + vsId = urlId(attr(ivs, "url")) + end + local vs = vsId and C.ids[vsId] + if not vs or lname(vs) ~= "visual_scene" then + local lib = child(root, "library_visual_scenes") + vs = lib and child(lib, "visual_scene") + end + if vs then + for _, n in __iter(children(vs, "node")) do + local idx = visitNode(C, n) + if C.err then + break + end + if idx then + table.insert(scene.roots, idx) + end + end + end + if C.err then + return nil, Err.new((find(C.err , "limit", 1, true) and{Err.LIMIT }or{Err.CORRUPT})[1], C.err ) + end + resolveSkins(C) + animations(C, root) + if C.err then + return nil, Err.new(Err.CORRUPT, C.err ) + end + local contributor = asset and child(asset, "contributor") + local tool = contributor and child(contributor, "authoring_tool") + scene.meta.source = { + format = "dae", + version = attr(root, "version"), + upAxis = upAxis, + authoringTool = (tool and{(text(tool) )}or{nil})[1], + skipped = (next(C.skipped) and{C.skipped }or{nil})[1], + } + return scene, nil +end + +return Read +end +__FILES["model/dae/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/dae/Write: Scene -> Collada 1.4.1 text. One <geometry> per mesh primitive (triangles, lines or polylist; strips +-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n +-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its +-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major <matrix>; cameras; +-- lights. Not written: skins, morph targets, animations. +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Base64 = __include("core/Base64") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + +local Scene = Types.Scene +local format, concat = string.format, table.concat +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" } + +local function f(v) +if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e15 then + return format("%d", v) + end + return format("%.9g", v) +end +local function list(v) +local out = table.create(#v) + for i, x in __iter(v) do + out[i] = f(x) + end + return concat(out, " ") +end +local function esc(s) +return Xml.escapeAttr(s) +end +local function nameAttr(s) +return (s and((' name="' .. esc(s) .. '"' ))or("" +))end + +-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind +local function corners(prim) +local n = prim.attributes.POSITION.count + local idx= {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil, nil, nil + end + for i = 0, prim.indices.count - 1 do + idx[i + 1] = get(i, 0) + end + else + for i = 0, n - 1 do + idx[i + 1] = i + end + end + for _, i in __iter(idx) do + if i < 0 or i >= n then + return nil, nil, nil + end + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + local m = #idx - #idx % 3 + return table.move(idx, 1, m, 1, {}), "triangles", nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local out = {} + for k = 1, #idx - 2 do + if mode == "triangle_fan" then + table.insert(out, idx[1]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + elseif k % 2 == 1 then + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + else + table.insert(out, idx[k + 1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 2]) + end + end + return out, "triangles", nil + elseif mode == "lines" then + local m = #idx - #idx % 2 + return table.move(idx, 1, m, 1, {}), "lines", nil + elseif mode == "line_strip" or mode == "line_loop" then + local out = {} + for k = 1, #idx - 1 do + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + if mode == "line_loop" and #idx > 2 then + table.insert(out, idx[#idx]) + table.insert(out, idx[1]) + end + return out, "lines", nil + elseif mode == "polygons" and prim.faces then + local get = Scene.reader(prim.faces) + if not get then + return nil, nil, nil + end + local sizes = {} + local total = 0 + for i = 0, prim.faces.count - 1 do + sizes[i + 1] = get(i, 0) + total =total+ sizes[i + 1] + end + if total ~= #idx then + return nil, nil, nil + end + return idx, "polylist", sizes + end + return nil, nil, nil +end + +local function source(out, id, acc, comps, params, flipV) + local get = Scene.reader(acc) + if not get then + return + end + local vals = table.create(acc.count * comps) + local n = 0 + for i = 0, acc.count - 1 do + for c = 0, comps - 1 do + n =n+ 1 + local v = (c < acc.components and{(get(i, c) )}or{(c == 3 and 1 or 0) +})[1] if flipV and c == 1 then + v = 1 - v + end + vals[n] = f(v) + end + end + table.insert(out, format('<source id="%s"><float_array id="%s-array" count="%d">%s</float_array>', id, id, n, concat(vals, " "))) + local ps = {} + for c = 1, comps do + ps[c] = format('<param name="%s" type="float"/>', params[c] or "V") + end + table.insert(out, format('<technique_common><accessor source="#%s-array" count="%d" stride="%d">%s</accessor></technique_common></source>\n', id, acc.count, comps, concat(ps))) +end + +local function colorEl(tag, c, tex, uv) +if tex then + return format('<%s><texture texture="%s" texcoord="UVSET%d"/></%s>', tag, tex, uv or 0, tag) + end + local v = c or { 0, 0, 0, 1 } + return format("<%s><color>%s %s %s %s</color></%s>", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag) +end + +function Write.build(scene, opts) +local files = opts and type(opts.files) == "table" and opts.files or nil + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local flipV = not (opts and opts.flipV == false) + local out= {} + local function w(s) + table.insert(out, s) + end + w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n') + local meta= scene.meta or {} + local up = meta.up == "z" and"Z_UP" or(meta.up == "x" and"X_UP" or"Y_UP" +) w(format('<asset><contributor><authoring_tool>rosetta</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up)) + -- images + local imageId= {} + if #scene.textures > 0 then + w("<library_images>\n") + for i, tex in __iter(scene.textures) do + local uri= nil + if tex.data then + if files then + uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + files[uri ] = tex.data + else + uri = Base64.dataUri(tex.data, tex.mime or "image/png") + end + elseif tex.uri then + uri = tex.uri + end + if uri then + local id = "image" .. i + imageId[i] = id + w(format('<image id="%s"%s><init_from>%s</init_from></image>\n', id, nameAttr(tex.name), Xml.escape(uri ))) + end + end + w("</library_images>\n") + end + -- effects + materials + if #scene.materials > 0 then + w("<library_effects>\n") + for i, mat in __iter(scene.materials) do + local ph= mat.extras and mat.extras.phong or {} + local params= {} -- the newparam strings, and their sids as seen-keys + local function texParam(ref) +if not ref or not imageId[ref.texture] then + return nil, nil + end + local sid = "tex" .. ref.texture + if not params[sid] then + params[sid] = true + table.insert(params, format('<newparam sid="%s-surface"><surface type="2D"><init_from>%s</init_from></surface></newparam><newparam sid="%s"><sampler2D><source>%s-surface</source></sampler2D></newparam>', sid, imageId[ref.texture], sid, sid)) + end + return sid, ref.texCoord + end + local dtex, duv = texParam(mat.baseColorTexture) + local etex, euv = texParam(mat.emissiveTexture) + local ntex, nuv = texParam(mat.normalTexture) + local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil + local model = unlit and"constant" or(ph.model == "lambert" and"lambert" or"phong" +) local body = {} + local bc = mat.baseColor + if unlit then + table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil)) + else + table.insert(body, colorEl("emission", (type(ph.emission) == "table" and{ph.emission }or{{ mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }})[1], etex, euv)) + table.insert(body, colorEl("ambient", (type(ph.ambient) == "table" and{ph.ambient }or{{ 0, 0, 0, 1 }})[1], nil, nil)) + table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv)) + if model == "phong" then + table.insert(body, colorEl("specular", (type(ph.specular) == "table" and{ph.specular }or{{ 0, 0, 0, 1 }})[1], nil, nil)) + local sh = (type(ph.shininess) == "number" and{ph.shininess }or{(math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0) +)})[1] table.insert(body, format("<shininess><float>%s</float></shininess>", f(sh))) + end + end + if (bc[4] or 1) < 1 then + table.insert(body, '<transparent opaque="A_ONE"><color>1 1 1 1</color></transparent>') + table.insert(body, format("<transparency><float>%s</float></transparency>", f(bc[4]))) + end + local extra = "" + if ntex or mat.doubleSided then + extra = "<extra><technique profile=\"FCOLLADA\">" .. ((ntex and{(format('<bump><texture texture="%s" texcoord="UVSET%d"/></bump>', ntex, nuv or 0) )}or{""})[1]) .. (mat.doubleSided and"<double_sided>1</double_sided>" or"") .. "</technique></extra>" + end + w(format('<effect id="effect%d"><profile_COMMON>%s<technique sid="common"><%s>%s</%s>%s</technique></profile_COMMON></effect>\n', i, concat(params), model, concat(body), model, extra)) + end + w("</library_effects>\n<library_materials>\n") + for i, mat in __iter(scene.materials) do + w(format('<material id="material%d"%s><instance_effect url="#effect%d"/></material>\n', i, nameAttr(mat.name), i)) + end + w("</library_materials>\n") + end + -- geometries: one per primitive + local geoms= {} + w("<library_geometries>\n") + for mi, mesh in __iter(scene.meshes) do + geoms[mi] = {} + for pi, prim in __iter(mesh.primitives) do +local __DARKLUA_CONTINUE_15=false repeat local pos = prim.attributes and prim.attributes.POSITION + if not pos then +__DARKLUA_CONTINUE_15=true break + end + local idx, kind, sizes = corners(prim) + if not idx or not kind or #idx == 0 then +__DARKLUA_CONTINUE_15=true break + end + local id = format("mesh%d-%d", mi, pi) + w(format('<geometry id="%s"%s><mesh>\n', id, nameAttr(mesh.name))) + source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false) + local ins = { format('<input semantic="VERTEX" source="#%s-vertices" offset="0"/>', id) } + if prim.attributes.NORMAL then + source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false) + table.insert(ins, format('<input semantic="NORMAL" source="#%s-normals" offset="0"/>', id)) + end + local sets = 0 + for k = 0, 7 do + local a = prim.attributes["TEXCOORD_" .. k] + if not a then + break + end + source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV) + table.insert(ins, format('<input semantic="TEXCOORD" source="#%s-uv%d" offset="0" set="%d"/>', id, k, k)) + sets =sets+ 1 + end + for k = 0, 7 do + local a = prim.attributes["COLOR_" .. k] + if not a then + break + end + local c = a.components >= 4 and 4 or 3 + source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false) + table.insert(ins, format('<input semantic="COLOR" source="#%s-color%d" offset="0" set="%d"/>', id, k, k)) + end + w(format('<vertices id="%s-vertices"><input semantic="POSITION" source="#%s-positions"/></vertices>\n', id, id)) + local matAttr = (prim.material and scene.materials[prim.material] and{(format(' material="m%d"', prim.material) )}or{"" +})[1] local count = (kind == "triangles" and{(math.floor(#idx / 3 ))}or{(kind == "lines" and{(math.floor(#idx / 2 ))}or{(#(sizes ) +)})[1]})[1] w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins))) + if sizes then + w("<vcount>" .. list(sizes) .. "</vcount>") + end + w("<p>" .. list(idx) .. "</p></" .. kind .. ">\n</mesh></geometry>\n") + table.insert(geoms[mi], { id = id, material = (matAttr ~= "" and{prim.material }or{nil})[1], sets = sets }) +__DARKLUA_CONTINUE_15=true until true if not __DARKLUA_CONTINUE_15 then break end end + end + w("</library_geometries>\n") + -- cameras / lights + if #scene.cameras > 0 then + w("<library_cameras>\n") + for i, cam in __iter(scene.cameras) do + local body +if cam.type == "orthographic" then + body = format("<orthographic><xmag>%s</xmag><ymag>%s</ymag><znear>%s</znear><zfar>%s</zfar></orthographic>", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000)) + else + body = format("<perspective><yfov>%s</yfov>%s<znear>%s</znear><zfar>%s</zfar></perspective>", f(math.deg(cam.yfov or 0.8)), (cam.aspect and{(format("<aspect_ratio>%s</aspect_ratio>", f(cam.aspect)) )}or{""})[1], f(cam.znear or 0.1), f(cam.zfar or 1000)) + end + w(format('<camera id="camera%d"%s><optics><technique_common>%s</technique_common></optics></camera>\n', i, nameAttr(cam.name), body)) + end + w("</library_cameras>\n") + end + if #scene.lights > 0 then + w("<library_lights>\n") + for i, l in __iter(scene.lights) do + local c = l.color or { 1, 1, 1 } + local k = l.intensity or 1 + local col = format("<color>%s %s %s</color>", f(c[1] * k), f(c[2] * k), f(c[3] * k)) + local body = (l.type == "spot" and{(format("<spot>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation><falloff_angle>%s</falloff_angle><falloff_exponent>0</falloff_exponent></spot>", col, f(math.deg(l.outerCone or math.pi / 4) * 2)) +)}or{(l.type == "point" and{(format("<point>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation></point>", col) +)}or{(format("<directional>%s</directional>", col) +)})[1]})[1] w(format('<light id="light%d"%s><technique_common>%s</technique_common></light>\n', i, nameAttr(l.name), body)) + end + w("</library_lights>\n") + end + -- the node tree + w('<library_visual_scenes><visual_scene id="scene" name="scene">\n') + local seen= {} + local function node(i, depth) + local n = scene.nodes[i] + if not n or seen[i] or depth > 512 then + return + end + seen[i] = true + w(format('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', i, nameAttr(n.name), list(Mat4.toRows(Scene.nodeMatrix(n))))) + if n.mesh and geoms[n.mesh] then + for _, g in __iter(geoms[n.mesh]) do + if g.material then + local binds = {} + for k = 0, g.sets - 1 do + table.insert(binds, format('<bind_vertex_input semantic="UVSET%d" input_semantic="TEXCOORD" input_set="%d"/>', k, k)) + end + w(format('<instance_geometry url="#%s"><bind_material><technique_common><instance_material symbol="m%d" target="#material%d">%s</instance_material></technique_common></bind_material></instance_geometry>', g.id, g.material, g.material, concat(binds))) + else + w(format('<instance_geometry url="#%s"/>', g.id)) + end + end + end + if n.camera and scene.cameras[n.camera] then + w(format('<instance_camera url="#camera%d"/>', n.camera)) + end + if n.light and scene.lights[n.light] then + w(format('<instance_light url="#light%d"/>', n.light)) + end + w("\n") + for _, c in __iter(n.children or {}) do + node(c, depth + 1) + end + w("</node>\n") + end + local roots = scene.roots + if not roots or #roots == 0 then + local isChild = {} + for _, n in __iter(scene.nodes) do + for _, c in __iter(n.children or {}) do + isChild[c] = true + end + end + roots = {} + for i in __iter(scene.nodes) do + if not isChild[i] then + table.insert(roots, i) + end + end + end + for _, r in __iter(roots) do + node(r, 0) + end + w('</visual_scene></library_visual_scenes>\n<scene><instance_visual_scene url="#scene"/></scene>\n</COLLADA>\n') + return concat(out) +end + +return Write +end +__FILES["model/fbx"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays +-- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and +-- assimp's FBX importer, and the FBX SDK's documentation of the transform model. +-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl +-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms +-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, +-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference +-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR +-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins +-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets +-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and +-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for +-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). +-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives +-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), +-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + +-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler +-- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). +-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered +-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/fbx/Binary") +local Ascii = __include("model/fbx/Ascii") +local Read = __include("model/fbx/Read") +local Write = __include("model/fbx/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Fbx = { + name = "fbx", + category = "model", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + 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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + + +local MAGIC = Binary.MAGIC + +-- ------------------------------------------------------------------------------------------------ sniff +function Fbx.sniff(r) +if r:peek(21) == MAGIC then + return 1 + end + local head = r:peek(2048) + if string.find(head, "FBXHeaderExtension:", 1, true) then + return 0.95 + end + if string.find(head, "^; FBX %d") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts) +return function(uri) +if not opts then + return nil + end + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1] end +end + +local toErr = Err.from + +-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. +-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. +function Fbx.tree(r, opts) +if r:peek(21) == MAGIC then + local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) + if not root then + return nil, toErr(version, off) + end + return root, version, true + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local root, version, off = Ascii.parse(text, opts) + if not root then + return nil, toErr(version, off and r.base + off) + end + if type(version) ~= "number" then + return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion") + end + if version < 7000 then + return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)") + end + return root, version, false +end + +function Fbx.decode(r, opts) +local root, version, binary = Fbx.tree(r, opts) + if not root then + return nil, version + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) + end + if not scene then + return nil, err + end + (scene.meta.source ).binary = binary + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Fbx.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local version = opts and opts.version or 7400 + if version ~= 7400 and version ~= 7500 then + return nil, Err.new(Err.ARG, "version must be 7400 or 7500") + end + local ok, root, err = pcall(Write.tree, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root)) + end + if not root then + return nil, err + end + if opts and opts.ascii then + return buffer.fromstring(Ascii.write(root, version)), nil + end + return Binary.write(root, version, not (opts and opts.compress == false)), nil +end + +return Fbx +end +__FILES["model/fbx/Ascii"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' +-- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary +-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +local Base64 = __include("core/Base64") + +local Ascii = {} + + + +local sbyte, sfind, ssub = string.byte, string.find, string.sub +local MAX_DEPTH = 128 + +local function isNameStart(c) +return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end + +-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset +function Ascii.parse(text, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local n = #text + local i = 1 + local total = 0 + + local function skip() + while i <= n do + local c = sbyte(text, i) + if c == 59 then -- ; comment + local e = sfind(text, "\n", i, true) + i = (e and((e + 1 ))or((n + 1 +))) elseif c == 32 or c == 9 or c == 10 or c == 13 then + i =i+ 1 + else + return + end + end + end + + -- at i: a name followed by ':'? -> name, the index after ':' + local function nameAt() +local c = sbyte(text, i) + if not c or not isNameStart(c) then + return nil, i + end + local s, e = sfind(text, "^[%w_|%-]+", i) + if not s then + return nil, i + end + local j = (e ) + 1 + while j <= n do + local d = sbyte(text, j) + if d == 32 or d == 9 then + j =j+ 1 + else + break + end + end + if sbyte(text, j) == 58 then + return ssub(text, i, e ), j + 1 + end + return nil, i + end + + -- the values of one node (after the ':'), up to a new name, '{' or '}' + local function values() +local props= {} + while true do + skip() + if i > n then + return props, nil + end + local c = sbyte(text, i) + if c == 44 then -- , + i =i+ 1 + elseif c == 123 or c == 125 then + return props, nil + elseif c == 34 then -- " + local e = sfind(text, "\"", i + 1, true) + if not e then + return nil, "unterminated string" + end + local s = ssub(text, i + 1, e - 1) + if sfind(s, "&", 1, true) then + s = string.gsub(s, """, "\"") + end + table.insert(props, s) + i = e + 1 + elseif c == 42 then -- *N + local s, e = sfind(text, "^%*%d+", i) + if not s then + return nil, "bad array length" + end + table.insert(props, { star = tonumber(ssub(text, i + 1, e )) }) + i = (e ) + 1 + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + local s, e = sfind(text, "^[-+%deE.]+", i) + local tok = ssub(text, i, e ) + local v = tonumber(tok) + if v == nil then + -- "1.#INF", "-1.#IND", "nan": special floats + local s2, e2 = sfind(text, "^[-+%w.#]+", i) + tok = ssub(text, i, e2 ) + local low = string.lower(tok) + if sfind(low, "inf", 1, true) then + v = (sbyte(tok, 1) == 45 and{(-math.huge )}or{math.huge +})[1] else + v = 0 / 0 + end + e = e2 + local _ = s2 + elseif #tok > 15 and not sfind(tok, "[.eE]") then + v = (sbyte(tok, 1) == 45 and"L-" or"L") .. (string.gsub(tok, "^[-+]", "") ) +end + local _ = s + table.insert(props, v) + i = (e ) + 1 + else + local nm = nameAt() + if nm then + return props, nil + end + local s, e = sfind(text, "^[%w_]+", i) + if not s then + return nil, string.format("unexpected character %q", ssub(text, i, i)) + end + table.insert(props, ssub(text, i, e )) + i = (e ) + 1 + end + end + end + + local function nodes(depth, into) +while true do + skip() + if i > n then + return depth > 0 and"unterminated {" or nil + end + if sbyte(text, i) == 125 then + if depth == 0 then + return "unbalanced }" + end + i =i+ 1 + return nil + end + local name, j = nameAt() + if not name then + return string.format("expected a node name at %q", ssub(text, i, i + 10)) + end + i = j + local props, err = values() + if not props then + return err + end + local node= { name = name, props = props, children = {} } + skip() + if sbyte(text, i) == 123 then + if depth >= MAX_DEPTH then + return "nodes nested too deep" + end + i =i+ 1 + local e = nodes(depth + 1, node.children) + if e then + return e + end + end + -- "*N { a: v, v, ... }" -> an Array + local p1 = props[1] + if #props == 1 and type(p1) == "table" and p1.star then + local a = node.children[1] + local count = (a and a.name == "a" and((#a.props ))or(0 +)) total =total+ count * 8 + if total > maxBytes then + return "limit:arrays over " .. maxBytes .. " bytes" + end + local data = buffer.create(count * 8) + for k = 1, count do + local v = (a ).props[k] + buffer.writef64(data, (k - 1) * 8, (type(v) == "number" and{v }or{(tonumber(v) or 0)})[1]) + end + node.props = { { array = true, type = "d", count = count, data = data } } + node.children = {} + end + table.insert(into, node) + end + end + + local root= { name = "", props = {}, children = {} } + local err = nodes(0, root.children) + if err then + return nil, err, i - 1 + end + local version = nil + for _, c in __iter(root.children) do + if c.name == "FBXHeaderExtension" then + for _, d in __iter(c.children) do + if d.name == "FBXVersion" then + version = d.props[1] + end + end + end + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +local function fmt(v) +if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + if v ~= v then + return "0" + end + return string.format("%.17g", v) +end + +-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) +function Ascii.write(root, version) +local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", math.floor((version or 7400) / 1000), math.floor((version or 7400) % 1000 / 100)) } + local function node(nd, indent) + local parts = {} + local arr = nil + for _, v in __iter(nd.props) do + local tv = type(v) + if tv == "number" then + table.insert(parts, fmt(v)) + elseif tv == "boolean" then + table.insert(parts, v and"T" or"F") + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then + table.insert(parts, string.sub(v, 2)) + else + local nm, cls = string.match(v, "^(.-)%z\1(.*)$") + local sv = (nm and(((cls ) .. "::" .. nm ))or(v +)) table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"") + end + elseif tv == "table" and v.array then + arr = v + elseif tv == "buffer" then + -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + local b64 = Base64.encode(v) + local chunks = {} + for k = 1, #b64, 2048 do + table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"") + end + table.insert(parts, (#chunks > 0 and{(table.concat(chunks, ",\n") )}or{"\"\""})[1]) + end + end + if arr then + local vals = (table.create(arr.count) ) +for k = 0, arr.count - 1 do + vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8)) + end + table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent)) + return + end + table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", ")) + local ch = nd.children + if ch and #ch > 0 then + table.insert(out, " {\n") + for _, c in __iter(ch) do + node(c, indent .. "\t") + end + table.insert(out, indent .. "}\n") + else + table.insert(out, "\n") + end + end + for _, c in __iter(root.children) do + node(c, "") + end + return table.concat(out) +end + +return Ascii +end +__FILES["model/fbx/Binary"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +--!native +-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit +-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's +-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array +-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become +-- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset). +local Deflate = __include("codecs/compress/Deflate") + +local Binary = {} + + + + +local MAGIC = "Kaydara FBX Binary \0" +Binary.MAGIC = MAGIC +local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126" +local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11" +local MAX_DEPTH = 128 + +local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 +local writef64 = buffer.writef64 + +-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +local function i64(b, p, asString) +local lo, hi = readu32(b, p), readu32(b, p + 4) + if hi >= 0x80000000 then + local v = (hi - 4294967296) * 4294967296 + lo + if v >= -9007199254740991 or not asString then + return v + end + else + if hi < 0x200000 or not asString then + return hi * 4294967296 + lo + end + end + return string.format("L%08x%08x", hi, lo) +end +Binary.i64 = i64 + +local ELEM= { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } + +-- the elements of a raw array (n elements of type t at p) as f64s +local function toF64(t, src, p, n) +local out = buffer.create(n * 8) + if t == "d" then + buffer.copy(out, 0, src, p, n * 8) + elseif t == "f" then + for k = 0, n - 1 do + writef64(out, k * 8, readf32(src, p + k * 4)) + end + elseif t == "i" then + for k = 0, n - 1 do + writef64(out, k * 8, readi32(src, p + k * 4)) + end + elseif t == "l" then + for k = 0, n - 1 do + local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4) + writef64(out, k * 8, (hi >= 0x80000000 and(((hi - 4294967296) * 4294967296 + lo ))or((hi * 4294967296 + lo)))) + end + else + for k = 0, n - 1 do + writef64(out, k * 8, readu8(src, p + k)) + end + end + return out +end + +-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset +function Binary.parse(b, base, limit, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then + return nil, "not a binary FBX", base + end + local version = readu32(b, base + 23) + if version < 7000 or version >= 10000 then + return nil, "unsupported:FBX version " .. version, base + 23 + end + local wide = version >= 7500 + local head = wide and 25 or 13 + local total = 0 + + local function props(p, n, stop) +local out = table.create(math.min(n, 64)) + for k = 1, n do + if p >= stop then + return nil, "property list runs past its record" + end + local c = readu8(b, p) + p =p+ 1 + local v +if c == 89 then -- Y + if p + 2 > stop then return nil, "truncated property" end + v = readi16(b, p) + p =p+ 2 + elseif c == 67 then -- C + if p + 1 > stop then return nil, "truncated property" end + v = readu8(b, p) ~= 0 + p =p+ 1 + elseif c == 73 then -- I + if p + 4 > stop then return nil, "truncated property" end + v = readi32(b, p) + p =p+ 4 + elseif c == 70 then -- F + if p + 4 > stop then return nil, "truncated property" end + v = readf32(b, p) + p =p+ 4 + elseif c == 68 then -- D + if p + 8 > stop then return nil, "truncated property" end + v = readf64(b, p) + p =p+ 8 + elseif c == 76 then -- L + if p + 8 > stop then return nil, "truncated property" end + v = i64(b, p, true) + p =p+ 8 + elseif c == 83 or c == 82 then -- S, R + if p + 4 > stop then return nil, "truncated property" end + local len = readu32(b, p) + p =p+ 4 + if len > stop - p then return nil, "string runs past its record" end + if c == 83 then + v = buffer.readstring(b, p, len) + else + local raw = buffer.create(len) + buffer.copy(raw, 0, b, p, len) + v = raw + end + p =p+ len + elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c + if p + 12 > stop then return nil, "truncated array header" end + local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8) + p =p+ 12 + local t = string.char(c) + local es = ELEM[t] + if clen > stop - p then return nil, "array runs past its record" end + total =total+ count * 8 + if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end + local data +if enc == 0 then + if clen < count * es then return nil, "raw array shorter than its count" end + data = toF64(t, b, p, count) + elseif enc == 1 then + local raw, err = Deflate.zlib(b, p, clen, count * es) + if not raw then + return nil, "array: " .. tostring((type(err) == "table" and{err.message }or{err})[1]) + end + data = toF64(t, raw, 0, count) + else + return nil, "unknown array encoding " .. enc + end + p =p+ clen + v = { array = true, type = t, count = count, data = data } + else + return nil, string.format("unknown property type 0x%02x", c) + end + out[k] = v + end + return out, p + end + + -- one node record at p: node | false (the null record), next offset | nil, message, offset + local function node(p, stop, depth) +if p + head > stop then + return nil, "truncated node record", p + end + local endOff, nprops, plen, nlen + if wide then + endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296 + nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296 + plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296 + nlen = readu8(b, p + 24) + else + endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), (readu8(b, p + 12)) + end + if endOff == 0 then + return false, p + head + end + local e = base + endOff + if e > stop or e < p + head + nlen + plen then + return nil, "node end offset out of range", p + end + if nprops > plen then + return nil, "more properties than bytes", p + end + local q = p + head + local name = buffer.readstring(b, q, nlen) + q =q+ nlen + local pl, nq = props(q, nprops, q + plen) + if not pl then + return nil, nq, q + end + q =q+ plen + local children= {} + if q < e then + if depth >= MAX_DEPTH then + return nil, "nodes nested too deep", p + end + while q < e do + local child, nx, off = node(q, e, depth + 1) + if child == nil then + return nil, nx, off + end + q = nx + if child == false then + break + end + table.insert(children, child) + end + end + return { name = name, props = pl, children = children }, e + end + + local root= { name = "", props = {}, children = {} } + local p = base + 27 + while p < limit do + local n, nx, off = node(p, limit, 0) + if n == nil then + if #root.children > 0 and p + head > limit then + break -- a file cut right after its last node: keep what was read + end + return nil, nx, off + end + if n == false then + break + end + table.insert(root.children, n) + p = nx + end + return root, version, nil +end +-- ------------------------------------------------------------------------------------------------ writer +-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit +-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint +-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their +-- type (compressed with zlib when longer than 32 elements, unless compress = false). + + + +local function sizeHint(n) +local s = 32 + #n.name + for _, v in __iter(n.props) do + if type(v) == "string" then + s =s+ (5 + #v +) elseif type(v) == "buffer" then + s =s+ (5 + buffer.len(v) +) elseif type(v) == "table" then + s =s+ (13 + (v.count or 0) * 8 +) else + s =s+ 9 + end + end + for _, c in __iter(n.children or {}) do + s =s+ sizeHint(c) + end + return s +end + +function Binary.write(root, version, compress) +local zip = compress ~= false + local ver = version or 7400 + local wide = ver >= 7500 + local head = wide and 25 or 13 + local cap = sizeHint(root) + 256 + local out = buffer.create(cap) + local pos = 0 + local function ensure(n) + if pos + n > cap then + while pos + n > cap do + cap =cap* 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, out, 0, pos) + out = nb + end + end + local function u8(v) + ensure(1) + buffer.writeu8(out, pos, v) + pos =pos+ 1 + end + local function u32(v) + ensure(4) + buffer.writeu32(out, pos, v) + pos =pos+ 4 + end + local function i64w(v) + ensure(8) + local hi = math.floor(v / 4294967296) + local lo = v - hi * 4294967296 + buffer.writeu32(out, pos, lo) + buffer.writeu32(out, pos + 4, hi % 4294967296) + pos =pos+ 8 + end + local function str(s) + ensure(#s) + buffer.writestring(out, pos, s) + pos =pos+ #s + end + local function bytes(src) + local n = buffer.len(src) + ensure(n) + buffer.copy(out, pos, src, 0, n) + pos =pos+ n + end + local function array(a) + local t, n, d = a.type, a.count, a.data + local es = ELEM[t] or 8 + local raw = buffer.create(n * es) + if a.raw then + buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es)) + else + for k = 0, n - 1 do + local v = readf64(d, k * 8) + if t == "d" then + writef64(raw, k * 8, v) + elseif t == "f" then + buffer.writef32(raw, k * 4, v) + elseif t == "i" then + buffer.writei32(raw, k * 4, v) + elseif t == "b" then + buffer.writeu8(raw, k, v ~= 0 and 1 or 0) + else + local hi = math.floor(v / 4294967296) + buffer.writeu32(raw, k * 8, v - hi * 4294967296) + buffer.writeu32(raw, k * 8 + 4, hi % 4294967296) + end + end + end + u8(string.byte(t)) + u32(n) + if zip and n > 32 then + local z = Deflate.zlibCompress(raw, { level = 6 }) + if z then + u32(1) + u32(buffer.len(z)) + bytes(z) + return + end + end + u32(0) + u32(n * es) + bytes(raw) + end + local function setOff(at, v) + if wide then + buffer.writeu32(out, at, v % 4294967296) + buffer.writeu32(out, at + 4, math.floor(v / 4294967296)) + else + buffer.writeu32(out, at, v) + end + end + local function nullRecord() + ensure(head) + buffer.fill(out, pos, 0, head) + pos =pos+ head + end + local function node(n) + local start = pos + ensure(head) + buffer.fill(out, pos, 0, head) + pos =pos+ head + buffer.writeu8(out, start + head - 1, #n.name) + str(n.name) + local pstart = pos + local hints = n.types or "" + for k, v in __iter(n.props) do + local h = string.sub(hints, k, k) + local tv = type(v) + if tv == "number" then + if h == "I" then + u8(73) + ensure(4) + buffer.writei32(out, pos, v) + pos =pos+ 4 + elseif h == "L" then + u8(76) + i64w(v) + elseif h == "F" then + u8(70) + ensure(4) + buffer.writef32(out, pos, v) + pos =pos+ 4 + elseif h == "Y" then + u8(89) + ensure(2) + buffer.writei16(out, pos, v) + pos =pos+ 2 + else + u8(68) + ensure(8) + writef64(out, pos, v) + pos =pos+ 8 + end + elseif tv == "boolean" then + u8(67) + u8(v and 1 or 0) + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then + u8(76) + local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0 + u32(lo) + u32(hi) + else + u8(83) + u32(#v) + str(v) + end + elseif tv == "buffer" then + u8(82) + u32(buffer.len(v)) + bytes(v) + elseif tv == "table" and v.array then + array(v) + else + u8(83) + u32(0) + end + end + local plen = pos - pstart + local children = n.children + if children and #children > 0 then + for _, c in __iter(children) do + node(c) + end + nullRecord() + elseif #n.props == 0 then + nullRecord() + end + setOff(start, pos) + if wide then + setOff(start + 8, #n.props) + setOff(start + 16, plen) + else + buffer.writeu32(out, start + 4, #n.props) + buffer.writeu32(out, start + 8, plen) + end + end + str(MAGIC) + u8(0x1A) + u8(0) + u32(ver) + for _, c in __iter(root.children or {}) do + node(c) + end + nullRecord() + str(FOOT_ID) + str("\0\0\0\0") + local pad = (math.floor((pos + 15) / 16)) * 16 - pos + if pad == 0 then + pad = 16 + end + str(string.rep("\0", pad)) + u32(ver) + str(string.rep("\0", 120)) + str(FOOT_MAGIC) + local res = buffer.create(pos) + buffer.copy(res, 0, out, 0, pos) + return res +end + +return Binary +end +__FILES["model/fbx/Read"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> +-- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric +-- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in +-- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one +-- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the +-- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file +-- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind +-- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's +-- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or +-- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node +-- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Xform = __include("model/fbx/Xform") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + + + + + + + +local TICKS = 46186158000 -- FBX time units per second +Read.TICKS = TICKS + +-- ------------------------------------------------------------------------------------------------ tree helpers +local function child(n, name) +if not n then + return nil + end + for _, c in __iter(n.children) do + if c.name == name then + return c + end + end + return nil +end +Read.child = child + +local function value(n, name) +local c = child(n, name) + return c and c.props[1] +end + +local function isArray(v) +return type(v) == "table" and v.array == true +end + +-- the array under n.<name> (or inline numbers: old ASCII files) +local function array(n, name) +local c = child(n, name) + if not c then + return nil + end + local p = c.props[1] + if isArray(p) then + return p + end + local count = 0 + for _, v in __iter(c.props) do + if type(v) == "number" then + count =count+ 1 + end + end + if count == 0 then + return nil + end + local data = buffer.create(count * 8) + local k = 0 + for _, v in __iter(c.props) do + if type(v) == "number" then + buffer.writef64(data, k * 8, v) + k =k+ 1 + end + end + return { array = true, type = "d", count = count, data = data } +end + +local function at(a, i) +if i < 0 or i >= a.count then + return 0 + end + return buffer.readf64(a.data, i * 8) +end + +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +local function objectName(s) +if type(s) ~= "string" then + return "" + end + local nm = string.match(s, "^(.-)%z\1") + if nm then + return nm + end + local _, rest = string.match(s, "^(%w+)::(.*)$") + if rest then + return rest + end + return s +end +Read.objectName = objectName + +-- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +local function properties(n, into) +local out = into or {} + local p70 = child(n, "Properties70") + if p70 then + for _, p in __iter(p70.children) do + local nm = p.props[1] + if p.name == "P" and type(nm) == "string" then + local v = { p.props[2] } + for k = 5, #p.props do + v[k - 3] = p.props[k] + end + out[nm] = v + end + end + end + return out +end +Read.properties = properties + +local function pnum(props, name, default) +local p = props[name] + local v = p and p[2] + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return v and 1 or 0 + end + return default +end +local function pvec(props, name, default) +local p = props[name] + if p and type(p[2]) == "number" and type(p[3]) == "number" and type(p[4]) == "number" then + return { p[2], p[3], p[4] } + end + return table.clone(default) +end +local function pstr(props, name) +local p = props[name] + local v = p and p[2] + return (type(v) == "string" and{v }or{nil +})[1]end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(root, version, fetch, opts) +local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local sampleRate = opts and type(opts.sampleRate) == "number" and opts.sampleRate > 0 and opts.sampleRate or nil + local maxVertices = opts and opts.maxVertices or 2 ^ 25 + local scene = Types.Scene.new() + + -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + local templates= {} + local defs = child(root, "Definitions") + if defs then + for _, ot in __iter(defs.children) do + if ot.name == "ObjectType" and type(ot.props[1]) == "string" then + local pt = child(ot, "PropertyTemplate") + if pt then + templates[ot.props[1] ] = properties(pt) + end + end + end + end + + -- objects + local objects= {} + local order= {} + local objs = child(root, "Objects") + if not objs then + return nil, Err.new(Err.CORRUPT, "no Objects section") + end + for _, n in __iter(objs.children) do + local id = n.props[1] + if (type(id) == "number" or type(id) == "string") and objects[id] == nil then + local base = templates[n.name] + local props = properties(n, (base and{(table.clone(base) )}or{nil})[1]) + local o= { id = id, node = n, name = objectName(n.props[2]), class = n.name, sub = (type(n.props[3]) == "string" and{n.props[3] }or{""})[1], props = props } + objects[id] = o + table.insert(order, o) + end + end + + -- connections: children (sources) of each parent, parents of each child, in file order + local kids= {} + local parents= {} + local conns = child(root, "Connections") + if conns then + for _, c in __iter(conns.children) do + if c.name == "C" or c.name == "Connect" then + local src, dst = c.props[2], c.props[3] + local prop = (type(c.props[4]) == "string" and{c.props[4] }or{nil +})[1] if src ~= nil and dst ~= nil and type(src) ~= "table" and type(dst) ~= "table" then + kids[dst] = kids[dst] or {} + table.insert(kids[dst], { id = src, prop = prop }) + parents[src] = parents[src] or {} + table.insert(parents[src], { id = dst, prop = prop }) + end + end + end + end + local function sources(id, class, sub) +local out = {} + for _, c in __iter(kids[id] or {}) do + local o = objects[c.id] + if o and (class == nil or o.class == class) and (sub == nil or o.sub == sub) then + table.insert(out, o) + end + end + return out + end + local function sourcesProp(id) +local out = {} + for _, c in __iter(kids[id] or {}) do + local o = objects[c.id] + if o then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + local function targets(id, class) +local out = {} + for _, c in __iter(parents[id] or {}) do + local o = objects[c.id] + if o and (class == nil or o.class == class) then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + + -- global settings + local gs = properties(child(root, "GlobalSettings")) + local upAxis = pnum(gs, "UpAxis", 1) + local unitScale = pnum(gs, "UnitScaleFactor", 1) + scene.meta.up = upAxis == 2 and"z" or"y" + scene.meta.unit = unitScale / 100 + local frameRates = { [1] = 120, [2] = 100, [3] = 60, [4] = 50, [5] = 48, [6] = 30, [7] = 30, [8] = 29.97, [9] = 29.97, [10] = 25, [11] = 24, [13] = 96, [14] = 72, [15] = 59.94, [17] = 119.88 } + local timeMode = pnum(gs, "TimeMode", 0) + local fps = (timeMode == 14 and{(pnum(gs, "CustomFrameRate", 24) )}or{frameRates[timeMode] or 24 +})[1] + -- ------------------------------------------------------------------------------------------ textures + local textureIndex= {} + local function mimeOf(data, name) +if data and buffer.len(data) >= 4 then + local h = buffer.readstring(data, 0, 4) + if h == "\137PNG" then + return "image/png" + elseif string.sub(h, 1, 3) == "\255\216\255" then + return "image/jpeg" + elseif string.sub(h, 1, 2) == "BM" then + return "image/bmp" + elseif h == "DDS " then + return "image/vnd-ms.dds" + elseif h == "RIFF" then + return "image/webp" + end + end + local ext = name and string.lower(string.match(name, "%.(%w+)$") or "") or "" + local M = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", webp = "image/webp", gif = "image/gif", psd = "image/vnd.adobe.photoshop" } + return M[ext] + end + local function content(v) +if not v then + return nil + end + local c = child(v, "Content") + if not c then + return nil + end + for _, p in __iter(c.props) do + if type(p) == "buffer" and buffer.len(p) > 0 then + return p + end + end + -- ASCII: base64 strings (possibly split into several) + local parts = {} + for _, p in __iter(c.props) do + if type(p) == "string" then + table.insert(parts, p) + end + end + local s = table.concat(parts) + if #s > 0 then + local d = Base64.decode(s) + if d and buffer.len(d) > 0 then + return d + end + end + return nil + end + local function texture(o) +local have = textureIndex[o.id] + if have then + return have + end + local n = o.node + local rel = value(n, "RelativeFilename") + local file = value(n, "FileName") or value(n, "Filename") + local data= nil + local video= sources(o.id, "Video")[1] + if video then + data = content(video.node) + rel = rel or value(video.node, "RelativeFilename") + file = file or value(video.node, "Filename") or value(video.node, "FileName") + end + local uri= nil + if type(rel) == "string" and rel ~= "" then + uri = (string.gsub(rel, "\\", "/")) + elseif type(file) == "string" and file ~= "" then + uri = (string.gsub(file, "\\", "/")) + end + if not data and uri then + data = fetch(uri ) + if not data then + local base = string.match(uri , "([^/]+)$") + if base and base ~= uri then + data = fetch(base) + end + end + end + local tex= { name = o.name, data = data, uri = (data and video and content(video.node) and{nil }or{uri})[1], mime = mimeOf(data, uri) } + local wrapU, wrapV = pnum(o.props, "WrapModeU", 0), pnum(o.props, "WrapModeV", 0) + if wrapU ~= 0 or wrapV ~= 0 then + tex.sampler = { wrapS = wrapU == 1 and"clamp" or"repeat", wrapT = wrapV == 1 and"clamp" or"repeat" } + end + tex.extras = { fbx = { uri = uri, uvSet = pstr(o.props, "UVSet") } } + table.insert(scene.textures, tex) + textureIndex[o.id] = #scene.textures + return #scene.textures + end + local function texRef(o) +local tobj = o + if o.class == "LayeredTexture" then + local t = sources(o.id, "Texture")[1] + if not t then + return nil + end + tobj = t + end + local ref= { texture = texture(tobj) } + local tr, sc = pvec(tobj.props, "Translation", { 0, 0, 0 }), pvec(tobj.props, "Scaling", { 1, 1, 1 }) + local rot = pvec(tobj.props, "Rotation", { 0, 0, 0 }) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot[3] ~= 0 then + ref.transform = { offset = { tr[1], tr[2] }, scale = { sc[1], sc[2] }, rotation = rot[3] * math.pi / 180 } + end + return ref + end + + -- ------------------------------------------------------------------------------------------ materials + local materialIndex= {} + local function material(o) +local have = materialIndex[o.id] + if have then + return have + end + local p = o.props + local m = Types.Scene.material(o.name) + local shading = value(o.node, "ShadingModel") + local diffuse = pvec(p, "DiffuseColor", pvec(p, "Diffuse", { 0.8, 0.8, 0.8 })) + local dfac = pnum(p, "DiffuseFactor", 1) + local emissive = pvec(p, "EmissiveColor", pvec(p, "Emissive", { 0, 0, 0 })) + local efac = pnum(p, "EmissiveFactor", 1) + local shininess = pnum(p, "ShininessExponent", pnum(p, "Shininess", 20)) + local opacity +if p.Opacity then + opacity = pnum(p, "Opacity", 1) + else + local tc = pvec(p, "TransparentColor", { 1, 1, 1 }) + opacity = 1 - pnum(p, "TransparencyFactor", 0) * (tc[1] + tc[2] + tc[3]) / 3 + end + opacity = math.clamp(opacity, 0, 1) + m.baseColor = { diffuse[1] * dfac, diffuse[2] * dfac, diffuse[3] * dfac, opacity } + m.emissive = { emissive[1] * efac, emissive[2] * efac, emissive[3] * efac } + m.metallic = 0 + m.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + if opacity < 1 then + m.alphaMode = "blend" + end + -- 3ds Max Physical / PBR materials + local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] + if pbr then + local prefix = p["3dsMax|main|basecolor"] and"3dsMax|main|" or"3dsMax|Parameters|" + local bc = pbr + if type(bc[2]) == "number" then + m.baseColor = { bc[2], bc[3] or 1, bc[4] or 1, (type(bc[5]) == "number" and{bc[5] }or{1 })[1]} + end + m.metallic = pnum(p, prefix .. "metalness", 0) + m.roughness = pnum(p, prefix .. "roughness", 1) + if pnum(p, prefix .. "useGlossiness", 0) == 1 or pnum(p, prefix .. "roughness_inv", 0) == 1 then + m.roughness = 1 - pnum(p, prefix .. "glossiness", 1 - m.roughness) + end + local ec = p[prefix .. "emit_color"] or p[prefix .. "emission_color"] + if ec and type(ec[2]) == "number" then + local k = pnum(p, prefix .. "emission", 1) + m.emissive = { ec[2] * k, (ec[3] or 0) * k, (ec[4] or 0) * k } + end + end + local extras= { + shadingModel = (type(shading) == "string" and{(string.lower(shading) )}or{(pstr(p, "ShadingModel"))})[1], + diffuse = diffuse, + diffuseFactor = dfac, + ambient = pvec(p, "AmbientColor", pvec(p, "Ambient", { 0, 0, 0 })), + ambientFactor = pnum(p, "AmbientFactor", 1), + specular = pvec(p, "SpecularColor", pvec(p, "Specular", { 0.2, 0.2, 0.2 })), + specularFactor = pnum(p, "SpecularFactor", 1), + shininess = shininess, + emissive = emissive, + emissiveFactor = efac, + opacity = opacity, + reflection = pvec(p, "ReflectionColor", { 0, 0, 0 }), + reflectionFactor = pnum(p, "ReflectionFactor", 0), + bumpFactor = pnum(p, "BumpFactor", 1), + textures = {}, + } + for _, s in __iter(sourcesProp(o.id)) do + local cls = s.obj.class + if (cls == "Texture" or cls == "LayeredTexture") and s.prop then + local ref = texRef(s.obj) + if ref then + local prop = s.prop +local lp = string.lower(prop) + extras.textures[prop] = ref.texture + if lp == "diffusecolor" or string.find(lp, "base_?color_map") or lp == "maya|basecolor" or lp == "maya|texturebasecolor" then + m.baseColorTexture = m.baseColorTexture or ref + elseif lp == "normalmap" or lp == "bump" or string.find(lp, "norm_map") or string.find(lp, "bump_map") or lp == "maya|normalcamera" then + m.normalTexture = m.normalTexture or ref + elseif lp == "emissivecolor" or string.find(lp, "emit_color_map") or string.find(lp, "emission_map") then + m.emissiveTexture = m.emissiveTexture or ref + if m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 1, 1, 1 } + end + elseif string.find(lp, "ao_map") then + m.occlusionTexture = m.occlusionTexture or ref + end + end + end + end + if not next(extras.textures) then + extras.textures = nil + end + m.extras = { fbx = extras } + table.insert(scene.materials, m) + materialIndex[o.id] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ nodes + local models= {} + local nodeOf= {} + for _, o in __iter(order) do + if o.class == "Model" then + table.insert(models, o) + local nd= { name = o.name, children = {} } + table.insert(scene.nodes, nd) + nodeOf[o.id] = #scene.nodes + end + end + if #models > maxVertices then + return nil, Err.new(Err.LIMIT, "too many models") + end + local function xprops(o, over) +local p = o.props + local function g(name, key, default) +if over and over[key] then + return over[key] + end + return pvec(p, name, default) + end + return { + T = g("Lcl Translation", "T", { 0, 0, 0 }), + R = g("Lcl Rotation", "R", { 0, 0, 0 }), + S = g("Lcl Scaling", "S", { 1, 1, 1 }), + Rpre = pvec(p, "PreRotation", { 0, 0, 0 }), + Rpost = pvec(p, "PostRotation", { 0, 0, 0 }), + Roff = pvec(p, "RotationOffset", { 0, 0, 0 }), + Rp = pvec(p, "RotationPivot", { 0, 0, 0 }), + Soff = pvec(p, "ScalingOffset", { 0, 0, 0 }), + Sp = pvec(p, "ScalingPivot", { 0, 0, 0 }), + order = pnum(p, "RotationOrder", 0), + } + end + local localM= {} + for _, o in __iter(models) do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + local m = Xform.localMatrix(xprops(o)) + localM[ni] = m + local t, r, s = Mat4.decompose(m) + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + nd.translation = t + end + if r[1] ~= 0 or r[2] ~= 0 or r[3] ~= 0 or r[4] ~= 1 then + nd.rotation = r + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + nd.scale = s + end + nd.extras = { fbx = { type = o.sub, id = o.id } } + -- parent + local parentModel= nil + for _, t2 in __iter(targets(o.id, "Model")) do + parentModel = t2.obj + break + end + local pi = parentModel and nodeOf[parentModel.id] + if pi and pi ~= ni then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + do + local placed= {} + local function visit(i) + placed[i] = true + local nd = scene.nodes[i] + local keepKids = {} + for _, c in __iter(nd.children) do + if not placed[c] then + table.insert(keepKids, c) + visit(c) + end + end + nd.children = keepKids + end + for _, r in __iter(scene.roots) do + visit(r) + end + for i in __iter(scene.nodes) do + if not placed[i] then + -- part of a parent cycle: make it a root + table.insert(scene.roots, i) + visit(i) + end + end + end + -- world matrices (rest pose) + local worldM= {} + local function world(i, parent) + worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) + for _, c in __iter(scene.nodes[i].children) do + if not worldM[c] then + world(c, worldM[i]) + end + end + end + for _, r in __iter(scene.roots) do + world(r, Mat4.identity()) + end + + -- ------------------------------------------------------------------------------------------ meshes + local corners = 0 + -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels + local function skinOf(geo) +local skin = sources(geo.id, "Deformer", "Skin")[1] + if not skin then + return nil, nil + end + local perCp= {} + local joints= {} + local ibms= {} + for _, cl in __iter(sources(skin.id, "Deformer", "Cluster")) do + local bone = sources(cl.id, "Model")[1] + local bi = bone and nodeOf[bone.id] + if bi then + local ji = #joints + 1 + joints[ji] = bi + local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") + local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") + local tm = Mat4.identity() + if T and T.count >= 16 then + for k = 1, 16 do + tm[k] = at(T, k - 1) + end + end + local tl= nil + if TL and TL.count >= 16 then + tl = {} + for k = 1, 16 do + (tl )[k] = at(TL, k - 1) + end + else + tl = worldM[bi] + end + local inv = Mat4.inverse(tl ) or Mat4.identity() + ibms[ji] = Mat4.mul(inv, tm) + if idx and w then + for k = 0, math.min(idx.count, w.count) - 1 do + local cp = at(idx, k) + local wt = at(w, k) + if cp >= 0 and cp == math.floor(cp) and cp < maxVertices and wt > 0 then + local l = perCp[cp + 1] + if not l then + l = {} + perCp[cp + 1] = l + end + table.insert(l, { ji - 1, wt }) + end + end + end + end + end + if #joints == 0 then + return nil, nil + end + local ibm = buffer.create(#joints * 64) + for j, m in __iter(ibms) do + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local acc = Types.Scene.accessor(ibm, "f32", 16, #joints) + acc.matrix = true + return perCp, { name = skin.name, joints = joints, inverseBindMatrices = acc } + end + +local function shapesOf(geo) +local out = {} + for _, bs in __iter(sources(geo.id, "Deformer", "BlendShape")) do + for _, ch in __iter(sources(bs.id, "Deformer", "BlendShapeChannel")) do + local shapes = sources(ch.id, "Geometry") + local sh = shapes[#shapes] -- in-betweens: the full (last) shape + if sh then + table.insert(out, { + name = ch.name ~= "" and ch.name or sh.name, + channel = ch, + weight = pnum(ch.props, "DeformPercent", 0) / 100, + idx = array(sh.node, "Indexes"), + dv = array(sh.node, "Vertices"), + dn = array(sh.node, "Normals"), + }) + end + end + end + return out + end + + local meshCache= {} + local shapeChannels= {} -- mesh index -> blend shape channel objects (for weights curves) + local nodeSkin= {} + local skinCache= {} + + local function buildMesh(geo, mats, G) +local g = geo.node + local verts = array(g, "Vertices") + local pvi = array(g, "PolygonVertexIndex") + if not verts or not pvi then + return nil, nil + end + local ncp = math.floor(verts.count / 3 +) local nc = pvi.count + corners =corners+ nc + if corners > maxVertices or ncp > maxVertices then + return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") + end + -- polygons: corner -> control point, polygon of each corner, polygon starts + local cp = table.create(nc, 0) + local polyOf = table.create(nc, 0) + local starts= { 0 } + local np = 0 + for c = 0, nc - 1 do + local v = at(pvi, c) + local last = v < 0 + if last then + v = -v - 1 + end + if v >= ncp or v ~= math.floor(v) then + v = 0 + end + cp[c + 1] = v + polyOf[c + 1] = np + if last then + np =np+ 1 + starts[np + 1] = c + 1 + end + end + if starts[np + 1] ~= nc then + -- the last polygon has no end marker + np =np+ 1 + starts[np + 1] = nc + end +-- layer elements + +local function elems(kind, dataName, indexName, comps) +local out= {} + for _, c in __iter(g.children) do + if c.name == kind then + local data = array(c, dataName) + local mapping = value(c, "MappingInformationType") + local ref = value(c, "ReferenceInformationType") + local index = ((ref == "IndexToDirect" or ref == "Index" )and{array(c, indexName) or array(c, dataName .. "Index") }or{nil +})[1] if kind == "LayerElementMaterial" then + index = data + end + if data and type(mapping) == "string" then + table.insert(out, { data = data, index = index, mapping = mapping, comps = comps, name = value(c, "Name"), order = (type(c.props[1]) == "number" and{c.props[1] }or{(#out )})[1]}) + end + end + end + table.sort(out, function(a, b) +return a.order < b.order + end) + return out + end + -- the data element of a corner (c 0-based), or -1 + local function lookup(e, c) +local m = e.mapping + local i + if m == "ByPolygonVertex" then + i = c + elseif m == "ByVertice" or m == "ByVertex" then + i = cp[c + 1] + elseif m == "ByPolygon" then + i = polyOf[c + 1] + elseif m == "AllSame" then + i = 0 + else + return -1 + end + if e.index and e.data ~= e.index then + if i >= (e.index ).count then + return -1 + end + i = at(e.index , i) + end + if i < 0 or (i + 1) * e.comps > e.data.count then + return -1 + end + return i + end + local normals = elems("LayerElementNormal", "Normals", "NormalsIndex", 3) + local uvs = elems("LayerElementUV", "UV", "UVIndex", 2) + local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) + local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) + local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] + -- the normals index name varies ("NormalsIndex" / "NormalIndex") + for _, e in __iter(normals) do + if not e.index then + local c = nil + for _, x in __iter(g.children) do + if x.name == "LayerElementNormal" then + c = x + break + end + end + local r = c and value(c, "ReferenceInformationType") + if r == "IndexToDirect" then + e.index = array(c, "NormalIndex") + end + end + end + -- polygons by material slot + local groups= {} + local slots= {} + for p = 0, np - 1 do + local slot = 0 + if matEl then + local c0 = starts[p + 1] + local i = matEl.mapping == "AllSame" and 0 or p + if matEl.mapping == "ByPolygonVertex" then + i = c0 + end + slot = at(matEl.data, i) + if slot < 0 or slot ~= math.floor(slot) then + slot = 0 + end + end + local grp = groups[slot] + if not grp then + grp = {} + groups[slot] = grp + table.insert(slots, slot) + end + table.insert(grp, p) + end + table.sort(slots) + local perCp, skin = skinOf(geo) + local shapes = shapesOf(geo) + local N3= nil -- normal matrix (inverse transpose of G) + if G then + local inv = Mat4.inverse(G) + if inv then + N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } + end + end + local mesh= { name = geo.name, primitives = {} } + local function v3(dst, o, x, y, z, M, w) + if M then + x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w + end + buffer.writef32(dst, o, x) + buffer.writef32(dst, o + 4, y) + buffer.writef32(dst, o + 8, z) + end + local skipped = 0 + for _, slot in __iter(slots) do + local polys = groups[slot] + local nv = 0 + local ntri = 0 + for _, p in __iter(polys) do + local k = starts[p + 2] - starts[p + 1] + if k >= 3 or not triangulate then + nv =nv+ k + ntri =ntri+ math.max(k - 2, 0) + else + skipped =skipped+ 1 + end + end + if nv > 0 then + local pos = buffer.create(nv * 12) + local nrm = (normals[1] and{(buffer.create(nv * 12) )}or{nil +})[1] local tan = (tangents[1] and{(buffer.create(nv * 16) )}or{nil +})[1] local uvb= {} + for k = 1, #uvs do + uvb[k] = buffer.create(nv * 8) + end + local colb= {} + for k = 1, #colors do + colb[k] = buffer.create(nv * 16) + end + local joints = (perCp and{(buffer.create(nv * 8) )}or{nil +})[1] local weights = (perCp and{(buffer.create(nv * 16) )}or{nil +})[1] local tgt= {} + local shapeData= {} + for si, sh in __iter(shapes) do + local map= {} + if sh.idx then + for k = 0, sh.idx.count - 1 do + map[at(sh.idx, k)] = k + end + end + shapeData[si] = { pos = buffer.create(nv * 12), nrm = (sh.dn and nrm and{(buffer.create(nv * 12) )}or{nil})[1], map = map } + end + local faces = (not triangulate and{(buffer.create(#polys * 4) )}or{nil +})[1] local idx = buffer.create(((triangulate and((ntri * 3 ))or(nv))) * 4) + local v = 0 + local ti = 0 + local fi = 0 + for _, p in __iter(polys) do + local c0, c1 = starts[p + 1], starts[p + 2] + local k = c1 - c0 + if k >= 3 or not triangulate then + local first = v + for c = c0, c1 - 1 do + local i = cp[c + 1] + v3(pos, v * 12, at(verts, i * 3), at(verts, i * 3 + 1), at(verts, i * 3 + 2), G, 1) + if nrm then + local d = lookup(normals[1], c) + local e = normals[1].data + if d >= 0 then + v3(nrm, v * 12, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), N3, 0) + end + end + if tan then + local d = lookup(tangents[1], c) + local e = tangents[1].data + if d >= 0 then + v3(tan, v * 16, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), G, 0) + buffer.writef32(tan, v * 16 + 12, 1) + end + end + for u, e in __iter(uvs) do + local d = lookup(e, c) + if d >= 0 then + local uu, vv = at(e.data, d * 2), at(e.data, d * 2 + 1) + buffer.writef32(uvb[u], v * 8, uu) + buffer.writef32(uvb[u], v * 8 + 4, (flipV and((1 - vv ))or(vv))) + end + end + for u, e in __iter(colors) do + local d = lookup(e, c) + local b = colb[u] + if d >= 0 then + for q = 0, 3 do + buffer.writef32(b, v * 16 + q * 4, at(e.data, d * 4 + q)) + end + else + buffer.writef32(b, v * 16 + 12, 1) + end + end + if perCp and joints and weights then + local l = perCp[i + 1] + if l then + if #l > 4 then + table.sort(l, function(a, b) +return a[2] > b[2] + end) + end + local sum = 0 + for q = 1, math.min(#l, 4) do + sum =sum+ l[q][2] + end + for q = 1, math.min(#l, 4) do + buffer.writeu16(joints, v * 8 + (q - 1) * 2, l[q][1]) + buffer.writef32(weights, v * 16 + (q - 1) * 4, (sum > 0 and((l[q][2] / sum ))or(0))) + end + end + end + for si, sd in __iter(shapeData) do + local sh = shapes[si] + local k2 = sd.map[i] + if k2 and sh.dv then + v3(sd.pos, v * 12, at(sh.dv, k2 * 3), at(sh.dv, k2 * 3 + 1), at(sh.dv, k2 * 3 + 2), G, 0) + if sd.nrm and sh.dn then + v3(sd.nrm, v * 12, at(sh.dn, k2 * 3), at(sh.dn, k2 * 3 + 1), at(sh.dn, k2 * 3 + 2), N3, 0) + end + end + end + if not triangulate then + buffer.writeu32(idx, v * 4, v) + end + v =v+ 1 + end + if triangulate then + for q = 1, k - 2 do + buffer.writeu32(idx, ti * 4, first) + buffer.writeu32(idx, ti * 4 + 4, first + q) + buffer.writeu32(idx, ti * 4 + 8, first + q + 1) + ti =ti+ 3 + end + elseif faces then + buffer.writeu32(faces, fi * 4, k) + fi =fi+ 1 + end + end + end + local attrs= { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if tan then + attrs.TANGENT = Types.Scene.accessor(tan, "f32", 4, nv) + end + for u, b in __iter(uvb) do + attrs["TEXCOORD_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 2, nv) + end + for u, b in __iter(colb) do + attrs["COLOR_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 4, nv) + end + if joints and weights then + attrs.JOINTS_0 = Types.Scene.accessor(joints, "u16", 4, nv) + attrs.WEIGHTS_0 = Types.Scene.accessor(weights, "f32", 4, nv) + end + for si, sd in __iter(shapeData) do + local t= { POSITION = Types.Scene.accessor(sd.pos, "f32", 3, nv) } + if sd.nrm then + t.NORMAL = Types.Scene.accessor(sd.nrm, "f32", 3, nv) + end + tgt[si] = t + end + local prim= { + attributes = attrs, + indices = Types.Scene.accessor(idx, "u32", 1, (triangulate and((ntri * 3 ))or(nv))), + mode = triangulate and"triangles" or"polygons", + faces = (faces and{(Types.Scene.accessor(faces, "u32", 1, #polys) )}or{nil})[1], + material = mats[slot + 1], + targets = (#tgt > 0 and{tgt }or{nil})[1], + } + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + local names = {} + for k, uv in __iter(uvs) do + names[k] = uv.name + end + mesh.extras = { fbx = { id = geo.id, uvSets = names, skippedPolygons = (skipped > 0 and{skipped }or{nil })[1]} } + if #shapes > 0 then + local w, tn, chans = {}, {}, {} + for si, sh in __iter(shapes) do + w[si] = sh.weight + tn[si] = sh.name + chans[si] = sh.channel + end + mesh.weights = w + ;(mesh.extras ).targetNames = tn + table.insert(scene.meshes, mesh) + shapeChannels[#scene.meshes] = chans + else + table.insert(scene.meshes, mesh) + end + local mi = #scene.meshes + if skin then + skinCache[geo.id] = skinCache[geo.id] or (function() +table.insert(scene.skins, skin) + return #scene.skins + end)() + end + return mi, nil + end + + local orient = math.sqrt(0.5) + for _, o in __iter(models) do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + -- materials of the model, in connection order + local mats= {} + for _, m in __iter(sources(o.id, "Material")) do + table.insert(mats, material(m)) + end + -- geometric transform (not inherited: baked into the mesh) + local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) + local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) + local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) + local G= nil + if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then + G = Mat4.mul(Mat4.translation(gt[1], gt[2], gt[3]), Mat4.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Mat4.scaling(gsc[1], gsc[2], gsc[3]))) + end + for _, geo in __iter(sources(o.id, "Geometry")) do + if geo.sub == "Mesh" or geo.sub == "" then + local key = tostring(geo.id) .. "|" .. table.concat(mats, ",") .. "|" .. ((G and{(table.concat(G , ",") )}or{""})[1]) + local mi = meshCache[key] + if mi == nil then + local m, err = buildMesh(geo, mats, G) + if err then + return nil, err + end + if m then + meshCache[key] = m + mi = m + end + end + if mi then + if nd.mesh == nil then + nd.mesh = mi + if skinCache[geo.id] then + nd.skin = skinCache[geo.id] + end + nd.weights = scene.meshes[mi].weights and table.clone(scene.meshes[mi].weights ) + else + -- a second geometry on the same model: a child node + table.insert(scene.nodes, { name = o.name, children = {}, mesh = mi, skin = skinCache[geo.id] }) + table.insert(nd.children, #scene.nodes) + end + nodeSkin[ni] = skinCache[geo.id] + end + end + end + -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + for _, a in __iter(sources(o.id, "NodeAttribute")) do + local p = a.props + if a.sub == "Camera" then + local ortho = pnum(p, "CameraProjectionType", 0) == 1 + local aw, ah = pnum(p, "AspectWidth", 0), pnum(p, "AspectHeight", 0) + local fw, fh = pnum(p, "FilmWidth", 0.816), pnum(p, "FilmHeight", 0.612) + local aspect = (aw > 0 and ah > 0 and((aw / ah ))or((fh > 0 and((fw / fh ))or((4 / 3 +))))) local cam +local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) + if ortho then + local zoom = pnum(p, "OrthoZoom", 1) + cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } +else + local focal = pnum(p, "FocalLength", 0) + local hfov + if focal > 0 and fw > 0 then + hfov = 2 * math.atan(fw * 25.4 / (2 * focal)) + else + hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 + end + local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) + cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } +end + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) + table.insert(nd.children, #scene.nodes) + elseif a.sub == "Light" then + local lt = pnum(p, "LightType", 0) + local col = pvec(p, "Color", { 1, 1, 1 }) + local light= { + name = a.name ~= "" and a.name or o.name, + type = lt == 1 and"directional" or(lt == 2 and"spot" or"point"), + color = col, + intensity = pnum(p, "Intensity", 100) / 100, + } + if lt == 2 then + local outer = pnum(p, "OuterAngle", pnum(p, "Cone angle", 45)) + local inner = pnum(p, "InnerAngle", pnum(p, "HotSpot", 0)) + light.outerCone = math.clamp(outer / 2, 0, 90) * math.pi / 180 + light.innerCone = math.clamp(math.min(inner, outer) / 2, 0, 90) * math.pi / 180 + end + if pnum(p, "EnableFarAttenuation", 0) == 1 then + light.range = pnum(p, "FarAttenuationEnd", 0) + end + table.insert(scene.lights, light) + table.insert(scene.nodes, { name = o.name .. "_light", children = {}, light = #scene.lights, rotation = { -orient, 0, 0, orient }, extras = { fbx = { orientation = "light", lightType = lt } } }) + table.insert(nd.children, #scene.nodes) + end + end + end +-- ------------------------------------------------------------------------------------------ animation + + +local curveCache= {} + local function curve(o) +local have = curveCache[o.id] + if have then + return have + end + local kt, kv = array(o.node, "KeyTime"), array(o.node, "KeyValueFloat") + if not kt or not kv then + return nil + end + local n = math.min(kt.count, kv.count) + if n == 0 then + return nil + end + local times, values = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = at(kt, k) / TICKS + values[k + 1] = at(kv, k) + end + -- per-key attribute flags (expanded through KeyAttrRefCount) + local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") + local flags = table.create(n, 4) + local slopes= {} + if fl and rc then + local key = 1 + for a = 0, math.min(fl.count, rc.count) - 1 do + local f = at(fl, a) + local cnt = at(rc, a) + for _ = 1, math.min(cnt, n - key + 1) do + flags[key] = f + if df and df.count >= (a + 1) * 4 then + slopes[key] = { at(df, a * 4), at(df, a * 4 + 1) } + end + key =key+ 1 + end + end + end + local c= { times = times, values = values, flags = flags, slopes = slopes } + curveCache[o.id] = c + return c + end + local function eval(c, t) +local ts, vs = c.times, c.values + local n = #ts + if t <= ts[1] then + return vs[1] + elseif t >= ts[n] then + return vs[n] + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = math.floor((lo + hi) / 2 +) if ts[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = ts[hi] - ts[lo] + if dt <= 0 then + return vs[hi] + end + local u = (t - ts[lo]) / dt + local f = bit32.band(c.flags[lo] or 4, 0x0E) + if f == 2 then + return vs[lo] + elseif f == 8 and c.slopes and c.slopes[lo] then + local s = (c.slopes )[lo] + local m0, m1 = s[1] * dt, s[2] * dt + local u2, u3 = u * u, u * u * u + return (2 * u3 - 3 * u2 + 1) * vs[lo] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * vs[hi] + (u3 - u2) * m1 + end + return vs[lo] + (vs[hi] - vs[lo]) * u + end + local function allConstant(cs) +for _, c in __iter(cs) do + for k = 1, #c.times - 1 do + if bit32.band(c.flags[k] or 4, 0x0E) ~= 2 then + return false + end + end + end + return true + end + local function sampleTimes(cs) +local set= {} + local out= {} + local tmin, tmax = math.huge, -math.huge + for _, c in __iter(cs) do + for _, t in __iter(c.times) do + tmin, tmax = math.min(tmin, t), math.max(tmax, t) + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + if sampleRate and tmax > tmin then + local steps = math.min(math.ceil((tmax - tmin) * sampleRate), 100000) + for k = 0, steps do + local t = tmin + (tmax - tmin) * k / steps + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + table.sort(out) + return out + end + local function f32acc(vals, comps) +local n = math.floor(#vals / comps +) local b = buffer.create(#vals * 4) + for k, v in __iter(vals) do + buffer.writef32(b, (k - 1) * 4, v) + end + return Types.Scene.accessor(b, "f32", comps, n) + end + local PROPS = { ["Lcl Translation"] = "T", ["Lcl Rotation"] = "R", ["Lcl Scaling"] = "S" } + for _, stack in __iter(order) do + if stack.class == "AnimationStack" then + local anim= { name = stack.name, channels = {} } +-- model id -> { T/R/S -> { axis -> curve } , defaults } + +local tracks= {} + local trackOrder= {} + local morph= {} -- blend shape channel id -> DeformPercent curve + local layers = sources(stack.id, "AnimationLayer") + for _, layer in __iter(layers) do + for _, cn in __iter(sources(layer.id, "AnimationCurveNode")) do + for _, tgt in __iter(targets(cn.id)) do + local key = tgt.prop and PROPS[tgt.prop] + if key and tgt.obj.class == "Model" and nodeOf[tgt.obj.id] then + local tr = tracks[tgt.obj.id] + if not tr then + tr = { curves = {}, defaults = {} } + tracks[tgt.obj.id] = tr + table.insert(trackOrder, tgt.obj.id) + end + if not tr.curves[key] then + local axes= {} + for _, s in __iter(sourcesProp(cn.id)) do + if s.obj.class == "AnimationCurve" and s.prop then + local ax = string.find(s.prop, "X$") and 1 or(string.find(s.prop, "Y$") and 2 or(string.find(s.prop, "Z$") and 3 or nil +)) local c = ax and curve(s.obj) + if ax and c then + axes[ax] = c + end + end + end + if next(axes) then + tr.curves[key] = axes + tr.defaults[key] = { pnum(cn.props, "d|X", 0), pnum(cn.props, "d|Y", 0), pnum(cn.props, "d|Z", 0) } + end + end + elseif tgt.prop == "DeformPercent" and tgt.obj.class == "Deformer" then + for _, s in __iter(sources(cn.id, "AnimationCurve")) do + local c = curve(s) + if c and not morph[tgt.obj.id] then + morph[tgt.obj.id] = c + end + end + end + end + end + end + for _, id in __iter(trackOrder) do + local tr = tracks[id] + local o = objects[id] + local ni = nodeOf[id] + local cs= {} + for _, axes in __iter(tr.curves) do + for _, c in pairs(axes) do + table.insert(cs, c) + end + end + local times = sampleTimes(cs) + if #times > 0 then + local base = xprops(o) + local T, R, S = {}, {}, {} + local prevQ= nil + for _, t in __iter(times) do + local over= {} + for key, axes in __iter(tr.curves) do + local stat = (base )[key] + local v = table.clone(stat) + for ax = 1, 3 do + local c = axes[ax] + if c then + v[ax] = eval(c, t) + end + end + over[key] = v + end + local tt, rr, ss = Mat4.decompose(Xform.localMatrix(xprops(o, over))) + if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then + rr = { -rr[1], -rr[2], -rr[3], -rr[4] } + end + prevQ = rr + table.move(tt, 1, 3, #T + 1, T) + table.move(rr, 1, 4, #R + 1, R) + table.move(ss, 1, 3, #S + 1, S) + end + local input = f32acc(times, 1) + local interp= allConstant(cs) and"STEP" or"LINEAR" + local nd = scene.nodes[ni] + local function varies(vals, comps, rest) +for k = 0, math.floor(#vals / comps )- 1 do + for q = 1, comps do + if math.abs(vals[k * comps + q] - rest[q]) > 1e-6 then + return true + end + end + end + return false + end + if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then + table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp } ) + end + if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then + table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp } ) + end + if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then + table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp } ) + end + end + end + -- morph target weights: every node whose mesh has an animated blend shape channel + if next(morph) then + for ni, nd in __iter(scene.nodes) do + local chans = nd.mesh and shapeChannels[nd.mesh] + if chans then + local cs= {} + for _, ch in __iter(chans) do + if morph[ch.id] then + table.insert(cs, morph[ch.id]) + end + end + if #cs > 0 then + local times = sampleTimes(cs) + local out = {} + for _, t in __iter(times) do + for _, ch in __iter(chans) do + local c = morph[ch.id] + table.insert(out, ((c and{(eval(c, t) )}or{(pnum(ch.props, "DeformPercent", 0))})[1]) / 100) + end + end + local acc = f32acc(out, 1) + table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = allConstant(cs) and"STEP" or"LINEAR" } ) + end + end + end + end + if #anim.channels > 0 then + table.insert(scene.animations, anim) + end + end + end + + -- ------------------------------------------------------------------------------------------ meta + local header = child(root, "FBXHeaderExtension") + local creator = value(root, "Creator") or value(header, "Creator") + scene.meta.source = { + format = "fbx", + version = version, + creator = (type(creator) == "string" and{creator }or{nil})[1], + upAxis = upAxis, + upAxisSign = pnum(gs, "UpAxisSign", 1), + frontAxis = pnum(gs, "FrontAxis", 2), + frontAxisSign = pnum(gs, "FrontAxisSign", 1), + coordAxis = pnum(gs, "CoordAxis", 0), + coordAxisSign = pnum(gs, "CoordAxisSign", 1), + unitScaleFactor = unitScale, + originalUnitScaleFactor = pnum(gs, "OriginalUnitScaleFactor", unitScale), + frameRate = fps, + } + local _ = nodeSkin + return scene, nil +end + +return Read +end +__FILES["model/fbx/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types +-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). +-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one +-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals +-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; +-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> +-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +local Err = __include("core/Err") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Write = {} + + + +local TICKS = 46186158000 +local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } } + +local function N(name, types, props, children) +return { name = name, types = types, props = props, children = children } +end +local function arr(t, list) +local n = #list + local d = buffer.create(n * 8) + for k = 1, n do + buffer.writef64(d, (k - 1) * 8, list[k]) + end + return { array = true, type = t, count = n, data = d } +end +-- P: name, type, label, flags, values (vt: one type character per value) +local function P(name, ptype, label, flags, vt, ...) +return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } +end +local function Pvec(name, ptype, label, v) +return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3]) +end +local function Pcolor(name, v) +return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0) +end +local function Pnum(name, v) +return P(name, "Number", "", "A", "D", v) +end +local function Pint(name, v) +return P(name, "int", "Integer", "", "I", v) +end +local function Penum(name, v) +return P(name, "enum", "", "", "I", v) +end +local function Pdouble(name, v) +return P(name, "double", "Number", "", "D", v) +end +local function Ptime(name, v) +return P(name, "KTime", "Time", "", "L", v) +end +local function cls(name, class) +return (name or "") .. "\0\1" .. class +end + +local function accessorReader(acc) +if not acc then + return nil + end + return Types.Scene.reader(acc) +end + +-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) +local function faces(prim) +local pos = prim.attributes.POSITION + if not pos then + return nil + end + local n = pos.count + local idx = accessorReader(prim.indices) + local count = (prim.indices and{prim.indices.count }or{n +})[1] local function I(k) +return (idx and{(idx(k, 0) )}or{k +})[1] end + local out= {} + local mode = prim.mode or "triangles" + if mode == "triangles" then + for k = 0, math.floor(count / 3 )- 1 do + table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) }) + end + elseif mode == "polygons" and prim.faces then + local f = accessorReader(prim.faces) + local p = 0 + if f then + for k = 0, prim.faces.count - 1 do + local sz = f(k, 0) + if p + sz > count then + break + end + local poly = (table.create(sz) ) +for q = 0, sz - 1 do + poly[q + 1] = I(p + q) + end + p =p+ sz + table.insert(out, poly) + end + end + elseif mode == "triangle_strip" then + for k = 0, count - 3 do + local a, b, c = I(k), I(k + 1), I(k + 2) + if k % 2 == 1 then + a, b = b, a + end + table.insert(out, { a, b, c }) + end + elseif mode == "triangle_fan" then + for k = 1, count - 2 do + table.insert(out, { I(0), I(k), I(k + 1) }) + end + else + return nil -- points / lines: not written + end + for _, f in __iter(out) do + for q, v in __iter(f) do + if v < 0 or v >= n then + f[q] = 0 + end + end + end + return out +end + +function Write.tree(scene, opts) +local flipV = not (opts and opts.flipV == false) + local embed = not (opts and opts.embedTextures == false) + local nextId = 1000000 + local function id() +nextId =nextId+ 1 + return nextId + end + local objects= {} + local conns= {} + local counts= {} + local function add(class, node) + table.insert(objects, node) + counts[class] = (counts[class] or 0) + 1 + end + local function OO(child, parent) + table.insert(conns, N("C", "SLL", { "OO", child, parent })) + end + local function OP(child, parent, prop) + table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop })) + end + local nodes = scene.nodes or {} + + -- ------------------------------------------------------------------------------------------ textures + local EXT= { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } + local texIds= {} + local base= opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + for ti, tex in __iter(scene.textures or {}) do + local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) + local tname = tex.name or ("Texture" .. ti) + local vid, tid = id(), id() + local vchildren = { + N("Type", "S", { "Clip" }), + N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }), + N("UseMipMap", "I", { 0 }), + N("Filename", "S", { file }), + N("RelativeFilename", "S", { file }), + } + if embed and tex.data then + table.insert(vchildren, N("Content", "R", { tex.data })) + end + add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren)) + local tp = { P("UseMaterial", "bool", "", "", "I", 1) } + local smp = tex.sampler + if smp and smp.wrapS == "clamp" then + table.insert(tp, Penum("WrapModeU", 1)) + end + if smp and smp.wrapT == "clamp" then + table.insert(tp, Penum("WrapModeV", 1)) + end + add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, { + N("Type", "S", { "TextureVideoClip" }), + N("Version", "I", { 202 }), + N("TextureName", "S", { cls(tname, "Texture") }), + N("Properties70", "", {}, tp), + N("Media", "S", { cls(tname, "Video") }), + N("FileName", "S", { file }), + N("RelativeFilename", "S", { file }), + N("ModelUVTranslation", "DD", { 0, 0 }), + N("ModelUVScaling", "DD", { 1, 1 }), + N("Texture_Alpha_Source", "S", { "None" }), + N("Cropping", "IIII", { 0, 0, 0, 0 }), + })) + OO(vid, tid) + texIds[ti] = tid + end + + -- ------------------------------------------------------------------------------------------ materials + local matIds= {} + for mi, m in __iter(scene.materials or {}) do + local x = m.extras and (m.extras ).fbx or {} + local bc = m.baseColor or { 1, 1, 1, 1 } + local alpha = bc[4] or 1 + local rough = math.clamp(m.roughness or 1, 0.02, 1) + local shin = (type(x.shininess) == "number" and{x.shininess }or{(2 / (rough * rough) - 2 +)})[1] local em = m.emissive or { 0, 0, 0 } + local spec = (type(x.specular) == "table" and{x.specular }or{{ 0.2, 0.2, 0.2 } +})[1] local pid = id() + local props = { + Pcolor("AmbientColor", (type(x.ambient) == "table" and{x.ambient }or{{ 0, 0, 0 }})[1]), + Pnum("AmbientFactor", (type(x.ambientFactor) == "number" and{x.ambientFactor }or{1})[1]), + Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }), + Pnum("DiffuseFactor", 1), + Pcolor("EmissiveColor", em), + Pnum("EmissiveFactor", 1), + Pcolor("SpecularColor", spec), + Pnum("SpecularFactor", (type(x.specularFactor) == "number" and{x.specularFactor }or{1})[1]), + Pnum("Shininess", shin), + Pnum("ShininessExponent", shin), + Pcolor("TransparentColor", { 1, 1, 1 }), + Pnum("TransparencyFactor", 1 - alpha), + Pnum("Opacity", alpha), + Pcolor("ReflectionColor", (type(x.reflection) == "table" and{x.reflection }or{{ 0, 0, 0 }})[1]), + Pnum("ReflectionFactor", (type(x.reflectionFactor) == "number" and{x.reflectionFactor }or{0})[1]), + } + add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, { + N("Version", "I", { 102 }), + N("ShadingModel", "S", { (type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" and{x.shadingModel }or{"phong" })[1]}), + N("MultiLayer", "I", { 0 }), + N("Properties70", "", {}, props), + })) + matIds[mi] = pid + local function link(ref, prop) + local t = ref and texIds[ref.texture] + if t then + OP(t, pid, prop) + end + end + link(m.baseColorTexture, "DiffuseColor") + link(m.normalTexture, "NormalMap") + link(m.emissiveTexture, "EmissiveColor") + -- the other textures the FBX material had (specular, metalness, ... maps), under their property names + local linked = { + [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, + [m.normalTexture and m.normalTexture.texture or -1] = true, + [m.emissiveTexture and m.emissiveTexture.texture or -1] = true, + } + if type(x.textures) == "table" then + local props = {} + for prop in __iter(x.textures) do + table.insert(props, prop) + end + table.sort(props) + for _, prop in __iter(props) do + local ti = x.textures[prop] + if type(ti) == "number" and not linked[ti] and texIds[ti] then + linked[ti] = true + OP(texIds[ti], pid, prop) + end + end + end + end + + -- ------------------------------------------------------------------------------------------ models + local modelIds= {} + local skip= {} + local attrHost= {} -- orientation node -> its parent node (the attribute moves there) + local parentOf= {} + for i, nd in __iter(nodes) do + for _, c in __iter(nd.children or {}) do + if parentOf[c] == nil and c ~= i then + parentOf[c] = i + end + end + end + local jointSet= {} + for _, s in __iter(scene.skins or {}) do + for _, j in __iter(s.joints) do + jointSet[j] = true + end + end + for i, nd in __iter(nodes) do + local o = nd.extras and (nd.extras ).fbx and (nd.extras ).fbx.orientation + local p = parentOf[i] + if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then + skip[i] = true + attrHost[i] = p + end + end + -- world matrices (rest pose) for clusters and the bind pose + local worldM= {} + local visiting= {} + local function world(i) +if worldM[i] then + return worldM[i] + end + if visiting[i] then + return Mat4.identity() + end + visiting[i] = true + local nd = nodes[i] + local l = (nd.matrix and #(nd.matrix ) == 16 and{nd.matrix }or{(Mat4.compose(nd.translation, nd.rotation, nd.scale) +)})[1] local p = parentOf[i] + local w = (p and{(Mat4.mul(world(p), l) )}or{l +})[1] worldM[i] = w + return w + end + local function trs(nd) +if nd.matrix and #(nd.matrix ) == 16 then + return Mat4.decompose(nd.matrix) + end + return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } + end + local function model(name, sub, t, r, s) +local mid = id() + add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, { + N("Version", "I", { 232 }), + N("Properties70", "", {}, { + Penum("RotationOrder", 0), + Penum("InheritType", 1), + Pint("DefaultAttributeIndex", 0), + Pvec("Lcl Translation", "Lcl Translation", "", t), + Pvec("Lcl Rotation", "Lcl Rotation", "", r), + Pvec("Lcl Scaling", "Lcl Scaling", "", s), + }), + N("Shading", "C", { true }), + N("Culling", "S", { "CullingOff" }), + })) + return mid + end + local function attribute(nd, mid, nodeName) + if nd.camera and scene.cameras[nd.camera] then + local c = scene.cameras[nd.camera] + local aid = id() + local aspect = c.aspect or 4 / 3 + local fh = 0.612 + local fw = fh * aspect + local props + if c.type == "orthographic" then + props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) } + else + local yfov = c.yfov or 0.8 + local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect) + local focal = fw * 25.4 / (2 * math.tan(hfov / 2)) + props = { + Penum("CameraProjectionType", 0), + Penum("ApertureMode", 1), + P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi), + P("FocalLength", "Number", "", "A", "D", focal), + Pdouble("FilmWidth", fw), + Pdouble("FilmHeight", fh), + Penum("AspectRatioMode", 0), + Pdouble("AspectWidth", aspect * 100), + Pdouble("AspectHeight", 100), + Pdouble("NearPlane", c.znear or 0.1), + Pdouble("FarPlane", c.zfar or 1000), + } + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Camera" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + elseif nd.light and scene.lights[nd.light] then + local l = scene.lights[nd.light] + local aid = id() + local lt = l.type == "directional" and 1 or(l.type == "spot" and 2 or 0 +) local props = { + Penum("LightType", lt), + Pcolor("Color", l.color or { 1, 1, 1 }), + Pnum("Intensity", (l.intensity or 1) * 100), + P("CastLight", "bool", "", "", "I", 1), + } + if lt == 2 then + table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi)) + table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi)) + end + if l.range then + table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1)) + table.insert(props, Pnum("FarAttenuationEnd", l.range)) + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Light" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + end + end + for i, nd in __iter(nodes) do + if not skip[i] then + local t, r, s = trs(nd) + local euler = Mat4.eulerXYZ(r) + local ftype = nd.extras and (nd.extras ).fbx and (nd.extras ).fbx.type + local sub = nd.mesh and"Mesh" or((jointSet[i] or ftype == "LimbNode" )and"LimbNode" or"Null" +) -- an orientation child folded into this node gives it its attribute + local folded= nil + for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) + if host == i then + folded = c + end + end + if not nd.mesh and folded then + sub = nodes[folded].camera and"Camera" or"Light" + end + local mid = model(nd.name or ("Node" .. i), sub, t, euler, s) + modelIds[i] = mid + if sub == "LimbNode" then + local aid = id() + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) })) + OO(aid, mid) + end + if folded then + attribute(nodes[folded], mid, nd.name or "") + end + if nd.camera or nd.light then + -- a glTF-oriented camera / light: an FBX-oriented child model carries it + local kind = nd.camera and"camera" or"light" + local cmid = model((nd.name or "") .. "_" .. kind, nd.camera and"Camera" or"Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 }) + OO(cmid, mid) + attribute(nd, cmid, nd.name or "") + end + end + end + for i in __iter(nodes) do + local mid = modelIds[i] + if mid then + local p = parentOf[i] + local pm = p and modelIds[p] + OO(mid, pm or 0) + end + end + + -- ------------------------------------------------------------------------------------------ geometry + local geoIds= {} + local geoSlots= {} -- mesh -> material indices by slot + local geoVerts= {} + local geoChannels= {} -- mesh index -> blend shape channel ids (for weights animation) + local geoCount= {} + local function geometry(mi) +if geoIds[mi] then + return geoIds[mi] + end + local mesh = scene.meshes[mi] + if not mesh then + return nil + end + local V, PVI, NRM, MATS = {}, {}, {}, {} + local UV= {} + local UVI= {} + local COL= {} + local COLI= {} + local slots= {} + local slotOf= {} + local hasN = false + local nuv, ncol = 0, 0 + for _, prim in __iter(mesh.primitives) do + for k = 0, 7 do + if prim.attributes["TEXCOORD_" .. k] then + nuv = math.max(nuv, k + 1) + end + if prim.attributes["COLOR_" .. k] then + ncol = math.max(ncol, k + 1) + end + end + if prim.attributes.NORMAL then + hasN = true + end + end + for k = 1, nuv do + UV[k], UVI[k] = {}, {} + end + for k = 1, ncol do + COL[k], COLI[k] = {}, {} + end + local layout = {} + local offset = 0 + for _, prim in __iter(mesh.primitives) do + local fs = faces(prim) + local pos = prim.attributes.POSITION + local R = accessorReader(pos) + if fs and R and pos then + table.insert(layout, { prim = prim, offset = offset }) + local n = pos.count + for v = 0, n - 1 do + table.insert(V, R(v, 0)) + table.insert(V, R(v, 1)) + table.insert(V, R(v, 2)) + end + local NR = accessorReader(prim.attributes.NORMAL) + if hasN then + for v = 0, n - 1 do + if NR then + table.insert(NRM, NR(v, 0)) + table.insert(NRM, NR(v, 1)) + table.insert(NRM, NR(v, 2)) + else + table.insert(NRM, 0) + table.insert(NRM, 0) + table.insert(NRM, 1) + end + end + end + local uvBase= {} + for k = 1, nuv do + uvBase[k] = math.floor(#UV[k] / 2 +) local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)]) + for v = 0, n - 1 do + local u, w = 0, 0 + if T then + u, w = T(v, 0), (T(v, 1)) + end + table.insert(UV[k], u) + table.insert(UV[k], (flipV and((1 - w ))or(w))) + end + end + local colBase= {} + for k = 1, ncol do + colBase[k] = math.floor(#COL[k] / 4 +) local acc = prim.attributes["COLOR_" .. (k - 1)] + local C = accessorReader(acc) + local comps = acc and acc.components or 4 + for v = 0, n - 1 do + table.insert(COL[k], (C and{(C(v, 0) )}or{1})[1]) + table.insert(COL[k], (C and{(C(v, 1) )}or{1})[1]) + table.insert(COL[k], (C and{(C(v, 2) )}or{1})[1]) + table.insert(COL[k], (C and comps >= 4 and{(C(v, 3) )}or{1})[1]) + end + end + local mat = prim.material or 0 + local slot = slotOf[mat] + if slot == nil then + table.insert(slots, mat) + slot = #slots - 1 + slotOf[mat] = slot + end + for _, f in __iter(fs) do + for q, v in __iter(f) do + local cp = v + offset + table.insert(PVI, (q == #f and((-cp - 1 ))or(cp))) + for k = 1, nuv do + table.insert(UVI[k], uvBase[k] + v) + end + for k = 1, ncol do + table.insert(COLI[k], colBase[k] + v) + end + end + table.insert(MATS, slot) + end + offset =offset+ n + end + end + if #PVI == 0 then + return nil + end + local gid = id() + local ch= { + N("Properties70", "", {}, {}), + N("GeometryVersion", "I", { 124 }), + N("Vertices", "", { arr("d", V) }), + N("PolygonVertexIndex", "", { arr("i", PVI) }), + } + local layer0= { N("Version", "I", { 100 }) } + if hasN then + table.insert(ch, N("LayerElementNormal", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { "ByVertice" }), + N("ReferenceInformationType", "S", { "Direct" }), + N("Normals", "", { arr("d", NRM) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) })) + end + local extraLayers= {} + local uvNames = mesh.extras and (mesh.extras ).fbx and (mesh.extras ).fbx.uvSets or {} + for k = 1, nuv do + table.insert(ch, N("LayerElementUV", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { (type(uvNames[k]) == "string" and{uvNames[k] }or{(k == 1 and"UVMap" or"UVMap" .. k) })[1]}), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("UV", "", { arr("d", UV[k]) }), + N("UVIndex", "", { arr("i", UVI[k]) }), + })) + local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) }) + if k == 1 then + table.insert(layer0, le) + else + table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le })) + end + end + for k = 1, ncol do + table.insert(ch, N("LayerElementColor", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "Col" .. ((k > 1 and{(tostring(k) )}or{""})[1]) }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Colors", "", { arr("d", COL[k]) }), + N("ColorIndex", "", { arr("i", COLI[k]) }), + })) + if k == 1 then + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) })) + end + end + local anyMat = false + for _, m in __iter(slots) do + if m ~= 0 and matIds[m] then + anyMat = true + end + end + if anyMat then + local allSame = #slots == 1 + table.insert(ch, N("LayerElementMaterial", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { allSame and"AllSame" or"ByPolygon" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Materials", "", { arr("i", allSame and{ 0 } or MATS) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) })) + end + table.insert(ch, N("Layer", "I", { 0 }, layer0)) + for _, l in __iter(extraLayers) do + table.insert(ch, l) + end + add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch)) + geoIds[mi] = gid + geoSlots[mi] = (anyMat and{slots }or{{} +})[1] geoVerts[mi] = layout + geoCount[mi] = offset + -- morph targets + local prims = mesh.primitives + local ntargets = 0 + for _, l in __iter(layout) do + ntargets = math.max(ntargets, (l.prim.targets and((#(l.prim.targets ) ))or(0))) + end + if ntargets > 0 then + local bsid = id() + add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) })) + OO(bsid, gid) + local names = mesh.extras and (mesh.extras ).targetNames or {} + for t = 1, ntargets do + local IDX, DV, DN = {}, {}, {} + local anyN = false + for _, l in __iter(layout) do + local tg = l.prim.targets and (l.prim.targets )[t] + if tg and tg.NORMAL then + anyN = true + end + end + for _, l in __iter(layout) do + local tg = l.prim.targets and (l.prim.targets )[t] + local TP= tg and accessorReader(tg.POSITION) + local TN= tg and accessorReader(tg.NORMAL) + if TP then + for v = 0, l.prim.attributes.POSITION.count - 1 do + local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) + local nx, ny, nz = 0, 0, 0 + if TN then + nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2) + end + if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then + table.insert(IDX, l.offset + v) + table.insert(DV, x) + table.insert(DV, y) + table.insert(DV, z) + if anyN then + table.insert(DN, nx) + table.insert(DN, ny) + table.insert(DN, nz) + end + end + end + end + end + local tname = (type(names[t]) == "string" and{names[t] }or{("Target" .. t) +})[1] local chid, shid = id(), id() + local w = mesh.weights and mesh.weights[t] or 0 + add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, { + N("Version", "I", { 100 }), + N("DeformPercent", "D", { w * 100 }), + N("FullWeights", "", { arr("d", { 100 }) }), + N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }), + })) + local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) } + if anyN then + table.insert(shch, N("Normals", "", { arr("d", DN) })) + end + add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch)) + OO(chid, bsid) + OO(shid, chid) + local gc= geoChannels + gc[mi] = gc[mi] or {} + gc[mi][t] = chid + end + end + local _ = prims + return gid + end + + local poseNodes= {} + local posed= {} + local function pose(mid, m) + if posed[mid] then + return + end + posed[mid] = true + table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) })) + end + local skinned= {} + for i, nd in __iter(nodes) do + local mid = modelIds[i] + if nd.mesh and mid then + local gid = geometry(nd.mesh) + if gid then + OO(gid, mid) + for _, m in __iter(geoSlots[nd.mesh]) do + local pm = matIds[m] + if pm then + OO(pm, mid) + end + end + -- skin: one Skin per (geometry, skin) + local skin = nd.skin and scene.skins[nd.skin] + local key = tostring(gid) .. ":" .. tostring(nd.skin) + if skin and not skinned[key] then + skinned[key] = true + local sid = id() + add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) })) + OO(sid, gid) + local meshWorld = world(i) + pose(mid, meshWorld) + local ibm = accessorReader(skin.inverseBindMatrices) + -- per joint: control points and weights + local perJoint= {} + for j in __iter(skin.joints) do + perJoint[j] = { idx = {}, w = {} } + end + for _, l in __iter(geoVerts[nd.mesh]) do + local J = accessorReader(l.prim.attributes.JOINTS_0) + local W = accessorReader(l.prim.attributes.WEIGHTS_0) + if J and W then + for v = 0, l.prim.attributes.POSITION.count - 1 do + for q = 0, 3 do + local j, w = J(v, q), W(v, q) + local pj = perJoint[j + 1] + if w > 0 and pj then + table.insert(pj.idx, l.offset + v) + table.insert(pj.w, w) + end + end + end + end + end + for j, ji in __iter(skin.joints) do + local jm = modelIds[ji] + if jm then + local IB = Mat4.identity() + if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then + for k = 1, 16 do + IB[k] = ibm(j - 1, k - 1) + end + end + local inv = Mat4.inverse(IB) or Mat4.identity() + local link = Mat4.mul(meshWorld, inv) + local cid = id() + add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { + N("Version", "I", { 100 }), + N("UserData", "SS", { "", "" }), + N("Indexes", "", { arr("i", perJoint[j].idx) }), + N("Weights", "", { arr("d", perJoint[j].w) }), + N("Transform", "", { arr("d", meshWorld) }), + N("TransformLink", "", { arr("d", link) }), + })) + OO(cid, sid) + OO(jm, cid) + pose(jm, link) + end + end + end + end + end + end + if #poseNodes > 0 then + local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) } + for _, pn in __iter(poseNodes) do + table.insert(pch, pn) + end + add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch)) + end + + -- ------------------------------------------------------------------------------------------ animations + local tmin, tmax = math.huge, -math.huge + local function curveNode(name, layer, target, prop, comps, times, labels, step) + local cnid = id() + local p = {} + for k, lab in __iter(labels) do + table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0)) + end + add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) })) + OO(cnid, layer) + OP(cnid, target, prop) + local ticks = table.create(#times, 0) + for k, t in __iter(times) do + ticks[k] = math.floor(t * TICKS + 0.5) + end + for k, lab in __iter(labels) do + local cid = id() + local df = buffer.create(32) + buffer.writeu32(df, 8, 218434821) + local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) } + buffer.writef64(dfa.data, 16, buffer.readf32(df, 8)) + add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, { + N("Default", "D", { comps[k][1] or 0 }), + N("KeyVer", "I", { 4009 }), + N("KeyTime", "", { arr("l", ticks) }), + N("KeyValueFloat", "", { arr("f", comps[k]) }), + N("KeyAttrFlags", "", { arr("i", { step and 0x00000002 or 0x00000104 }) }), + N("KeyAttrDataFloat", "", { dfa }), + N("KeyAttrRefCount", "", { arr("i", { #times }) }), + })) + OP(cid, cnid, "d|" .. lab) + end + end + local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } + for ai, anim in __iter(scene.animations or {}) do + local stid, lid = id(), id() + local astart, astop= math.huge, -math.huge + local layerNodes = {} + for _, ch in __iter(anim.channels) do + local mid = modelIds[ch.node] + local IN = accessorReader(ch.input) + local OUT = accessorReader(ch.output) + local spec = PATH[ch.path] + if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then + local n = ch.input.count + local times = table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = IN(k, 0) + astart, astop = math.min(astart, times[k + 1]), (math.max(astop, times[k + 1])) + end + local cubic = ch.interpolation == "CUBICSPLINE" + local step = ch.interpolation == "STEP" + if spec then + local comps = spec[3] + local function val(k, c) +local e = (cubic and((k * 3 + 1 ))or(k +)) if e >= ch.output.count then + return 0 + end + return OUT(e, c) + end + local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0) + local prev= nil + for k = 0, n - 1 do + local v + if comps == 4 then + local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) } + local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if ql > 0 then + q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } + else + q = { 0, 0, 0, 1 } + end + v = Mat4.eulerXYZ(q) + if prev then + for a = 1, 3 do + while v[a] - prev[a] > 180 do + v[a]=v[a]- 360 + end + while v[a] - prev[a] < -180 do + v[a]=v[a]+ 360 + end + end + end + prev = v + else + v = { val(k, 0), val(k, 1), val(k, 2) } + end + X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3] + end + table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) + else + -- weights: one DeformPercent curve per blend shape channel of the node's mesh + local nd = nodes[ch.node] + local gc= geoChannels + local chans = nd.mesh and gc[nd.mesh] + if chans then + local nt = #chans + for t = 1, nt do + local vals = table.create(n, 0) + for k = 0, n - 1 do + local e = (cubic and(((k * 3 + 1) * nt + (t - 1) ))or((k * nt + (t - 1) +))) vals[k + 1] = (e < ch.output.count and{(OUT(e, 0) * 100 )}or{0 +})[1] end + table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step }) + end + end + end + end + end + if astart > astop then + astart, astop = 0, 0 + end + tmin, tmax = math.min(tmin, astart), math.max(tmax, astop) + add("AnimationStack", N("AnimationStack", "LSS", { stid, cls((anim.name and anim.name ~= "" and{anim.name }or{("Animation" .. ai)})[1], "AnimStack"), "" }, { + N("Properties70", "", {}, { + Ptime("LocalStart", math.floor(astart * TICKS + 0.5)), + Ptime("LocalStop", math.floor(astop * TICKS + 0.5)), + Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)), + Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)), + }), + })) + add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) })) + OO(lid, stid) + for _, ln in __iter(layerNodes) do + curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8]) + end + end + if tmin > tmax then + tmin, tmax = 0, 0 + end + + -- ------------------------------------------------------------------------------------------ document + local meta= scene.meta or {} + local src= type(meta.source) == "table" and meta.source or {} + local up = meta.up == "z" and 2 or 1 + local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 + if up == 2 then + front, frontSign = 1, -1 + end + if src.format == "fbx" and src.upAxis == up then + upSign = src.upAxisSign or upSign + front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign + coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign + end + local unitScale = (type(meta.unit) == "number" and meta.unit > 0 and((meta.unit * 100 ))or(1 +)) local creator = opts and opts.creator or "rosetta" + local defs= { N("Version", "I", { 100 }) } + local total = 1 + local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" } + for _, c in __iter(CLASSES) do + total =total+ (counts[c] or 0 +) end + table.insert(defs, N("Count", "I", { total })) + table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) })) + for _, c in __iter(CLASSES) do + if counts[c] then + table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) })) + end + end + local docId = id() + local root= { name = "", props = {}, children = { + N("FBXHeaderExtension", "", {}, { + N("FBXHeaderVersion", "I", { 1003 }), + N("FBXVersion", "I", { opts and opts.version or 7400 }), + N("CreationTimeStamp", "", {}, { + N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }), + N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }), + }), + N("Creator", "S", { creator }), + }), + N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }), + N("CreationTime", "S", { "1970-01-01 10:00:00:000" }), + N("Creator", "S", { creator }), + N("GlobalSettings", "", {}, { + N("Version", "I", { 1000 }), + N("Properties70", "", {}, { + Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign), + Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign), + Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale), + P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0), + P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"), + Penum("TimeMode", 6), + Penum("TimeProtocol", 2), + Penum("SnapOnFrameMode", 0), + Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)), + Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)), + Pdouble("CustomFrameRate", -1), + }), + }), + N("Documents", "", {}, { + N("Count", "I", { 1 }), + N("Document", "LSS", { docId, "Scene", "Scene" }, { + N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }), + N("RootNode", "L", { 0 }), + }), + }), + N("References", "", {}, {}), + N("Definitions", "", {}, defs), + N("Objects", "", {}, objects), + N("Connections", "", {}, conns), + N("Takes", "", {}, { N("Current", "S", { "" }) }), + } } + local _ = Err + return root, nil +end + +return Write +end +__FILES["model/fbx/Xform"] = function() +--!strict +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model +-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The +-- matrix / quaternion arithmetic is codecs/model/Mat4. +local Mat4 = __include("codecs/model/Mat4") + +local Xform = {} + +-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ) +local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } +function Xform.euler(x, y, z, order) +return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") +end +-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers + + + + + + +local function isZero(v) +return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +function Xform.localMatrix(p) +local m = Mat4.translation(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) + if not isZero(p.Rpre) then + m = Mat4.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + end + m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + if not isZero(p.Rpost) then + -- the inverse of a rotation is its transpose + m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) + end + m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) + m = Mat4.mul(m, Mat4.scaling(p.S[1], p.S[2], p.S[3])) + if not isZero(p.Sp) then + m = Mat4.mul(m, Mat4.translation(-p.Sp[1], -p.Sp[2], -p.Sp[3])) + end + return m +end + +return Xform +end +__FILES["model/gltf"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and +-- binary (.glb). New code. +-- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every +-- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR +-- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior, +-- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept, +-- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime, +-- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins, +-- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a +-- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer. +-- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths). +-- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes <name>.bin and the +-- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension). +-- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the +-- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back +-- uncompressed (the extension is dropped). +-- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels +-- (skipped and counted in the animation's extras). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Json = __include("codecs/text/Json") +local Base64 = __include("core/Base64") +local Read = __include("model/gltf/Read") +local Write = __include("model/gltf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Gltf = { + name = "gltf", + category = "model", + extensions = { "gltf", "glb" }, + mime = { "model/gltf+json", "model/gltf-binary" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +local GLB_MAGIC = 0x46546C67 -- "glTF" +local CHUNK_JSON = 0x4E4F534A +local CHUNK_BIN = 0x004E4942 + +-- ------------------------------------------------------------------------------------------------ sniff +function Gltf.sniff(r) +if r:peek(4) == "glTF" then + return 1 + end + local head = r:peek(1024) + local s = Sniff.dropBom(head) + if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then + return 0.9 + end + if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts) +return function(uri) +if not opts then + return nil + end + local decoded = string.gsub(uri, "%%(%x%x)", function(h) +return string.char((tonumber(h, 16) )) + end) + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[decoded] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1] end +end + +-- the JSON text and BIN chunk of a GLB +local function glb(r) +local magic, version, length = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, nil, r.err + end + if magic ~= GLB_MAGIC then + return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic") + end + if version ~= 2 then + return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version) + end + if length > r:size() then + return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8) + end + local json= nil + local bin= nil + while r:tell() + 8 <= length do + local clen, ctype = r:u32le(), r:u32le() + if clen > length - r:tell() then + return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8) + end + if ctype == CHUNK_JSON and json == nil then + json = r:string(clen) + elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then + bin = r:bytes(clen) + else + r:skip(clen) + end + if r.err then + return nil, nil, r.err + end + end + if not json then + return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk") + end + return json, bin, nil +end + +function Gltf.decode(r, opts) +local binary = r:peek(4) == "glTF" + local text, bin +if binary then + local t, b, err = glb(r) + if not t then + return nil, err + end + text, bin = t, b + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, jerr = Json.decode(text ) + if doc == nil then + return nil, jerr + end + local scene, err = Read.scene(doc, bin, fetcher(opts), opts) + if not scene then + return nil, err + end + scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local EXT= { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" } + +function Gltf.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local binary = opts and (opts.binary or opts.format == "glb") or false + local external = opts and opts.external == true and type(opts.files) == "table" and not binary + local embedImages = (opts and opts.embedImages ~= nil and{opts.embedImages }or{(not external +)})[1] local out, err = Write.build(scene, { binary = binary, embedImages = embedImages }) + if not out then + return nil, err + end + local doc = out.doc + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local files = opts and opts.files + -- images: data: URIs, or files + if doc.images then + local n = 0 + for _, im in __iter(doc.images) do + if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then + for _, o in __iter(out.images) do + if o.name == im.uri then + if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then + im.uri = Base64.dataUri(o.data, o.mime or "image/png") + else + n =n+ 1 + local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png") + files[fname] = o.data + im.uri = fname + end + break + end + end + elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then + for _, o in __iter(out.images) do + if o.name == im.uri then + files[im.uri] = o.data + end + end + end + end + end + local binLen = buffer.len(out.bin) + if binLen > 0 then + local b = Types.object() + b.byteLength = binLen + if not binary then + if external then + local fname = base .. ".bin" + b.uri = fname + local ff= files + ff[fname] = out.bin + else + b.uri = Base64.dataUri(out.bin, "application/octet-stream") + end + end + doc.buffers = { b } + end + local text, jerr = Json.encode(doc, (binary and{nil }or{{ indent = 2 }})[1]) + if not text then + return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr)) + end + if not binary then + return buffer.fromstring(text ), nil + end + local jpad = (4 - #(text ) % 4) % 4 + local bpad = (4 - binLen % 4) % 4 + local w = Bytes.writer(12 + 8 + #(text ) + jpad + 8 + binLen + bpad) + w:u32le(GLB_MAGIC) + w:u32le(2) + local lenAt = w:tell() + w:u32le(0) + w:u32le(#(text ) + jpad) + w:u32le(CHUNK_JSON) + w:string(text ) + w:string(string.rep(" ", jpad)) + if binLen > 0 then + w:u32le(binLen + bpad) + w:u32le(CHUNK_BIN) + w:bytes(out.bin) + w:fill(0, bpad) + end + w:setU32le(lenAt, w:tell()) + return w:finish(), nil +end + +return Gltf +end +__FILES["model/gltf/Pack"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene +-- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range +-- first (offsets, strides and counts against the buffer lengths); nothing here throws. +local Pack = {} + +local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32 + +-- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is +-- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem = +-- cols * colBytes bytes each) +function Pack.gather(dst, src, off, count, elem, stride, cols, colBytes, colStride) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, 0, src, off, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, i * elem, src, off + i * stride, elem) + end + return + end + for i = 0, count - 1 do + local s = off + i * stride + local d = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colBytes, src, s + c * colStride, colBytes) + end + end +end + +-- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled) +function Pack.scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride) + if cols == 1 or colBytes == colStride then + if stride == elem then + bcopy(dst, at, src, 0, count * elem) + return + end + for i = 0, count - 1 do + bcopy(dst, at + i * stride, src, i * elem, elem) + end + return + end + for i = 0, count - 1 do + local d = at + i * stride + local s = i * elem + for c = 0, cols - 1 do + bcopy(dst, d + c * colStride, src, s + c * colBytes, colBytes) + end + end +end + +-- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element +-- idx[k] of dst becomes value k (values packed, elem bytes each) +function Pack.sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) +for k = 0, n - 1 do + local i + if idxSize == 1 then + i = readu8(idx, idxOff + k) + elseif idxSize == 2 then + i = readu16(idx, idxOff + k * 2) + else + i = readu32(idx, idxOff + k * 4) + end + if i >= count then + return false + end + bcopy(dst, i * elem, values, valOff + k * elem, elem) + end + return true +end + +return Pack +end +__FILES["model/gltf/Read"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type +-- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution, +-- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the +-- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the +-- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets, +-- scenes. glTF extras and unhandled extensions are kept in <object>.extras.gltf = { extras, extensions }. +local Err = __include("core/Err") +local Types = __include("Types") +local Base64 = __include("core/Base64") +local Pack = __include("model/gltf/Pack") +local Draco = __include("codecs/model/Draco") + +local Read = {} + +local COMPONENT= { + [5120] = { "i8", "snorm8" }, + [5121] = { "u8", "unorm8" }, + [5122] = { "i16", "snorm16" }, + [5123] = { "u16", "unorm16" }, + [5125] = { "u32", "" }, + [5126] = { "f32", "" }, +} +local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 } +local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 } +local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 } +local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" } +local WRAP= { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" } +local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" } +-- the extensions this reader understands (everything else that is required -> UNSUPPORTED) +local KNOWN = { + KHR_lights_punctual = true, + KHR_mesh_quantization = true, + KHR_texture_transform = true, + KHR_materials_emissive_strength = true, + KHR_materials_unlit = true, + KHR_materials_clearcoat = true, + KHR_materials_transmission = true, + KHR_materials_volume = true, + KHR_materials_ior = true, + KHR_materials_specular = true, + KHR_materials_sheen = true, + KHR_materials_iridescence = true, + KHR_materials_anisotropy = true, + KHR_materials_dispersion = true, + KHR_materials_diffuse_transmission = true, + KHR_materials_variants = true, + KHR_materials_pbrSpecularGlossiness = true, + KHR_texture_basisu = true, -- the image stays encoded (image/ktx2) + EXT_texture_webp = true, + EXT_texture_avif = true, + KHR_node_visibility = true, + KHR_xmp_json_ld = true, + KHR_draco_mesh_compression = true, +} +Read.KNOWN = KNOWN + + + + + +local function num(v, default) +return (type(v) == "number" and{v }or{default +})[1]end +local function int(v) +return (type(v) == "number" and v == math.floor(v) and v >= 0 and{v }or{nil +})[1]end +local function arr(v) +return (type(v) == "table" and{v }or{{} +})[1]end +local function str(v) +return (type(v) == "string" and{v }or{nil +})[1]end +local function numbers(v, n) +if type(v) ~= "table" or #v ~= n then + return nil + end + for i = 1, n do + if type(v[i]) ~= "number" then + return nil + end + end + return table.move(v, 1, n, 1, {} ) +end + +-- extras.gltf: the JSON extras and the extensions not turned into Scene fields +local function keep(obj, handled) +local extras = obj.extras + local ext= nil + if type(obj.extensions) == "table" then + for k, v in __iter(obj.extensions) do + if not (handled and handled[k]) then + ext = ext or {} + local e= ext + e[k] = v + end + end + end + if extras == nil and ext == nil then + return nil + end + return { gltf = { extras = extras, extensions = ext } } +end + +-- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value +-- by value: normalized integers <-> floats, ints widened or narrowed) +local DRACO_HANDLED = { KHR_draco_mesh_compression = true } +local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } +local DRACO_SAME= { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } +local DRACO_WRITE= { i8 = buffer.writei8, u8 = buffer.writeu8, i16 = buffer.writei16, u16 = buffer.writeu16, i32 = buffer.writei32, u32 = buffer.writeu32, f32 = buffer.writef32 } +local NORM_MAX= { u8 = 255, i8 = 127, u16 = 65535, i16 = 32767, u32 = 4294967295, i32 = 2147483647 } +local function dracoAccessor(da, acc, n) +if da.components ~= acc.components or not DRACO_SIZE[da.type] then + return nil + end + local out = Types.Scene.accessor(nil, acc.type, acc.components, n) + out.name = acc.name + if DRACO_SAME[acc.type] == da.type then + out.data = da.data + return out + end + local reader = Types.Scene.reader({ data = da.data, type = da.type , components = da.components, count = n }) + local size = Types.COMPONENT_SIZE[acc.type] + local norm = string.match(acc.type, "^[us]norm") ~= nil + local base= DRACO_SAME[acc.type] or acc.type + local wr = DRACO_WRITE[base] + local dmax = NORM_MAX[base] or 1 + if not reader or not wr or not size then + return nil + end + local get = reader +local w = wr +local stride = size * acc.components + local function put(v, c, x) + if base ~= "f32" then + if norm then + x = math.clamp(x, (base == "u8" or base == "u16" )and 0 or-1, 1) * dmax + end + x = math.floor(x + 0.5) + end + w(out.data, v * stride + c * size, x) + end + local srcMax = (da.normalized and{NORM_MAX[da.type] }or{nil +})[1] for v = 0, n - 1 do + for c = 0, da.components - 1 do + local x = get(v, c) + if srcMax then + x = math.max(x / srcMax, -1) + end + put(v, c, x) + end + end + return out +end + +function Read.scene(doc, bin, fetch, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if type(doc) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the JSON is not an object") + end + local asset = doc.asset + if type(asset) ~= "table" or type(asset.version) ~= "string" then + return nil, Err.new(Err.CORRUPT, "no asset.version") + end + if string.sub(asset.version, 1, 1) ~= "2" then + return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)") + end + for _, e in __iter(arr(doc.extensionsRequired)) do + if type(e) == "string" and not KNOWN[e] then + return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e) + end + end + local scene = Types.Scene.new() + -- buffers + local buffers= {} + local total = 0 + for i, b in __iter(arr(doc.buffers)) do + if type(b) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1)) + end + local len = int(b.byteLength) + if not len then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength") + end + total =total+ len + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes") + end + local data= nil + local uri = str(b.uri) + if uri == nil then + if i == 1 and bin then + data = bin + else + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk") + end + elseif string.sub(uri, 1, 5) == "data:" then + local d, derr = Base64.decodeDataUri(uri) + if not d then + return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr)) + end + data = d + else + data = fetch(uri) + if not data then + return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)") + end + end + if buffer.len(data ) < len then + return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength") + end + buffers[i] = data +end + -- buffer views -> { buf, offset, length, stride } + local views= {} + for i, v in __iter(arr(doc.bufferViews)) do + if type(v) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1)) + end + local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength) + local b = bi and buffers[bi + 1] + if not b or not off or not len or off + len > buffer.len(b) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range") + end + local stride = v.byteStride + if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then + return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride") + end + views[i] = { buf = b, offset = off, length = len, stride = stride } + end + -- accessors + local accessors= {} + for i, a in __iter(arr(doc.accessors)) do + local label = "accessor " .. (i - 1) + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad " .. label) + end + local ct, count, typ = a.componentType, int(a.count), a.type + local names = COMPONENT[ct] + local comps = TYPE_COMPONENTS[typ] + if not names or not count or not comps then + return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type") + end + local normalized = a.normalized == true + local tname = (normalized and{names[2] }or{names[1] +})[1] if tname == "" then + return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1]) + end + local size = SIZE[ct] + local cols = TYPE_COLUMNS[typ] or 1 + local rows = math.floor(comps / cols +) local colBytes = rows * size + local colStride = (cols > 1 and((math.floor((colBytes + 3) / 4 )* 4 ))or(colBytes +)) local elem = comps * size + local padded = cols * colStride + if count * elem > maxBytes then + return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes") + end + local data = buffer.create(count * elem) + local vi = a.bufferView + if vi ~= nil then + local view = int(vi) and views[vi + 1] + if not view then + return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView") + end + local off = int(a.byteOffset or 0) + if not off then + return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset") + end + local stride = view.stride or padded + if stride < padded and count > 1 then + return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element") + end + if count > 0 and off + (count - 1) * stride + padded > view.length then + return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView") + end + if count > 0 then + Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride) + end + end + local sp = a.sparse + if type(sp) == "table" then + local n = int(sp.count) + local si, sv = sp.indices, sp.values + if not n or type(si) ~= "table" or type(sv) ~= "table" then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse") + end + local isz = SIZE[si.componentType] + local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1] + local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0) + local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125 + if not okType or not isz or not iv or not vv or not io or not vo then + return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values") + end + if io + n * isz > iv.length or vo + n * elem > vv.length then + return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView") + end + -- sparse values are tightly packed (matrices: padded columns, rare enough to repack first) + local vals, valOff = vv.buf, vv.offset + vo + if cols > 1 and colBytes ~= colStride then + vals = buffer.create(n * elem) + Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride) + valOff = 0 + end + if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then + return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range") + end + end + local acc = Types.Scene.accessor(data, tname, comps, count) + if cols > 1 then + acc.matrix = true + end + acc.name = str(a.name) + accessors[i] = acc + end + local function accessor(v) +local k = int(v) + return (k and{accessors[k + 1] }or{nil +})[1] end + -- images (kept encoded), samplers, textures + local images= {} + for i, im in __iter(arr(doc.images)) do + if type(im) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1)) + end + local img= { mime = str(im.mimeType), name = str(im.name) } + if im.bufferView ~= nil then + local view = int(im.bufferView) and views[im.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView") + end + local d = buffer.create(view.length) + buffer.copy(d, 0, view.buf, view.offset, view.length) + img.data = d + elseif type(im.uri) == "string" then + if string.sub(im.uri, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(im.uri) + if d then + img.data = d + img.mime = img.mime or mime + end + else + img.uri = im.uri + img.data = fetch(im.uri) + if not img.mime then + local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "") + img.mime = ext == "png" and"image/png" or((ext == "jpg" or ext == "jpeg" )and"image/jpeg" or(ext == "webp" and"image/webp" or(ext == "ktx2" and"image/ktx2" or nil +))) end + end + end + images[i] = img + end + local samplers= {} + for i, s in __iter(arr(doc.samplers)) do + if type(s) == "table" then + samplers[i] = { + wrapS = WRAP[s.wrapS] or ((s.wrapS == nil and{nil }or{"repeat"})[1]) , + wrapT = WRAP[s.wrapT] or ((s.wrapT == nil and{nil }or{"repeat"})[1]) , + filter = s.magFilter == 9728 and"nearest" or(s.magFilter == 9729 and"linear" or nil), + minFilter = MIN_FILTER[s.minFilter], + } + else + samplers[i] = {} + end + end + local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" } + for i, t in __iter(arr(doc.textures)) do + if type(t) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1)) + end + local src = t.source + local handled = {} + if type(t.extensions) == "table" then + for _, e in __iter(TEX_SOURCE_EXT) do + local x = t.extensions[e] + if type(x) == "table" and int(x.source) then + src = x.source + handled[e] = true + break + end + end + end + local img = int(src) and images[src + 1] + local tex= { name = str(t.name) } + if img then + tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri + tex.name = tex.name or img.name + end + local si = int(t.sampler) + if si and samplers[si + 1] then + tex.sampler = table.clone(samplers[si + 1]) + end + tex.extras = keep(t, handled) + if next(handled) then + -- the fallback image (t.source) and the extension name, for writing the texture back the same way + tex.extras = tex.extras or { gltf = {} } + local g = (tex.extras ).gltf + g.sourceExtension = next(handled) + local fb = int(t.source) and images[t.source + 1] + if fb then + g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri } + end + end + table.insert(scene.textures, tex) + end + -- materials + local function texRef(info) +if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then + return nil + end + local r= { texture = info.index + 1, texCoord = int(info.texCoord), scale = (type(info.scale) == "number" and{info.scale }or{nil})[1], strength = (type(info.strength) == "number" and{info.strength }or{nil })[1]} + local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform + if type(tt) == "table" then + r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = (type(tt.rotation) == "number" and{tt.rotation }or{nil})[1], texCoord = int(tt.texCoord) } + end + return r + end + -- an extension object with every textureInfo (a table with an index, under a key ending in Texture) -> TextureRef + local function convertExt(v) +if type(v) ~= "table" then + return v + end + local out = ((Types.isObject(v) or next(v) == nil )and{(Types.object() )}or{{} +})[1] for k, x in __iter(v) do + if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then + out[k] = texRef(x) + else + out[k] = convertExt(x) + end + end + return out + end + for i, m in __iter(arr(doc.materials)) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1)) + end + local mat = Types.Scene.material(str(m.name)) + local pbr = (type(m.pbrMetallicRoughness) == "table" and{m.pbrMetallicRoughness }or{{} +})[1] mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 } + mat.baseColorTexture = texRef(pbr.baseColorTexture) + mat.metallic = num(pbr.metallicFactor, 1) + mat.roughness = num(pbr.roughnessFactor, 1) + mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture) + mat.normalTexture = texRef(m.normalTexture) + mat.occlusionTexture = texRef(m.occlusionTexture) + mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 } + mat.emissiveTexture = texRef(m.emissiveTexture) + mat.alphaMode = m.alphaMode == "MASK" and"mask" or(m.alphaMode == "BLEND" and"blend" or"opaque" +) mat.alphaCutoff = num(m.alphaCutoff, 0.5) + mat.doubleSided = m.doubleSided == true + if type(m.extensions) == "table" then + local ext = {} + for k, v in __iter(m.extensions) do + ext[k] = convertExt(v) + end + mat.extensions = ext + end + local kept = keep(m, mat.extensions and (mat.extensions ) or {}) + local pk = keep(pbr, nil) + if pk then + kept = kept or { gltf = {} } + local kk= kept + kk.gltf.pbr = pk.gltf + end + mat.extras = kept + table.insert(scene.materials, mat) + end + -- meshes + for i, m in __iter(arr(doc.meshes)) do + if type(m) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1)) + end + local mesh= { name = str(m.name), primitives = {}, weights = (type(m.weights) == "table" and{(table.clone(m.weights) )}or{nil})[1], extras = keep(m, nil) } + for k, p in __iter(arr(m.primitives)) do + if type(p) ~= "table" or type(p.attributes) ~= "table" then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1)) + end + local pext = (type(p.extensions) == "table" and{p.extensions }or{nil +})[1] if pext and pext.EXT_meshopt_compression then + return nil, Err.new(Err.UNSUPPORTED, "meshopt compressed primitives (EXT_meshopt_compression)") + end + -- KHR_draco_mesh_compression: the attributes it lists and the indices come from the Draco data + local dext = pext and pext.KHR_draco_mesh_compression + local draco= nil + local dmap= {} + if dext ~= nil then + local view = type(dext) == "table" and int(dext.bufferView) and views[dext.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: draco: bad bufferView", i - 1, k - 1)) + end + local g, derr = Draco.decode(view.buf, view.offset, view.length, { maxPoints = math.floor(maxBytes / 4), maxFaces = math.floor(maxBytes / 12 )}) + if not g then + local e = derr +return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - 1, e.message)) + end + draco = g + for name, id in __iter(((type(dext.attributes) == "table" and{dext.attributes }or{{}})[1])) do + if type(name) == "string" and int(id) then + dmap[name] = id + end + end + end + local attrs= {} + local count = -1 + for name, ai in __iter(p.attributes) do + local a = accessor(ai) + if a and draco and dmap[name] then + local da = Draco.attribute(draco, dmap[name]) + a = (da and{(dracoAccessor(da, a, draco.numPoints) )}or{nil +})[1] end + if not a then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) + end + if count >= 0 and a.count ~= count then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1)) + end + count = a.count + attrs[name] = a + end + local mode = MODES[p.mode == nil and 4 or p.mode] + if not mode then + return nil, Err.new(Err.CORRUPT, "bad primitive mode") + end + local prim= { attributes = attrs, mode = mode , material = (int(p.material) and p.material < #scene.materials and((p.material + 1 ))or(nil ))} + if draco then + if draco.kind == "mesh" then + prim.indices = Types.Scene.accessor(draco.indices, "u32", 1, draco.numFaces * 3) + prim.mode = "triangles" + else + prim.mode = "points" + end + elseif p.indices ~= nil then + local ind = accessor(p.indices) + if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then + return nil, Err.new(Err.CORRUPT, "bad indices accessor") + end + -- indices must reference existing vertices + local get = (Types.Scene.reader(ind ) ) +for q = 0, ind.count - 1 do + if get(q, 0) >= count then + return nil, Err.new(Err.CORRUPT, "index out of range") + end + end + prim.indices = ind +end + if type(p.targets) == "table" then + local targets = {} + for ti, t in __iter(p.targets) do + local tt = {} + for name, ai in __iter(((type(t) == "table" and{t }or{{}})[1])) do + local a = accessor(ai) + if not a or a.count ~= count then + return nil, Err.new(Err.CORRUPT, "bad morph target accessor") + end + tt[name] = a + end + targets[ti] = tt + end + prim.targets = targets + end + prim.extras = keep(p, DRACO_HANDLED) + table.insert(mesh.primitives, prim) + end + table.insert(scene.meshes, mesh) + end + -- cameras, lights + for _, c in __iter(arr(doc.cameras)) do + if type(c) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad camera") + end + if c.type == "orthographic" and type(c.orthographic) == "table" then + local o = c.orthographic + table.insert(scene.cameras, { name = str(c.name), type = "orthographic" , xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) } ) + else + local p = (type(c.perspective) == "table" and{c.perspective }or{{} +})[1] table.insert(scene.cameras, { name = str(c.name), type = "perspective" , yfov = num(p.yfov, 0.8), aspect = (type(p.aspectRatio) == "number" and{p.aspectRatio }or{nil})[1], znear = num(p.znear, 0.01), zfar = (type(p.zfar) == "number" and{p.zfar }or{nil })[1]} ) + end + end + local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual + for _, l in __iter(arr(lp and lp.lights)) do + if type(l) == "table" then + local spot = (type(l.spot) == "table" and{l.spot }or{{} +})[1] table.insert(scene.lights, { + name = str(l.name), + type = ((l.type == "spot" or l.type == "point" )and{l.type }or{"directional"})[1], + color = numbers(l.color, 3) or { 1, 1, 1 }, + intensity = num(l.intensity, 1), + range = (type(l.range) == "number" and{l.range }or{nil})[1], + innerCone = (l.type == "spot" and{(num(spot.innerConeAngle, 0) )}or{nil})[1], + outerCone = (l.type == "spot" and{(num(spot.outerConeAngle, math.pi / 4) )}or{nil})[1], + }) + end + end + -- nodes + local nodes = arr(doc.nodes) + for i, n in __iter(nodes) do + if type(n) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1)) + end + local node= { name = str(n.name), children = {} } + for _, c in __iter(arr(n.children)) do + if not int(c) or c >= #nodes then + return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child") + end + table.insert(node.children, c + 1) + end + if int(n.mesh) and n.mesh < #scene.meshes then + node.mesh = n.mesh + 1 + end + if int(n.camera) and n.camera < #scene.cameras then + node.camera = n.camera + 1 + end + if int(n.skin) and n.skin < #arr(doc.skins) then + node.skin = n.skin + 1 + end + node.matrix = numbers(n.matrix, 16) + node.translation = numbers(n.translation, 3) + node.rotation = numbers(n.rotation, 4) + node.scale = numbers(n.scale, 3) + node.weights = (type(n.weights) == "table" and{(table.clone(n.weights) )}or{nil +})[1] local handled = {} + local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual + if type(le) == "table" and int(le.light) and le.light < #scene.lights then + node.light = le.light + 1 + handled.KHR_lights_punctual = true + end + node.extras = keep(n, handled) + scene.nodes[i] = node + end + -- a node may have one parent only, and no cycles + local parent= {} + for i, node in __iter(scene.nodes) do + for _, c in __iter(node.children) do + if parent[c] or c == i then + return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child") + end + parent[c] = i + end + end + for i in __iter(scene.nodes) do + local seen, p = 0, parent[i] + while p do + seen =seen+ 1 + if seen > #scene.nodes then + return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle") + end + p = parent[p] + end + end + -- skins + for _, s in __iter(arr(doc.skins)) do + if type(s) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad skin") + end + local joints = {} + for _, j in __iter(arr(s.joints)) do + if not int(j) or j >= #scene.nodes then + return nil, Err.new(Err.CORRUPT, "skin: bad joint") + end + table.insert(joints, j + 1) + end + table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = (int(s.skeleton) and s.skeleton < #scene.nodes and((s.skeleton + 1 ))or(nil ))}) + end + -- animations + for _, a in __iter(arr(doc.animations)) do + if type(a) ~= "table" then + return nil, Err.new(Err.CORRUPT, "bad animation") + end + local anim= { name = str(a.name), channels = {} } + local samplersA = arr(a.samplers) + local skipped = {} + for _, c in __iter(arr(a.channels)) do + local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1] + local target = type(c) == "table" and c.target + if not s or type(target) ~= "table" then + return nil, Err.new(Err.CORRUPT, "animation: bad channel") + end + local input, output = accessor(s.input), accessor(s.output) + if not input or not output then + return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors") + end + local path = target.path + if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then + table.insert(anim.channels, { + node = target.node + 1, + path = path, + input = input, + output = output, + interpolation = ((s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" )and{s.interpolation }or{"LINEAR"})[1], + }) + else + table.insert(skipped, c) -- KHR_animation_pointer and friends + end + end + if #skipped > 0 then + local aa= anim + aa.extras = { gltf = { skippedChannels = #skipped } } + end + table.insert(scene.animations, anim) + end + -- scenes + local scenes = arr(doc.scenes) + local list = {} + for _, s in __iter(scenes) do + local roots = {} + for _, n in __iter(arr(type(s) == "table" and s.nodes)) do + if int(n) and n < #scene.nodes and not parent[n + 1] then + table.insert(roots, n + 1) + end + end + table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = (type(s) == "table" and{(keep(s, nil) )}or{nil })[1]}) + end + local which = int(doc.scene) or 0 + if list[which + 1] then + scene.roots = list[which + 1].nodes + elseif #list == 0 then + for i in __iter(scene.nodes) do + if not parent[i] then + table.insert(scene.roots, i) + end + end + end + -- root extensions other than the lights, asset info + local rootExt = nil + if type(doc.extensions) == "table" then + for k, v in __iter(doc.extensions) do + if k ~= "KHR_lights_punctual" then + rootExt = rootExt or {} + rootExt[k] = v + end + end + end + scene.meta.up = "y" + scene.meta.unit = 1 + scene.meta.gltf = { + asset = asset, + scenes = list, + scene = (doc.scene ~= nil and((which + 1 ))or(nil)), + extensionsUsed = doc.extensionsUsed, + extensionsRequired = doc.extensionsRequired, + extensions = rootExt, + extras = doc.extras, + } + return scene, nil +end + +return Read +end +__FILES["model/gltf/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/gltf/Write: Scene -> a glTF 2.0 JSON document + one binary buffer. One bufferView per accessor (vertex +-- attributes 4-byte aligned per element with a byteStride when needed, matrix columns padded as glTF requires), +-- accessors shared between primitives / animations written once, f64 / i32 data converted (glTF has neither), +-- POSITION and animation input min / max, KHR_mesh_quantization declared when attributes are not floats, +-- KHR_texture_transform / KHR_lights_punctual / material extensions declared when used, images deduplicated by their +-- bytes (or uri), samplers by their settings. "polygons" primitives are fan-triangulated (MeshOps.triangulate first +-- for concave faces). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Pack = __include("model/gltf/Pack") + +local Write = {} + +local object = Types.object +local CT = { i8 = 5120, u8 = 5121, i16 = 5122, u16 = 5123, u32 = 5125, f32 = 5126, unorm8 = 5121, unorm16 = 5123, snorm8 = 5120, snorm16 = 5122 } +local SIZE = Types.COMPONENT_SIZE +local NORMALIZED = { unorm8 = true, unorm16 = true, snorm8 = true, snorm16 = true } +local MODES = { points = 0, lines = 1, line_loop = 2, line_strip = 3, triangles = 4, triangle_strip = 5, triangle_fan = 6 } +local WRAP = { clamp = 33071, mirror = 33648, ["repeat"] = 10497 } +local MIN_FILTER = { nearest = 9728, linear = 9729, nearest_mipmap_nearest = 9984, linear_mipmap_nearest = 9985, nearest_mipmap_linear = 9986, linear_mipmap_linear = 9987 } +-- attribute types the core spec allows (others need KHR_mesh_quantization) +local CORE = { + POSITION = { f32 = true }, + NORMAL = { f32 = true }, + TANGENT = { f32 = true }, + TEXCOORD = { f32 = true, unorm8 = true, unorm16 = true }, + COLOR = { f32 = true, unorm8 = true, unorm16 = true }, + JOINTS = { u8 = true, u16 = true }, + WEIGHTS = { f32 = true, unorm8 = true, unorm16 = true }, +} + + + + +local function convert(acc, to) +local get = (Types.Scene.reader(acc) ) +local out = Types.Scene.accessor(nil, to, acc.components, acc.count) + local w = (to == "f32" and{buffer.writef32 }or{buffer.writeu32 +})[1] local size = SIZE[to] + for i = 0, acc.count - 1 do + for c = 0, acc.components - 1 do + local v = get(i, c) + if to == "u32" then + v = math.clamp(math.floor(v), 0, 4294967295) + end + w(out.data, (i * acc.components + c) * size, v) + end + end + out.matrix = acc.matrix + out.name = acc.name + return out +end + +local function checkAcc(acc, label) +if type(acc) ~= "table" or type(acc.data) ~= "buffer" or not SIZE[acc.type] or type(acc.count) ~= "number" or type(acc.components) ~= "number" then + return Err.new(Err.ARG, label .. ": not an accessor") + end + if acc.components < 1 or acc.components > 16 or buffer.len(acc.data) < acc.count * acc.components * SIZE[acc.type] then + return Err.new(Err.ARG, label .. ": data is smaller than count x components") + end + return nil +end + +function Write.build(scene, opts) +local binary = opts and opts.binary or false + local embedImages = not (opts and opts.embedImages == false) + local doc= object() + local used= {} + local required= {} + local bin = Bytes.writer(65536) + local views= {} + local accessors= {} + local accIndex= {} + local failure= nil + + local function view(data, length, target, stride) +local pad = (4 - bin:tell() % 4) % 4 + bin:fill(0, pad) + local v = object() + v.buffer = 0 + v.byteOffset = bin:tell() + v.byteLength = length + v.target = target + v.byteStride = stride + bin:bytes(data, 0, length) + table.insert(views, v) + return #views - 1 + end + + -- accessor(acc, usage, attribute?) -> the glTF index (0-based) + local function accessor(acc, usage, attribute) +local known = accIndex[acc] + if known then + return known + end + local err = checkAcc(acc, attribute or usage) + if err then + failure = failure or err + return 0 + end + local a = acc + if usage == "index" then + if a.type ~= "u8" and a.type ~= "u16" and a.type ~= "u32" then + a = convert(a, "u32") + end + elseif a.type == "f64" or a.type == "i32" or a.type == "u32" and usage ~= "index" and attribute ~= nil then + a = convert(a, "f32") + end + if attribute then + local kind = string.match(attribute, "^([A-Z]+)_%d+$") or attribute + local core = CORE[kind] + if core and not core[a.type] then + used.KHR_mesh_quantization = true + required.KHR_mesh_quantization = true + end + end + local size = SIZE[a.type] + local comps = a.components + local isMat = a.matrix == true and (comps == 4 or comps == 9 or comps == 16) + local cols = (isMat and{(math.sqrt(comps) )}or{1 +})[1] local colBytes = (math.floor(comps / cols)) * size + local colStride = (cols > 1 and((math.floor((colBytes + 3) / 4 )* 4 ))or(colBytes +)) local elem = comps * size + local padded = cols * colStride + local stride = padded + local byteStride= nil + if usage == "vertex" and padded % 4 ~= 0 then + stride = math.floor((padded + 3) / 4 )* 4 + byteStride = stride + end + local data = a.data + local length = a.count * stride + if stride ~= elem then + data = buffer.create(length) + Pack.scatter(data, 0, a.data, a.count, elem, stride, cols, colBytes, colStride) + end + local g = object() + g.bufferView = view(data, length, usage == "vertex" and 34962 or(usage == "index" and 34963 or nil), byteStride) + g.componentType = CT[a.type] + g.normalized = NORMALIZED[a.type] and true or nil + g.count = a.count + g.type = (isMat and{({ [4] = "MAT2", [9] = "MAT3", [16] = "MAT4" })[comps] }or{({ "SCALAR", "VEC2", "VEC3", "VEC4" })[comps] +})[1] g.name = acc.name + if not g.type then + failure = failure or Err.new(Err.ARG, (attribute or usage) .. ": " .. comps .. " components is not a glTF type") + return 0 + end + if attribute == "POSITION" or usage == "input" then + -- min / max of the raw component values + local raw = Types.Scene.accessor(a.data, a.type == "unorm8" and"u8" or(a.type == "unorm16" and"u16" or(a.type == "snorm8" and"i8" or(a.type == "snorm16" and"i16" or a.type))), comps, a.count) + local get = (Types.Scene.reader(raw) ) +local lo, hi = table.create(comps, math.huge), table.create(comps, -math.huge) + for i = 0, a.count - 1 do + for c = 1, comps do + local v = get(i, c - 1) + if v < lo[c] then + lo[c] = v + end + if v > hi[c] then + hi[c] = v + end + end + end + if a.count > 0 then + g.min, g.max = lo, hi + end + end + table.insert(accessors, g) + local index = #accessors - 1 + accIndex[acc] = index + return index + end + + -- extras.gltf -> extras / extensions fields of a glTF object + local function restore(g, extras) + local saved = type(extras) == "table" and extras.gltf + if type(saved) ~= "table" then + return + end + if saved.extras ~= nil then + g.extras = saved.extras + end + if type(saved.extensions) == "table" then + g.extensions = g.extensions or object() + for k, v in __iter(saved.extensions) do + if g.extensions[k] == nil then + g.extensions[k] = v + used[k] = true + end + end + end + end + + -- images, samplers, textures + local images= {} + local imageOut= {} + local imageIndex= {} + local function image(data, mime, uri, name) +local key= data or uri + if key == nil then + return nil + end + if imageIndex[key] then + return imageIndex[key] + end + local im = object() + im.name = name + if data then + if binary then + im.bufferView = view(data, buffer.len(data), nil, nil) + im.mimeType = mime or "image/png" + elseif embedImages then + im.uri = "\0image" .. (#images + 1) -- replaced by a data: URI by the caller (init) / a file name + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + else + im.uri = uri or ("\0file" .. (#images + 1)) + im.mimeType = mime + table.insert(imageOut, { data = data, mime = mime, name = im.uri }) + end + else + im.uri = uri + im.mimeType = mime + end + table.insert(images, im) + imageIndex[key] = #images - 1 + return #images - 1 + end + local samplers= {} + local samplerIndex= {} + local function sampler(s) +if type(s) ~= "table" then + return nil + end + local g = object() + g.wrapS = (s.wrapS and{WRAP[s.wrapS] }or{nil +})[1] g.wrapT = (s.wrapT and{WRAP[s.wrapT] }or{nil +})[1] g.magFilter = s.filter == "nearest" and 9728 or(s.filter == "linear" and 9729 or nil +) g.minFilter = (s.minFilter and{MIN_FILTER[s.minFilter] }or{nil +})[1] local key = string.format("%s/%s/%s/%s", tostring(g.wrapS), tostring(g.wrapT), tostring(g.magFilter), tostring(g.minFilter)) + if samplerIndex[key] == nil then + table.insert(samplers, g) + samplerIndex[key] = #samplers - 1 + end + return samplerIndex[key] + end + local textures= {} + for i, t in __iter(scene.textures or {}) do + if type(t) ~= "table" then + return nil, Err.new(Err.ARG, "texture " .. i .. ": not a table") + end + local g = object() + g.name = t.name + g.sampler = sampler(t.sampler) + local saved = type(t.extras) == "table" and type(t.extras.gltf) == "table" and t.extras.gltf or nil + local srcExt = saved and saved.sourceExtension + local img = image(t.data, t.mime, t.uri, t.name) + if srcExt and img then + g.extensions = object() + local e = object() + e.source = img + g.extensions[srcExt] = e + used[srcExt] = true + local fb = saved.fallback + if type(fb) == "table" then + g.source = image(fb.data, fb.mime, fb.uri, nil) + end + if g.source == nil then + required[srcExt] = true + end + else + g.source = img + end + restore(g, t.extras) + table.insert(textures, g) + end + local function texInfo(r, kind) +if type(r) ~= "table" or type(r.texture) ~= "number" or not textures[r.texture] then + return nil + end + local g = object() + g.index = r.texture - 1 + if r.texCoord and r.texCoord ~= 0 then + g.texCoord = r.texCoord + end + if kind == "normal" and r.scale ~= nil and r.scale ~= 1 then + g.scale = r.scale + end + if kind == "occlusion" and r.strength ~= nil and r.strength ~= 1 then + g.strength = r.strength + end + if type(r.transform) == "table" then + local tt = object() + tt.offset = r.transform.offset + tt.scale = r.transform.scale + tt.rotation = r.transform.rotation + tt.texCoord = r.transform.texCoord + g.extensions = object() + g.extensions.KHR_texture_transform = tt + used.KHR_texture_transform = true + end + return g + end + local function extValue(v, key) +if type(v) ~= "table" then + return v + end + if key and string.sub(key, -7) == "Texture" and type(v.texture) == "number" then + return texInfo(v, (key == "normalTexture" or key == "clearcoatNormalTexture" )and"normal" or nil) + end + local out = ((Types.isObject(v) or next(v) == nil )and{(object() )}or{{} +})[1] for k, x in __iter(v) do + out[k] = extValue(x, (type(k) == "string" and{k }or{nil})[1]) + end + return out + end + -- materials + local materials= {} + for i, m in __iter(scene.materials or {}) do + if type(m) ~= "table" then + return nil, Err.new(Err.ARG, "material " .. i .. ": not a table") + end + local g = object() + g.name = m.name + local pbr = object() + local bc = m.baseColor or { 1, 1, 1, 1 } + if bc[1] ~= 1 or bc[2] ~= 1 or bc[3] ~= 1 or (bc[4] or 1) ~= 1 then + pbr.baseColorFactor = { bc[1], bc[2], bc[3], bc[4] or 1 } + end + pbr.baseColorTexture = texInfo(m.baseColorTexture) + if m.metallic ~= nil and m.metallic ~= 1 then + pbr.metallicFactor = m.metallic + end + if m.roughness ~= nil and m.roughness ~= 1 then + pbr.roughnessFactor = m.roughness + end + pbr.metallicRoughnessTexture = texInfo(m.metallicRoughnessTexture) + local saved = type(m.extras) == "table" and type(m.extras.gltf) == "table" and m.extras.gltf or nil + if saved and saved.pbr then + restore(pbr, { gltf = saved.pbr }) + end + g.pbrMetallicRoughness = pbr + g.normalTexture = texInfo(m.normalTexture, "normal") + g.occlusionTexture = texInfo(m.occlusionTexture, "occlusion") + g.emissiveTexture = texInfo(m.emissiveTexture) + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 then + g.emissiveFactor = { em[1], em[2], em[3] } + end + if m.alphaMode == "mask" then + g.alphaMode = "MASK" + if m.alphaCutoff ~= nil and m.alphaCutoff ~= 0.5 then + g.alphaCutoff = m.alphaCutoff + end + elseif m.alphaMode == "blend" then + g.alphaMode = "BLEND" + end + if m.doubleSided then + g.doubleSided = true + end + if type(m.extensions) == "table" then + g.extensions = object() + for k, v in __iter(m.extensions) do + g.extensions[k] = extValue(v, nil) + used[k] = true + end + end + restore(g, m.extras) + table.insert(materials, g) + end + -- meshes + local meshes= {} + for i, mesh in __iter(scene.meshes or {}) do + if type(mesh) ~= "table" or type(mesh.primitives) ~= "table" then + return nil, Err.new(Err.ARG, "mesh " .. i .. ": no primitives") + end + local g = object() + g.name = mesh.name + g.primitives = {} + for k, p in __iter(mesh.primitives) do + if type(p) ~= "table" or type(p.attributes) ~= "table" or not p.attributes.POSITION then + return nil, Err.new(Err.ARG, string.format("mesh %d primitive %d: no POSITION", i, k)) + end + local gp = object() + gp.attributes = object() + local names= {} + for name in __iter(p.attributes) do + table.insert(names, name) + end + table.sort(names) + for _, name in __iter(names) do + gp.attributes[name] = accessor(p.attributes[name], "vertex", name) + end + local mode = p.mode or "triangles" + local indices = p.indices + if mode == "polygons" then + -- fan-triangulate + local faces = p.faces + local getf = faces and Types.Scene.reader(faces) + local n = (indices and{indices.count }or{p.attributes.POSITION.count +})[1] local geti = (indices and{(Types.Scene.reader(indices) )}or{nil +})[1] if not faces or not getf or (indices and not geti) then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local list = {} + local at = 0 + for f = 0, faces.count - 1 do + local c = getf(f, 0) + if at + c > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + for a = 1, c - 2 do + for _, j in __iter({ at, at + a, at + a + 1 }) do + table.insert(list, (geti and{(geti(j, 0) )}or{j})[1]) + end + end + at =at+ c + end + local ib = buffer.create(#list * 4) + for q, v in __iter(list) do + buffer.writeu32(ib, (q - 1) * 4, v) + end + indices = Types.Scene.accessor(ib, "u32", 1, #list) + mode = "triangles" + end + if MODES[mode] == nil then + return nil, Err.new(Err.ARG, "unknown primitive mode " .. tostring(mode)) + end + if indices then + gp.indices = accessor(indices, "index", nil) + end + if mode ~= "triangles" then + gp.mode = MODES[mode] + end + if type(p.material) == "number" and materials[p.material] then + gp.material = p.material - 1 + end + if type(p.targets) == "table" and #p.targets > 0 then + gp.targets = {} + for _, t in __iter(p.targets) do + local gt = object() + local tn = {} + for name in __iter(t) do + table.insert(tn, name) + end + table.sort(tn) + for _, name in __iter(tn) do + gt[name] = accessor(t[name], "vertex", nil) + end + table.insert(gp.targets, gt) + end + end + restore(gp, p.extras) + table.insert(g.primitives, gp) + end + g.weights = mesh.weights + restore(g, mesh.extras) + table.insert(meshes, g) + end + -- cameras, lights + local cameras= {} + for _, c in __iter(scene.cameras or {}) do + local g = object() + g.name = c.name + g.type = c.type + local p = object() + if c.type == "orthographic" then + p.xmag, p.ymag, p.znear, p.zfar = c.xmag or 1, c.ymag or 1, c.znear or 0, c.zfar or 100 + g.orthographic = p + else + g.type = "perspective" + p.yfov, p.aspectRatio, p.znear, p.zfar = c.yfov or 0.8, c.aspect, c.znear or 0.01, c.zfar + g.perspective = p + end + table.insert(cameras, g) + end + local lights= {} + for _, l in __iter(scene.lights or {}) do + local g = object() + g.name = l.name + g.type = l.type + if l.color and (l.color[1] ~= 1 or l.color[2] ~= 1 or l.color[3] ~= 1) then + g.color = { l.color[1], l.color[2], l.color[3] } + end + if l.intensity ~= nil and l.intensity ~= 1 then + g.intensity = l.intensity + end + if l.type ~= "directional" then + g.range = l.range + end + if l.type == "spot" then + local s = object() + s.innerConeAngle = (l.innerCone and l.innerCone ~= 0 and{l.innerCone }or{nil +})[1] s.outerConeAngle = (l.outerCone and math.abs(l.outerCone - math.pi / 4) > 1e-12 and{l.outerCone }or{nil +})[1] g.spot = s + end + table.insert(lights, g) + end + -- nodes + local nodes= {} + local nodeCount = #(scene.nodes or {}) + for i, n in __iter(scene.nodes or {}) do + if type(n) ~= "table" then + return nil, Err.new(Err.ARG, "node " .. i .. ": not a table") + end + local g = object() + g.name = n.name + if n.children and #n.children > 0 then + g.children = {} + for _, c in __iter(n.children) do + if type(c) ~= "number" or c < 1 or c > nodeCount then + return nil, Err.new(Err.ARG, "node " .. i .. ": bad child") + end + table.insert(g.children, c - 1) + end + end + if n.mesh and meshes[n.mesh] then + g.mesh = n.mesh - 1 + end + if n.camera and cameras[n.camera] then + g.camera = n.camera - 1 + end + if n.skin and scene.skins[n.skin] then + g.skin = n.skin - 1 + end + if n.matrix then + local ident = true + for k = 1, 16 do + if n.matrix[k] ~= Types.Scene.IDENTITY[k] then + ident = false + end + end + if not ident then + g.matrix = n.matrix + end + else + g.translation, g.rotation, g.scale = n.translation, n.rotation, n.scale + end + g.weights = n.weights + if n.light and lights[n.light] then + g.extensions = object() + local le = object() + le.light = n.light - 1 + g.extensions.KHR_lights_punctual = le + used.KHR_lights_punctual = true + end + restore(g, n.extras) + table.insert(nodes, g) + end + -- skins + local skins= {} + for _, s in __iter(scene.skins or {}) do + local g = object() + g.name = s.name + g.joints = {} + for _, j in __iter(s.joints or {}) do + table.insert(g.joints, j - 1) + end + if s.inverseBindMatrices then + local ibm = s.inverseBindMatrices + if ibm.matrix == nil and ibm.components == 16 then + ibm.matrix = true + end + g.inverseBindMatrices = accessor(ibm, "other", nil) + end + if s.skeleton then + g.skeleton = s.skeleton - 1 + end + table.insert(skins, g) + end + -- animations + local animations= {} + for _, a in __iter(scene.animations or {}) do + local g = object() + g.name = a.name + g.channels, g.samplers = {}, {} + local samplerOf= {} + for _, c in __iter(a.channels or {}) do + local input = accessor(c.input, "input", nil) + local output = accessor(c.output, "other", nil) + local key = input .. "/" .. output .. "/" .. tostring(c.interpolation) + if samplerOf[key] == nil then + local s = object() + s.input, s.output = input, output + if c.interpolation and c.interpolation ~= "LINEAR" then + s.interpolation = c.interpolation + end + table.insert(g.samplers, s) + samplerOf[key] = #g.samplers - 1 + end + local ch = object() + ch.sampler = samplerOf[key] + ch.target = object() + ch.target.node = c.node - 1 + ch.target.path = c.path + table.insert(g.channels, ch) + end + table.insert(animations, g) + end + if failure then + return nil, failure + end + -- scenes: the original list (meta.gltf.scenes) when it is there, else the roots + local meta= (type(scene.meta) == "table" and{scene.meta }or{{} +})[1] local mg = type(meta.gltf) == "table" and meta.gltf or {} + local scenes = {} + if type(mg.scenes) == "table" and #mg.scenes > 0 then + for _, s in __iter(mg.scenes) do + local g = object() + g.name = s.name + g.nodes = {} + for _, n in __iter(s.nodes or {}) do + if nodes[n] then + table.insert(g.nodes, n - 1) + end + end + restore(g, s.extras) + table.insert(scenes, g) + end + -- the current roots replace the default scene's list + local which = mg.scene or 1 + if scenes[which] then + scenes[which].nodes = {} + for _, r in __iter(scene.roots or {}) do + table.insert(scenes[which].nodes, r - 1) + end + end + doc.scene = (mg.scene or 1) - 1 + else + local g = object() + g.nodes = {} + for _, r in __iter(scene.roots or {}) do + table.insert(g.nodes, r - 1) + end + table.insert(scenes, g) + doc.scene = 0 + end + local asset = object() + asset.version = "2.0" + asset.generator = "rosetta" + if type(mg.asset) == "table" then + asset.copyright = mg.asset.copyright + asset.minVersion = mg.asset.minVersion + asset.extras = mg.asset.extras + end + doc.asset = asset + -- root extensions kept from the source (variants, ...), the lights + if type(mg.extensions) == "table" then + doc.extensions = object() + for k, v in __iter(mg.extensions) do + doc.extensions[k] = v + used[k] = true + end + end + if #lights > 0 then + doc.extensions = doc.extensions or object() + local lp = object() + lp.lights = lights + doc.extensions.KHR_lights_punctual = lp + used.KHR_lights_punctual = true + end + doc.extras = mg.extras + local function list(t) +local out = {} + for k in __iter(t) do + table.insert(out, k) + end + table.sort(out) + return (#out > 0 and{out }or{nil +})[1] end + -- the source's required extensions that are still used stay required + for _, e in __iter(((type(mg.extensionsRequired) == "table" and{mg.extensionsRequired }or{{}})[1])) do + if used[e] then + required[e] = true + end + end + doc.extensionsUsed = list(used) + doc.extensionsRequired = list(required) + doc.scenes = scenes + doc.nodes = (#nodes > 0 and{nodes }or{nil +})[1] doc.meshes = (#meshes > 0 and{meshes }or{nil +})[1] doc.materials = (#materials > 0 and{materials }or{nil +})[1] doc.textures = (#textures > 0 and{textures }or{nil +})[1] doc.images = (#images > 0 and{images }or{nil +})[1] doc.samplers = (#samplers > 0 and{samplers }or{nil +})[1] doc.cameras = (#cameras > 0 and{cameras }or{nil +})[1] doc.skins = (#skins > 0 and{skins }or{nil +})[1] doc.animations = (#animations > 0 and{animations }or{nil +})[1] doc.accessors = (#accessors > 0 and{accessors }or{nil +})[1] doc.bufferViews = (#views > 0 and{views }or{nil +})[1] return { doc = doc, bin = bin:finish(), images = imageOut }, nil +end + +return Write +end +__FILES["model/iqm"] = function() +local __compat = __compat local type = __compat.type --!strict +-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / +-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). +-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as +-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as +-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _<name>), joints +-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels +-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in +-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's +-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). +-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and +-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/iqm/Read") +local Write = __include("model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r) +return r:peek(16) == MAGIC and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r, opts) +if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new((e.code == Err.CORRUPT and{Err.ARG }or{e.code})[1], e.message) + end + return out, nil +end + +return Iqm +end +__FILES["model/iqm/Read"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and +-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). +-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h) +local s = bit32.band(h, 0x8000) ~= 0 and-1 or 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return (m == 0 and((s * math.huge ))or(0 +)) end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +local function values(b, at, format, n, normalized) +local out = (table.create(n) ) +local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v +if format == 0 then + v = readi8(b, p) + v = (normalized and{(math.max(v / 127, -1) )}or{v +})[1] elseif format == 1 then + v = readu8(b, p) + v = (normalized and((v / 255 ))or(v +)) elseif format == 2 then + v = readi16(b, p) + v = (normalized and{(math.max(v / 32767, -1) )}or{v +})[1] elseif format == 3 then + v = readu16(b, p) + v = (normalized and((v / 65535 ))or(v +)) elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals, comps) +local d = buffer.create(#vals * 4) + for i, v in __iter(vals) do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, math.floor(#vals / comps)) +end + +local MIME= { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +-- scene(b, base, limit, opts) -> Scene | nil, message +function Read.scene(b, base, limit, opts) +local size = limit - base + local H= {} + for i, name in __iter(Read.HEADER) do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs, count, each, what) +if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, (H.ofs_bounds > 0 and{H.num_frames }or{0})[1], 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = (H.num_text > 0 and{(buffer.readstring(b, base + H.ofs_text, H.num_text) )}or{"" +})[1] local function str(ofs) +if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source= { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + -- vertex arrays (the whole model's vertices; meshes are ranges of them) + local nv = H.num_vertexes + +local arrays= {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = (kind and{kind }or{("_" .. ((typ >= 0x10 and{(str(typ - 0x10) )}or{(tostring(typ))})[1]) +)})[1] table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + -- joints -> nodes + a skin + local jointNodes= {} + local skin= nil + if H.num_joints > 0 then + local joints= {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = (table.create(10) ) +for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = ql > 0 and{ q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } or{ 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM names its texture there) + local matOf= {} + local function material(name) +if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + -- meshes + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes= {} + for _, a in __iter(arrays) do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (big and 2 or 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = (c < a.comps and{vals[v * a.comps + c + 1] }or{0 +})[1] x = math.clamp(math.floor(x), 0, big and 65535 or 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, big and"u16" or"u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = (c < a.comps and{vals[v * a.comps + c + 1] }or{a.kind == "color" and c == 3 and 1 or 0 +})[1] writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[a.kind == "color" and"COLOR_0" or"WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = a.kind == "position" and"POSITION" or(a.kind == "texcoord" and"TEXCOORD_0" or(a.kind == "normal" and"NORMAL" or(a.kind == "tangent" and"TANGENT" or(a.kind == "color" and"COLOR_0" or a.name +)))) local want = (a.kind == "position" or a.kind == "normal" )and 3 or(a.kind == "texcoord" and 2 or((a.kind == "tangent" or a.kind == "color" )and 4 or a.comps +)) if want ~= a.comps then + local fixed = (table.create(cv * want, 0) ) +for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = (c < a.comps and{vals[v * a.comps + c + 1] }or{c == 3 and 1 or 0 +})[1] end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim= { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node= { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses= {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = (table.create(10) ), (table.create(10) ) +for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels =channels+ 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes= H.num_framechannels * 2 + local framesAt= base + H.ofs_frames + local function frame(f) +local out = (table.create(np) ) +local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = (table.create(10) ) +for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k= ps.scale[c + 1] + x =x+ readu16(b, q) * k + q =q+ 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims= {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = (rate > 0 and rate == rate and{rate }or{30 +})[1] local times = (table.create(count) ) +local tracks= {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in __iter(tracks) do + local v = fr[j] + local t, r, s = tr.translation , tr.rotation , tr.scale +table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = (ql > 0 and{ql }or{1 +})[1] table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read +end +__FILES["model/iqm/Write"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines +-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights +-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins +-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse +-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world +-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are +-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), +-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. +-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). +-- Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Bytes = __include("core/Bytes") +local Mat4 = __include("codecs/model/Mat4") +local Sampler = __include("codecs/model/Sampler") +local Read = __include("model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene + +-- ------------------------------------------------------------------------------------------------ scene walk +-- world matrices (rest pose, or with a pose's overrides) and the parent of every node + +local function parents(scene) +local parent= {} + for i, n in __iter(scene.nodes) do + for _, c in __iter(n.children or {}) do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node, over) +if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene, parent, pose) +local world= {} + local function get(i, depth) +local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in __iter(scene.nodes) do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points +local function triangles(prim) +local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx= {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out= {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = (fget and{(fget(f, 0) )}or{0 +})[1] for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at =at+ n + end + else + return nil + end + for _, v in __iter(out) do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc, comps, nv, default) +if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = (table.create(nv * comps) ) +for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = (c < acc.components and{(get(v, c) )}or{default[c + 1] +})[1] end + end + return out +end + +-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +local function influences(skin, jointIndex, joints, weights, v) +local pairs_= {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a, b) +return a[2] > b[2] + end) + local sum = 0 + for _, pr in __iter(pairs_) do + sum =sum+ pr[2] + end + local q= {} + local left = 255 + for k, pr in __iter(pairs_) do + q[k] = (sum > 0 and{(math.floor(pr[2] / sum * 255 + 0.5) )}or{0 +})[1] left =left- q[k] + end + if #pairs_ > 0 then + q[1]=q[1]+ left + end + local list= {} + for k, pr in __iter(pairs_) do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +-- appends a flat influence list to the blend index / weight arrays (4 slots) +local function push4(bi, bw, list) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end +-- ------------------------------------------------------------------------------------------------ writer + + + +function Write.iqm(scene, opts) +local parent = parents(scene) + local rest = worlds(scene, parent, nil) + -- the skeleton: every skin joint, parents first + local isJoint= {} + local ibmOf= {} + for _, skin in __iter(scene.skins) do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in __iter(skin.joints) do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = (table.create(16) ) +for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + local jointList= {} + local jointIndex= {} -- node -> 0-based joint + local function add(n, depth) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard =guard+ 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in __iter(scene.skins) do + for _, n in __iter(skin.joints) do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n) +local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard =guard+ 1 + end + return -1 + end + local bindWorld= {} + for _, n in __iter(jointList) do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n, world) +local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1] ]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + -- the meshes + local nodeOfMesh= {} + local placed= {} + local seen= {} + local function visit(i, depth) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in __iter(node.children or {}) do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in __iter(scene.nodes) do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in __iter(roots) do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in __iter(scene.meshes) do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris= {} + local meshes= {} + -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds + local skinOf= {} + local nvTotal = 0 + for _, pl in __iter(placed) do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = (pl.node > 0 and{rest[pl.node] }or{Scene.IDENTITY +})[1] local nrmM = Mat4.normalMatrix(world) + for pi, prim in __iter(mesh.primitives) do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = (readAll(pos, 3, nv, { 0, 0, 0 }) ) +local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = (pl.node > 0 and{pl.node }or{nil +})[1] local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard =guard+ 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + local list +if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- triangles back to IQM's clockwise order + local tfirst = math.floor(#tris / 3 +) for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = (tex and tex.uri and{tex.uri }or{(mat.name and{mat.name }or{"" +})[1]})[1] end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name =name.. "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = math.floor(#tri / 3 )}) + nvTotal =nvTotal+ nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + -- animation frames + local frames= {} -- frames[f][joint] = 10 values + local anims= {} + local frameWorld= {} + if hasJoints then + for ai, anim in __iter(scene.animations) do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second + local dt = (#keys > 1 and((keys[2] - keys[1] ))or(0 +)) local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = (uniform and((1 / dt ))or(30 +)) end + local fps= math.clamp(rate , 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ= {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = (table.create(#jointList) ) +for j, n in __iter(jointList) do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + -- quantization per pose channel + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in __iter(frames) do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels =numChannels+ 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + -- text + local text = { "\0" } + local textLen = 1 + local textAt= { [""] = 0 } + local function str(s) +local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen =textLen+ (#s + 1 +) textAt[s] = at + return at + end + for _, m in __iter(meshes) do + str(m.name) + str(m.material) + end + for _, n in __iter(jointList) do + str(scene.nodes[n].name or "") + end + for _, a in __iter(anims) do + str(a.name) + end + local comment = opts and opts.comment + -- layout + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H= {} + local function at() +return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text =H.num_text+ 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in __iter(meshes) do + for _, v in __iter({ str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount }) do + w:u32le(v) + end + end +-- vertex arrays: headers, then data + +local arrs= { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = #jointList > 256 and 3 or 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt= {} + for i, a in __iter(arrs) do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in __iter(a.data) do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in __iter(a.data) do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in __iter(a.data) do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in __iter(a.data) do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), math.floor(#tris / 3 +) for _, v in __iter(tris) do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in __iter(jointList) do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le((p < 0 and((p + 2 ^ 32 ))or(p))) + for _, v in __iter({ t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] }) do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in __iter(jointList) do + local jp = jointParent(n) + w:u32le((jp < 0 and((jp + 2 ^ 32 ))or(jp))) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in __iter(anims) do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in __iter(frames) do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + -- bounds of the skinned vertices per frame + H.ofs_bounds = at() + local skinM = (table.create(#jointList) ) +for f, world in __iter(frameWorld) do + for j, n in __iter(jointList) do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in __iter({ lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) }) do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in __iter(Read.HEADER) do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in __iter(arrs) do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write +end +__FILES["model/ldraw"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and +-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked +-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. +-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + +-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines +-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at +-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried +-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing +-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). +-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without +-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main +-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = +-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one +-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines +-- = false drops them); no normals, no indices (each triangle has its own three vertices). +-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise +-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or +-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. +-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge +-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig +-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered +-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> +-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). +-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node +-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = +-- false leaves it out (meta.up = nil, meta.source.up = "-y"). +-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. +-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta +-- commands (ignored); BFC in model files' references (models place parts as certified). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/ldraw/Read") +local Colors = __include("model/ldraw/Colors") + +-- ------------------------------------------------------------------------------------------------ contract +local Ldraw = { + name = "ldraw", + category = "model", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + +function Ldraw.sniff(r) +local head = Sniff.text(r, 2048, true) + if string.find(head, "^0%s+FILE%s") then + return 0.9 + end + if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then + return 0.8 + end + if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ldraw.decode(r, opts) +local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, text, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, +-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added +function Ldraw.colors(ldconfig) +local t = Colors.builtin() + if ldconfig then + Colors.parse(ldconfig, t) + end + return t +end + +return Ldraw +end +__FILES["model/ldraw/Colors"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from +-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see +-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. +local Colors = {} + + + + +local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } + +-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +function Colors.entry(rest) +local words= {} + for w in __iter(string.gmatch(rest, "%S+")) do + table.insert(words, w) + end + local name = words[1] + local code, rgb, edge, alpha, lum, finish = nil, nil, nil, 255, 0, nil + local i = 2 + while i <= #words do + local k, v = words[i], words[i + 1] + if k == "CODE" and v then + code = tonumber(v) + i =i+ 1 + elseif k == "VALUE" and v and rgb == nil then + rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16) + i =i+ 1 + elseif k == "EDGE" and v then + local hex = string.match(v, "^#(%x%x%x%x%x%x)$") + edge = (hex and{(0x2000000 + ((tonumber(hex, 16) )) )}or{(tonumber(v) +)})[1] i =i+ 1 + elseif k == "ALPHA" and v then + alpha = math.clamp(tonumber(v) or 255, 0, 255) + i =i+ 1 + elseif k == "LUMINANCE" and v then + lum = math.clamp(tonumber(v) or 0, 0, 255) + i =i+ 1 + elseif FINISHES[k] then + finish = k + elseif k == "MATERIAL" and v then + finish = v + break + end + i =i+ 1 + end + if not name or not code or not rgb or code % 1 ~= 0 then + return nil, nil + end + return code, { name = name, rgb = rgb , edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } +end + +-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added +function Colors.parse(text, into) +local t= into or {} + for line in __iter(string.gmatch(text, "[^\n]+")) do + local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$") + if rest then + local code, c = Colors.entry(rest) + if code and c then + t[code] = c + end + end + end + return t +end + +local BUILTIN = [[ +Black CODE 0 VALUE #1B2A34 EDGE #808080 +Blue CODE 1 VALUE #1E5AA8 EDGE #333333 +Green CODE 2 VALUE #00852B EDGE #333333 +Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333 +Red CODE 4 VALUE #B40000 EDGE #333333 +Dark_Pink CODE 5 VALUE #D3359D EDGE #333333 +Brown CODE 6 VALUE #543324 EDGE #1E1E1E +Light_Grey CODE 7 VALUE #8A928D EDGE #333333 +Dark_Grey CODE 8 VALUE #545955 EDGE #333333 +Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333 +Bright_Green CODE 10 VALUE #58AB41 EDGE #333333 +Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333 +Salmon CODE 12 VALUE #F06D61 EDGE #333333 +Pink CODE 13 VALUE #F6A9BB EDGE #333333 +Yellow CODE 14 VALUE #FAC80A EDGE #333333 +White CODE 15 VALUE #F4F4F4 EDGE #333333 +Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333 +Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333 +Tan CODE 19 VALUE #D7BA8C EDGE #333333 +Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333 +Purple CODE 22 VALUE #671F81 EDGE #333333 +Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333 +Orange CODE 25 VALUE #D67923 EDGE #333333 +Magenta CODE 26 VALUE #901F76 EDGE #333333 +Lime CODE 27 VALUE #A5CA18 EDGE #333333 +Dark_Tan CODE 28 VALUE #897D62 EDGE #333333 +Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333 +Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333 +Lavender CODE 31 VALUE #CDA4DE EDGE #333333 +Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333 +Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333 +Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080 +Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333 +Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333 +Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333 +Medium_Green CODE 74 VALUE #7FC475 EDGE #333333 +Light_Pink CODE 77 VALUE #FECCCF EDGE #333333 +Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333 +Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333 +Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333 +Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333 +Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333 +Nougat CODE 92 VALUE #BB805A EDGE #333333 +Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333 +Violet CODE 110 VALUE #26469A EDGE #333333 +Medium_Violet CODE 112 VALUE #4861AC EDGE #333333 +Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333 +Aqua CODE 118 VALUE #9CD6CC EDGE #333333 +Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333 +Light_Orange CODE 125 VALUE #F9A777 EDGE #333333 +Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333 +Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333 +Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333 +Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333 +Rust CODE 216 VALUE #872B17 EDGE #333333 +Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333 +Lilac CODE 219 VALUE #564E9D EDGE #333333 +Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333 +Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333 +Dark_Blue CODE 272 VALUE #19325A EDGE #333333 +Dark_Green CODE 288 VALUE #00451A EDGE #808080 +Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333 +Dark_Brown CODE 308 VALUE #352100 EDGE #808080 +Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333 +Dark_Red CODE 320 VALUE #720012 EDGE #333333 +Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333 +Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333 +Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333 +Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333 +Olive_Green CODE 330 VALUE #77774E EDGE #333333 +Sand_Red CODE 335 VALUE #88605E EDGE #333333 +Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333 +Coral CODE 353 VALUE #FF6D77 EDGE #333333 +Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333 +Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333 +Medium_Brown CODE 370 VALUE #755945 EDGE #333333 +Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333 +Sand_Purple CODE 373 VALUE #75657D EDGE #333333 +Sand_Green CODE 378 VALUE #708E7C EDGE #333333 +Sand_Blue CODE 379 VALUE #70819A EDGE #333333 +Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333 +Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333 +Umber_Brown CODE 423 VALUE #543F33 EDGE #333333 +Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333 +Medium_Orange CODE 462 VALUE #F58624 EDGE #333333 +Dark_Orange CODE 484 VALUE #91501C EDGE #333333 +Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333 +Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333 +Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333 +Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333 +Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333 +Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128 +Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128 +Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128 +Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128 +Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128 +Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128 +Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128 +Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128 +Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128 +Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128 +Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 +Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128 +Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128 +Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128 +Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 +Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128 +Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128 +Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 +Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210 +Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128 +Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128 +Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128 +Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128 +Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128 +Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128 +Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128 +Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128 +Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME +Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME +Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME +Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME +Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME +Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME +Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME +Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT +Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT +Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT +Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT +Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT +Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT +Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT +Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT +Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT +Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT +Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT +Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT +Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT +Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT +Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT +Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT +Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT +Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT +Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT +Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL +Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL +Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL +Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL +Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL +Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL +Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL +Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL +Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240 +Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15 +Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15 +Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15 +Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER +Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER +Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE +Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE +Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER +Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER +Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER +Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER +Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER +Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER +Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER +Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER +Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER +Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER +Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER +Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER +Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER +Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER +Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER +Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER +Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER +Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER +Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER +Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER +Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER +Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER +Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER +Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER +Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER +Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER +Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER +Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER +Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER +Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER +Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER +Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER +Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER +Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER +Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER +Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER +Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC +Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC +Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC +Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC +Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC +Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC +Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC +Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC +Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC +Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC +Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC +Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333 +Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333 +Magnet CODE 493 VALUE #656761 EDGE #333333 METAL +Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL +Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL +Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 +]] + +local cache= nil +-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) +function Colors.builtin() +if not cache then + local t= {} + for line in __iter(string.gmatch(BUILTIN, "[^\n]+")) do + local code, c = Colors.entry(line) + if code and c then + t[code] = c + end + end + cache = t + end + local copy= {} + for k, v in __iter(cache) do + copy[k] = v + end + return copy +end + +return Colors +end +__FILES["model/ldraw/Read"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command +-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into +-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Types = __include("Types") +local Colors = __include("model/ldraw/Colors") + +local Read = {} +-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" } +local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true } +local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 } +local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 } + +local function norm(name) +return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/"))) +end + +local function srgbToLinear(v) +return (v <= 0.04045 and((v / 12.92 ))or((((v + 0.055) / 1.055) ^ 2.4 +)))end + +-- parse(text, name) -> File (colour definitions go into colours as they are met) +local function parse(text, name, colours, stats) +local f= { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } + local cmds = f.cmds + local invert, step, first = false, 1, true + for line in __iter(string.gmatch(text, "[^\n]+")) do + local t = string.match(line, "^%s*(%d)%s") + if t then + stats.lines =stats.lines+ 1 + end + if t == "0" then + local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$") + if w1 == "BFC" and rest then + local u = string.upper(rest) + local cmd= nil + for word in __iter(string.gmatch(u, "%S+")) do + if word == "CERTIFY" then + f.certified = true + elseif word == "NOCERTIFY" then + f.certified = false + elseif word == "INVERTNEXT" then + invert = true + elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then + local c= cmd or { k = 0, c = 0, v = IDENTITY12 } + cmd = c + if word == "CW" or word == "CCW" then + c.cw = word == "CW" + else + c.clip = word == "CLIP" + end + end + end + if cmd then + table.insert(cmds, cmd) + end + elseif w1 == "!COLOUR" then + Colors.parse(line, colours) + elseif w1 == "!LDRAW_ORG" and rest then + f.org = string.match(rest, "^(%S+)") + elseif w1 == "STEP" then + step =step+ 1 + elseif w1 == "Author:" then + f.author = rest + elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then + -- (headers) + elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then + f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) + end + first = false + elseif t then + first = false + local k = (tonumber(t) ) +local inv = invert + invert = false + if k == 1 then + local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$") + local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) } + local code = tonumber(c) + local complete = true + for j = 1, 12 do + if v[j] == nil then + complete = false + end + end + if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then + table.insert(cmds, { k = 1, c = code, v = v , name = file, inv = inv, step = step }) + f.refs =f.refs+ 1 + else + stats.bad =stats.bad+ 1 + end + elseif k >= 2 and k <= 5 then + local need = k == 2 and 6 or(k == 3 and 9 or 12 +) local v= {} + local code= nil + local n = 0 + for w in __iter(string.gmatch(line, "%S+")) do + n =n+ 1 + if n == 2 then + code = tonumber(w) + elseif n > 2 and n <= need + 2 then + local num = tonumber(w) + if not num then + break + end + v[n - 2] = num + end + end + if code and code >= 0 and code % 1 == 0 and #v == need then + table.insert(cmds, { k = k, c = code, v = v }) + else + stats.bad =stats.bad+ 1 + end + elseif k ~= 0 then + stats.bad =stats.bad+ 1 + end + end + end + return f +end + +-- scene(text, opts) -> Scene | nil, message, kind +function Read.scene(text, opts) +local o= opts or {} + local colours = Colors.builtin() + if type(o.ldconfig) == "string" then + Colors.parse(o.ldconfig, colours) + end + local maxDepth = o.maxDepth or 64 + local maxTriangles = o.maxTriangles or 2 ^ 24 + local maxNodes = o.maxNodes or 2 ^ 20 + local withLines = o.lines ~= false + local withOptional = o.optionalLines == true + local stats = { bad = 0, lines = 0 } + + -- ------------------------------------------------------------------------------------------ MPD sections + text = string.gsub(text, "\r", "") + local sections= {} + local mainName= nil + local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil + local mainText = text + if mpd then + local cur= nil + local buf= {} + local function close() + if cur and sections[cur] == nil then + sections[cur] = table.concat(buf, "\n") + end + cur, buf = nil, {} + end + for line in __iter(string.gmatch(text, "[^\n]+")) do + local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$") + if fname then + close() + cur = norm(fname) + if not mainName then + mainName = fname + end + elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then + close() + elseif cur then + table.insert(buf, line) + end + end + close() + mainText = sections[norm(mainName or "")] or "" + end + + -- ------------------------------------------------------------------------------------------ files + local cache= {} + local missing= {} + local fetchFiles = o.files + local resolve = o.resolve + local function fetch(uri) +local v= (type(fetchFiles) == "table" and{fetchFiles[uri] }or{nil +})[1] if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = (ok and{res }or{nil +})[1] end + return (type(v) == "buffer" and{(buffer.tostring(v) )}or{(type(v) == "string" and{v }or{nil +})[1]})[1] end + local function lookup(name) +local key = norm(name) + local have = cache[key] + if have ~= nil then + return have or nil + end + local sec = sections[key] + if sec then + local f = parse(sec, name, colours, stats) + cache[key] = f + return f + end + local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/") + for _, prefix in __iter(PREFIXES) do + for _, cand in __iter({ prefix .. slash, prefix .. key }) do + local data = fetch(cand) + if data then + local f = parse((string.gsub(data, "\r", "")), name, colours, stats) + f.library = LIBRARY[prefix] == true + cache[key] = f + return f + end + end + end + missing[key] = true + cache[key] = false + return nil + end + local function isModel(f) +local m = f.model + if m == nil then + local org = string.lower(f.org or "") + local orgPart = org ~= "" and not string.find(org, "model", 1, true) + if f.main then + m = not orgPart and f.refs > 0 + else + local ext = string.match(f.key, "%.(%w+)$") + m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd") + end + f.model = m + end + return m +end + + -- ------------------------------------------------------------------------------------------ colours, materials + local scene = Types.Scene.new() + local function edgeOf(c) +local e = colours[c] + if e then + return e.edge + end + return c >= 0x2000000 and 0x2000000 or 0x2333333 + end + local function resolveColour(code, cur) +if code == 16 then + return cur + elseif code == 24 then + return edgeOf(cur) + end + return code + end + local materialOf= {} + local function material(col, ds) +local key = col .. (ds and"d" or"") + local have = materialOf[key] + if have then + return have + end + local entry = colours[col] + local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil + if entry then + rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish + elseif col >= 0x2000000 and col < 0x4000000 then + rgb = col % 0x1000000 + alpha = col >= 0x3000000 and 128 or 255 + name = string.format("#%06X", rgb) + elseif col >= 0x4000000 and col < 0x8000000 then + -- dithered: two 12-bit colours, shown as their mean + local lo, hi = col % 0x1000, (math.floor(col / 0x1000)) % 0x1000 + local function ch(v, s) +return ((math.floor(v / s)) % 16) * 17 + end + rgb = (math.floor((ch(lo, 256) + ch(hi, 256)) / 2)) * 65536 + (math.floor((ch(lo, 16) + ch(hi, 16)) / 2)) * 256 + math.floor((ch(lo, 1) + ch(hi, 1)) / 2 +) alpha = col >= 0x7000000 and 0 or(col >= 0x5000000 and 128 or 255 +) name = string.format("Dither_%X", col) + end + local m = Types.Scene.material(name) + m.baseColor = { srgbToLinear((math.floor(rgb / 65536)) / 255), srgbToLinear(((math.floor(rgb / 256)) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 } + if alpha < 255 then + m.alphaMode = "blend" + end + m.doubleSided = ds + m.metallic = 0 + m.roughness = 0.35 + if finish == "CHROME" or finish == "METAL" then + m.metallic, m.roughness = 1, finish == "CHROME" and 0.15 or 0.4 + elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then + m.metallic, m.roughness = 0.6, 0.45 + elseif finish == "RUBBER" then + m.roughness = 0.9 + end + m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = (entry and entry.luminance > 0 and{entry.luminance }or{nil })[1]} } + table.insert(scene.materials, m) + materialOf[key] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ baking + local failure, failKind= nil, nil + local triangles = 0 + local cycles = 0 + local function fail(msg, kind) + if not failure then + failure, failKind = msg, kind + end + end + + -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + local function bake(f, m, colour, inv, certified, depth, stack, groups, order, direct) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-files nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local model = isModel(f) + local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m) + local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9) + local cw, clip = false, true + local function group(mode, col, ds) +local key = mode .. col .. (ds and"d" or"") + local g = groups[key] + if not g then + g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = mode == "optional" and{} or nil } + groups[key] = g + table.insert(order, g) + end + return g + end + local function put(list, x, y, z) + local n = #list + list[n + 1] = m1 * x + m2 * y + m3 * z + m4 + list[n + 2] = m5 * x + m6 * y + m7 * z + m8 + list[n + 3] = m9 * x + m10 * y + m11 * z + m12 + end + for _, cmd in __iter(f.cmds) do + if failure then + break + end + local k = cmd.k + local v = cmd.v + if k == 0 then + if cmd.cw ~= nil then + cw = cmd.cw +end + if cmd.clip ~= nil then + clip = cmd.clip +end + elseif k == 1 then + if not direct then + local sub = lookup(cmd.name ) + if sub and stack[sub] then + cycles =cycles+ 1 + elseif sub then + local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v) + local child = { + m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4, + m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8, + m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12, + } + local childCert = model and true or certified and f.certified and clip + bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false) + end + end + elseif k == 3 or k == 4 then + local col = resolveColour(cmd.c, colour) + local one = certified and f.certified and clip + local g = group("triangles", col, not one) + local rev = cw ~= inv ~= (det < 0) + local p = g.pos + local nt = k == 3 and 1 or 2 + triangles =triangles+ nt + if triangles > maxTriangles then + return fail(string.format("limit: more than %d triangles", maxTriangles), "limit") + end + local function tri(a, b, c) + if rev then + a, c = c, a + end + put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3]) + put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3]) + put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3]) + end + tri(0, 1, 2) + if k == 4 then + tri(0, 2, 3) + end + elseif k == 2 and withLines then + local g = group("lines", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + elseif k == 5 and withOptional then + local g = group("optional", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + local ctrl = g.ctrl +for _ = 1, 2 do + put(ctrl, v[7], v[8], v[9]) + put(ctrl, v[10], v[11], v[12]) + end + end + end + stack[f] = nil + end + + local function f32(list, from, step, count) +local b = buffer.create(count * 12) + for i = 0, count - 1 do + local s = from + i * step + buffer.writef32(b, i * 12, list[s]) + buffer.writef32(b, i * 12 + 4, list[s + 1]) + buffer.writef32(b, i * 12 + 8, list[s + 2]) + end + return Types.Scene.accessor(b, "f32", 3, count) + end + + -- the mesh of a file baked at the identity (nil when it has no geometry) + local meshOf= {} + local function meshFor(f, colour, inv, direct) +local key = f.key .. "|" .. colour .. "|" .. (inv and"i" or"") .. (direct and"d" or"") + local have = meshOf[key] + if have ~= nil then + return have or nil + end + local groups= {} + local order= {} + bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct) + local mesh= { name = f.name, primitives = {} } + for _, g in __iter(order) do + local count = math.floor(#g.pos / 3 +) if count > 0 then + local prim= { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = g.mode == "triangles" and"triangles" or"lines" } + prim.material = material(g.colour, g.ds) + if g.mode == "optional" then + local ctrl = g.ctrl +prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count) + prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count) + prim.extras = { ldraw = { optional = true } } + end + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + meshOf[key] = false + return nil + end + table.insert(scene.meshes, mesh) + meshOf[key] = #scene.meshes + return #scene.meshes + end + + -- ------------------------------------------------------------------------------------------ the node tree + local mainFile = parse(mainText, mainName or "main", colours, stats) + mainFile.main = true + if stats.lines == 0 then + return nil, "no LDraw lines", nil + end + if mainName then + cache[norm(mainName)] = mainFile + end + local mainColour = o.color or 16 + local function newNode(node) +table.insert(scene.nodes, node) + if #scene.nodes > maxNodes then + fail(string.format("limit: more than %d nodes", maxNodes), "limit") + end + return #scene.nodes + end + local function expand(f, colour, inv, out, depth, stack) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-models nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local direct = meshFor(f, colour, inv, true) + if direct then + table.insert(out, newNode({ name = f.name, children = {}, mesh = direct })) + end + for _, cmd in __iter(f.cmds) do + if failure then + break + end + if cmd.k == 1 then + local sub = lookup(cmd.name ) + if sub and stack[sub] then + cycles =cycles+ 1 + elseif sub then + local v = cmd.v + local c = resolveColour(cmd.c, colour) + local subInv = inv ~= (cmd.inv == true) + local node= { + name = cmd.name, + children = {}, + matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 }, + extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = subInv and true or nil } }, + } + local index = newNode(node) + if isModel(sub) then + expand(sub, c, subInv, node.children, depth + 1, stack) + else + node.mesh = meshFor(sub, c, subInv, false) + end + table.insert(out, index) + end + end + end + stack[f] = nil + end + local top= {} + if o.flatten or not isModel(mainFile) then + local mesh = meshFor(mainFile, mainColour, false, false) + table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh })) + else + expand(mainFile, mainColour, false, top, 0, {}) + end + if failure then + return nil, failure, failKind + end + if o.upright == false then + scene.roots = top + else + table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) }) + scene.roots = { #scene.nodes } + scene.meta.up = "y" + end + scene.meta.unit = 0.0004 + local missingList= {} + for k in __iter(missing) do + table.insert(missingList, k) + end + table.sort(missingList) + local nfiles = 0 + for _, f in __iter(cache) do + if f then + nfiles =nfiles+ 1 + end + end + scene.meta.source = { + format = "ldraw", + mpd = mpd, + name = mainName, + title = mainFile.title, + author = mainFile.author, + files = nfiles, + missing = missingList, + cycles = cycles, + badLines = stats.bad, + up = o.upright == false and"-y" or nil, + } + return scene, nil, nil +end + +return Read +end +__FILES["model/lwo"] = function() +--!strict +-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from +-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. +-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / +-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and +-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: +-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the +-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has +-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces +-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> +-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, +-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: +-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding +-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. +-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / +-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") +local Build = __include("model/lwo/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Lwo = { + name = "lwo", + category = "model", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lwo.sniff(r) +if r:peek(4) ~= "FORM" then + return 0 + end + local v = r:peek(4, 8) + return VERSIONS[v] and 1 or(v == "LWO3" and 0.8 or 0 +)end + +-- ------------------------------------------------------------------------------------------------ decode +function Lwo.decode(r, opts) +if r.limit - r.base < 12 then + return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base) + end + if r:peek(4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base) + end + local v = r:peek(4, 8) + if v == "LWO3" then + return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8) + end + if not VERSIONS[v] then + return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8) + end + local maxCorners = opts and opts.maxVertices or 2 ^ 25 + local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model)) + end + if not model then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, model, opts) + if not ok2 then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + return scene, nil +end + +return Lwo +end +__FILES["model/lwo/Build"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z +-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's +-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its +-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), +-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, +-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. +-- Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Parse = __include("model/lwo/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + + +local MIME= { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } + +-- ------------------------------------------------------------------------------------------------ materials +local function textureIndex(scene, cache, path) +local hit = cache[path] + if hit then + return hit + end + local norm = string.gsub(path, "\\", "/") + local base = string.match(norm, "([^/:]+)$") or norm + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } }) + cache[path] = #scene.textures + return #scene.textures +end + +local function material(scene, m, surf, uvSets, cache) +local mat = Scene.material(surf.name) + local v = surf.values + local c = surf.color + local tran = math.clamp(v.TRAN or 0, 0, 1) + mat.baseColor = { c[1], c[2], c[3], 1 - tran } + if tran > 0 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + local gloss = v.GLOS + mat.roughness = (gloss and (v.SPEC or 0) > 0 and{(math.clamp(1 - gloss, 0, 1) )}or{1 +})[1] local lumi = v.LUMI or 0 + if lumi > 0 then + mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi } + end + mat.doubleSided = surf.side == 3 + local maps = {} + local blocks = table.clone(surf.blocks) + table.sort(blocks, function(a, b) +return a.ordinal < b.ordinal + end) + for _, blk in __iter(blocks) do + local path = (blk.file and{blk.file }or{(blk.clip and{m.clips[blk.clip] }or{nil +})[1]})[1] local entry= { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap } + if path and (blk.kind == "IMAP" or blk.kind == "TEX") then + local ti = textureIndex(scene, cache, path) + entry.texture = ti + if blk.enabled then + local ref= { texture = ti } + if blk.uvmap and uvSets[blk.uvmap] then + ref.texCoord = uvSets[blk.uvmap] + end + if blk.channel == "COLR" and not mat.baseColorTexture then + mat.baseColorTexture = ref + elseif blk.channel == "LUMI" and not mat.emissiveTexture then + mat.emissiveTexture = ref + if lumi <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + end + table.insert(maps, entry) + end + local extras= { color = table.clone(c), side = surf.side, maps = maps, source = surf.source } + for k, x in __iter(v) do + extras[string.lower(k)] = x + end + if surf.vcol then + extras.vcol = surf.vcol.name + end + mat.extras = { lwo = extras } + return mat +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function groupLayer(layer, surfaceOf) +local groups= {} + local byKey= {} + for i, poly in __iter(layer.polys) do + local kind = poly.kind + local n = #poly.corners + if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then + local class = n == 1 and"point" or(n == 2 and"line" or(kind == "FACE" and"poly" or"patch" +)) local mi = surfaceOf(poly.surf) + local key = mi .. class + local g = byKey[key] + if not g then + g = { material = mi, class = class, polys = {} } + byKey[key] = g + table.insert(groups, g) + end + table.insert(g.polys, i - 1) + end + end + local rank= { poly = 1, patch = 2, line = 3, point = 4 } + table.sort(groups, function(a, b) +if a.material ~= b.material then + return a.material < b.material + end + return rank[a.class] < rank[b.class] + end) + return groups +end + +-- the corners of a face in output order (winding reversed for the handedness change, first corner kept) +local function ordered(corners) +local n = #corners + local out = (table.create(n) ) +out[1] = corners[1] + for k = 2, n do + out[k] = corners[n - k + 2] + end + return out +end + + + +local function primitive(layer, g, attrs, morphs, triangulate) +local pts, pivot = layer.pts, layer.pivot + local vertOf= {} + local srcPoint= {} -- vertex (1-based) -> point + local srcPoly= {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local indices= {} + local faces= {} + local madMaps= {} + for _, a in __iter(attrs) do + if next(a.map.mad) then + table.insert(madMaps, a.map) + end + end + for _, m in __iter(morphs) do + if next(m.mad) then + table.insert(madMaps, m) + end + end + local function vertex(f, p) +local own = false + for _, m in __iter(madMaps) do + local row = m.mad[f] + if row and row[p] then + own = true + break + end + end + if not own then + local v = vertOf[p] + if v then + return v + end + end + table.insert(srcPoint, p) + table.insert(srcPoly, (own and{f }or{(-1)})[1]) + local v = #srcPoint - 1 + if not own then + vertOf[p] = v + end + return v + end + for _, f in __iter(g.polys) do + local corners = ordered(layer.polys[f + 1].corners) + local n = #corners + local vs = (table.create(n) ) +for k = 1, n do + vs[k] = vertex(f, corners[k]) + end + if g.class == "poly" or g.class == "patch" then + if triangulate then + for k = 2, n - 1 do + table.insert(indices, vs[1]) + table.insert(indices, vs[k]) + table.insert(indices, vs[k + 1]) + end + else + table.insert(faces, n) + table.move(vs, 1, n, #indices + 1, indices) + end + else + table.move(vs, 1, n, #indices + 1, indices) + end + end + local nv = #srcPoint + local pos = buffer.create(nv * 12) + for v = 1, nv do + local p = srcPoint[v] * 3 + local o = (v - 1) * 12 + writef32(pos, o, pts[p + 1] - pivot[1]) + writef32(pos, o + 4, pts[p + 2] - pivot[2]) + writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) + end + local attributes= { POSITION = Scene.accessor(pos, "f32", 3, nv) } + -- the value of map m for vertex v (1-based), or nil + local function value(m, v) +local f = srcPoly[v] + if f >= 0 then + local row = m.mad[f] + local hit = row and row[srcPoint[v] ] + if hit then + return hit, nil + end + end + local p = srcPoint[v] + if m.has[p] then + return nil, p * m.dims + end + return nil, nil + end + local names= {} + for _, a in __iter(attrs) do + local m, comps = a.map, a.comps + local data = buffer.create(nv * comps * 4) + for v = 1, nv do + local o = (v - 1) * comps * 4 + local direct, at = value(m, v) + local x= (direct and{direct }or{at and{ m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } or{} +})[1] if m.kind == "uv" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, 1 - (x[2] or 0)) + elseif m.kind == "color" then + writef32(data, o, x[1] or 1) + writef32(data, o + 4, x[2] or 1) + writef32(data, o + 8, x[3] or 1) + writef32(data, o + 12, (m.dims == 4 and x[4] and{x[4] }or{1})[1]) + elseif m.kind == "normal" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, x[2] or 0) + writef32(data, o + 8, -(x[3] or 0)) + else + writef32(data, o, x[1] or 0) + end + end + attributes[a.name] = Scene.accessor(data, "f32", comps, nv) + names[a.name] = m.name + end + local prim= { attributes = attributes, mode = "triangles" } + if #morphs > 0 then + local targets= {} + local targetNames= {} + for _, m in __iter(morphs) do + local d = buffer.create(nv * 12) + for v = 1, nv do + local direct, at = value(m, v) + local x= (direct and{direct }or{at and{ m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } or nil +})[1] if x then + local p = srcPoint[v] * 3 + local dx, dy, dz = x[1], x[2], x[3] + if m.kind == "spot" then + dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3] + end + writef32(d, (v - 1) * 12, dx) + writef32(d, (v - 1) * 12 + 4, dy) + writef32(d, (v - 1) * 12 + 8, -dz) + end + end + local tgt= { POSITION = Scene.accessor(d, "f32", 3, nv) } + table.insert(targets, tgt) + table.insert(targetNames, m.name) + end + prim.targets = targets + names._targets = table.concat(targetNames, "\n") + end + local ib = buffer.create(#indices * 4) + for k, x in __iter(indices) do + writeu32(ib, (k - 1) * 4, x) + end + prim.indices = Scene.accessor(ib, "u32", 1, #indices) + if g.class == "line" then + prim.mode = "lines" + elseif g.class == "point" then + prim.mode = "points" + elseif not triangulate then + prim.mode = "polygons" + local fb = buffer.create(#faces * 4) + for k, x in __iter(faces) do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #faces) + end + prim.material = g.material + local extras= { maps = names } + if g.class == "patch" then + extras.subdivision = true + end + prim.extras = { lwo = extras } + return prim +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(m, opts) +local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } + -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + local uvSets= {} + local nuv = 0 + for _, layer in __iter(m.layers) do + for _, map in __iter(layer.maps) do + if map.kind == "uv" and uvSets[map.name] == nil then + uvSets[map.name] = nuv + nuv =nuv+ 1 + end + end + end + -- materials: one per surface, then one per tag without a surface, then a default one + local texCache= {} + local bySurfName= {} + for i, surf in __iter(m.surfaces) do + scene.materials[i] = material(scene, m, surf, uvSets, texCache) + if bySurfName[surf.name] == nil then + bySurfName[surf.name] = i + end + local low = string.lower(surf.name) + if bySurfName[low] == nil then + bySurfName[low] = i + end + end + local tagMat= {} + local default= nil + local function surfaceOf(tag) +if tag ~= nil then + local hit = tagMat[tag] + if hit then + return hit + end + local name = m.tags[tag + 1] + if name then + local mi = bySurfName[name] or bySurfName[string.lower(name)] + if not mi then + table.insert(scene.materials, Scene.material(name)) + mi = #scene.materials + bySurfName[name] = mi + end + tagMat[tag] = mi + return mi + end + end + if not default then + local mat = Scene.material("Default") + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + mat.metallic = 0 + table.insert(scene.materials, mat) + default = #scene.materials + end + return default +end + -- nodes and meshes + local nodeOf= {} + local layerOfNode= {} + for _, layer in __iter(m.layers) do + local hasGeometry = #layer.polys > 0 + if not (layer.implicit and not hasGeometry) then + local node= { name = layer.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + layerOfNode[ni] = layer + if nodeOf[layer.index] == nil then + nodeOf[layer.index] = ni + end + node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } } + local groups = groupLayer(layer, surfaceOf) + if #groups > 0 then + local attrs= {} + local morphs= {} + local hasUv = {} + local maxUv = -1 + for _, map in __iter(layer.maps) do + if map.kind == "uv" then + hasUv[uvSets[map.name] ] = map + maxUv = math.max(maxUv, uvSets[map.name]) + elseif map.kind == "morph" or map.kind == "spot" then + table.insert(morphs, map) + end + end + local empty= { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} } + for k = 0, maxUv do + table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 }) + end + local nw, nc, hasNormal = 0, 0, false + for _, map in __iter(layer.maps) do + if map.kind == "normal" and not hasNormal then + hasNormal = true + table.insert(attrs, { map = map, name = "NORMAL", comps = 3 }) + elseif map.kind == "weight" then + table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 }) + nw =nw+ 1 + end + end + local prims = {} + for _, g in __iter(groups) do + local mat = scene.materials[g.material] + local ex= mat and mat.extras + local vcol = ex and ex.lwo and ex.lwo.vcol + local pa = table.clone(attrs) + nc = 0 + for _, map in __iter(layer.maps) do + if map.kind == "color" then + if map.name == vcol then + table.insert(pa, { map = map, name = "COLOR_0", comps = 4 }) + else + table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 }) + nc =nc+ 1 + end + end + end + table.insert(prims, primitive(layer, g, pa, morphs, triangulate)) + end + local mesh= { name = layer.name, primitives = prims } + if #morphs > 0 then + mesh.weights = table.create(#morphs, 0) + local tn = {} + for _, mp in __iter(morphs) do + table.insert(tn, mp.name) + end + mesh.extras = { targetNames = tn } + end + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + end + end + -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + local parentOf= {} + for ni, layer in __iter(layerOfNode) do + local pi = (layer.parent ~= nil and{nodeOf[layer.parent] }or{nil +})[1] if pi and pi ~= ni then + local up, steps = pi, 0 + while up and up ~= ni and steps <= #scene.nodes do + up = parentOf[up] + steps =steps+ 1 + end + if up ~= ni then + parentOf[ni] = pi + end + end + end + for ni = 1, #scene.nodes do + local layer = layerOfNode[ni] + local pi = parentOf[ni] + local pp = (pi and{layerOfNode[pi].pivot }or{{ 0, 0, 0 } +})[1] local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + scene.nodes[ni].translation = t + end + if pi then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + return scene, nil +end + +return Build +end +__FILES["model/lwo/Parse"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build +-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave +-- 5.x), checked against what assimp's LWO importer reads (no code taken). +-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are +-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS +-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo +-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural +-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). +-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, +-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. +-- Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Bytes = __include("core/Bytes") +local Chunks = __include("containers/Chunks") + +local Parse = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local MAP_KINDS= { + TXUV = "uv", + RGB = "color", + RGBA = "color", + WGHT = "weight", + MNVW = "weight", + NORM = "normal", + MORF = "morph", + SPOT = "spot", +} + +-- ------------------------------------------------------------------------------------------------ primitives +-- S0: a NUL-terminated string padded to an even length +local function s0(r) +local start = r.pos + local s = r:cstring() + if (r.pos - start) % 2 == 1 and r.pos < r.limit then + r.pos =r.pos+ 1 + end + return s +end + +-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +local function vx(r) +if r:peekU8() == 0xFF then + return r:u32be() - 0xFF000000 + end + return r:u16be() +end + +local function id4(r) +local s = r:string(4) + return (string.gsub(s, " +$", "")) +end + +-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +local function subchunks(buf, p, e, f) + while p + 6 <= e do + local id = buffer.readstring(buf, p, 4) + local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5) + local body = p + 6 + local avail = math.min(n, e - body) + f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail)) + p = body + n + (n % 2) + end +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function newLayer(index) +return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} } +end + +local function readPoints(r, layer, limit) +local n = math.floor(r:remaining() / 12 +) if math.floor(#layer.pts / 3 )+ n > limit then + return "limit: more than " .. limit .. " points" + end + local pts = layer.pts + local k = #pts + for _ = 1, n * 3 do + k =k+ 1 + pts[k] = r:f32be() + end + return nil +end + +-- POLS (LWO2): returns nil or an error +local function readPolys(r, layer, kind, ptBase, budget) +local polys = layer.polys + local npts = math.floor(#layer.pts / 3 +) while r:remaining() >= 2 do + local n = bit32.band(r:u16be(), 0x3FF) + local corners = (table.create(n) ) +for i = 1, n do + local p = vx(r) + ptBase + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + if r.err then + return "truncated polygon list" + end + budget[1]=budget[1]- n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + table.insert(polys, { kind = kind, surf = nil, corners = corners }) + end + return nil +end + +-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count) +local function readPolysB(r, layer, budget) +local polys = layer.polys + local npts = math.floor(#layer.pts / 3 +) while r:remaining() >= 4 do + local n = r:u16be() + local corners = (table.create(n) ) +for i = 1, n do + local p = r:u16be() + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + local surf = r:i16be() + if r.err then + return "truncated polygon list" + end + if surf < 0 then + surf = -surf + r:u16be() -- the detail polygon count: they follow as ordinary records + end + budget[1]=budget[1]- n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + if n > 0 then + table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners }) + end + end + return nil +end + +local function findMap(layer, kind, name, dims) +for _, m in __iter(layer.maps) do + if m.kind == kind and m.name == name then + return m + end + end + local m= { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} } + table.insert(layer.maps, m) + return m +end + +local function readVmap(r, layer, perPoly, ptBase, polyBase, skipped) + local typ = id4(r) + local dims = r:u16be() + local name = s0(r) + local kind = MAP_KINDS[typ] + if r.err or not kind then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local want = kind == "uv" and 2 or(kind == "color" and 4 or(kind == "weight" and 1 or 3 +)) if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local m = findMap(layer, kind, name, want) + local npts = math.floor(#layer.pts / 3 +) local npolys = #layer.polys + local vals, has, mad = m.vals, m.has, m.mad + while r:remaining() >= 2 do + local p = vx(r) + ptBase + local f = (perPoly and((vx(r) + polyBase ))or((-1 +))) local v = (table.create(want, 1) ) +for c = 1, dims do + local x = r:f32be() + if c <= want then + v[c] = x + end + end + if r.err then + break + end + if p < npts then + if perPoly then + if f < npolys then + local row = mad[f] + if not row then + row = {} + mad[f] = row + end + row[p] = v + end + else + has[p] = true + for c = 1, want do + vals[p * want + c] = v[c] + end + end + end + end +end + +local function readPtag(r, layer, polyBase) + local typ = id4(r) + if typ ~= "SURF" and typ ~= "MATR" then + return + end + local polys = layer.polys + while r:remaining() >= 4 do + local f = vx(r) + polyBase + local tag = r:u16be() + if r.err then + break + end + local poly = polys[f + 1] + if poly then + poly.surf = tag + end + end +end + +-- ------------------------------------------------------------------------------------------------ surfaces +local function newSurface(name) +return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil } +end + +local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } + +local function readBlock(r, surf) + -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + if r:remaining() < 6 then + return + end + local kind = id4(r) + local hn = r:u16be() + local hend = math.min(r.pos + hn, r.limit) + local blk= { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 } + local hr = Bytes.reader(r.buf, r.pos, hend - r.pos) + blk.ordinal = s0(hr) + subchunks(r.buf, hr.pos, hend, function(id, sr) + if id == "CHAN" then + blk.channel = id4(sr) + elseif id == "ENAB" then + blk.enabled = sr:u16be() ~= 0 + elseif id == "OPAC" then + sr:u16be() + blk.opacity = sr:f32be() + elseif id == "NEGA" then + blk.negative = sr:u16be() ~= 0 + elseif id == "AXIS" then + blk.axis = sr:u16be() + end + end) + subchunks(r.buf, hend + (hn % 2), r.limit, function(id, sr) + if id == "PROJ" then + blk.projection = sr:u16be() + elseif id == "AXIS" then + blk.axis = sr:u16be() + elseif id == "IMAG" then + blk.clip = vx(sr) + elseif id == "VMAP" then + blk.uvmap = s0(sr) + elseif id == "WRAP" then + blk.wrap = { sr:u16be(), sr:u16be() } + end + end) + table.insert(surf.blocks, blk) +end + +local function readSurface(r, surfaces) + local name = s0(r) + local source = s0(r) + local surf = newSurface(name) + if source ~= "" then + for _, s in __iter(surfaces) do + if s.name == source then + surf.values = table.clone(s.values) + surf.color = table.clone(s.color) + surf.side = s.side + surf.vcol = s.vcol + surf.blocks = table.clone(s.blocks) + break + end + end + surf.source = source + end + subchunks(r.buf, r.pos, r.limit, function(id, sr) + if id == "COLR" then + local c = { sr:f32be(), sr:f32be(), sr:f32be() } + if not sr.err then + surf.color = c + end + elseif SURF_VALUES[id] then + local v = sr:f32be() + if not sr.err then + surf.values[id] = v + end + elseif id == "SIDE" then + surf.side = sr:u16be() + elseif id == "VCOL" then + local intensity = sr:f32be() + vx(sr) + local kind = id4(sr) + local vname = s0(sr) + if not sr.err then + surf.vcol = { name = vname, kind = kind, intensity = intensity } + end + elseif id == "BLOK" then + readBlock(sr, surf) + end + end) + table.insert(surfaces, surf) +end + +-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks +local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" } +local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" } +local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" } +local B_PROJ= { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 } + +local function readSurfaceB(r, surfaces) + local surf = newSurface(s0(r)) + local tex= nil + subchunks(r.buf, r.pos, r.limit, function(id, sr) + if id == "COLR" then + local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 } + if not sr.err then + surf.color = c + end + elseif B_VALUES[id] then + local v = sr:u16be() + if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then + surf.values[B_VALUES[id] ] = v / 256 + end + elseif B_FLOATS[id] then + local v = sr:f32be() + if not sr.err then + surf.values[B_FLOATS[id] ] = v + surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one + end + elseif id == "GLOS" then + local v = sr:u16be() + if not sr.err then + -- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness + surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1) + end + elseif id == "SMAN" then + surf.values.SMAN = sr:f32be() + elseif id == "FLAG" then + local fl = sr:u16be() + if bit32.band(fl, 0x100) ~= 0 then + surf.side = 3 + end + elseif B_TEX[id] then + local desc = sr:cstring() + local proj= nil + for word, v in __iter(B_PROJ) do + if string.find(desc, word, 1, true) then + proj = v + end + end + local blk= { kind = string.find(desc, "Image Map", 1, true) and"TEX" or"PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj } + table.insert(surf.blocks, blk) + tex = blk + elseif id == "TIMG" and tex then + local path = sr:cstring() + if path ~= "" and path ~= "(none)" then + tex.file = path + end + elseif id == "TFLG" and tex then + local fl = sr:u16be() + tex.axis = bit32.band(fl, 1) ~= 0 and 0 or(bit32.band(fl, 2) ~= 0 and 1 or 2 +) tex.negative = bit32.band(fl, 16) ~= 0 + elseif id == "TVAL" and tex then + tex.opacity = sr:u16be() / 256 + end + end) + for k in __iter(surf.values) do + if string.sub(k, -1) == "!" then + surf.values[k] = nil + end + end + table.insert(surfaces, surf) +end + +local function readClip(r, clips, refs) + local index = r:u32be() + if r.err then + return + end + subchunks(r.buf, r.pos, r.limit, function(id, sr) + if id == "STIL" then + clips[index] = s0(sr) + elseif id == "ISEQ" then + local digits = sr:u8() + sr:u8() + local offset = sr:i16be() + sr:u16be() + local start = sr:i16be() + sr:u16be() + local prefix = s0(sr) + local suffix = s0(sr) + if not sr.err then + clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix + end + elseif id == "XREF" then + refs[index] = sr:u32be() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ the file +-- parse(buf, from, limit, opts) -> Model | nil, message +function Parse.model(buf, from, limit, maxCorners) +local version = buffer.readstring(buf, from + 8, 4) + local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) + local e = math.min(limit, from + 8 + declared) + local model= { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 } + local layer = newLayer(0) + layer.implicit = true + table.insert(model.layers, layer) + local ptBase, polyBase = 0, 0 + local budget = { maxCorners } + local refs= {} + local lwob = version == "LWOB" + local list = Chunks.walk(buf, from + 12, e, Chunks.IFF) + for _, c in __iter(list) do + local id = c.id + local r = Bytes.reader(buf, c.offset, c.avail) + local err= nil + if id == "TAGS" or id == "SRFS" then + while r:remaining() > 0 do + table.insert(model.tags, s0(r)) + end + elseif id == "LAYR" and not lwob then + local index = r:u16be() + r:u16be() -- flags (hidden) + local px, py, pz = r:f32be(), r:f32be(), r:f32be() + local name = s0(r) + local parent= (r:remaining() >= 2 and{(r:u16be() )}or{nil +})[1] if r.err then + return nil, "truncated LAYR chunk" + end + if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then + table.remove(model.layers, #model.layers) + end + layer = newLayer(index) + layer.name = name + layer.parent = (parent == 0xFFFF and{nil }or{parent +})[1] layer.pivot = { px, py, pz } + table.insert(model.layers, layer) + ptBase, polyBase = 0, 0 + elseif id == "PNTS" then + ptBase = math.floor(#layer.pts / 3 +) err = readPoints(r, layer, maxCorners) + elseif id == "POLS" then + polyBase = #layer.polys + if lwob then + err = readPolysB(r, layer, budget) + else + local kind = id4(r) + if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then + err = readPolys(r, layer, kind, ptBase, budget) + else + -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + local before = #layer.polys + err = readPolys(r, layer, kind, ptBase, budget) + model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before + end + end + elseif id == "VMAP" or id == "VMAD" then + readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped) + elseif id == "PTAG" then + readPtag(r, layer, polyBase) + elseif id == "SURF" then + if lwob then + readSurfaceB(r, model.surfaces) + else + readSurface(r, model.surfaces) + end + elseif id == "CLIP" then + readClip(r, model.clips, refs) + end + if err then + return nil, err + end + end + for index, target in __iter(refs) do + if model.clips[index] == nil and model.clips[target] then + model.clips[index] = model.clips[target] + end + end + model.corners = maxCorners - budget[1] + return model, nil +end + +return Parse +end +__FILES["model/mca"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/mca: Minecraft Anvil region files (r.<x>.<z>.mca: 32 x 32 chunks), read-only. New code, from the Minecraft +-- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads +-- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over +-- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, +-- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). +-- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks +-- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with +-- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its +-- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, +-- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header +-- and one chunk's NBT without building voxels. +-- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the +-- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Chunk = __include("model/mca/Chunk") +local Lz4Block = __include("model/mca/Lz4Block") + +-- ------------------------------------------------------------------------------------------------ contract +local Mca = { + name = "mca", + category = "model", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + +local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mca.sniff(r) +local n = r.limit - r.base + if n < 8192 then + return 0 + end + local sectors = math.floor((n + 4095) / 4096 +) local used, b = 0, r.buf + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) + if e ~= 0 then + local off, cnt = math.floor(e / 256), e % 256 + if off < 2 or cnt == 0 or off + cnt > sectors then + return 0 + end + used =used+ 1 + if used == 1 then + local p = r.base + off * 4096 + if p + 5 > r.limit then + return 0 + end + local c = buffer.readu8(b, p + 4) % 128 + if COMPRESSION[c] == nil then + return 0 + end + end + end + end + return used > 0 and 0.8 or 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) +function Mca.list(r) +local n = r.limit - r.base + if n < 8192 then + return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) + end + local out= {} + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) + if e ~= 0 then + table.insert(out, { + x = i % 32, + z = math.floor(i / 32), + sector = math.floor(e / 256), + sectors = e % 256, + timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), + }) + end + end + return out, nil +end + +local function regionCoords(o) +if o.region then + return o.region[1], o.region[2] + end + if o.name then + local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") + if x then + return tonumber(x), tonumber(z) + end + end + return nil, nil +end + +-- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err +local function payload(r, e, o) +local p = r.base + e.sector * 4096 + if p + 5 > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) + end + local len = bit32.byteswap(buffer.readu32(r.buf, p)) + local ctype = buffer.readu8(r.buf, p + 4) + local data, start, size= r.buf, p + 5, len - 1 + if ctype >= 128 then + -- stored in c.<x>.<z>.mcc next to the region (whole file = the compressed payload) + local rx, rz = regionCoords(o) + if not o.resolve or rx == nil then + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) + end + local name = string.format("c.%d.%d.mcc", (rx ) * 32 + e.x, (rz ) * 32 + e.z) + local ext = o.resolve(name) + if type(ext) ~= "buffer" then + return nil, Err.new(Err.IO, "cannot read " .. name) + end + data, start, size = ext, 0, buffer.len(ext) + ctype =ctype- 128 + elseif len < 1 or p + 4 + len > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) + end + local comp = COMPRESSION[ctype] + local maxBytes = o.maxBytes or 2 ^ 26 + local out, err + if comp == "gzip" then + out, err = Deflate.gunzip(data, start, size) + elseif comp == "zlib" then + out, err = Deflate.zlib(data, start, size) + elseif comp == "none" then + out = buffer.create(size ) + buffer.copy(out, 0, data, start, size) + elseif comp == "lz4" then + local msg + out, msg = Lz4Block.decode(data, start, size , maxBytes) + if not out then + err = Err.from(msg, start - r.base) + end + else + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) + end + if not out then + return nil, err + end + if buffer.len(out) > maxBytes then + return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) + end + return out, comp +end + +-- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) +function Mca.chunk(r, x, z, opts) +local o= opts or {} + if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then + return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") + end + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + for _, e in __iter(entries) do + if e.x == x and e.z == z then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, info + end + return v, comp + end + end + return nil, nil +end + +function Mca.decode(r, opts) +local o= opts or {} + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + local want= nil + if o.chunks then + local w= {} + for _, c in __iter(o.chunks) do + w[(c[1] or 0) + 32 * (c[2] or 0)] = true + end + want = w + end + local area = o.area + if area and #area ~= 6 then + return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") + end + local keep = o.keepNbt ~= false + local chunks= {} + local infos = {} + for _, e in __iter(entries) do + if not want or want[e.x + 32 * e.z] then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) + end + local blocks, berr = Chunk.blocks(v) + if not blocks then + return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) + end + local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) + if inArea then + table.insert(chunks, blocks) + table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = (keep and{v }or{nil })[1]}) + end + end + end + -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, c in __iter(chunks) do + lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) + lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) + for _, s in __iter(c.sections) do + local solid = false + for _, st in __iter(s.states) do + if not Mc.isAir(st) then + solid = true + break + end + end + if solid then + lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) + end + end + end + if area then + for k = 1, 3 do + lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) + if area[k] > area[k + 3] then + return nil, Err.new(Err.ARG, "area minimum past its maximum") + end + end + if lo[2] == math.huge then + lo[2], hi[2] = area[2], area[5] + end + end + if lo[2] == math.huge then + lo[2], hi[2] = 0, -1 -- no blocks at all + end + if #chunks == 0 then + lo, hi = { 0, 0, 0 }, { -1, -1, -1 } + end + local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) + local n = sx * sy * sz + if n > (o.maxCells or 2 ^ 25) then + return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) + end + -- one palette for the grid (air first), each section copied in through a remap table + local states = { "minecraft:air" } + local index= { ["minecraft:air"] = 0 } + local grid = buffer.create(n * 2) + local bes, ents = {}, {} + for _, c in __iter(chunks) do + local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] + for _, s in __iter(c.sections) do + local cy = s.y * 16 - lo[2] + if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then + local lut = (table.create(#s.states) ) +for i, st in __iter(s.states) do + local g = index[st] + if g == nil then + table.insert(states, st) + g = #states - 1 + index[st] = g + end + lut[i] = g + end + if #states > 65536 then + return nil, Err.new(Err.LIMIT, "more than 65536 block states") + end + local cells = s.cells + local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) + local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) + local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) + for y = y0, y1 do + for z = z0, z1 do + local src = ((y * 16 + z) * 16 + x0) * 2 + local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 + for _ = x0, x1 do + buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) + src =src+ 2 + dst =dst+ 2 + end + end + end + end + end + for _, rec in __iter(c.blockEntities) do + local be = Mc.blockEntity(rec, "flat") + if be then + local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] + if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then + be.pos = { px, py, pz } + table.insert(bes, be) + end + end + end + for _, ent in __iter(c.entities) do + table.insert(ents, ent) + end + end + local v = Mc.voxels(sx, sy, sz, states, grid) + local b = v.blocks +b.blockEntities = bes + b.entities = ents + local scene = Types.Scene.new() + scene.voxels = { v } + scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } + scene.roots = { 1 } + scene.meta.up = "y" + scene.meta.unit = 1 + local rx, rz = regionCoords(o) + scene.meta.source = { format = "mca", region = rx and{ rx, rz } or nil, chunks = infos } + return scene, nil +end + +return Mca +end +__FILES["model/mca/Chunk"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three +-- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least +-- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = +-- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through +-- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Chunk = {} + +local Packed = Mc.Packed + + + + + + + + + + + +local function int(v) +local n = Nbt.number(v) + return (n and n == n and n % 1 == 0 and{n }or{nil +})[1]end + +local function list(v) +return (type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) and{v }or{{} +})[1]end + +-- a palette section (1.13+): states from the palette compounds, cells from the packed array +local function paletted(y, palette, data, minBits, spanning) +local states = (table.create(#palette) ) +for i, c in __iter(palette) do + local s = Mc.stateFromNbt(c) + if not s then + return nil, "section " .. y .. ": bad palette entry " .. i + end + states[i] = s + end + if #states == 0 then + return nil, nil + end + local cells = buffer.create(8192) + if #states > 1 or data ~= nil then + if not (Nbt.isTag(data) and data.type == "longArray") then + return nil, "section " .. y .. ": no block state data" + end + local bits = Packed.bitsFor(#states, minBits) + local ok, e = Packed.unpack(data.value, bits, 4096, spanning, cells, #states) + if not ok then + return nil, "section " .. y .. ": " .. tostring(e) + end + end + return { y = y, states = states, cells = cells }, nil +end + +-- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk +function Chunk.blocks(root) +if type(root) ~= "table" or not Types.isObject(root) then + return nil, "chunk NBT is not a compound" + end + local dv = int(root.DataVersion) + local level = (Types.isObject(root.Level) and{root.Level }or{root +})[1] local x, z = int(level.xPos), int(level.zPos) + if not x or not z then + return nil, "chunk without xPos / zPos" + end + local out= { x = x, z = z, dataVersion = dv, sections = {}, blockEntities = {}, entities = list(level.Entities) } + if root.sections ~= nil then + -- 1.18+ + for _, s in __iter(list(root.sections)) do + local y = int(s.Y) + local bs = s.block_states + if y and type(bs) == "table" and not Nbt.isTag(bs) then + local sec, e = paletted(y, list(bs.palette), bs.data, 4, false) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + end + end + out.blockEntities = list(root.block_entities) + return out, nil + end + for _, s in __iter(list(level.Sections)) do + local y = int(s.Y) + if y then + if s.Palette ~= nil then + local sec, e = paletted(y, list(s.Palette), s.BlockStates, 4, (dv or 0) < 2529) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + elseif type(s.Blocks) == "buffer" then + local blocks = s.Blocks +if buffer.len(blocks) < 4096 then + return nil, "section " .. y .. ": short Blocks array" + end + local data = (type(s.Data) == "buffer" and buffer.len(s.Data) >= 2048 and{s.Data }or{nil +})[1] local add = (type(s.Add) == "buffer" and buffer.len(s.Add) >= 2048 and{s.Add }or{nil +})[1] local slots= {} + local states= {} + local cells = buffer.create(8192) + for i = 0, 4095 do + local id = buffer.readu8(blocks, i) + if add then + id =id+ Packed.nibble(add, 0, i, false) * 256 + end + local d = (data and{(Packed.nibble(data, 0, i, false) )}or{0 +})[1] local key = id * 16 + d + local slot = slots[key] + if not slot then + table.insert(states, Mc.legacyState(id, d)) + slot = #states - 1 + slots[key] = slot + end + buffer.writeu16(cells, i * 2, slot ) + end + table.insert(out.sections, { y = y, states = states, cells = cells }) + end + end + end + out.blockEntities = list(level.TileEntities) + return out, nil +end + +return Chunk +end +__FILES["model/mca/Lz4Block"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 +-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | +-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the +-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +local Lz4 = __include("codecs/compress/Lz4") + +local Lz4Block = {} + +local MAGIC = "LZ4Block" + +-- decode(buf, offset, length, maxBytes) -> buffer | nil, message +function Lz4Block.decode(b, offset, length, maxBytes) +local p, e = offset, offset + length + local parts, total = {}, 0 + while true do + if p + 21 > e then + if #parts > 0 and p >= e then + break -- some writers stop without the empty end block + end + return nil, "truncated LZ4 block header" + end + if buffer.readstring(b, p, 8) ~= MAGIC then + return nil, "bad LZ4Block magic" + end + local token = buffer.readu8(b, p + 8) + local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13) + p =p+ 21 + local method = math.floor(token / 16 )* 16 + if clen < 0 or dlen < 0 or p + clen > e then + return nil, "truncated LZ4 block" + end + if dlen == 0 and clen == 0 then + break + end + total =total+ dlen + if total > maxBytes then + return nil, "limit: chunk inflates past maxBytes" + end + if method == 0x10 then + if clen ~= dlen then + return nil, "raw LZ4 block length mismatch" + end + local out = buffer.create(dlen) + buffer.copy(out, 0, b, p, clen) + table.insert(parts, out) + elseif method == 0x20 then + local out, err = Lz4.decompress(b, p, clen, dlen) + if not out then + return nil, "LZ4: " .. tostring(err and err.message) + end + table.insert(parts, out) + else + return nil, "unsupported: LZ4Block method " .. method + end + p =p+ clen + end + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in __iter(parts) do + buffer.copy(res, w, part) + w =w+ buffer.len(part) + end + return res, nil +end + +return Lz4Block +end +__FILES["model/md2"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the +-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. +-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, +-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), +-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored +-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not +-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one +-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture +-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. +-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. +-- Not supported: the GL command list (the triangles carry the same geometry), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md2 = { + name = "md2", + category = "model", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local Scene = Types.Scene +local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Md2.sniff(r) +if r:remaining() < 68 then + return 0 + end + return Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- group frame names by their name without trailing digits, in file order +local function groups(names, fps) +local out= {} + for i, n in __iter(names) do + local stem = string.match(n, "^(.-)_?%d*$") or n + if stem == "" then + stem = n + end + local last = out[#out] + if last and last.name == stem and last.last == i - 1 then + last.last = i + else + table.insert(out, { name = stem, first = i, last = i, fps = fps }) + end + end + return out +end + +function Md2.decode(r, opts) +local size = r.limit - r.base + if not r:match("IDP2") then + return nil, Err.new((size < 4 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "bad magic", 0) + end + local h= {} + for i = 1, 16 do + h[i] = r:i32le() + end + if r.err then + return nil, r.err + end + local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14) + if version ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4) + end + if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then + return nil, Err.new(Err.CORRUPT, "bad counts", 8) + end + if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local function inside(o, n) +return o >= 0 and n >= 0 and o + n <= size + end + if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then + return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44) + end + if frameSize < 40 + nXyz * 4 then + return nil, Err.new(Err.CORRUPT, "frame size too small", 16) + end + local b, base = r.buf, r.base + -- skins + local skins= {} + for i = 0, nSkins - 1 do + local s = buffer.readstring(b, base + oSkins + i * 64, 64) + table.insert(skins, (string.match(s, "^[^%z]*")) ) + end + -- weld (xyz, st) pairs + local key= {} + local vx, vst= {}, {} + local indices= {} + for t = 0, nTris - 1 do + local o = base + oTris + t * 12 + local corner= {} + for c = 0, 2 do + local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2) + if xi >= nXyz or (nSt > 0 and si >= nSt) then + return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12) + end + local k = xi * 65536 + si + local v = key[k] + if not v then + table.insert(vx, xi) + table.insert(vst, si) + v = #vx - 1 + key[k] = v + end + corner[c + 1] = v + end + table.insert(indices, corner[3]) + table.insert(indices, corner[2]) + table.insert(indices, corner[1]) + end + local nv = #vx + local uv = buffer.create(nv * 8) + for i = 1, nv do + if nSt > 0 then + local o = base + oSt + vst[i] * 4 + writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1)) + writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) + end + end + -- frames + local frames= {} + local normals= {} + local names= {} + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + for f = 1, nFrames do + if morph or f == want then + local o = base + oFrames + (f - 1) * frameSize + local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) + local pos = buffer.create(nv * 12) + for i = 1, nv do + local p = o + 40 + vx[i] * 4 + writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx) + writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty) + writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz) + end + frames[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16) + names[f] = (string.match(nm, "^[^%z]*")) +end + local ib = buffer.create(#indices * 4) + for i, v in __iter(indices) do + writeu32(ib, (i - 1) * 4, v) + end + local prim= { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + if #skins > 0 then + for _, s in __iter(skins) do + table.insert(scene.textures, { name = s, uri = s }) + end + local mat = Scene.material(skins[1]) + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + table.insert(scene.materials, mat) + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + local fr= {} + for f = 1, nFrames do + fr[f] = frames[f] + end + Rig.morph(prim, fr, normals) + local w = table.create(nFrames, 0) + scene.meshes[1].weights = w + Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR") + end + scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false } + return scene, nil +end + +return Md2 +end +__FILES["model/md3"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format +-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format" +-- notes (PhaethonH); no code taken. +-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame +-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left +-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all +-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes +-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation). +-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md3 = { + name = "md3", + category = "model", + extensions = { "md3" }, + mime = { "model/x-md3" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true, tags = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local Scene = Types.Scene +local readi16, readu8, readi32, readf32, writef32, writeu32 = buffer.readi16, buffer.readu8, buffer.readi32, buffer.readf32, buffer.writef32, buffer.writeu32 +local K = math.pi / 128 -- the engine maps a byte to 2 pi / 256 (tr_surface.c LatLongToNormal) + +-- ------------------------------------------------------------------------------------------------ sniff +function Md3.sniff(r) +if r:remaining() < 108 then + return 0 + end + return Sniff.magic(r, "IDP3") == 1 and r:peekU8(4) == 15 and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function cstr(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +function Md3.decode(r, opts) +local size = r.limit - r.base + if size < 108 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + if not r:match("IDP3") then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 15 then + return nil, Err.new(Err.UNSUPPORTED, "MD3 version " .. version, 4) + end + local b, base = r.buf, r.base + local name = cstr(b, base + 8, 64) + r:skip(68) + local nFrames, nTags, nSurf, _nSkins = r:i32le(), r:i32le(), r:i32le(), r:i32le() + local oFrames, oTags, oSurf = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if nFrames <= 0 or nTags < 0 or nSurf < 0 or nFrames > 65536 or nTags > 4096 or nSurf > 4096 then + return nil, Err.new(Err.CORRUPT, "bad counts", 76) + end + local function inside(o, n) +return o >= 0 and n >= 0 and o + n <= size + end + if not inside(oFrames, nFrames * 56) or not inside(oTags, nFrames * nTags * 112) then + return nil, Err.new(Err.TRUNCATED, "frames / tags past the end", 88) + end + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + local maxV = opts and opts.maxVertices or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + local mesh= { name = (name ~= "" and{name }or{nil})[1], primitives = {} } + scene.meshes[1] = mesh + scene.nodes[1] = { name = mesh.name, children = {}, mesh = 1 } + scene.roots[1] = 1 + local total = 0 + local so = oSurf + for s = 1, nSurf do + if not inside(so, 108) or cstr(b, base + so, 4) ~= "IDP3" then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad header", so) + end + local p = base + so + local sname = cstr(b, p + 4, 64) + local sFrames, nShaders, nVerts, nTris = readi32(b, p + 72), readi32(b, p + 76), readi32(b, p + 80), readi32(b, p + 84) + local oTri, oSh, oSt, oXyz, oEnd = readi32(b, p + 88), readi32(b, p + 92), readi32(b, p + 96), readi32(b, p + 100), readi32(b, p + 104) + if sFrames ~= nFrames or nShaders < 0 or nVerts < 0 or nTris < 0 or oEnd <= 0 then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": bad counts", so + 72) + end + total =total+ nVerts * nFrames + if total > maxV then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + if not (inside(so + oTri, nTris * 12) and inside(so + oSh, nShaders * 68) and inside(so + oSt, nVerts * 8) and inside(so + oXyz, nVerts * nFrames * 8)) then + return nil, Err.new(Err.TRUNCATED, "surface " .. s .. " past the end", so) + end + local ib = buffer.create(nTris * 12) + local idx = (table.create(nTris * 3, 0) ) +for t = 0, nTris - 1 do + for c = 0, 2 do + local v = readi32(b, p + oTri + t * 12 + c * 4) + if v < 0 or v >= nVerts then + return nil, Err.new(Err.CORRUPT, "surface " .. s .. ": triangle index out of range", so + oTri + t * 12) + end + idx[t * 3 + 3 - c] = v + end + end + for i, v in __iter(idx) do + writeu32(ib, (i - 1) * 4, v) + end + local uv = buffer.create(nVerts * 8) + buffer.copy(uv, 0, b, p + oSt, nVerts * 8) + local frames, normals= {}, {} + for f = 1, nFrames do + if morph or f == want then + local pos, nrm = buffer.create(nVerts * 12), buffer.create(nVerts * 12) + local q = p + oXyz + (f - 1) * nVerts * 8 + for v = 0, nVerts - 1 do + local o = q + v * 8 + writef32(pos, v * 12, readi16(b, o) / 64) + writef32(pos, v * 12 + 4, readi16(b, o + 2) / 64) + writef32(pos, v * 12 + 8, readi16(b, o + 4) / 64) + local lng, lat = readu8(b, o + 6) * K, readu8(b, o + 7) * K + writef32(nrm, v * 12, math.cos(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 4, math.sin(lat) * math.sin(lng)) + writef32(nrm, v * 12 + 8, math.cos(lng)) + end + frames[f], normals[f] = pos, nrm + end + end + local prim= { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nVerts), + NORMAL = Scene.accessor(normals[want], "f32", 3, nVerts), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nVerts), + }, + indices = Scene.accessor(ib, "u32", 1, nTris * 3), + mode = "triangles", + extras = { md3 = { surface = sname } }, + } + if morph then + Rig.morph(prim, frames, normals) + end + local shaders= {} + for k = 0, nShaders - 1 do + table.insert(shaders, cstr(b, p + oSh + k * 68, 64)) + end + local mat = Scene.material(sname) + mat.metallic = 0 + if shaders[1] and shaders[1] ~= "" then + table.insert(scene.textures, { name = shaders[1], uri = shaders[1] }) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { md3 = { shaders = shaders } } + table.insert(scene.materials, mat) + prim.material = #scene.materials + table.insert(mesh.primitives, prim) + so =so+ oEnd + end + -- frames and tags + local frameNames= {} + for f = 0, nFrames - 1 do + frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16) + end + local tagNodes= {} + local tracks= {} + local tagNames= {} + for k = 0, nTags - 1 do + local tr= { translation = {}, rotation = {} } + local first= nil + for f = 0, nFrames - 1 do + local o = base + oTags + (f * nTags + k) * 112 + local t = { readf32(b, o + 64), readf32(b, o + 68), readf32(b, o + 72) } + local a= {} + for i = 0, 8 do + a[i + 1] = readf32(b, o + 76 + i * 4) + end + local m = { a[1], a[2], a[3], 0, a[4], a[5], a[6], 0, a[7], a[8], a[9], 0, t[1], t[2], t[3], 1 } + local q = Mat4.quat(m) + for c = 1, 3 do + table.insert(tr.translation , t[c]) + end + for c = 1, 4 do + table.insert(tr.rotation , q[c]) + end + if f == want - 1 then + first = { name = cstr(b, o, 64), t = t, q = q } + end + end + table.insert(tagNames, first.name) + table.insert(scene.nodes, { name = first.name, children = {}, translation = first.t, rotation = first.q, extras = { md3 = { tag = true } } }) + table.insert(scene.nodes[1].children, #scene.nodes) + tagNodes[k + 1] = #scene.nodes + tracks[k + 1] = tr + end + if morph and nFrames > 1 then + scene.meshes[1].weights = table.create(nFrames, 0) + local fps = opts and opts.fps or 15 + Rig.morphAnimation(scene, 1, nFrames, { { name = "frames", first = 1, last = nFrames, fps = fps } }, "LINEAR") + if nTags > 0 then + local times= {} + for f = 1, nFrames do + times[f] = (f - 1) / fps + end + local ai = Rig.animation(scene, "tags", tagNodes, times, tracks) + local tagAnim = (table.remove(scene.animations, ai) ) +for _, ch in __iter(tagAnim.channels) do + table.insert(scene.animations[1].channels, ch) + end + end + end + scene.meta.source = { format = "md3", name = name, frames = nFrames, frameNames = frameNames, tags = tagNames } + return scene, nil +end + +return Md3 +end +__FILES["model/md5"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim +-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from +-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by +-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless +-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom +-- units, z up. Not supported: writing, .md5camera. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/md5/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local Md5 = { + name = "md5", + category = "model", + extensions = { "md5mesh", "md5anim" }, + mime = { "model/x-md5mesh", "model/x-md5anim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, skins = true, animation = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function Md5.sniff(r) +local head = Sniff.text(r, 512, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + return string.match(head, "^MD5Version%s+%d+") and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function stem(name) +local base = string.match(name, "([^/\\]+)$") or name + return (string.gsub(base, "%.[^.]*$", "")) +end + +function Md5.decode(r, opts) +local text = Sniff.dropBom(r:string(r:remaining())) + if string.find(text, "numAnimatedComponents", 1, true) then + local a, msg = Read.anim(text) + if not a then + return nil, Err.from(msg) + end + return Read.animScene(a, (opts and type(opts.name) == "string" and{(stem(opts.name) )}or{"animation"})[1]), nil + end + local scene, byName = Read.mesh(text, opts ) + if not scene then + return nil, Err.from(byName) + end + if opts and type(opts.anims) == "table" then + for _, name in __iter(opts.anims) do + local got = (type(name) == "string" and{(Input.sibling(opts, name) )}or{nil +})[1] local src = (got and{(buffer.tostring(got) )}or{nil +})[1] if not src then + if not opts.skipMissing then + return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)") + end + else + local a, msg = Read.anim(Sniff.dropBom(src)) + if not a then + return nil, Err.from("animation " .. name .. ": " .. tostring(msg)) + end + Read.addAnim(scene, byName, a, stem(name)) + end + end + end + return scene, nil +end + +return Md5 +end +__FILES["model/md5/Read"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose: +-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive +-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed +-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim: +-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at +-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding +-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 +-- ------------------------------------------------------------------------------------------------ tokens + + + + + +local function token(L) +local s = L.text + while true do + local a = string.find(s, "%S", L.pos) + if not a then + L.pos = #s + 1 + return nil + end + if string.sub(s, a, a + 1) == "//" then + local nl = string.find(s, "\n", a, true) + L.pos = (nl and((nl + 1 ))or((#s + 1 +))) else + L.pos = a + break + end + end + local c = string.sub(s, L.pos, L.pos) + if c == '"' then + local e = string.find(s, '"', L.pos + 1, true) + if not e then + L.err = "unterminated string" + L.pos = #s + 1 + return nil + end + local v = string.sub(s, L.pos + 1, e - 1) + L.pos = e + 1 + return '"' .. v + end + if c == "(" or c == ")" or c == "{" or c == "}" then + L.pos =L.pos+ 1 + return c + end + local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1) + local v = string.sub(s, L.pos, e - 1) + L.pos = e + return v +end + +local function num(L) +local t = token(L) + local v = t and tonumber(t) + if not v then + L.err = L.err or ("expected a number, got " .. tostring(t)) + return 0 + end + return v +end + +local function str(L) +local t = token(L) + if not t or string.sub(t, 1, 1) ~= '"' then + L.err = L.err or ("expected a string, got " .. tostring(t)) + return "" + end + return string.sub(t, 2) +end + +local function expect(L, want) + local t = token(L) + if t ~= want then + L.err = L.err or ("expected " .. want .. ", got " .. tostring(t)) + end +end + +local function vec(L, n) +expect(L, "(") + local v = table.create(n, 0) + for i = 1, n do + v[i] = num(L) + end + expect(L, ")") + return v +end + +-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it) +local function quat(x, y, z) +local t = 1 - x * x - y * y - z * z + return { x, y, z, t < 0 and 0 or-math.sqrt(t) } +end + +local function rotate(q, vx, vy, vz) +local qx, qy, qz, qw = q[1], q[2], q[3], q[4] + -- v + 2 w (q x v) + 2 q x (q x v) + local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx) + return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx) +end +-- ------------------------------------------------------------------------------------------------ md5mesh +-- mesh(text, opts) -> Scene, joint node indices by name | nil, message + + + +function Read.mesh(text, opts) +local L= { text = text, pos = 1, err = nil } + local joints= {} + local scene = Scene.new() + scene.meta.up = "z" + local root= { name = "md5", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local version= nil + local mesh= { primitives = {} } + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + local skinIndex = 0 + local nodes= {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numJoints" or t == "numMeshes" then + num(L) + elseif t == "joints" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad joint line" + end + local parent = num(L) + local p, q = vec(L, 3), vec(L, 3) + table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) }) + end + local list= {} + for i, j in __iter(joints) do + list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q } + end + local n, si = Rig.skeleton(scene, list, "world", 1) + nodes, skinIndex = n, si + elseif t == "mesh" then + expect(L, "{") + local shader = "" + local verts= {} -- s, t, startWeight, countWeight + local tris= {} + local weights= {} -- joint, bias, x, y, z + while not L.err do + local k = token(L) + if k == "}" then + break + elseif k == "shader" then + shader = str(L) + elseif k == "numverts" or k == "numtris" or k == "numweights" then + local n = num(L) + total =total+ (k == "numverts" and{n }or{0 +})[1] if total > maxV then + return nil, "limit: too many vertices" + end + elseif k == "vert" then + local i = num(L) + local st = vec(L, 2) + verts[i + 1] = { st[1], st[2], num(L), num(L) } + elseif k == "tri" then + num(L) + local a, b, c = num(L), num(L), num(L) + table.insert(tris, c) + table.insert(tris, b) + table.insert(tris, a) + elseif k == "weight" then + local i = num(L) + local j, bias = num(L), num(L) + local p = vec(L, 3) + weights[i + 1] = { j, bias, p[1], p[2], p[3] } + else + return nil, "unknown mesh keyword " .. tostring(k) + end + end + local nv = #verts + local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8) + local lists= {} + for vi = 1, nv do + local v = verts[vi] + if not v then + return nil, "missing vert " .. (vi - 1) + end + local x, y, z = 0, 0, 0 + local l= {} + for w = v[3] + 1, v[3] + v[4] do + local wt = weights[w] + local j = wt and joints[wt[1] + 1] + if not wt or not j then + return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1) + end + local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5]) + x =x+ (j.pos[1] + rx) * wt[2] + y =y+ (j.pos[2] + ry) * wt[2] + z =z+ (j.pos[3] + rz) * wt[2] + table.insert(l, wt[1]) + table.insert(l, wt[2]) + end + writef32(pos, (vi - 1) * 12, x) + writef32(pos, (vi - 1) * 12 + 4, y) + writef32(pos, (vi - 1) * 12 + 8, z) + writef32(uv, (vi - 1) * 8, v[1]) + writef32(uv, (vi - 1) * 8 + 4, v[2]) + lists[vi] = l + end + for _, ix in __iter(tris) do + if ix < 0 or ix >= nv then + return nil, "triangle index out of range" + end + end + local ib = buffer.create(#tris * 4) + for i, ix in __iter(tris) do + writeu32(ib, (i - 1) * 4, ix) + end + local attrs= { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #joints > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(shader) + mat.metallic = 0 + table.insert(scene.textures, { name = shader, uri = shader }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" , material = #scene.materials }) + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, (version and(("unsupported: MD5Version " .. version ))or("no MD5Version" +)) end + if #mesh.primitives > 0 then + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = (#joints > 0 and{skinIndex }or{nil })[1]}) + table.insert(root.children, #scene.nodes) + end + local byName= {} + for i, j in __iter(joints) do + byName[j.name] = nodes[i] + end + scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives } + return scene, byName +end +-- ------------------------------------------------------------------------------------------------ md5anim +-- anim(text) -> Anim | nil, message + + + + + + + + + +function Read.anim(text) +local L= { text = text, pos = 1, err = nil } + local a= { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} } + local hier= {} -- flags, startIndex + local version= nil + local nComp = 0 + local frames= {} + while not L.err do + local t = token(L) + if not t then + break + end + if t == "MD5Version" then + version = num(L) + elseif t == "commandline" then + str(L) + elseif t == "numFrames" then + a.frames = num(L) + elseif t == "numJoints" then + num(L) + elseif t == "frameRate" then + a.frameRate = num(L) + elseif t == "numAnimatedComponents" then + nComp = num(L) + if nComp < 0 or nComp > 2 ^ 20 then + return nil, "bad numAnimatedComponents" + end + elseif t == "hierarchy" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if not s or string.sub(s, 1, 1) ~= '"' then + return nil, "bad hierarchy line" + end + local parent, flags, start = num(L), num(L), num(L) + table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 }) + table.insert(hier, { flags, start }) + end + elseif t == "bounds" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" or s == nil then + break + end + end + elseif t == "baseframe" then + expect(L, "{") + while not L.err do + local s = token(L) + if s == "}" then + break + end + if s ~= "(" then + return nil, "bad baseframe line" + end + L.pos =L.pos- 1 + local p, q = vec(L, 3), vec(L, 3) + table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] }) + end + elseif t == "frame" then + local fi = num(L) + expect(L, "{") + local vals = table.create(nComp, 0) + for k = 1, nComp do + vals[k] = num(L) + end + expect(L, "}") + if fi < 0 or fi > 2 ^ 20 then + return nil, "bad frame index" + end + frames[fi + 1] = vals + else + return nil, "unknown keyword " .. t + end + end + if L.err then + return nil, L.err + end + if version ~= 10 then + return nil, (version and(("unsupported: MD5Version " .. version ))or("no MD5Version" +)) end + if #a.base ~= #a.joints then + return nil, "baseframe and hierarchy disagree" + end + for f = 1, a.frames do + if not frames[f] then + return nil, "missing frame " .. (f - 1) + end + end + for j, h in __iter(hier) do + local tr, rot= {}, {} + local flags, start = h[1], h[2] + for f = 1, a.frames do + local v = table.clone(a.base[j]) + local k = start + 1 + for bit = 0, 5 do + if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then + v[bit + 1] = frames[f][k] or v[bit + 1] + k =k+ 1 + end + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = quat(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + a.tracks[j] = { translation = tr, rotation = rot } + end + return a, nil +end + +-- addAnim(scene, nodes by joint name, anim, name) -> channels added +function Read.addAnim(scene, byName, a, name) +local nodes= {} + local tracks= {} + for j, jt in __iter(a.joints) do + local nd = byName[jt.name] + if nd then + table.insert(nodes, nd) + tracks[#nodes] = a.tracks[j] + end + end + local times= {} + local rate = (a.frameRate > 0 and{a.frameRate }or{24 +})[1] for f = 1, a.frames do + times[f] = (f - 1) / rate + end + local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR") + return #scene.animations[ai].channels +end + +-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation +function Read.animScene(a, name) +local scene = Scene.new() + scene.meta.up = "z" + table.insert(scene.nodes, { name = "md5", children = {} }) + scene.roots[1] = 1 + local list= {} + for j, jt in __iter(a.joints) do + local b = a.base[j] + list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) } + end + local nodes = Rig.skeleton(scene, list, "local", 1) + local byName= {} + for j, jt in __iter(a.joints) do + byName[jt.name] = nodes[j] + end + Read.addAnim(scene, byName, a, name) + scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate } + return scene +end + +return Read +end +__FILES["model/mdl"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10: +-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the +-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string), +-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette = +-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx +-- files) is UNSUPPORTED. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Quake = __include("model/mdl/Quake") +local HalfLife = __include("model/mdl/HalfLife") + +-- ------------------------------------------------------------------------------------------------ contract +local Mdl = { + name = "mdl", + category = "model", + extensions = { "mdl" }, + mime = { "model/x-mdl" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + +function Mdl.sniff(r) +local m = r:peek(4) + local v = r:peekU8(4) + if (m == "IDPO" and v == 6) or (m == "IDST" and v == 10) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mdl.decode(r, opts) +local size = r.limit - r.base + if size < 8 then + return nil, Err.new(Err.TRUNCATED, "header", 0) + end + local magic, version = r:peek(4), buffer.readi32(r.buf, r.base + 4) + local scene, msg +if magic == "IDPO" then + if version ~= 6 then + return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4) + end + local pal = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{(Input.sibling(opts, "gfx/palette.lmp") +)})[1] if pal and buffer.len(pal) < 768 then + pal = nil + end + scene, msg = Quake.decode(r.buf, r.base, size, pal, opts ) + elseif magic == "IDST" then + if version ~= 10 then + return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version .. " (Source engine models need .vvd / .vtx)", 4) + end + local o= opts and table.clone(opts ) or {} + o.textures = (opts and opts.textures and{(Bytes.toBuffer(opts.textures) )}or{nil +})[1] scene, msg = HalfLife.decode(r.buf, r.base, size, o) + else + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +return Mdl +end +__FILES["model/mdl/HalfLife"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h +-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken. +-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts -> +-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans +-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 = +-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family -> +-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only). +-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone +-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "<name>t.mdl" (pass it +-- as opts.textures = that file's bytes). +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local HalfLife = {} + +local Scene = Types.Scene +local readi32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32 +local writef32, writeu32, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu16 + + + + +local function str(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message +local function textures(b, base, size, maxPixels) +local n, at = readi32(b, base + 180), readi32(b, base + 184) + if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then + return nil, "bad texture table" + end + local out= {} + local names= {} + for i = 0, n - 1 do + local o = base + at + i * 80 + local w, h, data = readi32(b, o + 68), readi32(b, o + 72), readi32(b, o + 76) + if w <= 0 or h <= 0 or w * h > maxPixels or data < 0 or data + w * h + 768 > size then + return nil, "bad texture " .. i + end + local img = Types.Image.new(w, h) + local pal = Pixels.palette(b, base + data + w * h, 256) + Pixels.indexed(b, base + data, w, 8, img.pixels, w, h, true, pal) + local flags = readi32(b, o + 64) + img.meta.source = { format = "mdl", flags = flags } + out[i + 1] = img + names[i + 1] = str(b, o, 64) + end + return out, names +end + +-- one animation value: bone default + stored value * scale (frame f, 0-based) +local function animValue(b, at, limit, f) +local p = at + local k = f + for _ = 1, 65536 do + if p + 2 > limit then + return nil + end + local valid, total = readu8(b, p), readu8(b, p + 1) + if total == 0 then + return nil + end + if total > k then + local idx = (valid > k and((k + 1 ))or(valid +)) if p + idx * 2 + 2 > limit then + return nil + end + return readi16(b, p + idx * 2) + end + k =k- total + p =p+ (valid + 1) * 2 + end + return nil +end + +-- decode(b, base, size, opts) -> Scene | nil, message +function HalfLife.decode(b, base, size, opts) +if size < 244 then + return nil, "truncated header" + end + local limit = base + size + local function hdr(o) +return readi32(b, base + o) + end + local nBones, oBones = hdr(140), hdr(144) + local nSeq, oSeq = hdr(164), hdr(168) + local nTex = hdr(180) + local nSkinRef, nFamilies, oSkins = hdr(192), hdr(196), hdr(200) + local nParts, oParts = hdr(204), hdr(208) + local function inside(o, n) +return o >= 0 and n >= 0 and o + n <= size + end + if nBones < 0 or nBones > 256 or not inside(oBones, nBones * 112) then + return nil, "bad bone table" + end + if nSeq < 0 or nSeq > 4096 or not inside(oSeq, nSeq * 176) then + return nil, "bad sequence table" + end + if nParts < 0 or nParts > 256 or not inside(oParts, nParts * 76) then + return nil, "bad body part table" + end + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + local scene = Scene.new() + scene.meta.up = "z" + -- bones + local bones= {} + local joints= {} + for i = 0, nBones - 1 do + local o = base + oBones + i * 112 + local value, scale = {}, {} + for k = 0, 5 do + value[k + 1] = readf32(b, o + 64 + k * 4) + scale[k + 1] = readf32(b, o + 88 + k * 4) + end + local parent = readi32(b, o + 32) + bones[i + 1] = { name = str(b, o, 32), parent = parent + 1, value = value, scale = scale } + joints[i + 1] = { name = bones[i + 1].name, parent = parent + 1, translation = { value[1], value[2], value[3] }, rotation = Rig.angles(value[4], value[5], value[6]) } + end + local root= { name = str(b, base + 8, 64), children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1) + -- textures and skins + local texSrc, texBase, texSize = b, base, size + if nTex == 0 and opts and opts.textures then + texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures) + if texSize < 244 or buffer.readstring(texSrc, 0, 4) ~= "IDST" then + return nil, "opts.textures is not a studio texture file" + end + nSkinRef, nFamilies, oSkins = readi32(texSrc, 192), readi32(texSrc, 196), readi32(texSrc, 200) + end + local images, texNames = textures(texSrc, texBase, texSize, maxPixels) + if not images then + return nil, texNames +end + local names = texNames +for i, img in __iter(images) do + table.insert(scene.textures, { name = names[i], image = img, uri = names[i] }) + local mat = Scene.material(names[i]) + mat.metallic = 0 + mat.baseColorTexture = { texture = i } + table.insert(scene.materials, mat) + end + local skinMap= {} + if nSkinRef > 0 and nFamilies > 0 and oSkins >= 0 and oSkins + nSkinRef * 2 <= texSize then + for r = 0, nSkinRef - 1 do + skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1 + end + end + -- body parts + local totalVerts = 0 + for part = 0, nParts - 1 do + local po = base + oParts + part * 76 + local pname = str(b, po, 64) + local nModels, oModels = readi32(b, po + 64), readi32(b, po + 72) + local pick = (opts and opts.bodies and opts.bodies[part + 1]) or 1 + if nModels > 0 and pick >= 1 and pick <= nModels and inside(oModels, nModels * 112) then + local mo = base + oModels + (pick - 1) * 112 + local nMesh, oMesh = readi32(b, mo + 72), readi32(b, mo + 76) + local nVerts, oVertInfo, oVerts = readi32(b, mo + 80), readi32(b, mo + 84), readi32(b, mo + 88) + local nNorms, oNormInfo, oNorms = readi32(b, mo + 92), readi32(b, mo + 96), readi32(b, mo + 100) + if nMesh < 0 or nMesh > 4096 or not inside(oMesh, nMesh * 20) or nVerts < 0 or not inside(oVertInfo, nVerts) or not inside(oVerts, nVerts * 12) or nNorms < 0 or not inside(oNormInfo, nNorms) or not inside(oNorms, nNorms * 12) then + return nil, "body part " .. pname .. ": bad model tables" + end + local mesh= { name = pname, primitives = {}, extras = { mdl = { model = str(b, mo, 64), models = nModels } } } + for m = 0, nMesh - 1 do + local me = base + oMesh + m * 20 + local oTri, skinref = readi32(b, me + 4), readi32(b, me + 8) + local tex = skinMap[skinref + 1] or (skinref + 1) + local img = images[tex] + local tw, th = (img and{img.width }or{1})[1], (img and{img.height }or{1 +})[1] -- triangle commands + local weld= {} + local corners= {} + local indices= {} + local p = base + oTri + if oTri < 0 or oTri >= size then + return nil, "bad triangle command offset" + end + while true do + if p + 2 > limit then + return nil, "truncated triangle commands" + end + local n = readi16(b, p) + p =p+ 2 + if n == 0 then + break + end + local fan = n < 0 + n = math.abs(n) + if p + n * 8 > limit then + return nil, "truncated triangle commands" + end + local ids= {} + for k = 0, n - 1 do + local o = p + k * 8 + local vi, ni, s, t = readu16(b, o), readu16(b, o + 2), readi16(b, o + 4), readi16(b, o + 6) + if vi >= nVerts or ni >= nNorms then + return nil, "triangle command vertex out of range" + end + local key = vi .. ":" .. ni .. ":" .. s .. ":" .. t + local id = weld[key] + if not id then + table.insert(corners, { vi, ni, s, t }) + id = #corners - 1 + weld[key] = id + end + ids[k + 1] = id + end + p =p+ n * 8 + for k = 3, n do + local a, c2, c3 + if fan then + a, c2, c3 = ids[1], ids[k - 1], ids[k] + elseif k % 2 == 1 then + a, c2, c3 = ids[k - 2], ids[k - 1], ids[k] + else + a, c2, c3 = ids[k - 1], ids[k - 2], ids[k] + end + -- studio models wind clockwise: reverse + table.insert(indices, c3) + table.insert(indices, c2) + table.insert(indices, a) + end + end + local nv = #corners + totalVerts =totalVerts+ nv + if totalVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for i, c in __iter(corners) do + local o = (i - 1) * 12 + local bone = readu8(b, base + oVertInfo + c[1]) + local nbone = readu8(b, base + oNormInfo + c[2]) + local vo, no = base + oVerts + c[1] * 12, base + oNorms + c[2] * 12 + local x, y, z = readf32(b, vo), readf32(b, vo + 4), readf32(b, vo + 8) + local m4 = world[bone + 1] + if m4 then + x, y, z = Mat4.point(m4, x, y, z) + end + writef32(pos, o, x) + writef32(pos, o + 4, y) + writef32(pos, o + 8, z) + local nx, ny, nz = readf32(b, no), readf32(b, no + 4), readf32(b, no + 8) + local n4 = world[nbone + 1] + if n4 then + nx, ny, nz = n4[1] * nx + n4[5] * ny + n4[9] * nz, n4[2] * nx + n4[6] * ny + n4[10] * nz, n4[3] * nx + n4[7] * ny + n4[11] * nz + end + writef32(nrm, o, nx) + writef32(nrm, o + 4, ny) + writef32(nrm, o + 8, nz) + writef32(uv, (i - 1) * 8, c[3] / tw) + writef32(uv, (i - 1) * 8 + 4, c[4] / th) + writeu16(jb, (i - 1) * 8, math.min(bone, math.max(0, nBones - 1))) + writef32(wb, (i - 1) * 16, 1) + end + local ib = buffer.create(#indices * 4) + for i, v in __iter(indices) do + writeu32(ib, (i - 1) * 4, v) + end + local attrs= { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if nBones > 0 then + attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, nv) + end + table.insert(mesh.primitives, { + attributes = attrs, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles" , + material = (img and{tex }or{nil})[1], + }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = pname, children = {}, mesh = #scene.meshes, skin = (nBones > 0 and{skinIndex }or{nil })[1]}) + table.insert(root.children, #scene.nodes) + end + end + -- sequences + local seqs= {} + for s = 0, nSeq - 1 do + local so = base + oSeq + s * 176 + local label, fps, nFrames = str(b, so, 32), readf32(b, so + 32), readi32(b, so + 56) + local nBlends, oAnim, group = readi32(b, so + 120), readi32(b, so + 124), readi32(b, so + 156) + table.insert(seqs, { name = label, fps = fps, frames = nFrames, blends = nBlends, group = group }) + if group == 0 and nFrames > 0 and nFrames <= 65536 and nBones > 0 and inside(oAnim, nBones * 12) then + local rate = (fps > 0 and{fps }or{30 +})[1] local times= {} + for f = 0, nFrames - 1 do + times[f + 1] = f / rate + end + local tracks= {} + for j = 1, nBones do + local bn = bones[j] + local ao = base + oAnim + (j - 1) * 12 + local tr, rot = {}, {} + for f = 0, nFrames - 1 do + local v= {} + for k = 0, 5 do + local off = readu16(b, ao + k * 2) + local raw = (off ~= 0 and{(animValue(b, ao + off, limit, f) )}or{nil +})[1] v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] + end + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for k = 1, 4 do + table.insert(rot, q[k]) + end + end + tracks[j] = { translation = tr, rotation = rot } + end + Rig.animation(scene, label, jointNodes, times, tracks, "LINEAR") + end + end + scene.meta.source = { + format = "mdl", + variant = "halflife", + name = root.name, + bones = nBones, + sequences = seqs, + textures = #images, + skinFamilies = nFamilies, + hitboxes = hdr(156), + attachments = hdr(212), + } + return scene, nil +end + +return HalfLife +end +__FILES["model/mdl/Quake"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et +-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken. +-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette; +-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per +-- side); simple and grouped frames become morph targets with one animation per frame-name group. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Rig = __include("codecs/model/Rig") + +local Quake = {} + +local Scene = Types.Scene +local readi32, readf32, readu8, writef32, writeu32 = buffer.readi32, buffer.readf32, buffer.readu8, buffer.writef32, buffer.writeu32 + + + +local function name16(b, at) +return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) +end + +-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base) +function Quake.decode(b, base, size, palette, opts) +if size < 84 then + return nil, "truncated header" + end + local scale = { readf32(b, base + 8), readf32(b, base + 12), readf32(b, base + 16) } + local origin = { readf32(b, base + 20), readf32(b, base + 24), readf32(b, base + 28) } + local nSkins, sw, sh = readi32(b, base + 48), readi32(b, base + 52), readi32(b, base + 56) + local nVerts, nTris, nFrames = readi32(b, base + 60), readi32(b, base + 64), readi32(b, base + 68) + if nSkins < 0 or sw < 0 or sh < 0 or nVerts <= 0 or nTris < 0 or nFrames <= 0 or nSkins > 1024 or nFrames > 65536 then + return nil, "bad counts" + end + if sw * sh > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: skin too big" + end + if nFrames * nVerts > (opts and opts.maxVertices or 2 ^ 24) then + return nil, "limit: too many vertices" + end + local p = 84 + local function need(n) +return n >= 0 and p + n <= size + end + -- skins + local pal = (palette and{(Pixels.palette(palette, 0, 256) )}or{nil +})[1] local skins= {} + local px = sw * sh + for _ = 1, nSkins do + if not need(4) then + return nil, "truncated skins" + end + local group = readi32(b, base + p) + p =p+ 4 + local count = 1 + if group ~= 0 then + if not need(4) then + return nil, "truncated skin group" + end + count = readi32(b, base + p) + p =p+ 4 + if count <= 0 or count > 256 or not need(count * 4) then + return nil, "bad skin group" + end + p =p+ count * 4 + end + if not need(count * px) then + return nil, "truncated skin pixels" + end + local img = Types.Image.new(sw, sh) + if pal then + Pixels.indexed(b, base + p, sw, 8, img.pixels, sw, sh, true, pal) + else + for i = 0, px - 1 do + local v = readu8(b, base + p + i) + writeu32(img.pixels, i * 4, 0xFF000000 + v * 0x10101) + end + end + img.meta.source = { format = "mdl", palette = pal ~= nil, frames = count } + table.insert(skins, img) + p =p+ count * px + end + -- texture coordinates and triangles + if not need(nVerts * 12 + nTris * 16) then + return nil, "truncated vertices / triangles" + end + local stAt = p + p =p+ nVerts * 12 + local weld= {} + local src, uvs= {}, {} + local indices= {} + for t = 0, nTris - 1 do + local o = base + p + t * 16 + local front = readi32(b, o) ~= 0 + local c= {} + for k = 1, 3 do + local v = readi32(b, o + k * 4) + if v < 0 or v >= nVerts then + return nil, "triangle vertex out of range" + end + local so = base + stAt + v * 12 + local seam = readi32(b, so) ~= 0 and not front + local key = v * 2 + (seam and 1 or 0) + local id = weld[key] + if not id then + table.insert(src, v) + local s = readi32(b, so + 4) + ((seam and((sw / 2 ))or(0))) + table.insert(uvs, (s + 0.5) / math.max(sw, 1)) + table.insert(uvs, (readi32(b, so + 8) + 0.5) / math.max(sh, 1)) + id = #src - 1 + weld[key] = id + end + c[k] = id + end + -- Quake's front faces are clockwise + table.insert(indices, c[3]) + table.insert(indices, c[2]) + table.insert(indices, c[1]) + end + p =p+ nTris * 16 + -- frames: simple (type 0) or groups of simple frames + local frameAt= {} + local names= {} + local fsize = 24 + nVerts * 4 + for _ = 1, nFrames do + if not need(4) then + return nil, "truncated frames" + end + local kind = readi32(b, base + p) + p =p+ 4 + if kind == 0 then + if not need(fsize) then + return nil, "truncated frame" + end + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p =p+ fsize + else + if not need(12) then + return nil, "truncated frame group" + end + local count = readi32(b, base + p) + if count <= 0 or count > 4096 or not need(12 + count * 4 + count * fsize) then + return nil, "bad frame group" + end + p =p+ (12 + count * 4 +) for _ = 1, count do + table.insert(frameAt, p + 8) + table.insert(names, name16(b, base + p + 8)) + p =p+ fsize + end + end + end + local nv = #src + local total = #frameAt + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, total) + local positions, normals= {}, {} + for f, at in __iter(frameAt) do + if morph or f == want then + local pos = buffer.create(nv * 12) + local vo = base + at + 16 + for i, v in __iter(src) do + for k = 0, 2 do + writef32(pos, (i - 1) * 12 + k * 4, readu8(b, vo + v * 4 + k) * scale[k + 1] + origin[k + 1]) + end + end + positions[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + end + local ib = buffer.create(#indices * 4) + for i, v in __iter(indices) do + writeu32(ib, (i - 1) * 4, v) + end + local uvb = buffer.create(nv * 8) + for i, v in __iter(uvs) do + writef32(uvb, (i - 1) * 4, v) + end + local prim= { + attributes = { + POSITION = Scene.accessor(positions[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uvb, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + for i, img in __iter(skins) do + table.insert(scene.textures, { name = "skin " .. i, image = img, sampler = { filter = "nearest" } }) + end + if #skins > 0 then + local mat = Scene.material("skin") + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + scene.materials[1] = mat + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + Rig.morph(prim, positions, normals) + scene.meshes[1].weights = table.create(total, 0) + local ranges= {} + for i, n in __iter(names) do + local stem = string.match(n, "^(.-)%d*$") or n + local last = ranges[#ranges] + if last and last.name == stem then + last.last = i + else + table.insert(ranges, { name = (stem ~= "" and{stem }or{n})[1], first = i, last = i, fps = opts and opts.fps or 10 }) + end + end + Rig.morphAnimation(scene, 1, total, ranges, "LINEAR") + end + scene.meta.source = { format = "mdl", variant = "quake", frames = total, frameNames = names, skinWidth = sw, skinHeight = sh, palette = pal ~= nil } + return scene, nil +end + +return Quake +end +__FILES["model/ms3d"] = function() +local __compat = __compat local type = __compat.type --!strict +-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of +-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested +-- against (no code ported). +-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and +-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in +-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; +-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use +-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse +-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes +-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, +-- the model comment / fps / frames / joint size in meta.source. meta.up = "y". +-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), +-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 +-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/ms3d/Read") +local Write = __include("model/ms3d/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ms3d = { + name = "ms3d", + category = "model", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + +function Ms3d.sniff(r) +local h = r:peek(14) + if string.sub(h, 1, 10) ~= Read.MAGIC then + return 0 + end + local v = string.byte(h, 11) + return (v == 3 or v == 4 )and 1 or 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ms3d.decode(r, opts) -- the scene builder is plain (not native) code: a bug there must not escape as an error + +local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, at) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ms3d.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return Ms3d +end +__FILES["model/ms3d/Read"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h +-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a +-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess +-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and +-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds +-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), +-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), +-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). +-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices +-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + +-- key positions). Never throws on bad data: returns nil, message, offset. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") + +local Read = {} + +local S = Types.Scene +local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring +local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32 + +Read.MAGIC = "MS3D000000" + +-- ------------------------------------------------------------------------------------------------ helpers + + +local function fixed(b, p, n) +local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1]end + +local function floats(values, comps) +local n = math.floor(#values / comps +) local a = S.accessor(nil, "f32", comps, n) + for i = 1, n * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +local function color(b, p) +return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) } +end + +-- the texture file name as a relative uri (MilkShape writes ".\name.jpg") +local function uri(s) +local u = string.gsub(s, "\\", "/") + u = string.gsub(u, "^%./", "") + return u +end + +-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion +local function euler(x, y, z) +return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) +end +-- ------------------------------------------------------------------------------------------------ parse +-- scene(b, base, limit, opts) -> Scene | nil, message, offset + + + + + + + +function Read.scene(b, base, limit, opts) +local p = base + local function need(n) +return p + n <= limit + end + if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then + return nil, "not a MilkShape 3D file", base + end + local version = readi32(b, p + 10) + if version ~= 3 and version ~= 4 then + return nil, "unsupported: version " .. version, p + 10 + end + p =p+ 14 + local maxV = opts and opts.maxVertices or 2 ^ 20 + -- vertices + if not need(2) then + return nil, "truncated vertex count", p + end + local nv = readu16(b, p) + p =p+ 2 + if not need(nv * 15) then + return nil, "truncated vertices", p + end + local verts= {} + for i = 1, nv do + local q = p + (i - 1) * 15 + verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } + end + p =p+ nv * 15 + -- triangles + if not need(2) then + return nil, "truncated triangle count", p + end + local nt = readu16(b, p) + p =p+ 2 + if not need(nt * 70) then + return nil, "truncated triangles", p + end + if nt * 3 > maxV then + return nil, "limit: more than " .. maxV .. " triangle corners", p + end + local triAt = p + p =p+ nt * 70 + -- groups + if not need(2) then + return nil, "truncated group count", p + end + local ng = readu16(b, p) + p =p+ 2 + local groups = {} + for _ = 1, ng do + if not need(35) then + return nil, "truncated group", p + end + local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} , material = -1, comment = nil } + local n = readu16(b, p + 33) + p =p+ 35 + if not need(n * 2 + 1) then + return nil, "truncated group triangles", p + end + for k = 0, n - 1 do + local ti = readu16(b, p + k * 2) + if ti >= nt then + return nil, "group triangle " .. ti .. " out of range", p + k * 2 + end + table.insert(g.tris, ti) + end + p =p+ n * 2 + g.material = readi8(b, p) + p =p+ 1 + table.insert(groups, g) + end + -- materials + if not need(2) then + return nil, "truncated material count", p + end + local nm = readu16(b, p) + p =p+ 2 + if not need(nm * 361) then + return nil, "truncated materials", p + end + local mats = {} + for i = 0, nm - 1 do + local q = p + i * 361 + table.insert(mats, { + name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64), + emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100), + mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil , + }) + end + p =p+ nm * 361 + -- animation header and joints (version 3 files may end here) + local fps, current, frames = 24, 0, 0 + local joints= {} + if need(12) then + fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8) + p =p+ 12 + if not need(2) then + return nil, "truncated joint count", p + end + local nj = readu16(b, p) + p =p+ 2 + for _ = 1, nj do + if not need(93) then + return nil, "truncated joint", p + end + local j= { + flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32), + rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) }, + pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) }, + rotKeys = {}, posKeys = {}, + } + local nr, np = readu16(b, p + 89), readu16(b, p + 91) + p =p+ 93 + if not need((nr + np) * 16) then + return nil, "truncated joint keys", p + end + for k = 0, nr + np - 1 do + local q = p + k * 16 + local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) } + table.insert((k < nr and{j.rotKeys }or{j.posKeys})[1], key) + end + p =p+ (nr + np) * 16 + table.insert(joints, j) + end + end + -- sub-versioned blocks + local source= { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } + local function comments(list) +if not need(4) then + return "truncated comments" + end + local n = readi32(b, p) + p =p+ 4 + for _ = 1, math.max(n, 0) do + if not need(8) then + return "truncated comment" + end + local index, len = readi32(b, p), readi32(b, p + 4) + p =p+ 8 + if len < 0 or not need(len) then + return "comment runs past the end" + end + if list[index + 1] then + list[index + 1].comment = readstring(b, p, len) + end + p =p+ len + end + return nil + end + if need(4) then + local sub = readi32(b, p) + p =p+ 4 + source.commentVersion = sub + if sub == 1 then + for _, list in __iter({ groups, mats, joints }) do + local e = comments(list) + if e then + return nil, e, p + end + end + if not need(4) then + return nil, "truncated model comment", p + end + local has = readi32(b, p) + p =p+ 4 + if has ~= 0 then + if not need(4) then + return nil, "truncated model comment", p + end + local len = readi32(b, p) + p =p+ 4 + if len < 0 or not need(len) then + return nil, "model comment runs past the end", p + end + source.comment = readstring(b, p, len) + p =p+ len + end + end + end + if need(4) then + local sub = readi32(b, p) + p =p+ 4 + source.vertexVersion = sub + local size = sub == 1 and 6 or(sub == 2 and 10 or(sub == 3 and 14 or 0 +)) if size > 0 and need(nv * size) then + for i = 1, nv do + local q = p + (i - 1) * size + local v = verts[i] + local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5) + if w0 + w1 + w2 > 0 then + local scale = (w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 )and 255 or 100 + v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) } + v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) } + end + end + p =p+ nv * size + end + end + if need(4) then + local sub = readi32(b, p) + p =p+ 4 + if (sub == 1 or sub == 2) and need(#joints * 12) then + for _, j in __iter(joints) do + j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } + p =p+ 12 + end + end + end + if need(16) and readi32(b, p) >= 1 then + source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12) + end + return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil +end + +-- ------------------------------------------------------------------------------------------------ build +function Read.build(b, triAt, verts, groups, mats, joints, source) +local scene = S.new() + scene.meta.up = "y" + scene.meta.source = source -- materials, textures + +for _, m in __iter(mats) do + local mat = S.material(m.name) + local d = m.diffuse + mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) } + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1) + mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] } + mat.alphaMode = m.transparency < 1 and"blend" or"opaque" + if m.texture ~= "" then + local tex= { name = m.texture, uri = uri(m.texture) } + table.insert(scene.textures, tex) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { + ms3d = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess, + transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment, + }, + } + table.insert(scene.materials, mat) + end + -- joints: nodes, rest pose, skin + local nj = #joints + local jointNode= {} + local byName= {} + local abs= {} + for i, j in __iter(joints) do + local node= { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) } + node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } } + table.insert(scene.nodes, node) + jointNode[i] = #scene.nodes + if byName[j.name] == nil then + byName[j.name] = i + end + end + for i, j in __iter(joints) do + local pi = byName[j.parent] + -- parents must come first (MilkShape writes them in that order); others become roots + local local_ = S.nodeMatrix(scene.nodes[jointNode[i] ]) + if pi and pi < i then + table.insert(scene.nodes[jointNode[pi] ].children, jointNode[i]) + abs[i] = S.mul(abs[pi], local_) + else + table.insert(scene.roots, jointNode[i]) + abs[i] = local_ + end + end + local skinned = false + for _, v in __iter(verts) do + for k = 1, 4 do + if v.bones[k] >= nj then + v.bones[k] = -1 + end + end + skinned = skinned or (nj > 0 and v.bones[1] >= 0) + end + if nj > 0 then + local ibm = S.accessor(nil, "f32", 16, nj) + ibm.matrix = true + for i = 1, nj do + local inv = Mat4.inverse(abs[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local list = table.create(nj, 0) + for i = 1, nj do + list[i] = jointNode[i] + end + scene.skins[1] = { joints = list, inverseBindMatrices = ibm } + end + -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner + local nv = #verts + for gi, g in __iter(groups) do + local remap= {} + local P, N, U, J, W = {}, {}, {}, {}, {} + local idx= {} + local sgs= {} + local count = 0 + for _, ti in __iter(g.tris) do +local __DARKLUA_CONTINUE_21=false repeat local q = triAt + ti * 70 + -- a triangle with an out-of-range vertex is dropped + if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then +__DARKLUA_CONTINUE_21=true break + end + table.insert(sgs, readu8(b, q + 68)) + for k = 0, 2 do + local vi = readu16(b, q + 2 + k * 2) + local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4) + local o = remap[key] + if o == nil then + o = count + count =count+ 1 + remap[key] = o + local v = verts[vi + 1] + table.move(v.pos, 1, 3, o * 3 + 1, P) + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) + U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) + -- influences: the valid bones, weights normalized + local sum = 0 + for c = 1, 4 do + if v.bones[c] >= 0 then + sum =sum+ v.weights[c] + end + end + for c = 1, 4 do + local ok = v.bones[c] >= 0 and sum > 0 + J[o * 4 + c] = (ok and{v.bones[c] }or{0 +})[1] W[o * 4 + c] = (ok and((v.weights[c] / sum ))or(0 +)) end + end + table.insert(idx, o ) + end +__DARKLUA_CONTINUE_21=true until true if not __DARKLUA_CONTINUE_21 then break end end + local prim= { + attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) }, + mode = "triangles", + material = (g.material >= 0 and g.material < #mats and((g.material + 1 ))or(nil)), + extras = { ms3d = { smoothing = sgs } }, + } + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in __iter(idx) do + writeu32(ind.data, (i - 1) * 4, v) + end + prim.indices = ind + local node= { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } } + if skinned then + local ja = S.accessor(nil, nj > 255 and"u16" or"u8", 4, count) + for i = 1, count * 4 do + if nj > 255 then + writeu16(ja.data, (i - 1) * 2, J[i]) + else + writeu8(ja.data, i - 1, J[i]) + end + end + prim.attributes.JOINTS_0 = ja + prim.attributes.WEIGHTS_0 = floats(W, 4) + node.skin = 1 + end + local mesh= { name = g.name , primitives = { prim } } + scene.meshes[gi] = mesh + node.mesh = gi + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- the animation: rest * key rotations, rest + key positions + local channels= {} + for i, j in __iter(joints) do + if #j.rotKeys > 0 then + local times, vals = {}, {} + local rest = scene.nodes[jointNode[i] ].rotation +for _, k in __iter(j.rotKeys) do + table.insert(times, k[1]) + local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4])))) + table.move(q, 1, 4, #vals + 1, vals) + end + local ch= { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" } + table.insert(channels, ch) + end + if #j.posKeys > 0 then + local times, vals = {}, {} + for _, k in __iter(j.posKeys) do + table.insert(times, k[1]) + table.insert(vals, j.pos[1] + k[2]) + table.insert(vals, j.pos[2] + k[3]) + table.insert(vals, j.pos[3] + k[4]) + end + local ch= { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" } + table.insert(channels, ch) + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "ms3d", channels = channels }) + end + return scene +end + +return Read +end +__FILES["model/ms3d/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, +-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first +-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); +-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each +-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's +-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: +-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and +-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), +-- joint colours and model extras are written in their sub-versioned blocks. +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + +local S = Types.Scene +local sqrt = math.sqrt + + + +local function fixedString(w, s, n) + local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1) + w:string(v) + for _ = #v + 1, n do + w:u8(0) + end +end + +local function msg(s) +return (type(s) == "string" and{s }or{"" +})[1]end +-- ------------------------------------------------------------------------------------------------ tree + + +local function tree(scene) +local t= { world = {}, parent = {}, order = {} } + local function visit(i, p, pm, depth) + local n = scene.nodes[i] + if type(n) ~= "table" or t.world[i] or depth > 256 then + return + end + t.world[i] = S.mul(pm, S.nodeMatrix(n)) + t.parent[i] = p + table.insert(t.order, i) + for _, c in __iter(n.children or {}) do + visit(c, i, t.world[i], depth + 1) + end + end + for _, r in __iter(scene.roots) do + visit(r, 0, S.IDENTITY, 0) + end + return t +end +-- ------------------------------------------------------------------------------------------------ joints +-- the rigid part (rotation and translation) of a matrix + + + +local function rigid(m) +local t, r = Mat4.decompose(m) + return Mat4.compose(t, r, nil) +end + +-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; +-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices +local function joints(scene, tr) +local skin = scene.skins[1] + local anim = scene.animations[1] + local out= {} + local bySkin= {} + local byNode= {} + local skinIndex= {} + local isJoint= {} + for k, ni in __iter(((skin and{skin.joints }or{{}})[1])) do + skinIndex[ni] = k - 1 + isJoint[ni] = true + end + local chans= {} + for _, ch in __iter(((anim and{anim.channels }or{{}})[1])) do + if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then + isJoint[ch.node] = true + chans[ch.node] = chans[ch.node] or {} + table.insert(chans[ch.node], ch) + end + end + -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix + local B = S.IDENTITY + local IBM= (skin and skin.inverseBindMatrices and{(S.reader(skin.inverseBindMatrices) )}or{nil +})[1] if skin and IBM and tr.world[skin.joints[1] ] then + local m = table.create(16, 0) + for c = 1, 16 do + m[c] = (IBM )(0, c - 1) + end + B = S.mul(tr.world[skin.joints[1] ], m) + end + local names= {} + for _, ni in __iter(tr.order) do +local __DARKLUA_CONTINUE_7=false repeat if not isJoint[ni] or #out >= 127 then +__DARKLUA_CONTINUE_7=true break + end + local p = tr.parent[ni] + while p ~= 0 and byNode[p] == nil do + p = tr.parent[p] + end + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the + -- joint and its joint parent (C) carry over to the keys + local invP = (p ~= 0 and{Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() }or{(Mat4.identity() +)})[1] local gp = tr.parent[ni] + local C = S.mul(invP, (gp ~= 0 and{tr.world[gp] }or{S.IDENTITY})[1]) + local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni]))) + local e = Mat4.eulerXYZ(r) + local base = string.sub(msg(scene.nodes[ni].name), 1, 27) + local name = (base ~= "" and{base }or{("joint" .. #out +)})[1] local n = 1 + while names[name] do + n =n+ 1 + name = base .. "_" .. n + end + names[name] = true + local j= { + node = ni, name = name, parent = (p ~= 0 and{out[byNode[p] + 1].name }or{""})[1], pos = t, + rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {}, + } + table.insert(out, j) + byNode[ni] = #out - 1 + if skinIndex[ni] then + bySkin[skinIndex[ni] ] = #out - 1 + end + -- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest + local _, rc = Mat4.decompose(C) + local inv = Mat4.transpose3(Mat4.fromQuat(r)) + for _, ch in __iter(chans[ni] or {}) do + local IN, OUT = (S.reader(ch.input) ), (S.reader(ch.output) ) +local cubic = ch.interpolation == "CUBICSPLINE" + for k = 0, ch.input.count - 1 do + local v = (cubic and((k * 3 + 1 ))or(k +)) local time = IN(k, 0) + if ch.path == "rotation" then + local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) } + local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + q = l > 0 and{ q[1] / l, q[2] / l, q[3] / l, q[4] / l } or{ 0, 0, 0, 1 } + local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q))))) + table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) }) + else + local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2)) + table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] }) + end + end + end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + return out, bySkin, byNode, B +end +-- ------------------------------------------------------------------------------------------------ geometry +-- every placed primitive as a group: vertices, triangles; or nil, message + + + + + +local function geometry(scene, tr, bySkin, byNode, B) +local verts, tris, groups= {}, {}, {} + for _, pl in __iter(S.flatten(scene)) do +local __DARKLUA_CONTINUE_12=false repeat local prim= pl.primitive + local node = scene.nodes[pl.node] + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function() +return false + end, { triangulate = true }) + if not merged then + return verts, tris, groups, err + end + local corners = merged.corners + if #corners == 0 then +__DARKLUA_CONTINUE_12=true break + end + local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil + -- a rigid mesh follows its nearest joint + local rigid = -1 + if not skinned then + local p = pl.node + while p and p ~= 0 do + if byNode[p] then + rigid = byNode[p] + break + end + p = tr.parent[p] + end + end + local M = (skinned and{B }or{pl.matrix +})[1] local NM = Mat4.normalMatrix(M) + local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0 + local A = prim.attributes + local POS = (S.reader(A.POSITION) ) +local zero = function(_, _) +return 0 + end + +local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil + local NOR= ((hasN and{(S.reader(A.NORMAL) )}or{nil})[1]) or zero + local UV= ((hasUV and{(S.reader(A.TEXCOORD_0) )}or{nil})[1]) or zero + local JO= ((skinned and{(S.reader(A.JOINTS_0) )}or{nil})[1]) or zero + local WE= ((skinned and{(S.reader(A.WEIGHTS_0) )}or{nil})[1]) or zero + local base = #verts + local nv = A.POSITION.count + if base + nv > 65535 then + return verts, tris, groups, "more than 65535 vertices" + end + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2)) + local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 } + if skinned then + local inf = {} + for c = 0, 3 do + local w = WE(v, c) + local j = bySkin[JO(v, c)] + if w > 0 and j then + table.insert(inf, { j, w }) + end + end + table.sort(inf, function(a, b) +return a[2] > b[2] + end) + local sum = 0 + for _, e in __iter(inf) do + sum =sum+ e[2] + end + for c = 1, 4 do + local e = inf[c] + bones[c] = (e and{e[1] }or{(-1 +)})[1] weights[c] = (e and sum > 0 and((e[2] / sum ))or(0 +)) end + end + table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights }) + end + local gi = #groups + if gi >= 255 then + return verts, tris, groups, "more than 255 groups" + end + local name = msg(node.name) + if name == "" then + name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name) + end + local x = node.extras and node.extras.ms3d + local g= { + name = (name ~= "" and{name }or{("group" .. gi)})[1], tris = {}, flags = (x and type(x.flags) == "number" and{x.flags }or{0})[1], + material = (type(prim.material) == "number" and prim.material <= 127 and((prim.material - 1 ))or((-1))), + comment = x and x.comment, + } + local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing + if type(saved) ~= "table" or #saved ~= math.floor(#corners / 3 )then + saved = nil + end + for f = 0, math.floor(#corners / 3 )- 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if mirror then + b, c = c, b + end + local t= { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = (saved and{saved[f + 1] }or{1})[1], group = gi } + -- the face normal for primitives without normals + local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] + local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z + local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z + local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in __iter({ a, b, c }) do + local nx, ny, nz = fx, fy, fz + if hasN then + local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2) + nx = NM[1] * ox + NM[5] * oy + NM[9] * oz + ny = NM[2] * ox + NM[6] * oy + NM[10] * oz + nz = NM[3] * ox + NM[7] * oy + NM[11] * oz + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n) + table.insert(t.uv, UV(v, 0)) + table.insert(t.uv, UV(v, 1)) + end + table.insert(tris, t) + table.insert(g.tris, #tris - 1) + end + if #tris > 65535 then + return verts, tris, groups, "more than 65535 triangles" + end + table.insert(groups, g) +__DARKLUA_CONTINUE_12=true until true if not __DARKLUA_CONTINUE_12 then break end end + return verts, tris, groups, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene, opts) +local o= opts or {} + local tr = tree(scene) + local js, bySkin, byNode, B = joints(scene, tr) + local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B) + if gerr then + return nil, gerr + end + if #scene.materials > 127 then + return nil, "more than 127 materials" + end + local src= scene.meta.source + local fromMs3d = src ~= nil and src.format == "ms3d" + local w = Bytes.writer(65536) + w:string("MS3D000000") + w:u32le(4) + w:u16le(#verts) + for _, v in __iter(verts) do + w:u8(0) + w:f32le(v.x) + w:f32le(v.y) + w:f32le(v.z) + w:i8(v.bones[1] % 256) + w:u8(1) + end + w:u16le(#tris) + for _, t in __iter(tris) do + w:u16le(0) + for k = 1, 3 do + w:u16le(t.v[k]) + end + for k = 1, 9 do + w:f32le(t.n[k]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2 - 1]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2]) + end + w:u8(math.clamp(t.sg, 0, 255)) + w:u8(t.group) + end + w:u16le(#groups) + for _, g in __iter(groups) do + w:u8(g.flags % 256) + fixedString(w, g.name, 32) + w:u16le(#g.tris) + for _, ti in __iter(g.tris) do + w:u16le(ti) + end + w:i8(g.material % 256) + end + -- materials + w:u16le(#scene.materials) + local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" + for i, m in __iter(scene.materials) do + local x = (m.extras and m.extras.ms3d or {}) +local bc = m.baseColor or { 1, 1, 1, 1 } + fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32) + local e = m.emissive or { 0, 0, 0 } + for _, c in __iter({ x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } }) do + for k = 1, 4 do + w:f32le(c[k] or 1) + end + end + local r = math.max(m.roughness or 1, 0.1) + w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128)) + w:f32le(bc[4] or 1) + w:i8((tonumber(x.mode) or 0) % 256) + local file = "" + local ref= m.baseColorTexture + local tex= ref and scene.textures[ref.texture] + if tex then + file = tex.uri or "" + if file == "" or string.sub(file, 1, 5) == "data:" then + file = base .. "_" .. ref.texture .. ".png" + if o.files and tex.data then + o.files[file] = tex.data + end + end + end + fixedString(w, file, 128) + fixedString(w, msg(x.alphamap), 128) + end + -- the animation header and joints + local fps = o.fps or ((fromMs3d and type(src.fps) == "number" and src.fps > 0 and{src.fps }or{24})[1]) + local last = 0 + for _, j in __iter(js) do + for _, k in __iter(j.rotKeys) do + last = math.max(last, k[1]) + end + for _, k in __iter(j.posKeys) do + last = math.max(last, k[1]) + end + end + w:f32le(fps) + w:f32le(0) + w:u32le(math.max(1, math.ceil(last * fps))) + w:u16le(#js) + for _, j in __iter(js) do + local x = scene.nodes[j.node].extras + local jx = x and x.ms3d + w:u8((jx and type(jx.flags) == "number" and((jx.flags % 256 ))or(0))) + fixedString(w, j.name, 32) + fixedString(w, j.parent, 32) + for k = 1, 3 do + w:f32le(j.rot[k]) + end + for k = 1, 3 do + w:f32le(j.pos[k]) + end + w:u16le(#j.rotKeys) + w:u16le(#j.posKeys) + for _, list in __iter({ j.rotKeys, j.posKeys }) do + for _, k in __iter(list) do + for c = 1, 4 do + w:f32le(k[c]) + end + end + end + end + -- comments + w:u32le(1) + local function comments(list, get) + local found = {} + for i, item in __iter(list) do + local c = get(item) + if type(c) == "string" and c ~= "" then + table.insert(found, { i - 1, c }) + end + end + w:u32le(#found) + for _, f in __iter(found) do + w:u32le(f[1]) + w:u32le(#f[2]) + w:string(f[2]) + end + end + comments(groups, function(g) +return g.comment + end) + comments(scene.materials, function(m) +return m.extras and m.extras.ms3d and m.extras.ms3d.comment + end) + comments(js, function(j) +local x= scene.nodes[j.node].extras + return x and x.ms3d and x.ms3d.comment + end) + local mc = (fromMs3d and{(msg(src.comment) )}or{"" +})[1] w:u32le(mc ~= "" and 1 or 0) + if mc ~= "" then + w:u32le(#mc) + w:string(mc) + end + -- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32 + w:u32le(2) + for _, v in __iter(verts) do + local p = table.create(3, 0) + local left = 100 + for c = 1, 3 do + p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left) + left =left- p[c] + end + if v.bones[2] < 0 and v.bones[1] >= 0 then + p = { 100, 0, 0 } + end + for c = 2, 4 do + w:i8(v.bones[c] % 256) + end + for c = 1, 3 do + w:u8(p[c]) + end + w:u32le(0) + end + -- joint colours, model extras + w:u32le(1) + for _, j in __iter(js) do + local x= scene.nodes[j.node].extras + local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 } + for k = 1, 3 do + w:f32le(c[k] or 1) + end + end + w:u32le(1) + w:f32le((fromMs3d and type(src.jointSize) == "number" and{src.jointSize }or{1})[1]) + w:u32le((fromMs3d and type(src.transparencyMode) == "number" and{src.transparencyMode }or{0})[1]) + w:f32le((fromMs3d and type(src.alphaRef) == "number" and{src.alphaRef }or{0.5})[1]) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write +end +__FILES["model/obj"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp +-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form +-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR +-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line +-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons", +-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false +-- keeps OBJ's). +-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group. +-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination. +-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups +-- (s: kept per node in extras.obj.smoothing, not used to compute normals). +-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to +-- opts.files[<name>.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mtl = __include("model/obj/Mtl") + +-- ------------------------------------------------------------------------------------------------ contract +local Obj = { + name = "obj", + category = "model", + extensions = { "obj" }, + mime = { "model/obj" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + + +function Obj.sniff(r) +local head = r:peek(512) + if string.find(head, "\0", 1, true) then + return 0 + end + if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then + return 0.6 + end + if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetch(opts, uri) +if not opts then + return nil + end + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "buffer" then + return buffer.tostring(v) + elseif type(v) == "string" then + return v + end + return nil +end + + + + + + + + + + + + + +function Obj.decode(r, opts) +local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local maxV = opts and opts.maxVertices or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local P, C, UV, N = {}, {}, {}, {} + local np, nt, nn = 0, 0, 0 + local hasColor = false + local sections= {} + local byName= {} + local cur= nil + local object= nil + local group= nil + local material= nil + local smoothing= nil + local mtllibs= {} + local skipped = 0 + local corners = 0 + local hasObjects = false + local lineNo = 0 + local pos = 1 + local len = #text + local function section() +if cur then + return cur + end + local key = (object or "") .. "\0" .. (group or "") + local s = byName[key] + if not s then + s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing } + byName[key] = s + table.insert(sections, s) + end + cur = s + return s + end + local function prim(mode) +local s = section() + local key = mode .. "\0" .. (material or "") + local p = s.byKey[key] + if not p then + p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false } + s.byKey[key] = p + table.insert(s.prims, p) + end + return p + end + -- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil + local function corner(tok) +local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$") + local vi = tonumber(a) + if not vi then + return nil, -1, -1 + end + vi = (vi < 0 and((np + vi ))or((vi - 1 +))) local ti, ni = -1, -1 + local t = tonumber(b) + if t then + ti = (t < 0 and((nt + t ))or((t - 1 +))) if ti < 0 or ti >= nt then + return nil, -1, -1 + end + end + local n = tonumber(c) + if n then + ni = (n < 0 and((nn + n ))or((n - 1 +))) if ni < 0 or ni >= nn then + return nil, -1, -1 + end + end + if vi < 0 or vi >= np then + return nil, -1, -1 + end + return vi, ti, ni + end + local fs= {} + while pos <= len do +local __DARKLUA_CONTINUE_1=false repeat local e = string.find(text, "\n", pos, true) or (len + 1) + local line = string.sub(text, pos, e - 1) + pos = e + 1 + lineNo =lineNo+ 1 + -- continuation lines + while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do + line = string.gsub(line, "\\\r?$", " ") + local e2 = string.find(text, "\n", pos, true) or (len + 1) + line =line.. string.sub(text, pos, e2 - 1) + pos = e2 + 1 + lineNo =lineNo+ 1 + end + local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$") + if key == nil or string.sub(key, 1, 1) == "#" then +__DARKLUA_CONTINUE_1=true break + end + local rest= rest +local hash = string.find(rest, "#", 1, true) + if hash then + rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "") + end + if key == "v" then + local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo) + end + if np >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices") + end + P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz + local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c) + if cr and cg and cb then + hasColor = true + C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb + end + np =np+ 1 + elseif key == "vt" then + local u, v = string.match(rest, "^(%S+)%s*(%S*)") + local fu = tonumber(u) + if not fu then + return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo) + end + if nt >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates") + end + local fv = tonumber(v) or 0 + UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, (flipV and((1 - fv ))or(fv +)) nt =nt+ 1 + elseif key == "vn" then + local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)") + local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z) + if not fx or not fy or not fz then + return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo) + end + if nn >= maxV then + return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals") + end + N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz + nn =nn+ 1 + elseif key == "f" or key == "l" or key == "p" then + table.clear(fs) + for tok in __iter(string.gmatch(rest, "%S+")) do + table.insert(fs, tok) + end + local k = #fs + local mode = (key == "f" and{(triangulate and"triangles" or"polygons") }or{key == "l" and"lines" or"points" +})[1] if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then + return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo) + end + corners =corners+ k + if corners > maxV * 4 then + return nil, Err.new(Err.LIMIT, "too many face corners") + end + local p = prim(mode) + local base = #p.cv + for i, tok in __iter(fs) do + local vi, ti, ni = corner(tok) + if not vi then + return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo) + end + p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni + if ti >= 0 then + p.hasT = true + end + if ni >= 0 then + p.hasN = true + end + end + if mode == "triangles" and k > 3 then + -- fan: rewrite the k corners as (k - 2) triangles + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 2, k - 1 do + for _, j in __iter({ 1, a, a + 1 }) do + o =o+ 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "lines" then + -- a polyline -> segments + local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {}) + local o = base + for a = 1, k - 1 do + for _, j in __iter({ a, a + 1 }) do + o =o+ 1 + p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j] + end + end + elseif mode == "polygons" then + table.insert(p.faces, k) + end + elseif key == "o" then + object = rest + group = nil + hasObjects = true + cur = nil + elseif key == "g" then + group = (rest == "" and{nil }or{rest +})[1] cur = nil + elseif key == "usemtl" then + material = rest + elseif key == "mtllib" then + table.insert(mtllibs, rest) + elseif key == "s" then + smoothing = rest + if cur then + cur.smoothing = cur.smoothing or rest + end + else + skipped =skipped+ 1 + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + -- materials + local scene = Types.Scene.new() + local matIndex= {} + local texIndex= {} + local function texture(map) +local file = string.gsub(map.file, "\\", "/") + local i = texIndex[file] + if i then + return i + end + local tex= { uri = file, mime = Mtl.mime(file) } + local data = fetch(opts, file) + if data then + tex.data = buffer.fromstring(data) + end + if map.options.clamp and map.options.clamp[1] == "on" then + tex.sampler = { wrapS = "clamp", wrapT = "clamp" } + end + table.insert(scene.textures, tex) + i = #scene.textures + texIndex[file] = i + return i + end + local mtlText = (opts and opts.mtl and{((type(opts.mtl) == "buffer" and{(buffer.tostring(opts.mtl) )}or{opts.mtl})[1]) }or{nil +})[1] local missing= {} + local libs= {} + if mtlText then + table.insert(libs, mtlText ) + end + for _, lib in __iter(mtllibs) do + local t = fetch(opts, lib) + if t then + table.insert(libs, t) + elseif not mtlText then + table.insert(missing, lib) + end + end + for _, lt in __iter(libs) do + for _, e in __iter(Mtl.parse(lt)) do + if not matIndex[e.name] then + table.insert(scene.materials, Mtl.toMaterial(e, texture)) + matIndex[e.name] = #scene.materials + end + end + end + -- materials named by usemtl but not defined anywhere: a default one with the name + for _, s in __iter(sections) do + for _, p in __iter(s.prims) do + if p.material and not matIndex[p.material] then + table.insert(scene.materials, Types.Scene.material(p.material)) + scene.materials[#scene.materials].metallic = 0 + matIndex[p.material] = #scene.materials + end + end + end + -- vertices: one per distinct (v, vt, vn) in each primitive + local f32 = buffer.writef32 + local KT, KN = nt + 1, nn + 1 + local numericKeys = np * KT * KN < 2 ^ 52 + local function build(p) +local n = #p.cv + local map= {} + local verts= {} + local idx = buffer.create(n * 4) + local count = 0 + for i = 1, n do + local v, t, nr = p.cv[i], p.ct[i], p.cn[i] + local key= (numericKeys and{((v * KT + (t + 1)) * KN + (nr + 1) )}or{(string.format("%d/%d/%d", v, t, nr) +)})[1] local k = map[key] + if k == nil then + k = count + map[key] = k + count =count+ 1 + verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr + end + buffer.writeu32(idx, (i - 1) * 4, k) + end + local pb = buffer.create(count * 12) + local tb = (p.hasT and{(buffer.create(count * 8) )}or{nil +})[1] local nb = (p.hasN and{(buffer.create(count * 12) )}or{nil +})[1] local cb = (hasColor and{(buffer.create(count * 12) )}or{nil +})[1] for k = 0, count - 1 do + local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3] + f32(pb, k * 12, P[v * 3 + 1]) + f32(pb, k * 12 + 4, P[v * 3 + 2]) + f32(pb, k * 12 + 8, P[v * 3 + 3]) + if tb and t >= 0 then + f32(tb, k * 8, UV[t * 2 + 1]) + f32(tb, k * 8 + 4, UV[t * 2 + 2]) + end + if nb and nr >= 0 then + f32(nb, k * 12, N[nr * 3 + 1]) + f32(nb, k * 12 + 4, N[nr * 3 + 2]) + f32(nb, k * 12 + 8, N[nr * 3 + 3]) + end + if cb then + f32(cb, k * 12, C[v * 3 + 1] or 1) + f32(cb, k * 12 + 4, C[v * 3 + 2] or 1) + f32(cb, k * 12 + 8, C[v * 3 + 3] or 1) + end + end + local A = Types.Scene.accessor + local attrs= { POSITION = A(pb, "f32", 3, count) } + if tb then + attrs.TEXCOORD_0 = A(tb, "f32", 2, count) + end + if nb then + attrs.NORMAL = A(nb, "f32", 3, count) + end + if cb then + attrs.COLOR_0 = A(cb, "f32", 3, count) + end + local out= { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode , material = (p.material and{matIndex[p.material] }or{nil })[1]} + if p.mode == "points" then + out.indices = (count == n and{nil }or{out.indices +})[1] end + if p.mode == "polygons" then + local fb = buffer.create(#p.faces * 4) + for i, k in __iter(p.faces) do + buffer.writeu32(fb, (i - 1) * 4, k) + end + out.faces = A(fb, "u32", 1, #p.faces) + end + return out + end + -- nodes: objects at the root, their groups as children; without objects every group is a root + local objectNode= {} + for _, s in __iter(sections) do + if #s.prims > 0 then + local mesh= { name = s.group or s.object, primitives = {} } + for _, p in __iter(s.prims) do + table.insert(mesh.primitives, build(p)) + end + table.insert(scene.meshes, mesh) + local node= { name = s.group or s.object, children = {}, mesh = #scene.meshes } + if s.smoothing then + node.extras = { obj = { smoothing = s.smoothing } } + end + if hasObjects and s.object and s.group then + local oi = objectNode[s.object] + if not oi then + table.insert(scene.nodes, { name = s.object, children = {} }) + oi = #scene.nodes + objectNode[s.object] = oi + table.insert(scene.roots, oi) + end + table.insert(scene.nodes, node) + table.insert(scene.nodes[oi].children, #scene.nodes) + else + if hasObjects and s.object and not s.group and objectNode[s.object] == nil then + table.insert(scene.nodes, node) + objectNode[s.object] = #scene.nodes + table.insert(scene.roots, #scene.nodes) + elseif hasObjects and s.object and objectNode[s.object] then + -- the object's own faces after its groups: a child too + table.insert(scene.nodes, node) + table.insert(scene.nodes[objectNode[s.object] ].children, #scene.nodes) + else + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + end + end + end + scene.meta.up = "y" + scene.meta.source = { + format = "obj", + positions = np, + texcoords = nt, + normals = nn, + vertexColors = hasColor, + mtllib = (#mtllibs > 0 and{mtllibs }or{nil})[1], + missingMtl = (#missing > 0 and{missing }or{nil})[1], + skipped = skipped, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest decimal that reads back as the same f32 +local probe = buffer.create(4) +local function f32str(v) +if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e7 then + return string.format("%d", v) + end + buffer.writef32(probe, 0, v) + local want = buffer.readf32(probe, 0) + for _, f in __iter({ "%.6g", "%.7g", "%.8g" }) do + local s = string.format(f, v) + buffer.writef32(probe, 0, (tonumber(s) )) + if buffer.readf32(probe, 0) == want then + return s + end + end + return string.format("%.9g", v) +end + +local function nameOk(s) +local t = string.gsub(s, "[\r\n]", " ") + return t +end + +local EXT= { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" } + +function Obj.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local flipV = not (opts and opts.flipV == false) + local base= opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local mtlName = opts and opts.mtlName or (base .. ".mtl") + local files = opts and opts.files + local placed = Types.Scene.flatten(scene) + local out = { "# written by rosetta" } + local mats = scene.materials or {} + -- material names (unique), texture file names + local names= {} + local used= {} + for i, m in __iter(mats) do + local n = string.gsub(m.name or ("material_" .. i), "%s", "_") + while used[n] do + n =n.. "_" .. i + end + used[n] = true + names[i] = n + end + local texFiles= {} + local function textureFile(i) +if texFiles[i] then + return texFiles[i] + end + local tex = scene.textures and scene.textures[i] + if not tex then + return nil + end + local file = tex.uri + if (file == nil or string.find(file, "^data:")) and tex.data then + file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + if file and tex.data and type(files) == "table" then + files[file] = tex.data + end + texFiles[i] = file + return file + end + if #mats > 0 then + table.insert(out, "mtllib " .. mtlName) + if type(files) == "table" then + files[mtlName] = Mtl.write(mats, names, textureFile) + end + end + local nv, nt, nn = 0, 0, 0 + local lastNode = -1 + for _, pl in __iter(placed) do +local __DARKLUA_CONTINUE_22=false repeat local prim = pl.primitive + local attrs = prim.attributes + local pos = attrs and attrs.POSITION + if not pos then +__DARKLUA_CONTINUE_22=true break + end + local P = Types.Scene.reader(pos) + if not P then + return nil, Err.new(Err.ARG, "bad POSITION accessor") + end + if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then + return nil, Err.new(Err.ARG, "POSITION data is smaller than its count") + end + local m = pl.matrix + local ident = m == Types.Scene.IDENTITY + local node = scene.nodes[pl.node] + if pl.node ~= lastNode then + lastNode = pl.node + table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node))) + end + local n = pos.count + local Cc = (attrs.COLOR_0 and not (opts and opts.colors == false) and{(Types.Scene.reader(attrs.COLOR_0 ) )}or{nil +})[1] local T = (attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) and{(Types.Scene.reader(attrs.TEXCOORD_0 ) )}or{nil +})[1] local Nr = (attrs.NORMAL and not (opts and opts.normals == false) and{(Types.Scene.reader(attrs.NORMAL ) )}or{nil +})[1] for _, a in __iter({ attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL }) do + if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then + return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION") + end + end + -- the normal matrix (inverse transpose) for baked normals + local nm= nil + if Nr and not ident then + local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + local k = (det ~= 0 and((1 / det ))or(1 +)) nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k } + end + for v = 0, n - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if not ident then + x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + end + if Cc then + table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2)))) + else + table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if T then + for v = 0, n - 1 do + local tv = T(v, 1) + table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num((flipV and((1 - tv ))or(tv))))) + end + end + if Nr then + for v = 0, n - 1 do + local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2) + if nm then + x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + end + table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z))) + end + end + if prim.material and names[prim.material] then + table.insert(out, "usemtl " .. names[prim.material]) + end + local function ref(i) +local s = tostring(nv + i + 1) + if T and Nr then + return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1) + elseif T then + return string.format("%s/%d", s, nt + i + 1) + elseif Nr then + return string.format("%s//%d", s, nn + i + 1) + end + return s + end + -- the corner list + local ind = prim.indices + local I= (ind and{(Types.Scene.reader(ind) )}or{nil +})[1] local count = (ind and{ind.count }or{n +})[1] if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then + return nil, Err.new(Err.ARG, "indices data is smaller than its count") + end + local function at(i) +return (I and{(I(i, 0) )}or{i +})[1] end + for i = 0, count - 1 do + if at(i) >= n then + return nil, Err.new(Err.ARG, "index out of range") + end + end + local mirror = not ident and (m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])) < 0 + local function face(list) + local parts = table.create(#list + 1) + parts[1] = "f" + if mirror then + for k = #list, 1, -1 do + table.insert(parts, ref(list[k])) + end + else + for k = 1, #list do + table.insert(parts, ref(list[k])) + end + end + table.insert(out, table.concat(parts, " ")) + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + for t = 0, math.floor(count / 3 )- 1 do + face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) }) + end + elseif mode == "polygons" then + local F = (prim.faces and{(Types.Scene.reader(prim.faces) )}or{nil +})[1] if not F or not prim.faces then + return nil, Err.new(Err.ARG, "polygons without faces") + end + local o = 0 + for f = 0, prim.faces.count - 1 do + local k = F(f, 0) + if o + k > count then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + local list = (table.create(k) ) +for j = 0, k - 1 do + list[j + 1] = at(o + j) + end + if k >= 3 then + face(list) + end + o =o+ k + end + elseif mode == "triangle_strip" or mode == "triangle_fan" then + for t = 0, count - 3 do + local a, b, c = at(t), at(t + 1), at(t + 2) + if mode == "triangle_fan" then + a = at(0) + elseif t % 2 == 1 then + a, b = b, a + end + face({ a, b, c }) + end + elseif mode == "lines" then + for s = 0, math.floor(count / 2 )- 1 do + table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1))) + end + elseif mode == "line_strip" or mode == "line_loop" then + local parts = { "l" } + for i = 0, count - 1 do + table.insert(parts, ref(at(i))) + end + if mode == "line_loop" and count > 0 then + table.insert(parts, ref(at(0))) + end + table.insert(out, table.concat(parts, " ")) + elseif mode == "points" then + for i = 0, count - 1 do + table.insert(out, "p " .. ref(at(i))) + end + end + nv =nv+ n + if T then + nt =nt+ n + end + if Nr then + nn =nn+ n + end +__DARKLUA_CONTINUE_22=true until true if not __DARKLUA_CONTINUE_22 then break end end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files) +function Obj.encodeMtl(scene, opts) +if type(scene) ~= "table" or type(scene.materials) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local files= {} + local o= table.clone(opts or {}) + o.files = files + o.mtlName = "x.mtl" + local _, err = Obj.encode(scene, o) + if err then + return nil, err + end + local text = files["x.mtl"] + return buffer.fromstring(text or ""), nil +end + +return Obj +end +__FILES["model/obj/Mtl"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc, +-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping +-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the +-- reverse (from extras.obj when present, else from the PBR fields). +local Types = __include("Types") + +local Mtl = {} + +-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers + + + +local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 } +local MAPS = { + map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true, + map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true, + map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true, +} +Mtl.MAPS = MAPS + +local function parseMap(args) +local opts= {} + local i = 1 + while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do + local key = string.sub(args[i], 2) + local vals = {} + i =i+ 1 + local n = OPT_ARGS[key] + if n then + for _ = 1, n do + if i <= #args then + table.insert(vals, args[i]) + i =i+ 1 + end + end + else + -- -o / -s / -t: up to three numbers + while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do + table.insert(vals, args[i]) + i =i+ 1 + end + end + opts[key] = vals + end + -- the file name is the rest (it may contain spaces) + local file = table.concat(args, " ", i) + return { file = file, options = opts } +end + +-- parse(text) -> { Entry } in file order +function Mtl.parse(text) +local out= {} + local cur= nil + for line in __iter(string.gmatch(text, "[^\r\n]+")) do + local l = string.gsub(line, "#.*$", "") + local words = {} + for w in __iter(string.gmatch(l, "%S+")) do + table.insert(words, w) + end + local key = words[1] + if key == "newmtl" then + cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} } + table.insert(out, cur ) + elseif key and cur then + local e = cur +local args = table.move(words, 2, #words, 1, {}) + if MAPS[key] then + e.maps[key] = parseMap(args) + table.insert(e.order, key) + else + local nums = {} + for _, a in __iter(args) do + local v = tonumber(a) + if v == nil then + nums = nil +break + end + table.insert(nums, v) + end + if nums then + if e.values[key] == nil then + table.insert(e.order, key) + end + e.values[key] = nums + end + end + end + end + return out +end + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" } +function Mtl.mime(file) +local ext = string.match(file, "%.([%w]+)$") + return (ext and{MIME[string.lower(ext)] }or{nil +})[1]end + +-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map +function Mtl.toMaterial(e, texture) +local m = Types.Scene.material(e.name) + local v = e.values + local kd = v.Kd + if kd and #kd >= 3 then + m.baseColor = { kd[1], kd[2], kd[3], 1 } + end + local d = (v.d and{(v.d )[1] }or{(v.Tr and((1 - (v.Tr )[1] ))or(1 +))})[1] m.baseColor[4] = d + if d < 1 then + m.alphaMode = "blend" + end + local ke = v.Ke + if ke and #ke >= 3 then + m.emissive = { ke[1], ke[2], ke[3] } + end + m.metallic = (v.Pm and{(v.Pm )[1] }or{0 +})[1] if v.Pr then + m.roughness = v.Pr[1] + elseif v.Ns then + m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1) + end + local function ref(key) +local map = e.maps[key] + if not map or map.file == "" then + return nil + end + local r= { texture = texture(map) } + local o, s = map.options.o, map.options.s + if o or s then + r.transform = { + offset = o and{ tonumber(o[1]) or 0, tonumber(o[2]) or 0 } or nil, + scale = s and{ tonumber(s[1]) or 1, tonumber(s[2]) or 1 } or nil, + } + end + if map.options.bm then + r.scale = tonumber(map.options.bm[1]) + end + return r + end + m.baseColorTexture = ref("map_Kd") + m.emissiveTexture = ref("map_Ke") + m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump") + m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA") + if m.emissiveTexture and not ke then + m.emissive = { 1, 1, 1 } + end + -- everything else as it was, for the writer and for Phong renderers + local extra= {} + for k, vals in __iter(v) do + extra[k] = vals + end + local maps= {} + for k, map in __iter(e.maps) do + maps[k] = { file = map.file, options = map.options, texture = texture(map) } + end + m.extras = { obj = { values = extra, maps = maps, order = e.order } } + return m +end + +local function num(v) +if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + for _, f in __iter({ "%.6g", "%.9g", "%.17g" }) do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end +Mtl.num = num + +-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to. +function Mtl.write(materials, names, textureFile) +local out = { "# written by rosetta" } + for i, m in __iter(materials) do + table.insert(out, "") + table.insert(out, "newmtl " .. names[i]) + local saved = m.extras and m.extras.obj + local values= {} + local maps= {} + local order= {} + if type(saved) == "table" and type(saved.values) == "table" then + for k, vals in __iter(saved.values) do + values[k] = vals + end + for k, mp in __iter(saved.maps or {}) do + maps[k] = mp + end + order = table.clone(saved.order or {}) + end + -- the PBR fields win over the saved Phong values they map to + local bc = m.baseColor or { 1, 1, 1, 1 } + values.Kd = { bc[1], bc[2], bc[3] } + if (bc[4] or 1) < 1 or values.d then + values.d = { bc[4] or 1 } + values.Tr = nil + end + local em = m.emissive or { 0, 0, 0 } + if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then + values.Ke = { em[1], em[2], em[3] } + end + if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then + values.Pr = { m.roughness } + end + if m.metallic ~= 0 or values.Pm then + values.Pm = { m.metallic } + end + local function setMap(key, ref) + if ref then + local file = textureFile(ref.texture) + if file then + local prev = maps[key] + local options = (prev and prev.texture == ref.texture and{prev.options }or{{} +})[1] options = table.clone(options or {}) + if ref.transform then + if ref.transform.offset then + options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) } + end + if ref.transform.scale then + options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) } + end + end + if ref.scale and key ~= "map_Kd" then + options.bm = { num(ref.scale) } + end + maps[key] = { file = file, options = options, texture = ref.texture } + end + end + end + setMap("map_Kd", m.baseColorTexture) + setMap("map_Ke", m.emissiveTexture) + if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then + setMap("norm", m.normalTexture) + end + setMap("map_ORM", m.metallicRoughnessTexture) + -- the saved order first, then the rest sorted + local keys = {} + local seen = {} + for _, k in __iter(order) do + if (values[k] or maps[k]) and not seen[k] then + table.insert(keys, k) + seen[k] = true + end + end + local rest = {} + for k in __iter(values) do + if not seen[k] then + table.insert(rest, k) + end + end + for k in __iter(maps) do + if not seen[k] and not values[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in __iter(rest) do + seen[k] = true + table.insert(keys, k) + end + for _, k in __iter(keys) do + local mp = maps[k] + if mp and type(mp.file) == "string" then + local file = (type(mp.texture) == "number" and{(textureFile(mp.texture) or mp.file) }or{mp.file +})[1] local parts = { k } + local okeys = {} + for ok in __iter(mp.options or {}) do + table.insert(okeys, ok) + end + table.sort(okeys) + for _, ok in __iter(okeys) do + table.insert(parts, "-" .. ok) + for _, ov in __iter(mp.options[ok]) do + table.insert(parts, tostring(ov)) + end + end + table.insert(parts, file) + table.insert(out, table.concat(parts, " ")) + elseif values[k] then + local parts = { k } + for _, x in __iter(values[k]) do + table.insert(parts, num(x)) + end + table.insert(out, table.concat(parts, " ")) + end + end + end + table.insert(out, "") + return table.concat(out, "\n") +end + +return Mtl +end +__FILES["model/off"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description +-- (geomview.org/docs/html/OFF.html). +-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the +-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`; +-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8 +-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given). +-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces; +-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are +-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or +-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single +-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points". +-- meta.source = { format, keyword, vertices, faces, edges }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes +-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons +-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are +-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF +-- (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Off = { + name = "off", + category = "model", + extensions = { "off" }, + mime = { "model/off", "text/plain" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Off.sniff(r) +local head = r:peek(512) + for _ = 1, 16 do -- leading comment lines + local rest = string.match(head, "^%s*#[^\n]*\n(.*)$") + if not rest then + break + end + head = rest + end + local kw = string.match(head, "^%s*(%w+)") + if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then + return 0.9 + end + return 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32 + + + +local function colorType(c) +return not c.float and c.max > 1 and"unorm8" or"f32" +end + +-- the colour accessor for count entries of 4 values (nan = absent: opaque white) +local function colorAccessor(c, count) +local t = colorType(c) + local buf = buffer.create(count * (t == "unorm8" and 4 or 16)) + local vals = c.values + for i = 0, count * 4 - 1 do + local v = vals[i + 1] + if t == "unorm8" then + if v ~= v then + v = 255 + elseif v < 0 or v > 255 or v % 1 ~= 0 then + return nil, "colour value out of range" + end + writeu8(buf, i, v) + else + writef32(buf, i * 4, v ~= v and 1 or v) + end + end + return Types.Scene.accessor(buf, t, 4, count), nil +end + +local function addColor(c, toks, from, n) + local vals = c.values + for k = 0, 3 do + if k < n then + local s = toks[from + k] + local v = (tonumber(s) ) +table.insert(vals, v) + if not c.float and string.find(s, "[%.eEnN]") then + c.float = true + end + if v > c.max then + c.max = v + end + else + table.insert(vals, 0 / 0) -- absent: full (opaque white) + end + end +end + +function Off.decode(r, opts) +local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + -- the next non-empty line's tokens (comments stripped) + local at = 1 + local lineNo = 0 + local function line() +while at <= #text do + local e = string.find(text, "\n", at, true) or (#text + 1) + local s = string.sub(text, at, e - 1) + at = e + 1 + lineNo =lineNo+ 1 + local hash = string.find(s, "#", 1, true) + if hash then + s = string.sub(s, 1, hash - 1) + end + local toks = {} + for w in __iter(string.gmatch(s, "%S+")) do + table.insert(toks, w) + end + if #toks > 0 then + return toks + end + end + return nil + end + local head = line() + if not head then + return nil, Err.new(Err.TRUNCATED, "empty file") + end + local kw = head[1] + local rest = kw + local st, hasC, hasN = false, false, false + if string.sub(rest, 1, 2) == "ST" then + st, rest = true, (string.sub(rest, 3)) + end + if string.sub(rest, 1, 1) == "C" then + hasC, rest = true, (string.sub(rest, 2)) + end + if string.sub(rest, 1, 1) == "N" then + hasN, rest = true, (string.sub(rest, 2)) + end + if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then + return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)") + elseif rest ~= "OFF" then + return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20)) + end + local counts +if head[2] == "BINARY" then + return nil, Err.new(Err.UNSUPPORTED, "binary OFF") + elseif #head >= 3 then + counts = { head[2], head[3], head[4] } + else + local c = line() + if not c then + return nil, Err.new(Err.TRUNCATED, "no counts line") + end + counts = c + end + local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0") + if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad counts line") + end + if nv > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices)) + end + if nf > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces)) + end + -- every vertex / face line takes at least 6 / 2 bytes + if nv * 6 + nf * 2 > #text - at + 2 then + return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need") + end + local fixed = 3 + (hasN and 3 or 0) + (st and 2 or 0) + local pos = buffer.create(nv * 12) + local nrm = (hasN and{(buffer.create(nv * 12) )}or{nil +})[1] local tex = (st and{(buffer.create(nv * 8) )}or{nil +})[1] local vcol= { values = {}, float = false, max = 0 } + for i = 0, nv - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i)) + end + local n = #t + local nc = 0 + if hasC then + nc = n - fixed + if nc ~= 3 and nc ~= 4 then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed)) + end + elseif n < fixed then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed)) + end + for k = 1, fixed + nc do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i)) + end + end + writef32(pos, i * 12, (tonumber(t[1]) )) + writef32(pos, i * 12 + 4, (tonumber(t[2]) )) + writef32(pos, i * 12 + 8, (tonumber(t[3]) )) + local k = 4 + if nrm then + writef32(nrm, i * 12, (tonumber(t[4]) )) + writef32(nrm, i * 12 + 4, (tonumber(t[5]) )) + writef32(nrm, i * 12 + 8, (tonumber(t[6]) )) + k = 7 + end + if hasC then + addColor(vcol, t, k, nc) + k =k+ nc + end + if tex then + writef32(tex, i * 8, (tonumber(t[k]) )) + writef32(tex, i * 8 + 4, (tonumber(t[k + 1]) )) + end + end + local sizes = buffer.create(nf * 4) + local corners= {} + local fcol= { values = {}, float = false, max = 0 } + local anyFaceColor, colormap = false, false + for f = 0, nf - 1 do + local t = line() + if not t then + return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f)) + end + local n = tonumber(t[1]) + if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f)) + end + writeu32(sizes, f * 4, n) + for k = 2, n + 1 do + local v = tonumber(t[k]) + if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f)) + end + table.insert(corners, v) + end + local nc = #t - n - 1 + if nc == 3 or nc == 4 then + for k = n + 2, #t do + if tonumber(t[k]) == nil then + return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f)) + end + end + addColor(fcol, t, n + 2, nc) + anyFaceColor = true + else + if nc == 1 then + colormap = true + end + addColor(fcol, t, 1, 0) + end + end + -- the primitive + local attrs= { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if hasC then + local acc, cerr = colorAccessor(vcol, nv) + if not acc then + return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr)) + end + attrs.COLOR_0 = acc + end + if tex then + attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv) + end + local prim= { attributes = attrs, mode = "points" } + local extras= {} + if anyFaceColor then + local acc, cerr = colorAccessor(fcol, nf) + if not acc then + return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr)) + end + extras.faceColors = acc + end + if nf > 0 then + local total = #corners + local cbuf = buffer.create(total * 4) + for i = 1, total do + writeu32(cbuf, (i - 1) * 4, corners[i]) + end + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + elseif triangulate then + local tris= {} + local fot= {} + local p = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + for k = 1, s - 2 do + table.insert(tris, corners[p + 1]) + table.insert(tris, corners[p + k + 1]) + table.insert(tris, corners[p + k + 2]) + table.insert(fot, f) + end + p =p+ s + end + local ib = buffer.create(#tris * 4) + for i, v in __iter(tris) do + writeu32(ib, (i - 1) * 4, v) + end + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris) + if anyFaceColor then + local fb = buffer.create(#fot * 4) + for i, v in __iter(fot) do + writeu32(fb, (i - 1) * 4, v) + end + extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + if next(extras) then + prim.extras = extras + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function fnum(v) +writef32(scratch, 0, v) + v = buffer.readf32(scratch, 0) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) +end + +-- a colour attribute's 4 components of entry i (0-based) as text +local function colorText(a, vals, comps, i) +local out = table.create(4) + for c = 1, 4 do + local v = (c <= comps and{vals[i * comps + c] }or{nil +})[1] if a.raw and a.type == "unorm8" then + out[c] = string.format("%d", v == nil and 255 or math.clamp(v, 0, 255)) + else + if v == nil then + v = 1 + elseif a.raw then + v = (a.type == "unorm16" and{(v / 65535 )}or{(a.type == "snorm8" and{(math.max(v / 127, -1) )}or{(math.max(v / 32767, -1) +)})[1]})[1] end + out[c] = fnum(v ) or "0" + end + end + return table.concat(out, " ") +end + +function Off.encode(scene, opts) +local o= opts or {} + local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false + local m, merr = Flatten.merge(scene, function(name) +return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT) + end, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local A = m.attrs + local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0 + if T and T.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + local nv = m.count + local sizes = m.sizes or {} + local nf = #sizes + local out = table.create(nv + nf + 3) + table.insert(out, (T and"ST" or"") .. (C and"C" or"") .. (N and"N" or"") .. "OFF") + if o.comment then + table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " ")) + end + table.insert(out, string.format("%d %d 0", nv, nf)) + local pv = P.values + for i = 0, nv - 1 do + local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate") + end + local s = x .. " " .. y .. " " .. z + if N then + local nvv = N.values + s =s.. " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0") + end + if C then + s =s.. " " .. colorText(C, C.values, C.components, i) + end + if T then + local tv, tc = T.values, T.components + s =s.. " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum((tc >= 2 and{tv[i * tc + 2] }or{0})[1]) or "0") + end + table.insert(out, s) + end + -- face colours of a single primitive (per file face, or through faceOfTriangle) + local fc= nil + local fcMap= nil + if wantC and #m.parts == 1 and nf > 0 then + local ex = m.parts[1].prim.extras + local acc = type(ex) == "table" and ex.faceColors + if acc then + local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16" + local vals = Flatten.numbers(acc, raw) + if vals then + local a= { type = acc.type, components = acc.components, raw = raw, values = vals } + if acc.count == nf then + fc = a + elseif (ex ).faceOfTriangle then + local fot = Flatten.numbers(ex.faceOfTriangle, true) + if fot and #fot == nf then + fc, fcMap = a, fot + for _, f in __iter(fot) do + if f < 0 or f >= acc.count then + fc = nil + break + end + end + end + end + end + end + end + local corners = m.corners + local p = 0 + for f = 1, nf do + local s = sizes[f] + local line = table.create(s + 2) + line[1] = string.format("%d", s) + for k = 1, s do + line[k + 1] = string.format("%d", corners[p + k]) + end + p =p+ s + if fc then + local src = (fcMap and{(fcMap )[f] }or{(f - 1 +)})[1] table.insert(line, colorText(fc, fc.values, fc.components, src)) + end + table.insert(out, table.concat(line, " ")) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Off +end +__FILES["model/ply"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, +-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). +-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> +-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u +-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> +-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's +-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are +-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are +-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", +-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face +-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after +-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, +-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments +-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and +-- types. meta.source = { format, encoding, vertices, faces }. +-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, +-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces +-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when +-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. +-- Not supported: list properties in the vertex element (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Binary = __include("model/ply/Binary") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Ply = { + name = "ply", + category = "model", + extensions = { "ply" }, + mime = { "model/ply", "application/ply" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + +local CODES= { + char = 1, + int8 = 1, + uchar = 2, + uint8 = 2, + short = 3, + int16 = 3, + ushort = 4, + uint16 = 4, + int = 5, + int32 = 5, + uint = 6, + uint32 = 6, + float = 7, + float32 = 7, + double = 8, + float64 = 8, +} +local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } +local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } +local CODE_OF_ACC= { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } +local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } +local SIZE = Binary.SIZE +local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } +local MAX_HEADER = 1048576 +local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Ply.sniff(r) +local h = r:peek(4) + return (h == "ply\n" or h == "ply\r" )and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +local function parseHeader(r) +local b, base, size = r.buf, r.base, r.limit - r.base + local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) + if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local h= { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } + local at = 1 + local first = true + while true do + local e = string.find(text, "\n", at, true) + if not e then + if size > MAX_HEADER then + return nil, Err.new(Err.LIMIT, "header longer than 1 MB") + end + return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) + end + local line = string.sub(text, at, e - 1) + if string.sub(line, -1) == "\r" then + line = string.sub(line, 1, -2) + end + local lineAt = base + at - 1 + at = e + 1 + local kw = string.match(line, "^%s*(%S+)") + if first then + first = false -- "ply" + elseif kw == nil then + -- blank line + elseif kw == "end_header" then + h.dataStart = base + at - 1 + break + elseif kw == "comment" or kw == "obj_info" then + local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" + table.insert((kw == "comment" and{h.comments }or{h.objInfo})[1], rest) + elseif kw == "format" then + local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") + if not enc or not ENCODINGS[enc] then + return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) + end + if string.sub(ver , 1, 1) ~= "1" then + return nil, Err.new(Err.UNSUPPORTED, "version " .. (ver ), lineAt) + end + h.encoding = enc + elseif kw == "element" then + local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") + local n = tonumber(count) + if not name or not n then + return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) + end + table.insert(h.elems, { name = name, count = n, props = {} }) + elseif kw == "property" then + local el = h.elems[#h.elems] + if not el then + return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) + end + local words= {} + for w in __iter(string.gmatch(line, "%S+")) do + table.insert(words, w) + end + local p +if words[2] == "list" and #words == 5 then + local cc, ic = CODES[words[3] ], CODES[words[4] ] + if not cc or not ic then + return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) + end + p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } +elseif #words == 3 and CODES[words[2] ] then + p = { name = words[3], ply = words[2], code = CODES[words[2] ], list = false } +else + return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) + end + for _, q in __iter(el.props) do + if q.name == p.name then + return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) + end + end + table.insert(el.props, p) + else + return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) + end + end + if h.encoding == "" then + return nil, Err.new(Err.CORRUPT, "no format line", base) + end + return h, nil +end +-- the reading plan of one element: per property, where its values go + + + + + + + + + + + + + + +local function newPlan(e) +local np = #e.props + local pl= { + code = table.create(np, 0), + isList = table.create(np, false), + countCode = table.create(np, 2), + dst = (table.create(np) ), + dOff = table.create(np, 0), + dStride = table.create(np, 0), + dCode = table.create(np, 0), + sizes = (table.create(np) ), + bound = table.create(np, -1), + totals = table.create(np, 0), + } + for k, p in __iter(e.props) do + pl.code[k] = p.code + pl.isList[k] = p.list + pl.countCode[k] = p.countCode or 2 + pl.dCode[k] = p.code + pl.dStride[k] = SIZE[p.code] + end + return pl +end + +-- unset scalar destinations get their own native buffer +local function ownBuffers(e, pl) + for k, p in __iter(e.props) do + if not p.list and pl.dst[k] == nil then + pl.dst[k] = buffer.create(e.count * SIZE[p.code]) + end + end +end + +-- read one element's rows (binary) into the plan; returns the next offset or nil, Err +local function readBinary(r, p, e, pl, be) +local b, limit, n, np = r.buf, r.limit, e.count, #e.props + local hasList, rowSize = false, 0 + for k, pr in __iter(e.props) do + if pr.list then + hasList = true + rowSize =rowSize+ SIZE[pr.countCode ] + else + rowSize =rowSize+ SIZE[pr.code] + end + end + if n * rowSize > limit - p then + return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) + end + if not hasList then + ownBuffers(e, pl) + local srcOff = table.create(np, 0) + local o = 0 + for k, pr in __iter(e.props) do + srcOff[k] = o + o =o+ SIZE[pr.code] + end + Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) + return p + n * rowSize, nil + end + local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) + if q < 0 then + return nil, Err.new((totals == "bad list count" and{Err.CORRUPT }or{Err.TRUNCATED})[1], "element " .. e.name .. ": " .. tostring(totals), p) + end + ownBuffers(e, pl) + for k, pr in __iter(e.props) do + if pr.list then + pl.totals[k] = totals[k] + pl.sizes[k] = buffer.create(n * 4) + pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k] ]) + end + end + local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) + if not ok then + return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) + end + return q, nil +end + +-- a token as a value of type code, or nil +local function value(tok, code) +if tok == nil then + return nil + end + local v = tonumber(tok) + if v == nil then + return nil + end + local rg = RANGE[code] + if rg and (v ~= math.floor(v / 1 )or v < rg[1] or v > rg[2]) then + return nil + end + return v +end + +-- read one element's rows (ascii) from the token stream +local function readAscii(nextTok, e, pl) +ownBuffers(e, pl) + local n = e.count + local listSizes= {} + local listItems= {} + for k, p in __iter(e.props) do + if p.list then + listSizes[k] = (table.create(n) ) +listItems[k] = {} + end + end + local wr = Binary.wr + for i = 0, n - 1 do + for k, p in __iter(e.props) do + if p.list then + local t = nextTok() + local c = value(t, p.countCode ) + if c == nil or c < 0 or c % 1 ~= 0 then + return Err.new((t == nil and{Err.TRUNCATED }or{Err.CORRUPT})[1], string.format("element %s row %d: bad list count", e.name, i)) + end + listSizes[k][i + 1] = c + local items, bd, code = listItems[k], pl.bound[k], p.code + for _ = 1, c do + local t2 = nextTok() + local v = value(t2, code) + if v == nil then + return Err.new((t2 == nil and{Err.TRUNCATED }or{Err.CORRUPT})[1], string.format("element %s row %d: bad value", e.name, i)) + end + if bd >= 0 and (v < 0 or v >= bd or v ~= math.floor(v / 1)) then + return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) + end + table.insert(items, v) + end + else + local t = nextTok() + local v = value(t, p.code) + if v == nil then + return Err.new((t == nil and{Err.TRUNCATED }or{Err.CORRUPT})[1], string.format("element %s row %d: bad %s value", e.name, i, p.name)) + end + wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) + end + end + end + for k in __iter(listSizes) do + local sz, items = listSizes[k], listItems[k] + local s = buffer.create(n * 4) + for i = 1, n do + buffer.writeu32(s, (i - 1) * 4, sz[i]) + end + local dc = pl.dCode[k] + local d = buffer.create(#items * SIZE[dc]) + for j = 1, #items do + wr(d, (j - 1) * SIZE[dc], dc, items[j]) + end + pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items + end + return nil +end + +local function propIndex(e, name) +for k, p in __iter(e.props) do + if p.name == name then + return k + end + end + return nil +end + +-- vertex element -> attributes: sets the plan's destinations, returns the attribute table +local function planVertex(e, pl) +local nv = e.count + local attrs= {} + local taken= {} + for _, p in __iter(e.props) do + if p.list then + return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") + end + end + -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional + local function group(attr, names, required, ok, comps, fillValue) + local ks= {} + local codes = {} + for i, nm in __iter(names) do + local k = propIndex(e, nm) + if k == nil then + if i <= required then + return + end + else + ks[i] = k + table.insert(codes, e.props[k].code) + end + end + local dc = ok(codes) + if dc == nil then + return + end + local sz = SIZE[dc] + local buf = buffer.create(nv * comps * sz) + if fillValue then + for i = 0, nv - 1 do + Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) + end + end + for i, k in __iter(ks) do + pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc + taken[k] = true + end + local accType = attr == "COLOR_0" and dc == 2 and"unorm8" or(attr == "COLOR_0" and dc == 4 and"unorm16" or ACC_TYPE[dc] +) attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) + end + local function floats(codes) +for _, c in __iter(codes) do + if c ~= 7 and c ~= 8 then + return nil + end + end + return 7 + end + local function anyNumber(_codes) +return 7 + end + group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) + group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) + -- colours: one type class for all channels + do + local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") + if rk and gk and bk then + local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } + if ak then + table.insert(codes, e.props[ak].code) + end + local cls= codes[1] + for _, c in __iter(codes) do + local a = c == 8 and 7 or c + local b0 = cls == 8 and 7 or cls + if a ~= b0 then + cls = nil + end + end + local dc = cls == 2 and 2 or(cls == 4 and 4 or((cls == 7 or cls == 8 )and 7 or nil +)) if dc then + group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() + return dc + end, 4, dc == 2 and 255 or(dc == 4 and 65535 or 1)) + end + end + end + for _, pair in __iter(TEXCOORD_PAIRS) do + if attrs.TEXCOORD_0 == nil then + group("TEXCOORD_0", pair, 2, floats, 2, nil) + end + end + for k, p in __iter(e.props) do + if not taken[k] then + local buf = buffer.create(nv * SIZE[p.code]) + pl.dst[k] = buf + attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) + end + end + return attrs, nil +end + +-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle +local function fan(sizes, corners, nf) +local nt = 0 + for f = 0, nf - 1 do + local s = buffer.readu32(sizes, f * 4) + if s >= 3 then + nt =nt+ (s - 2 +) end + end + local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) + local p, t = 0, 0 + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + for f = 0, nf - 1 do + local s = readu32(sizes, f * 4) + local a = readu32(corners, p * 4) + for k = 1, s - 2 do + writeu32(idx, t * 12, a) + writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) + writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) + writeu32(fot, t * 4, f) + t =t+ 1 + end + p =p+ s + end + return idx, nt, fot +end + +function Ply.decode(r, opts) +local triangulate = true + if opts and opts.triangulate == false then + triangulate = false + end + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local h, herr = parseHeader(r) + if not h then + return nil, herr + end + local vi, fi, idxK +for i, e in __iter(h.elems) do + if e.name == "vertex" and vi == nil then + vi = i + if e.count > maxVertices then + return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) + end + elseif e.name == "face" and fi == nil then + local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") + if k and e.props[k].list then + fi, idxK = i, k + end + end + if e.count > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) + end + end + if vi == nil then + return nil, Err.new(Err.CORRUPT, "no vertex element") + end + local nv = h.elems[vi].count + local be = h.encoding == "binary_big_endian" + local ascii = h.encoding == "ascii" + local nextTok= function() + return nil + end + if ascii then + local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) + -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating + local need = 0 + for _, e in __iter(h.elems) do + need =need+ e.count * #e.props + end + if need > math.floor((#body + 1) / 2 )then + return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) + end + nextTok = (string.gmatch(body, "%S+") ) +end + local plans= {} + local attrs= {} + local p = h.dataStart + if not ascii then + -- every row takes at least its scalar sizes and list counts: bound the counts before allocating + local need = 0 + for _, e in __iter(h.elems) do + local row = 0 + for _, pr in __iter(e.props) do + row =row+ SIZE[(pr.list and{pr.countCode }or{pr.code})[1] ] + end + need =need+ e.count * row + end + if need > r.limit - h.dataStart then + return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) + end + end + for i, e in __iter(h.elems) do + local pl = newPlan(e) + plans[i] = pl + if i == vi then + local a, aerr = planVertex(e, pl) + if not a then + return nil, aerr + end + attrs = a + elseif i == fi then + pl.dCode[idxK] = 6 + pl.bound[idxK] = nv + end + if ascii then + local err = readAscii(nextTok, e, pl) + if err then + return nil, err + end + else + local q, err = readBinary(r, p, e, pl, be) + if not q then + return nil, err + end + p = q + end + end + -- the primitive + local prim= { attributes = attrs, mode = "points" } + local nf = 0 + local extras= {} + local faceProps= {} + if fi then + local e, pl = h.elems[fi], plans[fi] + nf = e.count + local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] + local faceAttributes= {} + local faceLists= {} + local anyExtra = false + for k, pr in __iter(e.props) do + table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) + if k ~= idxK then + anyExtra = true + if pr.list then + faceLists[pr.name] = { + countType = pr.countPly, + itemType = pr.ply, + sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), + items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), + } + else + faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) + end + end + end + if next(faceAttributes) then + extras.faceAttributes = faceAttributes + end + if next(faceLists) then + extras.faceLists = faceLists + end + if nf > 0 then + local allTri = total == nf * 3 + if allTri then + for f = 0, nf - 1 do + if buffer.readu32(sizes, f * 4) ~= 3 then + allTri = false + break + end + end + end + if allTri then + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + elseif triangulate then + local idx, nt, fot = fan(sizes, corners, nf) + prim.mode = "triangles" + prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) + if anyExtra then + extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) + end + else + prim.mode = "polygons" + prim.indices = Types.Scene.accessor(corners, "u32", 1, total) + prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) + end + end + end + if next(extras) then + prim.extras = extras + end + -- raw elements, element order, property order + local elements= {} + local order= {} + for i, e in __iter(h.elems) do + table.insert(order, e.name) + if i ~= vi and i ~= fi then + local pl = plans[i] + local props = {} + for k, pr in __iter(e.props) do + props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = (pr.list and{pl.totals[k] }or{nil })[1]} + end + table.insert(elements, { name = e.name, count = e.count, properties = props }) + end + end + local vprops = {} + for _, pr in __iter(h.elems[vi].props) do + table.insert(vprops, { name = pr.name, type = pr.ply }) + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } + scene.meta.ply = { + comments = h.comments, + objInfo = h.objInfo, + elements = elements, + order = order, + vertexProperties = vprops, + faceProperties = (fi and{faceProps }or{nil})[1], + } + return scene, nil +end +-- ------------------------------------------------------------------------------------------------ encode +-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) + + + + +local function keep(name) +return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" +end + +-- the spelling `want` from the source file when it means the same type as code, else the classic name +local function spell(want, code) +if want and CODES[want] == code then + return want + end + return PLY_NAME[code] +end + +local function toInt(v, code) +local rg = RANGE[code] + if rg then + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) + end + return v +end +-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer + + + +local function rowsAscii(out, n, cols) + local fmt = string.format + local function num(code, v) +if code == 7 then + return fmt("%.9g", v) + elseif code == 8 then + return fmt("%.17g", v) + end + return fmt("%d", toInt(v, code)) + end + local at= {} + for i = 0, n - 1 do + local parts = {} + for k, c in __iter(cols) do + if c.kind == "s" then + local col = c.col +table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) + else + local col = c.col +local s = col.sizes[i + 1] + table.insert(parts, fmt("%d", s)) + local a = at[k] or 0 + for j = 1, s do + table.insert(parts, num(col.code, col.items[a + j])) + end + at[k] = a + s + end + end + table.insert(out, table.concat(parts, " ")) + end +end + +local function rowsBinary(w, n, cols, be) + local size = 0 + for _, c in __iter(cols) do + if c.kind == "s" then + size =size+ n * SIZE[(c.col ).code] + else + local col = c.col +size =size+ (n * SIZE[col.countCode] + #col.items * SIZE[col.code] +) end + end + local o = w:reserve(size) + local d = w.buf + local put = Binary.put + local at= {} + for i = 0, n - 1 do + for k, c in __iter(cols) do + if c.kind == "s" then + local col = c.col +local code = col.code + put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) + o =o+ SIZE[code] + else + local col = c.col +local s = col.sizes[i + 1] + put(d, o, col.countCode, s, be) + o =o+ SIZE[col.countCode] + local a, code = at[k] or 0, col.code + for j = 1, s do + put(d, o, code, toInt(col.items[a + j], code), be) + o =o+ SIZE[code] + end + at[k] = a + s + end + end + end + w.pos = o +end + +-- numbers of a raw element column (buffer of a ply type) +local function bufNumbers(b, code, count) +if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then + return nil + end + local out = (table.create(count) ) +for i = 0, count - 1 do + out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) + end + return out +end + +-- the list count type for a maximum count +local function countCodeFor(maxCount) +return maxCount <= 255 and 2 or(maxCount <= 65535 and 4 or 6 +)end + +function Ply.encode(scene, opts) +local o= opts or {} + local enc = o.format or "binary_little_endian" + if not ENCODINGS[enc] then + return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = false }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local meta= (type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" and{scene.meta.ply }or{{} +})[1] local nv = m.count + -- source property spellings / order + local srcType= {} + local srcOrder= {} + if type(meta.vertexProperties) == "table" then + for i, vp in __iter(meta.vertexProperties) do + if type(vp) == "table" and type(vp.name) == "string" then + srcType[vp.name] = vp.type + srcOrder[vp.name] = i + end + end + end + local cols= {} + local function add(name, code, a, comp) + table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) + end + local function floatCode(name) +return CODES[srcType[name] or ""] == 8 and 8 or 7 + end + local A = m.attrs + for i, nm in __iter({ "x", "y", "z" }) do + add(nm, floatCode(nm), A.POSITION, i - 1) + end + if A.NORMAL then + for i, nm in __iter({ "nx", "ny", "nz" }) do + add(nm, floatCode(nm), A.NORMAL, i - 1) + end + end + local C = A.COLOR_0 + if C then + local code = C.raw and C.type == "unorm8" and 2 or(C.raw and C.type == "unorm16" and 4 or 7 +) if C.raw and code == 7 then + -- another normalized type: as floats + local vals = table.create(#C.values) + local scale = C.type == "snorm8" and 127 or 32767 + for i, v in __iter(C.values) do + vals[i] = math.max(v / scale, -1) + end + C = { type = "f32", components = C.components, raw = false, values = vals } + end + local cc = C +for i, nm in __iter({ "red", "green", "blue" }) do + if i <= cc.components then + add(nm, code, cc, i - 1) + end + end + if cc.components >= 4 then + local full = code == 2 and 255 or(code == 4 and 65535 or 1 +) local need = srcOrder.alpha ~= nil + if not need then + for i = 0, nv - 1 do + if cc.values[i * cc.components + 4] ~= full then + need = true + break + end + end + end + if need then + add("alpha", code, cc, 3) + end + end + end + if A.TEXCOORD_0 then + local names = { "s", "t" } + for _, pair in __iter(TEXCOORD_PAIRS) do + if srcOrder[pair[1] ] and srcOrder[pair[2] ] then + names = pair + break + end + end + local tc = A.TEXCOORD_0 + if tc.raw then + return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") + end + add(names[1], floatCode(names[1]), tc, 0) + if tc.components >= 2 then + add(names[2], floatCode(names[2]), tc, 1) + end + end + local customs = {} + for name in __iter(A) do + if string.sub(name, 1, 1) == "_" then + table.insert(customs, name) + end + end + table.sort(customs) + for _, name in __iter(customs) do + local a = A[name] + local code = CODE_OF_ACC[a.type] or 7 + local base = string.sub(name, 2) + if a.components == 1 then + add(base, code, a, 0) + else + for c = 0, a.components - 1 do + add(base .. "_" .. c, code, a, c) + end + end + end + -- the source order first (stable for the rest) + local rank= {} + for i, c in __iter(cols) do + rank[c] = (srcOrder[c.name] or (1000000 + i)) + end + table.sort(cols, function(a, b) +return rank[a] < rank[b] + end) + -- faces + local faceRows= nil + local nf = 0 + if m.sizes then + local sizes = m.sizes +nf = #sizes + local maxS, maxI = 0, 0 + for _, s in __iter(sizes) do + maxS = math.max(maxS, s) + end + for _, c in __iter(m.corners) do + maxI = math.max(maxI, c) + end + local fprops= (type(meta.faceProperties) == "table" and{meta.faceProperties }or{{} +})[1] local idxName, idxType, idxCount = "vertex_indices", nil, nil + for _, fp in __iter(fprops) do + if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then + idxName, idxType, idxCount = fp.name, fp.type, fp.countType + end + end + local cc = countCodeFor(maxS) + local srcCC = CODES[idxCount or ""] + if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then + cc = srcCC + end + local ic = maxI < 2147483648 and 5 or 6 + local srcIC = CODES[idxType or ""] + if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then + ic = srcIC + end + local rows= { + { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, + } + -- per-face data of a single primitive + if #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fot= nil + if type(ex) == "table" and ex.faceOfTriangle then + fot = Flatten.numbers(ex.faceOfTriangle, true) + end + local function perFace(vals, count) +if count == nf then + return vals + elseif fot and #fot == nf then + local out = (table.create(nf) ) +for i = 1, nf do + local v = vals[fot[i] + 1] + if v == nil then + return nil + end + out[i] = v + end + return out + end + return nil + end + local extraRows= {} + if type(ex) == "table" and type(ex.faceAttributes) == "table" then + for name, acc in __iter(ex.faceAttributes) do + local vals = Flatten.numbers(acc, true) + local code = CODE_OF_ACC[acc.type] + if vals and code and acc.components == 1 then + local pv = perFace(vals, acc.count) + if pv then + extraRows[name] = { kind = "s" , col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } + end + end + end + end + if type(ex) == "table" and type(ex.faceLists) == "table" then + for name, fl in __iter(ex.faceLists) do + local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) + local items = type(fl) == "table" and Flatten.numbers(fl.items, true) + local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) + if sz and items and code and #sz == nf and fot == nil then + local mx = 0 + for _, s in __iter(sz) do + mx = math.max(mx, s) + end + local lcc = countCodeFor(mx) + local scc = CODES[fl.countType or ""] + if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then + lcc = scc + end + extraRows[name] = { kind = "l" , col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } + end + end + end + -- the source order, then the rest by name + local placed= { [idxName] = true } + local ordered= {} + for _, fp in __iter(fprops) do + if type(fp) == "table" then + if fp.name == idxName then + table.insert(ordered, rows[1]) + elseif extraRows[fp.name] then + table.insert(ordered, extraRows[fp.name]) + placed[fp.name] = true + end + end + end + if not table.find(ordered, rows[1]) then + table.insert(ordered, 1, rows[1]) + end + local rest = {} + for name in __iter(extraRows) do + if not placed[name] then + table.insert(rest, name) + end + end + table.sort(rest) + for _, name in __iter(rest) do + table.insert(ordered, extraRows[name]) + end + rows = ordered + end + faceRows = rows + end +-- raw elements + +local raws= {} + local rawOrder= {} + if type(meta.elements) == "table" then + for _, el in __iter(meta.elements) do +local __DARKLUA_CONTINUE_67=false repeat if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then + if el.name == "face" and faceRows then +__DARKLUA_CONTINUE_67=true break + end + local rows= {} + for _, pr in __iter(el.properties) do + local code = CODES[pr.type or ""] + if not code then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") + end + if pr.countType then + local cc = CODES[pr.countType] + local sz = cc and bufNumbers(pr.sizes, 6, el.count) + local total = 0 + if sz then + for _, s in __iter(sz) do + total =total+ s + end + end + local items = sz and bufNumbers(pr.values, code, total) + if not (cc and sz and items) then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "l" , col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) + else + local vals = bufNumbers(pr.values, code, el.count) + if not vals then + return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) + end + table.insert(rows, { kind = "s" , col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) + end + end + raws[el.name] = { name = el.name, count = el.count, rows = rows } + table.insert(rawOrder, el.name) + end +__DARKLUA_CONTINUE_67=true until true if not __DARKLUA_CONTINUE_67 then break end end + end + -- element order: the source's, then vertex, face, the rest + local order= {} + local seen= {} + local function want(name) + if seen[name] then + return + end + if name == "vertex" or (name == "face" and faceRows) or raws[name] then + seen[name] = true + table.insert(order, name) + end + end + if type(meta.order) == "table" then + for _, name in __iter(meta.order) do + if type(name) == "string" then + want(name) + end + end + end + want("vertex") + want("face") + for _, name in __iter(rawOrder) do + want(name) + end + -- header + local vrows= {} + for _, c in __iter(cols) do + table.insert(vrows, { kind = "s" , col = c }) + end + local lines = { "ply", "format " .. enc .. " 1.0" } + local function noNewline(s) +return (string.gsub(tostring(s), "[\r\n]", " ")) + end + for _, c in __iter(((type(meta.comments) == "table" and{meta.comments }or{{}})[1])) do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in __iter(o.comments or {}) do + table.insert(lines, "comment " .. noNewline(c)) + end + for _, c in __iter(((type(meta.objInfo) == "table" and{meta.objInfo }or{{}})[1])) do + table.insert(lines, "obj_info " .. noNewline(c)) + end + local function elementRows(name) +if name == "vertex" then + return nv, vrows + elseif name == "face" and faceRows then + return nf, faceRows + end + local raw = raws[name] + return raw.count, raw.rows + end + for _, name in __iter(order) do + local n, rows = elementRows(name) + table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) + for _, rw in __iter(rows) do + if rw.kind == "s" then + local c = rw.col +table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) + else + local c = rw.col +table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) + end + end + end + table.insert(lines, "end_header") + local header = table.concat(lines, "\n") .. "\n" + if enc == "ascii" then + local out = { header } + local body= {} + for _, name in __iter(order) do + local n, rows = elementRows(name) + rowsAscii(body, n, rows) + end + if #body > 0 then + table.insert(out, table.concat(body, "\n")) + table.insert(out, "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + local w = Bytes.writer(#header + nv * 32 + nf * 16) + w:string(header) + for _, name in __iter(order) do + local n, rows = elementRows(name) + rowsBinary(w, n, rows, enc == "binary_big_endian") + end + return w:finish(), nil +end + +return Ply +end +__FILES["model/ply/Binary"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, +-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of +-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the +-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list +-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws. +local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32 +local readf32, readf64 = buffer.readf32, buffer.readf64 +local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32 +local writef32, writef64 = buffer.writef32, buffer.writef64 +local byteswap, band, rshift = bit32.byteswap, bit32.band, bit32.rshift + +local Binary = {} + +Binary.SIZE = { 1, 1, 2, 2, 4, 4, 4, 8 } +local SIZE = Binary.SIZE +local scratch = buffer.create(8) + +local function swap16(v) +return rshift(v, 8) + band(v, 255) * 256 +end + +-- rd(b, q, code, be) -> the value at q +local function rd(b, q, code, be) +if not be then + if code == 7 then + return readf32(b, q) + elseif code == 2 then + return readu8(b, q) + elseif code == 5 then + return readi32(b, q) + elseif code == 6 then + return readu32(b, q) + elseif code == 8 then + return readf64(b, q) + elseif code == 1 then + return readi8(b, q) + elseif code == 3 then + return readi16(b, q) + end + return readu16(b, q) + end + if code <= 2 then + return (code == 1 and{(readi8(b, q) )}or{(readu8(b, q) +)})[1] elseif code <= 4 then + local v = swap16(readu16(b, q)) + return (code == 3 and v >= 32768 and((v - 65536 ))or(v +)) elseif code <= 7 then + local v = byteswap(readu32(b, q)) + if code == 6 then + return v + elseif code == 5 then + return (v >= 2147483648 and((v - 4294967296 ))or(v +)) end + writeu32(scratch, 0, v) + return readf32(scratch, 0) + end + writeu32(scratch, 0, byteswap(readu32(b, q + 4))) + writeu32(scratch, 4, byteswap(readu32(b, q))) + return readf64(scratch, 0) +end +Binary.rd = rd + +-- wr(d, o, code, v): v as code, little endian +local function wr(d, o, code, v) + if code == 7 then + writef32(d, o, v) + elseif code == 6 then + writeu32(d, o, v) + elseif code == 5 then + writei32(d, o, v) + elseif code == 2 then + writeu8(d, o, v) + elseif code == 8 then + writef64(d, o, v) + elseif code == 1 then + writei8(d, o, v) + elseif code == 3 then + writei16(d, o, v) + else + writeu16(d, o, v) + end +end +Binary.wr = wr + +-- put(d, o, code, v, be): v as code in either byte order (the writer) +function Binary.put(d, o, code, v, be) + if not be or code <= 2 then + wr(d, o, code, v) + return + end + wr(scratch, 0, code, v) + if code <= 4 then + writeu16(d, o, swap16(readu16(scratch, 0))) + elseif code <= 7 then + writeu32(d, o, byteswap(readu32(scratch, 0))) + else + writeu32(d, o, byteswap(readu32(scratch, 4))) + writeu32(d, o + 4, byteswap(readu32(scratch, 0))) + end +end + +-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p +function Binary.fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode) + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + local q0, o0, st = p + srcOff[k], dOff[k], dStride[k] + if sc == dc and not be then + local sz = SIZE[sc] + if sz == 4 then + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + end + elseif sz == 1 then + for i = 0, n - 1 do + writeu8(d, o0 + i * st, readu8(b, q0 + i * rowSize)) + end + elseif sz == 2 then + for i = 0, n - 1 do + writeu16(d, o0 + i * st, readu16(b, q0 + i * rowSize)) + end + else + for i = 0, n - 1 do + writeu32(d, o0 + i * st, readu32(b, q0 + i * rowSize)) + writeu32(d, o0 + i * st + 4, readu32(b, q0 + i * rowSize + 4)) + end + end + else + for i = 0, n - 1 do + wr(d, o0 + i * st, dc, rd(b, q0 + i * rowSize, sc, be)) + end + end + end +end + +-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property, +-- or -1, message (truncated rows, a negative / fractional count) +function Binary.scan(b, p, limit, n, np, code, isList, countCode, be) +local totals = table.create(np, 0) + local q = p + for _ = 1, n do + for k = 1, np do + if isList[k] then + local cc = countCode[k] + local csz = SIZE[cc] + if q + csz > limit then + return -1, "list runs past the end" + end + local c = rd(b, q, cc, be) + if c < 0 or c ~= math.floor(c / 1 )then + return -1, "bad list count" + end + q =q+ (csz + c * SIZE[code[k] ] +) if q > limit then + return -1, "list runs past the end" + end + totals[k]=totals[k]+ c + else + q =q+ SIZE[code[k] ] + if q > limit then + return -1, "row runs past the end" + end + end + end + end + return q, totals +end + +-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message. +-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their +-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows +-- must have passed scan() with the same arguments. +function Binary.rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) +local at = table.create(np, 0) + local q = p + for i = 0, n - 1 do + for k = 1, np do + local sc, dc, d = code[k], dCode[k], dst[k] + if isList[k] then + local cc = countCode[k] + local c = rd(b, q, cc, be) + q =q+ SIZE[cc] + writeu32(sizes[k], i * 4, c) + local ia, ssz, dsz, bd = at[k], SIZE[sc], SIZE[dc], bound[k] + if bd >= 0 then + for j = 0, c - 1 do + local v = rd(b, q, sc, be) + q =q+ ssz + if v < 0 or v >= bd or v ~= math.floor(v / 1 )then + return false, "vertex index out of range" + end + wr(d, (ia + j) * dsz, dc, v) + end + else + for j = 0, c - 1 do + wr(d, (ia + j) * dsz, dc, rd(b, q, sc, be)) + q =q+ ssz + end + end + at[k] = ia + c + else + wr(d, dOff[k] + i * dStride[k], dc, rd(b, q, sc, be)) + q =q+ SIZE[sc] + end + end + end + return true, nil +end + +return Binary +end +__FILES["model/pmx"] = function() +--!strict +-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD +-- format, as documented by the MMD community). New code, no third-party code. +-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / +-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / +-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one +-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, +-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon +-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; +-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), +-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras +-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the +-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). +-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Read = __include("model/pmx/Read") +local Pmd = __include("model/pmx/Pmd") +local Build = __include("model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + +function Pmx.sniff(r) +local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r, opts) +local pmd = r:peek(3) == "Pmd" + local m, msg, kind +if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx +end +__FILES["model/pmx/Build"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, +-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed +-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with +-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as +-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex +-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative +-- translation each) and one skin with translation-only inverse bind matrices. +local Types = __include("Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve +local function fetcher(opts) +return function(uri) +if not opts then + return nil + end + local v= nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = (ok and{res }or{nil +})[1] end + return (type(v) == "string" and{(buffer.fromstring(v) )}or{(type(v) == "buffer" and{v }or{nil +})[1]})[1] end +end + +local function lh(v) +return v and{ v[1], v[2], -v[3] } or nil +end + +-- the scene index of a file texture index (0-based, -1 = none) +local function texIndex(m, i) +return (type(i) == "number" and i >= 0 and i < #m.textures and((i + 1 ))or(nil +))end + +local function material(m, mat) +local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x= { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root +local function parents(bones) +local nb = #bones + local par = table.create(nb, 0) + for i, b in __iter(bones) do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps =steps+ 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered +local function primitive(m, first, n, morphs, sdef) +local map= {} + local verts= {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, math.floor(n / 3 )- 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (c == 0 and 0 or(c == 1 and 2 or 1))) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs= { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd= nil + local deform= nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = c == 2 and-1 or 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in __iter(uvas) do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + -- weights: invalid bones get weight 0, the rest is normalized + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum =sum+ w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, (sum > 0 and((ws[c + 1] / sum ))or((c == 0 and 1 or 0)))) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, (c == 2 and{(-x )}or{x})[1]) + end + end + end + end + end + local prim= { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets= {} + for k, mo in __iter(morphs) do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in __iter(mo.vertices) do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, (c == 2 and{(-x )}or{x})[1]) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m, opts) +local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in __iter(m.textures) do + local uri = string.gsub(path, "\\", "/") + local tex= { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = (ext and{MIME[string.lower(ext)] }or{nil +})[1] scene.textures[i] = tex + end + for i, mat in __iter(m.materials) do + scene.materials[i] = material(m, mat) + end + + -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in __iter(m.morphs) do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = (opts and opts.maxBytes and{opts.maxBytes }or{(2 ^ 28 +)})[1] if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh= { name = m.name, primitives = {} } + local first = 0 + for i, mat in __iter(m.materials) do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first =first+ n + end + if first < m.indexCount then + -- faces no material covers + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = (#names > 0 and{names }or{nil})[1], pmx = #others > 0 and{ morphs = others } or nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + -- nodes: 1 = the model, 2 = the mesh, then one per bone + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world= {} + for i, b in __iter(bones) do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints= {} + for i, b in __iter(bones) do + local w, p = world[i], par[i] + local t = p ~= 0 and{ w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } or{ w[1], w[2], w[3] } + local x= { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = c % 5 == 0 and 1 or(c >= 12 and c <= 14 and{(-w[c - 11] )}or{0 +})[1] writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[(p ~= 0 and((2 + p ))or(1)) ].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build +end +__FILES["model/pmx/Pmd"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as +-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community +-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, +-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to +-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in +-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in +-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +local Bytes = __include("core/Bytes") + +local Pmd = {} + +local function vec(r, n) +local v= {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s) +return not string.find(s, "[\128-\255]") +end + +local function counted(r, n, size, what) +if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r, opts) +if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m= { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = (opts and opts.maxVertices and{opts.maxVertices }or{(2 ^ 24 +)})[1] if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, single and 0 or 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, single and-1 or b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, single and 1 or w) + buffer.writef32(weights, v * 16 + 4, single and 0 or 1 - w) + buffer.writef32(edge, v * 4, buffer.readu8(buf, p + 37) ~= 0 and 0 or 1) + end + r.pos =r.pos+ nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos =r.pos+ ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each; texture names collected into the texture list + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex= {} + local function tex(name) +if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat= { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (edgeFlag ~= 0 and 0x10 or 0) + (d[4] < 1 and 0x01 or 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in __iter(string.gmatch(file, "[^*]+")) do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), ext == "sph" and 1 or 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b= { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = parent == 0xFFFF and-1 or parent + b.tail = (tail ~= 0 and tail ~= 0xFFFF and{tail }or{{ 0, 0, 0 } +})[1] b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (type(b.tail) == "number" and 0x1 or 0) + 0x2 + (kind == 1 and 0x4 or 0) + (kind ~= 7 and 0x8 or 0) + 0x10 + m.bones[i] = b + end + + -- IK chains + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base= {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups= {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t, en) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = (ascii(raw) and{raw }or{(en and en ~= "" and{en }or{raw +})[1]})[1] if ascii(raw) then + t.nameSjis = nil + end + end + local en= {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = (ascii(m.commentSjis) and{m.commentSjis }or{(en.comment or m.commentSjis)})[1], en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in __iter(m.bones) do + name(b, en.bones and en.bones[i]) + end + for i, mo in __iter(m.morphs) do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in __iter(groups) do + name(g, en.groups and en.groups[i]) + end + local toons= {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in __iter(m.materials) do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b= { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j= { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd +end +__FILES["model/pmx/Read"] = function() +local __compat = __compat local buffer, bit32, utf8, type = __compat.buffer, __compat.bit32, __compat.utf8, __compat.type --!strict +-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that +-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. +-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices +-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, +-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, +-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). +-- Never throws: returns nil, message[, kind]. +local Bytes = __include("core/Bytes") +local Text = __include("codecs/text/Text") + +local Read = {} + + + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r, size, vertex) +if size == 1 then + return vertex and function() return r:u8() end or function() return r:i8() end + elseif size == 2 then + return vertex and function() return r:u16le() end or function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r, n) +local v= {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 and at most remaining / minSize records +local function count(r, minSize, what) +local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r, opts) +if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = version > 2.05 and 2.1 or 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g= {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text() +local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos =r.pos+ n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m= { version = version, encoding = utf8 and"utf8" or"utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = (opts and opts.maxVertices and{opts.maxVertices }or{(2 ^ 24 +)})[1] if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv , maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef= nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p =p+ 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p =p+ 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = (vsize == 1 and{(readu8(buf, p + i) )}or{(vsize == 2 and{(readu16(buf, p + i * 2) )}or{(readi32(buf, p + i * 4) +)})[1]})[1] if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv ), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + -- textures + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + -- materials + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat= { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + -- bones + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b= { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = (bit32.btest(fl, 0x1) and{(bidx() )}or{(vec(r, 3) +)})[1] if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik= { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link= { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + -- morphs + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo= { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas), they become morph targets + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off +if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f= { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = kind == 0 and{ bone = bidx() } or{ morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b= { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j= { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read +end +__FILES["model/qb"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the +-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA +-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 +-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. +-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as +-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view +-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and +-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). +-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; +-- options default to the source file's settings. +-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Qb = { + name = "qb", + category = "model", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local CODEFLAG, NEXTSLICEFLAG = 2, 6 +-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour +local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 + +-- ------------------------------------------------------------------------------------------------ sniff +function Qb.sniff(r) +if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then + return 0 + end + local b, p = r.buf, r.pos + local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) + if fmt > 1 or z > 1 or comp > 1 or mask > 1 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them +local function indexed(v, colors, n) + local count= {} + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + if c >= 0x1000000 then -- alpha > 0: filled + local rgb = c % 0x1000000 + local k = count[rgb] + if k == nil then + count[rgb] = 1 + else + count[rgb] = k + 1 + end + end + end + local order = {} + for rgb in __iter(count) do + table.insert(order, rgb) + end + table.sort(order, function(a, b) +if count[a] ~= count[b] then + return count[a] > count[b] + end + return a < b + end) + local slot= {} + for i = 1, math.min(255, #order) do + local rgb = order[i] + slot[rgb] = i + v.palette[i] = { rgb % 256, (math.floor(rgb / 256)) % 256, math.floor(rgb / 65536), 255 } + end + for i = 256, #order do + local rgb = order[i] + local r, g, b = rgb % 256, (math.floor(rgb / 256)) % 256, math.floor(rgb / 65536 +) local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot[rgb] = best + end + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + buffer.writeu8(v.data, i, (c >= 0x1000000 and{slot[c % 0x1000000] }or{0})[1]) + end +end + +function Qb.decode(r, opts) +local o= opts or {} + local maxCells = o.maxCells or 2 ^ 27 + local ver = r:string(4) + local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= "\1\1\0\0" then + return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) + end + if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then + return nil, Err.new(Err.CORRUPT, "bad header flags", 4) + end + if count > math.floor(r:remaining() / 25 )then + return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) + end + local scene = Types.Scene.new() + local grids= {} + scene.voxels = grids + local total = 0 + local bgra = fmt == 1 + for m = 1, count do + local at = r:tell() + local nameLen = r:u8() + local name = r:string(nameLen) + local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() + local px, py, pz = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if sx * sy * sz + total > maxCells then + return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) + end + local n = sx * sy * sz + total =total+ n + local colors = buffer.create(n * 4) + local b = r.buf + local function put(x, y, z, c) + if bgra then -- b, g, r, a -> r, g, b, a + c = (math.floor(c / 65536)) % 256 + (math.floor(c / 256)) % 256 * 256 + c % 256 * 65536 + (math.floor(c / 16777216)) * 16777216 + end + if c < 0x1000000 then + c = 0 -- alpha 0: empty + end + local zz = (zAxis == 0 and((sz - 1 - z ))or(z +)) buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) + end + if compressed == 0 then + if not r:need(n * 4) then + return nil, r.err + end + local p = r.pos + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + put(x, y, z, buffer.readu32(b, p)) + p =p+ 4 + end + end + end + r.pos = p + else + local slice = sx * sy + for z = 0, sz - 1 do + local index = 0 + while true do + local d = r:u32le() + if r.err then + return nil, r.err + end + if d == NEXTSLICEFLAG then + break + elseif d == CODEFLAG then + local run, c = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if index + run > slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) + end + for _ = 1, run do + put(index % sx, math.floor(index / sx), z, c) + index =index+ 1 + end + else + if index >= slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) + end + put(index % sx, math.floor(index / sx), z, d) + index =index+ 1 + end + end + end + end + local v = Types.Voxels.new(sx, sy, sz) + v.name = name + v.colors = colors + indexed(v, colors, n) + table.insert(grids, v) + local tz = (zAxis == 0 and((0 - (pz + sz) ))or(pz +)) table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.source = { + format = "qb", + colorFormat = bgra and"bgra" or"rgba", + rightHanded = zAxis == 1, + compressed = compressed == 1, + visibilityMask = mask == 1, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function cellColor(v, i) +if v.colors then + return buffer.readu32(v.colors, i * 4) + end + local idx = buffer.readu8(v.data, i) + if idx == 0 then + return 0 + end + local p = v.palette[idx] or { 0, 0, 0, 255 } + return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 +end + +function Qb.encode(value, opts) +local o= opts or {} + local grids= {} + local function add(v, name, pos) +if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local n = v.size[1] * v.size[2] * v.size[3] + if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then + return "voxel data shorter than its size" + end + local nm = name or v.name or ("matrix" .. (#grids + 1)) + if #nm > 255 then + return "matrix name longer than 255 bytes" + end + table.insert(grids, { v = v, name = nm, pos = pos }) + return nil + end + local src = (type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" and{value.meta.source }or{nil +})[1] if type(value) == "table" and value.kind == "voxels" then + local e = add(value, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then + local used= {} + local function walk(i, base, depth) +local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + used[node.voxels] = true + local e = add(value.voxels[node.voxels], node.name, p) + if e then + return e + end + end + for _, c in __iter(node.children or {}) do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in __iter(value.roots or {}) do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, Err.new(Err.ARG, e) + end + end + for i, v in __iter(value.voxels) do + if not used[i] then + local e = add(v, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + end + end + else + return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") + end + local function pick(opt, key, default) +if opt ~= nil then + return opt + elseif src and src[key] ~= nil then + return src[key] + end + return default + end + local compressed = pick(o.compressed, "compressed", true) + local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" + local right = pick(o.rightHanded, "rightHanded", true) + local mask = pick(o.visibilityMask, "visibilityMask", false) + local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks + local w = Bytes.writer(1024) + w:string("\1\1\0\0") + w:u32le(bgra and 1 or 0) + w:u32le(right and 1 or 0) + w:u32le(compressed and 1 or 0) + w:u32le(mask and 1 or 0) + w:u32le(#grids) + for _, g in __iter(grids) do + local v = g.v + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + w:u8(#g.name) + w:string(g.name) + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) + w:u32le(px % 4294967296) + w:u32le(py % 4294967296) + w:u32le(((right and{pz }or{(-pz - sz)})[1]) % 4294967296) + local function filled(x, y, z) +if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then + return false + end + return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 + end + -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked + local function value(x, y, z) +local zz = (right and{z }or{(sz - 1 - z +)})[1] local c = cellColor(v, x + sx * (y + sy * zz)) + if c < 0x1000000 then + return 0 + end + local a = math.floor(c / 16777216 +) if mask and not keepMask then + a = 1 + if not filled(x - 1, y, zz) then a =a+ LEFT end + if not filled(x + 1, y, zz) then a =a+ RIGHT end + if not filled(x, y + 1, zz) then a =a+ TOP end + if not filled(x, y - 1, zz) then a =a+ BOTTOM end + if not filled(x, y, zz + 1) then a =a+ FRONT end + if not filled(x, y, zz - 1) then a =a+ BACK end + elseif not mask and src and src.visibilityMask then + a = 255 -- masks are not colours + end + local r, gg, b = c % 256, (math.floor(c / 256)) % 256, (math.floor(c / 65536)) % 256 + if bgra then + r, b = b, r + end + return r + gg * 256 + b * 65536 + a * 16777216 + end + for z = 0, sz - 1 do + if compressed then + local x, y = 0, 0 + local slice = sx * sy + local i = 0 + while i < slice do + x, y = i % sx, math.floor(i / sx +) local c = value(x, y, z) + local run = 1 + while i + run < slice and value((i + run) % sx, math.floor((i + run) / sx), z) == c do + run =run+ 1 + end + if run > 2 then + w:u32le(CODEFLAG) + w:u32le(run) + w:u32le(c) + else + for _ = 1, run do + w:u32le(c) + end + end + i =i+ run + end + w:u32le(NEXTSLICEFLAG) + else + for y = 0, sy - 1 do + for x = 0, sx - 1 do + w:u32le(value(x, y, z)) + end + end + end + end + end + return w:finish(), nil +end + +return Qb +end +__FILES["model/rbxm"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, "<roblox!"), read + write, to and from the instance +-- tree of codecs/model/Rbx (an RbxTree, kind "rbxtree"; not a Scene: Roblox files hold instances, not meshes). +-- Written from the rbx-dom format notes (docs/binary.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. +-- Decode: the header, META (tree.metadata), SSTR (shared strings), INST (classes, referents, service flags), PROP (every +-- property type of codecs/model/Rbx/Binary), PRNT (the hierarchy), END; chunk bodies raw, LZ4 or Zstandard. Unknown +-- chunks are kept raw in tree.extra and written back; properties of unknown types become "Raw" values that are +-- written back verbatim while the class keeps its instances. tree.place is true when the file marks services (rbxl). +-- Encode: every instance depth first (referents 0..n-1), classes sorted by name, properties sorted by name, chunks +-- LZ4-compressed (opts.compression = "none" writes them raw), SharedStrings deduplicated (MD5 keys). An instance +-- without a property its class's other instances have gets the type's default (the format stores one value per +-- instance). "XmlRaw" values (unknown XML types) are skipped. Not supported: writing Zstandard chunks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Md5 = __include("core/Md5") +local Lz4 = __include("codecs/compress/Lz4") +local Zstd = __include("codecs/compress/Zstd") +local Rbx = __include("codecs/model/Rbx") +local Binary = __include("codecs/model/Rbx/Binary") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxm = { + name = "rbxm", + category = "model", + extensions = { "rbxm", "rbxl" }, + mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" }, + deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" }, + caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local MAGIC = "<roblox!\137\255\13\10\26\10" +local readu8, readu32, readi32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxm.sniff(r) +return r:peek(14) == MAGIC and 1 or 0 +end + +-- variant(r) -> "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks +function Rbxm.variant(r) +local b, p, e = r.buf, r.base + 32, r.limit + if r:peek(14) ~= MAGIC then + return nil + end + while p + 16 <= e do + local name, clen, ulen = readstring(b, p, 4), readu32(b, p + 4), readu32(b, p + 8) + local size = (clen == 0 and{ulen }or{clen +})[1] if p + 16 + size > e or name == "END\0" then + break + end + if name == "INST" then + local body, o = b, p + 16 + if clen ~= 0 then + body = (Zstd.isFrame(b, p + 16) and{(Zstd.decompress(b, p + 16, clen, { maxBytes = ulen }) )}or{(Lz4.decompress(b, p + 16, clen, ulen) +)})[1] o = 0 + end + if body and o + 8 <= buffer.len(body) then + local q = o + 8 + readu32(body, o + 4) + if q < buffer.len(body) and readu8(body, q) == 1 then + return "rbxl" + end + end + end + p =p+ (16 + size +) end + return "rbxm" +end +-- ------------------------------------------------------------------------------------------------ decode +-- a length-prefixed string at p of b (limit e): string, next | nil + + + +local function str(b, p, e) +if p + 4 > e then + return nil, p + end + local n = readu32(b, p) + if p + 4 + n > e then + return nil, p + end + return readstring(b, p + 4, n), p + 4 + n +end + +function Rbxm.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 28 + local maxInstances = opts and opts.maxInstances or 2 ^ 22 + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "header", base) + end + if readstring(b, base, 14) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad signature", base) + end + local version = buffer.readu16(b, base + 14) + if version ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14) + end + local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20) + if nClasses < 0 or nInstances < 0 then + return nil, Err.new(Err.CORRUPT, "negative counts", base + 16) + end + if nInstances > maxInstances then + return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20) + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} } + local classes= {} + local byRef= {} + local shared= {} + local parented= {} + local order= {} + local anyService = false + local comp= {} + local ctx= { + ref = function(n) +return byRef[n] + end, + shared = shared, + } + local p = base + 32 + local ended = false + while p < limit do + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header", p) + end + local name = readstring(b, p, 4) + local clen, ulen = readu32(b, p + 4), readu32(b, p + 8) + local at = p + p =p+ 16 + if ulen > maxBytes then + return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at) + end + local body, bo, be +if clen == 0 then + if p + ulen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + body, bo, be = b, p, p + ulen + p =p+ ulen + comp.none = true + else + if p + clen > limit then + return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at) + end + local out, err + if Zstd.isFrame(b, p) then + out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen }) + comp.zstd = true + else + out, err = Lz4.decompress(b, p, clen, ulen) + comp.lz4 = true + end + if not out then + return nil, err + end + if buffer.len(out) ~= ulen then + return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at) + end + body, bo, be = out, 0, ulen + p =p+ clen + end + if name == "END\0" then + ended = true + break + elseif name == "META" then + if bo + 4 > be then + return nil, Err.new(Err.TRUNCATED, "META", at) + end + local q = bo + 4 + for _ = 1, readu32(body, bo) do + local k, q1 = str(body, q, be) + local v, q2 = str(body, q1, be) + if not k or not v then + return nil, Err.new(Err.TRUNCATED, "META entry", at) + end + tree.metadata[k] = v + q = q2 + end + elseif name == "SSTR" then + if bo + 8 > be then + return nil, Err.new(Err.TRUNCATED, "SSTR", at) + end + local q = bo + 8 + for i = 1, readu32(body, bo + 4) do + local s, q2 = str(body, q + 16, be) + if not s then + return nil, Err.new(Err.TRUNCATED, "shared string", at) + end + shared[i] = s + q = q2 + end + elseif name == "INST" then + local id = (bo + 4 <= be and{(readi32(body, bo) )}or{(-1 +)})[1] local cname, q = str(body, bo + 4, be) + if not cname or q + 5 > be then + return nil, Err.new(Err.TRUNCATED, "INST", at) + end + local fmt, count = readu8(body, q), readu32(body, q + 1) + if count > nInstances then + return nil, Err.new(Err.CORRUPT, "more instances than the header says", at) + end + local refs, q2 = Binary.readRefs(body, q + 5, be, count) + if not refs then + return nil, Err.new(Err.TRUNCATED, "INST referents", at) + end + if id < 0 or classes[id] then + return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at) + end + local service = fmt == 1 + if service and q2 + count > be then + return nil, Err.new(Err.TRUNCATED, "INST service markers", at) + end + classes[id] = { id = id, name = cname, refs = refs, service = service } + for i, ref in __iter(refs) do + if byRef[ref] then + return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at) + end + local inst = Rbx.instance(cname) + inst.referent = tostring(ref) + if service and readu8(body, q2 + i - 1) ~= 0 then + inst.service = true + anyService = true + end + byRef[ref] = inst + table.insert(order, inst) + end + elseif name == "PROP" then + local id = (bo + 4 <= be and{(readi32(body, bo) )}or{(-1 +)})[1] local pname, q = str(body, bo + 4, be) + if not pname or q + 1 > be then + return nil, Err.new(Err.TRUNCATED, "PROP", at) + end + local cls = classes[id] + if not cls then + return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at) + end + local t = readu8(body, q) + local n = #cls.refs + local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx) + if vals then + local tname = Rbx.TYPE_NAMES[t] + for i, ref in __iter(cls.refs) do + local inst = byRef[ref] + if pname == "Name" and t == 0x01 then + inst.name = vals[i] + else + inst.properties[pname] = { type = tname, value = vals[i] } + end + end + elseif msg == "unknown" then + local data = buffer.create(be - q - 1) + buffer.copy(data, 0, body, q + 1, be - q - 1) + for i, ref in __iter(cls.refs) do + byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } } + end + else + return nil, Err.from(msg, at) + end + elseif name == "PRNT" then + if bo + 5 > be then + return nil, Err.new(Err.TRUNCATED, "PRNT", at) + end + if readu8(body, bo) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at) + end + local count = readu32(body, bo + 1) + local kids, q = Binary.readRefs(body, bo + 5, be, count) + local parents = (kids and{(Binary.readRefs(body, q, be, count) )}or{nil +})[1] if not kids or not parents then + return nil, Err.new(Err.TRUNCATED, "PRNT referents", at) + end + for i = 1, count do + local child, parent = byRef[kids[i] ], parents[i] >= 0 and byRef[parents[i] ] or nil + if not child or (parents[i] >= 0 and not parent) then + return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at) + end + if parented[child] then + return nil, Err.new(Err.CORRUPT, "an instance with two parents", at) + end + parented[child] = true + -- refuse cycles: the parent may not be a descendant of the child + local up= parent + while up do + if up == child then + return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at) + end + up = up.parent + end + Rbx.add(parent or tree, child) + end + else + local data = buffer.create(be - bo) + buffer.copy(data, 0, body, bo, be - bo) + table.insert(tree.extra, { name = name, data = data }) + end + end + if not ended then + return nil, Err.new(Err.TRUNCATED, "no END chunk", limit) + end + -- instances PRNT does not mention are roots + for _, inst in __iter(order) do + if not parented[inst] then + table.insert(tree.roots, inst) + end + end + tree.place = anyService + local list = {} + for k in __iter(comp) do + table.insert(list, k) + end + table.sort(list) + local src= tree.meta.source + src.compression = list + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the binary type of a property over a class's instances: type id, type name | nil, message +local function columnType(insts, pname) +local id, tname = nil, nil + for _, inst in __iter(insts) do + local v = inst.properties[pname] + if v then + if type(v) ~= "table" or type(v.type) ~= "string" then + return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table" + end + local t = v.type == "Raw" and-1 or(v.type == "XmlRaw" and-2 or Rbx.TYPE_IDS[v.type] +) if not t then + return nil, "property " .. pname .. ": unknown type " .. v.type + end + if id == nil then + id, tname = t, v.type + elseif id ~= t then + return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type + end + end + end + return id, tname +end + +local function chunk(w, name, body, compress) + w:string(name) + local n = buffer.len(body) + if compress then + local z = (Lz4.compress(body) ) +w:u32le(buffer.len(z)) + w:u32le(n) + w:u32le(0) + w:bytes(z) + else + w:u32le(0) + w:u32le(n) + w:u32le(0) + w:bytes(body) + end +end + +local function putStr(w, s) + w:u32le(#s) + w:string(s) +end + +function Rbxm.encode(tree, opts) +if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local o= opts or {} + local compress = o.compression ~= "none" + local place = (o.place ~= nil and{(o.place == true )}or{o.format == "rbxl" and true or tree.place == true +})[1] -- every instance depth first; referents in that order + local insts= {} + local refOf= {} + local parentOf= {} + local function visit(inst, parent) +if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refOf[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refOf[inst] = #insts + table.insert(insts, inst) + parentOf[inst] = parent + for _, c in __iter(inst.children or {}) do + local e = visit(c, inst) + if e then + return e + end + end + return nil + end + for _, root in __iter(tree.roots) do + local e = visit(root, nil) + if e then + return nil, e + end + end + -- classes by name + local byClass= {} + local names = {} + for _, inst in __iter(insts) do + local list = byClass[inst.className] + if not list then + list = {} + byClass[inst.className] = list + table.insert(names, inst.className) + end + table.insert(list, inst) + end + table.sort(names) + -- shared strings, in order of first use + local sharedIdx= {} + local sharedList= {} + local ctx= { + refOf = function(v) +return refOf[v] or -1 + end, + sharedIndex = function(s) +local i = sharedIdx[s] + if not i then + table.insert(sharedList, s) + i = #sharedList - 1 + sharedIdx[s] = i + end + return i + end, + } + local props= {} + local instChunks= {} + for classId, cname in __iter(names) do + local list = byClass[cname] + local id = classId - 1 + -- INST + local w = Bytes.writer(64 + 5 * #list) + w:u32le(id) + putStr(w, cname) + local service = place and parentOf[list[1] ] == nil + for _, inst in __iter(list) do + if inst.service then + service = true + end + end + w:u8(service and 1 or 0) + w:u32le(#list) + local refs = table.create(#list, 0) + for i, inst in __iter(list) do + refs[i] = refOf[inst] + end + Binary.writeRefs(w, refs) + if service then + for _, inst in __iter(list) do + w:u8((inst.service or (place and parentOf[inst] == nil) )and 1 or 0) + end + end + table.insert(instChunks, w:finish()) + -- PROP: Name, then every property any instance of the class has, sorted + local pnames= {} + local seen= {} + for _, inst in __iter(list) do + for pn in __iter(inst.properties) do + if not seen[pn] and pn ~= "Name" then + seen[pn] = true + table.insert(pnames, pn) + end + end + end + table.sort(pnames) + table.insert(pnames, 1, "Name") + for _, pn in __iter(pnames) do + local t, tname +if pn == "Name" then + t, tname = 0x01, "String" + else + local e + t, e = columnType(list, pn) + if not t then + return nil, Err.new(Err.ARG, e or "bad property") + end + tname = e + end + local pw = Bytes.writer(64) + pw:u32le(id) + putStr(pw, pn) + local tid = t +if tid == -1 then + -- Raw: the column read from a file, written back only when this class still has exactly its instances + local first = list[1].properties[pn] + local raw = first and first.value + local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer" + if ok then + for i, inst in __iter(list) do + local v = inst.properties[pn] + if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then + ok = false + break + end + end + end + if ok then + pw:u8(raw.typeId) + pw:bytes(raw.data) + table.insert(props, pw:finish()) + end + elseif tid ~= -2 then + pw:u8(tid) + local vals = table.create(#list) + for i, inst in __iter(list) do + if pn == "Name" then + vals[i] = (type(inst.name) == "string" and{inst.name }or{inst.className +})[1] else + local v = inst.properties[pn] + if v then + vals[i] = v.value + else + vals[i] = Rbx.default(tname ) + end + end + end + local e = Binary.encode(tid, vals, #list, pw, ctx) + if e then + return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e) + end + table.insert(props, pw:finish()) + end + end + end + -- PRNT + local pw = Bytes.writer(16 + 8 * #insts) + pw:u8(0) + pw:u32le(#insts) + local kids, parents = table.create(#insts, 0), table.create(#insts, 0) + for i, inst in __iter(insts) do + kids[i] = i - 1 + local par = parentOf[inst] + parents[i] = (par and{refOf[par] }or{(-1 +)})[1] end + Binary.writeRefs(pw, kids) + Binary.writeRefs(pw, parents) + + local out = Bytes.writer(1024) + out:string(MAGIC) + out:u16le(0) + out:u32le(#names) + out:u32le(#insts) + out:u32le(0) + out:u32le(0) + local metaKeys = {} + for k, v in __iter(tree.metadata or {}) do + if type(k) == "string" and type(v) == "string" then + table.insert(metaKeys, k) + end + end + if #metaKeys > 0 then + table.sort(metaKeys) + local mw = Bytes.writer(64) + mw:u32le(#metaKeys) + for _, k in __iter(metaKeys) do + putStr(mw, k) + putStr(mw, (tree.metadata )[k]) + end + chunk(out, "META", mw:finish(), compress) + end + if #sharedList > 0 then + local sw = Bytes.writer(64) + sw:u32le(0) + sw:u32le(#sharedList) + for _, s in __iter(sharedList) do + local h = Md5.new() + h:update(buffer.fromstring(s)) + sw:string(h:digest()) + putStr(sw, s) + end + chunk(out, "SSTR", sw:finish(), compress) + end + for _, c in __iter(instChunks) do + chunk(out, "INST", c, compress) + end + for _, c in __iter(props) do + chunk(out, "PROP", c, compress) + end + chunk(out, "PRNT", pw:finish(), compress) + for _, x in __iter(tree.extra or {}) do + if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then + chunk(out, x.name, x.data, compress) + end + end + chunk(out, "END\0", buffer.fromstring("</roblox>"), false) + return out:finish(), nil +end + +return Rbxm +end +__FILES["model/rbxmx"] = function() +local __compat = __compat local buffer, utf8, type, __iter = __compat.buffer, __compat.utf8, __compat.type, __compat.__iter --!strict +-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, `<roblox version="4">`), read + write, to and from +-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save). +-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways. +-- Decode: <Meta>, <Item class referent> with <Properties> of every type codecs/model/Rbx lists (string, BinaryString +-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN), +-- token, BrickColor (as rbx-dom: an <int>; read back as BrickColor for the BrickColor properties of a short +-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame, +-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange, +-- PhysicalProperties, Ref, SharedString (+ <SharedStrings>), UniqueId, Font, SecurityCapabilities); unknown property +-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra. +-- tree.place is true when a root is a Workspace (rbxlx). +-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent, +-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control +-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Base64 = __include("core/Base64") +local Md5 = __include("core/Md5") +local Xml = __include("codecs/text/Xml") +local Rbx = __include("codecs/model/Rbx") + +-- ------------------------------------------------------------------------------------------------ contract +local Rbxmx = { + name = "rbxmx", + category = "model", + extensions = { "rbxmx", "rbxlx" }, + mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" }, + deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" }, + caps = { decode = true, encode = true, tree = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local XmlNode = Xml.element +local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch + +-- tag name -> type name for the simple (text) types +local SCALAR_TAGS= { + string = "String", + ProtectedString = "ProtectedString", + bool = "Bool", + int = "Int32", + int64 = "Int64", + float = "Float32", + double = "Float64", + token = "Enum", + BrickColor = "BrickColor", + SecurityCapabilities = "SecurityCapabilities", + UniqueId = "UniqueId", +} +-- BrickColor properties: XML writes them as <int> (rbx-dom reads them through its reflection database); these known ones +-- read back as BrickColor (the rest of an <int> stays Int32) +local BRICKCOLOR= { + ["BrickColorValue.Value"] = true, + ["SpawnLocation.TeamColor"] = true, + ["Team.TeamColor"] = true, + ["FlagStand.TeamColor"] = true, + ["Skin.SkinColor"] = true, +} +-- the strings rbx-dom writes as BinaryString (the rest decides by content) +local BINARY_NAMES= { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Rbxmx.sniff(r) +local head = r:peek(256) + head = string.gsub(head, "^\239\187\191", "") + head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "") + if match(head, "^%s*<roblox[%s>]") then + return find(head, "version=", 1, true) and 1 or 0.8 + end + return 0 +end + +-- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect) +function Rbxmx.variant(r) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + return find(text, '<Item class="Workspace"', 1, true) and"rbxlx" or"rbxmx" +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(s) +if s == nil then + return 0 + end + local t = string.lower((string.gsub(s, "^%s+", ""))) + t = string.gsub(t, "%s+$", "") + if t == "inf" or t == "+inf" or t == "infinity" then + return math.huge + elseif t == "-inf" or t == "-infinity" then + return -math.huge + elseif t == "nan" or t == "-nan" then + return 0 / 0 + end + return tonumber(t) or 0 +end + +local function childText(node, name) +local c = Xml.child(node, name) + return (c and{(Xml.text(c) )}or{nil +})[1]end +local function comps(node, names) +local out = table.create(#names, 0) + if node then + for i, n in __iter(names) do + out[i] = num(childText(node, n)) + end + end + return out +end +local function numbers(s) +local out = {} + for w in __iter(gmatch(s, "%S+")) do + table.insert(out, num(w)) + end + return out +end + +local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" } +local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" } + +-- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs +-- come back as { pending = referent }) +local function readRaw(node, shared, key) +local tag = node.name + local scalar = SCALAR_TAGS[tag] + if tag == "int" and BRICKCOLOR[key] then + scalar = "BrickColor" + end + if scalar then + local s = Xml.text(node) + if scalar == "String" or scalar == "ProtectedString" then + return scalar, s + elseif scalar == "Bool" then + return scalar, match(s, "^%s*true%s*$") ~= nil + elseif scalar == "UniqueId" then + return scalar, string.lower((string.gsub(s, "%s", ""))) + end + return scalar, num(s) + elseif tag == "BinaryString" then + local data = Base64.decode((string.gsub(Xml.text(node), "%s", ""))) + return "BinaryString", (data and{(buffer.tostring(data) )}or{"" +})[1] elseif tag == "Content" or tag == "ContentId" then + local url = Xml.child(node, "url") + if url then + return "ContentId", Xml.text(url) + end + local uri = Xml.child(node, "uri") + if uri then + return "Content", Xml.text(uri) + end + local obj = Xml.child(node, "Object") or Xml.child(node, "Ref") + if obj then + return "Content", { pending = Xml.text(obj) } + end + if Xml.child(node, "null") then + return (tag == "ContentId" and"ContentId" or"Content"), (tag == "ContentId" and"" or nil) + end + return "ContentId", Xml.text(node) + elseif tag == "Vector2" or tag == "Vector2int16" then + return tag, comps(node, { "X", "Y" }) + elseif tag == "Vector3" or tag == "Vector3int16" then + return tag, comps(node, { "X", "Y", "Z" }) + elseif tag == "Color3" then + if Xml.child(node, "R") then + return tag, comps(node, { "R", "G", "B" }) + end + local v = num(Xml.text(node)) % 4294967296 + return tag, { (math.floor(v / 65536)) % 256 / 255, (math.floor(v / 256)) % 256 / 255, v % 256 / 255 } + elseif tag == "Color3uint8" then + local v = num(Xml.text(node)) % 4294967296 + return tag, { (math.floor(v / 65536)) % 256, (math.floor(v / 256)) % 256, v % 256 } + elseif tag == "CoordinateFrame" or tag == "CFrame" then + return "CFrame", comps(node, CF_NAMES) + elseif tag == "OptionalCoordinateFrame" then + local cf = Xml.child(node, "CFrame") + return "OptionalCFrame", (cf and{(comps(cf, CF_NAMES) )}or{nil +})[1] elseif tag == "UDim" then + return tag, comps(node, { "S", "O" }) + elseif tag == "UDim2" then + return tag, comps(node, { "XS", "XO", "YS", "YO" }) + elseif tag == "Rect2D" then + local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" }) + return "Rect", { a[1], a[2], b[1], b[2] } + elseif tag == "Ray" then + local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" }) + return tag, { a[1], a[2], a[3], b[1], b[2], b[3] } + elseif tag == "Faces" or tag == "Axes" then + local t = childText(node, string.lower(tag)) + return tag, num(t or Xml.text(node)) + elseif tag == "NumberRange" then + local v = numbers(Xml.text(node)) + return tag, { v[1] or 0, v[2] or 0 } + elseif tag == "NumberSequence" or tag == "ColorSequence" then + local k = tag == "NumberSequence" and 3 or 5 + local v = numbers(Xml.text(node)) + local seq = {} + for i = 1, #v - k + 1, k do + table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0))) + end + return tag, seq + elseif tag == "PhysicalProperties" then + local custom = childText(node, "CustomPhysics") + if not custom or not match(custom, "^%s*true%s*$") then + return tag, nil + end + local v = comps(node, PHYS_NAMES) + local a = childText(node, "AcousticAbsorption") + v[6] = (a and{(num(a) )}or{1 +})[1] return tag, v + elseif tag == "Ref" then + local s = string.gsub(Xml.text(node), "%s", "") + return tag, ((s == "" or s == "null" )and{nil }or{{ pending = s } +})[1] elseif tag == "SharedString" then + local key = string.gsub(Xml.text(node), "%s", "") + return tag, shared[key] or "" + elseif tag == "Font" then + local fam = Xml.child(node, "Family") + local face = Xml.child(node, "CachedFaceId") + local f = { + family = (fam and{childText(fam, "url") or Xml.text(fam) }or{""})[1], + weight = num(childText(node, "Weight") or "400"), + style = match(childText(node, "Style") or "", "Italic") and"Italic" or"Normal", + cachedFaceId = (face and{childText(face, "url") or nil }or{nil})[1], + } + if f.cachedFaceId == "" then + f.cachedFaceId = nil + end + return tag, f + end + return "XmlRaw", node +end + +-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary +-- decodes of the same data are equal. Which components are floats, by type (true = all) +local F32= { + Float32 = true, + Vector2 = true, + Vector3 = true, + Color3 = true, + CFrame = true, + OptionalCFrame = true, + Rect = true, + Ray = true, + NumberRange = true, + NumberSequence = true, + ColorSequence = true, + PhysicalProperties = true, + UDim = { true, false }, + UDim2 = { true, false, true, false }, +} +local f32buf = buffer.create(4) +local function f32(v) +buffer.writef32(f32buf, 0, v) + return buffer.readf32(f32buf, 0) +end +local function round32(v, which) +if type(v) == "number" then + return f32(v) + elseif type(v) == "table" then + for i, x in __iter(v) do + if type(x) == "table" then + round32(x, true) + elseif type(x) == "number" and (which == true or which[i]) then + v[i] = f32(x) + end + end + end + return v +end +local function readValue(node, shared, key) +local t, v = readRaw(node, shared, key) + local which = F32[t] + if which then + v = round32(v, which) + end + return t, v +end + +function Rbxmx.decode(r, opts) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } ) + if not doc then + return nil, err + end + local root = (doc ).root + if not root or root.name ~= "roblox" then + return nil, Err.new(Err.CORRUPT, "the root element is not <roblox>") + end + local tree = Rbx.tree() + tree.meta.source = { format = "rbxmx", version = root.attrs.version } + -- shared strings first (properties name them by key) + local shared= {} + for _, ss in __iter(Xml.children(root, "SharedStrings")) do + for _, s in __iter(Xml.children(ss, "SharedString")) do + local key = s.attrs.md5 + local data = Base64.decode((string.gsub(Xml.text(s), "%s", ""))) + if key and data then + shared[key] = buffer.tostring(data) + end + end + end + local byRef= {} + local pending= {} -- { value table, field, referent } + local function item(node, parent) +local cls = node.attrs.class + if type(cls) ~= "string" then + return Err.new(Err.CORRUPT, "an <Item> without a class") + end + local inst = Rbx.instance(cls) + local ref = node.attrs.referent + if type(ref) == "string" then + inst.referent = ref + byRef[ref] = inst + end + Rbx.add(parent, inst) + for _, c in __iter(node.children) do + if type(c) == "table" then + if c.name == "Properties" then + for _, pnode in __iter(c.children) do + if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then + local pname = pnode.attrs.name + if type(pname) == "string" then + local t, v = readValue(pnode, shared, cls .. "." .. pname) + if pname == "Name" and (t == "String" or t == "ProtectedString") then + inst.name = v + else + local val = { type = t, value = v } + inst.properties[pname] = val + if type(v) == "table" and v.pending then + table.insert(pending, { val, v.pending }) + end + end + end + end + end + elseif c.name == "Item" then + local e = item(c, inst) + if e then + return e + end + end + end + end + return nil + end + for _, c in __iter(root.children) do + if type(c) == "table" then + if c.name == "Item" then + local e = item(c, tree) + if e then + return nil, e + end + elseif c.name == "Meta" then + if type(c.attrs.name) == "string" then + tree.metadata[c.attrs.name] = Xml.text(c) + end + elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then + table.insert(tree.extra, c) + end + end + end + for _, p in __iter(pending) do + p[1].value = byRef[p[2] ] + end + for _, rt in __iter(tree.roots) do + if rt.className == "Workspace" then + tree.place = true + end + end + return tree, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the shortest text that reads back as the same float (single: f32 values; else f64) +local function fmt(v, single) +if type(v) ~= "number" then + v = 0 + end + if v ~= v then + return "NAN" + elseif v == math.huge then + return "INF" + elseif v == -math.huge then + return "-INF" + end + if single then + v = f32(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%.0f", v) + end + for d = single and 6 or 15, single and 9 or 17 do + local s = format("%." .. d .. "g", v) + local back = tonumber(s) or 0 + if ((single and{(f32(back) )}or{back})[1]) == v then + return s + end + end + return format("%.17g", v) +end +local function int(v) +return format("%.0f", math.floor((type(v) == "number" and v == v and math.abs(v) ~= math.huge and{v }or{0})[1])) +end + +local function textEl(tag, text) +return XmlNode(tag, nil, { text }) +end +local function compsEl(tag, attrs, names, v, single, ints) +local kids = {} + for i, n in __iter(names) do + local x = (type(v) == "table" and{v[i] }or{0 +})[1] table.insert(kids, textEl(n, (ints and{(int(x) )}or{(fmt(x, single))})[1])) + end + return XmlNode(tag, attrs, kids) +end + +local function hexDigits(i) +return format("%032X", i) +end + +local function xmlSafe(s) +if find(s, "[%z\1-\8\11\12\14-\31\127]") then + return false + end + return utf8.len(s) ~= nil +end + +-- a property -> its element, or nil to skip +local function writeValue(name, v, refOf, sharedKey) +local t, x = v.type, v.value + local a = { name = name } + if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then + local s = (type(x) == "string" and{x }or{"" +})[1] if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then + return XmlNode("BinaryString", a, { Base64.encode(s) }) + end + return XmlNode(t == "ProtectedString" and"ProtectedString" or"string", a, { s }) + elseif t == "ContentId" then + local s = (type(x) == "string" and{x }or{"" +})[1] return XmlNode("ContentId", a, { (s == "" and{(XmlNode("null") )}or{(textEl("url", s) )})[1]}) + elseif t == "Content" then + if type(x) == "string" then + return XmlNode("Content", a, { textEl("uri", x) }) + elseif type(x) == "table" then + return XmlNode("Content", a, { textEl("Object", refOf(x)) }) + end + return XmlNode("Content", a, { XmlNode("null") }) + elseif t == "Bool" then + return XmlNode("bool", a, { x and"true" or"false" }) + elseif t == "Int32" then + return XmlNode("int", a, { int(x) }) + elseif t == "Int64" then + return XmlNode("int64", a, { int(x) }) + elseif t == "Float32" then + return XmlNode("float", a, { fmt(x, true) }) + elseif t == "Float64" then + return XmlNode("double", a, { fmt(x) }) + elseif t == "Enum" then + return XmlNode("token", a, { int(x) }) + elseif t == "BrickColor" then + return XmlNode("int", a, { int(x) }) + elseif t == "SecurityCapabilities" then + return XmlNode("SecurityCapabilities", a, { int(x) }) + elseif t == "UniqueId" then + return XmlNode("UniqueId", a, { (type(x) == "string" and{(string.lower(x) )}or{(string.rep("0", 32) )})[1]}) + elseif t == "Vector2" then + return compsEl(t, a, { "X", "Y" }, x, true) + elseif t == "Vector3" then + return compsEl(t, a, { "X", "Y", "Z" }, x, true) + elseif t == "Vector2int16" then + return compsEl(t, a, { "X", "Y" }, x, false, true) + elseif t == "Vector3int16" then + return compsEl(t, a, { "X", "Y", "Z" }, x, false, true) + elseif t == "Color3" then + return compsEl(t, a, { "R", "G", "B" }, x, true) + elseif t == "Color3uint8" then + local c = (type(x) == "table" and{x }or{{ 0, 0, 0 } +})[1] local function b(i) +return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255) + end + return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) }) + elseif t == "CFrame" then + return compsEl("CoordinateFrame", a, CF_NAMES, x, true) + elseif t == "OptionalCFrame" then + return XmlNode("OptionalCoordinateFrame", a, type(x) == "table" and{ compsEl("CFrame", nil, CF_NAMES, x, true) } or{}) + elseif t == "UDim" then + local u = (type(x) == "table" and{x }or{{ 0, 0 } +})[1] return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) }) + elseif t == "UDim2" then + local u = (type(x) == "table" and{x }or{{ 0, 0, 0, 0 } +})[1] return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) }) + elseif t == "Rect" then + local u = (type(x) == "table" and{x }or{{ 0, 0, 0, 0 } +})[1] return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) }) + elseif t == "Ray" then + local u = (type(x) == "table" and{x }or{{ 0, 0, 0, 0, 0, 0 } +})[1] return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) }) + elseif t == "Faces" or t == "Axes" then + return XmlNode(t, a, { textEl(string.lower(t), int(x)) }) + elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then + local parts = {} + local list = type(x) ~= "table" and{} or(t == "NumberRange" and{ x } or x +) for _, key in __iter(list) do + for _, c in __iter(key) do + table.insert(parts, fmt(c, true) .. " ") + end + end + return XmlNode(t, a, { table.concat(parts) }) + elseif t == "PhysicalProperties" then + if type(x) ~= "table" then + return XmlNode(t, a, { textEl("CustomPhysics", "false") }) + end + local kids = { textEl("CustomPhysics", "true") } + for i, n in __iter(PHYS_NAMES) do + table.insert(kids, textEl(n, fmt(x[i], true))) + end + table.insert(kids, textEl("AcousticAbsorption", fmt((x[6] ~= nil and{x[6] }or{1})[1], true))) + return XmlNode(t, a, kids) + elseif t == "Ref" then + return XmlNode("Ref", a, { (x ~= nil and{(refOf(x) )}or{"null" })[1]}) + elseif t == "SharedString" then + return XmlNode("SharedString", a, { sharedKey((type(x) == "string" and{x }or{""})[1]) }) + elseif t == "Font" then + local f = (type(x) == "table" and{x }or{(Rbx.default("Font") +)})[1] local kids = { + XmlNode("Family", nil, { textEl("url", (type(f.family) == "string" and{f.family }or{""})[1]) }), + textEl("Weight", int(f.weight or 400)), + textEl("Style", f.style == "Italic" and"Italic" or"Normal"), + } + if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then + table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) })) + end + return XmlNode("Font", a, kids) + elseif t == "XmlRaw" then + if type(x) == "table" and type(x.name) == "string" then + local copy = XmlNode(x.name, nil, x.children) + for k, val in __iter(x.attrs) do + Xml.setAttr(copy, k, val) + end + Xml.setAttr(copy, "name", name) + return copy + end + end + return nil +end + +function Rbxmx.encode(tree, opts) +if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then + return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)") + end + local refs= {} + local count = 0 + local function assign(inst) +if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then + return Err.new(Err.ARG, "an instance needs className and properties") + end + if refs[inst] then + return Err.new(Err.ARG, "an instance appears twice in the tree") + end + refs[inst] = "RBX" .. hexDigits(count) + count =count+ 1 + for _, c in __iter(inst.children or {}) do + local e = assign(c) + if e then + return e + end + end + return nil + end + for _, rt in __iter(tree.roots) do + local e = assign(rt) + if e then + return nil, e + end + end + local function refOf(x) +return refs[x] or "null" + end + local sharedKeys= {} + local sharedList= {} + local function sharedKey(s) +local k = sharedKeys[s] + if not k then + local h = Md5.new() + h:update(buffer.fromstring(s)) + k = Base64.encode(h:digest()) + sharedKeys[s] = k + table.insert(sharedList, s) + end + return k + end + local function item(inst) +local props = { textEl("string", inst.name or inst.className) } + props[1].attrs.name = "Name" + local names= {} + for k in __iter(inst.properties) do + if k ~= "Name" then + table.insert(names, k) + end + end + table.sort(names) + for _, k in __iter(names) do + local v = inst.properties[k] + if type(v) == "table" then + local el = writeValue(k, v, refOf, sharedKey) + if el then + table.insert(props, el) + end + end + end + local kids = { XmlNode("Properties", nil, props) } + for _, c in __iter(inst.children or {}) do + table.insert(kids, item(c)) + end + local el = XmlNode("Item", nil, kids) + Xml.setAttr(el, "class", inst.className) + Xml.setAttr(el, "referent", refs[inst]) + return el + end + local root = XmlNode("roblox", nil, {}) + Xml.setAttr(root, "version", "4") + local metaKeys = {} + for k in __iter(tree.metadata or {}) do + table.insert(metaKeys, k) + end + table.sort(metaKeys) + for _, k in __iter(metaKeys) do + local m = textEl("Meta", tostring((tree.metadata )[k])) + m.attrs.name = k + Xml.append(root, m) + end + for _, rt in __iter(tree.roots) do + Xml.append(root, item(rt)) + end + for _, x in __iter(tree.extra or {}) do + if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then + Xml.append(root, x) + end + end + if #sharedList > 0 then + local ss = XmlNode("SharedStrings", nil, {}) + for _, s in __iter(sharedList) do + local el = XmlNode("SharedString", nil, { Base64.encode(s) }) + Xml.setAttr(el, "md5", sharedKeys[s]) + Xml.append(ss, el) + end + Xml.append(root, ss) + end + local indent = (opts and opts.indent ~= nil and{opts.indent }or{2 +})[1] local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false }) + if not s then + return nil, err + end + return buffer.fromstring(s), nil +end + +return Rbxmx +end +__FILES["model/robloxmesh"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh +-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port. +-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, +-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown +-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes +-- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC +-- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed +-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in +-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files' +-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes +-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw +-- (meta.source.facs). meta.up = "y"; units are studs. +-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every +-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes +-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to +-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive). +-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing +-- 3.00 / 5.00+ / FACS. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") +local Draco = __include("codecs/model/Draco") +local Parse = __include("model/robloxmesh/Parse") +local Write = __include("model/robloxmesh/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local RobloxMesh = { + name = "robloxmesh", + category = "model", + extensions = { "mesh" }, + mime = { "application/x-roblox-mesh" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Draco" }, + caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16 +local accessor = Types.Scene.accessor + +-- ------------------------------------------------------------------------------------------------ sniff +function RobloxMesh.sniff(r) +return string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z) +local function boneMatrix(cf) +return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 } +end + +local function indices(r, from, to) +local n = math.max(0, to - from) + local d = buffer.create(n * 12) + buffer.copy(d, 0, r.faces, from * 12, n * 12) + return accessor(d, "u32", 1, n * 3) +end + +-- a Draco-compressed COREMESH body -> the record's vertex / face fields +local function dracoCore(b, off, len) -- the stream follows a u32 byte count (accepted without it too) + +if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then + len = buffer.readu32(b, off) + off =off+ 4 + end + local g, err = Draco.decode(b, off, len) + if not g then + return nil, (err ).message + end + if g.kind ~= "mesh" then + return nil, "corrupt: Draco COREMESH holds a point cloud" + end + local n = g.numPoints + local by= {} + for _, a in __iter(g.attributes) do + local key = a.name == "GENERIC" and a.components == 4 and"TANGENT" or a.name + if not by[key] then + by[key] = a + end + end + local pos = by.POSITION + if not pos or pos.components < 3 then + return nil, "corrupt: Draco COREMESH without positions" + end + -- an attribute's values as numbers (normalized integers as -1..1 / 0..1) + local function getter(a) +local t = (a.normalized and{(({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) )[a.type] or a.type }or{a.type +})[1] local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n }) + if not rd then + return function(_i, _c) +return 0 + end + end + return rd + end + local function floats(a, comps) +local out = buffer.create(n * comps * 4) + if a then + local get = getter(a) + local m = math.min(comps, a.components) + for i = 0, n - 1 do + for c = 0, m - 1 do + writef32(out, (i * comps + c) * 4, get(i, c)) + end + end + end + return out + end + local tan= nil + if by.TANGENT then + local get = getter(by.TANGENT) + local t = buffer.create(n * 4) + for i = 0, n - 1 do + for c = 0, 3 do + local v = (c < by.TANGENT.components and{(get(i, c) )}or{1 +})[1] buffer.writei8(t, i * 4 + c, math.clamp(math.floor(v * 127 + 0.5), -127, 127)) + end + end + tan = t + end + local col= nil + if by.COLOR then + local a = by.COLOR + local c = buffer.create(n * 4) + if a.type == "u8" and a.components == 4 then + buffer.copy(c, 0, a.data, 0, n * 4) + else + local get = getter(a) + for i = 0, n - 1 do + for k = 0, 3 do + local v = (k < a.components and{(get(i, k) )}or{1 +})[1] if a.type ~= "f32" and not a.normalized then + v =v/ 255 + end + writeu8(c, i * 4 + k, math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + end + end + col = c + end + return { + numVerts = n, + pos = floats(pos, 3), + nrm = floats(by.NORMAL, 3), + uv = floats(by.TEX_COORD, 2), + tan = tan, + col = col, + numFaces = g.numFaces, + faces = g.indices , + }, nil +end + +-- Parse is native: nothing may throw through it, so the callback never does +local function safeCore(b, off, len) +local ok, c, err = pcall(dracoCore, b, off, len) + if not ok then + return nil, "corrupt: Draco COREMESH: " .. tostring(c) + end + return c, err +end + +function RobloxMesh.decode(rd, opts) +local lim= { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25, core = safeCore } + local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim) + if not r then + return nil, Err.from(msg, rd.base) + end + local nv, nf = r.numVerts, r.numFaces + local attrs= { + POSITION = accessor(r.pos, "f32", 3, nv), + NORMAL = accessor(r.nrm, "f32", 3, nv), + TEXCOORD_0 = accessor(r.uv, "f32", 2, nv), + } + local tan = r.tan + if tan then + local t = buffer.create(nv * 16) + for i = 0, nv - 1 do + local x, y, z, w = Parse.tangent(tan, i) + writef32(t, i * 16, x) + writef32(t, i * 16 + 4, y) + writef32(t, i * 16 + 8, z) + writef32(t, i * 16 + 12, w) + end + attrs.TANGENT = accessor(t, "f32", 4, nv) + end + if r.col then + attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv) + end + -- LOD ranges (offsets clamped to the faces) + local offs = {} + for _, o in __iter(r.lods) do + table.insert(offs, math.clamp(o, 0, nf)) + end + if #offs < 2 then + offs = { 0, nf } + end + local scene = Types.Scene.new() + local prim= { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" } + local lods = {} + for k = 2, #offs - 1 do + table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" }) + end + local mesh= { name = "Mesh", primitives = { prim } } + if #lods > 0 then + mesh.extras = { lods = lods } + end + scene.meshes[1] = mesh + scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + -- bones and skinning + local nb = #r.bones + if nb > 0 then + local world= (table.create(nb) ) +for i, bone in __iter(r.bones) do + world[i] = boneMatrix(bone.cf) + end + local joints = table.create(nb, 0) + local ibm = buffer.create(nb * 64) + for i, bone in __iter(r.bones) do + local parent = (bone.parent and bone.parent < nb and bone.parent ~= i - 1 and((bone.parent + 1 ))or(nil +)) local m = world[i] + if parent then + local inv = Mat4.inverse(world[parent]) + if inv then + m = Mat4.mul(inv, m) + end + end + local node= { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } } + table.insert(scene.nodes, node) + joints[i] = #scene.nodes + local inv = Mat4.inverse(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k]) + end + end + for i, bone in __iter(r.bones) do + local parent = (bone.parent and bone.parent < nb and bone.parent ~= i - 1 and((bone.parent + 1 ))or(nil +)) if parent then + table.insert(scene.nodes[joints[parent] ].children, joints[i]) + else + table.insert(scene.roots, joints[i]) + end + end + scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) } + scene.nodes[1].skin = 1 + local env = r.env + if env then + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4) + for i = 0, nv - 1 do + for k = 0, 3 do + writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k)) + end + end + for _, s in __iter(r.subsets) do + local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1 + for v = s.vertsBegin, last do + for k = 0, 3 do + local li = readu8(env, v * 8 + k) + local g = s.bones[li + 1] + writeu16(jb, v * 8 + k * 2, (g and g < nb and readu8(wb, v * 4 + k) > 0 and{g }or{0})[1]) + end + end + end + attrs.JOINTS_0 = accessor(jb, "u16", 4, nv) + attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv) + end + end + local subsets = {} + for _, s in __iter(r.subsets) do + table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones }) + end + scene.meta.up = "y" + scene.meta.source = { + format = "robloxmesh", + version = r.version, + lodType = r.lodType, + highQualityLods = r.highQualityLods, + lodOffsets = r.lods, + subsets = subsets, + facsFormat = r.facsFormat, + facs = r.facs, + chunks = r.chunks, + draco = r.coreVersion == 2 and true or nil, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function num(attr, i, c, default) +if not attr or c >= attr.components then + return default + end + return attr.values[i * attr.components + c + 1] +end + +-- area-weighted vertex normals +local function normals(pos, nv, corners) +local acc = table.create(nv * 3, 0) + for f = 0, math.floor(#corners / 3 )- 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in __iter({ a, b, c }) do +do local __DARKLUA_VAR=v * 3 + 1 acc[__DARKLUA_VAR]=acc[__DARKLUA_VAR]+ nx +end do local __DARKLUA_VAR0=v * 3 + 2 acc[__DARKLUA_VAR0]=acc[__DARKLUA_VAR0]+ ny +end do local __DARKLUA_VAR1=v * 3 + 3 acc[__DARKLUA_VAR1]=acc[__DARKLUA_VAR1]+ nz +end end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + writef32(out, v * 12, x / l) + writef32(out, v * 12 + 4, y / l) + writef32(out, v * 12 + 8, z / l) + else + writef32(out, v * 12 + 4, 1) + end + end + return out +end + +-- world matrices of every node (parents through children lists) +local function worlds(scene) +local out= {} + local parent= {} + for i, n in __iter(scene.nodes) do + for _, c in __iter(n.children or {}) do + parent[c] = i + end + end + local function world(i, depth) +if out[i] then + return out[i] + end + local m = Types.Scene.nodeMatrix(scene.nodes[i]) + local p = parent[i] + if p and depth < 256 then + m = Mat4.mul(world(p, depth + 1), m) + end + out[i] = m + return m + end + for i in __iter(scene.nodes) do + world(i, 0) + end + return out +end + +-- the bones of a skin: Parse.Bone list, or nil, message +local function skinBones(scene, skin) +local joints = skin.joints + if type(joints) ~= "table" or #joints == 0 then + return nil, "a skin without joints" + end + if #joints > 65534 then + return nil, "too many joints" + end + local w = worlds(scene) + local index= {} + for i, j in __iter(joints) do + index[j] = i - 1 + end + local parentOf= {} + for i, n in __iter(scene.nodes) do + for _, c in __iter(n.children or {}) do + parentOf[c] = i + end + end + local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices) + local out = {} + for i, j in __iter(joints) do + local node = scene.nodes[j] + if not node then + return nil, "a joint names a missing node" + end + local m = w[j] + if ibm and #ibm >= i * 16 then + local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0))) + if inv then + m = inv + end + end + local ex = (type(node.extras) == "table" and{node.extras }or{{} +})[1] local p = parentOf[j] + out[i] = { + name = (type(node.name) == "string" and{node.name }or{("Bone" .. i)})[1], + parent = (p and{index[p] }or{nil})[1], + lodParent = (type(ex.lodParent) == "number" and{ex.lodParent }or{0xFFFF})[1], + culling = (type(ex.culling) == "number" and{ex.culling }or{0})[1], + cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] }, + } + end + return out, nil +end + +-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index) +local function fill(r, m, order, nrm) + local nv = #order + local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4) + local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0 + local col = nil + if C then + local scale = C.raw and 1 or 255 + local white = true + col = buffer.create(nv * 4) + for i, src in __iter(order) do + for k = 0, 3 do + local v = math.clamp(math.floor(num(C, src, k, C.raw and 255 or 1) * scale + 0.5), 0, 255) + writeu8(col, (i - 1) * 4 + k, v) + if v ~= 255 then + white = false + end + end + end + if white then + col = nil + end + end + for i, src in __iter(order) do + local o = i - 1 + for k = 0, 2 do + writef32(pos, o * 12 + k * 4, num(P, src, k, 0)) + end + if N then + for k = 0, 2 do + writef32(nb, o * 12 + k * 4, num(N, src, k, 0)) + end + elseif nrm then + buffer.copy(nb, o * 12, nrm, src * 12, 12) + end + writef32(uv, o * 8, num(U, src, 0, 0)) + writef32(uv, o * 8 + 4, num(U, src, 1, 0)) + if T then + for k = 0, 3 do + local v = math.clamp(math.floor(num(T, src, k, k == 3 and 1 or 0) * 127 + 0.5), -127, 127) + writeu8(tan, o * 4 + k, v % 256) + end + else + buffer.writeu32(tan, o * 4, 0x7F810000) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv +end + +function RobloxMesh.encode(scene, opts) +local version = opts and opts.version or "2.00" + if version ~= "2.00" and version ~= "4.00" then + return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"") + end + if type(scene) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true } + local m, merr = Flatten.merge(scene, function(name) +return keep[name] == true + end, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local corners = m.corners + if not m.sizes or #corners == 0 then + return nil, Err.new(Err.ARG, "no triangles to write") + end + local nv0 = m.count + if nv0 > 2 ^ 32 - 1 then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local r= { + version = version, + numVerts = 0, + numFaces = math.floor(#corners / 3), + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + facsFormat = 0, + chunks = {}, + } + local src = (type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" and{scene.meta.source }or{nil +})[1] if src and type(src.lodType) == "number" then + r.lodType, r.highQualityLods = src.lodType, (type(src.highQualityLods) == "number" and{src.highQualityLods }or{0 +})[1] end + -- normals when the scene has none + local nrm= nil + if not m.attrs.NORMAL then + local pb = buffer.create(nv0 * 12) + for i = 0, nv0 - 1 do + for k = 0, 2 do + writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0)) + end + end + nrm = normals(pb, nv0, corners) + end + -- the skin (4.00): the first node with a mesh and a skin + local skin = nil + if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then + for _, n in __iter(scene.nodes or {}) do + if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then + skin = scene.skins[n.skin] + break + end + end + end + local nf = math.floor(#corners / 3 +) if skin then + local bones, berr = skinBones(scene, skin) + if not bones then + return nil, Err.new(Err.ARG, berr or "bad skin") + end + r.bones = bones + local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0 + local wscale = W.raw and 1 / 255 or 1 + local nb = #bones + -- per vertex: up to 4 (joint, weight) pairs with weight > 0 + local influences= (table.create(nv0) ) +for v = 0, nv0 - 1 do + local list = {} + for k = 0, 3 do + local wt = num(W, v, k, 0) * wscale + local j = num(J, v, k, 0) + if wt > 0 and j >= 0 and j < nb then + table.insert(list, { j, wt }) + end + end + influences[v + 1] = list + end + -- subsets: faces in order, a new subset when a face's joints do not fit in 26 + local faceIdx = buffer.create(nf * 12) + local order= {} + local s= nil + local function close() + if s then + table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones }) + end + end + local function open(f) + s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} } + end + open(0) + for f = 0, nf - 1 do + local need = {} + local extra = 0 + for c = 1, 3 do + for _, inf in __iter(influences[corners[f * 3 + c] + 1]) do + if s.local_[inf[1] ] == nil and not need[inf[1] ] then + need[inf[1] ] = true + extra =extra+ 1 + end + end + end + if #s.bones + extra > 26 then + close() + open(f) + for c = 1, 3 do + for _, inf in __iter(influences[corners[f * 3 + c] + 1]) do + need[inf[1] ] = true + end + end + end + for j in __iter(need) do + if s.local_[j] == nil then + table.insert(s.bones, j) + s.local_[j] = #s.bones - 1 + end + end + for c = 1, 3 do + local v = corners[f * 3 + c] + local nvx = s.remap[v] + if not nvx then + table.insert(order, v) + nvx = #order - 1 + s.remap[v] = nvx + end + buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx) + end + s.faceCount =s.faceCount+ 1 + end + close() + r.faces = faceIdx + fill(r, m, order, nrm) + -- envelopes: subset-local bone indices, weights summing to 255 + local env = buffer.create(#order * 8) + for _, sub in __iter(r.subsets) do + local loc= {} + for i, j in __iter(sub.bones) do + loc[j] = i - 1 + end + for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do + local list = influences[order[o + 1] + 1] + local total = 0 + for _, inf in __iter(list) do + total =total+ inf[2] + end + local bytes, sum, best = {}, 0, 1 + for k, inf in __iter(list) do + local b = (total > 0 and{(math.floor(inf[2] / total * 255 + 0.5) )}or{0 +})[1] bytes[k] = b + sum =sum+ b + if inf[2] > list[best][2] then + best = k + end + end + if #list > 0 then + bytes[best]=bytes[best]+ (255 - sum +) end + for k = 0, 3 do + local inf = list[k + 1] + writeu8(env, o * 8 + k, (inf and{loc[inf[1] ] or 0 }or{0})[1]) + writeu8(env, o * 8 + 4 + k, (inf and{(math.clamp(bytes[k + 1], 0, 255) )}or{0})[1]) + end + end + end + r.env = env + r.lods = { 0, nf } + else + local order = table.create(nv0, 0) + for i = 1, nv0 do + order[i] = i - 1 + end + fill(r, m, order, nrm) + local faces = buffer.create(nf * 12) + for i, c in __iter(corners) do + buffer.writeu32(faces, (i - 1) * 4, c) + end + r.faces = faces + r.lods = { 0, nf } + -- extra LODs of a single untransformed primitive + local part = m.parts[1] + local mesh = part and part.mesh + local lods = (#m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" and{mesh.extras.lods }or{nil +})[1] if version == "4.00" and type(lods) == "table" and #lods > 0 then + local list = {} + for _, lp in __iter(lods) do + local idx = (type(lp) == "table" and lp.indices and{(Flatten.numbers(lp.indices) )}or{nil +})[1] if idx and #idx % 3 == 0 then + table.insert(list, idx) + end + end + local total = nf + for _, idx in __iter(list) do + total =total+ math.floor(#idx / 3 +) end + local all = buffer.create(total * 12) + buffer.copy(all, 0, faces, 0, nf * 12) + local at = nf + for _, idx in __iter(list) do + for i, c in __iter(idx) do + if c >= nv0 then + return nil, Err.new(Err.ARG, "a LOD index is out of range") + end + buffer.writeu32(all, at * 12 + (i - 1) * 4, c) + end + at =at+ math.floor(#idx / 3 +) table.insert(r.lods, at) + end + r.faces, r.numFaces = all, total + end + end + return Write.write(r, version), nil +end + +return RobloxMesh +end +__FILES["model/robloxmesh/Parse"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version: +-- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the +-- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core +-- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data. +local Parse = {} + +local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring +local writef32, writeu32 = buffer.writef32, buffer.writeu32 +-- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record +-- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco) + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function record(version) +return { + version = version, + numVerts = 0, + numFaces = 0, + pos = buffer.create(0), + nrm = buffer.create(0), + uv = buffer.create(0), + tan = nil, + col = nil, + faces = buffer.create(0), + lods = {}, + lodType = 0, + highQualityLods = 0, + bones = {}, + subsets = {}, + env = nil, + facsFormat = 0, + facs = nil, + chunks = {}, + coreVersion = nil, + } +end + +-- ------------------------------------------------------------------------------------------------ version 1 +local function ascii(text, version, lim) +local nf = tonumber(string.match(text, "^[^\n]*\n%s*(%d+)")) + if not nf then + return nil, "corrupt: no face count" + end + if nf * 3 > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + local r = record(version) + local nv = nf * 3 + r.numVerts, r.numFaces = nv, nf + r.pos, r.nrm, r.uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + r.faces = buffer.create(nf * 12) + local scale = version == "1.00" and 0.5 or 1 + local i = 0 + local vals = table.create(9, 0) + local k = 0 + local start = string.find(text, "[", 1, true) or (#text + 1) + for a, b, c in __iter(string.gmatch(string.sub(text, start), "%[%s*([^,%]]+)%s*,%s*([^,%]]+)%s*,%s*([^,%]]+)%s*%]")) do + local x, y, z = tonumber(a), tonumber(b), tonumber(c) + if not x or not y or not z then + return nil, "corrupt: bad number in a vector" + end + vals[k * 3 + 1], vals[k * 3 + 2], vals[k * 3 + 3] = x, y, z + k =k+ 1 + if k == 3 then + if i >= nv then + break + end + writef32(r.pos, i * 12, vals[1] * scale) + writef32(r.pos, i * 12 + 4, vals[2] * scale) + writef32(r.pos, i * 12 + 8, vals[3] * scale) + writef32(r.nrm, i * 12, vals[4]) + writef32(r.nrm, i * 12 + 4, vals[5]) + writef32(r.nrm, i * 12 + 8, vals[6]) + writef32(r.uv, i * 8, vals[7]) + writef32(r.uv, i * 8 + 4, 1 - vals[8]) -- version 1 stores V upside down + i =i+ 1 + k = 0 + end + end + if i < nv then + return nil, "truncated: " .. i .. " of " .. nv .. " vertices" + end + for f = 0, nv - 1 do + writeu32(r.faces, f * 4, f) + end + r.lods = { 0, nf } + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ binary parts +-- vertices of size vs (36 / 40) at p +local function vertices(b, p, n, vs, r) + local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4) + local col = (vs >= 40 and{(buffer.create(n * 4) )}or{nil +})[1] for i = 0, n - 1 do + local q = p + i * vs + buffer.copy(pos, i * 12, b, q, 12) + buffer.copy(nrm, i * 12, b, q + 12, 12) + buffer.copy(uv, i * 8, b, q + 24, 8) + buffer.copy(tan, i * 4, b, q + 32, 4) + if col then + buffer.copy(col, i * 4, b, q + 36, 4) + end + end + r.pos, r.nrm, r.uv, r.tan, r.col = pos, nrm, uv, tan, col + r.numVerts = n +end + +local function faces(b, p, n, fs, r) +local out = buffer.create(n * 12) + local nv = r.numVerts + for i = 0, n - 1 do + for k = 0, 2 do + local v = readu32(b, p + i * fs + k * 4) + if v >= nv then + return "corrupt: face " .. i .. " uses vertex " .. v .. " of " .. nv + end + writeu32(out, i * 12 + k * 4, v) + end + end + r.faces, r.numFaces = out, n + return nil +end + +local function bones(b, p, n, names, r) + for i = 0, n - 1 do + local q = p + i * 60 + local ni = readu32(b, q) + local name = string.match(string.sub(names, ni + 1), "^[^%z]*") or "" + local parent = readu16(b, q + 4) + local cf = table.create(12, 0) + for k = 0, 11 do + cf[k + 1] = readf32(b, q + 12 + 4 * k) + end + r.bones[i + 1] = { name = name, parent = (parent == 0xFFFF and{nil }or{parent})[1], lodParent = readu16(b, q + 6), culling = readf32(b, q + 8), cf = cf } + end +end + +local function subsets(b, p, n, r) + for i = 0, n - 1 do + local q = p + i * 72 + local count = math.min(readu32(b, q + 16), 26) + local list = table.create(count, 0) + for k = 0, count - 1 do + list[k + 1] = readu16(b, q + 20 + 2 * k) + end + r.subsets[i + 1] = { facesBegin = readu32(b, q), facesLength = readu32(b, q + 4), vertsBegin = readu32(b, q + 8), vertsLength = readu32(b, q + 12), bones = list } + end +end + +local function lods(b, p, n, r) + local out = table.create(n, 0) + for i = 0, n - 1 do + out[i + 1] = readu32(b, p + 4 * i) + end + r.lods = out +end + +-- ------------------------------------------------------------------------------------------------ versions 2 .. 5 +local function classic(b, p, e, version, lim) +local r = record(version) + local major = tonumber(string.sub(version, 1, 1)) or 0 + if p + 12 > e then + return nil, "truncated header" + end + local hs = readu16(b, p) + local nv, nf, vs, fs= 0, 0, 40, 12 + local nlod, nbones, namesSize, nsub= 0, 0, 0, 0 + if major == 2 or major == 3 then + vs = readu8(b, p + 2) + fs = readu8(b, p + 3) + if major == 2 then + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + else + if p + 16 > e then + return nil, "truncated header" + end + nlod = readu16(b, p + 6) + nv = readu32(b, p + 8) + nf = readu32(b, p + 12) + end + else + if p + 24 > e then + return nil, "truncated header" + end + r.lodType = readu16(b, p + 2) + nv = readu32(b, p + 4) + nf = readu32(b, p + 8) + nlod = readu16(b, p + 12) + nbones = readu16(b, p + 14) + namesSize = readu32(b, p + 16) + nsub = readu16(b, p + 20) + r.highQualityLods = readu8(b, p + 22) + if major >= 5 then + if p + 32 > e then + return nil, "truncated header" + end + r.facsFormat = readu32(b, p + 24) + end + end + if vs < 36 or fs < 12 then + return nil, "corrupt: vertex size " .. vs .. ", face size " .. fs + end + if nv > lim.maxVertices or nf > lim.maxFaces then + return nil, "limit: " .. nv .. " vertices, " .. nf .. " faces" + end + local q = p + hs + if q + nv * vs > e then + return nil, "truncated vertices" + end + vertices(b, q, nv, vs, r) + q =q+ nv * vs + if nbones > 0 then + if q + nv * 8 > e then + return nil, "truncated skinning" + end + local env = buffer.create(nv * 8) + buffer.copy(env, 0, b, q, nv * 8) + r.env = env + q =q+ nv * 8 + end + if q + nf * fs > e then + return nil, "truncated faces" + end + local ferr = faces(b, q, nf, fs, r) + if ferr then + return nil, ferr + end + q =q+ nf * fs + if q + nlod * 4 > e then + return nil, "truncated LOD offsets" + end + lods(b, q, nlod, r) + q =q+ nlod * 4 + if q + nbones * 60 + namesSize + nsub * 72 > e then + return nil, "truncated bones / subsets" + end + local names = readstring(b, q + nbones * 60, namesSize) + bones(b, q, nbones, names, r) + q =q+ (nbones * 60 + namesSize +) subsets(b, q, nsub, r) + q =q+ nsub * 72 + if major >= 5 then + local size = readu32(b, p + 28) + if size > 0 then + if q + size > e then + return nil, "truncated FACS data" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q, size) + r.facs = facs + end + end + if #r.lods == 0 then + r.lods = { 0, nf } + end + return r, nil +end + +-- ------------------------------------------------------------------------------------------------ versions 6 / 7 +local function chunked(b, p, e, version, lim) +local r = record(version) + local core = false + while p < e do + if p + 16 > e then + return nil, "truncated chunk header" + end + local name = string.gsub(readstring(b, p, 8), "%z+$", "") + local cv, size = readu32(b, p + 8), readu32(b, p + 12) + local q = p + 16 + local ce = q + size + if ce > e then + return nil, "truncated chunk " .. name + end + if name == "COREMESH" then + if cv == 2 then + local decodeCore = lim.core + if not decodeCore then + return nil, "unsupported: Draco-compressed COREMESH" + end + local c, cerr = decodeCore(b, q, size) + if not c then + return nil, cerr or "corrupt: bad Draco COREMESH" + end + if c.numVerts > lim.maxVertices or c.numFaces > lim.maxFaces then + return nil, "limit: " .. c.numVerts .. " vertices, " .. c.numFaces .. " faces" + end + r.numVerts, r.pos, r.nrm, r.uv, r.tan, r.col = c.numVerts, c.pos, c.nrm, c.uv, c.tan, c.col + r.numFaces, r.faces = c.numFaces, c.faces + core = true + r.coreVersion = 2 + elseif cv ~= 1 then + return nil, "unsupported: COREMESH version " .. cv + else + if q + 4 > ce then + return nil, "truncated COREMESH" + end + local nv = readu32(b, q) + if nv > lim.maxVertices then + return nil, "limit: " .. nv .. " vertices" + end + if q + 4 + nv * 40 + 4 > ce then + return nil, "truncated COREMESH vertices" + end + vertices(b, q + 4, nv, 40, r) + local fq = q + 4 + nv * 40 + local nf = readu32(b, fq) + if nf > lim.maxFaces then + return nil, "limit: " .. nf .. " faces" + end + if fq + 4 + nf * 12 > ce then + return nil, "truncated COREMESH faces" + end + local ferr = faces(b, fq + 4, nf, 12, r) + if ferr then + return nil, ferr + end + core = true + end + elseif name == "LODS" and cv == 1 then + if q + 7 > ce then + return nil, "truncated LODS" + end + r.lodType = readu16(b, q) + r.highQualityLods = readu8(b, q + 2) + local n = readu32(b, q + 3) + if q + 7 + n * 4 > ce then + return nil, "truncated LODS" + end + lods(b, q + 7, n, r) + elseif name == "SKINNING" and cv == 1 then + if not core then + return nil, "corrupt: SKINNING before COREMESH" + end + if q + 4 > ce then + return nil, "truncated SKINNING" + end + local ns = readu32(b, q) + local s = q + 4 + if ns ~= r.numVerts or s + ns * 8 + 4 > ce then + return nil, "corrupt: SKINNING count" + end + local env = buffer.create(ns * 8) + buffer.copy(env, 0, b, s, ns * 8) + r.env = env + s =s+ ns * 8 + local nb = readu32(b, s) + s =s+ 4 + if s + nb * 60 + 4 > ce then + return nil, "truncated SKINNING bones" + end + local bq = s + s =s+ nb * 60 + local namesSize = readu32(b, s) + s =s+ 4 + if s + namesSize + 4 > ce then + return nil, "truncated SKINNING names" + end + bones(b, bq, nb, readstring(b, s, namesSize), r) + s =s+ namesSize + local nsub = readu32(b, s) + s =s+ 4 + if s + nsub * 72 > ce then + return nil, "truncated SKINNING subsets" + end + subsets(b, s, nsub, r) + if nb == 0 then + r.env = nil + end + elseif name == "FACS" and cv == 1 then + if q + 4 > ce then + return nil, "truncated FACS" + end + local size = readu32(b, q) + if q + 4 + size > ce then + return nil, "truncated FACS" + end + local facs = buffer.create(size) + buffer.copy(facs, 0, b, q + 4, size) + r.facs, r.facsFormat = facs, 1 + else + local data = buffer.create(size) + buffer.copy(data, 0, b, q, size) + table.insert(r.chunks, { name = name, version = cv, data = data }) + end + p = ce + end + if not core then + return nil, "corrupt: no COREMESH chunk" + end + if #r.lods == 0 then + r.lods = { 0, r.numFaces } + end + return r, nil +end + +-- parse(b, p, e, lim) -> Record | nil, message +function Parse.parse(b, p, e, lim) +if e - p < 13 then + return nil, "truncated: no version line" + end + local line = readstring(b, p, 12) + local version = string.match(line, "^version (%d%.%d%d)$") + if not version or readu8(b, p + 12) ~= 10 and readu8(b, p + 12) ~= 13 then + return nil, "corrupt: bad version line" + end + local q = p + 13 + if readu8(b, p + 12) == 13 and q < e and readu8(b, q) == 10 then + q =q+ 1 + end + local major = string.sub(version, 1, 1) + if major == "1" then + return ascii(readstring(b, p, e - p), version, lim) + elseif major == "2" or major == "3" or major == "4" or major == "5" then + return classic(b, q, e, version, lim) + elseif major == "6" or major == "7" then + return chunked(b, q, e, version, lim) + end + return nil, "unsupported: version " .. version +end + +-- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127) +local function snorm(v) +local x = (v >= 128 and((v - 256 ))or(v +)) return math.clamp(x / 127, -1, 1) +end +function Parse.tangent(tan, i) +return snorm(readu8(tan, i * 4)), snorm(readu8(tan, i * 4 + 1)), snorm(readu8(tan, i * 4 + 2)), snorm(readu8(tan, i * 4 + 3)) +end + +return Parse +end +__FILES["model/robloxmesh/Write"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00: +-- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning +-- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws. +local Parse = __include("model/robloxmesh/Parse") +local Bytes = __include("core/Bytes") + +local Write = {} + +local function vertex(w, r, i, colors) + local p = w:reserve(colors and 40 or 36) + local b = w.buf + buffer.copy(b, p, r.pos, i * 12, 12) + buffer.copy(b, p + 12, r.nrm, i * 12, 12) + buffer.copy(b, p + 24, r.uv, i * 8, 8) + if r.tan then + buffer.copy(b, p + 32, r.tan, i * 4, 4) + else + buffer.writeu32(b, p + 32, 0x7F810000) -- (0, 0, -1, 1) + end + if colors then + if r.col then + buffer.copy(b, p + 36, r.col, i * 4, 4) + else + buffer.writeu32(b, p + 36, 0xFFFFFFFF) + end + end + w.pos = p + (colors and 40 or 36) +end + +-- write(r, version) -> buffer ("2.00" | "4.00") +function Write.write(r, version) +local nv, nf = r.numVerts, r.numFaces + local w = Bytes.writer(64 + nv * 48 + nf * 12) + w:string("version " .. version .. "\n") + if version == "2.00" then + local colors = r.col ~= nil + w:u16le(12) + w:u8(colors and 40 or 36) + w:u8(12) + w:u32le(nv) + w:u32le(nf) + for i = 0, nv - 1 do + vertex(w, r, i, colors) + end + w:bytes(r.faces, 0, nf * 12) + return w:finish() + end + -- 4.00 + local names = {} + local nameAt = {} + local size = 0 + for i, bone in __iter(r.bones) do + nameAt[i] = size + table.insert(names, bone.name .. "\0") + size =size+ (#bone.name + 1 +) end + local nb = #r.bones + w:u16le(24) + w:u16le(r.lodType) + w:u32le(nv) + w:u32le(nf) + w:u16le(#r.lods) + w:u16le(nb) + w:u32le(size) + w:u16le(#r.subsets) + w:u8(r.highQualityLods) + w:u8(0) + for i = 0, nv - 1 do + vertex(w, r, i, true) + end + if nb > 0 then + local env = r.env + if env then + w:bytes(env, 0, nv * 8) + else + w:fill(0, nv * 8) + end + end + w:bytes(r.faces, 0, nf * 12) + for _, o in __iter(r.lods) do + w:u32le(o) + end + for i, bone in __iter(r.bones) do + w:u32le(nameAt[i]) + w:u16le((bone.parent and{bone.parent }or{0xFFFF})[1]) + w:u16le(bone.lodParent) + w:f32le(bone.culling) + for k = 1, 12 do + w:f32le(bone.cf[k] or 0) + end + end + w:string(table.concat(names)) + for _, s in __iter(r.subsets) do + w:u32le(s.facesBegin) + w:u32le(s.facesLength) + w:u32le(s.vertsBegin) + w:u32le(s.vertsLength) + w:u32le(#s.bones) + for k = 1, 26 do + w:u16le(s.bones[k] or 0xFFFF) + end + end + return w:finish() +end + +return Write +end +__FILES["model/schematic"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: +-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and +-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, +-- Sponge, Litematic. +-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic +-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as +-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = +-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the +-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). +-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) +-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, +-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the +-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. +-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with +-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") +local Mcedit = __include("model/schematic/Mcedit") +local Sponge = __include("model/schematic/Sponge") +local Litematic = __include("model/schematic/Litematic") + +-- ------------------------------------------------------------------------------------------------ contract +local Schematic = { + name = "schematic", + category = "model", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + +local DEFAULT_DATA_VERSION = 3953 +local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } +local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed) + +local function hinted(head, hints) +for _, h in __iter(hints) do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return true + end + end + return false +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Schematic.sniff(r) +local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" or p.endian ~= "big" then + return 0 + end + if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then + return 1 + end + local head = buffer.tostring(p.head) + return (hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) )and 1 or 0 +end + +-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) +function Schematic.variant(r) +local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p then + return nil + end + if p.firstName == "Schematic" then + return "schem" + end + local head = buffer.tostring(p.head) + if hinted(head, LITEMATIC_HINTS) then + return "litematic" + elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then + return "schem" + end + return p.name == "Schematic" and"schematic" or nil +end + +-- ------------------------------------------------------------------------------------------------ decode +-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil +local function variantOf(root) +if type(root) ~= "table" or not Types.isObject(root) then + return nil, nil + end + if Types.isObject(root.Regions) then + return "litematic", root + end + if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then + return "schem", root.Schematic + end + if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then + return "schem", root + end + if type(root.Blocks) == "buffer" then + return "schematic", root + end + return nil, nil +end + +function Schematic.decode(r, opts) +local o= opts or {} + local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base) + if root == nil then + return nil, info + end + local variant, s = variantOf(root) + if not variant then + return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)") + end + local maxCells = o.maxCells or 2 ^ 26 + local regions, extra + if variant == "litematic" then + regions, extra = Litematic.read(s, maxCells) + elseif variant == "schem" then + regions, extra = Sponge.read(s, maxCells) + else + regions, extra = Mcedit.read(s, maxCells) + end + if not regions then + local msg = tostring(extra) + return nil, Err.from(msg, nil, string.find(msg, "limit: ", 1, true) and"limit" or nil) + end + local scene = Types.Scene.new() + scene.voxels = {} + for i, reg in __iter(regions) do + local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices) + v.name = reg.name + local b = v.blocks +b.blockEntities = reg.blockEntities + b.entities = reg.entities + table.insert(scene.voxels , v) + table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.unit = 1 + local src= { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression } + for k, v in __iter(extra) do + src[k] = v + end + scene.meta.source = src +return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function regionsOf(value) +local out= {} + local function add(v, pos, name) +if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local states, indices = Mc.blocksOf(v) + if not states then + return indices + end + local b = v.blocks + table.insert(out, { + name = name or v.name, + size = { v.size[1], v.size[2], v.size[3] }, + position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) }, + states = states, + indices = indices, + blockEntities = (b and b.blockEntities and{b.blockEntities }or{{}})[1], + entities = (b and b.entities and{b.entities }or{{}})[1], + }) + return nil + end + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, { 0, 0, 0 }, nil) + return (e and{nil }or{out})[1], e + end + if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then + return nil, "expected a Scene with voxels or a Types.Voxels" + end + local placed = false + local function walk(i, base, depth) +local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + placed = true + local e = add(value.voxels[node.voxels], p, node.name) + if e then + return e + end + end + for _, c in __iter(node.children or {}) do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in __iter(value.roots or {}) do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, e + end + end + if not placed then + for _, v in __iter(value.voxels) do + local e = add(v, { 0, 0, 0 }, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- merge(regions) -> one region covering them all (air where none is) +local function merge(regions) +if #regions == 1 then + return regions[1] + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, r in __iter(regions) do + for k = 1, 3 do + lo[k] = math.min(lo[k], r.position[k]) + hi[k] = math.max(hi[k], r.position[k] + r.size[k]) + end + end + local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] + local states = { "minecraft:air" } + local out = buffer.create(sx * sy * sz * 2) + local bes, ents = {}, {} + for _, r in __iter(regions) do + local base = #states + for _, st in __iter(r.states) do + table.insert(states, st) + end + local rx, ry, rz = r.size[1], r.size[2], r.size[3] + local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3] + for z = 0, rz - 1 do + for y = 0, ry - 1 do + local s = (rx * (y + ry * z)) * 2 + local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2 + for _ = 0, rx - 1 do + buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base) + s =s+ 2 + d =d+ 2 + end + end + end + for _, be in __iter(r.blockEntities) do + table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data }) + end + for _, e in __iter(r.entities) do + table.insert(ents, e) + end + end + local st, idx = Common.dedupe(states, out, sx * sy * sz) + return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents } +end + +function Schematic.encode(value, opts) +local o= opts or {} + local regions, rerr = regionsOf(value) + if not regions then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + local src = (type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" and{value.meta.source }or{nil +})[1] local ext = (o.name and{(string.lower(string.match(o.name, "%.([%w]+)$") or "") )}or{nil +})[1] local key = o.format and string.lower(o.format) + local variant = o.variant + or (((ext == "schem" or ext == "schematic" or ext == "litematic" )and{ext }or{nil})[1]) + or (((key == "schem" or key == "litematic" )and{key }or{nil})[1]) + or (src and src.variant) + or "schem" + if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local same = src ~= nil and src.variant == variant + local base = (same and{(src ).nbt }or{nil +})[1] local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION + local root, rootName, e + if variant == "litematic" then + local version = o.version or ((same and{(src ).version }or{nil})[1]) or 6 + local title = o.title or ((o.name and{(string.match(o.name, "([^/\\]-)%.[%w]+$") )}or{nil})[1]) + root, e = Litematic.write(regions, version, dataVersion, base, title) + rootName = "" + elseif variant == "schem" then + local version = o.version or ((same and{(src ).version }or{nil})[1]) or 3 + if version ~= 1 and version ~= 2 and version ~= 3 then + return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3") + end + local sameVersion = same and (src ).version == version + local inner = (sameVersion and base and{((version >= 3 and{base.Schematic }or{base})[1]) }or{nil +})[1] local sch + sch, e = Sponge.write(merge(regions), version, dataVersion, inner) + if sch and version >= 3 then + root, rootName = Common.merge((sameVersion and{base }or{nil})[1], { { "Schematic", sch } }), "" + else + root, rootName = sch, "Schematic" + end + else + root, e = Mcedit.write(merge(regions), base) + rootName = "Schematic" + end + if not root then + return nil, Err.new(Err.ARG, tostring(e)) + end + if same and (src ).rootName ~= nil then + rootName = (src ).rootName + end + return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level }) +end + +return Schematic +end +__FILES["model/schematic/Common"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, +-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, +-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") + +local Common = {} +-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil + + + + + + + + + + + +Common.int = Mc.int + +-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells +function Common.dims(a, b, c, max) +local x, y, z = Common.int(a), Common.int(b), Common.int(c) + if not x or not y or not z then + return nil, "missing or non-integer size", nil + end + if x < 0 or y < 0 or z < 0 then + return nil, "negative size", nil + end + if x * y * z > max then + return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil + end + return x, y, z +end + +-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil +Common.ints = Mc.ints + +-- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) +Common.blockEntity = Mc.blockEntity +Common.flatBlockEntity = Mc.flatBlockEntity + +-- list(v) -> v when it is an NBT list (array), else an empty list +function Common.list(v) +if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then + return v + end + return {} +end + +-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) +function Common.compound(fields) +local o, keys = {}, {} + for _, kv in __iter(fields) do + if kv[2] ~= nil then + o[kv[1] ] = kv[2] + table.insert(keys, kv[1]) + end + end + return Types.object(o, keys) +end + +-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key +-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after +function Common.merge(base, fields, drop) +if type(base) ~= "table" or not Types.isObject(base) then + return Common.compound(fields) + end + local mine= {} + local present= {} + for _, kv in __iter(fields) do + present[kv[1] ] = true + mine[kv[1] ] = kv[2] + end + local out = {} + for _, k in __iter(Types.keys(base)) do + if present[k] then + if mine[k] ~= nil then + table.insert(out, { k, mine[k] }) + end + elseif not (drop and drop[k]) then + table.insert(out, { k, base[k] }) + end + end + local seen= {} + for _, kv in __iter(out) do + seen[kv[1] ] = true + end + for _, kv in __iter(fields) do + if not seen[kv[1] ] and kv[2] ~= nil then + table.insert(out, kv) + end + end + return Common.compound(out) +end + +-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) +function Common.dedupe(states, indices, n) +local first= {} + local remap= {} + local out= {} + local dup = false + for i, s in __iter(states) do + local at = first[s] + if at == nil then + table.insert(out, s) + at = #out - 1 + first[s] = at + else + dup = true + end + remap[i] = at + end + if not dup then + return states, indices + end + local res = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0) + end + return out, res +end + +return Common +end +__FILES["model/schematic/Litematic"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, +-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, +-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state +-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative +-- to the region's minimum corner), Entities and pending ticks (kept as they are). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Litematic = {} + +local Packed = Mc.Packed + +local function xyz(c) +if type(c) ~= "table" then + return nil + end + local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z) + if not x or not y or not z then + return nil + end + return { x, y, z } +end + +local function vec(v) +return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) +end + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Litematic.read(root, maxCells) +if not Types.isObject(root.Regions) then + return nil, "no Regions" + end + local out= {} + local total = 0 + local raw= {} + for _, name in __iter(Types.keys(root.Regions)) do + local reg = root.Regions[name] + if type(reg) ~= "table" then + return nil, "region " .. name .. " is not a compound" + end + local pos, size = xyz(reg.Position), xyz(reg.Size) + if not pos or not size then + return nil, "region " .. name .. ": no Position / Size" + end + local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3]) + local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total) + if not sx then + return nil, "region " .. name .. ": " .. tostring(sy) + end + total =total+ ax * ay * az + local states= {} + for i, c in __iter(Common.list(reg.BlockStatePalette)) do + local st = Mc.stateFromNbt(c) + if not st then + return nil, "region " .. name .. ": bad palette entry " .. i + end + states[i] = st + end + if #states == 0 then + states[1] = "minecraft:air" + end + local n = ax * ay * az + local yzx = buffer.create(n * 2) + local bs = reg.BlockStates + if n > 0 then + if not (Nbt.isTag(bs) and bs.type == "longArray") then + return nil, "region " .. name .. ": no BlockStates" + end + local bits = Packed.bitsFor(#states, 2) + local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states) + if not ok then + return nil, "region " .. name .. ": " .. tostring(e) + end + end + local bes = {} + for _, c in __iter(Common.list(reg.TileEntities)) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + table.insert(out, { + name = name, + size = { ax, ay, az }, + position = { + pos[1] + ((size[1] < 0 and((size[1] + 1 ))or(0))), + pos[2] + ((size[2] < 0 and((size[2] + 1 ))or(0))), + pos[3] + ((size[3] < 0 and((size[3] + 1 ))or(0))), + }, + states = states, + indices = Packed.fromYzx(yzx, ax, ay, az), + blockEntities = bes, + entities = Common.list(reg.Entities), + }) + raw[name] = reg + end + return out, { + version = Common.int(root.Version), + subVersion = Common.int(root.SubVersion), + dataVersion = Common.int(root.MinecraftDataVersion), + metadata = root.Metadata, + regions = raw, + } +end + +-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root +-- (Metadata fields and each region's Position / Size signs and pending ticks are kept) +function Litematic.write(regions, version, dataVersion, base, title) +local baseRegions = (type(base) == "table" and Types.isObject(base.Regions) and{base.Regions }or{nil +})[1] local regs, order = {}, {} + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local blocks, volume = 0, 0 + for i, r in __iter(regions) do + local name = r.name or ("Region" .. (i == 1 and"" or tostring(i))) + while regs[name] ~= nil do + name =name.. "_" + end + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + if states[1] ~= "minecraft:air" then + -- Litematica keeps air at index 0 + local at = table.find(states, "minecraft:air") + local shifted = buffer.create(n * 2) + local nst = table.clone(states) + if at then + nst[1], nst[at] = states[at], states[1] + else + table.insert(nst, 1, "minecraft:air") + end + for c = 0, n - 1 do + local v = buffer.readu16(indices, c * 2) + local w = (at and{((v == 0 and((at - 1 ))or(v == at - 1 and 0 or v))) }or{(v + 1 +)})[1] buffer.writeu16(shifted, c * 2, w) + end + states, indices = nst, shifted + end + local palette = Nbt.list("compound") + for k, st in __iter(states) do + palette[k] = Mc.stateToNbt(st) + end + local airLike= {} + for k, st in __iter(states) do + airLike[k - 1] = Mc.isAir(st) + end + for c = 0, n - 1 do + if not airLike[buffer.readu16(indices, c * 2)] then + blocks =blocks+ 1 + end + end + volume =volume+ n + local bits = Packed.bitsFor(#states, 2) + local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true) + local tiles = Nbt.list("compound") + for _, be in __iter(r.blockEntities) do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local p = r.position + local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz } + local b = (baseRegions and{baseRegions[name] }or{nil +})[1] local bsize = (type(b) == "table" and{(xyz(b.Size) )}or{nil +})[1] if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then + -- keep the source's corner and signs + for k = 1, 3 do + if bsize[k] < 0 then + size[k] = bsize[k] + pos[k] = p[k] - bsize[k] - 1 + end + end + end + for k = 1, 3 do + lo[k] = math.min(lo[k], p[k]) + hi[k] = math.max(hi[k], p[k] + r.size[k]) + end + regs[name] = Common.merge(b, { + { "BlockStatePalette", palette }, + { "BlockStates", Nbt.longArray(longs) }, + { "Entities", (#r.entities > 0 and{r.entities }or{(Nbt.list("compound") )})[1]}, + { "PendingBlockTicks", (type(b) == "table" and{b.PendingBlockTicks }or{(Nbt.list("compound") )})[1]}, + { "PendingFluidTicks", (type(b) == "table" and{b.PendingFluidTicks }or{(Nbt.list("compound") )})[1]}, + { "Position", vec(pos) }, + { "Size", vec(size) }, + { "TileEntities", tiles }, + }) + table.insert(order, name) + end + if #order == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local bm = (type(base) == "table" and type(base.Metadata) == "table" and{base.Metadata }or{nil +})[1] local metadata = Common.merge(bm, { + { "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }, + { "Author", (bm and bm.Author and{bm.Author }or{"" })[1]}, + { "Description", (bm and bm.Description and{bm.Description }or{"" })[1]}, + { "Name", title or ((bm and bm.Name and{bm.Name }or{"Unnamed"})[1]) }, + { "RegionCount", #order }, + { "TimeCreated", (bm and bm.TimeCreated and{bm.TimeCreated }or{(Nbt.long(0) )})[1]}, + { "TimeModified", (bm and bm.TimeModified and{bm.TimeModified }or{(Nbt.long(0) )})[1]}, + { "TotalBlocks", blocks }, + { "TotalVolume", volume }, + }) + local regions_ = Types.object(regs, order) + return Common.merge(base, { + { "MinecraftDataVersion", dataVersion }, + { "Version", version }, + { "SubVersion", (type(base) == "table" and base.SubVersion ~= nil and{base.SubVersion }or{version >= 6 and 1 or nil })[1]}, + { "Metadata", metadata }, + { "Regions", regions_ }, + }), nil +end + +return Litematic +end +__FILES["model/schematic/Mcedit"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki +-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high +-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name +-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft +-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block +-- nearest in colour). +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Mcedit = {} + +local Packed = Mc.Packed + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Mcedit.read(root, maxCells) +local blocks = root.Blocks + if type(blocks) ~= "buffer" then + return nil, "no Blocks byte array" + end + local function u16(v) +local n = Common.int(v) + return (n and n < 0 and((n + 65536 ))or(n +)) end + local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells) + if not sx then + return nil, sy + end + local n = sx * sy * (sz ) + if buffer.len(blocks) < n then + return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells" + end + local data = (type(root.Data) == "buffer" and buffer.len(root.Data) >= n and{root.Data }or{nil +})[1] local add = (type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= math.floor((n + 1) / 2 )and{root.AddBlocks }or{nil +})[1] -- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name) + local names= {} + if Types.isObject(root.SchematicaMapping) then + for _, k in __iter(Types.keys(root.SchematicaMapping)) do + local id = Common.int(root.SchematicaMapping[k]) + if id then + names[id] = k + end + end + end + if Types.isObject(root.BlockIDs) then + for _, k in __iter(Types.keys(root.BlockIDs)) do + local id = tonumber(k) + if id and type(root.BlockIDs[k]) == "string" then + names[id] = root.BlockIDs[k] + end + end + end + local function state(id, d) +local name = names[id] + if name then + local base = string.match(name, "^minecraft:(.*)$") or ((string.find(name, ":", 1, true) and{nil }or{name})[1]) + if base then + local std = table.find(Mc.Legacy.NAMES, base) + if std then + return Mc.legacyState(std - 1, d) + end + end + return Mc.stateString((string.find(name, ":", 1, true) and{name }or{("minecraft:" .. name)})[1], d ~= 0 and{ { "data", tostring(d) } } or nil) + end + return Mc.legacyState(id, d) + end + local slots= {} + local states= {} + local yzx = buffer.create(n * 2) + for i = 0, n - 1 do + local id = buffer.readu8(blocks, i) + if add then + id =id+ Packed.nibble(add, 0, i, true) * 256 + end + local d = (data and{(buffer.readu8(data, i) % 16 )}or{0 +})[1] local key = id * 16 + d + local s = slots[key] + if not s then + table.insert(states, state(id, d)) + s = #states - 1 + slots[key] = s + end + buffer.writeu16(yzx, i * 2, s ) + end + local bes = {} + for _, c in __iter(Common.list(root.TileEntities)) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + local regions= { + { + name = nil, + size = { sx, sy , sz }, + position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy , sz ), + blockEntities = bes, + entities = Common.list(root.Entities), + }, + } + return regions, { materials = root.Materials } +end + +-- the legacy blocks a colour can become (full blocks of distinct colours) +local CANDIDATES= nil +local function candidates() +if CANDIDATES then + return CANDIDATES + end + local out = {} + local function add(id, d) + local c = Mc.color(Mc.legacyState(id, d)) + if c then + table.insert(out, { id, d, c }) + end + end + for d = 0, 15 do + add(35, d) -- wool + add(159, d) -- stained clay + add(251, d) -- concrete + end + for d = 0, 5 do + add(5, d) -- planks + end + for _, id in __iter({ 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 }) do + add(id, 0) + end + CANDIDATES = out + return out +end + +local function nearest(state) +local c = Mc.color(state) + if not c then + return 0, 0 + end + if c[4] < 200 then + return 20, 0 -- glass + end + local bid, bd, best = 1, 0, math.huge + for _, k in __iter(candidates()) do + local kc = k[3] + local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2 + if dist < best then + bid, bd, best = k[1], k[2], dist + end + end + return bid, bd +end + +-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other +-- fields are kept +function Mcedit.write(r, base) +local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a .schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list + local map= {} + if type(base) == "table" then + if Types.isObject(base.SchematicaMapping) then + for _, k in __iter(Types.keys(base.SchematicaMapping)) do + local id = Common.int(base.SchematicaMapping[k]) + if id then + map[k] = id + end + end + end + if Types.isObject(base.BlockIDs) then + for _, k in __iter(Types.keys(base.BlockIDs)) do + local id = tonumber(k) + if id and type(base.BlockIDs[k]) == "string" then + map[base.BlockIDs[k] ] = id + end + end + end + end + local ids, datas = (table.create(#r.states) ), (table.create(#r.states) ) +local high = false + for i, s in __iter(r.states) do + local id, d = Mc.legacyId(s) + if id ~= nil then + local lname = Mc.Legacy.NAMES[id + 1] + local mapped = lname and map["minecraft:" .. lname] + if mapped then + id = mapped + end + else + local name, props = Mc.parseState(s) + if map[name] then + id, d = map[name], 0 + for _, kv in __iter(props) do + if kv[1] == "data" then + d = (tonumber(kv[2]) or 0) % 16 + end + end + else + id, d = nearest(s) + end + end + ids[i], datas[i] = id , d +if (id ) > 255 then + high = true + end + end + local yzx = Packed.toYzx(r.indices, sx, sy, sz) + local blocks, data = buffer.create(n), buffer.create(n) + local add = (high and{(buffer.create(math.floor((n + 1) / 2)) )}or{nil +})[1] for i = 0, n - 1 do + local s = buffer.readu16(yzx, i * 2) + 1 + local id = ids[s] or 0 + buffer.writeu8(blocks, i, id % 256) + buffer.writeu8(data, i, datas[s] or 0) + if add then + Packed.setNibble(add, 0, i, math.floor(id / 256), true) + end + end + local tiles = Nbt.list("compound") + for _, be in __iter(r.blockEntities) do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local ents = (#r.entities > 0 and{r.entities }or{(Nbt.list("compound") +)})[1] local fields= { + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Materials", "Alpha" }, + { "Blocks", blocks }, + { "Data", data }, + { "AddBlocks", add }, + { "Entities", ents }, + { "TileEntities", tiles }, + } + local p = r.position + if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then + table.insert(fields, { "WEOffsetX", p[1] }) + table.insert(fields, { "WEOffsetY", p[2] }) + table.insert(fields, { "WEOffsetZ", p[3] }) + end + local root = Common.merge(base, fields, { Add = true }) + return root, nil +end + +return Mcedit +end +__FILES["model/schematic/Sponge"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the +-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the +-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / +-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +local Types = __include("Types") +local Nbt = __include("codecs/text/Nbt") +local Mc = __include("codecs/model/Minecraft") +local Common = __include("model/schematic/Common") + +local Sponge = {} + +local Packed = Mc.Packed + +-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) +function Sponge.read(s, maxCells) +local version = Common.int(s.Version) or 1 + local function u16(v) +local n = Common.int(v) + return (n and n < 0 and((n + 65536 ))or(n +)) end + local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells) + if not sx then + return nil, sy + end + local container = (version >= 3 and{s.Blocks }or{s +})[1] if version >= 3 and type(container) ~= "table" then + return nil, "no Blocks container" + end + local palette = (version >= 3 and{container.Palette }or{s.Palette +})[1] local data = (version >= 3 and{container.Data }or{s.BlockData +})[1] if not Types.isObject(palette) then + return nil, "no block palette" + end + if type(data) ~= "buffer" then + return nil, "no block data" + end + local states= {} + local max = -1 + for _, k in __iter(Types.keys(palette)) do + local i = Common.int(palette[k]) + if i == nil or i < 0 or i > 65535 then + return nil, "bad palette index for " .. k + end + states[i + 1] = k + if i > max then + max = i + end + end + for i = 1, max + 1 do + if states[i] == nil then + states[i] = "minecraft:air" + end + end + local n = sx * sy * (sz ) + local yzx = buffer.create(n * 2) + local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1) + if not ok then + return nil, e + end + local bes = {} + local raw = (version >= 3 and{container.BlockEntities }or{(version == 2 and{s.BlockEntities }or{s.TileEntities +})[1]})[1] for _, c in __iter(Common.list(raw)) do + local be = Common.blockEntity(c, version >= 3 and"data" or"pos") + if be then + table.insert(bes, be) + end + end + local off = Common.ints(s.Offset) or { 0, 0, 0 } + local regions= { + { + name = nil, + size = { sx, sy , sz }, + position = { off[1] or 0, off[2] or 0, off[3] or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy , sz ), + blockEntities = bes, + entities = Common.list(s.Entities), + }, + } + return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } +end + +-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, +-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept +function Sponge.write(r, version, dataVersion, base) +local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a Sponge schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + local palette, keys = {}, {} + for i, st in __iter(states) do + palette[st] = i - 1 + keys[i] = st + end + local pal = Types.object(palette, keys) + local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n) + local bes = Nbt.list("compound") + for _, be in __iter(r.blockEntities) do + table.insert(bes, Common.flatBlockEntity(be, version >= 3 and"data" or"pos")) + end + local ents = (#r.entities > 0 and{r.entities }or{(Nbt.list("compound") -- optional, but readers expect it +)})[1] local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) + local fields= { + { "Version", version }, + { "DataVersion", (version >= 2 and{dataVersion }or{nil })[1]}, + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Offset", off }, + } + if version >= 3 then + local blocksBase = (type(base) == "table" and{base.Blocks }or{nil +})[1] table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) }) + table.insert(fields, { "Entities", ents }) + else + table.insert(fields, { "PaletteMax", #states }) + table.insert(fields, { "Palette", pal }) + table.insert(fields, { "BlockData", data }) + table.insert(fields, { version == 2 and"BlockEntities" or"TileEntities", bes }) + table.insert(fields, { "Entities", (version == 2 and{ents }or{nil })[1]}) + end + -- the other version's block fields never carry over + local drop = version >= 3 and{ PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true } +or{ Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 } + return Common.merge(base, fields, drop ), nil +end + +return Sponge +end +__FILES["model/smd"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the +-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a +-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation +-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation, +-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up. +-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Sniff = __include("core/Sniff") +local Types = __include("Types") +local Read = __include("model/smd/Read") +local Write = __include("model/smd/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Smd = { + name = "smd", + category = "model", + extensions = { "smd" }, + mime = { "model/x-smd", "text/plain" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" }, + caps = { decode = true, encode = true, skins = true, animation = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + +function Smd.sniff(r) +local head = Sniff.text(r, 256, true) + head = string.gsub(head, "^//[^\n]*\n%s*", "") + if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Smd.decode(r, opts) +local text = Sniff.dropBom(r:string(r:remaining())) + local o= opts and table.clone(opts ) or {} + if type(o.name) == "string" then + o.name = string.match(o.name, "([^/\\]+)$") or o.name + o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "") + end + local scene, msg = Read.read(text, o) + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Smd.encode(scene, opts) +local text, msg = Write.write(scene, opts) + if not text then + return nil, Err.new(Err.ARG, tostring(msg)) + end + return buffer.fromstring(text), nil +end + +return Smd +end +__FILES["model/smd/Read"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id, +-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone +-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px +-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted). +-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material +-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links, +-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond +-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation. +local Types = __include("Types") +local Rig = __include("codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + + + +local ZERO= { 0, 0, 0, 0, 0, 0 } + +-- read(text, opts) -> Scene | nil, message +function Read.read(text, opts) +local lines= {} + for line in __iter(string.gmatch(text, "[^\r\n]*")) do + table.insert(lines, line) + end + local i = 1 + local n = #lines + local function nextLine() +while i <= n do + local l = lines[i] + i =i+ 1 + local s = (string.match(l, "^%s*(.-)%s*$") ) +s = (string.gsub(s, "%s*//.*$", "") ) +if s ~= "" then + return s + end + end + return nil + end + local bones= {} + local byId= {} -- SMD bone id -> index into bones (1-based) + local frames= {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz } + local times= {} + +local batches= {} + local byMat= {} + local version= nil + local vertexAnimations = 0 + local maxV = opts and opts.maxVertices or 2 ^ 24 + local total = 0 + while true do + local l = nextLine() + if not l then + break + end + local kw = string.lower(string.match(l, "^(%S+)") or "") + if kw == "version" then + version = tonumber(string.match(l, "^%S+%s+(%S+)")) + elseif kw == "nodes" then + while true do + local s = nextLine() + if not s then + return nil, "truncated: nodes without end" + end + if string.lower(s) == "end" then + break + end + local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)') + if not id then + id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)") + end + if not id then + return nil, "bad node line: " .. s + end + table.insert(bones, { id = (tonumber(id) ), name = name , parent = (tonumber(parent) )}) + byId[(tonumber(id) )] = #bones + end + elseif kw == "skeleton" then + local cur= nil + while true do + local s = nextLine() + if not s then + return nil, "truncated: skeleton without end" + end + local low = string.lower(s) + if low == "end" then + break + end + local tm = string.match(low, "^time%s+(%-?[%d%.]+)") + if tm then + local prev = frames[#frames] + local f= {} + if prev then + for k, v in __iter(prev) do + f[k] = v + end + end + table.insert(frames, f) + table.insert(times, (tonumber(tm) )) + cur = f + else + local nums= {} + for tok in __iter(string.gmatch(s, "%S+")) do + table.insert(nums, tonumber(tok) or 0 / 0) + end + local bi = byId[nums[1] ] + if not cur or #nums < 7 or not bi then + return nil, "bad skeleton line: " .. s + end + cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] } + end + end + elseif kw == "triangles" then + while true do + local mat = nextLine() + if not mat then + return nil, "truncated: triangles without end" + end + if string.lower(mat) == "end" then + break + end + local b = byMat[mat] + if not b then + b = { name = mat, keys = {}, verts = {}, indices = {} } + byMat[mat] = b + table.insert(batches, b) + end + for _ = 1, 3 do + local s = nextLine() + if not s then + return nil, "truncated triangle" + end + local nums= {} + for tok in __iter(string.gmatch(s, "%S+")) do + local v = tonumber(tok) + if not v then + return nil, "bad vertex line: " .. s + end + table.insert(nums, v) + end + if #nums < 9 then + return nil, "short vertex line: " .. s + end + local id = b.keys[s] + if not id then + total =total+ 1 + if total > maxV then + return nil, "limit: too many vertices" + end + table.insert(b.verts, nums) + id = #b.verts - 1 + b.keys[s] = id + end + table.insert(b.indices, id) + end + end + elseif kw == "vertexanimation" then + vertexAnimations =vertexAnimations+ 1 + while true do + local s = nextLine() + if not s or string.lower(s) == "end" then + break + end + end + else + return nil, "unknown section " .. kw + end + end + if version ~= 1 then + return nil, version == nil and"no version line" or"unsupported: SMD version " .. tostring(version) + end + local scene = Scene.new() + scene.meta.up = "z" + local root= { name = opts and opts.name or "smd", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + -- skeleton (bind pose: the first frame) + local joints= {} + local bind= frames[1] or {} + for k, bn in __iter(bones) do + local v= bind[k] or ZERO + local parent = (bn.parent >= 0 and{byId[bn.parent] or 0 }or{0 +})[1] joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) } + end + local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1) + -- meshes + if #batches > 0 then + local mesh= { primitives = {} } + for _, b in __iter(batches) do + local nv = #b.verts + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local lists= {} + for vi, v in __iter(b.verts) do + local o = (vi - 1) * 12 + writef32(pos, o, v[2]) + writef32(pos, o + 4, v[3]) + writef32(pos, o + 8, v[4]) + writef32(nrm, o, v[5]) + writef32(nrm, o + 4, v[6]) + writef32(nrm, o + 8, v[7]) + writef32(uv, (vi - 1) * 8, v[8]) + writef32(uv, (vi - 1) * 8 + 4, 1 - v[9]) + local l= {} + local sum = 0 + local nl = (#v >= 10 and{(math.floor(v[10]) )}or{0 +})[1] for k = 0, nl - 1 do + local bi, w = byId[v[11 + k * 2] ], v[12 + k * 2] + if bi and w then + table.insert(l, bi - 1) + table.insert(l, w) + sum =sum+ w + end + end + local parent = byId[v[1] ] + if parent and sum < 0.999 then + table.insert(l, parent - 1) + table.insert(l, 1 - sum) + end + lists[vi] = l + end + local ib = buffer.create(#b.indices * 4) + for k, id in __iter(b.indices) do + writeu32(ib, (k - 1) * 4, id) + end + local attrs= { + POSITION = Scene.accessor(pos, "f32", 3, nv), + NORMAL = Scene.accessor(nrm, "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + } + if #bones > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local mat = Scene.material(b.name) + mat.metallic = 0 + table.insert(scene.textures, { name = b.name, uri = b.name }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" , material = #scene.materials }) + end + table.insert(scene.meshes, mesh) + table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = (#bones > 0 and{skinIndex }or{nil })[1]}) + table.insert(root.children, #scene.nodes) + end + -- animation + if #frames > 1 or (#frames == 1 and #batches == 0) then + local fps = opts and opts.fps or 30 + local t= {} + for k, tm in __iter(times) do + t[k] = (tm - times[1]) / fps + end + local tracks= {} + for k = 1, #bones do + local tr, rot= {}, {} + for _, f in __iter(frames) do + local v= f[k] or bind[k] or ZERO + table.insert(tr, v[1]) + table.insert(tr, v[2]) + table.insert(tr, v[3]) + local q = Rig.angles(v[4], v[5], v[6]) + for c = 1, 4 do + table.insert(rot, q[c]) + end + end + tracks[k] = { translation = tr, rotation = rot } + end + Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR") + end + scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = #batches > 0 and"reference" or"animation" } + return scene, nil +end + +return Read +end +__FILES["model/smd/Write"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node +-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose +-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled +-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every +-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material +-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the +-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless +-- opts.triangles is true. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Flatten = __include("codecs/model/MeshFlatten") + +local Write = {} + + + +local fmt = string.format + +local function num(v) +if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local s = fmt("%.6f", v) + if s == "-0.000000" then + return "0.000000" + end + return s +end + +-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x) +local function angles(q) +local m = Mat4.fromQuat(q) + local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1] + local y = math.asin(math.clamp(-r31, -1, 1)) + local x, z + if math.abs(r31) < 0.9999999 then + x = math.atan2(r32, r33) + z = math.atan2(r21, r11) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return x, y, z +end + +local function lerp(a, b, t) +local out= {} + for i = 1, #a do + out[i] = a[i] + (b[i] - a[i]) * t + end + return out +end + +-- the value of channel ch at time tm (nil when the channel has no keys) +local function sample(ch, tm) +local input, output = ch.input, ch.output + local n = input.count + if n == 0 then + return nil + end + local comps = ch.path == "rotation" and 4 or 3 + local function key(k) +local out= {} + for c = 0, comps - 1 do + out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4) + end + return out + end + local times = input.data + if tm <= buffer.readf32(times, 0) then + return key(0) + end + for k = 1, n - 1 do + local t1 = buffer.readf32(times, k * 4) + if tm <= t1 then + local t0 = buffer.readf32(times, (k - 1) * 4) + local f = (ch.interpolation == "STEP" or t1 <= t0 )and 0 or(tm - t0) / (t1 - t0) + local a, b = key(k - 1), key(k) + if comps == 4 then + if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + local q = lerp(a, b, f) + local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + return l > 0 and{ q[1] / l, q[2] / l, q[3] / l, q[4] / l } or a + end + return lerp(a, b, f) + end + end + return key(n - 1) +end + +-- write(scene, opts) -> text | nil, message +function Write.write(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, "expected a Scene" + end + local out= { "version 1", "nodes" } + local skin = scene.skins and scene.skins[1] + local joints= (skin and{skin.joints }or{{} +})[1] local jointOf= {} -- node index -> bone id (0-based) + for k, nd in __iter(joints) do + jointOf[nd] = k - 1 + end + local parentOf= {} + for ni, nd in __iter(scene.nodes) do + for _, c in __iter(nd.children) do + parentOf[c] = ni + end + end + if #joints == 0 then + table.insert(out, '0 "root" -1') + else + for k, nd in __iter(joints) do + local p = parentOf[nd] + while p and jointOf[p] == nil do + p = parentOf[p] + end + local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1)) + table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), (p and{jointOf[p] }or{(-1)})[1])) + end + end + table.insert(out, "end") + table.insert(out, "skeleton") + local function pose(tr, rot) +local t = tr or { 0, 0, 0 } + local x, y, z = angles(rot or { 0, 0, 0, 1 }) + return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ") + end + local animIndex = opts and opts.animation + local anim = animIndex and scene.animations[animIndex] + if animIndex and not anim then + return nil, "no animation " .. tostring(animIndex) + end + if anim then + local keyset= {} + for _, ch in __iter(anim.channels) do + for k = 0, ch.input.count - 1 do + keyset[buffer.readf32(ch.input.data, k * 4)] = true + end + end + local keys= {} + for tm in __iter(keyset) do + table.insert(keys, tm) + end + table.sort(keys) + local byNode= {} + for _, ch in __iter(anim.channels) do + local m = byNode[ch.node] or {} + byNode[ch.node] = m + m[ch.path] = ch + end + for f, tm in __iter(keys) do + table.insert(out, "time " .. (f - 1)) + for k, nd in __iter(joints) do + local node = scene.nodes[nd] + local chs= byNode[nd] or {} + local tch, rch = chs.translation, chs.rotation + local tr = (tch and{(sample(tch, tm) )}or{node.translation +})[1] local rot = (rch and{(sample(rch, tm) )}or{node.rotation +})[1] table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + else + table.insert(out, "time 0") + if #joints == 0 then + table.insert(out, "0 " .. pose(nil, nil)) + else + for k, nd in __iter(joints) do + local node = scene.nodes[nd] + local tr, rot = node.translation, node.rotation + if node.matrix then + local t, r = Mat4.decompose(node.matrix) + tr, rot = t, r + end + table.insert(out, (k - 1) .. " " .. pose(tr, rot)) + end + end + end + table.insert(out, "end") + -- triangles + if not anim or (opts and opts.triangles) then + local m, err = Flatten.merge(scene, function(name) +return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0" + end, { triangulate = true }) + if not m then + return nil, err + end + local A = m.attrs + local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0 + local links = not (opts and opts.links == false) + local nbones = math.max(1, #joints) + if #m.corners > 0 then + table.insert(out, "triangles") + for _, part in __iter(m.parts) do + local mat = part.prim.material and scene.materials[part.prim.material] + local mname = (mat and mat.name and mat.name ~= "" and{mat.name }or{"default" +})[1] for f = part.firstFace, part.firstFace + part.faceCount - 1 do + table.insert(out, mname) + for c = 0, 2 do + local v = m.corners[f * 3 + c + 1] + local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3] + local nx, ny, nz = 0, 0, 1 + if N then + nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3] + end + local u, w = 0, 0 + if UV then + local k = UV.components + u, w = UV.values[v * k + 1], UV.values[v * k + 2] + end + local parent = 0 + local lk= {} + if J and W and #joints > 0 then + local jk, wk = J.components, W.components + local best, bestW = 0, -1 + local count = 0 + for c2 = 1, math.min(4, jk, wk) do + local jw = W.values[v * wk + c2] + local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1) + if jw and jw > 0 then + count =count+ 1 + table.insert(lk, fmt("%d %s", jj, num(jw))) + if jw > bestW then + best, bestW = jj, jw + end + end + end + parent = best + if count > 0 then + table.insert(lk, 1, tostring(count)) + end + end + local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w)) + if links and #lk > 0 then + line =line.. " " .. table.concat(lk, " ") + end + table.insert(out, line) + end + end + end + table.insert(out, "end") + end + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end +__FILES["model/stl"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description +-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec). +-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the +-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView: +-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the +-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in +-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly +-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in +-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final +-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material, +-- solids, facets }. +-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans +-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after +-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle +-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either +-- convention. Not supported: binary-only extensions other than the two colour conventions. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Decode = __include("model/stl/Decode") +local Flatten = __include("codecs/model/MeshFlatten") + +-- ------------------------------------------------------------------------------------------------ contract +local Stl = { + name = "stl", + category = "model", + extensions = { "stl" }, + mime = { "model/stl", "application/sla" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + +local readu8, readu32 = buffer.readu8, buffer.readu32 +local writef32, writeu16, writeu32 = buffer.writef32, buffer.writeu16, buffer.writeu32 + +local function lower5(s) +return string.lower(s) == "solid" +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Stl.sniff(r) +local size = r:remaining() + if size >= 84 then + local c = r:peek(4, 80) + local n = string.byte(c, 1) + string.byte(c, 2) * 256 + string.byte(c, 3) * 65536 + string.byte(c, 4) * 16777216 + if 84 + 50 * n == size then + return 0.9 + end + end + local head = r:peek(512) + local s = string.match(head, "^%s*(%a+)") + if s and lower5(s) then + local l = string.lower(head) + return (string.find(l, "facet", 1, true) or string.find(l, "endsolid", 1, true) )and 0.9 or 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function soupPrim(n, pos, nrm) +return { + attributes = { + POSITION = Types.Scene.accessor(pos, "f32", 3, n * 3), + NORMAL = Types.Scene.accessor(nrm, "f32", 3, n * 3), + }, + mode = "triangles", + } +end + +local function decodeBinary(r, maxFaces, colors) +local b, base, size = r.buf, r.base, r.limit - r.base + local n = readu32(b, base + 80) + if n > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("%d facets is over the %d facet limit", n, maxFaces), base + 80) + end + if 84 + 50 * n > size then + return nil, Err.new(Err.TRUNCATED, string.format("%d facets need %d bytes, the file has %d", n, 84 + 50 * n, size), base + 80) + end + local pos, nrm, attr = buffer.create(n * 36), buffer.create(n * 36), buffer.create(n * 2) + local any = Decode.binary(b, base + 84, n, pos, nrm, attr) + local header = buffer.readstring(b, base, 80) + local cut = string.find(header, "\0", 1, true) -- the text before the first NUL + local text = (cut and{(string.sub(header, 1, cut - 1) )}or{header +})[1] local mode = colors + local ci = string.find(header, "COLOR=", 1, true) + if mode == "auto" then + mode = ci and ci + 9 <= 80 and"magics" or(any >= 0x8000 and"viscam" or"none" +) end + local prim = soupPrim(n, pos, nrm) + local source= { format = "stl", binary = true, header = text, facets = n } + if mode == "viscam" or mode == "magics" then + local dc = { 255, 255, 255, 255 } + if mode == "magics" and ci and ci + 9 <= 80 then + local o = base + ci + 5 -- the 4 bytes after "COLOR=" (ci is 1-based) + dc = { readu8(b, o), readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) } + source.defaultColor = dc + local mi = string.find(header, "MATERIAL=", 1, true) + if mi and mi + 8 + 12 <= 80 then + local m = base + mi + 8 + local function rgba(k) +return { readu8(b, m + k), readu8(b, m + k + 1), readu8(b, m + k + 2), readu8(b, m + k + 3) } + end + source.material = { diffuse = rgba(0), specular = rgba(4), ambient = rgba(8) } + end + end + local col = buffer.create(n * 12) + Decode.colors(attr, n, mode == "magics", dc[1], dc[2], dc[3], dc[4], col) + prim.attributes.COLOR_0 = Types.Scene.accessor(col, "unorm8", 4, n * 3) + source.colors = mode + elseif any ~= 0 then + prim.extras = { faceAttributes = { attribute = Types.Scene.accessor(attr, "u16", 1, n) } } + end + local scene = Types.Scene.fromPrimitive(prim, nil) + scene.meta.up = "z" + scene.meta.source = source +return scene, nil +end + +local function decodeAscii(r, maxFaces) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local at = 1 + local function tok() +local s, e = string.find(text, "%S+", at) + if not s then + return nil + end + at = (e ) + 1 + return string.sub(text, s, e) + end + local function restOfLine() +local e = string.find(text, "\n", at, true) or (#text + 1) + local line = string.sub(text, at, e - 1) + at = e + 1 + return string.match(line, "^%s*(.-)%s*$") or "" + end + local function num() +local t = tok() + return (t and{(tonumber(t) )}or{nil +})[1] end + +local solids= {} + local facets = 0 + while true do + local t = tok() + if t == nil then + break + end + if string.lower(t) ~= "solid" then + return nil, Err.new(Err.CORRUPT, "expected solid, found " .. string.sub(t, 1, 20)) + end + local cur= { name = restOfLine(), pos = {}, nrm = {} } + table.insert(solids, cur) + local pos, nrm = cur.pos, cur.nrm + while true do + local w = tok() + if w == nil then + break -- a missing endsolid at the end + end + local lw = string.lower(w) + if lw == "endsolid" then + restOfLine() + break + elseif lw ~= "facet" then + return nil, Err.new(Err.CORRUPT, "expected facet or endsolid, found " .. string.sub(w, 1, 20)) + end + local nx, ny, nz = 0, 0, 0 + local k = tok() + if k and string.lower(k) == "normal" then + local a, bb, c = num(), num(), num() + if a == nil or bb == nil or c == nil then + return nil, Err.new((at > #text and{Err.TRUNCATED }or{Err.CORRUPT})[1], "bad facet normal") + end + nx, ny, nz = a, bb, c + k = tok() + end + local l2 = tok() + if k == nil or l2 == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + if string.lower(k) ~= "outer" or string.lower(l2) ~= "loop" then + return nil, Err.new(Err.CORRUPT, "expected outer loop") + end + local vs= {} + while true do + local v = tok() + if v == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + end + local lv = string.lower(v) + if lv == "endloop" then + break + elseif lv ~= "vertex" then + return nil, Err.new(Err.CORRUPT, "expected vertex or endloop, found " .. string.sub(v, 1, 20)) + end + local x, y, z = num(), num(), num() + if x == nil or y == nil or z == nil then + return nil, Err.new((at > #text and{Err.TRUNCATED }or{Err.CORRUPT})[1], "bad vertex") + end + table.insert(vs, x) + table.insert(vs, y) + table.insert(vs, z) + end + local e = tok() + if e == nil then + return nil, Err.new(Err.TRUNCATED, "facet cut short") + elseif string.lower(e) ~= "endfacet" then + return nil, Err.new(Err.CORRUPT, "expected endfacet") + end + local nvs = math.floor(#vs / 3 +) if nvs < 3 then + return nil, Err.new(Err.CORRUPT, "facet with fewer than 3 vertices") + end + for j = 2, nvs - 1 do + for _, vi in __iter({ 0, j - 1, j }) do + table.insert(pos, vs[vi * 3 + 1]) + table.insert(pos, vs[vi * 3 + 2]) + table.insert(pos, vs[vi * 3 + 3]) + table.insert(nrm, nx) + table.insert(nrm, ny) + table.insert(nrm, nz) + end + facets =facets+ 1 + end + if facets > maxFaces then + return nil, Err.new(Err.LIMIT, string.format("over the %d facet limit", maxFaces)) + end + end + end + if #solids == 0 then + return nil, Err.new(Err.TRUNCATED, "no solid") + end + local prims= {} + local names= {} + for i, s in __iter(solids) do + local n = math.floor(#s.pos / 9 +) local pos, nrm = buffer.create(n * 36), buffer.create(n * 36) + for j = 1, n * 9 do + writef32(pos, (j - 1) * 4, s.pos[j]) + writef32(nrm, (j - 1) * 4, s.nrm[j]) + end + local prim = soupPrim(n, pos, nrm) + prim.extras = { solid = s.name } + prims[i] = prim + names[i] = s.name + end + local first = solids[1].name + local scene = Types.Scene.fromPrimitive(prims[1], (first ~= "" and{first }or{nil})[1]) + for i = 2, #prims do + table.insert(scene.meshes[1].primitives, prims[i]) + end + scene.meta.up = "z" + scene.meta.source = { format = "stl", binary = false, solids = names, facets = facets } + return scene, nil +end + +function Stl.decode(r, opts) +local maxFaces = opts and opts.maxFaces or 2 ^ 25 + local colors = opts and opts.colors or "auto" + if colors ~= "auto" and colors ~= "viscam" and colors ~= "magics" and colors ~= "none" then + return nil, Err.new(Err.ARG, "colors must be auto, viscam, magics or none") + end + local size = r.limit - r.base + if size >= 84 and 84 + 50 * readu32(r.buf, r.base + 80) == size then + return decodeBinary(r, maxFaces, colors) + end + local s = string.match(buffer.readstring(r.buf, r.base, math.min(size, 256)), "^%s*(%a+)") + if s and lower5(s) then + return decodeAscii(r, maxFaces) + end + if size < 84 then + return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base) + end + -- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED) + return decodeBinary(r, maxFaces, colors) +end + +-- ------------------------------------------------------------------------------------------------ encode +local scratch = buffer.create(4) +local function f32(v) +writef32(scratch, 0, v) + return buffer.readf32(scratch, 0) +end + +-- a COLOR_0 component as 0..255 +local function byte(a, v) +if a.raw then + if a.type == "unorm16" then + return math.floor((v * 255 + 32767) / 65535 +) end + return math.clamp(v, 0, 255) + end + return math.floor(math.clamp(v, 0, 1) * 255 + 0.5) +end + +local function to5(c) +return math.floor((c * 31 + 127) / 255 +)end + +local function keep(name) +return name == "NORMAL" or name == "COLOR_0" +end + +function Stl.encode(scene, opts) +local o= opts or {} + local colors = o.colors + if colors ~= nil and colors ~= "viscam" and colors ~= "magics" then + return nil, Err.new(Err.ARG, "colors must be viscam or magics") + end + if o.normals ~= nil and o.normals ~= "compute" and o.normals ~= "attribute" then + return nil, Err.new(Err.ARG, "normals must be compute or attribute") + end + if o.header ~= nil and (type(o.header) ~= "string" or #o.header > 80) then + return nil, Err.new(Err.ARG, "header must be a string of at most 80 bytes") + end + local m, merr = Flatten.merge(scene, keep, { triangulate = true }) + if not m then + return nil, Err.new(Err.ARG, tostring(merr)) + end + local P = m.attrs.POSITION.values + local N = (o.normals == "attribute" and m.attrs.NORMAL and{(m.attrs.NORMAL ).values }or{nil +})[1] local C = m.attrs.COLOR_0 + local corners = m.corners + local nf = math.floor(#corners / 3 +) -- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based) + local function normal(f) +local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if N then + return N[a * 3 + 1], N[a * 3 + 2], N[a * 3 + 3] + end + local ax, ay, az = P[a * 3 + 1], P[a * 3 + 2], P[a * 3 + 3] + local ux, uy, uz = P[b * 3 + 1] - ax, P[b * 3 + 2] - ay, P[b * 3 + 3] - az + local vx, vy, vz = P[c * 3 + 1] - ax, P[c * 3 + 2] - ay, P[c * 3 + 3] - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 and l < math.huge then + return nx / l, ny / l, nz / l + end + return 0, 0, 0 + end + if o.ascii then + local out = table.create(nf * 7 + 2 * #m.parts) + local used= {} + local function fmt(v) +v = f32(v) + if v ~= v or v == math.huge or v == -math.huge then + return nil + end + return string.format("%.9g", v) + end + for _, part in __iter(m.parts) do + local name = o.name + if name == nil then + local ex = part.prim.extras + name = (ex and type(ex.solid) == "string" and{ex.solid }or{(part.mesh and part.mesh.name and{part.mesh.name }or{(part.node and part.node.name and{part.node.name }or{"mesh" +})[1]})[1]})[1] end + name = string.gsub(tostring(name), "[\r\n]", " ") + if used[name] then -- distinct names: some readers merge solids by name + local k = 2 + while used[name .. "_" .. k] do + k =k+ 1 + end + name = name .. "_" .. k + end + used[name] = true + table.insert(out, "solid " .. name .. "\n") + for f = part.firstFace, part.firstFace + part.faceCount - 1 do + local nx, ny, nz = normal(f) + table.insert(out, string.format(" facet normal %s %s %s\n outer loop\n", fmt(nx) or "0", fmt(ny) or "0", fmt(nz) or "0")) + for k = 1, 3 do + local v = corners[f * 3 + k] * 3 + local x, y, z = fmt(P[v + 1]), fmt(P[v + 2]), fmt(P[v + 3]) + if not (x and y and z) then + return nil, Err.new(Err.ARG, "ASCII STL cannot hold a non-finite coordinate") + end + table.insert(out, " vertex " .. x .. " " .. y .. " " .. z .. "\n") + end + table.insert(out, " endloop\n endfacet\n") + end + table.insert(out, "endsolid " .. name .. "\n") + end + if #m.parts == 0 then + table.insert(out, "solid " .. (o.name or "mesh") .. "\nendsolid " .. (o.name or "mesh") .. "\n") + end + return buffer.fromstring(table.concat(out)), nil + end + -- binary + local buf = buffer.create(84 + 50 * nf) + local header = o.header or "rosetta STL" + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + if type(dc) ~= "table" or #dc < 4 then + return nil, Err.new(Err.ARG, "defaultColor must be { r, g, b, a }") + end + header = string.sub(header, 1, 69) .. " COLOR=" .. string.char(math.floor(math.clamp(dc[1], 0, 255) / 1), math.floor(math.clamp(dc[2], 0, 255) / 1), math.floor(math.clamp(dc[3], 0, 255) / 1), math.floor(math.clamp(dc[4], 0, 255) / 1)) + end + local dcol= nil + if colors == "magics" then + local dc = o.defaultColor or { 255, 255, 255, 255 } + dcol = { math.floor(dc[1] / 1), math.floor(dc[2] / 1), math.floor(dc[3] / 1), math.floor(dc[4] / 1 )} + end + buffer.writestring(buf, 0, header) + writeu32(buf, 80, nf) + -- the attribute words: colours, or the raw words of a single STL-decoded primitive + local rawAttr= nil + if colors == nil and #m.parts == 1 then + local ex = m.parts[1].prim.extras + local fa = ex and ex.faceAttributes + local acc = fa and fa.attribute + if acc and acc.count == nf then + rawAttr = Flatten.numbers(acc, true) + end + end + for f = 0, nf - 1 do + local q = 84 + f * 50 + local nx, ny, nz = normal(f) + writef32(buf, q, nx) + writef32(buf, q + 4, ny) + writef32(buf, q + 8, nz) + for k = 0, 2 do + local v = corners[f * 3 + k + 1] * 3 + writef32(buf, q + 12 + k * 12, P[v + 1]) + writef32(buf, q + 16 + k * 12, P[v + 2]) + writef32(buf, q + 20 + k * 12, P[v + 3]) + end + local w = 0 + if colors and C then + local a = corners[f * 3 + 1] * C.components + local cv = C.values + local r5, g5, b5 = to5(byte(C, cv[a + 1])), to5(byte(C, cv[a + 2] or 0)), to5(byte(C, cv[a + 3] or 0)) + if colors == "viscam" then + w = 0x8000 + r5 * 1024 + g5 * 32 + b5 + elseif dcol and byte(C, cv[a + 1]) == dcol[1] and byte(C, cv[a + 2] or 0) == dcol[2] and byte(C, cv[a + 3] or 0) == dcol[3] and ((C.components >= 4 and{(byte(C, cv[a + 4]) )}or{255})[1]) == dcol[4] then + w = 0x8000 -- the object colour + else + w = r5 + g5 * 32 + b5 * 1024 + end + elseif colors == "magics" then + w = 0x8000 -- the object colour + elseif rawAttr then + w = math.clamp(math.floor(rawAttr[f + 1] / 1), 0, 65535) + end + writeu16(buf, q + 48, w) + end + return buf, nil +end + +return Stl +end +__FILES["model/stl/Decode"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +--!optimize 2 +-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5 +-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that +-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws. +local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + +local Decode = {} + +-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into +-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes). +function Decode.binary(b, p, n, pos, nrm, attr) +local any = 0 + for i = 0, n - 1 do + local q = p + i * 50 + local o = i * 36 + local nx, ny, nz = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + writeu32(nrm, o, nx) + writeu32(nrm, o + 4, ny) + writeu32(nrm, o + 8, nz) + writeu32(nrm, o + 12, nx) + writeu32(nrm, o + 16, ny) + writeu32(nrm, o + 20, nz) + writeu32(nrm, o + 24, nx) + writeu32(nrm, o + 28, ny) + writeu32(nrm, o + 32, nz) + writeu32(pos, o, readu32(b, q + 12)) + writeu32(pos, o + 4, readu32(b, q + 16)) + writeu32(pos, o + 8, readu32(b, q + 20)) + writeu32(pos, o + 12, readu32(b, q + 24)) + writeu32(pos, o + 16, readu32(b, q + 28)) + writeu32(pos, o + 20, readu32(b, q + 32)) + writeu32(pos, o + 24, readu32(b, q + 36)) + writeu32(pos, o + 28, readu32(b, q + 40)) + writeu32(pos, o + 32, readu32(b, q + 44)) + local a = readu16(b, q + 48) + writeu16(attr, i * 2, a) + any = bor(any, a) + end + return any +end + +-- 5-bit -> 8-bit, rounded +local function x8(v) +return math.floor((v * 255 + 15) / 31 +)end + +-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid, +-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour, +-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a). +function Decode.colors(attr, n, magics, dr, dg, db, da, out) + for i = 0, n - 1 do + local w = readu16(attr, i * 2) + local r, g, bl, al = dr, dg, db, da + local own = (magics and{(w < 0x8000 )}or{(w >= 0x8000 +)})[1] if own then + local lo, mid, hi = x8(band(w, 31)), x8(band(rshift(w, 5), 31)), x8(band(rshift(w, 10), 31)) + g, al = mid, 255 + if magics then + r, bl = lo, hi + else + r, bl = hi, lo + end + end + local o = i * 12 + for k = 0, 2 do + writeu8(out, o + k * 4, r) + writeu8(out, o + k * 4 + 1, g) + writeu8(out, o + k * 4 + 2, bl) + writeu8(out, o + k * 4 + 3, al) + end + end +end + +return Decode +end +__FILES["model/usda"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text +-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own +-- reader / writer (pxr) and Blender's USD exporter. +-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / +-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, +-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one +-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every +-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, +-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / +-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> +-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / +-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). +-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. +-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs +-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel +-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Zip = __include("containers/Zip") +local Parse = __include("model/usda/Parse") +local Build = __include("model/usda/Build") +local Write = __include("model/usda/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Usda = { + name = "usda", + category = "model", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+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 }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + +local function isUsdz(r) +if r:peek(4) ~= "PK\3\4" then + return false + end + -- the first entry is the root layer + local lo, hi = r:peekU8(26), r:peekU8(27) + if lo < 0 or hi < 0 then + return false + end + local nameLen = lo + hi * 256 + local name = string.lower(r:peek(30 + nameLen)) + name = string.sub(name, 31) + return string.find(name, "%.usd[ac]?$") ~= nil +end + +function Usda.sniff(r) +local head = r:peek(8) + if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then + return 1 + end + if head == "PXR-USDC" then + return 0.9 -- recognised so the error says USDC is not supported + end + if isUsdz(r) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts, package) +return function(uri) +local candidates = { uri } + local slashed = string.gsub(uri, "\\", "/") + local stripped = string.gsub(slashed, "^%./", "") + if slashed ~= uri then + table.insert(candidates, slashed) + end + if stripped ~= slashed then + table.insert(candidates, stripped) + end + -- packaged assets: "model.usdz[textures/a.png]" + local inner = string.match(uri, "%[(.+)%]$") + if inner then + table.insert(candidates, inner) + end + for _, u in __iter(candidates) do + if package then + local data = package:read(u) + if data then + return data + end + end + local v= nil + if opts and type((opts ).files) == "table" then + v = ((opts ).files )[u] + end + if v == nil and opts and type((opts ).resolve) == "function" then + local ok, res = pcall((opts ).resolve , u) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + elseif type(v) == "buffer" then + return v + end + end + return nil + end +end + +function Usda.decode(r, opts) +local head = r:peek(8) + if head == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)") + end + local text +local package= nil + local usdz = false + if string.sub(head, 1, 4) == "PK\3\4" then + local archive, zerr = Zip.open(r) + if not archive then + return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package") + end + local entries = archive:list() + local root = nil + for _, e in __iter(entries) do + if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then + root = e + break + end + end + if not root then + return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer") + end + local data, rerr = archive:read(root) + if not data then + return nil, rerr + end + if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer") + end + text = buffer.tostring(data) + package = archive + usdz = true + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + if not Parse.version(text) then + return nil, Err.new(Err.CORRUPT, "no #usda header") + end + local layer, msg, at = Parse.layer(text, opts and opts.maxBytes) + if not layer then + if msg == "array over the size limit" then + return nil, Err.new(Err.LIMIT, msg , at) + end + local code = (at and at >= #text - 1 and{Err.TRUNCATED }or{Err.CORRUPT +})[1] if msg and string.find(msg, "^unterminated") then + code = Err.TRUNCATED + end + return nil, Err.new(code, msg or "parse error", (usdz and{nil }or{at})[1]) + end + local scene, err = Build.scene(layer, { + triangulate = opts and opts.triangulate, + flipV = opts and opts.flipV, + maxVertices = opts and opts.maxVertices, + fetch = fetcher(opts, package), + }) + if not scene then + if err == "LIMIT" then + return nil, Err.new(Err.LIMIT, "a mesh over maxVertices") + end + return nil, Err.new(Err.CORRUPT, err or "bad scene") + end + local src= scene.meta.source + src.version = Parse.version(text) + src.usdz = usdz or nil + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Usda.encode(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "usdz" then + return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda") + end + local ok, text = pcall(Write.text, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text)) + end + return buffer.fromstring(text ), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover +function Usda.parse(text) +local layer, msg, at = Parse.layer(text) + if not layer then + return nil, Err.new(Err.CORRUPT, msg or "parse error", at) + end + return layer, nil +end + +return Usda +end +__FILES["model/usda/Build"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux +-- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; +-- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh +-- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / +-- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. +-- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the +-- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local +-- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); +-- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / +-- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor +-- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every +-- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated +-- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. +-- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with +-- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> +-- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). +-- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in +-- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Parse = __include("model/usda/Parse") + +local Build = {} + + + + +local NONE = Parse.NONE +local DEG = math.pi / 180 + +local NOT_NODES = { Material = true, Shader = true, NodeGraph = true, GeomSubset = true, Skeleton = true, SkelAnimation = true, BlendShape = true } +local SKEL = { Skeleton = true, SkelAnimation = true, BlendShape = true } +local LIGHTS = { DistantLight = true, SphereLight = true, RectLight = true, DiskLight = true, CylinderLight = true, DomeLight = true } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", ktx2 = "image/ktx2", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", avif = "image/avif" } + +-- ------------------------------------------------------------------------------------------------ helpers + + + + + + + +local function isArr(v) +return type(v) == "table" and v.t == "arr" +end +local function str(v) +if type(v) == "string" then + return v + elseif type(v) == "table" and (v.t == "id" or v.t == "asset" or v.t == "path") then + return v.v + end + return nil +end +-- a tuple / scalar -> numbers (nil when not numeric) +local function nums(v) +if type(v) == "number" then + return { v } + elseif type(v) == "boolean" then + return { v and 1 or 0 } + elseif type(v) == "table" and v.t == "tuple" then + local out = {} + for k, x in __iter(v.v) do + if type(x) == "number" then + out[k] = x + elseif type(x) == "table" and x.t == "tuple" then + for _, y in __iter(x.v) do + if type(y) ~= "number" then + return nil + end + table.insert(out, y) + end + else + return nil + end + end + return out + elseif type(v) == "table" and v.t == "arr" then + return v.v + end + return nil +end +local function num(v) +if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return v and 1 or 0 + end + return nil +end + +-- the value of a property: its default, else its earliest time sample +local function propValue(p) +if not p then + return nil + end + if p.samples and #p.samples.times > 0 then + local best, bi = math.huge, 0 + for k, t in __iter(p.samples.times) do + if t < best then + best, bi = t, k + end + end + local v = p.samples.values[bi] + if v ~= NONE then + return v + end + end + if p.hasValue and p.value ~= NONE then + return p.value + end + return nil +end + +local function joinPath(parent, name) +return (parent == "/" and(("/" .. name ))or((parent .. "/" .. name +)))end + +-- resolve a (possibly relative) Sdf path against the prim path that holds it +local function resolvePath(base, p) +if string.sub(p, 1, 1) == "/" then + return p + end + local parts = string.split(base, "/") + local out= {} + for _, x in __iter(parts) do + if x ~= "" then + table.insert(out, x) + end + end + for _, x in __iter(string.split(p, "/")) do + if x == ".." then + table.remove(out) + elseif x ~= "." and x ~= "" then + table.insert(out, x) + end + end + return "/" .. table.concat(out, "/") +end +-- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" +local function splitProp(p) +local prim, prop = string.match(p, "^(.-)%.([^/]+)$") + if prim and prop then + return prim, prop + end + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ matrices +-- column-major 4x4 (glTF layout = USD's row-major row-vector text order) +local mul = Types.Scene.mul +local function quatM(x, y, z, w) +local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return Mat4.fromQuat({ x, y, z, w }) +end +-- ------------------------------------------------------------------------------------------------ xform ops +-- the op stack of a prim: ops in xformOpOrder, resetXformStack + + + +local function xformOps(p) +local order = p.props.xformOpOrder + local list = order and propValue(order) + local ops= {} + local reset = false + if type(list) ~= "table" or list.t ~= "list" then + return ops, false + end + for _, item in __iter(list.v) do + local name = str(item) + if name == "!resetXformStack!" then + reset = true + table.clear(ops) + elseif name then + local invert = false + if string.sub(name, 1, 8) == "!invert!" then + invert = true + name = string.sub(name, 9) + end + local prop = p.props[name] + local kind = string.match(name, "^xformOp:(%a+)") + if prop and kind then + local axes = string.match(kind, "^rotate([XYZ]+)$") + table.insert(ops, { kind = axes and"rotate" or kind, axes = axes, prop = prop, invert = invert }) + end + end + end + return ops, reset +end + +local AXIS = { X = 1, Y = 2, Z = 3 } +-- the matrix of one op for a value +local function opMatrix(op, v) +local n = nums(v) + if not n then + return nil + end + local m +local k = op.kind + if k == "translate" then + m = Mat4.translation(n[1] or 0, n[2] or 0, n[3] or 0) + elseif k == "scale" then + local s1 = n[1] or 1 + m = Mat4.scaling(s1, n[2] or s1, n[3] or s1) + elseif k == "orient" then + -- USD quaternions are written (real, i, j, k) + m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) + elseif k == "transform" then + if #n ~= 16 then + return nil + end + m = table.clone(n) + elseif k == "rotate" and op.axes then + local axes = op.axes +local r= Types.Scene.IDENTITY -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + +for c = 1, #axes do + local a = AXIS[string.sub(axes, c, c)] + local angle = (#axes == 1 and{n[1] or 0 }or{n[a] or 0 +})[1] r = mul(Mat4.rotation(a, angle), r) + end + m = r + else + return nil + end + if op.invert and m then + m = Mat4.inverseFull(m) + end + return m +end + +local function lerpValue(a, b, f, quat) +local na, nb = nums(a), nums(b) + if not na or not nb or #na ~= #nb then + return a + end + local out = table.create(#na) + if quat and #na == 4 then + -- (w, x, y, z): slerp through nlerp with the short path + local dot = 0 + for k = 1, 4 do + dot =dot+ na[k] * nb[k] + end + local sgn = dot < 0 and-1 or 1 + for k = 1, 4 do + out[k] = na[k] + (nb[k] * sgn - na[k]) * f + end + return { t = "tuple", v = out } + end + for k = 1, #na do + out[k] = na[k] + (nb[k] - na[k]) * f + end + return { t = "tuple", v = out } +end + +-- an op's value at time code t (samples interpolated linearly, held outside their range) +local function opValueAt(op, t) +local p = op.prop + local s = p.samples + if t ~= nil and s and #s.times > 0 then + local times, values = s.times, s.values + local lo, hi + for k = 1, #times do + local tk = times[k] + if values[k] ~= NONE then + if tk <= t and (lo == nil or tk > times[lo]) then + lo = k + end + if tk >= t and (hi == nil or tk < times[hi]) then + hi = k + end + end + end + if lo and hi then + if lo == hi or times[hi] == times[lo] then + return values[lo] + end + local f = (t - times[lo]) / (times[hi] - times[lo]) + return lerpValue(values[lo], values[hi], f, op.kind == "orient") + end + return values[lo or hi] + end + return propValue(p) +end + +local function localMatrix(ops, t) +local m= Types.Scene.IDENTITY +for _, op in __iter(ops) do + local om = opMatrix(op, opValueAt(op, t)) + if om then + m = mul(m, om) + end + end + return m +end +Build.localMatrix = localMatrix + +-- ------------------------------------------------------------------------------------------------ build +function Build.scene(layer, opts) +local scene = Types.Scene.new() + local flipV = opts.flipV ~= false + local triangulate = opts.triangulate ~= false + local maxVertices = opts.maxVertices or 2 ^ 25 + local fetch = opts.fetch + local unsupported= {} + local meta = layer.meta + + -- prim index (variants merged), paths + local byPath= {} + local parentOf= {} + local pathOf= {} + local function merge(p) + if not p.variantSets then + return + end + local nested= nil + local sel = p.meta.variants + local chosen = (type(sel) == "table" and sel.t == "dict" and{sel.v }or{{} +})[1] for setName, set in __iter(p.variantSets) do + local name = str(chosen[setName]) + local body = name and set[name] -- unselected sets contribute nothing + if body then + for _, pn in __iter(body.order) do + if not p.props[pn] then + p.props[pn] = body.props[pn] + table.insert(p.order, pn) + end + end + for _, c in __iter(body.children) do + table.insert(p.children, c) + end + for k, v in __iter(body.meta) do + if p.meta[k] == nil then + p.meta[k] = v + end + end + if body.variantSets then + nested = nested or {} + table.insert(nested , body.variantSets) + end + end + end + p.variantSets = nil + for _, vs in __iter(nested or {}) do + p.variantSets = vs + merge(p) + end + end + local function index(p, parent, depth) + if depth > 200 then + return + end + merge(p) + local path = joinPath(parent, p.name) + pathOf[p] = path + parentOf[p] = parent + local existing = byPath[path] + if existing and existing ~= p then + -- over / def of the same path in one layer: merge into the first spec + for _, pn in __iter(p.order) do + if not existing.props[pn] then + existing.props[pn] = p.props[pn] + table.insert(existing.order, pn) + end + end + existing.typeName = existing.typeName or p.typeName + if p.specifier == "def" then + existing.specifier = "def" + end + for _, c in __iter(p.children) do + table.insert(existing.children, c) + end + table.clear(p.children) + p.specifier = "class" -- skipped below + else + byPath[path] = p + end + for _, key in __iter({ "references", "payload", "inherits", "specializes" }) do + local v = p.meta[key] + if v ~= nil and v ~= NONE then + unsupported[key] = true + end + end + for _, c in __iter(p.children) do + index(c, path, depth + 1) + end + end + for _, p in __iter(layer.prims) do + index(p, "/", 1) + end + if meta.subLayers ~= nil then + unsupported.subLayers = true + end + + -- a property of a prim path ("/a/b.inputs:x") + local function propAt(path) +local pp, pn = splitProp(path) + local prim = byPath[pp] + if not prim or not pn then + return prim, nil + end + return prim, prim.props[pn] + end + + -- --------------------------------------------------------------------------------------------- materials + local texCoordIndex= {} + local texCoordCount = 0 + local function texCoordFor(name) +local k = texCoordIndex[name] + if k == nil then + k = texCoordCount + texCoordIndex[name] = k + texCoordCount =texCoordCount+ 1 + end + return k + end + -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + do + local names= {} + for _, p in __iter(byPath) do + if p.typeName == "Mesh" then + for pn, pr in __iter(p.props) do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") and pr.array then + names[nm] = true + end + end + end + end + local list = {} + for nm in __iter(names) do + table.insert(list, nm) + end + table.sort(list, function(a, b) +local pa = a == "st" and 0 or(string.sub(a, 1, 2) == "st" and 1 or 2 +) local pb = b == "st" and 0 or(string.sub(b, 1, 2) == "st" and 1 or 2 +) if pa ~= pb then + return pa < pb + end + return a < b + end) + for _, nm in __iter(list) do + texCoordFor(nm) + end + end +-- an input's resolved source: a value, or { shader = Prim, output = name } + + +local function input(prim, name, depth) +local d = depth or 0 + if d > 32 then + return nil + end + local p = prim.props["inputs:" .. name] + if not p then + return nil + end + if p.connect and #p.connect > 0 then + local target = resolvePath(pathOf[prim] or "/", p.connect[1]) + local tp, tn = splitProp(target) + local tprim = byPath[tp] + if tprim and tn then + local outName = string.match(tn, "^outputs:(.+)$") + local inName = string.match(tn, "^inputs:(.+)$") + if outName and tprim.typeName == "Shader" then + return { shader = tprim, output = outName } + elseif outName then + -- a NodeGraph output: follow its connection + local op = tprim.props[tn] + if op and op.connect and #op.connect > 0 then + local t2 = resolvePath(tp, op.connect[1]) + local sp, sn = splitProp(t2) + local sprim = byPath[sp] + if sprim and sn and string.match(sn, "^outputs:") then + return { shader = sprim, output = string.sub(sn, 9) } + end + end + elseif inName then + local r = input(tprim, inName, d + 1) + if r then + return r + end + end + end + end + local v = propValue(p) + if v ~= nil then + return { value = v } + end + return nil + end + local function shaderId(p) +return str(propValue(p.props["info:id"])) + end + + local textureIndex= {} + local WRAP= { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) + local function textureRef(shader) +if shaderId(shader) ~= "UsdUVTexture" then + return nil + end + local f = input(shader, "file") + local file = f and str(f.value) + if not file or file == "" then + return nil + end + local ws = input(shader, "wrapS") + local wt = input(shader, "wrapT") + local wrapS = WRAP[ws and str(ws.value) or "repeat"] or "repeat" + local wrapT = WRAP[wt and str(wt.value) or "repeat"] or "repeat" + local key = file .. "|" .. wrapS .. "|" .. wrapT + local ti = textureIndex[key] + if not ti then + local tex= { name = shader.name, uri = file, sampler = { wrapS = wrapS , wrapT = wrapT } } + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + tex.mime = MIME[ext] + local data = fetch and fetch(file) + if not data and string.sub(file, 1, 2) == "./" and fetch then + data = fetch(string.sub(file, 3)) + end + tex.data = data + local extras= { path = pathOf[shader] } + local cs = input(shader, "sourceColorSpace") + if cs and str(cs.value) then + extras.sourceColorSpace = str(cs.value) + end + tex.extras = { usd = extras } + table.insert(scene.textures, tex) + ti = #scene.textures + textureIndex[key] = ti + end + local ref= { texture = ti } + -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + local st = input(shader, "st") + local reader = st and st.shader + if reader and shaderId(reader) == "UsdTransform2d" then + local tr= {} + local rot = input(reader, "rotation") + local scl = input(reader, "scale") + local off = input(reader, "translation") + if rot and num(rot.value) and num(rot.value) ~= 0 then + tr.rotation = ((num(rot.value) )) * DEG + end + if scl and nums(scl.value) then + tr.scale = nums(scl.value) + end + if off and nums(off.value) then + tr.offset = nums(off.value) + end + if next(tr) then + ref.transform = tr +end + local inn = input(reader, "in") + reader = inn and inn.shader + end + if reader and string.find(shaderId(reader) or "", "^UsdPrimvarReader") then + local vn = input(reader, "varname") + local name = vn and str(vn.value) + if name then + local k = texCoordFor(name) + if k ~= 0 then + ref.texCoord = k + end + end + end + return ref + end + + local materialIndex= {} + local function material(path) +local mi = materialIndex[path] + if mi ~= nil then + return (mi > 0 and{mi }or{nil +})[1] end + local mp = byPath[path] + if not mp or mp.typeName ~= "Material" then + materialIndex[path] = 0 + return nil + end + local mat = Types.Scene.material(mp.name) + mat.baseColor = { 0.18, 0.18, 0.18, 1 } + mat.metallic = 0 + mat.roughness = 0.5 + mat.extras = { usd = { path = path } } + -- the surface shader + local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] + local shader= nil + if surf and surf.connect and #surf.connect > 0 then + local sp = splitProp(resolvePath(path, surf.connect[1])) + shader = byPath[sp] + end + if shader and shaderId(shader) == "UsdPreviewSurface" then + local sh = shader +local function value(name) +local s = input(sh, name) + return s and s.value + end + local function tex(name) +local s = input(sh, name) + if s and s.shader then + local ref = textureRef(s.shader) + return ref, (ref and{s.shader }or{nil +})[1] end + return nil, nil + end + local dc = nums(value("diffuseColor")) + if dc and #dc >= 3 then + mat.baseColor = { dc[1], dc[2], dc[3], 1 } + end + local dt, dshader = tex("diffuseColor") + if dt then + mat.baseColorTexture = dt + mat.baseColor = { 1, 1, 1, 1 } + local sc = input(dshader , "scale") + local s = sc and nums(sc.value) + if s and #s >= 3 then + mat.baseColor = { s[1], s[2], s[3], s[4] or 1 } + end + end + local op = num(value("opacity")) + local ot = tex("opacity") + if op then + mat.baseColor[4] = op + end + local thr = num(value("opacityThreshold")) + if thr and thr > 0 then + mat.alphaMode = "mask" + mat.alphaCutoff = thr + elseif (op and op < 1) or ot then + mat.alphaMode = "blend" + end + local m = num(value("metallic")) + if m then + mat.metallic = m + end + local r = num(value("roughness")) + if r then + mat.roughness = r + end + local mt = tex("metallic") + local rt = tex("roughness") + if rt or mt then + mat.metallicRoughnessTexture = rt or mt + if mt then + mat.metallic = 1 + end + if rt then + mat.roughness = 1 + end + end + local e = nums(value("emissiveColor")) + if e and #e >= 3 then + mat.emissive = { e[1], e[2], e[3] } + end + local et = tex("emissiveColor") + if et then + mat.emissiveTexture = et + mat.emissive = { 1, 1, 1 } + end + local nt = tex("normal") + if nt then + mat.normalTexture = nt + end + local oc = tex("occlusion") + if oc then + mat.occlusionTexture = oc + end + local ext= {} + local ior = num(value("ior")) + if ior and ior ~= 1.5 then + ext.KHR_materials_ior = { ior = ior } + end + local cc = num(value("clearcoat")) + if cc and cc > 0 then + ext.KHR_materials_clearcoat = { clearcoatFactor = cc, clearcoatRoughnessFactor = num(value("clearcoatRoughness")) or 0.01 } + end + if next(ext) then + mat.extensions = ext + end + local usd= (mat.extras ).usd + if num(value("useSpecularWorkflow")) == 1 then + usd.useSpecularWorkflow = true + usd.specularColor = nums(value("specularColor")) + end + elseif shader then + unsupported["shader " .. (shaderId(shader ) or "?")] = true + end + table.insert(scene.materials, mat) + materialIndex[path] = #scene.materials + return #scene.materials + end + + -- the bound material of a prim (material:binding, inherited from ancestors) + local function binding(prim, path) +local p= prim + local pp = path + while p do + local rel = p.props["material:binding"] or p.props["material:binding:preview"] or p.props["material:binding:full"] + if rel and rel.value and #rel.value > 0 then + return material(resolvePath(pp, rel.value[1])) + end + if pp == "/" then + break + end + pp = parentOf[p ] or "/" + p = byPath[pp] + end + return nil + end + + local colorMaterials= {} + local function colorMaterial(c) +local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) + local mi = colorMaterials[key] + if not mi then + local mat = Types.Scene.material("displayColor") + mat.baseColor = { c[1], c[2], c[3], c[4] or 1 } + mat.metallic = 0 + mat.roughness = 0.5 + if (c[4] or 1) < 1 then + mat.alphaMode = "blend" + end + mat.extras = { usd = { displayColor = true } } + table.insert(scene.materials, mat) + mi = #scene.materials + colorMaterials[key] = mi + end + return mi +end +-- --------------------------------------------------------------------------------------------- meshes + + +local function primvar(p, defaultInterp) +if not p then + return nil + end + local v = propValue(p) + if not isArr(v) then + return nil + end + local interp = defaultInterp + if p.meta and str(p.meta.interpolation) then + interp = (str(p.meta.interpolation) ) +end + return { data = v.v, w = v.w, interp = interp } + end + + local function buildMesh(prim, path) +local pts = propValue(prim.props.points) + local cnt = propValue(prim.props.faceVertexCounts) + local idx = propValue(prim.props.faceVertexIndices) + if not isArr(pts) or pts.w ~= 3 then + return nil, nil + end + local points= pts.v + local npts = math.floor(#points / 3 +) local counts= (isArr(cnt) and{cnt.v }or{{} +})[1] local indices= (isArr(idx) and{idx.v }or{{} +})[1] local nfaces = #counts + local ncorners = 0 + for f = 1, nfaces do + local c = counts[f] + if c < 0 or c ~= math.floor(c / 1 )then + return nil, "bad faceVertexCounts at " .. path + end + ncorners =ncorners+ c + end + if ncorners ~= #indices then + return nil, "faceVertexCounts and faceVertexIndices disagree at " .. path + end + if ncorners > maxVertices or npts > maxVertices then + return nil, "LIMIT" + end + for k = 1, ncorners do + local v = indices[k] + if v < 0 or v >= npts or v ~= math.floor(v / 1 )then + return nil, "a face vertex index out of range at " .. path + end + end + local faceStart = table.create(nfaces + 1, 0) + do + local acc = 0 + for f = 1, nfaces do + faceStart[f] = acc + acc =acc+ counts[f] + end + faceStart[nfaces + 1] = acc + end + -- primvars, validated + local function sizeOk(pv) +local n = ((pv.idx and((#pv.idx ))or((math.floor(#pv.data / pv.w))))) + local want = pv.interp == "constant" and 1 +or(pv.interp == "uniform" and{nfaces +}or{(pv.interp == "faceVarying" and{ncorners +}or{npts +})[1]})[1] if n < want then + return false + end + if pv.idx then + local m = math.floor(#pv.data / pv.w +) for _, k in __iter(pv.idx) do + if k < 0 or k >= m or k ~= math.floor(k / 1 )then + return false + end + end + end + return #pv.data % pv.w == 0 + end + local function withIndices(pv, name) +if not pv then + return nil + end + local ip = propValue(prim.props[name .. ":indices"]) + if isArr(ip) and ip.w == 1 then + pv.idx = ip.v + end + if not sizeOk(pv) then + unsupported["mismatched primvar " .. name] = true + return nil + end + return pv + end + local normals = withIndices(primvar(prim.props["primvars:normals"], "vertex"), "primvars:normals") + or withIndices(primvar(prim.props.normals, "vertex"), "normals") + if normals and normals.w ~= 3 then + normals = nil + end + local color = withIndices(primvar(prim.props["primvars:displayColor"], "constant"), "primvars:displayColor") + if color and color.w ~= 3 then + color = nil + end + local opacity = withIndices(primvar(prim.props["primvars:displayOpacity"], "constant"), "primvars:displayOpacity") + if opacity and opacity.w ~= 1 then + opacity = nil + end + local uvs= {} + for pn, pr in __iter(prim.props) do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and pr.array and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") then + local pv = withIndices(primvar(pr, "vertex"), pn) + if pv and pv.w == 2 then + uvs[texCoordFor(nm)] = pv + end + end + end + -- the value of a primvar for (point, face, corner) (0-based), component c + local function get(pv, point, face, corner, c) +local e = pv.interp == "constant" and 0 +or(pv.interp == "uniform" and{face +}or{(pv.interp == "faceVarying" and{corner +}or{point +})[1]})[1] if pv.idx then + e = (pv.idx )[e + 1] + end + return pv.data[e * pv.w + c + 1] or 0 + end + local perCorner = false + for _, pv in __iter({ normals, color, opacity }) do + if pv and (pv.interp == "faceVarying" or pv.interp == "uniform") then + perCorner = true + end + end + for _, pv in __iter(uvs) do + if pv.interp == "faceVarying" or pv.interp == "uniform" then + perCorner = true + end + end + local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" + -- holes + local hole= {} + local hv = propValue(prim.props.holeIndices) + if isArr(hv) then + for _, f in __iter(hv.v) do + hole[f] = true + end + end + -- face sets: GeomSubsets ("face" elements), the rest + local meshMaterial = binding(prim, path) + local constantColor= nil + if color and color.interp == "constant" then + constantColor = { get(color, 0, 0, 0, 0), get(color, 0, 0, 0, 1), get(color, 0, 0, 0, 2), (opacity and opacity.interp == "constant" and{(get(opacity, 0, 0, 0, 0) )}or{1 })[1]} + end + +local sets= {} + local used= {} + for _, c in __iter(prim.children) do + if c.typeName == "GeomSubset" and c.specifier ~= "class" then + local et = str(propValue(c.props.elementType)) or "face" + local fi = propValue(c.props.indices) + if et == "face" and isArr(fi) then + local faces = {} + for _, f in __iter(fi.v) do + if f >= 0 and f < nfaces and f == math.floor(f / 1 )and not used[f] then + used[f] = true + table.insert(faces, f) + end + end + table.sort(faces) + local cpath = joinPath(path, c.name) + local rel = c.props["material:binding"] or c.props["material:binding:preview"] + local mi = (rel and rel.value and #rel.value > 0 and{(material(resolvePath(cpath, rel.value[1])) )}or{meshMaterial +})[1] table.insert(sets, { faces = faces, material = mi, name = c.name }) + end + end + end + do + local rest = {} + for f = 0, nfaces - 1 do + if not used[f] then + table.insert(rest, f) + end + end + if #rest > 0 or #sets == 0 then + table.insert(sets, 1, { faces = rest, material = meshMaterial }) + end + end + local mesh= { name = prim.name, primitives = {} } + for _, set in __iter(sets) do + -- vertices: one per point (vertex-rate data) or per corner + local keyToVert= {} + local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local nv = 0 + local out= {} + local faceSizes= {} + for _, f in __iter(set.faces) do + local cnt0 = counts[f + 1] + if cnt0 >= 3 and not hole[f] then + local base = faceStart[f + 1] + local verts = (table.create(cnt0) ) +for k = 0, cnt0 - 1 do + local corner = base + k + local point = indices[corner + 1] + local key = (perCorner and{corner }or{point +})[1] local v = keyToVert[key] + if not v then + v = nv + keyToVert[key] = v + nv =nv+ 1 + vp[nv], vf[nv], vc[nv] = point, f, corner + end + verts[k + 1] = v + end + if leftHanded then + local r = (table.create(cnt0) ) +for k = 1, cnt0 do + r[k] = verts[cnt0 - k + 1] + end + verts = r + end + if triangulate then + for k = 2, cnt0 - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[k]) + table.insert(out, verts[k + 1]) + end + else + for k = 1, cnt0 do + table.insert(out, verts[k]) + end + table.insert(faceSizes, cnt0) + end + end + end + if nv > 0 then + local attrs= {} + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + for v = 1, nv do + local p0 = vp[v] * 3 + buffer.writef32(pos.data, (v - 1) * 12, points[p0 + 1]) + buffer.writef32(pos.data, (v - 1) * 12 + 4, points[p0 + 2]) + buffer.writef32(pos.data, (v - 1) * 12 + 8, points[p0 + 3]) + end + attrs.POSITION = pos + local function fill(pv, comps, flip) +local a = Types.Scene.accessor(nil, "f32", comps, nv) + for v = 1, nv do + for c = 0, comps - 1 do + local x = get(pv, vp[v], vf[v], vc[v], c) + if flip and c == 1 then + x = 1 - x + end + buffer.writef32(a.data, ((v - 1) * comps + c) * 4, x) + end + end + return a + end + if normals then + local nrm = fill(normals, 3, false) + if leftHanded then + -- normals follow the authored (left-handed) winding: keep them as authored + end + attrs.NORMAL = nrm + end + for k, pv in __iter(uvs) do + attrs["TEXCOORD_" .. k] = fill(pv, 2, flipV) + end + local mi = set.material + if color and not constantColor then + -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) + if opacity then + local a = Types.Scene.accessor(nil, "f32", 4, nv) + for v = 1, nv do + for c = 0, 2 do + buffer.writef32(a.data, ((v - 1) * 4 + c) * 4, get(color, vp[v], vf[v], vc[v], c)) + end + buffer.writef32(a.data, ((v - 1) * 4 + 3) * 4, get(opacity, vp[v], vf[v], vc[v], 0)) + end + attrs.COLOR_0 = a + else + attrs.COLOR_0 = fill(color, 3, false) + end + elseif constantColor and mi == nil then + mi = colorMaterial(constantColor) + end + local ind = Types.Scene.accessor(nil, "u32", 1, #out) + for k, v in __iter(out) do + buffer.writeu32(ind.data, (k - 1) * 4, v) + end + local prm= { attributes = attrs, indices = ind, mode = triangulate and"triangles" or"polygons", material = mi } + if not triangulate then + local fa = Types.Scene.accessor(nil, "u32", 1, #faceSizes) + for k, v in __iter(faceSizes) do + buffer.writeu32(fa.data, (k - 1) * 4, v) + end + prm.faces = fa + end + if set.name then + prm.extras = { usd = { subset = set.name } } + end + local ds = propValue(prim.props.doubleSided) + if mi and (ds == 1 or ds == true) then + local m = mi and scene.materials[mi] + if m then + m.doubleSided = true + end + end + table.insert(mesh.primitives, prm) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + return mesh, nil + end + + -- --------------------------------------------------------------------------------------------- cameras / lights + local function camera(prim) +local function f(name, d) +return num(propValue(prim.props[name])) or d + end + local focal = f("focalLength", 50) + local hap = f("horizontalAperture", 20.955) + local vap = f("verticalAperture", 15.2908) + local clip = nums(propValue(prim.props.clippingRange)) or { 1, 1000000 } + local proj = str(propValue(prim.props.projection)) or "perspective" + if proj == "orthographic" then + return { name = prim.name, type = "orthographic", xmag = hap / 20, ymag = vap / 20, znear = clip[1] or 1, zfar = clip[2] or 1000000 } + end + return { + name = prim.name, + type = "perspective", + yfov = 2 * math.atan(vap / (2 * focal)), + aspect = (vap > 0 and((hap / vap ))or(nil)), + znear = clip[1] or 1, + zfar = clip[2], + } + end + local function light(prim) +local function f(name, d) +return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props[name])) or d + end + local col = nums(propValue(prim.props["inputs:color"])) or nums(propValue(prim.props.color)) or { 1, 1, 1 } + local intensity = f("intensity", 1) * 2 ^ f("exposure", 0) + local l= { name = prim.name, type = "point", color = { col[1] or 1, col[2] or 1, col[3] or 1 }, intensity = intensity } + local t = prim.typeName + local cone = num(propValue(prim.props["inputs:shaping:cone:angle"])) or num(propValue(prim.props["shaping:cone:angle"])) + if t == "DistantLight" then + l.type = "directional" + elseif t == "RectLight" or t == "DiskLight" then + l.type = "spot" + l.outerCone = math.pi / 2 + l.innerCone = 0 + end + if cone and cone < 90 then + local soft = num(propValue(prim.props["inputs:shaping:cone:softness"])) or 0 + l.type = "spot" + l.outerCone = cone * DEG + l.innerCone = math.max(0, cone * DEG * (1 - soft)) + end + return l + end + + -- --------------------------------------------------------------------------------------------- nodes + local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 + if tcps <= 0 then + tcps = 24 + end + local animation= { name = "usd", channels = {} } + local failure= nil + + local function isNode(p) -- class prims are abstract; an over with no def is not defined (UsdStage traversal skips both) + +if p.specifier == "class" or p.specifier == "over" or NOT_NODES[p.typeName or ""] then + if SKEL[p.typeName or ""] then + unsupported["UsdSkel (skeletons, skinning, blend shapes)"] = true + end + return false + end + if p.typeName == "Scope" or p.typeName == nil then + -- scopes / untyped prims holding only materials are not nodes + local function hasContent(q, d) +if d > 100 then + return false + end + for _, c in __iter(q.children) do + if c.specifier ~= "class" and not NOT_NODES[c.typeName or ""] then + if c.typeName ~= nil and c.typeName ~= "Scope" then + return true + end + if hasContent(c, d + 1) then + return true + end + end + end + return false + end + if p.typeName == "Scope" or #p.children > 0 then + return hasContent(p, 0) + end + end + return true + end + + local function node(p, path, parent, depth) + if depth > 200 or failure then + return + end + if not isNode(p) then + return + end + local n= { name = p.name, children = {}, extras = { usd = { path = path, type = p.typeName } } } + table.insert(scene.nodes, n) + local ni = #scene.nodes + local ops, reset = xformOps(p) + -- animated ops: the local matrix at the union of their time codes + local times= {} + do + local seen= {} + for _, op in __iter(ops) do + local s = op.prop.samples + if s and #s.times > 1 then + for _, t in __iter(s.times) do + if not seen[t] then + seen[t] = true + table.insert(times, t) + end + end + end + end + table.sort(times) + end + if #times > 1 then + local count = math.min(#times, 100000) + local tin = Types.Scene.accessor(nil, "f32", 1, count) + local tr = Types.Scene.accessor(nil, "f32", 3, count) + local ro = Types.Scene.accessor(nil, "f32", 4, count) + local sc = Types.Scene.accessor(nil, "f32", 3, count) + local prev= nil + for k = 1, count do + local T, R, S = Mat4.decompose(localMatrix(ops, times[k])) + if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then + R = { -R[1], -R[2], -R[3], -R[4] } + end + prev = R + buffer.writef32(tin.data, (k - 1) * 4, times[k] / tcps) + for c = 0, 2 do + buffer.writef32(tr.data, ((k - 1) * 3 + c) * 4, T[c + 1]) + buffer.writef32(sc.data, ((k - 1) * 3 + c) * 4, S[c + 1]) + end + for c = 0, 3 do + buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) + end + end + table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } ) + table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } ) + table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } ) + local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) + n.translation, n.rotation, n.scale = T, R, S + elseif #ops > 0 then + -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix + local simple = true + local stage = 0 + for _, op in __iter(ops) do + local st = op.kind == "translate" and 1 or((op.kind == "rotate" or op.kind == "orient" )and 2 or(op.kind == "scale" and 3 or 9 +)) if op.invert or st == 9 or st <= stage or string.find(op.prop.name, "^xformOp:%a+:") then + simple = false + end + stage = st + end + local m = localMatrix(ops, nil) + if simple then + local T, R, S = Mat4.decompose(m) + local tx = ops[1].kind == "translate" + if tx then + n.translation = T + end + for _, op in __iter(ops) do + if op.kind == "rotate" or op.kind == "orient" then + n.rotation = R + elseif op.kind == "scale" then + n.scale = S + end + end + -- a negative scale with a rotation is not TRS-representable through decompose: keep the matrix + local back = Types.Scene.nodeMatrix(n) + for k = 1, 16 do + if math.abs(back[k] - m[k]) > 1e-5 * math.max(1, math.abs(m[k])) then + simple = false + break + end + end + if not simple then + n.translation, n.rotation, n.scale = nil, nil, nil + end + end + if not simple then + local identity = true + for k = 1, 16 do + if m[k] ~= Types.Scene.IDENTITY[k] then + identity = false + end + end + if not identity then + n.matrix = m + end + end + end + if reset or parent == nil then + table.insert(scene.roots, ni) + if reset and parent then + (n.extras ).usd.resetXformStack = true + end + else + table.insert(scene.nodes[parent].children, ni) + end + local t = p.typeName + if t == "Mesh" then + local mesh, err = buildMesh(p, path) + if err == "LIMIT" then + failure = "LIMIT" + return + elseif err then + failure = err + return + end + if mesh then + table.insert(scene.meshes, mesh) + n.mesh = #scene.meshes + end + elseif t == "Camera" then + table.insert(scene.cameras, camera(p)) + n.camera = #scene.cameras + elseif t and LIGHTS[t] and t ~= "DomeLight" then + table.insert(scene.lights, light(p)) + n.light = #scene.lights + elseif t and t ~= "Xform" and t ~= "Scope" and t ~= "Mesh" and t ~= "DomeLight" and t ~= "SkelRoot" then + unsupported["prim type " .. t] = true + end + for _, c in __iter(p.children) do + node(c, joinPath(path, c.name), ni, depth + 1) + end + end + + for _, p in __iter(layer.prims) do + if p.specifier ~= "class" then + node(p, "/" .. p.name, nil, 1) + end + end + if failure then + return nil, failure + end + if #animation.channels > 0 then + table.insert(scene.animations, animation) + end + + -- stage metadata + local up = str(meta.upAxis) + scene.meta.up = up == "Z" and"z" or"y" + local mpu = num(meta.metersPerUnit) + if mpu and mpu > 0 then + scene.meta.unit = mpu + end + local list = {} + for k in __iter(unsupported) do + table.insert(list, k) + end + table.sort(list) + scene.meta.source = { + format = "usda", + defaultPrim = str(meta.defaultPrim), + timeCodesPerSecond = tcps, + startTimeCode = num(meta.startTimeCode), + endTimeCode = num(meta.endTimeCode), + doc = str(meta.doc), + unsupported = (#list > 0 and{list }or{nil})[1], + } + return scene, nil +end + +return Build +end +__FILES["model/usda/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text +-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes +-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, +-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), +-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast +-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. +-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and +-- returns nil, message, offset - nothing escapes. +local Parse = {} +-- values: numbers, booleans, strings, and these tagged tables + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local NONE = table.freeze({ t = "none" }) +Parse.NONE = NONE + +local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true } +local VARIABILITY = { uniform = true, varying = true, config = true } +local MAX_DEPTH = 200 + +local function fail(msg, at) +error({ usda = msg, at = at }, 0) +end + +-- the parser over one text; positions are 1-based string indices +local function parser(s, maxBytes) + local n = #s + local depth = 0 + + -- whitespace and comments (newlines included) + local function ws(i) +while true do + local _, e = sfind(s, "^[ \t\r\n]+", i) + if e then + i = e + 1 + end + local c = sbyte(s, i) + if c == 35 then -- # + local nl = sfind(s, "\n", i, true) + i = (nl and((nl + 1 ))or((n + 1 +))) elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + local nl = sfind(s, "\n", i, true) + i = (nl and((nl + 1 ))or((n + 1 +))) elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + local _, ce = sfind(s, "*/", i + 2, true) + if not ce then + fail("unterminated comment", i) + end + i = (ce ) + 1 + else + return i + end + end + end + + local function expect(i, ch) +i = ws(i) + if ssub(s, i, i) ~= ch then + fail("expected '" .. ch .. "'", i) + end + return i + 1 + end + + local function ident(i) +local a, e = sfind(s, "^[%a_][%w_:]*", i) + if not a then + return nil, i + end + return ssub(s, a, e), (e ) + 1 + end + + local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" } + local function unescape(str) +if not sfind(str, "\\", 1, true) then + return str + end + return (string.gsub(str, "\\(x?)(.)", function(x, c) +if x == "x" then + return "\\x" .. c -- left alone (rare) + end + return ESC[c] or c + end)) + end + + local function str(i) +local q = ssub(s, i, i) + if ssub(s, i, i + 2) == q .. q .. q then + local e = sfind(s, q .. q .. q, i + 3, true) + if not e then + fail("unterminated string", i) + end + return unescape(ssub(s, i + 3, (e ) - 1)), (e ) + 3 + end + local j = i + 1 + while true do + local a = sfind(s, "[\\\n" .. q .. "]", j) + if not a then + fail("unterminated string", i) + end + local c = sbyte(s, a ) + if c == 92 then + j = (a ) + 2 + elseif c == 10 then + fail("newline in string", a ) + else + return unescape(ssub(s, i + 1, (a ) - 1)), (a ) + 1 + end + end + end + + local function number(i) +local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) + if not a then + a, e = sfind(s, "^[-+]?%d*%.?%d*", i) + end + if a and (e ) >= (a ) then + local v = tonumber(ssub(s, a, e)) + if v then + return v, (e ) + 1 + end + end + -- inf / -inf / nan + local w, e2 = sfind(s, "^[-+]?%a+", i) + if w then + local word = string.lower(ssub(s, w, e2)) + if word == "inf" or word == "+inf" then + return math.huge, (e2 ) + 1 + elseif word == "-inf" then + return -math.huge, (e2 ) + 1 + elseif word == "nan" or word == "-nan" or word == "+nan" then + return 0 / 0, (e2 ) + 1 + end + end + return nil, i + end + + -- skip a balanced (), [], {} block starting at i (strings and comments respected) + local function skipBalanced(i) +local open = sbyte(s, i) + local level = 0 + while i <= n do + i = ws(i) + local c = sbyte(s, i) + if c == nil then + break + end + if c == 40 or c == 91 or c == 123 then + level =level+ 1 + i =i+ 1 + elseif c == 41 or c == 93 or c == 125 then + level =level- 1 + i =i+ 1 + if level == 0 then + return i + end + elseif c == 34 or c == 39 then + local _, j = str(i) + i = j + elseif c == 64 then + local e = sfind(s, "@", i + 1, true) + i = (e and((e + 1 ))or((n + 1 +))) elseif c == 60 then + local e = sfind(s, ">", i + 1, true) + i = (e and((e + 1 ))or((n + 1 +))) else + local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i) + i = (e and((e + 1 ))or((i + 1 +))) end + end + fail("unbalanced " .. string.char(open or 63), i) + end + + local value +local metadata + -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list + +local function list(i) +local close = sfind(s, "]", i + 1, true) + if close then + local body = ssub(s, i + 1, close - 1) + if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then + local first = smatch(body, "^%s*%(([^%)]*)%)") + local w = 1 + if first then + w = 0 + for _ in __iter(gmatch(first, "[^%s,]+")) do + w =w+ 1 + end + elseif sfind(body, "[%(%)]") then + w = -1 -- nested tuples: the generic path + end + if w > 0 then + local out= {} + local k = 0 + local ok = true + for tok in __iter(gmatch(body, "[^%s,%(%)]+")) do + local v = tonumber(tok) + if not v then + ok = false + break + end + k =k+ 1 + out[k] = v + end + if ok and k % w == 0 then + if k * 8 > maxBytes then + fail("array over the size limit", i) + end + return { t = "arr", w = w, v = out } , close + 1 + end + end + end + end + -- generic + local items = {} + i =i+ 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "]" then + i =i+ 1 + break + elseif c == "" then + fail("unterminated list", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + local _ + _, i = metadata(i) + i = ws(i) + end + c = ssub(s, i, i) + if c == "," then + i =i+ 1 + elseif c ~= "]" then + fail("expected ',' or ']' in a list", i) + end + end + -- all numbers, or all equal-width numeric tuples -> arr + local w= nil + local flat= {} + for _, it in __iter(items) do + if type(it) == "number" then + if w and w ~= 1 then + return { t = "list", v = items }, i + end + w = 1 + table.insert(flat, it) + elseif type(it) == "table" and it.t == "tuple" then + local tw = #it.v + if (w and w ~= tw) or tw == 0 then + return { t = "list", v = items }, i + end + w = tw + for _, x in __iter(it.v) do + if type(x) ~= "number" then + return { t = "list", v = items }, i + end + table.insert(flat, x) + end + else + return { t = "list", v = items }, i + end + end + if w == nil then + return { t = "list", v = items }, i + end + return { t = "arr", w = w, v = flat } , i + end + + local function tuple(i) +local items = {} + i =i+ 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + i =i+ 1 + break + elseif c == "" then + fail("unterminated tuple", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + c = ssub(s, i, i) + if c == "," then + i =i+ 1 + elseif c ~= ")" then + fail("expected ',' or ')' in a tuple", i) + end + end + return { t = "tuple", v = items }, i + end + + -- { type key = value ... } (metadata dictionaries) + local function dict(i) +local out= {} + i =i+ 1 + while true do +local __DARKLUA_CONTINUE_10=false repeat i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i =i+ 1 + break + elseif c == "" then + fail("unterminated dictionary", i) + elseif c == ";" or c == "," then + i =i+ 1 +__DARKLUA_CONTINUE_10=true break + end + local ty + ty, i = ident(i) + if not ty then + fail("expected a type in a dictionary", i) + end + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + i =i+ 2 + end + i = ws(i) + local key +c = ssub(s, i, i) + if c == '"' or c == "'" then + key, i = str(i) + else + key, i = ident(i) + end + if not key then + fail("expected a key in a dictionary", i) + end + i = expect(i, "=") + local v + v, i = value(i) + out[key ] = v +__DARKLUA_CONTINUE_10=true until true if not __DARKLUA_CONTINUE_10 then break end end + return { t = "dict", v = out }, i + end + + function value(i) +depth =depth+ 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + i = ws(i) + local c = ssub(s, i, i) + local v +if c == "[" then + v, i = list(i) + elseif c == "(" then + v, i = tuple(i) + elseif c == "{" then + v, i = dict(i) + elseif c == '"' or c == "'" then + v, i = str(i) + elseif c == "@" then + local path + if ssub(s, i, i + 2) == "@@@" then + local e = sfind(s, "@@@", i + 3, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 3, (e ) - 1), (e ) + 3 + else + local e = sfind(s, "@", i + 1, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 1, (e ) - 1), (e ) + 1 + end + local a= { t = "asset", v = path } + local j = ws(i) + if ssub(s, j, j) == "<" then -- references = @file@</prim> + local e = sfind(s, ">", j + 1, true) + if not e then + fail("unterminated path", j) + end + a.path = ssub(s, j + 1, (e ) - 1) + i = (e ) + 1 + end + v = a + elseif c == "<" then + local e = sfind(s, ">", i + 1, true) + if not e then + fail("unterminated path", i) + end + v, i = { t = "path", v = ssub(s, i + 1, (e ) - 1) }, (e ) + 1 + else + local num, j = number(i) + if num ~= nil then + v, i = num, j + else + local id + id, j = ident(i) + if not id then + fail("expected a value", i) + end + i = j + if id == "None" then + v = NONE + elseif id == "true" then + v = true + elseif id == "false" then + v = false + else + v = { t = "id", v = id } + end + end + end + depth =depth- 1 + return v, i + end + + -- ( key = value ; "doc" ; prepend key = value ... ) + function metadata(i) +local out= {} + i = expect(i, "(") + while true do +local __DARKLUA_CONTINUE_11=false repeat i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + return out, i + 1 + elseif c == "" then + fail("unterminated metadata", i) + elseif c == ";" or c == "," then + i =i+ 1 +__DARKLUA_CONTINUE_11=true break + elseif c == '"' or c == "'" then + out.doc, i = str(i) +__DARKLUA_CONTINUE_11=true break + end + local key + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + local op= nil + if LISTOPS[key] then + op = key + i = ws(i) + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + end + i = ws(i) + if ssub(s, i, i) == "=" then + local v + v, i = value(i + 1) + if op == "delete" then + -- deletions only matter for composition + elseif op and op ~= "reorder" then + -- prepend / append / add: merge into one list + local prev = out[key ] + if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then + for _, x in __iter(v.v) do + table.insert(prev.v, x) + end + else + out[key ] = v + end + else + out[key ] = v + end + end +__DARKLUA_CONTINUE_11=true until true if not __DARKLUA_CONTINUE_11 then break end end + end + + -- time samples: { time: value, ... } + local function samples(i) +local times, values= {}, {} + i = expect(i, "{") + while true do +local __DARKLUA_CONTINUE_13=false repeat i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i =i+ 1 + break + elseif c == "" then + fail("unterminated time samples", i) + elseif c == "," then + i =i+ 1 +__DARKLUA_CONTINUE_13=true break + end + local t + t, i = number(i) + if t == nil then + fail("expected a time code", i) + end + i = expect(i, ":") + local v + v, i = value(i) + table.insert(times, t ) -- fail() threw on nil + table.insert(values, v) +__DARKLUA_CONTINUE_13=true until true if not __DARKLUA_CONTINUE_13 then break end end + return { times = times, values = values }, i + end + + local function targets(v) +local out = {} + if type(v) == "table" then + if v.t == "path" then + table.insert(out, v.v) + elseif v.t == "list" then + for _, x in __iter(v.v) do + if type(x) == "table" and x.t == "path" then + table.insert(out, x.v) + end + end + end + end + return out + end + + local primBody + +local function newPrim(specifier, typeName, name) +return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} } + end + + -- def Type "name" ( meta ) { body } + local function prim(i, specifier) +i = ws(i) + local typeName= nil + local c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + typeName, i = ident(i) + if not typeName then + fail("expected a prim type or name", i) + end + i = ws(i) + -- dotted schema names (rare) + while ssub(s, i, i) == "." do + local more + more, i = ident(i + 1) + typeName = (typeName ) .. "." .. (more or "") + end + i = ws(i) + end + c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + fail("expected a prim name", i) + end + local name + name, i = str(i) + local p = newPrim(specifier, typeName, name) + i = ws(i) + if ssub(s, i, i) == "(" then + p.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, p) + return p, i + end + + -- variantSet "name" = { "variant" ( meta ) { body } ... } + local function variantSet(i, p) +i = ws(i) + local setName + setName, i = str(i) + i = expect(i, "=") + i = expect(i, "{") + local sets = p.variantSets or {} + p.variantSets = sets + local set = sets[setName] or {} + sets[setName] = set + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + return i + 1 + elseif c ~= '"' and c ~= "'" then + fail("expected a variant name", i) + end + local vname + vname, i = str(i) + local body = newPrim("def", nil, vname) + i = ws(i) + if ssub(s, i, i) == "(" then + body.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, body) + set[vname] = body + end + end + + -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + local function property(i, first, p) +local word= first + local op= nil + if LISTOPS[word ] then + op = word + i = ws(i) + word, i = ident(i) + end + local custom, uniform = false, false + if word == "custom" then + custom = true + i = ws(i) + word, i = ident(i) + end + if word and VARIABILITY[word] then + uniform = word == "uniform" + i = ws(i) + word, i = ident(i) + end + if not word then + fail("expected a property", i) + end + local isRel = word == "rel" + local typeName= nil + local array = false + if not isRel then + typeName = word + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + array = true + i =i+ 2 + end + end + i = ws(i) + local name + name, i = ident(i) + if not name then + fail("expected a property name", i) + end + local suffix= nil + if ssub(s, i, i) == "." then + suffix, i = ident(i + 1) + end + local prop = p.props[name ] + if not prop then + prop = { name = name , rel = isRel } +p.props[name ] = prop + table.insert(p.order, name ) + end + local pr = prop +if typeName then + pr.typeName, pr.array = typeName, array + end + pr.uniform = pr.uniform or uniform or nil + pr.custom = pr.custom or custom or nil + i = ws(i) + if ssub(s, i, i) == "=" then + i = ws(i + 1) + if suffix == "timeSamples" then + pr.samples, i = samples(i) + elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then + i = skipBalanced(i) + else + local v + v, i = value(i) + if op == "delete" then + -- composition only + elseif suffix == "connect" then + pr.connect = targets(v) + elseif isRel then + pr.value = targets(v) + pr.hasValue = true + else + pr.value = v + pr.hasValue = true + end + end + end + i = ws(i) + if ssub(s, i, i) == "(" then + local m + m, i = metadata(i) + if pr.meta then + for k, v in __iter(m) do + (pr.meta )[k] = v + end + else + pr.meta = m + end + end + return i + end + + function primBody(i, p) +depth =depth+ 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + while true do +local __DARKLUA_CONTINUE_18=false repeat i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + depth =depth- 1 + return i + 1 + elseif c == "" then + fail("unterminated prim", i) + elseif c == ";" then + i =i+ 1 +__DARKLUA_CONTINUE_18=true break + end + local word, j = ident(i) + if not word then + fail("unexpected character in a prim", i) + end + if word == "def" or word == "over" or word == "class" then + local child + child, i = prim(j, word) + table.insert(p.children, child) + elseif word == "variantSet" then + i = variantSet(j, p) + elseif word == "reorder" then + local k = ws(j) + local w2, k2 = ident(k) + if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then + k2 = expect(k2, "=") + local _ + _, i = value(k2) + else + i = property(j, word, p) + end + else + i = property(j, word, p) + end +__DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end + end + + -- the whole layer + local function layer() +local i = 1 + if ssub(s, 1, 3) == "\239\187\191" then + i = 4 + end + if ssub(s, i, i + 4) ~= "#usda" then + fail("not a USDA file (no #usda header)", i) + end + local nl = sfind(s, "\n", i, true) + i = (nl and((nl + 1 ))or((n + 1 +))) local out= { meta = {}, prims = {} } + i = ws(i) + if ssub(s, i, i) == "(" then + out.meta, i = metadata(i) + end + while true do + i = ws(i) + if i > n then + break + end + local word, j = ident(i) + if word == "def" or word == "over" or word == "class" then + local p + p, i = prim(j, word) + table.insert(out.prims, p) + elseif word == "reorder" then + j = ws(j) + local _ + _, j = ident(j) + j = expect(j, "=") + _, i = value(j) + elseif ssub(s, i, i) == ";" then + i =i+ 1 + else + fail("expected def / over / class", i) + end + end + return out + end + + return layer +end + +-- layer(text, opts?) -> Layer | nil, message, offset (0-based) +function Parse.layer(text, maxBytes) +local run = parser(text, maxBytes or 2 ^ 30) + local ok, res = pcall(run) + if ok then + return res, nil, nil + end + if type(res) == "table" and (res ).usda then + return nil, (res ).usda, math.max(((res ).at or 1) - 1, 0) + end + return nil, "parse error: " .. tostring(res), nil +end + +-- version(text) -> the "#usda <version>" string +function Parse.version(text) +return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") +end + +return Parse +end +__FILES["model/usda/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. +-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, +-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture +-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a +-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, +-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are +-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) +-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), +-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the +-- embedded bytes written into opts.files as <name>_<n>.<ext>. Not written: skins, morph targets, weights animation, +-- lines / points primitives (counted in the returned notes). +local Types = __include("Types") + +local Write = {} + +local EXT= { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } +local RAD = 180 / math.pi + +-- ------------------------------------------------------------------------------------------------ text helpers + + +local function fmt(x) +if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 1e15 then + return string.format("%d", x) + end + return string.format("%.9g", x) +end +local function tuple(t) +local parts = table.create(#t) + for k, v in __iter(t) do + parts[k] = fmt(v) + end + return "(" .. table.concat(parts, ", ") .. ")" +end +local function quote(s) +return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"' +end +local function asset(s) +if string.find(s, "@", 1, true) then + return "@@@" .. s .. "@@@" + end + return "@" .. s .. "@" +end +-- a valid, sibling-unique prim name +local function namer() +local used= {} + return function(name, fallback) +local n = string.gsub(name or "", "[^%w_]", "_") + if n == "" then + n = fallback + end + if string.find(n, "^%d") then + n = "_" .. n + end + local base, k = n, 1 + while used[n] do + k =k+ 1 + n = base .. "_" .. k + end + used[n] = true + return n + end +end + +-- an accessor's elements as numbers (normalized types to floats) +local function values(acc) +if not acc then + return nil, 0 + end + local get = Types.Scene.reader(acc) + if not get then + return nil, 0 + end + local n, c = acc.count, acc.components + local out = (table.create(n * c) ) +for i = 0, n - 1 do + for k = 0, c - 1 do + out[i * c + k + 1] = get(i, k) + end + end + return out, c +end + +-- array literal of tuples ("[(x, y, z), ...]") or scalars +local function arrayText(vals, width, stride, count, map) +local st = stride or width + local n = count or (math.floor(#vals / st)) + local parts = table.create(n) + local buf = table.create(width) + for i = 0, n - 1 do + for k = 1, width do + local v = vals[i * st + k] or 0 + if map then + v = map(i, k, v) + end + buf[k] = fmt(v) + end + parts[i + 1] = (width == 1 and{buf[1] }or{("(" .. table.concat(buf, ", ", 1, width) .. ")" +)})[1] end + return "[" .. table.concat(parts, ", ") .. "]" +end +-- ------------------------------------------------------------------------------------------------ primitives +-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points + + + + + + + + + + + + +local function faces(p, nverts) +local idx +if p.indices then + idx = (values(p.indices)) or {} +else + idx = (table.create(nverts) ) +for i = 1, nverts do + idx[i] = i - 1 + end + end + local counts, out= {}, {} + local mode = p.mode + if mode == "triangles" or mode == nil then + for k = 1, #idx - 2, 3 do + table.insert(counts, 3) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "polygons" then + local fs = (values(p.faces)) or {} + local at = 1 + for _, n in __iter(fs) do + if at + n - 1 > #idx then + break + end + table.insert(counts, n) + for k = at, at + n - 1 do + table.insert(out, idx[k]) + end + at =at+ n + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b, c = idx[k], idx[k + 1], idx[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(counts, 3) + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(counts, 3) + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + else + return nil, nil + end + return counts, out +end + +-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable +local function merge(mesh, notes) +local prims= {} + for _, p in __iter(mesh.primitives) do + if p.attributes and p.attributes.POSITION and (p.attributes.POSITION ).components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then + table.insert(prims, p) + else + notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 + end + if p.targets and #p.targets > 0 then + notes["morph targets"] = (notes["morph targets"] or 0) + 1 + end + end + if #prims == 0 then + return nil + end + -- attributes every primitive has + local all = { NORMAL = true } + local uvSets= {} + for k = 0, 7 do + local every = true + for _, p in __iter(prims) do + if not p.attributes["TEXCOORD_" .. k] then + every = false + end + end + if every then + table.insert(uvSets, k) + end + end + local anyColor = false + for _, p in __iter(prims) do + if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then + all.NORMAL = false + end + if p.attributes.COLOR_0 then + anyColor = true + end + end + local m= { points = {}, counts = {}, indices = {}, normals = all.NORMAL and{} or nil, uvs = {}, colors = anyColor and{} or nil, hasAlpha = false, subsets = {} } + for _, k in __iter(uvSets) do + m.uvs[k] = {} + end + local face = 0 + for _, p in __iter(prims) do + local base = math.floor(#m.points / 3 +) local pos = (values(p.attributes.POSITION)) or {} + local nv = p.attributes.POSITION.count + table.move(pos, 1, nv * 3, #m.points + 1, m.points) + if m.normals then + local nrm = (values(p.attributes.NORMAL)) or {} + table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals) + end + for _, k in __iter(uvSets) do + local uv, c = values(p.attributes["TEXCOORD_" .. k]) + local dst = m.uvs[k] + for i = 0, nv - 1 do + table.insert(dst, (uv )[i * c + 1] or 0) + table.insert(dst, (uv )[i * c + 2] or 0) + end + end + if m.colors then + local col, c = values(p.attributes.COLOR_0) + local dst = m.colors +for i = 0, nv - 1 do + if col then + table.insert(dst, col[i * c + 1] or 1) + table.insert(dst, col[i * c + 2] or 1) + table.insert(dst, col[i * c + 3] or 1) + local a = (c >= 4 and{col[i * c + 4] or 1 }or{1 +})[1] if a ~= 1 then + m.hasAlpha = true + end + table.insert(dst, a) + else + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + end + end + end + local counts, idx = faces(p, nv) + local sub = { faces = {}, material = p.material } + if counts and idx then + local ok = true + for _, v in __iter(idx) do + if v < 0 or v >= nv then + ok = false + break + end + end + if ok then + for _, c in __iter(counts) do + table.insert(m.counts, c) + table.insert(sub.faces, face) + face =face+ 1 + end + for _, v in __iter(idx) do + table.insert(m.indices, v + base) + end + else + notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1 + end + end + table.insert(m.subsets, sub) + end + return m +end + +-- ------------------------------------------------------------------------------------------------ write +function Write.text(scene, opts) +local o= opts or {} + local notes= {} + local out= {} + local function line(depth, s) + table.insert(out, string.rep(" ", depth) .. s) + end + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in __iter(nodes) do + for _, c in __iter(n.children or {}) do + child[c] = true + end + end + roots = {} + for i in __iter(nodes) do + if not child[i] then + table.insert(roots, i) + end + end + end + if #(scene.skins or {}) > 0 then + notes.skins = #scene.skins + end + local wrap = #roots ~= 1 or (nodes[roots[1] ] == nil) + local rootNames = namer() + local rootName = wrap and"root" or rootNames(nodes[roots[1] ].name, "root") + + -- texture files + local base= o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" + local texFile= {} + for i, tex in __iter(scene.textures or {}) do + local uri= (tex.uri and{(string.gsub(tex.uri, "\\", "/")) }or{nil +})[1] if tex.data and type(o.files) == "table" then + uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")) + if string.find(uri , "^data:") or string.find(uri , "^%a+://") then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + local files= o.files + if files[uri] == nil then + files[uri] = tex.data + end + elseif not uri then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1 + end + texFile[i] = uri +end +-- animation: per node, per path -> { times, values (components) } + + +local tracks= {} + local tcps = 24 + local tMin, tMax = math.huge, -math.huge + for _, anim in __iter(scene.animations or {}) do + for _, ch in __iter(anim.channels or {}) do + if ch.path == "weights" then + notes["weights animation"] = (notes["weights animation"] or 0) + 1 + elseif nodes[ch.node] and ch.input and ch.output then + local times = (values(ch.input)) or {} + local vals, comps = values(ch.output) + if vals and #times > 0 then + local stride = comps + local per = math.floor(#vals / (comps * #times) +) -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + local off = (ch.interpolation == "CUBICSPLINE" and per == 3 and{comps }or{0 +})[1] local mult = ch.interpolation == "CUBICSPLINE" and per == 3 and 3 or 1 + local tv = {} + for k = 0, #times - 1 do + for c = 1, stride do + table.insert(tv, vals[k * comps * mult + off + c] or 0) + end + end + tracks[ch.node] = tracks[ch.node] or {} + tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps } + for _, t in __iter(times) do + tMin = math.min(tMin, t * tcps) + tMax = math.max(tMax, t * tcps) + end + end + end + end + end + + -- header + table.insert(out, "#usda 1.0") + table.insert(out, "(") + line(1, "defaultPrim = " .. quote(rootName)) + line(1, 'doc = "rosetta"') + if tMin <= tMax then + line(1, "endTimeCode = " .. fmt(tMax)) + end + line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1)) + if tMin <= tMax then + line(1, "startTimeCode = " .. fmt(tMin)) + line(1, "timeCodesPerSecond = " .. fmt(tcps)) + end + line(1, "upAxis = " .. quote(o.upAxis or (scene.meta.up == "z" and"Z" or"Y"))) + table.insert(out, ")") + table.insert(out, "") + + local looksPath = "/" .. rootName .. "/Looks" + local matNames = namer() + local matPath= {} + for i, mat in __iter(scene.materials or {}) do + matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) + end + + -- xform ops of a node (+ its animation) + local function xform(depth, ni, n) + local tr= tracks[ni] + local order= {} + local function samples(track, f) +local parts = {} + for k, t in __iter(track.times) do + table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps)) + end + return "{ " .. table.concat(parts, ", ") .. " }" + end + local function quat(v, at) -- USD writes (real, i, j, k) + +return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local function vec3(v, at) +return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local t, r, s = n.translation, n.rotation, n.scale + if n.matrix and #n.matrix == 16 then + if tr then + -- animated: start from the matrix's TRS + local m = n.matrix + local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) + local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) + local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2) + t, s = { m[13], m[14], m[15] }, { sx, sy, sz } + r = nil + notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1 + else + local m = n.matrix + line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] }))) + line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]') + return + end + end + if t or (tr and tr.translation) then + if t then + line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) + end + if tr and tr.translation then + line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation , vec3)) + end + table.insert(order, '"xformOp:translate"') + end + if r or (tr and tr.rotation) then + if r then + line(depth, "quatf xformOp:orient = " .. quat(r, 0)) + end + if tr and tr.rotation then + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation , quat)) + end + table.insert(order, '"xformOp:orient"') + end + if s or (tr and tr.scale) then + if s then + line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) + end + if tr and tr.scale then + line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale , vec3)) + end + table.insert(order, '"xformOp:scale"') + end + if #order > 0 then + line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]") + end + end + + local function meshBody(depth, m, path) + local doubleSided = false + for _, sub in __iter(m.subsets) do + local mat = sub.material and scene.materials[sub.material] + if mat and mat.doubleSided then + doubleSided = true + end + end + if doubleSided then + line(depth, "uniform bool doubleSided = 1") + end + -- extent + local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, math.floor(#m.points / 3 )- 1 do + for c = 1, 3 do + local v = m.points[i * 3 + c] + if v < mn[c] then + mn[c] = v + end + if v > mx[c] then + mx[c] = v + end + end + end + if #m.points > 0 then + line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]") + end + line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1)) + line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1)) + local single = #m.subsets == 1 + if single and m.subsets[1].material and matPath[m.subsets[1].material ] then + line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material ] .. ">") + end + if m.normals then + line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, "point3f[] points = " .. arrayText(m.points, 3)) + if m.colors then + line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + if m.hasAlpha then + local alpha = {} + for i = 0, math.floor(#m.colors / 4 )- 1 do + alpha[i + 1] = m.colors[i * 4 + 4] + end + line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + end + local uvKeys = {} + for k in __iter(m.uvs) do + table.insert(uvKeys, k) + end + table.sort(uvKeys) + for _, k in __iter(uvKeys) do + local name = k == 0 and"st" or"st" .. k + line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i, c, v) +return (c == 2 and((1 - v ))or(v +)) end) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, 'uniform token subdivisionScheme = "none"') + if not single then + local names = namer() + for k, sub in __iter(m.subsets) do + if #sub.faces > 0 then + local mp = sub.material and matPath[sub.material ] + table.insert(out, "") + line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. ((mp and{(' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" )}or{""})[1])) + line(depth, "{") + line(depth + 1, 'uniform token elementType = "face"') + line(depth + 1, 'uniform token familyName = "materialBind"') + line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1)) + if mp then + line(depth + 1, "rel material:binding = <" .. mp .. ">") + end + line(depth, "}") + end + end + end + end + + local function cameraBody(depth, c) + if c.type == "orthographic" then + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20)) + line(depth, 'token projection = "orthographic"') + line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20)) + return + end + local vap = 24 + local yfov = c.yfov or 0.8 + local focal = vap / (2 * math.tan(yfov / 2)) + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float focalLength = " .. fmt(focal)) + line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1))) + line(depth, 'token projection = "perspective"') + line(depth, "float verticalAperture = " .. fmt(vap)) + end + + local LIGHT_TYPE= { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } + local function lightBody(depth, l) + local c = l.color or { 1, 1, 1 } + line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) + line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1)) + if l.type ~= "directional" then + line(depth, "float inputs:radius = 0") + end + if l.type == "spot" then + local outer = l.outerCone or math.pi / 4 + line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD)) + line(depth, "float inputs:shaping:cone:softness = " .. fmt((outer > 0 and((1 - (l.innerCone or 0) / outer ))or(0)))) + end + if l.type ~= "directional" then + line(depth, "bool treatAsPoint = 1") + end + end + local function lightHead(l) +return l.type == "spot" and' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' or"" + end + + local visited= {} + local function writeNode(depth, ni, path, names, isRoot) + local n = nodes[ni] + if not n or visited[ni] then + return + end + visited[ni] = true + local name = (isRoot and not wrap and{rootName }or{(names(n.name, "node_" .. ni) +)})[1] local myPath = path .. "/" .. name + local mesh = n.mesh and scene.meshes[n.mesh] + local merged = mesh and merge(mesh, notes) + local cam = n.camera and scene.cameras[n.camera] + local lig = n.light and scene.lights[n.light] + local kind = "Xform" + local head = "" + local pad = string.rep(" ", depth) + if merged then + kind = "Mesh" + if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material ] then + head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")" + end + elseif cam and not lig then + kind = "Camera" + elseif lig and not cam then + kind = LIGHT_TYPE[lig.type] or "SphereLight" + local h = lightHead(lig) + head = (h ~= "" and{(string.format(h, pad, pad) )}or{"" +})[1] end + if n.skin then + notes.skins = (notes.skins or 0) + 0 + end + table.insert(out, "") + line(depth, "def " .. kind .. " " .. quote(name) .. head) + line(depth, "{") + xform(depth + 1, ni, n) + if kind == "Mesh" then + meshBody(depth + 1, merged , myPath) + elseif kind == "Camera" then + cameraBody(depth + 1, cam ) + elseif kind ~= "Xform" then + lightBody(depth + 1, lig ) + end + local childNames = namer() + -- a camera / light that did not take the node's prim + if cam and kind ~= "Camera" then + table.insert(out, "") + line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) + line(depth + 1, "{") + cameraBody(depth + 2, cam) + line(depth + 1, "}") + end + if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then + local l = lig +local h = lightHead(l) + local pad2 = string.rep(" ", depth + 1) + table.insert(out, "") + line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. ((h ~= "" and{(string.format(h, pad2, pad2) )}or{""})[1])) + line(depth + 1, "{") + lightBody(depth + 2, l) + line(depth + 1, "}") + end + if isRoot and not wrap then + Write._looks(out, depth + 1, scene, matPath, texFile, line) + end + for _, c in __iter(n.children or {}) do + writeNode(depth + 1, c, myPath, childNames, false) + end + line(depth, "}") + end + + if wrap then + line(0, "def Xform " .. quote(rootName)) + line(0, "{") + Write._looks(out, 1, scene, matPath, texFile, line) + local names = namer() + names("Looks", "Looks") + for _, r in __iter(roots) do + writeNode(1, r, "/" .. rootName, names, false) + end + line(0, "}") + else + writeNode(0, roots[1], "", rootNames, true) + end + table.insert(out, "") + return table.concat(out, "\n"), notes +end + +-- the Looks scope: materials as UsdPreviewSurface networks +function Write._looks(out, depth, scene, matPath, texFile, line) + local mats = scene.materials or {} + if #mats == 0 then + return + end + table.insert(out, "") + line(depth, 'def Scope "Looks"') + line(depth, "{") + for i, mat in __iter(mats) do + local path = matPath[i] + local mname = (string.match(path, "([^/]+)$") ) +table.insert(out, "") + line(depth + 1, "def Material " .. quote(mname)) + line(depth + 1, "{") + local d = depth + 2 + line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") +-- texture nodes (one per distinct ref) + +local texNodes= {} + local function texNode(ref, color) +if not ref or not texFile[ref.texture] then + return nil + end + for _, tn in __iter(texNodes) do + if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then + return tn.name + end + end + local name = "Texture_" .. (#texNodes + 1) + table.insert(texNodes, { name = name, ref = ref, color = color }) + return name + end + local bc = mat.baseColor or { 1, 1, 1, 1 } + local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask" + local diffuseTex = texNode(mat.baseColorTexture, true) + local mrTex = texNode(mat.metallicRoughnessTexture, false) + local emTex = texNode(mat.emissiveTexture, true) + local nTex = texNode(mat.normalTexture, false) + local oTex = texNode(mat.occlusionTexture, false) + table.insert(out, "") + line(d, 'def Shader "PreviewSurface"') + line(d, "{") + local e = d + 1 + line(e, 'uniform token info:id = "UsdPreviewSurface"') + if diffuseTex then + line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>") + else + line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 })) + end + local em = mat.emissive or { 0, 0, 0 } + if emTex then + line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>") + elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then + line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 })) + end + local ext = mat.extensions or {} + if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then + line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor)) + line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0)) + end + if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then + line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior)) + end + if mrTex then + line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>") + else + line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0)) + end + if nTex then + line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>") + end + if oTex then + line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>") + end + if blend and diffuseTex then + line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>") + elseif blend then + line(e, "float inputs:opacity = " .. fmt(bc[4] or 1)) + end + if mat.alphaMode == "mask" then + line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5)) + end + if mrTex then + line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>") + else + line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1)) + end + line(e, "token outputs:surface") + line(d, "}") + -- primvar readers per texCoord set, transforms, textures + local readers= {} + for _, tn in __iter(texNodes) do + local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 + if not readers[tc] then + readers[tc] = true + table.insert(out, "") + line(d, 'def Shader "PrimvarReader_' .. tc .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"') + line(d + 1, "string inputs:varname = " .. quote(tc == 0 and"st" or"st" .. tc)) + line(d + 1, "float2 outputs:result") + line(d, "}") + end + end + for _, tn in __iter(texNodes) do + local ref = tn.ref + local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0 + local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result" + if ref.transform then + local tr = ref.transform +table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '_Transform"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdTransform2d"') + line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">") + if tr.rotation then + line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD)) + end + if tr.scale then + line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 })) + end + if tr.offset then + line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 })) + end + line(d + 1, "float2 outputs:result") + line(d, "}") + stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" + end + local tex = scene.textures[ref.texture] + local sampler= tex and tex.sampler or {} + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdUVTexture"') + line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture])) + if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then + line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 })) + end + if tn.ref == mat.normalTexture then + line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)") + line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)") + end + line(d + 1, 'token inputs:sourceColorSpace = "' .. (tn.color and"sRGB" or"raw") .. '"') + line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">") + line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"') + line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"') + line(d + 1, "float outputs:a") + line(d + 1, "float outputs:b") + line(d + 1, "float outputs:g") + line(d + 1, "float outputs:r") + line(d + 1, "float3 outputs:rgb") + line(d, "}") + end + line(depth + 1, "}") + end + line(depth, "}") +end + +return Write +end +__FILES["model/vox"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt) +-- and the files MagicaVoxel 0.99.x saves (version 150 and 200). +-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP / +-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials, +-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown +-- chunks are kept raw and written back. +-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per +-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as +-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is +-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes. +-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must +-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk. +-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Grid = __include("model/vox/Grid") + +-- ------------------------------------------------------------------------------------------------ contract +local Vox = { + name = "vox", + category = "model", + extensions = { "vox" }, + mime = { "model/x-vox" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants +-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps + + + + + + + + + + + + + + + + + + + +local DEFAULT_PALETTE= {} +do + local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 } + for _, r in __iter(steps) do + for _, g in __iter(steps) do + for _, b in __iter(steps) do + if #DEFAULT_PALETTE < 215 then + table.insert(DEFAULT_PALETTE, { r, g, b, 255 }) + end + end + end + end + local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + for ch = 1, 4 do + for _, v in __iter(ramp) do + local c = { 0, 0, 0, 255 } + if ch == 4 then + c = { v, v, v, 255 } + else + c[ch] = v + end + table.insert(DEFAULT_PALETTE, c) + end + end +end +Vox.DEFAULT_PALETTE = DEFAULT_PALETTE + +local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs +local MAX_DEPTH = 256 + +-- ------------------------------------------------------------------------------------------------ sniff +function Vox.sniff(r) +return r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" and 1 or(r:peek(4) == "VOX " and 0.8 or 0 +)end + +-- ------------------------------------------------------------------------------------------------ decode +local function str(r) +local n = r:i32le() + if n < 0 or n > r:remaining() then + r:fail(Err.CORRUPT, "bad string length") + return "" + end + return r:string(n) +end + +local function dict(r) +local d= {} + local n = r:i32le() + if n < 0 or n * 8 > r:remaining() then + r:fail(Err.CORRUPT, "bad dictionary size") + return d + end + for _ = 1, n do + local k = str(r) + local v = str(r) + if r.err then + break + end + d[k] = v + end + return d +end + +local function ints(s) +local out = {} + if s then + for w in __iter(string.gmatch(s, "%S+")) do + table.insert(out, tonumber(w) or 0) + end + end + return out +end + +-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation +local function rotation(b) +local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3) + if i0 > 2 or i1 > 2 or i0 == i1 then + return nil + end + local i2 = 3 - i0 - i1 + local function sign(bit) +return bit32.band(b, bit32.lshift(1, bit)) ~= 0 and-1 or 1 + end + return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } } +end + +-- the node transform of a frame dictionary (_r, _t) +local function applyFrame(node, f) + local t = ints(f._t) + local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0 + local rb = tonumber(f._r) + local rows = (rb and rb ~= IDENTITY_R and{(rotation(rb) )}or{nil +})[1] if not rows then + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end + return + end + -- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix + local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } } + for row = 1, 3 do + R[row][rows[row][1] + 1] = rows[row][2] + end + local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1]) + if det < 0 then + node.matrix = { + R[1][1], R[2][1], R[3][1], 0, + R[1][2], R[2][2], R[3][2], 0, + R[1][3], R[2][3], R[3][3], 0, + tx, ty, tz, 1, + } + return + end + local m00, m11, m22 = R[1][1], R[2][2], R[3][3] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(1 + m00 - m11 - m22) * 2 + w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s + elseif m11 > m22 then + local s = math.sqrt(1 + m11 - m00 - m22) * 2 + w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s + else + local s = math.sqrt(1 + m22 - m00 - m11) * 2 + w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s + end + node.rotation = { x, y, z, w } + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + node.translation = { tx, ty, tz } + end +end + +-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers +local function material(d) +local m= { type = "diffuse" } + for k, v in __iter(d) do + local key = (string.sub(k, 1, 1) == "_" and{(string.sub(k, 2) )}or{k +})[1] if key == "type" then + m.type = (string.sub(v, 1, 1) == "_" and{(string.sub(v, 2) )}or{v +})[1] else + m[key] = tonumber(v) or v + end + end + return m +end + + + + + + + + + + + +local function parse(r, opts) +local maxCells = opts and opts.maxCells or 2 ^ 27 + if r:string(4) ~= "VOX " then + return nil, Err.new(Err.CORRUPT, "bad signature", r.base) + end + local version = r:u32le() + if r:string(4) ~= "MAIN" then + if r.err then + return nil, r.err + end + return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8) + end + local mainN, mainM = r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if mainN < 0 or mainM < 0 or not r:skip(mainN) then + return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12) + end + local out= { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 } + local meta = out.meta + local unknown= {} + local layers, robjs, cams = {}, {}, {} + local stop = r:tell() + mainM + if stop > r:size() then + return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16) + end + local pending= nil + local cells = 0 + while r:tell() + 12 <= stop do + local at = r:tell() + local id = r:string(4) + local n, m = r:i32le(), r:i32le() + if n < 0 or m < 0 then + return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at) + elseif n > stop - r:tell() or m > stop - r:tell() - n then + return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at) + end + local c = r:slice(n) + if id == "SIZE" then + local sx, sy, sz = c:i32le(), c:i32le(), c:i32le() + if c.err or sx < 1 or sy < 1 or sz < 1 then + return nil, Err.new(Err.CORRUPT, "bad model size", at) + end + cells =cells+ sx * sy * sz + if cells > maxCells then + return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at) + end + pending = { sx, sy, sz } + elseif id == "XYZI" then + local size = pending + if not size then + return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at) + end + pending = nil + local count = c:i32le() + if c.err or count < 0 or count * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad voxel count", at) + end + local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE) + out.skipped =out.skipped+ Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count) + table.insert(out.models, v) + elseif id == "RGBA" then + if n < 1024 then + return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at) + end + local pal = (table.create(255) ) +for i = 1, 255 do + pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() } + end + out.palette = pal + elseif id == "MATL" then + local mid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at) + end + out.materials[mid] = material(d) + elseif id == "nTRN" then + local node= { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() } + c:i32le() -- reserved + node.layer = c:i32le() + local nf = c:i32le() + if c.err or nf < 0 or nf * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at) + end + local frames = {} + for k = 1, nf do + frames[k] = dict(c) + end + node.frames = frames + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at) + end + out.graph[node.id] = node + elseif id == "nGRP" then + local node= { kind = id, id = c:i32le(), attrs = dict(c) } + local nc = c:i32le() + if c.err or nc < 0 or nc * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at) + end + local children = (table.create(nc) ) +for k = 1, nc do + children[k] = c:i32le() + end + node.children = children + out.graph[node.id] = node + elseif id == "nSHP" then + local node= { kind = id, id = c:i32le(), attrs = dict(c) } + local nm = c:i32le() + if c.err or nm < 0 or nm * 8 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at) + end + local models = {} + for k = 1, nm do + models[k] = { model = c:i32le() + 1, attributes = dict(c) } + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad nSHP models", at) + end + node.models = models + out.graph[node.id] = node + elseif id == "LAYR" then + local lid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at) + end + table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d }) + elseif id == "rOBJ" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at) + end + table.insert(robjs, d) + elseif id == "rCAM" then + local cid = c:i32le() + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at) + end + table.insert(cams, { id = cid, attributes = d }) + elseif id == "NOTE" then + local nn = c:i32le() + if c.err or nn < 0 or nn * 4 > c:remaining() then + return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at) + end + local notes = table.create(nn) + for k = 1, nn do + notes[k] = str(c) + end + if c.err then + return nil, Err.new(Err.CORRUPT, "bad NOTE names", at) + end + meta.notes = notes + elseif id == "IMAP" then + local map = {} + for k = 1, math.min(n, 256) do + map[k] = c:u8() + end + meta.indexMap = map + elseif id == "META" then + local d = dict(c) + if c.err then + return nil, Err.new(Err.CORRUPT, "bad META chunk", at) + end + meta.info = d + else + if id == "PACK" then + meta.pack = c:i32le() + end + table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil }) + end + if m > 0 then + local kids = r:bytes(math.min(m, r:remaining())) + if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then + unknown[#unknown].children = kids + end + end + if r.err then + return nil, r.err + end + end + if r:tell() < stop then + return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell()) + end + if #out.models == 0 then + return nil, Err.new(Err.CORRUPT, "no models") + end + if #layers > 0 then + meta.layers = layers + end + if #robjs > 0 then + meta.renderObjects = robjs + end + if #cams > 0 then + meta.cameras = cams + end + if #unknown > 0 then + meta.chunks = unknown + end + return out, nil +end + +-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node) +local function build(scene, graph, id, depth, visiting, nmodels) +local t = graph[id] + if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then + return nil + end + visiting[id] = true + local node= { name = t.attrs._name, children = {} } + local index = #scene.nodes + 1 + scene.nodes[index] = node + local frames = t.frames or {} + if frames[1] then + applyFrame(node, frames[1]) + end + local vox= { attributes = t.attrs, layer = t.layer } + if #frames > 1 or (frames[1] and frames[1]._f) then + vox.frames = frames + end + node.extras = { vox = vox } + local child = (t.child and{graph[t.child] }or{nil +})[1] if child and child.kind == "nGRP" then + vox.group = child.attrs + for _, c in __iter(child.children or {}) do + local ci = build(scene, graph, c, depth + 1, visiting, nmodels) + if ci then + table.insert(node.children, ci) + end + end + elseif child and child.kind == "nSHP" then + local models = child.models or {} + vox.shape = { attributes = child.attrs, models = models } + local first = models[1] + if first and first.model >= 1 and first.model <= nmodels then + node.voxels = first.model + end + end + visiting[id] = nil + return index +end + +-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err +function Vox.decodeVoxels(r, opts) +local p, err = parse(r, opts) + if not p then + return nil, err + end + local pal = p.palette or DEFAULT_PALETTE + local mats = (next(p.materials) and{p.materials }or{nil +})[1] for _, v in __iter(p.models) do + v.palette = pal + v.materials = mats + end + return p.models, nil +end + +function Vox.decode(r, opts) +local p, err = parse(r, opts) + if not p then + return nil, err + end + local scene = Types.Scene.new() + local pal = p.palette or DEFAULT_PALETTE + local mats = (next(p.materials) and{p.materials }or{nil +})[1] for _, v in __iter(p.models) do + v.palette = pal + v.materials = mats + end + scene.voxels = p.models + if p.graph[0] then + local root = build(scene, p.graph, 0, 0, {}, #p.models) + if root then + scene.roots = { root } + end + end + if #scene.nodes == 0 then + -- no scene graph (version 150 files): one node per model + for i = 1, #p.models do + scene.nodes[i] = { children = {}, voxels = i } + scene.roots[i] = i + end + end + scene.meta.up = "z" + scene.meta.vox = p.meta + scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function number(v) +if type(v) ~= "number" then + return tostring(v) + end + if v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return string.format("%d", v) + end + for _, f in __iter({ "%.6g", "%.9g", "%.17g" }) do + local s = string.format(f, v) + if tonumber(s) == v then + return s + end + end + return string.format("%.17g", v) +end + +local function sortedKeys(d) +local keys = {} + for k in __iter(d) do + if type(k) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + return keys +end + +local function wstr(w, s) + w:u32le(#s) + w:string(s) +end + +local function wdict(w, d) + if not d then + w:u32le(0) + return + end + local keys = sortedKeys(d) + w:u32le(#keys) + for _, k in __iter(keys) do + wstr(w, k) + wstr(w, number(d[k])) + end +end + +-- a node's transform as a frame dictionary (_r, _t) | nil, message +local function frameOf(node, base) +local f= {} + if base then + for k, v in __iter(base) do + if k ~= "_r" and k ~= "_t" then + f[k] = v + end + end + end + local m = Types.Scene.nodeMatrix(node) + local cols, signs = {}, {} + for row = 0, 2 do + local best, bv, rest = 0, 0, 0 + for col = 0, 2 do + local v = m[col * 4 + row + 1] + if math.abs(v) > math.abs(bv) then + rest = math.max(rest, math.abs(bv)) + best, bv = col, v + else + rest = math.max(rest, math.abs(v)) + end + end + if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then + return nil, "node rotation is not a multiple of 90 degrees (or has a scale)" + end + table.insert(cols, best) + signs[row + 1] = bv < 0 and 1 or 0 + end + local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64 + if rb ~= IDENTITY_R then + f._r = tostring(rb) + end + local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5) + if tx ~= 0 or ty ~= 0 or tz ~= 0 then + f._t = string.format("%d %d %d", tx, ty, tz) + end + return f, nil +end + + + +function Vox.encode(value, opts) +local version = opts and opts.version or 200 + if type(version) ~= "number" or version < 0 then + return nil, Err.new(Err.ARG, "bad version") + end + if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local scene +if value.kind == "voxels" then + scene = Types.Scene.new() + scene.voxels = { value } + scene.nodes[1] = { children = {}, voxels = 1 } + scene.roots[1] = 1 + elseif value.kind == "scene" then + scene = value + else + return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid") + end + local models = scene.voxels + if type(models) ~= "table" or #models == 0 then + return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)") + end + for i, v in __iter(models) do + local s = v.size + if type(s) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid") + end + for k = 1, 3 do + if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis") + end + end + if buffer.len(v.data) < s[1] * s[2] * s[3] then + return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid") + end + end + local meta= (type(scene.meta) == "table" and type(scene.meta.vox) == "table" and{scene.meta.vox }or{{} +})[1] local w = Bytes.writer(65536) + w:string("VOX ") + w:u32le(version) + w:string("MAIN") + w:u32le(0) + local mAt = w:tell() + w:u32le(0) + local function chunk(id, body) + w:string(id) + local at = w:tell() + w:u32le(0) + w:u32le(0) + body() + w:setU32le(at, w:tell() - at - 8) + end + if type(meta.info) == "table" then + chunk("META", function() + wdict(w, meta.info) + end) + end + -- models + for _, v in __iter(models) do + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + chunk("SIZE", function() + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + end) + local count = Grid.count(v.data, sx * sy * sz) + chunk("XYZI", function() + w:u32le(count) + local at = w:reserve(count * 4) + Grid.write(w.buf, at, v.data, sx, sy, sz) + w.pos = at + count * 4 + end) + end + -- the scene graph + local records= {} + local nextId = 0 + local function alloc() +local id = nextId + nextId =nextId+ 1 + return id + end + local nodes = scene.nodes or {} + local visiting= {} + local failure= nil + local function shape(model, vx) +local id = alloc() + local ms= {} + local saved = vx and vx.shape + if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then + for _, sm in __iter(saved.models) do + if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then + table.insert(ms, { model = sm.model - 1, attributes = sm.attributes }) + end + end + end + if #ms == 0 then + ms[1] = { model = model - 1, attributes = nil } + end + table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms }) + return id + end + local function visit(index, depth, layer) +local node = nodes[index] + if not node or visiting[index] or depth > MAX_DEPTH then + failure = failure or "the node tree has a loop or is too deep" + return nil + end + visiting[index] = true + local vx = (type(node.extras) == "table" and type(node.extras.vox) == "table" and{node.extras.vox }or{nil +})[1] local id = alloc() + local attrs= {} + if vx and type(vx.attributes) == "table" then + for k, v in __iter(vx.attributes) do + attrs[k] = v + end + end + attrs._name = node.name + local saved = vx and type(vx.frames) == "table" and vx.frames or nil + local f, ferr = frameOf(node, saved and saved[1]) + if not f then + failure = failure or ferr + f = {} + end + local frames = { f } + if saved then + for k = 2, #saved do + frames[k] = saved[k] + end + end + local rec= { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames } + table.insert(records, rec) + local kids = node.children or {} + local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models + if hasVox and #kids == 0 then + rec.child = shape(node.voxels , vx) + else + local gid = alloc() + local grp= { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} } + table.insert(records, grp) + rec.child = gid + if hasVox then + local tid = alloc() + local t2= { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } } + table.insert(records, t2) + table.insert(grp.children , tid) + t2.child = shape(node.voxels , vx) + end + for _, c in __iter(kids) do + local cid = visit(c, depth + 1, nil) + if cid then + table.insert(grp.children , cid) + end + end + end + visiting[index] = nil + return id + end + local roots = scene.roots or {} + local single = (#roots == 1 and{nodes[roots[1] ] }or{nil +})[1] if single and single.voxels == nil then + visit(roots[1], 0, -1) + elseif #roots > 0 then + local rid = alloc() + local gid = alloc() + local rec= { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } } + local grp= { kind = "nGRP", id = gid, attrs = nil, children = {} } + table.insert(records, rec) + table.insert(records, grp) + for _, ri in __iter(roots) do + local cid = visit(ri, 1, nil) + if cid then + table.insert(grp.children , cid) + end + end + end + if failure then + return nil, Err.new(Err.ARG, failure) + end + for _, rec in __iter(records) do + chunk(rec.kind, function() + w:u32le(rec.id) + wdict(w, rec.attrs) + if rec.kind == "nTRN" then + w:u32le(rec.child or 0) + w:u32le(0xFFFFFFFF) + w:u32le((rec.layer or 0) % 4294967296) + local frames = rec.frames or { {} } + w:u32le(#frames) + for _, f in __iter(frames) do + wdict(w, f) + end + elseif rec.kind == "nGRP" then + local ch = rec.children or {} + w:u32le(#ch) + for _, c in __iter(ch) do + w:u32le(c) + end + else + local ms = rec.models or {} + w:u32le(#ms) + for _, sm in __iter(ms) do + w:u32le(sm.model) + wdict(w, sm.attributes) + end + end + end) + end + -- layers + if type(meta.layers) == "table" then + for _, l in __iter(meta.layers) do + chunk("LAYR", function() + w:u32le(tonumber(l.id) or 0) + local d= {} + if type(l.attributes) == "table" then + for k, v in __iter(l.attributes) do + d[k] = v + end + end + d._name = l.name + d._hidden = l.hidden and"1" or(d._hidden ~= nil and"0" or nil +) wdict(w, d) + w:u32le(0xFFFFFFFF) + end) + end + end + -- palette + local pal = models[1].palette or DEFAULT_PALETTE + chunk("RGBA", function() + for i = 1, 256 do + local c = pal[i] + if type(c) == "table" then + w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255)) + w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255)) + else + w:u32le(0) + end + end + end) + if type(meta.indexMap) == "table" then + chunk("IMAP", function() + for k = 1, 256 do + w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255)) + end + end) + end + -- materials + local mats = models[1].materials + if type(mats) == "table" then + local ids = {} + for id in __iter(mats) do + if type(id) == "number" then + table.insert(ids, id) + end + end + table.sort(ids) + for _, id in __iter(ids) do + local m = mats[id] + chunk("MATL", function() + w:u32le(id) + local d= { _type = "_" .. tostring(m.type or "diffuse") } + for k, v in __iter(m) do + if k ~= "type" and type(k) == "string" then + d["_" .. k] = v + end + end + wdict(w, d) + end) + end + end + if type(meta.renderObjects) == "table" then + for _, d in __iter(meta.renderObjects) do + chunk("rOBJ", function() + wdict(w, d) + end) + end + end + if type(meta.cameras) == "table" then + for _, cam in __iter(meta.cameras) do + chunk("rCAM", function() + w:u32le(tonumber(cam.id) or 0) + wdict(w, cam.attributes) + end) + end + end + if type(meta.notes) == "table" then + chunk("NOTE", function() + w:u32le(#meta.notes) + for _, s in __iter(meta.notes) do + wstr(w, tostring(s)) + end + end) + end + if type(meta.chunks) == "table" then + for _, u in __iter(meta.chunks) do + if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then + w:string(u.id) + w:u32le(buffer.len(u.content)) + w:u32le((u.children and{(buffer.len(u.children) )}or{0})[1]) + w:bytes(u.content) + if u.children then + w:bytes(u.children) + end + end + end + end + w:setU32le(mAt, w:tell() - mAt - 4) + return w:finish(), nil +end + +return Vox +end +__FILES["model/vox/Grid"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI +-- records. Callers check every range first; nothing here throws. +local Grid = {} + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the +-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted. +-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz. +function Grid.fill(dst, sx, sy, sz, src, off, n) +local skipped = 0 + local sxy = sx * sy + for k = 0, n - 1 do + local p = off + k * 4 + local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3) + if x < sx and y < sy and z < sz and i ~= 0 then + writeu8(dst, x + sx * y + sxy * z, i) + else + skipped =skipped+ 1 + end + end + return skipped +end + +-- count(data, cells) -> the number of non-empty cells in data[0, cells) +function Grid.count(data, cells) +local n = 0 + for k = 0, cells - 1 do + if readu8(data, k) ~= 0 then + n =n+ 1 + end + end + return n +end + +-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest). +-- The caller sizes dst with count() (sx, sy, sz <= 256). +function Grid.write(dst, at, data, sx, sy, sz) +local p = at + local k = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local i = readu8(data, k) + if i ~= 0 then + writeu8(dst, p, x) + writeu8(dst, p + 1, y) + writeu8(dst, p + 2, z) + writeu8(dst, p + 3, i) + p =p+ 4 + end + k =k+ 1 + end + end + end + return p +end + +return Grid +end +__FILES["model/vrml"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over +-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. +-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, +-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and +-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, +-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), +-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated +-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> +-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons +-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless +-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). +-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / +-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, +-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). +-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and +-- skins on write (the rest pose is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + +function Wrl.sniff(r) +local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return string.sub(head, 1, 10) == "#VRML V2.0" and 1 or(string.sub(head, 1, 6) == "#VRML " and 0.6 or 0 +)end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r, opts) +local o= table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene, opts) +local o= table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl +end +__FILES["model/x"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", +-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format +-- specification and the standard templates, checked against assimp's X importer and test models. +-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per +-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal +-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global +-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, +-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), +-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four +-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, +-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. +-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. +-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in +-- meta.source.skippedFaces). +-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key +-- interpolation options (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Deflate = __include("codecs/compress/Deflate") +local Parse = __include("model/x/Parse") +local Build = __include("model/x/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local X = { + name = "x", + category = "model", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + +local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" } + +-- ------------------------------------------------------------------------------------------------ sniff +function X.sniff(r) +if r:peek(4) ~= "xof " then + return 0 + end + return ENCODINGS[r:peek(4, 8)] and 1 or 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size, +-- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may +-- refer back into the previous block's output). +local function mszip(b, p, limit, maxBytes) +if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) + end + local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p) + end + p =p+ 4 + local spans= {} + local o = 0 + while p + 6 <= limit and o < total do + local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2) + if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then + return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p) + end + if o + usize > total then + return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p) + end + table.insert(spans, { offset = p + 4, length = math.min(csize, limit - p - 4), size = usize }) + o =o+ usize + p =p+ (4 + csize +) end + if o < total then + return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p) + end + local out, err = Deflate.mszip(b, spans) + if not out then + return nil, Err.new((err ).code, "MSZIP: " .. (err ).message, (err ).offset) + end + return out, nil +end + +function X.decode(r, opts) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < 16 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", base) + end + if buffer.readstring(b, base, 4) ~= "xof " then + return nil, Err.new(Err.CORRUPT, "no xof header", base) + end + local enc = buffer.readstring(b, base + 8, 4) + local kind = ENCODINGS[enc] + if not kind then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8) + end + local bits = buffer.readstring(b, base + 12, 4) + local floatSize = bits == "0064" and 8 or(bits == "0032" and 4 or 0 +) if floatSize == 0 then + return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12) + end + local data, from, to= b, base + 16, limit + if enc == "tzip" or enc == "bzip" then + local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30) + if not inflated then + return nil, err + end + data, from, to = inflated, 0, buffer.len(inflated) + end + local maxValues= opts and opts.maxValues or 2 ^ 27 + local ok, root, msg = pcall(Parse.tree, data, from, to , kind == "binary", floatSize, maxValues) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root)) + end + if not root then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, root, opts) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + local src = scene.meta.source +src.version = buffer.readstring(b, base + 4, 4) + src.encoding = kind + src.compressed = enc == "tzip" or enc == "bzip" + src.floatSize = floatSize * 8 + return scene, nil +end + +return X +end +__FILES["model/x/Build"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is +-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding +-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). +-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep +-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Parse = __include("model/x/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 +-- a cursor over an object's flattened values + + + + +local function num(c) +local x = c.v[c.i] + c.i =c.i+ 1 + if type(x) ~= "number" then + error("expected a number in the data", 0) + end + return x +end +local function str(c) +local x = c.v[c.i] + c.i =c.i+ 1 + if type(x) ~= "string" then + error("expected a string in the data", 0) + end + return x +end +-- a non-negative integer (an index) +local function index(c, limit) +local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad index " .. n, 0) + end + return n +end + +-- a count of items that follow (each takes at least one value: a count past the data is refused before anything +-- is allocated for it) +local function count(c, limit) +local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad count " .. n, 0) + end + if n > #c.v - c.i + 1 then + error("truncated: a count of " .. n .. " runs past the data", 0) + end + return n +end + +-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +local function mirror(m) +local o = table.clone(m) + for _, k in __iter({ 3, 7, 9, 10, 12, 15 }) do + o[k] = -o[k] + end + return o +end + +local function matrix(c) +local m = (table.create(16) ) +for k = 1, 16 do + m[k] = num(c) + end + return mirror(m) +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME= { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function material(scene, node, texCache) +local c= { v = node.vals, i = 1 } + local mat = Scene.material(node.name) + local r, g, b, a = num(c), num(c), num(c), num(c) + local power = num(c) + local sr, sg, sb = num(c), num(c), num(c) + local er, eg, eb = num(c), num(c), num(c) + mat.baseColor = { r, g, b, a } + if a < 1 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1) + mat.emissive = { er, eg, eb } + local textures = {} + for _, k in __iter(node.kids) do + local lt = string.lower(k.type) + if lt == "texturefilename" or lt == "normalmapfilename" then + local path = k.vals[1] + if type(path) == "string" and path ~= "" then + path = string.gsub(path, "\\\\", "\\") + local uri = string.gsub(path, "\\", "/") + local ti = texCache[uri] + if not ti then + local base = string.match(uri, "([^/]+)$") or uri + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] }) + ti = #scene.textures + texCache[uri] = ti + end + table.insert(textures, uri) + if lt == "normalmapfilename" then + mat.normalTexture = mat.normalTexture or { texture = ti } + else + mat.baseColorTexture = mat.baseColorTexture or { texture = ti } + end + end + end + end + mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } } + return mat +end +-- ------------------------------------------------------------------------------------------------ meshes + + + + + + + + + + + + +local function accessorF32(values, comps) +local n = #values + local b = buffer.create(n * 4) + for i = 1, n do + writef32(b, (i - 1) * 4, values[i]) + end + return Scene.accessor(b, "f32", comps, math.floor(n / comps)) +end + +-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) +local function mesh(ctx, m, triangulate) +local scene = ctx.scene + local c= { v = m.vals, i = 1 } + local nv = count(c, ctx.maxVertices) + local pos = (table.create(nv * 3) ) +for k = 1, nv * 3 do + pos[k] = num(c) + end + local nf = count(c, ctx.maxVertices) + local faces = (table.create(nf) ) +local corners = 0 + for f = 1, nf do + local n = count(c, ctx.maxVertices) + corners =corners+ n + if corners > ctx.maxVertices then + error("limit: more than " .. ctx.maxVertices .. " face corners", 0) + end + local face = (table.create(n) ) +for k = 1, n do + local idx = index(c, 2 ^ 32) + if idx >= nv then + error("face index " .. idx .. " out of range", 0) + end + face[k] = idx + end + faces[f] = face + end + -- the optional data objects + local normals= nil + local nfaces= nil + local uvSets= {} + local colors= {} + local faceMat= {} + local mats= {} + local bones= {} + for _, k in __iter(m.kids) do + local kc= { v = k.vals, i = 1 } + if k.type == "MeshNormals" then + local nn = count(kc, ctx.maxVertices) + local nr = (table.create(nn * 3) ) +for q = 1, nn * 3 do + nr[q] = num(kc) + end + local nnf = count(kc, ctx.maxVertices) + local nfs = (table.create(nnf) ) +for f = 1, nnf do + local n = count(kc, ctx.maxVertices) + local face = (table.create(n) ) +for q = 1, n do + face[q] = index(kc, 2 ^ 32) + end + nfs[f] = face + end + normals, nfaces = nr, nfs + elseif k.type == "MeshTextureCoords" then + local n = count(kc, ctx.maxVertices) + local uv = (table.create(n * 2) ) +for q = 1, n * 2 do + uv[q] = num(kc) + end + if n == nv then + table.insert(uvSets, uv) + end + elseif k.type == "MeshVertexColors" then + local n = count(kc, ctx.maxVertices) + local col = (table.create(nv * 4, 1) ) +for _ = 1, n do + local idx = index(kc, 2 ^ 32) + local r, g, b, a = num(kc), num(kc), num(kc), num(kc) + if idx < nv then + col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a + end + end + table.insert(colors, col) + elseif k.type == "MeshMaterialList" then + num(kc) -- material count (the objects below are authoritative) + local ni = count(kc, ctx.maxVertices) + for q = 1, ni do + faceMat[q] = index(kc, 2 ^ 20) + end + for _, mk in __iter(k.kids) do + if mk.type == "@ref" then + table.insert(mats, (mk.name and{ctx.globalMats[mk.name] or 0 }or{0})[1]) + elseif mk.type == "Material" then + table.insert(scene.materials, material(scene, mk, ctx.texCache)) + table.insert(mats, #scene.materials) + end + end + elseif k.type == "SkinWeights" then + local name = str(kc) + local n = count(kc, ctx.maxVertices) + local verts = (table.create(n) ) +for q = 1, n do + verts[q] = index(kc, 2 ^ 32) + end + local weights = (table.create(n) ) +for q = 1, n do + weights[q] = num(kc) + end + table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) + end + end + -- material per face (a single index applies to every face) + local function matOf(f) +local mi = (#faceMat == 1 and{faceMat[1] }or{faceMat[f] +})[1] return (mi and((mi + 1 ))or(1 +)) end + -- unique vertices per (position, normal index) + local key= {} + local srcPos= {} + local srcNrm= {} + local groups= {} + local order= {} + local faceSizes= {} + local nNormals = (normals and{(math.floor(#normals / 3 ))}or{0 +})[1] for f, face in __iter(faces) do + local n = #face + if n < 3 then + ctx.skippedFaces =ctx.skippedFaces+ 1 + else + local nface = nfaces and nfaces[f] + local vs = (table.create(n) ) +for k = 1, n do + local src = k == 1 and 1 or n - k + 2 -- winding reversed, first corner kept + local p = face[src] + local q = (nface and nface[src] and nface[src] < nNormals and{nface[src] }or{(-1 +)})[1] local kk = p * (nNormals + 1) + q + 1 + local v = key[kk] + if not v then + table.insert(srcPos, p) + table.insert(srcNrm, q) + v = #srcPos - 1 + key[kk] = v + end + vs[k] = v + end + local mi = matOf(f) + local g = groups[mi] + if not g then + g = {} + groups[mi] = g + faceSizes[mi] = {} + table.insert(order, mi) + end + if triangulate then + for k = 2, n - 1 do + table.insert(g, vs[1]) + table.insert(g, vs[k]) + table.insert(g, vs[k + 1]) + end + else + table.move(vs, 1, n, #g + 1, g) + table.insert(faceSizes[mi], n) + end + end + end + if #order == 0 then + return nil, nil + end + table.sort(order) + -- shared vertex attributes (one vertex buffer for every primitive of the mesh) + local nout = #srcPos + local P = (table.create(nout * 3) ) +for v = 1, nout do + local p = srcPos[v] * 3 + P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3] + end + local attributes= { POSITION = accessorF32(P, 3) } + if normals then + local N = (table.create(nout * 3, 0) ) +for v = 1, nout do + local q = srcNrm[v] + if q >= 0 then + N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3] + end + end + attributes.NORMAL = accessorF32(N, 3) + end + for s, uv in __iter(uvSets) do + local U = (table.create(nout * 2) ) +for v = 1, nout do + local p = srcPos[v] * 2 + U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2] + end + attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2) + end + for s, col in __iter(colors) do + local C = (table.create(nout * 4) ) +for v = 1, nout do + local p = srcPos[v] * 4 + C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4] + end + attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4) + end + if #bones > 0 then + local lists = (table.create(nout) ) +local byPos= {} + for j, bone in __iter(bones) do + for q, vi in __iter(bone.verts) do + local l = byPos[vi] + if not l then + l = {} + byPos[vi] = l + end + table.insert(l, j - 1) + table.insert(l, bone.weights[q] or 0) + end + end + for v = 1, nout do + lists[v] = byPos[srcPos[v] ] or {} + end + attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists) + end + local skinBones= nil + if #bones > 0 then + local list= {} + for _, bone in __iter(bones) do + table.insert(list, { name = bone.name, matrix = bone.matrix }) + end + skinBones = list + end + local prims= {} + for _, mi in __iter(order) do + local idx = groups[mi] + local ib = buffer.create(#idx * 4) + for k, x in __iter(idx) do + writeu32(ib, (k - 1) * 4, x) + end + local prim= { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" } + local mat = mats[mi] + prim.material = (mat and mat > 0 and{mat }or{nil +})[1] if not triangulate then + prim.mode = "polygons" + local fs = faceSizes[mi] + local fb = buffer.create(#fs * 4) + for k, x in __iter(fs) do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #fs) + end + table.insert(prims, prim) + end + table.insert(scene.meshes, { name = m.name, primitives = prims }) + return #scene.meshes, skinBones +end + +-- ------------------------------------------------------------------------------------------------ frames +local function frame(ctx, f, parent, triangulate, depth) + if depth > 200 then + error("frames nested too deep", 0) + end + local scene = ctx.scene + local node= { name = f.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + if f.name and ctx.nodeByName[f.name] == nil then + ctx.nodeByName[f.name] = ni + end + if parent then + table.insert(scene.nodes[parent].children, ni) + else + table.insert(scene.roots, ni) + end + local first = true + for _, k in __iter(f.kids) do + if k.type == "FrameTransformMatrix" then + local m = matrix({ v = k.vals, i = 1 }) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + else + node.matrix = m + end + elseif k.type == "Mesh" then + -- the first mesh on the frame's node, more as child nodes + local mi, bones = mesh(ctx, k, triangulate) + if mi then + local holder = ni + if first then + node.mesh = mi + first = false + else + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + holder = #scene.nodes + table.insert(node.children, holder) + end + if bones then + table.insert(ctx.pendingSkins, { node = holder, bones = bones }) + end + end + elseif k.type == "Frame" then + frame(ctx, k, ni, triangulate, depth + 1) + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +local function channel(input, output, comps, node, path) +return { node = node, path = path , input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" } +end + +local function animationSet(ctx, set, tps) +local channels= {} + for _, a in __iter(set.kids) do + if a.type == "Animation" then + local target= nil + for _, k in __iter(a.kids) do + if k.type == "@ref" then + target = k.name + end + end + local node = target and ctx.nodeByName[target] + if node then + for _, k in __iter(a.kids) do + if k.type == "AnimationKey" then + local c= { v = k.vals, i = 1 } + local kind = num(c) + local nk = count(c, ctx.maxVertices) + local times = (table.create(nk) ) +local T, R, S = {}, {}, {} + for q = 1, nk do + times[q] = num(c) / tps + local nvals = count(c, 16) + if kind == 0 and nvals == 4 then + local w, x, y, z = num(c), num(c), num(c), num(c) + -- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y + table.move({ x, y, -z, w }, 1, 4, #R + 1, R) + elseif (kind == 1 or kind == 2) and nvals == 3 then + local x, y, z = num(c), num(c), num(c) + if kind == 1 then + table.move({ x, y, z }, 1, 3, #S + 1, S) + else + table.move({ x, y, -z }, 1, 3, #T + 1, T) + end + elseif (kind == 3 or kind == 4) and nvals == 16 then + local t, r, s = Mat4.decompose(matrix(c)) + table.move(t, 1, 3, #T + 1, T) + table.move(r, 1, 4, #R + 1, R) + table.move(s, 1, 3, #S + 1, S) + else + error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0) + end + end + if #T == nk * 3 and nk > 0 then + table.insert(channels, channel(times, T, 3, node, "translation")) + end + if #R == nk * 4 and nk > 0 then + table.insert(channels, channel(times, R, 4, node, "rotation")) + end + if #S == nk * 3 and nk > 0 then + table.insert(channels, channel(times, S, 3, node, "scale")) + end + end + end + end + end + end + if #channels == 0 then + return nil + end + return { name = set.name, channels = channels } +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(root, opts) +local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + local ctx= { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 } + local tps = 4800 + for _, k in __iter(root.kids) do + if k.type == "Material" then + table.insert(scene.materials, material(scene, k, ctx.texCache)) + if k.name then + ctx.globalMats[k.name] = #scene.materials + end + elseif k.type == "AnimTicksPerSecond" then + local v = k.vals[1] + if type(v) == "number" and v > 0 then + tps = v + end + end + end + for _, k in __iter(root.kids) do + if k.type == "Frame" then + frame(ctx, k, nil, triangulate, 0) + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + table.insert(scene.roots, #scene.nodes) + if bones then + table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones }) + end + end + end + -- skins: bone names -> frames + for _, ps in __iter(ctx.pendingSkins) do + local joints= {} + local ibm = buffer.create(#ps.bones * 64) + for j, bone in __iter(ps.bones) do + local ni = ctx.nodeByName[bone.name] + if not ni then + -- a bone without a frame: an extra root node keeps the joint numbering + table.insert(scene.nodes, { name = bone.name, children = {} }) + ni = #scene.nodes + table.insert(scene.roots, ni) + ctx.nodeByName[bone.name] = ni + end + joints[j] = ni + for k = 1, 16 do + writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, #ps.bones) + acc.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc }) + scene.nodes[ps.node].skin = #scene.skins + end + for _, k in __iter(root.kids) do + if k.type == "AnimationSet" then + local anim = animationSet(ctx, k, tps) + if anim then + table.insert(scene.animations, anim) + end + end + end + scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces } + return scene, nil +end + +return Build +end +__FILES["model/x/Parse"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the +-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and +-- binary tokens), checked against what assimp's XFileParser accepts (no code taken). +-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and +-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), +-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. +-- Text: ; and , separators, // and # comments, quoted strings, <guid>s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). +-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and +-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Parse = {} + + + +local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring +-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), +-- "punct", "eof"; err holds a message after a bad token + + + +local KEYWORDS= { + [0x1F] = "template", + [0x28] = "WORD", + [0x29] = "DWORD", + [0x2A] = "FLOAT", + [0x2B] = "DOUBLE", + [0x2C] = "CHAR", + [0x2D] = "UCHAR", + [0x2E] = "SWORD", + [0x2F] = "SDWORD", + [0x30] = "void", + [0x31] = "string", + [0x32] = "unicode", + [0x33] = "cstring", + [0x34] = "array", +} + +-- ------------------------------------------------------------------------------------------------ text +local function textLexer(s) +local lex= { next = nil , err = nil } + local p = 1 + local n = #s + lex.next = function() +while true do + local _, e = string.find(s, "^[%s,;]+", p) + if e then + p = e + 1 + end + if p > n then + return "eof", nil + end + local c = string.byte(s, p) + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + local nl = string.find(s, "[\r\n]", p) + p = (nl and((nl + 1 ))or((n + 1 +))) else + break + end + end + local c = string.byte(s, p) + if c == 123 then + p =p+ 1 + return "{", nil + elseif c == 125 then + p =p+ 1 + return "}", nil + elseif c == 34 then + local q = string.find(s, '"', p + 1, true) + if not q then + lex.err = "unterminated string" + p = n + 1 + return "eof", nil + end + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "str", v + elseif c == 60 then + local q = string.find(s, ">", p + 1, true) or n + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "guid", v + end + local _, e = string.find(s, '^[^%s,;{}"]+', p) + local tok = string.sub(s, p, e ) + p = (e ) + 1 + if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + return "num", tonumber(tok) or 0 + end + return "id", tok + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ binary +local function binaryLexer(b, from, limit, floatSize) +local lex= { next = nil , err = nil } + local p = from + local function fail(msg) +lex.err = msg + p = limit + return "eof", nil + end + lex.next = function() +if p + 2 > limit then + return "eof", nil + end + local tok = readu16(b, p) + p =p+ 2 + if tok == 0x0A then + return "{", nil + elseif tok == 0x0B then + return "}", nil + elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token) + if p + 4 > limit then + return fail("truncated name") + end + local len = readu32(b, p) + p =p+ 4 + if len > limit - p then + return fail("truncated name") + end + local v = readstring(b, p, len) + p =p+ len + if tok == 2 then + p = math.min(p + 2, limit) + return "str", v + end + return "id", v + elseif tok == 3 then + if p + 4 > limit then + return fail("truncated integer") + end + local v = readu32(b, p) + p =p+ 4 + return "num", v + elseif tok == 5 then + if p + 16 > limit then + return fail("truncated guid") + end + p =p+ 16 + return "guid", "" + elseif tok == 6 or tok == 7 then + if p + 4 > limit then + return fail("truncated list") + end + local count = readu32(b, p) + p =p+ 4 + local size = tok == 6 and 4 or floatSize + if count > math.floor((limit - p) / size )then + return fail("truncated list") + end + local out = (table.create(count) ) +if tok == 6 then + for i = 1, count do + out[i] = readu32(b, p) + p =p+ 4 + end + elseif size == 8 then + for i = 1, count do + out[i] = readf64(b, p) + p =p+ 8 + end + else + for i = 1, count do + out[i] = readf32(b, p) + p =p+ 4 + end + end + return "list", out + elseif tok >= 0x0C and tok <= 0x14 then + return "punct", nil + elseif KEYWORDS[tok] then + return "id", KEYWORDS[tok] + end + return fail(string.format("unknown binary token 0x%x", tok)) + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ tree +local function tree(lex, maxValues) +local queue= {} + local function take() +local q = table.remove(queue, 1) + if q then + return q[1], q[2] + end + return lex.next() + end + local function peek(k) +while #queue < k do + local kind, v = lex.next() + table.insert(queue, { kind, v }) + if kind == "eof" then + break + end + end + local q = queue[k] + return (q and{q[1] }or{"eof" +})[1] end + local budget = maxValues + -- skips a template / unknown block whose "{" was just read + local function skipBlock() +local depth = 1 + while depth > 0 do + local kind = take() + if kind == "eof" then + return "unexpected end of file in a template" + elseif kind == "{" then + depth =depth+ 1 + elseif kind == "}" then + depth =depth- 1 + end + end + return nil + end + local body -- an object whose type token was read: [name] { ... } + +local function object(parent, typ, depth) +local name= nil + local kind, v = take() + if kind ~= "{" then + name = (v ~= nil and{(tostring(v) )}or{nil +})[1] kind = take() + if kind ~= "{" then + return "expected { after " .. typ + end + end + if typ == "template" then + return skipBlock() + end + local node= { type = typ, name = name, vals = {}, kids = {} } + table.insert(parent.kids, node) + return body(node, depth + 1) + end + body = function(node, depth) +if depth > 200 then + return "objects nested too deep" + end + local vals = node.vals + while true do + local kind, v = take() + if kind == "}" then + return nil + elseif kind == "eof" then + return (depth == 0 and{nil }or{("unexpected end of file in " .. node.type +)})[1] elseif kind == "num" or kind == "str" then + budget =budget- 1 + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + vals[#vals + 1] = v + elseif kind == "list" then + budget =budget- #v + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + table.move(v, 1, #v, #vals + 1, vals) + elseif kind == "{" then + -- a reference: { name [guid] } + local ref= { type = "@ref", name = nil, vals = {}, kids = {} } + while true do + local k2, v2 = take() + if k2 == "}" then + break + elseif k2 == "eof" then + return "unexpected end of file in a reference" + elseif (k2 == "id" or k2 == "num") and ref.name == nil then + ref.name = tostring(v2) + end + end + table.insert(node.kids, ref) + elseif kind == "id" then + local k1 = peek(1) + if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then + local err = object(node, v, depth) + if err then + return err + end + end + -- a lone identifier (an enum value): ignored + end + -- guid / punct: ignored + if lex.err then + return lex.err + end + end + end + local root= { type = "@root", name = nil, vals = {}, kids = {} } + local err = body(root, 0) + if err then + return nil, err + end + if lex.err then + return nil, lex.err + end + return root, nil +end + +-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message +function Parse.tree(b, from, limit, binary, floatSize, maxValues) +local lex = (binary and{(binaryLexer(b, from, limit, floatSize) )}or{(textLexer(readstring(b, from, limit - from)) +)})[1] return tree(lex, maxValues) +end + +return Parse +end +__FILES["model/x3d"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, +-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). +-- New code. +-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, +-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, +-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / +-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; +-- head meta, components and UNIT length (-> meta.unit). +-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the +-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). +-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, +-- H-Anim skinning, scripts. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Vrml = __include("codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + +function X3d.sniff(r) +local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "<X3D[%s>]") or string.find(head, "<!DOCTYPE X3D", 1, true) then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function X3d.decode(r, opts) +local o= table.clone(opts or {}) + o.format = "x3d" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function X3d.encode(scene, opts) +local o= table.clone(opts or {}) + local classic = o.encoding == "x3dv" or o.format == "x3dv" or o.format == "x3dvz" + o.encoding = classic and"x3dv" or"xml" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return X3d +end +__FILES["music/669"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- music/669: Composer 669 and UNIS 669 modules ("if" / "JN"; 8 channels, 64-row patterns with their own speed and +-- break row). Ported from OpenMPT's Load_669.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "s3m" effect family with 669's quirks (flags): periods in Hz (slides +-- move the frequency 80 Hz per step, tone portamento 40 Hz), slides on every tick, auto portamentos that run until +-- the channel's next effect, a tone portamento that keeps going, frequency adjust (D), frequency vibrato (E), speed (F), +-- UNIS 669 balance slides (G) and slot retrigger (H). The tempo is fixed (78 BPM in tracker terms). +-- Not supported: UNIS 669's "super fast" speed 0, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Six69 = { + name = "669", + category = "music", + extensions = { "669" }, + mime = { "audio/x-669" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 8, 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + +local IT = Load.IT +-- the 669 effects (high nibble of the effect byte) by name +local EFFECTS = { "autoportaup", "autoportadown", "toneporta", "freqadjust", "vibrato", "speed", "panslide", "retrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +-- the 497-byte header is valid (669 has a two-byte magic only, so the rest is checked too) +local function validHeader(r) +if r:size() < 497 then + return false + end + local magic = r:peek(2) + if magic ~= "if" and magic ~= "JN" then + return false + end + local nsmp, npat, restart = r:peekU8(110), r:peekU8(111), r:peekU8(112) + if nsmp > 64 or restart >= 128 or npat > 128 then + return false + end + local bad = 0 + for i = 2, 109 do + local c = r:peekU8(i) + if c > 0 and c <= 31 then + bad =bad+ 1 + if bad > 40 then + return false + end + end + end + for i = 0, 127 do + local o, t, b = r:peekU8(113 + i), r:peekU8(241 + i), r:peekU8(369 + i) + if (o >= 128 and o < 0xFE) or (o < 128 and t == 0) or t > 15 or b >= 64 then + return false + end + end + return true +end + +function Six69.sniff(r) +return validHeader(r) and 0.6 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Six69.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new((r:size() < 497 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a 669 module") + end + local extended = r:peek(2) == "JN" + r:skip(2) + local message = r:string(108) + local nsmp, npat, restart = r:u8(), r:u8(), r:u8() + local orders, tempos, breaks = {}, {}, {} + for i = 1, 128 do + orders[i] = r:u8() + end + for i = 1, 128 do + tempos[i] = r:u8() + end + for i = 1, 128 do + breaks[i] = r:u8() + end + if not r:need(nsmp * 25 + npat * 1536) then + return nil, r.err + end + local m = Tracker.newModule("669", 8, "s3m") + m.title = (string.gsub(string.sub(message, 1, 36), "[%z ]+$", "")) + m.meta.message = message + m.speed, m.tempo = 4, 78 + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide, m.flags.hzTonePorta = "hz", 20, 0.5 + m.flags.fastPortas, m.flags.autoTonePorta, m.flags.autoReset = true, true, true + for i = 1, 8 do + m.channelPan[i] = i % 2 == 0 and 0xD0 or 0x30 + end + local lengths= {} + for i = 1, nsmp do + local s = Tracker.newSample(r:fixed(13)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + if len >= 0x4000000 then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. " too long") + end + s.c5speed = 8363 + if not (le > len and ls == 0) and le ~= 0 then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + lengths[i] = len + m.samples[i] = s + end + for i = 1, 128 do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + if orders[restart + 1] < npat then + m.restart = restart + end + -- patterns: 64 rows x 8 channels x 3 bytes (note / instrument, instrument / volume, effect / parameter) + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 8) + m.patterns[p + 1] = pat + local d = pat.data + local effect = table.create(8, 0xFF) -- the last effect per channel (balance slides repeat) + for row = 0, 63 do + for ch = 0, 7 do + local o = r.pos + (row * 8 + ch) * 3 + local ni, iv, ep = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * 8 + ch) * 5 + local hasNote = ni < 0xFE + if hasNote then + buffer.writeu8(d, q, math.floor(ni / 4 )+ 37) + buffer.writeu8(d, q + 1, (ni % 4) * 16 + math.floor(iv / 16 )+ 1) + effect[ch + 1] = 0xFF + end + if ni <= 0xFE then + buffer.writeu8(d, q + 2, math.floor(((iv % 16) * 64 + 8) / 15 )+ 1) + end + if ep ~= 0xFF then + effect[ch + 1] = ep + end + local e = effect[ch + 1] + if e ~= 0xFF then + local cmd, param = math.floor(e / 16), e % 16 + local name = EFFECTS[cmd + 1] + if cmd == 4 then + param = param * 17 -- vibrato: speed = depth + elseif cmd == 6 then + param = param == 0 and 0x4F or(param == 1 and 0xF4 or-1 +) elseif cmd == 7 and not (hasNote and extended) then + name = nil + end + if name ~= "panslide" then + effect[ch + 1] = 0xFF + end + if name and param >= 0 then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + r:skip(1536) + if breaks[p + 1] < 63 then + Load.writeEffect(m, p, breaks[p + 1], IT["break"], 0, "next") + end + Load.writeEffect(m, p, 0, IT.speed, tempos[p + 1], "next") + end + -- sample data: unsigned 8-bit + local pos = r.pos + for i = 1, nsmp do + local s = m.samples[i] + local ok, err = Load.readSample(buf, pos, lengths[i], { bits = 8, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos =pos+ lengths[i] + end + m.meta.source = { format = "669", tracker = extended and"UNIS 669" or"Composer 669" } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Six69.open(r, opts) +local m, err = Six69.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Six69 +end +__FILES["music/ahx"] = function() +--!strict +-- music/ahx: AHX (Abyss' Highest eXperience) modules, "THX\0" .. "THX\2": 4-channel Amiga synth tunes (no samples: +-- triangle / sawtooth / square / noise waveforms through filters, square modulation, the PList instrument programs). +-- Loads into a Types.Module-shaped value (kind "music", format "ahx": tracks as patterns, positions with per-channel +-- transposes, instruments with play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's +-- hvl2wav replayer (BSD-3-Clause): at 44.1 kHz with stereo = 0 the samples equal hvl2wav's. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Ahx = { + name = "ahx", + category = "music", + extensions = { "ahx", "thx" }, + mime = { "audio/x-ahx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 }, subsongs = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + +function Ahx.sniff(r) +local m = r:peek(4) + return m and #m == 4 and string.sub(m, 1, 3) == "THX" and string.byte(m, 4) < 3 and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ahx.decode(r, _opts) +local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "ahx" then + return nil, err or Err.new(Err.CORRUPT, "not an AHX module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) +function Ahx.open(r, opts) +local song, err = Ahx.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song ).tune, opts) +end + +return Ahx +end +__FILES["music/far"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- music/far: Farandole Composer modules (FAR, Daniel Potter's DOS tracker; 16 channels, up to 256 patterns of any +-- length with a break row, 64 samples). Ported from OpenMPT's Load_far.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads +-- into the codecs/audio/Tracker Module and plays as the "s3m" effect family with Farandole's quirks (flags): periods +-- in Hz (a slide step moves the frequency 36318 / 1024 Hz), a tone portamento that keeps going, fine pitch slides, +-- retrigger, vibrato depth / speed, volume slides, volume portamento (as a set volume), panning, speed; the fixed +-- tempo OpenMPT uses (80 BPM in tracker terms). +-- Not supported: Farandole's own tempo model (fine tempo up / down, D / E), the note-offset effect (C), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Far = { + name = "far", + category = "music", + extensions = { "far" }, + mime = { "audio/x-far" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 16, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + +local IT = Load.IT + +-- ------------------------------------------------------------------------------------------------ sniff +function Far.sniff(r) +if r:size() >= 98 and r:peek(4) == "FAR\xFE" and r:peek(3, 44) == "\r\n\x1A" and r:peekU8(47) + r:peekU8(48) * 256 >= 98 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a pattern cell's effect byte -> effect code, parameter, volume byte (S3M coding, 0 = none) (OpenMPT's table) +local function effect(e) +local cmd, p = math.floor(e / 16), e % 16 + if cmd == 1 then + return IT.portaup, 0xF0 + p, 0 + elseif cmd == 2 then + return IT.portadown, 0xF0 + p, 0 + elseif cmd == 3 then + return IT.toneporta, (p ~= 0 and{(math.floor(60 / p ))}or{0})[1], 0 + elseif cmd == 4 then + return IT.retrig, math.floor(6 / (1 + p) )+ 1, 0 + elseif cmd == 5 or cmd == 9 then + return IT.vibrato, p, 0 + elseif cmd == 6 then + return IT.vibrato, p * 8, 0 + elseif cmd == 7 then + return IT.volslide, p * 8, 0 + elseif cmd == 8 then + return IT.volslide, p, 0 + elseif cmd == 0xA then + return 0, 0, p * 4 + 4 + 1 -- volume portamento: a set volume + elseif cmd == 0xB then + return IT.s3mex, 0x80 + p, 0 + elseif cmd == 0xF then + return IT.speed, p, 0 + end + return 0, 0, 0 +end + +function Far.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Far.sniff(r) == 0 then + return nil, Err.new((r:size() < 98 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a Farandole module") + end + r:skip(4) + local title = r:fixed(40) + r:skip(3) + local headerLength, version = r:u16le(), r:u8() + local onOff, pans = {}, {} + for i = 1, 16 do + onOff[i] = r:u8() + end + r:skip(9) + local speed = r:u8() + for i = 1, 16 do + pans[i] = r:u8() + end + r:skip(4) + local msgLen = r:u16le() + local message = r:string(msgLen) + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + local _npat, nord, restart = r:u8(), r:u8(), r:u8() + local sizes = {} + for i = 1, 256 do + sizes[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local m = Tracker.newModule("far", 16, "s3m") + m.title = title + m.meta.message = message + m.speed, m.tempo = (speed > 0 and{speed }or{4})[1], 80 + m.mixVolume = 32 -- OpenMPT's pre-amp for FAR + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.hzSlide = "hz", 36318 / 1024 + m.flags.autoTonePorta = true + for i = 1, 16 do + m.channelMute[i] = onOff[i] == 0 + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + for i = 1, nord do + m.order[i] = orders[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + m.restart = restart + -- patterns: (size - 2) / 64 rows of 16 channels x (note, instrument, volume, effect), after a break row byte + if not r:seek(headerLength) then + return nil, r.err + end + local last = -1 + for p = 0, 255 do + if sizes[p + 1] > 0 then + last = p + end + end + for p = 0, last do + local size = sizes[p + 1] + local rows = math.clamp(math.floor((size - 2) / 64), 1, 1024) + local pat = Tracker.newPattern((size > 0 and{rows }or{64})[1], 16) + m.patterns[p + 1] = pat + if size > 0 then + local pr = r:slice(size) + if r.err then + return nil, r.err + end + local br = pr:u8() + pr:skip(1) + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, 15 do + local note, ins, vol, e = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * 16 + ch) * 5 + if note > 0 and note <= 72 then + buffer.writeu8(d, q, note + 36) + buffer.writeu8(d, q + 1, ins + 1) + end + if vol > 0 and vol <= 16 then + buffer.writeu8(d, q + 2, math.floor((vol - 1) * 64 / 15 )+ 1) + end + local fx, param, setVol = effect(e) + if setVol > 0 then + buffer.writeu8(d, q + 2, setVol) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + end + end + if br > 0 and br < rows - 2 then + Load.writeEffect(m, p, br + 1, IT["break"], 0, "next") + end + end + end + -- samples: a 64-bit map of the stored ones, each a 48-byte header + signed 8 / 16-bit data + local map = {} + for i = 1, 8 do + map[i] = r:u8() + end + r.err = nil + for i = 0, 63 do + if bit32.band(map[math.floor(i / 8 )+ 1] or 0, bit32.lshift(1, i % 8)) ~= 0 then + local h = r:slice(48) + if r.err then + break + end + local s = Tracker.newSample(h:fixed(32)) + local len = h:u32le() + h:skip(1) + local vol = h:u8() + local ls, le = h:u32le(), h:u32le() + local typ, loop = h:u8(), h:u8() + local bits = typ % 2 == 1 and 16 or 8 + local frames = (bits == 16 and{(math.floor(len / 2 ))}or{len +})[1] if bits == 16 then + ls, le = math.floor(ls / 2), math.floor(le / 2 +) end + s.c5speed = 8363 * 2 + s.volume = math.min(vol * 4, 64) + local ok, err = Load.readSample(r.buf, r.pos, frames, { bits = bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + r:skip(math.min(len, r:remaining())) + if bit32.band(loop, 8) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + for k = #m.samples + 1, i do + m.samples[k] = Tracker.newSample() + end + m.samples[i + 1] = s + end + end + m.meta.source = { format = "far", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Far.open(r, opts) +local m, err = Far.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Far +end +__FILES["music/hmp"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header) +-- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the +-- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE +-- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per +-- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker +-- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a +-- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP +-- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the +-- tracks apply on top. Renders through codecs/audio/MidiRender. +-- Not supported: writing; HMP branch tables (skipped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Hmp = { + name = "hmp", + category = "music", + extensions = { "hmp", "hmi" }, + mime = { "audio/x-hmp" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, hmi = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + +local HMI_MAGIC = "HMI-MIDISONG061595" + +function Hmp.sniff(r) +return (r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC )and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8, readu32 = buffer.readu8, buffer.readu32 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +-- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set; +-- otherwise the MIDI encoding +local function delta(b, p, e, hmp) +local v, shift = 0, 1 + for _ = 1, 5 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p =p+ 1 + if hmp then + v =v+ (c % 128) * shift + shift =shift* 128 + if c >= 128 then + return v, p + end + else + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + end + return nil, p +end + +local function bytes(b, p, n) +local t= (table.create(n) ) +for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +-- one track [p, e) -> events (note-offs merged in) | nil, message + + +local function track(b, p, e, hmp, ctx) +local list, offs= {}, {} + local tick, running = 0, 0 + while p < e do + local d, q = delta(b, p, e, hmp) + if not d then + break -- (a track cut inside its last delta: keep what was read) + end + tick =tick+ d + p = q + if p >= e then + return nil, "truncated event" + end + local st = readu8(b, p) + if st == 0xFE and not hmp then + -- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes + local n = 4 + if p + 1 < e and readu8(b, p + 1) == 0x10 then + n = (p + 4 < e and{(readu8(b, p + 4) + 9 )}or{(e - p + 1 +)})[1] elseif p + 1 < e and readu8(b, p + 1) == 0x15 then + n = 8 + end + if p + n > e then + return nil, "truncated FE event" + end + p =p+ n + elseif st == 0xFF then + local kind = (p + 1 < e and{(readu8(b, p + 1) )}or{(-1 +)})[1] local n, r = delta(b, p + 2, e, false) + if kind < 0 or not n or r + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + end + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) }) + p = r + n + elseif st == 0xF0 or st == 0xF7 then + local n, r = delta(b, p + 1, e, false) + if not n or r + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = st == 0xF0 and"sysex" or"escape", data = bytes(b, r, n) }) + p = r + n + running = 0 + else + if st >= 0x80 then + if st >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02X", st) + end + running = st + p =p+ 1 + elseif running == 0 then + return nil, "running status without a status byte" + end + local hi, ch = math.floor(running / 16), running % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local data = bytes(b, p, n) + p =p+ n + if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then + ctx.loops =ctx.loops+ 1 + else + for i = 1, n do + data[i]=data[i]% 128 + end + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data }) + end + if hi == 9 and not hmp then + local dur, r = delta(b, p, e, false) + if not dur then + return nil, "truncated note duration" + end + p = r + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } }) + end + end + ctx.budget =ctx.budget- 1 + if ctx.budget < 0 then + return nil, "limit: too many events" + end + end + -- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them) + local out = Render.merge(list, offs) + table.insert(out, { tick = math.max(tick, (#out > 0 and{out[#out].tick }or{0})[1]), type = "meta", meta = 0x2F, data = {} }) + return out, nil +end + +-- the chunk table -> { { start, stop } } track ranges | nil, message, kind +local function hmpTracks(b, base, limit) +local new = buffer.readstring(b, base + 8, 6) == "013195" + local n = readu32(b, base + 0x30) + local p = base + (new and 0x388 or 0x308) + if n == 0 or n > 256 then + return nil, string.format("bad track count %d", n), nil + end + local ranges = {} + for _ = 1, n do + if p + 12 > limit then + return nil, "truncated chunk header", "truncated" + end + local len = readu32(b, p + 4) + if len < 12 or p + len > limit then + return nil, "truncated chunk", "truncated" + end + table.insert(ranges, { p + 12, p + len }) + p =p+ len + end + return ranges, nil, nil +end + +local function hmiTracks(b, base, limit) +local n = readu8(b, base + 228) + if n == 0 then + return nil, "no tracks", nil + end + if base + 370 + n * 4 > limit then + return nil, "truncated track table", "truncated" + end + local ranges, heads = {}, {} + for i = 0, n - 1 do + local at = base + readu32(b, base + 370 + i * 4) + if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then + return nil, string.format("bad track %d header", i), nil + end + local start = at + readu32(b, at + 0x57) + if start >= limit then + return nil, "truncated track", "truncated" + end + table.insert(ranges, { start, limit }) + table.insert(heads, at) + end + -- a track ends where the next track header starts (or at the end of the file) + for _, rg in __iter(ranges) do + for _, h in __iter(heads) do + if h >= rg[1] and h < rg[2] then + rg[2] = h + end + end + end + return ranges, nil, nil +end + +function Hmp.decode(r, opts) +local b, base, limit = r.buf, r.base, r.limit + local hmi = r:peek(18) == HMI_MAGIC + if not hmi and r:peek(8) ~= "HMIMIDIP" then + return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file") + end + if limit - base < (hmi and 371 or 0x40) then + return nil, Err.new(Err.TRUNCATED, "truncated header") + end + local rate = (hmi and{(readu8(b, base + 212) )}or{(readu32(b, base + 0x38) +)})[1] if rate == 0 or rate > 100000 then + return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate) + end + local ranges, msg, kind = ((hmi and{hmiTracks }or{hmpTracks})[1])(b, base, limit) + if not ranges then + return nil, Err.from(msg , nil, kind) + end + local ctx= { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 } + local midi = Types.Midi.new(60) + for i, rg in __iter(ranges) do + local evs, err = track(b, rg[1], rg[2], not hmi, ctx) + if not evs then + return nil, Err.from(err , rg[1]) + end + if i == 1 then + local us = math.min(math.floor(60000000 / rate), 0xFFFFFF) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { math.floor(us / 65536), (math.floor(us / 256)) % 256, us % 256 } }) + end + midi.tracks[i] = { events = evs } + end + local version = hmi and"hmi" or(buffer.readstring(b, base + 8, 6) == "013195" and"013195" or"hmp" +) Render.attach(midi, { format = hmi and"hmi" or"hmp", version = version, rate = rate, loops = ctx.loops }) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Hmp.open(r, opts) +local midi, err = Hmp.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Hmp +end +__FILES["music/hvl"] = function() +--!strict +-- music/hvl: HivelyTracker modules, "HVL\0" / "HVL\1": AHX's synth extended to 4..16 channels, two effect columns, +-- ring modulation, per-channel panning, mix gain and stereo separation stored in the file. Loads into a Types.Module- +-- shaped value (kind "music", format "hvl": tracks as patterns, positions with per-channel transposes, instruments with +-- play lists, subsongs) and renders through codecs/audio/Hively, a port of HivelyTracker's hvl2wav replayer +-- (BSD-3-Clause): at 44.1 kHz the samples equal hvl2wav's. +-- Not supported: writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Hively = __include("codecs/audio/Hively") + +-- ------------------------------------------------------------------------------------------------ contract +local Hvl = { + name = "hvl", + category = "music", + extensions = { "hvl" }, + mime = { "audio/x-hvl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Hively" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 16 }, subsongs = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + +function Hvl.sniff(r) +local m = r:peek(4) + return m and #m == 4 and string.sub(m, 1, 3) == "HVL" and string.byte(m, 4) <= 1 and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Hvl.decode(r, _opts) +local tune, err = Hively.parse(r.buf, r.base, r.limit) + if not tune or tune.format ~= "hvl" then + return nil, err or Err.new(Err.CORRUPT, "not an HVL module") + end + return Hively.module(tune), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: RenderOptions) +function Hvl.open(r, opts) +local song, err = Hvl.decode(r) + if not song then + return nil, err + end + return Hively.decoder((song ).tune, opts) +end + +return Hvl +end +__FILES["music/it"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the +-- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or +-- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, +-- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo +-- samples, IT 2.14 / 2.15 compressed samples, sustain loops, auto-vibrato, the song message. +-- Not supported: embedded MIDI macro configurations (the default filter macros are used), MIDI output, OpenMPT's +-- extension chunks (plugins, extended instrument properties), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Itsex = __include("music/it/Itsex") + +-- ------------------------------------------------------------------------------------------------ contract +local It = { + name = "it", + category = "music", + extensions = { "it" }, + mime = { "audio/it", "audio/x-it" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function It.sniff(r) +return r:peek(4) == "IMPM" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 82-byte envelope of a new-format instrument +local function readEnvelope(r, kind) +local flags, n = r:u8(), r:u8() + local lb, le, sb, se = r:u8(), r:u8(), r:u8(), r:u8() + local e = Tracker.newEnvelope() + n = math.min(n, 25) + for i = 1, 25 do + local y, x = r:i8(), r:u16le() + if i <= n then + e.ticks[i] = x + e.values[i] = (kind == "vol" and{(math.clamp(y, 0, 64) )}or{(math.clamp(y, -32, 32) +)})[1] end + end + r:skip(1) + e.enabled = bit32.band(flags, 1) ~= 0 and n > 0 + e.loop = bit32.band(flags, 2) ~= 0 + e.sustain = bit32.band(flags, 4) ~= 0 + e.carry = bit32.band(flags, 8) ~= 0 + e.filter = kind == "pitch" and bit32.band(flags, 128) ~= 0 + e.loopStart, e.loopEnd = lb + 1, le + 1 + e.susStart, e.susEnd = sb + 1, se + 1 + return e +end + +local function readInstrument(r, old) +if r:string(4) ~= "IMPI" then + return nil, "bad instrument signature" + end + local ins = Tracker.newInstrument() + r:skip(13) + if old then + -- the pre-2.0 layout: volume envelope only (flags, loop and sustain points), fadeout 0..64 of 512 + local flg, vls, vle, sls, sle = r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:skip(2) + ins.fadeout = r:u16le() * 2 + ins.nna = r:u8() + ins.dct = r:u8() ~= 0 and 1 or 0 + r:skip(4) + ins.name = r:fixed(26) + r:skip(6) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + r:skip(200) + local e = Tracker.newEnvelope() + for i = 1, 25 do + local t, v = r:u8(), r:u8() + if t == 0xFF or (i > 1 and t <= (e.ticks[#e.ticks] or -1)) then + r:skip((25 - i) * 2) + break + end + table.insert(e.ticks, t) + table.insert(e.values, math.min(v, 64)) + end + e.enabled = bit32.band(flg, 1) ~= 0 and #e.ticks > 0 + e.loop = bit32.band(flg, 2) ~= 0 + e.sustain = bit32.band(flg, 4) ~= 0 + e.loopStart, e.loopEnd, e.susStart, e.susEnd = vls + 1, vle + 1, sls + 1, sle + 1 + ins.volEnv = e + return ins + end + ins.nna, ins.dct, ins.dca = r:u8() % 4, r:u8() % 4, r:u8() % 3 + ins.fadeout = math.min(r:u16le(), 1024) + ins.pps, ins.ppc = r:i8(), r:u8() + ins.globalVolume = math.min(r:u8(), 128) + local dfp = r:u8() + if dfp < 128 then + ins.pan = math.min(dfp, 64) * 4 + end + r:skip(2 + 2 + 1 + 1) + ins.name = r:fixed(26) + local ifc, ifr = r:u8(), r:u8() + if ifc >= 128 then + ins.cutoff = ifc - 128 + end + if ifr >= 128 then + ins.resonance = ifr - 128 + end + r:skip(4) + for n = 1, 120 do + local note, smp = r:u8(), r:u8() + ins.noteMap[n] = math.clamp(note + 1, 1, 120) + ins.sampleMap[n] = smp + end + ins.volEnv = readEnvelope(r, "vol") + ins.panEnv = readEnvelope(r, "pan") + ins.pitchEnv = readEnvelope(r, "pitch") + if r.err then + return nil, "instrument truncated" + end + return ins +end + +function It.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(4) ~= "IMPM" then + return nil, Err.new(Err.CORRUPT, "no IMPM signature") + end + r:skip(4) + local title = r:fixed(26) + r:skip(2) + local ordnum, insnum, smpnum, patnum = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local cwt, cmwt, flags, special = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local gv, mv, speed, tempo, _sep, _pwd = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local msgLen, msgOff = r:u16le(), r:u32le() + r:skip(4) + local chnPan, chnVol = {}, {} + for i = 1, 64 do + chnPan[i] = r:u8() + end + for i = 1, 64 do + chnVol[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 255 or smpnum > 255 or patnum > 255 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + local orders = {} + for i = 1, ordnum do + orders[i] = r:u8() + end + local insOff, smpOff, patOff = {}, {}, {} + for i = 1, insnum do + insOff[i] = r:u32le() + end + for i = 1, smpnum do + smpOff[i] = r:u32le() + end + for i = 1, patnum do + patOff[i] = r:u32le() + end + if r.err then + return nil, r.err + end + -- channels: the highest one any pattern uses + local nch = 1 + local packed= {} + local rowsOf= {} + for p = 1, patnum do + if patOff[p] > 0 then + local pr = r:sub(patOff[p]) + local len, rows = pr:u16le(), pr:u16le() + pr:skip(4) + if pr.err or rows < 1 or rows > 1024 then + return nil, Err.new(Err.CORRUPT, "bad pattern " .. (p - 1), r.base + patOff[p]) + end + local data = pr:slice(len) + packed[p], rowsOf[p] = data, rows + -- scan for the channel count + local scan = data:sub(0) + local seen= {} + while not scan:eof() do +local __DARKLUA_CONTINUE_12=false repeat local cv = scan:u8() + if cv == 0 then +__DARKLUA_CONTINUE_12=true break + end + local ch = (cv - 1) % 64 + nch = math.max(nch, ch + 1) + local mask = 0 + if cv >= 128 then + mask = scan:u8() + seen[ch] = mask + else + mask = seen[ch] or 0 + end + if bit32.band(mask, 1) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 2) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 4) ~= 0 then + scan:skip(1) + end + if bit32.band(mask, 8) ~= 0 then + scan:skip(2) + end +__DARKLUA_CONTINUE_12=true until true if not __DARKLUA_CONTINUE_12 then break end end + else + rowsOf[p] = 64 + end + end + local m = Tracker.newModule("it", nch) + m.title = title + m.speed = (speed > 0 and{speed }or{6 +})[1] m.tempo = (tempo >= 31 and{tempo }or{125 +})[1] m.globalVolume = math.min(gv, 128) + m.mixVolume = math.min(mv, 128) + m.linear = bit32.band(flags, 8) ~= 0 + m.instrumentMode = bit32.band(flags, 4) ~= 0 + m.flags.oldEffects = bit32.band(flags, 16) ~= 0 + m.flags.compatGxx = bit32.band(flags, 32) ~= 0 + local stereo = bit32.band(flags, 1) ~= 0 + for i = 1, nch do + local p = chnPan[i] + if p >= 128 then + m.channelMute[i] = true + p =p- 128 + end + if not stereo then + m.channelPan[i] = 128 + elseif p == 100 then + m.channelPan[i] = 512 + else + m.channelPan[i] = math.min(p, 64) * 4 + end + m.channelVolume[i] = math.min(chnVol[i], 64) + end + for i = 1, ordnum do + if orders[i] == 255 then + break + end + table.insert(m.order, orders[i]) + end + m.meta.source = { format = "it", tracker = cwt, compatible = cmwt } + if bit32.band(special, 1) ~= 0 and msgLen > 0 then + local mr = r:sub(msgOff, msgLen) + m.meta.message = string.gsub(mr:fixed(msgLen), "\r", "\n") + end + -- instruments + for i = 1, insnum do + local ins, ierr = readInstrument(r:sub(insOff[i]), cmwt < 0x200) + if not ins then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. ": " .. tostring(ierr), r.base + insOff[i]) + end + m.instruments[i] = ins + end + -- samples + local total = 0 + for i = 1, smpnum do + local h = r:sub(smpOff[i], 80) + if h:string(4) ~= "IMPS" then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": bad signature", r.base + smpOff[i]) + end + h:skip(13) + local s = Tracker.newSample() + m.samples[i] = s + local gvl, flg, vol = h:u8(), h:u8(), h:u8() + s.name = h:fixed(26) + local cvt, dfp = h:u8(), h:u8() + local len, lb, le, c5, slb, sle, ptr = h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le(), h:u32le() + local vis, vid, vir, vit = h:u8(), h:u8(), h:u8(), h:u8() + if h.err then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i) + end + s.globalVolume = math.min(gvl, 64) + s.volume = math.min(vol, 64) + if dfp >= 128 then + s.pan = math.min(dfp - 128, 64) * 4 + end + s.c5speed = (c5 > 0 and{c5 }or{8363 +})[1] s.vibRate, s.vibDepth, s.vibSweep, s.vibType = vis, vid, vir, vit % 4 + local bits = bit32.band(flg, 2) ~= 0 and 16 or 8 + local nchs = bit32.band(flg, 4) ~= 0 and 2 or 1 + s.bits = bits + if bit32.band(flg, 1) ~= 0 and len > 0 then + len = math.min(len, 2 ^ 26) + total =total+ len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data= nil + if bit32.band(flg, 8) ~= 0 then + -- compressed: each channel separately + local it215 = bit32.band(cvt, 4) ~= 0 + local p = r.base + ptr + local parts = {} + for c = 1, nchs do + local d, used = Itsex.decompress(r.buf, p, r.limit, len, bits, it215) + if not d then + return nil, Err.new(Err.CORRUPT, "sample " .. i .. ": " .. tostring(used)) + end + parts[c] = d + p =p+ used +end + if nchs == 1 then + data = parts[1] + else + local inter = buffer.create(len * 8) + for f = 0, len - 1 do + buffer.writef32(inter, f * 8, buffer.readf32(parts[1], f * 4)) + buffer.writef32(inter, f * 8 + 4, buffer.readf32(parts[2], f * 4)) + end + data = inter + end + else + local bps = math.floor(bits / 8 +) local avail = math.floor(math.max(0, r:size() - ptr) / (bps * nchs) +) len = math.min(len, avail) + data = Tracker.Pcm.decode(r.buf, r.base + ptr, len, { + bits = bits, + signed = bit32.band(cvt, 1) ~= 0, + bigEndian = bit32.band(cvt, 2) ~= 0, + delta = bit32.band(cvt, 4) ~= 0, + channels = nchs, + planar = true, + }) + end + if data then + s.data, s.length, s.channels = data, len, nchs + if bit32.band(flg, 16) ~= 0 then + s.loopStart, s.loopEnd, s.loopType = lb, math.min(le, len), bit32.band(flg, 64) ~= 0 and 2 or 1 + end + if bit32.band(flg, 32) ~= 0 then + s.susStart, s.susEnd, s.susType = slb, math.min(sle, len), bit32.band(flg, 128) ~= 0 and 2 or 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(rowsOf[p], nch) + m.patterns[p] = pat + local pr = packed[p] + if pr then + local d = pat.data + local lastMask, lastNote, lastIns, lastVol, lastFx, lastParam = {}, {}, {}, {}, {}, {} + local row = 0 + while row < pat.rows and not pr:eof() do +local __DARKLUA_CONTINUE_20=false repeat local cv = pr:u8() + if cv == 0 then + row =row+ 1 +__DARKLUA_CONTINUE_20=true break + end + local ch = (cv - 1) % 64 + local mask = (cv >= 128 and{(pr:u8() )}or{(lastMask[ch] or 0) +})[1] lastMask[ch] = mask + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if bit32.band(mask, 1) ~= 0 then + local n = pr:u8() + -- 255 note off, 254 note cut, 246 note fade (as IT and OpenMPT store "~~~"); other values: nothing + note = (n < 120 and((n + 1 ))or(n == 255 and 255 or(n == 254 and 254 or(n == 246 and 253 or 0 +)))) lastNote[ch] = note + elseif bit32.band(mask, 16) ~= 0 then + note = lastNote[ch] or 0 + end + if bit32.band(mask, 2) ~= 0 then + ins = pr:u8() + lastIns[ch] = ins + elseif bit32.band(mask, 32) ~= 0 then + ins = lastIns[ch] or 0 + end + if bit32.band(mask, 4) ~= 0 then + vol = math.min(pr:u8(), 212) + 1 + lastVol[ch] = vol + elseif bit32.band(mask, 64) ~= 0 then + vol = lastVol[ch] or 0 + end + if bit32.band(mask, 8) ~= 0 then + fx, param = pr:u8(), pr:u8() + if fx > 26 then + fx, param = 0, 0 + end + lastFx[ch], lastParam[ch] = fx, param + elseif bit32.band(mask, 128) ~= 0 then + fx, param = lastFx[ch] or 0, lastParam[ch] or 0 + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end +__DARKLUA_CONTINUE_20=true until true if not __DARKLUA_CONTINUE_20 then break end end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function It.open(r, opts) +local m, err = It.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return It +end +__FILES["music/it/Itsex"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +--!native +-- music/it/Itsex: Impulse Tracker sample decompression (IT 2.14 and the IT 2.15 double-delta variant, 8 and 16-bit). +-- Written from the algorithm description in ITTECH.TXT / the public notes on the format: blocks of 0x8000 bytes of +-- output, each a u16 length then an LSB-first bit stream of deltas with three width-change methods. +-- +-- Never throws: every read is bounds-checked; corrupt streams return nil, message. +local readu8, readu16, writef32 = buffer.readu8, buffer.readu16, buffer.writef32 + +local Itsex = {} + +-- decompress(buf, off, limit, frames, bits, it215) -> f32 buffer (frames), bytes consumed | nil, message +function Itsex.decompress(buf, off, limit, frames, bits, it215) +local out = buffer.create(frames * 4) + local blockLen = bits == 16 and 0x4000 or 0x8000 + local topWidth = bits == 16 and 17 or 9 + local fetchA = bits == 16 and 4 or 3 + local lowerB = bits == 16 and-8 or-4 + local upperB = bits == 16 and 7 or 3 + local scale = bits == 16 and 1 / 32768 or 1 / 128 + local wrap = bits == 16 and 65536 or 256 + local half = math.floor(wrap / 2 +) local p = off + local done = 0 + while done < frames do + if p + 2 > limit then + return nil, "compressed sample truncated" + end + local clen = readu16(buf, p) + p =p+ 2 + local bstart = p + local bend = p + clen + if bend > limit then + return nil, "compressed block runs past the end" + end + p = bend + -- bit reader over [bstart, bend) + local bytePos = bstart + local bitBuf = 0 + local bitCount = 0 + local function readBits(n) +while bitCount < n do + if bytePos >= bend then + return -1 + end + bitBuf =bitBuf+ readu8(buf, bytePos) * 2 ^ bitCount + bytePos =bytePos+ 1 + bitCount =bitCount+ 8 + end + local v = bitBuf % 2 ^ n + bitBuf = (bitBuf - v) / 2 ^ n + bitCount =bitCount- n + return v + end + local count = math.min(blockLen, frames - done) + local width = topWidth + local d1, d2 = 0, 0 + local i = 0 + while i < count do +local __DARKLUA_CONTINUE_3=false repeat if width < 1 or width > topWidth then + return nil, "bad bit width" + end + local v = readBits(width) + if v < 0 then + return nil, "compressed block ends early" + end + if width < 7 then + -- method A: a marker value, then the new width in fetchA bits + if v == 2 ^ (width - 1) then + local nw = readBits(fetchA) + if nw < 0 then + return nil, "compressed block ends early" + end + nw =nw+ 1 + width = (nw < width and{nw }or{(nw + 1 +)})[1]__DARKLUA_CONTINUE_3=true break + end + elseif width < topWidth then + -- method B: values just below the top of the range encode the new width + local border = bit32.rshift(bits == 16 and 0xFFFF or 0xFF, topWidth - width) + lowerB + if v > border and v <= border + (upperB - lowerB + 1) then + local nw = v - border + width = (nw < width and{nw }or{(nw + 1 +)})[1]__DARKLUA_CONTINUE_3=true break + end + else + -- method C: the top bit flags a width change + if v >= wrap then + width = (v + 1) % 256 +__DARKLUA_CONTINUE_3=true break + end + end + -- a delta, sign-extended from its width + local x = v + if width < topWidth then + local shift = 2 ^ width + if x >= shift / 2 then + x =x- shift + end + else + x = v % wrap + if x >= half then + x =x- wrap + end + end + d1 = (d1 + x + half) % wrap - half + local s = d1 + if it215 then + d2 = (d2 + d1 + half) % wrap - half + s = d2 + end + writef32(out, (done + i) * 4, s * scale) + i =i+ 1 +__DARKLUA_CONTINUE_3=true until true if not __DARKLUA_CONTINUE_3 then break end end + done =done+ count + end + return out, p - off +end + +return Itsex +end +__FILES["music/med"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- music/med: MED / OctaMED modules (MMD0, MMD1, MMD2, MMD3; Amiga MED 2+, OctaMED 4 .. Soundstudio; 1..64 tracks, +-- blocks of any length). Ported from OpenMPT's Load_med.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads the first song +-- into the codecs/audio/Tracker Module and plays it as the "xm" effect family with ProTracker periods and the PAL +-- clock (flags.periods = "amiga"): MED's effects mapped as OpenMPT maps them, slides on every tick unless the song asks +-- for ProTracker-style slides, the SPD / 8-channel / BPM tempo modes, MMD2 / MMD3 play sequences and sections (stop +-- and jump commands), track volumes and pans, hold / decay (as a volume envelope and fadeout), IFF multi-octave +-- samples (instruments with keymaps), 8 / 16-bit, stereo and delta samples, instrument extras (finetune, loops, +-- default pitch, volume). +-- Not supported: synthetic and hybrid instruments (silent), MIDI instruments and commands, extra command pages and +-- the second command parameter, songs past the first, echo / stereo separation, packed (ADPCM) samples, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Med = { + name = "med", + category = "music", + extensions = { "med", "mmd0", "mmd1", "mmd2", "mmd3", "omed" }, + mime = { "audio/x-med" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 64 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- IFF multi-octave samples: the sample (0 = the lowest octave stored first... as OpenMPT orders them) and the +-- transpose used per octave of the keyboard, by the number of octaves stored (2..7) + + + + +local OCT_SAMPLE = { + { 1, 1, 0, 0, 0, 0, 0, 0 }, + { 2, 2, 1, 1, 0, 0, 0, 0 }, + { 3, 3, 2, 2, 1, 0, 0, 0 }, + { 4, 3, 2, 1, 1, 0, 0, 0 }, + { 5, 4, 3, 2, 1, 0, 0, 0 }, + { 6, 5, 4, 3, 2, 1, 0, 0 }, +} +local OCT_TRANSPOSE = { + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 0, 0, -12, -12, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -24, -36, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -48, -60 }, + { 12, 0, -12, -24, -36, -48, -60, -72 }, +} +local SAMPLES_PER_TYPE = { [0] = 1, 5, 3, 2, 4, 6, 7 } +local TEMPO_8CH = { 179, 164, 152, 141, 131, 123, 116, 110, 104, 99 } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r) +if r:size() < 52 or r:peek(3) ~= "MMD" then + return false + end + local v = r:peekU8(3) + if v < 0x30 or v > 0x33 then + return false + end + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + return songOff >= 52 and songOff + 63 * 8 + 284 <= r:size() and blockOff >= 52 and (smpOff == 0 or smpOff >= 52) +end + +function Med.sniff(r) +return validHeader(r) and 1 or 0 +end +-- ------------------------------------------------------------------------------------------------ decode +-- a MED tempo -> BPM (OpenMPT's MMDTempoToBPM: the SPD / 8-channel / BPM modes) + + + +local function tempoToBpm(tempo, ctx) +if ctx.bpm and not ctx.is8Ch then + return tempo < 7 and 111.5 or tempo * ctx.rowsPerBeat / 4 + end + if ctx.is8Ch and tempo > 0 then + return TEMPO_8CH[math.min(tempo, 10)] + elseif not ctx.softMix and tempo > 0 and tempo <= 10 then + return 6 * 1773447 / 14500 / tempo -- SoundTracker-compatible tempo + elseif ctx.softMix and tempo < 8 then + return 157.86 + end + return tempo / 0.264 +end + +-- a MED command -> MOD / XM effect, param, and a note-cut flag (OpenMPT's ConvertMEDEffect) +local function effect(cmd, p, ctx) +local lo = math.min(p, 15) + if cmd == 1 or cmd == 2 then + return (p > 0 and{cmd }or{0})[1], p, false + elseif cmd == 4 then + return 4, p - p % 16 + math.min((p % 16) * 2, 15), false -- twice as deep as ProTracker's + elseif cmd == 5 then + return p > 0 and 5 or 3, p, false + elseif cmd == 6 then + return p > 0 and 6 or 4, p, false + elseif cmd == 8 or cmd == 0xE or cmd == 0x10 or cmd == 0x1C or cmd == 0x20 or cmd == 0x29 then + return 0, 0, false -- hold / decay (instrument data), synth jump, MIDI, reverse, relative offset + elseif cmd == 9 then + return p > 0 and p <= 0x20 and 0xF or 0, math.min(p, 0x1F), false + elseif cmd == 0xC then + if not ctx.volHex and p < 0x99 then + return 0xC, (math.floor(p / 16)) * 10 + p % 16, false + elseif ctx.volHex and not ctx.vol7bit then + return 0xC, math.min(p % 128, 64), false + elseif ctx.volHex then + return 0xC, math.floor((p % 128 + 1) / 2), false + end + return 0, 0, false + elseif cmd == 0xD then + return p > 0 and 0xA or 0, p, false + elseif cmd == 0xF then + if p == 0 then + return 0xD, 0, false + elseif p <= 0xF0 then + local bpm = p < 3 and 0x70 or math.floor(tempoToBpm(p, ctx) + 0.5) + if bpm > 255 then + local ext = Tracker.EXT.TEMPO_256 + math.min(math.floor(bpm / 256), 3) - 1 -- tempos past 255 (EXT 0x47..0x49) + return ext, math.min(bpm - (ext - Tracker.EXT.TEMPO_256 + 1) * 256, 255), false + end + return 0xF, math.max(bpm, 0x20), false + elseif p == 0xF1 then + return 0xE, 0x93, false + elseif p == 0xF2 then + return 0xE, 0xD3, false + elseif p == 0xF3 then + return 0xE, 0x92, false + elseif p == 0xFF then + return 0, 0, true + end + return 0, 0, false + elseif cmd == 0x11 then + return 0xE, 0x10 + lo, false + elseif cmd == 0x12 then + return 0xE, 0x20 + lo, false + elseif cmd == 0x14 then + return 4, p, false -- ProTracker depth, faster + elseif cmd == 0x15 then + return 0xE, 0x50 + p % 16, false + elseif cmd == 0x16 then + return 0xE, 0x60 + lo, false + elseif cmd == 0x18 then + return 0xE, 0xC0 + lo, false + elseif cmd == 0x19 then + return 9, p, false + elseif cmd == 0x1A then + return 0xE, 0xA0 + lo, false + elseif cmd == 0x1B then + return 0xE, 0xB0 + lo, false + elseif cmd == 0x1D then + return 0xD, Load.bcd(p), false -- pattern break, the row in hex + elseif cmd == 0x1E then + return 0xE, 0xE0 + lo, false + elseif cmd == 0x1F then + if p >= 16 then + return 0xE, 0xD0 + math.floor(p / 16), false + elseif p > 0 then + return 0xE, 0x90 + p, false + end + return 0, 0, false + elseif cmd == 0x2E then + if p <= 0x10 or p >= 0xF0 then + return 8, math.clamp((bit32.bxor(p, 0x80) - 0x70) * 8, 0, 255), false + end + return 0, 0, false + elseif cmd < 0x10 and (cmd > 0 or p > 0) then + return cmd, p, false -- the remaining ProTracker effects as they are (0, 3, 7, 8, A, B) + end + return 0, 0, false +end + +-- a MED note (with the play transpose) -> our note, or 0 (OpenMPT's octave wrapping) +local function wrapNote(note, vol7bit) +local n = note + 12 -- OpenMPT's numbering (ProTracker notes an octave up) + if n > 132 and not vol7bit then + n =n- 108 + elseif n > 120 then + n =n- ((n - 109) - (n - 109) % 12 +) end + return (n >= 13 and((n - 12 ))or(0 +))end + +-- one block -> a Pattern (the main command page); returns whether a note needs the instruments' octave folding +local function readBlock(r, off, version, ctx, nch) +local br = r:sub(off) + local ntracks, nrows, info + if version < 1 then + ntracks, nrows, info = br:u8(), br:u8() + 1, 0 + else + ntracks, nrows, info = br:u16be(), br:u16be() + 1, br:u32be() + end + if br.err or nrows > 1024 then + return nil, false + end + local cmdExt= nil + if version >= 1 and info > 0 then + local ir = r:sub(info, 36) + ir:skip(16) + local ext = ir:u32be() + if not ir.err and ext > 0 then + local p = r:sub(ext, 4):u32be() + if p > 0 then + cmdExt = r:sub(p) + end + end + end + local lctx = table.clone(ctx) + lctx.vol7bit = cmdExt ~= nil + local pat = Tracker.newPattern(nrows, nch) + local d = pat.data + local high = false + local used = math.min(ntracks, nch) + for row = 0, nrows - 1 do + for ch = 0, ntracks - 1 do + local note, ins, cmd, param, cut = 0, 0, 0, 0, false + if version < 1 then + local ni, ic, p = br:u8(), br:u8(), br:u8() + if ni % 64 > 0 then + note = ni % 64 + lctx.transpose + end + ins = math.floor(ic / 16 )+ bit32.rshift(bit32.band(ni, 0x80), 3) + bit32.rshift(bit32.band(ni, 0x40), 1) + cmd, param = ic % 16, p + else + local nv, iv, c, p = br:u8(), br:u8(), br:u8(), br:u8() + if nv % 128 > 0 then + note = nv % 128 + lctx.transpose + elseif nv == 0x80 then + cut = true + end + ins, cmd, param = iv % 64, c, p + end + if br.err then + return pat, high + end + if ch < used then + local q = (row * nch + ch) * 5 + if note >= 61 + 24 - 12 then + high = true + end + local n = wrapNote(note, lctx.vol7bit) + if n > 0 then + buffer.writeu8(d, q, n) + elseif cut then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 1, ins) + if cmd ~= 0 or param ~= 0 then + local fx, fp, noteCut = effect(cmd, param, lctx) + if noteCut and n == 0 then + buffer.writeu8(d, q, 254) + end + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + end + return pat, high +end + +function Med.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new((r:size() < 52 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a MED module") + end + local version = r:peekU8(3) - 0x30 + local h = r:sub(8, 44) + local songOff = h:u32be() + h:skip(4) + local blockOff = h:u32be() + h:skip(4) + local smpOff = h:u32be() + h:skip(4) + local expOff = h:u32be() + -- the song: 63 sample headers, then the song header + local sh = r:sub(songOff, 63 * 8) + local song = r:sub(songOff + 63 * 8, 284) + local numBlocks, songLength = song:u16be(), song:u16be() + local seq = song:sub(4, 256) + song:skip(256) + local defTempo, playTranspose, flags, flags2, tempo2 = song:u16be(), song:i8(), song:u8(), song:u8(), song:u8() + local trackVol = {} + for i = 1, 16 do + trackVol[i] = song:u8() + end + local masterVol, numSamples = song:u8(), song:u8() + if song.err or numSamples > 63 or numBlocks > 0x7FFF then + return nil, Err.new(Err.CORRUPT, "bad song header") + end + if numSamples > 0 and smpOff == 0 then + return nil, Err.new(Err.CORRUPT, "no sample table") + end + -- channels: the widest block (at least 4) + local nch = 4 + local blockPtr= {} + for b = 0, numBlocks - 1 do + local p = r:sub(blockOff + b * 4, 4):u32be() + blockPtr[b + 1] = p + if p > 0 and p < r:size() then + local w = (version < 1 and{(r:peekU8(p) )}or{(r:peekU8(p) * 256 + r:peekU8(p + 1) +)})[1] nch = math.max(nch, w) + end + end + if nch > 64 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " tracks") + end + local m = Tracker.newModule("med", nch, "xm") + m.linear = false + m.instrumentMode = false + m.flags.periods, m.flags.envRowHold = "amiga", true + local stSlides = bit32.band(flags, 0x20) ~= 0 + m.flags.fastSlides, m.flags.fastPortas = not stSlides, not stSlides + local hardwareMix = version < 2 or bit32.band(flags2, 0x80) == 0 + m.flags.amigaLimits = hardwareMix + -- the expansion data: instrument extras and names, the song name + local ext = { instrExt = 0, instrExtN = 0, instrExtSize = 0, infoOff = 0, infoN = 0, infoSize = 0, nameOff = 0, nameLen = 0, annoOff = 0, annoLen = 0 } + if expOff > 0 then + local e = r:sub(expOff, 80) + e:skip(4) + ext.instrExt, ext.instrExtN, ext.instrExtSize = e:u32be(), e:u16be(), e:u16be() + ext.annoOff, ext.annoLen = e:u32be(), e:u32be() + ext.infoOff, ext.infoN, ext.infoSize = e:u32be(), e:u16be(), e:u16be() + e:skip(16) + ext.nameOff, ext.nameLen = e:u32be(), e:u32be() + if e.err then + ext.instrExt, ext.infoOff, ext.nameOff, ext.annoOff = 0, 0, 0, 0 + end + end + if ext.nameOff > 0 and ext.nameLen > 0 then + m.title = r:sub(ext.nameOff, math.min(ext.nameLen, 256)):fixed(math.min(ext.nameLen, 256)) + end + -- instruments and samples + local needInstruments = false + local instruments, samples = {}, {} + local unsupported = {} + for ins = 1, numSamples do + local smpHead = sh:sub((ins - 1) * 8, 8) + local loopStart, loopLen = smpHead:u16be() * 2, smpHead:u16be() * 2 + local midiCh, _midiPreset, volume, transpose = smpHead:u8(), smpHead:u8(), smpHead:u8(), smpHead:i8() + local x = { hold = 0, decay = 0, finetune = 0, pitch = 0, flags = 0, loopStart = 0, loopLen = 0, volume = 0 } + local xsize = 0 + if ext.instrExt > 0 and ins <= ext.instrExtN then + xsize = ext.instrExtSize + local xr = r:sub(ext.instrExt + (ins - 1) * xsize, xsize) + x.hold, x.decay = xr:u8(), xr:u8() + xr:skip(1) + x.finetune = xr:i8() + x.pitch, x.flags = xr:u8(), xr:u8() + xr:skip(4) + x.loopStart, x.loopLen = xr:u32be(), xr:u32be() + x.volume = xr:u8() + end + local name = "" + if ext.infoOff > 0 and ins <= ext.infoN then + name = r:sub(ext.infoOff + (ins - 1) * ext.infoSize, math.min(ext.infoSize, 40)):fixed(math.min(ext.infoSize, 40)) + end + local instr = Tracker.newInstrument(name) + instruments[ins] = instr + local iptr = (smpOff > 0 and{(r:sub(smpOff + (ins - 1) * 4, 4):u32be() )}or{0 +})[1] local length, typ = 0, 0 + if iptr > 0 then + local ih = r:sub(iptr, 6) + length, typ = ih:u32be(), ih:i16be() + if ih.err then + length, typ = 0, 0 + end + end + local isSynth = typ < 0 + local masked = bit32.band(typ % 65536, 0x0F) + local count = (not isSynth and{(SAMPLES_PER_TYPE[masked] or 1) }or{1 +})[1] if isSynth then + table.insert(unsupported, "synth / hybrid instrument " .. ins) + needInstruments = needInstruments or typ == -1 or typ == -2 + end + if midiCh > 0 and midiCh <= 16 then + needInstruments = true + table.insert(unsupported, "MIDI instrument " .. ins) + end + local first = #samples + 1 + -- keymap: one sample per note, multi-octave samples spread over the octaves + for n = 1, 120 do + instr.sampleMap[n] = first + end + if count > 1 then + needInstruments = true + for n = 1, 120 do + local note = n + 11 + transpose -- OpenMPT's keyboard index + if note < 0 then + note = -note % 12 + end + local oct = math.clamp(math.floor(note / 12 )- 4, 0, 7) + instr.sampleMap[n] = first + OCT_SAMPLE[count - 1][oct + 1] + instr.noteMap[n] = math.clamp(1 + note + OCT_TRANSPOSE[count - 1][oct + 1] - 12, 1, 120) + end + transpose = 0 + elseif masked == 7 then + needInstruments = true -- two extra-low octaves + for n = 1, 120 do + instr.noteMap[n] = math.clamp(n - 24, 1, 120) + end + end + if midiCh == 0 then + -- notes past the mixer's range fold down (by octaves) + local top = 61 + (hardwareMix and 24 or 36) + for n = 1, 120 do + local real = instr.noteMap[n] + 12 + transpose + if real >= top then + instr.noteMap[n] = math.max(1, instr.noteMap[n] - ((real - top + 12) - (real - top + 12) % 12)) + end + end + end + -- sample data + local list = {} + for i = 0, count - 1 do + local s = Tracker.newSample(name) + s.volume = math.min(volume, 64) + s.relativeNote = transpose + list[i + 1] = s + samples[first + i] = s + end + local hasLoop = loopLen > 2 + if not isSynth and iptr > 0 and length > 0 then + local bits = bit32.band(typ, 0x10) ~= 0 and 16 or 8 + local stereo = bit32.band(typ, 0x20) ~= 0 + local nchs = stereo and 2 or 1 + local bytes = length * nchs + local frames = math.floor(length / (math.floor(bits / 8)) +) if count > 1 then + frames =math.floor(frames/ (2 ^ count - 1) +) end + local pos = r.base + iptr + 6 + local ls, le = loopStart, loopStart + loopLen + for i = 1, count do + local s = list[i] + local spec = { bits = bits, signed = true, bigEndian = true, channels = nchs, planar = stereo, delta = bit32.band(typ, 0x40) ~= 0, limit = math.min(r.limit, r.base + iptr + 6 + bytes) } + local ok, err = Load.readSample(r.buf, pos, frames, spec, s, budget) + if not ok then + return nil, err + end + pos =pos+ math.floor(frames * nchs * bits / 8 +) if hasLoop then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, s.length), 1 + end + frames, ls, le = frames * 2, ls * 2, le * 2 + end + end + -- the instrument extras + if xsize > 0 then + if x.hold > 0 and not isSynth then + local env = Tracker.newEnvelope() + env.enabled = true + local fall = x.hold + ((x.decay > 0 and{(math.floor(64 / x.decay ))}or{0})[1]) + if x.hold == 1 then + env.ticks, env.values = { 0, fall }, { 64, 0 } + else + env.ticks, env.values = { 0, x.hold - 1, fall }, { 64, 64, 0 } + end + instr.volEnv = env + instr.fadeout = (x.decay > 0 and{(math.min(x.decay * 512, 65535) )}or{32767 +})[1] needInstruments = true + end + if xsize > 4 and x.pitch ~= 0 then + instr.noteMap[24 - 12 + 1] = math.clamp(x.pitch + 1 + 23 - 12, 1, 120) + needInstruments = true + end + if xsize > 18 then + instr.globalVolume = math.floor((x.volume + 1) / 2 )* 2 + end + local ls, le = x.loopStart, x.loopStart + x.loopLen + for _, s in __iter(list) do + s.finetune = math.clamp(x.finetune * 16, -128, 127) + if not isSynth and xsize > 14 then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + ls, le = ls * 2, le * 2 + end + if xsize > 5 then + if not isSynth then + s.loopType = bit32.band(x.flags, 1) == 0 and 0 or(bit32.band(x.flags, 8) ~= 0 and 2 or 1 +) end + if bit32.band(x.flags, 4) ~= 0 then + s.globalVolume = 0 + end + end + end + end + end + -- the play order: MMD0 / MMD1 a sequence of blocks; MMD2 / MMD3 sections of play sequences (stop / jump commands) + local jumps= {} + local preamp = 32 + if version < 2 then + if songLength > 256 then + return nil, Err.new(Err.CORRUPT, "bad song length") + end + for i = 1, songLength do + m.order[i] = seq:u8() + end + for i = 1, nch do + local k = (i - 1) % 4 + m.channelPan[i] = (k == 1 or k == 2 )and 0xC0 or 0x40 + if i <= 16 then + m.channelVolume[i] = math.min(trackVol[i], 64) + end + end + else + local s2 = song:sub(4, 256) + local playSeqTable, sectionTable, trackVolsOff = s2:u32be(), s2:u32be(), s2:u32be() + local numTracks, numPlaySeqs = s2:u16be(), s2:u16be() + local trackPanOff, flags3, volAdjust = s2:u32be(), s2:u32be(), s2:u16be() + if numTracks < 1 or numTracks > 64 then + return nil, Err.new(Err.CORRUPT, "bad track count") + end + local freePan = not hardwareMix and bit32.band(flags3, 2) ~= 0 + if volAdjust > 0 then + preamp = math.floor((preamp * math.min(volAdjust, 800) + 50) / 100 +) end + if freePan then + preamp =math.floor(preamp/ 2 +) end + if trackVolsOff > 0 then + for i = 1, nch do + m.channelVolume[i] = math.min(r:sub(trackVolsOff + i - 1, 1):u8(), 64) + end + end + local pans = (freePan or version > 2) and trackPanOff > 0 + for i = 1, nch do + if pans then + m.channelPan[i] = (math.clamp(r:sub(trackPanOff + i - 1, 1):i8(), -16, 16) + 16) * 8 + else + local k = (i - 1) % 4 + m.channelPan[i] = (k == 1 or k == 2 )and 0xC0 or 0x40 + end + end + local sections = r:sub(sectionTable, songLength * 2) + for _ = 1, songLength do + local sec = sections:u16be() + if sections.err then + break + end + if sec <= numPlaySeqs then + local ps = r:sub(playSeqTable + sec * 4, 4):u32be() + local pr = r:sub(ps, 42) + pr:skip(32) + local cmdTable = pr:u32be() + pr:skip(4) + local len = pr:u16be() + if not pr.err then + if #m.order > 0 then + table.insert(m.order, 254) + end + local start = #m.order + local er = r:sub(ps + 42, len * 2) + for _ = 1, len do + local b = er:u16be() + if er.err then + break + end + if b < 0x8000 then + table.insert(m.order, math.min(b, 253)) + end + end + if cmdTable > 0 then + local cr = r:sub(cmdTable) + for _ = 1, 4096 do + local off, c, extra = cr:u16be(), cr:u8(), cr:u8() + local arg = (extra >= 2 and{(cr:sub(cr:tell(), 2):u16be() )}or{0 +})[1] cr:skip(extra) + local at = start + off + 1 + if cr.err or off == 0xFFFF or at > #m.order then + break + end + if c == 1 then + m.order[at] = 255 + elseif c == 2 then + jumps[at] = arg + m.order[at] = 254 + end + end + end + end + end + end + end + m.preamp = preamp + -- tempo, speed, volume, the pattern context + local ctx= { + transpose = 36 + playTranspose - (version > 2 and 24 or 0), + is8Ch = bit32.band(flags, 0x40) ~= 0, + softMix = bit32.band(flags2, 0x80) ~= 0, + bpm = bit32.band(flags2, 0x20) ~= 0, + rowsPerBeat = 1 + bit32.band(flags2, 0x1F), + volHex = bit32.band(flags, 0x10) ~= 0, + vol7bit = false, + } + m.tempo = tempoToBpm(defTempo, ctx) + m.speed = math.clamp(tempo2, 1, 32) + if masterVol > 0 then + m.globalVolume = math.min(masterVol, 64) * 2 + end + -- blocks + for b = 0, numBlocks - 1 do + local p = blockPtr[b + 1] + local pat, high = nil, false + if p and p > 0 then + pat, high = readBlock(r, p, version, ctx, nch) + end + m.patterns[b + 1] = pat or Tracker.newPattern(64, nch) + needInstruments = needInstruments or high + end + -- play-sequence jumps: a jump effect at the end of the block before the command + for at, to in __iter(jumps) do + local prev = m.order[at - 1] + if prev and prev < 254 and m.patterns[prev + 1] then + -- the block may be played elsewhere: give this order entry its own copy + local src = m.patterns[prev + 1] + local cp = Tracker.newPattern(src.rows, nch) + buffer.copy(cp.data, 0, src.data) + table.insert(m.patterns, cp) + m.order[at - 1] = #m.patterns - 1 + Load.writeEffect(m, #m.patterns - 1, cp.rows - 1, 0xB, math.min(to, 255), "prev") + end + end + m.samples = samples + if needInstruments then + m.instrumentMode = true + m.instruments = instruments + end + if #unsupported > 0 then + m.meta.unsupported = unsupported + end + if ext.annoOff > 0 and ext.annoLen > 1 then + m.meta.message = r:sub(ext.annoOff, ext.annoLen - 1):string(math.min(ext.annoLen - 1, r:size())) + end + m.meta.source = { format = "med", version = "MMD" .. version, instruments = needInstruments } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Med.open(r, opts) +local m, err = Med.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Med +end +__FILES["music/midi"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the +-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). +-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / +-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: +-- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to +-- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), encode (running +-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and +-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set. +-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Smf = __include("music/midi/Smf") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Midi = { + name = "midi", + category = "music", + extensions = { "mid", "midi", "smf", "kar", "rmi" }, + mime = { "audio/midi", "audio/x-midi" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, + caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + +function Midi.sniff(r) +if r:peek(4) == "MThd" then + return 1 + end + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and +-- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +local function karaoke(midi) + local lyrics= {} + local headers= {} + local map = Render.tempoMap(midi) + local kar, hasWords = false, false + for _, t in __iter(midi.tracks) do + if t.name == "Words" then + kar, hasWords = true, true + end + for _, ev in __iter(t.events) do + if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then + local c = ev.data[2] + if c == 75 or c == 84 then -- @K, @T + kar = true + end + end + end + end + for ti, t in __iter(midi.tracks) do + local tmap = (midi.format == 2 and{(Render.tempoMap(midi, ti) )}or{map +})[1] local words = kar and (t.name == "Words" or not hasWords) + for _, ev in __iter(t.events) do + if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then + local text = Smf.text(ev.data ) + if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then + local key = string.sub(text, 2, 2) + local list = headers[key] or {} + headers[key] = list + table.insert(list, string.sub(text, 3)) + else + table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text }) + end + end + end + end + if #lyrics == 0 and next(headers) == nil then + return + end + table.sort(lyrics, function(a, b) +return a.time < b.time + end) + midi.meta.lyrics = lyrics + midi.meta.karaoke = headers + local tags= {} + if headers.T then + tags.title = headers.T[1] + tags.artist = headers.T[2] + end + if headers.L then + tags.language = headers.L[1] + end + if headers.I then + tags.comment = table.concat(headers.I, "\n") + end + midi.meta.tags = tags +end + +function Midi.decode(r, opts) +local midi, err = Smf.read(r, opts) + if not midi then + return nil, err + end + Render.attach(midi, { format = "midi", smf = midi.format }) + karaoke(midi) + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Midi.encode(midi, opts) +return Smf.write(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions) +function Midi.open(r, opts) +local midi, err = Midi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new) +function Midi.render(midi, opts) +return Render.decoder(midi, opts) +end + +-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map) +function Midi.tickToSeconds(midi, tick, track) +return Render.seconds(Render.tempoMap(midi, track), tick) +end + +-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points) +Midi.tempoMap = Render.tempoMap +Midi.seconds = Render.seconds + +-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1) +function Midi.length(midi) +return Render.length(midi) +end + +-- text(data) -> the bytes of a text meta event as a string +Midi.text = Smf.text + +return Midi +end +__FILES["music/midi/Smf"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE +-- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps +-- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are +-- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the +-- end, mid-track end-of-track events dropped); a track's name is written as a 0x03 event at tick 0 when the track +-- has none. Written from the SMF 1.0 specification (no third-party code). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +local Smf = {} + +local readu8 = buffer.readu8 + +local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } +local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } +Smf.TYPE_STATUS = TYPE_STATUS + + + + + + + + + +local function bytesOf(b, p, n) +local t= (table.create(n) ) +for i = 0, n - 1 do + t[i + 1] = readu8(b, p + i) + end + return t +end + +local function text(data) +local parts = table.create(#data) + for i, c in __iter(data) do + parts[i] = string.char(c) + end + return table.concat(parts) +end +Smf.text = text + +-- ------------------------------------------------------------------------------------------------ read +-- one MTrk body [p, e): events | nil, message, truncated +local function readTrack(b, p, e, budget) +local events= {} + local tick = 0 + local running = 0 + while p < e do + -- delta time + local delta, n = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p =p+ 1 + n =n+ 1 + delta = delta * 128 + c % 128 + if n > 4 then + return nil, "delta time longer than 4 bytes", false + end + until c < 128 + tick =tick+ delta + if p >= e then + return events, nil, true + end + local status = readu8(b, p) + if status < 0x80 then + if running == 0 then + return nil, "running status without a previous status byte", false + end + status = running + else + p =p+ 1 + if status < 0xF0 then + running = status + end + end + budget[1]=budget[1]- 1 + if budget[1] < 0 then + return nil, "LIMIT", false + end + if status == 0xFF or status == 0xF0 or status == 0xF7 then + local mtype = 0 + if status == 0xFF then + if p >= e then + return events, nil, true + end + mtype = readu8(b, p) + p =p+ 1 + end + local len, m = 0, 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p =p+ 1 + m =m+ 1 + len = len * 128 + c % 128 + if m > 4 then + return nil, "length longer than 4 bytes", false + end + until c < 128 + if p + len > e then + return events, nil, true + end + local data = bytesOf(b, p, len) + p =p+ len + if status == 0xFF then + table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) + else + table.insert(events, { tick = tick, type = status == 0xF0 and"sysex" or"escape", data = data }) + end + elseif status >= 0xF0 then + return nil, string.format("unexpected status byte 0x%02x in a track", status), false + else + local kind = math.floor(status / 16 +) local count = (kind == 12 or kind == 13 )and 1 or 2 + if p + count > e then + return events, nil, true + end + local d1 = readu8(b, p) + local d2 = (count == 2 and{(readu8(b, p + 1) )}or{0 +})[1] if d1 >= 128 or d2 >= 128 then + return nil, "data byte over 127", false + end + p =p+ count + table.insert(events, { + tick = tick, + type = CHANNEL_TYPES[kind], + channel = status % 16, + data = count == 2 and{ d1, d2 } or{ d1 }, + }) + end + end + return events, nil, false +end + +-- read(r, opts?) -> Midi | nil, Err +function Smf.read(r, opts) +local strict = opts and opts.strict or false + local budget = { opts and opts.maxEvents or 2 ^ 24 } + local b = r.buf + local base, limit = r.base, r.limit + local rmid = false + -- RIFF RMID: the SMF is the "data" chunk + if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then + local q = base + 12 + local found = false + while q + 8 <= limit do + local id = buffer.readstring(b, q, 4) + local size = buffer.readu32(b, q + 4) + if id == "data" then + base = q + 8 + limit = math.min(limit, base + size) + found = true + break + end + q =q+ (8 + size + size % 2 +) end + if not found then + return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) + end + rmid = true + end + local h = Bytes.reader(b, base, limit - base) + if h:string(4) ~= "MThd" then + return nil, Err.new(Err.CORRUPT, "no MThd header", base) + end + local hlen = h:u32be() + local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() + if h.err then + return nil, h.err + end + if hlen < 6 then + return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) + end + if format > 2 then + return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) + end + if division == 0 then + return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) + end + local midi = Types.Midi.new(division) + midi.format = format + local truncated = false + local p = base + 8 + hlen + while #midi.tracks < ntrks and p + 8 <= limit do + local id = buffer.readstring(b, p, 4) + local size = bit32.byteswap(buffer.readu32(b, p + 4)) + local s = p + 8 + local e = s + size + if e > limit then + e = limit + truncated = true + end + if id == "MTrk" then + local events, msg, short = readTrack(b, s, e, budget) + if not events then + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "over the event limit") + end + return nil, Err.new(Err.CORRUPT, msg or "bad track", s) + end + truncated = truncated or short + local track= { events = events, name = nil } + for _, ev in __iter(events) do + if ev.type == "meta" and ev.meta == 3 then + track.name = text(ev.data ) + break + end + end + table.insert(midi.tracks, track) + end + p = s + size + end + if #midi.tracks < ntrks and p < limit then + truncated = true + elseif #midi.tracks < ntrks then + truncated = true + end + if truncated and strict then + return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") + end + midi.meta.declaredTracks = ntrks + midi.meta.truncated = truncated + midi.meta.rmid = rmid + if division < 0 then + local fps = -(math.floor(division / 256)) + midi.meta.smpte = { fps = fps == 29 and 29.97 or fps, ticksPerFrame = division % 256 } + end + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function vlq(w, v) + if v < 128 then + w:u8(v) + return + end + local bytes = {} + while v > 0 do + table.insert(bytes, 1, v % 128) + v = math.floor(v / 128 +) end + for i, c in __iter(bytes) do + w:u8((i < #bytes and((c + 128 ))or(c))) + end +end + +local function byteList(d, want) +if type(d) ~= "table" then + return want == 0 and{} or nil + end + for i, v in __iter(d) do + if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then + return nil + end + end + if want and #d < want then + return nil + end + return d +end + +-- write(midi, opts?) -> buffer | nil, Err +function Smf.write(midi, opts) +if type(midi) ~= "table" or type(midi.tracks) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Midi value with tracks") + end + local running = not (opts and opts.runningStatus == false) + local format = midi.format or 1 + local division = midi.division or 480 + if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then + return nil, Err.new(Err.ARG, "format must be 0, 1 or 2") + end + if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then + return nil, Err.new(Err.ARG, "division must be a non-zero 16-bit integer") + end + if format == 0 and #midi.tracks ~= 1 then + return nil, Err.new(Err.ARG, "format 0 needs exactly one track") + end + if #midi.tracks > 65535 then + return nil, Err.new(Err.ARG, "too many tracks") + end + local w = Bytes.writer(1024) + w:string("MThd") + w:u32be(6) + w:u16be(format) + w:u16be(#midi.tracks) + w:u16be((division < 0 and((division + 65536 ))or(division))) + for ti, track in __iter(midi.tracks) do + local events = (type(track) == "table" and{track.events }or{nil +})[1] if type(events) ~= "table" then + return nil, Err.new(Err.ARG, "track " .. ti .. " has no events list") + end + -- stable order by tick + local sorted = true + local last = 0 + for i, ev in __iter(events) do + if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) + end + if ev.tick < last then + sorted = false + end + last = ev.tick + end + local list= events + if not sorted then + list = table.clone(events) + local order= {} + for i, ev in __iter(list) do + order[ev] = i + end + table.sort(list, function(a, c) +if a.tick ~= c.tick then + return a.tick < c.tick + end + return order[a] < order[c] + end) + end + -- track.name: written as a track-name meta event (0x03) at tick 0 when the track has none of its own + if type(track.name) == "string" and track.name ~= "" then + local named = false + for _, ev in __iter(list) do + if ev.type == "meta" and ev.meta == 0x03 then + named = true + break + end + end + if not named then + local bytes = { string.byte(track.name, 1, math.min(#track.name, 4096)) } + list = table.clone(list) + table.insert(list, 1, { tick = 0, type = "meta", meta = 0x03, data = bytes }) + end + end + w:string("MTrk") + local lenAt = w:tell() + w:u32be(0) + local start = w:tell() + local prev = 0 + local status = 0 + local endTick = 0 + for i, ev in __iter(list) do +local __DARKLUA_CONTINUE_16=false repeat local t = ev.type + endTick = ev.tick + if t == "meta" and ev.meta == 0x2F then +__DARKLUA_CONTINUE_16=true break -- written once at the end + end + local delta = ev.tick - prev + if delta > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "a delta time over 0x0FFFFFFF ticks") + end + local base = TYPE_STATUS[t] + if base then + local ch = ev.channel or 0 + if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) + end + local n = (base == 0xC0 or base == 0xD0 )and 1 or 2 + local d = byteList(ev.data, n) + if not d or d[1] > 127 or (n == 2 and d[2] > 127) then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) + end + vlq(w, delta) + local st = base + ch + if not (running and st == status) then + w:u8(st) + end + status = st + w:u8(d[1]) + if n == 2 then + w:u8(d[2]) + end + elseif t == "meta" or t == "sysex" or t == "escape" then + local d = byteList(ev.data, 0) + if not d then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) + end + vlq(w, delta) + if t == "meta" then + local m = ev.meta + if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) + end + w:u8(0xFF) + w:u8(m) + else + w:u8(t == "sysex" and 0xF0 or 0xF7) + end + if #d > 0x0FFFFFFF then + return nil, Err.new(Err.ARG, "event data too long") + end + vlq(w, #d) + for _, c in __iter(d) do + w:u8(c) + end + status = 0 + else + return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) + end + prev = ev.tick +__DARKLUA_CONTINUE_16=true until true if not __DARKLUA_CONTINUE_16 then break end end + vlq(w, math.max(0, endTick - prev)) + w:u8(0xFF) + w:u8(0x2F) + w:u8(0) + w:setU32be(lenAt, w:tell() - start) + end + return w:finish(), nil +end + +return Smf +end +__FILES["music/mod"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, +-- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through +-- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" +-- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). +-- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter +-- (E0x), PowerPacker-packed files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Mod = { + name = "mod", + category = "music", + extensions = { "mod", "m15", "stk", "nst" }, + mime = { "audio/x-mod", "audio/mod" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local Pcm = Tracker.Pcm +local Tables = Tracker.Tables + +local FIXED= { + ["M.K."] = 4, + ["M!K!"] = 4, + ["M&K!"] = 4, + ["N.T."] = 4, + ["FLT4"] = 4, + ["FLT8"] = 8, + ["CD81"] = 8, + ["OKTA"] = 8, + ["OCTA"] = 8, + ["EXO4"] = 4, + ["EXO8"] = 8, +} + +-- channels from the 4-byte signature at 1080, or nil +local function signatureChannels(sig) +local fixed = FIXED[sig] + if fixed then + return fixed + end + local d = string.match(sig, "^(%d)CHN$") + if d then + local n = (tonumber(d) ) +return (n >= 1 and{n }or{nil +})[1] end + local dd = string.match(sig, "^(%d%d)C[HN]$") + if dd then + local n = (tonumber(dd) ) +return (n >= 1 and n <= 32 and{n }or{nil +})[1] end + local t = string.match(sig, "^TDZ(%d)$") + if t then + local n = (tonumber(t) ) +return (n >= 1 and{n }or{nil +})[1] end + return nil +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Mod.sniff(r) +if r:size() < 1084 then + return 0 + end + local sig = r:peek(4, 1080) + if signatureChannels(sig) then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Mod.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 26 + local size = r:size() + local sig = (size >= 1084 and{(r:peek(4, 1080) )}or{"" +})[1] local channels = signatureChannels(sig) + local nsamples = 31 + if not channels then + -- a 15-sample Soundtracker module (no signature): only when the header is plausible + nsamples, channels = 15, 4 + end + local nch = channels +local m = Tracker.newModule("mod", nch) + m.title = r:fixed(20) + local lengths= {} + for i = 1, nsamples do + local s = Tracker.newSample(r:fixed(22)) + local len = r:u16be() * 2 + local ft = r:u8() % 16 + local vol = r:u8() + local ls = r:u16be() * 2 + local ll = r:u16be() * 2 + if r.err then + return nil, r.err + end + if nsamples == 15 and (vol > 64 or ft ~= 0) then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad sample header)") + end + s.finetune = ((ft >= 8 and((ft - 16 ))or(ft))) * 16 + s.volume = math.min(vol, 64) + s.bits = 8 + if ll > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, ls + ll, 1 + end + lengths[i] = len + m.samples[i] = s + end + local songLength = r:u8() + local restart = r:u8() + local order= {} + local maxPat = 0 + for i = 1, 128 do + local p = r:u8() + order[i] = p + maxPat = math.max(maxPat, p) + end + if r.err then + return nil, r.err + end + if songLength == 0 or songLength > 128 or maxPat >= 128 then + return nil, Err.new(Err.CORRUPT, "not a MOD (bad order list)") + end + if nsamples == 31 then + r:skip(4) + end + for i = 1, songLength do + m.order[i] = order[i] + end + m.restart = (restart < songLength and{restart }or{0 +})[1] m.meta.signature = (nsamples == 31 and{sig }or{nil +})[1] m.flags.amigaLimits = nch == 4 + -- patterns + local npat = maxPat + 1 + local patBytes = 64 * nch * 4 + if not r:need(npat * patBytes) then + return nil, r.err + end + local buf = r.buf + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, nch) + local base = r.pos + p * patBytes + local d = pat.data + for i = 0, 64 * nch - 1 do + local o = base + i * 4 + local b0, b1, b2, b3 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2), buffer.readu8(buf, o + 3) + local period = (b0 % 16) * 256 + b1 + local ins = (math.floor(b0 / 16)) * 16 + math.floor(b2 / 16 +) local q = i * 5 + buffer.writeu8(d, q, Tables.periodToNote(period)) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 3, b2 % 16) + buffer.writeu8(d, q + 4, b3) + end + m.patterns[p + 1] = pat + end + r:skip(npat * patBytes) + -- sample data (8-bit signed; the last samples of a truncated file are cut short) + local total = 0 + for i = 1, nsamples do + local s = m.samples[i] + local len = math.min(lengths[i], r:remaining()) + total =total+ len * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(buf, r.pos, len, { bits = 8, signed = true }) + if not data then + return nil, Err.new(Err.TRUNCATED, "sample data", r.pos) + end + r:skip(len) + s.data, s.length = data, len + if s.loopEnd > len then + s.loopEnd = len + if s.loopEnd - s.loopStart < 2 then + s.loopType, s.loopStart, s.loopEnd = 0, 0, 0 + end + end + end + m.meta.source = { format = "mod", samples = nsamples } + m.render = Tracker.renderMethod + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w, s, n) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- encode(module) -> MOD bytes. The module must be "mod", or an "xm" module whose instruments each map every note to +-- one sample; patterns must have 64 rows, at most 31 samples, effects 0..F. +function Mod.encode(m, _opts) +local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "mod" and m.format ~= "xm" then + return nil, Err.new(Err.UNSUPPORTED, "only mod and xm modules can be written as MOD (got " .. tostring(m.format) .. "); xm is the closest writable format") + end + local nch = m.channels + if nch > 32 then + return nil, Err.new(Err.ARG, "MOD holds at most 32 channels") + end + -- the sample for each instrument number + local smpOf= {} + if m.format == "xm" then + for i, ins in __iter(m.instruments) do + local first = 0 + for n = 1, 120 do + local s = ins.sampleMap[n] + if s ~= 0 then + if first ~= 0 and s ~= first then + return nil, Err.new(Err.ARG, "instrument " .. i .. " uses several samples") + end + first = s + end + end + smpOf[i] = m.samples[first] or Tracker.newSample(ins.name) + end + else + for i, s in __iter(m.samples) do + smpOf[i] = s + end + end + if #smpOf > 31 then + return nil, Err.new(Err.ARG, "MOD holds at most 31 samples") + end + local order= {} + for _, o in __iter(m.order) do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order == 0 or #order > 128 then + return nil, Err.new(Err.ARG, "MOD needs 1..128 order entries") + end + local npat = #m.patterns + if npat > 100 then + return nil, Err.new(Err.ARG, "too many patterns for MOD") + end + for p, pat in __iter(m.patterns) do + if pat.rows ~= 64 then + return nil, Err.new(Err.ARG, "pattern " .. (p - 1) .. " has " .. pat.rows .. " rows (MOD patterns have 64)") + end + end + local w = Bytes.writer(1084 + npat * 64 * nch * 4 + 65536) + writeName(w, m.title or "", 20) + local datas= {} + for i = 1, 31 do + local s = smpOf[i] + if s then + local len = math.min(s.length, 131070) + local pcm = Pcm.encode(s.data, len, { bits = 8, signed = true, channels = 1 }) + if s.channels == 2 then + -- mix stereo samples down + local mono = buffer.create(len * 4) + for k = 0, len - 1 do + buffer.writef32(mono, k * 4, (buffer.readf32(s.data, k * 8) + buffer.readf32(s.data, k * 8 + 4)) / 2) + end + pcm = Pcm.encode(mono, len, { bits = 8, signed = true }) + end + local even = len + len % 2 + local padded = buffer.create(even) + buffer.copy(padded, 0, pcm, 0, len) + datas[i] = padded + writeName(w, s.name or "", 22) + w:u16be(math.floor(even / 2)) + local ft = math.clamp(math.floor((s.finetune or 0) / 16 + 0.5), -8, 7) + w:u8(ft % 16) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + if s.loopType > 0 and s.loopEnd <= even then + w:u16be(math.floor(s.loopStart / 2)) + w:u16be(math.max(1, math.floor((s.loopEnd - s.loopStart) / 2))) + else + w:u16be(0) + w:u16be(1) + end + else + w:fill(0, 22) + w:u16be(0) + w:u8(0) + w:u8(0) + w:u16be(0) + w:u16be(1) + end + end + w:u8(#order) + w:u8((m.restart < #order and m.restart > 0 and{m.restart }or{127})[1]) + for i = 1, 128 do + w:u8(order[i] or 0) + end + local sig + if nch == 4 then + sig = npat > 64 and"M!K!" or"M.K." + elseif nch < 10 then + sig = nch .. "CHN" + else + sig = nch .. "CH" + end + w:string(sig) + for p = 1, npat do + local d = m.patterns[p].data + for i = 0, 64 * nch - 1 do + local q = i * 5 + local note, ins, fx, param = buffer.readu8(d, q), buffer.readu8(d, q + 1), buffer.readu8(d, q + 3), buffer.readu8(d, q + 4) + local period = (note >= 1 and note <= 120 and{(Tables.noteToPeriod(note) )}or{0 +})[1] if period > 4095 then + period = 0 + end + if fx > 15 then + fx, param = 0, 0 + end + if ins > 31 then + ins = 0 + end + w:u8((math.floor(ins / 16)) * 16 + math.floor(period / 256)) + w:u8(period % 256) + w:u8((ins % 16) * 16 + fx) + w:u8(param) + end + end + for i = 1, 31 do + if datas[i] then + w:bytes(datas[i]) + end + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mod.open(r, opts) +local m, err = Mod.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mod +end +__FILES["music/mtm"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- music/mtm: MultiTracker modules (MTM, Renaissance's DOS tracker, 1..32 channels; patterns built from shared +-- tracks). Ported from OpenMPT's Load_mtm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "xm" effect family with Amiga periods (OpenMPT plays MTM like XM): +-- MOD effects (no 8xx panning, E8x pans), 8 / 16-bit unsigned samples, finetune, the song speed / tempo quirk +-- (MultiTracker resets the tempo on a speed command and the speed on a tempo command when they never share a row). +-- Not supported: MultiTracker's E9x / EDx retrigger timing and its vibrato start phase (played as in XM), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Mtm = { + name = "mtm", + category = "music", + extensions = { "mtm" }, + mime = { "audio/x-mtm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function Mtm.sniff(r) +if r:size() >= 66 and r:peek(3) == "MTM" and r:peekU8(3) < 0x20 and r:peekU8(33) >= 1 and r:peekU8(33) <= 32 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MultiTracker: a speed command resets the tempo to 125 and a tempo command the speed to 6, unless the module puts +-- both on one row somewhere (then it was written for players that treat them as ProTracker does) +local function speedTempoQuirk(m) + local speed, tempo, together = false, false, false + for _, p in __iter(m.patterns) do + for row = 0, p.rows - 1 do + local s, t = false, false + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + if param < 0x20 then + s = true + else + t = true + end + end + end + speed, tempo, together = speed or s, tempo or t, together or (s and t) + end + end + if not (speed and tempo) or together then + return + end + for pi, p in __iter(m.patterns) do + for row = 0, p.rows - 1 do + for c = 1, m.channels do + local o = (row * m.channels + c - 1) * 5 + local fx, param = buffer.readu8(p.data, o + 3), buffer.readu8(p.data, o + 4) + if fx == 0xF then + Load.writeEffect(m, pi - 1, row, 0xF, param < 0x20 and 125 or 6, nil, nil, true) + break + end + end + end + end +end + +function Mtm.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:size() < 66 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(3) ~= "MTM" then + return nil, Err.new(Err.CORRUPT, "no MTM signature") + end + r:skip(3) + local version = r:u8() + local title = r:fixed(20) + local numTracks, lastPattern, lastOrder = r:u16le(), r:u8(), r:u8() + local commentSize, numSamples, _attr, rowsPerTrack, nch = r:u16le(), r:u8(), r:u8(), r:u8(), r:u8() + local pans= {} + for i = 1, 32 do + pans[i] = r:u8() + end + if r.err then + return nil, r.err + end + if version >= 0x20 or lastOrder > 127 or rowsPerTrack > 64 or nch == 0 or nch > 32 then + return nil, Err.new(Err.CORRUPT, "bad header") + end + local m = Tracker.newModule("mtm", nch, "xm") + m.title = title + m.linear = false + m.instrumentMode = false + for i = 1, nch do + m.channelPan[i] = (pans[i] % 16) * 16 + 8 + end + -- samples + local sizes= {} + for i = 1, numSamples do + local s = Tracker.newSample(r:fixed(22)) + local len, ls, le = r:u32le(), r:u32le(), r:u32le() + local ft, vol, attr = r:i8(), r:u8(), r:u8() + if r.err then + return nil, r.err + end + s.volume = math.min(vol, 64) + s.finetune = math.clamp(ft * 16, -128, 127) + local bits = attr % 2 == 1 and 16 or 8 + s.bits = bits + local frames = 0 + if len > 2 then + frames = len + le = math.min(math.max(le, 1) - 1, len) + if ls + 4 >= le then + ls, le = 0, 0 + end + if bits == 16 then + frames, ls, le = math.floor(frames / 2), math.floor(ls / 2), math.floor(le / 2 +) end + if le > 2 then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + end + end + sizes[i] = (len > 2 and{len }or{0 +})[1] s.length = frames + m.samples[i] = s + end + -- the order list + for i = 1, 128 do + local o = r:u8() + if i <= lastOrder + 1 then + m.order[i] = o + end + end + if r.err then + return nil, r.err + end + -- tracks (64 rows of 3 bytes each) and the patterns made of them + local rows = (rowsPerTrack > 0 and{rowsPerTrack }or{64 +})[1] local tracks = r:tell() + if not r:skip(192 * numTracks) then + return nil, r.err + end + local buf = r.buf + for p = 0, lastPattern do + local pat = Tracker.newPattern(rows, nch) + m.patterns[p + 1] = pat + for ch = 0, 31 do + local track = r:u16le() + if r.err then + return nil, r.err + end + if track > 0 and track <= numTracks and ch < nch then + local base = r.base + tracks + 192 * (track - 1) + for row = 0, rows - 1 do + local o = base + row * 3 + local b0, b1, b2 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1), buffer.readu8(buf, o + 2) + local q = (row * nch + ch) * 5 + if b0 >= 4 then + buffer.writeu8(pat.data, q, math.floor(b0 / 4 )+ 25) -- C-4 = 49 plays the sample at 8363 Hz (OpenMPT keeps MTM / XM notes an octave up) + end + buffer.writeu8(pat.data, q + 1, (b0 % 4) * 16 + math.floor(b1 / 16)) + local cmd, param = b1 % 16, b2 + if cmd == 0xA then + param = (param >= 16 and((param - param % 16 ))or(param +)) elseif cmd == 8 then + cmd, param = 0, 0 -- no 8xx panning in MultiTracker + elseif cmd == 0xE then + local x = math.floor(param / 16 +) if x == 0 or x == 3 or x == 4 or x == 6 or x == 7 or x == 0xF then + cmd, param = 0, 0 -- not in MultiTracker + end + end + buffer.writeu8(pat.data, q + 3, cmd) + buffer.writeu8(pat.data, q + 4, param) + end + end + end + end + speedTempoQuirk(m) + -- the song message (40-character lines), then the sample data (unsigned PCM) + m.meta.message = r:string(commentSize) + if r.err then + r.err = nil + end + local pos = r.pos + for i = 1, numSamples do + local s = m.samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(buf, pos, s.length, { bits = s.bits, signed = false, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos =pos+ sizes[i] + s.loopEnd = math.min(s.loopEnd, s.length) + end + end + m.meta.source = { format = "mtm", version = version, tracks = numTracks } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Mtm.open(r, opts) +local m, err = Mtm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Mtm +end +__FILES["music/mus"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format +-- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter +-- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel +-- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at +-- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without +-- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per +-- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont / +-- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate. +-- Not supported: writing (save as .mid through the midi format's encoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Mus = { + name = "mus", + category = "music", + extensions = { "mus" }, + mime = { "audio/x-mus" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants +-- MUS controller / system event number -> MIDI controller (0 is the program change) + + + + + + +local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mus.sniff(r) +return r:peek(4) == "MUS\x1a" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +-- the score [p, e) -> events | nil, message +local function score(b, p, e, primary, maxEvents) +local events= { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } } + local map= { [15] = 9 } + local volume= {} + local nextChannel = 0 + local tick = 0 + while p < e do + local ev = readu8(b, p) + p =p+ 1 + local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15) + if kind == 6 then + return events, nil, false + end + local ch = map[mch] + if not ch then + ch = nextChannel + map[mch] = ch + nextChannel =nextChannel+ (nextChannel == 8 and 2 or 1 +) table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } }) + end + local need = (kind == 1 and{(p < e and readu8(b, p) >= 128 and 2 or 1) }or{kind == 4 and 2 or(kind == 5 and 0 or 1 +)})[1] if kind == 7 then + return nil, "unknown event type 7", false + elseif p + need > e then + return events, nil, true + end + local d1, d2 = (need > 0 and{(readu8(b, p) )}or{0})[1], (need > 1 and{(readu8(b, p + 1) )}or{0 +})[1] p =p+ need + if kind == 0 then + table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } }) + elseif kind == 1 then + if need == 2 then + volume[ch] = math.min(d2, 127) + end + table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } }) + elseif kind == 2 then + table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } }) + elseif kind == 3 or kind == 4 then + local c, v = d1, (kind == 3 and{((d1 == 12 and{(math.min(primary + 1, 127) )}or{0})[1]) }or{(math.min(d2, 127) +)})[1] if CONTROLLER[c] == nil then + return nil, string.format("unknown controller %d", c), false + end + if kind == 4 and c == 0 then + table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } }) + else + table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } }) + end + end + if #events > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events", false + end + if ev >= 128 then + local delay = 0 + repeat + if p >= e then + return events, nil, true + end + local c = readu8(b, p) + p =p+ 1 + delay = delay * 128 + c % 128 + until c < 128 or delay > 2 ^ 28 + tick =tick+ delay + end + end + return events, nil, true +end + +function Mus.decode(r, opts) +local o= opts or {} + local rate = o.rate or 140 + if type(rate) ~= "number" or rate < 1 or rate > 100000 then + return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second") + end + if r:peek(4) ~= "MUS\x1a" then + return nil, Err.new(Err.CORRUPT, "not a MUS file") + end + r:skip(4) + local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:skip(2) + local instruments = {} + for i = 1, ninst do + instruments[i] = r:u16le() + end + if r.err then + return nil, r.err + end + local size = r.limit - r.base + if start > size then + return nil, Err.new(Err.TRUNCATED, "score starts past the end") + end + local p = r.base + start + local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24) + if not events then + return nil, Err.from(msg , p) + end + local last = events[#events].tick + table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) }) + table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local midi = Types.Midi.new(70) + midi.format = 0 + midi.tracks = { { events = events } } + Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate }) + midi.meta.truncated = truncated or p + len > r.limit + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Mus.open(r, opts) +local midi, err = Mus.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Mus +end +__FILES["music/okt"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- music/okt: Oktalyzer modules (OKTASONG, Armin Sander's Amiga tracker; 4 to 8 channels: each of the Amiga's four can +-- be split into a mixed pair). Ported from OpenMPT's Load_okt.cpp (BSD, licenses/openmpt-LICENSE.txt). An IFF-style +-- chunk list (containers/Chunks) read into the codecs/audio/Tracker Module, played as the "it" effect family with +-- ProTracker periods and the PAL clock (flags.periods = "amiga"), Amiga period limits, slides on every tick, sample +-- loops as sustain loops (released by R), Oktalyzer's three arpeggios, note slides (D / U every tick, L / H once: +-- flags.oktSlides), and its volume command: on a mixed pair the volume is the pair's channel volume. +-- Not supported: the Amiga LED filter (F), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Okt = { + name = "okt", + category = "music", + extensions = { "okt", "okta" }, + mime = { "audio/x-okt" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + +local IT = Load.IT +local LAYOUT = (table.freeze({ bigEndian = true }) ) +-- ------------------------------------------------------------------------------------------------ sniff + +function Okt.sniff(r) +return r:peek(8) == "OKTASONG" and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a negative arpeggio offset as the equivalent positive one +local function invert(p) +p =p% 16 + if p == 0 then + return 0 + end + return (p <= 12 and((12 - p ))or((24 - p +)))end + +-- the Oktalyzer effect of a cell -> effect name?, param, volume (0..64, the volume column) or -1, a key off +local function effect(e, p, paired) +if e == 1 and p > 0 then + return "portaup", p, -1, false -- "portamento down (period)": the period goes down + elseif e == 2 and p > 0 then + return "portadown", p, -1, false + elseif e == 10 and p > 0 then + return "arpeggio", p % 16 + invert(math.floor(p / 16)) * 16, -1, false -- down, original, up + elseif e == 11 and p > 0 then + return "arpeggio", p - p % 16 + invert(p % 16), -1, false -- original, up, original, down + elseif e == 12 and p > 0 then + return "arpeggio", p, -1, false -- up, up, original + elseif e == 13 and p > 0 then + return "noteslidedown", 0x10 + math.min(p, 15), -1, false + elseif e == 30 and p > 0 then + return "noteslideup", 0x10 + math.min(p, 15), -1, false + elseif e == 21 and p > 0 then + return "noteslidedown", 0x50 + math.min(p, 15), -1, false + elseif e == 17 and p > 0 then + return "noteslideup", 0x50 + math.min(p, 15), -1, false + elseif e == 25 then + return "jump", p, -1, false + elseif e == 27 then + return nil, 0, -1, true + elseif e == 28 and p < 0x20 then + return "speed", p, -1, false + elseif e == 31 then + local x, y = math.floor(p / 16), p % 16 + local slide = paired and"chanvolslide" or"volslide" + if p <= 0x40 then + if paired then + return "chanvol", p, -1, false + end + return nil, 0, p, false + elseif x == 4 then + return slide, y, -1, false + elseif x == 5 then + return slide, y * 16, -1, false + elseif x == 6 then + return slide, 0xF0 + math.min(y, 0xE), -1, false + elseif x == 7 then + return slide, math.min(y, 0xE) * 16 + 0xF, -1, false + end + end + return nil, 0, -1, false +end + +function Okt.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if r:peek(8) ~= "OKTASONG" then + return nil, Err.new((r:size() < 8 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "no OKTASONG signature") + end + local buf = r.buf + local list = Chunks.walk(buf, r.base + 8, r.limit, LAYOUT) + local cmod = Chunks.find(list, "CMOD") + if not cmod or cmod.avail < 8 then + return nil, Err.new(Err.CORRUPT, "no channel table (CMOD)") + end + -- channels: each Amiga channel is one channel, or a mixed pair + local paired= {} -- 1: the first of a pair, -1: the second, 0: a raw Paula channel + local pans= {} + for ch = 0, 3 do + local pan = (ch == 1 or ch == 2 )and 0xC0 or 0x40 + if buffer.readu16(buf, cmod.offset + ch * 2) ~= 0 then + table.insert(paired, 1) + table.insert(pans, pan) + table.insert(paired, -1) + else + table.insert(paired, 0) + end + table.insert(pans, pan) + end + local nch = #paired + local m = Tracker.newModule("okt", nch, "it") + m.linear = false + m.instrumentMode = false + m.tempo = 125 + m.flags.periods, m.flags.amigaLimits, m.flags.fastPortas, m.flags.oktSlides = "amiga", true, true, true + for i = 1, nch do + m.channelPan[i] = pans[i] + end + -- samples: 32-byte headers (name, length, loop start / length in words, volume, type 0 / 1 / 2) + local types= {} + local samp = Chunks.find(list, "SAMP") + if samp then + for i = 1, math.min(math.floor(samp.avail / 32), 36) do + local h = Bytes.reader(buf, samp.offset + (i - 1) * 32, 32) + local s = Tracker.newSample(h:fixed(20)) + local len, ls, ll, vol, typ = h:u32be(), h:u16be() * 2, h:u16be() * 2, h:u16be(), h:u16be() + s.c5speed = 8287 + s.volume = math.min(vol, 64) + s.length = len - len % 2 + if ll > 2 and ls + ll <= s.length then + s.susStart, s.susEnd, s.susType = ls, ls + ll, 1 + end + types[i] = typ + m.samples[i] = s + end + end + local spee = Chunks.find(list, "SPEE") + if spee and spee.avail >= 2 then + m.speed = math.clamp(buffer.readu8(buf, spee.offset) * 256 + buffer.readu8(buf, spee.offset + 1), 1, 255) + end + local nord = 0 + local plen = Chunks.find(list, "PLEN") + if plen and plen.avail >= 2 then + nord = buffer.readu8(buf, plen.offset) * 256 + buffer.readu8(buf, plen.offset + 1) + end + local patt = Chunks.find(list, "PATT") + for i = 1, math.min(nord, (patt and{patt.avail }or{0})[1]) do + m.order[i] = buffer.readu8(buf, (patt ).offset + i - 1) + end + -- patterns (PBOD: rows, then 4 bytes per cell: note 1..36, sample, effect, parameter) + local copies= {} -- type B samples with a loop also need an unlooped copy (paired channels) + local npat = 0 + for _, c in __iter(list) do + if c.id == "PBOD" and npat < 256 then + local pr = Bytes.reader(buf, c.offset, c.avail) + local rows = (c.avail >= 2 and{(math.clamp(pr:u16be(), 1, 1024) )}or{64 +})[1] local pat = Tracker.newPattern(rows, nch) + npat =npat+ 1 + m.patterns[npat] = pat + local d = pat.data + for row = 0, rows - 1 do + for ch = 0, nch - 1 do + local note, ins, e, p = pr:u8(), pr:u8(), pr:u8(), pr:u8() + if pr.err then + break + end + local q = (row * nch + ch) * 5 + local pair = paired[ch + 1] ~= 0 + if note > 0 and note <= 36 then + local n = note + 36 -- note 13 = C-4 = ProTracker period 428 (OpenMPT keeps MOD notes an octave up) + if pair and n >= 49 + 22 then + n = 49 + 21 -- the mixer's highest note + end + local smp = ins + 1 + local s = m.samples[smp] + if s then + if pair and s.volume < 64 then + buffer.writeu8(d, q + 2, 64 + 1) -- the default volume only works on raw Paula channels + end + local t = types[smp] + if (t == 1 and pair) or (t == 0 and not pair) then + smp =smp+ 100 -- a sample of the wrong type stops the channel + elseif t == 2 and pair and s.susType > 0 then + copies[smp] = true + smp =smp+ 36 + end + end + buffer.writeu8(d, q, n) + buffer.writeu8(d, q + 1, smp) + end + local name, param, vol, off = effect(e, p, pair) + if off then + buffer.writeu8(d, q, 255) + buffer.writeu8(d, q + 1, 0) + end + if vol >= 0 then + buffer.writeu8(d, q + 2, vol + 1) + end + local fx, fp = Load.itEffect(name, param) + if fx ~= 0 then + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + if name == "chanvol" or name == "chanvolslide" then + -- a mixed pair shares its volume: the other channel gets it too (the second one wins) + local other = ch + paired[ch + 1] + local o2 = (row * nch + other) * 5 + local ofx = buffer.readu8(d, o2 + 3) + if ofx == 0 or ofx == IT.chanvol or ofx == IT.chanvolslide then + buffer.writeu8(d, o2 + 3, fx) + buffer.writeu8(d, o2 + 4, fp) + end + end + end + end + end + end + end + -- sample data: SBOD chunks in order (signed 8-bit), for the samples with a length + local k = 0 + local bodies= {} + for _, c in __iter(list) do + if c.id == "SBOD" and c.avail > 0 then + table.insert(bodies, c) + end + end + local nsmp = #m.samples + for i = 1, nsmp do +local __DARKLUA_CONTINUE_9=false repeat local s = m.samples[i] + if s.length > 0 then + k =k+ 1 + local c = bodies[k] + if not c then + s.length = 0 +__DARKLUA_CONTINUE_9=true break + end + local ok, err = Load.readSample(buf, c.offset, math.min(s.length, c.avail), { bits = 8, signed = true, limit = c.offset + c.avail }, s, budget) + if not ok then + return nil, err + end + end +__DARKLUA_CONTINUE_9=true until true if not __DARKLUA_CONTINUE_9 then break end end + for i = 1, nsmp do + local s = m.samples[i] + if copies[i] then + local cp = Tracker.newSample(s.name) + cp.c5speed, cp.volume, cp.data, cp.length = s.c5speed, s.volume, s.data, s.length + m.samples[i + 36] = cp + end + end + for i = 1, (next(copies) and 72 or nsmp) do + if m.samples[i] == nil then + m.samples[i] = Tracker.newSample() + end + end + m.meta.source = { format = "okt", channels = nch } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Okt.open(r, opts) +local m, err = Okt.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Okt +end +__FILES["music/ptm"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- music/ptm: PolyTracker modules (PTMF, Lone Ranger's DOS tracker; up to 32 channels, S3M-like packed patterns, MOD +-- effect letters). Ported from OpenMPT's Load_ptm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the +-- codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects and linked Gxx +-- memory (as OpenMPT converts PTM): MOD effects whose slides take S3M-style fine values, global volume, retrigger, +-- fine vibrato and the note slides (G..J: Tracker.EXT), delta-coded 8-bit and 16-bit samples (8-bit deltas of the +-- byte stream, as PolyTracker stores them), ping-pong loops. +-- Not supported: reverse sample offset (K), sample offsets scaled for 16-bit samples, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ptm = { + name = "ptm", + category = "music", + extensions = { "ptm" }, + mime = { "audio/x-ptm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants +-- PolyTracker's effects past MOD's 0..F + + + + +local EXTRA = { "globalvol", "retrig", "finevibrato", "noteslideup", "noteslidedown", "noteslideupretrig", "noteslidedownretrig" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r) +if r:size() < 608 or r:peek(4, 44) ~= "PTMF" or r:peekU8(28) ~= 26 or r:peekU8(30) > 2 then + return false + end + local h = r:sub(32, 10) + local nord, nsmp, npat, nch, flags = h:u16le(), h:u16le(), h:u16le(), h:u16le(), h:u16le() + return flags == 0 and nch >= 1 and nch <= 32 and nord >= 1 and nord <= 256 and nsmp >= 1 and nsmp <= 255 and npat >= 1 and npat <= 128 +end + +function Ptm.sniff(r) +return validHeader(r) and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- 16-bit samples: the byte stream is 8-bit delta coded, then read as little-endian 16-bit values +local function delta16(buf, off, frames, limit) +local n = math.max(0, math.min(frames, math.floor((limit - off) / 2))) + local raw = buffer.create(n * 2) + local acc = 0 + for i = 0, n * 2 - 1 do + acc = (acc + buffer.readu8(buf, off + i)) % 256 + buffer.writeu8(raw, i, acc) + end + return raw, n +end + +-- a PolyTracker effect -> name?, param +local function effect(cmd, param) +if cmd == 0x10 then + return "globalvol", math.min(param, 0x40) * 2 + elseif cmd > 0x10 then + return EXTRA[cmd - 0x10 + 1], param + elseif cmd == 8 then + return "s3mex", 0x80 + (math.max(math.floor(param / 8), 1) - 1) % 16 -- 8xx pans in 16 steps + end + return Load.modCommand(cmd, param) +end + +-- one pattern (S3M-style packing: 0 ends a row; channel | 0x20 note + instrument, 0x40 effect, 0x80 volume) +local function readPattern(pr, d, nch) + local row = 0 + while row < 64 and not pr:eof() do + local b = pr:u8() + if b == 0 then + row =row+ 1 + else + local ch = b % 32 + local q = (row * nch + ch) * 5 + local ok = ch < nch + if bit32.band(b, 0x20) ~= 0 then + local note, ins = pr:u8(), pr:u8() + if note == 254 then + note = 254 + elseif note == 0 or note > 120 then + note = 0 + end + if ok then + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + end + end + if bit32.band(b, 0x40) ~= 0 then + local name, param = effect(pr:u8(), pr:u8()) + if ok then + if name == "volume" then + if buffer.readu8(d, q + 2) == 0 then + buffer.writeu8(d, q + 2, math.min(param, 64) + 1) + end + else + local fx, fp = Load.itEffect(name, param) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, fp) + end + end + end + if bit32.band(b, 0x80) ~= 0 then + local v = pr:u8() + if ok then + buffer.writeu8(d, q + 2, math.min(v, 64) + 1) + end + end + end + end +end + +function Ptm.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new((r:size() < 608 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a PolyTracker module") + end + local title = r:fixed(28) + r:skip(1) + local vlo, vhi = r:u8(), r:u8() + r:skip(1) + local nord, nsmp, npat, nch = r:u16le(), r:u16le(), r:u16le(), r:u16le() + r:seek(64) + local m = Tracker.newModule("ptm", nch, "it") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx = true, true + m.flags.panLaw = "ft2" -- OpenMPT plays PTM with its FT2 mix levels + for i = 1, 32 do + local p = r:u8() + if i <= nch then + m.channelPan[i] = (p % 16) * 16 + 4 + end + end + for i = 1, 256 do + local o = r:u8() + if i <= nord then + m.order[i] = o + end + end + local patOff= {} + for i = 1, 128 do + patOff[i] = r:u16le() * 16 + end + if r.err then + return nil, r.err + end + -- samples + local buf = r.buf + for i = 1, nsmp do + local h = r:slice(80) + if r.err then + return nil, r.err + end + local flags = h:u8() + h:skip(12) + local vol, c4 = h:u8(), h:u16le() + h:skip(2) + local off, len, ls, le = h:u32le(), h:u32le(), h:u32le(), h:u32le() + h:skip(14) + local s = Tracker.newSample(h:fixed(28)) + m.samples[i] = s + s.volume = math.min(vol, 64) + s.c5speed = math.max(1, c4 * 2) + if flags % 4 == 1 and len > 0 then + local bits = bit32.band(flags, 0x10) ~= 0 and 16 or 8 + if le > ls then + le =le- 1 + end + local frames = len + if bits == 16 then + frames, ls, le = math.floor(frames / 2), math.floor(ls / 2), math.floor(le / 2 +) end + local at = r.base + off + if at < r.limit then + local ok, err + if bits == 16 then + local raw, n = delta16(buf, at, frames, r.limit) + ok, err = Load.readSample(raw, 0, n, { bits = 16, signed = true }, s, budget) + else + ok, err = Load.readSample(buf, at, frames, { bits = 8, signed = true, delta = true, limit = r.limit }, s, budget) + end + if not ok then + return nil, err + end + end + if bit32.band(flags, 4) ~= 0 and le > ls then + s.loopStart, s.loopEnd = ls, math.min(le, s.length) + s.loopType = bit32.band(flags, 8) ~= 0 and 2 or 1 + end + end + end + for p = 1, npat do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + if patOff[p] > 0 and patOff[p] < r:size() then + readPattern(r:sub(patOff[p]), pat.data, nch) + end + end + m.meta.source = { format = "ptm", version = string.format("%d.%02x", vhi, vlo) } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ptm.open(r, opts) +local m, err = Ptm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ptm +end +__FILES["music/s3m"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism +-- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning +-- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 +-- speed reference, as IT shows S3M files). +-- Not supported: AdLib (OPL) instruments and channels (read as silent), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local S3m = { + name = "s3m", + category = "music", + extensions = { "s3m" }, + mime = { "audio/s3m", "audio/x-s3m" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + +function S3m.sniff(r) +if r:size() >= 48 and r:peek(4, 44) == "SCRM" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function S3m.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:size() < 96 then + return nil, Err.new(Err.TRUNCATED, "header") + end + if r:peek(4, 44) ~= "SCRM" then + return nil, Err.new(Err.CORRUPT, "no SCRM signature") + end + local title = r:fixed(28) + r:seek(32) + local ordnum, insnum, patnum = r:u16le(), r:u16le(), r:u16le() + local flags, cwt, ffi = r:u16le(), r:u16le(), r:u16le() + r:seek(48) + local gv, speed, tempo, mv, _uc, dp = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + r:seek(64) + local chnset= {} + for i = 1, 32 do + chnset[i] = r:u8() + end + if r.err then + return nil, r.err + end + if ordnum > 256 or insnum > 256 or patnum > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + -- channels: enabled PCM channels (0..15); the count is the last used one + local nch = 0 + for i = 1, 32 do + local c = chnset[i] + if c < 16 then + nch = i + end + end + if nch == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no PCM channels (AdLib only)") + end + local m = Tracker.newModule("s3m", nch) + m.title = title + m.speed = (speed > 0 and speed < 255 and{speed }or{6 +})[1] m.tempo = (tempo >= 33 and{tempo }or{125 +})[1] m.globalVolume = math.min(gv, 64) * 2 + m.mixVolume = math.max(mv % 128, 16) + if mv < 128 then + -- mono files play at 8 / 11 of the master volume (ST3's stereo boost is missing; OpenMPT does the same) + m.mixVolume = math.floor(m.mixVolume * 8 / 11 + 0.5) + end + m.linear = false + m.instrumentMode = false + m.flags.fastSlides = cwt == 0x1300 or bit32.band(flags, 64) ~= 0 + m.flags.amigaLimits = bit32.band(flags, 16) ~= 0 + m.meta.source = { format = "s3m", tracker = cwt, stereo = mv >= 128 } + -- orders, parapointers, panning + r:seek(96) + for i = 1, ordnum do + local o = r:u8() + table.insert(m.order, o) + end + local insPtr, patPtr = {}, {} + for i = 1, insnum do + insPtr[i] = r:u16le() * 16 + end + for i = 1, patnum do + patPtr[i] = r:u16le() * 16 + end + local pans= {} + if dp == 252 then + for i = 1, 32 do + pans[i] = r:u8() + end + end + if r.err then + return nil, r.err + end + -- drop trailing end markers; keep inner "+++" / "---" + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + local stereo = mv >= 128 + for i = 1, nch do + local c = chnset[i] + local pan = 128 + if stereo then + pan = c % 16 >= 8 and 0xCC or 0x33 + local p = pans[i] + if p and bit32.band(p, 0x20) ~= 0 then + pan = (p % 16) * 0x11 + end + end + m.channelPan[i] = pan + m.channelMute[i] = c >= 16 + end + -- samples + local total = 0 + local unsigned = ffi ~= 1 + for i = 1, insnum do + local s = Tracker.newSample() + m.samples[i] = s + local h = r:sub(insPtr[i], 80) + if h:size() < 80 then + return nil, Err.new(Err.TRUNCATED, "sample header " .. i, insPtr[i]) + end + local typ = h:u8() + h:skip(12) + local hi = h:u8() + local lo = h:u16le() + local len, ls, le = h:u32le(), h:u32le(), h:u32le() + local vol = h:u8() + h:skip(1) + local pack, sflags = h:u8(), h:u8() + local c2spd = h:u32le() + h:seek(48) + s.name = h:fixed(28) + s.volume = math.min(vol, 64) + s.c5speed = (c2spd > 0 and{c2spd }or{8363 +})[1] if typ == 1 and len > 0 and pack == 0 then + local bits = bit32.band(sflags, 4) ~= 0 and 16 or 8 + local nchs = bit32.band(sflags, 2) ~= 0 and 2 or 1 + local off = (hi * 65536 + lo) * 16 + len = math.min(len, 2 ^ 26) + -- a short file: keep what is there + local avail = math.floor(math.max(0, r:size() - off) / (math.floor(nchs * bits / 8)) +) len = math.min(len, avail) + total =total+ len * nchs * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Tracker.Pcm.decode(r.buf, r.base + off, len, { bits = bits, signed = not unsigned, channels = nchs, planar = true }) + if data then + s.data, s.length, s.bits, s.channels = data, len, bits, nchs + if bit32.band(sflags, 1) ~= 0 and le > ls then + s.loopStart, s.loopEnd, s.loopType = ls, math.min(le, len), 1 + end + end + end + end + -- patterns + for p = 1, patnum do + local pat = Tracker.newPattern(64, nch) + m.patterns[p] = pat + local ptr = patPtr[p] + if ptr > 0 then + local pr = r:sub(ptr) + local plen = pr:u16le() + pr = pr:sub(2, math.max(0, plen - 2)) + local d = pat.data + local row = 0 + while row < 64 and not pr:eof() do + local what = pr:u8() + if what == 0 then + row =row+ 1 + else + local ch = what % 32 + local note, ins, vol, cmd, info = 0, 0, 0, 0, 0 + if bit32.band(what, 0x20) ~= 0 then + local nb = pr:u8() + ins = pr:u8() + if nb == 254 then + note = 254 + elseif nb < 254 and nb % 16 < 12 then + note = (math.floor(nb / 16)) * 12 + nb % 16 + 13 + if note > 120 then + note = 0 + end + end + end + if bit32.band(what, 0x40) ~= 0 then + vol = math.min(pr:u8(), 64) + 1 + end + if bit32.band(what, 0x80) ~= 0 then + cmd = pr:u8() + info = pr:u8() + if cmd > 26 then + cmd, info = 0, 0 + end + end + if ch < nch then + local o = (row * nch + ch) * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, cmd) + buffer.writeu8(d, o + 4, info) + end + end + end + end + end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function S3m.open(r, opts) +local m, err = S3m.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return S3m +end +__FILES["music/sf2"] = function() +--!strict +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the +-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), +-- presets / instruments / sample headers with global zones, generator merging into playable regions. +-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). +-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local SoundFont = __include("codecs/audio/SoundFont") + +-- ------------------------------------------------------------------------------------------------ contract +local Sf2 = { + name = "sf2", + category = "music", + extensions = { "sf2" }, + mime = { "audio/x-soundfont" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" }, + caps = { decode = true, encode = false, sm24 = true, sf3 = false }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function Sf2.sniff(r) +return SoundFont.sniff(r) and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sf2.decode(r, opts) +return SoundFont.parse(r, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) +Sf2.synth = SoundFont.synth +Sf2.fallback = SoundFont.fallback + +return Sf2 +end +__FILES["music/stm"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- music/stm: Scream Tracker 2 modules (STM, "!Scream!" / BMOD2STM / WUZAMOD! / SWavePro; 4 channels, 31 samples). +-- Ported from OpenMPT's Load_stm.cpp (BSD, licenses/openmpt-LICENSE.txt). Reads into the codecs/audio/Tracker Module +-- and plays as the "s3m" effect family with Scream Tracker 2's tempo (flags.st2Tempo: the speed byte also sets the +-- tick length), no effect memory, no fine slides (the loader drops what ST2 ignores) and its deferred Bxx (the jump +-- happens at the end of the pattern or at the next Cxx). +-- Not supported: STX (Scream Tracker Music Interface Kit), ST2's noise for samples at volume 0 (silent here), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Stm = { + name = "stm", + category = "music", + extensions = { "stm" }, + mime = { "audio/x-stm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 4, 4 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + +local IT = Load.IT +-- .ABCDEFGHIJ (K..O do nothing) +local EFFECTS = { "speed", "jump", "break", "volslide", "portadown", "portaup", "toneporta", "vibrato", "tremor", "arpeggio" } + +-- ------------------------------------------------------------------------------------------------ sniff +local function validHeader(r) +if r:size() < 48 then + return false + end + local eof, ftype, major, minor = r:peekU8(28), r:peekU8(29), r:peekU8(30), r:peekU8(31) + local npat, gv = r:peekU8(33), r:peekU8(34) + if ftype ~= 2 or (eof ~= 0x1A and eof ~= 2) or major ~= 2 or (minor ~= 0 and minor ~= 10 and minor ~= 20 and minor ~= 21) then + return false + end + if npat > 64 or (gv > 64 and gv ~= 0x58) then + return false + end + for i = 20, 27 do + local c = r:peekU8(i) + if c < 0x20 or c >= 0x7F then + return false + end + end + return true +end + +function Stm.sniff(r) +return validHeader(r) and 0.7 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a tempo byte of files before ST 2.21 is decimal +local function tempoByte(v, minor) +return (minor < 21 and(((math.floor(v / 10)) * 16 + v % 10 ))or(v +))end + +function Stm.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if not validHeader(r) then + return nil, Err.new((r:size() < 48 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not a Scream Tracker 2 module") + end + local title = r:fixed(20) + local tracker = r:fixed(8) + r:skip(3) + local minor, initTempo, npat, gv = r:u8(), r:u8(), r:u8(), r:u8() + r:skip(13) + local m = Tracker.newModule("stm", 4, "s3m") + m.title = title + m.linear = false + m.instrumentMode = false + m.flags.st2Tempo = true + initTempo = tempoByte(initTempo, minor) + if initTempo == 0 then + initTempo = 0x60 + end + m.speed, m.tempo = Tracker.st2Tempo(initTempo) + if minor > 10 then + m.globalVolume = math.min(gv, 64) * 2 + end + local offsets= {} + for i = 1, 31 do + local s = Tracker.newSample(r:fixed(12)) + local zero = r:u8() + r:skip(1) + local off, len, ls, le = r:u16le(), r:u16le(), r:u16le(), r:u16le() + local vol = r:u8() + r:skip(1) + local rate = r:u16le() + r:skip(6) + if r.err then + return nil, r.err + end + if zero ~= 0 and zero ~= 46 then + return nil, Err.new(Err.CORRUPT, "bad sample header " .. i) + end + s.c5speed = (rate > 0 and{rate }or{8363 +})[1] s.volume = math.min(vol, 64) + if len < 2 then + len = 0 + end + if ls < len and le > ls and le ~= 0xFFFF then + s.loopStart, s.loopEnd, s.loopType = ls, le, 1 + len = math.max(le, len) -- ST2 lets a loop run into the next sample's data + end + s.length = len + offsets[i] = off * 16 + m.samples[i] = s + end + for i = 1, (minor == 0 and 64 or 128) do + local o = r:u8() + if o == 99 or o == 255 then + o = 255 + elseif o > 63 then + return nil, Err.new(Err.CORRUPT, "bad order list") + end + m.order[i] = o + end + if r.err then + return nil, r.err + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + -- patterns: 64 rows x 4 channels; one byte 0xFB (C-0, volume 0), 0xFC (nothing) or 0xFD (note cut), else 4 bytes + for p = 0, npat - 1 do + local pat = Tracker.newPattern(64, 4) + m.patterns[p + 1] = pat + local d = pat.data + local breakPos, breakRow = -1, 63 -- ST2: Bxx only sets the next order, taken at the pattern's end or a Cxx + for row = 0, 63 do + for ch = 0, 3 do + local q = (row * 4 + ch) * 5 + local note = r:u8() + local insVol, volCmd, info = 0, 0, 0 + if note == 0xFB then + note = 0 -- a C-0 at volume 0 (OpenMPT reads it so) + elseif note == 0xFD then + buffer.writeu8(d, q, 254) + elseif note ~= 0xFC then + insVol, volCmd, info = r:u8(), r:u8(), r:u8() + end + if note ~= 0xFC and note ~= 0xFD then + if note == 0xFE then + buffer.writeu8(d, q, 254) + elseif note < 0x60 then + buffer.writeu8(d, q, (math.floor(note / 16)) * 12 + note % 16 + 37) + end + local ins = math.floor(insVol / 8 +) buffer.writeu8(d, q + 1, ins > 31 and 0 or ins) + local vol = insVol % 8 + (math.floor(volCmd / 16)) * 8 + if vol <= 64 then + buffer.writeu8(d, q + 2, vol + 1) + end + local name, param = EFFECTS[volCmd % 16], info + if name == "volslide" then + param = (param % 16 > 0 and((param % 16 ))or((param - param % 16 +))) elseif name == "break" then + param = ((param - param % 16) * 10 + param % 16) % 256 + if breakPos >= 0 and param == 0 then + name, param = "jump", breakPos -- Bxx + C00 is a plain Bxx + breakPos = -1 + end + breakRow = math.min(breakRow, row) + if name == "break" then + param = Load.bcd(param) + end + elseif name == "jump" then + breakPos, breakRow = param, 63 + name = nil + elseif name == "speed" then + param = tempoByte(param, minor) + if param == 0 then + name = nil + end + elseif name ~= "tremor" and param == 0 then + name = nil -- no effect memory in ST2 + end + if name then + buffer.writeu8(d, q + 3, IT[name]) + buffer.writeu8(d, q + 4, param) + end + end + end + end + if r.err then + return nil, r.err + end + if breakPos >= 0 then + Load.writeEffect(m, p, breakRow, IT.jump, breakPos, "prev") + end + end + -- sample data: signed 8-bit at the paragraph offsets (samples at volume 0 are not read) + local buf = r.buf + for i = 1, 31 do + local s = m.samples[i] + local len = s.length + s.length = 0 + if len > 0 and s.volume > 0 and offsets[i] > 48 then + local ok, err = Load.readSample(buf, r.base + offsets[i], len, { bits = 8, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + end + end + m.meta.source = { format = "stm", tracker = tracker, version = "2." .. minor } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Stm.open(r, opts) +local m, err = Stm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Stm +end +__FILES["music/ult"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- music/ult: UltraTracker modules (MAS_UTrack_V001 .. V004; up to 32 channels, two effects per cell, patterns stored +-- channel by channel with run-length repeats). Ported from OpenMPT's Load_ult.cpp (BSD, licenses/openmpt-LICENSE.txt). +-- Reads into the codecs/audio/Tracker Module and plays as the "it" effect family with Amiga periods, IT old effects +-- and linked Gxx memory (as OpenMPT converts ULT): the two effect columns go into the IT volume column and the effect +-- column (or the more important one is kept), sample loops are sustain loops (released by a key off), the tone +-- portamento keeps going on later rows. 8 / 16-bit signed samples, the v1.4+ sample speed and finetune. +-- Not supported: reverse playback (5x2), "no loop" (5x1), vibrato strength (E0x), sample offsets past 64 KiB (the +-- high byte is dropped), the logarithmic volumes of pre-1.4 files, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Load = __include("codecs/audio/Tracker/Load") + +-- ------------------------------------------------------------------------------------------------ contract +local Ult = { + name = "ult", + category = "music", + extensions = { "ult" }, + mime = { "audio/x-ult" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Tracker/Load" }, + caps = { decode = true, encode = false, render = true, channels = { 1, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + +local EFFECTS= { + [0] = "arpeggio", [1] = "portaup", [2] = "portadown", [3] = "toneporta", [4] = "vibrato", [7] = "tremolo", + [9] = "offset", [10] = "volslide", [11] = "panning8", [12] = "volume8", [13] = "break", [15] = "speed", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ult.sniff(r) +local v = r:peekU8(14) + if r:size() >= 48 and r:peek(14) == "MAS_UTrack_V00" and v >= 0x31 and v <= 0x34 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- one effect nibble + parameter -> name?, param (OpenMPT's TranslateULTCommands) +local function translate(e, param, version) +local name = EFFECTS[e] + if e == 0 then + if param == 0 or version < 3 then + name = nil + end + elseif e == 5 then + if (param % 16 == 0xC or math.floor(param / 16 )== 0xC) and version >= 3 then + return "keyoff", 0 + end + elseif e == 7 then + if version < 4 then + name = nil + end + elseif e == 0xA then + if param >= 16 then + param =param- param % 16 + end + elseif e == 0xB then + param = (param % 16) * 0x11 + elseif e == 0xD then + param = 10 * (math.floor(param / 16)) + param % 16 + elseif e == 0xE then + local x, y = math.floor(param / 16), param % 16 + if x == 1 then + return "portaup", 0xF0 + y + elseif x == 2 then + return "portadown", 0xF0 + y + elseif x == 8 and version >= 4 then + return "s3mex", 0x60 + y + elseif x == 9 then + return "retrig", y + elseif x == 0xA then + return "volslide", y * 16 + 0xF + elseif x == 0xB then + return "volslide", 0xF0 + y + elseif x == 0xC or x == 0xD then + return "s3mex", param + end + return nil, param + elseif e == 0xF then + if param > 0x2F then + name = "tempo" + end + end + return name, param +end + +-- volume slide + vibrato / tone portamento without a parameter -> one combined effect (OpenMPT's CombineEffects) +local function combine(a, pa, b, pb) +if a == "volslide" and (b == "vibrato" or b == "toneportavol") and pb == 0 then + return b == "vibrato" and"vibratovol" or"toneportavol", pa, nil, 0 + elseif b == "volslide" and (a == "vibrato" or a == "toneportavol") and pa == 0 then + return a == "vibrato" and"vibratovol" or"toneportavol", pb, nil, 0 + end + return a, pa, b, pb +end + +-- an event: [0xFC repeat] note instrument effects param1 param2 -> repeat, note, instrument, volume byte, fx, param, +-- lost global effect (name?, param) +local function readEvent(r, version) +local rep = 1 + local b = r:u8() + if b == 0xFC then + rep = r:u8() + b = r:u8() + end + local note = (b > 0 and b < 97 and((b + 24 ))or(0 +)) local ins, cmd, p1, p2 = r:u8(), r:u8(), r:u8(), r:u8() + local c1, q1 = translate(cmd % 16, p1, version) + local c2, q2 = translate(math.floor(cmd / 16), p2, version) + if c1 == "offset" and c2 == "offset" then + local off = math.floor((p2 * 256 + p1) / 64 +) return rep, note, ins, 0, Load.IT.offset, off % 256, nil, 0 + elseif c1 == "offset" then + q1 = math.min(p1 * 4, 255) + elseif c2 == "offset" then + q2 = math.min(p2 * 4, 255) + elseif c1 ~= nil and c1 == c2 then + c2 = nil + end + if c2 == nil then -- (OpenMPT also swaps for CMD_VOLUME, which ULT never produces) + c1, q1, c2, q2 = c2, q2, c1, q1 + end + c2, q2, c1, q1 = combine(c2, q2, c1, q1) + if c1 == "keyoff" or c2 == "keyoff" then + -- key off (5xC): a note-off when the cell has no note + if note == 0 then + note = 255 + end + if c1 == "keyoff" then + c1 = nil + else + c2 = nil + end + end + local vol, name, param, lost, lostParam = Load.fillTwo(c1, q1, c2, q2) + local fx, fp = Load.itEffect(name, param) + return rep, note, ins, vol, fx, fp, lost, lostParam +end + +function Ult.decode(r, opts) +local budget = { left = opts and opts.maxBytes or 2 ^ 28 } + if Ult.sniff(r) == 0 then + return nil, Err.new((r:size() < 48 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not an UltraTracker module") + end + r:skip(14) + local version = r:u8() - 0x30 + local title = (string.gsub(r:fixed(32), " +$", "")) + local lines = r:u8() + local message = r:string(lines * 32) + local nsmp = r:u8() + if r.err then + return nil, r.err + end + local samples, sizes = {}, {} + for i = 1, nsmp do + local s = Tracker.newSample((string.gsub(r:fixed(32), " +$", ""))) + r:skip(12) + local ls, le, ss, se = r:u32le(), r:u32le(), r:u32le(), r:u32le() + local vol, flags = r:u8(), r:u8() + local speed, finetune = 8363, 0 + if version >= 4 then + speed, finetune = r:u16le(), r:i16le() + else + finetune = r:i16le() + end + if r.err then + return nil, r.err + end + local bits = bit32.band(flags, 4) ~= 0 and 16 or 8 + s.bits = bits + sizes[i] = 0 + if se > ss then + s.length = se - ss + sizes[i] = math.floor(s.length * bits / 8 +) s.volume = vol / 4 + s.c5speed = math.max(1, speed * 2 * 2 ^ (finetune / (12 * 32768))) + if bit32.band(flags, 8) ~= 0 then + if bits == 16 then + ls, le = math.floor(ls / 2), math.floor(le / 2 +) end + s.susStart, s.susEnd = ls, le + s.susType = bit32.band(flags, 16) ~= 0 and 2 or 1 + end + end + samples[i] = s + end + local order = {} + for i = 1, 256 do + order[i] = r:u8() + end + local nch, npat = r:u8() + 1, r:u8() + 1 + if r.err then + return nil, r.err + end + if nch > 32 then + return nil, Err.new(Err.UNSUPPORTED, nch .. " channels") + end + local m = Tracker.newModule("ult", nch, "it") + m.title = title + m.meta.message = message + m.linear = false + m.instrumentMode = false + m.flags.oldEffects, m.flags.compatGxx, m.flags.autoTonePorta = true, true, true + m.samples = samples + for i = 1, 256 do + m.order[i] = order[i] + end + while #m.order > 0 and m.order[#m.order] == 255 do + table.remove(m.order) + end + for i = 1, nch do + m.channelPan[i] = (version >= 3 and(((r:u8() % 16) * 16 + 8 ))or(i % 2 == 0 and 192 or 64 +)) end + for p = 1, npat do + m.patterns[p] = Tracker.newPattern(64, nch) + end + -- events, channel by channel, pattern by pattern + local speed0 = false + for ch = 0, nch - 1 do + for p = 0, npat - 1 do + if r:remaining() < 5 then + break + end + local d = m.patterns[p + 1].data + local row = 0 + while row < 64 do + local rep, note, ins, vol, fx, param, lost, lostParam = readEvent(r, version) + if r.err then + break + end + if lost and Load.isGlobal(lost, lostParam) then + local lf, lp = Load.itEffect(lost, lostParam) + Load.writeEffect(m, p, row, lf, lp, "next") + end + rep = math.min(rep, 64 - row) + if rep == 0 then + break + end + if fx == Load.IT.speed and param == 0 then + speed0 = true + end + for _ = 1, rep do + local q = (row * nch + ch) * 5 + buffer.writeu8(d, q, note) + buffer.writeu8(d, q + 1, ins) + buffer.writeu8(d, q + 2, vol) + buffer.writeu8(d, q + 3, fx) + buffer.writeu8(d, q + 4, param) + row =row+ 1 + end + end + end + end + r.err = nil + if speed0 then + -- speed 0 resets the song speed and tempo (UltraTracker) + for p, pat in __iter(m.patterns) do + for row = 0, 63 do + for ch = 0, nch - 1 do + local q = (row * nch + ch) * 5 + if buffer.readu8(pat.data, q + 3) == Load.IT.speed and buffer.readu8(pat.data, q + 4) == 0 then + buffer.writeu8(pat.data, q + 4, 6) + Load.writeEffect(m, p - 1, row, Load.IT.tempo, 125, "next") + end + end + end + end + end + -- sample data: signed 8 / 16-bit + local pos = r.pos + for i = 1, nsmp do + local s = samples[i] + if sizes[i] > 0 then + local ok, err = Load.readSample(r.buf, pos, s.length, { bits = s.bits, signed = true, limit = r.limit }, s, budget) + if not ok then + return nil, err + end + pos =pos+ sizes[i] + end + end + m.meta.source = { format = "ult", version = version } + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Ult.open(r, opts) +local m, err = Ult.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Ult +end +__FILES["music/umx"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- music/umx: Unreal music packages (.umx, Unreal / Unreal Tournament / Deus Ex era Unreal Engine 1 packages; package +-- versions up to 128). Ported from OpenMPT's UMXTools.cpp / ContainerUMX.cpp (BSD, licenses/openmpt-LICENSE.txt): +-- reads the package's name, import and export tables, finds the exports of class "music" and unwraps the module each +-- one embeds (IT, S3M, XM or MOD, kept as it is). A format never requires another one, so decode hands the first +-- module's bytes to opts.decodeModule (the api passes it: F.load / F.music.load sniff and load the inner module) and +-- returns that Module with meta.container = { format = "umx", name, version }; without the hook decode is +-- Err.UNSUPPORTED. Umx.extract(r) lists every embedded module without decoding it. +-- Not supported: Unreal Engine 2+ packages (sounds, .uax), writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") + +-- ------------------------------------------------------------------------------------------------ contract +local Umx = { + name = "umx", + category = "music", + extensions = { "umx" }, + mime = { "audio/x-umx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" }, + caps = { decode = true, encode = false, render = true, container = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local MAGIC = "\xC1\x83\x2A\x9E" +-- ------------------------------------------------------------------------------------------------ sniff + + + +local function header(r) +if r:size() < 36 or r:peek(4) ~= MAGIC then + return nil + end + local h = r:sub(4, 32) + local version = h:u16le() + h:skip(6) + local hd= { + version = version, + nameCount = h:u32le(), + nameOffset = h:u32le(), + exportCount = h:u32le(), + exportOffset = h:u32le(), + importCount = h:u32le(), + importOffset = h:u32le(), + } + if h.err or hd.nameOffset < 36 or hd.exportOffset < 36 or hd.importOffset < 36 then + return nil + end + if hd.nameCount == 0 or hd.exportCount == 0 or hd.importCount == 0 or hd.nameCount > 2 ^ 20 or hd.exportCount > 2 ^ 20 or hd.importCount > 2 ^ 20 then + return nil + end + return hd +end + +-- a compact index: sign and 6 bits, then 7 bits per byte while the continue bits are set +local function index(r) +local b = r:u8() + local neg = b >= 0x80 + local v = b % 64 + if bit32.band(b, 0x40) ~= 0 then + local shift = 6 + repeat + b = r:u8() + v =v+ (b % 128) * 2 ^ shift + shift =shift+ 7 + until b < 0x80 or shift >= 32 + end + return (neg and{(-v )}or{v +})[1]end + +-- the name table (lower case) +local function names(r, h) +local list = {} + local nr = r:sub(h.nameOffset) + for _ = 1, math.min(h.nameCount, 65536) do + if nr:remaining() < 5 then + break + end + if h.version >= 64 then + index(nr) + end + table.insert(list, string.lower(nr:cstring(1024))) + nr:skip(4) + end + return list +end + +function Umx.sniff(r) +local h = header(r) + if not h then + return 0 + end + return table.find(names(r, h), "music") and 1 or 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- extract(r) -> { { name, data, format? } } | nil, Err: every module embedded in the package's music exports (format: +-- a guess from the inner module's signature: "it", "s3m", "xm", "mod") +function Umx.extract(r) +local h = header(r) + if not h then + return nil, Err.new((r:size() < 36 and{Err.TRUNCATED }or{Err.CORRUPT})[1], "not an Unreal package") + end + local nm = names(r, h) + -- imports: the class names objects refer to + local classes = {} + local ir = r:sub(h.importOffset) + for _ = 1, math.min(h.importCount, 65536) do + if ir:remaining() < 4 then + break + end + index(ir) + index(ir) + if h.version >= 60 then + ir:skip(4) + else + index(ir) + end + local obj = index(ir) + if obj >= 0 and obj < #nm then + table.insert(classes, obj) + end + end + local out= {} + local er = r:sub(h.exportOffset) + for _ = 1, math.min(h.exportCount, 65536) do + if er:remaining() < 8 then + break + end + local cls = -index(er) - 1 -- ~index: the import the class is + index(er) + if h.version >= 60 then + er:skip(4) + end + local objName = index(er) + er:skip(4) + local size, offset = index(er), index(er) + if er.err then + break + end + if cls >= 0 and cls < #classes and nm[classes[cls + 1] + 1] == "music" and size > 0 and offset > 36 then + local c = r:sub(offset, size) + if h.version < 40 then + c:skip(8) + end + if h.version < 60 then + c:skip(16) + end + index(c) -- the property list's "none" + if h.version >= 120 then + index(c) + c:skip(8) + elseif h.version >= 100 then + c:skip(4) + index(c) + c:skip(4) + elseif h.version >= 62 then + index(c) + c:skip(4) + else + index(c) + end + local len = index(c) + if not c.err and len > 0 and len <= c:remaining() then + local data = c:bytes(len) + local sig = Bytes.reader(data) + local fmt = sig:peek(4) == "IMPM" and"it" or(sig:peek(4, 44) == "SCRM" and"s3m" or(sig:peek(17) == "Extended Module: " and"xm" or(buffer.len(data) >= 1084 and"mod" or nil +))) table.insert(out, { name = nm[objName + 1] or "", data = data, format = fmt }) + end + end + end + return out, nil +end + +function Umx.decode(r, opts) +local list, err = Umx.extract(r) + if not list then + return nil, err + end + local i = opts and opts.index or 1 + local e = list[i] + if not e then + return nil, Err.new(Err.CORRUPT, "no music export" .. ((i > 1 and((" " .. i ))or("")))) + end + local hook = opts and opts.decodeModule + if type(hook) ~= "function" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded " .. (e.format or "tracker") .. " module needs opts.decodeModule (F.load passes it; Umx.extract gives the bytes)") + end + local m, merr = hook(e.data, nil) + if not m then + return nil, merr + end + if type(m) ~= "table" or m.kind ~= "music" then + return nil, Err.new(Err.UNSUPPORTED, "the embedded module is not a tracker module") + end + local h = (header(r) ) +m.meta = (type(m.meta) == "table" and{m.meta }or{{} +})[1] m.meta.container = { format = "umx", name = e.name, version = h.version, count = #list } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the embedded module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Umx.open(r, opts) +local m, err = Umx.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Umx +end +__FILES["music/xm"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and +-- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit +-- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga +-- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files +-- in FT2's layout) and from "mod" modules (one instrument per sample, Amiga frequencies). +-- ModPlug ADPCM samples decode (codecs/audio/Adpcm; written back as plain delta PCM). Not supported: OpenMPT's +-- stereo-sample / extra-effect extensions on write. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Tracker = __include("codecs/audio/Tracker") +local Adpcm = __include("codecs/audio/Adpcm") + +-- ------------------------------------------------------------------------------------------------ contract +local Xm = { + name = "xm", + category = "music", + extensions = { "xm" }, + mime = { "audio/xm", "audio/x-xm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker", "codecs/audio/Adpcm" }, + caps = { decode = true, encode = true, render = true, channels = { 1, 64 } }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local MAGIC = "Extended Module: " +local Pcm = Tracker.Pcm + +-- ------------------------------------------------------------------------------------------------ sniff +function Xm.sniff(r) +return r:peek(17) == MAGIC and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function readEnvelope(r) +local xs, ys = {}, {} + for i = 1, 12 do + xs[i] = r:u16le() + ys[i] = r:u16le() + end + return xs, ys +end + +local function makeEnvelope(xs, ys, n, typ, sus, ls, le, pan) +local e = Tracker.newEnvelope() + n = math.min(n, 12) + for i = 1, n do + e.ticks[i] = xs[i] + e.values[i] = (pan and{(math.clamp(ys[i], 0, 64) - 32 )}or{(math.clamp(ys[i], 0, 64) +)})[1] end + e.enabled = bit32.band(typ, 1) ~= 0 and n > 0 + e.sustain = bit32.band(typ, 2) ~= 0 + e.loop = bit32.band(typ, 4) ~= 0 + e.susStart, e.susEnd = sus + 1, sus + 1 + e.loopStart, e.loopEnd = ls + 1, le + 1 + -- the raw fields, for a faithful re-save + e.raw = { type = typ, sustain = sus, loopStart = ls, loopEnd = le, count = n } + return e +end + +function Xm.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r:peek(17) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no XM signature") + end + r:skip(17) + local title = r:fixed(20) + r:skip(1) + local tracker = r:fixed(20) + local version = r:u16le() + local hdrStart = r:tell() + local hdrSize = r:u32le() + local songLen, restart, nch, npat, nins = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le() + local flags, speed, bpm = r:u16le(), r:u16le(), r:u16le() + local orders = {} + for i = 1, 256 do + orders[i] = r:u8() + end + if r.err then + return nil, r.err + end + if nch < 1 or nch > 128 or npat > 256 or nins > 256 or songLen > 256 then + return nil, Err.new(Err.CORRUPT, "bad header counts") + end + if version < 0x0104 then + return nil, Err.new(Err.UNSUPPORTED, string.format("XM version %x (only 1.04 is supported)", version)) + end + local m = Tracker.newModule("xm", nch) + m.title = title + m.speed = (speed > 0 and speed < 256 and{speed }or{6 +})[1] m.tempo = (bpm >= 32 and bpm <= 999 and{bpm }or{125 +})[1] m.linear = bit32.band(flags, 1) ~= 0 + m.restart = restart + for i = 1, songLen do + m.order[i] = orders[i] + end + m.meta.tracker = tracker + m.meta.source = { format = "xm", tracker = tracker, version = version } + -- patterns + if not r:seek(hdrStart + hdrSize) then + return nil, r.err + end + for p = 1, npat do + local start = r:tell() + local plen = r:u32le() + r:u8() + local rows = r:u16le() + local psize = r:u16le() + if r.err then + return nil, r.err + end + if rows < 1 or rows > 256 then + return nil, Err.new(Err.CORRUPT, "pattern " .. (p - 1) .. " has " .. rows .. " rows", r.pos) + end + r:seek(start + plen) + local pat = Tracker.newPattern(rows, nch) + m.patterns[p] = pat + local pr = r:slice(psize) + if r.err then + return nil, r.err + end + local d = pat.data + if psize > 0 then + for i = 0, rows * nch - 1 do + local b = pr:u8() + local note, ins, vol, fx, param = 0, 0, 0, 0, 0 + if b >= 128 then + if bit32.band(b, 1) ~= 0 then + note = pr:u8() + end + if bit32.band(b, 2) ~= 0 then + ins = pr:u8() + end + if bit32.band(b, 4) ~= 0 then + vol = pr:u8() + end + if bit32.band(b, 8) ~= 0 then + fx = pr:u8() + end + if bit32.band(b, 16) ~= 0 then + param = pr:u8() + end + else + note = b + ins = pr:u8() + vol = pr:u8() + fx = pr:u8() + param = pr:u8() + end + if pr.err then + break -- a short pattern: the rest stays empty + end + if note == 97 then + note = 255 + elseif note > 96 then + note = 0 + end + if fx > 35 then + fx, param = 0, 0 + end + local o = i * 5 + buffer.writeu8(d, o, note) + buffer.writeu8(d, o + 1, ins) + buffer.writeu8(d, o + 2, vol) + buffer.writeu8(d, o + 3, fx) + buffer.writeu8(d, o + 4, param) + end + end + end + -- instruments and their samples + local total = 0 + for i = 1, nins do +local __DARKLUA_CONTINUE_7=false repeat local start = r:tell() + local isize = r:u32le() + local ins = Tracker.newInstrument(r:fixed(22)) + r:u8() + local ns = r:u16le() + if r.err then + -- a file cut inside the instruments: keep what was read + r.err = nil + break + end + m.instruments[i] = ins + ins.samples = {} + if ns == 0 then + r:seek(start + math.max(isize, 29)) +__DARKLUA_CONTINUE_7=true break + end + if ns > 256 then + return nil, Err.new(Err.CORRUPT, "instrument " .. i .. " has " .. ns .. " samples") + end + local shSize = r:u32le() + local keymap = {} + for n = 1, 96 do + keymap[n] = r:u8() + end + local vx, vy = readEnvelope(r) + local px, py = readEnvelope(r) + local nv, np = r:u8(), r:u8() + local vs, vls, vle, ps, pls, ple = r:u8(), r:u8(), r:u8(), r:u8(), r:u8(), r:u8() + local vt, pt = r:u8(), r:u8() + ins.vibType, ins.vibSweep, ins.vibDepth, ins.vibRate = r:u8(), r:u8(), r:u8(), r:u8() + ins.fadeout = r:u16le() + if r.err then + return nil, r.err + end + ins.volEnv = makeEnvelope(vx, vy, nv, vt, vs, vls, vle, false) + ins.panEnv = makeEnvelope(px, py, np, pt, ps, pls, ple, true) + ins.headerSize = isize + r:seek(start + isize) + local base = #m.samples + local heads = {} + for k = 1, ns do + local hs = r:tell() + local len, ls, ll = r:u32le(), r:u32le(), r:u32le() + local vol, ft, typ, pan, rel, res = r:u8(), r:i8(), r:u8(), r:u8(), r:i8(), r:u8() + local nm = r:fixed(22) + r:seek(hs + math.max(shSize, 40)) + heads[k] = { len = len, ls = ls, ll = ll, vol = vol, ft = ft, typ = typ, pan = pan, rel = rel, res = res, name = nm } + end + if r.err then + return nil, r.err + end + for k = 1, ns do + local h = heads[k] + local s = Tracker.newSample(h.name) + local bits = bit32.band(h.typ, 16) ~= 0 and 16 or 8 + local bps = math.floor(bits / 8 +) s.bits = bits + s.volume = math.min(h.vol, 64) + s.finetune = h.ft + s.relativeNote = h.rel + s.pan = h.pan + local frames = math.floor(h.len / bps +) if h.res == 0xAD and bits == 8 then + -- ModPlug ADPCM (codecs/audio/Adpcm): a 16-byte delta table, then 4 bits per sample; a cut file keeps + -- the samples whose nibbles are present + frames = math.max(0, math.min(h.len, (r:remaining() - 16) * 2)) + total =total+ frames * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + s.data = buffer.create(frames * 4) + if frames > 0 then + Adpcm.modplug(r.buf, r.pos, frames, s.data, 0) + end + r:skip(math.min(16 + math.floor((h.len + 1) / 2), r:remaining())) + else + local avail = math.floor(r:remaining() / bps +) local got = math.min(frames, avail) + total =total+ got * 4 + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "sample data over the maxBytes limit") + end + local data = Pcm.decode(r.buf, r.pos, got, { bits = bits, signed = true, delta = true }) + r:skip(got * bps) + s.data = data or buffer.create(0) + frames = (data and{got }or{0 +})[1] end + s.length = frames + local lt = h.typ % 4 + if lt == 3 then + lt = 2 + end + if lt > 0 and h.ll > 0 then + s.loopStart = math.floor(h.ls / bps +) s.loopEnd = math.floor((h.ls + h.ll) / bps +) s.loopType = lt + end + m.samples[base + k] = s + table.insert(ins.samples, base + k) + end + for n = 1, 120 do + local k = keymap[math.min(n, 96)] + ins.sampleMap[n] = (n <= 96 and k < ns and((base + k + 1 ))or(0 +)) end + ins.keymap = keymap +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + local ok, verr = Tracker.validate(m) + if not ok then + return nil, Err.new(Err.CORRUPT, verr and verr.message or "invalid module") + end + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function writeName(w, s, n) + local t = string.sub(s or "", 1, n) + w:string(t) + w:fill(0, n - #t) +end + +-- the instruments to write: { name, samples = { sample table }, keymap = { 96 local indexes }, ins? } +local function instrumentsOf(m) +local out = {} + if m.format == "mod" then + for i, s in __iter(m.samples) do + local km = table.create(96, 0) + out[i] = { name = s.name, samples = s.length > 0 and{ s } or{}, keymap = km, ins = nil } + end + return out + end + for i, ins in __iter(m.instruments) do + local list= {} + if type(ins.samples) == "table" then + for _, g in __iter(ins.samples) do + table.insert(list, g) + end + end + local index= {} + for k, g in __iter(list) do + index[g] = k - 1 + end + local km = table.create(96, 0) + for n = 1, 96 do + local g = ins.sampleMap[n] or 0 + if g > 0 and m.samples[g] then + if index[g] == nil then + table.insert(list, g) + index[g] = #list - 1 + end + km[n] = index[g] + end + end + if #list > 255 then + return nil, "instrument " .. i .. " uses more than 255 samples" + end + local smps = {} + for k, g in __iter(list) do + smps[k] = m.samples[g] or Tracker.newSample() + end + out[i] = { name = ins.name, samples = smps, keymap = km, ins = ins } + end + return out +end + +local function writeEnvelope(w, e, pan) + local n = (e and{(math.min(#e.ticks, 12) )}or{0 +})[1] for i = 1, 12 do + if i <= n then + w:u16le(math.clamp(math.floor(e.ticks[i]), 0, 65535)) + w:u16le(math.clamp(math.floor(e.values[i] + (pan and 32 or 0) + 0.5), 0, 64)) + else + w:u32le(0) + end + end +end + +-- envelope count, type, sustain, loop start, loop end +local function envelopeFields(e) +if not e then + return 0, 0, 0, 0, 0 + end + local n = math.min(#e.ticks, 12) + local typ = (e.enabled and 1 or 0) + (e.sustain and 2 or 0) + (e.loop and 4 or 0) + local raw = e.raw + if raw and raw.type % 8 == typ then + typ = raw.type -- keep unknown bits + end + local function idx(v) +return math.clamp(math.floor(v) - 1, 0, math.max(0, n - 1)) + end + local sus = idx(e.susStart) + local ls, le = idx(e.loopStart), idx(e.loopEnd) + if raw and n == 0 then + sus, ls, le = raw.sustain, raw.loopStart, raw.loopEnd + end + return n, typ, sus, ls, le +end + +-- encode(module, opts) -> XM bytes ("xm" or "mod" modules) +function Xm.encode(m, opts) +local ok, verr = Tracker.validate(m) + if not ok then + return nil, verr + end + if m.format ~= "xm" and m.format ~= "mod" then + return nil, Err.new(Err.UNSUPPORTED, "only xm and mod modules can be written as XM (got " .. tostring(m.format) .. ")") + end + local nch = m.channels + if nch > 64 then + return nil, Err.new(Err.ARG, "XM holds at most 64 channels") + end + local insts, ierr = instrumentsOf(m) + if not insts then + return nil, Err.new(Err.ARG, ierr or "bad instruments") + end + if #insts > 128 then + return nil, Err.new(Err.ARG, "XM holds at most 128 instruments") + end + if #m.patterns > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 patterns") + end + local order= {} + for _, o in __iter(m.order) do + if o == 255 then + break + elseif o ~= 254 then + table.insert(order, o) + end + end + if #order > 256 then + return nil, Err.new(Err.ARG, "XM holds at most 256 order entries") + end + local w = Bytes.writer(65536) + w:string(MAGIC) + writeName(w, m.title, 20) + w:u8(0x1A) + writeName(w, opts and opts.tracker or (m.meta and m.meta.tracker) or "rosetta", 20) + w:u16le(0x0104) + w:u32le(276) + w:u16le(#order) + w:u16le((m.restart < #order and{m.restart }or{0})[1]) + w:u16le(nch) + w:u16le(#m.patterns) + w:u16le(#insts) + w:u16le(m.linear and 1 or 0) + w:u16le(m.speed) + w:u16le(math.clamp(math.floor(m.tempo), 32, 999)) + for i = 1, 256 do + w:u8(order[i] or 0) + end + -- patterns (every cell packed, as FT2-compatible writers may) + for _, pat in __iter(m.patterns) do + local pk = Bytes.writer(pat.rows * nch * 2) + local d = pat.data + for i = 0, pat.rows * nch - 1 do + local o = i * 5 + local note, ins, vol, fx, param = buffer.readu8(d, o), buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3), buffer.readu8(d, o + 4) + if note == 255 then + note = 97 + elseif note > 96 then + note = 0 + end + if m.format == "mod" then + vol = 0 + if fx > 15 then + fx, param = 0, 0 + end + end + if ins > 128 then + ins = 0 + end + local flags = 0x80 + (note > 0 and 1 or 0) + (ins > 0 and 2 or 0) + (vol > 0 and 4 or 0) + (fx > 0 and 8 or 0) + (param > 0 and 16 or 0) + pk:u8(flags) + if note > 0 then + pk:u8(note) + end + if ins > 0 then + pk:u8(ins) + end + if vol > 0 then + pk:u8(vol) + end + if fx > 0 then + pk:u8(fx) + end + if param > 0 then + pk:u8(param) + end + end + local data = pk:finish() + if buffer.len(data) > 65535 then + return nil, Err.new(Err.ARG, "a pattern packs to more than 64 KB") + end + w:u32le(9) + w:u8(0) + w:u16le(pat.rows) + w:u16le(buffer.len(data)) + w:bytes(data) + end + -- instruments + for _, it in __iter(insts) do +local __DARKLUA_CONTINUE_23=false repeat local ins = it.ins + local smps = it.samples + if #smps == 0 then + w:u32le(29) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(0) +__DARKLUA_CONTINUE_23=true break + end + w:u32le(263) + writeName(w, it.name, 22) + w:u8(0) + w:u16le(#smps) + w:u32le(40) + for n = 1, 96 do + w:u8(it.keymap[n]) + end + local ve, pe = ins and ins.volEnv, ins and ins.panEnv + writeEnvelope(w, ve, false) + writeEnvelope(w, pe, true) + local vn, vt, vs, vls, vle = envelopeFields(ve) + local pn, pt, ps, pls, ple = envelopeFields(pe) + w:u8(vn) + w:u8(pn) + w:u8(vs) + w:u8(vls) + w:u8(vle) + w:u8(ps) + w:u8(pls) + w:u8(ple) + w:u8(vt) + w:u8(pt) + w:u8(ins and ins.vibType or 0) + w:u8(ins and ins.vibSweep or 0) + w:u8(ins and ins.vibDepth or 0) + w:u8(ins and ins.vibRate or 0) + w:u16le(ins and math.clamp(ins.fadeout, 0, 0xFFF) or 0) + w:fill(0, 22) + local datas = {} + for k, s in __iter(smps) do + local mono = s.data + if s.channels == 2 then + mono = buffer.create(s.length * 4) + for f = 0, s.length - 1 do + buffer.writef32(mono, f * 4, (buffer.readf32(s.data, f * 8) + buffer.readf32(s.data, f * 8 + 4)) / 2) + end + end + local bits = s.bits == 16 and 16 or 8 + local bps = math.floor(bits / 8 +) datas[k] = Pcm.encode(mono, s.length, { bits = bits, signed = true, delta = true }) + local typ = (bits == 16 and 16 or 0) + local ls, ll = 0, 0 + if s.loopType > 0 then + typ =typ+ s.loopType + ls, ll = s.loopStart * bps, (s.loopEnd - s.loopStart) * bps + end + local ft = s.finetune + local rel = s.relativeNote + if m.format == "mod" then + rel = 0 + end + w:u32le(s.length * bps) + w:u32le(ls) + w:u32le(ll) + w:u8(math.clamp(math.floor(s.volume), 0, 64)) + w:u8(math.clamp(math.floor(ft), -128, 127) % 256) + w:u8(typ) + w:u8(math.clamp(math.floor(s.pan or 128), 0, 255)) + w:u8(math.clamp(math.floor(rel), -128, 127) % 256) + w:u8(0) + writeName(w, s.name, 22) + end + for _, dd in __iter(datas) do + w:bytes(dd) + end +__DARKLUA_CONTINUE_23=true until true if not __DARKLUA_CONTINUE_23 then break end end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts) -> the module rendered as an audio Decoder (opts: Tracker.RenderOptions + DecodeOptions) +function Xm.open(r, opts) +local m, err = Xm.decode(r, opts) + if not m then + return nil, err + end + return Tracker.render(m, opts) +end + +return Xm +end +__FILES["music/xmi"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs, +-- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description +-- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track, +-- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's +-- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second +-- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the +-- first tempo event's value, unused). Renders through codecs/audio/MidiRender. +-- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Chunks = __include("containers/Chunks") +local Render = __include("codecs/audio/MidiRender") + +-- ------------------------------------------------------------------------------------------------ contract +local Xmi = { + name = "xmi", + category = "music", + extensions = { "xmi", "xmidi" }, + mime = { "audio/x-xmidi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" }, + caps = { decode = true, encode = false, render = true, songs = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function Xmi.sniff(r) +local id, kind = r:peek(4), r:peek(4, 8) + if id == "FORM" and (kind == "XDIR" or kind == "XMID") then + return 1 + end + return id == "CAT " and kind == "XMID" and 0.9 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 +local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 } +local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } + +-- a MIDI variable-length number at p -> value, next p (nil past e) +local function vlq(b, p, e) +local v = 0 + for _ = 1, 4 do + if p >= e then + return nil, p + end + local c = readu8(b, p) + p =p+ 1 + v = v * 128 + c % 128 + if c < 128 then + return v, p + end + end + return nil, p +end + +local function bytes(b, p, n) +local t= (table.create(n) ) +for i = 1, n do + t[i] = readu8(b, p + i - 1) + end + return t +end + +-- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message +local function events(b, p, e, maxEvents) +local list, offs= {}, {} + local tick, tempo = 0, nil + while p < e do + local st = readu8(b, p) + p =p+ 1 + if st < 0x80 then + tick =tick+ st + elseif st == 0xFF then + if p >= e then + return nil, "truncated meta event" + end + local kind = readu8(b, p) + local n, q = vlq(b, p + 1, e) + if not n or q + n > e then + return nil, "truncated meta event" + end + if kind == 0x2F then + break + elseif kind == 0x51 and n >= 3 then + tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + else + table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) }) + end + p = q + n + elseif st == 0xF0 or st == 0xF7 then + local n, q = vlq(b, p, e) + if not n or q + n > e then + return nil, "truncated sysex" + end + table.insert(list, { tick = tick, type = st == 0xF0 and"sysex" or"escape", data = bytes(b, q, n) }) + p = q + n + elseif st < 0xF0 then + local hi, ch = math.floor(st / 16), st % 16 + local n = DATA[hi] + if p + n > e then + return nil, "truncated event" + end + local d = bytes(b, p, n) + p =p+ n + table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d }) + if hi == 9 then + local dur, q = vlq(b, p, e) + if not dur then + return nil, "truncated note duration" + end + p = q + table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } }) + end + else + return nil, string.format("unexpected status byte 0x%02X", st) + end + if #list + #offs > maxEvents then + return nil, "limit: more than " .. maxEvents .. " events" + end + end + -- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging) + for _, o in __iter(offs) do + if o.tick > tick then + o.tick = tick + o.ev.tick = tick + end + end + return Render.merge(list, offs), tick, tempo +end + +-- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree +local function songs(b, base, limit) +local out = {} + local function form(c) + local song = {} + for _, s in __iter(Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF)) do + song[s.id] = song[s.id] or s + end + if song.EVNT then + table.insert(out, song) + end + end + for _, c in __iter(Chunks.walk(b, base, limit, Chunks.IFF)) do + local kind = (c.avail >= 4 and{(buffer.readstring(b, c.offset, 4) )}or{"" +})[1] if c.id == "FORM" and kind == "XMID" then + form(c) + elseif c.id == "CAT " and kind == "XMID" then + for _, s in __iter(Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF)) do + if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then + form(s) + end + end + end + end + return out +end + +function Xmi.decode(r, opts) +local o= opts or {} + if Xmi.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not an XMIDI file") + end + local list = songs(r.buf, r.base, r.limit) + local index = o.track or 1 + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk") + elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then + return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list)) + end + local song = list[index] + local ev = song.EVNT + local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24) + if not evs then + return nil, Err.from(endTick , ev.offset) + end + local last = math.max(endTick , (#evs > 0 and{evs[#evs].tick }or{0})[1]) + table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) }) + table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} }) + local timbres = {} + local tb = song.TIMB + if tb and tb.avail >= 2 then + for i = 0, math.min(buffer.readu16(r.buf, tb.offset), math.floor((tb.avail - 2) / 2)) - 1 do + table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) }) + end + end + local rb = song.RBRN + local branches = (rb and rb.avail >= 2 and{(buffer.readu16(r.buf, rb.offset) )}or{0 +})[1] local midi = Types.Midi.new(60) + midi.format = 0 + midi.tracks = { { events = evs } } + Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = branches }) + midi.meta.truncated = ev.truncated + return midi, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions) +function Xmi.open(r, opts) +local midi, err = Xmi.decode(r, opts) + if not midi then + return nil, err + end + return Render.decoder(midi, opts) +end + +return Xmi +end +__FILES["ops/AudioOps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an +-- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), +-- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. +-- +-- local AudioOps = require("rosetta.ops.AudioOps") -- F.ops.audio in the api +-- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder +-- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) +-- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) +-- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) +-- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's +-- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) +-- local both = AudioOps.concat({ a, b }) +-- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape +-- +-- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders +-- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the +-- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot +-- exceed full scale; upmixes copy mono to FL / FR and stereo to FL / FR (other channels silent). Tags and meta are +-- copied from the (first) input. +local Err = __include("core/Err") +local Types = __include("Types") +local Pcm = __include("codecs/audio/Pcm") +local Resample = __include("codecs/audio/Resample") + +local AudioOps = {} + +local readf32, writef32 = buffer.readf32, buffer.writef32 +local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt + +-- ------------------------------------------------------------------------------------------------ validation +local function isAudio(a) +return type(a) == "table" + and a.kind == "audio" + and type(a.samples) == "buffer" + and type(a.frames) == "number" + and type(a.channels) == "number" + and a.channels >= 1 + and type(a.sampleRate) == "number" + and a.sampleRate > 0 + and buffer.len(a.samples) >= a.frames * a.channels * 4 +end + +local function bad(what) +return nil, Err.new(Err.ARG, what) +end + +-- a new Audio with a's rate / tags / meta and the given layout +local function like(a, channels, frames, rate) +local out = Types.Audio.new(rate or a.sampleRate, channels, frames) + out.tags = table.clone(a.tags or {}) + out.meta = table.clone(a.meta or {}) + return out +end + +-- ------------------------------------------------------------------------------------------------ conversion +-- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT +-- past it; default 2^31) +function AudioOps.toAudio(v, opts) +if isAudio(v) then + return v, nil + end + local src, err = Pcm.source(v) + if not src then + return nil, err + end + return Pcm.collect(src, opts and opts.maxFrames) +end +AudioOps.fromDecoder = AudioOps.toAudio + +-- ------------------------------------------------------------------------------------------------ levels +-- gain(a, factor) -> Audio with every sample times factor +function AudioOps.gain(a, factor) +if not isAudio(a) then + return bad("gain: expected an Audio") + end + if type(factor) ~= "number" or factor ~= factor then + return bad("gain: factor must be a number") + end + local n = a.frames * a.channels + local out = like(a, a.channels, a.frames) + local s, d = a.samples, out.samples + for i = 0, n - 1 do + writef32(d, i * 4, readf32(s, i * 4) * factor) + end + return out, nil +end + +-- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) +function AudioOps.gainDb(a, db) +if type(db) ~= "number" or db ~= db then + return bad("gainDb: dB must be a number") + end + return AudioOps.gain(a, 10 ^ (db / 20)) +end + +-- peak(a) -> the largest |sample|, { per channel } +function AudioOps.peak(a) +if not isAudio(a) then + return nil, Err.new(Err.ARG, "peak: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = abs(readf32(s, p + (c - 1) * 4)) + if v > per[c] then + per[c] = v + end + end + end + local m = 0 + for c = 1, ch do + m = max(m, per[c]) + end + return m, per +end + +-- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) +function AudioOps.rms(a) +if not isAudio(a) then + return nil, Err.new(Err.ARG, "rms: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = readf32(s, p + (c - 1) * 4) + per[c]=per[c]+ v * v + end + end + local total = 0 + local n = max(1, a.frames) + for c = 1, ch do + total =total+ per[c] + per[c] = sqrt(per[c] / n) + end + return sqrt(total / (n * ch)), per +end + +-- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) +function AudioOps.normalize(a, target) +local p, perr = AudioOps.peak(a) + if not p then + return nil, perr +end + local t = target or 1 + if type(t) ~= "number" or t ~= t or t < 0 then + return bad("normalize: target must be a number >= 0") + end + return AudioOps.gain(a, (p > 0 and((t / p ))or(1))) +end + +-- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps +function AudioOps.fade(a, inSec, outSec) +if not isAudio(a) then + return bad("fade: expected an Audio") + end + local fi = floor(max(0, (inSec or 0) * a.sampleRate) + 0.5) + local fo = floor(max(0, (outSec or 0) * a.sampleRate) + 0.5) + if fi ~= fi or fo ~= fo then + return bad("fade: bad duration") + end + local out = like(a, a.channels, a.frames) + buffer.copy(out.samples, 0, a.samples, 0, a.frames * a.channels * 4) + local ch, d, n = a.channels, out.samples, a.frames + for f = 0, min(fi, n) - 1 do + local g = f / fi + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + for k = 0, min(fo, n) - 1 do + local f = n - 1 - k + local g = k / fo + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ channels +-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) +local LAYOUT= { + { "C" }, + { "FL", "FR" }, + { "FL", "FR", "C" }, + { "FL", "FR", "BL", "BR" }, + { "FL", "FR", "C", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BC", "SL", "SR" }, + { "FL", "FR", "C", "LFE", "BL", "BR", "SL", "SR" }, +} +local H = sqrt(0.5) -- -3 dB +-- speaker -> its contribution to (left, right) in a stereo downmix +local TO_STEREO= { + FL = { 1, 0 }, FR = { 0, 1 }, C = { H, H }, LFE = { 0, 0 }, BL = { H, 0 }, BR = { 0, H }, SL = { H, 0 }, + SR = { 0, H }, BC = { 0.5, 0.5 }, +} + +-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +local function matrix(from, to) +local m= (table.create(to) ) +for o = 1, to do + m[o] = table.create(from, 0) + end + if from == to then + for c = 1, to do + m[c][c] = 1 + end + return m + end + local inL, outL = LAYOUT[from], LAYOUT[to] + if to < from and inL and outL and to <= 2 then + -- down to stereo (then mono = the average of the two) + local l, r= table.create(from, 0), table.create(from, 0) + local sl, sr = 0, 0 + for i, sp in __iter(inL) do + local w = TO_STEREO[sp] or { 0, 0 } + l[i], r[i] = w[1], w[2] + sl =sl+ w[1] + sr =sr+ w[2] + end + local norm = 1 / max(sl, sr, 1) + for i = 1, from do + if to == 2 then + m[1][i], m[2][i] = l[i] * norm, r[i] * norm + else + m[1][i] = (l[i] + r[i]) * norm * 0.5 + end + end + return m + end + if from == 1 then + -- mono up: FL and FR (or the only channel) + if outL then + local placed = false + for o, sp in __iter(outL) do + if sp == "FL" or sp == "FR" then + m[o][1] = 1 + placed = true + end + end + if not placed then + m[1][1] = 1 + end + else + m[1][1] = 1 + end + return m + end + if inL and outL then + -- same-named speakers carry over; down: missing speakers fold into the stereo pair at their weights + local outIdx= {} + for o, sp in __iter(outL) do + outIdx[sp] = o + end + for i, sp in __iter(inL) do + local o = outIdx[sp] + if o then + m[o][i] = 1 + elseif to < from and outIdx.FL ~= nil and outIdx.FR ~= nil then + local w = TO_STEREO[sp] or { 0, 0 } + local fl, fr = outIdx.FL , outIdx.FR do local __DARKLUA_VAR= +m[fl]__DARKLUA_VAR[i]=__DARKLUA_VAR[i]+ w[1] +end do local __DARKLUA_VAR0= m[fr]__DARKLUA_VAR0[i]=__DARKLUA_VAR0[i]+ w[2] +end end + end + if to < from then + for o = 1, to do + local s = 0 + for i = 1, from do + s =s+ m[o][i] + end + if s > 1 then + for i = 1, from do +do local __DARKLUA_VAR= m[o]__DARKLUA_VAR[i]=__DARKLUA_VAR[i]/ s +end end + end + end + end + return m + end + -- unknown layouts: channel i -> i, extra outputs silent, extra inputs dropped + for c = 1, min(from, to) do + m[c][c] = 1 + end + return m +end +AudioOps.matrix = matrix + +-- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) +function AudioOps.remix(a, channels, m) +if not isAudio(a) then + return bad("remix: expected an Audio") + end + if type(channels) ~= "number" or channels < 1 or channels > 256 or channels % 1 ~= 0 then + return bad("remix: channels must be 1 .. 256") + end + local from = a.channels + local mm = m or matrix(from, channels) + if type(mm) ~= "table" or #mm ~= channels then + return bad("remix: the matrix needs one row per output channel") + end + for o = 1, channels do + if type(mm[o]) ~= "table" then + return bad("remix: matrix row " .. o .. " is not a table") + end + end + local out = like(a, channels, a.frames) + local s, d = a.samples, out.samples + local x = table.create(from, 0) + for f = 0, a.frames - 1 do + local p = f * from * 4 + for i = 1, from do + x[i] = readf32(s, p + (i - 1) * 4) + end + local q = f * channels * 4 + for o = 1, channels do + local row = mm[o] + local v = 0 + for i = 1, from do + local w = row[i] + if w and w ~= 0 then + v =v+ w * x[i] + end + end + writef32(d, q + (o - 1) * 4, v) + end + end + return out, nil +end + +-- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) +function AudioOps.downmix(a, channels) +if not isAudio(a) then + return bad("downmix: expected an Audio") + end + local n = channels or min(2, a.channels) + if n > a.channels then + return bad("downmix: more output channels than input") + end + return AudioOps.remix(a, n) +end + +-- upmix(a, channels) -> Audio with more channels +function AudioOps.upmix(a, channels) +if not isAudio(a) then + return bad("upmix: expected an Audio") + end + if type(channels) ~= "number" or channels < a.channels then + return bad("upmix: fewer output channels than input") + end + return AudioOps.remix(a, channels) +end + +-- ------------------------------------------------------------------------------------------------ time +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") +function AudioOps.resample(a, rate, opts) +if not isAudio(a) then + return bad("resample: expected an Audio") + end + local samples, frames = Resample.buffer(a.samples, a.frames, a.channels, a.sampleRate, rate, opts) + if not samples then + return bad("resample: " .. tostring(frames)) + end + local out = like(a, a.channels, 0, rate) + out.samples = samples + out.frames = frames +return out, nil +end + +-- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) +function AudioOps.trim(a, start, stop) +if not isAudio(a) then + return bad("trim: expected an Audio") + end + if type(start) ~= "number" or start ~= start or (stop ~= nil and (type(stop) ~= "number" or stop ~= stop)) then + return bad("trim: start / stop must be numbers (seconds)") + end + local f0 = math.clamp(floor(start * a.sampleRate + 0.5), 0, a.frames) + local f1 = (stop and{(math.clamp(floor(stop * a.sampleRate + 0.5), f0, a.frames) )}or{a.frames +})[1] local ch = a.channels + local out = like(a, ch, f1 - f0) + buffer.copy(out.samples, 0, a.samples, f0 * ch * 4, (f1 - f0) * ch * 4) + return out, nil +end + +-- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err +local function conform(list, what) +if type(list) ~= "table" or #list == 0 then + return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") + end + local first = list[1] + if not isAudio(first) then + return nil, Err.new(Err.ARG, what .. ": item 1 is not an Audio") + end + local out = { first } + for i = 2, #list do + local a = list[i] + if not isAudio(a) then + return nil, Err.new(Err.ARG, what .. ": item " .. i .. " is not an Audio") + end + if a.sampleRate ~= first.sampleRate then + local r, err = AudioOps.resample(a, first.sampleRate) + if not r then + return nil, err + end + a = r + end + if a.channels ~= first.channels then + local r, err = AudioOps.remix(a, first.channels) + if not r then + return nil, err + end + a = r + end + out[i] = a + end + return out, nil +end + +-- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) +function AudioOps.concat(list) +local items, err = conform(list, "concat") + if not items then + return nil, err + end + local first = items[1] + local ch = first.channels + local total = 0 + for _, a in __iter(items) do + total =total+ a.frames + end + local out = like(first, ch, total) + local at = 0 + for _, a in __iter(items) do + buffer.copy(out.samples, at * ch * 4, a.samples, 0, a.frames * ch * 4) + at =at+ a.frames + end + return out, nil +end + +-- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at +-- the first one's rate and channel count +function AudioOps.mix(list, weights) +local items, err = conform(list, "mix") + if not items then + return nil, err + end + if weights ~= nil and type(weights) ~= "table" then + return bad("mix: weights must be a list of numbers") + end + local first = items[1] + local ch = first.channels + local frames = 0 + for _, a in __iter(items) do + frames = max(frames, a.frames) + end + local out = like(first, ch, frames) + local d = out.samples + for i, a in __iter(items) do + local w = (weights and{weights[i] or 1 }or{1 +})[1] if type(w) ~= "number" then + return bad("mix: weight " .. i .. " is not a number") + end + local s = a.samples + for k = 0, a.frames * ch - 1 do + writef32(d, k * 4, readf32(d, k * 4) + readf32(s, k * 4) * w) + end + end + return out, nil +end + +return AudioOps +end +__FILES["ops/ImageOps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion, +-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as +-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and +-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources. +-- +-- local Ops = require("rosetta.ops.ImageOps") +-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws) +-- local grey = Ops.convert(img, "gray8") +-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over" +-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation +-- +-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as +-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's +-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and +-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with +-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8. +local Err = __include("core/Err") +local Types = __include("Types") +local K = __include("ops/ImageOps/Kernels") + +local ImageOps = {} + +local MAX_PIXELS = 2 ^ 26 + +-- ------------------------------------------------------------------------------------------------ validation + + +local function arg(msg) +return nil, Err.new(Err.ARG, msg) +end + +local function isInt(v) +return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31 +end + +local function bytesOf(fmt, w, h) +if fmt == "yuv420p" then + return w * h + 2 * (math.floor((w + 1) / 2)) * (math.floor((h + 1) / 2)) + end + local bpp = Types.BPP[fmt] + return (bpp and((w * h * bpp ))or(nil +))end + +-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough) +local function check(img) +if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return arg("expected an Image") + end + if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then + return arg("bad image size") + end + local need = bytesOf(img.format, img.width, img.height) + if not need then + return arg("unknown pixel format " .. tostring(img.format)) + end + if buffer.len(img.pixels) < need then + return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format) + end + return true, nil +end +ImageOps.check = check + +local function limit(w, h, opts) +local max= (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS + if w * h > max then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max)) + end + return true, nil +end + +-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames +local function like(img, w, h, fmt) +local out = Types.Image.new(w, h, (fmt or img.format) ) + for k, v in __iter(img.meta) do + out.meta[k] = v + end + out.loops = img.loops + return out +end + +-- ------------------------------------------------------------------------------------------------ basics +-- new(w, h, format?) -> a zero-filled Image | nil, Err +function ImageOps.new(w, h, format) +local fmt = format or "rgba8" + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("bad image size") + end + if not bytesOf(fmt, 1, 1) then + return arg("unknown pixel format " .. tostring(fmt)) + end + local ok, e = limit(w, h, nil) + if not ok then + return nil, e + end + return Types.Image.new(w, h, fmt ), nil +end + +-- copy(img) -> a deep copy of the pixels (frames are shared) +function ImageOps.copy(img) +local ok, e = check(img) + if not ok then + return nil, e + end + local out = like(img, img.width, img.height) + buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels)) + out.frames = img.frames + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ convert +-- convert(img, format) -> a new Image in format (a copy when it is already) +function ImageOps.convert(img, format) +local ok, e = check(img) + if not ok then + return nil, e + end + if not bytesOf(format, 1, 1) then + return arg("unknown pixel format " .. tostring(format)) + end + local w, h = img.width, img.height + if img.format == format then + return ImageOps.copy(img) + end + local src = img + if img.format == "yuv420p" then + local rgba = like(img, w, h, "rgba8") + K.yuvToRgba(img.pixels, w, h, rgba.pixels) + if format == "rgba8" then + return rgba, nil + end + src = rgba + end + local out = like(img, w, h, format) + if format == "yuv420p" then + local rgba = src + if src.format ~= "rgba8" then + rgba = like(img, w, h, "rgba8") + K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h) + end + K.rgbaToYuv(rgba.pixels, w, h, out.pixels) + return out, nil + end + K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h) + return out, nil +end + +-- ops on yuv420p run on rgba8 and convert back +local function viaRgba(img, f) +if img.format ~= "yuv420p" then + return f(img) + end + local rgba = (ImageOps.convert(img, "rgba8") ) +local res, e = f(rgba) + if not res then + return nil, e + end + return ImageOps.convert(res, "yuv420p") +end + +-- ------------------------------------------------------------------------------------------------ geometry +local ALPHA_CH= { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 } + +-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty) +function ImageOps.crop(img, x, y, w, h) +local ok, e = check(img) + if not ok then + return nil, e + end + if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then + return arg("crop: integer x, y, w, h") + end + local x0, y0 = math.max(0, x), math.max(0, y) + local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h) + if x1 <= x0 or y1 <= y0 then + return arg("crop: the rectangle is outside the image or empty") + end + return viaRgba(img, function(im) +local bpp = Types.BPP[im.format] +local out = like(im, x1 - x0, y1 - y0) + K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp) + return out, nil + end) +end + +-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom) +function ImageOps.flip(img, axis) +local ok, e = check(img) + if not ok then + return nil, e + end + if axis ~= "h" and axis ~= "v" then + return arg("flip: axis must be \"h\" or \"v\"") + end + return viaRgba(img, function(im) +local out = like(im, im.width, im.height) + K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] , axis == "h") + return out, nil + end) +end + +-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise) +function ImageOps.rotate90(img, turns) +local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(turns) then + return arg("rotate90: integer turns") + end + local t = turns % 4 + if t == 0 then + return ImageOps.copy(img) + end + return viaRgba(img, function(im) +local swap = t ~= 2 + local out = like(im, (swap and{im.height }or{im.width})[1], (swap and{im.width }or{im.height})[1]) + K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] , t) + return out, nil + end) +end + +-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels) + + +function ImageOps.resize(img, w, h, filter, opts) +local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(w) or not isInt(h) or w < 1 or h < 1 then + return arg("resize: bad target size") + end + local f = filter or "bilinear" + if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then + return arg("resize: filter must be nearest, bilinear or lanczos") + end + local lok, le = limit(w, h, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im) +local fmt = im.format + local bpp = Types.BPP[fmt] +local out = like(im, w, h) + if f == "nearest" then + K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h) + return out, nil + end + local kind, ch = K.KIND[fmt], K.CHANNELS[fmt] + local src, sw, sh = im.pixels, im.width, im.height + local alpha = ALPHA_CH[fmt] + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, sw * sh, alpha, kind, false) + end + if w ~= sw then + local tmp = buffer.create(w * sh * bpp) + K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true) + src, sw = tmp, w + end + if h ~= sh then + K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false) + elseif src == im.pixels or (w == im.width and alpha) then + buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp) + return out, nil + else + out.pixels = src + end + if alpha then + K.premultiply(out.pixels, w * h, alpha, kind, true) + end + return out, nil + end) +end + +-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's +-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered +-- pixels are zero (transparent). opts.maxPixels. +function ImageOps.rotate(img, degrees, opts) +local ok, e = check(img) + if not ok then + return nil, e + end + if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then + return arg("rotate: degrees must be a finite number") + end + local expand = not (opts and opts.expand == false) + if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then + return ImageOps.rotate90(img, (math.floor(degrees / 90)) % 4) + end + local w, h = img.width, img.height + local ang = -math.rad(degrees) + local function r15(v) +return math.floor(v * 1e15 + 0.5) / 1e15 + end + local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 } + local function tr(x, y) +return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6] + end + local cx, cy = w / 2, h / 2 + m[3], m[6] = tr(-cx, -cy) + m[3]=m[3]+ cx + m[6]=m[6]+ cy + local nw, nh = w, h + if expand then + local xs, ys = {}, {} + for _, p in __iter({ { 0, 0 }, { w, 0 }, { w, h }, { 0, h } }) do + local x, y = tr(p[1], p[2]) + table.insert(xs, x) + table.insert(ys, y) + end + nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4])) + nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4])) + m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2) + end + local lok, le = limit(nw, nh, opts) + if not lok then + return nil, le + end + return viaRgba(img, function(im) +local out = like(im, nw, nh) + local kind = K.KIND[im.format] + local alpha = ALPHA_CH[im.format] + local src = im.pixels + if alpha then + src = buffer.create(buffer.len(im.pixels)) + buffer.copy(src, 0, im.pixels) + K.premultiply(src, w * h, alpha, kind, false) + end + K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m) + if alpha then + K.premultiply(out.pixels, nw * nh, alpha, kind, true) + end + return out, nil + end) +end + +-- ------------------------------------------------------------------------------------------------ compositing +local RGBA= { rgba8 = true, rgba16 = true, rgbaf32 = true } + +-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's +-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite +-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only). + + +function ImageOps.blit(dst, src, x, y, opts) +local ok, e = check(dst) + if not ok then + return nil, e + end + local ok2, e2 = check(src) + if not ok2 then + return nil, e2 + end + if not isInt(x) or not isInt(y) then + return arg("blit: integer x, y") + end + local blend = (opts and opts.blend) or "over" + if blend ~= "over" and blend ~= "source" then + return arg("blit: blend must be \"over\" or \"source\"") + end + local opacity = (opts and opts.opacity) or 1 + if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then + return arg("blit: opacity must be 0..1") + end + -- clip + local sx, sy = math.max(0, -x), math.max(0, -y) + local dx, dy = math.max(0, x), math.max(0, y) + local w = math.min(src.width - sx, dst.width - dx) + local h = math.min(src.height - sy, dst.height - dy) + if w <= 0 or h <= 0 then + return dst, nil + end + if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then + -- work on an rgba copy of the region, then write it back in dst's format + local region = (ImageOps.crop(dst, dx, dy, w, h) ) +local work = (region.format == "rgba8" and{region }or{(ImageOps.convert(region, "rgba8") )})[1] +ImageOps.blit(work, src, x - dx, y - dy, opts) + if dst.format == "yuv420p" then + local full = (ImageOps.convert(dst, "rgba8") ) +ImageOps.blit(full, work, dx, dy, { blend = "source" }) + local back = (ImageOps.convert(full, "yuv420p") ) +buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels)) + else + local back = (ImageOps.convert(work, dst.format) ) +K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] ) + end + return dst, nil + end + local s = src + if src.format ~= dst.format then + s = (ImageOps.convert(src, dst.format) ) +end + if blend == "source" then + K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] ) + elseif dst.format == "rgba8" then + K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5)) + else + K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format]) + end + return dst, nil +end + +-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it +function ImageOps.composite(dst, src, x, y, opts) +local out, e = ImageOps.copy(dst) + if not out then + return nil, e + end + out.frames = nil + return ImageOps.blit(out, src, x or 0, y or 0, opts) +end + +local function premul(img, un) +local out, e = ImageOps.copy(img) + if not out then + return nil, e + end + out.frames = nil + local ch = ALPHA_CH[img.format] + if ch then + K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un) + end + return out, nil +end + +-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged) +function ImageOps.premultiply(img) +return premul(img, false) +end +function ImageOps.unpremultiply(img) +return premul(img, true) +end + +-- ------------------------------------------------------------------------------------------------ pixels +local MAXV= { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 } + +-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b; +-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range. +function ImageOps.getPixel(img, x, y) +local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("getPixel: coordinates out of range") + end + local b, f, i = img.pixels, img.format, y * img.width + x + local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32 + if f == "rgba8" then + return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3) + elseif f == "rgba16" then + return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6) + elseif f == "rgbaf32" then + return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12) + elseif f == "rgb8" then + return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255 + elseif f == "gray8" then + local v = ru8(b, i) + return v, v, v, 255 + elseif f == "gray16" then + local v = ru16(b, i * 2) + return v, v, v, 65535 + elseif f == "graya8" then + local v = ru8(b, i * 2) + return v, v, v, ru8(b, i * 2 + 1) + elseif f == "alpha8" then + return 255, 255, 255, ru8(b, i) + end + local one = (ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) ) +local rgba = (ImageOps.convert(one, "rgba8") ) +local j = ((y % 2) * rgba.width + (x % 2)) * 4 + if j + 4 > buffer.len(rgba.pixels) then + j = 0 + end + return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255 +end + +-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and +-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p. +function ImageOps.setPixel(img, x, y, r, g, b, a) +local ok, e = check(img) + if not ok then + return nil, e + end + if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then + return arg("setPixel: coordinates out of range") + end + if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then + return arg("setPixel: numeric channels") + end + local f = img.format + if f == "yuv420p" then + return arg("setPixel: not supported on yuv420p (convert to rgba8 first)") + end + local max = MAXV[f] + local al = (a == nil and{max }or{a +})[1] local function q(v) +if max == 1 then + return v + end + if v ~= v then + return 0 + end + return math.clamp(math.floor(v + 0.5), 0, max) + end + local px, i = img.pixels, y * img.width + x + local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32 + local function grey() +if max == 1 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return math.floor((q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) / 65536 +) end + if f == "rgba8" then + wu8(px, i * 4, q(r)) + wu8(px, i * 4 + 1, q(g)) + wu8(px, i * 4 + 2, q(b)) + wu8(px, i * 4 + 3, q(al)) + elseif f == "rgba16" then + wu16(px, i * 8, q(r)) + wu16(px, i * 8 + 2, q(g)) + wu16(px, i * 8 + 4, q(b)) + wu16(px, i * 8 + 6, q(al)) + elseif f == "rgbaf32" then + wf(px, i * 16, r) + wf(px, i * 16 + 4, g) + wf(px, i * 16 + 8, b) + wf(px, i * 16 + 12, al) + elseif f == "rgb8" then + wu8(px, i * 3, q(r)) + wu8(px, i * 3 + 1, q(g)) + wu8(px, i * 3 + 2, q(b)) + elseif f == "gray8" then + wu8(px, i, grey()) + elseif f == "gray16" then + wu16(px, i * 2, grey()) + elseif f == "graya8" then + wu8(px, i * 2, grey()) + wu8(px, i * 2 + 1, q(al)) + else + wu8(px, i, q(al)) + end + return true, nil +end + +-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel) +function ImageOps.fill(img, r, g, b, a) +local ok, e = check(img) + if not ok then + return nil, e + end + if img.format == "yuv420p" then + return arg("fill: not supported on yuv420p") + end + local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a) + if not sok then + return nil, se + end + local bpp = Types.BPP[img.format] +local n = img.width * img.height * bpp + local filled = bpp + while filled < n do + local c = math.min(filled, n - filled) + buffer.copy(img.pixels, filled, img.pixels, 0, c) + filled =filled+ c + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ animation +-- frameCount(img) -> the number of frames (1 for a still image) +function ImageOps.frameCount(img) +if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + return #img.frames + end + return 1 +end + +-- durations(img) -> { seconds } per frame ({ 0 } for a still image) +function ImageOps.durations(img) +local out = {} + if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then + for i, f in __iter(img.frames) do + out[i] = (type(f.delay) == "number" and{f.delay }or{0 +})[1] end + return out + end + return { 0 } +end + +-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 / +-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's +-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores +-- the canvas from before the frame). A still image gives { img }. +function ImageOps.coalesce(img) +local ok, e = check(img) + if not ok then + return nil, e + end + local frames = img.frames + if type(frames) ~= "table" or #frames == 0 then + return { img }, nil + end + local fmt = (RGBA[img.format] and{img.format }or{"rgba8" +})[1] local canvas = Types.Image.new(img.width, img.height, fmt ) + local bpp = Types.BPP[fmt] +local out = {} + for i, f in __iter(frames) do + if type(f) ~= "table" then + return arg("coalesce: frame " .. i .. " is not a Frame") + end + local fi = f.image + local fok, fe = check(fi) + if not fok then + return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe ).message) + end + local fx, fy = (isInt(f.x) and{f.x }or{0})[1], (isInt(f.y) and{f.y }or{0 +})[1] local saved= nil + if f.dispose == "previous" then + local sb = buffer.create(buffer.len(canvas.pixels)) + buffer.copy(sb, 0, canvas.pixels) + saved = sb + end + local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = f.blend == "source" and"source" or"over" }) + if not bok then + return nil, be + end + local snap = Types.Image.new(img.width, img.height, fmt ) + buffer.copy(snap.pixels, 0, canvas.pixels) + for k, v in __iter(img.meta) do + snap.meta[k] = v + end + snap.meta.delay = f.delay + out[i] = snap + if f.dispose == "background" then + local x0, y0 = math.max(0, fx), math.max(0, fy) + local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height) + for y = y0, y1 - 1 do + if x1 > x0 then + buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp) + end + end + elseif saved then + canvas.pixels = saved + end + end + return out, nil +end + +-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0, +-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds } +-- (default 0.1). All images need the same size and format. +function ImageOps.fromFrames(images, delays) +if type(images) ~= "table" or #images == 0 then + return arg("fromFrames: a non-empty list of Images") + end + local first = images[1] + local ok, e = check(first) + if not ok then + return nil, e + end + local frames = {} + for i, im in __iter(images) do + local iok, ie = check(im) + if not iok then + return nil, ie + end + if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then + return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1") + end + local d = 0.1 + if type(delays) == "number" then + d = delays + elseif type(delays) == "table" and type(delays[i]) == "number" then + d = delays[i] + end + frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" } + end + local out = like(first, first.width, first.height) + buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels)) + out.frames = frames +out.loops = 0 + return out, nil +end + +return ImageOps +end +__FILES["ops/ImageOps/Kernels"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +--!optimize 2 +-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller +-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by +-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers). +-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by +-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through +-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c. +local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32 +local floor, clamp = math.floor, math.clamp + +local K = {} + +-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8 +K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 } +K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 } +K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 } + +local function rd(b, o, kind) +if kind == 1 then + return readu8(b, o) + elseif kind == 2 then + return readu16(b, o) + end + return readf32(b, o) +end + +local function wr(b, o, kind, v) + if kind == 1 then + writeu8(b, o, clamp(floor(v + 0.5), 0, 255)) + elseif kind == 2 then + writeu16(b, o, clamp(floor(v + 0.5), 0, 65535)) + else + writef32(b, o, v) + end +end + +-- ------------------------------------------------------------------------------------------------ convert +-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1 +local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 } + +local function depthConv(v, from, to) +if from == to then + return v + end + if from == 8 then + if to == 16 then + return v * 257 + end + return v / 255 + elseif from == 16 then + if to == 8 then + return math.floor((v * 255 + 32767) / 65535 +) end + return v / 65535 + end + -- float + if v ~= v then + v = 0 + end + if to == 8 then + return clamp(floor(v * 255 + 0.5), 0, 255) + end + return clamp(floor(v * 65535 + 0.5), 0, 65535) +end + +-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth +local function luma(r, g, b, depth) +if depth == 0 then + return (r * 19595 + g * 38470 + b * 7471) / 65536 + end + return math.floor((r * 19595 + g * 38470 + b * 7471 + 32768) / 65536 +)end + +function K.convert(src, sf, dst, df, n) + local sd, dd = DEPTH[sf] , DEPTH[df] +local smax = sd == 8 and 255 or(sd == 16 and 65535 or 1 +) local toGray = df == 5 or df == 6 or df == 7 + for i = 0, n - 1 do + local r, g, b, a +if sf == 1 then + local o = i * 4 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), (readu8(src, o + 3) ) +elseif sf == 2 then + local o = i * 8 + r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), (readu16(src, o + 6) ) +elseif sf == 3 then + local o = i * 16 + r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), (readf32(src, o + 12) ) +elseif sf == 4 then + local o = i * 3 + r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255 + elseif sf == 5 then + local v = readu8(src, i) + r, g, b, a = v, v, v, 255 + elseif sf == 6 then + local v = readu16(src, i * 2) + r, g, b, a = v, v, v, 65535 + elseif sf == 7 then + local v = readu8(src, i * 2) + r, g, b, a = v, v, v, (readu8(src, i * 2 + 1) ) +else + r, g, b, a = 255, 255, 255, readu8(src, i) + end + if toGray then + local isGray = sf == 5 or sf == 6 or sf == 7 + local l = (isGray and{r }or{(luma(r, g, b, sd) +)})[1] l = depthConv(l, sd, dd) + if df == 5 then + writeu8(dst, i, l) + elseif df == 6 then + writeu16(dst, i * 2, l) + else + writeu8(dst, i * 2, l) + writeu8(dst, i * 2 + 1, depthConv(a, sd, dd)) + end + elseif df == 8 then + writeu8(dst, i, depthConv(a, sd, 8)) + else + r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), (depthConv(b, sd, dd) ) +if df == 1 then + local o = i * 4 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + writeu8(dst, o + 3, depthConv(a, sd, dd)) + elseif df == 2 then + local o = i * 8 + writeu16(dst, o, r) + writeu16(dst, o + 2, g) + writeu16(dst, o + 4, b) + writeu16(dst, o + 6, depthConv(a, sd, dd)) + elseif df == 3 then + local o = i * 16 + writef32(dst, o, r) + writef32(dst, o + 4, g) + writef32(dst, o + 8, b) + writef32(dst, o + 12, a == smax and sd ~= 0 and 1 or depthConv(a, sd, dd)) + else -- rgb8 + local o = i * 3 + writeu8(dst, o, r) + writeu8(dst, o + 1, g) + writeu8(dst, o + 2, b) + end + end + end +end + +-- JPEG-style BT.601 full range +function K.rgbaToYuv(src, w, h, dst) + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local uo, vo = w * h, w * h + cw * ch + for i = 0, w * h - 1 do + local o = i * 4 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255)) + end + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local sr, sg, sb, n = 0, 0, 0, 0 + for dy = 0, 1 do + local y = cy * 2 + dy + if y < h then + for dx = 0, 1 do + local x = cx * 2 + dx + if x < w then + local o = (y * w + x) * 4 + sr =sr+ readu8(src, o) + sg =sg+ readu8(src, o + 1) + sb =sb+ readu8(src, o + 2) + n =n+ 1 + end + end + end + end + sr, sg, sb = sr / n, sg / n, sb / n + local i = cy * cw + cx + writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255)) + writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255)) + end + end +end + +function K.yuvToRgba(src, w, h, dst) + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) local uo, vo = w * h, w * h + cw * ch + for y = 0, h - 1 do + local crow = (math.floor(y / 2)) * cw + for x = 0, w - 1 do + local yy = readu8(src, y * w + x) + local ci = crow + math.floor(x / 2 +) local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128 + local o = (y * w + x) * 4 + writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255)) + writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255)) + writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255)) + writeu8(dst, o + 3, 255) + end + end + local _ = ch +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- flip(src, dst, w, h, bpp, horizontal) +function K.flip(src, dst, w, h, bpp, horizontal) + local stride = w * bpp + if not horizontal then + for y = 0, h - 1 do + buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride) + end + return + end + for y = 0, h - 1 do + local row = y * stride + for x = 0, w - 1 do + buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp) + end + end +end + +-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3 +function K.rotate90(src, dst, w, h, bpp, turns) + for y = 0, h - 1 do + for x = 0, w - 1 do + local ox, oy, ow + if turns == 1 then + ox, oy, ow = y, w - 1 - x, h + elseif turns == 2 then + ox, oy, ow = w - 1 - x, h - 1 - y, w + else + ox, oy, ow = h - 1 - y, x, h + end + local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp + if bpp == 4 then + buffer.writeu32(dst, d, buffer.readu32(src, so)) + else + buffer.copy(dst, d, src, so, bpp) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ resample +local function bilinearF(x) +if x < 0 then + x = -x + end + if x < 1 then + return 1 - x + end + return 0 +end + +local function sinc(x) +if x == 0 then + return 1 + end + x =x* math.pi + return math.sin(x) / x +end + +local function lanczosF(x) +if x > -3 and x < 3 then + return sinc(x) * sinc(x / 3) + end + return 0 +end + +local function trunc(x) +return (x < 0 and{(math.ceil(x) )}or{(floor(x) +)})[1]end +-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised) + + + +function K.coeffs(inSize, outSize, filter) +local support0 = filter == "lanczos" and 3 or 1 + local f = (filter == "lanczos" and{lanczosF }or{bilinearF +})[1] local scale = inSize / outSize + local filterscale = math.max(scale, 1) + local support = support0 * filterscale + local ss = 1 / filterscale + local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), (table.create(outSize) ) +for xx = 0, outSize - 1 do + local center = (xx + 0.5) * scale + local xmin = math.max(0, trunc(center - support + 0.5)) + local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin + local w = table.create(math.max(xmax, 0), 0) + local ww = 0 + for x = 0, xmax - 1 do + local v = f((x + xmin - center + 0.5) * ss) + w[x + 1] = v + ww =ww+ v + end + if ww ~= 0 then + for x = 1, xmax do + w[x]=w[x]/ ww + end + end + start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w + end + return { start = start, count = count, weights = weights } +end + +-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind. +function K.resamplePass(src, w, h, ch, kind, dst, outN, c, horizontal) + local start, count, weights = c.start, c.count, c.weights + local size = kind + local fixed = kind == 1 + -- 8-bit: Pillow's 22-bit fixed-point coefficients + local iw= weights + if fixed then + iw = (table.create(outN) ) +for i = 1, outN do + local src0 = weights[i] + local t = table.create(#src0, 0) + for k = 1, #src0 do + local v = src0[k] * 4194304 + t[k] = (v < 0 and{(math.ceil(v - 0.5) )}or{(floor(v + 0.5) +)})[1] end + iw[i] = t + end + end + if horizontal then + for y = 0, h - 1 do + local row = y * w + for xx = 0, outN - 1 do + local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1] + local o = ((y * outN) + xx) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc =acc+ readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(math.floor(acc / 4194304), 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc =acc+ rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + else + for yy = 0, outN - 1 do + local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1] + for x = 0, w - 1 do + local o = (yy * w + x) * ch * size + for cc = 0, ch - 1 do + if fixed then + local acc = 2097152 + for k = 0, n - 1 do + acc =acc+ readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1] + end + writeu8(dst, o + cc, clamp(math.floor(acc / 4194304), 0, 255)) + else + local acc = 0 + for k = 0, n - 1 do + acc =acc+ rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1] + end + wr(dst, o + cc * size, kind, acc) + end + end + end + end + end + local _ = h +end + +-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...) +function K.nearest(src, w, h, bpp, dst, ow, oh) + local sx, sy = w / ow, h / oh + for y = 0, oh - 1 do + local iy = math.min(floor((y + 0.5) * sy), h - 1) + for x = 0, ow - 1 do + local ix = math.min(floor((x + 0.5) * sx), w - 1) + buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp) + end + end +end + +-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src +-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow) +function K.affine(src, w, h, ch, kind, dst, ow, oh, m) + local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6] + local size = kind + for y = 0, oh - 1 do + local py = y + 0.5 + for x = 0, ow - 1 do +local __DARKLUA_CONTINUE_32=false repeat local px = x + 0.5 + local xin = a * px + b * py + c - 0.5 + local yin = d * px + e * py + f - 0.5 + local o = (y * ow + x) * ch * size + local x0 = floor(xin) + local y0 = floor(yin) + if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then +__DARKLUA_CONTINUE_32=true break -- dst starts zeroed + end + local dx, dy = xin - x0, yin - y0 + local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1) + local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1) + for cc = 0, ch - 1 do + local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind) + local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind) + local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind) + local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind) + local top = p00 + (p01 - p00) * dx + local bot = p10 + (p11 - p10) * dx + local v = top + (bot - top) * dy + if kind == 1 then + writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates + else + wr(dst, o + cc * size, kind, v) + end + end +__DARKLUA_CONTINUE_32=true until true if not __DARKLUA_CONTINUE_32 then break end end + end +end + +-- ------------------------------------------------------------------------------------------------ compositing +-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place +function K.overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity) + for y = 0, h - 1 do + for x = 0, w - 1 do +local __DARKLUA_CONTINUE_35=false repeat local so = ((sy + y) * sw + sx + x) * 4 + local doff = ((dy + y) * dw + dx + x) * 4 + local sa = readu8(src, so + 3) + if opacity < 255 then + sa = math.floor((sa * opacity + 127) / 255 +) end + if sa == 0 then +__DARKLUA_CONTINUE_35=true break + end + local da = readu8(dst, doff + 3) + local blend = da * (255 - sa) + local outa255 = sa * 255 + blend + local coef1 = math.floor((sa * 255 * 255 * 128) / outa255 +) local coef2 = 255 * 128 - coef1 + for cc = 0, 2 do + local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128 + t = math.floor(((math.floor(t / 256)) + t) / 256 +) writeu8(dst, doff + cc, math.floor(t / 128)) + end + local t = outa255 + 0x80 + writeu8(dst, doff + 3, math.floor(((math.floor(t / 256)) + t) / 256)) +__DARKLUA_CONTINUE_35=true until true if not __DARKLUA_CONTINUE_35 then break end end + end +end + +-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1 +function K.overFloat(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity, kind) + local max = kind == 2 and 65535 or 1 + local px = 4 * kind + for y = 0, h - 1 do + for x = 0, w - 1 do +local __DARKLUA_CONTINUE_38=false repeat local so = ((sy + y) * sw + sx + x) * px + local doff = ((dy + y) * dw + dx + x) * px + local sa = rd(src, so + 3 * kind, kind) / max * opacity + if sa <= 0 then +__DARKLUA_CONTINUE_38=true break + end + local da = rd(dst, doff + 3 * kind, kind) / max + local oa = sa + da * (1 - sa) + for cc = 0, 2 do + local s = rd(src, so + cc * kind, kind) + local d = rd(dst, doff + cc * kind, kind) + wr(dst, doff + cc * kind, kind, (oa > 0 and(((s * sa + d * da * (1 - sa)) / oa ))or(0))) + end + wr(dst, doff + 3 * kind, kind, oa * max) +__DARKLUA_CONTINUE_38=true until true if not __DARKLUA_CONTINUE_38 then break end end + end +end + +-- copyRect: rows of a rectangle (bpp bytes per pixel) +function K.copyRect(dst, dw, src, sw, sx, sy, dx, dy, w, h, bpp) + for y = 0, h - 1 do + buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp) + end +end + +-- premultiply / unpremultiply in place: ch channels, alpha last, kind +function K.premultiply(b, n, ch, kind, un) + local max = kind == 1 and 255 or(kind == 2 and 65535 or 1 +) local px = ch * kind + for i = 0, n - 1 do + local o = i * px + local a = rd(b, o + (ch - 1) * kind, kind) + for cc = 0, ch - 2 do + local v = rd(b, o + cc * kind, kind) + local r + if un then + if a <= 0 then + r = 0 + elseif kind == 4 then + r = v / a + elseif kind == 1 then + r = math.min(255, math.floor((v * 255) / a)) -- Pillow's rgbA2rgba + else + r = math.min(max, math.floor((v * max + math.floor(a / 2)) / a)) + end + else + if kind == 4 then + r = v * a + elseif kind == 1 then + local t = v * a + 128 -- Pillow's MULDIV255 + r = math.floor(((math.floor(t / 256)) + t) / 256 +) else + r = math.floor((v * a + math.floor(max / 2)) / max +) end + end + wr(b, o + cc * kind, kind, r) + end + end +end + +return K +end +__FILES["ops/LayerOps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an +-- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- grey layer masks; every frame as an animated Image; walking the leaves. +-- +-- local LayerOps = require("rosetta.ops.LayerOps") +-- local img = LayerOps.flatten(layered) -- frame 1 / the layers +-- local img3 = LayerOps.flatten(layered, { frame = 3 }) +-- local anim = LayerOps.flattenFrames(layered) -- an Image with frames (delays from the Layered frames) +-- for layer, depth in LayerOps.leaves(layered.layers) do ... end +-- +-- Never throws: bad values return nil, Err.ARG. +local Err = __include("core/Err") +local Types = __include("Types") +local Blend = __include("codecs/image/Blend") + +local LayerOps = {} + +-- flatten(layered, opts?) -> rgba8 Image (layered.width x layered.height) | nil, Err + + + + + + +function LayerOps.flatten(layered, opts) +if type(layered) ~= "table" or type(layered.width) ~= "number" or type(layered.height) ~= "number" or type(layered.layers) ~= "table" then + return nil, Err.new(Err.ARG, "flatten: needs a Layered value") + end + local o= opts or {} + local w, h = math.floor(layered.width), math.floor(layered.height) + if w < 0 or h < 0 or w * h > 2 ^ 28 then + return nil, Err.new(Err.ARG, "flatten: bad size") + end + local layers = layered.layers + if o.frame then + local f = (type(layered.frames) == "table" and{layered.frames[o.frame] }or{nil +})[1] if f == nil and o.frame ~= 1 then + return nil, Err.new(Err.ARG, "flatten: no frame " .. tostring(o.frame)) + end + if f then + layers = f.layers + end + end + local img = Types.Image.new(w, h) + local bg = o.background + if type(bg) == "table" then + local v = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, w * h - 1 do + buffer.writeu32(img.pixels, i * 4, v) + end + end + Blend.flatten(layers, img.pixels, w, h, o.hidden == true) + return img, nil +end + +-- flattenFrames(layered, opts?) -> an rgba8 Image whose frames are every flattened frame (frame 1 is the image) +function LayerOps.flattenFrames(layered, opts) +local first, err = LayerOps.flatten(layered, opts) + if not first then + return nil, err + end + local frames = (type(layered.frames) == "table" and{layered.frames }or{{} +})[1] if #frames == 0 then + return first, nil + end + local list= {} + for i, f in __iter(frames) do + local o= (table.clone(opts or {}) ) +o.frame = i + local img = (i == 1 and{first }or{(LayerOps.flatten(layered, o) +)})[1] if not img then + return nil, Err.new(Err.ARG, "flatten: frame " .. i) + end + list[i] = { image = img, delay = tonumber(f.delay) or 0.1, x = 0, y = 0, dispose = "none", blend = "source" } + end + first.frames = list + return first, nil +end + +-- leaves(layers) -> iterator of (layer, depth) over the non-group layers of a tree, bottom to top +function LayerOps.leaves(layers) +local stack= { { layers, 0, 0 } } + return function() +while #stack > 0 do + local top = stack[#stack] + top[2]=top[2]+ 1 + local l = top[1][top[2] ] + if l == nil then + table.remove(stack) + elseif type(l.children) == "table" then + table.insert(stack, { l.children, 0, top[3] + 1 }) + else + return l, top[3] + end + end + return nil, nil + end +end + +return LayerOps +end +__FILES["ops/MeshOps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear +-- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat), +-- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an +-- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis +-- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels). +-- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type +-- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw). +-- +-- local MeshOps = require("rosetta.ops.MeshOps") -- F.ops.mesh in the api (when it lists ops) +-- local prim = MeshOps.merge(scene) -- one triangle primitive in world space +-- MeshOps.computeNormals(prim) +-- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape +local Err = __include("core/Err") +local Types = __include("Types") +local Greedy = __include("ops/MeshOps/Greedy") + +local MeshOps = {} + + + + + +local Scene = Types.Scene +local readf32, writef32 = buffer.readf32, buffer.writef32 +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ accessors +-- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one +function MeshOps.f32(acc) +if acc.type == "f32" then + return acc + end + local get = Scene.reader(acc) + if not get then + return nil + end + local n, c = acc.count, acc.components + local out = buffer.create(n * c * 4) + for i = 0, n - 1 do + for k = 0, c - 1 do + writef32(out, (i * c + k) * 4, get(i, k)) + end + end + local a = Scene.accessor(out, "f32", c, n) + a.matrix = acc.matrix + return a +end + +-- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1 +local function indexBuffer(prim) +local ind = prim.indices + if ind then + if ind.type == "u32" and ind.components == 1 then + return ind.data, ind.count + end + local get = Scene.reader(ind) + local out = buffer.create(ind.count * 4) + if get then + for i = 0, ind.count - 1 do + writeu32(out, i * 4, get(i, 0)) + end + end + return out, ind.count + end + local pos = prim.attributes.POSITION + local n = (pos and{pos.count }or{0 +})[1] local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, i) + end + return out, n +end + +local function vertexCount(prim) +local pos = prim.attributes.POSITION + return (pos and{pos.count }or{0 +})[1]end + +local function checkPrim(prim) +if type(prim) ~= "table" or type(prim.attributes) ~= "table" then + return Err.new(Err.ARG, "expected a Primitive") + end + local pos = prim.attributes.POSITION + if not pos or type(pos.data) ~= "buffer" or pos.components < 3 then + return Err.new(Err.ARG, "primitive without a POSITION accessor") + end + local n = pos.count + for name, a in __iter(prim.attributes) do + local size = Types.COMPONENT_SIZE[a.type] + if not size or type(a.data) ~= "buffer" or buffer.len(a.data) < a.count * a.components * size then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": bad accessor") + end + if a.count ~= n then + return Err.new(Err.ARG, "attribute " .. tostring(name) .. ": count differs from POSITION") + end + end + if prim.indices then + local ind = prim.indices + local size = Types.COMPONENT_SIZE[ind.type] + if not size or type(ind.data) ~= "buffer" or buffer.len(ind.data) < ind.count * size then + return Err.new(Err.ARG, "bad indices accessor") + end + local get = Scene.reader(ind) + if get then + for i = 0, ind.count - 1 do + if get(i, 0) >= n then + return Err.new(Err.ARG, "index out of range") + end + end + end + end + return nil +end +MeshOps.check = checkPrim + +-- ------------------------------------------------------------------------------------------------ triangulate +-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck +local function earclip(poly, P, out) + local k = #poly + if k < 3 then + return + end + if k == 3 then + table.insert(out, poly[1]) + table.insert(out, poly[2]) + table.insert(out, poly[3]) + return + end + -- Newell normal -> the projection plane (drop the dominant axis) + local nx, ny, nz = 0, 0, 0 + for a = 1, k do + local i, j = poly[a], poly[a % k + 1] + local xi, yi, zi = P(i, 0), P(i, 1), P(i, 2) + local xj, yj, zj = P(j, 0), P(j, 1), P(j, 2) + nx =nx+ (yi - yj) * (zi + zj) + ny =ny+ (zi - zj) * (xi + xj) + nz =nz+ (xi - xj) * (yi + yj) + end + local ax, ay, az = math.abs(nx), math.abs(ny), math.abs(nz) + local cu, cv, sign = 0, 1, nz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, nx + elseif ay >= az then + cu, cv, sign = 2, 0, ny + end + local function uv(i) +return P(i, cu), P(i, cv) + end + local s = sign < 0 and-1 or 1 + local ring = table.clone(poly) + local guard = 0 + while #ring > 3 and guard < k * k do + guard =guard+ 1 + local n = #ring + local clipped = false + for a = 1, n do + local ia, ib, ic = ring[(a - 2) % n + 1], ring[a], ring[a % n + 1] + local ax2, ay2 = uv(ia) + local bx, by = uv(ib) + local cx, cy = uv(ic) + local cross = ((bx - ax2) * (cy - ay2) - (by - ay2) * (cx - ax2)) * s + if cross > 0 then + local inside = false + for q = 1, n do + local iq = ring[q] + if iq ~= ia and iq ~= ib and iq ~= ic then + local qx, qy = uv(iq) + local d1 = ((bx - ax2) * (qy - ay2) - (by - ay2) * (qx - ax2)) * s + local d2 = ((cx - bx) * (qy - by) - (cy - by) * (qx - bx)) * s + local d3 = ((ax2 - cx) * (qy - cy) - (ay2 - cy) * (qx - cx)) * s + if d1 >= 0 and d2 >= 0 and d3 >= 0 then + inside = true + break + end + end + end + if not inside then + table.insert(out, ia) + table.insert(out, ib) + table.insert(out, ic) + table.remove(ring, a) + clipped = true + break + end + end + end + if not clipped then + break + end + end + -- whatever is left (3 corners, or a degenerate / self-intersecting rest): a fan + for a = 2, #ring - 1 do + table.insert(out, ring[1]) + table.insert(out, ring[a]) + table.insert(out, ring[a + 1]) + end +end + +local function u32(list) +local n = #list + local b = buffer.create(n * 4) + for i = 1, n do + writeu32(b, (i - 1) * 4, list[i]) + end + return Scene.accessor(b, "u32", 1, n) +end + +-- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip" +-- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says). +-- Lines and points come back unchanged. +function MeshOps.triangulate(prim, opts) +local err = checkPrim(prim) + if err then + return nil, err + end + local mode = prim.mode or "triangles" + if mode == "lines" or mode == "points" or mode == "line_strip" or mode == "line_loop" then + return prim, nil + end + local method = opts and opts.method or "earclip" + local ib, n = indexBuffer(prim) + local out= {} + if mode == "triangles" then + local m = n - n % 3 + for i = 0, m - 1 do + out[i + 1] = readu32(ib, i * 4) + end + elseif mode == "triangle_strip" then + for i = 0, n - 3 do + local a, b, c = readu32(ib, i * 4), readu32(ib, i * 4 + 4), readu32(ib, i * 4 + 8) + if i % 2 == 1 then + a, b = b, a + end + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + elseif mode == "triangle_fan" then + for i = 1, n - 2 do + table.insert(out, readu32(ib, 0)) + table.insert(out, readu32(ib, i * 4)) + table.insert(out, readu32(ib, i * 4 + 4)) + end + elseif mode == "polygons" then + local faces = prim.faces + if not faces then + return nil, Err.new(Err.ARG, "polygons primitive without faces") + end + local getf = Scene.reader(faces) + if not getf then + return nil, Err.new(Err.ARG, "bad faces accessor") + end + local pos = (MeshOps.f32(prim.attributes.POSITION) ) +local pd = pos.data + local P = function(i, c) +return readf32(pd, (i * 3 + c) * 4) + end + local at = 0 + for f = 0, faces.count - 1 do + local k = getf(f, 0) + if at + k > n then + return nil, Err.new(Err.ARG, "faces run past the indices") + end + if k >= 3 then + if method == "fan" or k == 3 then + for a = 1, k - 2 do + table.insert(out, readu32(ib, at * 4)) + table.insert(out, readu32(ib, (at + a) * 4)) + table.insert(out, readu32(ib, (at + a + 1) * 4)) + end + else + local poly = (table.create(k) ) +for a = 0, k - 1 do + poly[a + 1] = readu32(ib, (at + a) * 4) + end + earclip(poly, P, out) + end + end + at =at+ k + end + else + return nil, Err.new(Err.ARG, "unknown mode " .. tostring(mode)) + end + return { + attributes = prim.attributes, + indices = u32(out), + mode = "triangles", + material = prim.material, + targets = prim.targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ transform +local function det3(m) +return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +-- the inverse transpose of m's 3 x 3 part (column-major 9), for normals +local function normalMatrix(m) +local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) + if det == 0 then + det = 1 + end + local k = 1 / det + -- cofactor matrix / det (= inverse transpose), column-major + return { + (e * i - f * h) * k, -(b * i - c * h) * k, (b * f - c * e) * k, + -(d * i - f * g) * k, (a * i - c * g) * k, -(a * f - c * d) * k, + (d * h - e * g) * k, -(a * h - b * g) * k, (a * e - b * d) * k, + } +end + +-- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too). +-- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing. +function MeshOps.transform(prim, m) +local err = checkPrim(prim) + if err then + return nil, err + end + if type(m) ~= "table" or #m ~= 16 then + return nil, Err.new(Err.ARG, "expected a column-major 4x4 matrix (16 numbers)") + end + local nm = normalMatrix(m) + local function points(acc, w) +if not acc then + return nil + end + local a = (MeshOps.f32(acc) ) +if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + writef32(d, o, m[1] * x + m[5] * y + m[9] * z + m[13] * w) + writef32(d, o + 4, m[2] * x + m[6] * y + m[10] * z + m[14] * w) + writef32(d, o + 8, m[3] * x + m[7] * y + m[11] * z + m[15] * w) + end + return a + end + local function dirs(acc, mat, normalize, flipW) +if not acc then + return nil + end + local a = (MeshOps.f32(acc) ) +if a == acc then + a = Scene.accessor(buffer.create(buffer.len(acc.data)), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + local d, c = a.data, a.components + for i = 0, a.count - 1 do + local o = i * c * 4 + local x, y, z = readf32(d, o), readf32(d, o + 4), readf32(d, o + 8) + local nx = mat[1] * x + mat[4] * y + mat[7] * z + local ny = mat[2] * x + mat[5] * y + mat[8] * z + local nz = mat[3] * x + mat[6] * y + mat[9] * z + if normalize then + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + writef32(d, o, nx) + writef32(d, o + 4, ny) + writef32(d, o + 8, nz) + if flipW and c >= 4 then + writef32(d, o + 12, -readf32(d, o + 12)) + end + end + return a + end + local mirror = det3(m) < 0 + local m3 = { m[1], m[2], m[3], m[5], m[6], m[7], m[9], m[10], m[11] } + local attrs = prim.attributes + attrs.POSITION = (points(attrs.POSITION, 1) ) +attrs.NORMAL = dirs(attrs.NORMAL, nm, true, false) + attrs.TANGENT = dirs(attrs.TANGENT, m3, true, mirror) + if prim.targets then + for _, t in __iter(prim.targets) do + t.POSITION = points(t.POSITION, 0) + t.NORMAL = dirs(t.NORMAL, nm, false, false) + t.TANGENT = dirs(t.TANGENT, m3, false, false) + end + end + if mirror and (prim.mode == "triangles" or prim.mode == nil) then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + buffer.copy(nb, 0, ib, 0, n * 4) + for t = 0, math.floor(n / 3 )- 1 do + local o = t * 12 + local b = readu32(nb, o + 4) + writeu32(nb, o + 4, readu32(nb, o + 8)) + writeu32(nb, o + 8, b) + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + elseif mirror and prim.mode == "polygons" and prim.faces then + local ib, n = indexBuffer(prim) + local nb = buffer.create(n * 4) + local getf = Scene.reader(prim.faces) + local at = 0 + if getf then + for f = 0, prim.faces.count - 1 do + local k = getf(f, 0) + for a = 0, k - 1 do + if at + a < n then + writeu32(nb, (at + a) * 4, readu32(ib, (at + k - 1 - a) * 4)) + end + end + at =at+ k + end + end + prim.indices = Scene.accessor(nb, "u32", 1, n) + end + return prim, nil +end + +-- ------------------------------------------------------------------------------------------------ normals / tangents +-- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) | +-- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle +-- modes are triangulated first (the returned primitive is then a new one). +function MeshOps.computeNormals(prim, opts) +local p = prim + if (prim.mode or "triangles") ~= "triangles" then + local t, err = MeshOps.triangulate(prim) + if not t then + return nil, err + end + p = t + else + local err = checkPrim(prim) + if err then + return nil, err + end + end + if p.mode ~= "triangles" then + return p, nil -- lines / points: nothing to do + end + if opts and opts.flat then + p = MeshOps.unweld(p) + end + local pos = (MeshOps.f32(p.attributes.POSITION) ) +local pd = pos.data + local nv = pos.count + local ib, n = indexBuffer(p) + local acc = table.create(nv * 3, 0) + for t = 0, math.floor(n / 3 )- 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local e1x, e1y, e1z = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local e2x, e2y, e2z = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + -- the cross product is twice the area times the unit normal: area weighting for free + local nx, ny, nz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in __iter({ a, b, c }) do +do local __DARKLUA_VAR=v * 3 + 1 acc[__DARKLUA_VAR]=acc[__DARKLUA_VAR]+ nx +end do local __DARKLUA_VAR0=v * 3 + 2 acc[__DARKLUA_VAR0]=acc[__DARKLUA_VAR0]+ ny +end do local __DARKLUA_VAR1=v * 3 + 3 acc[__DARKLUA_VAR1]=acc[__DARKLUA_VAR1]+ nz +end end + end + local out = buffer.create(nv * 12) + for v = 0, nv - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + else + x, y, z = 0, 0, 1 + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + p.attributes.NORMAL = Scene.accessor(out, "f32", 3, nv) + return p, nil +end + +-- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) | +-- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_<opts.texCoord or 0>. +function MeshOps.computeTangents(prim, opts) +local p = prim + if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then + local q, err = MeshOps.computeNormals(prim) + if not q then + return nil, err + end + p = q + end + local err = checkPrim(p) + if err then + return nil, err + end + local uvAcc = p.attributes["TEXCOORD_" .. tostring(opts and opts.texCoord or 0)] + if not uvAcc then + return nil, Err.new(Err.ARG, "computeTangents needs texture coordinates") + end + local pos = (MeshOps.f32(p.attributes.POSITION) ) +local nrm = (MeshOps.f32(p.attributes.NORMAL ) ) +local uv = (MeshOps.f32(uvAcc) ) +local pd, nd, ud = pos.data, nrm.data, uv.data + local nv = pos.count + local ib, n = indexBuffer(p) + local tan = table.create(nv * 3, 0) + local bit = table.create(nv * 3, 0) + for t = 0, math.floor(n / 3 )- 1 do + local a, b, c = readu32(ib, t * 12), readu32(ib, t * 12 + 4), readu32(ib, t * 12 + 8) + local ax, ay, az = readf32(pd, a * 12), readf32(pd, a * 12 + 4), readf32(pd, a * 12 + 8) + local x1, y1, z1 = readf32(pd, b * 12) - ax, readf32(pd, b * 12 + 4) - ay, readf32(pd, b * 12 + 8) - az + local x2, y2, z2 = readf32(pd, c * 12) - ax, readf32(pd, c * 12 + 4) - ay, readf32(pd, c * 12 + 8) - az + local us, vs = readf32(ud, a * 8), readf32(ud, a * 8 + 4) + local s1, t1 = readf32(ud, b * 8) - us, readf32(ud, b * 8 + 4) - vs + local s2, t2 = readf32(ud, c * 8) - us, readf32(ud, c * 8 + 4) - vs + local den = s1 * t2 - s2 * t1 + if den ~= 0 then + local r = 1 / den + local tx, ty, tz = (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r + local bx, by, bz = (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r + for _, v in __iter({ a, b, c }) do +do local __DARKLUA_VAR=v * 3 + 1 tan[__DARKLUA_VAR]=tan[__DARKLUA_VAR]+ tx +end do local __DARKLUA_VAR0=v * 3 + 2 tan[__DARKLUA_VAR0]=tan[__DARKLUA_VAR0]+ ty +end do local __DARKLUA_VAR1=v * 3 + 3 tan[__DARKLUA_VAR1]=tan[__DARKLUA_VAR1]+ tz +end do local __DARKLUA_VAR2=v * 3 + 1 bit[__DARKLUA_VAR2]=bit[__DARKLUA_VAR2]+ bx +end do local __DARKLUA_VAR3=v * 3 + 2 bit[__DARKLUA_VAR3]=bit[__DARKLUA_VAR3]+ by +end do local __DARKLUA_VAR4=v * 3 + 3 bit[__DARKLUA_VAR4]=bit[__DARKLUA_VAR4]+ bz +end end + end + end + local out = buffer.create(nv * 16) + for v = 0, nv - 1 do + local nx, ny, nz = readf32(nd, v * 12), readf32(nd, v * 12 + 4), readf32(nd, v * 12 + 8) + local tx, ty, tz = tan[v * 3 + 1], tan[v * 3 + 2], tan[v * 3 + 3] + local dot = nx * tx + ny * ty + nz * tz + tx, ty, tz = tx - nx * dot, ty - ny * dot, tz - nz * dot + local l = math.sqrt(tx * tx + ty * ty + tz * tz) + if l > 1e-20 then + tx, ty, tz = tx / l, ty / l, tz / l + else + -- no UV gradient: any unit vector orthogonal to the normal + if math.abs(nx) < 0.9 then + tx, ty, tz = 0, nz, -ny + else + tx, ty, tz = -nz, 0, nx + end + local l2 = math.sqrt(tx * tx + ty * ty + tz * tz) + if l2 > 0 then + tx, ty, tz = tx / l2, ty / l2, tz / l2 + end + end + -- handedness: (n x t) . b + local cx, cy, cz = ny * tz - nz * ty, nz * tx - nx * tz, nx * ty - ny * tx + local w = cx * bit[v * 3 + 1] + cy * bit[v * 3 + 2] + cz * bit[v * 3 + 3] < 0 and-1 or 1 + writef32(out, v * 16, tx) + writef32(out, v * 16 + 4, ty) + writef32(out, v * 16 + 8, tz) + writef32(out, v * 16 + 12, w) + end + p.attributes.TANGENT = Scene.accessor(out, "f32", 4, nv) + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ weld / unweld +local function gather(acc, ib, n) +local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components + local out = buffer.create(n * size) + for i = 0, n - 1 do + buffer.copy(out, i * size, acc.data, readu32(ib, i * 4) * size, size) + end + local a = Scene.accessor(out, acc.type, acc.components, n) + a.matrix = acc.matrix + return a +end + +-- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals) +function MeshOps.unweld(prim) +local ib, n = indexBuffer(prim) + local attrs = {} + for name, a in __iter(prim.attributes) do + attrs[name] = gather(a, ib, n) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in __iter(prim.targets) do + local tt = {} + for name, a in __iter(t) do + tt[name] = gather(a, ib, n) + end + targets[k] = tt + end + end + return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras } +end + +-- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err. +-- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other +-- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex). +-- Morph targets are kept per merged vertex (the first one's). +function MeshOps.weld(prim, opts) +local err = checkPrim(prim) + if err then + return nil, err + end + local eps = opts and opts.epsilon or 0 + local posOnly = opts and opts.positionsOnly or false + local names = {} + for name in __iter(prim.attributes) do + if not (posOnly and name ~= "POSITION") and not (eps > 0 and name == "POSITION") then + table.insert(names, name) + end + end + table.sort(names) + local nv = vertexCount(prim) + local pos = (MeshOps.f32(prim.attributes.POSITION) ) +local pd = pos.data + local inv = (eps > 0 and((1 / eps ))or(0 +)) local remap = buffer.create(nv * 4) + local keep= {} + local seen= {} + local parts = table.create(#names + 1) + for v = 0, nv - 1 do + local np = 0 + if eps > 0 then + np =np+ 1 + parts[np] = string.format("%d,%d,%d", math.floor(readf32(pd, v * 12) * inv + 0.5), math.floor(readf32(pd, v * 12 + 4) * inv + 0.5), math.floor(readf32(pd, v * 12 + 8) * inv + 0.5)) + end + for _, name in __iter(names) do + local a = prim.attributes[name] + local size = (Types.COMPONENT_SIZE[a.type] or 4) * a.components + np =np+ 1 + parts[np] = buffer.readstring(a.data, v * size, size) + end + local key = table.concat(parts, "\1", 1, np) + local k = seen[key] + if k == nil then + k = #keep + seen[key] = k + table.insert(keep, v) + end + writeu32(remap, v * 4, k) + end + local kb = buffer.create(#keep * 4) + for i, v in __iter(keep) do + writeu32(kb, (i - 1) * 4, v) + end + local attrs = {} + for name, a in __iter(prim.attributes) do + attrs[name] = gather(a, kb, #keep) + end + local targets = nil + if prim.targets then + targets = {} + for k, t in __iter(prim.targets) do + local tt = {} + for name, a in __iter(t) do + tt[name] = gather(a, kb, #keep) + end + targets[k] = tt + end + end + local ib, n = indexBuffer(prim) + local out = buffer.create(n * 4) + for i = 0, n - 1 do + writeu32(out, i * 4, readu32(remap, readu32(ib, i * 4) * 4)) + end + return { + attributes = attrs, + indices = Scene.accessor(out, "u32", 1, n), + mode = prim.mode, + faces = prim.faces, + material = prim.material, + targets = targets, + extras = prim.extras, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ bounds +-- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and +-- voxel shape cell corners excluded) | nil, nil when there are no positions +function MeshOps.bounds(x) +local lo = { math.huge, math.huge, math.huge } + local hi = { -math.huge, -math.huge, -math.huge } + local function add(prim, m) + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + return + end + local get = Scene.reader(pos) + if not get then + return + end + for i = 0, pos.count - 1 do + local px, py, pz = get(i, 0), get(i, 1), get(i, 2) + if m and m ~= Scene.IDENTITY then + px, py, pz = m[1] * px + m[5] * py + m[9] * pz + m[13], m[2] * px + m[6] * py + m[10] * pz + m[14], m[3] * px + m[7] * py + m[11] * pz + m[15] + end + if px < lo[1] then + lo[1] = px + end + if py < lo[2] then + lo[2] = py + end + if pz < lo[3] then + lo[3] = pz + end + if px > hi[1] then + hi[1] = px + end + if py > hi[2] then + hi[2] = py + end + if pz > hi[3] then + hi[3] = pz + end + end + end + if type(x) ~= "table" then + return nil, nil + end + if x.kind == "scene" then + for _, pl in __iter(Scene.flatten(x)) do + add(pl.primitive, pl.matrix) + end + else + add(x, nil) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- ------------------------------------------------------------------------------------------------ merge +-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero) +local function defaultFor(name, k) +if string.sub(name, 1, 6) == "COLOR_" then + return 1 + end + if string.sub(name, 1, 8) == "WEIGHTS_" then + return k == 0 and 1 or 0 + end + return 0 +end + +-- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space | +-- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input +-- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too. +-- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets +-- are not applied (the rest pose). +function MeshOps.merge(input, opts) +local placed= {} + if type(input) ~= "table" then + return nil, Err.new(Err.ARG, "merge: expected a Scene or a list of Primitives") + end + if input.kind == "scene" then + placed = Scene.flatten(input) + else + for i, p in __iter(input) do + placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 } + end + end + -- triangulate + bake each + local groups= {} + local order= {} + local allPoints = #placed > 0 + for _, pl in __iter(placed) do + if pl.primitive.mode ~= "points" then + allPoints = false + end + end + for _, pl in __iter(placed) do + local p = pl.primitive + local mode = p.mode or "triangles" + if mode ~= "lines" and mode ~= "line_strip" and mode ~= "line_loop" and (mode ~= "points" or allPoints) then + local t, err = (mode == "points" and{p }or{(MeshOps.triangulate(p, opts) +)})[1] if not t then + return nil, err + end + -- a private copy of the attributes to bake + local copy= { attributes = {}, indices = t.indices, mode = t.mode, material = t.material } + for name, a in __iter(t.attributes) do + copy.attributes[name] = MeshOps.f32(a) + end + if pl.matrix ~= Scene.IDENTITY then + local ok, terr = MeshOps.transform(copy, pl.matrix) + if not ok then + return nil, terr + end + end + local key = (opts and opts.byMaterial and{(copy.material or 0) }or{0 +})[1] if not groups[key] then + groups[key] = {} + table.insert(order, key) + end + table.insert(groups[key], copy) + end + end + table.sort(order) + local function concat(list, material) +local names= {} + local nv, ni = 0, 0 + local points = false + for _, p in __iter(list) do + for name, a in __iter(p.attributes) do + names[name] = math.max(names[name] or 0, a.components) + end + nv =nv+ vertexCount(p) + local _, n = indexBuffer(p) + ni =ni+ n + points = points or p.mode == "points" + end + local attrs= {} + for name, comps in __iter(names) do + local out = buffer.create(nv * comps * 4) + local base = 0 + for _, p in __iter(list) do + local a = p.attributes[name] + local cnt = vertexCount(p) + for v = 0, cnt - 1 do + for k = 0, comps - 1 do + local value = (a and k < a.components and{(readf32(a.data, (v * a.components + k) * 4) )}or{(defaultFor(name, k) +)})[1] writef32(out, ((base + v) * comps + k) * 4, value) + end + end + base =base+ cnt + end + attrs[name] = Scene.accessor(out, "f32", comps, nv) + end + local idx = buffer.create(ni * 4) + local base, at = 0, 0 + for _, p in __iter(list) do + local ib, n = indexBuffer(p) + for i = 0, n - 1 do + writeu32(idx, (at + i) * 4, readu32(ib, i * 4) + base) + end + at =at+ n + base =base+ vertexCount(p) + end + return { + attributes = attrs, + indices = (points and{nil }or{(Scene.accessor(idx, "u32", 1, ni))})[1], + mode = points and"points" or"triangles", + material = material, + } + end + if opts and opts.byMaterial then + local out = {} + for _, key in __iter(order) do + table.insert(out, concat(groups[key], (key == 0 and{nil }or{key})[1])) + end + return out, nil + end + local all= groups[0] or {} + local first = all[1] + return concat(all, first and first.material), nil +end + +-- ------------------------------------------------------------------------------------------------ units / up axis +local function scaleAccessor(acc, f) +if not acc then + return nil + end + local a = (MeshOps.f32(acc) ) +if a == acc then + a = Scene.accessor(buffer.create(acc.count * acc.components * 4), "f32", acc.components, acc.count) + buffer.copy(a.data, 0, acc.data, 0, acc.count * acc.components * 4) + end + for i = 0, a.count * a.components - 1 do + writef32(a.data, i * 4, readf32(a.data, i * 4) * f) + end + return a +end + +-- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and +-- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by +-- factor (the same physical size in smaller units). +function MeshOps.scale(scene, f) +if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then + return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor") + end + local done= {} + for _, mesh in __iter(scene.meshes) do + for _, p in __iter(mesh.primitives) do + if not done[p] then + done[p] = true + p.attributes.POSITION = (scaleAccessor(p.attributes.POSITION, f) ) +for _, t in __iter(p.targets or {}) do + t.POSITION = scaleAccessor(t.POSITION, f) + end + end + end + end + for _, n in __iter(scene.nodes) do + if n.translation then + n.translation = { n.translation[1] * f, n.translation[2] * f, n.translation[3] * f } + end + if n.matrix then + local m = table.clone(n.matrix) + m[13], m[14], m[15] = m[13] * f, m[14] * f, m[15] * f + n.matrix = m + end + end + for _, a in __iter(scene.animations) do + for _, c in __iter(a.channels) do + if c.path == "translation" and not done[c.output] then + done[c.output] = true + c.output = (scaleAccessor(c.output, f) ) +end + end + end + for _, s in __iter(scene.skins) do + local ibm = s.inverseBindMatrices + if ibm and not done[ibm] then + local a = (MeshOps.f32(ibm) ) +if a == ibm then + a = Scene.accessor(buffer.create(ibm.count * 64), "f32", 16, ibm.count) + buffer.copy(a.data, 0, ibm.data, 0, ibm.count * 64) + end + for i = 0, a.count - 1 do + for k = 12, 14 do + writef32(a.data, (i * 16 + k) * 4, readf32(a.data, (i * 16 + k) * 4) * f) + end + end + a.matrix = true + s.inverseBindMatrices = a + done[a] = true + end + end + for _, c in __iter(scene.cameras) do + if c.type == "perspective" then + c.znear =c.znear* math.abs(f) + if c.zfar then + c.zfar =c.zfar* math.abs(f) + end + else + c.znear =c.znear* math.abs(f) + if c.zfar then + c.zfar =c.zfar* math.abs(f) + end + c.xmag = c.xmag and c.xmag * math.abs(f) + c.ymag = c.ymag and c.ymag * math.abs(f) + end + end + for _, l in __iter(scene.lights) do + if l.range then + l.range =l.range* math.abs(f) + end + end + scene.meta.unit = (scene.meta.unit or 1) / f + return scene, nil +end + +-- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m) +function MeshOps.setUnit(scene, metresPerUnit) +if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then + return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit") + end + local from = scene.meta.unit or 1 + return MeshOps.scale(scene, from / metresPerUnit) +end + +-- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up. +-- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it). +function MeshOps.setUp(scene, up) +if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then + return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"") + end + local from = scene.meta.up or "y" + if from == up then + return scene, nil + end + local h = math.sqrt(0.5) + -- z-up -> y-up: -90 degrees about x; y-up -> z-up: +90 degrees about x + local q = up == "y" and{ -h, 0, 0, h } or{ h, 0, 0, h } + table.insert(scene.nodes, { name = "up_" .. up, children = scene.roots, rotation = q }) + scene.roots = { #scene.nodes } + scene.meta.up = up +return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ voxels +local function linear(c) +local s = c / 255 + return (s <= 0.04045 and((s / 12.92 ))or((((s + 0.055) / 1.055) ^ 2.4 +)))end + +-- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION, +-- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err. +-- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx); +-- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or +-- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex). +function MeshOps.voxelsToPrimitive(v, opts) +if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected a Voxels grid") + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + if type(sx) ~= "number" or type(sy) ~= "number" or type(sz) ~= "number" or sx < 1 or sy < 1 or sz < 1 or buffer.len(v.data) < sx * sy * sz then + return nil, Err.new(Err.ARG, "bad voxel grid size") + end + local pivot = opts and opts.pivot or "center" + local scale = opts and opts.scale or 1 + local ox, oy, oz = 0, 0, 0 + if pivot == "center" then + ox, oy, oz = -(math.floor(sx / 2)), -(math.floor(sy / 2)), -(math.floor(sz / 2)) + end + local g = Greedy.run(v.data, sx, sy, sz, ox, oy, oz, scale) + local nv = g.vertices + local function trim(b, size) +local out = buffer.create(size) + buffer.copy(out, 0, b, 0, size) + return out + end + local attrs= { + POSITION = Scene.accessor(trim(g.positions, nv * 12), "f32", 3, nv), + NORMAL = Scene.accessor(trim(g.normals, nv * 12), "f32", 3, nv), + } + local pal = v.palette or {} + local srgb = opts and opts.colors == "srgb" + local col = buffer.create(nv * (srgb and 4 or 16)) + local lut= {} + for i = 1, 255 do + local c= pal[i] or { 255, 255, 255, 255 } + if srgb then + lut[i] = { c[1] or 0, c[2] or 0, c[3] or 0, c[4] or 255 } + else + lut[i] = { linear(c[1] or 0), linear(c[2] or 0), linear(c[3] or 0), (c[4] or 255) / 255 } + end + end + for k = 0, nv - 1 do + local c = lut[buffer.readu8(g.index, k)] or lut[1] + if srgb then + for j = 0, 3 do + buffer.writeu8(col, k * 4 + j, c[j + 1]) + end + else + for j = 0, 3 do + writef32(col, k * 16 + j * 4, c[j + 1]) + end + end + end + attrs.COLOR_0 = Scene.accessor(col, srgb and"unorm8" or"f32", 4, nv) + if opts and opts.indexAttribute then + attrs._PALETTE_INDEX = Scene.accessor(trim(g.index, nv), "u8", 1, nv) + end + return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil +end + +-- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node +-- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as +-- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids). +function MeshOps.meshVoxels(scene, opts) +if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local grids = scene.voxels or {} + local mat = 0 + local meshOf= {} + for i, v in __iter(grids) do + local prim, err = MeshOps.voxelsToPrimitive(v, opts) + if not prim then + return nil, err + end + if mat == 0 then + local m = Scene.material("voxels") + m.metallic = 0 + table.insert(scene.materials, m) + mat = #scene.materials + end + prim.material = mat + table.insert(scene.meshes, { name = v.name or ("voxels " .. i), primitives = { prim } }) + meshOf[i] = #scene.meshes + end + for _, n in __iter(scene.nodes) do + if n.voxels and meshOf[n.voxels] then + n.mesh = meshOf[n.voxels] + end + end + return scene, nil +end + +return MeshOps +end +__FILES["ops/MeshOps/Greedy"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +--!native +-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each +-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged +-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are +-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the +-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz. +local Greedy = {} + +local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32 +local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32 + +-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale + + + + + + + + + +function Greedy.run(data, sx, sy, sz, ox, oy, oz, scale) +local cap = 1024 + local pos = buffer.create(cap * 48) + local nrm = buffer.create(cap * 48) + local idx = buffer.create(cap * 4) + local tri = buffer.create(cap * 24) + local quads = 0 + local maxFace = math.max(sx * sy, sy * sz, sz * sx) + local mask = buffer.create(maxFace * 4) + local corner = { 0, 0, 0 } + for d = 0, 2 do + -- u, v: the two other axes, cyclic so that e_u x e_v = e_d + local u, v = (d + 1) % 3, (d + 2) % 3 + local nd = (d == 0 and{sx }or{(d == 1 and{sy }or{sz +})[1]})[1] local nu = (u == 0 and{sx }or{(u == 1 and{sy }or{sz +})[1]})[1] local nv = (v == 0 and{sx }or{(v == 1 and{sy }or{sz +})[1]})[1] local std = d == 0 and 1 or(d == 1 and{sx }or{(sx * sy +)})[1] local stu = u == 0 and 1 or(u == 1 and{sx }or{(sx * sy +)})[1] local stv = v == 0 and 1 or(v == 1 and{sx }or{(sx * sy +)})[1] for slice = -1, nd - 1 do + -- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d) + local any = false + for j = 0, nv - 1 do + for i = 0, nu - 1 do + local base = i * stu + j * stv + local a = (slice >= 0 and{(readu8(data, base + slice * std) )}or{0 +})[1] local b = (slice + 1 < nd and{(readu8(data, base + (slice + 1) * std) )}or{0 +})[1] local m = 0 + if a ~= 0 and b == 0 then + m = a + elseif a == 0 and b ~= 0 then + m = -b + end + if m ~= 0 then + any = true + end + writei32(mask, (i + j * nu) * 4, m) + end + end + if any then + for j = 0, nv - 1 do + local i = 0 + while i < nu do + local m = readi32(mask, (i + j * nu) * 4) + if m == 0 then + i =i+ 1 + else + local w = 1 + while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do + w =w+ 1 + end + local h = 1 + local grow = true + while j + h < nv and grow do + for k = 0, w - 1 do + if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then + grow = false + break + end + end + if grow then + h =h+ 1 + end + end + for jj = j, j + h - 1 do + for k = 0, w - 1 do + writei32(mask, (i + k + jj * nu) * 4, 0) + end + end + -- emit the rectangle + if quads == cap then + local ncap = cap * 2 + local function grow2(b, per) +local nb = buffer.create(ncap * per) + buffer.copy(nb, 0, b, 0, cap * per) + return nb + end + pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), (grow2(tri, 24) ) +cap = ncap + end + corner[d + 1] = slice + 1 + corner[u + 1] = i + corner[v + 1] = j + local cx, cy, cz = corner[1], corner[2], corner[3] + -- the u and v edge vectors + local ux = (u == 0 and{w }or{0 +})[1] local uy = (u == 1 and{w }or{0 +})[1] local uz = (u == 2 and{w }or{0 +})[1] local vx = (v == 0 and{h }or{0 +})[1] local vy = (v == 1 and{h }or{0 +})[1] local vz = (v == 2 and{h }or{0 +})[1] local nsign = m > 0 and 1 or-1 + local nx = (d == 0 and{nsign }or{0 +})[1] local ny = (d == 1 and{nsign }or{0 +})[1] local nz = (d == 2 and{nsign }or{0 +})[1] local col = (m > 0 and{m }or{(-m +)})[1] local vb = quads * 48 + local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale + writef32(pos, vb, px0) + writef32(pos, vb + 4, py0) + writef32(pos, vb + 8, pz0) + writef32(pos, vb + 12, px0 + ux * scale) + writef32(pos, vb + 16, py0 + uy * scale) + writef32(pos, vb + 20, pz0 + uz * scale) + writef32(pos, vb + 24, px0 + (ux + vx) * scale) + writef32(pos, vb + 28, py0 + (uy + vy) * scale) + writef32(pos, vb + 32, pz0 + (uz + vz) * scale) + writef32(pos, vb + 36, px0 + vx * scale) + writef32(pos, vb + 40, py0 + vy * scale) + writef32(pos, vb + 44, pz0 + vz * scale) + for k = 0, 3 do + writef32(nrm, vb + k * 12, nx) + writef32(nrm, vb + k * 12 + 4, ny) + writef32(nrm, vb + k * 12 + 8, nz) + writeu8(idx, quads * 4 + k, col) + end + local v0 = quads * 4 + local ib = quads * 24 + if m > 0 then + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 1) + writeu32(tri, ib + 8, v0 + 2) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 2) + writeu32(tri, ib + 20, v0 + 3) + else + writeu32(tri, ib, v0) + writeu32(tri, ib + 4, v0 + 2) + writeu32(tri, ib + 8, v0 + 1) + writeu32(tri, ib + 12, v0) + writeu32(tri, ib + 16, v0 + 3) + writeu32(tri, ib + 20, v0 + 2) + end + quads =quads+ 1 + i =i+ w + end + end + end + end + end + end + return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads } +end + +return Greedy +end +__FILES["ops/MusicOps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- ops/MusicOps: building and editing tracker Modules (layer 5.5, over codecs/audio/Tracker) without touching the +-- engine's internal layout (5-byte cells, f32 sample buffers, tuning fields): a new module, patterns, cells by name, +-- samples from an Audio, instruments. New code. F.music.new / addPattern / setCell / getCell / addSample / +-- addInstrument / note in the api (also F.ops.music). +-- +-- local M = require("rosetta.ops.MusicOps") +-- local song = M.new({ format = "mod", channels = 4, title = "demo" }) +-- local s = M.addSample(song, { name = "beep", audio = someAudio, loop = "forward" }) -- sample 1 +-- local p = M.addPattern(song) -- pattern 0 (64 rows), appended to the order list +-- M.setCell(song, p, 0, 1, { note = "C-4", instrument = s, effect = 0xC, param = 40 }) +-- local wav = F.save(song, nil, { format = "wav" }) -- rendered; or F.save(song) for the .mod +-- +-- Conventions: pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, sample +-- and instrument numbers 1-based (0 = none in a cell). Notes are numbers (1 = C-0, 49 = C-4, 61 = C-5; 254 cut, 255 +-- key off, 253 fade) or names: "C-4", "C#4", "Db4", "off", "cut", "fade". Effects keep the format's own numbering +-- (MOD / XM 0..35, S3M / IT 1..26 = A..Z). Never throws: bad arguments return nil, Err.ARG. +local Err = __include("core/Err") +local Tracker = __include("codecs/audio/Tracker") + +local MusicOps = {} + +local FORMATS = { mod = true, xm = true, s3m = true, it = true } + +local function bad(what) +return nil, Err.new(Err.ARG, what) +end + +local function isModule(m) -- (the engine family: modules of the other tracker formats, music/mtm etc., play as one of the four) + +return type(m) == "table" and m.kind == "music" and FORMATS[Tracker.family(m) or ""] == true and type(m.patterns) == "table" +end + +local function int(v, lo, hi) +return type(v) == "number" and v == v and v % 1 == 0 and v >= lo and v <= hi +end +-- ------------------------------------------------------------------------------------------------ module +-- new(opts?) -> an empty Module (kind "music") with a render method; meta.source.format = the format + + + + + + + + + +function MusicOps.new(opts) +local o= opts or {} + local format = o.format or "mod" + if not FORMATS[format] then + return bad("new: format must be mod, xm, s3m or it") + end + local channels = o.channels or 4 + if not int(channels, 1, format == "mod" and 32 or 64) then + return bad("new: bad channel count") + end + local m = Tracker.newModule(format, channels) + m.title = (type(o.title) == "string" and{o.title }or{"" +})[1] if o.speed ~= nil then + if not int(o.speed, 1, 255) then + return bad("new: speed must be 1..255") + end + m.speed = o.speed + end + if o.tempo ~= nil then + if type(o.tempo) ~= "number" or o.tempo < 32 or o.tempo > 1000 then + return bad("new: tempo must be 32..1000") + end + m.tempo = o.tempo + end + m.meta = { source = { format = format } } + return m, nil +end + +-- ------------------------------------------------------------------------------------------------ patterns +-- addPattern(module, rows?, opts?) -> the new pattern's number (0-based) | nil, Err. rows default 64 (MOD needs 64). +-- The pattern is appended to the order list unless opts.order == false. +function MusicOps.addPattern(m, rows, opts) +if not isModule(m) then + return bad("addPattern: needs a tracker Module") + end + local n = rows or 64 + if not int(n, 1, 1024) then + return bad("addPattern: rows must be 1..1024") + end + table.insert(m.patterns, Tracker.newPattern(n, m.channels)) + local index = #m.patterns - 1 + if not (opts and opts.order == false) then + table.insert(m.order, index) + end + return index, nil +end + +local NAMES= { c = 0, d = 2, e = 4, f = 5, g = 7, a = 9, b = 11 } +local SPECIAL= { off = 255, ["==="] = 255, cut = 254, ["^^^"] = 254, fade = 253, ["~~~"] = 253 } + +-- note(nameOrNumber) -> the note number (1 = C-0 .. 120 = B-9, 253 / 254 / 255) | nil, Err: "C-4" = 49, "C#4" = 50, +-- "Db4" = 50, "off", "cut", "fade" +function MusicOps.note(v) +if type(v) == "number" then + if int(v, 0, 120) or v == 253 or v == 254 or v == 255 then + return v, nil + end + return bad("note: number must be 0..120 or 253..255") + end + if type(v) ~= "string" then + return bad("note: expected a number or a name") + end + local s = string.lower(v) + if SPECIAL[s] then + return SPECIAL[s], nil + end + local letter, acc, oct = string.match(s, "^([a-g])([#b%-]?)(%d)$") + if not letter then + return bad("note: bad name " .. v) + end + local n = NAMES[letter ] + (acc == "#" and 1 or(acc == "b" and-1 or 0)) + local num = 1 + ((tonumber(oct) )) * 12 + n + if num < 1 or num > 120 then + return bad("note: out of range " .. v) + end + return num, nil +end + + + + + + + + + +local function patternAt(m, pattern, row, channel) +if not isModule(m) then + return bad("needs a tracker Module") + end + local p= (int(pattern, 0, 1e6) and{m.patterns[pattern + 1] }or{nil +})[1] if p == nil then + return bad("no pattern " .. tostring(pattern)) + end + if not int(row, 0, p.rows - 1) then + return bad("row " .. tostring(row) .. " outside 0.." .. (p.rows - 1)) + end + if not int(channel, 1, m.channels) then + return bad("channel " .. tostring(channel) .. " outside 1.." .. m.channels) + end + return p, nil +end + +-- setCell(module, pattern, row, channel, cell) -> true | nil, Err: writes one cell (missing fields = 0) +function MusicOps.setCell(m, pattern, row, channel, cell) +local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + if type(cell) ~= "table" then + return bad("setCell: cell must be a table") + end + local note = 0 + if cell.note ~= nil then + local n, nerr = MusicOps.note(cell.note) + if not n then + return nil, nerr + end + note = n + end + for _, k in __iter({ "instrument", "volume", "effect", "param" }) do + local v = (cell )[k] + if v ~= nil and not int(v, 0, 255) then + return bad("setCell: " .. k .. " must be 0..255") + end + end + Tracker.setCell(m, pattern, row, channel, note, cell.instrument or 0, cell.volume or 0, cell.effect or 0, cell.param or 0) + return true, nil +end + +-- getCell(module, pattern, row, channel) -> { note, instrument, volume, effect, param } (numbers) | nil, Err +function MusicOps.getCell(m, pattern, row, channel) +local p, err = patternAt(m, pattern, row, channel) + if not p then + return nil, err + end + local note, ins, vol, fx, param = Tracker.cell(m, pattern, row, channel) + return { note = note, instrument = ins, volume = vol, effect = fx, param = param }, nil +end +-- ------------------------------------------------------------------------------------------------ samples + + + + + + + + + + + + + + + + +local LOOPS= { none = 0, forward = 1, pingpong = 2 } + +-- addSample(module, spec) -> the new sample's number (1-based) | nil, Err. The rate sets the tuning: c5speed for +-- S3M / IT, relativeNote + finetune (1/128 semitones from 8363 Hz) for MOD / XM (MOD files store only the finetune, +-- -1..+7/8 semitone: use rates near 8363 Hz when saving a MOD). +function MusicOps.addSample(m, spec) +if not isModule(m) then + return bad("addSample: needs a tracker Module") + end + if type(spec) ~= "table" then + return bad("addSample: spec must be a table") + end + local data, length, channels +local rate = spec.rate + local a = spec.audio + if a ~= nil then + if type(a) ~= "table" or a.kind ~= "audio" or type(a.samples) ~= "buffer" or not int(a.frames, 0, 2 ^ 31) or (a.channels ~= 1 and a.channels ~= 2) or buffer.len(a.samples) < a.frames * a.channels * 4 then + return bad("addSample: audio must be a mono or stereo Audio") + end + data, length, channels = a.samples, a.frames, a.channels + rate = rate or a.sampleRate + elseif type(spec.data) == "buffer" then + channels = spec.channels or 1 + if channels ~= 1 and channels ~= 2 then + return bad("addSample: channels must be 1 or 2") + end + local d= spec.data + length = spec.length or math.floor(buffer.len(d) / (4 * channels) +) if not int(length, 0, 2 ^ 31) or buffer.len(d) < length * channels * 4 then + return bad("addSample: data shorter than length") + end + data = d + else + return bad("addSample: needs audio or data") + end + rate = rate or 8363 + if type(rate) ~= "number" or rate < 1 or rate > 1e7 then + return bad("addSample: bad rate") + end + local s = Tracker.newSample(spec.name) + local copy = buffer.create(length * channels * 4) + buffer.copy(copy, 0, data, 0, length * channels * 4) + s.data, s.length, s.channels = copy, length, channels + s.bits = spec.bits or (Tracker.family(m) == "mod" and 8 or 16) + if s.bits ~= 8 and s.bits ~= 16 then + return bad("addSample: bits must be 8 or 16") + end + s.c5speed = rate + local semis = 12 * math.log(rate / 8363) / math.log(2) + local rn = math.floor(semis + 0.5) + if rn < -96 or rn > 95 then + return bad("addSample: rate out of range") + end + s.relativeNote = rn + s.finetune = math.clamp(math.floor((semis - rn) * 128 + 0.5), -128, 127) + local lt = LOOPS[spec.loop or "none"] + if lt == nil then + return bad("addSample: loop must be none, forward or pingpong") + end + if lt > 0 then + local ls, le = spec.loopStart or 0, spec.loopEnd or length + if not int(ls, 0, length) or not int(le, 0, length) or le - ls < 1 then + return bad("addSample: bad loop") + end + s.loopStart, s.loopEnd, s.loopType = ls, le, lt + end + if spec.volume ~= nil then + if type(spec.volume) ~= "number" or spec.volume < 0 or spec.volume > 64 then + return bad("addSample: volume must be 0..64") + end + s.volume = spec.volume + end + if spec.pan ~= nil then + if type(spec.pan) ~= "number" or spec.pan < 0 or spec.pan > 256 then + return bad("addSample: pan must be 0..256") + end + s.pan = spec.pan + end + table.insert(m.samples, s) + return #m.samples, nil +end +-- ------------------------------------------------------------------------------------------------ instruments +-- addInstrument(module, spec) -> the new instrument's number (1-based) | nil, Err. XM and IT modules only (MOD / +-- S3M cells name samples directly). + + + + + + + + + + +function MusicOps.addInstrument(m, spec) +if not isModule(m) then + return bad("addInstrument: needs a tracker Module") + end + if Tracker.family(m) ~= "xm" and Tracker.family(m) ~= "it" then + return bad("addInstrument: only xm and it modules have instruments (mod / s3m cells name samples)") + end + if type(spec) ~= "table" then + return bad("addInstrument: spec must be a table") + end + local ins = Tracker.newInstrument(spec.name) + if spec.sample ~= nil then + if not int(spec.sample, 1, #m.samples) then + return bad("addInstrument: no sample " .. tostring(spec.sample)) + end + for n = 1, 120 do + ins.sampleMap[n] = spec.sample + end + elseif type(spec.samples) == "table" then + for note, smp in __iter(spec.samples) do + if not int(note, 1, 120) or not int(smp, 0, #m.samples) then + return bad("addInstrument: bad keymap entry") + end + ins.sampleMap[note] = smp + end + end + if spec.fadeout ~= nil then + if not int(spec.fadeout, 0, 65535) then + return bad("addInstrument: bad fadeout") + end + ins.fadeout = spec.fadeout + end + local e = spec.envelope + if e ~= nil then + if type(e) ~= "table" or type(e.points) ~= "table" or #e.points == 0 then + return bad("addInstrument: envelope needs points") + end + local env = Tracker.newEnvelope() + local last = -1 + for i, pt in __iter(e.points) do + local tick, value= nil, nil + if type(pt) == "table" then + tick, value = pt[1], pt[2] + end + if not int(tick, 0, 65535) or type(value) ~= "number" or value < 0 or value > 64 or (tick ) <= last then + return bad("addInstrument: envelope point " .. i .. " must be { tick, 0..64 } with increasing ticks") + end + last = tick +env.ticks[i], env.values[i] = tick, value + end + env.enabled = true + local n = #e.points + if e.sustain ~= nil then + if not int(e.sustain, 1, n) then + return bad("addInstrument: bad sustain point") + end + env.sustain, env.susStart, env.susEnd = true, e.sustain, e.sustain + end + if e.loopStart ~= nil or e.loopEnd ~= nil then + local ls, le = e.loopStart or 1, e.loopEnd or n + if not int(ls, 1, n) or not int(le, ls, n) then + return bad("addInstrument: bad envelope loop") + end + env.loop, env.loopStart, env.loopEnd = true, ls, le + end + ins.volEnv = env + end + table.insert(m.instruments, ins) + return #m.instruments, nil +end + +return MusicOps +end +__FILES["playlist/m3u"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- playlist/m3u: M3U / M3U8 and HLS (RFC 8216) playlists. Absorbed from playlist-luau 3fc7fd3 (same author, no +-- third-party code). Decode: #EXTM3U / #EXTINF (durations, titles with attributes and commas), #PLAYLIST, plain +-- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / +-- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media +-- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, +-- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, +-- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. +-- +-- local pl = M3u.decode(Bytes.reader(buf), { baseUrl = "https://example.com/music/list.m3u" }) +-- for _, e in pl.entries do print(e.url, e.title, e.duration, e.playable) end -- pl.format: "m3u" | "hls" +-- local out = M3u.encode(pl, { title = "My Mix" }) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local M3u = { + name = "m3u", + category = "playlist", + extensions = { "m3u", "m3u8" }, + mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true, hls = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local UNSUPPORTED_SEGMENTS = { ts = true, aac = true, m4s = true, mp4 = true, m4a = true, fmp4 = true, cmfa = true } + +-- The extension of a URL's path (lower case), or nil +local function extension(url) +local p = Url.split(url).path + local ext = string.match(p, "%.([%w]+)$") + return (ext and{(string.lower(ext) )}or{nil +})[1]end + +local function duration(s) +local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- RFC 8216 attribute list: KEY=value pairs, quoted strings may hold commas +local function attributes(s) +local out = {} + local i, n = 1, #s + while i <= n do + local key, eq = string.match(s, "^%s*([%w%-_]+)%s*()=", i) + if not key then + break + end + i = (eq ) + 1 + local value + if string.sub(s, i, i) == '"' then + local j = string.find(s, '"', i + 1, true) or (n + 1) + value = string.sub(s, i + 1, j - 1) + i = j + 1 + else + local j = string.find(s, ",", i, true) or (n + 1) + value = Text.trim(string.sub(s, i, j - 1)) + i = j + end + out[string.upper(key)] = value + local c = string.find(s, ",", i, true) + if not c then + break + end + i = c + 1 + end + return out +end + +-- #EXTINF:<duration>[ attr="v" ...],<title> +local function extinf(rest) -- the first comma outside quoted attribute values + +local comma, quoted = nil, false + for i = 1, #rest do + local c = string.byte(rest, i) + if c == 34 then + quoted = not quoted + elseif c == 44 and not quoted then + comma = i + break + end + end + local head = (comma and{(string.sub(rest, 1, comma - 1) )}or{rest +})[1] local title = (comma and{(Text.trim(string.sub(rest, comma + 1)) )}or{nil +})[1] local d = string.match(head, "^%s*([%-%+]?[%d%.]+)") + return duration(d), (title and title ~= "" and{title }or{nil +})[1]end + + +-- ------------------------------------------------------------------------------------------------ sniff +function M3u.sniff(r) +local s = Sniff.text(r, 512) + s = ((string.match(s, "^%s*(.*)$") )) + if string.sub(s, 1, 7) == "#EXTM3U" then + return 0.95 + end + if string.find(s, "^#EXTINF:") or string.find(s, "^#EXT%-X%-") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parseM3u(ls, base, baseScheme, warnings) +local res= { kind = "playlist", format = "m3u", entries = {}, warnings = warnings, meta = {} } + local pendingDur, pendingTitle = nil, nil + for n, line in __iter(ls) do +local __DARKLUA_CONTINUE_3=false repeat local l = Text.trim(line) + if l == "" then +__DARKLUA_CONTINUE_3=true break + end + if string.sub(l, 1, 1) == "#" then + local upper = string.upper(string.sub(l, 1, 10)) + if string.sub(upper, 1, 8) == "#EXTINF:" then + pendingDur, pendingTitle = extinf(string.sub(l, 9)) + elseif string.sub(upper, 1, 10) == "#PLAYLIST:" then + res.title = Text.trim(string.sub(l, 11)) + end +__DARKLUA_CONTINUE_3=true -- #EXTM3U, #EXTGRP, #EXTALB, ... and plain comments: ignored + break + end + local e= Url.locate(l, base, baseScheme) + e.title = pendingTitle + e.duration = pendingDur + pendingDur, pendingTitle = nil, nil + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end +__DARKLUA_CONTINUE_3=true until true if not __DARKLUA_CONTINUE_3 then break end end + return res +end + +local function parseHls(ls, base, baseScheme, warnings) +local hls= { master = false, endList = false, encrypted = false } + local res= { kind = "playlist", format = "hls", entries = {}, warnings = warnings, hls = hls, meta = {} } + local pendingDur, pendingTitle, pendingRange = nil, nil, nil + local pendingStream= nil + local lastRangeEnd= nil + local total = 0 + local formats = {} + local fmp4 = false + for n, line in __iter(ls) do +local __DARKLUA_CONTINUE_4=false repeat local l = Text.trim(line) + if l == "" then +__DARKLUA_CONTINUE_4=true break + end + if string.sub(l, 1, 1) == "#" then + local tag, rest = string.match(l, "^(#[%w%-]+):?(.*)$") + tag = (tag and{(string.upper(tag) )}or{nil +})[1] if tag == "#EXT-X-STREAM-INF" then + hls.master = true + pendingStream = attributes(rest ) + elseif tag == "#EXT-X-MEDIA" then + hls.master = true + local a = attributes(rest ) + if a.URI then + local e= Url.locate(a.URI, base, baseScheme) + e.title = a.NAME + e.attributes = a + e.codecs = a.CODECS + table.insert(res.entries, e) + end + elseif tag == "#EXT-X-TARGETDURATION" then + hls.targetDuration = tonumber(Text.trim(rest )) + elseif tag == "#EXT-X-MEDIA-SEQUENCE" then + hls.mediaSequence = tonumber(Text.trim(rest )) + elseif tag == "#EXT-X-ENDLIST" then + hls.endList = true + elseif tag == "#EXT-X-KEY" then + local a = attributes(rest ) + if a.METHOD and string.upper(a.METHOD) ~= "NONE" then + if not hls.encrypted then + table.insert(warnings, ("line %d: encrypted segments (METHOD=%s) are not supported"):format(n, a.METHOD)) + end + hls.encrypted = true + end + elseif tag == "#EXT-X-MAP" then + fmp4 = true + elseif tag == "#EXTINF" then + pendingDur, pendingTitle = extinf(rest ) + elseif tag == "#EXT-X-BYTERANGE" then + local len, off = string.match(rest , "^%s*(%d+)@?(%d*)") + if len then + local o = tonumber(off) or lastRangeEnd + pendingRange = { length = (tonumber(len) ), offset = o } + lastRangeEnd = (o or 0) + ((tonumber(len) )) + end + end +__DARKLUA_CONTINUE_4=true break + end + local e= Url.locate(l, base, baseScheme) + if pendingStream then + e.attributes = pendingStream + e.bandwidth = tonumber(pendingStream.BANDWIDTH) + e.codecs = pendingStream.CODECS + e.title = pendingStream.NAME + pendingStream = nil + else + e.title = pendingTitle + e.duration = pendingDur + e.byteRange = pendingRange + if pendingDur then + total =total+ pendingDur + end + local ext = extension(e.url) or "?" + formats[ext] = true + if e.playable and (UNSUPPORTED_SEGMENTS[ext] or fmp4) then + e.playable = false + e.reason = "segment format " .. (fmp4 and"fmp4" or ext) + end + if e.playable and hls.encrypted then + e.playable = false + e.reason = "encrypted" + end + end + pendingDur, pendingTitle, pendingRange = nil, nil, nil + table.insert(res.entries, e) + if e.reason == "relative path without a base URL" or (e.reason and string.sub(e.reason, 1, 7) == "scheme ") then + table.insert(warnings, ("line %d: %s: %s"):format(n, e.reason, e.url)) + end +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end + if not hls.master then + hls.totalDuration = total + local list = {} + for ext in __iter(formats) do + table.insert(list, ext) + end + table.sort(list) + hls.segmentFormat = (#list == 1 and{list[1] }or{(#list == 0 and{nil }or{"mixed" +})[1]})[1] local bad = {} + for _, ext in __iter(list) do + if UNSUPPORTED_SEGMENTS[ext] then + table.insert(bad, "." .. ext) + end + end + if fmp4 then + table.insert(bad, "fMP4 (EXT-X-MAP)") + end + if #bad > 0 then + table.insert(warnings, "HLS segments are " .. table.concat(bad, ", ") + .. ": only mp3 segments can be played (concatenated)") + end + if not hls.endList then + table.insert(warnings, "live HLS playlist (no EXT-X-ENDLIST): it has to be reloaded for new segments") + end + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function M3u.decode(r, opts) +local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local ls = Text.lines(t) + local res = (string.find(t, "#EXT%-X%-") and{(parseHls(ls, base, baseScheme, warnings) )}or{(parseM3u(ls, base, baseScheme, warnings) +)})[1] local nLocal = 0 + for _, e in __iter(res.entries) do + if e.reason == "local path" then + nLocal =nLocal+ 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, nLocal == 1 and"" or"s")) + end + res.meta.source = { format = "m3u", hls = res.format == "hls" } + return res , nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- Writes entries as M3U8 (UTF-8, #EXTM3U, #EXTINF:<seconds>,<title>). Durations are rounded; unknown = -1. +-- opts.title adds #PLAYLIST:. Line breaks inside titles and URLs become spaces. +local function serialize(entries, opts) +local out = { "#EXTM3U" } + local function clean(s) +return (string.gsub(s, "[\r\n]+", " ")) + end + if opts and opts.title then + table.insert(out, "#PLAYLIST:" .. clean(opts.title)) + end + for _, e in __iter(entries or {}) do +local __DARKLUA_CONTINUE_8=false repeat if type(e) ~= "table" or type(e.url) ~= "string" then +__DARKLUA_CONTINUE_8=true break + end + local d = tonumber(e.duration) + local secs = (d and d >= 0 and d == d and d ~= math.huge and{(math.floor(d + 0.5) )}or{(-1 +)})[1] if e.title or d then + table.insert(out, ("#EXTINF:%d,%s"):format(secs, clean(tostring(e.title or "")))) + end + table.insert(out, clean(e.url)) +__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end + return table.concat(out, "\n") .. "\n" +end + +-- encode(playlist, opts?) -> buffer | nil, Err: M3U8 text. playlist: a Types.Playlist (any format's) or a list of +-- entries ({ url, title?, duration? }) +function M3u.encode(value, opts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = (type(value.entries) == "table" and{value.entries }or{value +})[1] local title = (opts and opts.title and{opts.title }or{value.title +})[1] return buffer.fromstring(serialize(entries, { title = (type(title) == "string" and{title }or{nil })[1]})), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +M3u.Url = Url + +return M3u +end +__FILES["playlist/pls"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from +-- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case +-- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / +-- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. +-- +-- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) +-- local out = Pls.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Text = __include("codecs/text/Text") + +-- ------------------------------------------------------------------------------------------------ contract +local Pls = { + name = "pls", + category = "playlist", + extensions = { "pls" }, + mime = { "audio/x-scpls", "audio/scpls" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" }, + caps = { decode = true, encode = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function duration(s) +local d = tonumber(s and Text.trim(s)) + if not d or d < 0 or d ~= d or d == math.huge then + return nil + end + return d +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Pls.sniff(r) +local s = Sniff.text(r, 64) + local first = string.match(s, "^%s*([^\r\n]*)") + return first and string.lower(Text.trim(first)) == "[playlist]" and 0.95 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function parsePls(ls, base, baseScheme, warnings) +local res= { kind = "playlist", format = "pls", entries = {}, warnings = warnings, meta = {} } + local files, titles, lengths= {}, {}, {} + local declared = nil + for _, line in __iter(ls) do +local __DARKLUA_CONTINUE_1=false repeat local l = Text.trim(line) + if l == "" or string.sub(l, 1, 1) == ";" or string.sub(l, 1, 1) == "#" or string.sub(l, 1, 1) == "[" then +__DARKLUA_CONTINUE_1=true break + end + local key, value = string.match(l, "^([^=]-)%s*=%s*(.*)$") + if not key then +__DARKLUA_CONTINUE_1=true break + end + local k = string.lower(Text.trim(key )) + local name, idx = string.match(k, "^(%a+)(%d+)$") + local i = tonumber(idx) + if name == "file" and i then + files[i] = value + elseif name == "title" and i then + titles[i] = value + elseif name == "length" and i then + lengths[i] = value + elseif k == "numberofentries" then + declared = tonumber(value) + end +__DARKLUA_CONTINUE_1=true until true if not __DARKLUA_CONTINUE_1 then break end end + local order = {} + for i in __iter(files) do + table.insert(order, i) + end + table.sort(order) + for _, i in __iter(order) do + local e= Url.locate(files[i], base, baseScheme) + local t = titles[i] and Text.trim(titles[i]) + e.title = (t and t ~= "" and{t }or{nil +})[1] e.duration = duration(lengths[i]) + table.insert(res.entries, e) + if e.reason and e.reason ~= "local path" then + table.insert(warnings, ("File%d: %s: %s"):format(i, e.reason, e.url)) + end + end + if declared and declared ~= #order then + table.insert(warnings, ("NumberOfEntries=%d but %d files"):format(declared, #order)) + end + return res +end + +-- decode(r, opts?) -> Types.Playlist | nil, Err. Bad lines become warnings (pl.warnings), never errors. +function Pls.decode(r, opts) +local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local warnings = {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local t = Text.toUtf8(r:string(n), warnings) + local res = parsePls(Text.lines(t), base, baseScheme, warnings) + local nLocal = 0 + for _, e in __iter(res.entries) do + if e.reason == "local path" then + nLocal =nLocal+ 1 + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, nLocal == 1 and"" or"s")) + end + res.meta.source = { format = "pls" } + return res , nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: PLS text (Version=2). playlist: a Types.Playlist (any format's) or a +-- list of entries ({ url, title?, duration? }). Line breaks inside titles and URLs become spaces. +function Pls.encode(value, _opts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = (type(value.entries) == "table" and{value.entries }or{value +})[1] local function clean(s) +return (string.gsub(s, "[\r\n]+", " ")) + end + local out = { "[playlist]" } + local n = 0 + for _, e in __iter(entries) do + if type(e) == "table" and type(e.url) == "string" then + n =n+ 1 + table.insert(out, string.format("File%d=%s", n, clean(e.url))) + if type(e.title) == "string" then + table.insert(out, string.format("Title%d=%s", n, clean(e.title))) + end + local d = tonumber(e.duration) + local secs = (d and d >= 0 and d == d and d ~= math.huge and{(math.floor(d + 0.5) )}or{(-1 +)})[1] table.insert(out, string.format("Length%d=%d", n, secs)) + end + end + table.insert(out, "NumberOfEntries=" .. n) + table.insert(out, "Version=2") + return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil +end + +return Pls +end +__FILES["playlist/xspf"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in rosetta (playlist-luau +-- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, +-- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, +-- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other +-- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. +-- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. +-- +-- local pl = Xspf.decode(Bytes.reader(buf), { baseUrl = "https://example.com/list.xspf" }) +-- for _, e in pl.entries do print(e.url, e.title, e.creator, e.duration) end +-- local out = Xspf.encode(pl) + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Url = __include("codecs/text/Url") +local Xml = __include("codecs/text/Xml") + +-- ------------------------------------------------------------------------------------------------ contract +local Xspf = { + name = "xspf", + category = "playlist", + extensions = { "xspf" }, + mime = { "application/xspf+xml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" }, + caps = { decode = true, encode = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + +local NS = "http://xspf.org/ns/0/" +local PLAYLIST_FIELDS = { "title", "creator", "annotation", "info", "location", "identifier", "image", "date", "license" } +local TRACK_FIELDS = { "title", "creator", "album", "annotation", "info", "image" } + +local function trim(s) +return ((string.match(s, "^%s*(.-)%s*$") )) +end + +-- the text of the first child element with this local name, trimmed (nil when missing or empty) +local function field(node, name) +for _, c in __iter(node.children) do + if type(c) == "table" and Xml.localName(c.name) == name then + local s = trim(Xml.text(c)) + return (s ~= "" and{s }or{nil +})[1] end + end + return nil +end + +local function elements(node, name) +local out = {} + for _, c in __iter(node.children) do + if type(c) == "table" and Xml.localName(c.name) == name then + table.insert(out, c) + end + end + return out +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Xspf.sniff(r) +local s = r:peek(1024) + local i = string.find(s, "<%w*:?playlist[%s>]") + if i and string.find(s, NS, 1, true) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> Types.Playlist | nil, Err (malformed XML or a root that is not <playlist> is an error; odd +-- tracks become warnings) +function Xspf.decode(r, opts) +local n = r.limit - r.pos + if n > (opts and opts.maxBytes or 2 ^ 26) then + return nil, Err.new(Err.LIMIT, "playlist over the size limit") + end + local doc, err = Xml.decode(r:string(n)) + if not doc then + return nil, err + end + local root = (doc ).root + if not root or Xml.localName(root.name) ~= "playlist" then + return nil, Err.new(Err.CORRUPT, "the root element is not <playlist>") + end + local warnings= {} + local base, baseScheme = Url.base(opts and opts.baseUrl, warnings) + local function withXmlBase(node, b, s) +local xb = node.attrs and node.attrs["xml:base"] + if type(xb) ~= "string" or xb == "" then + return b, s + end + local l = Url.locate(xb, b, s) + if Url.scheme(l.url) then + return l.url, Url.scheme(l.url) + end + return b, s + end + local pbase, pscheme = withXmlBase(root, base, baseScheme) + local pl= { + kind = "playlist", + format = "xspf", + entries = {}, + warnings = warnings, + title = field(root, "title"), + meta = { source = { format = "xspf", version = root.attrs and root.attrs.version } }, + } + for _, k in __iter(PLAYLIST_FIELDS) do + if k ~= "title" then + pl.meta[k] = field(root, k) + end + end + local nLocal = 0 + for _, list in __iter(elements(root, "trackList")) do + for i, track in __iter(elements(list, "track")) do + local tbase, tscheme = withXmlBase(track, pbase, pscheme) + local locs= {} + for _, l in __iter(elements(track, "location")) do + local s = trim(Xml.text(l)) + if s ~= "" then + table.insert(locs, s) + end + end + if #locs == 0 then + table.insert(warnings, string.format("track %d: no location", i)) + else + local e= Url.locate(locs[1], tbase, tscheme) + for _, k in __iter(TRACK_FIELDS) do + e[k] = field(track, k) + end + local d = tonumber(field(track, "duration")) + e.duration = (d and d >= 0 and d == d and d ~= math.huge and((d / 1000 ))or(nil +)) e.trackNum = tonumber(field(track, "trackNum")) + if #locs > 1 then + local all = {} + for _, l in __iter(locs) do + table.insert(all, Url.locate(l, tbase, tscheme).url) + end + e.locations = all + end + if e.reason == "local path" then + nLocal =nLocal+ 1 + elseif e.reason then + table.insert(warnings, string.format("track %d: %s: %s", i, e.reason, e.url)) + end + table.insert(pl.entries, e) + end + end + end + if nLocal > 0 then + table.insert(warnings, string.format("%d local path%s (not playable)", nLocal, nLocal == 1 and"" or"s")) + end + return pl, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(playlist, opts?) -> buffer | nil, Err: XSPF version 1. playlist: a Types.Playlist (any format's) or a list +-- of entries ({ url, title?, duration?, creator?, album?, ... }). opts.indent (default 2) pretty-prints. +function Xspf.encode(value, opts) +if type(value) ~= "table" then + return nil, Err.new(Err.ARG, "encode: needs a Playlist or a list of entries") + end + local entries = (type(value.entries) == "table" and{value.entries }or{value +})[1] local root = Xml.element("playlist", { version = "1", xmlns = NS }) + local function add(parent, name, v) + if type(v) == "string" and v ~= "" then + Xml.append(parent, Xml.element(name, nil, { v })) + elseif type(v) == "number" and v == v and v ~= math.huge and v ~= -math.huge then + Xml.append(parent, Xml.element(name, nil, { tostring(math.floor(v + 0.5)) })) + end + end + local title = (opts and opts.title and{opts.title }or{value.title +})[1] add(root, "title", title) + local meta = (type(value.meta) == "table" and{value.meta }or{{} +})[1] for _, k in __iter(PLAYLIST_FIELDS) do + if k ~= "title" then + add(root, k, meta[k]) + end + end + local list = Xml.append(root, Xml.element("trackList")) + for _, e in __iter(entries) do + if type(e) == "table" and type(e.url) == "string" then + local tr = Xml.append(list, Xml.element("track")) + add(tr, "location", e.url) + if type(e.locations) == "table" then + for i = 2, #e.locations do + add(tr, "location", e.locations[i]) + end + end + for _, k in __iter(TRACK_FIELDS) do + add(tr, k, e[k]) + end + local d = tonumber(e.duration) + if d and d >= 0 then + add(tr, "duration", d * 1000) + end + add(tr, "trackNum", tonumber(e.trackNum)) + end + end + local s = Xml.encode(Xml.document(root), { indent = (opts and opts.indent ~= nil and{opts.indent }or{2 })[1]}) + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "encode: the XML serializer failed") + end + return buffer.fromstring(s), nil +end + +return Xspf +end +__FILES["subtitle/ass"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- subtitle/ass: Advanced SubStation Alpha (v4.00+) and SubStation Alpha (v4.00) scripts (the de-facto spec of +-- Aegisub / libass / ffmpeg). Supports: [Script Info] (meta.scriptInfo, in order), the [V4+ Styles] / [V4 Styles] +-- Format + Style lines (subs.styles[name] = { field = value } as strings, meta.styleFormat / meta.styleOrder), the +-- [Events] Format + Dialogue lines (cues with layer, name, margins, effect; Comment lines in meta.comments), any +-- other section kept verbatim (meta.sections: [Fonts], [Graphics], [Aegisub Project Garbage], ...), H:MM:SS.cc times. +-- Cue text: `\N` / `\n` become line breaks, `\h` a no-break space, the {\i1} / {\b1} / {\u1} / {\s1} overrides become +-- the shared <i> / <b> / <u> / <s> markup and other override blocks are dropped; the original text stays in cue.raw. +-- Encode: an ASS v4.00+ script (or the source's style / event formats), cue.raw when cue.text still matches it, +-- otherwise the markup converted back; times rounded to the centisecond. Styles are data: nothing is rendered. Not supported: +-- rendering, karaoke timing (\k overrides are dropped from text, kept in cue.raw), embedded font / graphic decoding. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Ass = { + name = "ass", + category = "subtitle", + extensions = { "ass", "ssa" }, + mime = { "text/x-ssa", "text/x-ass" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local STYLE_FORMAT = { "Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour", "Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle", "Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding" } +local STYLE_DEFAULT= { + Name = "Default", + Fontname = "Arial", + Fontsize = "16", + PrimaryColour = "&Hffffff", + SecondaryColour = "&Hffffff", + OutlineColour = "&H0", + TertiaryColour = "&H0", + BackColour = "&H0", + Bold = "0", + Italic = "0", + Underline = "0", + StrikeOut = "0", + ScaleX = "100", + ScaleY = "100", + Spacing = "0", + Angle = "0", + BorderStyle = "1", + Outline = "1", + Shadow = "0", + Alignment = "2", + MarginL = "10", + MarginR = "10", + MarginV = "10", + AlphaLevel = "0", + Encoding = "0", +} +local EVENT_FORMAT = { "Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text" } +-- event fields -> cue keys (the rest keep their field name) +local EVENT_KEY = { Layer = "layer", Name = "name", Actor = "name", MarginL = "marginL", MarginR = "marginR", MarginV = "marginV", Effect = "effect", Marked = "marked" } + +local function trim(s) +return (string.match(s, "^%s*(.-)%s*$")) +end + +local function fields(s) +local out = {} + for _, f in __iter(string.split(s, ",")) do + table.insert(out, trim(f)) + end + return out +end + +-- H:MM:SS.cc (also more / fewer fraction digits) -> seconds | nil +local function time(s) +local h, m, sec, f = string.match(s, "^%s*(%d+):(%d+):(%d+)%.?(%d*)%s*$") + if not h then + return nil + end + local fr = (f ~= "" and((((tonumber(f) )) / 10 ^ #(f ) ))or(0 +)) return (tonumber(h) )* 3600 + (tonumber(m) )* 60 + (tonumber(sec) )+ fr +end + +-- ASS text -> the shared markup +local TAGS = { i = "i", b = "b", u = "u", s = "s" } +function Ass.toMarkup(raw) +local open= {} + local out = string.gsub(raw, "{([^}]*)}", function(block) +local acc = {} + for tag, arg in __iter(string.gmatch(block, "\\(%a+)([^\\]*)")) do + local t = TAGS[tag] + if t then + local on = arg == "" or (tonumber(arg) or 0) ~= 0 + if arg == "" then + on = not open[t] + end + if on and not open[t] then + table.insert(acc, "<" .. t .. ">") + open[t] = true + elseif not on and open[t] then + table.insert(acc, "</" .. t .. ">") + open[t] = false + end + elseif tag == "r" then + for _, k in __iter({ "s", "u", "b", "i" }) do + if open[k] then + table.insert(acc, "</" .. k .. ">") + open[k] = false + end + end + end + end + return table.concat(acc) + end) + out = string.gsub(out, "\\[Nn]", "\n") + out = string.gsub(out, "\\h", "\194\160") + for _, k in __iter({ "s", "u", "b", "i" }) do + if open[k] then + out =out.. "</" .. k .. ">" + end + end + return out +end + +-- the shared markup -> ASS text +function Ass.fromMarkup(text) +local s = string.gsub(text, "\r\n?", "\n") + s = string.gsub(s, "<(/?)(%a+)[^>]*>", function(close, tag) +local t = TAGS[string.lower(tag)] + if not t then + return "" + end + return "{\\" .. t .. (close == "/" and"0" or"1") .. "}" + end) + s = string.gsub(s, "\n", "\\N") + return s +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ass.sniff(r) +local head = Sniff.text(r, 64) + if string.match(head, "^%s*%[[Ss]cript [Ii]nfo%]") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ass.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Ass.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing [Script Info]", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local subs = Types.Subtitles.new() + local info= {} + local infoOrder= {} + local styleFormat= nil + local styleOrder= {} + local eventFormat= EVENT_FORMAT + local comments = {} + local sections= {} + local section = "" + local stylesName= nil + for _, line in __iter(string.split(s, "\n")) do +local __DARKLUA_CONTINUE_5=false repeat local name = string.match(line, "^%s*%[(.-)%]%s*$") + if name then + section = string.lower(name) + if section == "v4+ styles" or section == "v4 styles" or section == "v4 styles+" then + stylesName = name + section = "styles" + elseif section ~= "script info" and section ~= "events" then + table.insert(sections, { name = name, lines = {} }) + end +__DARKLUA_CONTINUE_5=true break + end + if section == "script info" then + if string.sub(line, 1, 1) == ";" or string.sub(line, 1, 1) == "!" then + table.insert(infoOrder, line) -- a comment line, kept in place + else + local k, v = string.match(line, "^([^:]+):%s?(.*)$") + if k then + k = trim(k) + if info[k] == nil then + table.insert(infoOrder, k) + end + info[k] = v +end + end + elseif section == "styles" then + local k, v = string.match(line, "^%s*(%a+):%s*(.*)$") + if k == "Format" then + styleFormat = fields(v ) + elseif k == "Style" then + local fmt = styleFormat or STYLE_FORMAT + local vals = string.split(v , ",") + local st= {} + for fi, f in __iter(fmt) do + st[f] = trim(vals[fi] or "") + end + local sname = st.Name or "" + if subs.styles[sname] == nil then + table.insert(styleOrder, sname) + end + subs.styles[sname] = st + end + elseif section == "events" then + local k, v = string.match(line, "^%s*(%a+):%s?(.*)$") + if k == "Format" then + eventFormat = fields(v ) + elseif k == "Dialogue" or k == "Comment" then + local vals= {} + local rest = v +for fi = 1, #eventFormat do + if fi == #eventFormat then + vals[fi] = rest + else + local c = string.find(rest, ",", 1, true) + if not c then + vals[fi] = rest + rest = "" + else + vals[fi] = string.sub(rest, 1, c - 1) + rest = string.sub(rest, c + 1) + end + end + end + local cue= { text = "", start = 0, stop = 0 } + local ok = true + for fi, f in __iter(eventFormat) do + local val = vals[fi] or "" + if f == "Start" or f == "End" then + local t = time(val) + if not t then + ok = false + else + cue[f == "Start" and"start" or"stop"] = t + end + elseif f == "Text" then + cue.raw = val + cue.text = Ass.toMarkup(val) + elseif f == "Style" then + cue.style = trim(val) + elseif f == "Layer" then + cue.layer = tonumber(trim(val)) or 0 + else + cue[EVENT_KEY[f] or f] = trim(val) + end + end + if ok then + if k == "Comment" then + cue.after = #subs.cues -- written back after that many dialogue lines + table.insert(comments, cue) + else + table.insert(subs.cues, cue ) + end + end + end + elseif section ~= "" then + table.insert(sections[#sections].lines, line) + end +__DARKLUA_CONTINUE_5=true until true if not __DARKLUA_CONTINUE_5 then break end end + subs.meta.scriptInfo = info + subs.meta.scriptInfoOrder = infoOrder + subs.meta.styleFormat = styleFormat + subs.meta.styleOrder = styleOrder + subs.meta.stylesSection = stylesName + subs.meta.eventFormat = eventFormat + if #comments > 0 then + subs.meta.comments = comments + end + if #sections > 0 then + -- drop trailing blank lines (the writer adds its own) + for _, sec in __iter(sections) do + while #sec.lines > 0 and string.match(sec.lines[#sec.lines], "^%s*$") do + table.remove(sec.lines) + end + end + subs.meta.sections = sections + end + subs.meta.source = { format = "ass", scriptType = info.ScriptType } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t) +local cs = math.floor(t * 100 + 0.5) + return string.format("%d:%02d:%02d.%02d", math.floor(cs / 360000), math.floor(cs / 6000 )% 60, math.floor(cs / 100 )% 60, cs % 100) +end + +local function field(v) +return (string.gsub(tostring(v), "[\r\n,]", " ")) +end + +function Ass.encode(subs, opts) +if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta= (type(subs.meta) == "table" and{subs.meta }or{{} +})[1] local out = { "[Script Info]" } + local info= (type(meta.scriptInfo) == "table" and{meta.scriptInfo }or{{} +})[1] local order = (type(meta.scriptInfoOrder) == "table" and{meta.scriptInfoOrder }or{{} +})[1] local written= {} + if info.ScriptType == nil then + table.insert(out, "ScriptType: v4.00+") + end + for _, k in __iter(order) do + if type(k) == "string" and (string.sub(k, 1, 1) == ";" or string.sub(k, 1, 1) == "!") then + table.insert(out, k) + elseif info[k] ~= nil and not written[k] then + table.insert(out, k .. ": " .. tostring(info[k])) + written[k] = true + end + end + local rest = {} + for k, v in __iter(info) do + if not written[k] and type(k) == "string" then + table.insert(rest, k .. ": " .. string.gsub(tostring(v), "[\r\n]", " ")) + end + end + table.sort(rest) + table.move(rest, 1, #rest, #out + 1, out) + -- styles + local ssa = type(info.ScriptType) == "string" and string.lower(info.ScriptType) == "v4.00" + local sfmt= (type(meta.styleFormat) == "table" and{meta.styleFormat }or{STYLE_FORMAT +})[1] table.insert(out, "") + table.insert(out, "[" .. ((type(meta.stylesSection) == "string" and{meta.stylesSection }or{ssa and"V4 Styles" or"V4+ Styles"})[1]) .. "]") + table.insert(out, "Format: " .. table.concat(sfmt, ", ")) + local names= {} + local seen= {} + if type(meta.styleOrder) == "table" then + for _, nm in __iter(meta.styleOrder) do + if type(nm) == "string" and type(subs.styles) == "table" and subs.styles[nm] ~= nil and not seen[nm] then + table.insert(names, nm) + seen[nm] = true + end + end + end + local extra = {} + if type(subs.styles) == "table" then + for nm, st in __iter(subs.styles) do + if type(nm) == "string" and type(st) == "table" and not seen[nm] then + table.insert(extra, nm) + end + end + end + table.sort(extra) + table.move(extra, 1, #extra, #names + 1, names) + if #names == 0 then + names = { "Default" } + end + for _, nm in __iter(names) do + local st = (type(subs.styles) == "table" and type(subs.styles[nm]) == "table" and{subs.styles[nm] }or{{} +})[1] local vals = {} + for fi, f in __iter(sfmt) do + local v = (f == "Name" and{nm }or{st[f] +})[1] vals[fi] = field((v ~= nil and{v }or{(STYLE_DEFAULT[f] or "0")})[1]) + end + table.insert(out, "Style: " .. table.concat(vals, ",")) + end + -- events + local efmt= (type(meta.eventFormat) == "table" and{meta.eventFormat }or{EVENT_FORMAT +})[1] if efmt[#efmt] ~= "Text" then + return nil, Err.new(Err.ARG, "meta.eventFormat must end with Text") + end + table.insert(out, "") + table.insert(out, "[Events]") + table.insert(out, "Format: " .. table.concat(efmt, ", ")) + local function event(kind, c, i) +if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local vals = {} + for fi, f in __iter(efmt) do + local v +if f == "Start" then + v = stamp(c.start) + elseif f == "End" then + v = stamp(c.stop) + elseif f == "Style" then + v = field(c.style or names[1]) + elseif f == "Text" then + if type(c.raw) == "string" and Ass.toMarkup(c.raw) == c.text then + v = string.gsub(c.raw, "[\r\n]", " ") + else + v = Ass.fromMarkup(c.text) + end + elseif f == "Layer" then + v = tostring(tonumber(c.layer) or 0) + elseif f == "Marked" then + v = field(c.marked or "Marked=0") + else + local key = EVENT_KEY[f] or f + local x = c[key] + v = field((x ~= nil and{x }or{string.sub(f, 1, 6) == "Margin" and"0" or""})[1]) + end + vals[fi] = v + end + table.insert(out, kind .. ": " .. table.concat(vals, ",")) + return nil + end + local comments = (type(meta.comments) == "table" and{meta.comments }or{{} +})[1] local function commentsAfter(n) +for i, c in __iter(comments) do + if (type(c) == "table" and c.after == n) or (n == nil and (type(c) ~= "table" or type(c.after) ~= "number" or c.after > #subs.cues)) then + local e = event("Comment", c, i) + if e then + return e + end + end + end + return nil + end + for i = 0, #subs.cues do + local e = ((i > 0 and{(event("Dialogue", subs.cues[i], i) )}or{nil})[1]) or commentsAfter(i) + if e then + return nil, e + end + end + local e = commentsAfter(nil) + if e then + return nil, e + end + if type(meta.sections) == "table" then + for _, sec in __iter(meta.sections) do + if type(sec) == "table" and type(sec.name) == "string" and type(sec.lines) == "table" then + table.insert(out, "") + table.insert(out, "[" .. sec.name .. "]") + for _, l in __iter(sec.lines) do + table.insert(out, tostring(l)) + end + end + end + end + table.insert(out, "") + local nl = opts and opts.crlf and"\r\n" or"\n" + return buffer.fromstring(table.concat(out, nl)), nil +end + +return Ass +end +__FILES["subtitle/srt"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- subtitle/srt: SubRip text (the de-facto format; matches ffmpeg's srt demuxer / muxer). Supports: numbered or +-- unnumbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm` timings (also `.` decimals and 1..3 fraction digits), the trailing +-- `X1:.. Y1:..` coordinates (kept in cue.settings), multi-line text with blank lines inside a cue (a blank line ends +-- the cue only before an index / timing line), BOM, CRLF / CR line ends. Text is kept as written (its <i> / <b> / +-- <u> / <s> / <font> tags included): the shared markup of Subtitles cue text. +-- Encode: cues renumbered from 1 in order, times rounded to the millisecond, opts.crlf for CRLF line ends. +-- Not supported: positioning beyond keeping the coordinates; the tags are not validated. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Srt = { + name = "srt", + category = "subtitle", + extensions = { "srt" }, + mime = { "application/x-subrip", "text/srt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = false }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local TIMING = "^%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*%-%->%s*(%d+):(%d%d?):(%d%d?)[,.](%d+)%s*(.-)%s*$" + +-- text of the reader's range: BOM stripped, line ends normalised to LF; nil when it holds NUL bytes (binary) +local function text(r) +local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + return s +end + +local function frac(digits) +return ((tonumber(digits) )) / 10 ^ #digits +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line) +local h1, m1, s1, f1, h2, m2, s2, f2, rest = string.match(line, TIMING) + if not h1 then + return nil, nil, nil + end + local a = (tonumber(h1) )* 3600 + (tonumber(m1) )* 60 + (tonumber(s1) )+ frac(f1 ) + local b = (tonumber(h2) )* 3600 + (tonumber(m2) )* 60 + (tonumber(s2) )+ frac(f2 ) + return a, b, rest +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Srt.sniff(r) +local head = Sniff.text(r, 512) + head = string.gsub(head, "\r", "\n") + local first, second = string.match(head, "^%s*([^\n]*)\n([^\n]*)") + if first and string.match(first, "^%d+%s*$") and second and timing(second) then + return 0.9 + end + if first and timing(first) then + return 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Srt.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + local s = text(r) + if not s then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + local i = 1 + local function isStart(k) +local l = lines[k] + if l == nil then + return false + end + if timing(l) then + return true + end + return string.match(l, "^%s*%d+%s*$") ~= nil and lines[k + 1] ~= nil and timing(lines[k + 1]) ~= nil + end + while i <= n do + local line = lines[i] + local a, b, settings = timing(line) + if a then + local id= nil + if i > 1 then + local prev = string.match(lines[i - 1], "^%s*(%d+)%s*$") + id = prev + end + i =i+ 1 + local body = {} + while i <= n do + local l = lines[i] + if string.match(l, "^%s*$") then + -- blank: the end of the cue unless more text follows before the next cue + local k = i + while k <= n and string.match(lines[k], "^%s*$") do + k =k+ 1 + end + if k > n or isStart(k) then + break + end + for _ = i, k - 1 do + table.insert(body, "") + end + i = k + elseif timing(l) then + break -- a cue without the blank separator + else + table.insert(body, l) + i =i+ 1 + end + end + -- an index line right before the next timing belongs to the next cue + if #body > 0 and i <= n and timing(lines[i]) and string.match(body[#body], "^%s*%d+%s*$") then + table.remove(body) + end + local cue= { start = a, stop = b , text = table.concat(body, "\n"), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + else + i =i+ 1 + end + end + if #subs.cues == 0 and string.find(s, "%S") then + return nil, Err.new(Err.CORRUPT, "no cues (no `-->` timing line)") + end + subs.meta.source = { format = "srt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t) +local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d,%03d", math.floor(ms / 3600000), math.floor(ms / 60000 )% 60, math.floor(ms / 1000 )% 60, ms % 1000) +end + +function Srt.encode(subs, opts) +if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local nl = opts and opts.crlf and"\r\n" or"\n" + local out = table.create(#subs.cues) + for i, c in __iter(subs.cues) do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + -- blank lines inside the text are fine: the decoder ends a cue at a blank line only before the next cue + local body = string.gsub(c.text, "\r\n?", "\n") + local settings = (type(c.settings) == "string" and c.settings ~= "" and string.match(c.settings, "X1:") and((" " .. c.settings ))or("" +)) out[i] = i .. nl .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. nl .. (string.gsub(body, "\n", nl)) .. nl + end + return buffer.fromstring(table.concat(out, nl) .. nl), nil +end + +return Srt +end +__FILES["subtitle/vtt"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- subtitle/vtt: WebVTT (W3C WebVTT, 2019 CR). Supports: the WEBVTT header (its trailing text and header lines kept in +-- meta.header), cue identifiers, `[hh:]mm:ss.ttt` timings, cue settings (cue.settings, as written), NOTE comments +-- (meta.notes), STYLE blocks (meta.css) and REGION blocks (meta.regions); BOM, CRLF / CR line ends. Cue text is kept +-- as written (<i> / <b> / <c.class> / <v Name> spans, timestamps, entities). +-- Encode: the header, STYLE / REGION blocks, then the cues (times to the millisecond); blank lines inside cue text +-- are dropped and `-->` escaped (WebVTT cue text cannot hold them). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Vtt = { + name = "vtt", + category = "subtitle", + extensions = { "vtt", "webvtt" }, + mime = { "text/vtt" }, + deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" }, + caps = { decode = true, encode = true, styles = true }, +} + +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local function frac(digits) +return ((tonumber(digits) )) / 10 ^ #digits +end + +-- one timestamp at the start of s: seconds, the rest | nil +local function timestamp(s) +local h, m, sec, f, rest = string.match(s, "^(%d+):(%d%d):(%d%d)%.(%d+)(.*)$") + if h then + return (tonumber(h) )* 3600 + (tonumber(m) )* 60 + (tonumber(sec) )+ frac(f ), rest +end + local m2, s2, f2, rest2 = string.match(s, "^(%d+):(%d%d)%.(%d+)(.*)$") + if m2 then + return (tonumber(m2) )* 60 + (tonumber(s2) )+ frac(f2 ), rest2 +end + return nil, s +end + +-- timing(line) -> start, stop, settings | nil +local function timing(line) +local a, rest = timestamp((string.gsub(line, "^%s+", ""))) + if not a then + return nil, nil, nil + end + local after = string.match(rest, "^%s*%-%->%s*(.*)$") + if not after then + return nil, nil, nil + end + local b, rest2 = timestamp(after) + if not b then + return nil, nil, nil + end + local settings = string.match(rest2, "^%s*(.-)%s*$") or "" + return a, b, settings +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Vtt.sniff(r) +local head = Sniff.text(r, 10) + if string.sub(head, 1, 6) == "WEBVTT" then + local c = string.sub(head, 7, 7) + if c == "" or c == " " or c == "\t" or c == "\n" or c == "\r" then + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Vtt.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the " .. maxBytes .. " byte limit") + end + if Vtt.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "missing the WEBVTT signature", r.base) + end + local s = buffer.readstring(r.buf, r.base, r.limit - r.base) + if string.find(s, "\0", 1, true) then + return nil, Err.new(Err.CORRUPT, "binary data (NUL bytes) in a text format") + end + s = Sniff.dropBom(s) + s = string.gsub(s, "\r\n", "\n") + s = string.gsub(s, "\r", "\n") + local lines = string.split(s, "\n") + local n = #lines + local subs = Types.Subtitles.new() + -- the header block: WEBVTT[ text] + lines up to the first blank + local header = { (string.match(lines[1], "^WEBVTT[ \t]*(.*)$")) or "" } + local i = 2 + while i <= n and lines[i] ~= "" do + table.insert(header, lines[i]) + i =i+ 1 + end + if #header > 1 or header[1] ~= "" then + subs.meta.header = table.concat(header, "\n") + end + local notes, css, regions = {}, {}, {} + while i <= n do +local __DARKLUA_CONTINUE_2=false repeat if lines[i] == "" then + i =i+ 1 +__DARKLUA_CONTINUE_2=true break + end + -- a block: lines up to the next blank + local first = i + while i <= n and lines[i] ~= "" do + i =i+ 1 + end + local block = table.move(lines, first, i - 1, 1, {}) + local head = block[1] + if string.match(head, "^NOTE[ \t]") or head == "NOTE" then + table.insert(notes, (string.gsub(table.concat(block, "\n"), "^NOTE[ \t]?", ""))) + elseif (head == "STYLE" or string.match(head, "^STYLE[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(css, table.concat(block, "\n", 2)) + elseif (head == "REGION" or string.match(head, "^REGION[ \t]")) and not string.find(table.concat(block, "\n"), "-->", 1, true) then + table.insert(regions, table.concat(block, "\n", 2)) + else + local k, id = 1, nil + local a, b, settings = timing(block[1]) + if not a and block[2] then + id = block[1] + k = 2 + a, b, settings = timing(block[2]) + end + if a then + local cue= { start = a, stop = b , text = table.concat(block, "\n", k + 1), id = id } + if settings and settings ~= "" then + cue.settings = settings + end + table.insert(subs.cues, cue) + end + -- a block with no timing is skipped (the spec's parser ignores it) + end +__DARKLUA_CONTINUE_2=true until true if not __DARKLUA_CONTINUE_2 then break end end + if #notes > 0 then + subs.meta.notes = notes + end + if #css > 0 then + subs.meta.css = css + end + if #regions > 0 then + subs.meta.regions = regions + end + subs.meta.source = { format = "vtt" } + return subs, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function stamp(t) +local ms = math.floor(t * 1000 + 0.5) + return string.format("%02d:%02d:%02d.%03d", math.floor(ms / 3600000), math.floor(ms / 60000 )% 60, math.floor(ms / 1000 )% 60, ms % 1000) +end + +-- one block's text: no blank lines (they end a block), no `-->` +local function clean(s) +s = string.gsub(s, "\r\n?", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "\n[ \t]*\n", "\n") + s = string.gsub(s, "^\n+", "") + s = string.gsub(s, "%-%->", "-->") + return s +end + +function Vtt.encode(subs, opts) +if type(subs) ~= "table" or type(subs.cues) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Subtitles value") + end + local meta= (type(subs.meta) == "table" and{subs.meta }or{{} +})[1] local out = {} + local header = (type(meta.header) == "string" and meta.header ~= "" and{meta.header }or{nil +})[1] if header then + local h = string.gsub(clean(header), "%-%->", "") + table.insert(out, "WEBVTT " .. h .. "\n") + else + table.insert(out, "WEBVTT\n") + end + for _, key in __iter({ "regions", "css" }) do + local list = meta[key] + if type(list) == "table" then + for _, b in __iter(list) do + if type(b) == "string" then + table.insert(out, (key == "css" and"STYLE\n" or"REGION\n") .. clean(b) .. "\n") + end + end + end + end + for i, c in __iter(subs.cues) do + if type(c) ~= "table" or type(c.start) ~= "number" or type(c.stop) ~= "number" or type(c.text) ~= "string" or c.start < 0 or c.stop < 0 then + return nil, Err.new(Err.ARG, "cue " .. i .. ": needs start / stop >= 0 (seconds) and a text string") + end + local id = (type(c.id) == "string" and c.id ~= "" and not string.find(c.id, "-->", 1, true) and{((string.gsub(c.id, "[\r\n]", " ")) .. "\n" )}or{"" +})[1] local settings = (type(c.settings) == "string" and c.settings ~= "" and{(" " .. (string.gsub(c.settings, "[\r\n]", " ")) )}or{"" +})[1] local body = clean(c.text) + table.insert(out, id .. stamp(c.start) .. " --> " .. stamp(c.stop) .. settings .. "\n" .. body .. (body ~= "" and"\n" or"")) + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +return Vtt +end +__FILES["vector/svg"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs +-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg +-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from +-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke / +-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and +-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path +-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %). +-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and +-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector. +-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also +-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Parse = __include("vector/svg/Parse") +local Render = __include("vector/svg/Render") +local Write = __include("vector/svg/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Svg = { + name = "svg", + category = "vector", + extensions = { "svg" }, + mime = { "image/svg+xml" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + +function Svg.sniff(r) +local h = Sniff.text(r, 4096) + if not string.match(h, "^%s*<") then + return 0 + end + if string.find(h, "<svg[%s>:]") or string.find(h, "<%w+:svg[%s>]") then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Svg.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 26 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local doc, xerr = Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base)) + if not doc then + return nil, xerr + end + local v, msg = Parse.document(doc) + if not v then + return nil, Err.new(Err.CORRUPT, msg or "bad SVG") + end + v.meta.source = { format = "svg" } + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Svg.encode(v, opts) +local s, err = Write.vector(v) + if not s then + return nil, Err.new(Err.ARG, err or "bad Vector") + end + return buffer.fromstring(s), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox +-- maps onto w x h by its preserveAspectRatio. +function Svg.rasterize(v, w, h, opts) +if type(v) ~= "table" or type(v.paths) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Vector value") + end + local W = math.ceil(w or v.width or 0) + local H = math.ceil(h or v.height or 0) + if W < 1 or H < 1 or W * H > 2 ^ 26 then + return nil, Err.new(Err.ARG, "bad raster size") + end + return Render.rasterize(v, W, H, opts), nil +end + +return Svg +end +__FILES["vector/svg/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, +-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space +-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into +-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a +-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>. +-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported. +-- Never throws. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Style = __include("vector/svg/Style") +local PathData = __include("vector/svg/PathData") + +local Parse = {} + + + + +local IDENTITY = { 1, 0, 0, 1, 0, 0 } +local mul = Style.multiply + +-- properties that inherit, and their initial values +local INHERITED= { + fill = "black", + ["fill-opacity"] = "1", + ["fill-rule"] = "nonzero", + stroke = "none", + ["stroke-width"] = "1", + ["stroke-opacity"] = "1", + ["stroke-linecap"] = "butt", + ["stroke-linejoin"] = "miter", + ["stroke-miterlimit"] = "4", + ["stroke-dasharray"] = "none", + ["stroke-dashoffset"] = "0", + ["clip-rule"] = "nonzero", + visibility = "visible", + color = "black", + ["font-size"] = "16", +} +-- not inherited (reset per element) +local LOCAL= { + opacity = true, + ["clip-path"] = true, + display = true, + ["stop-color"] = true, + ["stop-opacity"] = true, + mask = true, + filter = true, +} + +local UNSUPPORTED= { text = true, image = true, pattern = true, mask = true, marker = true, filter = true, foreignObject = true, textPath = true, tspan = true } +local CONTAINERS = { g = true, a = true, switch = true } +local SHAPES = { path = true, rect = true, circle = true, ellipse = true, line = true, polyline = true, polygon = true } + + + + + + + + + + + + + + +local function local_(n) +return Xml.localName(n.name) +end +local function attr(n, k) +local a = n.attrs +return a[k] +end +local function href(n) +local h = attr(n, "href") or attr(n, "xlink:href") + if h == nil then + for k, v in pairs(n.attrs ) do + if type(k) == "string" and Xml.localName(k) == "href" then + return v + end + end + end + return h +end +local function refId(s) +if s == nil then + return nil + end + return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)") +end + +-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style="" +local function specified(n, ctx) +local out= {} + for k, v in pairs(n.attrs ) do + if type(k) == "string" and type(v) == "string" and (INHERITED[k] or LOCAL[k]) then + out[k] = v + end + end + if #ctx.rules > 0 then + local classes= {} + for c in __iter(string.gmatch(attr(n, "class") or "", "%S+")) do + classes[c] = true + end + local hits= {} + for _, r in __iter(ctx.rules) do + if Style.matches(r.selector, local_(n), attr(n, "id"), classes) then + table.insert(hits, r) + end + end + table.sort(hits, function(a, b) +if a.selector.specificity ~= b.selector.specificity then + return a.selector.specificity < b.selector.specificity + end + return a.order < b.order + end) + for _, r in __iter(hits) do + for k, v in pairs(r.decls) do + out[k] = v + end + end + end + local st = attr(n, "style") + if st then + for k, v in pairs(Style.declarations(st)) do + out[k] = v + end + end + return out +end + +-- computed(parent, n) -> the element's computed property strings +local function computed(parent, n, ctx) +local out= {} + for k in pairs(INHERITED) do + out[k] = parent[k] + end + for k, v in pairs(specified(n, ctx)) do + if v == "inherit" then + out[k] = parent[k] + elseif INHERITED[k] or LOCAL[k] then + out[k] = v + end + end + return out +end + +local function len(s, ref, st, default) +local fs = Style.length(st["font-size"], 16) or 16 + local v = Style.length(s, ref, fs) + if v == nil then + return default + end + return v +end + +-- ------------------------------------------------------------------------------------------------ paints +local function stops(g, ctx, seen) +local list = {} + local parentStyle = computed(INHERITED, g, ctx) + for _, s in __iter(Xml.children(g)) do + if local_(s) == "stop" then + local st = computed(parentStyle, s, ctx) + local off = attr(s, "offset") or "0" + local o = tonumber(string.match(off, "^%s*([%d.eE+-]+)%s*%%%s*$") or "") + local offset = (o and((o / 100 ))or((tonumber(off) or 0) +)) offset = math.clamp(offset, 0, 1) + if #list > 0 and offset < list[#list][1] then + offset = list[#list][1] + end + local col = Style.color(st["stop-color"] or "black", Style.color(st.color or "black")) or { 0, 0, 0, 255 } + if col == "none" then + col = { 0, 0, 0, 0 } + end + local op = math.clamp(tonumber(st["stop-opacity"] or "1") or 1, 0, 1) + table.insert(list, { offset, col[1], col[2], col[3], math.floor(col[4] * op + 0.5) }) + end + end + if #list == 0 then + local h = refId(href(g)) + local other = (h and{ctx.ids[h] }or{nil +})[1] if other and not seen[other] then + seen[other] = true + return stops(other, ctx, seen) + end + end + return list +end + +-- a gradient attribute, looked up through href templates +local function gattr(g, k, ctx) +local cur= g + local guard = 0 + while cur and guard < 16 do + local v = attr(cur, k) + if v ~= nil then + return v + end + local h = refId(href(cur)) + cur = (h and{ctx.ids[h] }or{nil +})[1] guard =guard+ 1 + end + return nil +end + +local function gradient(g, opacity, ctx) +local kind = local_(g) + local units = gattr(g, "gradientUnits", ctx) or "objectBoundingBox" + local obb = units ~= "userSpaceOnUse" + local list = stops(g, ctx, { [g] = true }) + if #list == 0 then + return "none" + end + if #list == 1 then + local s = list[1] + return { type = "color", color = { s[2], s[3], s[4], math.floor(s[5] * opacity + 0.5) } } + end + local function coord(k, default, ref) +local v = gattr(g, k, ctx) or default + local pct = string.match(v, "^%s*([%d.eE+-]+)%s*%%%s*$") + if pct then + local x = tonumber(pct) or 0 + return (obb and((x / 100 ))or((x / 100 * ref +))) end + return Style.length(v, ref) or 0 + end + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local p= { + type = kind == "linearGradient" and"linear" or"radial", + units = obb and"objectBoundingBox" or"userSpaceOnUse", + spread = gattr(g, "spreadMethod", ctx) or "pad", + stops = list, + opacity = opacity, + } + local t = gattr(g, "gradientTransform", ctx) + if t then + p.transform = Style.transform(t) + end + if p.type == "linear" then + p.x1, p.y1 = coord("x1", "0%", ctx.vw), coord("y1", "0%", ctx.vh) + p.x2, p.y2 = coord("x2", "100%", ctx.vw), coord("y2", "0%", ctx.vh) + else + p.cx, p.cy = coord("cx", "50%", ctx.vw), coord("cy", "50%", ctx.vh) + p.r = coord("r", "50%", diag) + p.fx = (gattr(g, "fx", ctx) and{(coord("fx", "50%", ctx.vw) )}or{p.cx +})[1] p.fy = (gattr(g, "fy", ctx) and{(coord("fy", "50%", ctx.vh) )}or{p.cy +})[1] p.fr = coord("fr", "0%", diag) + end + return p +end + +-- paint(value, opacity, st) -> Paint | nil (none) +local function paint(value, opacity, st, ctx) +if value == nil then + return nil + end + local id = string.match(value, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)%s*(.*)$") + if id then + local fallback = string.match(value, "%)%s*(.-)%s*$") + local g = ctx.ids[id] + if g and (local_(g) == "linearGradient" or local_(g) == "radialGradient") then + local p = gradient(g, opacity, ctx) + return (p == "none" and{nil }or{p +})[1] end + if g and local_(g) == "pattern" then + ctx.unsupported.pattern = (ctx.unsupported.pattern or 0) + 1 + end + if fallback and fallback ~= "" then + return paint(fallback, opacity, st, ctx) + end + return nil + end + local c = Style.color(value, (Style.color(st.color or "black") )) + if c == nil or c == "none" then + return nil + end + return { type = "color", color = { c[1], c[2], c[3], math.floor(c[4] * opacity + 0.5) } } +end + +-- ------------------------------------------------------------------------------------------------ shapes +local function shape(n, st, ctx) +local kind = local_(n) + local vw, vh = ctx.vw, ctx.vh + local diag = math.sqrt((vw * vw + vh * vh) / 2) + if kind == "path" then + local d = attr(n, "d") + if d == nil then + return nil + end + local cmds = PathData.parse(d) + return cmds + elseif kind == "rect" then + local x, y = (len(attr(n, "x"), vw, st, 0) ), (len(attr(n, "y"), vh, st, 0) ) +local w, h = (len(attr(n, "width"), vw, st, 0) ), (len(attr(n, "height"), vh, st, 0) ) +if w <= 0 or h <= 0 then + return nil + end + local rx, ry= len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + if rx and rx < 0 then + rx = nil + end + if ry and ry < 0 then + ry = nil + end + rx = rx or ry or 0 + ry = ry or rx + local rx, ry= math.min(rx , w / 2), math.min(ry , h / 2) + if rx <= 0 or ry <= 0 then + return { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } +end + local out= { { op = "M", x + rx, y }, { op = "L", x + w - rx, y } } + PathData.arc(x + w - rx, y, rx, ry, 0, false, true, x + w, y + ry, out) + table.insert(out, { op = "L", x + w, y + h - ry }) + PathData.arc(x + w, y + h - ry, rx, ry, 0, false, true, x + w - rx, y + h, out) + table.insert(out, { op = "L", x + rx, y + h }) + PathData.arc(x + rx, y + h, rx, ry, 0, false, true, x, y + h - ry, out) + table.insert(out, { op = "L", x, y + ry }) + PathData.arc(x, y + ry, rx, ry, 0, false, true, x + rx, y, out) + table.insert(out, { op = "Z" } ) + return out + elseif kind == "circle" or kind == "ellipse" then + local cx, cy = (len(attr(n, "cx"), vw, st, 0) ), (len(attr(n, "cy"), vh, st, 0) ) +local rx, ry + if kind == "circle" then + rx = (len(attr(n, "r"), diag, st, 0) ) +ry = rx + else + rx, ry = len(attr(n, "rx"), vw, st), len(attr(n, "ry"), vh, st) + rx = rx or ry or 0 + ry = ry or rx + end + if (rx ) <= 0 or (ry ) <= 0 then + return nil + end + local out= { { op = "M", cx + rx, cy } } + PathData.arc(cx + rx, cy, rx, ry, 0, false, true, cx, cy + ry, out) + PathData.arc(cx, cy + ry, rx, ry, 0, false, true, cx - rx, cy, out) + PathData.arc(cx - rx, cy, rx, ry, 0, false, true, cx, cy - ry, out) + PathData.arc(cx, cy - ry, rx, ry, 0, false, true, cx + rx, cy, out) + table.insert(out, { op = "Z" } ) + return out + elseif kind == "line" then + local x1, y1 = (len(attr(n, "x1"), vw, st, 0) ), (len(attr(n, "y1"), vh, st, 0) ) +local x2, y2 = (len(attr(n, "x2"), vw, st, 0) ), (len(attr(n, "y2"), vh, st, 0) ) +return { { op = "M", x1, y1 }, { op = "L", x2, y2 } } +elseif kind == "polyline" or kind == "polygon" then + local v = Style.numbers(attr(n, "points")) + if #v < 4 then + return nil + end + local out= { { op = "M", v[1], v[2] } } + for i = 3, #v - 1, 2 do + table.insert(out, { op = "L", v[i], v[i + 1] }) + end + if kind == "polygon" then + table.insert(out, { op = "Z" } ) + end + return out + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ clip paths +local function transformOf(n) +local t = attr(n, "transform") + if t then + return Style.transform(t) or IDENTITY + end + return IDENTITY +end + +-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox. +local function clip(ref, ctm, bbox, st, ctx) +local cp = ctx.ids[ref] + if cp == nil or local_(cp) ~= "clipPath" then + return nil + end + local base = mul(ctm, transformOf(cp)) + if attr(cp, "clipPathUnits") == "objectBoundingBox" then + if not bbox then + return nil + end + base = mul(base, { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] }) + end + local cpStyle = computed(st, cp, ctx) + local paths = {} + local function add(n, parentStyle, m, depth) + if depth > 8 then + return + end + local s = computed(parentStyle, n, ctx) + if s.display == "none" or s.visibility == "hidden" then + return + end + local k = local_(n) + local tm = mul(m, transformOf(n)) + if SHAPES[k] then + local cmds = shape(n, s, ctx) + if cmds and #cmds > 0 then + table.insert(paths, { d = cmds, transform = tm, rule = s["clip-rule"] or "nonzero" }) + end + elseif k == "use" then + local h = refId(href(n)) + local target = (h and{ctx.ids[h] }or{nil +})[1] if target then + local x, y = (len(attr(n, "x"), ctx.vw, s, 0) ), (len(attr(n, "y"), ctx.vh, s, 0) ) +add(target, s, mul(tm, { 1, 0, 0, 1, x, y }), depth + 1) + end + end + end + for _, c in __iter(Xml.children(cp)) do + add(c, cpStyle, base, 0) + end + table.insert(ctx.clips, { paths = paths }) + return #ctx.clips +end + +-- ------------------------------------------------------------------------------------------------ the walk +local walk + +local function bboxOf(cmds) +local x0, y0, x1, y1 = PathData.bounds(cmds) + if not x0 then + return nil + end + return { x0 , y0 , x1 , y1 } +end + +local function emitShape(n, st, ctm, group, ctx) + if st.visibility == "hidden" or st.visibility == "collapse" then + return + end + local cmds = shape(n, st, ctx) + if not cmds or #cmds == 0 then + return + end + local tm = mul(ctm, transformOf(n)) + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local fill = paint(st.fill, math.clamp(tonumber(st["fill-opacity"]) or 1, 0, 1), st, ctx) + local stroke = paint(st.stroke, math.clamp(tonumber(st["stroke-opacity"]) or 1, 0, 1), st, ctx) + local diag = math.sqrt((ctx.vw * ctx.vw + ctx.vh * ctx.vh) / 2) + local sw = (len(st["stroke-width"], diag, st, 1) ) +if sw <= 0 then + stroke = nil + end + if fill == nil and stroke == nil then + return + end + if local_(n) == "line" then + fill = nil -- a line has no inside + end + local clipRef = refId(st["clip-path"]) + local clipId= nil + if clipRef then + clipId = clip(clipRef, tm, bboxOf(cmds), st, ctx) + if clipId == nil and ctx.ids[clipRef] then + return -- a broken clip reference (bad units): nothing shows + end + end + -- opacity on a shape with both a fill and a stroke: a group, so the overlap is not counted twice + local g = group + if opacity < 1 and fill and stroke then + table.insert(ctx.groups, { opacity = opacity, parent = group }) + g = #ctx.groups + opacity = 1 + end + local p= { + d = cmds, + fill = fill, + fillRule = st["fill-rule"] == "evenodd" and"evenodd" or"nonzero", + stroke = stroke, + strokeWidth = sw, + transform = tm, + opacity = opacity, + group = g, + clip = clipId, + id = attr(n, "id"), + } + if stroke then + p.strokeLineJoin = st["stroke-linejoin"] + p.strokeLineCap = st["stroke-linecap"] + p.strokeMiterLimit = tonumber(st["stroke-miterlimit"]) or 4 + local dash = st["stroke-dasharray"] + if dash and dash ~= "none" then + local list = {} + local ok = true + for part in __iter(string.gmatch(dash, "[^,%s]+")) do + local v = len(part, diag, st) + if v == nil or v < 0 then + ok = false + end + table.insert(list, v or 0) + end + local sum = 0 + for _, v in __iter(list) do + sum =sum+ v + end + if ok and sum > 0 then + if #list % 2 == 1 then + table.move(list, 1, #list, #list + 1, list) + end + p.strokeDashArray = list + p.strokeDashOffset = len(st["stroke-dashoffset"], diag, st, 0) + end + end + end + table.insert(ctx.vector.paths, p) +end + +-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y) +function Parse.viewTransform(vb, par, x, y, w, h) +if vb == nil or vb[3] <= 0 or vb[4] <= 0 then + return { 1, 0, 0, 1, x, y } + end + local sx, sy = w / vb[3], h / vb[4] + local align, mode = "xmidymid", "meet" + if par then + local a, m = string.match(string.lower(par), "^%s*([%w]+)%s*(%a*)") + if a == "defer" then + a, m = string.match(string.lower(par), "^%s*defer%s+([%w]+)%s*(%a*)") + end + align = a or align + if m and m ~= "" then + mode = m + end + end + if align == "none" then + return { sx, 0, 0, sy, x - vb[1] * sx, y - vb[2] * sy } + end + local s = (mode == "slice" and{(math.max(sx, sy) )}or{(math.min(sx, sy) +)})[1] local tx, ty = x - vb[1] * s, y - vb[2] * s + local ax, ay = string.match(align, "^x(%a%a%a)y(%a%a%a)$") + if ax == "mid" then + tx =tx+ (w - vb[3] * s) / 2 + elseif ax == "max" then + tx =tx+ (w - vb[3] * s +) end + if ay == "mid" then + ty =ty+ (h - vb[4] * s) / 2 + elseif ay == "max" then + ty =ty+ (h - vb[4] * s +) end + return { s, 0, 0, s, tx, ty } +end + +local function viewBox(n) +local v = Style.numbers(attr(n, "viewBox")) + if #v == 4 and v[3] > 0 and v[4] > 0 then + return v + end + return nil +end + +local function container(n, st, ctm, group, ctx, children) + -- a layer for opacity / clip-path + local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + local clipRef = refId(st["clip-path"]) + local g = group + if opacity < 1 or clipRef then + local clipId= nil + if clipRef then + local bbox= nil + local cp = ctx.ids[clipRef] + if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then + -- the group's bounding box in its user space: walk once into a scratch vector + local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips + local scratch = Types.Vector.new(0, 0) + ctx.vector, ctx.groups, ctx.clips = scratch, {}, {} + for _, c in __iter(children or Xml.children(n)) do + walk(c, st, IDENTITY, nil, ctx) + end + ctx.vector, ctx.groups, ctx.clips = saveV, saveG, saveC + local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + for _, p in __iter(scratch.paths) do + local b = bboxOf(p.d) + if b then + local m = p.transform or IDENTITY + for _, corner in __iter({ { b[1], b[2] }, { b[3], b[2] }, { b[1], b[4] }, { b[3], b[4] } }) do + local px = m[1] * corner[1] + m[3] * corner[2] + m[5] + local py = m[2] * corner[1] + m[4] * corner[2] + m[6] + x0, y0, x1, y1 = math.min(x0, px), math.min(y0, py), math.max(x1, px), math.max(y1, py) + end + end + end + if x0 <= x1 then + bbox = { x0, y0, x1, y1 } + end + end + clipId = clip(clipRef, ctm, bbox, st, ctx) + if clipId == nil and cp then + return + end + end + table.insert(ctx.groups, { opacity = opacity, parent = group, clip = clipId }) + g = #ctx.groups + end + if local_(n) == "switch" then + -- the first child that renders (conditional attributes are not evaluated) + for _, c in __iter(children or Xml.children(n)) do + if UNSUPPORTED[local_(c)] == nil then + walk(c, st, ctm, g, ctx) + return + end + end + return + end + for _, c in __iter(children or Xml.children(n)) do + walk(c, st, ctm, g, ctx) + end +end + +-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own +local function viewportGroup(n, m, x, y, w, h, group, ctx) +local ov = attr(n, "overflow") + if ov == "visible" or ov == "auto" then + return group + end + local rect = { { op = "M", x, y }, { op = "L", x + w, y }, { op = "L", x + w, y + h }, { op = "L", x, y + h }, { op = "Z" } } + table.insert(ctx.clips, { paths = { { d = rect, transform = m, rule = "nonzero" } } }) + table.insert(ctx.groups, { opacity = 1, parent = group, clip = #ctx.clips }) + return #ctx.groups +end + +walk = function(n, parentStyle, ctm, group, ctx) + if ctx.depth > 200 then + return + end + local kind = local_(n) + if kind == "defs" or kind == "clipPath" or kind == "linearGradient" or kind == "radialGradient" or kind == "symbol" or kind == "style" or kind == "title" or kind == "desc" or kind == "metadata" then + return + end + local st = computed(parentStyle, n, ctx) + if st.display == "none" then + return + end + if UNSUPPORTED[kind] then + ctx.unsupported[kind] = (ctx.unsupported[kind] or 0) + 1 + return + end + ctx.depth =ctx.depth+ 1 + if CONTAINERS[kind] then + container(n, st, mul(ctm, transformOf(n)), group, ctx) + elseif SHAPES[kind] then + emitShape(n, st, ctm, group, ctx) + elseif kind == "use" then + local h = refId(href(n)) + local target = (h and{ctx.ids[h] }or{nil +})[1] if target and ctx.useDepth < 16 then + ctx.useDepth =ctx.useDepth+ 1 + local x, y = (len(attr(n, "x"), ctx.vw, st, 0) ), (len(attr(n, "y"), ctx.vh, st, 0) ) +local m = mul(mul(ctm, transformOf(n)), { 1, 0, 0, 1, x, y }) + local tk = local_(target) + if tk == "symbol" or tk == "svg" then + local w = (len(attr(n, "width") or attr(target, "width") or "100%", ctx.vw, st, ctx.vw) ) +local h2 = (len(attr(n, "height") or attr(target, "height") or "100%", ctx.vh, st, ctx.vh) ) +local vb = viewBox(target) + local inner = mul(m, Parse.viewTransform(vb, attr(target, "preserveAspectRatio"), 0, 0, w, h2)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + end + local tst = computed(st, target, ctx) + -- the use element's own opacity applies to the symbol's content too + local uo = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1) + if uo < 1 then + tst.opacity = tostring(uo * math.clamp(tonumber(tst.opacity or "1") or 1, 0, 1)) + end + if tst["clip-path"] == nil then + tst["clip-path"] = st["clip-path"] + end + -- the symbol's children as a group of the use element, clipped to its viewport + local vg = viewportGroup(target, m, 0, 0, w, h2, group, ctx) + container(n, tst, mul(inner, transformOf(target)), vg, ctx, Xml.children(target)) + ctx.vw, ctx.vh = saveW, saveH + else + -- the referenced element as if it were the use element's only child + container(n, st, m, group, ctx, { target }) + end + ctx.useDepth =ctx.useDepth- 1 + end + elseif kind == "svg" then + local x, y = (len(attr(n, "x"), ctx.vw, st, 0) ), (len(attr(n, "y"), ctx.vh, st, 0) ) +local w = (len(attr(n, "width") or "100%", ctx.vw, st, ctx.vw) ) +local h = (len(attr(n, "height") or "100%", ctx.vh, st, ctx.vh) ) +local vb = viewBox(n) + local m = mul(ctm, Parse.viewTransform(vb, attr(n, "preserveAspectRatio"), x, y, w, h)) + local saveW, saveH = ctx.vw, ctx.vh + if vb then + ctx.vw, ctx.vh = vb[3], vb[4] + else + ctx.vw, ctx.vh = w, h + end + container(n, st, m, viewportGroup(n, ctm, x, y, w, h, group, ctx), ctx) + ctx.vw, ctx.vh = saveW, saveH + end + ctx.depth =ctx.depth- 1 +end + +-- ------------------------------------------------------------------------------------------------ entry +-- document(doc, opts) -> Vector | nil, message +function Parse.document(doc) +local root = doc.root + if root == nil or Xml.localName(root.name) ~= "svg" then + return nil, "the root element is not <svg>" + end + local ids= {} + local rules= {} + local count = 0 + local function index(n) + count =count+ 1 + if count > 1000000 then + return + end + local id = attr(n, "id") + if id and ids[id] == nil then + ids[id] = n + end + if local_(n) == "style" then + Style.css(Xml.text(n), rules) + end + for _, c in __iter(Xml.children(n)) do + index(c) + end + end + index(root) + local vb = viewBox(root) + local w = Style.length(attr(root, "width") or "100%", (vb and{vb[3] }or{100})[1]) or 100 + local h = Style.length(attr(root, "height") or "100%", (vb and{vb[4] }or{100})[1]) or 100 + if w <= 0 or h <= 0 then + w, h = 100, 100 + end + local v = Types.Vector.new(w, h) + v.viewBox = vb or { 0, 0, w, h } + local ctx= { + ids = ids, + rules = rules, + vector = v, + groups = {}, + clips = {}, + unsupported = {}, + vw = v.viewBox[3], + vh = v.viewBox[4], + depth = 0, + useDepth = 0, + } + local st = computed(INHERITED, root, ctx) + container(root, st, IDENTITY, nil, ctx) + v.meta.preserveAspectRatio = attr(root, "preserveAspectRatio") + v.meta.groups = ctx.groups + v.meta.clips = ctx.clips + if next(ctx.unsupported) then + v.meta.unsupported = ctx.unsupported + end + return v, nil +end + +return Parse +end +__FILES["vector/svg/PathData"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands +-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the +-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a +-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the +-- commands so far are kept, as the spec's error handling says). +local PathData = {} + + + +local byte, sub, find = string.byte, string.sub, string.find +local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math.sin, math.atan2, math.ceil, math.pi + +local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 } + +-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out +local function arc(x1, y1, rx, ry, phiDeg, fa, fs, x2, y2, out) + if x1 == x2 and y1 == y2 then + return + end + rx, ry = abs(rx), abs(ry) + if rx == 0 or ry == 0 then + table.insert(out, { op = "L", x2, y2 }) + return + end + local phi = phiDeg % 360 * pi / 180 + local cp, sp = cos(phi), sin(phi) + local dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + local x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + local lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry) + if lambda > 1 then + local s = sqrt(lambda) + rx, ry = rx * s, ry * s + end + local num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + local den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + local coef = den == 0 and 0 or sqrt(math.max(0, num / den)) + if fa == fs then + coef = -coef + end + local cxp, cyp = coef * rx * y1p / ry, -coef * ry * x1p / rx + local cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + local function angle(ux, uy, vx, vy) +return atan2(ux * vy - uy * vx, ux * vx + uy * vy) + end + local ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry + local vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry + local t1 = angle(1, 0, ux, uy) + local dt = angle(ux, uy, vx, vy) + if not fs and dt > 0 then + dt =dt- 2 * pi + elseif fs and dt < 0 then + dt =dt+ 2 * pi + end + local n = math.max(1, ceil(abs(dt) / (pi / 2) - 1e-9)) + local step = dt / n + local k = 4 / 3 * math.tan(step / 4) + local px, py = x1, y1 + for i = 1, n do + local a0 = t1 + (i - 1) * step + local a1 = t1 + i * step + local c0, s0, c1, s1 = cos(a0), sin(a0), cos(a1), sin(a1) + -- the unit-circle segment's control points, scaled by the radii, rotated by phi, moved to the centre + local e1x, e1y = c0 - k * s0, s0 + k * c0 + local e2x, e2y = c1 + k * s1, s1 - k * c1 + local ex, ey = c1, s1 + local function map(x, y) +x, y = x * rx, y * ry + return cp * x - sp * y + cx, sp * x + cp * y + cy + end + local ax, ay = map(e1x, e1y) + local bx, by = map(e2x, e2y) + local qx, qy = map(ex, ey) + if i == n then + qx, qy = x2, y2 + end + table.insert(out, { op = "C", ax, ay, bx, by, qx, qy }) + px, py = qx, qy + end + local _ = px + py +end +PathData.arc = arc + +-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing) +function PathData.parse(d) +local out= {} + local i, n = 1, #d + local cx, cy = 0, 0 -- current point + local sx, sy = 0, 0 -- subpath start + local lcx, lcy = 0, 0 -- last control point (for S / T) + local last = "" -- previous command letter (upper case) + local cmd= nil + local rel = false + local nums= (table.create(7) ) +local function ws() + while i <= n do + local c = byte(d, i) + if c == 32 or c == 9 or c == 10 or c == 13 or c == 12 then + i =i+ 1 + else + break + end + end + end + local function comma() + ws() + if i <= n and byte(d, i) == 44 then + i =i+ 1 + ws() + end + end + local function digits() +local any = false + while i <= n do + local c = byte(d, i) + if c >= 48 and c <= 57 then + i =i+ 1 + any = true + else + break + end + end + return any + end + -- an SVG number: sign? (digits ("." digits?)? | "." digits) exponent?; "1.5.5" is 1.5 then .5 + local function number() +ws() + local s = i + local c = byte(d, i) + if c == 43 or c == 45 then + i =i+ 1 + end + local whole = digits() + local frac = false + if i <= n and byte(d, i) == 46 then + i =i+ 1 + frac = digits() + end + if not whole and not frac then + i = s + return nil + end + c = byte(d, i) + if c == 101 or c == 69 then + local save = i + i =i+ 1 + c = byte(d, i) + if c == 43 or c == 45 then + i =i+ 1 + end + if not digits() then + i = save + end + end + return tonumber(sub(d, s, i - 1)) + end + local function flag() +ws() + local c = byte(d, i) + if c == 48 or c == 49 then + i =i+ 1 + return c - 48 + end + return nil + end + while true do +local __DARKLUA_CONTINUE_4=false repeat ws() + if i > n then + break + end + local c = sub(d, i, i) + local up = string.upper(c) + if ARGS[up] ~= nil and find(c, "%a") then + cmd = up + rel = c ~= up + i =i+ 1 + if up == "Z" then + table.insert(out, { op = "Z" } ) + cx, cy = sx, sy + last = "Z" + cmd = nil +__DARKLUA_CONTINUE_4=true break + end + elseif cmd == nil then + return out, false + end + local c2 = cmd +local na = ARGS[c2] + for k = 1, na do + local v = (c2 == "A" and (k == 4 or k == 5) and{(flag() )}or{(number() +)})[1] if v == nil then + return out, false + end + nums[k] = v + if k < na then + comma() + end + end + comma() + local ox, oy = (rel and{cx }or{0})[1], (rel and{cy }or{0 +})[1] if c2 == "M" then + cx, cy = nums[1] + ox, nums[2] + oy + sx, sy = cx, cy + table.insert(out, { op = "M", cx, cy }) + cmd = "L" -- further pairs are line-tos + elseif c2 == "L" then + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "H" then + cx = nums[1] + ox + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "V" then + cy = nums[1] + ((rel and{cy }or{0})[1]) + table.insert(out, { op = "L", cx, cy }) + elseif c2 == "C" then + local x1, y1, x2, y2 = nums[1] + ox, nums[2] + oy, nums[3] + ox, nums[4] + oy + cx, cy = nums[5] + ox, nums[6] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "S" then + local x1, y1 = cx, cy + if last == "C" or last == "S" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + local x2, y2 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "C", x1, y1, x2, y2, cx, cy }) + lcx, lcy = x2, y2 + elseif c2 == "Q" then + local x1, y1 = nums[1] + ox, nums[2] + oy + cx, cy = nums[3] + ox, nums[4] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "T" then + local x1, y1 = cx, cy + if last == "Q" or last == "T" then + x1, y1 = 2 * cx - lcx, 2 * cy - lcy + end + cx, cy = nums[1] + ox, nums[2] + oy + table.insert(out, { op = "Q", x1, y1, cx, cy }) + lcx, lcy = x1, y1 + elseif c2 == "A" then + local x2, y2 = nums[6] + ox, nums[7] + oy + arc(cx, cy, nums[1], nums[2], nums[3], nums[4] ~= 0, nums[5] ~= 0, x2, y2, out) + cx, cy = x2, y2 + end + last = c2 == "M" and"M" or c2 +__DARKLUA_CONTINUE_4=true until true if not __DARKLUA_CONTINUE_4 then break end end + return out, true +end + +-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box +-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves +function PathData.bounds(cmds) +local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge + local px, py = 0, 0 + for _, c in __iter(cmds) do + local op = c.op + if op == "C" then + -- the curve's exact extrema + local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6] + for axis = 1, 2 do + local p0 = (axis == 1 and{px }or{py +})[1] local p1 = (axis == 1 and{ax }or{ay +})[1] local p2 = (axis == 1 and{bx }or{by +})[1] local p3 = (axis == 1 and{ex }or{ey +})[1] local a = -p0 + 3 * p1 - 3 * p2 + p3 + local b = 2 * (p0 - 2 * p1 + p2) + local cc = p1 - p0 + local ts = {} + if abs(a) < 1e-12 then + if abs(b) > 1e-12 then + table.insert(ts, -cc / b) + end + else + local disc = b * b - 4 * a * cc + if disc >= 0 then + local s = sqrt(disc) + table.insert(ts, (-b + s) / (2 * a)) + table.insert(ts, (-b - s) / (2 * a)) + end + end + for _, t in __iter(ts) do + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * mt * p0 + 3 * mt * mt * t * p1 + 3 * mt * t * t * p2 + t * t * t * p3 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "Q" then + local ax, ay, ex, ey = c[1], c[2], c[3], c[4] + for axis = 1, 2 do + local p0 = (axis == 1 and{px }or{py +})[1] local p1 = (axis == 1 and{ax }or{ay +})[1] local p2 = (axis == 1 and{ex }or{ey +})[1] local den = p0 - 2 * p1 + p2 + if abs(den) > 1e-12 then + local t = (p0 - p1) / den + if t > 0 and t < 1 then + local mt = 1 - t + local v = mt * mt * p0 + 2 * mt * t * p1 + t * t * p2 + if axis == 1 then + x0, x1 = math.min(x0, v), math.max(x1, v) + else + y0, y1 = math.min(y0, v), math.max(y1, v) + end + end + end + end + px, py = ex, ey + elseif op == "M" or op == "L" then + px, py = c[1], c[2] + end + if op ~= "Z" then + x0, x1 = math.min(x0, px), math.max(x1, px) + y0, y1 = math.min(y0, py), math.max(y1, py) + end + end + if x0 > x1 then + return nil, nil, nil, nil + end + return x0, y0, x1, y1 +end + +-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros) +local function num(v) +if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + local r = math.floor(v * 10000 + 0.5) / 10000 + if r == math.floor(r) and abs(r) < 1e15 then + return string.format("%d", r) + end + local s = string.format("%.4f", r) + s = string.gsub(s, "0+$", "") + return s +end +PathData.num = num + +-- serialize(cmds) -> path data text +function PathData.serialize(cmds) +local out = {} + for _, c in __iter(cmds) do + local k = ARGS[c.op] + if k ~= nil then + local parts = { c.op } + local cnt = c.op == "C" and 6 or(c.op == "Q" and 4 or(c.op == "Z" and 0 or 2 +)) for j = 1, cnt do + table.insert(parts, num(tonumber(c[j]) or 0)) + end + table.insert(out, table.concat(parts, " ")) + end + end + return table.concat(out, " ") +end + +-- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close) +local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" } +function PathData.toRaster(cmds) +local out = table.create(#cmds) + for i, c in __iter(cmds) do + local r= { op = RASTER[c.op] or "close" } + for j = 1, #c do + r[j] = c[j] + end + out[i] = r + end + return out +end + +return PathData +end +__FILES["vector/svg/Render"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd, +-- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and +-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat, +-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox +-- maps onto the image by meta.preserveAspectRatio. Never throws. +local Types = __include("Types") +local Raster = __include("codecs/image/Raster") +local Blend = __include("codecs/image/Blend") +local PathData = __include("vector/svg/PathData") +local Parse = __include("vector/svg/Parse") + +local Render = {} + + + +local function mul(m, n) +return Raster.multiply(m, n) +end + +-- ------------------------------------------------------------------------------------------------ gradients +local function stopColor(stops, t) +local n = #stops + if t <= stops[1][1] then + local s = stops[1] + return s[2], s[3], s[4], s[5] + end + if t >= stops[n][1] then + local s = stops[n] + return s[2], s[3], s[4], s[5] + end + for i = 2, n do + local b = stops[i] + if t <= b[1] then + local a = stops[i - 1] + local span = b[1] - a[1] + local f = (span > 0 and(((t - a[1]) / span ))or(1 +)) return a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f, a[4] + (b[4] - a[4]) * f, a[5] + (b[5] - a[5]) * f + end + end + local s = stops[n] + return s[2], s[3], s[4], s[5] +end + +-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds +local function gradientFn(p, device, bbox) +local stops = p.stops + if type(stops) ~= "table" or #stops == 0 then + return nil + end + local g= { 1, 0, 0, 1, 0, 0 } + if p.units ~= "userSpaceOnUse" then + if not bbox or bbox[3] - bbox[1] <= 0 or bbox[4] - bbox[2] <= 0 then + return nil -- a zero-size box: the gradient is not rendered + end + g = { bbox[3] - bbox[1], 0, 0, bbox[4] - bbox[2], bbox[1], bbox[2] } + end + if type(p.transform) == "table" then + g = mul(g, p.transform) + end + local inv = Raster.invert(mul(device, g)) + if not inv then + return nil + end + local a, b, c, d, e, f = inv[1], inv[2], inv[3], inv[4], inv[5], inv[6] + local spread = p.spread + local opacity = tonumber(p.opacity) or 1 + local function wrap(t) +if spread == "repeat" then + return t - math.floor(t) + elseif spread == "reflect" then + local r = t % 2 + return (r > 1 and((2 - r ))or(r +)) end + return t + end + if p.type == "linear" then + local x1, y1, x2, y2 = p.x1 or 0, p.y1 or 0, p.x2 or 1, p.y2 or 0 + local dx, dy = x2 - x1, y2 - y1 + local dd = dx * dx + dy * dy + if dd == 0 then + local r, gg, bb, aa = stopColor(stops, 1) + return function() +return r, gg, bb, aa * opacity + end + end + return function(x, y) +local gx, gy = a * x + c * y + e, b * x + d * y + f + local t = wrap(((gx - x1) * dx + (gy - y1) * dy) / dd) + local r, gg, bb, aa = stopColor(stops, t) + return r, gg, bb, aa * opacity + end + end + local cx, cy, r = p.cx or 0.5, p.cy or 0.5, p.r or 0.5 + local fx, fy = p.fx or cx, p.fy or cy + if r <= 0 then + local rr, gg, bb, aa = stopColor(stops, 1) + return function() +return rr, gg, bb, aa * opacity + end + end + -- SVG 1.1: a focal point outside the circle moves onto it + local fdx, fdy = fx - cx, fy - cy + local fd = math.sqrt(fdx * fdx + fdy * fdy) + if fd > r * 0.999 then + local k = r * 0.999 / fd + fx, fy = cx + fdx * k, cy + fdy * k + end + return function(x, y) +local gx, gy = a * x + c * y + e, b * x + d * y + f + local dx, dy = gx - fx, gy - fy + local t + if dx == 0 and dy == 0 then + t = 0 + else + -- the ray from the focus through the point meets the circle at s: t = 1 / s + local ox, oy = fx - cx, fy - cy + local qa = dx * dx + dy * dy + local qb = 2 * (dx * ox + dy * oy) + local qc = ox * ox + oy * oy - r * r + local disc = qb * qb - 4 * qa * qc + local s = (-qb + math.sqrt(math.max(0, disc))) / (2 * qa) + t = (s > 0 and((1 / s ))or(1 +)) end + local rr, gg, bb, aa = stopColor(stops, wrap(t)) + return rr, gg, bb, aa * opacity + end +end + +-- ------------------------------------------------------------------------------------------------ dashes +-- subpaths of a command list with their closed flag +local function subpaths(cmds) +local out = {} + local cur= nil + for _, c in __iter(cmds) do + if c.op == "M" then + cur = { c } + table.insert(out, { cmds = cur, closed = false }) + elseif c.op == "Z" then + if cur then + out[#out].closed = true + -- a new subpath starts at the same point if more segments follow + local first = (cur )[1] + cur = { { op = "M", first[1], first[2] } } + table.insert(out, { cmds = cur, closed = false }) + end + elseif cur then + table.insert(cur, c) + end + end + return out +end + +-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol) +local function polyline(cmds, tol) +local pts= {} + local px, py = 0, 0 + for _, c in __iter(cmds) do + local op = c.op + if op == "M" or op == "L" then + px, py = c[1], c[2] + table.insert(pts, px) + table.insert(pts, py) + elseif op == "Q" or op == "C" then + local len = 0 + local lx, ly = px, py + for k = 1, #c - 1, 2 do + len =len+ math.sqrt((c[k] - lx) ^ 2 + (c[k + 1] - ly) ^ 2) + lx, ly = c[k], c[k + 1] + end + local steps = math.clamp(math.ceil(math.sqrt(len / math.max(tol, 1e-4))), 1, 512) + for i = 1, steps do + local t = i / steps + local mt = 1 - t + local x, y + if op == "Q" then + x = mt * mt * px + 2 * mt * t * c[1] + t * t * c[3] + y = mt * mt * py + 2 * mt * t * c[2] + t * t * c[4] + else + x = mt * mt * mt * px + 3 * mt * mt * t * c[1] + 3 * mt * t * t * c[3] + t * t * t * c[5] + y = mt * mt * mt * py + 3 * mt * mt * t * c[2] + 3 * mt * t * t * c[4] + t * t * t * c[6] + end + table.insert(pts, x) + table.insert(pts, y) + end + px, py = c[#c - 1], c[#c] + end + end + return pts +end + +local function dashed(cmds, dashes, offset, tol) +local out = {} + local total = 0 + for _, v in __iter(dashes) do + total =total+ v + end + if total <= 0 then + return cmds + end + for _, sp in __iter(subpaths(cmds)) do +local __DARKLUA_CONTINUE_7=false repeat if #sp.cmds < 2 then +__DARKLUA_CONTINUE_7=true break + end + local pts = polyline(sp.cmds, tol) + if #pts < 4 then +__DARKLUA_CONTINUE_7=true break + end + if sp.closed then + table.insert(pts, pts[1]) + table.insert(pts, pts[2]) + end + -- dash state at the start (offset wraps through the pattern) + local idx, left = 1, 0 + local o = offset % total + if o < 0 then + o =o+ total + end + while o > 0 do + if o >= dashes[idx] then + o =o- dashes[idx] + idx = idx % #dashes + 1 + else + break + end + end + left = dashes[idx] - o + local on = idx % 2 == 1 + local cur= nil + if on then + cur = { { op = "M", pts[1], pts[2] } } + end + for i = 1, #pts - 3, 2 do + local x0, y0, x1, y1 = pts[i], pts[i + 1], pts[i + 2], pts[i + 3] + local seg = math.sqrt((x1 - x0) ^ 2 + (y1 - y0) ^ 2) + local pos = 0 + local guard = 0 + while seg - pos > left and guard < 100000 do + guard =guard+ 1 + pos =pos+ left + local t = pos / seg + local x, y = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + if on then + table.insert(cur , { op = "L", x, y }) + for _, c in __iter(cur) do + table.insert(out, c) + end + cur = nil + else + cur = { { op = "M", x, y } } + end + on = not on + idx = idx % #dashes + 1 + left = dashes[idx] + end + left =left- (seg - pos +) if on and cur then + table.insert(cur, { op = "L", x1, y1 }) + end + end + if on and cur and #cur > 1 then + for _, c in __iter(cur) do + table.insert(out, c) + end + end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + return out +end +-- ------------------------------------------------------------------------------------------------ rendering +-- the device transform scale (for stroke flattening tolerances) + + + + + + +local function scaleOf(m) +return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3])) +end + +-- rasterize(v, w, h, opts?) -> rgba8 Image +function Render.rasterize(v, w, h, opts) +local o= opts or {} + local img = Types.Image.new(w, h) + local px = img.pixels + local n = w * h + local bg = o.background + if type(bg) == "table" then + local val = (bg[1] or 0) + (bg[2] or 0) * 256 + (bg[3] or 0) * 65536 + (bg[4] or 255) * 16777216 + for i = 0, n - 1 do + buffer.writeu32(px, i * 4, val) + end + end + local meta= (type(v.meta) == "table" and{v.meta }or{{} +})[1] local view = Parse.viewTransform(v.viewBox, meta.preserveAspectRatio, 0, 0, w, h) + local groups= (type(meta.groups) == "table" and{meta.groups }or{{} +})[1] local clips= (type(meta.clips) == "table" and{meta.clips }or{{} +})[1] local tol = o.tolerance or 0.1 + local clipCache= {} + -- a clip's coverage over the whole image (1 byte per pixel) + local function clipMask(id) +if clipCache[id] then + return clipCache[id] + end + local c = clips[id] + if type(c) ~= "table" then + return nil + end + local mask = buffer.create(n) + for _, cp in __iter(((type(c.paths) == "table" and{c.paths }or{{}})[1])) do + local m = Raster.mask(PathData.toRaster(cp.d), { transform = mul(view, cp.transform or Raster.IDENTITY), rule = cp.rule, clip = { 0, 0, w, h }, tolerance = tol }) + if m then + for y = 0, m.height - 1 do + for x = 0, m.width - 1 do + local cv = buffer.readu8(m.coverage, y * m.width + x) + if cv > 0 then + local i = (m.y + y) * w + m.x + x + local old = buffer.readu8(mask, i) + buffer.writeu8(mask, i, math.min(255, old + cv - math.floor(old * cv / 255 + 0.5))) + end + end + end + end + end + clipCache[id] = mask + return mask + end + -- the layer stack: { group id, image } + local stack= { { id = nil, img = img } } + local function chain(g) +local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = (type(gr) == "table" and{gr.parent }or{nil +})[1] guard =guard+ 1 + end + return out + end + local function pop() + local top = (table.remove(stack) ) +local below = stack[#stack].img + local gr = groups[top.id] or {} + local mask= nil + if gr.clip then + local cm = clipMask(gr.clip) + mask = cm and{ pixels = cm, width = w, height = h, x = 0, y = 0, default = 0 } or{ default = 0 } + end + Blend.composite(below.pixels, w, h, top.img.pixels, w, h, 0, 0, math.clamp(tonumber(gr.opacity) or 1, 0, 1), "normal", { mask = mask }) + end + local function draw(target, cmds, paint, device, rule, opacity, bbox) + local fill +if paint.type == "color" then + fill = paint.color + else + fill = gradientFn(paint, device, bbox) + if not fill then + return + end + end + Raster.fill(target, cmds, fill, { transform = device, rule = rule, opacity = opacity, tolerance = tol }) + end + for _, p in __iter(v.paths) do +local __DARKLUA_CONTINUE_18=false repeat if type(p) ~= "table" or type(p.d) ~= "table" then +__DARKLUA_CONTINUE_18=true break + end + -- groups: pop the layers this path is not in, push the ones it needs + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep =keep+ 1 + end + while #stack > keep do + pop() + end + for k = keep, #want do + table.insert(stack, { id = want[k], img = Types.Image.new(w, h) }) + end + local device = mul(view, p.transform or Raster.IDENTITY) + local target = stack[#stack].img + local clipMaskBuf= nil + if p.clip then + clipMaskBuf = clipMask(p.clip) + if not clipMaskBuf then +__DARKLUA_CONTINUE_18=true break + end + target = Types.Image.new(w, h) + end + local opacity = math.clamp(tonumber(p.opacity) or 1, 0, 1) + local rcmds = PathData.toRaster(p.d) + local bbox= nil + if (p.fill and p.fill.type ~= "color") or (p.stroke and p.stroke.type ~= "color") then + local x0, y0, x1, y1 = PathData.bounds(p.d) + if x0 then + bbox = { x0 , y0 , x1 , y1 } + end + end + if type(p.fill) == "table" then + draw(target, rcmds, p.fill, device, p.fillRule, opacity, bbox) + end + if type(p.stroke) == "table" and (tonumber(p.strokeWidth) or 1) > 0 then + local scale = math.max(scaleOf(device), 1e-6) + local src = p.d + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + src = dashed(p.d, p.strokeDashArray, tonumber(p.strokeDashOffset) or 0, tol / scale) + end + local outline = Raster.stroke(PathData.toRaster(src), { + width = tonumber(p.strokeWidth) or 1, + join = p.strokeLineJoin, + cap = p.strokeLineCap, + miterLimit = p.strokeMiterLimit, + tolerance = tol / scale, + }) + draw(target, outline, p.stroke, device, "nonzero", opacity, bbox) + end + if clipMaskBuf then + Blend.composite(stack[#stack].img.pixels, w, h, target.pixels, w, h, 0, 0, 1, "normal", { mask = { pixels = clipMaskBuf, width = w, height = h, x = 0, y = 0, default = 0 } }) + end +__DARKLUA_CONTINUE_18=true until true if not __DARKLUA_CONTINUE_18 then break end end + while #stack > 1 do + pop() + end + return img +end + +return Render +end +__FILES["vector/svg/Style"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba / +-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor), +-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated +-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped). +-- Never throws. +local Raster = __include("codecs/image/Raster") +local Style = {} + +local NAMED= { + aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff, + beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff, + blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00, + chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c, + cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9, + darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f, + darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f, + darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1, + darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff, + gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080, + grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4, + indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa, + lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080, + lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90, + lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa, + lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de, + lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff, + maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3, + mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a, + mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa, + mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6, + olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6, + palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093, + papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd, + powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f, + royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57, + seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd, + slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4, + tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee, + wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32, +} + +local function clamp255(v) +return math.clamp(math.floor(v + 0.5), 0, 255) +end + +local function hue(p, q, t) +t =t% 1 + if t < 1 / 6 then + return p + (q - p) * 6 * t + elseif t < 1 / 2 then + return q + elseif t < 2 / 3 then + return p + (q - p) * (2 / 3 - t) * 6 + end + return p +end + +-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value +function Style.color(s, current) +s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1"))) + if s == "none" then + return "none" + elseif s == "transparent" then + return { 0, 0, 0, 0 } + elseif s == "currentcolor" then + return current or { 0, 0, 0, 255 } + end + local hex = string.match(s, "^#(%x+)$") + if hex then + local n = #hex + if n == 3 or n == 4 then + local v = {} + for k = 1, n do + v[k] = ((tonumber(string.sub(hex, k, k), 16) )) * 17 + end + return { v[1], v[2], v[3], v[4] or 255 } + elseif n == 6 or n == 8 then + local v = {} + for k = 1, math.floor(n / 2 )do + v[k] = (tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) ) +end + return { v[1], v[2], v[3], v[4] or 255 } + end + return nil + end + local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$") + if fn then + local parts = {} + for p in __iter(string.gmatch(args , "[^,%s/]+")) do + table.insert(parts, p) + end + local function comp(p, scale) +if p == nil then + return nil + end + local pct = string.match(p, "^([%d.eE+-]+)%%$") + if pct then + local v = tonumber(pct) + return (v and((v / 100 * scale ))or(nil +)) end + return tonumber(p) + end + local function alpha(p) +if p == nil then + return 255 + end + local v = comp(p, 1) + return clamp255((v or 1) * 255) + end + if fn == "rgb" or fn == "rgba" then + local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255) + if not (r and g and b) then + return nil + end + return { clamp255(r ), clamp255(g ), clamp255(b ), alpha(parts[4]) } + elseif fn == "hsl" or fn == "hsla" then + local h = tonumber((string.gsub(parts[1] or "", "deg$", ""))) + local sat, l = comp(parts[2], 1), comp(parts[3], 1) + if not (h and sat and l) then + return nil + end + local hh = (h ) / 360 + local ss, ll = math.clamp(sat , 0, 1), math.clamp(l , 0, 1) + local q = (ll < 0.5 and((ll * (1 + ss) ))or((ll + ss - ll * ss +))) local p = 2 * ll - q + return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) } + end + return nil + end + local v = NAMED[s] + if v then + return { math.floor(v / 65536), math.floor(v / 256 )% 256, v % 256, 255 } + end + return nil +end + +-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil +local function scan(s, i) +local n = #s + local st = i + local c = string.byte(s, i) + if c == 43 or c == 45 then + i =i+ 1 + end + local any = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i =i+ 1 + any = true + else + break + end + end + if i <= n and string.byte(s, i) == 46 then + i =i+ 1 + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i =i+ 1 + any = true + else + break + end + end + end + if not any then + return nil, st + end + c = string.byte(s, i) + if c == 101 or c == 69 then + local save = i + i =i+ 1 + c = string.byte(s, i) + if c == 43 or c == 45 then + i =i+ 1 + end + local e = false + while i <= n do + c = string.byte(s, i) + if c >= 48 and c <= 57 then + i =i+ 1 + e = true + else + break + end + end + if not e then + i = save + end + end + return tonumber(string.sub(s, st, i - 1)), i +end + +-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100) +local UNITS= { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 } +function Style.length(s, ref, fontSize) +if s == nil then + return nil + end + local t = (string.match(s, "^%s*(.-)%s*$") ) +local x, j = scan(t, 1) + if x == nil then + return nil + end + local u = string.lower(string.sub(t, j)) + if u == "" then + return x + elseif u == "%" then + return x / 100 * (ref or 100) + elseif u == "em" then + return x * (fontSize or 16) + elseif u == "ex" then + return x * (fontSize or 16) / 2 + end + local k = UNITS[u] + return (k and((x * k ))or(nil +))end + +-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else +function Style.numbers(s) +local out = {} + if s == nil then + return out + end + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then + i =i+ 1 + else + local v, j = scan(s, i) + if v == nil then + break + end + table.insert(out, v) + i = j + end + end + return out +end + +-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error +local mul = Raster.multiply +Style.multiply = mul +function Style.transform(s) +local m = { 1, 0, 0, 1, 0, 0 } + local rest = s + while true do + rest = string.gsub(rest, "^[%s,]+", "") + if rest == "" then + break + end + local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$") + if not name then + return nil + end + rest = after +local v = Style.numbers(string.sub(args , 2, -2)) + local t +if name == "matrix" and #v == 6 then + t = v + elseif name == "translate" and (#v == 1 or #v == 2) then + t = { 1, 0, 0, 1, v[1], v[2] or 0 } + elseif name == "scale" and (#v == 1 or #v == 2) then + t = { v[1], 0, 0, v[2] or v[1], 0, 0 } + elseif name == "rotate" and (#v == 1 or #v == 3) then + local r = v[1] * math.pi / 180 + local c, sn = math.cos(r), math.sin(r) + t = { c, sn, -sn, c, 0, 0 } + if #v == 3 then + t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] }) + end + elseif name == "skewX" and #v == 1 then + t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 } + elseif name == "skewY" and #v == 1 then + t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 } + else + return nil + end + m = mul(m, t) + end + return m +end + +-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped) +function Style.declarations(s) +local out= {} + for decl in __iter(string.gmatch(s, "[^;]+")) do + local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$") + if k and v then + v = string.gsub(v , "%s*!important$", "") + out[string.lower(k )] = v +end + end + return out +end +-- ------------------------------------------------------------------------------------------------ CSS + + + + +local function selector(s) +s = string.gsub(s, "^%s*(.-)%s*$", "%1") + if s == "" or string.find(s, "[%s>+~%[:]") then + return nil -- combinators, attribute and pseudo selectors: not supported + end + local sel= { classes = {}, specificity = 0 } + local tag = string.match(s, "^([%a_][%w_-]*)") + if tag then + sel.tag = tag + sel.specificity =sel.specificity+ 1 + s = string.sub(s, #tag + 1) + elseif string.sub(s, 1, 1) == "*" then + s = string.sub(s, 2) + end + while s ~= "" do + local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$") + if not kind then + return nil + end + if kind == "." then + table.insert(sel.classes, name ) + sel.specificity =sel.specificity+ 100 + else + sel.id = name + sel.specificity =sel.specificity+ 10000 + end + s = rest +end + return sel +end + +-- css(text, rules?) -> rules (appended to the list given) +function Style.css(text, rules) +local out= rules or {} + text = string.gsub(text, "/%*.-%*/", "") + text = string.gsub(text, "<!%-%-", "") + text = string.gsub(text, "%-%->", "") + -- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;) + local guard = 0 + while guard < 100 do + guard =guard+ 1 + local s, e = string.find(text, "@[%w-]+[^{;]*%b{}") + if not s then + break + end + text = string.sub(text, 1, s - 1) .. string.sub(text, (e ) + 1) + end + text = string.gsub(text, "@[%w-]+[^;{]*;", "") + for sels, body in __iter(string.gmatch(text, "([^{}]+)(%b{})")) do + local decls = Style.declarations(string.sub(body , 2, -2)) + for one in __iter(string.gmatch(sels, "[^,]+")) do + local sel = selector(one) + if sel then + table.insert(out, { selector = sel, decls = decls, order = #out + 1 }) + end + end + end + return out +end + +-- matches(sel, tag, id, classes) -> boolean +function Style.matches(sel, tag, id, classes) +if sel.tag and sel.tag ~= tag then + return false + end + if sel.id and sel.id ~= id then + return false + end + for _, c in __iter(sel.classes) do + if not classes[c] then + return false + end + end + return true +end + +return Style +end +__FILES["vector/svg/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients +-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...> +-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local PathData = __include("vector/svg/PathData") + +local Write = {} + +local num = PathData.num + +local function el(name, attrs, children) +local o = Types.object() + for _, kv in __iter(attrs) do + if kv[2] ~= nil then + Types.set(o, kv[1], (type(kv[2]) == "number" and{(num(kv[2]) )}or{(tostring(kv[2]))})[1]) + end + end + return Xml.element(name, o , children) +end + +local function hex(c) +return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255)) +end + +local function matrix(m) +if type(m) ~= "table" or #m < 6 then + return nil + end + if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then + if m[5] == 0 and m[6] == 0 then + return nil + end + return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")" + end + local parts = {} + for k = 1, 6 do + parts[k] = num(tonumber(m[k]) or 0) + end + return "matrix(" .. table.concat(parts, " ") .. ")" +end + +-- write(v) -> SVG text | nil, message +function Write.vector(v) +if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then + return nil, "needs a Vector value" + end + local meta= (type(v.meta) == "table" and{v.meta }or{{} +})[1] local groups= (type(meta.groups) == "table" and{meta.groups }or{{} +})[1] local clips= (type(meta.clips) == "table" and{meta.clips }or{{} +})[1] local defs = {} + local gradients = 0 + -- paints -> attribute values (gradients go to defs) + local function paintAttrs(p, which) +if type(p) ~= "table" then + return { { which, "none" } } + end + if p.type == "color" and type(p.color) == "table" then + local a = p.color[4] or 255 + return { { which, hex(p.color) }, { which .. "-opacity", (a < 255 and{(num(a / 255) )}or{nil })[1]} } + end + if p.type ~= "linear" and p.type ~= "radial" then + return { { which, "none" } } + end + gradients =gradients+ 1 + local id = "g" .. gradients + local kids = {} + for _, s in __iter(((type(p.stops) == "table" and{p.stops }or{{}})[1])) do + local a = s[5] or 255 + table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", (a < 255 and{(num(a / 255) )}or{nil })[1]} })) + end + local attrs= { { "id", id }, { "gradientUnits", p.units == "userSpaceOnUse" and"userSpaceOnUse" or nil } } + if p.type == "linear" then + table.insert(attrs, { "x1", p.x1 or 0 }) + table.insert(attrs, { "y1", p.y1 or 0 }) + table.insert(attrs, { "x2", p.x2 or 1 }) + table.insert(attrs, { "y2", p.y2 or 0 }) + else + table.insert(attrs, { "cx", p.cx or 0.5 }) + table.insert(attrs, { "cy", p.cy or 0.5 }) + table.insert(attrs, { "r", p.r or 0.5 }) + table.insert(attrs, { "fx", p.fx }) + table.insert(attrs, { "fy", p.fy }) + if p.fr and p.fr ~= 0 then + table.insert(attrs, { "fr", p.fr }) + end + end + table.insert(attrs, { "spreadMethod", (p.spread and p.spread ~= "pad" and{p.spread }or{nil })[1]}) + table.insert(attrs, { "gradientTransform", matrix(p.transform) }) + table.insert(defs, el(p.type == "linear" and"linearGradient" or"radialGradient", attrs, kids)) + local op = tonumber(p.opacity) or 1 + return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", (op < 1 and{(num(op) )}or{nil })[1]} } + end + local clipIds= {} + local function clipRef(id) +if id == nil or type(clips[id]) ~= "table" then + return nil + end + if clipIds[id] == nil then + local cid = "c" .. id + clipIds[id] = cid + local kids = {} + for _, cp in __iter(((type(clips[id].paths) == "table" and{clips[id].paths }or{{}})[1])) do + table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", cp.rule == "evenodd" and"evenodd" or nil } })) + end + table.insert(defs, el("clipPath", { { "id", cid } }, kids)) + end + return "url(#" .. clipIds[id] .. ")" + end + local root = {} + -- the open <g> stack: { id, children } + local stack= { { id = nil, kids = root } } + local function chain(g) +local out = {} + local guard = 0 + while g ~= nil and guard < 256 do + table.insert(out, 1, g) + local gr = groups[g] + g = (type(gr) == "table" and{gr.parent }or{nil +})[1] guard =guard+ 1 + end + return out + end + for _, p in __iter(v.paths) do +local __DARKLUA_CONTINUE_6=false repeat if type(p) ~= "table" or type(p.d) ~= "table" then +__DARKLUA_CONTINUE_6=true break + end + local want = chain(p.group) + local keep = 1 + while keep < #stack and stack[keep + 1].id == want[keep] do + keep =keep+ 1 + end + while #stack > keep do + table.remove(stack) + end + for k = keep, #want do + local gr = groups[want[k] ] or {} + local kids = {} + local op = tonumber(gr.opacity) or 1 + table.insert(stack[#stack].kids, el("g", { { "opacity", (op < 1 and{op }or{nil })[1]}, { "clip-path", clipRef(gr.clip) } }, kids)) + table.insert(stack, { id = want[k], kids = kids }) + end + local attrs= { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } } + for _, kv in __iter(paintAttrs(p.fill, "fill")) do + table.insert(attrs, kv) + end + table.insert(attrs, { "fill-rule", p.fillRule == "evenodd" and"evenodd" or nil }) + for _, kv in __iter(paintAttrs(p.stroke, "stroke")) do + if kv[2] ~= "none" then + table.insert(attrs, kv) + end + end + if type(p.stroke) == "table" then + local sw = tonumber(p.strokeWidth) or 1 + table.insert(attrs, { "stroke-width", (sw ~= 1 and{sw }or{nil })[1]}) + table.insert(attrs, { "stroke-linejoin", (p.strokeLineJoin and p.strokeLineJoin ~= "miter" and{p.strokeLineJoin }or{nil })[1]}) + table.insert(attrs, { "stroke-linecap", (p.strokeLineCap and p.strokeLineCap ~= "butt" and{p.strokeLineCap }or{nil })[1]}) + local ml = tonumber(p.strokeMiterLimit) + table.insert(attrs, { "stroke-miterlimit", (ml and ml ~= 4 and{ml }or{nil })[1]}) + if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then + local parts = {} + for k, d in __iter(p.strokeDashArray) do + parts[k] = num(tonumber(d) or 0) + end + table.insert(attrs, { "stroke-dasharray", table.concat(parts , " ") }) + local off = tonumber(p.strokeDashOffset) + table.insert(attrs, { "stroke-dashoffset", (off and off ~= 0 and{off }or{nil })[1]}) + end + end + local op = tonumber(p.opacity) or 1 + table.insert(attrs, { "opacity", (op < 1 and{op }or{nil })[1]}) + local node = el("path", attrs) + local cr = clipRef(p.clip) + if cr then + node = el("g", { { "clip-path", cr } }, { node }) + end + table.insert(stack[#stack].kids, node) +__DARKLUA_CONTINUE_6=true until true if not __DARKLUA_CONTINUE_6 then break end end + local children = {} + if #defs > 0 then + table.insert(children, el("defs", {}, defs)) + end + for _, c in __iter(root) do + table.insert(children, c) + end + local vb = v.viewBox + local vbText = (type(vb) == "table" and #vb == 4 and((num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) ))or(nil +)) local svg = el("svg", { + { "xmlns", "http://www.w3.org/2000/svg" }, + { "width", v.width }, + { "height", v.height }, + { "viewBox", vbText }, + { "preserveAspectRatio", meta.preserveAspectRatio }, + }, children) + local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 }) + if not s then + return nil, tostring(err) + end + return s .. "\n", nil +end + +return Write +end +__FILES["vector/tiled"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map +-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib / +-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles, +-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers, +-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets +-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay +-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the +-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json". +-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external +-- tilesets or images (callers resolve `source` / `imageSource` paths themselves). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Sniff = __include("core/Sniff") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Xml = __include("codecs/text/Xml") +local Json = __include("codecs/text/Json") +local Tmx = __include("vector/tiled/Tmx") +local Tmj = __include("vector/tiled/Tmj") + +-- ------------------------------------------------------------------------------------------------ contract +local Tiled = { + name = "tiled", + category = "vector", + extensions = { "tmx", "tmj", "tsx", "tsj" }, + mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" }, + 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 }, +} + +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + +local function head(r) +local h = Sniff.text(r, 1024) + return h +end + +function Tiled.sniff(r) +local h = head(r) + if string.match(h, "^%s*<") then + if string.find(h, "<map[%s>]") or string.find(h, "<tileset[%s>]") then + return 0.9 + end + return 0 + end + if string.match(h, "^%s*{") then + -- Tiled writes its keys sorted: "type" comes last, so look at the tail too + local n = r:remaining() + local tail = (n > 1024 and{(r:peek(1024, n - 1024) )}or{"" +})[1] for _, part in __iter({ h, tail }) do + if string.find(part, "\"type\"%s*:%s*\"map\"") or string.find(part, "\"type\"%s*:%s*\"tileset\"") then + return 0.8 + end + end + if string.find(h, "\"tilewidth\"", 1, true) and (string.find(h, "\"orientation\"", 1, true) or string.find(h, "\"tilesets\"", 1, true)) then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its +-- meta.tileset is true) | nil, Err +function Tiled.decode(r, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 28 + if r.limit - r.base > maxBytes then + return nil, Err.new(Err.LIMIT, "file is over the byte limit") + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local h = head(r) + local map, msg, unsupported +local flavour + if string.match(h, "^%s*<") then + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local root = (doc ).root + if root == nil then + return nil, Err.new(Err.CORRUPT, "no root element") + end + if root.name == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmx.tileset(root) } + map.meta.tileset = true + flavour = "tsx" + else + map, msg, unsupported = Tmx.read(root) + flavour = "tmx" + end + else + local v, jerr = Json.decode(text) + if v == nil then + return nil, jerr + end + if type(v) == "table" and v.type == "tileset" then + map = Types.TileMap.new(0, 0, 0, 0) + map.tilesets = { Tmj.tileset(v) } + map.meta.tileset = true + flavour = "tsj" + else + map, msg, unsupported = Tmj.read(v) + flavour = "tmj" + end + end + if not map then + return nil, Err.new((unsupported and{Err.UNSUPPORTED }or{Err.CORRUPT})[1], msg or "bad map") + end + map.meta.source = { format = flavour } + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Tiled.encode(map, opts) +if type(map) ~= "table" or type(map.layers) ~= "table" or type(map.tilesets) ~= "table" then + return nil, Err.new(Err.ARG, "needs a TileMap value") + end + local o= opts or {} + local meta= (type(map.meta) == "table" and{map.meta }or{{} +})[1] local fmt = o.format or ((type(meta.source) == "table" and{meta.source.format }or{nil})[1]) or "tmx" + fmt = string.lower(fmt) + if fmt == "tiled" then + fmt = (type(meta.source) == "table" and meta.source.format and{meta.source.format }or{"tmx" +})[1] end + local tilesetOnly = meta.tileset == true or fmt == "tsx" or fmt == "tsj" + if o.encoding and o.encoding ~= "csv" and o.encoding ~= "base64" and o.encoding ~= "xml" then + return nil, Err.new(Err.ARG, "encoding must be csv, base64 or xml") + end + if o.compression and o.compression ~= "zlib" and o.compression ~= "gzip" then + return nil, Err.new(Err.ARG, "compression must be zlib or gzip") + end + local wo= { encoding = o.encoding , compression = o.compression, level = o.level } + if fmt == "tmx" or fmt == "tsx" or fmt == "xml" then + local doc, err +if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + doc = Xml.document(Tmx.tilesetNode(map.tilesets[1], false), { version = "1.0", encoding = "UTF-8" }) + else + doc, err = Tmx.write(map, wo) + end + if not doc then + return nil, Err.new(Err.ARG, err or "bad map") + end + local s, xerr = Xml.encode(doc, { indent = o.indent or 1 }) + if not s then + return nil, xerr + end + return buffer.fromstring(s .. "\n"), nil + elseif fmt == "tmj" or fmt == "tsj" or fmt == "json" then + local v, err +if tilesetOnly then + if not map.tilesets[1] then + return nil, Err.new(Err.ARG, "no tileset to write") + end + v = Tmj.tilesetValue(map.tilesets[1], false) + else + v, err = Tmj.write(map, wo) + end + if v == nil then + return nil, Err.new(Err.ARG, err or "bad map") + end + local indent = (o.indent == 0 and{nil }or{(o.indent or 2) +})[1] local s, jerr = Json.encode(v, { indent = indent }) + if not s then + return nil, jerr + end + return buffer.fromstring(s .. "\n"), nil + end + return nil, Err.new(Err.ARG, "unknown format " .. tostring(fmt) .. " (tmx, tmj, tsx, tsj)") +end + +return Tiled +end +__FILES["vector/tiled/Data"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip) +-- to gids and back; property values and their types; number formatting. Never throws. +local Base64 = __include("core/Base64") +local Deflate = __include("codecs/compress/Deflate") + +local Data = {} + +-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message +function Data.csv(text) +local out = {} + for tok in __iter(string.gmatch(text, "[^,%s]+")) do + local v = tonumber(tok) + if v == nil or v < 0 or v >= 4294967296 or v % 1 ~= 0 then + return nil, "bad gid " .. string.sub(tok, 1, 20) + end + table.insert(out, v) + end + return out, nil +end + +-- base64(text, compression) -> { gid } | nil, message, unsupported? +function Data.base64(text, compression) +local raw, err = Base64.decode(text) + if not raw then + return nil, err, nil + end + local bytes= raw + if compression == "zlib" then + local z, zerr = Deflate.zlib(bytes) + if not z then + return nil, "zlib: " .. tostring(zerr), nil + end + bytes = z + elseif compression == "gzip" then + local z, zerr = Deflate.gunzip(bytes) + if not z then + return nil, "gzip: " .. tostring(zerr), nil + end + bytes = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported", true + end + local n = math.floor(buffer.len(bytes) / 4 +) local out= (table.create(n) ) +for i = 0, n - 1 do + out[i + 1] = buffer.readu32(bytes, i * 4) + end + return out, nil, nil +end + +-- toBase64(gids, compression?, level?) -> text | nil, message +function Data.toBase64(gids, compression, level) +local b = buffer.create(#gids * 4) + for i, g in __iter(gids) do + buffer.writeu32(b, (i - 1) * 4, g % 4294967296) + end + if compression == "zlib" then + local z = Deflate.zlibCompress(b, { level = level or 6 }) + if not z then + return nil, "zlib failed" + end + b = z + elseif compression == "gzip" then + local z = Deflate.gzip(b, { level = level or 6 }) + if not z then + return nil, "gzip failed" + end + b = z + elseif compression ~= nil and compression ~= "" then + return nil, "compression " .. compression .. " is not supported" + end + return Base64.encode(b), nil +end + +-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print +function Data.num(v) +if v % 1 == 0 and math.abs(v) < 2 ^ 53 then + return string.format("%.0f", v) + end + local s = string.format("%.15g", v) + if tonumber(s) ~= v then + s = string.format("%.17g", v) + end + return s +end + +-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line) +function Data.csvText(gids, width) +local rows = {} + local row = {} + for i, g in __iter(gids) do + table.insert(row, Data.num(g)) + if width > 0 and i % width == 0 then + table.insert(rows, table.concat(row, ",")) + row = {} + end + end + if #row > 0 then + table.insert(rows, table.concat(row, ",")) + end + return "\n" .. table.concat(rows, ",\n") .. "\n" +end + +-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil) +function Data.color(s) +if type(s) ~= "string" then + return nil + end + local h = string.lower((string.gsub(s, "^#", ""))) + if #h == 8 and string.sub(h, 1, 2) == "ff" then + h = string.sub(h, 3) + end + return "#" .. h +end + +-- property values: TMX / TMJ type names -> a Luau value from text +function Data.value(typ, text) +if typ == "int" or typ == "float" or typ == "object" then + return tonumber(text) or 0 + elseif typ == "bool" then + return text == "true" or text == "1" + elseif typ == "color" then + return Data.color(text) or "" + end + return text +end + +-- typeOf(v, declared?) -> the Tiled type to write for v +function Data.typeOf(v, declared) +if declared then + return declared + end + if type(v) == "boolean" then + return "bool" + elseif type(v) == "number" then + return v % 1 == 0 and"int" or"float" + elseif type(v) == "table" then + return "class" + end + return "string" +end + +-- sortedKeys(t) -> its string keys, sorted +function Data.sortedKeys(t) +local out = {} + for k in pairs(t) do + if type(k) == "string" then + table.insert(out, k) + end + end + table.sort(out) + return out +end + +return Data +end +__FILES["vector/tiled/Tmj"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ +-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmj = {} + +local function n(v, default) +if type(v) == "number" then + return v + end + return default +end +local function b(v, default) +if type(v) == "boolean" then + return v + end + return default +end +local function s(v) +if type(v) == "string" then + return v + end + return nil +end +local function list(v) +if type(v) == "table" then + return v + end + return {} +end + +-- ------------------------------------------------------------------------------------------------ read +local function properties(v) +local props= {} + local types= nil + for _, p in __iter(list(v)) do + if type(p) == "table" and type(p.name) == "string" then + local typ = s(p.type) or "string" + local val= p.value + if typ == "class" then + local inner, innerTypes = {}, nil + if type(val) == "table" then + -- a class value is an object of member -> value (types come from the project): keep them as they are + for k, x in pairs(val) do + if type(k) == "string" then + inner[k] = x + end + end + end + val = { class = s(p.propertytype) or "", properties = inner, propertyTypes = innerTypes } + elseif typ == "int" or typ == "float" or typ == "object" then + val = n(val, 0) + elseif typ == "bool" then + val = val == true + elseif typ == "color" then + val = Data.color(s(val)) or "" + elseif type(val) ~= "string" then + val = val == nil and"" or tostring(val) + end + props[p.name] = val + if typ ~= "string" then + types = types or {} + ;(types )[p.name] = typ + end + end + end + return props, types +end + +local function withProps(t, v) + local props, types = properties(v.properties) + t.properties = props + if types then + t.propertyTypes = types + end +end + +local function gids(v, encoding, compression) +if type(v) == "string" then + if encoding == "base64" or encoding == nil then + return Data.base64(v, compression) + end + return nil, "unknown encoding " .. tostring(encoding), true + end + local out = {} + for _, g in __iter(list(v)) do + if type(g) ~= "number" or g < 0 or g >= 4294967296 then + return nil, "bad gid", nil + end + table.insert(out, g) + end + return out, nil, nil +end + +local function object(o) +local obj= { + id = n(o.id), + name = s(o.name) or "", + class = s(o.class) or s(o.type) or "", + x = n(o.x, 0), + y = n(o.y, 0), + width = n(o.width, 0), + height = n(o.height, 0), + rotation = n(o.rotation, 0), + gid = n(o.gid), + visible = b(o.visible, true), + template = s(o.template), + shape = "rectangle", + } + withProps(obj, o) + if o.ellipse == true then + obj.shape = "ellipse" + elseif o.point == true then + obj.shape = "point" + end + for _, kind in __iter({ "polygon", "polyline" }) do + if type(o[kind]) == "table" then + obj.shape = kind + local pts = {} + for _, p in __iter(o[kind]) do + if type(p) == "table" then + table.insert(pts, { n(p.x, 0), n(p.y, 0) }) + end + end + obj.points = pts + end + end + if type(o.text) == "table" then + local t = o.text + obj.shape = "text" + obj.text = { + text = s(t.text) or "", + fontFamily = s(t.fontfamily) or "sans-serif", + pixelSize = n(t.pixelsize, 16), + wrap = b(t.wrap, false), + color = Data.color(s(t.color)) or "#000000", + bold = b(t.bold, false), + italic = b(t.italic, false), + underline = b(t.underline, false), + strikeout = b(t.strikeout, false), + kerning = b(t.kerning, true), + halign = s(t.halign) or "left", + valign = s(t.valign) or "top", + } + end + return obj +end + +local TYPES = { tilelayer = "tiles", objectgroup = "objects", imagelayer = "image", group = "group" } + +local layer + +local function common(v, typ) +local l= { + type = typ, + id = n(v.id), + name = s(v.name) or "", + visible = b(v.visible, true), + opacity = n(v.opacity, 1), + x = n(v.x, 0), + y = n(v.y, 0), + offsetX = n(v.offsetx, 0), + offsetY = n(v.offsety, 0), + parallaxX = n(v.parallaxx, 1), + parallaxY = n(v.parallaxy, 1), + tintColor = Data.color(s(v.tintcolor)), + class = s(v.class) or "", + locked = b(v.locked, false), + } + withProps(l, v) + return l +end + +local function objectGroup(v) +local l = common(v, "objects") + l.drawOrder = s(v.draworder) or "topdown" + l.color = Data.color(s(v.color)) + l.objects = {} + for _, o in __iter(list(v.objects)) do + if type(o) == "table" then + table.insert(l.objects, object(o)) + end + end + return l +end + +layer = function(v, depth) +if type(v) ~= "table" then + return nil, "a layer is not an object" + end + if depth > 100 then + return nil, "groups nested too deep" + end + local typ = TYPES[v.type] + if typ == "tiles" then + local l = common(v, "tiles") + l.width = n(v.width, 0) + l.height = n(v.height, 0) + l.encoding = s(v.encoding) + l.compression = s(v.compression) + if type(v.chunks) == "table" then + l.chunks = {} + for _, c in __iter(v.chunks) do + if type(c) == "table" then + local g, err, uns = gids(c.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = n(c.x, 0), y = n(c.y, 0), width = n(c.width, 0), height = n(c.height, 0), data = g }) + end + end + elseif v.data ~= nil then + local g, err, uns = gids(v.data, l.encoding, l.compression) + if not g then + return nil, err, uns + end + l.data = g + end + return l + elseif typ == "objects" then + return objectGroup(v) + elseif typ == "image" then + local l = common(v, "image") + l.imageSource = s(v.image) + l.imageWidth = n(v.imagewidth) + l.imageHeight = n(v.imageheight) + l.transparentColor = Data.color(s(v.transparentcolor)) + l.repeatX = b(v.repeatx, false) + l.repeatY = b(v.repeaty, false) + return l + elseif typ == "group" then + local l = common(v, "group") + l.layers = {} + for _, c in __iter(list(v.layers)) do + local sub, err, uns = layer(c, depth + 1) + if not sub then + return nil, err, uns + end + table.insert(l.layers, sub) + end + return l + end + return nil, "unknown layer type " .. tostring(v.type) +end + +-- tileset(v) -> Tileset (a map's entry, or a .tsj root) +function Tmj.tileset(v) +local ts= { + firstGid = n(v.firstgid, 1), + source = s(v.source), + name = s(v.name) or "", + tileWidth = n(v.tilewidth, 0), + tileHeight = n(v.tileheight, 0), + spacing = n(v.spacing, 0), + margin = n(v.margin, 0), + count = n(v.tilecount, 0), + columns = n(v.columns, 0), + objectAlignment = s(v.objectalignment), + class = s(v.class) or "", + imageSource = s(v.image), + imageWidth = n(v.imagewidth), + imageHeight = n(v.imageheight), + transparentColor = Data.color(s(v.transparentcolor)), + } + withProps(ts, v) + if type(v.tileoffset) == "table" then + ts.tileOffset = { x = n(v.tileoffset.x, 0), y = n(v.tileoffset.y, 0) } + end + local tiles = {} + for _, t in __iter(list(v.tiles)) do + if type(t) == "table" then + local tile= { id = n(t.id, 0), class = s(t.class) or s(t.type) or "", probability = n(t.probability) } + withProps(tile, t) + tile.imageSource = s(t.image) + tile.imageWidth = n(t.imagewidth) + tile.imageHeight = n(t.imageheight) + if type(t.animation) == "table" then + tile.animation = {} + for _, f in __iter(t.animation) do + if type(f) == "table" then + table.insert(tile.animation, { tileId = n(f.tileid, 0), duration = n(f.duration, 0) }) + end + end + end + if type(t.objectgroup) == "table" then + tile.objectGroup = objectGroup(t.objectgroup) + end + table.insert(tiles, tile) + end + end + table.sort(tiles, function(x, y) +return x.id < y.id + end) + ts.tiles = tiles + return ts +end + +-- read(value) -> TileMap | nil, message, unsupported? +function Tmj.read(v) +if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then + return nil, "not a Tiled map (type is not \"map\")" + end + local map= Types.TileMap.new((n(v.width, 0) ), (n(v.height, 0) ), (n(v.tilewidth, 0) ), (n(v.tileheight, 0) )) + map.version = (type(v.version) == "number" and{(Data.num(v.version) )}or{(s(v.version) +)})[1] map.tiledVersion = s(v.tiledversion) + map.orientation = s(v.orientation) or "orthogonal" + map.renderOrder = s(v.renderorder) or "right-down" + map.infinite = b(v.infinite, false) + map.nextLayerId = n(v.nextlayerid) + map.nextObjectId = n(v.nextobjectid) + map.backgroundColor = Data.color(s(v.backgroundcolor)) + map.hexSideLength = n(v.hexsidelength) + map.staggerAxis = s(v.staggeraxis) + map.staggerIndex = s(v.staggerindex) + map.class = s(v.class) or "" + map.parallaxOriginX = n(v.parallaxoriginx, 0) + map.parallaxOriginY = n(v.parallaxoriginy, 0) + withProps(map, v) + for _, ts in __iter(list(v.tilesets)) do + if type(ts) == "table" then + table.insert(map.tilesets, Tmj.tileset(ts)) + end + end + for _, l in __iter(list(v.layers)) do + local x, err, uns = layer(l, 0) + if not x then + return nil, err, uns + end + table.insert(map.layers, x) + end + return map, nil +end + +-- ------------------------------------------------------------------------------------------------ write +local function obj(pairs_) +local o = Types.object() + for _, kv in __iter(pairs_) do + if kv[2] ~= nil then + Types.set(o, kv[1], kv[2]) + end + end + return o +end +local function nz(v, default) +if v == nil or v == default then + return nil + end + return v +end +local function str(v) +if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propList(props, types) +if type(props) ~= "table" or next(props) == nil then + return nil + end + local out = {} + for _, k in __iter(Data.sortedKeys(props)) do + local v = props[k] + local typ = Data.typeOf(v, (type(types) == "table" and{types[k] }or{nil})[1]) + if typ == "class" and type(v) == "table" then + local members = Types.object() + if type(v.properties) == "table" then + for _, mk in __iter(Data.sortedKeys(v.properties)) do + Types.set(members, mk, v.properties[mk]) + end + end + table.insert(out, obj({ { "name", k }, { "propertytype", v.class or "" }, { "type", "class" }, { "value", members } })) + else + table.insert(out, obj({ { "name", k }, { "type", typ }, { "value", v } })) + end + end + return out +end + +local function writeObject(o) +local t= nil + if o.shape == "text" and type(o.text) == "table" then + local x = o.text + t = obj({ + { "bold", nz(x.bold, false) }, + { "color", nz(x.color, "#000000") }, + { "fontfamily", nz(x.fontFamily, "sans-serif") }, + { "halign", nz(x.halign, "left") }, + { "italic", nz(x.italic, false) }, + { "kerning", nz(x.kerning, true) }, + { "pixelsize", nz(x.pixelSize, 16) }, + { "strikeout", nz(x.strikeout, false) }, + { "text", tostring(x.text or "") }, + { "underline", nz(x.underline, false) }, + { "valign", nz(x.valign, "top") }, + { "wrap", nz(x.wrap, false) }, + }) + end + local pts= nil + if (o.shape == "polygon" or o.shape == "polyline") and type(o.points) == "table" then + pts = {} + for _, p in __iter(o.points) do + table.insert(pts, obj({ { "x", tonumber(p[1]) or 0 }, { "y", tonumber(p[2]) or 0 } })) + end + end + return obj({ + { "ellipse", o.shape == "ellipse" and true or nil }, + { "gid", o.gid }, + { "height", o.height or 0 }, + { "id", o.id }, + { "name", o.name or "" }, + { "point", o.shape == "point" and true or nil }, + { "polygon", (o.shape == "polygon" and{pts }or{nil })[1]}, + { "polyline", (o.shape == "polyline" and{pts }or{nil })[1]}, + { "properties", propList(o.properties, o.propertyTypes) }, + { "rotation", o.rotation or 0 }, + { "template", o.template }, + { "text", t }, + { "type", o.class or "" }, + { "visible", o.visible ~= false }, + { "width", o.width or 0 }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + }) +end + + + +local function writeObjectGroup(l) +local objs = {} + for _, o in __iter(((type(l.objects) == "table" and{l.objects }or{{}})[1])) do + table.insert(objs, writeObject(o)) + end + return objs +end + +local writeLayer + +writeLayer = function(l, o) +local t = l.type + local fields= {} + local function add(k, v) + table.insert(fields, { k, v }) + end + if t == "tiles" then + local enc = o.encoding or l.encoding + if enc ~= "base64" then + enc = nil + end + local comp = (enc and{(o.compression or ((o.encoding and{nil }or{l.compression})[1])) }or{nil +})[1] local function payload(g) +if enc == "base64" then + return Data.toBase64(g, comp, o.level) + end + return g, nil + end + if type(l.chunks) == "table" then + local chunks = {} + for _, c in __iter(l.chunks) do + local d, err = payload(c.data or {}) + if d == nil then + return nil, err + end + table.insert(chunks, obj({ { "data", d }, { "height", c.height or 0 }, { "width", c.width or 0 }, { "x", c.x or 0 }, { "y", c.y or 0 } })) + end + add("chunks", chunks) + local sx, sy = math.huge, math.huge + for _, c in __iter(l.chunks) do + sx, sy = math.min(sx, c.x or 0), math.min(sy, c.y or 0) + end + if #l.chunks > 0 then + add("startx", sx) + add("starty", sy) + end + elseif type(l.data) == "table" then + local d, err = payload(l.data) + if d == nil then + return nil, err + end + add("data", d) + end + add("compression", comp) + add("encoding", enc) + add("height", l.height or 0) + elseif t == "objects" then + add("color", l.color) + add("draworder", l.drawOrder or "topdown") + elseif t == "image" then + add("image", l.imageSource or "") + add("imageheight", l.imageHeight) + add("imagewidth", l.imageWidth) + elseif t == "group" then + local kids = {} + for _, c in __iter(((type(l.layers) == "table" and{l.layers }or{{}})[1])) do + local x, err = writeLayer(c, o) + if x == nil then + return nil, err + end + table.insert(kids, x) + end + add("layers", kids) + else + return nil, "unknown layer type " .. tostring(t) + end + add("class", str(l.class)) + add("id", l.id) + add("locked", nz(l.locked, false)) + add("name", l.name or "") + if t == "objects" then + add("objects", writeObjectGroup(l)) + end + add("offsetx", nz(l.offsetX, 0)) + add("offsety", nz(l.offsetY, 0)) + add("opacity", l.opacity or 1) + add("parallaxx", nz(l.parallaxX, 1)) + add("parallaxy", nz(l.parallaxY, 1)) + add("properties", propList(l.properties, l.propertyTypes)) + if t == "image" then + add("repeatx", nz(l.repeatX, false)) + add("repeaty", nz(l.repeatY, false)) + end + add("tintcolor", l.tintColor) + if t == "image" then + add("transparentcolor", l.transparentColor) + end + add("type", t == "tiles" and"tilelayer" or(t == "objects" and"objectgroup" or(t == "image" and"imagelayer" or"group"))) + add("visible", l.visible ~= false) + if t == "tiles" then + add("width", l.width or 0) + end + add("x", l.x or 0) + add("y", l.y or 0) + return obj(fields), nil +end + +-- tilesetValue(ts, inMap) -> a JSON object +function Tmj.tilesetValue(ts, inMap) +if inMap and type(ts.source) == "string" then + return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local tiles= nil + if type(ts.tiles) == "table" and #ts.tiles > 0 then + tiles = {} + for _, tile in __iter(ts.tiles) do + local anim= nil + if type(tile.animation) == "table" then + anim = {} + for _, f in __iter(tile.animation) do + table.insert(anim, obj({ { "duration", f.duration or 0 }, { "tileid", f.tileId or 0 } })) + end + end + local og= nil + if type(tile.objectGroup) == "table" then + og = writeLayer(tile.objectGroup, {}) + end + table.insert(tiles, obj({ + { "animation", anim }, + { "id", tile.id or 0 }, + { "image", tile.imageSource }, + { "imageheight", tile.imageHeight }, + { "imagewidth", tile.imageWidth }, + { "objectgroup", og }, + { "probability", tile.probability }, + { "properties", propList(tile.properties, tile.propertyTypes) }, + { "type", str(tile.class) }, + })) + end + end + return obj({ + { "class", str(ts.class) }, + { "columns", ts.columns or 0 }, + { "firstgid", (inMap and{ts.firstGid or 1 }or{nil })[1]}, + { "image", ts.imageSource }, + { "imageheight", ts.imageHeight }, + { "imagewidth", ts.imageWidth }, + { "margin", ts.margin or 0 }, + { "name", ts.name or "" }, + { "objectalignment", ts.objectAlignment }, + { "properties", propList(ts.properties, ts.propertyTypes) }, + { "spacing", ts.spacing or 0 }, + { "tilecount", ts.count or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "tileoffset", (type(ts.tileOffset) == "table" and{(obj({ { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } }) )}or{nil })[1]}, + { "tiles", tiles }, + { "tilewidth", ts.tileWidth or 0 }, + { "transparentcolor", ts.transparentColor }, + { "type", (inMap and{nil }or{"tileset" })[1]}, + }) +end + +-- write(map, opts) -> a JSON value | nil, message +function Tmj.write(map, o) +local layers = {} + for _, l in __iter(map.layers) do + local x, err = writeLayer(l, o) + if x == nil then + return nil, err + end + table.insert(layers, x) + end + local tilesets = {} + for _, ts in __iter(map.tilesets) do + table.insert(tilesets, Tmj.tilesetValue(ts, true)) + end + return obj({ + { "backgroundcolor", map.backgroundColor }, + { "class", str(map.class) }, + { "compressionlevel", -1 }, + { "height", map.height }, + { "hexsidelength", map.hexSideLength }, + { "infinite", map.infinite == true }, + { "layers", layers }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + { "orientation", map.orientation or "orthogonal" }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "properties", propList(map.properties, map.propertyTypes) }, + { "renderorder", map.renderOrder or "right-down" }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "tiledversion", map.tiledVersion }, + { "tileheight", map.tileHeight }, + { "tilesets", tilesets }, + { "tilewidth", map.tileWidth }, + { "type", "map" }, + { "version", map.version or "1.10" }, + { "width", map.width }, + }), nil +end + +return Tmj +end +__FILES["vector/tiled/Tmx"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets. +-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?. +local Xml = __include("codecs/text/Xml") +local Types = __include("Types") +local Data = __include("vector/tiled/Data") + +local Tmx = {} + + + +local function a(n, k) +return (n.attrs )[k] +end +local function num(n, k, default) +local v = a(n, k) + if v == nil then + return default + end + return tonumber(v) or default +end +local function flag(n, k, default) +local v = a(n, k) + if v == nil then + return default + end + return v == "1" or v == "true" +end + +-- ------------------------------------------------------------------------------------------------ read +-- <properties> -> values, types (types only for the non-string ones) +local function properties(n) +local props= {} + local types= nil + if n == nil then + return props, nil + end + for _, p in __iter(Xml.children(n, "property")) do + local name = a(p, "name") + if name then + local typ = a(p, "type") or "string" + local v +if typ == "class" then + local inner, innerTypes = properties(Xml.child(p, "properties")) + v = { class = a(p, "propertytype") or "", properties = inner, propertyTypes = innerTypes } + else + local text = a(p, "value") + if text == nil then + text = Xml.text(p) -- multi-line strings + end + v = Data.value(typ, text ) + end + props[name] = v + if typ ~= "string" then + types = types or {} + ;(types )[name] = typ + end + end + end + return props, types +end + +local function withProps(t, n) + local props, types = properties(Xml.child(n, "properties")) + t.properties = props + if types then + t.propertyTypes = types + end +end + +-- the gids of a <data> (or <chunk>) node +local function gids(d, encoding, compression) +if encoding == "csv" then + return Data.csv(Xml.text(d)) + elseif encoding == "base64" then + return Data.base64(Xml.text(d), compression) + elseif encoding == nil or encoding == "" then + local out = {} + for _, t in __iter(Xml.children(d, "tile")) do + table.insert(out, (num(t, "gid", 0) )) + end + return out, nil, nil + end + return nil, "unknown encoding " .. encoding, true +end + +local function object(o) +local obj= { + id = num(o, "id"), + name = a(o, "name") or "", + class = a(o, "class") or a(o, "type") or "", + x = num(o, "x", 0), + y = num(o, "y", 0), + width = num(o, "width", 0), + height = num(o, "height", 0), + rotation = num(o, "rotation", 0), + gid = num(o, "gid"), + visible = flag(o, "visible", true), + template = a(o, "template"), + shape = "rectangle", + } + withProps(obj, o) + if Xml.child(o, "ellipse") then + obj.shape = "ellipse" + elseif Xml.child(o, "point") then + obj.shape = "point" + end + for _, kind in __iter({ "polygon", "polyline" }) do + local p = Xml.child(o, kind) + if p then + obj.shape = kind + local pts = {} + for x, y in __iter(string.gmatch(a(p, "points") or "", "([^,%s]+),([^,%s]+)")) do + table.insert(pts, { tonumber(x) or 0, tonumber(y) or 0 }) + end + obj.points = pts + end + end + local t = Xml.child(o, "text") + if t then + obj.shape = "text" + obj.text = { + text = Xml.text(t), + fontFamily = a(t, "fontfamily") or "sans-serif", + pixelSize = num(t, "pixelsize", 16), + wrap = flag(t, "wrap", false), + color = Data.color(a(t, "color")) or "#000000", + bold = flag(t, "bold", false), + italic = flag(t, "italic", false), + underline = flag(t, "underline", false), + strikeout = flag(t, "strikeout", false), + kerning = flag(t, "kerning", true), + halign = a(t, "halign") or "left", + valign = a(t, "valign") or "top", + } + end + return obj +end + +local layer + +local function common(n, typ) +local l= { + type = typ, + id = num(n, "id"), + name = a(n, "name") or "", + visible = flag(n, "visible", true), + opacity = num(n, "opacity", 1), + x = num(n, "x", 0), + y = num(n, "y", 0), + offsetX = num(n, "offsetx", 0), + offsetY = num(n, "offsety", 0), + parallaxX = num(n, "parallaxx", 1), + parallaxY = num(n, "parallaxy", 1), + tintColor = Data.color(a(n, "tintcolor")), + class = a(n, "class") or "", + locked = flag(n, "locked", false), + } + withProps(l, n) + return l +end + +local function objectGroup(n) +local l = common(n, "objects") + l.drawOrder = a(n, "draworder") or "topdown" + l.color = Data.color(a(n, "color")) + l.objects = {} + for _, o in __iter(Xml.children(n, "object")) do + table.insert(l.objects, object(o)) + end + return l +end + +layer = function(n) +local name = n.name + if name == "layer" then + local l = common(n, "tiles") + l.width = num(n, "width", 0) + l.height = num(n, "height", 0) + local d = Xml.child(n, "data") + if d then + local enc, comp = a(d, "encoding"), a(d, "compression") + l.encoding, l.compression = enc, comp + local chunks = Xml.children(d, "chunk") + if #chunks > 0 then + l.chunks = {} + for _, c in __iter(chunks) do + local g, err, uns = gids(c, enc, comp) + if not g then + return nil, err, uns + end + table.insert(l.chunks, { x = num(c, "x", 0), y = num(c, "y", 0), width = num(c, "width", 0), height = num(c, "height", 0), data = g }) + end + else + local g, err, uns = gids(d, enc, comp) + if not g then + return nil, err, uns + end + l.data = g + end + end + return l + elseif name == "objectgroup" then + return objectGroup(n) + elseif name == "imagelayer" then + local l = common(n, "image") + l.repeatX = flag(n, "repeatx", false) + l.repeatY = flag(n, "repeaty", false) + local img = Xml.child(n, "image") + if img then + l.imageSource = a(img, "source") + l.imageWidth = num(img, "width") + l.imageHeight = num(img, "height") + l.transparentColor = Data.color(a(img, "trans")) + end + return l + elseif name == "group" then + local l = common(n, "group") + l.layers = {} + for _, c in __iter(n.children) do + if type(c) == "table" then + local sub, err, uns = layer(c) + if err then + return nil, err, uns + end + if sub then + table.insert(l.layers, sub) + end + end + end + return l + end + return nil +end + +-- a <tileset> element (in a map, or a .tsx root) -> Tileset +function Tmx.tileset(n) +local ts= { + firstGid = num(n, "firstgid", 1), + source = a(n, "source"), + name = a(n, "name") or "", + tileWidth = num(n, "tilewidth", 0), + tileHeight = num(n, "tileheight", 0), + spacing = num(n, "spacing", 0), + margin = num(n, "margin", 0), + count = num(n, "tilecount", 0), + columns = num(n, "columns", 0), + objectAlignment = a(n, "objectalignment"), + class = a(n, "class") or "", + } + withProps(ts, n) + local off = Xml.child(n, "tileoffset") + if off then + ts.tileOffset = { x = num(off, "x", 0), y = num(off, "y", 0) } + end + local img = Xml.child(n, "image") + if img then + ts.imageSource = a(img, "source") + ts.imageWidth = num(img, "width") + ts.imageHeight = num(img, "height") + ts.transparentColor = Data.color(a(img, "trans")) + end + local tiles = {} + for _, t in __iter(Xml.children(n, "tile")) do + local tile= { id = num(t, "id", 0), class = a(t, "class") or a(t, "type") or "", probability = num(t, "probability") } + withProps(tile, t) + local ti = Xml.child(t, "image") + if ti then + tile.imageSource = a(ti, "source") + tile.imageWidth = num(ti, "width") + tile.imageHeight = num(ti, "height") + end + local anim = Xml.child(t, "animation") + if anim then + tile.animation = {} + for _, f in __iter(Xml.children(anim, "frame")) do + table.insert(tile.animation, { tileId = num(f, "tileid", 0), duration = num(f, "duration", 0) }) + end + end + local og = Xml.child(t, "objectgroup") + if og then + tile.objectGroup = objectGroup(og) + end + table.insert(tiles, tile) + end + ts.tiles = tiles + return ts +end + +-- read(root) -> TileMap | nil, message, unsupported? +function Tmx.read(root) +if root.name ~= "map" then + return nil, "the root element is <" .. root.name .. ">, not <map>" + end + local map= Types.TileMap.new((num(root, "width", 0) ), (num(root, "height", 0) ), (num(root, "tilewidth", 0) ), (num(root, "tileheight", 0) )) + map.version = a(root, "version") + map.tiledVersion = a(root, "tiledversion") + map.orientation = a(root, "orientation") or "orthogonal" + map.renderOrder = a(root, "renderorder") or "right-down" + map.infinite = flag(root, "infinite", false) + map.nextLayerId = num(root, "nextlayerid") + map.nextObjectId = num(root, "nextobjectid") + map.backgroundColor = Data.color(a(root, "backgroundcolor")) + map.hexSideLength = num(root, "hexsidelength") + map.staggerAxis = a(root, "staggeraxis") + map.staggerIndex = a(root, "staggerindex") + map.class = a(root, "class") or "" + map.parallaxOriginX = num(root, "parallaxoriginx", 0) + map.parallaxOriginY = num(root, "parallaxoriginy", 0) + withProps(map, root) + for _, c in __iter(root.children) do + if type(c) == "table" then + if c.name == "tileset" then + table.insert(map.tilesets, Tmx.tileset(c)) + else + local l, err, uns = layer(c) + if err then + return nil, err, uns + end + if l then + table.insert(map.layers, l) + end + end + end + end + return map, nil +end +-- ------------------------------------------------------------------------------------------------ write + + + +local function el(name, attrs, children) -- attrs in order; nil / default values dropped by the caller + +local o = Types.object() + for _, kv in __iter(attrs) do + if kv[2] ~= nil then + local v = kv[2] + Types.set(o, kv[1], (type(v) == "number" and{(Data.num(v) )}or{(type(v) == "boolean" and{(v and"1" or"0") }or{(tostring(v))})[1]})[1]) + end + end + return Xml.element(name, o , children) +end + +local function nz(v, default) +if v == nil or v == default then + return nil + end + return v +end +local function str(v) +if type(v) == "string" and v ~= "" then + return v + end + return nil +end + +local function propsNode(props, types) +if type(props) ~= "table" or next(props) == nil then + return nil + end + local list = {} + for _, k in __iter(Data.sortedKeys(props)) do + local v = props[k] + local typ = Data.typeOf(v, (type(types) == "table" and{types[k] }or{nil})[1]) + if typ == "class" and type(v) == "table" then + local inner = propsNode(v.properties, v.propertyTypes) + table.insert(list, el("property", { { "name", k }, { "type", "class" }, { "propertytype", v.class or "" } }, inner and{ inner } or nil)) + else + local text = (type(v) == "boolean" and{(v and"true" or"false") }or{(type(v) == "number" and{(Data.num(v) )}or{(tostring(v) +)})[1]})[1] if string.find(text, "\n", 1, true) then + table.insert(list, el("property", { { "name", k }, { "type", (typ ~= "string" and{typ }or{nil })[1]} }, { text })) + else + table.insert(list, el("property", { { "name", k }, { "type", (typ ~= "string" and{typ }or{nil })[1]}, { "value", text } })) + end + end + end + return el("properties", {}, list) +end + +local function addProps(children, t) + local p = propsNode(t.properties, t.propertyTypes) + if p then + table.insert(children, p) + end +end + +local function writeObject(o) +local kids = {} + addProps(kids, o) + local shape = o.shape + if shape == "ellipse" then + table.insert(kids, el("ellipse", {})) + elseif shape == "point" then + table.insert(kids, el("point", {})) + elseif (shape == "polygon" or shape == "polyline") and type(o.points) == "table" then + local pts = {} + for _, p in __iter(o.points) do + table.insert(pts, Data.num(tonumber(p[1]) or 0) .. "," .. Data.num(tonumber(p[2]) or 0)) + end + table.insert(kids, el(shape, { { "points", table.concat(pts, " ") } })) + elseif shape == "text" and type(o.text) == "table" then + local t = o.text + table.insert(kids, el("text", { + { "fontfamily", nz(t.fontFamily, "sans-serif") }, + { "pixelsize", nz(t.pixelSize, 16) }, + { "wrap", nz(t.wrap, false) }, + { "color", nz(t.color, "#000000") }, + { "bold", nz(t.bold, false) }, + { "italic", nz(t.italic, false) }, + { "underline", nz(t.underline, false) }, + { "strikeout", nz(t.strikeout, false) }, + { "kerning", nz(t.kerning, true) }, + { "halign", nz(t.halign, "left") }, + { "valign", nz(t.valign, "top") }, + }, { tostring(t.text or "") })) + end + return el("object", { + { "id", o.id }, + { "name", str(o.name) }, + { "type", str(o.class) }, + { "gid", o.gid }, + { "x", o.x or 0 }, + { "y", o.y or 0 }, + { "width", nz(o.width, 0) }, + { "height", nz(o.height, 0) }, + { "rotation", nz(o.rotation, 0) }, + { "visible", nz(o.visible, true) }, + { "template", o.template }, + }, kids) +end + +local function commonAttrs(l, extra) +local out= { { "id", l.id }, { "name", str(l.name) or "" }, { "class", str(l.class) } } + table.move(extra, 1, #extra, #out + 1, out) + local tail = { + { "visible", nz(l.visible, true) }, + { "locked", nz(l.locked, false) }, + { "opacity", nz(l.opacity, 1) }, + { "tintcolor", l.tintColor }, + { "offsetx", nz(l.offsetX, 0) }, + { "offsety", nz(l.offsetY, 0) }, + { "parallaxx", nz(l.parallaxX, 1) }, + { "parallaxy", nz(l.parallaxY, 1) }, + } + table.move(tail, 1, #tail, #out + 1, out) + return out +end + +local function writeObjectGroup(l, tag) +local kids = {} + addProps(kids, l) + for _, o in __iter(((type(l.objects) == "table" and{l.objects }or{{}})[1])) do + table.insert(kids, writeObject(o)) + end + return el(tag or "objectgroup", commonAttrs(l, { { "color", l.color }, { "draworder", nz(l.drawOrder, "topdown") } }), kids) +end + + + +local writeLayer + +writeLayer = function(l, o) +local t = l.type + if t == "tiles" then + local kids = {} + addProps(kids, l) + local enc = o.encoding or l.encoding or "csv" + local comp = (o.encoding and{o.compression }or{(o.compression or l.compression) +})[1] if enc ~= "base64" then + comp = nil + end + local function payload(g, width) +if enc == "csv" then + return Data.csvText(g, width), nil + end + local s, err = Data.toBase64(g, comp, o.level) + if not s then + return nil, err + end + return "\n " .. s .. "\n ", nil + end + local dataKids = {} + if type(l.chunks) == "table" then + for _, c in __iter(l.chunks) do + local kids= {} + if enc == "xml" then + for _, g in __iter((c.data or {})) do + table.insert(kids, el("tile", { { "gid", (g ~= 0 and{g }or{nil })[1]} })) + end + else + local s, err = payload(c.data or {}, c.width or 0) + if not s then + return nil, err + end + kids = { s } + end + table.insert(dataKids, el("chunk", { { "x", c.x or 0 }, { "y", c.y or 0 }, { "width", c.width or 0 }, { "height", c.height or 0 } }, kids)) + end + elseif type(l.data) == "table" and enc == "xml" then + for _, g in __iter(l.data) do + table.insert(dataKids, el("tile", { { "gid", (g ~= 0 and{g }or{nil })[1]} })) + end + elseif type(l.data) == "table" then + local s, err = payload(l.data, l.width or 0) + if not s then + return nil, err + end + dataKids = { s } + end + table.insert(kids, el("data", { { "encoding", (enc == "xml" and{nil }or{enc })[1]}, { "compression", comp } }, dataKids)) + return el("layer", commonAttrs(l, { { "x", nz(l.x, 0) }, { "y", nz(l.y, 0) }, { "width", l.width or 0 }, { "height", l.height or 0 } }), kids), nil + elseif t == "objects" then + return writeObjectGroup(l), nil + elseif t == "image" then + local kids = {} + addProps(kids, l) + if l.imageSource then + table.insert(kids, el("image", { { "source", l.imageSource }, { "trans", l.transparentColor }, { "width", l.imageWidth }, { "height", l.imageHeight } })) + end + return el("imagelayer", commonAttrs(l, { { "repeatx", nz(l.repeatX, false) }, { "repeaty", nz(l.repeatY, false) } }), kids), nil + elseif t == "group" then + local kids = {} + addProps(kids, l) + for _, c in __iter(((type(l.layers) == "table" and{l.layers }or{{}})[1])) do + local n, err = writeLayer(c, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + return el("group", commonAttrs(l, {}), kids), nil + end + return nil, "unknown layer type " .. tostring(t) +end + +-- tilesetNode(ts, inMap) -> <tileset> +function Tmx.tilesetNode(ts, inMap) +if inMap and type(ts.source) == "string" then + return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } }) + end + local kids = {} + if type(ts.tileOffset) == "table" then + table.insert(kids, el("tileoffset", { { "x", ts.tileOffset.x or 0 }, { "y", ts.tileOffset.y or 0 } })) + end + addProps(kids, ts) + if ts.imageSource then + table.insert(kids, el("image", { { "source", ts.imageSource }, { "trans", ts.transparentColor }, { "width", ts.imageWidth }, { "height", ts.imageHeight } })) + end + for _, tile in __iter(((type(ts.tiles) == "table" and{ts.tiles }or{{}})[1])) do + local tk = {} + addProps(tk, tile) + if tile.imageSource then + table.insert(tk, el("image", { { "source", tile.imageSource }, { "width", tile.imageWidth }, { "height", tile.imageHeight } })) + end + if type(tile.objectGroup) == "table" then + table.insert(tk, writeObjectGroup(tile.objectGroup)) + end + if type(tile.animation) == "table" then + local frames = {} + for _, f in __iter(tile.animation) do + table.insert(frames, el("frame", { { "tileid", f.tileId or 0 }, { "duration", f.duration or 0 } })) + end + table.insert(tk, el("animation", {}, frames)) + end + table.insert(kids, el("tile", { { "id", tile.id or 0 }, { "type", str(tile.class) }, { "probability", tile.probability } }, tk)) + end + return el("tileset", { + { "firstgid", (inMap and{ts.firstGid or 1 }or{nil })[1]}, + { "name", ts.name or "" }, + { "class", str(ts.class) }, + { "tilewidth", ts.tileWidth or 0 }, + { "tileheight", ts.tileHeight or 0 }, + { "spacing", nz(ts.spacing, 0) }, + { "margin", nz(ts.margin, 0) }, + { "tilecount", ts.count or 0 }, + { "columns", ts.columns or 0 }, + { "objectalignment", ts.objectAlignment }, + }, kids) +end + +-- write(map, opts) -> an XML document node | nil, message +function Tmx.write(map, o) +local kids = {} + addProps(kids, map) + for _, ts in __iter(map.tilesets) do + table.insert(kids, Tmx.tilesetNode(ts, true)) + end + for _, l in __iter(map.layers) do + local n, err = writeLayer(l, o) + if not n then + return nil, err + end + table.insert(kids, n) + end + local root = el("map", { + { "version", map.version or "1.10" }, + { "tiledversion", map.tiledVersion }, + { "class", str(map.class) }, + { "orientation", map.orientation or "orthogonal" }, + { "renderorder", map.renderOrder or "right-down" }, + { "width", map.width }, + { "height", map.height }, + { "tilewidth", map.tileWidth }, + { "tileheight", map.tileHeight }, + { "hexsidelength", map.hexSideLength }, + { "staggeraxis", map.staggerAxis }, + { "staggerindex", map.staggerIndex }, + { "parallaxoriginx", nz(map.parallaxOriginX, 0) }, + { "parallaxoriginy", nz(map.parallaxOriginY, 0) }, + { "backgroundcolor", map.backgroundColor }, + { "infinite", map.infinite == true }, + { "nextlayerid", map.nextLayerId }, + { "nextobjectid", map.nextObjectId }, + }, kids) + return Xml.document(root, { version = "1.0", encoding = "UTF-8" }), nil +end + +return Tmx +end +__FILES["video/avi"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in rosetta, on containers/Avi. +-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces +-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/video/Video registry by FourCC (MJPEG, MPEG-1, +-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is +-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, +-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. +-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's +-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. +-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Avi = __include("containers/Avi") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local AviFormat = { + name = "avi", + category = "video", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + 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", "mpeg2", "rawvideo" }, audio = true, odml = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants +-- WAVEFORMATEX wFormatTag -> codec id + + + + + + + + + + + + + + + + +local AUDIO_TAGS= { + [0x0001] = "pcm", + [0x0002] = "adpcm_ms", + [0x0003] = "pcm_f", + [0x0006] = "pcm_alaw", + [0x0007] = "pcm_mulaw", + [0x0011] = "adpcm_ima_wav", + [0x0050] = "mp2", + [0x0055] = "mp3", + [0x00FF] = "aac", + [0x1610] = "aac", + [0x706D] = "aac", + [0x2000] = "ac3", + [0x2001] = "dts", + [0xF1AC] = "flac", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function AviFormat.sniff(r) +if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoTrack(s, id) +local f = s.strf + local t= { + id = id, + kind = "video", + codec = "", + codecTag = s.handler, + timescale = (s.scale > 0 and((s.rate / s.scale ))or(25)), + frameRate = (s.scale > 0 and((s.rate / s.scale ))or(0)), + default = true, + name = s.name, + frames = s.length, + } + if buffer.len(f) >= 40 then + local w = buffer.readi32(f, 4) + local h = buffer.readi32(f, 8) + local bits = buffer.readu16(f, 14) + local comp = buffer.readstring(f, 16, 4) + t.width = math.abs(w) + t.height = math.abs(h) + t.codecTag = comp + t.bitsPerPixel = bits + if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then + t.codec = "rawvideo" + t.pixelFormat = bits == 32 and"bgra" or"bgr24" + t.flip = h > 0 + t.stride = (math.floor((math.abs(w) * bits + 31) / 32)) * 4 + if bits ~= 24 and bits ~= 32 then + t.codec = "rawvideo_" .. bits + end + else + t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", ""))) + if comp == "YV12" then + t.pixelFormat = "yv12" + elseif t.codec == "rawvideo" then + t.pixelFormat = "yuv420p" + end + end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end + local size = buffer.readu32(f, 0) + if size > 40 and buffer.len(f) > 40 then + local c = buffer.create(buffer.len(f) - 40) + buffer.copy(c, 0, f, 40) + t.config = c + end + else + t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler) + local fr = s.frame + t.width, t.height = fr[3] - fr[1], fr[4] - fr[2] + end + return t +end + +local function audioTrack(s, id) +local f = s.strf + local t= { + id = id, + kind = "audio", + codec = "unknown", + codecTag = s.handler, + timescale = (s.scale > 0 and((s.rate / s.scale ))or(1)), + default = true, + name = s.name, + waveFormat = f, + } + if buffer.len(f) >= 16 then + local tag = buffer.readu16(f, 0) + t.channels = buffer.readu16(f, 2) + t.sampleRate = buffer.readu32(f, 4) + t.blockAlign = buffer.readu16(f, 12) + local bits = buffer.readu16(f, 14) + t.bitsPerSample = bits + if tag == 0xFFFE and buffer.len(f) >= 26 then + tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag + end + t.formatTag = tag + local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag) + if c == "pcm" then + c = bits == 8 and"pcm_u8" or"pcm_s" .. bits .. "le" + elseif c == "pcm_f" then + c = "pcm_f" .. bits .. "le" + end + t.codec = c + if buffer.len(f) >= 18 then + local cb = buffer.readu16(f, 16) + if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then + local cfg = buffer.create(cb) + buffer.copy(cfg, 0, f, 18, cb) + t.config = cfg + end + end + end + return t +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function AviFormat.demux(r, _opts) +local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks= {} + local streams= {} + for i, s in __iter(file.streams) do + local t= nil + if s.type == "vids" then + t = videoTrack(s, i) + elseif s.type == "auds" then + t = audioTrack(s, i) + elseif s.type == "txts" then + t = { id = i, kind = "subtitle", codec = "text", timescale = (s.scale > 0 and((s.rate / s.scale ))or(1 ))} + end + if t then + table.insert(tracks, t) + table.insert(streams, { s, t }) + end + end + local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } + local dmx = Demux.new("avi", tracks, r.buf, meta) + -- packets in file order across streams: merge by offset + local items= {} + for k, st in __iter(streams) do + local s, t= st[1], st[2] + local tick = s.start + for _, c in __iter(s.chunks) do + local dur = (s.sampleSize > 0 and((c.size / s.sampleSize ))or(1 +)) if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then + dur = c.size / t.blockAlign + end + if c.size > 0 then + table.insert(items, { c.offset, k, tick, dur, c.key and 1 or 0, c.size }) + tick =tick+ dur + elseif t.kind == "video" then + tick =tick+ 1 -- an empty video chunk: a dropped frame keeps its slot (empty audio chunks are padding) + end + end + end + table.sort(items, function(a, b) +return a[1] < b[1] + end) + for _, it in __iter(items) do + local t= streams[it[2] ][2] + dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function AviFormat.encode(value, opts) +local o= table.clone(opts or {}) + o.quality = o.quality or 90 + local streams, err = Source.streams(value, o, { + video = { copy = { mjpeg = true }, encode = "mjpeg" }, + audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true }, + }) + if not streams then + return nil, err + end + local wstreams= {} + local width, height, usPerFrame = 0, 0, 0 + local frameDur = 0 + for _, s in __iter(streams) do + if s.kind == "video" then + -- a constant frame rate: the shortest frame duration (variable delays repeat frames) + local num, den, packets = Source.constantRate(s, o.maxFps) + s.packets = packets + frameDur = den / num + width, height = s.width or 0, s.height or 0 + usPerFrame = 1e6 * frameDur + local bih = Bytes.writer(40) + bih:u32le(40) + bih:u32le(width) + bih:u32le(height) + bih:u16le(1) + bih:u16le(24) + bih:string("MJPG") + bih:u32le(width * height * 3) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" }) + else + local ch = s.channels or 1 + local bits = s.codec == "pcm_u8" and 8 or 16 + local align = math.floor(ch * bits / 8 +) local rate = math.floor((s.sampleRate or 44100) + 0.5) + local wf = Bytes.writer(18) + wf:u16le(1) + wf:u16le(ch) + wf:u32le(rate) + wf:u32le(rate * align) + wf:u16le(align) + wf:u16le(bits) + wf:u16le(0) + table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) + end + end + -- chunks in time order (the video packets already repeated to the constant rate) + local chunks= {} + for _, item in __iter(Source.interleave(streams)) do + table.insert(chunks, { item[1], item[2].data, true }) + end + local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height } , chunks) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function AviFormat.open(r, opts) +local dmx, err = AviFormat.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return AviFormat +end +__FILES["video/fli"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in rosetta, written from the FLIC +-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). +-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: +-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, +-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 +-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the +-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. +-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r) +local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer | nil, Err +function Fli.demux(r, opts) +local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = magic == FLI and 70 or 1000 + local track= { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + -- the frame chunks + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, size) + end + p =p+ size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Fli.open(r, opts) +local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Fli +end +__FILES["video/flv"] = function() +local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict +-- video/flv: Flash Video (FLV, Adobe's Video File Format Specification v10, and the Enhanced RTMP / FLV extension's +-- FourCC video tags). New in rosetta. +-- Read: the header, the tag stream and onMetaData (AMF0: duration, width, height, framerate, codec ids, keyframes, ... +-- into meta.metadata) into a Demuxer (times in milliseconds; keyframe flags from the video tags; seeking by +-- keyframes) and open() returns a VideoDecoder: video through the codecs/video/Video registry (Sorenson Spark / FLV1 +-- and H.264 decode; VP6 / VP6 alpha, screen video 1 / 2 and enhanced FourCC codecs (HEVC, AV1, VP9) are known tracks +-- whose decoding is UNSUPPORTED); H.264's AVCDecoderConfigurationRecord in track.config, composition time offsets +-- in the pts. Audio through the api's opts.openAudio hook: MP3 (also 8 kHz), AAC (AudioSpecificConfig in track.config), +-- linear PCM (platform-endian read as little-endian), A-law / mu-law, Flash ADPCM (codecs/audio/Adpcm.swf, through +-- containers/AudioWrap); Nellymoser and Speex are known tracks without an audio decoder (UNSUPPORTED). Flv.demux(r) gives the Demuxer. +-- Write: H.264 / Sorenson Spark / VP6 / screen video copied from the source (FLV has no codec we encode), AAC / MP3 / +-- PCM / A-law / mu-law / ADPCM / Nellymoser / Speex audio copied (AAC from ADTS sources re-framed), else PCM s16 at +-- the FLV sample rates (5512 / 11025 / 22050 / 44100 Hz), with onMetaData (duration, sizes, frame rate, data +-- rates, codec ids, file size). +-- Not supported: encrypted tags (the track's packets are dropped, track.unsupported says so), multitrack and ModEx +-- enhanced packets (skipped), writing H.264 from Annex B sources (no avcC). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H263 = __include("codecs/video/H263") +local H264 = __include("codecs/video/H264") +local Aac = __include("codecs/audio/Aac") +local Amf = __include("video/flv/Amf") +local Mux = __include("video/flv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Flv = { + name = "flv", + category = "video", + extensions = { "flv" }, + mime = { "video/x-flv", "video/flv" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H263", "codecs/video/H264", "codecs/audio/Aac" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "flv1", "h264" }, audio = true, metadata = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +Flv.VIDEO_ID = 1 +Flv.AUDIO_ID = 2 + +-- SoundFormat -> codec id +local AUDIO_CODECS= { + [0] = "pcm", -- platform-endian (little-endian in practice) + [1] = "adpcm_swf", + [2] = "mp3", + [3] = "pcm", + [4] = "nellymoser", + [5] = "nellymoser", + [6] = "nellymoser", + [7] = "pcm_alaw", + [8] = "pcm_mulaw", + [10] = "aac", + [11] = "speex", + [14] = "mp3", + [15] = "device_specific", +} +local AUDIO_RATES = { [0] = 5512, 11025, 22050, 44100 } +-- the formats with a fixed rate (G.711: 8 kHz as ffmpeg reads them) / always mono +local FIXED_RATE= { [4] = 16000, [5] = 8000, [7] = 8000, [8] = 8000, [11] = 16000, [14] = 8000 } +local MONO= { [4] = true, [5] = true, [11] = true } + +-- CodecID -> codec id +local VIDEO_CODECS= { + [2] = "flv1", + [3] = "flashsv", + [4] = "vp6f", + [5] = "vp6a", + [6] = "flashsv2", + [7] = "h264", +} + +-- Enhanced FLV audio FourCCs +local AUDIO_FOURCC= { Opus = "opus", fLaC = "flac", mp4a = "aac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Flv.sniff(r) +if r:remaining() >= 9 and r:peek(3) == "FLV" then + return r:peekU8(3) == 1 and 1 or 0.6 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local readu8 = buffer.readu8 + +local function u24(b, p) +return readu8(b, p) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) +end + +local function s24(b, p) +local v = u24(b, p) + return (v >= 0x800000 and((v - 0x1000000 ))or(v +))end + +local function copy(b, p, n) +local c = buffer.create(n) + buffer.copy(c, 0, b, p, n) + return c +end + +-- the picture size of a codec's first keyframe (Sorenson, VP6, screen video) | nil +local function frameSize(codec, b, p, n) +if codec == "flv1" then + local h = H263.header(b, p, n, true) + if h then + return h.width, h.height + end + elseif (codec == "vp6f" or codec == "vp6a") and n >= 8 then + -- VP6 key frame header: type / quant / marker, version / profile / interlace, [16-bit offset], MB rows, MB + -- cols, display rows, display cols; the FLV adjustment byte (p - 1, before the frame) crops width / height + local adj = readu8(b, p - 1) + local q = p + (codec == "vp6a" and 3 or 0) + if q + 6 > p + n or readu8(b, q) >= 128 then + return nil, nil + end + local b1 = readu8(b, q + 1) + local o = q + 2 + if readu8(b, q) % 2 == 1 or (math.floor(b1 / 2)) % 4 == 0 then + o =o+ 2 + end + if o + 4 > p + n then + return nil, nil + end + local w = readu8(b, o + 3) * 16 - math.floor(adj / 16 +) local h = readu8(b, o + 2) * 16 - adj % 16 + if w > 0 and h > 0 then + return w, h + end + elseif (codec == "flashsv" or codec == "flashsv2") and n >= 4 then + return (readu8(b, p) % 16) * 256 + readu8(b, p + 1), (readu8(b, p + 2) % 16) * 256 + readu8(b, p + 3) + end + return nil, nil +end + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Flv.demux(r, opts) +local o= opts or {} + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 9 or buffer.readstring(b, base, 3) ~= "FLV" then + return nil, Err.new(Err.CORRUPT, "not an FLV file (no FLV signature)", base) + end + local flags = readu8(b, base + 4) + local dataOffset = buffer.readu32(b, base + 5) + dataOffset = bit32.byteswap(dataOffset) + if dataOffset < 9 or base + dataOffset > limit then + return nil, Err.new(Err.CORRUPT, "bad header size " .. dataOffset, base + 5) + end + local meta= { version = readu8(b, base + 3), hasAudio = bit32.band(flags, 4) ~= 0, hasVideo = bit32.band(flags, 1) ~= 0 } + local tracks= {} + local dmx = Demux.new("flv", tracks, b, meta) + local vt, at= nil, nil + local keyOff, keyLen = -1, 0 -- the first video keyframe + local maxPackets = o.maxPackets or 2 ^ 24 + local count = 0 + local p = base + dataOffset + 4 -- after PreviousTagSize0 + while p + 11 <= limit do + local tagType = bit32.band(readu8(b, p), 0x1F) + local filtered = bit32.band(readu8(b, p), 0x20) ~= 0 + local size = u24(b, p + 1) + local ts = u24(b, p + 4) + readu8(b, p + 7) * 0x1000000 + if ts >= 0x80000000 then + ts =ts- 0x100000000 + end + local d = p + 11 + if d + size > limit then + meta.truncated = true + break + end + count =count+ 1 + if count > maxPackets then + return nil, Err.new(Err.LIMIT, "more than " .. maxPackets .. " tags") + end + if tagType == 8 and size >= 1 then + local a = readu8(b, d) + local fmt = math.floor(a / 16 +) if not at then + at = { id = Flv.AUDIO_ID, kind = "audio", codec = "unknown", codecTag = "flv audio " .. fmt, timescale = 1000, default = true } + table.insert(tracks, at) + local bits = (math.floor(a / 2)) % 2 == 1 and 16 or 8 + local codec = AUDIO_CODECS[fmt] or ("flv_audio_" .. fmt) + if codec == "pcm" then + codec = bits == 16 and"pcm_s16le" or"pcm_u8" + end + at.codec = codec + at.soundFormat = fmt + at.sampleRate = FIXED_RATE[fmt] or AUDIO_RATES[(math.floor(a / 4)) % 4] + at.channels = MONO[fmt] and 1 or a % 2 + 1 + at.bitsPerSample = (codec == "pcm_alaw" or codec == "pcm_mulaw" )and 8 or bits + end + if filtered then + at.unsupported = "encrypted audio tags" + elseif fmt == 10 and at.soundFormat == 10 then + if size >= 2 then + if readu8(b, d + 1) == 0 then + local c = copy(b, d + 2, size - 2) + at.config = c + local cfg = Aac.config(c) + if cfg then + at.sampleRate = cfg.extensionRate or cfg.sampleRate + at.channels = cfg.channels + end + elseif size > 2 then + dmx:add(at.id, ts, nil, nil, true, d + 2, size - 2) + end + end + elseif fmt == 9 and at.soundFormat == 9 then + -- Enhanced FLV: packet type, FourCC + if size >= 5 then + local pt = a % 16 + local fcc = buffer.readstring(b, d + 1, 4) + at.codec = AUDIO_FOURCC[fcc] or fcc + at.codecTag = fcc + if pt == 0 then + at.config = copy(b, d + 5, size - 5) + elseif pt == 1 and size > 5 then + dmx:add(at.id, ts, nil, nil, true, d + 5, size - 5) + end + end + elseif fmt == at.soundFormat and size > 1 then + dmx:add(at.id, ts, nil, nil, true, d + 1, size - 1) + end + elseif tagType == 9 and size >= 1 then + local v = readu8(b, d) + local enhanced = v >= 128 + local frameType = (enhanced and(((math.floor(v / 16)) % 8 ))or((math.floor(v / 16 +)))) if frameType ~= 5 then -- not a video info / command frame + local codec, codecTag= nil, nil + local pt, cts, q, n = 0, 0, 0, 0 + if enhanced then + if size < 5 then + codec = nil + else + local fcc = buffer.readstring(b, d + 1, 4) + codec, codecTag = Video.fromFourcc(fcc) or fcc, fcc + pt = v % 16 + q, n, cts = d + 5, size - 5, 0 + if pt == 1 and (fcc == "avc1" or fcc == "hvc1") then + if n >= 3 then + cts = s24(b, q) + end + q, n = q + 3, n - 3 + elseif pt == 3 then + pt = 1 -- coded frames without a composition time + end + end + else + local id = v % 16 + codec = VIDEO_CODECS[id] or ("flv_video_" .. id) + codecTag = "flv video " .. id + pt, q, n, cts = 1, d + 1, size - 1, 0 + if codec == "h264" then + if size >= 5 then + pt = readu8(b, d + 1) + cts = s24(b, d + 2) + else + pt = 2 + end + q, n = d + 5, size - 5 + elseif codec == "vp6f" or codec == "vp6a" then + q, n = d + 2, size - 2 -- after the adjustment byte (the track's config, as ffmpeg's extradata) + end + end + if codec then + if not vt then + vt = { id = Flv.VIDEO_ID, kind = "video", codec = codec, codecTag = codecTag, timescale = 1000, default = true } + table.insert(tracks, vt) + end + if (codec == "vp6f" or codec == "vp6a") and not vt.config and size >= 2 then + vt.config = copy(b, d + 1, 1) -- the crop (adjustment) byte + end + if filtered then + vt.unsupported = "encrypted video tags" + elseif codec == vt.codec then + if pt == 0 then + if n > 0 then + vt.config = copy(b, q, n) + end + elseif pt == 1 and n > 0 then + local key = frameType == 1 + dmx:add(vt.id, ts + cts, ts, nil, key, q, n) + if key and keyOff < 0 then + keyOff, keyLen = q, n + end + end + end + end + end + elseif tagType == 18 and size > 0 then + local name, value = Amf.script(Bytes.reader(b, d, size)) + if name == "onMetaData" and type(value) == "table" and meta.metadata == nil then + meta.metadata = value + elseif name then + meta.scripts = meta.scripts or {} + table.insert(meta.scripts, { name = name, time = ts / 1000, value = value }) + end + end + p = d + size + 4 + end + -- the track facts onMetaData and the codec headers give + local md= meta.metadata or {} + if type(md.duration) == "number" and md.duration > 0 then + meta.duration = md.duration + end + if vt then + if vt.codec == "h264" and vt.config then + local ok, info = pcall(H264.info, vt.config) + if ok and info then + vt.width, vt.height = info.width, info.height + end + elseif keyOff >= 0 then + local w, h = frameSize(vt.codec, b, keyOff, keyLen) + vt.width, vt.height = w, h + end + if not vt.width and type(md.width) == "number" and type(md.height) == "number" then + vt.width, vt.height = math.floor(md.width), math.floor(md.height) + end + local fr = md.framerate or md.videoframerate + if type(fr) == "number" and fr > 0 and fr < 1000 then + vt.frameRate = fr + else + -- from the timestamps: the frames over the time they span + local n = dmx:count(vt.id) + local t0 = (n > 0 and{(dmx:info(vt.id, 1) )}or{nil +})[1] local t1 = (n > 1 and{(dmx:info(vt.id, n) )}or{nil +})[1] if t0 and t1 and t1 > t0 then + vt.frameRate = math.floor((n - 1) / ((t1 - t0) / 1000) * 1000 + 0.5) / 1000 + end + end + end + if at and at.codec == "aac" and not at.config then + at.unsupported = "AAC without its AudioSpecificConfig" + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open) or a Demuxer +function Flv.encode(value, opts) +local o= opts or {} + local streams, err = Source.streams(value, o, { + video = { copy = Mux.VIDEO_COPY }, + audio = { copy = Mux.AUDIO_COPY, pcm = true }, + }) + if not streams then + return nil, err + end + -- audio FLV cannot hold (PCM at other rates): dropped, or an error with opts.audio = true + for i = #streams, 1, -1 do + local s = streams[i] + local why = s.kind == "audio" and Mux.audioProblem(s) + if why then + if o.audio == true then + return nil, Err.new(Err.UNSUPPORTED, why) + end + table.remove(streams, i) + end + end + if #streams == 0 then + return nil, Err.new(Err.UNSUPPORTED, "nothing FLV can hold") + end + local ok, buf, merr = pcall(Mux.mux, streams) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Flv.open(r, opts) +local ok, dmx, err = pcall(Flv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Flv +end +__FILES["video/flv/Amf"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- video/flv/Amf: AMF0 values (Adobe's Action Message Format 0, as FLV script data tags use it). Written from the AMF0 +-- specification and the FLV specification v10. Read: number, boolean, string, object, null, undefined, reference +-- (the referenced object), ECMA array, strict array, date (milliseconds), long string; anything else stops the +-- value. Write: numbers, booleans, strings, strict arrays and ECMA arrays (ordered key / value lists). Never throws. +-- +-- local name, value = Amf.script(reader) -- a script tag body: "onMetaData", { duration = 12.3, ... } +-- Amf.writeValue(w, v); Amf.writeEcma(w, { { "duration", 12.3 }, ... }) +local Bytes = __include("core/Bytes") + +local Amf = {} + +-- null / undefined inside arrays (dropped from objects) +Amf.NULL = table.freeze({}) + +local MAX_DEPTH = 32 + +local function str(r, long) +local n = (long and{(r:u32be() )}or{(r:u16be() +)})[1] return r:string(n) +end + +local readValue +-- object properties up to the end marker (00 00 09) or the end of the data + +local function props(r, depth, refs, into) +while not r.err and r:remaining() >= 3 do + local key = str(r, false) + if key == "" and r:peekU8() == 9 then + r:skip(1) + return true + end + local v = readValue(r, depth + 1, refs) + if r.err or v == nil then + return false + end + if v ~= Amf.NULL then + into[key] = v + end + end + return false +end + +readValue = function(r, depth, refs) +if depth > MAX_DEPTH or r:remaining() < 1 then + return nil + end + local t = r:u8() + if t == 0 then + return r:f64be() + elseif t == 1 then + return r:u8() ~= 0 + elseif t == 2 then + return str(r, false) + elseif t == 12 then + return str(r, true) + elseif t == 3 or t == 8 then + if t == 8 then + r:u32be() -- the count (approximate in practice: the end marker ends it) + end + local o= {} + table.insert(refs, o) + props(r, depth, refs, o) + return o + elseif t == 10 then + local n = r:u32be() + local a= {} + table.insert(refs, a) + for i = 1, n do + if r.err or r:remaining() < 1 then + break + end + local v = readValue(r, depth + 1, refs) + if v == nil then + break + end + a[i] = v + end + return a + elseif t == 5 or t == 6 then + return Amf.NULL + elseif t == 7 then + local i = r:u16be() + return refs[i + 1] or Amf.NULL + elseif t == 11 then + local ms = r:f64be() + r:i16be() + return ms + end + return nil +end + +-- value(reader) -> the next AMF0 value | nil (unknown type, truncated, nested too deep) +function Amf.value(r) +local ok, v = pcall(readValue, r, 0, {}) + return (ok and not r.err and{v }or{nil +})[1]end + +-- script(reader) -> name, value: a script data tag body (an AMF0 string, then its value) | nil +function Amf.script(r) +local name = Amf.value(r) + if type(name) ~= "string" then + return nil, nil + end + return name, Amf.value(r) +end + +-- ------------------------------------------------------------------------------------------------ write +local function writeString(w, s) + if #s > 65535 then + w:u8(12) + w:u32be(#s) + else + w:u8(2) + w:u16be(#s) + end + w:string(s) +end + +-- writeValue(w, v): a number, boolean, string, array (strict array) or Amf.NULL; other values are written as null +function Amf.writeValue(w, v) + local t = type(v) + if t == "number" then + w:u8(0) + w:f64be(v) + elseif t == "boolean" then + w:u8(1) + w:u8(v and 1 or 0) + elseif t == "string" then + writeString(w, v) + elseif t == "table" and v ~= Amf.NULL and #v > 0 then + w:u8(10) + w:u32be(#v) + for _, x in __iter(v) do + Amf.writeValue(w, x) + end + else + w:u8(5) + end +end + +-- writeEcma(w, list): an ECMA array of { key, value } pairs (values: as writeValue; a list nested as +-- { key, { pairs = { ... } } } becomes an object) +function Amf.writeEcma(w, list, object) + if object then + w:u8(3) + else + w:u8(8) + w:u32be(#list) + end + for _, kv in __iter(list) do + local k= kv[1] + w:u16be(#k) + w:string(k) + local v = kv[2] + if type(v) == "table" and v.pairs then + Amf.writeEcma(w, v.pairs, true) + else + Amf.writeValue(w, v) + end + end + w:u16be(0) + w:u8(9) +end + +return Amf +end +__FILES["video/flv/Mux"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- video/flv/Mux: the FLV writer (Adobe's Video File Format Specification v10): the header, an onMetaData script tag +-- (duration, width, height, data rates, frame rate, codec ids, audio format, encoder, file size), the H.264 +-- AVCDecoderConfigurationRecord / AAC AudioSpecificConfig sequence headers, the packets of codecs/video/Video/Source +-- streams as tags interleaved by decode time (milliseconds, shifted so none is negative; H.264 composition times), +-- and H.264's end-of-sequence tag. AAC from ADTS sources (MPEG-TS) is split into raw frames with a configuration made +-- from the first ADTS header. Interpreted; never throws (returns nil, Err). +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Amf = __include("video/flv/Amf") + +local Mux = {} + +-- the codecs FLV holds (copied from the source) +local VIDEO_COPY= { h264 = true, flv1 = true, vp6f = true, vp6a = true, flashsv = true, flashsv2 = true } +local AUDIO_COPY= { aac = true, mp3 = true, pcm_s16le = true, pcm_u8 = true, pcm_alaw = true, pcm_mulaw = true, adpcm_swf = true, nellymoser = true, speex = true } +Mux.VIDEO_COPY = VIDEO_COPY +Mux.AUDIO_COPY = AUDIO_COPY + +local VIDEO_IDS= { flv1 = 2, flashsv = 3, vp6f = 4, vp6a = 5, flashsv2 = 6, h264 = 7 } +local AUDIO_FORMATS= { pcm_s16le = 3, pcm_u8 = 3, adpcm_swf = 1, mp3 = 2, nellymoser = 6, pcm_alaw = 7, pcm_mulaw = 8, aac = 10, speex = 11 } +local RATE_CODES= { [5512] = 0, [5513] = 0, [11025] = 1, [22050] = 2, [44100] = 3 } +local AAC_RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + +local function isAdts(s) +if s.track and s.track.adts then + return true + end + local p = s.packets[1] + return s.config == nil and p ~= nil and buffer.len(p.data) >= 7 and buffer.readu8(p.data, 0) == 0xFF and buffer.readu8(p.data, 1) >= 0xF0 +end + +-- audioProblem(stream) -> why FLV cannot hold this audio stream | nil +function Mux.audioProblem(s) +local fmt = AUDIO_FORMATS[s.codec] + if not fmt then + return "FLV has no audio codec " .. tostring(s.codec) + end + if (s.channels or 1) > 2 then + return "FLV audio has at most 2 channels" + end + local rate = math.floor((s.sampleRate or 0) + 0.5) + if s.codec == "aac" then + if not s.config and not isAdts(s) then + return "AAC without its AudioSpecificConfig" + end + elseif (s.codec == "pcm_alaw" or s.codec == "pcm_mulaw") and rate ~= 8000 then + return "FLV G.711 audio is 8000 Hz (not " .. rate .. ")" + elseif s.codec ~= "mp3" and s.codec ~= "speex" and s.codec ~= "nellymoser" and s.codec ~= "pcm_alaw" and s.codec ~= "pcm_mulaw" and RATE_CODES[rate] == nil then + return "FLV " .. s.codec .. " audio is 5512, 11025, 22050 or 44100 Hz (not " .. rate .. ")" + end + return nil +end + +local function audioFlags(s) +local fmt = AUDIO_FORMATS[s.codec] + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local rc = RATE_CODES[rate] or 3 + local size = s.codec == "pcm_u8" and 0 or 1 + local stereo = (s.channels or 1) > 1 and 1 or 0 + if s.codec == "aac" then + rc, stereo = 3, 1 + elseif s.codec == "mp3" and rate == 8000 then + fmt = 14 + elseif s.codec == "speex" then + rc, stereo = 0, 0 + elseif s.codec == "pcm_alaw" or s.codec == "pcm_mulaw" then + rc = 0 + elseif s.codec == "nellymoser" then + if rate == 16000 then + fmt = 4 + elseif rate == 8000 then + fmt = 5 + end + stereo = 0 + end + return fmt * 16 + rc * 4 + size * 2 + stereo +end + +-- ADTS frames -> raw AAC frames (1024 samples each) and the AudioSpecificConfig of the first header +local function fromAdts(s) +local out = {} + local cfg= nil + local rate = s.sampleRate or 44100 + for _, p in __iter(s.packets) do + local d= p.data + local n = buffer.len(d) + local o = 0 + local t = p.pts + while o + 7 <= n do + local b1, b2, b3 = buffer.readu8(d, o + 1), buffer.readu8(d, o + 2), buffer.readu8(d, o + 3) + if buffer.readu8(d, o) ~= 0xFF or b1 < 0xF0 then + return nil, nil + end + local len = (b3 % 4) * 2048 + buffer.readu8(d, o + 4) * 8 + math.floor(buffer.readu8(d, o + 5) / 32 +) local hl = b1 % 2 == 1 and 7 or 9 + if len < hl or o + len > n then + return nil, nil + end + if not cfg then + local aot = math.floor(b2 / 64 )+ 1 + local sfi = (math.floor(b2 / 4)) % 16 + local ch = (b2 % 2) * 4 + math.floor(b3 / 64 +) cfg = buffer.create(2) + buffer.writeu8(cfg, 0, aot * 8 + math.floor(sfi / 2)) + buffer.writeu8(cfg, 1, (sfi % 2) * 128 + ch * 8) + rate = AAC_RATES[sfi + 1] or rate + end + local f = buffer.create(len - hl) + buffer.copy(f, 0, d, o + hl, len - hl) + table.insert(out, { pts = t, dts = t, duration = 1024 / rate, keyframe = true, data = f }) + t =t+ 1024 / rate + o =o+ len + end + end + return out, cfg +end + +local function f64At(b, at, v) + local t = buffer.create(8) + buffer.writef64(t, 0, v) + for i = 0, 7 do + buffer.writeu8(b, at + i, buffer.readu8(t, 7 - i)) + end +end + +-- mux(streams) -> buffer | nil, Err +function Mux.mux(streams) +local video, audio = nil , nil +for _, s in __iter(streams) do + if s.kind == "video" and not video then + if not VIDEO_IDS[s.codec] then + return nil, Err.new(Err.UNSUPPORTED, "FLV has no video codec " .. tostring(s.codec)) + end + if s.codec == "h264" and (s.config == nil or buffer.len(s.config) < 7 or buffer.readu8(s.config, 0) ~= 1) then + return nil, Err.new(Err.UNSUPPORTED, "H.264 without an avcC (an Annex B source) cannot be written to FLV") + end + video = s + elseif s.kind == "audio" and not audio then + audio = s + end + end + if not video and not audio then + return nil, Err.new(Err.ARG, "no video or audio stream") + end + local aConfig= audio and audio.config + local aPackets= audio and audio.packets or {} + if audio and audio.codec == "aac" and isAdts(audio) then + local pk, cfg = fromAdts(audio) + if not pk or not cfg then + return nil, Err.new(Err.CORRUPT, "bad ADTS AAC audio") + end + aPackets, aConfig = pk, cfg + end + local order= {} -- { kind, packet } + do + local vi, ai = 1, 1 + local vp= (video and{video.packets }or{{} +})[1] while vi <= #vp or ai <= #aPackets do + local a, v = aPackets[ai], vp[vi] + if v and (not a or (v.dts or v.pts) <= (a.dts or a.pts)) then + table.insert(order, { "video", v }) + vi =vi+ 1 + else + table.insert(order, { "audio", a }) + ai =ai+ 1 + end + end + end + -- times: milliseconds, shifted so the earliest decode time is 0 when any is negative + local shift = 0 + local duration = 0 + local vBytes, aBytes = 0, 0 + for _, e in __iter(order) do + local p = e[2] + local t = p.dts or p.pts + if t < -shift then + shift = -t + end + duration = math.max(duration, p.pts + (p.duration or 0)) + if e[1] == "video" then + vBytes =vBytes+ buffer.len(p.data) + else + aBytes =aBytes+ buffer.len(p.data) + end + end + local function ms(t) +return math.floor((t + shift) * 1000 + 0.5) + end + + local w = Bytes.writer(65536 + vBytes + aBytes + #order * 20) + w:string("FLV") + w:u8(1) + w:u8((audio and 4 or 0) + (video and 1 or 0)) + w:u32be(9) + w:u32be(0) + local function tag(kind, ts, head, data) + local n = #head + ((data and{(buffer.len(data) )}or{0})[1]) + w:u8(kind) + w:u24be(n) + local t = ts % 0x100000000 + w:u24be(t % 0x1000000) + w:u8(math.floor(t / 0x1000000)) + w:u24be(0) + for _, x in __iter(head) do + w:u8(x) + end + if data then + w:bytes(data) + end + w:u32be(11 + n) + end + + -- onMetaData + local props= { { "duration", duration } } + if video then + table.insert(props, { "width", video.width or 0 }) + table.insert(props, { "height", video.height or 0 }) + table.insert(props, { "videodatarate", (duration > 0 and((vBytes * 8 / duration / 1000 ))or(0 ))}) + table.insert(props, { "framerate", video.frameRate or 0 }) + table.insert(props, { "videocodecid", VIDEO_IDS[video.codec] }) + end + if audio then + local flags = audioFlags(audio) + table.insert(props, { "audiodatarate", (duration > 0 and((aBytes * 8 / duration / 1000 ))or(0 ))}) + table.insert(props, { "audiosamplerate", math.floor((audio.sampleRate or 44100) + 0.5) }) + table.insert(props, { "audiosamplesize", audio.codec == "pcm_u8" and 8 or 16 }) + table.insert(props, { "stereo", (audio.channels or 1) > 1 }) + table.insert(props, { "audiocodecid", math.floor(flags / 16 )}) + end + table.insert(props, { "encoder", "rosetta" }) + table.insert(props, { "filesize", 0 }) + local mw = Bytes.writer(512) + Amf.writeValue(mw, "onMetaData") + Amf.writeEcma(mw, props) + local metaBody = mw:finish() + local metaAt = w:tell() + 11 + tag(18, 0, {}, metaBody) + local fileSizeAt = metaAt + buffer.len(metaBody) - 3 - 8 -- the last value (filesize) before the end marker + + -- sequence headers + local vid = (video and{VIDEO_IDS[video.codec] }or{0 +})[1] if video and video.codec == "h264" then + tag(9, 0, { 0x10 + vid, 0, 0, 0, 0 }, video.config) + end + local aflags = (audio and{(audioFlags(audio) )}or{0 +})[1] if audio and audio.codec == "aac" then + tag(8, 0, { aflags, 0 }, aConfig) + end + local vp6 = (video and (video.codec == "vp6f" or video.codec == "vp6a") and{video.config }or{nil +})[1] local vp6Byte = (vp6 and buffer.len(vp6) > 0 and{(buffer.readu8(vp6, 0) )}or{0 +})[1] if video and (video.codec == "vp6f" or video.codec == "vp6a") and not vp6 then + local wd, ht = video.width or 0, video.height or 0 + vp6Byte = ((16 - wd % 16) % 16) * 16 + (16 - ht % 16) % 16 + end + local lastVideo = 0 + for _, e in __iter(order) do + local p = e[2] + local dts = ms(p.dts or p.pts) + if e[1] == "video" then + local ft = (p.keyframe and 1 or 2) * 16 + vid + if video.codec == "h264" then + local cts = ms(p.pts) - dts + if cts < 0 then + cts =cts+ 0x1000000 + end + tag(9, dts, { ft, 1, math.floor(cts / 65536 )% 256, math.floor(cts / 256 )% 256, cts % 256 }, p.data) + elseif vp6 or video.codec == "vp6f" or video.codec == "vp6a" then + tag(9, dts, { ft, vp6Byte }, p.data) + else + tag(9, dts, { ft }, p.data) + end + lastVideo = math.max(lastVideo, dts) + elseif audio.codec == "aac" then + tag(8, dts, { aflags, 1 }, p.data) + else + tag(8, dts, { aflags }, p.data) + end + end + if video and video.codec == "h264" then + tag(9, lastVideo, { 0x10 + vid, 2, 0, 0, 0 }, nil) + end + local out = w:finish() + f64At(out, fileSizeAt, buffer.len(out)) + return out, nil +end + +return Mux +end +__FILES["video/h264"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- video/h264: raw H.264 / AVC elementary streams (ITU-T H.264 Annex B byte stream: .h264 / .264 files, x264 / ffmpeg +-- `-f h264` output, the JVT conformance bitstreams). New in rosetta. +-- Read: the stream cut into access units (codecs/video/H264.accessUnits) as a one-track Demuxer; open() returns a +-- VideoDecoder decoding through codecs/video/H264 (yuv420p frames in display order, numbered in output order since a raw +-- stream has no timestamps; the frame rate comes from the SPS VUI timing, else opts.frameRate, else 25). +-- Write: H.264 tracks copied from any video (MP4 / MKV samples are converted from length-prefixed NAL units to Annex B, +-- the avcC parameter sets put in front of every keyframe). Not supported: re-encoding other codecs to H.264 (there is +-- no H.264 encoder), and whatever codecs/video/H264 does not decode (interlaced, 4:2:2 / 4:4:4, > 8 bits: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local H264 = __include("codecs/video/H264") + +-- ------------------------------------------------------------------------------------------------ contract +local Format = { + name = "h264", + category = "video", + extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" }, + mime = { "video/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 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff +-- a start code then an SPS / AUD / SEI / PPS NAL header (forbidden bit 0) + + + + + + + + +function Format.sniff(r) +local s = r:peek(5) + if not s or #s < 4 then + return 0 + end + local hdr + if string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 1 then + hdr = string.byte(s, 4) + elseif #s >= 5 and string.byte(s, 1) == 0 and string.byte(s, 2) == 0 and string.byte(s, 3) == 0 and string.byte(s, 4) == 1 then + hdr = string.byte(s, 5) + else + return 0 + end + if hdr >= 128 then + return 0 + end + local t = hdr % 32 + if t == 7 then + return 0.8 + elseif t == 9 or t == 6 or t == 8 then + return 0.5 + elseif t == 5 then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer (one video track, one packet per access unit) | nil, Err +function Format.demux(r, opts) +local buf, base, limit = r.buf, r.base, r.limit + local units = H264.accessUnits(buf, base, limit - base) + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no access units (no slices after a start code)", base) + end + local info = H264.info(buffer.readstring(buf, base, math.min(limit - base, 4096))) or {} + if info.interlaced or (info.chromaFormat and info.chromaFormat ~= 1) or (info.bitDepth and info.bitDepth ~= 8) then + -- still demuxable (remuxing works); decoding reports UNSUPPORTED + info.unsupported = true + end + local fps = info.frameRate or (opts and opts.frameRate) or 25 + if fps <= 0 or fps > 1000 then + fps = 25 + end + local track= { + id = 1, + kind = "video", + codec = "h264", + timescale = fps, + width = info.width, + height = info.height, + frameRate = fps, + profile = info.profile, + level = info.level, + ptsInOutputOrder = true, + default = true, + } + local dmx = Demux.new("h264", { track }, buf, { profile = info.profile, level = info.level }) + local k = 0 + for i = 1, #units, 3 do + dmx:add(1, k, k, 1, units[i + 2] or k == 0, units[i], units[i + 1]) + k =k+ 1 + end + track.frames = k + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> an Annex B buffer of the source's H.264 track | nil, Err (UNSUPPORTED for other codecs) +function Format.encode(value, _opts) +local streams, err = Source.streams(value, { audio = false }, { video = { copy = { h264 = true } } }) + if not streams then + return nil, err + end + local s = streams[1] + if not s or s.codec ~= "h264" then + return nil, Err.new(Err.UNSUPPORTED, "only H.264 tracks can be written as a raw H.264 stream") + end + local parts = {} + for i, p in __iter(s.packets) do + local data = p.data + if s.config then + local key = i == 1 or p.keyframe + local out, e = H264.toAnnexB((key and{s.config }or{nil})[1], data) + if not out then + return nil, e + end + data = out + end + table.insert(parts, buffer.tostring(data)) + end + return buffer.fromstring(table.concat(parts)), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Format.open(r, opts) +local dmx, err = Format.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Format +end +__FILES["video/mkv"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in +-- rosetta, on containers/Ebml. +-- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, +-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video +-- through the codecs/video/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio +-- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text +-- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. +-- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied +-- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from +-- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. +-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, +-- track.unsupported says why), chapters / attachments (skipped), writing subtitles. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") +local Mux = __include("video/mkv/Mux") + +-- ------------------------------------------------------------------------------------------------ contract +local Mkv = { + name = "mkv", + category = "video", + 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", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "theora", "rawvideo" }, audio = true, subtitles = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + + + + +local WEBM_VIDEO = { vp8 = true, vp9 = true, av1 = true } +local WEBM_AUDIO = { opus = true, vorbis = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mkv.sniff(r) +if r:peek(4) ~= "\26\69\223\163" then + return 0 + end + local head = r:peek(math.min(64, r:remaining())) + if string.find(head, "webm", 1, true) or string.find(head, "matroska", 1, true) then + return 1 + end + return 0.5 +end + +-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws) +function Mkv.variant(r) +local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit) + if ok and docType == "webm" then + return "webm" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image) +-- or a Demuxer +function Mkv.encode(value, opts) +local o= opts or {} + local webm = o.webm == true or (type(o.format) == "string" and string.lower(o.format) == "webm") + local want +if webm then + want = { video = { copy = WEBM_VIDEO }, audio = { copy = WEBM_AUDIO } } + else + local copy= {} + for id, e in __iter(Video.codecs) do + if e.matroska then + copy[id] = true + end + end + want = { video = { copy = copy, encode = "mjpeg" }, audio = { copy = { ["*"] = true }, pcm = true } } + end + local so = table.clone(o) + so.quality = so.quality or 90 + local streams, err = Source.streams(value, so, want) + if not streams then + return nil, err + end + if not webm then + -- audio codecs Matroska cannot name: PCM instead + for i, s in __iter(streams) do + if s.kind == "audio" and not Mux.codecId("audio", s.codec) then + local alt, aerr = Source.streams(value, { video = false, reencodeAudio = true }, { audio = { pcm = true } }) + if alt and alt[1] then + streams[i] = alt[1] + else + return nil, aerr + end + end + end + end + local ok, buf, merr = pcall(Mux.mux, streams, { webm = webm, title = o.title, clusterSeconds = o.clusterSeconds }) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, merr +end + +-- ------------------------------------------------------------------------------------------------ open +-- demux(r, opts?) -> the Demuxer (containers/Demux: tracks, packets, read, seek, count / get) | nil, Err +function Mkv.demux(r, opts) +local ok, dmx, err = pcall(Parse.parse, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + return dmx, err +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Mkv.open(r, opts) +local dmx, err = Mkv.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +-- ------------------------------------------------------------------------------------------------ extras +-- subtitles(demuxer, trackId?) -> Types.Subtitles from a text subtitle track (S_TEXT/UTF8, WebVTT, ASS text) | nil +function Mkv.subtitles(dmx, trackId) +local track = nil + for _, t in __iter(dmx.tracks) do + if t.kind == "subtitle" and (trackId == nil or t.id == trackId) then + track = t + break + end + end + if not track then + return nil + end + local subs = Types.Subtitles.new() + subs.meta.codec = track.codec + subs.meta.language = track.language + for k = 1, dmx:count(track.id) do + local p = dmx:get(track.id, k) + if p then + local start = p.pts / track.timescale + local stop = start + (p.duration or 0) / track.timescale + table.insert(subs.cues, { start = start, stop = stop, text = buffer.tostring(p.data) } ) + end + end + return subs +end + +return Mkv +end +__FILES["video/mkv/Mux"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- video/mkv/Mux: the Matroska / WebM muxer: EBML header, Segment with SeekHead, Info (1 ms TimecodeScale, Duration), +-- Tracks (CodecPrivate, DefaultDuration, Video / Audio settings, Opus CodecDelay / SeekPreRoll), Clusters of +-- SimpleBlocks (a new cluster at a video keyframe once the current one spans 2 s, and before the 16-bit relative +-- timestamp would overflow), and Cues (one CuePoint per cluster, on the video track when there is one). Streams come +-- from codecs/video/Video/Source (copied packets or encoded frames). Interpreted; never throws. +local Err = __include("core/Err") +local Ebml = __include("containers/Ebml") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") +local Parse = __include("video/mkv/Parse") + +local ID = Parse.ID +local Mux = {} + +local AUDIO_IDS= { + vorbis = "A_VORBIS", + opus = "A_OPUS", + flac = "A_FLAC", + mp3 = "A_MPEG/L3", + mp2 = "A_MPEG/L2", + mp1 = "A_MPEG/L1", + aac = "A_AAC", + ac3 = "A_AC3", + eac3 = "A_EAC3", + alac = "A_ALAC", + pcm_u8 = "A_PCM/INT/LIT", + pcm_s16le = "A_PCM/INT/LIT", + pcm_s24le = "A_PCM/INT/LIT", + pcm_s32le = "A_PCM/INT/LIT", + pcm_s16be = "A_PCM/INT/BIG", + pcm_s24be = "A_PCM/INT/BIG", + pcm_s32be = "A_PCM/INT/BIG", + pcm_f32le = "A_PCM/FLOAT/IEEE", + pcm_f64le = "A_PCM/FLOAT/IEEE", +} +Mux.AUDIO_IDS = AUDIO_IDS + +-- codecId(stream) -> the Matroska CodecID | nil +function Mux.codecId(kind, codec) +if kind == "video" then + local e = Video.entry(codec) + local m = e and e.matroska + return m and m[1] + end + return AUDIO_IDS[codec] +end + +local function pcmBits(codec) +local b = string.match(codec, "^pcm_[suf](%d+)") + if b then + return tonumber(b) + end + if codec == "pcm_u8" then + return 8 + end + return nil +end + +-- mux(streams, opts) -> buffer | nil, Err + + + + + + + +function Mux.mux(streams, opts) +local webm = opts.webm == true + local app = opts.app or "rosetta" + local clusterSpan = opts.clusterSeconds or 2 + -- tracks + local ids= {} + local videoIndex = 0 + for i, s in __iter(streams) do + local cid = Mux.codecId(s.kind, s.codec) + if not cid then + return nil, Err.new(Err.UNSUPPORTED, "no Matroska CodecID for " .. s.kind .. " codec " .. s.codec) + end + ids[i] = cid + if s.kind == "video" and videoIndex == 0 then + videoIndex = i + end + end + local order = Source.interleave(streams) + local duration = 0 + for _, s in __iter(streams) do + for _, p in __iter(s.packets) do + local e = p.pts + (p.duration or 0) + if e > duration then + duration = e + end + end + end + + -- segment body: Info, Tracks, Clusters, Cues (the SeekHead goes in front once their offsets are known) + local body = Ebml.writer(65536) + local infoAt = body:tell() + local info = body:open(ID.Info) + body:uint(ID.TimecodeScale, 1000000) + body:string(ID.MuxingApp, app) + body:string(ID.WritingApp, app) + if opts.title then + body:string(ID.Title, opts.title) + end + body:float(ID.Duration, duration * 1000) + body:close(info) + + local tracksAt = body:tell() + local tracks = body:open(ID.Tracks) + for i, s in __iter(streams) do + local te = body:open(ID.TrackEntry) + body:uint(ID.TrackNumber, i) + body:uint(ID.TrackUID, i) + body:uint(ID.TrackType, s.kind == "video" and 1 or 2) + body:uint(ID.FlagLacing, 0) + body:string(ID.Language, "und") + body:string(ID.CodecID, ids[i]) + if s.config and buffer.len(s.config) > 0 then + body:binary(ID.CodecPrivate, s.config) + end + if s.kind == "video" then + if s.frameRate and s.frameRate > 0 then + body:uint(ID.DefaultDuration, math.floor(1e9 / s.frameRate + 0.5)) + end + local v = body:open(ID.Video) + body:uint(ID.PixelWidth, s.width or 0) + body:uint(ID.PixelHeight, s.height or 0) + body:close(v) + else + if s.codec == "opus" then + local pre = 0 + local c = s.config + if c and buffer.len(c) >= 12 then + pre = buffer.readu16(c, 10) + end + body:uint(ID.CodecDelay, math.floor(pre * 1e9 / 48000 + 0.5)) + body:uint(ID.SeekPreRoll, 80000000) + end + local a = body:open(ID.Audio) + body:float(ID.SamplingFrequency, s.sampleRate or 48000) + body:uint(ID.Channels, s.channels or 1) + local bits = pcmBits(s.codec) or s.bitsPerSample + if bits and string.sub(s.codec, 1, 4) == "pcm_" then + body:uint(ID.BitDepth, bits) + end + body:close(a) + end + body:close(te) + end + body:close(tracks) + + -- clusters + local cues= {} -- { time ms, track, cluster offset in body } + local cl= nil + local clTime = 0 + local clStart = 0 + for _, item in __iter(order) do + local si, p = item[1], item[2] + local ms = math.floor(p.pts * 1000 + 0.5) + local isVideoKey = si == videoIndex and p.keyframe + local need = cl == nil + or ms - clTime > 30000 + or ms < clTime + or (isVideoKey and ms - clStart >= clusterSpan * 1000) + or (videoIndex == 0 and ms - clStart >= clusterSpan * 1000) + if need then + if cl then + body:close(cl) + end + local at = body:tell() + cl = body:open(ID.Cluster) + clTime = ms + clStart = ms + body:uint(ID.Timecode, ms) + if videoIndex == 0 or isVideoKey then + table.insert(cues, { ms, (videoIndex > 0 and{videoIndex }or{si})[1], at }) + end + end + local data= p.data + local hdr = Ebml.vintString(si, 1) + local rel = ms - clTime + local size = #hdr + 3 + buffer.len(data) + body:header(ID.SimpleBlock, size) + body:raw(hdr) + body:raw(string.char(math.floor(rel / 256), rel % 256, (p.keyframe or streams[si].kind ~= "video" )and 0x80 or 0)) + body:rawBuffer(data) + end + if cl then + body:close(cl) + end + local cuesAt = body:tell() + if #cues > 0 then + local c = body:open(ID.Cues) + for _, q in __iter(cues) do + local cp = body:open(ID.CuePoint) + body:uint(ID.CueTime, q[1]) + local tp = body:open(ID.CueTrackPositions) + body:uint(ID.CueTrack, q[2]) + body:uint(ID.CueClusterPosition, q[3]) -- patched below by the SeekHead length + body:close(tp) + body:close(cp) + end + body:close(c) + end + local bodyBuf = body:finish() + + -- the SeekHead: its own length shifts every position, so build it until its size is stable + local function seekHead(shift) +local w = Ebml.writer(256) + local sh = w:open(ID.SeekHead) + local entries = { { ID.Info, infoAt }, { ID.Tracks, tracksAt } } + if #cues > 0 then + table.insert(entries, { ID.Cues, cuesAt }) + end + for _, e in __iter(entries) do + local sk = w:open(0x4DBB) + local idv = e[1] + local bytes = {} + while idv > 0 do + table.insert(bytes, 1, idv % 256) + idv = math.floor(idv / 256 +) end + w:header(0x53AB, #bytes) + for _, b in __iter(bytes) do + w:raw(string.char(b)) + end + w:uint(0x53AC, e[2] + shift) + w:close(sk) + end + w:close(sh) + return w:finish() + end + local shift = 0 + local head = seekHead(0) + for _ = 1, 4 do + local n = buffer.len(head) + if n == shift then + break + end + shift = n + head = seekHead(shift) + end + shift = buffer.len(head) + -- cue cluster positions (relative to the segment data) must include the SeekHead: rewrite the Cues element + -- (its uint widths may grow, but Cues are last, so nothing after them moves) + if #cues > 0 then + local w = Ebml.writer(4096) + local c = w:open(ID.Cues) + for _, q in __iter(cues) do + local cp = w:open(ID.CuePoint) + w:uint(ID.CueTime, q[1]) + local tp = w:open(ID.CueTrackPositions) + w:uint(ID.CueTrack, q[2]) + w:uint(ID.CueClusterPosition, q[3] + shift) + w:close(tp) + w:close(cp) + end + w:close(c) + local cuesBuf = w:finish() + local nb = buffer.create(cuesAt + buffer.len(cuesBuf)) + buffer.copy(nb, 0, bodyBuf, 0, cuesAt) + buffer.copy(nb, cuesAt, cuesBuf) + bodyBuf = nb + end + + -- the file + local out = Ebml.writer(buffer.len(bodyBuf) + 256) + local eb = out:open(ID.EBML) + out:uint(0x4286, 1) + out:uint(0x42F7, 1) + out:uint(0x42F2, 4) + out:uint(0x42F3, 8) + out:string(ID.DocType, webm and"webm" or"matroska") + out:uint(0x4287, 4) + out:uint(0x4285, 2) + out:close(eb) + local seg = out:open(ID.Segment) + out:rawBuffer(head) + out:rawBuffer(bodyBuf) + out:close(seg) + return out:finish(), nil +end + +return Mux +end +__FILES["video/mkv/Parse"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- video/mkv/Parse: the Matroska / WebM demuxer: EBML header, Segment Info / Tracks / Cues / Tags / Chapters (titles +-- only), and every Cluster into a containers/Demux packet index: SimpleBlock and BlockGroup (BlockDuration, +-- ReferenceBlock -> not a keyframe), the three lacings (Xiph, EBML, fixed), header-stripping content compression, +-- clusters of unknown size (live streams). Times: every track's timescale is 1e9 / TimecodeScale (milliseconds by +-- default). Interpreted (it only walks headers); never throws. +local Err = __include("core/Err") +local Types = __include("Types") +local Ebml = __include("containers/Ebml") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Avi = __include("containers/Avi") +local QtPalette = __include("containers/IsoBmff/QtPalette") +local Deflate = __include("codecs/compress/Deflate") + +local Parse = {} + +-- element IDs +local ID = { + EBML = 0x1A45DFA3, + DocType = 0x4282, + Segment = 0x18538067, + SeekHead = 0x114D9B74, + Info = 0x1549A966, + TimecodeScale = 0x2AD7B1, + Duration = 0x4489, + Title = 0x7BA9, + MuxingApp = 0x4D80, + WritingApp = 0x5741, + DateUTC = 0x4461, + Tracks = 0x1654AE6B, + TrackEntry = 0xAE, + TrackNumber = 0xD7, + TrackUID = 0x73C5, + TrackType = 0x83, + FlagEnabled = 0xB9, + FlagDefault = 0x88, + FlagForced = 0x55AA, + FlagLacing = 0x9C, + DefaultDuration = 0x23E383, + Name = 0x536E, + Language = 0x22B59C, + LanguageBCP47 = 0x22B59D, + CodecID = 0x86, + CodecPrivate = 0x63A2, + CodecDelay = 0x56AA, + SeekPreRoll = 0x56BB, + Video = 0xE0, + PixelWidth = 0xB0, + PixelHeight = 0xBA, + DisplayWidth = 0x54B0, + DisplayHeight = 0x54BA, + ColourSpace = 0x2EB524, + Audio = 0xE1, + SamplingFrequency = 0xB5, + OutputSamplingFrequency = 0x78B5, + Channels = 0x9F, + BitDepth = 0x6264, + ContentEncodings = 0x6D80, + ContentEncoding = 0x6240, + ContentEncodingType = 0x5033, + ContentEncodingScope = 0x5032, + ContentCompression = 0x5034, + ContentCompAlgo = 0x4254, + ContentCompSettings = 0x4255, + ContentEncryption = 0x5035, + Cluster = 0x1F43B675, + Timecode = 0xE7, + SimpleBlock = 0xA3, + BlockGroup = 0xA0, + Block = 0xA1, + BlockDuration = 0x9B, + ReferenceBlock = 0xFB, + DiscardPadding = 0x75A2, + Cues = 0x1C53BB6B, + CuePoint = 0xBB, + CueTime = 0xB3, + CueTrackPositions = 0xB7, + CueTrack = 0xF7, + CueClusterPosition = 0xF1, + CueRelativePosition = 0xF0, + Tags = 0x1254C367, + Tag = 0x7373, + SimpleTag = 0x67C8, + TagName = 0x45A3, + TagString = 0x4487, + Targets = 0x63C0, + Chapters = 0x1043A770, + Attachments = 0x1941A469, + Void = 0xEC, + Crc32 = 0xBF, +} +Parse.ID = ID + +-- the top-level children of a Segment (an unknown-size Cluster ends where one of these starts) +local TOP= { + [ID.SeekHead] = true, + [ID.Info] = true, + [ID.Tracks] = true, + [ID.Cluster] = true, + [ID.Cues] = true, + [ID.Tags] = true, + [ID.Chapters] = true, + [ID.Attachments] = true, + [ID.Segment] = true, + [ID.EBML] = true, +} + +-- Matroska audio / subtitle CodecIDs -> our codec ids (video ids come from the codecs/video/Video registry) +local AUDIO= { + A_VORBIS = "vorbis", + A_OPUS = "opus", + A_FLAC = "flac", + ["A_MPEG/L3"] = "mp3", + ["A_MPEG/L2"] = "mp2", + ["A_MPEG/L1"] = "mp1", + A_AAC = "aac", + ["A_AAC/MPEG4/LC"] = "aac", + ["A_AAC/MPEG4/LC/SBR"] = "aac", + ["A_AAC/MPEG2/LC"] = "aac", + A_AC3 = "ac3", + A_EAC3 = "eac3", + A_DTS = "dts", + A_ALAC = "alac", + A_TTA1 = "tta", + A_WAVPACK4 = "wavpack", + ["A_MS/ACM"] = "acm", +} +local SUBS= { + ["S_TEXT/UTF8"] = "text", + ["S_TEXT/ASCII"] = "text", + ["S_TEXT/WEBVTT"] = "webvtt", + ["S_TEXT/ASS"] = "ass", + ["S_TEXT/SSA"] = "ssa", + ["S_ASS"] = "ass", + ["S_SSA"] = "ssa", + ["S_VOBSUB"] = "dvdsub", + ["S_HDMV/PGS"] = "pgs", +} + +-- codecFor(CodecID, bitDepth) -> our codec id +local function codecFor(id, kind, bits) +if kind == "video" then + return Video.fromMatroska(id) or string.lower((string.gsub(id, "^V_", ""))) + end + if id == "A_PCM/INT/LIT" then + return bits == 8 and"pcm_u8" or"pcm_s" .. (bits or 16) .. "le" + elseif id == "A_PCM/INT/BIG" then + return bits == 8 and"pcm_u8" or"pcm_s" .. (bits or 16) .. "be" + elseif id == "A_PCM/FLOAT/IEEE" then + return "pcm_f" .. (bits or 32) .. "le" + end + return AUDIO[id] or SUBS[id] or string.lower((string.gsub(id, "^[AS]_", ""))) +end +Parse.codecFor = codecFor + +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t, codecId, priv) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, math.floor(size / 16777216 )% 256) + buffer.writeu8(desc, 1, math.floor(size / 65536 )% 256) + buffer.writeu8(desc, 2, math.floor(size / 256 )% 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + + + +local function parseVideo(buf, off, len, t) + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.PixelWidth then + t.width = Ebml.uint(buf, o, n) + elseif id == ID.PixelHeight then + t.height = Ebml.uint(buf, o, n) + elseif id == ID.DisplayWidth then + t.displayWidth = Ebml.uint(buf, o, n) + elseif id == ID.DisplayHeight then + t.displayHeight = Ebml.uint(buf, o, n) + elseif id == ID.ColourSpace then + t.colourSpace = buffer.readstring(buf, o, math.min(n, 4)) + end + end +end + +local function parseAudio(buf, off, len, t) + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.SamplingFrequency then + t.sampleRate = Ebml.float(buf, o, n) + elseif id == ID.OutputSamplingFrequency then + t.outputSampleRate = Ebml.float(buf, o, n) + elseif id == ID.Channels then + t.channels = Ebml.uint(buf, o, n) + elseif id == ID.BitDepth then + t.bitsPerSample = Ebml.uint(buf, o, n) + end + end +end + +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption +-- are not +local function parseEncodings(buf, off, len, t) +for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.ContentEncoding then + local etype = 0 + local scope = 1 + for id2, o2, n2 in __iter(Ebml.children(buf, o, o + n)) do + if id2 == ID.ContentEncodingScope then + scope = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentEncodingType then + etype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentCompression then + local algo, settings = 0, nil + for id3, o3, n3 in __iter(Ebml.children(buf, o2, o2 + n2)) do + if id3 == ID.ContentCompAlgo then + algo = Ebml.uint(buf, o3, n3) + elseif id3 == ID.ContentCompSettings then + settings = Ebml.binary(buf, o3, n3) + end + end + if algo == 3 then + t.strip = settings + elseif algo == 0 then + t.zlib = scope -- 1: frames, 2: CodecPrivate + else + return "content compression algorithm " .. algo + end + elseif id2 == ID.ContentEncryption then + return "encrypted track" + end + end + if etype ~= 0 then + return "encrypted track" + end + end + end + return nil +end + +local function parseTracks(buf, off, len, scaleNs) +local tracks= {} + local problems= {} + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.TrackEntry then + local t= { id = 0, kind = "data", codec = "", timescale = 1e9 / scaleNs, default = true, lacing = true, language = "eng" } + local ttype, codecId = 0, "" + local problem= nil + for id2, o2, n2 in __iter(Ebml.children(buf, o, o + n)) do + if id2 == ID.TrackNumber then + t.id = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackUID then + t.uid = Ebml.uint(buf, o2, n2) + elseif id2 == ID.TrackType then + ttype = Ebml.uint(buf, o2, n2) + elseif id2 == ID.FlagDefault then + t.default = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagEnabled then + t.enabled = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.FlagLacing then + t.lacing = Ebml.uint(buf, o2, n2) ~= 0 + elseif id2 == ID.DefaultDuration then + t.defaultDurationNs = Ebml.uint(buf, o2, n2) + elseif id2 == ID.Name then + t.name = Ebml.string(buf, o2, n2) + elseif id2 == ID.Language then + t.language = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecID then + codecId = Ebml.string(buf, o2, n2) + elseif id2 == ID.CodecPrivate then + t.config = Ebml.binary(buf, o2, n2) + elseif id2 == ID.CodecDelay then + t.codecDelay = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.SeekPreRoll then + t.seekPreRoll = Ebml.uint(buf, o2, n2) / 1e9 + elseif id2 == ID.Video then + parseVideo(buf, o2, n2, t) + elseif id2 == ID.Audio then + parseAudio(buf, o2, n2, t) + elseif id2 == ID.ContentEncodings then + problem = parseEncodings(buf, o2, n2, t) + end + end + if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then + local c = Deflate.zlib(t.config) + if c then + t.config = c + else + problem = "bad zlib-compressed CodecPrivate" + end + end + t.kind = ttype == 1 and"video" or(ttype == 2 and"audio" or(ttype == 17 and"subtitle" or"data" +)) t.codecTag = codecId + t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + local cfg= t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) + end + if t.kind == "audio" then + t.sampleRate = t.sampleRate or 8000 + t.channels = t.channels or 1 + end + if t.defaultDurationNs and t.defaultDurationNs > 0 and t.kind == "video" then + t.frameRate = 1e9 / t.defaultDurationNs + end + if t.id > 0 then + table.insert(tracks, t) + if problem then + problems[t.id] = problem + end + end + end + end + return tracks, problems +end + +local function parseInfo(buf, off, len, meta) +local scale, duration = 1000000, nil + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.TimecodeScale then + scale = Ebml.uint(buf, o, n) + elseif id == ID.Duration then + duration = Ebml.float(buf, o, n) + elseif id == ID.Title then + meta.title = Ebml.string(buf, o, n) + elseif id == ID.MuxingApp then + meta.muxingApp = Ebml.string(buf, o, n) + elseif id == ID.WritingApp then + meta.writingApp = Ebml.string(buf, o, n) + end + end + if scale <= 0 then + scale = 1000000 + end + return scale, duration +end + +local function parseCues(buf, off, len, segData) +local cues = {} + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.CuePoint then + local time = 0 + local positions = {} + for id2, o2, n2 in __iter(Ebml.children(buf, o, o + n)) do + if id2 == ID.CueTime then + time = Ebml.uint(buf, o2, n2) + elseif id2 == ID.CueTrackPositions then + local tr, pos = 0, 0 + for id3, o3, n3 in __iter(Ebml.children(buf, o2, o2 + n2)) do + if id3 == ID.CueTrack then + tr = Ebml.uint(buf, o3, n3) + elseif id3 == ID.CueClusterPosition then + pos = Ebml.uint(buf, o3, n3) + end + end + table.insert(positions, { tr, pos }) + end + end + for _, p in __iter(positions) do + table.insert(cues, { time = time, track = p[1], position = segData + p[2] }) + end + end + end + return cues +end + +local function parseTags(buf, off, len, meta) + local tags = meta.tags or {} + meta.tags = tags + for id, o, n in __iter(Ebml.children(buf, off, off + len)) do + if id == ID.Tag then + for id2, o2, n2 in __iter(Ebml.children(buf, o, o + n)) do + if id2 == ID.SimpleTag then + local name, value = nil, nil + for id3, o3, n3 in __iter(Ebml.children(buf, o2, o2 + n2)) do + if id3 == ID.TagName then + name = Ebml.string(buf, o3, n3) + elseif id3 == ID.TagString then + value = Ebml.string(buf, o3, n3) + end + end + if name and value and tags[string.lower(name)] == nil then + tags[string.lower(name)] = value + end + end + end + end + end +end + +-- one Block / SimpleBlock payload at [off, off + len): track, relative timecode, flags, lacing + + + + + + + + + +local function block(ctx, off, len, clusterTime, simple, keyHint, durTicks, discardNs) + local buf = ctx.buf + local limit = off + len + local tn, tl = Ebml.vint(buf, off, limit) + if not tn or not tl or tn < 0 or off + tl + 3 > limit then + return + end + local p = off + tl + local rel = buffer.readu8(buf, p) * 256 + buffer.readu8(buf, p + 1) + if rel >= 32768 then + rel =rel- 65536 + end + local flags = buffer.readu8(buf, p + 2) + p =p+ 3 + local t = ctx.byNum[tn] + if not t then + return + end + local key = (simple and{(bit32.band(flags, 0x80) ~= 0 )}or{(keyHint ~= false) +})[1] if t.kind == "audio" or t.kind == "subtitle" then + key = true + end + local pts = clusterTime + rel + local lacing = bit32.band(bit32.rshift(flags, 1), 3) + local sizes= {} + if lacing == 0 then + sizes[1] = limit - p + else + if p >= limit then + return + end + local count = buffer.readu8(buf, p) + 1 + p =p+ 1 + if lacing == 1 then -- Xiph + local total = 0 + for k = 1, count - 1 do + local s = 0 + while true do + if p >= limit then + return + end + local b = buffer.readu8(buf, p) + p =p+ 1 + s =s+ b + if b ~= 255 then + break + end + end + sizes[k] = s + total =total+ s + end + sizes[count] = limit - p - total + elseif lacing == 3 then -- EBML + local s, l = Ebml.vint(buf, p, limit) + if not s or not l or s < 0 then + return + end + p =p+ l + sizes[1] = s + local total = s + for k = 2, count - 1 do + local d, dl = Ebml.svint(buf, p, limit) + if not d or not dl then + return + end + p =p+ dl + s =s+ d + if s < 0 then + return + end + sizes[k] = s + total =total+ s + end + sizes[count] = limit - p - total + else -- fixed + local each = math.floor((limit - p) / count +) for k = 1, count do + sizes[k] = each + end + end + if sizes[count] < 0 then + return + end + end + -- frames after the first of a lace: the track's default duration + local stepTicks = 0 + if t.defaultDurationNs and t.defaultDurationNs > 0 then + stepTicks = t.defaultDurationNs / ctx.scaleNs + elseif durTicks and #sizes > 0 then + stepTicks = durTicks / #sizes + end + local dmx = ctx.dmx + for k, s in __iter(sizes) do + if p + s > limit then + return + end + if dmx.n >= ctx.maxPackets then + ctx.err = "too many packets" + return + end + local d = (#sizes == 1 and{durTicks }or{((stepTicks > 0 and{stepTicks }or{nil})[1]) +})[1] local kf = key and (k == 1 or t.kind ~= "video") + local strip = t.strip + local z = (t ).zlib + if z and bit32.band(z, 1) ~= 0 then + local out = Deflate.zlib(buf, p, s) + if out then + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out) + end + elseif strip then + local nb = buffer.create(buffer.len(strip) + s) + buffer.copy(nb, 0, strip) + buffer.copy(nb, buffer.len(strip), buf, p, s) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb) + else + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s) + end + if discardNs and k == #sizes then + dmx:setExtra("discardPadding", discardNs / 1e9) + end + p =p+ s + end +end + +-- a Cluster's children from off to limit (an unknown-size cluster: until a top-level ID); returns where it ended +local function cluster(ctx, off, limit, unknown) +local buf = ctx.buf + local pos = off + local time = 0 + while pos < limit and not ctx.err do + local id, size, data = Ebml.header(buf, pos, limit) + if not id or not size or not data then + return limit + end + if unknown and TOP[id] then + return pos + end + if size < 0 then + size = limit - data -- an unknown-size child: to the end + end + if data + size > limit then + size = limit - data + end + if id == ID.Timecode then + time = Ebml.uint(buf, data, size) + elseif id == ID.SimpleBlock then + block(ctx, data, size, time, true) + elseif id == ID.BlockGroup then + local bo, bl = -1, 0 + local ref, dur, discard = false, nil, nil + for id2, o2, n2 in __iter(Ebml.children(buf, data, data + size)) do + if id2 == ID.Block then + bo, bl = o2, n2 + elseif id2 == ID.ReferenceBlock then + ref = true + elseif id2 == ID.BlockDuration then + dur = Ebml.uint(buf, o2, n2) + elseif id2 == ID.DiscardPadding then + discard = Ebml.int(buf, o2, n2) + end + end + if bo >= 0 then + block(ctx, bo, bl, time, false, not ref, dur, discard) + end + end + pos = data + size + end + return pos +end + +-- parse(buf, base, limit, opts) -> a Demux | nil, Err +-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data +-- offset | nil, Err + + +function Parse.docType(buf, base, limit) +local id, size, data = Ebml.header(buf, base, limit) + if id ~= ID.EBML or not size or not data then + return nil, Err.new(Err.CORRUPT, "not an EBML file", base) + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "EBML header of unknown size", base) + end + local docType = "matroska" + for cid, o, n in __iter(Ebml.children(buf, data, math.min(limit, data + size))) do + if cid == ID.DocType then + docType = Ebml.string(buf, o, n) + end + end + return docType, size, data +end + +function Parse.parse(buf, base, limit, opts) +local docType, size, data = Parse.docType(buf, base, limit) + if not docType then + return nil, size + end + if docType ~= "matroska" and docType ~= "webm" then + return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType) + end + local pos = data + size + -- the Segment (skip anything else at the top level) + local segData, segEnd = -1, limit + while pos < limit do + local sid, ssize, sdata = Ebml.header(buf, pos, limit) + if not sid or not ssize or not sdata then + break + end + if sid == ID.Segment then + segData = sdata + segEnd = ((ssize < 0 or sdata + ssize > limit )and{limit }or{(sdata + ssize +)})[1] break + end + if ssize < 0 then + break + end + pos = sdata + ssize + end + if segData < 0 then + return nil, Err.new(Err.TRUNCATED, "no Segment") + end + local meta= { docType = docType } + local scaleNs, duration = 1000000, nil +local tracks= {} + local problems= {} + local cuesAt= {} + local clusters= {} + -- first pass: the top-level elements (clusters are walked after Info / Tracks, which may come later via SeekHead) + pos = segData + while pos < segEnd do + local cid, csize, cdata = Ebml.header(buf, pos, segEnd) + if not cid or not csize or not cdata then + break + end + local unknown = csize < 0 + local cend = ((unknown or cdata + csize > segEnd )and{segEnd }or{(cdata + csize +)})[1] if cid == ID.Info then + local d + scaleNs, d = parseInfo(buf, cdata, cend - cdata, meta) + duration = d + elseif cid == ID.Tracks then + tracks, problems = parseTracks(buf, cdata, cend - cdata, scaleNs) + elseif cid == ID.Cluster then + if unknown then + -- find its end: walk children until a top-level ID + local p = cdata + while p < segEnd do + local xid, xsize, xdata = Ebml.header(buf, p, segEnd) + if not xid or not xsize or not xdata or TOP[xid] then + break + end + if xsize < 0 then + p = segEnd + break + end + p = math.min(segEnd, xdata + xsize) + end + cend = p + end + table.insert(clusters, { cdata, cend }) + elseif cid == ID.Cues then + table.insert(cuesAt, cdata) + table.insert(cuesAt, cend - cdata) + elseif cid == ID.Tags then + parseTags(buf, cdata, cend - cdata, meta) + end + if cend <= pos then + break + end + pos = cend + end + if #tracks == 0 then + return nil, Err.new(Err.CORRUPT, "no tracks") + end + -- track timescales follow the final TimecodeScale (Info may follow Tracks) + local byNum= {} + for _, t in __iter(tracks) do + t.timescale = 1e9 / scaleNs + byNum[t.id] = t + end + local dmx = Demux.new(docType == "webm" and"webm" or"mkv", tracks , buf, meta) + local ctx= { buf = buf, dmx = dmx, byNum = byNum, scaleNs = scaleNs, err = nil, maxPackets = opts and opts.maxPackets or 2 ^ 24 } + for _, c in __iter(clusters) do + cluster(ctx, c[1], c[2], false) + if ctx.err then + return nil, Err.new(Err.LIMIT, ctx.err) + end + end + if duration then + dmx.duration = duration * scaleNs / 1e9 + end + local cues = {} + for k = 1, #cuesAt, 2 do + for _, c in __iter(parseCues(buf, cuesAt[k], cuesAt[k + 1], segData)) do + c.time = c.time * scaleNs / 1e9 + table.insert(cues, c) + end + end + meta.cues = cues + meta.timecodeScale = scaleNs + for tid, msg in __iter(problems) do + local t = byNum[tid] + t.unsupported = msg + end + dmx:finish() + return dmx, nil +end + +return Parse +end +__FILES["video/mp4"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- video/mp4: MP4 / M4V / QuickTime MOV / 3GP (ISO/IEC 14496-12 / 14496-14, the QuickTime file format), on +-- containers/IsoBmff (ws-m4a's box parser, sample tables, fragments and muxer). New in rosetta. +-- Read: every track's samples into a Demuxer (pts = dts + composition offset, moved by the edit list: the first +-- edit's media time is subtracted (B-frame delay, AAC priming), an initial empty edit added; sync samples as +-- keyframes; fragmented files too) and open() returns a VideoDecoder: video through the codecs/video/Video registry (MJPEG +-- 'jpeg' / 'mjpa' / mp4v 0x6C, MPEG-1, raw; H.264 'avc1' with its avcC when a decoder is registered), audio through +-- the api's opts.openAudio hook (AAC, ALAC (audio/m4a), MP3, Opus (dOps -> OpusHead), FLAC, PCM 'sowt' / 'twos' / +-- 'lpcm' / 'ipcm'). +-- Write: MP4 (or MOV with opts.format = "mov" / a .mov destination): H.264 / HEVC / AV1 / MJPEG / MPEG-4 video copied +-- from an ISO / Matroska source (their configurations are the same boxes), else MJPEG encoded from the frames (mp4v +-- object type 0x6C in MP4, 'jpeg' in MOV); AAC / ALAC / Opus / FLAC / MP3 audio copied, else PCM s16 ('sowt', MOV +-- only; MP4 drops other audio unless opts.audio = true, which fails). +-- Edit lists are written for a B-frame delay and an audio codec delay (AAC priming). Not supported: fragmented +-- writing, timed text tracks, encrypted tracks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local IsoBmff = __include("containers/IsoBmff") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Mp4 = { + name = "mp4", + category = "video", + 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/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + + +local IMAGE_BRANDS = { avif = true, avis = true, heic = true, heix = true, mif1 = true, msf1 = true, ["crx "] = true } +local AUDIO_BRANDS = { ["M4A "] = true, ["M4B "] = true, ["M4P "] = true } +-- copied video codecs -> sample entry (MP4 / MOV) +local VIDEO_ENTRY= { h264 = "avc1", hevc = "hvc1", av1 = "av01", vp9 = "vp09" } +local AUDIO_ENTRY= { aac = "mp4a", alac = "alac", opus = "Opus", flac = "fLaC", mp3 = "mp4a" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mp4.sniff(r) +local brand = IsoBmff.sniff(r) + if brand == nil or IMAGE_BRANDS[brand] then + return 0 + end + if AUDIO_BRANDS[brand] then + return 0.2 + end + if brand == "M4V " then + return 0.9 + end + return brand == "" and 0.6 or 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- OpusHead (RFC 7845, little-endian) from an ISO dOps box payload (big-endian) +local function opusHead(d) +if buffer.len(d) < 11 then + return nil + end + local w = Bytes.writer(19 + buffer.len(d)) + w:string("OpusHead") + w:u8(1) + local ch = buffer.readu8(d, 1) + w:u8(ch) + w:u16le(buffer.readu8(d, 2) * 256 + buffer.readu8(d, 3)) + w:u32le(((buffer.readu8(d, 4) * 256 + buffer.readu8(d, 5)) * 256 + buffer.readu8(d, 6)) * 256 + buffer.readu8(d, 7)) + w:u16le(buffer.readu8(d, 8) * 256 + buffer.readu8(d, 9)) + local family = buffer.readu8(d, 10) + w:u8(family) + if family ~= 0 and buffer.len(d) >= 13 + ch then + w:bytes(d, 11, 2 + ch) -- stream count, coupled count, mapping + end + return w:finish() +end + +local function pcmCodec(t) +local p = t.pcm + local bits = (p and{p.bits }or{(t.bitsPerSample or 16) +})[1] if p and p.float then + return "pcm_f" .. bits .. (p.little and"le" or"be") + end + if bits == 8 then + return t.entry == "raw " and"pcm_u8" or"pcm_s8" + end + return "pcm_s" .. bits .. ((p == nil or p.little )and"le" or"be") +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Mp4.demux(r, opts) +local ok, movie, err = pcall(IsoBmff.parse, r, opts and opts.maxSamples and { maxSamples = opts.maxSamples } or nil) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(movie)) + end + if not movie then + return nil, err + end + local tracks= {} + local src = {} + for _, it in __iter(movie.tracks) do + local t= { + id = it.id, + kind = it.kind, + codec = it.codec, + codecTag = it.entry, + timescale = it.timescale, + duration = it.duration, + language = it.language, + width = it.width, + height = it.height, + sampleRate = it.sampleRate, + channels = it.channels, + bitsPerSample = it.bitsPerSample, + config = it.config, + default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, + } + if it.kind == "video" then + if not Video.entry(t.codec) then + t.codec = Video.fromFourcc(it.entry) or t.codec + end + if it.sampleCount > 0 and it.duration > 0 then + t.frameRate = it.sampleCount / it.duration + end + elseif it.kind == "audio" then + if it.codec == "pcm" then + t.codec = pcmCodec(it) + elseif it.codec == "ulaw" then + t.codec = "pcm_mulaw" + elseif it.codec == "alaw" then + t.codec = "pcm_alaw" + elseif it.codec == "opus" and it.config then + t.config = opusHead(it.config) + end + if it.skip and it.skip > 0 then + t.codecDelay = it.skip / it.timescale -- AAC priming: dropped like ffmpeg + end + if it.playDuration and it.playDuration > 0 and it.timescale > 0 then + t.playDuration = it.playDuration / it.timescale -- the edit's length: the end padding is not played + end + end + table.insert(tracks, t) + table.insert(src, it) + end + local dmx = Demux.new(movie.brand == "qt " and"mov" or"mp4", tracks, r.buf, { brand = movie.brand }) + -- samples in file order across tracks + local items= {} + for k, it in __iter(src) do + -- the edit list moves presentation times: minus the first edit's media time (video: the B-frame delay; audio + -- keeps it as its codec delay), plus an initial empty edit (converted to media ticks) + local shift = 0 + if it.kind == "video" then + shift = -(it.skip or 0) + end + if it.delay and it.delay > 0 and movie.timescale and movie.timescale > 0 then + shift =shift+ it.delay / movie.timescale * it.timescale + end + for i = 1, it.sampleCount do + table.insert(items, { it.offsets[i], k, i, shift }) + end + end + table.sort(items, function(a, b) +return a[1] < b[1] + end) + for _, e in __iter(items) do + local it = src[e[2] ] + local i = e[3] + local dts = it.dts[i] + local pts = dts + ((it.cts and{it.cts[i] or 0 }or{0})[1]) + e[4] + dmx:add(it.id, pts, dts + e[4], it.durations[i], it.sync == nil or it.sync[i] == true, it.offsets[i], it.sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- OpusHead -> dOps payload +local function dOps(head) +if not head or buffer.len(head) < 19 then + return nil + end + local w = Bytes.writer(16) + w:u8(0) + local ch = buffer.readu8(head, 9) + w:u8(ch) + w:u16be(buffer.readu16(head, 10)) + w:u32be(buffer.readu32(head, 12)) + w:u16be(buffer.readu16(head, 16)) + local family = buffer.readu8(head, 18) + w:u8(family) + if family ~= 0 and buffer.len(head) >= 21 + ch then + w:bytes(head, 19, 2 + ch) + end + return w:finish() +end + +-- encode(video, opts?) -> buffer | nil, Err +function Mp4.encode(value, opts) +local o= table.clone(opts or {}) + o.quality = o.quality or 90 + local mov = type(o.format) == "string" and (string.lower(o.format) == "mov" or string.lower(o.format) == "qt") + local vcopy= { mjpeg = true } + for id in __iter(VIDEO_ENTRY) do + vcopy[id] = true + end + local acopy= {} + for id in __iter(AUDIO_ENTRY) do + acopy[id] = true + end + acopy.pcm_s16le = mov + local streams, err = Source.streams(value, o, { + video = { copy = vcopy, encode = "mjpeg" }, + audio = { copy = acopy, pcm = mov }, + }) + if not streams then + return nil, err + end + local mtracks = {} + for _, s in __iter(streams) do + local scale = (s.kind == "audio" and{(math.floor((s.sampleRate or 48000) + 0.5) )}or{90000 +})[1] if s.kind == "video" and s.track and s.track.timescale and s.copied and s.track.timescale == math.floor(s.track.timescale) then + scale = s.track.timescale + end + local samples, durations, cts, sync = {}, {}, {}, {} + local anyCts = false + local firstDts = nil +for i, p in __iter(s.packets) do + samples[i] = p.data + local dts = p.dts or p.pts + firstDts = firstDts or dts + local nextP = s.packets[i + 1] + local d = (nextP and(((nextP.dts or nextP.pts) - dts ))or(p.duration +)) durations[i] = math.max(0, math.floor(d * scale + 0.5)) + local c = math.floor((p.pts - dts) * scale + 0.5) + cts[i] = c + if c ~= 0 then + anyCts = true + end + if p.keyframe then + sync[i] = true + end + end + -- an edit list keeps the source's start: video decode times before 0 (B-frame delay), audio codec delay + local skip = 0 + if firstDts and firstDts < 0 then + skip = math.floor(-firstDts * scale + 0.5) + end + if s.kind == "audio" and s.track and s.track.codecDelay and s.copied then + skip = math.floor(s.track.codecDelay * scale + 0.5) + end + -- video: the skipped decode delay is a composition shift, every frame still plays (ffmpeg drops the frames an + -- edit cuts); audio: the codec delay samples are not played + local playDuration = nil + if s.kind == "video" and skip > 0 then + playDuration = 0 + for _, d in __iter(durations) do + playDuration =playDuration+ d + end + elseif s.kind == "audio" and s.track and s.copied and type(s.track.playDuration) == "number" then + playDuration = math.floor(s.track.playDuration * scale + 0.5) -- keep the source's end trim + end + local t= { + kind = s.kind, + timescale = scale, + skip = (skip > 0 and{skip }or{nil})[1], + playDuration = playDuration, + samples = samples, + durations = durations, + cts = (anyCts and{cts }or{nil})[1], + sync = sync, + width = s.width, + height = s.height, + sampleRate = s.sampleRate and math.floor(s.sampleRate + 0.5), + channels = s.channels, + } + if s.kind == "video" then + if s.codec == "mjpeg" then + t.entry = mov and"jpeg" or"mp4v" + if not mov then + t.objectType = 0x6C + t.configBox = "esds" + t.config = buffer.create(0) + end + else + t.entry = VIDEO_ENTRY[s.codec] + t.config = s.config + end + else + if s.codec == "pcm_s16le" then + t.entry = "sowt" + t.bitsPerSample = 16 + else + t.entry = AUDIO_ENTRY[s.codec] + t.config = (s.codec == "opus" and{(dOps(s.config) )}or{s.config +})[1] if s.codec == "mp3" then + t.objectType = 0x6B + t.configBox = "esds" + t.config = buffer.create(0) + end + end + end + if not t.entry then + return nil, Err.new(Err.UNSUPPORTED, "no sample entry for " .. s.kind .. " codec " .. s.codec) + end + table.insert(mtracks, t) + end + return IsoBmff.mux({ brand = mov and"qt " or"isom", compatible = mov and{ "qt " } or{ "isom", "iso2", "mp41" }, tracks = mtracks }) +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Mp4.open(r, opts) +local dmx, err = Mp4.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Mp4 +end +__FILES["video/mpegps"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / +-- .vob / VCD .dat). New in rosetta, on containers/MpegPs. Video PES payloads are joined into the elementary +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both +-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get +-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). +-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its +-- sequence extension), audio through the api's opts.openAudio hook. +-- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegPs = __include("containers/MpegPs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ps = { + name = "mpegps", + category = "video", + extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, + mime = { "video/mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + +function Ps.sniff(r) +if r:peek(4) == "\0\0\1\186" then + return 0.9 + end + if r:peek(4) == "\0\0\1\179" then + return 0.5 -- an MPEG-1 / 2 video elementary stream (sequence header) + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the pictures of a video stream as packets: join the PES payloads, cut at pictures, place the timestamps +local function videoPackets(dmx, buf, s, t) + local total = 0 + for _, p in __iter(s.pes) do + total =total+ p.size + end + local es = buffer.create(total) + local starts= {} + local o = 0 + for i, p in __iter(s.pes) do + starts[i] = o + buffer.copy(es, o, buf, p.offset, p.size) + o =o+ p.size + end + local info = MpegEs.info(es, 0, total) + if info then + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + if info.mpeg2 then + t.codec = "mpeg2" + end + end + local pics = MpegEs.pictures(es, 0, total) + local fd = (t.frameRate and t.frameRate > 0 and((90000 / t.frameRate ))or(3600 +)) -- the PTS of the PES each picture starts in (only the first picture starting in a PES takes it) + local k = 1 + local used= {} + local ptsOf= {} + for i, pic in __iter(pics) do + while k < #s.pes and starts[k + 1] <= pic.offset do + k =k+ 1 + end + -- a PES whose payload starts inside this picture's headers also labels it + local pes = s.pes[k] + if pes and pes.pts and not used[k] then + used[k] = true + ptsOf[i] = pes.pts + end + end + -- fill the rest from the temporal references of each GOP (an elementary stream without any PTS: from 0) + local anchorPts, anchorTr = nil , 0 + local lastPts = nil +local timed = next(ptsOf) ~= nil + local count = 0 + for i, pic in __iter(pics) do + if pic.gop then + anchorPts = nil + if not timed then + anchorPts, anchorTr = count * fd, 0 + end + end + if not timed and anchorPts == nil then + anchorPts, anchorTr = count * fd, pic.temporal + end + count =count+ 1 + local pts = ptsOf[i] + if pts then + anchorPts, anchorTr = pts, pic.temporal + elseif anchorPts then + pts = anchorPts + (pic.temporal - anchorTr) * fd + elseif lastPts then + pts = lastPts + fd + end + if pts then + lastPts = pts + local d = buffer.create(pic.size) + buffer.copy(d, 0, es, pic.offset, pic.size) + dmx:addData(t.id, pts, nil, fd, pic.type == 1, d) + end + end +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ps.demux(r, _opts) +if r:peek(4) == "\0\0\1\179" then + -- an MPEG-1 / 2 video elementary stream (.m1v): one video stream, no timestamps + local t= { id = 0xE0, kind = "video", codec = "mpeg1", codecTag = "es", timescale = 90000, streamId = 0xE0 } + local dmx = Demux.new("mpegps", { t }, r.buf, { elementary = true }) + videoPackets(dmx, r.buf, { id = 0xE0, kind = "video", codec = "mpeg1", pes = { { offset = r.base, size = r.limit - r.base } } }, t) + dmx:finish() + return dmx, nil + end + local ok, file, err = pcall(MpegPs.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks= {} + for _, id in __iter(file.order) do + local s = file.streams[id] + table.insert(tracks, { + id = id, + kind = s.kind , + codec = s.codec, + codecTag = string.format("0x%02x", id % 256), + timescale = 90000, + streamId = id, + } ) + end + local dmx = Demux.new("mpegps", tracks, r.buf, { mpeg2 = file.mpeg2, errors = file.errors }) + for i, id in __iter(file.order) do + local s = file.streams[id] + local t= tracks[i] + if t.kind == "video" and (t.codec == "mpeg1" or t.codec == "mpeg2") then + videoPackets(dmx, r.buf, s, t) + else + local last = nil +for _, p in __iter(s.pes) do + local pts = p.pts or last + if pts and p.size > 0 then + last = pts + dmx:add(id, pts, p.dts, nil, true, p.offset, p.size) + end + end + if t.codec == "mp2" and #s.pes > 0 then + local p = s.pes[1] + local b = r.buf + for i2 = p.offset, math.min(p.offset + p.size, r.limit) - 2 do + if buffer.readu8(b, i2) == 0xFF and buffer.readu8(b, i2 + 1) >= 0xE0 then + local layer = (math.floor(buffer.readu8(b, i2 + 1) / 2)) % 4 + t.codec = layer == 1 and"mp3" or(layer == 3 and"mp1" or"mp2" +) break + end + end + end + end + end + dmx:finish() -- (read() without a track gives the video packets first, then the audio ones) + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ps.open(r, opts) +local dmx, err = Ps.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Ps +end +__FILES["video/mpegts"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, +-- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS +-- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the +-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, +-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. +-- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, +-- PES without PTS for video before the first one (dropped). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local MpegTs = __include("containers/MpegTs") +local MpegEs = __include("containers/MpegEs") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Ts = { + name = "mpegts", + category = "video", + extensions = { "ts", "m2ts", "mts", "tsv" }, + mime = { "video/mp2t" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local CODEC= { + mpeg1video = "mpeg1", + mpeg2video = "mpeg2", + mpegaudio = "mp2", + aac = "aac", + aac_latm = "aac_latm", + h264 = "h264", + hevc = "hevc", + mpeg4 = "mpeg4", + ac3 = "ac3", + eac3 = "eac3", +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- packetSize(r) -> 188 | 192 (M2TS) | 0, and the offset of the first sync byte: three sync bytes a packet apart +-- (fewer in a short file) within the first 2 KB +local function packetSize(r) +local n = r:remaining() + for start = 0, math.min(n, 2048) - 1 do + if r:peekU8(start) == 0x47 then + for _, size in __iter({ 188, 192 }) do + local hits, need = 0, math.min(3, math.floor((n - start - 1) / size )+ 1) + for k = 0, 2 do + local at = start + k * size + if at < n and r:peekU8(at) == 0x47 then + hits =hits+ 1 + end + end + if hits >= need and (need >= 2 or start == 0) then + if size == 192 and start >= 4 then + return 192, start - 4 + elseif size == 188 then + return 188, start + end + end + end + end + end + return 0, 0 +end + +function Ts.sniff(r) +local s, off = packetSize(r) + if s == 0 then + return 0 + end + if off > 0 then + return 0.6 + end + return r:remaining() >= 3 * s and 0.9 or 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the 188-byte packets of an M2TS file (192-byte packets: drop the 4-byte timestamps) +local function strip192(b, base, limit) +local n = math.floor((limit - base) / 192 +) local out = buffer.create(n * 188) + for i = 0, n - 1 do + buffer.copy(out, i * 188, b, base + i * 192 + 4, 188) + end + return out +end + +local function mpegAudioCodec(u) +local d= u.data + for i = 0, math.min(buffer.len(d), 4096) - 2 do + if buffer.readu8(d, i) == 0xFF and buffer.readu8(d, i + 1) >= 0xE0 then + local layer = (math.floor(buffer.readu8(d, i + 1) / 2)) % 4 + return layer == 1 and"mp3" or(layer == 3 and"mp1" or"mp2" +) end + end + return "mp2" +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Ts.demux(r, _opts) +local size, off = packetSize(r) + if size == 0 then + return nil, Err.new(Err.CORRUPT, "no transport stream sync", r.base) + end + local d = MpegTs.new() + if size == 192 then + local b = strip192(r.buf, r.base + off, r.limit) + d:push(b, 0, buffer.len(b)) + else + d:push(r.buf, r.base + off, r.limit - r.base - off) + end + d:flush() + local units = {} + while true do + local u = d:pull() + if u == nil then + break + end + table.insert(units, u) + end + if #units == 0 then + return nil, Err.new(Err.CORRUPT, "no PES units") + end + -- tracks: the PMT's streams, then PIDs found without one + local tracks= {} + local byPid= {} + local function track(pid, kind, codec, st, lang) +local t = byPid[pid] + if t then + return t + end + t = { + id = pid, + kind = kind == "other" and"data" or kind, + codec = CODEC[codec] or codec, + codecTag = string.format("0x%02x", st), + timescale = 90000, + language = lang, + streamType = st, + } + byPid[pid] = t + table.insert(tracks, t ) + return t + end + for _, s in __iter(d.streams) do + track(s.pid, s.kind, s.codec, s.streamType, s.language) + end + for _, u in __iter(units) do + track(u.pid, u.kind, u.codec, u.streamType, nil) + end + -- codec details from the first unit + local seen= {} + for _, u in __iter(units) do + local t = byPid[u.pid] + if not seen[u.pid] then + seen[u.pid] = true + if t.codec == "unknown" or t.kind == "data" then + -- a private / unknown stream type: go by the PES stream id and the payload + local sid = u.streamId or 0 + if sid >= 0xE0 and sid <= 0xEF then + t.kind = "video" + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + t.codec = (info and{(info.mpeg2 and"mpeg2" or"mpeg1") }or{MpegEs.findStart(u.data, 0, math.min(buffer.len(u.data), 8)) and"h264" or"unknown" +})[1] elseif sid >= 0xC0 and sid <= 0xDF then + t.kind, t.codec = "audio", "mp2" + end + end + if t.codec == "mpeg1" or t.codec == "mpeg2" then + local info = MpegEs.info(u.data, 0, buffer.len(u.data)) + if info then + t.codec = info.mpeg2 and"mpeg2" or"mpeg1" + t.width, t.height, t.frameRate = info.width, info.height, info.frameRate + end + elseif t.codec == "mp2" then + t.codec = mpegAudioCodec(u) + elseif t.codec == "aac" then + t.adts = true + local b= u.data + if buffer.len(b) >= 4 and buffer.readu8(b, 0) == 0xFF then + local rates = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } + t.sampleRate = rates[(math.floor(buffer.readu8(b, 2) / 4)) % 16 + 1] + t.channels = (buffer.readu8(b, 2) % 2) * 4 + math.floor(buffer.readu8(b, 3) / 64 +) end + end + end + end + local dmx = Demux.new("mpegts", tracks, r.buf, { stats = d.stats }) + local lastPts= {} + for _, u in __iter(units) do + local t = byPid[u.pid] + local pts = u.pts90 or u.dts90 + if pts == nil then + local prev = lastPts[u.pid] + if prev and t.frameRate and t.frameRate > 0 then + pts = prev + 90000 / t.frameRate + else + pts = prev + end + end + if pts ~= nil then + lastPts[u.pid] = pts + local key = true + local data= u.data + if t.kind == "video" then + if t.codec == "mpeg1" or t.codec == "mpeg2" then + key = MpegEs.pictureType(data, 0, buffer.len(data)) == 1 + elseif t.codec == "h264" then + key = u.randomAccess or MpegEs.h264Key(data, 0, buffer.len(data)) + else + key = u.randomAccess + end + end + dmx:addData(u.pid, pts, u.dts90 or pts, nil, key, data) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Ts.open(r, opts) +local dmx, err = Ts.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Ts +end +__FILES["video/ogv"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in rosetta, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Ogg = __include("containers/Ogg") +local Demux = __include("containers/Demux") +local AudioWrap = __include("containers/AudioWrap") +local Theora = __include("codecs/video/Theora") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r) +if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size =size+ buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b) +local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, p.bos and 1 or 0, p.continued and 1 or 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value, opts) +local o= opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs= nil + local as= nil + for _, s in __iter(streams) do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs +local headers = Theora.splitConfig(v.config ) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 and 1 or 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = (#v.packets > 0 and{v.packets[1].pts }or{0 +})[1] for i, p in __iter(v.packets) do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and math.floor(buffer.readu8(p.data, 0) / 64 )== 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio= nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as +local track= { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_, _t) +return #a.packets + end, + get = function(_, _t, k) +local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = (c and buffer.len(c) >= 12 and{(buffer.readu16(c, 10) )}or{0 +})[1] else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = (audio and{(pages(audio) )}or{{} +})[1] local out = Bytes.writer(buffer.len(video) + ((audio and{(buffer.len(audio) )}or{0})[1])) + local function put(b, pg) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio , ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list, i) +local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi =vi+ 1 + end + while audio and headerPage(ap, ai) do + put(audio , ap[ai]) + ai =ai+ 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi =vi+ 1 + else + put(audio , na) + ai =ai+ 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list) +local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n =n- 255 + end + w:u8(n) + end + for _, h in __iter(list) do + w:bytes(h) + end + return w:finish() +end + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err + + +function Ogv.demux(r, opts) +local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src= ogg.buf + local tracks= {} + local all= {} + local meta= {} + local function add(track, pts, key, p) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in __iter(ogg:streams()) do +local __DARKLUA_CONTINUE_12=false repeat local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then +__DARKLUA_CONTINUE_12=true break + end + local rd = ogg:reader(st.serial) + local headers= {} + local nh = (codec == "theora" or codec == "vorbis" )and 3 or(codec == "opus" and 2 or 1 +) while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + math.floor(buffer.readu16(p.data, p.offset + 7) / 256 )+ (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then +__DARKLUA_CONTINUE_12=true break + end + local id = #tracks + 1 + local track= { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then +__DARKLUA_CONTINUE_12=true break + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base= nil + while true do +local __DARKLUA_CONTINUE_14=false repeat local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then +__DARKLUA_CONTINUE_14=true break -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end +__DARKLUA_CONTINUE_14=true until true if not __DARKLUA_CONTINUE_14 then break end end + local b0 = base or 0 + for k, p in __iter(packets) do + local key = p.size > 0 and math.floor(buffer.readu8(p.data, p.offset) / 64 )== 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + math.floor(buffer.readu8(h, o + 2) / 16 +) channels = (math.floor(buffer.readu8(h, o + 2) / 2)) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in __iter(parts) do + total =total+ buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in __iter(parts) do + buffer.copy(cfg, o2, x) + o2 =o2+ buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then +__DARKLUA_CONTINUE_12=true break + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) +__DARKLUA_CONTINUE_12=true until true if not __DARKLUA_CONTINUE_12 then break end end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a, c) +local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in __iter(order) do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r, opts) +local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Ogv +end +__FILES["video/smk"] = function() +local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in rosetta, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Stream = __include("codecs/audio/Stream") +local Audio = __include("video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + math.floor(i / 16 +)end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r) +local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b, p, stop, old) +local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8() +local v = (p < stop and{(buffer.readu8(b, p) )}or{0 +})[1] p =p+ 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz =sz+ (t - 0x80 + 1 +) elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz =sz+ 1 + off =off+ 1 + j =j- 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz =sz+ 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r, opts) +local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames =frames+ 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = (ptsInc < 0 and{(-ptsInc )}or{(ptsInc > 0 and((ptsInc * 100 ))or(10000 +))})[1] local tracks= { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } , + } + local audio= {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = bit32.band(f, 0x20) ~= 0 and 16 or 8 + local codec = bit32.band(f, 0x0C) ~= 0 and"binkaudio" +or(bit32.band(f, 0x80) ~= 0 and"smackaudio" +or(bits == 16 and"pcm_s16le" +or"pcm_u8" +)) local t= { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = bit32.band(f, 0x10) ~= 0 and 2 or 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = (opts and opts.ringFrame and{frames }or{shown +})[1] local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at =at+ size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q =q+ psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = t and t.codec ~= "pcm_s16le" and 8 or 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = math.floor((t.channels ) * (t.bitsPerSample ) / 8 +) local n = (t.codec == "smackaudio" and{(math.floor(buffer.readu32(b, q + 4) / frameBytes +))}or{t.codec == "binkaudio" and 0 +or math.floor(len / frameBytes +)})[1] dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k]=apts[k]+ n + end + q =q+ asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx, track) +local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts= {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate , track.channels , track.bitsPerSample +local packed = codec == "smackaudio" + local floats= {} + local dec= { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i) +return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i) +local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out ) + end + floats = out +return n, nil + end, + pcm = function() +return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r, opts) +local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o= table.clone(opts or {}) + +local hook = o.openAudio +o.openAudio = function(d, track) +if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk +end +__FILES["video/smk/Audio"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = __include("codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +function Audio.decode(d, channels, bits, packed) +local n = buffer.len(d) + if not packed then + local bps = math.floor(bits / 8 +) local frames = math.floor(n / (bps * channels) +) local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees= {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in __iter(trees) do + if #t > 1 then + coded = true + end + end + local frames = math.floor(size / (ch * bytes) +) local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (math.floor(v / 256)) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = ((v >= 32768 and((v - 65536 ))or(v))) / 32768 + end + for i = ch, total - 1 do + local c = (ch == 2 and((i % 2 ))or(0 +)) if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = ((v >= 32768 and((v - 65536 ))or(v))) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = (ch == 2 and((i % 2 ))or(0 +)) if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio +end +__FILES["video/y4m"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in rosetta. +-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder +-- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono +-- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. +-- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 +-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), +-- alpha (C444alpha drops it). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Demux = __include("containers/Demux") +local Video = __include("codecs/video/Video") +local Source = __include("codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Y4m = { + name = "y4m", + category = "video", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + 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 } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + +local MAGIC = "YUV4MPEG2 " +-- C tag -> pixel format, bits +local COLOR= { + ["420jpeg"] = { "yuv420p", 8 }, + ["420paldv"] = { "yuv420p", 8 }, + ["420mpeg2"] = { "yuv420p", 8 }, + ["420"] = { "yuv420p", 8 }, + ["422"] = { "yuv422p", 8 }, + ["444"] = { "yuv444p", 8 }, + ["444alpha"] = { "yuva444p", 8 }, + mono = { "gray", 8 }, +} +for _, b in __iter({ 9, 10, 12, 14, 16 }) do + COLOR["420p" .. b] = { "yuv420p", b } + COLOR["422p" .. b] = { "yuv422p", b } + COLOR["444p" .. b] = { "yuv444p", b } + COLOR["mono" .. b] = { "gray", b } +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Y4m.sniff(r) +return r:peek(10) == MAGIC and 1 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function frameSize(pf, bits, w, h) +local bps = bits > 8 and 2 or 1 + local cw, ch = math.floor((w + 1) / 2), math.floor((h + 1) / 2 +) if pf == "yuv420p" then + return (w * h + 2 * cw * ch) * bps + elseif pf == "yuv422p" then + return (w * h + 2 * cw * h) * bps + elseif pf == "yuv444p" then + return w * h * 3 * bps + elseif pf == "yuva444p" then + return w * h * 4 * bps + end + return w * h * bps +end + +-- demux(r, opts?) -> the raw-video Demuxer | nil, Err +function Y4m.demux(r, opts) +local buf, base, limit = r.buf, r.base, r.limit + local nl = -1 + for i = base, math.min(limit, base + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + nl = i + break + end + end + if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base) + end + if nl < 0 then + return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base) + end + local header = buffer.readstring(buf, base + 10, nl - base - 10) + local w, h, fn, fd = 0, 0, 25, 1 + local ctag, itag, atag = "420jpeg", "p", "0:0" + local extra = {} + for tok in __iter(string.gmatch(header, "%S+")) do + local k, v = string.sub(tok, 1, 1), string.sub(tok, 2) + if k == "W" then + w = tonumber(v) or 0 + elseif k == "H" then + h = tonumber(v) or 0 + elseif k == "F" then + local a, b = string.match(v, "^(%d+):(%d+)$") + if a and b and ((tonumber(a) )) > 0 and ((tonumber(b) )) > 0 then + fn, fd = (tonumber(a) ), (tonumber(b) ) +end + elseif k == "C" then + ctag = v + elseif k == "I" then + itag = v + elseif k == "A" then + atag = v + elseif k == "X" then + table.insert(extra, v) + end + end + local color = COLOR[ctag] + if not color then + return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag) + end + if w <= 0 or h <= 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels") + end + local pf, bits = color[1], color[2] + local size = frameSize(pf, bits, w, h) + local track= { + id = 1, + kind = "video", + codec = "rawvideo", + codecTag = "C" .. ctag, + timescale = fn / fd, + width = w, + height = h, + frameRate = fn / fd, + pixelFormat = pf, + bitDepth = bits, + default = true, + } + local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag } + local dmx = Demux.new("y4m", { track }, buf, meta) + local pos = nl + 1 + local k = 0 + while pos + 5 <= limit do + if buffer.readstring(buf, pos, 5) ~= "FRAME" then + return nil, Err.new(Err.CORRUPT, "expected FRAME", pos) + end + local e = -1 + for i = pos + 5, math.min(limit, pos + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + e = i + break + end + end + if e < 0 then + break + end + local data = e + 1 + if data + size > limit then + break -- a truncated last frame is dropped + end + dmx:add(1, k, k, 1, true, data, size) + k =k+ 1 + pos = data + size + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(video, opts?) -> buffer | nil, Err +function Y4m.encode(value, opts) +local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) + if not streams then + return nil, err + end + local s = streams[1] + local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps) + if opts and type(opts.frameRate) == "table" then + fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets + end + s.packets = packets + local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6)) + w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd)) + for _, p in __iter(s.packets) do + w:string("FRAME\n") + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Y4m.open(r, opts) +local dmx, err = Y4m.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts ) +end + +return Y4m +end +local Rosetta = __include("") +Rosetta._internal = function(path) + return __include(path) +end +return Rosetta diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json new file mode 100644 index 0000000..e10c8ed --- /dev/null +++ b/build/rosetta.lua.linemap.json @@ -0,0 +1,539 @@ +[ +[689, "src/Rosetta/init.luau"], +[1617, "src/Rosetta/Registry.luau"], +[3726, "src/Rosetta/Types.luau"], +[4883, "src/Rosetta/archive/7z/init.luau"], +[5276, "src/Rosetta/archive/7z/Header.luau"], +[5808, "src/Rosetta/archive/adf/init.luau"], +[6098, "src/Rosetta/archive/applesingle/init.luau"], +[6290, "src/Rosetta/archive/ar/init.luau"], +[6702, "src/Rosetta/archive/arj/init.luau"], +[6916, "src/Rosetta/archive/binhex/init.luau"], +[7172, "src/Rosetta/archive/br/init.luau"], +[7250, "src/Rosetta/archive/bz2/init.luau"], +[7316, "src/Rosetta/archive/cab/init.luau"], +[7745, "src/Rosetta/archive/cab/Sum.luau"], +[7789, "src/Rosetta/archive/cpio/init.luau"], +[7963, "src/Rosetta/archive/d64/init.luau"], +[8389, "src/Rosetta/archive/fat/init.luau"], +[8515, "src/Rosetta/archive/grp/init.luau"], +[8632, "src/Rosetta/archive/gzip/init.luau"], +[8821, "src/Rosetta/archive/iso/init.luau"], +[8898, "src/Rosetta/archive/lha/init.luau"], +[9334, "src/Rosetta/archive/lz4/init.luau"], +[9689, "src/Rosetta/archive/macbinary/init.luau"], +[9892, "src/Rosetta/archive/mpq/init.luau"], +[10313, "src/Rosetta/archive/mpq/Crypt.luau"], +[10380, "src/Rosetta/archive/pak/init.luau"], +[10517, "src/Rosetta/archive/rpm/init.luau"], +[10852, "src/Rosetta/archive/tar/init.luau"], +[10974, "src/Rosetta/archive/uu/init.luau"], +[11252, "src/Rosetta/archive/vpk/init.luau"], +[11571, "src/Rosetta/archive/wad/init.luau"], +[12047, "src/Rosetta/archive/wad/Map.luau"], +[12490, "src/Rosetta/archive/wad/Picture.luau"], +[12601, "src/Rosetta/archive/xz/init.luau"], +[12704, "src/Rosetta/archive/yenc/init.luau"], +[12983, "src/Rosetta/archive/z/init.luau"], +[13083, "src/Rosetta/archive/zip/init.luau"], +[13323, "src/Rosetta/archive/zoo/init.luau"], +[13522, "src/Rosetta/archive/zst/init.luau"], +[13587, "src/Rosetta/audio/aac/init.luau"], +[13798, "src/Rosetta/audio/ac3/init.luau"], +[13947, "src/Rosetta/audio/adpcm/init.luau"], +[14104, "src/Rosetta/audio/adx/init.luau"], +[14343, "src/Rosetta/audio/aiff/init.luau"], +[14745, "src/Rosetta/audio/ape/init.luau"], +[14881, "src/Rosetta/audio/au/init.luau"], +[15044, "src/Rosetta/audio/brstm/init.luau"], +[15344, "src/Rosetta/audio/caf/init.luau"], +[16014, "src/Rosetta/audio/flac/init.luau"], +[16177, "src/Rosetta/audio/flac/Meta.luau"], +[16402, "src/Rosetta/audio/flac/Stream.luau"], +[16787, "src/Rosetta/audio/m4a/init.luau"], +[17129, "src/Rosetta/audio/mp3/init.luau"], +[17409, "src/Rosetta/audio/mp3/Index.luau"], +[17605, "src/Rosetta/audio/mp3/Stream.luau"], +[17840, "src/Rosetta/audio/mp3/Tags.luau"], +[18159, "src/Rosetta/audio/mpc/init.luau"], +[18257, "src/Rosetta/audio/opus/init.luau"], +[18661, "src/Rosetta/audio/opus/Encode.luau"], +[18780, "src/Rosetta/audio/qoa/init.luau"], +[18967, "src/Rosetta/audio/tta/init.luau"], +[19092, "src/Rosetta/audio/vag/init.luau"], +[19325, "src/Rosetta/audio/voc/init.luau"], +[19605, "src/Rosetta/audio/vorbis/init.luau"], +[20077, "src/Rosetta/audio/vorbis/Encode.luau"], +[20906, "src/Rosetta/audio/wav/init.luau"], +[21551, "src/Rosetta/audio/wav/Codecs.luau"], +[21726, "src/Rosetta/audio/wavpack/init.luau"], +[21947, "src/Rosetta/cad/step/init.luau"], +[22359, "src/Rosetta/cad/step/Brep.luau"], +[22609, "src/Rosetta/cad/step/Parse.luau"], +[23184, "src/Rosetta/cad/step/Write.luau"], +[23438, "src/Rosetta/codecs/audio/Aac/init.luau"], +[23776, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[24681, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[25017, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[25191, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[26109, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[26213, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[27033, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[27363, "src/Rosetta/codecs/audio/Alac/init.luau"], +[27616, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[28045, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[28474, "src/Rosetta/codecs/audio/Ape/init.luau"], +[28705, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[29485, "src/Rosetta/codecs/audio/ApeTag.luau"], +[29597, "src/Rosetta/codecs/audio/Flac/init.luau"], +[29610, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[30600, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[31212, "src/Rosetta/codecs/audio/Hively/init.luau"], +[31423, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[31674, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[32646, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[32869, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[33074, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[33287, "src/Rosetta/codecs/audio/MidiRender.luau"], +[33648, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[33663, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[33728, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[35367, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[35661, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[36057, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[36724, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[36866, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[37092, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[37453, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[38354, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[38735, "src/Rosetta/codecs/audio/Opus/init.luau"], +[38752, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[40618, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[41698, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[41758, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[42226, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[42574, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[42811, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[44883, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[45257, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[45553, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[45863, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[46162, "src/Rosetta/codecs/audio/Resample/init.luau"], +[46541, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[46612, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[46763, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[47288, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[48093, "src/Rosetta/codecs/audio/Stream.luau"], +[48276, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[48830, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[49123, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[49298, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[49432, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[51460, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[51588, "src/Rosetta/codecs/audio/Tta/init.luau"], +[51716, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[51977, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[51992, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[52388, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[52976, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[53407, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[53446, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[53510, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[53750, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[55235, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[55302, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[55405, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[56403, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[57271, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[57329, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[57859, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[58217, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[58651, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[59107, "src/Rosetta/codecs/compress/Explode.luau"], +[59313, "src/Rosetta/codecs/compress/Lz4.luau"], +[59606, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[60234, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[60803, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[60842, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[61336, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[61515, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[61806, "src/Rosetta/codecs/compress/Lzx.luau"], +[62257, "src/Rosetta/codecs/compress/PackBits.luau"], +[62354, "src/Rosetta/codecs/compress/Quantum.luau"], +[62607, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[62928, "src/Rosetta/codecs/compress/Xxh32.luau"], +[63002, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[63072, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[64054, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[64211, "src/Rosetta/codecs/entropy/Huffman.luau"], +[64519, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[64534, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[64751, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[65005, "src/Rosetta/codecs/font/Bitmap.luau"], +[65227, "src/Rosetta/codecs/font/Cff/init.luau"], +[65886, "src/Rosetta/codecs/font/GlyphNames.luau"], +[66042, "src/Rosetta/codecs/font/TrueType/init.luau"], +[66382, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[66787, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[67308, "src/Rosetta/codecs/image/Bcn/init.luau"], +[67431, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[67931, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[68375, "src/Rosetta/codecs/image/Blend.luau"], +[68776, "src/Rosetta/codecs/image/Dct/init.luau"], +[69174, "src/Rosetta/codecs/image/Etc.luau"], +[69491, "src/Rosetta/codecs/image/Half.luau"], +[69567, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[69959, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[70375, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[70625, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[71398, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[72299, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[72762, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[72841, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[72919, "src/Rosetta/codecs/image/Pixels.luau"], +[73204, "src/Rosetta/codecs/image/Quantize/init.luau"], +[73689, "src/Rosetta/codecs/image/Raster.luau"], +[74435, "src/Rosetta/codecs/image/Texel.luau"], +[74835, "src/Rosetta/codecs/image/Texture.luau"], +[74999, "src/Rosetta/codecs/image/Vp8/init.luau"], +[75159, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[77148, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[77424, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[77675, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[77800, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[77922, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[78797, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[79775, "src/Rosetta/codecs/image/Yuv.luau"], +[80065, "src/Rosetta/codecs/model/Draco/init.luau"], +[80420, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[80901, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[82107, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[82265, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[82630, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[83609, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[84091, "src/Rosetta/codecs/model/Mat4.luau"], +[84375, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[84920, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[85509, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[85592, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[85702, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[85924, "src/Rosetta/codecs/model/Polygon.luau"], +[86174, "src/Rosetta/codecs/model/Rbx/init.luau"], +[86457, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[87233, "src/Rosetta/codecs/model/Rig.luau"], +[87509, "src/Rosetta/codecs/model/Sampler.luau"], +[87684, "src/Rosetta/codecs/model/Vrml/init.luau"], +[87846, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[88438, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[88608, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[89380, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[89918, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[90670, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[90910, "src/Rosetta/codecs/text/Json/init.luau"], +[91206, "src/Rosetta/codecs/text/Json/Decode.luau"], +[91633, "src/Rosetta/codecs/text/Json/Encode.luau"], +[91942, "src/Rosetta/codecs/text/Nbt/init.luau"], +[92324, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[93024, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[93675, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[93933, "src/Rosetta/codecs/text/Text/init.luau"], +[94029, "src/Rosetta/codecs/text/Url/init.luau"], +[94247, "src/Rosetta/codecs/text/Xml/init.luau"], +[94689, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[95454, "src/Rosetta/codecs/video/Dsp.luau"], +[96199, "src/Rosetta/codecs/video/H263/init.luau"], +[96377, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[97273, "src/Rosetta/codecs/video/H263/Tables.luau"], +[97481, "src/Rosetta/codecs/video/H264/init.luau"], +[97898, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[98193, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[99338, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[100117, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[100383, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[101409, "src/Rosetta/codecs/video/H264/Inter.luau"], +[101677, "src/Rosetta/codecs/video/H264/Intra.luau"], +[102089, "src/Rosetta/codecs/video/H264/Mb.luau"], +[103022, "src/Rosetta/codecs/video/H264/Params.luau"], +[103477, "src/Rosetta/codecs/video/H264/Slice.luau"], +[103730, "src/Rosetta/codecs/video/H264/Tables.luau"], +[103774, "src/Rosetta/codecs/video/H264/Transform.luau"], +[103950, "src/Rosetta/codecs/video/Legacy/init.luau"], +[104166, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[104471, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[104845, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[104968, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[105085, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[105363, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[105770, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[105955, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[105968, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[106384, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[107948, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[108088, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[108234, "src/Rosetta/codecs/video/Theora/init.luau"], +[108525, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[109815, "src/Rosetta/codecs/video/Theora/Header.luau"], +[110187, "src/Rosetta/codecs/video/Video/init.luau"], +[110790, "src/Rosetta/codecs/video/Video/Source.luau"], +[111097, "src/Rosetta/containers/Archive.luau"], +[111390, "src/Rosetta/containers/AudioWrap.luau"], +[111911, "src/Rosetta/containers/Avi/init.luau"], +[112483, "src/Rosetta/containers/Chunks.luau"], +[112627, "src/Rosetta/containers/Cpio.luau"], +[113069, "src/Rosetta/containers/Demux.luau"], +[113367, "src/Rosetta/containers/Ebml/init.luau"], +[113704, "src/Rosetta/containers/Fat.luau"], +[114413, "src/Rosetta/containers/Iso9660.luau"], +[114940, "src/Rosetta/containers/IsoBmff/init.luau"], +[115130, "src/Rosetta/containers/IsoBmff/Box.luau"], +[115325, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[116189, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[116719, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[117240, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[117362, "src/Rosetta/containers/MacFile.luau"], +[117522, "src/Rosetta/containers/MpegEs.luau"], +[117697, "src/Rosetta/containers/MpegPs/init.luau"], +[117923, "src/Rosetta/containers/MpegTs/init.luau"], +[118740, "src/Rosetta/containers/Ogg/init.luau"], +[119198, "src/Rosetta/containers/Ogg/Mux.luau"], +[119408, "src/Rosetta/containers/Ogg/Page.luau"], +[119585, "src/Rosetta/containers/Riff/init.luau"], +[119930, "src/Rosetta/containers/Tar.luau"], +[120358, "src/Rosetta/containers/Zip/init.luau"], +[121018, "src/Rosetta/core/Adler32.luau"], +[121070, "src/Rosetta/core/Base64.luau"], +[121239, "src/Rosetta/core/Bits.luau"], +[121551, "src/Rosetta/core/Bytes.luau"], +[122120, "src/Rosetta/core/Crc16.luau"], +[122174, "src/Rosetta/core/Crc32.luau"], +[122297, "src/Rosetta/core/Err.luau"], +[122393, "src/Rosetta/core/Input.luau"], +[122477, "src/Rosetta/core/Md5.luau"], +[122643, "src/Rosetta/core/Sniff.luau"], +[122681, "src/Rosetta/data/cbor/init.luau"], +[122783, "src/Rosetta/data/cbor/Codec.luau"], +[123360, "src/Rosetta/data/csv/init.luau"], +[123677, "src/Rosetta/data/ini/init.luau"], +[123928, "src/Rosetta/data/json/init.luau"], +[124021, "src/Rosetta/data/msgpack/init.luau"], +[124113, "src/Rosetta/data/msgpack/Codec.luau"], +[124561, "src/Rosetta/data/nbt/init.luau"], +[124623, "src/Rosetta/data/plist/init.luau"], +[124931, "src/Rosetta/data/plist/Binary.luau"], +[125204, "src/Rosetta/data/snbt/init.luau"], +[125269, "src/Rosetta/data/toml/init.luau"], +[125341, "src/Rosetta/data/toml/Decode.luau"], +[125978, "src/Rosetta/data/toml/Encode.luau"], +[126194, "src/Rosetta/data/xml/init.luau"], +[126251, "src/Rosetta/data/yaml/init.luau"], +[126330, "src/Rosetta/data/yaml/Emit.luau"], +[126631, "src/Rosetta/data/yaml/Parse.luau"], +[127955, "src/Rosetta/font/bdf/init.luau"], +[128252, "src/Rosetta/font/bmfont/init.luau"], +[128694, "src/Rosetta/font/bmfont/Parse.luau"], +[129153, "src/Rosetta/font/eot/init.luau"], +[129388, "src/Rosetta/font/fon/init.luau"], +[129678, "src/Rosetta/font/hershey/init.luau"], +[129880, "src/Rosetta/font/pcf/init.luau"], +[130172, "src/Rosetta/font/psf/init.luau"], +[130502, "src/Rosetta/font/ttf/init.luau"], +[130556, "src/Rosetta/font/type1/init.luau"], +[130926, "src/Rosetta/font/type1/Charstring.luau"], +[131211, "src/Rosetta/font/woff/init.luau"], +[131345, "src/Rosetta/font/woff2/init.luau"], +[131404, "src/Rosetta/font/woff2/Rebuild.luau"], +[131954, "src/Rosetta/host/init.luau"], +[132006, "src/Rosetta/host/Love.luau"], +[132157, "src/Rosetta/host/LuaJIT.luau"], +[132207, "src/Rosetta/host/Luau.luau"], +[132230, "src/Rosetta/host/Roblox.luau"], +[132621, "src/Rosetta/image/ani/init.luau"], +[132806, "src/Rosetta/image/blp/init.luau"], +[133074, "src/Rosetta/image/bmp/init.luau"], +[133505, "src/Rosetta/image/dds/init.luau"], +[134004, "src/Rosetta/image/exr/init.luau"], +[134788, "src/Rosetta/image/exr/Codec.luau"], +[134907, "src/Rosetta/image/exr/Piz.luau"], +[135276, "src/Rosetta/image/gif/init.luau"], +[135812, "src/Rosetta/image/gif/Decode.luau"], +[135882, "src/Rosetta/image/hdr/init.luau"], +[136118, "src/Rosetta/image/hdr/Codec.luau"], +[136339, "src/Rosetta/image/icns/init.luau"], +[136678, "src/Rosetta/image/ico/init.luau"], +[136962, "src/Rosetta/image/ico/Dib.luau"], +[137063, "src/Rosetta/image/ilbm/init.luau"], +[137389, "src/Rosetta/image/jpeg/init.luau"], +[137540, "src/Rosetta/image/ktx/init.luau"], +[138214, "src/Rosetta/image/pcx/init.luau"], +[138482, "src/Rosetta/image/png/init.luau"], +[139080, "src/Rosetta/image/png/Apng.luau"], +[139164, "src/Rosetta/image/png/Decode.luau"], +[139419, "src/Rosetta/image/png/Encode.luau"], +[139583, "src/Rosetta/image/pnm/init.luau"], +[139969, "src/Rosetta/image/pnm/Codec.luau"], +[140260, "src/Rosetta/image/qoi/init.luau"], +[140384, "src/Rosetta/image/qoi/Codec.luau"], +[140538, "src/Rosetta/image/sgi/init.luau"], +[140826, "src/Rosetta/image/sunras/init.luau"], +[141075, "src/Rosetta/image/tga/init.luau"], +[141353, "src/Rosetta/image/tga/Codec.luau"], +[141512, "src/Rosetta/image/tiff/init.luau"], +[142356, "src/Rosetta/image/tiff/Pixels.luau"], +[142757, "src/Rosetta/image/tim/init.luau"], +[143006, "src/Rosetta/image/vtf/init.luau"], +[143253, "src/Rosetta/image/webp/init.luau"], +[143882, "src/Rosetta/image/webp/Alpha.luau"], +[143960, "src/Rosetta/image/webp/Anim.luau"], +[144124, "src/Rosetta/image/xbm/init.luau"], +[144288, "src/Rosetta/image/xpm/init.luau"], +[144562, "src/Rosetta/image/xpm/Names.luau"], +[144621, "src/Rosetta/layered/aseprite/init.luau"], +[145377, "src/Rosetta/layered/ora/init.luau"], +[145672, "src/Rosetta/layered/psd/init.luau"], +[146417, "src/Rosetta/layered/psd/Channels.luau"], +[146788, "src/Rosetta/model/3ds/init.luau"], +[146890, "src/Rosetta/model/3ds/Build.luau"], +[147555, "src/Rosetta/model/3ds/Read.luau"], +[148063, "src/Rosetta/model/3ds/Write.luau"], +[148892, "src/Rosetta/model/3mf/init.luau"], +[148989, "src/Rosetta/model/3mf/Read.luau"], +[149589, "src/Rosetta/model/3mf/Write.luau"], +[150008, "src/Rosetta/model/b3d/init.luau"], +[150078, "src/Rosetta/model/b3d/Read.luau"], +[150656, "src/Rosetta/model/bsp/init.luau"], +[150808, "src/Rosetta/model/bsp/Brush.luau"], +[151101, "src/Rosetta/model/bsp/Quake3.luau"], +[151364, "src/Rosetta/model/dae/init.luau"], +[151572, "src/Rosetta/model/dae/Math.luau"], +[151620, "src/Rosetta/model/dae/Read.luau"], +[153502, "src/Rosetta/model/dae/Write.luau"], +[153880, "src/Rosetta/model/fbx/init.luau"], +[154048, "src/Rosetta/model/fbx/Ascii.luau"], +[154324, "src/Rosetta/model/fbx/Binary.luau"], +[154787, "src/Rosetta/model/fbx/Read.luau"], +[156173, "src/Rosetta/model/fbx/Write.luau"], +[157171, "src/Rosetta/model/fbx/Xform.luau"], +[157215, "src/Rosetta/model/gltf/init.luau"], +[157469, "src/Rosetta/model/gltf/Pack.luau"], +[157545, "src/Rosetta/model/gltf/Read.luau"], +[158294, "src/Rosetta/model/gltf/Write.luau"], +[158992, "src/Rosetta/model/iqm/init.luau"], +[159076, "src/Rosetta/model/iqm/Read.luau"], +[159437, "src/Rosetta/model/iqm/Write.luau"], +[160145, "src/Rosetta/model/ldraw/init.luau"], +[160252, "src/Rosetta/model/ldraw/Colors.luau"], +[160573, "src/Rosetta/model/ldraw/Read.luau"], +[161155, "src/Rosetta/model/lwo/init.luau"], +[161243, "src/Rosetta/model/lwo/Build.luau"], +[161714, "src/Rosetta/model/lwo/Parse.luau"], +[162267, "src/Rosetta/model/mca/init.luau"], +[162624, "src/Rosetta/model/mca/Chunk.luau"], +[162761, "src/Rosetta/model/mca/Lz4Block.luau"], +[162833, "src/Rosetta/model/md2/init.luau"], +[163044, "src/Rosetta/model/md3/init.luau"], +[163280, "src/Rosetta/model/md5/init.luau"], +[163365, "src/Rosetta/model/md5/Read.luau"], +[163807, "src/Rosetta/model/mdl/init.luau"], +[163893, "src/Rosetta/model/mdl/HalfLife.luau"], +[164235, "src/Rosetta/model/mdl/Quake.luau"], +[164459, "src/Rosetta/model/ms3d/init.luau"], +[164543, "src/Rosetta/model/ms3d/Read.luau"], +[165009, "src/Rosetta/model/ms3d/Write.luau"], +[165497, "src/Rosetta/model/obj/init.luau"], +[166262, "src/Rosetta/model/obj/Mtl.luau"], +[166558, "src/Rosetta/model/off/init.luau"], +[167040, "src/Rosetta/model/ply/init.luau"], +[168190, "src/Rosetta/model/ply/Binary.luau"], +[168404, "src/Rosetta/model/pmx/init.luau"], +[168483, "src/Rosetta/model/pmx/Build.luau"], +[168792, "src/Rosetta/model/pmx/Pmd.luau"], +[169133, "src/Rosetta/model/pmx/Read.luau"], +[169546, "src/Rosetta/model/qb/init.luau"], +[169949, "src/Rosetta/model/rbxm/init.luau"], +[170556, "src/Rosetta/model/rbxmx/init.luau"], +[171225, "src/Rosetta/model/robloxmesh/init.luau"], +[171911, "src/Rosetta/model/robloxmesh/Parse.luau"], +[172373, "src/Rosetta/model/robloxmesh/Write.luau"], +[172484, "src/Rosetta/model/schematic/init.luau"], +[172820, "src/Rosetta/model/schematic/Common.luau"], +[172950, "src/Rosetta/model/schematic/Litematic.luau"], +[173167, "src/Rosetta/model/schematic/Mcedit.luau"], +[173418, "src/Rosetta/model/schematic/Sponge.luau"], +[173551, "src/Rosetta/model/smd/init.luau"], +[173622, "src/Rosetta/model/smd/Read.luau"], +[173899, "src/Rosetta/model/smd/Write.luau"], +[174151, "src/Rosetta/model/stl/init.luau"], +[174620, "src/Rosetta/model/stl/Decode.luau"], +[174699, "src/Rosetta/model/usda/init.luau"], +[174922, "src/Rosetta/model/usda/Build.luau"], +[176239, "src/Rosetta/model/usda/Parse.luau"], +[177061, "src/Rosetta/model/usda/Write.luau"], +[177903, "src/Rosetta/model/vox/init.luau"], +[178808, "src/Rosetta/model/vox/Grid.luau"], +[178871, "src/Rosetta/model/vrml/init.luau"], +[178950, "src/Rosetta/model/x/init.luau"], +[179094, "src/Rosetta/model/x/Build.luau"], +[179670, "src/Rosetta/model/x/Parse.luau"], +[179978, "src/Rosetta/model/x3d/init.luau"], +[180065, "src/Rosetta/music/669/init.luau"], +[180276, "src/Rosetta/music/ahx/init.luau"], +[180331, "src/Rosetta/music/far/init.luau"], +[180565, "src/Rosetta/music/hmp/init.luau"], +[180840, "src/Rosetta/music/hvl/init.luau"], +[180895, "src/Rosetta/music/it/init.luau"], +[181324, "src/Rosetta/music/it/Itsex.luau"], +[181446, "src/Rosetta/music/med/init.luau"], +[182109, "src/Rosetta/music/midi/init.luau"], +[182265, "src/Rosetta/music/midi/Smf.luau"], +[182685, "src/Rosetta/music/mod/init.luau"], +[183048, "src/Rosetta/music/mtm/init.luau"], +[183276, "src/Rosetta/music/mus/init.luau"], +[183441, "src/Rosetta/music/okt/init.luau"], +[183729, "src/Rosetta/music/ptm/init.luau"], +[183958, "src/Rosetta/music/s3m/init.luau"], +[184202, "src/Rosetta/music/sf2/init.luau"], +[184248, "src/Rosetta/music/stm/init.luau"], +[184483, "src/Rosetta/music/ult/init.luau"], +[184794, "src/Rosetta/music/umx/init.luau"], +[185018, "src/Rosetta/music/xm/init.luau"], +[185593, "src/Rosetta/music/xmi/init.luau"], +[185810, "src/Rosetta/ops/AudioOps.luau"], +[186294, "src/Rosetta/ops/ImageOps/init.luau"], +[186985, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[187507, "src/Rosetta/ops/LayerOps.luau"], +[187610, "src/Rosetta/ops/MeshOps/init.luau"], +[188699, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[188868, "src/Rosetta/ops/MusicOps.luau"], +[189239, "src/Rosetta/playlist/m3u/init.luau"], +[189608, "src/Rosetta/playlist/pls/init.luau"], +[189795, "src/Rosetta/playlist/xspf/init.luau"], +[190011, "src/Rosetta/subtitle/ass/init.luau"], +[190469, "src/Rosetta/subtitle/srt/init.luau"], +[190649, "src/Rosetta/subtitle/vtt/init.luau"], +[190859, "src/Rosetta/vector/svg/init.luau"], +[190955, "src/Rosetta/vector/svg/Parse.luau"], +[191715, "src/Rosetta/vector/svg/PathData.luau"], +[192094, "src/Rosetta/vector/svg/Render.luau"], +[192523, "src/Rosetta/vector/svg/Style.luau"], +[192906, "src/Rosetta/vector/svg/Write.luau"], +[193111, "src/Rosetta/vector/tiled/init.luau"], +[193300, "src/Rosetta/vector/tiled/Data.luau"], +[193458, "src/Rosetta/vector/tiled/Tmj.luau"], +[194094, "src/Rosetta/vector/tiled/Tmx.luau"], +[194714, "src/Rosetta/video/avi/init.luau"], +[195019, "src/Rosetta/video/fli/init.luau"], +[195178, "src/Rosetta/video/flv/init.luau"], +[195582, "src/Rosetta/video/flv/Amf.luau"], +[195750, "src/Rosetta/video/flv/Mux.luau"], +[196040, "src/Rosetta/video/h264/init.luau"], +[196187, "src/Rosetta/video/mkv/init.luau"], +[196358, "src/Rosetta/video/mkv/Mux.luau"], +[196645, "src/Rosetta/video/mkv/Parse.luau"], +[197377, "src/Rosetta/video/mp4/init.luau"], +[197720, "src/Rosetta/video/mpegps/init.luau"], +[197915, "src/Rosetta/video/mpegts/init.luau"], +[198163, "src/Rosetta/video/ogv/init.luau"], +[198572, "src/Rosetta/video/smk/init.luau"], +[198894, "src/Rosetta/video/smk/Audio.luau"], +[199019, "src/Rosetta/video/y4m/init.luau"] +] diff --git a/compat/luajit.lua b/compat/luajit.lua index ae30c82..973a5dc 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -1,5 +1,6 @@ -- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain luajit and LÖVE). --- tools/build.py copies this file to build/luajit/rosetta/_compat.lua, and every built module starts with +-- tools/build.py copies this file to build/_modules/luajit/rosetta/_compat.lua (tools/bundle.py inlines it at the top +-- of build/rosetta.lua), and every built module starts with -- local __compat = require("rosetta._compat") local buffer, bit32, utf8, typeof, type, __iter = ... -- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string -- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing. diff --git a/default.project.json b/default.project.json index 1c396aa..1f22683 100644 --- a/default.project.json +++ b/default.project.json @@ -1,6 +1,6 @@ { "name": "Rosetta", "tree": { - "$path": "build/roblox/Rosetta" + "$path": "build/Rosetta.luau" } } diff --git a/docs/guide/README.md b/docs/guide/README.md index a4a0d77..cae0420 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -41,34 +41,29 @@ as `F`, and its input files as variables such as `pngBytes` (a buffer) or `srtTe ## Installing -**Roblox (Rojo).** Build the Roblox tree, then let Rojo turn it into a model or sync it into Studio: - -```sh -python3 -I tools/build.py roblox # writes build/roblox/Rosetta (requires become instance paths) -rojo build -o Rosetta.rbxm # default.project.json mounts build/roblox/Rosetta; or: rojo serve -``` - -Put the `Rosetta` ModuleScript somewhere both client and server can see it, for example ReplicatedStorage: +**Roblox.** The library is one ModuleScript, [`build/Rosetta.luau`](../../build/Rosetta.luau) (committed; rebuilt by +`python3 -I tools/build.py roblox`). Paste it into a ModuleScript named `Rosetta`, or mount it with Rojo +(`"Rosetta": { "$path": "rosetta/build/Rosetta.luau" }`; this repository's `default.project.json` does, so +`rojo build -o Rosetta.rbxm` or `rojo serve` works from here). Put it where both client and server can see it, for +example ReplicatedStorage: <!-- doc:display needs Roblox --> ```luau local F = require(game:GetService("ReplicatedStorage").Rosetta) +local Mpeg1 = F._internal("codecs/video/Mpeg1") -- an internal module, by its path under src/Rosetta ``` -Roblox has no file system: pass buffers or strings, for example from `HttpService:GetAsync` or a `buffer` you built. +Requiring it runs only the API and what it needs at load time; every format and codec runs on first use. Roblox has +no file system: pass buffers or strings, for example from `HttpService:GetAsync` or a `buffer` you built. -**LuaJIT and LÖVE.** Build the Lua 5.1 tree: - -```sh -python3 -I tools/build.py luajit # writes build/luajit/rosetta/ (plain Lua 5.1 + the LuaJIT FFI) -``` - -Then either copy `build/luajit/rosetta` into your game, or put the build on `package.path`: +**LuaJIT and LÖVE.** The library is one file, [`build/rosetta.lua`](../../build/rosetta.lua) (plain Lua 5.1 + the +LuaJIT FFI; rebuilt by `python3 -I tools/build.py luajit`). Copy it into your game and require it from a folder on +`package.path`, or load it with `dofile`: <!-- doc:display plain LuaJIT code --> ```lua -package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path -local F = require("rosetta") +package.path = "build/?.lua;" .. package.path +local F = require("rosetta") -- or: local F = dofile("build/rosetta.lua") ``` The library carries its own copy of the Luau standard library pieces it uses (`buffer`, `bit32`, `utf8`, ...). diff --git a/examples/love/main.lua b/examples/love/main.lua index 78ba79f..38499c1 100644 --- a/examples/love/main.lua +++ b/examples/love/main.lua @@ -1,4 +1,4 @@ --- LÖVE smoke test / example for the LuaJIT build (tools/build.py luajit), run from the repo root: +-- LÖVE smoke test / example for the LuaJIT bundle build/rosetta.lua (tools/build.py luajit), run from the repo root: -- love examples/love (a window: images, a voxel model, a tone) -- ROSETTA_SMOKE=1 xvfb-run love examples/love (headless: checks, a screenshot, then quits; exit code 1 on -- failure) @@ -7,7 +7,7 @@ -- video (decoded in love.update with a time budget per frame), and shows them with love.graphics / love.audio through -- the host's toImageData / toSoundData. docs/guide/README.md explains the API. local root = (love.filesystem.getSource():gsub("/examples/love/?$", "")) -package.path = root .. "/build/luajit/?.lua;" .. root .. "/build/luajit/?/init.lua;" .. package.path +package.path = root .. "/build/?.lua;" .. package.path -- build/rosetta.lua (or: local F = dofile(root .. "/build/rosetta.lua")) local F = require("rosetta") require("rosetta._compat").install() -- buffer / bit32 globals for this file (the library itself does not need them) @@ -46,7 +46,7 @@ function love.load() if check(png ~= nil and png.width == 32, "png fixture", errstr(e)) then tile("basn6a08.png", png) end -- a generated image, saved and reloaded through every image writer - local Types = require("rosetta.Types") + local Types = F.Types local img = Types.Image.new(96, 64, "rgba8") for y = 0, 63 do for x = 0, 95 do diff --git a/tools/bench.sh b/tools/bench.sh index 64e3012..000a49f 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash -# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the build output). +# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the module build, build/_modules/luajit). cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} python3 -I tools/fixtures.py > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau -"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua +"$LUAJIT" -e 'package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path' build/_modules/luajit/tools/bench.lua diff --git a/tools/build.py b/tools/build.py index 4d84872..82314e8 100644 --- a/tools/build.py +++ b/tools/build.py @@ -1,16 +1,20 @@ #!/usr/bin/env python3 # Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree. # -# build/roblox/Rosetta/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native and -# @native are kept. Mounted by default.project.json (rojo build / rojo serve). -# build/luajit/rosetta/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and the -# Luau-only syntax, then the token passes below; requires become require("rosetta.a.b"). -# build/luajit/tools/... tools/*.luau (bench), built the same way. -# build/luajit/tests/... the tests, built the same way (require("@tests/T") -> require("tests.T")); tests/gen -# fixture modules are copied as they are (plain string literals; darklua is slow on them). +# The shipped files are the single-file bundles build/Rosetta.luau (roblox) and build/rosetta.lua (luajit), written by +# tools/bundle.py after each target (committed). The multi-file trees below are internal (gitignored), for the tests: +# build/_modules/roblox/Rosetta/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native +# and @native are kept. +# build/_modules/luajit/rosetta/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and +# the Luau-only syntax, then the token passes below; requires become +# require("rosetta.a.b"). tools/bundle.py builds build/rosetta.lua from it. +# build/_modules/luajit/tools/... tools/*.luau (bench), built the same way. +# build/_modules/luajit/tests/... the tests, built the same way (require("@tests/T") -> require("tests.T")); +# tests/gen fixture modules are copied as they are (plain string literals; darklua +# is slow on them). # -# Load the LuaJIT output with package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path, then -# local F = require("rosetta"). +# Load the LuaJIT tree with package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. +# package.path, then local F = require("rosetta"). # # What darklua 0.19 cannot do, done here as token-level passes (lexer from imgui-luau tools/minify.py): # 1. Generalized iteration (`for k, v in t do`): darklua has no rule for it. Every generic for whose iterator @@ -29,6 +33,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SRC = os.path.join(ROOT, "src", "Rosetta") TESTS = os.path.join(ROOT, "tests") BUILD = os.path.join(ROOT, "build") +MODULES = os.path.join(BUILD, "_modules") # darklua 0.19: $DARKLUA, else on PATH, else through nix DARKLUA = os.environ.get("DARKLUA", "").split() or (["darklua"] if shutil.which("darklua") else ["nix", "shell", "nixpkgs#darklua", "-c", "darklua"]) @@ -329,8 +334,8 @@ def pass_reserved_children(src): def build_roblox(): - out = os.path.join(BUILD, "roblox", "Rosetta") - shutil.rmtree(os.path.join(BUILD, "roblox"), ignore_errors=True) + out = os.path.join(MODULES, "roblox", "Rosetta") + shutil.rmtree(os.path.join(MODULES, "roblox"), ignore_errors=True) darklua(ROBLOX_RULES, os.path.relpath(SRC, ROOT), os.path.relpath(out, ROOT), ROOT) for f in files(out): with open(f) as fh: @@ -379,7 +384,7 @@ def build_luajit_tree(src_root, out_root, skip_dirs=()): def build_luajit(): - base = os.path.join(BUILD, "luajit") + base = os.path.join(MODULES, "luajit") shutil.rmtree(base, ignore_errors=True) out = os.path.join(base, "rosetta") n = build_luajit_tree(SRC, out) @@ -459,7 +464,11 @@ if __name__ == "__main__": if "--test" in targets: selftest() sys.exit(0) + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + import bundle if "roblox" in targets: build_roblox() + bundle.bundle_roblox() if "luajit" in targets: build_luajit() + bundle.bundle_luajit() diff --git a/tools/bundle.py b/tools/bundle.py new file mode 100644 index 0000000..cc289a8 --- /dev/null +++ b/tools/bundle.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +# Single-file bundles (python3 -I tools/bundle.py [roblox|luajit ...] [--stage-tests] [--where <file> <line>]): +# +# build/Rosetta.luau Roblox (one ModuleScript; also runs under the luau CLI), from src/Rosetta directly +# build/rosetta.lua LÖVE / LuaJIT (one file), from build/_modules/luajit/rosetta (tools/build.py luajit first) +# build/<file>.linemap.json [[first bundle line, source file], ...]: bundle line L of a module starting at line S is +# line L - S + 1 of its source file (both bundles keep every source line on its line) +# +# Every module becomes a function in __FILES, keyed by its module path ("core/Bytes", "image/png", "" for the root); +# __include(path) runs it on first use and caches the result. Requires become __include calls, so requiring the bundle +# runs only the root and what it requires at load time; every other module runs on first use, like separate modules. +# The returned table is the root's API table plus Rosetta._internal(path): __include of any module by its src path +# ("codecs/video/Mpeg1"), for code that uses internals. An unknown path throws. +# +# Roblox bundle: +# --!optimize 2 for the whole file and --!nocheck (types are kept, but a cross-module type such as Bytes.Reader +# cannot resolve once requires are __include calls; native codegen reads the annotations, not the checker). +# --!native cannot apply to one module inside a file, so a --!native module gets @native on every function it +# defines, its module function included (@native does not reach nested functions). The NATIVE lint rule (no +# error / assert in a --!native module or what it requires) is checked again here on the bundled text. +# export type -> type (a function body cannot export). +# LuaJIT bundle: compat/luajit.lua runs once at the top; each module's compat header reads it (`__compat`) instead of +# require("rosetta._compat"). The bundle sets package.loaded["rosetta._compat"] (when unset), so +# require("rosetta._compat").install() keeps working, and _internal("_compat") returns it too. +# Load: package.path = "build/?.lua;" .. package.path; require("rosetta"), or dofile("build/rosetta.lua"). +# +# Limits (Luau 200 locals / 200 upvalues per function, LuaJIT 60 upvalues, constants per function): the main chunk +# holds 3 locals and one string constant per module; a module function adds at most 2 upvalues (__include, +# __compat) to what its source chunk had. Both bundles are compiled here as a check (luau-compile, luajit -bl). +# +# --stage-tests: the api test and the docs / example tests (tests/docs/snippets) rewritten to use the bundles, in +# build/_modules/bundle_tests/{luau,luajit} (tools/test.sh runs them). +# --where <Rosetta.luau|rosetta.lua> <line>: the source file and line of a bundle line. +import json, os, re, shutil, subprocess, sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from build import lex, apply, ROOT, SRC, BUILD, MODULES + +LJ_MODULES = os.path.join(MODULES, "luajit", "rosetta") +STAGE = os.path.join(MODULES, "bundle_tests") +THROW = {"error", "assert"} +DIRECTIVE = re.compile(r"^--!(strict|nonstrict|nocheck|native|optimize \d)[ \t]*$") + + +def modpath(rel): + """'image/png/init.luau' -> 'image/png', 'init.luau' -> '', 'core/Bytes.lua' -> 'core/Bytes'""" + rel = rel.replace(os.sep, "/").rsplit(".", 1)[0] + if rel == "init": + return "" + return rel[:-5] if rel.endswith("/init") else rel + + +def modules(root, ext): + out = {} + for d, dirs, fs in os.walk(root): + dirs.sort() + for f in sorted(fs): + if f.endswith(ext): + p = os.path.join(d, f) + out[modpath(os.path.relpath(p, root))] = p + return dict(sorted(out.items())) + + +def include_requires(src, pattern, key, known, where): + """require("<literal>") -> __include("<key>") for the literals matching pattern (a compiled regex on the string + contents); other requires stay. Token-based: comments and strings are never touched.""" + toks = lex(src) + edits = [] + for i in range(len(toks) - 3): + if toks[i][1] != "require" or toks[i][0] != "name" or toks[i + 1][1] != "(" or toks[i + 2][0] != "str" \ + or toks[i + 3][1] != ")" or (i > 0 and toks[i - 1][1] in (".", ":")): + continue + lit = toks[i + 2][1] + m = pattern.fullmatch(lit[1:-1]) + if not m: + continue + k = key(m) + if k is not None and k not in known: + sys.exit("bundle: %s requires %s: no such module" % (where, lit)) + edits.append((toks[i][2], toks[i + 3][3], "__include(%s)" % json.dumps(k) if k is not None else "__compat")) + return apply(src, edits) + + +def native_functions(src): + """@native before every function a module defines (`@native local function`, `@native function a.b()`, + `@native function(...)`).""" + toks = lex(src) + edits = [] + for i, (k, t, s, e) in enumerate(toks): + if k == "name" and t == "function": + at = toks[i - 1][2] if i > 0 and toks[i - 1][1] == "local" else s + edits.append((at, at, "@native ")) + return apply(src, edits) + + +def header_lines(src): + """the leading --! directive lines become empty lines (same line count)""" + lines = src.split("\n") + native = False + for i, l in enumerate(lines): + if not l.startswith("--!"): + break + if DIRECTIVE.match(l): + native = native or l.strip() == "--!native" + lines[i] = "" + return "\n".join(lines), native + + +RUNTIME = """local __FILES = {} +local __LOADED = {} +local function __include(path) + local r = __LOADED[path] + if r == nil then + local f = __FILES[path] + if f == nil then + error("rosetta: no module '" .. tostring(path) .. "'", 2) + end + __LOADED[path] = false -- while it runs (a cycle, or a module that threw) + r = f() + if r == nil then + r = true + end + __LOADED[path] = r + elseif r == false then + error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) + end + return r +end""" + +TAIL = """local Rosetta = __include("") +Rosetta._internal = function(path) + return __include(path) +end +return Rosetta""" + + +def assemble(head, mods, native): + """head lines + one __FILES function per module + the tail -> (text, linemap)""" + out = list(head) + RUNTIME.split("\n") + linemap = [] + for key, (src, rel) in mods.items(): + out.append("__FILES[%s] = %sfunction()" % (json.dumps(key), "@native " if key in native else "")) + linemap.append([len(out) + 1, rel]) + body = src.rstrip("\n") + out += body.split("\n") + out.append("end") + out += TAIL.split("\n") + return "\n".join(out) + "\n", linemap + + +def check_native(mods, native, deps): + """NATIVE on the bundled text: a native module's code has no error( / assert( and requires no module that has.""" + def throws(src): + toks = lex(src) + return any(t[0] == "name" and t[1] in THROW and toks[i + 1][1] == "(" and (i == 0 or toks[i - 1][1] not in (".", ":")) + for i, t in enumerate(toks[:-1])) + throwing = {k for k, (s, _) in mods.items() if throws(s)} + bad = [] + for k in sorted(native): + if k in throwing: + bad.append("%s is @native and calls error / assert" % (k or "<root>")) + for d in sorted(deps[k] & throwing): + bad.append("%s is @native and includes %s, which can throw" % (k or "<root>", d)) + if bad: + sys.exit("bundle: NATIVE:\n " + "\n ".join(bad)) + + +INCLUDES = re.compile(r'__include\("([^"]*)"\)') + + +def write(name, text, linemap): + os.makedirs(BUILD, exist_ok=True) + with open(os.path.join(BUILD, name), "w") as f: + f.write(text) + with open(os.path.join(BUILD, name + ".linemap.json"), "w") as f: + f.write("[\n" + ",\n".join(json.dumps(x) for x in linemap) + "\n]\n") + print("bundle: %-14s %4d modules, %d lines, %.2f MB -> build/%s" % ( + name, len(linemap), text.count("\n"), len(text) / 1e6, name)) + + +def tool(name): + env = {"luau-compile": "LUAU_COMPILE", "luajit": "LUAJIT"}[name] + if os.environ.get(env): + return [os.environ[env]] + if shutil.which(name): + return [name] + pkg = "luau" if name.startswith("luau") else name + return ["nix", "shell", "nixpkgs#" + pkg, "-c", name] + + +def compile_check(cmd, what): + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode != 0: + sys.exit("bundle: %s does not compile:\n%s" % (what, (r.stdout + r.stderr)[-3000:])) + + +# ------------------------------------------------------------------------------------------------ roblox +ROSETTA_REQ = re.compile(r"@rosetta(?:/([\w/]+))?") + + +def bundle_roblox(): + files = modules(SRC, ".luau") + mods, native, deps = {}, set(), {} + for key, path in files.items(): + with open(path) as f: + src = f.read() + src, is_native = header_lines(src) + src = include_requires(src, ROSETTA_REQ, lambda m: m.group(1) or "", files, os.path.relpath(path, ROOT)) + src = re.sub(r"^export type\b", "type", src, flags=re.M) + deps[key] = set(INCLUDES.findall(src)) + if is_native: + native.add(key) + src = native_functions(src) + mods[key] = (src, os.path.relpath(path, ROOT).replace(os.sep, "/")) + check_native(mods, native, deps) + head = ["--!optimize 2", "--!nocheck", + "-- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", + "-- require(this) -> the API (docs/API.md); Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module.", + "-- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where)."] + text, linemap = assemble(head, mods, native) + write("Rosetta.luau", text, linemap) + compile_check(tool("luau-compile") + ["--null", os.path.join(BUILD, "Rosetta.luau")], "build/Rosetta.luau") + + +# ------------------------------------------------------------------------------------------------ luajit +LJ_REQ = re.compile(r"rosetta(?:\.([\w.]+))?") + + +def bundle_luajit(): + if not os.path.isdir(LJ_MODULES): + sys.exit("bundle: no %s (python3 -I tools/build.py luajit)" % os.path.relpath(LJ_MODULES, ROOT)) + files = modules(LJ_MODULES, ".lua") + files.pop("_compat", None) + srcs = modules(SRC, ".luau") + + def key(m): + k = (m.group(1) or "").replace(".", "/") + return None if k == "_compat" else k + + mods = {} + for k, path in files.items(): + with open(path) as f: + src = f.read() + src = include_requires(src, LJ_REQ, key, files, os.path.relpath(path, ROOT)) + mods[k] = (src, os.path.relpath(srcs[k], ROOT).replace(os.sep, "/")) + with open(os.path.join(ROOT, "compat", "luajit.lua")) as f: + compat = f.read().rstrip("\n") + head = ["-- rosetta (LuaJIT / LÖVE bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", + "-- require(\"rosetta\") with build/?.lua on package.path, or dofile(\"build/rosetta.lua\"): the API", + "-- (docs/API.md); Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module. Error lines map back to", + "-- the sources through rosetta.lua.linemap.json (python3 -I tools/bundle.py --where).", + "local __compat = (function()"] + compat.split("\n") + [ + "end)()", + "if package and package.loaded and package.loaded[\"rosetta._compat\"] == nil then", + "\tpackage.loaded[\"rosetta._compat\"] = __compat", + "end"] + text, linemap = assemble(head, mods, set()) + text = text.replace(RUNTIME, RUNTIME + "\n__LOADED[\"_compat\"] = __compat", 1) + linemap = [[a + 1, b] for a, b in linemap] + write("rosetta.lua", text, linemap) + compile_check(tool("luajit") + ["-bl", os.path.join(BUILD, "rosetta.lua"), "/dev/null"], "build/rosetta.lua") + + +# ------------------------------------------------------------------------------------------------ tests on the bundles +LUAU_RC = {"languageMode": "nonstrict", "aliases": {"tests": "../../../../tests", "bundle": "../../.."}} + + +def stage_tests(): + """tests/api.luau + tests/docs/snippets/*.luau against build/Rosetta.luau (luau) and their LuaJIT builds against + build/rosetta.lua: build/_modules/bundle_tests/{luau,luajit}/<same relative path>""" + shutil.rmtree(STAGE, ignore_errors=True) + names = ["api.luau"] + ["docs/snippets/" + f for f in sorted(os.listdir(os.path.join(ROOT, "tests", "docs", "snippets"))) + if f.endswith(".luau") and not f.startswith("_")] + luau_req = re.compile(r"@rosetta(?:/([\w/]+))?") + lj_req = re.compile(r"rosetta(?:\.([\w.]+))?") + n = 0 + for rel in names: + with open(os.path.join(ROOT, "tests", rel)) as f: + src = f.read() + src = rewrite_api(src, luau_req, lambda m: m.group(1), 'require("@bundle/Rosetta")') + dst = os.path.join(STAGE, "luau", rel) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "w") as f: + f.write(src) + lj = os.path.join(MODULES, "luajit", "tests", rel[:-5] + ".lua") + with open(lj) as f: + src = f.read() + src = rewrite_api(src, lj_req, lambda m: m.group(1) and m.group(1).replace(".", "/"), 'require("rosetta")') + dst = os.path.join(STAGE, "luajit", rel[:-5] + ".lua") + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "w") as f: + f.write(src) + n += 1 + with open(os.path.join(STAGE, "luau", ".luaurc"), "w") as f: + json.dump(LUAU_RC, f, indent="\t") + print("bundle: %d tests staged -> %s/{luau,luajit}" % (n, os.path.relpath(STAGE, ROOT))) + + +def rewrite_api(src, pattern, sub, root): + """the library requires of a test -> the bundle: the root as it is, a submodule through _internal""" + toks = lex(src) + edits = [] + for i in range(len(toks) - 3): + if toks[i][1] == "require" and toks[i + 1][1] == "(" and toks[i + 2][0] == "str" and toks[i + 3][1] == ")": + m = pattern.fullmatch(toks[i + 2][1][1:-1]) + if m: + k = sub(m) + edits.append((toks[i][2], toks[i + 3][3], root if not k else "%s._internal(%s)" % (root, json.dumps(k)))) + return apply(src, edits) + + +def where(name, line): + with open(os.path.join(BUILD, name + ".linemap.json")) as f: + lm = json.load(f) + best = None + for start, path in lm: + if start <= line: + best = (start, path) + if not best: + return "%s:%d (bundle runtime)" % (name, line) + return "%s:%d" % (best[1], line - best[0] + 1) + + +if __name__ == "__main__": + args = sys.argv[1:] + if args[:1] == ["--where"]: + print(where(os.path.basename(args[1]), int(args[2]))) + sys.exit(0) + targets = [a for a in args if not a.startswith("--")] or ([] if "--stage-tests" in args else ["roblox", "luajit"]) + if "roblox" in targets: + bundle_roblox() + if "luajit" in targets: + bundle_luajit() + if "--stage-tests" in args: + stage_tests() diff --git a/tools/gen_registry.py b/tools/gen_registry.py index 58c77be..e7ec47e 100644 --- a/tools/gen_registry.py +++ b/tools/gen_registry.py @@ -4,9 +4,11 @@ # src/Rosetta/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied # from its init.luau, and a load() that requires the module on first use # docs/FORMATS.md the capability matrix, from each contract's caps +# README.md the format table (read / write) and the codec + container list, between the markers +# <!-- formats:begin --> / <!-- formats:end --> and <!-- codecs:begin --> / <!-- codecs:end --> # The metadata fields must be one-line literals in the contract table (tools/lint.sh CONTRACT checks the shape): # name = "png", category = "image", extensions = { ... }, mime = { ... }, deps = { ... }, caps = { ... }, -# --check: exit 1 when either file is out of date (tools/lint.sh runs this). +# --check: exit 1 when any of them is out of date (tools/lint.sh runs this). import os, re, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -156,21 +158,80 @@ def formats_md(formats): return "\n".join(lines) +LABELS = {"image": "Images", "audio": "Audio", "video": "Video", "model": "3D models", "cad": "CAD", "font": "Fonts", + "archive": "Archives", "data": "Data", "vector": "Vector graphics and tile maps", "layered": "Layered images", + "subtitle": "Subtitles", "music": "Music", "playlist": "Playlists"} + + +def module_list(rel): + """[(name, file)] of the modules directly under src/Rosetta/<rel> (Foo.luau or Foo/init.luau)""" + d = os.path.join(SRC, rel) + out = [] + for name in sorted(os.listdir(d)) if os.path.isdir(d) else []: + p = os.path.join(d, name) + f = os.path.join(p, "init.luau") if os.path.isdir(p) else p + if os.path.isfile(f) and f.endswith(".luau"): + out.append((name[:-5] if name.endswith(".luau") else name, f)) + return out + + +def readme_formats(formats): + by = {} + for c in formats: + by.setdefault(c["folder_category"], []).append(c) + lines = ["%d formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)" + % len(formats), "adds each format's capabilities.", "", + "| Category | Format | Extensions | Read | Write |", "|---|---|---|---|---|"] + for cat in CATEGORIES: + for c in by.get(cat, []): + cd = dict(caps_dict(c["caps"])) + lines.append("| %s | %s | %s | %s | %s |" % ( + LABELS[cat], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])), + "yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-")) + return "\n".join(lines) + + +def readme_codecs(): + lines = ["Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`, `src/Rosetta/containers/`;", + "[docs/FORMATS.md](docs/FORMATS.md) describes each). The bundles reach them as `F._internal(\"codecs/video/Mpeg1\")`.", + "", "| Domain | Modules |", "|---|---|"] + cdir = os.path.join(SRC, "codecs") + for domain in sorted(os.listdir(cdir)): + if os.path.isdir(os.path.join(cdir, domain)): + lines.append("| %s | %s |" % (domain, ", ".join(n for n, _ in module_list("codecs/" + domain)))) + lines.append("| containers | %s |" % ", ".join(n for n, _ in module_list("containers"))) + return "\n".join(lines) + + +def readme(formats, path): + """README.md with its generated sections replaced""" + text = open(path, encoding="utf-8").read() + for tag, body in (("formats", readme_formats(formats)), ("codecs", readme_codecs())): + begin, end = "<!-- %s:begin -->" % tag, "<!-- %s:end -->" % tag + m = re.search(re.escape(begin) + r".*?" + re.escape(end), text, re.S) + if not m: + sys.exit("gen_registry: README.md has no %s ... %s section" % (begin, end)) + text = text[:m.start()] + begin + "\n" + body + "\n" + end + text[m.end():] + return text + + def main(): formats = scan() + readme_path = os.path.join(ROOT, "README.md") outputs = { os.path.join(SRC, "Registry.luau"): registry(formats), os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats), + readme_path: readme(formats, readme_path), } check = "--check" in sys.argv stale = [] for path, text in outputs.items(): - old = open(path).read() if os.path.exists(path) else None + old = open(path, encoding="utf-8").read() if os.path.exists(path) else None if old != text: stale.append(os.path.relpath(path, ROOT)) if not check: os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w") as f: + with open(path, "w", encoding="utf-8") as f: f.write(text) if check: if stale: @@ -178,7 +239,7 @@ def main(): sys.exit(1) print("gen_registry: up to date (%d formats)" % len(formats)) else: - print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md%s" % ( + print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md, README.md%s" % ( len(formats), "" if stale else " (unchanged)")) diff --git a/tools/lint_rules.py b/tools/lint_rules.py index 8215842..7027f61 100644 --- a/tools/lint_rules.py +++ b/tools/lint_rules.py @@ -20,9 +20,10 @@ # DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and # whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a # shared module (core / codecs / containers) and call it from both. -# DOCS the module lists in README.md's Layout block and docs/STYLE.md's layer block name every codec -# (codecs/<domain>/<Name>), container and core module in the tree; README.md's format counts -# ("images (25)", ...) match the registry (docs/FORMATS.md); docs/guide/README.md links every guide page. +# DOCS docs/STYLE.md's layer block names every codec (codecs/<domain>/<Name>), container and core module in the +# tree; README.md's generated format table and codec list (<!-- formats:begin --> ... <!-- codecs:end -->) +# match tools/gen_registry.py's output; README.md links every docs/guide page, docs/API.md and +# docs/STYLE.md; docs/guide/README.md links every guide page. import os, re, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -347,7 +348,7 @@ for dom in sorted(os.listdir(os.path.join(SRC, "codecs"))): modules += ["codecs/%s/%s" % (dom, n) for n in sorted(module_names("codecs/" + dom))] modules += ["containers/" + n for n in sorted(module_names("containers"))] modules += ["core/" + n for n in sorted(module_names("core"))] -for doc in ("README.md", os.path.join("docs", "STYLE.md")): +for doc in (os.path.join("docs", "STYLE.md"),): path = os.path.join(ROOT, doc) ln, block = layout_block(path) if not block: @@ -357,23 +358,21 @@ for doc in ("README.md", os.path.join("docs", "STYLE.md")): if not re.search(r"(?<![\w/])" + re.escape(m.rsplit("/", 1)[1]) + r"\b", block): bad(path, ln, "DOCS: the layout block does not list %s" % m) -LABELS = {"image": "images", "audio": "audio", "video": "video", "model": "3D models", "cad": "CAD", "font": "fonts", - "archive": "archives", "data": "data", "vector": "vector graphics and tile maps", "layered": "layered images", - "subtitle": "subtitles", "music": "music", "playlist": "playlists"} -counts = {} -for line in open(os.path.join(ROOT, "docs", "FORMATS.md"), encoding="utf-8"): - cells = [c.strip() for c in line.split("|")] - if len(cells) > 3 and cells[1] in LABELS: - counts[cells[1]] = counts.get(cells[1], 0) + 1 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gen_registry readme = os.path.join(ROOT, "README.md") rtext = open(readme, encoding="utf-8").read() -m = re.search(r"(\d+) formats:", rtext) -if not m or int(m.group(1)) != sum(counts.values()): - bad(readme, 1, "DOCS: README.md should say \"%d formats:\" (docs/FORMATS.md)" % sum(counts.values())) -for cat, label in LABELS.items(): - m = re.search(r"\s+".join(map(re.escape, label.split())) + r"\s+\((\d+)\)", rtext) - if not m or int(m.group(1)) != counts.get(cat, 0): - bad(readme, 1, "DOCS: README.md should say \"%s (%d)\" (docs/FORMATS.md)" % (label, counts.get(cat, 0))) +want = gen_registry.readme(gen_registry.scan(), readme) +for tag in ("formats", "codecs"): + begin, end = "<!-- %s:begin -->" % tag, "<!-- %s:end -->" % tag + if begin not in rtext or end not in rtext: + bad(readme, 1, "DOCS: README.md has no generated %s section (%s ... %s)" % (tag, begin, end)) +if rtext != want: + bad(readme, 1, "DOCS: README.md's generated format / codec sections are out of date (python3 -I tools/gen_registry.py)") +for link in ["docs/guide/" + n for n in sorted(os.listdir(os.path.join(ROOT, "docs", "guide"))) if n.endswith(".md")] + \ + ["docs/API.md", "docs/STYLE.md"]: + if "](%s)" % link not in rtext: + bad(readme, 1, "DOCS: README.md does not link %s" % link) guide = os.path.join(ROOT, "docs", "guide") gindex = open(os.path.join(guide, "README.md"), encoding="utf-8").read() diff --git a/tools/test.sh b/tools/test.sh index d014218..a889d17 100644 --- a/tools/test.sh +++ b/tools/test.sh @@ -1,33 +1,60 @@ #!/usr/bin/env bash # Tests (bash tools/test.sh [filter]): generate the fixtures (tools/fixtures.py -> tests/gen), regenerate the registry, -# build both targets (tools/build.py), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source, -# through the .luaurc aliases) and under `luajit` (build/luajit/tests/**/*.lua, with the compat prelude), then the lint. +# build both targets (tools/build.py: the module trees in build/_modules and the bundles build/Rosetta.luau, +# build/rosetta.lua), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source, through the +# .luaurc aliases) and under `luajit` (build/_modules/luajit/tests/**/*.lua, with the compat prelude). The api test and +# the docs / example tests run once more against the bundles (build/Rosetta.luau under luau, build/rosetta.lua under +# LuaJIT; tools/bundle.py --stage-tests). Then the lint, and a check that the committed bundles are up to date. # A filter runs only the tests whose path contains it (and the fixture generators whose name contains it), and skips -# the lint. RUNTIMES="luau" or "luajit" runs one runtime only. +# the lint and the bundle check. RUNTIMES="luau" or "luajit" runs one runtime only. cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} +export LUAJIT RUNTIMES=${RUNTIMES:-"luau luajit"} -LJPATH='package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' +LJPATH='package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path' +# the bundle first: rosetta and rosetta._compat come from build/rosetta.lua, tests.* from the module build +LJBUNDLE='package.path = "build/?.lua;build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path; require("rosetta")' +BUNDLES="build/Rosetta.luau build/rosetta.lua build/Rosetta.luau.linemap.json build/rosetta.lua.linemap.json" fail=0 python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; } python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; } python3 -I tools/build.py || { echo "FAILED: build"; exit 1; } +python3 -I tools/bundle.py --stage-tests > /dev/null || { echo "FAILED: bundle --stage-tests"; exit 1; } passed=0 +run() { # run <test label> <runtime> <command...> + local t=$1 rt=$2 + shift 2 + echo "== $t ($rt)" + if "$@"; then passed=$((passed + 1)); else echo "FAILED: $t ($rt)"; fail=1; fi +} for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do [ -n "$1" ] && [[ "$t" != *$1* ]] && continue for rt in $RUNTIMES; do - echo "== $t ($rt)" if [ "$rt" = luau ]; then - "$LUAU" --codegen -O2 "$t" || { echo "FAILED: $t ($rt)"; fail=1; continue; } + run "$t" luau "$LUAU" --codegen -O2 "$t" else - "$LUAJIT" -e "$LJPATH" "build/luajit/${t%.luau}.lua" || { echo "FAILED: $t ($rt)"; fail=1; continue; } + run "$t" luajit "$LUAJIT" -e "$LJPATH" "build/_modules/luajit/${t%.luau}.lua" + fi + done +done +for t in $(cd build/_modules/bundle_tests/luau && find . -name '*.luau' | sed 's#^\./##' | sort); do + [ -n "$1" ] && [[ "tests/$t" != *$1* ]] && continue + for rt in $RUNTIMES; do + if [ "$rt" = luau ]; then + run "tests/$t" "luau, build/Rosetta.luau" "$LUAU" --codegen -O2 "build/_modules/bundle_tests/luau/$t" + else + run "tests/$t" "luajit, build/rosetta.lua" "$LUAJIT" -e "$LJBUNDLE" "build/_modules/bundle_tests/luajit/${t%.luau}.lua" fi - passed=$((passed + 1)) done done if [ -z "$1" ]; then bash tools/lint.sh || fail=1 + if [ -n "$(git status --porcelain -- $BUNDLES)" ]; then + git status --short -- $BUNDLES + echo "FAILED: the bundles in build/ differ from the committed ones (tools/build.py rewrote them): commit them" + fail=1 + fi fi [ $fail -eq 0 ] && echo "rosetta: all tests passed ($passed runs)" || echo "rosetta: FAILURES" exit $fail